private static void WritePEImage(
            Stream peStream,
            MetadataBuilder metadataBuilder,
            BlobBuilder ilBuilder,
            MethodDefinitionHandle entryPointHandle
            )
        {
            // Create executable with the managed metadata from the specified MetadataBuilder.

            var peHeaderBuilder = new PEHeaderBuilder(
                imageCharacteristics: Characteristics.ExecutableImage
                );

            var peBuilder = new ManagedPEBuilder(
                peHeaderBuilder,
                new MetadataRootBuilder(metadataBuilder),
                ilBuilder,
                entryPoint: entryPointHandle,
                flags: CorFlags.ILOnly,
                deterministicIdProvider: content => s_contentId);

            // Write executable into the specified stream.

            var           peBlob    = new BlobBuilder();
            BlobContentId contentId = peBuilder.Serialize(peBlob);

            peBlob.WriteContentTo(peStream);
        }
Пример #2
0
        private static void WritePEImage(
            Stream peStream, 
            MetadataBuilder metadataBuilder, 
            BlobBuilder ilBuilder, 
            MethodDefinitionHandle entryPointHandle,
            Blob mvidFixup = default(Blob),
            byte[] privateKeyOpt = null)
        {
            var peBuilder = new ManagedPEBuilder(
                entryPointHandle.IsNil ? PEHeaderBuilder.CreateLibraryHeader() : PEHeaderBuilder.CreateExecutableHeader(),
                new MetadataRootBuilder(metadataBuilder),
                ilBuilder,
                entryPoint: entryPointHandle,
                flags: CorFlags.ILOnly | (privateKeyOpt != null ? CorFlags.StrongNameSigned : 0),
                deterministicIdProvider: content => s_contentId);

            var peBlob = new BlobBuilder();

            var contentId = peBuilder.Serialize(peBlob);

            if (!mvidFixup.IsDefault)
            {
                new BlobWriter(mvidFixup).WriteGuid(contentId.Guid);
            }

            if (privateKeyOpt != null)
            {
                peBuilder.Sign(peBlob, content => SigningUtilities.CalculateRsaSignature(content, privateKeyOpt));
            }

            peBlob.WriteContentTo(peStream);
        }
Пример #3
0
        private static void WritePEImage(
            Stream peStream,
            MetadataBuilder metadataBuilder,
            BlobBuilder ilBuilder,
            MethodDefinitionHandle entryPointHandle,
            Blob mvidFixup       = default(Blob),
            byte[] privateKeyOpt = null)
        {
            var peBuilder = new ManagedPEBuilder(
                entryPointHandle.IsNil ? PEHeaderBuilder.CreateLibraryHeader() : PEHeaderBuilder.CreateExecutableHeader(),
                new MetadataRootBuilder(metadataBuilder),
                ilBuilder,
                entryPoint: entryPointHandle,
                flags: CorFlags.ILOnly | (privateKeyOpt != null ? CorFlags.StrongNameSigned : 0),
                deterministicIdProvider: content => s_contentId);

            var peBlob = new BlobBuilder();

            BlobContentId contentId;

            peBuilder.Serialize(peBlob, out contentId);

            if (!mvidFixup.IsDefault)
            {
                new BlobWriter(mvidFixup).WriteGuid(contentId.Guid);
            }

            if (privateKeyOpt != null)
            {
                peBuilder.Sign(peBlob, content => SigningUtilities.CalculateRsaSignature(content, privateKeyOpt));
            }

            peBlob.WriteContentTo(peStream);
        }
