예제 #1
0
 // Expects correct arguments.
 private CSharpCompilationOptions(
     OutputKind outputKind,
     string moduleName,
     string mainTypeName,
     string scriptClassName,
     IEnumerable <string> usings,
     bool optimize,
     bool checkOverflow,
     bool allowUnsafe,
     string cryptoKeyContainer,
     string cryptoKeyFile,
     bool?delaySign,
     int fileAlignment,
     ulong baseAddress,
     Platform platform,
     ReportDiagnostic generalDiagnosticOption,
     int warningLevel,
     IEnumerable <KeyValuePair <string, ReportDiagnostic> > specificDiagnosticOptions,
     bool highEntropyVirtualAddressSpace,
     DebugInformationKind debugInformationKind,
     SubsystemVersion subsystemVersion,
     string runtimeMetadataVersion,
     bool concurrentBuild,
     FileResolver fileResolver,
     MetadataReferenceProvider metadataReferenceProvider,
     AssemblyIdentityComparer assemblyIdentityComparer,
     StrongNameProvider strongNameProvider,
     MetadataImportOptions metadataImportOptions,
     IEnumerable <string> features)
     : base(outputKind, moduleName, mainTypeName, scriptClassName, cryptoKeyContainer, cryptoKeyFile, delaySign, optimize, checkOverflow, fileAlignment, baseAddress,
            platform, generalDiagnosticOption, warningLevel, specificDiagnosticOptions, highEntropyVirtualAddressSpace, debugInformationKind,
            subsystemVersion, concurrentBuild, fileResolver, metadataReferenceProvider, assemblyIdentityComparer, strongNameProvider, metadataImportOptions)
 {
     Initialize(usings, allowUnsafe, features, runtimeMetadataVersion);
 }
예제 #2
0
        internal void ValidateOptions(DiagnosticBag diagnostics, CommonMessageProvider messageProvider)
        {
            if (!DebugInformationFormat.IsValid())
            {
                diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidDebugInformationFormat, Location.None, (int)DebugInformationFormat));
            }

            if (OutputNameOverride != null)
            {
                Exception error = MetadataHelpers.CheckAssemblyOrModuleName(OutputNameOverride, argumentName: null);
                if (error != null)
                {
                    diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidOutputName, Location.None, error.Message));
                }
            }

            if (FileAlignment != 0 && !IsValidFileAlignment(FileAlignment))
            {
                diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidFileAlignment, Location.None, FileAlignment));
            }

            if (!SubsystemVersion.Equals(SubsystemVersion.None) && !SubsystemVersion.IsValid)
            {
                diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidSubsystemVersion, Location.None, SubsystemVersion.ToString()));
            }
        }
 // Defaults correspond to the compiler's defaults or indicate that the user did not specify when that is significant.
 // That's significant when one option depends on another's setting. SubsystemVersion depends on Platform and Target.
 public CSharpCompilationOptions(
     OutputKind outputKind,
     string moduleName           = null,
     string mainTypeName         = null,
     string scriptClassName      = WellKnownMemberNames.DefaultScriptClassName,
     IEnumerable <string> usings = null,
     bool optimize             = false,
     bool checkOverflow        = false,
     bool allowUnsafe          = false,
     string cryptoKeyContainer = null,
     string cryptoKeyFile      = null,
     bool?delaySign            = null,
     int fileAlignment         = 0,
     ulong baseAddress         = 0,
     Platform platform         = Platform.AnyCpu,
     ReportDiagnostic generalDiagnosticOption = ReportDiagnostic.Default,
     int warningLevel = 4,
     IEnumerable <KeyValuePair <string, ReportDiagnostic> > specificDiagnosticOptions = null,
     bool highEntropyVirtualAddressSpace       = false,
     DebugInformationKind debugInformationKind = DebugInformationKind.None,
     SubsystemVersion subsystemVersion         = default(SubsystemVersion),
     string runtimeMetadataVersion             = null,
     bool concurrentBuild = true,
     XmlReferenceResolver xmlReferenceResolver           = null,
     SourceReferenceResolver sourceReferenceResolver     = null,
     MetadataReferenceResolver metadataReferenceResolver = null,
     MetadataReferenceProvider metadataReferenceProvider = null,
     AssemblyIdentityComparer assemblyIdentityComparer   = null,
     StrongNameProvider strongNameProvider = null)
     : this(outputKind, moduleName, mainTypeName, scriptClassName, usings, optimize, checkOverflow, allowUnsafe,
            cryptoKeyContainer, cryptoKeyFile, delaySign, fileAlignment, baseAddress, platform, generalDiagnosticOption, warningLevel,
            specificDiagnosticOptions, highEntropyVirtualAddressSpace, debugInformationKind, subsystemVersion, runtimeMetadataVersion, concurrentBuild,
            xmlReferenceResolver, sourceReferenceResolver, metadataReferenceResolver, metadataReferenceProvider, assemblyIdentityComparer, strongNameProvider, MetadataImportOptions.Public, features : null)
 {
 }
