public void RespectCustomTempPath()
        {
            var tempDir  = Temp.CreateDirectory();
            var provider = new DesktopStrongNameProvider(tempPath: tempDir.Path);

            Assert.Equal(tempDir.Path, provider.FileSystem.GetTempPath());
        }
        private static CSharpCompilationOptions CreateCSharpCompilationOptions()
        {
            string moduleName                        = null;
            string mainTypeName                      = null;
            string scriptClassName                   = null;
            IEnumerable <string> usings              = null;
            OptimizationLevel    optimizationLevel   = OptimizationLevel.Debug;
            bool             checkOverflow           = false;
            bool             allowUnsafe             = false;
            string           cryptoKeyContainer      = null;
            string           cryptoKeyFile           = null;
            bool?            delaySign               = null;
            Platform         platform                = 0;
            ReportDiagnostic generalDiagnosticOption = 0;
            int warningLevel = 0;
            IEnumerable <KeyValuePair <string, ReportDiagnostic> > specificDiagnosticOptions = null;
            bool concurrentBuild = false;
            bool extendedCustomDebugInformation                 = true;
            XmlReferenceResolver      xmlReferenceResolver      = new XmlFileResolver(null);
            SourceReferenceResolver   sourceReferenceResolver   = new SourceFileResolver(ImmutableArray <string> .Empty, null);
            MetadataReferenceResolver metadataReferenceResolver = new AssemblyReferenceResolver(new MetadataFileReferenceResolver(ImmutableArray <string> .Empty, null), MetadataFileReferenceProvider.Default);
            AssemblyIdentityComparer  assemblyIdentityComparer  = AssemblyIdentityComparer.Default;         // Currently uses reference equality
            StrongNameProvider        strongNameProvider        = new DesktopStrongNameProvider();
            MetadataImportOptions     metadataImportOptions     = 0;
            ImmutableArray <string>   features = ImmutableArray <string> .Empty;

            return(new CSharpCompilationOptions(OutputKind.ConsoleApplication, moduleName, mainTypeName, scriptClassName, usings,
                                                optimizationLevel, checkOverflow, allowUnsafe, cryptoKeyContainer, cryptoKeyFile, delaySign,
                                                platform, generalDiagnosticOption, warningLevel, specificDiagnosticOptions,
                                                concurrentBuild, extendedCustomDebugInformation, xmlReferenceResolver, sourceReferenceResolver, metadataReferenceResolver,
                                                assemblyIdentityComparer, strongNameProvider, metadataImportOptions, features));
        }
        private void ApplyStrongNameSettings(CompilationContext compilationContext)
        {
            // This is temporary, eventually we'll want a project.json feature for this
            var keyFile = Environment.GetEnvironmentVariable(EnvironmentNames.BuildKeyFile);

            if (!string.IsNullOrEmpty(keyFile))
            {
#if DNX451
                var delaySignString = Environment.GetEnvironmentVariable(EnvironmentNames.BuildDelaySign);
                var delaySign       = !string.IsNullOrEmpty(delaySignString) && (
                    string.Equals(delaySignString, "true", StringComparison.OrdinalIgnoreCase) ||
                    string.Equals(delaySignString, "1", StringComparison.OrdinalIgnoreCase));

                var strongNameProvider = new DesktopStrongNameProvider();
                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);
#endif
            }
        }