Пример #4
0
        public unsafe void NativeResources()
        {
            var peStream        = new MemoryStream();
            var ilBuilder       = new BlobBuilder();
            var metadataBuilder = new MetadataBuilder();

            var peBuilder = new ManagedPEBuilder(
                PEHeaderBuilder.CreateLibraryHeader(),
                new MetadataRootBuilder(metadataBuilder),
                ilBuilder,
                nativeResources: new TestResourceSectionBuilder(),
                deterministicIdProvider: content => s_contentId);

            var peBlob = new BlobBuilder();

            var contentId = peBuilder.Serialize(peBlob);

            peBlob.WriteContentTo(peStream);

            peStream.Position = 0;
            var peReader      = new PEReader(peStream);
            var sectionHeader = peReader.PEHeaders.SectionHeaders.Single(s => s.Name == ".rsrc");

            var image = peReader.GetEntireImage();

            var reader = new BlobReader(image.Pointer + sectionHeader.PointerToRawData, sectionHeader.SizeOfRawData);

            Assert.Equal(0x12345678, reader.ReadInt32());
            Assert.Equal(sectionHeader.PointerToRawData, reader.ReadInt32());
            Assert.Equal(sectionHeader.VirtualAddress, reader.ReadInt32());
        }
Пример #5
0
        public void SerializeToStream(Stream peStream)
        {
            var peHeaderBuilder = new PEHeaderBuilder();
            var peBuilder       = new ManagedPEBuilder(peHeaderBuilder, new MetadataRootBuilder(_metadataBuilder), _ilBuilder,
                                                       deterministicIdProvider: content => s_contentId);

            var peBlob    = new BlobBuilder();
            var contentId = peBuilder.Serialize(peBlob);

            new BlobWriter(_mvidFixup).WriteGuid(contentId.Guid);
            peBlob.WriteContentTo(peStream);
        }
Пример #6
0
        public void BlahBlahBlah()
        {
            var peHeader = PEHeaderBuilder.CreateLibraryHeader();

            var meta = new MetadataBuilder();

            var module = meta.AddModule(1,
                                        meta.GetOrAddString("Module1"),
                                        meta.GetOrAddGuid(Guid.Parse("11112222-3333-4444-5555-666677778888")),
                                        meta.GetOrAddGuid(Guid.Parse("88887777-6666-5555-4444-333322221111")),
                                        meta.GetOrAddGuid(Guid.Parse("22223333-4444-5555-6666-777788889999"))
                                        );

            var tObject = meta.AddTypeReference(
                EntityHandle.ModuleDefinition,
                meta.GetOrAddString("System"),
                meta.GetOrAddString("Object"));

            var fields  = new FieldDefinitionHandle();  //EMPTY!!
            var methods = new MethodDefinitionHandle(); //EMPTY!!

            meta.AddTypeDefinition(
                TypeAttributes.Class | TypeAttributes.Public,
                meta.GetOrAddString("Namespace1"),
                meta.GetOrAddString("Class1"),
                tObject,
                fields,
                methods);

            meta.GetOrAddString("Module1");



            var metadataRoot = new MetadataRootBuilder(meta);

            var ilBlob = new BlobBuilder();

            ilBlob.WriteByte(0);
            ilBlob.WriteByte(42);

            var pe = new ManagedPEBuilder(peHeader, metadataRoot, ilBlob);

            var blob = new BlobBuilder();

            pe.Serialize(blob);

            Assembly.Load(blob.ToArray());
        }
Пример #7
0
        public static byte[] BuildPEWithDebugDirectory(DebugDirectoryBuilder debugDirectoryBuilder)
        {
            var peStream = new MemoryStream();
            var ilBuilder = new BlobBuilder();
            var metadataBuilder = new MetadataBuilder();

            var peBuilder = new ManagedPEBuilder(
                PEHeaderBuilder.CreateLibraryHeader(),
                new MetadataRootBuilder(metadataBuilder),
                ilBuilder,
                debugDirectoryBuilder: debugDirectoryBuilder);

            var peImageBuilder = new BlobBuilder();
            peBuilder.Serialize(peImageBuilder);
            return peImageBuilder.ToArray();
        }