예제 #4
0
 private CSharpSerializableCompilationOptions(SerializationInfo info, StreamingContext context)
 {
     this.options = new CSharpCompilationOptions(
         outputKind: (OutputKind)info.GetInt32(OutputKindString),
         moduleName: info.GetString(ModuleNameString),
         mainTypeName: info.GetString(MainTypeNameString),
         scriptClassName: info.GetString(ScriptClassNameString),
         usings: (string[])info.GetValue(UsingsString, typeof(string[])),
         cryptoKeyContainer: info.GetString(CryptoKeyContainerString),
         cryptoKeyFile: info.GetString(CryptoKeyFileString),
         delaySign: (bool?)info.GetValue(DelaySignString, typeof(bool?)),
         optimizationLevel: (OptimizationLevel)info.GetInt32(OptimizeString),
         checkOverflow: info.GetBoolean(CheckOverflowString),
         allowUnsafe: info.GetBoolean(AllowUnsafeString),
         fileAlignment: info.GetInt32(FileAlignmentString),
         baseAddress: info.GetUInt64(BaseAddressString),
         platform: (Platform)info.GetInt32(PlatformString),
         generalDiagnosticOption: (ReportDiagnostic)info.GetInt32(GeneralDiagnosticOptionString),
         warningLevel: info.GetInt32(WarningLevelString),
         specificDiagnosticOptions: ((Dictionary <string, ReportDiagnostic>)info.GetValue(SpecificDiagnosticOptionsString, typeof(Dictionary <string, ReportDiagnostic>))).ToImmutableDictionary(),
         highEntropyVirtualAddressSpace: info.GetBoolean(HighEntropyVirtualAddressSpaceString),
         subsystemVersion: SubsystemVersion.Create(info.GetInt32(SubsystemVersionMajorString), info.GetInt32(SubsystemVersionMinorString)),
         runtimeMetadataVersion: info.GetString(RuntimeMetadataVersionString),
         concurrentBuild: info.GetBoolean(ConcurrentBuildString),
         xmlReferenceResolver: XmlFileResolver.Default,
         sourceReferenceResolver: SourceFileResolver.Default,
         metadataReferenceResolver: MetadataFileReferenceResolver.Default,
         metadataReferenceProvider: MetadataFileReferenceProvider.Default,
         assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default,
         strongNameProvider: new DesktopStrongNameProvider(),
         metadataImportOptions: (MetadataImportOptions)info.GetByte(MetadataImportOptionsString),
         features: ((string[])info.GetValue(FeaturesString, typeof(string[]))).AsImmutable());
 }
예제 #5
0
 internal ModulePropertiesForSerialization(
     Guid persistentIdentifier,
     ushort fileAlignment,
     string targetRuntimeVersion,
     Platform platform,
     bool trackDebugData,
     ulong baseAddress,
     ulong sizeOfHeapReserve,
     ulong sizeOfHeapCommit,
     ulong sizeOfStackReserve,
     ulong sizeOfStackCommit,
     bool enableHighEntropyVA,
     bool strongNameSigned,
     bool configureToExecuteInAppContainer,
     SubsystemVersion subsystemVersion)
 {
     this.PersistentIdentifier             = persistentIdentifier;
     this.FileAlignment                    = fileAlignment;
     this.TargetRuntimeVersion             = targetRuntimeVersion;
     this.Platform                         = platform;
     this.TrackDebugData                   = trackDebugData;
     this.BaseAddress                      = baseAddress;
     this.SizeOfHeapReserve                = sizeOfHeapReserve;
     this.SizeOfHeapCommit                 = sizeOfHeapCommit;
     this.SizeOfStackReserve               = sizeOfStackReserve;
     this.SizeOfStackCommit                = sizeOfStackCommit;
     this.EnableHighEntropyVA              = enableHighEntropyVA;
     this.StrongNameSigned                 = strongNameSigned;
     this.ConfigureToExecuteInAppContainer = configureToExecuteInAppContainer;
     this.SubsystemVersion                 = subsystemVersion.Equals(SubsystemVersion.None)
         ? SubsystemVersion.Default(OutputKind.ConsoleApplication, this.Platform)
         : subsystemVersion;
 }
예제 #6
0
        public bool Equals(EmitOptions?other)
        {
            if (ReferenceEquals(other, null))
            {
                return(false);
            }

            return(EmitMetadataOnly == other.EmitMetadataOnly &&
                   BaseAddress == other.BaseAddress &&
                   FileAlignment == other.FileAlignment &&
                   HighEntropyVirtualAddressSpace == other.HighEntropyVirtualAddressSpace &&
                   SubsystemVersion.Equals(other.SubsystemVersion) &&
                   DebugInformationFormat == other.DebugInformationFormat &&
                   PdbFilePath == other.PdbFilePath &&
                   PdbChecksumAlgorithm == other.PdbChecksumAlgorithm &&
                   OutputNameOverride == other.OutputNameOverride &&
                   RuntimeMetadataVersion == other.RuntimeMetadataVersion &&
                   TolerateErrors == other.TolerateErrors &&
                   IncludePrivateMembers == other.IncludePrivateMembers &&
                   InstrumentationKinds
                   .NullToEmpty()
                   .SequenceEqual(other.InstrumentationKinds.NullToEmpty(), (a, b) => a == b) &&
                   DefaultSourceFileEncoding == other.DefaultSourceFileEncoding &&
                   FallbackSourceFileEncoding == other.FallbackSourceFileEncoding);
        }