Exemplo n.º 4
0
        public void ResolveStrongNameKeyFile()
        {
            string fileName    = "f.snk";
            string dir         = @"C:\dir";
            string subdir      = @"C:\dir\subdir";
            string filePath    = dir + @"\" + fileName;
            string subFilePath = subdir + @"\" + fileName;

            var fs = new HashSet <string> {
                filePath, subFilePath
            };

            // with no search paths
            var provider = new VirtualizedStrongNameProvider(
                existingFullPaths: fs,
                searchPaths: ImmutableArray.Create(subdir)
                );
            var subdirSearchPath = ImmutableArray.Create(subdir);

            // using base directory; base path ignored
            var path = resolve(fileName, subdirSearchPath);

            Assert.Equal(subFilePath, path, StringComparer.OrdinalIgnoreCase);

            // search paths
            var searchPathsSP = ImmutableArray.Create(@"C:\goo", dir, subdir);

            path = resolve(fileName, searchPathsSP);
            Assert.Equal(filePath, path, StringComparer.OrdinalIgnoreCase);

            // null base dir, no search paths
            var searchPathsEmpty = ImmutableArray <string> .Empty;

            // relative path
            path = resolve(fileName, searchPathsEmpty);
            Assert.Null(path);

            // full path
            path = resolve(filePath, searchPathsEmpty);
            Assert.Equal(filePath, path, StringComparer.OrdinalIgnoreCase);

            // null base dir
            var searchPathsNullBaseSP = ImmutableArray.Create(dir, subdir);

            // relative path
            path = resolve(fileName, searchPathsNullBaseSP);
            Assert.Equal(filePath, path, StringComparer.OrdinalIgnoreCase);

            // full path
            path = resolve(filePath, searchPathsNullBaseSP);
            Assert.Equal(filePath, path, StringComparer.OrdinalIgnoreCase);

            string resolve(string keyFilePath, ImmutableArray <string> searchPaths) =>
            DesktopStrongNameProvider.ResolveStrongNameKeyFile(
                keyFilePath,
                provider.FileSystem,
                searchPaths
                );
        }
        public void BeforeCompile(IBeforeCompileContext context)
        {
            string keyPath         = Environment.GetEnvironmentVariable("NUGET_BUILD_KEY_PATH");
            string delaySignString = Environment.GetEnvironmentVariable("NUGET_BUILD_DELAY_SIGN");

            if (!string.IsNullOrEmpty(keyPath))
            {
                FileInfo keyFile = new FileInfo(keyPath);

                if (keyFile.Exists)
                {
                    bool delaySign = delaySignString != null && StringComparer.OrdinalIgnoreCase.Equals("true", delaySignString);

                    // Console.WriteLine("Signing assembly with: {0} Delay sign: {1}", keyFile.FullName, delaySign ? "true" : "false");

                    var parms = new CspParameters();
                    parms.KeyNumber = 2;

                    var    provider = new RSACryptoServiceProvider(parms);
                    byte[] array    = provider.ExportCspBlob(!provider.PublicOnly);

                    var strongNameProvider = new DesktopStrongNameProvider();


                    var options = context.Compilation.Options.WithStrongNameProvider(strongNameProvider)
                                  .WithCryptoKeyFile(keyFile.FullName)
                                  .WithDelaySign(delaySign);

                    // Enfore viral strong naming
                    var specificDiagnosticOptions = new Dictionary <string, ReportDiagnostic>(options.SpecificDiagnosticOptions);
                    specificDiagnosticOptions["CS8002"] = ReportDiagnostic.Error;
                    options = options.WithSpecificDiagnosticOptions(specificDiagnosticOptions);

                    context.Compilation = context.Compilation.WithOptions(options);
                }
                else
                {
                    // The key was not found. Throw a compile error.
                    var descriptor = new DiagnosticDescriptor(
                        id: "SN1001",
                        title: "Missing key file",
                        messageFormat: "Key file '{0}' could not be found",
                        category: "CA1001: \"StrongNaming\"",
                        defaultSeverity: DiagnosticSeverity.Error,
                        isEnabledByDefault: true);

                    // TODO: what should this reference for the location?
                    var textSpan = new TextSpan();
                    var position = new LinePosition(0, 0);
                    var span     = new LinePositionSpan(position, position);

                    var location = Location.Create(context.ProjectContext.ProjectFilePath, textSpan, span);

                    var diagnsotic = Diagnostic.Create(descriptor, location, keyPath);

                    context.Diagnostics.Add(diagnsotic);
                }
            }
        }
 public void RespectDefaultTempPath()
 {
     var provider = new DesktopStrongNameProvider(tempPath: null);
     using (var stream = (DesktopStrongNameProvider.TempFileStream)provider.CreateInputStream())
     {
         Assert.Equal(Path.GetTempPath(), Path.GetDirectoryName(stream.Path) + @"\");
     }
 }
 public void RespectCustomTempPath()
 {
     var tempDir = Temp.CreateDirectory();
     var provider = new DesktopStrongNameProvider(tempPath: tempDir.Path);
     using (var stream = (DesktopStrongNameProvider.TempFileStream)provider.CreateInputStream())
     {
         Assert.Equal(tempDir.Path, Path.GetDirectoryName(stream.Path));
     }
 }
        public void RespectDefaultTempPath()
        {
            var provider = new DesktopStrongNameProvider(tempPath: null);

            using (var stream = (DesktopStrongNameProvider.TempFileStream)provider.CreateInputStream())
            {
                Assert.Equal(Path.GetTempPath(), Path.GetDirectoryName(stream.Path) + @"\");
            }
        }
        public void RespectCustomTempPath()
        {
            var tempDir  = Temp.CreateDirectory();
            var provider = new DesktopStrongNameProvider(tempPath: tempDir.Path);

            using (var stream = (DesktopStrongNameProvider.TempFileStream)provider.CreateInputStream())
            {
                Assert.Equal(tempDir.Path, Path.GetDirectoryName(stream.Path));
            }
        }
Exemplo n.º 10
0
        private void AddStrongNameProvider(CompilationContext compilationContext)
        {
            if (!string.IsNullOrEmpty(compilationContext.Compilation.Options.CryptoKeyFile))
            {
                var strongNameProvider =
                    new DesktopStrongNameProvider(ImmutableArray.Create(compilationContext.Project.ProjectDirectory));

                compilationContext.Compilation =
                    compilationContext.Compilation.WithOptions(
                        compilationContext.Compilation.Options.WithStrongNameProvider(strongNameProvider));
            }
        }
Exemplo n.º 11
0
        internal override Microsoft.CodeAnalysis.Compilation CreateCompilation(CommonCompilationArguments arguments, IEnumerable <SyntaxTree> syntaxTrees)
        {
            var provider = new DesktopStrongNameProvider(arguments.CmdArguments.KeyFileSearchPaths);
            var cSharpCompilationOptions = ((CSharpCommandLineArguments)arguments.CmdArguments)
                                           .CompilationOptions
                                           .WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)
                                           .WithStrongNameProvider(provider);

            return(CSharpCompilation.Create(GetAssemblyName(arguments),
                                            syntaxTrees
                                            .Where(tree => tree != null),
                                            arguments.MetadataReferences, cSharpCompilationOptions));
        }
Exemplo n.º 12
0
        private void UpdateCompilationOption(ProjectState state)
        {
            var context = state.ProjectContext;
            var project = context.ProjectFile;
            var option  = project.GetCompilerOptions(context.TargetFramework, _compilationConfiguration);

            var outputKind = option.EmitEntryPoint.GetValueOrDefault() ? OutputKind.ConsoleApplication :
                             OutputKind.DynamicallyLinkedLibrary;

            var generalDiagnosticOpt = (option.WarningsAsErrors ?? false) ? ReportDiagnostic.Error :
                                       ReportDiagnostic.Default;

            var optimize = (option.Optimize ?? false) ? OptimizationLevel.Release : OptimizationLevel.Debug;

            var csharpOptions = new CSharpCompilationOptions(outputKind)
                                .WithAllowUnsafe(option.AllowUnsafe ?? false)
                                .WithPlatform(ParsePlatfrom(option.Platform))
                                .WithGeneralDiagnosticOption(generalDiagnosticOpt)
                                .WithOptimizationLevel(optimize)
                                .WithSpecificDiagnosticOptions(new Dictionary <string, ReportDiagnostic> {
                { "CS1701", ReportDiagnostic.Suppress },
                { "CS1702", ReportDiagnostic.Suppress },
                { "CS1705", ReportDiagnostic.Suppress },
            })
                                .WithConcurrentBuild(false); // TODO: actually just need to disable on mono

            if (!string.IsNullOrEmpty(option.KeyFile))
            {
                var cryptoKeyFile = Path.GetFullPath(Path.Combine(project.ProjectDirectory, option.KeyFile));
                if (File.Exists(cryptoKeyFile))
                {
                    var strongNameProvider = new DesktopStrongNameProvider(ImmutableArray.Create(project.ProjectDirectory));
                    csharpOptions = csharpOptions
                                    .WithStrongNameProvider(strongNameProvider)
                                    .WithCryptoPublicKey(SnkUtils.ExtractPublicKey(File.ReadAllBytes(cryptoKeyFile)));
                }
            }

            var parseOptions = new CSharpParseOptions(languageVersion: ParseLanguageVersion(option.LanguageVersion),
                                                      preprocessorSymbols: option.Defines);

            if (option.GenerateXmlDocumentation ?? false)
            {
                csharpOptions = csharpOptions.WithXmlReferenceResolver(XmlFileResolver.Default);
                parseOptions  = parseOptions.WithDocumentationMode(DocumentationMode.Diagnose);
            }

            _omnisharpWorkspace.SetCompilationOptions(state.Id, csharpOptions);
            _omnisharpWorkspace.SetParseOptions(state.Id, parseOptions);
        }
        public void EmitWithDefaultTempPath()
        {
            string src      = @"
class C
{
    public static void Main(string[] args) { }
}";
            var    provider = new DesktopStrongNameProvider(ImmutableArray <string> .Empty, new VirtualizedStrongNameFileSystem());
            var    options  = TestOptions
                              .DebugExe
                              .WithStrongNameProvider(provider)
                              .WithCryptoKeyFile(SigningTestHelpers.KeyPairFile);
            var comp = CreateCompilation(src, options: options);

            comp.VerifyEmitDiagnostics();
        }
Exemplo n.º 14
0
        private static CSharpCompilationOptions CreateCSharpCompilationOptions()
        {
            string moduleName                        = null;
            string mainTypeName                      = null;
            string scriptClassName                   = null;
            IEnumerable <string> usings              = null;
            OptimizationLevel    optimizationLevel   = OptimizationLevel.Debug;
            bool   checkOverflow                     = false;
            bool   allowUnsafe                       = false;
            string cryptoKeyContainer                = null;
            string cryptoKeyFile                     = null;
            ImmutableArray <byte> cryptoPublicKey    = default(ImmutableArray <byte>);
            bool?            delaySign               = null;
            Platform         platform                = 0;
            ReportDiagnostic generalDiagnosticOption = 0;
            int warningLevel = 0;
            IEnumerable <KeyValuePair <string, ReportDiagnostic> > specificDiagnosticOptions = null;
            bool                      concurrentBuild                  = false;
            bool                      deterministic                    = false;
            DateTime                  currentLocalTime                 = default(DateTime);
            bool                      debugPlusMode                    = false;
            XmlReferenceResolver      xmlReferenceResolver             = new XmlFileResolver(null);
            SourceReferenceResolver   sourceReferenceResolver          = new SourceFileResolver(ImmutableArray <string> .Empty, null);
            SyntaxTreeOptionsProvider syntaxTreeOptionsProvider        = null;
            MetadataReferenceResolver metadataReferenceResolver        = new MetadataReferenceResolverWithEquality();
            AssemblyIdentityComparer  assemblyIdentityComparer         = AssemblyIdentityComparer.Default;  // Currently uses reference equality
            StrongNameProvider        strongNameProvider               = new DesktopStrongNameProvider();
            MetadataImportOptions     metadataImportOptions            = 0;
            bool                      referencesSupersedeLowerVersions = false;
            bool                      reportSuppressedDiagnostics      = false;
            var topLevelBinderFlags = BinderFlags.None;
            var publicSign          = false;
            NullableContextOptions nullableContextOptions = NullableContextOptions.Disable;

            return(new CSharpCompilationOptions(OutputKind.ConsoleApplication,
                                                reportSuppressedDiagnostics, moduleName, mainTypeName, scriptClassName, usings,
                                                optimizationLevel, checkOverflow, allowUnsafe, cryptoKeyContainer, cryptoKeyFile,
                                                cryptoPublicKey, delaySign, platform, generalDiagnosticOption, warningLevel,
                                                specificDiagnosticOptions, concurrentBuild, deterministic, currentLocalTime,
                                                debugPlusMode, xmlReferenceResolver, sourceReferenceResolver,
                                                syntaxTreeOptionsProvider, metadataReferenceResolver, assemblyIdentityComparer,
                                                strongNameProvider, metadataImportOptions, referencesSupersedeLowerVersions,
                                                publicSign, topLevelBinderFlags, nullableContextOptions));
        }
Exemplo n.º 15
0
        private unsafe static void InstallKey(byte[] keyBlob, string keyName)
        {
            try
            {
                IClrStrongName strongName = new DesktopStrongNameProvider().GetStrongNameInterface();

                //EDMAURER use marshal to be safe?
                fixed(byte *p = keyBlob)
                {
                    strongName.StrongNameKeyInstall(keyName, (IntPtr)p, keyBlob.Length);
                }
            }
            catch (COMException ex)
            {
                if (unchecked ((uint)ex.ErrorCode) != 0x8009000F)
                {
                    throw;
                }
            }
        }
Exemplo n.º 16
0
        private void ApplyStrongNameSettings(CompilationContext compilationContext)
        {
            var keyFile =
                Environment.GetEnvironmentVariable(EnvironmentNames.BuildKeyFile) ??
                compilationContext.Compilation.Options.CryptoKeyFile;

            if (!string.IsNullOrEmpty(keyFile) && !RuntimeEnvironmentHelper.IsMono)
            {
#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);
#endif
            }

            // If both CryptoPublicKey and CryptoKeyFile compilation will fail so we don't need a check
            if (compilationContext.Compilation.Options.CryptoPublicKey != null)
            {
                var options = compilationContext.Compilation.Options
                              .WithCryptoPublicKey(compilationContext.Compilation.Options.CryptoPublicKey);
                compilationContext.Compilation = compilationContext.Compilation.WithOptions(options);
            }
        }
        public CSharpCompilationOptions CreateCSharpCompilationOptions()
        {
            string moduleName                        = null;
            string mainTypeName                      = null;
            string scriptClassName                   = null;
            IEnumerable <string> usings              = null;
            OptimizationLevel    optimizationLevel   = OptimizationLevel.Debug;
            bool             checkOverflow           = false;
            bool             allowUnsafe             = false;
            string           cryptoKeyContainer      = null;
            string           cryptoKeyFile           = null;
            bool?            delaySign               = null;
            int              fileAlignment           = 0;
            ulong            baseAddress             = 0;
            Platform         platform                = 0;
            ReportDiagnostic generalDiagnosticOption = 0;
            int              warningLevel            = 0;
            IEnumerable <KeyValuePair <string, ReportDiagnostic> > specificDiagnosticOptions = null;
            bool                      highEntropyVirtualAddressSpace = false;
            SubsystemVersion          subsystemVersion          = default(SubsystemVersion);
            string                    runtimeMetadataVersion    = null;
            bool                      concurrentBuild           = false;
            XmlReferenceResolver      xmlReferenceResolver      = new XmlFileResolver(null);
            SourceReferenceResolver   sourceReferenceResolver   = new SourceFileResolver(ImmutableArray <string> .Empty, null);
            MetadataReferenceResolver metadataReferenceResolver = new MetadataFileReferenceResolver(ImmutableArray <string> .Empty, null);
            MetadataReferenceProvider metadataReferenceProvider = MetadataFileReferenceProvider.Default;    // Currently uses reference equality
            AssemblyIdentityComparer  assemblyIdentityComparer  = AssemblyIdentityComparer.Default;         // Currently uses reference equality
            StrongNameProvider        strongNameProvider        = new DesktopStrongNameProvider();
            MetadataImportOptions     metadataImportOptions     = 0;
            ImmutableArray <string>   features = ImmutableArray <string> .Empty;

            return(new CSharpCompilationOptions(OutputKind.ConsoleApplication, moduleName, mainTypeName, scriptClassName, usings,
                                                optimizationLevel, checkOverflow, allowUnsafe, cryptoKeyContainer, cryptoKeyFile, delaySign, fileAlignment, baseAddress,
                                                platform, generalDiagnosticOption, warningLevel, specificDiagnosticOptions, highEntropyVirtualAddressSpace,
                                                subsystemVersion, runtimeMetadataVersion, concurrentBuild, xmlReferenceResolver, sourceReferenceResolver, metadataReferenceResolver, metadataReferenceProvider,
                                                assemblyIdentityComparer, strongNameProvider, metadataImportOptions, features));
        }
        internal static void FixResources(CommandLineArguments args, Compilation compilation)
        {
            if (!string.IsNullOrEmpty(args.Win32ResourceFile) ||
                !string.IsNullOrEmpty(args.Win32Icon) ||
                !string.IsNullOrEmpty(args.Win32Manifest))
            {
                var file = System.IO.Path.Combine(args.OutputDirectory, args.OutputFileName);
                if (System.IO.File.Exists(file))
                {
                    var hRes = BeginUpdateResource(file, false);
                    if (hRes != IntPtr.Zero)
                    {
                        var res = EndUpdateResource(hRes, false);
                    }

                    if (compilation.HasStrongName)
                    {
                        // We have to resign the assembly because updating the resources
                        // may have invalidated the signature.
                        var provider = new DesktopStrongNameProvider();
                        using (var inputstream = provider.CreateInputStream())
                        {
                            using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                fs.CopyTo(inputstream);
                            }
                            using (var outputstream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.Write))
                            {
                                provider.SignStream(compilation.StrongNameKeys, inputstream, outputstream);
                                outputstream.Flush();
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 19
0
        protected void ReadCompilationOptionsFrom(
            ObjectReader reader,
            out OutputKind outputKind,
            out bool reportSuppressedDiagnostics,
            out string moduleName,
            out string mainTypeName,
            out string scriptClassName,
            out OptimizationLevel optimizationLevel,
            out bool checkOverflow,
            out string cryptoKeyContainer,
            out string cryptoKeyFile,
            out ImmutableArray <byte> cryptoPublicKey,
            out bool?delaySign,
            out Platform platform,
            out ReportDiagnostic generalDiagnosticOption,
            out int warningLevel,
            out IEnumerable <KeyValuePair <string, ReportDiagnostic> > specificDiagnosticOptions,
            out bool concurrentBuild,
            out bool deterministic,
            out bool publicSign,
            out XmlReferenceResolver xmlReferenceResolver,
            out SourceReferenceResolver sourceReferenceResolver,
            out MetadataReferenceResolver metadataReferenceResolver,
            out AssemblyIdentityComparer assemblyIdentityComparer,
            out StrongNameProvider strongNameProvider,
            CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            outputKind = (OutputKind)reader.ReadInt32();
            reportSuppressedDiagnostics = reader.ReadBoolean();
            moduleName   = reader.ReadString();
            mainTypeName = reader.ReadString();

            scriptClassName   = reader.ReadString();
            optimizationLevel = (OptimizationLevel)reader.ReadInt32();
            checkOverflow     = reader.ReadBoolean();

            // REVIEW: is it okay this being not part of snapshot?
            cryptoKeyContainer = reader.ReadString();
            cryptoKeyFile      = reader.ReadString();

            cryptoPublicKey = reader.ReadArray <byte>().ToImmutableArrayOrEmpty();

            delaySign = reader.ReadBoolean() ? (bool?)reader.ReadBoolean() : null;

            platform = (Platform)reader.ReadInt32();
            generalDiagnosticOption = (ReportDiagnostic)reader.ReadInt32();

            warningLevel = reader.ReadInt32();

            // REVIEW: I don't think there is a guarantee on ordering of elements in the immutable dictionary.
            //         unfortunately, we need to sort them to make it deterministic
            //         not sure why CompilationOptions uses SequencialEqual to check options equality
            //         when ordering can change result of it even if contents are same.
            var count = reader.ReadInt32();
            List <KeyValuePair <string, ReportDiagnostic> > specificDiagnosticOptionsList = null;

            if (count > 0)
            {
                specificDiagnosticOptionsList = new List <KeyValuePair <string, ReportDiagnostic> >(count);

                for (var i = 0; i < count; i++)
                {
                    var key   = reader.ReadString();
                    var value = (ReportDiagnostic)reader.ReadInt32();

                    specificDiagnosticOptionsList.Add(KeyValuePair.Create(key, value));
                }
            }

            specificDiagnosticOptions = specificDiagnosticOptionsList ?? SpecializedCollections.EmptyEnumerable <KeyValuePair <string, ReportDiagnostic> >();

            concurrentBuild = reader.ReadBoolean();
            deterministic   = reader.ReadBoolean();
            publicSign      = reader.ReadBoolean();

            // REVIEW: What should I do with these. are these service required when compilation is built ourselves, not through
            //         compiler.
            xmlReferenceResolver      = XmlFileResolver.Default;
            sourceReferenceResolver   = SourceFileResolver.Default;
            metadataReferenceResolver = null;
            assemblyIdentityComparer  = DesktopAssemblyIdentityComparer.Default;
            strongNameProvider        = new DesktopStrongNameProvider();
        }
        private static CompilationOptions CreateCompilationOptions(TestWorkspace workspace, string language, XElement compilationOptionsElement, ParseOptions parseOptions)
        {
            var rootNamespace      = new VisualBasicCompilationOptions(OutputKind.ConsoleApplication).RootNamespace;
            var globalImports      = new List <GlobalImport>();
            var reportDiagnostic   = ReportDiagnostic.Default;
            var cryptoKeyFile      = default(string);
            var strongNameProvider = default(StrongNameProvider);
            var delaySign          = default(bool?);

            if (compilationOptionsElement != null)
            {
                globalImports = compilationOptionsElement.Elements(GlobalImportElementName)
                                .Select(x => GlobalImport.Parse(x.Value)).ToList();
                var rootNamespaceAttribute = compilationOptionsElement.Attribute(RootNamespaceAttributeName);
                if (rootNamespaceAttribute != null)
                {
                    rootNamespace = rootNamespaceAttribute.Value;
                }

                var reportDiagnosticAttribute = compilationOptionsElement.Attribute(ReportDiagnosticAttributeName);
                if (reportDiagnosticAttribute != null)
                {
                    reportDiagnostic = (ReportDiagnostic)Enum.Parse(typeof(ReportDiagnostic), (string)reportDiagnosticAttribute);
                }

                var cryptoKeyFileAttribute = compilationOptionsElement.Attribute(CryptoKeyFileAttributeName);
                if (cryptoKeyFileAttribute != null)
                {
                    cryptoKeyFile = (string)cryptoKeyFileAttribute;
                }

                var strongNameProviderAttribute = compilationOptionsElement.Attribute(StrongNameProviderAttributeName);
                if (strongNameProviderAttribute != null)
                {
                    var type = Type.GetType((string)strongNameProviderAttribute);
                    // DesktopStrongNameProvider and SigningTestHelpers.VirtualizedStrongNameProvider do
                    // not have a default constructor but constructors with optional parameters.
                    // Activator.CreateInstance does not work with this.
                    if (type == typeof(DesktopStrongNameProvider))
                    {
                        strongNameProvider = new DesktopStrongNameProvider();
                    }
                    else if (type == typeof(SigningTestHelpers.VirtualizedStrongNameProvider))
                    {
                        strongNameProvider = new SigningTestHelpers.VirtualizedStrongNameProvider();
                    }
                    else
                    {
                        strongNameProvider = (StrongNameProvider)Activator.CreateInstance(type);
                    }
                }

                var delaySignAttribute = compilationOptionsElement.Attribute(DelaySignAttributeName);
                if (delaySignAttribute != null)
                {
                    delaySign = (bool)delaySignAttribute;
                }

                var outputTypeAttribute = compilationOptionsElement.Attribute(OutputTypeAttributeName);
                if (outputTypeAttribute != null &&
                    outputTypeAttribute.Value == "WindowsRuntimeMetadata")
                {
                    if (rootNamespaceAttribute == null)
                    {
                        rootNamespace = new VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata).RootNamespace;
                    }

                    // VB needs Compilation.ParseOptions set (we do the same at the VS layer)
                    return(language == LanguageNames.CSharp
                       ? (CompilationOptions) new CSharpCompilationOptions(OutputKind.WindowsRuntimeMetadata)
                       : new VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata).WithGlobalImports(globalImports).WithRootNamespace(rootNamespace)
                           .WithParseOptions((VisualBasicParseOptions)parseOptions ?? VisualBasicParseOptions.Default));
                }
            }
            else
            {
                // Add some common global imports by default for VB
                globalImports.Add(GlobalImport.Parse("System"));
                globalImports.Add(GlobalImport.Parse("System.Collections.Generic"));
                globalImports.Add(GlobalImport.Parse("System.Linq"));
            }

            // TODO: Allow these to be specified.
            var languageServices   = workspace.Services.GetLanguageServices(language);
            var metadataService    = workspace.Services.GetService <IMetadataService>();
            var compilationOptions = languageServices.GetService <ICompilationFactoryService>().GetDefaultCompilationOptions();

            compilationOptions = compilationOptions.WithOutputKind(OutputKind.DynamicallyLinkedLibrary)
                                 .WithGeneralDiagnosticOption(reportDiagnostic)
                                 .WithSourceReferenceResolver(SourceFileResolver.Default)
                                 .WithXmlReferenceResolver(XmlFileResolver.Default)
                                 .WithMetadataReferenceResolver(new WorkspaceMetadataFileReferenceResolver(metadataService, new RelativePathResolver(ImmutableArray <string> .Empty, null)))
                                 .WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)
                                 .WithCryptoKeyFile(cryptoKeyFile)
                                 .WithStrongNameProvider(strongNameProvider)
                                 .WithDelaySign(delaySign);

            if (language == LanguageNames.VisualBasic)
            {
                // VB needs Compilation.ParseOptions set (we do the same at the VS layer)
                compilationOptions = ((VisualBasicCompilationOptions)compilationOptions).WithRootNamespace(rootNamespace)
                                     .WithGlobalImports(globalImports)
                                     .WithParseOptions((VisualBasicParseOptions)parseOptions ??
                                                       VisualBasicParseOptions.Default);
            }

            return(compilationOptions);
        }
        public void RespectDefaultTempPath()
        {
            var provider = new DesktopStrongNameProvider(tempPath: null);

            Assert.Equal(Path.GetTempPath(), provider.FileSystem.GetTempPath());
        }
        protected void ReadCompilationOptionsFrom(
            ObjectReader reader,
            out OutputKind outputKind,
            out bool reportSuppressedDiagnostics,
            out string moduleName,
            out string mainTypeName,
            out string scriptClassName,
            out OptimizationLevel optimizationLevel,
            out bool checkOverflow,
            out string cryptoKeyContainer,
            out string cryptoKeyFile,
            out ImmutableArray<byte> cryptoPublicKey,
            out bool? delaySign,
            out Platform platform,
            out ReportDiagnostic generalDiagnosticOption,
            out int warningLevel,
            out IEnumerable<KeyValuePair<string, ReportDiagnostic>> specificDiagnosticOptions,
            out bool concurrentBuild,
            out bool deterministic,
            out bool publicSign,
            out XmlReferenceResolver xmlReferenceResolver,
            out SourceReferenceResolver sourceReferenceResolver,
            out MetadataReferenceResolver metadataReferenceResolver,
            out AssemblyIdentityComparer assemblyIdentityComparer,
            out StrongNameProvider strongNameProvider,
            CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            outputKind = (OutputKind)reader.ReadInt32();
            reportSuppressedDiagnostics = reader.ReadBoolean();
            moduleName = reader.ReadString();
            mainTypeName = reader.ReadString();

            scriptClassName = reader.ReadString();
            optimizationLevel = (OptimizationLevel)reader.ReadInt32();
            checkOverflow = reader.ReadBoolean();

            // REVIEW: is it okay this being not part of snapshot?
            cryptoKeyContainer = reader.ReadString();
            cryptoKeyFile = reader.ReadString();

            cryptoPublicKey = reader.ReadArray<byte>().ToImmutableArrayOrEmpty();

            delaySign = reader.ReadBoolean() ? (bool?)reader.ReadBoolean() : null;

            platform = (Platform)reader.ReadInt32();
            generalDiagnosticOption = (ReportDiagnostic)reader.ReadInt32();

            warningLevel = reader.ReadInt32();

            // REVIEW: I don't think there is a guarantee on ordering of elements in the immutable dictionary.
            //         unfortunately, we need to sort them to make it deterministic
            //         not sure why CompilationOptions uses SequencialEqual to check options equality
            //         when ordering can change result of it even if contents are same.
            var count = reader.ReadInt32();
            List<KeyValuePair<string, ReportDiagnostic>> specificDiagnosticOptionsList = null;

            if (count > 0)
            {
                specificDiagnosticOptionsList = new List<KeyValuePair<string, ReportDiagnostic>>(count);

                for (var i = 0; i < count; i++)
                {
                    var key = reader.ReadString();
                    var value = (ReportDiagnostic)reader.ReadInt32();

                    specificDiagnosticOptionsList.Add(KeyValuePair.Create(key, value));
                }
            }

            specificDiagnosticOptions = specificDiagnosticOptionsList ?? SpecializedCollections.EmptyEnumerable<KeyValuePair<string, ReportDiagnostic>>();

            concurrentBuild = reader.ReadBoolean();
            deterministic = reader.ReadBoolean();
            publicSign = reader.ReadBoolean();

            // REVIEW: What should I do with these. are these service required when compilation is built ourselves, not through
            //         compiler.
            xmlReferenceResolver = XmlFileResolver.Default;
            sourceReferenceResolver = SourceFileResolver.Default;
            metadataReferenceResolver = null;
            assemblyIdentityComparer = DesktopAssemblyIdentityComparer.Default;
            strongNameProvider = new DesktopStrongNameProvider();
        }