Пример #8
0
        /// <summary>
        /// Assembles this instance.
        /// </summary>
        public void Assemble()
        {
            // TODO: Complete this so that it actually generate the hello world sample
            // TODO: Use the data generated from the parser instead of hard coding here
            PEHeaderBuilder header   = new PEHeaderBuilder();
            MetadataBuilder metadata = new MetadataBuilder();

            metadata.AddAssembly(metadata.GetOrAddString("HelloWorld"), new Version(), default(StringHandle), default(BlobHandle), (System.Reflection.AssemblyFlags) 0, AssemblyHashAlgorithm.None);
            MetadataRootBuilder metadataRootBuilder = new MetadataRootBuilder(metadata);
            BlobBuilder         stream           = new BlobBuilder();
            ManagedPEBuilder    managedPEBuilder = new ManagedPEBuilder(header, metadataRootBuilder, stream);
            BlobBuilder         output           = new BlobBuilder();

            managedPEBuilder.Serialize(output);
            File.WriteAllBytes(@"C:\Temp\HelloWorld.dll", output.ToArray());
        }
Пример #9
0
        public unsafe void NativeResources_BadImpl()
        {
            var peStream        = new MemoryStream();
            var ilBuilder       = new BlobBuilder();
            var metadataBuilder = new MetadataBuilder();

            var peBuilder = new ManagedPEBuilder(
                PEHeaderBuilder.CreateLibraryHeader(),
                new MetadataRootBuilder(metadataBuilder),
                ilBuilder,
                nativeResources: new BadResourceSectionBuilder(),
                deterministicIdProvider: content => s_contentId);

            var peBlob = new BlobBuilder();

            Assert.Throws <NotImplementedException>(() => peBuilder.Serialize(peBlob));
        }
Пример #10
0
        public static byte[] BuildPEWithDebugDirectory(DebugDirectoryBuilder debugDirectoryBuilder)
        {
            var peStream        = new MemoryStream();
            var ilBuilder       = new BlobBuilder();
            var metadataBuilder = new MetadataBuilder();

            var peBuilder = new ManagedPEBuilder(
                PEHeaderBuilder.CreateLibraryHeader(),
                new MetadataRootBuilder(metadataBuilder),
                ilBuilder,
                debugDirectoryBuilder: debugDirectoryBuilder);

            var peImageBuilder = new BlobBuilder();

            peBuilder.Serialize(peImageBuilder);
            return(peImageBuilder.ToArray());
        }
Пример #11
0
        private void GenerateWinMD(MetadataBuilder metadataBuilder, string outputFile)
        {
            Logger.Log("Writing " + outputFile);
            var managedPeBuilder = new ManagedPEBuilder(
                new PEHeaderBuilder(
                    machine: Machine.I386,
                    imageCharacteristics: Characteristics.ExecutableImage | Characteristics.Dll | Characteristics.Bit32Machine),
                new MetadataRootBuilder(metadataBuilder, "WindowsRuntime 1.4"),
                new BlobBuilder(),
                flags: CorFlags.ILOnly);

            var peBlob = new BlobBuilder();

            managedPeBuilder.Serialize(peBlob);

            using var fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write);
            peBlob.WriteContentTo(fs);
        }
Пример #12
0
        private ImmutableArray <Diagnostic> EmitAssembly(BoundProgram program)
        {
            var header              = new PEHeaderBuilder();
            var metadataBuilder     = new MetadataBuilder();
            var metadataRootBuilder = new MetadataRootBuilder(metadataBuilder);
            var blobBuilder         = new BlobBuilder();
            var peBuilder           = new ManagedPEBuilder(header, metadataRootBuilder, blobBuilder);

            peBuilder.Serialize(blobBuilder);

            // TODO: Produce portable assembly contents here
            using (var stream = new StreamWriter(program.PackageName + ".dll"))
            {
                blobBuilder.WriteContentTo(stream.BaseStream);
            }

            return(ImmutableArray <Diagnostic> .Empty);
        }