예제 #7
0
        internal void ValidateOptions(DiagnosticBag diagnostics, CommonMessageProvider messageProvider)
        {
            if (!DebugInformationFormat.IsValid())
            {
                diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidDebugInformationFormat, Location.None, (int)DebugInformationFormat));
            }

            foreach (var instrumentationKind in InstrumentationKinds)
            {
                if (!instrumentationKind.IsValid())
                {
                    diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidInstrumentationKind, Location.None, (int)instrumentationKind));
                }
            }

            if (OutputNameOverride != null)
            {
                MetadataHelpers.CheckAssemblyOrModuleName(OutputNameOverride, messageProvider, messageProvider.ERR_InvalidOutputName, diagnostics);
            }

            if (FileAlignment != 0 && !IsValidFileAlignment(FileAlignment))
            {
                diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidFileAlignment, Location.None, FileAlignment));
            }

            if (!SubsystemVersion.Equals(SubsystemVersion.None) && !SubsystemVersion.IsValid)
            {
                diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidSubsystemVersion, Location.None, SubsystemVersion.ToString()));
            }
        }
 internal ModulePropertiesForSerialization(
     Guid persistentIdentifier,
     ushort fileAlignment,
     string targetRuntimeVersion,
     Platform platform,
     bool trackDebugData,
     ulong baseAddress,
     ulong sizeOfHeapReserve,
     ulong sizeOfHeapCommit,
     ulong sizeOfStackReserve,
     ulong sizeOfStackCommit,
     bool enableHighEntropyVA,
     bool strongNameSigned,
     bool configureToExecuteInAppContainer,
     SubsystemVersion subsystemVersion)
 {
     this.PersistentIdentifier = (persistentIdentifier == default(Guid)) ? Guid.NewGuid() : persistentIdentifier;
     this.FileAlignment = fileAlignment;
     this.TargetRuntimeVersion = targetRuntimeVersion;
     this.Platform = platform;
     this.TrackDebugData = trackDebugData;
     this.BaseAddress = baseAddress;
     this.SizeOfHeapReserve = sizeOfHeapReserve;
     this.SizeOfHeapCommit = sizeOfHeapCommit;
     this.SizeOfStackReserve = sizeOfStackReserve;
     this.SizeOfStackCommit = sizeOfStackCommit;
     this.EnableHighEntropyVA = enableHighEntropyVA;
     this.StrongNameSigned = strongNameSigned;
     this.ConfigureToExecuteInAppContainer = configureToExecuteInAppContainer;
     this.SubsystemVersion = subsystemVersion.Equals(SubsystemVersion.None)
         ? SubsystemVersion.Default(OutputKind.ConsoleApplication, this.Platform)
         : subsystemVersion;
 }
예제 #9
0
 // 2.7 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
 public EmitOptions(
     bool metadataOnly,
     DebugInformationFormat debugInformationFormat,
     string pdbFilePath,
     string outputNameOverride,
     int fileAlignment,
     ulong baseAddress,
     bool highEntropyVirtualAddressSpace,
     SubsystemVersion subsystemVersion,
     string runtimeMetadataVersion,
     bool tolerateErrors,
     bool includePrivateMembers,
     ImmutableArray <InstrumentationKind> instrumentationKinds)
     : this(
         metadataOnly,
         debugInformationFormat,
         pdbFilePath,
         outputNameOverride,
         fileAlignment,
         baseAddress,
         highEntropyVirtualAddressSpace,
         subsystemVersion,
         runtimeMetadataVersion,
         tolerateErrors,
         includePrivateMembers,
         instrumentationKinds,
         pdbChecksumAlgorithm : default)
 {
 }
예제 #10
0
 public EmitOptions(
     bool metadataOnly = false,
     DebugInformationFormat debugInformationFormat = 0,
     string pdbFilePath                  = null,
     string outputNameOverride           = null,
     int fileAlignment                   = 0,
     ulong baseAddress                   = 0,
     bool highEntropyVirtualAddressSpace = false,
     SubsystemVersion subsystemVersion   = default,
     string runtimeMetadataVersion       = null,
     bool tolerateErrors                 = false,
     bool includePrivateMembers          = true,
     ImmutableArray <InstrumentationKind> instrumentationKinds = default,
     HashAlgorithmName?pdbChecksumAlgorithm = null)
 {
     EmitMetadataOnly               = metadataOnly;
     DebugInformationFormat         = (debugInformationFormat == 0) ? DebugInformationFormat.Pdb : debugInformationFormat;
     PdbFilePath                    = pdbFilePath;
     OutputNameOverride             = outputNameOverride;
     FileAlignment                  = fileAlignment;
     BaseAddress                    = baseAddress;
     HighEntropyVirtualAddressSpace = highEntropyVirtualAddressSpace;
     SubsystemVersion               = subsystemVersion;
     RuntimeMetadataVersion         = runtimeMetadataVersion;
     TolerateErrors                 = tolerateErrors;
     IncludePrivateMembers          = includePrivateMembers;
     InstrumentationKinds           = instrumentationKinds.NullToEmpty();
     PdbChecksumAlgorithm           = pdbChecksumAlgorithm ?? HashAlgorithmName.SHA256;
 }
