Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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<string> ();
var dylibs = new List<string> ();

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;
}
}
}
21 changes: 1 addition & 20 deletions msbuild/Xamarin.iOS.Tasks.Core/Tasks/MTouchTaskBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -177,9 +177,6 @@ public GccOptions ()
[Required]
[Output]
public ITaskItem NativeExecutable { get; set; }

[Output]
public ITaskItem[] NativeLibraries { get; set; }

#endregion

Expand Down Expand Up @@ -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<ITaskItem> ();

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)
Expand Down
43 changes: 22 additions & 21 deletions msbuild/Xamarin.iOS.Tasks.Core/Xamarin.iOS.Common.targets
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ Copyright (C) 2013-2016 Xamarin. All rights reserved.

<UsingTask TaskName="Xamarin.iOS.Tasks.ACTool" AssemblyFile="Xamarin.iOS.Tasks.dll" />
<UsingTask TaskName="Xamarin.iOS.Tasks.Archive" AssemblyFile="Xamarin.iOS.Tasks.dll" />
<UsingTask TaskName="Xamarin.iOS.Tasks.CodesignNativeLibraries" AssemblyFile="Xamarin.iOS.Tasks.dll" />
<UsingTask TaskName="Xamarin.iOS.Tasks.CodesignVerify" AssemblyFile="Xamarin.iOS.Tasks.dll" />
<UsingTask TaskName="Xamarin.iOS.Tasks.CollectAssetPacks" AssemblyFile="Xamarin.iOS.Tasks.dll" />
<UsingTask TaskName="Xamarin.iOS.Tasks.CollectFrameworks" AssemblyFile="Xamarin.iOS.Tasks.dll" />
Expand Down Expand Up @@ -525,10 +526,6 @@ Copyright (C) 2013-2016 Xamarin. All rights reserved.
SdkDevPath="$(_SdkDevPath)"
OutputLibrary="$(_AppBundlePath)default.metallib">
</MetalLib>

<CreateItem Include="$(_AppBundlePath)default.metallib">
<Output TaskParameter="Include" ItemName="_NativeLibrary" />
</CreateItem>
</Target>

<Target Name="_PackLibraryResources" Condition="'$(_CanOutputAppBundle)' == 'false'" DependsOnTargets="_CollectBundleResources">
Expand Down Expand Up @@ -753,7 +750,6 @@ Copyright (C) 2013-2016 Xamarin. All rights reserved.
Verbosity="$(MtouchVerbosity)"
>
<Output TaskParameter="CompiledArchitectures" PropertyName="_CompiledArchitectures" />
<Output TaskParameter="NativeLibraries" ItemName="_NativeLibrary" />
</MTouch>
</Target>

Expand Down Expand Up @@ -1618,38 +1614,27 @@ Copyright (C) 2013-2016 Xamarin. All rights reserved.
</Target>

<!-- Note: Always codesign *.dylibs even for Simulator builds. We use $(_CanOutputAppBundle) because dylibs can exist in app extensions as well. -->
<Target Name="_CodesignNativeLibraries" Condition="'$(_CanOutputAppBundle)' == 'true' And '$(_CodeSigningKey)' != '' And '@(_NativeLibrary)' != ''" DependsOnTargets="_DetectSigningIdentity;_CompileToNative"
Inputs="%(_NativeLibrary.Identity)" Outputs="$(DeviceSpecificIntermediateOutputPath)codesign\%(_NativeLibrary.Filename)%(_NativeLibrary.Extension)">
<Target Name="_CodesignNativeLibraries" Condition="'$(_CanOutputAppBundle)' == 'true' And '$(_CodeSigningKey)' != ''" DependsOnTargets="_DetectSigningIdentity;_CompileToNative">

<PropertyGroup>
<_CodesignDisableTimestamp>False</_CodesignDisableTimestamp>
<_CodesignDisableTimestamp Condition="'$(_SdkIsSimulator)' == 'true' Or '$(MtouchDebug)' == 'true'">True</_CodesignDisableTimestamp>
</PropertyGroup>