Пример #13
0
            public override ConstraintResult ApplyTo <TActual>(TActual actual)
            {
                string actualContract;

                switch (actual)
                {
                case string sourceCode:
                    actualContract = isVisualBasic
                            ? AssemblyUtils.GenerateContract(generator, sourceCode, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion.Latest, assemblyResolver)
                            : AssemblyUtils.GenerateContract(generator, sourceCode, Microsoft.CodeAnalysis.CSharp.LanguageVersion.Latest, assemblyResolver);
                    break;

                case Compilation compilation:
                    using (var stream = new MemoryStream())
                    {
                        AssemblyUtils.EmitCompilation(compilation, stream);
                        stream.Seek(0, SeekOrigin.Begin);
                        actualContract = AssemblyUtils.GenerateContract(generator, stream, assemblyResolver);
                    }
                    break;

                case MetadataBuilder metadataBuilder:
                    var blobBuilder = new BlobBuilder();

                    var peBuilder = new ManagedPEBuilder(
                        PEHeaderBuilder.CreateLibraryHeader(),
                        new MetadataRootBuilder(metadataBuilder),
                        ilStream: new BlobBuilder());

                    peBuilder.Serialize(blobBuilder);

                    using (var stream = new MemoryStream(blobBuilder.ToArray(), writable: false))
                        actualContract = AssemblyUtils.GenerateContract(generator, stream, assemblyResolver);
                    break;

                default:
                    throw new ArgumentException("Expected source code as string or library IL as MetadataBuilder.", nameof(actual));
                }

                return(new ContractConstraintResult(this, actualContract, expected));
            }
Пример #14
0
        private static void WritePEImage(
            Stream peStream,
            MetadataBuilder metadataBuilder,
            BlobBuilder ilBuilder,
            MethodDefinitionHandle entryPointHandle,
            Blob mvidFixup              = default(Blob),
            byte[] privateKeyOpt        = null,
            bool publicSigned           = false,
            Machine machine             = 0,
            BlobBuilder?mappedFieldData = null)
        {
            var peHeaderBuilder = new PEHeaderBuilder(imageCharacteristics: entryPointHandle.IsNil ? Characteristics.Dll : Characteristics.ExecutableImage,
                                                      machine: machine);

            var peBuilder = new ManagedPEBuilder(
                peHeaderBuilder,
                new MetadataRootBuilder(metadataBuilder),
                ilBuilder,
                entryPoint: entryPointHandle,
                flags: CorFlags.ILOnly | (privateKeyOpt != null || publicSigned ? CorFlags.StrongNameSigned : 0),
                deterministicIdProvider: content => s_contentId,
                mappedFieldData: mappedFieldData);

            var peBlob = new BlobBuilder();

            var contentId = peBuilder.Serialize(peBlob);

            if (!mvidFixup.IsDefault)
            {
                new BlobWriter(mvidFixup).WriteGuid(contentId.Guid);
            }

            if (privateKeyOpt != null)
            {
                peBuilder.Sign(peBlob, content => SigningUtilities.CalculateRsaSignature(content, privateKeyOpt));
            }

            peBlob.WriteContentTo(peStream);
        }