예제 #11
0
 // 1.2 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
 public EmitOptions(
     bool metadataOnly,
     DebugInformationFormat debugInformationFormat,
     string pdbFilePath,
     string outputNameOverride,
     int fileAlignment,
     ulong baseAddress,
     bool highEntropyVirtualAddressSpace,
     SubsystemVersion subsystemVersion,
     string runtimeMetadataVersion,
     bool tolerateErrors,
     bool includePrivateMembers)
     : this(
         metadataOnly,
         debugInformationFormat,
         pdbFilePath,
         outputNameOverride,
         fileAlignment,
         baseAddress,
         highEntropyVirtualAddressSpace,
         subsystemVersion,
         runtimeMetadataVersion,
         tolerateErrors,
         includePrivateMembers,
         instrument : "")
 {
 }
예제 #12
0
 public EmitOptions(
     bool metadataOnly = false,
     DebugInformationFormat debugInformationFormat = 0,
     string pdbFilePath                  = null,
     string outputNameOverride           = null,
     int fileAlignment                   = 0,
     ulong baseAddress                   = 0,
     bool highEntropyVirtualAddressSpace = false,
     SubsystemVersion subsystemVersion   = default(SubsystemVersion),
     string runtimeMetadataVersion       = null,
     bool tolerateErrors                 = false,
     bool includePrivateMembers          = false,
     string instrument                   = "")
 {
     this.EmitMetadataOnly               = metadataOnly;
     this.DebugInformationFormat         = (debugInformationFormat == 0) ? DebugInformationFormat.Pdb : debugInformationFormat;
     this.PdbFilePath                    = pdbFilePath;
     this.OutputNameOverride             = outputNameOverride;
     this.FileAlignment                  = fileAlignment;
     this.BaseAddress                    = baseAddress;
     this.HighEntropyVirtualAddressSpace = highEntropyVirtualAddressSpace;
     this.SubsystemVersion               = subsystemVersion;
     this.RuntimeMetadataVersion         = runtimeMetadataVersion;
     this.TolerateErrors                 = tolerateErrors;
     this.IncludePrivateMembers          = includePrivateMembers;
     this.Instrument = instrument;
 }
예제 #13
0
        public unsafe EmitResult Emit(
            Stream rebuildPeStream,
            Compilation rebuildCompilation,
            ImmutableArray <EmbeddedText> embeddedTexts,
            CancellationToken cancellationToken)
        {
            var peHeader       = OptionsReader.PeReader.PEHeaders.PEHeader !;
            var win32Resources = OptionsReader.PeReader.GetSectionData(peHeader.ResourceTableDirectory.RelativeVirtualAddress);

            using var win32ResourceStream = win32Resources.Pointer != null
                ? new UnmanagedMemoryStream(win32Resources.Pointer, win32Resources.Length)
                : null;

            var sourceLink = OptionsReader.GetSourceLinkUTF8();

            var debugEntryPoint = getDebugEntryPoint();

            var emitResult = rebuildCompilation.Emit(
                peStream: rebuildPeStream,
                pdbStream: null,
                xmlDocumentationStream: null,
                win32Resources: win32ResourceStream,
                useRawWin32Resources: true,
                manifestResources: OptionsReader.GetManifestResources(),
                options: new EmitOptions(
                    debugInformationFormat: DebugInformationFormat.Embedded,
                    highEntropyVirtualAddressSpace: (peHeader.DllCharacteristics & DllCharacteristics.HighEntropyVirtualAddressSpace) != 0,
                    subsystemVersion: SubsystemVersion.Create(peHeader.MajorSubsystemVersion, peHeader.MinorSubsystemVersion)),
                debugEntryPoint: debugEntryPoint,
                metadataPEStream: null,
                pdbOptionsBlobReader: OptionsReader.GetMetadataCompilationOptionsBlobReader(),
                sourceLinkStream: sourceLink != null ? new MemoryStream(sourceLink) : null,
                embeddedTexts: embeddedTexts,
                cancellationToken: cancellationToken);

            return(emitResult);

            IMethodSymbol?getDebugEntryPoint()
            {
                if (OptionsReader.GetMainMethodInfo() is (string mainTypeName, string mainMethodName))
                {
                    var typeSymbol = rebuildCompilation.GetTypeByMetadataName(mainTypeName);
                    if (typeSymbol is object)
                    {
                        var methodSymbols = typeSymbol
                                            .GetMembers(mainMethodName)
                                            .OfType <IMethodSymbol>();
                        return(methodSymbols.FirstOrDefault());
                    }
                }

                return(null);
            }
        }
        public CSharpCompilationOptions WithSubsystemVersion(SubsystemVersion subsystemVersion)
        {
            if (subsystemVersion.Equals(this.SubsystemVersion))
            {
                return(this);
            }

            return(new CSharpCompilationOptions(this)
            {
                SubsystemVersion = subsystemVersion
            });
        }
예제 #15
0
        public EmitOptions WithSubsystemVersion(SubsystemVersion subsystemVersion)
        {
            if (subsystemVersion.Equals(SubsystemVersion))
            {
                return(this);
            }

            return(new EmitOptions(this)
            {
                SubsystemVersion = subsystemVersion
            });
        }
