Skip to content
This repository has been archived by the owner on Dec 18, 2017. It is now read-only.

Commit

Permalink
Using OSS signing on Mono if project json requires real signing
Browse files Browse the repository at this point in the history
If project json contains the `keyFile` property the assembly should
be signed using the provided snk. However real signing is not
supported on Mono. Currently we just error out in this case, after
this change we will fall back to using OSS signing. (Fixes #2558)

Also adding a warning for a case where if both `strongName` and `keyFile`
settings are provided we would just display errors from Roslyn which might
be hard to understand/troubleshoot because the names used in the errors
are different from the names we use in project.json (Fixes #2452)
  • Loading branch information
moozzyk committed Oct 14, 2015
1 parent d569fbf commit 4805b7f
Show file tree
Hide file tree
Showing 5 changed files with 215 additions and 38 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -72,21 +72,53 @@ private static CSharpCompilationOptions GetCompilationOptions(ICompilerOptions c
bool allowUnsafe = compilerOptions.AllowUnsafe ?? false;
bool optimize = compilerOptions.Optimize ?? false;
bool warningsAsErrors = compilerOptions.WarningsAsErrors ?? false;
bool strongName = compilerOptions.StrongName ?? false;

Platform platform;
if (!Enum.TryParse(value: platformValue, ignoreCase: true, result: out platform))
{
platform = Platform.AnyCpu;
}

return options.WithAllowUnsafe(allowUnsafe)
.WithPlatform(platform)
.WithGeneralDiagnosticOption(warningsAsErrors ? ReportDiagnostic.Error : ReportDiagnostic.Default)
.WithOptimizationLevel(optimize ? OptimizationLevel.Release : OptimizationLevel.Debug)
.WithCryptoKeyFile(compilerOptions.KeyFile)
.WithDelaySign(compilerOptions.DelaySign)
.WithCryptoPublicKey(strongName ? StrongNameKey : ImmutableArray<byte>.Empty);
options = options
.WithAllowUnsafe(allowUnsafe)
.WithPlatform(platform)
.WithGeneralDiagnosticOption(warningsAsErrors ? ReportDiagnostic.Error : ReportDiagnostic.Default)
.WithOptimizationLevel(optimize ? OptimizationLevel.Release : OptimizationLevel.Debug);

return AddSigningOptions(options, compilerOptions);
}

private static CSharpCompilationOptions AddSigningOptions(CSharpCompilationOptions options, ICompilerOptions compilerOptions)
{
var strongName = compilerOptions.StrongName == true;

var keyFile =
Environment.GetEnvironmentVariable(EnvironmentNames.BuildKeyFile) ??
compilerOptions.KeyFile;
#if DNX451
if (!string.IsNullOrEmpty(compilerOptions.KeyFile))
{
// For Mono signing with snk is not supported so we want to fallback to OSS sigining unless both
// snk and OSS signing is requested. This is incorrect so we leave it to be able to show an error.
if (RuntimeEnvironmentHelper.IsMono && !strongName)
{
return options.WithCryptoPublicKey(StrongNameKey);
}

var delaySignString = Environment.GetEnvironmentVariable(EnvironmentNames.BuildDelaySign);
var delaySign =
delaySignString == null
? compilerOptions.DelaySign
: string.Equals(delaySignString, "true", StringComparison.OrdinalIgnoreCase) ||
string.Equals(delaySignString, "1", StringComparison.OrdinalIgnoreCase);

options = options
.WithCryptoKeyFile(keyFile)
.WithDelaySign(delaySign);
}
#endif

return strongName ? options.WithCryptoPublicKey(StrongNameKey) : options;
}

private static bool IsDesktop(FrameworkName frameworkName)
Expand Down
63 changes: 33 additions & 30 deletions src/Microsoft.Dnx.Compilation.CSharp/RoslynCompiler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,8 @@ public class RoslynCompiler
incomingReferences,
resourcesResolver);

// Apply strong-name settings
ApplyStrongNameSettings(compilationContext);
ValidateSigningOptions(compilationContext);
AddStrongNameProvider(compilationContext);

if (isMainAspect && projectContext.Files.PreprocessSourceFiles.Any())
{
Expand Down Expand Up @@ -180,43 +180,46 @@ public class RoslynCompiler
return compilationContext;
}

private void ApplyStrongNameSettings(CompilationContext compilationContext)
private void ValidateSigningOptions(CompilationContext compilationContext)
{
var compilerOptions = compilationContext.Project.CompilerOptions;

var keyFile =
Environment.GetEnvironmentVariable(EnvironmentNames.BuildKeyFile) ??
compilationContext.Compilation.Options.CryptoKeyFile;
compilerOptions.KeyFile;

if (!string.IsNullOrEmpty(keyFile) && !RuntimeEnvironmentHelper.IsMono)
if (!string.IsNullOrEmpty(keyFile))
{
#if DNX451
var delaySignString = Environment.GetEnvironmentVariable(EnvironmentNames.BuildDelaySign);
var delaySign =
delaySignString == null
? compilationContext.Compilation.Options.DelaySign
: string.Equals(delaySignString, "true", StringComparison.OrdinalIgnoreCase) ||
string.Equals(delaySignString, "1", StringComparison.OrdinalIgnoreCase);

var strongNameProvider = new DesktopStrongNameProvider(
ImmutableArray.Create(compilationContext.Project.ProjectDirectory));
var newOptions = compilationContext.Compilation.Options
.WithStrongNameProvider(strongNameProvider)
.WithCryptoKeyFile(keyFile)
.WithDelaySign(delaySign);
compilationContext.Compilation = compilationContext.Compilation.WithOptions(newOptions);
#else
var diag = Diagnostic.Create(
RoslynDiagnostics.StrongNamingNotSupported,
null);
compilationContext.Diagnostics.Add(diag);
if (compilerOptions.StrongName == true)
{
compilationContext.Diagnostics.Add(
Diagnostic.Create(RoslynDiagnostics.OssAndSnkSigningAreExclusive, null));
return;
}

if (RuntimeEnvironmentHelper.IsMono)
{
compilationContext.Diagnostics.Add(
Diagnostic.Create(RoslynDiagnostics.SnkNotSupportedOnMono, null));
return;
}
#if DNXCORE50
compilationContext.Diagnostics.Add(
Diagnostic.Create(RoslynDiagnostics.StrongNamingNotSupported, null));
#endif
}
}

// If both CryptoPublicKey and CryptoKeyFile compilation will fail so we don't need a check
if (compilationContext.Compilation.Options.CryptoPublicKey != null)
private void AddStrongNameProvider(CompilationContext compilationContext)
{
if (!string.IsNullOrEmpty(compilationContext.Compilation.Options.CryptoKeyFile))
{
var options = compilationContext.Compilation.Options
.WithCryptoPublicKey(compilationContext.Compilation.Options.CryptoPublicKey);
compilationContext.Compilation = compilationContext.Compilation.WithOptions(options);
var strongNameProvider =
new DesktopStrongNameProvider(ImmutableArray.Create(compilationContext.Project.ProjectDirectory));

compilationContext.Compilation =
compilationContext.Compilation.WithOptions(
compilationContext.Compilation.Options.WithStrongNameProvider(strongNameProvider));
}
}

Expand Down
16 changes: 16 additions & 0 deletions src/Microsoft.Dnx.Compilation.CSharp/RoslynDiagnostics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,21 @@ internal class RoslynDiagnostics
category: "StrongNaming",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);