Пример #15
0
        private static void WritePEImage(
            Stream peStream,
            MetadataBuilder metadataBuilder,
            BlobBuilder ilBuilder,
            MethodDefinitionHandle entryPointHandle,
            byte[] privateKeyOpt = null)
        {
            var mappedFieldDataBuilder     = new BlobBuilder();
            var managedResourceDataBuilder = new BlobBuilder();

            var peBuilder = new ManagedPEBuilder(
                entryPointHandle.IsNil ? PEHeaderBuilder.CreateLibraryHeader() : PEHeaderBuilder.CreateExecutableHeader(),
                new TypeSystemMetadataSerializer(metadataBuilder, "v4.0.30319", isMinimalDelta: false),
                ilBuilder,
                mappedFieldDataBuilder,
                managedResourceDataBuilder,
                nativeResourceSectionSerializer: null,
                strongNameSignatureSize: 128,
                entryPoint: entryPointHandle,
                pdbPathOpt: null,
                nativePdbContentId: default(ContentId),
                portablePdbContentId: default(ContentId),
                corFlags: CorFlags.ILOnly | (privateKeyOpt != null ? CorFlags.StrongNameSigned : 0),
                deterministicIdProvider: content => s_contentId);

            var peBlob = new BlobBuilder();

            ContentId contentId;

            peBuilder.Serialize(peBlob, out contentId);

            if (privateKeyOpt != null)
            {
                peBuilder.Sign(peBlob, content => SigningUtilities.CalculateRsaSignature(content, privateKeyOpt));
            }

            peBlob.WriteContentTo(peStream);
        }
        public byte[] GenerateAssemblyBytes()
        {
            var name = _currentAssembly.GetName();

            var assemblyHandle = _metadataBuilder.AddAssembly(
                GetString(name.Name),
                name.Version,
                GetString(name.CultureName),
                GetBlob(name.GetPublicKey()),
                _assemblyNameFlagsConvert(name.Flags),
                _assemblyHashAlgorithmConvert(name.HashAlgorithm));

            CreateReferencedAssemblies(_currentAssembly.GetReferencedAssemblies());
            CreateCustomAttributes(assemblyHandle, _currentAssembly.GetCustomAttributesData());

            CreateModules(_currentAssembly.GetModules());
            CreateTypes(_currentAssembly.GetTypes());

            var entryPoint = GetMethodDefinitionHandle(_currentAssembly.EntryPoint);


            var metadataRootBuilder = new MetadataRootBuilder(_metadataBuilder);
            var header = PEHeaderBuilder.CreateLibraryHeader();

            var peBuilder = new ManagedPEBuilder(
                header,
                metadataRootBuilder,
                _ilBuilder,
                debugDirectoryBuilder: _debugDirectoryBuilder,
                entryPoint: entryPoint);

            var peImageBuilder = new BlobBuilder();

            peBuilder.Serialize(peImageBuilder);

            return(peImageBuilder.ToArray());
        }