예제 #16
0
        internal void ValidateOptions(DiagnosticBag diagnostics, CommonMessageProvider messageProvider, bool isDeterministic)
        {
            if (!DebugInformationFormat.IsValid())
            {
                diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidDebugInformationFormat, Location.None, (int)DebugInformationFormat));
            }

            foreach (var instrumentationKind in InstrumentationKinds)
            {
                if (!instrumentationKind.IsValid())
                {
                    diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidInstrumentationKind, Location.None, (int)instrumentationKind));
                }
            }

            if (OutputNameOverride != null)
            {
                MetadataHelpers.CheckAssemblyOrModuleName(OutputNameOverride, messageProvider, messageProvider.ERR_InvalidOutputName, diagnostics);
            }

            if (FileAlignment != 0 && !IsValidFileAlignment(FileAlignment))
            {
                diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidFileAlignment, Location.None, FileAlignment));
            }

            if (!SubsystemVersion.Equals(SubsystemVersion.None) && !SubsystemVersion.IsValid)
            {
                diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidSubsystemVersion, Location.None, SubsystemVersion.ToString()));
            }

            if (PdbChecksumAlgorithm.Name != null)
            {
                try
                {
                    IncrementalHash.CreateHash(PdbChecksumAlgorithm).Dispose();
                }
                catch
                {
                    diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidHashAlgorithmName, Location.None, PdbChecksumAlgorithm.ToString()));
                }
            }
            else if (isDeterministic)
            {
                diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidHashAlgorithmName, Location.None, ""));
            }

            if (PdbFilePath != null && !PathUtilities.IsValidFilePath(PdbFilePath))
            {
                diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.FTL_InvalidInputFileName, Location.None, PdbFilePath));
            }
        }
예제 #17
0
 public override int GetHashCode()
 {
     return(Hash.Combine(
                EmitMetadataOnly,
                Hash.Combine(
                    BaseAddress.GetHashCode(),
                    Hash.Combine(
                        FileAlignment,
                        Hash.Combine(
                            HighEntropyVirtualAddressSpace,
                            Hash.Combine(
                                SubsystemVersion.GetHashCode(),
                                Hash.Combine(
                                    (int)DebugInformationFormat,
                                    Hash.Combine(
                                        PdbFilePath,
                                        Hash.Combine(
                                            PdbChecksumAlgorithm.GetHashCode(),
                                            Hash.Combine(
                                                OutputNameOverride,
                                                Hash.Combine(
                                                    RuntimeMetadataVersion,
                                                    Hash.Combine(
                                                        TolerateErrors,
                                                        Hash.Combine(
                                                            IncludePrivateMembers,
                                                            Hash.Combine(
                                                                Hash.CombineValues(
                                                                    InstrumentationKinds
                                                                    ),
                                                                Hash.Combine(
                                                                    DefaultSourceFileEncoding,
                                                                    Hash.Combine(
                                                                        FallbackSourceFileEncoding,
                                                                        0
                                                                        )
                                                                    )
                                                                )
                                                            )
                                                        )
                                                    )
                                                )
                                            )
                                        )
                                    )
                                )
                            )
                        )
                    )
                ));
 }
예제 #18
0
                public bool SetSubsystemVersion(string subsystemVersion)
                {
                    SubsystemVersion parsedVersion;

                    if (!string.IsNullOrEmpty(subsystemVersion))
                    {
                        if (SubsystemVersion.TryParse(subsystemVersion, out parsedVersion))
                        {
                            this.CompilationOptions = this.CompilationOptions.WithSubsystemVersion(parsedVersion);
                        }

                        return(true);
                    }

                    return(false);
                }
예제 #19
0
        private static Microsoft.CodeAnalysis.Emit.EmitOptions GetEmitOptions(EmitOptions options)
        {
            SubsystemVersion subsystemVersion;

            SubsystemVersion.TryParse(options.SubsystemVersion, out subsystemVersion);
            return(new Microsoft.CodeAnalysis.Emit.EmitOptions(
                       metadataOnly: false,
                       debugInformationFormat: DebugInformationFormat.Pdb,
                       pdbFilePath: null,
                       outputNameOverride: null,
                       fileAlignment: options.FileAlignment,
                       baseAddress: options.BaseAddress,
                       highEntropyVirtualAddressSpace: options.HighEntropyVirtualAddressSpace,
                       subsystemVersion: subsystemVersion,
                       runtimeMetadataVersion: null,
                       tolerateErrors: false,
                       includePrivateMembers: true,
                       instrument: options.Instrument));
        }
