diff --git a/msbuild/Xamarin.iOS.Tasks.Core/Tasks/CodesignNativeLibrariesTaskBase.cs b/msbuild/Xamarin.iOS.Tasks.Core/Tasks/CodesignNativeLibrariesTaskBase.cs new file mode 100644 index 000000000000..cd5066a00dae --- /dev/null +++ b/msbuild/Xamarin.iOS.Tasks.Core/Tasks/CodesignNativeLibrariesTaskBase.cs @@ -0,0 +1,210 @@ +using System; +using System.IO; +using System.Text; +using System.Diagnostics; +using System.Collections.Generic; + +using Parallel = System.Threading.Tasks.Parallel; +using ParallelOptions = System.Threading.Tasks.ParallelOptions; + +using Microsoft.Build.Framework; +using Microsoft.Build.Utilities; + +using Xamarin.MacDev; +using Xamarin.MacDev.Tasks; + +namespace Xamarin.iOS.Tasks +{ + public abstract class CodesignNativeLibrariesTaskBase : Task + { + const string ToolName = "codesign"; + string toolExe; + + #region Inputs + + public string SessionId { get; set; } + + [Required] + public string AppBundleDir { get; set; } + + [Required] + public string IntermediateOutputPath { get; set; } + + [Required] + public string CodesignAllocate { get; set; } + + public bool DisableTimestamp { get; set; } + + public string Keychain { get; set; } + + [Required] + public string SigningKey { get; set; } + + public string ExtraArgs { get; set; } + + public string ToolExe { + get { return toolExe ?? ToolName; } + set { toolExe = value; } + } + + public string ToolPath { get; set; } + + #endregion + + string GetFullPathToTool () + { + if (!string.IsNullOrEmpty (ToolPath)) + return Path.Combine (ToolPath, ToolExe); + + var path = Path.Combine ("/usr/bin", ToolExe); + + return File.Exists (path) ? path : ToolExe; + } + + ProcessStartInfo GetProcessStartInfo (string tool, string args) + { + var startInfo = new ProcessStartInfo (tool, args); + + startInfo.WorkingDirectory = Environment.CurrentDirectory; + startInfo.EnvironmentVariables["CODESIGN_ALLOCATE"] = CodesignAllocate; + + startInfo.CreateNoWindow = true; + + return startInfo; + } + + string GenerateCommandLineArguments (string dylib) + { + var args = new ProcessArgumentBuilder (); + + args.Add ("-v"); + args.Add ("--force"); + + args.Add ("--sign"); + args.AddQuoted (SigningKey); + + if (!string.IsNullOrEmpty (Keychain)) { + args.Add ("--keychain"); + args.AddQuoted (Path.GetFullPath (Keychain)); + } + + if (DisableTimestamp) + args.Add ("--timestamp=none"); + + if (!string.IsNullOrEmpty (ExtraArgs)) + args.Add (ExtraArgs); + + args.AddQuoted (dylib); + + return args.ToString (); + } + + void Codesign (string dylib) + { + var startInfo = GetProcessStartInfo (GetFullPathToTool (), GenerateCommandLineArguments (dylib)); + var messages = new StringBuilder (); + var errors = new StringBuilder (); + int exitCode; + + try { + Log.LogMessage (MessageImportance.Normal, "Tool {0} execution started with arguments: {1}", startInfo.FileName, startInfo.Arguments); + + using (var stdout = new StringWriter (messages)) { + using (var stderr = new StringWriter (errors)) { + var process = ProcessUtils.StartProcess (startInfo, stdout, stderr); + + process.Wait (); + + exitCode = process.Result; + } + + Log.LogMessage (MessageImportance.Low, "Tool {0} execution finished (exit code = {1}).", startInfo.FileName, exitCode); + } + } catch (Exception ex) { + Log.LogError ("Error executing tool '{0}': {1}", startInfo.FileName, ex.Message); + return; + } + + if (messages.Length > 0) + Log.LogMessage (MessageImportance.Normal, "{0}", messages.ToString ()); + + if (exitCode != 0) { + if (errors.Length > 0) + Log.LogError ("Failed to codesign '{0}': {1}", dylib, errors); + else + Log.LogError ("Failed to codesign '{0}'", dylib); + } else { + var output = GetOutputPath (dylib); + var dir = Path.GetDirectoryName (output); + + Directory.CreateDirectory (dir); + + File.WriteAllText (output, string.Empty); + } + } + + string GetOutputPath (string path) + { + var rpath = PathUtils.AbsoluteToRelative (AppBundleDir, path); + + return Path.Combine (IntermediateOutputPath, rpath); + } + + bool NeedsCodesign (string path) + { + var output = GetOutputPath (path); + + return !File.Exists (output) || File.GetLastWriteTimeUtc (path) >= File.GetLastWriteTimeUtc (output); + } + + public override bool Execute () + { + Log.LogTaskName ("CodesignNativeLibraries"); + Log.LogTaskProperty ("AppBundleDir", AppBundleDir); + Log.LogTaskProperty ("CodesignAllocate", CodesignAllocate); + Log.LogTaskProperty ("DisableTimestamp", DisableTimestamp); + Log.LogTaskProperty ("IntermediateOutputPath", IntermediateOutputPath); + Log.LogTaskProperty ("Keychain", Keychain); + Log.LogTaskProperty ("SigningKey", SigningKey); + Log.LogTaskProperty ("ExtraArgs", ExtraArgs); + + if (!Directory.Exists (AppBundleDir)) + return true; + + var subdirs = new List (); + var dylibs = new List (); + + foreach (var path in Directory.EnumerateFileSystemEntries (AppBundleDir)) { + if (Directory.Exists (path)) { + var name = Path.GetFileName (path); + + if (name != "PlugIns" && name != "Watch") + subdirs.Add (path); + } else { + if (path.EndsWith (".metallib", StringComparison.Ordinal) || path.EndsWith (".dylib", StringComparison.Ordinal)) { + if (NeedsCodesign (path)) + dylibs.Add (path); + } + } + } + + foreach (var subdir in subdirs) { + foreach (var dylib in Directory.EnumerateFiles (subdir, "*.*", SearchOption.AllDirectories)) { + if (dylib.EndsWith (".metallib", StringComparison.Ordinal) || dylib.EndsWith (".dylib", StringComparison.Ordinal)) { + if (NeedsCodesign (dylib)) + dylibs.Add (dylib); + } + } + } + + if (dylibs.Count == 0) + return true; + + Parallel.ForEach (dylibs, new ParallelOptions { MaxDegreeOfParallelism = Math.Max (Environment.ProcessorCount / 2, 1) }, (dylib) => { + Codesign (dylib); + }); + + return !Log.HasLoggedErrors; + } + } +} diff --git a/msbuild/Xamarin.iOS.Tasks.Core/Tasks/MTouchTaskBase.cs b/msbuild/Xamarin.iOS.Tasks.Core/Tasks/MTouchTaskBase.cs index b459ba982f07..bfee47c4488c 100644 --- a/msbuild/Xamarin.iOS.Tasks.Core/Tasks/MTouchTaskBase.cs +++ b/msbuild/Xamarin.iOS.Tasks.Core/Tasks/MTouchTaskBase.cs @@ -177,9 +177,6 @@ public GccOptions () [Required] [Output] public ITaskItem NativeExecutable { get; set; } - - [Output] - public ITaskItem[] NativeLibraries { get; set; } #endregion @@ -707,23 +704,7 @@ public override bool Execute () Directory.CreateDirectory (AppBundleDir); - var mtouchExecution = base.Execute (); - - try { - var nativeLibrariesPath = Directory.EnumerateFiles (AppBundleDir, "*.dylib", SearchOption.AllDirectories); - var nativeLibraryItems = new List (); - - foreach (var nativeLibrary in nativeLibrariesPath) { - nativeLibraryItems.Add (new TaskItem (nativeLibrary)); - } - - NativeLibraries = nativeLibraryItems.ToArray (); - } catch (Exception ex) { - Log.LogError (null, null, null, AppManifest.ItemSpec, 0, 0, 0, 0, "Could not get native libraries: {0}", ex.Message); - return false; - } - - return mtouchExecution; + return base.Execute (); } string ResolveFrameworkFile (string fullName) diff --git a/msbuild/Xamarin.iOS.Tasks.Core/Xamarin.iOS.Common.targets b/msbuild/Xamarin.iOS.Tasks.Core/Xamarin.iOS.Common.targets index af534149dc94..a50587eff8c7 100644 --- a/msbuild/Xamarin.iOS.Tasks.Core/Xamarin.iOS.Common.targets +++ b/msbuild/Xamarin.iOS.Tasks.Core/Xamarin.iOS.Common.targets @@ -39,6 +39,7 @@ Copyright (C) 2013-2016 Xamarin. All rights reserved. + @@ -525,10 +526,6 @@ Copyright (C) 2013-2016 Xamarin. All rights reserved. SdkDevPath="$(_SdkDevPath)" OutputLibrary="$(_AppBundlePath)default.metallib"> - - - - @@ -753,7 +750,6 @@ Copyright (C) 2013-2016 Xamarin. All rights reserved. Verbosity="$(MtouchVerbosity)" > - @@ -1618,38 +1614,27 @@ Copyright (C) 2013-2016 Xamarin. All rights reserved. - + <_CodesignDisableTimestamp>False <_CodesignDisableTimestamp Condition="'$(_SdkIsSimulator)' == 'true' Or '$(MtouchDebug)' == 'true'">True - - - - - - - - + + + + + + diff --git a/msbuild/Xamarin.iOS.Tasks/Tasks/CodesignNativeLibraries.cs b/msbuild/Xamarin.iOS.Tasks/Tasks/CodesignNativeLibraries.cs new file mode 100644 index 000000000000..13891b8aa60c --- /dev/null +++ b/msbuild/Xamarin.iOS.Tasks/Tasks/CodesignNativeLibraries.cs @@ -0,0 +1,6 @@ +namespace Xamarin.iOS.Tasks +{ + public class CodesignNativeLibraries : CodesignNativeLibrariesTaskBase + { + } +} diff --git a/msbuild/Xamarin.iOS.Tasks/Xamarin.iOS.Tasks.csproj b/msbuild/Xamarin.iOS.Tasks/Xamarin.iOS.Tasks.csproj index b029e40fa867..c141d2ee355a 100644 --- a/msbuild/Xamarin.iOS.Tasks/Xamarin.iOS.Tasks.csproj +++ b/msbuild/Xamarin.iOS.Tasks/Xamarin.iOS.Tasks.csproj @@ -71,6 +71,7 @@ + diff --git a/msbuild/tests/Xamarin.iOS.Tasks.Tests/ProjectsTests/CodesignAppBundle.cs b/msbuild/tests/Xamarin.iOS.Tasks.Tests/ProjectsTests/CodesignAppBundle.cs index 2ea7d1996232..4078b71c6b22 100644 --- a/msbuild/tests/Xamarin.iOS.Tasks.Tests/ProjectsTests/CodesignAppBundle.cs +++ b/msbuild/tests/Xamarin.iOS.Tasks.Tests/ProjectsTests/CodesignAppBundle.cs @@ -1,55 +1,88 @@ using System.IO; using System.Linq; using System.Threading; +using System.Diagnostics; using NUnit.Framework; +using Xamarin.MacDev; + namespace Xamarin.iOS.Tasks { - [TestFixture ("iPhone")] + [TestFixture ("Debug")] + [TestFixture ("Release")] public class CodesignAppBundle : ProjectTest { - public CodesignAppBundle (string platform) : base (platform) + readonly string config; + + public CodesignAppBundle (string configuration) : base ("iPhone") { + config = configuration; + } + + static bool IsCodesigned (string path) + { + var psi = new ProcessStartInfo ("/usr/bin/codesign"); + var args = new ProcessArgumentBuilder (); + + args.Add ("--verify"); + args.AddQuoted (path); + + psi.Arguments = args.ToString (); + + var process = Process.Start (psi); + process.WaitForExit (); + + return process.ExitCode == 0; + } + + void AssertProperlyCodesigned () + { + foreach (var dylib in Directory.EnumerateFiles (AppBundlePath, "*.dylib", SearchOption.AllDirectories)) + Assert.IsTrue (IsCodesigned (dylib), "{0} is not properly codesigned.", dylib); } - [Ignore] // requires msbuild instead of xbuild [Test] public void RebuildNoChanges () { - BuildProject ("MyTabbedApplication", Platform, "Release", clean: true); + BuildProject ("MyTabbedApplication", Platform, config, clean: true); + + AssertProperlyCodesigned (); - var dsymDir = Path.GetFullPath (Path.Combine (AppBundlePath, "..", "MyTabbedApplication.app.dSYM")); - var appexDsymDir = Path.GetFullPath (Path.Combine (AppBundlePath, "..", "MyActionExtension.appex.dSYM")); + //var dsymDir = Path.GetFullPath (Path.Combine (AppBundlePath, "..", "MyTabbedApplication.app.dSYM")); + //var appexDsymDir = Path.GetFullPath (Path.Combine (AppBundlePath, "..", "MyActionExtension.appex.dSYM")); - var timestamps = Directory.EnumerateFiles (AppBundlePath, "*.*", SearchOption.AllDirectories).ToDictionary (file => file, file => GetLastModified (file)); - var dsymTimestamps = Directory.EnumerateFiles (dsymDir, "*.*", SearchOption.AllDirectories).ToDictionary (file => file, file => GetLastModified (file)); - var appexDsymTimestamps = Directory.EnumerateFiles (appexDsymDir, "*.*", SearchOption.AllDirectories).ToDictionary (file => file, file => GetLastModified (file)); + //var timestamps = Directory.EnumerateFiles (AppBundlePath, "*.*", SearchOption.AllDirectories).ToDictionary (file => file, file => GetLastModified (file)); + //var dsymTimestamps = Directory.EnumerateFiles (dsymDir, "*.*", SearchOption.AllDirectories).ToDictionary (file => file, file => GetLastModified (file)); + //var appexDsymTimestamps = Directory.EnumerateFiles (appexDsymDir, "*.*", SearchOption.AllDirectories).ToDictionary (file => file, file => GetLastModified (file)); Thread.Sleep (1000); // Rebuild w/ no changes - BuildProject ("MyTabbedApplication", Platform, "Release", clean: false); + BuildProject ("MyTabbedApplication", Platform, config, clean: false); + + AssertProperlyCodesigned (); - var newTimestamps = Directory.EnumerateFiles (AppBundlePath, "*.*", SearchOption.AllDirectories).ToDictionary (file => file, file => GetLastModified (file)); - var newDsymTimestamps = Directory.EnumerateFiles (dsymDir, "*.*", SearchOption.AllDirectories).ToDictionary (file => file, file => GetLastModified (file)); - var newAppexDsymTimestamps = Directory.EnumerateFiles (appexDsymDir, "*.*", SearchOption.AllDirectories).ToDictionary (file => file, file => GetLastModified (file)); + // Note: the following checks all require msbuild instead of xbuild to work properly - foreach (var file in timestamps.Keys) - Assert.AreEqual (timestamps[file], newTimestamps[file], "App Bundle timestamp changed: " + file); + //var newTimestamps = Directory.EnumerateFiles (AppBundlePath, "*.*", SearchOption.AllDirectories).ToDictionary (file => file, file => GetLastModified (file)); + //var newDsymTimestamps = Directory.EnumerateFiles (dsymDir, "*.*", SearchOption.AllDirectories).ToDictionary (file => file, file => GetLastModified (file)); + //var newAppexDsymTimestamps = Directory.EnumerateFiles (appexDsymDir, "*.*", SearchOption.AllDirectories).ToDictionary (file => file, file => GetLastModified (file)); - foreach (var file in dsymTimestamps.Keys) - Assert.AreEqual (dsymTimestamps[file], newDsymTimestamps[file], "App Bundle DSym timestamp changed: " + file); + //foreach (var file in timestamps.Keys) + // Assert.AreEqual (timestamps[file], newTimestamps[file], "App Bundle timestamp changed: " + file); - foreach (var file in appexDsymTimestamps.Keys) - Assert.AreEqual (appexDsymTimestamps[file], newAppexDsymTimestamps[file], "App Extension DSym timestamp changed: " + file); + //foreach (var file in dsymTimestamps.Keys) + // Assert.AreEqual (dsymTimestamps[file], newDsymTimestamps[file], "App Bundle DSym timestamp changed: " + file); + + //foreach (var file in appexDsymTimestamps.Keys) + // Assert.AreEqual (appexDsymTimestamps[file], newAppexDsymTimestamps[file], "App Extension DSym timestamp changed: " + file); } - [Ignore] // requires msbuild instead of xbuild [Test] public void CodesignAfterModifyingAppExtensionTest () { - var csproj = BuildProject ("MyTabbedApplication", Platform, "Release", clean: true); + var csproj = BuildProject ("MyTabbedApplication", Platform, config, clean: true); var testsDir = Path.GetDirectoryName (Path.GetDirectoryName (csproj)); var appexProjectDir = Path.Combine (testsDir, "MyActionExtension"); var viewController = Path.Combine (appexProjectDir, "ActionViewController.cs"); @@ -57,6 +90,8 @@ public void CodesignAfterModifyingAppExtensionTest () var timestamp = File.GetLastWriteTimeUtc (mainExecutable); var text = File.ReadAllText (viewController); + AssertProperlyCodesigned (); + Thread.Sleep (1000); // replace "bool imageFound = false;" with "bool imageFound = true;" so that we force the appex to get rebuilt @@ -64,11 +99,13 @@ public void CodesignAfterModifyingAppExtensionTest () File.WriteAllText (viewController, text); try { - BuildProject ("MyTabbedApplication", Platform, "Release", clean: false); + BuildProject ("MyTabbedApplication", Platform, config, clean: false); var newTimestamp = File.GetLastWriteTimeUtc (mainExecutable); // make sure that the main app bundle was codesigned due to the changes in the appex Assert.IsTrue (newTimestamp > timestamp, "The main app bundle does not seem to have been re-codesigned"); + + AssertProperlyCodesigned (); } finally { // restore the original ActionViewController.cs code... text = text.Replace ("bool imageFound = true;", "bool imageFound = false;"); @@ -76,11 +113,10 @@ public void CodesignAfterModifyingAppExtensionTest () } } - [Ignore] // requires msbuild instead of xbuild [Test] public void CodesignAfterModifyingWatchApp2Test () { - var csproj = BuildProject ("MyWatch2Container", Platform, "Release", clean: true); + var csproj = BuildProject ("MyWatch2Container", Platform, config, clean: true); var testsDir = Path.GetDirectoryName (Path.GetDirectoryName (csproj)); var appexProjectDir = Path.Combine (testsDir, "MyWatchKit2Extension"); var viewController = Path.Combine (appexProjectDir, "InterfaceController.cs"); @@ -88,6 +124,8 @@ public void CodesignAfterModifyingWatchApp2Test () var timestamp = File.GetLastWriteTimeUtc (mainExecutable); var text = File.ReadAllText (viewController); + AssertProperlyCodesigned (); + Thread.Sleep (1000); // replace "bool imageFound = false;" with "bool imageFound = true;" so that we force the appex to get rebuilt @@ -95,11 +133,15 @@ public void CodesignAfterModifyingWatchApp2Test () File.WriteAllText (viewController, text); try { - BuildProject ("MyWatch2Container", Platform, "Release", clean: false); + BuildProject ("MyWatch2Container", Platform, config, clean: false); + + AssertProperlyCodesigned (); + var newTimestamp = File.GetLastWriteTimeUtc (mainExecutable); // make sure that the main app bundle was codesigned due to the changes in the appex - Assert.IsTrue (newTimestamp > timestamp, "The main app bundle does not seem to have been re-codesigned"); + // Note: this step requires msbuild instead of xbuild to work properly + //Assert.IsTrue (newTimestamp > timestamp, "The main app bundle does not seem to have been re-codesigned"); } finally { // restore the original ActionViewController.cs code... text = text.Replace ("{0} The Awakening...", "{0} awake with context");