Пример #17
0
        public static bool WritePeToStream(
            EmitContext context,
            CommonMessageProvider messageProvider,
            Func <Stream> getPeStream,
            Func <Stream> getPortablePdbStreamOpt,
            PdbWriter nativePdbWriterOpt,
            string pdbPathOpt,
            bool allowMissingMethodBodies,
            bool isDeterministic,
            CancellationToken cancellationToken)
        {
            // If PDB writer is given, we have to have PDB path.
            Debug.Assert(nativePdbWriterOpt == null || pdbPathOpt != null);

            var mdWriter = FullMetadataWriter.Create(context, messageProvider, allowMissingMethodBodies, isDeterministic, getPortablePdbStreamOpt != null, cancellationToken);

            var properties = context.Module.Properties;

            nativePdbWriterOpt?.SetMetadataEmitter(mdWriter);

            // Since we are producing a full assembly, we should not have a module version ID
            // imposed ahead-of time. Instead we will compute a deterministic module version ID
            // based on the contents of the generated stream.
            Debug.Assert(properties.PersistentIdentifier == default(Guid));

            var ilBuilder = new BlobBuilder(32 * 1024);
            var mappedFieldDataBuilder = new BlobBuilder();
            var managedResourceBuilder = new BlobBuilder(1024);

            Blob mvidFixup;

            mdWriter.BuildMetadataAndIL(
                nativePdbWriterOpt,
                ilBuilder,
                mappedFieldDataBuilder,
                managedResourceBuilder,
                out mvidFixup);

            MethodDefinitionHandle entryPointHandle;
            MethodDefinitionHandle debugEntryPointHandle;

            mdWriter.GetEntryPoints(out entryPointHandle, out debugEntryPointHandle);

            if (!debugEntryPointHandle.IsNil)
            {
                nativePdbWriterOpt?.SetEntryPoint((uint)MetadataTokens.GetToken(debugEntryPointHandle));
            }

            if (nativePdbWriterOpt != null)
            {
                var assembly = mdWriter.Module.AsAssembly;
                if (assembly != null && assembly.Kind == OutputKind.WindowsRuntimeMetadata)
                {
                    // Dev12: If compiling to winmdobj, we need to add to PDB source spans of
                    //        all types and members for better error reporting by WinMDExp.
                    nativePdbWriterOpt.WriteDefinitionLocations(mdWriter.Module.GetSymbolToLocationMap());
                }
                else
                {
#if DEBUG
                    // validate that all definitions are writable
                    // if same scenario would happen in an winmdobj project
                    nativePdbWriterOpt.AssertAllDefinitionsHaveTokens(mdWriter.Module.GetSymbolToLocationMap());
#endif
                }
            }

            Stream peStream = getPeStream();
            if (peStream == null)
            {
                return(false);
            }

            BlobContentId pdbContentId = nativePdbWriterOpt?.GetContentId() ?? default(BlobContentId);

            // the writer shall not be used after this point for writing:
            nativePdbWriterOpt = null;

            ushort portablePdbVersion = 0;
            var    metadataSerializer = mdWriter.GetTypeSystemMetadataSerializer();

            var peHeaderBuilder = new PEHeaderBuilder(
                machine: properties.Machine,
                sectionAlignment: properties.SectionAlignment,
                fileAlignment: properties.FileAlignment,
                imageBase: properties.BaseAddress,
                majorLinkerVersion: properties.LinkerMajorVersion,
                minorLinkerVersion: properties.LinkerMinorVersion,
                majorOperatingSystemVersion: 4,
                minorOperatingSystemVersion: 0,
                majorImageVersion: 0,
                minorImageVersion: 0,
                majorSubsystemVersion: properties.MajorSubsystemVersion,
                minorSubsystemVersion: properties.MinorSubsystemVersion,
                subsystem: properties.Subsystem,
                dllCharacteristics: properties.DllCharacteristics,
                imageCharacteristics: properties.ImageCharacteristics,
                sizeOfStackReserve: properties.SizeOfStackReserve,
                sizeOfStackCommit: properties.SizeOfStackCommit,
                sizeOfHeapReserve: properties.SizeOfHeapReserve,
                sizeOfHeapCommit: properties.SizeOfHeapCommit);

            var deterministicIdProvider = isDeterministic ?
                                          new Func <IEnumerable <Blob>, BlobContentId>(content => BlobContentId.FromHash(CryptographicHashProvider.ComputeSha1(content))) :
                                          null;

            if (mdWriter.EmitStandaloneDebugMetadata)
            {
                Debug.Assert(getPortablePdbStreamOpt != null);

                var debugMetadataBuilder    = new BlobBuilder();
                var debugMetadataSerializer = mdWriter.GetStandaloneDebugMetadataSerializer(metadataSerializer.MetadataSizes, debugEntryPointHandle, deterministicIdProvider);
                debugMetadataSerializer.SerializeMetadata(debugMetadataBuilder, out pdbContentId);
                portablePdbVersion = debugMetadataSerializer.FormatVersion;

                // write to Portable PDB stream:
                Stream portablePdbStream = getPortablePdbStreamOpt();
                if (portablePdbStream != null)
                {
                    debugMetadataBuilder.WriteContentTo(portablePdbStream);
                }
            }

            DebugDirectoryBuilder debugDirectoryBuilder;
            if (pdbPathOpt != null || isDeterministic)
            {
                debugDirectoryBuilder = new DebugDirectoryBuilder();
                if (pdbPathOpt != null)
                {
                    string paddedPath = isDeterministic ? pdbPathOpt : PadPdbPath(pdbPathOpt);
                    debugDirectoryBuilder.AddCodeViewEntry(paddedPath, pdbContentId, portablePdbVersion);
                }

                if (isDeterministic)
                {
                    debugDirectoryBuilder.AddReproducibleEntry();
                }
            }
            else
            {
                debugDirectoryBuilder = null;
            }

            var peBuilder = new ManagedPEBuilder(
                peHeaderBuilder,
                metadataSerializer,
                ilBuilder,
                mappedFieldDataBuilder,
                managedResourceBuilder,
                CreateNativeResourceSectionSerializer(context.Module),
                debugDirectoryBuilder,
                CalculateStrongNameSignatureSize(context.Module),
                entryPointHandle,
                properties.CorFlags,
                deterministicIdProvider);

            var           peBlob = new BlobBuilder();
            BlobContentId peContentId;
            peBuilder.Serialize(peBlob, out peContentId);

            // Patch MVID
            if (!mvidFixup.IsDefault)
            {
                var writer = new BlobWriter(mvidFixup);
                writer.WriteGuid(peContentId.Guid);
                Debug.Assert(writer.RemainingBytes == 0);
            }

            try
            {
                peBlob.WriteContentTo(peStream);
            }
            catch (Exception e) when(!(e is OperationCanceledException))
            {
                throw new PeWritingException(e);
            }

            return(true);
        }