예제 #20
0
 // Expects correct arguments.
 internal CSharpCompilationOptions(
     OutputKind outputKind,
     string moduleName,
     string mainTypeName,
     string scriptClassName,
     IEnumerable <string> usings,
     OptimizationLevel optimizationLevel,
     bool checkOverflow,
     bool allowUnsafe,
     string cryptoKeyContainer,
     string cryptoKeyFile,
     bool?delaySign,
     int fileAlignment,
     ulong baseAddress,
     Platform platform,
     ReportDiagnostic generalDiagnosticOption,
     int warningLevel,
     IEnumerable <KeyValuePair <string, ReportDiagnostic> > specificDiagnosticOptions,
     bool highEntropyVirtualAddressSpace,
     SubsystemVersion subsystemVersion,
     string runtimeMetadataVersion,
     bool concurrentBuild,
     XmlReferenceResolver xmlReferenceResolver,
     SourceReferenceResolver sourceReferenceResolver,
     MetadataReferenceResolver metadataReferenceResolver,
     MetadataReferenceProvider metadataReferenceProvider,
     AssemblyIdentityComparer assemblyIdentityComparer,
     StrongNameProvider strongNameProvider,
     MetadataImportOptions metadataImportOptions,
     ImmutableArray <string> features)
     : base(outputKind, moduleName, mainTypeName, scriptClassName, cryptoKeyContainer, cryptoKeyFile, delaySign, optimizationLevel, checkOverflow, fileAlignment, baseAddress,
            platform, generalDiagnosticOption, warningLevel, specificDiagnosticOptions.ToImmutableDictionaryOrEmpty(), highEntropyVirtualAddressSpace,
            subsystemVersion, concurrentBuild, xmlReferenceResolver, sourceReferenceResolver, metadataReferenceResolver, metadataReferenceProvider, assemblyIdentityComparer, strongNameProvider, metadataImportOptions, features)
 {
     this.Usings                 = usings.AsImmutableOrEmpty();
     this.AllowUnsafe            = allowUnsafe;
     this.RuntimeMetadataVersion = runtimeMetadataVersion;
 }
        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));
        }
예제 #22
0
 // Expects correct arguments.
 internal CompilationOptions(
     OutputKind outputKind,
     string moduleName,
     string mainTypeName,
     string scriptClassName,
     string cryptoKeyContainer,
     string cryptoKeyFile,
     bool? delaySign,
     bool optimize,
     bool checkOverflow,
     int fileAlignment,
     ulong baseAddress,
     Platform platform,
     ReportDiagnostic generalDiagnosticOption,
     int warningLevel,
     IEnumerable<KeyValuePair<string, ReportDiagnostic>> specificDiagnosticOptions,
     bool highEntropyVirtualAddressSpace,
     DebugInformationKind debugInformationKind,
     SubsystemVersion subsystemVersion,
     bool concurrentBuild,
     XmlReferenceResolver xmlReferenceResolver,
     SourceReferenceResolver sourceReferenceResolver,
     MetadataReferenceResolver metadataReferenceResolver,
     MetadataReferenceProvider metadataReferenceProvider,
     AssemblyIdentityComparer assemblyIdentityComparer,
     StrongNameProvider strongNameProvider,
     MetadataImportOptions metadataImportOptions)
 {
     Initialize(
         outputKind, moduleName, mainTypeName, scriptClassName, cryptoKeyContainer, cryptoKeyFile, delaySign, optimize, checkOverflow, fileAlignment, 
         baseAddress, platform, generalDiagnosticOption, warningLevel, specificDiagnosticOptions, highEntropyVirtualAddressSpace, debugInformationKind, 
         subsystemVersion, concurrentBuild, xmlReferenceResolver, sourceReferenceResolver, metadataReferenceResolver, metadataReferenceProvider, assemblyIdentityComparer, strongNameProvider, 
         metadataImportOptions);
 }