<Codesign
<CodesignNativeLibraries
Condition="'$(IsMacEnabled)' == 'true'"
SessionId="$(BuildSessionId)"
ToolExe="$(CodesignExe)"
ToolPath="$(CodesignPath)"
AppBundleDir="$(AppBundleDir)"
IntermediateOutputPath="$(DeviceSpecificIntermediateOutputPath)codesign"
CodesignAllocate="$(_CodesignAllocate)"
DisableTimestamp="$(_CodesignDisableTimestamp)"
Keychain="$(CodesignKeychain)"
Resources="@(_NativeLibrary)"
SigningKey="$(_CodeSigningKey)"
ExtraArgs="$(CodesignExtraArgs)"
>
</Codesign>

<MakeDir SessionId="$(BuildSessionId)" Condition="'$(IsMacEnabled)' == 'true'" Directories="$(DeviceSpecificIntermediateOutputPath)codesign" />

<Touch
SessionId="$(BuildSessionId)"
Condition="'$(IsMacEnabled)' == 'true'"
AlwaysCreate="true"
Files="$(DeviceSpecificIntermediateOutputPath)codesign\%(_NativeLibrary.Filename)%(_NativeLibrary.Extension)"
>
<Output TaskParameter="TouchedFiles" ItemName="FileWrites" />
</Touch>
</CodesignNativeLibraries>
</Target>

<Target Name="_CodesignFrameworks" Condition="'$(_CanOutputAppBundle)' == 'true' And '$(_CodeSigningKey)' != '' And '@(_Frameworks)' != ''" DependsOnTargets="_DetectSigningIdentity;_CollectFrameworks"
Expand Down Expand Up @@ -1696,6 +1681,22 @@ Copyright (C) 2013-2016 Xamarin. All rights reserved.
DependsOnTargets="_DetectSigningIdentity;_ReadAppExtensionCodesignProperties"
Inputs="$(_AppBundlePath)PlugIns\%(_AppExtensionCodesignProperties.Identity)\%(_AppExtensionCodesignProperties.NativeExecutable);%(_AppExtensionCodesignProperties.CodesignAppExtensionInputs)"
Outputs="$(_AppBundlePath)PlugIns\%(_AppExtensionCodesignProperties.Identity)\_CodeSignature\CodeResources">

<CodesignNativeLibraries
SessionId="$(BuildSessionId)"
Condition="'$(IsMacEnabled)' == 'true'"
ToolExe="$(CodesignExe)"
ToolPath="$(CodesignPath)"
AppBundleDir="$(_AppBundlePath)PlugIns\%(_AppExtensionCodesignProperties.Identity)"
IntermediateOutputPath="$(DeviceSpecificIntermediateOutputPath)codesign\PlugIns\%(_AppExtensionCodesignProperties.Identity)"
CodesignAllocate="%(_AppExtensionCodesignProperties.CodesignAllocate)"
DisableTimestamp="%(_AppExtensionCodesignProperties.DisableTimestamp)"
Keychain="%(_AppExtensionCodesignProperties.Keychain)"
SigningKey="%(_AppExtensionCodesignProperties.SigningKey)"
ExtraArgs="%(_AppExtensionCodesignProperties.ExtraArgs)"
>
</CodesignNativeLibraries>

<Codesign
SessionId="$(BuildSessionId)"
Condition="'$(IsMacEnabled)' == 'true'"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@
<Compile Include="Tasks\WriteAssetPackManifestTaskBase.cs" />
<Compile Include="Tasks\FindWatchOS2AppBundleTaskBase.cs" />
<Compile Include="Tasks\DetectDebugNetworkConfigurationTaskBase.cs" />
<Compile Include="Tasks\CodesignNativeLibrariesTaskBase.cs" />
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
Expand Down
6 changes: 6 additions & 0 deletions msbuild/Xamarin.iOS.Tasks/Tasks/CodesignNativeLibraries.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace Xamarin.iOS.Tasks
{
public class CodesignNativeLibraries : CodesignNativeLibrariesTaskBase
{
}
}
1 change: 1 addition & 0 deletions msbuild/Xamarin.iOS.Tasks/Xamarin.iOS.Tasks.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
<Compile Include="Tasks\WriteAssetPackManifest.cs" />
<Compile Include="Tasks\FindWatchOS2AppBundle.cs" />
<Compile Include="Tasks\DetectDebugNetworkConfiguration.cs" />
<Compile Include="Tasks\CodesignNativeLibraries.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Xamarin.iOS.Tasks.Core\Xamarin.iOS.Tasks.Core.csproj">
Expand Down
Loading