Пример #18
0
        public byte[] GenerateAssemblyBytes()
        {
            if (_currentAssembly.EntryPoint != null)
            {
                // See "<Module>" type definition below.
                throw new NotSupportedException("Entry point is not supported.");
            }

            var name = _currentAssembly.GetName();

            var assemblyPublicKey = name.GetPublicKey();
            var assemblyHandle    = _metadataBuilder.AddAssembly(
                GetString(name.Name),
                name.Version,
                GetString(name.CultureName),
                assemblyPublicKey.Length > 0 ? GetBlob(name.GetPublicKey()) : default(BlobHandle),
                ConvertGeneratedAssemblyNameFlags(name),
                ConvertAssemblyHashAlgorithm(name.HashAlgorithm));

            // Add "<Module>" type definition *before* any type definition.
            //
            // TODO: [osman] methodList argument should be as following:
            //
            //   methodList: entryPoint.IsNil ? MetadataTokens.MethodDefinitionHandle(1) : entryPoint
            //
            // But, in order to work above code, we need to serialize
            // entry point *without* serializing any type definition.
            // This is not needed for libraries since they don't have any entry point.
            _metadataBuilder.AddTypeDefinition(
                default(TypeAttributes),
                default(StringHandle),
                GetString("<Module>"),
                default(EntityHandle),
                MetadataTokens.FieldDefinitionHandle(1),
                MetadataTokens.MethodDefinitionHandle(1));

            CreateReferencedAssemblies(_currentAssembly.GetReferencedAssemblies());
            CreateCustomAttributes(assemblyHandle, _currentAssembly.GetCustomAttributesData());

            CreateModules(_currentAssembly.GetModules());
            CreateTypes(_currentAssembly.GetTypes());

            var entryPoint = GetMethodDefinitionHandle(_currentAssembly.EntryPoint);

            var metadataRootBuilder = new MetadataRootBuilder(_metadataBuilder);

            // Without Characteristics.ExecutableImage flag, .NET runtime refuses
            // to load an assembly even it's a DLL. PEHeaderBuilder.CreateLibraryHeader
            // does not set this flag. So, we set it explicitly.
            var header = new PEHeaderBuilder(imageCharacteristics: Characteristics.ExecutableImage |
                                             (entryPoint.IsNil ? Characteristics.Dll : 0));

            var peBuilder = new ManagedPEBuilder(
                header,
                metadataRootBuilder,
                _ilBuilder,
                debugDirectoryBuilder: _debugDirectoryBuilder,
                entryPoint: entryPoint);

            var peImageBuilder = new BlobBuilder();

            peBuilder.Serialize(peImageBuilder);

            return(peImageBuilder.ToArray());
        }