예제 #23
0
        public unsafe EmitResult Emit(
            Stream rebuildPeStream,
            Stream?rebuildPdbStream,
            Compilation rebuildCompilation,
            ImmutableArray <EmbeddedText> embeddedTexts,
            CancellationToken cancellationToken)
        {
            var peHeader       = OptionsReader.PeReader.PEHeaders.PEHeader !;
            var win32Resources = OptionsReader.PeReader.GetSectionData(peHeader.ResourceTableDirectory.RelativeVirtualAddress);

            using var win32ResourceStream = win32Resources.Pointer != null
                ? new UnmanagedMemoryStream(win32Resources.Pointer, win32Resources.Length)
                : null;

            var sourceLink = OptionsReader.GetSourceLinkUTF8();

            var    debugEntryPoint = getDebugEntryPoint();
            string?pdbFilePath;
            DebugInformationFormat debugInformationFormat;

            if (OptionsReader.HasEmbeddedPdb)
            {
                if (rebuildPdbStream is object)
                {
                    throw new ArgumentException("PDB stream must be null because the compilation has an embedded PDB", nameof(rebuildPdbStream));
                }

                debugInformationFormat = DebugInformationFormat.Embedded;
                pdbFilePath            = null;
            }
            else
            {
                if (rebuildPdbStream is null)
                {
                    throw new ArgumentException("A non-null PDB stream must be provided because the compilation does not have an embedded PDB", nameof(rebuildPdbStream));
                }

                debugInformationFormat = DebugInformationFormat.PortablePdb;
                var codeViewEntry = OptionsReader.PeReader.ReadDebugDirectory().Single(entry => entry.Type == DebugDirectoryEntryType.CodeView);
                var codeView      = OptionsReader.PeReader.ReadCodeViewDebugDirectoryData(codeViewEntry);
                pdbFilePath = codeView.Path ?? throw new InvalidOperationException("Could not get PDB file path");
            }

            var emitResult = rebuildCompilation.Emit(
                peStream: rebuildPeStream,
                pdbStream: rebuildPdbStream,
                xmlDocumentationStream: null,
                win32Resources: win32ResourceStream,
                useRawWin32Resources: true,
                manifestResources: OptionsReader.GetManifestResources(),
                options: new EmitOptions(
                    debugInformationFormat: debugInformationFormat,
                    pdbFilePath: pdbFilePath,
                    highEntropyVirtualAddressSpace: (peHeader.DllCharacteristics & DllCharacteristics.HighEntropyVirtualAddressSpace) != 0,
                    subsystemVersion: SubsystemVersion.Create(peHeader.MajorSubsystemVersion, peHeader.MinorSubsystemVersion)),
                debugEntryPoint: debugEntryPoint,
                metadataPEStream: null,
                pdbOptionsBlobReader: OptionsReader.GetMetadataCompilationOptionsBlobReader(),
                sourceLinkStream: sourceLink != null ? new MemoryStream(sourceLink) : null,
                embeddedTexts: embeddedTexts,
                cancellationToken: cancellationToken);

            return(emitResult);

            IMethodSymbol?getDebugEntryPoint()
            {
                if (OptionsReader.GetMainMethodInfo() is (string mainTypeName, string mainMethodName))
                {
                    var typeSymbol = rebuildCompilation.GetTypeByMetadataName(mainTypeName);
                    if (typeSymbol is object)
                    {
                        var methodSymbols = typeSymbol
                                            .GetMembers(mainMethodName)
                                            .OfType <IMethodSymbol>();
                        return(methodSymbols.FirstOrDefault());
                    }
                }

                return(null);
            }
        }
        // Expects correct arguments.
        internal CompilationOptions(
            OutputKind outputKind,
            string moduleName,
            string mainTypeName,
            string scriptClassName,
            string cryptoKeyContainer,
            string cryptoKeyFile,
            bool? delaySign,
            OptimizationLevel optimizationLevel,
            bool checkOverflow,
            int fileAlignment,
            ulong baseAddress,
            Platform platform,
            ReportDiagnostic generalDiagnosticOption,
            int warningLevel,
            ImmutableDictionary<string, ReportDiagnostic> specificDiagnosticOptions,
            bool highEntropyVirtualAddressSpace,
            SubsystemVersion subsystemVersion,
            bool concurrentBuild,
            XmlReferenceResolver xmlReferenceResolver,
            SourceReferenceResolver sourceReferenceResolver,
            MetadataReferenceResolver metadataReferenceResolver,
            MetadataReferenceProvider metadataReferenceProvider,
            AssemblyIdentityComparer assemblyIdentityComparer,
            StrongNameProvider strongNameProvider,
            MetadataImportOptions metadataImportOptions,
            ImmutableArray<string> features)
        {
            this.OutputKind = outputKind;
            this.ModuleName = moduleName;
            this.MainTypeName = mainTypeName;
            this.ScriptClassName = scriptClassName;
            this.CryptoKeyContainer = cryptoKeyContainer;
            this.CryptoKeyFile = cryptoKeyFile;
            this.DelaySign = delaySign;
            this.CheckOverflow = checkOverflow;
            this.FileAlignment = fileAlignment;
            this.BaseAddress = baseAddress;
            this.Platform = platform;
            this.GeneralDiagnosticOption = generalDiagnosticOption;
            this.WarningLevel = warningLevel;
            this.SpecificDiagnosticOptions = specificDiagnosticOptions;
            this.HighEntropyVirtualAddressSpace = highEntropyVirtualAddressSpace;
            this.OptimizationLevel = optimizationLevel;
            this.ConcurrentBuild = concurrentBuild;
            this.SubsystemVersion = subsystemVersion;
            this.XmlReferenceResolver = xmlReferenceResolver;
            this.SourceReferenceResolver = sourceReferenceResolver;
            this.MetadataReferenceResolver = metadataReferenceResolver;
            this.MetadataReferenceProvider = metadataReferenceProvider;
            this.StrongNameProvider = strongNameProvider;
            this.AssemblyIdentityComparer = assemblyIdentityComparer ?? AssemblyIdentityComparer.Default;
            this.MetadataImportOptions = metadataImportOptions;
            this.Features = features;

            this.lazyErrors = new Lazy<ImmutableArray<Diagnostic>>(() =>
            {
                var builder = ArrayBuilder<Diagnostic>.GetInstance();
                ValidateOptions(builder);
                return builder.ToImmutableAndFree();
            });
        }
