public void __DefineUnmanagedResource(byte[] resource)
 {
     // The standard .NET DefineUnmanagedResource(byte[]) is useless, because it embeds "resource" (as-is) as the .rsrc section,
     // but it doesn't set the PE file Resource Directory entry to point to it. That's why we have a renamed version, which behaves
     // like DefineUnmanagedResource(string).
     unmanagedResources = new ResourceSection();
     unmanagedResources.ExtractResources(resource);
 }
Esempio n. 2
0
        private PeWriter(
            ModulePropertiesForSerialization properties,
            IEnumerable<IWin32Resource> nativeResourcesOpt,
            ResourceSection nativeResourceSectionOpt,
            string pdbPathOpt, 
            bool deterministic)
        {
            _properties = properties;
            _pdbPathOpt = pdbPathOpt;
            _deterministic = deterministic;

            _nativeResourcesOpt = nativeResourcesOpt;
            _nativeResourceSectionOpt = nativeResourceSectionOpt;
            _is32bit = !_properties.Requires64bits;
            _sizeOfImportAddressTable = _properties.RequiresStartupStub ? (_is32bit ? 8 : 16) : 0;
        }
Esempio n. 3
0
        private PeWriter(
            ModulePropertiesForSerialization properties,
            IEnumerable<IWin32Resource> nativeResourcesOpt,
            ResourceSection nativeResourceSectionOpt,
            string pdbPathOpt, 
            bool deterministic)
        {
            _properties = properties;
            _pdbPathOpt = pdbPathOpt;
            _deterministic = deterministic;

            _nativeResourcesOpt = nativeResourcesOpt;
            _nativeResourceSectionOpt = nativeResourceSectionOpt;
            _is32bit = !_properties.Requires64bits;

            // In the PE File Header this is a "Time/Date Stamp" whose description is "Time and date
            // the file was created in seconds since January 1st 1970 00:00:00 or 0"
            // However, when we want to make it deterministic we fill it in (later) with bits from the hash of the full PE file.
            _timeStamp = _deterministic ? 0 : (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
        }
Esempio n. 4
0
        private void SerializeWin32Resources(ResourceSection resourceSections, int resourcesRva)
        {
            var sectionWriter = _win32ResourceWriter.ReserveBytes(resourceSections.SectionBytes.Length);
            sectionWriter.WriteBytes(resourceSections.SectionBytes);

            var readStream = new MemoryStream(resourceSections.SectionBytes);
            var reader = new BinaryReader(readStream);

            foreach (int addressToFixup in resourceSections.Relocations)
            {
                sectionWriter.Offset = addressToFixup;
                reader.BaseStream.Position = addressToFixup;
                sectionWriter.WriteUInt32(reader.ReadUInt32() + (uint)resourcesRva);
            }
        }
Esempio n. 5
0
        private void SerializeWin32Resources(ResourceSection resourceSections, int resourcesRva)
        {
            _win32ResourceWriter.WriteBytes(resourceSections.SectionBytes);

            var savedPosition = _win32ResourceWriter.Position;

            var readStream = new MemoryStream(resourceSections.SectionBytes);
            var reader = new BinaryReader(readStream);

            foreach (int addressToFixup in resourceSections.Relocations)
            {
                _win32ResourceWriter.SetPosition(addressToFixup);
                reader.BaseStream.Position = addressToFixup;
                _win32ResourceWriter.WriteUInt32(reader.ReadUInt32() + (uint)resourcesRva);
            }

            _win32ResourceWriter.SetPosition(savedPosition);
        }
Esempio n. 6
0
        private void SaveImpl(string assemblyFileName, Stream streamOrNull, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
        {
            ModuleBuilder manifestModule = null;

            foreach (ModuleBuilder moduleBuilder in modules)
            {
                moduleBuilder.SetIsSaved();
                moduleBuilder.PopulatePropertyAndEventTables();

                if (manifestModule == null &&
                    string.Compare(moduleBuilder.fileName, assemblyFileName, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    manifestModule = moduleBuilder;
                }
            }

            if (manifestModule == null)
            {
                manifestModule = DefineDynamicModule("RefEmit_OnDiskManifestModule", assemblyFileName, false);
            }

            AssemblyTable.Record assemblyRecord = new AssemblyTable.Record();
            assemblyRecord.HashAlgId      = (int)hashAlgorithm;
            assemblyRecord.Name           = manifestModule.Strings.Add(name);
            assemblyRecord.MajorVersion   = majorVersion;
            assemblyRecord.MinorVersion   = minorVersion;
            assemblyRecord.BuildNumber    = buildVersion;
            assemblyRecord.RevisionNumber = revisionVersion;
            if (publicKey != null)
            {
                assemblyRecord.PublicKey = manifestModule.Blobs.Add(ByteBuffer.Wrap(publicKey));
                assemblyRecord.Flags     = (int)(flags | AssemblyNameFlags.PublicKey);
            }
            else
            {
                assemblyRecord.Flags = (int)(flags & ~AssemblyNameFlags.PublicKey);
            }
            if (culture != null)
            {
                assemblyRecord.Culture = manifestModule.Strings.Add(culture);
            }
            manifestModule.AssemblyTable.AddRecord(assemblyRecord);

            ResourceSection unmanagedResources = versionInfo != null || win32icon != null || win32manifest != null || win32resources != null
                                ? new ResourceSection()
                                : null;

            if (versionInfo != null)
            {
                versionInfo.SetName(GetName());
                versionInfo.SetFileName(assemblyFileName);
                foreach (CustomAttributeBuilder cab in customAttributes)
                {
                    // .NET doesn't support copying blob custom attributes into the version info
                    if (!cab.HasBlob || universe.DecodeVersionInfoAttributeBlobs)
                    {
                        versionInfo.SetAttribute(this, cab);
                    }
                }
                ByteBuffer versionInfoData = new ByteBuffer(512);
                versionInfo.Write(versionInfoData);
                unmanagedResources.AddVersionInfo(versionInfoData);
            }

            if (win32icon != null)
            {
                unmanagedResources.AddIcon(win32icon);
            }

            if (win32manifest != null)
            {
                unmanagedResources.AddManifest(win32manifest, fileKind == PEFileKinds.Dll ? (ushort)2 : (ushort)1);
            }

            if (win32resources != null)
            {
                unmanagedResources.ExtractResources(win32resources);
            }

            foreach (CustomAttributeBuilder cab in customAttributes)
            {
                // we intentionally don't filter out the version info (pseudo) custom attributes (to be compatible with .NET)
                manifestModule.SetCustomAttribute(0x20000001, cab);
            }

            manifestModule.AddDeclarativeSecurity(0x20000001, declarativeSecurity);

            foreach (TypeForwarder fwd in typeForwarders)
            {
                manifestModule.AddTypeForwarder(fwd.Type, fwd.IncludeNested);
            }

            foreach (ResourceFile resfile in resourceFiles)
            {
#if !CORECLR
                if (resfile.Writer != null)
                {
                    resfile.Writer.Generate();
                    resfile.Writer.Close();
                }
#endif
                int fileToken = AddFile(manifestModule, resfile.FileName, 1 /*ContainsNoMetaData*/);
                ManifestResourceTable.Record rec = new ManifestResourceTable.Record();
                rec.Offset         = 0;
                rec.Flags          = (int)resfile.Attributes;
                rec.Name           = manifestModule.Strings.Add(resfile.Name);
                rec.Implementation = fileToken;
                manifestModule.ManifestResource.AddRecord(rec);
            }

            int entryPointToken = 0;

            foreach (ModuleBuilder moduleBuilder in modules)
            {
                moduleBuilder.FillAssemblyRefTable();
                moduleBuilder.EmitResources();
                if (moduleBuilder != manifestModule)
                {
                    int fileToken;
                    if (entryPoint != null && entryPoint.Module == moduleBuilder)
                    {
                        ModuleWriter.WriteModule(null, null, moduleBuilder, fileKind, portableExecutableKind, imageFileMachine, moduleBuilder.unmanagedResources, entryPoint.MetadataToken);
                        entryPointToken = fileToken = AddFile(manifestModule, moduleBuilder.fileName, 0 /*ContainsMetaData*/);
                    }
                    else
                    {
                        ModuleWriter.WriteModule(null, null, moduleBuilder, fileKind, portableExecutableKind, imageFileMachine, moduleBuilder.unmanagedResources, 0);
                        fileToken = AddFile(manifestModule, moduleBuilder.fileName, 0 /*ContainsMetaData*/);
                    }
                    moduleBuilder.ExportTypes(fileToken, manifestModule);
                }
                moduleBuilder.CloseResources();
            }

            foreach (Module module in addedModules)
            {
                int fileToken = AddFile(manifestModule, module.FullyQualifiedName, 0 /*ContainsMetaData*/);
                module.ExportTypes(fileToken, manifestModule);
            }

            if (entryPointToken == 0 && entryPoint != null)
            {
                entryPointToken = entryPoint.MetadataToken;
            }

            // finally, write the manifest module
            ModuleWriter.WriteModule(keyPair, publicKey, manifestModule, fileKind, portableExecutableKind, imageFileMachine, unmanagedResources ?? manifestModule.unmanagedResources, entryPointToken, streamOrNull);
        }
Esempio n. 7
0
 public ResourceSectionBuilderFromObj(ResourceSection resourceSection)
 {
     Debug.Assert(resourceSection != null);
     _resourceSection = resourceSection;
 }
Esempio n. 8
0
        private void SerializeWin32Resources(ResourceSection resourceSections, uint resourcesRva)
        {
            _win32ResourceWriter.WriteBytes(resourceSections.SectionBytes);

            var savedPosition = _win32ResourceWriter.BaseStream.Position;

            var readStream = new System.IO.MemoryStream(resourceSections.SectionBytes);
            var reader = new System.IO.BinaryReader(readStream);

            foreach (int addressToFixup in resourceSections.Relocations)
            {
                _win32ResourceWriter.BaseStream.Position = (uint)addressToFixup;
                reader.BaseStream.Position = addressToFixup;
                _win32ResourceWriter.WriteUint(reader.ReadUInt32() + resourcesRva);
            }

            _win32ResourceWriter.BaseStream.Position = savedPosition;
        }
 public void __DefineIconResource(byte[] iconFile)
 {
     unmanagedResources = new ResourceSection();
     unmanagedResources.AddIcon(iconFile);
 }
        public void Save(string assemblyFileName, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
        {
            ModuleBuilder manifestModule = null;

            foreach (ModuleBuilder moduleBuilder in modules)
            {
                moduleBuilder.PopulatePropertyAndEventTables();

                if (manifestModule == null &&
                    string.Compare(moduleBuilder.fileName, assemblyFileName, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    manifestModule = moduleBuilder;
                }
            }

            if (manifestModule == null)
            {
                manifestModule = DefineDynamicModule("RefEmit_OnDiskManifestModule", assemblyFileName, false);
            }

            AssemblyTable.Record assemblyRecord = new AssemblyTable.Record();
            assemblyRecord.HashAlgId      = (int)hashAlgorithm;
            assemblyRecord.Name           = manifestModule.Strings.Add(name);
            assemblyRecord.MajorVersion   = majorVersion;
            assemblyRecord.MinorVersion   = minorVersion;
            assemblyRecord.BuildNumber    = buildVersion;
            assemblyRecord.RevisionNumber = revisionVersion;
            if (publicKey != null)
            {
                assemblyRecord.PublicKey = manifestModule.Blobs.Add(ByteBuffer.Wrap(publicKey));
                assemblyRecord.Flags     = (int)(flags | AssemblyNameFlags.PublicKey);
            }
            else
            {
                assemblyRecord.Flags = (int)(flags & ~AssemblyNameFlags.PublicKey);
            }
            if (culture != null)
            {
                assemblyRecord.Culture = manifestModule.Strings.Add(culture);
            }
            int token = 0x20000000 + manifestModule.AssemblyTable.AddRecord(assemblyRecord);

#pragma warning disable 618
            // this values are obsolete, but we already know that so we disable the warning
            System.Security.Permissions.SecurityAction requestMinimum  = System.Security.Permissions.SecurityAction.RequestMinimum;
            System.Security.Permissions.SecurityAction requestOptional = System.Security.Permissions.SecurityAction.RequestOptional;
            System.Security.Permissions.SecurityAction requestRefuse   = System.Security.Permissions.SecurityAction.RequestRefuse;
#pragma warning restore 618
            if (requiredPermissions != null)
            {
                manifestModule.AddDeclarativeSecurity(token, requestMinimum, requiredPermissions);
            }
            if (optionalPermissions != null)
            {
                manifestModule.AddDeclarativeSecurity(token, requestOptional, optionalPermissions);
            }
            if (refusedPermissions != null)
            {
                manifestModule.AddDeclarativeSecurity(token, requestRefuse, refusedPermissions);
            }

            if (versionInfo != null)
            {
                versionInfo.SetName(GetName());
                versionInfo.SetFileName(assemblyFileName);
                foreach (CustomAttributeBuilder cab in customAttributes)
                {
                    // .NET doesn't support copying blob custom attributes into the version info
                    if (!cab.HasBlob)
                    {
                        versionInfo.SetAttribute(cab);
                    }
                }
                ByteBuffer versionInfoData = new ByteBuffer(512);
                versionInfo.Write(versionInfoData);
                if (unmanagedResources == null)
                {
                    unmanagedResources = new ResourceSection();
                }
                unmanagedResources.AddVersionInfo(versionInfoData);
            }

            foreach (CustomAttributeBuilder cab in customAttributes)
            {
                // we intentionally don't filter out the version info (pseudo) custom attributes (to be compatible with .NET)
                manifestModule.SetCustomAttribute(0x20000001, cab);
            }

            manifestModule.AddDeclarativeSecurity(0x20000001, declarativeSecurity);

            foreach (Type type in typeForwarders)
            {
                manifestModule.AddTypeForwarder(type);
            }

            foreach (ResourceFile resfile in resourceFiles)
            {
                int fileToken = AddFile(manifestModule, resfile.FileName, 1 /*ContainsNoMetaData*/);
                ManifestResourceTable.Record rec = new ManifestResourceTable.Record();
                rec.Offset         = 0;
                rec.Flags          = (int)resfile.Attributes;
                rec.Name           = manifestModule.Strings.Add(resfile.Name);
                rec.Implementation = fileToken;
                manifestModule.ManifestResource.AddRecord(rec);
            }

            int entryPointToken = 0;

            foreach (ModuleBuilder moduleBuilder in modules)
            {
                moduleBuilder.FillAssemblyRefTable();
                if (moduleBuilder != manifestModule)
                {
                    int fileToken;
                    if (entryPoint != null && entryPoint.Module == moduleBuilder)
                    {
                        ModuleWriter.WriteModule(null, null, moduleBuilder, fileKind, portableExecutableKind, imageFileMachine, moduleBuilder.unmanagedResources, entryPoint.MetadataToken);
                        entryPointToken = fileToken = AddFile(manifestModule, moduleBuilder.fileName, 0 /*ContainsMetaData*/);
                    }
                    else
                    {
                        ModuleWriter.WriteModule(null, null, moduleBuilder, fileKind, portableExecutableKind, imageFileMachine, moduleBuilder.unmanagedResources, 0);
                        fileToken = AddFile(manifestModule, moduleBuilder.fileName, 0 /*ContainsMetaData*/);
                    }
                    moduleBuilder.ExportTypes(fileToken, manifestModule);
                }
            }

            foreach (Module module in addedModules)
            {
                int fileToken = AddFile(manifestModule, module.FullyQualifiedName, 0 /*ContainsMetaData*/);
                module.ExportTypes(fileToken, manifestModule);
            }

            if (entryPointToken == 0 && entryPoint != null)
            {
                entryPointToken = entryPoint.MetadataToken;
            }

            // finally, write the manifest module
            ModuleWriter.WriteModule(keyPair, publicKey, manifestModule, fileKind, portableExecutableKind, imageFileMachine, unmanagedResources ?? manifestModule.unmanagedResources, entryPointToken);
        }
 protected void ConstructPEImage(FileStream file, bool partialConstruct)
 {
     this._partialConstruct = partialConstruct;
     this._dosHeader = new DosHeader(file);
     long size = this._dosHeader.NtHeaderPosition - (this._dosHeader.Address + this._dosHeader.Size);
     if (size < 0L)
     {
         throw new Win32Exception(11, Resources.GetString("Ex_InvalidPEFormat"));
     }
     this._dosStub = new DosStub(file, this._dosHeader.Address + this._dosHeader.Size, size);
     this._ntSignature = new NtSignature(file, (long) this._dosHeader.NtHeaderPosition);
     this._fileHeader = new FileHeader(file, this._ntSignature.Address + this._ntSignature.Size);
     this._optionalHeader = new OptionalHeader(file, this._fileHeader.Address + this._fileHeader.Size);
     long address = this._optionalHeader.Address + this._optionalHeader.Size;
     int num3 = 0;
     for (num3 = 0; num3 < this._optionalHeader.NumberOfRvaAndSizes; num3++)
     {
         DataDirectory directory = new DataDirectory(file, address);
         address += directory.Size;
         this._dataDirectories.Add(directory);
     }
     if (this._fileHeader.SizeOfOptionalHeader < (((ulong) this._optionalHeader.Size) + (this._optionalHeader.NumberOfRvaAndSizes * Marshal.SizeOf(typeof(IMAGE_DATA_DIRECTORY)))))
     {
         throw new Win32Exception(11, Resources.GetString("Ex_InvalidPEFormat"));
     }
     bool flag = false;
     uint virtualAddress = 0;
     if (this._optionalHeader.NumberOfRvaAndSizes > 2)
     {
         virtualAddress = ((DataDirectory) this._dataDirectories[2]).VirtualAddress;
         flag = true;
     }
     long num5 = this._optionalHeader.Address + this._fileHeader.SizeOfOptionalHeader;
     for (num3 = 0; num3 < this._fileHeader.NumberOfSections; num3++)
     {
         SectionHeader sectionHeader = new SectionHeader(file, num5);
         Section section = null;
         if (flag && (sectionHeader.VirtualAddress == virtualAddress))
         {
             section = this._resourceSection = new ResourceSection(file, sectionHeader, partialConstruct);
         }
         else
         {
             section = new Section(file, sectionHeader);
         }
         sectionHeader.Section = section;
         this._sectionHeaders.Add(sectionHeader);
         this._sections.Add(section);
         num5 += sectionHeader.Size;
     }
     this.ConstructStream();
     ArrayList c = new ArrayList();
     long num6 = 0L;
     foreach (PEComponent component in this._streamComponents)
     {
         if (component.Address < num6)
         {
             throw new Win32Exception(11, Resources.GetString("Ex_InvalidPEFormat"));
         }
         if (component.Address > num6)
         {
             PEComponent component2 = new PEComponent(file, num6, component.Address - num6);
             c.Add(component2);
         }
         num6 = component.Address + component.Size;
     }
     if (num6 < file.Length)
     {
         PEComponent component3 = new PEComponent(file, num6, file.Length - num6);
         c.Add(component3);
     }
     this._streamComponents.AddRange(c);
     this._streamComponents.Sort(new PEComponentComparer());
     this._canRead = true;
     this._canSeek = true;
     this._length = file.Length;
     this._position = 0L;
 }
        protected void ConstructPEImage(FileStream file, bool partialConstruct)
        {
            this._partialConstruct = partialConstruct;
            this._dosHeader        = new DosHeader(file);
            long size = this._dosHeader.NtHeaderPosition - (this._dosHeader.Address + this._dosHeader.Size);

            if (size < 0L)
            {
                throw new Win32Exception(11, Resources.GetString("Ex_InvalidPEFormat"));
            }
            this._dosStub        = new DosStub(file, this._dosHeader.Address + this._dosHeader.Size, size);
            this._ntSignature    = new NtSignature(file, (long)this._dosHeader.NtHeaderPosition);
            this._fileHeader     = new FileHeader(file, this._ntSignature.Address + this._ntSignature.Size);
            this._optionalHeader = new OptionalHeader(file, this._fileHeader.Address + this._fileHeader.Size);
            long address = this._optionalHeader.Address + this._optionalHeader.Size;
            int  num3    = 0;

            for (num3 = 0; num3 < this._optionalHeader.NumberOfRvaAndSizes; num3++)
            {
                DataDirectory directory = new DataDirectory(file, address);
                address += directory.Size;
                this._dataDirectories.Add(directory);
            }
            if (this._fileHeader.SizeOfOptionalHeader < (((ulong)this._optionalHeader.Size) + (this._optionalHeader.NumberOfRvaAndSizes * Marshal.SizeOf(typeof(IMAGE_DATA_DIRECTORY)))))
            {
                throw new Win32Exception(11, Resources.GetString("Ex_InvalidPEFormat"));
            }
            bool flag           = false;
            uint virtualAddress = 0;

            if (this._optionalHeader.NumberOfRvaAndSizes > 2)
            {
                virtualAddress = ((DataDirectory)this._dataDirectories[2]).VirtualAddress;
                flag           = true;
            }
            long num5 = this._optionalHeader.Address + this._fileHeader.SizeOfOptionalHeader;

            for (num3 = 0; num3 < this._fileHeader.NumberOfSections; num3++)
            {
                SectionHeader sectionHeader = new SectionHeader(file, num5);
                Section       section       = null;
                if (flag && (sectionHeader.VirtualAddress == virtualAddress))
                {
                    section = this._resourceSection = new ResourceSection(file, sectionHeader, partialConstruct);
                }
                else
                {
                    section = new Section(file, sectionHeader);
                }
                sectionHeader.Section = section;
                this._sectionHeaders.Add(sectionHeader);
                this._sections.Add(section);
                num5 += sectionHeader.Size;
            }
            this.ConstructStream();
            ArrayList c    = new ArrayList();
            long      num6 = 0L;

            foreach (PEComponent component in this._streamComponents)
            {
                if (component.Address < num6)
                {
                    throw new Win32Exception(11, Resources.GetString("Ex_InvalidPEFormat"));
                }
                if (component.Address > num6)
                {
                    PEComponent component2 = new PEComponent(file, num6, component.Address - num6);
                    c.Add(component2);
                }
                num6 = component.Address + component.Size;
            }
            if (num6 < file.Length)
            {
                PEComponent component3 = new PEComponent(file, num6, file.Length - num6);
                c.Add(component3);
            }
            this._streamComponents.AddRange(c);
            this._streamComponents.Sort(new PEComponentComparer());
            this._canRead  = true;
            this._canSeek  = true;
            this._length   = file.Length;
            this._position = 0L;
        }