Пример #19
0
        /// <summary>
        /// Emits this dynamic assembly to a Portable Executable file image.
        /// </summary>
        /// <returns>An <see cref="AssemblyBuilderEmitResult"/> instance containing the
        /// emitted PE image.</returns>
        /// <remarks>
        /// This method can be called only once. Any subsequent calls will throw an exception.
        /// </remarks>
        public AssemblyBuilderEmitResult emit()
        {
            if (m_isPEFileCreated)
            {
                throw new InvalidOperationException("The PE file for this assembly has already been created.");
            }

            m_isPEFileCreated = true;

            var         tokenMap = new TokenMapping(m_metadataContext.fieldDefRowCount, m_metadataContext.methodDefRowCount);
            BlobBuilder ilStream;

            lock (m_typeBuildersLock) {
                var typeBuilders             = m_typeBuilders.asReadOnlyArrayView();
                int currentMethodBodyAddress = 0;

                for (int i = 0; i < typeBuilders.length; i++)
                {
                    currentMethodBodyAddress = typeBuilders[i].assignMethodBodyAddresses(currentMethodBodyAddress);
                }

                var genParamEntries = new DynamicArray <GenericParameter>();

                using (var mdBuilder = m_metadataContext.getMetadataBuilder()) {
                    for (int i = 0; i < typeBuilders.length; i++)
                    {
                        typeBuilders[i].writeTypeMetadata(mdBuilder.value, tokenMap);
                    }
                    for (int i = 0; i < typeBuilders.length; i++)
                    {
                        typeBuilders[i].writeMethodImplEntries(mdBuilder.value, tokenMap);
                    }
                }

                for (int i = 0; i < typeBuilders.length; i++)
                {
                    typeBuilders[i].appendGenParamEntries(tokenMap, ref genParamEntries);
                }

                m_metadataContext.emitMethodSpecTable(tokenMap);
                _sortAndWriteGenParamEntries(ref genParamEntries);

                ilStream = new BlobBuilder(currentMethodBodyAddress);

                for (int i = 0; i < typeBuilders.length; i++)
                {
                    typeBuilders[i].writeMethodBodies(ilStream, tokenMap);
                }
            }

            BlobBuilder            peFileBlob = new BlobBuilder();
            MethodDefinitionHandle entryPoint = default;

            if (!m_entryPoint.IsNil)
            {
                entryPoint = (MethodDefinitionHandle)tokenMap.getMappedHandle(m_entryPoint);
            }

            using (var mdBuilder = m_metadataContext.getMetadataBuilder()) {
                var metadataRootBuilder = new MetadataRootBuilder(mdBuilder.value, null, true);
                var peHeader            = m_peHeader ?? new PEHeaderBuilder(Machine.I386);
                var peBuilder           = new ManagedPEBuilder(peHeader, metadataRootBuilder, ilStream, entryPoint: entryPoint);
                peBuilder.Serialize(peFileBlob);
            }

            return(new AssemblyBuilderEmitResult(peFileBlob.ToArray(), tokenMap));
        }
Пример #20
0
        public unsafe void NativeResources_BadImpl()
        {
            var peStream = new MemoryStream();
            var ilBuilder = new BlobBuilder();
            var metadataBuilder = new MetadataBuilder();

            var peBuilder = new ManagedPEBuilder(
                PEHeaderBuilder.CreateLibraryHeader(),
                new MetadataRootBuilder(metadataBuilder),
                ilBuilder,
                nativeResources: new BadResourceSectionBuilder(),
                deterministicIdProvider: content => s_contentId);

            var peBlob = new BlobBuilder();

            Assert.Throws<NotImplementedException>(() => peBuilder.Serialize(peBlob));
        }
Пример #21
0
        public unsafe void NativeResources()
        {
            var peStream = new MemoryStream();
            var ilBuilder = new BlobBuilder();
            var metadataBuilder = new MetadataBuilder();
            
            var peBuilder = new ManagedPEBuilder(
                PEHeaderBuilder.CreateLibraryHeader(),
                new MetadataRootBuilder(metadataBuilder),
                ilBuilder,
                nativeResources: new TestResourceSectionBuilder(),
                deterministicIdProvider: content => s_contentId);
            
            var peBlob = new BlobBuilder();
            
            var contentId = peBuilder.Serialize(peBlob);
            
            peBlob.WriteContentTo(peStream);

            peStream.Position = 0;
            var peReader = new PEReader(peStream);
            var sectionHeader = peReader.PEHeaders.SectionHeaders.Single(s => s.Name == ".rsrc");

            var image = peReader.GetEntireImage();

            var reader = new BlobReader(image.Pointer + sectionHeader.PointerToRawData, sectionHeader.SizeOfRawData);
            Assert.Equal(0x12345678, reader.ReadInt32());
            Assert.Equal(sectionHeader.PointerToRawData, reader.ReadInt32());
            Assert.Equal(sectionHeader.VirtualAddress, reader.ReadInt32());
        }