예제 #25
0
        public unsafe EmitResult Emit(
            Stream rebuildPeStream,
            Stream?rebuildPdbStream,
            Compilation rebuildCompilation,
            ImmutableArray <EmbeddedText> embeddedTexts,
            CancellationToken cancellationToken)
        {
            var peHeader       = OptionsReader.PeReader.PEHeaders.PEHeader !;
            var win32Resources = OptionsReader.PeReader.GetSectionData(peHeader.ResourceTableDirectory.RelativeVirtualAddress);

            using var win32ResourceStream = win32Resources.Pointer != null
                ? new UnmanagedMemoryStream(win32Resources.Pointer, win32Resources.Length)
                : null;

            var sourceLink = OptionsReader.GetSourceLinkUtf8();

            var    debugEntryPoint = getDebugEntryPoint();
            string?pdbFilePath;
            DebugInformationFormat debugInformationFormat;

            if (OptionsReader.HasEmbeddedPdb)
            {
                if (rebuildPdbStream is object)
                {
                    throw new ArgumentException(RebuildResources.PDB_stream_must_be_null_because_the_compilation_has_an_embedded_PDB, nameof(rebuildPdbStream));
                }

                debugInformationFormat = DebugInformationFormat.Embedded;
                pdbFilePath            = null;
            }
            else
            {
                if (rebuildPdbStream is null)
                {
                    throw new ArgumentException(RebuildResources.A_non_null_PDB_stream_must_be_provided_because_the_compilation_does_not_have_an_embedded_PDB, nameof(rebuildPdbStream));
                }

                debugInformationFormat = DebugInformationFormat.PortablePdb;
                var codeViewEntry = OptionsReader.PeReader.ReadDebugDirectory().Single(entry => entry.Type == DebugDirectoryEntryType.CodeView);
                var codeView      = OptionsReader.PeReader.ReadCodeViewDebugDirectoryData(codeViewEntry);
                pdbFilePath = codeView.Path ?? throw new InvalidOperationException(RebuildResources.Could_not_get_PDB_file_path);
            }

            var rebuildData = new RebuildData(
                OptionsReader.GetMetadataCompilationOptionsBlobReader(),
                getNonSourceFileDocumentNames(OptionsReader.PdbReader, OptionsReader.GetSourceFileCount()));
            var emitResult = rebuildCompilation.Emit(
                peStream: rebuildPeStream,
                pdbStream: rebuildPdbStream,
                xmlDocumentationStream: null,
                win32Resources: win32ResourceStream,
                manifestResources: OptionsReader.GetManifestResources(),
                options: new EmitOptions(
                    debugInformationFormat: debugInformationFormat,
                    pdbFilePath: pdbFilePath,
                    highEntropyVirtualAddressSpace: (peHeader.DllCharacteristics & DllCharacteristics.HighEntropyVirtualAddressSpace) != 0,
                    subsystemVersion: SubsystemVersion.Create(peHeader.MajorSubsystemVersion, peHeader.MinorSubsystemVersion)),
                debugEntryPoint: debugEntryPoint,
                metadataPEStream: null,
                rebuildData: rebuildData,
                sourceLinkStream: sourceLink != null ? new MemoryStream(sourceLink) : null,
                embeddedTexts: embeddedTexts,
                cancellationToken: cancellationToken);

            return(emitResult);
        internal override void ValidateOptions(ArrayBuilder <Diagnostic> builder)
        {
            //  /main & /target:{library|netmodule|winmdobj}
            if (this.MainTypeName != null)
            {
                if (this.OutputKind.IsValid() && !this.OutputKind.IsApplication())
                {
                    builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_NoMainOnDLL));
                }

                if (!MainTypeName.IsValidClrTypeName())
                {
                    builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadCompilationOptionValue, "MainTypeName", MainTypeName));
                }
            }

            if (FileAlignment != 0 && !IsValidFileAlignment(FileAlignment))
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadFileAlignment, FileAlignment));
            }

            if (!Platform.IsValid())
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadPlatformType, Platform));
            }

            if (ModuleName != null)
            {
                Exception e = MetadataHelpers.CheckAssemblyOrModuleName(ModuleName, "ModuleName");
                if (e != null)
                {
                    builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadCompilationOption, e.Message));
                }
            }

            if (!OutputKind.IsValid())
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadCompilationOptionValue, "OutputKind", OutputKind));
            }

            if (!DebugInformationKind.IsValid())
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadCompilationOptionValue, "DebugInformationKind", DebugInformationKind));
            }

            if (!SubsystemVersion.Equals(SubsystemVersion.None) && !SubsystemVersion.IsValid)
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadSubsystemVersion, SubsystemVersion.ToString()));
            }

            if (ScriptClassName == null || !ScriptClassName.IsValidClrTypeName())
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadCompilationOptionValue, "ScriptClassName", ScriptClassName ?? "null"));
            }

            if (Features == null)
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadCompilationOptionValue, "Features", "null"));
            }

            if (WarningLevel < 0 || WarningLevel > 4)
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadCompilationOptionValue, "WarningLevel", WarningLevel));
            }

            if (Usings != null && Usings.Any(u => !u.IsValidClrNamespaceName()))
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadCompilationOptionValue, "Usings", Usings.Where(u => !u.IsValidClrNamespaceName()).First() ?? "null"));
            }

            if (Platform == Platform.AnyCpu32BitPreferred && OutputKind.IsValid() && !(OutputKind == OutputKind.ConsoleApplication || OutputKind == OutputKind.WindowsApplication || OutputKind == OutputKind.WindowsRuntimeApplication))
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadPrefer32OnLib));
            }

            // TODO: add check for
            //          (kind == 'arm' || kind == 'appcontainer' || kind == 'winmdobj') &&
            //          (version >= "6.2")
        }