internal static readonly DiagnosticDescriptor SnkNotSupportedOnMono = new DiagnosticDescriptor(
id: "DNX1002",
title: "Signing assemblies using a key file is not supported on Mono",
messageFormat: "Signing assemblies using a key file is not supported on Mono. Using OSS signing instead.",
category: "StrongNaming",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);

internal static readonly DiagnosticDescriptor OssAndSnkSigningAreExclusive = new DiagnosticDescriptor(
id: "DNX1003",
title: "The \"keyFile\" and \"strongName\" options are mutually exclusive",
messageFormat: "The \"keyFile\" and \"strongName\" options are mutually exclusive and cannot be used together.",
category: "StrongNaming",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
}
}
125 changes: 125 additions & 0 deletions test/Microsoft.Dnx.Compilation.CSharp.Tests/SigningFacts.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Versioning;
using Microsoft.AspNet.Testing.xunit;
using Microsoft.Dnx.Compilation.Caching;
using Microsoft.Dnx.Runtime;
using Xunit;

namespace Microsoft.Dnx.Compilation.CSharp.Tests
{
public class SigningFacts
{
[ConditionalFact]
[FrameworkSkipCondition(RuntimeFrameworks.Mono | RuntimeFrameworks.CLR)]
public void CompileIgnoresRealStrongNameSigningOnCoreClr()
{
RoslynCompiler compiler;
CompilationProjectContext projectContext;
PrepareCompilation(new FakeCompilerOptions { KeyFile = "keyFile.snk" }, out compiler, out projectContext);

var compilationContext = compiler.CompileProject(projectContext, Enumerable.Empty<IMetadataReference>(),
Enumerable.Empty<ISourceReference>(), () => new List<ResourceDescriptor>());

Assert.Equal(1, compilationContext.Diagnostics.Count);
Assert.Equal("DNX1001", compilationContext.Diagnostics[0].Id);
}

[ConditionalFact]
[FrameworkSkipCondition(RuntimeFrameworks.CLR | RuntimeFrameworks.CoreCLR)]
public void CompileFallsBackToOssSigningIfKeyFileSpecifiedOnMono()
{
RoslynCompiler compiler;
CompilationProjectContext projectContext;
PrepareCompilation(new FakeCompilerOptions { KeyFile = "keyFile.snk" }, out compiler, out projectContext);

var compilationContext = compiler.CompileProject(projectContext, Enumerable.Empty<IMetadataReference>(),
Enumerable.Empty<ISourceReference>(), () => new List<ResourceDescriptor>());

Assert.Equal(1, compilationContext.Diagnostics.Count);
Assert.Equal("DNX1002", compilationContext.Diagnostics[0].Id);
}

[Fact]
public void OssSigningAndRealSigningAreMutuallyExclusive()
{
RoslynCompiler compiler;
CompilationProjectContext projectContext;
PrepareCompilation(new FakeCompilerOptions { KeyFile = "keyFile.snk", StrongName = true }, out compiler, out projectContext);

var compilationContext = compiler.CompileProject(projectContext, Enumerable.Empty<IMetadataReference>(),
Enumerable.Empty<ISourceReference>(), () => new List<ResourceDescriptor>());

Assert.Equal(1, compilationContext.Diagnostics.Count);
Assert.Equal("DNX1003", compilationContext.Diagnostics[0].Id);
}

private static void PrepareCompilation(ICompilerOptions compilerOptions, out RoslynCompiler compiler,
out CompilationProjectContext projectContext)
{
var cacheContextAccessor = new FakeCacheContextAccessor { Current = new CacheContext(null, (d) => { }) };
compiler = new RoslynCompiler(null, cacheContextAccessor, new FakeNamedDependencyProvider(), null, new FakeWatcher(), null, null);
var compilationTarget = new CompilationTarget("test", new FrameworkName(".NET Framework, Version=4.0"), "Release", null);
projectContext = new CompilationProjectContext(
compilationTarget, Directory.GetCurrentDirectory(), "project.json", "1.0.0", new System.Version(1, 0), false,
new CompilationFiles(Enumerable.Empty<string>(), Enumerable.Empty<string>()), compilerOptions);
}

private class FakeWatcher : IFileWatcher
{
public event Action<string> OnChanged;

public void Dispose() { }

public void WatchDirectory(string path, string extension) { }

public bool WatchFile(string path)
{
return false;
}

public void WatchProject(string path) { }
}

private class FakeCacheContextAccessor : ICacheContextAccessor
{
public CacheContext Current { get; set; }
}

private class FakeCompilerOptions : ICompilerOptions
{
public bool? AllowUnsafe { get; set; }

public IEnumerable<string> Defines { get; set; }

public bool? DelaySign { get; set; }

public bool? EmitEntryPoint { get; set; }

public string KeyFile { get; set; }

public string LanguageVersion { get; set; }

public bool? Optimize { get; set; }

public string Platform { get; set; }

public bool? StrongName { get; set; }

public bool? WarningsAsErrors { get; set; }
}

private class FakeNamedDependencyProvider : INamedCacheDependencyProvider
{
public ICacheDependency GetNamedDependency(string name)
{
return null;
}

public void Trigger(string name)
{ }
}
}
}
1 change: 1 addition & 0 deletions test/Microsoft.Dnx.Compilation.CSharp.Tests/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"dependencies": {
"Microsoft.Dnx.Runtime.Abstractions": "1.0.0-*",
"Microsoft.Dnx.Compilation.CSharp": "1.0.0-*",
"Microsoft.AspNet.Testing": "1.0.0-*",
"xunit.runner.aspnet": "2.0.0-aspnet-*"
},
"frameworks": {
Expand Down

0 comments on commit 4805b7f

Please sign in to comment.