Example #1
0
 internal ResourcesReader(NTHeader header)
 {
     this.header = header;
     image = header.assembly.peImage;
     resourceDirectory = header.OptionalHeader.DataDirectories[(int)DataDirectoryName.Resource];
     ReadRootDirectory();
 }
Example #2
0
 private void WriteDataDirectories(DataDirectory[] directories)
 {
     foreach (DataDirectory directory in directories)
     {
         Writer.WriteStructure<Structures.IMAGE_DATA_DIRECTORY>(directory.rawDataDir);
     }
 }
Example #3
0
        private DataDirectory GetOverlappingDirectory(DataDirectory[] parentDirectories, DataDirectory directory)
        {
            int currentIndex = Array.IndexOf(parentDirectories, directory);

            for (int i = 0; i < parentDirectories.Length; i++)
            {
                if (parentDirectories[i].TargetOffset.FileOffset != 0)
                {
                    if (parentDirectories[i].Name == DataDirectoryName.Clr)
                    {
                        DataDirectory dir = GetOverlappingDirectory(Writer.OriginalAssembly.NETHeader.DataDirectories, directory);
                        if (dir != null)
                            return dir;
                    }

                    if (currentIndex != i &&
                        (((parentDirectories[i].TargetOffset.FileOffset >= directory.TargetOffset.FileOffset) &&
                        (parentDirectories[i].TargetOffset.FileOffset < directory.TargetOffset.FileOffset + directory.Size)) ||
                        ((directory.TargetOffset.FileOffset >= parentDirectories[i].TargetOffset.FileOffset) &&
                        (directory.TargetOffset.FileOffset < parentDirectories[i].TargetOffset.FileOffset + parentDirectories[i].Size))))

                        return parentDirectories[i];
                }
            }
            return null;
        }
Example #4
0
		public void SetDefaultValues ()
		{
			Cb = 0x48;
			Flags = RuntimeImage.ILOnly;
			CodeManagerTable = DataDirectory.Zero;
			ExportAddressTableJumps = DataDirectory.Zero;
			ManagedNativeHeader = DataDirectory.Zero;
		}
Example #5
0
        internal CLRContent(DataDirectory dataDirectory, Section section) : base(dataDirectory,section)
        {
            long offset = section.RVAToOffset(dataDirectory.VirtualAddress);

            location = new StreamLocation(offset,dataDirectory.Size);
            header = new CLRHeader(this,dataDirectory);
            meta_data = null;
        }
Example #6
0
 internal ResourceDirectoryEntry(DataDirectory dataDirectory, Location dataLocation, ResourceDirectory parentDirectory, IMAGE_RESOURCE_DIRECTORY_ENTRY directoryEntry)
     : base(dataDirectory,dataLocation)
 {
     parent_directory = parentDirectory;
     entry = directoryEntry;
     name = null;
     directory = null;
     data = null;
 }
Example #7
0
 internal ExportDirectory(DataDirectory dataDirectory, Location dirLocation, IMAGE_EXPORT_DIRECTORY exportDirectory)
     : base(dataDirectory,dirLocation)
 {
     directory = exportDirectory;
     name = new Lazy<string>(DoGetName);
     function_addresses = new Lazy<uint[]>(DoGetFunctionAddresses);
     function_name_addresses = new Lazy<uint[]>(DoGetFunctionNameAddresses);
     function_ordinals = new Lazy<ushort[]>(DoGetFunctionOrdinals);
 }
Example #8
0
        internal CLRHeader(CLRContent clrContent, DataDirectory dataDirectory)
        {
            long offset = clrContent.Section.RVAToOffset(dataDirectory.VirtualAddress);
            Stream stream = clrContent.Section.Sections.Reader.GetStream();

            stream.Seek(offset,SeekOrigin.Begin);

            content = clrContent;
            location = new StreamLocation(offset,size);
            header = Utils.Read<IMAGE_COR20_HEADER>(stream);        
        }
Example #9
0
        internal ResourceDataEntry(DataDirectory dataDirectory, Location dataLocation, ResourceDirectoryEntry directoryEntry)
            : base(dataDirectory,dataLocation)
        {
            Stream stream = directoryEntry.Directory.DataDirectory.Directories.Image.GetStream();

            stream.Seek(dataLocation.FileOffset.ToInt64(),SeekOrigin.Begin);

            directory_entry = directoryEntry;
            entry = Utils.Read<IMAGE_RESOURCE_DATA_ENTRY>(stream);
            data = GetData();
        }
Example #10
0
 public void RunProcedure()
 {
     if (clrDirectory.TargetOffset.FileOffset != 0)
     {
         Writer.MoveToOffset(clrDirectory.TargetOffset.FileOffset);
         Writer.WriteStructure<Structures.IMAGE_COR20_HEADER>(Writer.OriginalAssembly.NETHeader.reader.netHeader);
         metadataDirectory = Writer.OriginalAssembly.NETHeader.MetaDataDirectory;
         WriteMetaDataHeader();
         WriteStreamHeaders();
         WriteStreams();
     }
 }
Example #11
0
 internal ResourcesReader(NTHeader header)
 {
     this.header = header;
     this.image = header._assembly._peImage;
     resourceDirectory = header.OptionalHeader.DataDirectories[(int)DataDirectoryName.Resource];
     if (header._assembly._peImage.TrySetOffset(resourceDirectory.TargetOffset.FileOffset))
     {
         stream = header._assembly._peImage.ReadStream((int)resourceDirectory.Size);
         reader = new BinaryReader(stream);
         ReadRootDirectory();
     }
 }
Example #12
0
        public static bool IsNullOrEmpty(DataDirectory dataDirectory)
        {
            if (dataDirectory == null)
                return true;

            if (dataDirectory.VirtualAddress == 0)
                return true;

            if (dataDirectory.Size == 0)
                return true;

            return false;
        }
Example #13
0
 private void ReorderDataDirectories(DataDirectory[] directories)
 {
     // Definitely need work :D
     for (int i = 0; i < directories.Length;i ++)
     {
         if (directories[i].TargetOffset.FileOffset != 0)
         {
             DataDirectory overlap = GetOverlappingDirectory(directories, directories[i]);
             while (overlap != null)
             {
                 directories[i].TargetOffset = Offset.FromFileOffset(overlap.TargetOffset.FileOffset + overlap.Size, Writer.OriginalAssembly);
                 overlap = GetOverlappingDirectory(directories, directories[i]);
             }
         }
     }
 }
Example #14
0
 private void WriteDirectories(DataDirectory[] directories)
 {
     foreach (DataDirectory dataDirectory in directories)
     {
         if (dataDirectory.TargetOffset.FileOffset != 0)
         {
             Writer.MoveToOffset(dataDirectory.TargetOffset.FileOffset);
             if (AllowedToWriteDirectory(dataDirectory))
             {
                 Writer.BinWriter.Write(dataDirectory.GetBytes());
                 if (dataDirectory.Name == DataDirectoryName.Clr)
                 {
                     WriteDirectories(Writer.OriginalAssembly.NETHeader.DataDirectories);
                 }
             }
         }
     }
 }
Example #15
0
 private bool AllowedToWriteDirectory(DataDirectory directory)
 {
     switch (directory.Name)
     {
         case DataDirectoryName.Export:
             return !Writer.Parameters.RebuildExportTable;
         case DataDirectoryName.Import:
             return !Writer.Parameters.RebuildImportTable;
         case DataDirectoryName.Resource:
             return !Writer.Parameters.RebuildResources;
         case DataDirectoryName.Clr:
         case DataDirectoryName.NETCodeManager:
         case DataDirectoryName.NETMetadata:
         case DataDirectoryName.NETResource:
             return !Writer.Parameters.RebuildNETHeaders;
         default:
             return true;
     }
 }
Example #16
0
File: CLR.cs Project: Workshell/pe
 internal CLRContent(DataDirectory dataDirectory, Location dataLocation)
     : base(dataDirectory,dataLocation)
 {
 }
Example #17
0
 internal ImportExportWriter(PEWriter writer)
 {
     Writer = writer;
     exportDirectory = Writer.OriginalAssembly.NTHeader.OptionalHeader.DataDirectories[(int)DataDirectoryName.Export];
     importDirectory = Writer.OriginalAssembly.NTHeader.OptionalHeader.DataDirectories[(int)DataDirectoryName.Import];
 }
Example #18
0
 private void CompleteDataDirectories(Dictionary<uint, Structures.IMAGE_DATA_DIRECTORY> rawdatadirs)
 {
     var keys = rawdatadirs.Keys.ToArray();
     var values = rawdatadirs.Values.ToArray();
     for (int i = 0;i < rawdatadirs.Count-1;i++)
     {
         DataDirectory datadir = new DataDirectory((DataDirectoryName)i, sections.ToArray(), keys[i], values[i]);
         datadirectories.Add(datadir);
     }
 }
Example #19
0
        void ReadOptionalHeaders(BinaryReader reader)
        {
            var stream = reader.BaseStream;
            // - PEOptionalHeader
            //   - StandardFieldsHeader

            // pe32 = 0x10b     pe64 = 0x20b
            // Magic				2
            bool pe64 = reader.ReadUInt16() == 0x20b;

            //						pe32 || pe64

            // LMajor				1
            // LMinor				1
            // CodeSize				4
            // InitializedDataSize	4
            // UninitializedDataSize4
            // EntryPointRVA		4
            // BaseOfCode			4
            // BaseOfData			4 || 0

            //   - NTSpecificFieldsHeader

            // ImageBase			4 || 8
            // SectionAlignment		4
            // FileAlignement		4
            // OSMajor				2
            // OSMinor				2
            // UserMajor			2
            // UserMinor			2
            // SubSysMajor			2
            // SubSysMinor			2
            // Reserved				4
            // ImageSize			4
            // HeaderSize			4
            // FileChecksum			4
            stream.Seek(66, SeekOrigin.Current);

            // SubSystem			2
            var subsystem = reader.ReadUInt16();
            if ((Characteristics & 0x2000) != 0)
                Kind = PEFileKinds.Dll;
            else
            {
                switch (subsystem)
                {
                    case 1:
                        Kind = PEFileKinds.Dll;
                        break;
                    case 2:
                    case 9: // WinCE
                        Kind = PEFileKinds.WindowApplication;
                        break;
                    case 3:
                        Kind = PEFileKinds.ConsoleApplication;
                        break;
                    default:
                        Kind = (PEFileKinds)subsystem;
                        break;
                }
            }

            // DLLFlags				2
            // StackReserveSize		4 || 8
            // StackCommitSize		4 || 8
            // HeapReserveSize		4 || 8
            // HeapCommitSize		4 || 8
            // LoaderFlags			4
            // NumberOfDataDir		4

            //   - DataDirectoriesHeader

            // ExportTable			8
            // ImportTable			8
            // ResourceTable		8
            // ExceptionTable		8
            // CertificateTable		8
            // BaseRelocationTable	8

            stream.Seek(pe64 ? 90 : 74, SeekOrigin.Current);

            // Debug				8
            //image.Debug = new DataDirectory(reader.ReadUInt32(), reader.ReadUInt32());
            stream.Seek(8, SeekOrigin.Current);

            // Copyright			8
            // GlobalPtr			8
            // TLSTable				8
            // LoadConfigTable		8
            // BoundImport			8
            // IAT					8
            // DelayImportDescriptor8
            stream.Seek(56, SeekOrigin.Current);

            // CLIHeader			8
            cli = new DataDirectory(reader);
            //stream.Seek(8, SeekOrigin.Current);

            //if (cli.IsZero)
            //    throw new BadImageFormatException();

            // Reserved				8
            stream.Seek(8, SeekOrigin.Current);
        }
Example #20
0
 private Certificate(PortableExecutableImage image, DataDirectory dataDirectory, Location location, WIN_CERTIFICATE cert) : base(image, dataDirectory, location)
 {
     Length          = cert.dwLength;
     Revision        = cert.wRevision;
     CertificateType = cert.wCertificateType;
 }
Example #21
0
        public static async Task <RelocationTable> GetAsync(PortableExecutableImage image)
        {
            if (!image.NTHeaders.DataDirectories.Exists(DataDirectoryType.BaseRelocationTable))
            {
                return(null);
            }

            var dataDirectory = image.NTHeaders.DataDirectories[DataDirectoryType.BaseRelocationTable];

            if (DataDirectory.IsNullOrEmpty(dataDirectory))
            {
                return(null);
            }

            var calc       = image.GetCalculator();
            var section    = calc.RVAToSection(dataDirectory.VirtualAddress);
            var fileOffset = calc.RVAToOffset(section, dataDirectory.VirtualAddress);
            var imageBase  = image.NTHeaders.OptionalHeader.ImageBase;
            var location   = new Location(image, fileOffset, dataDirectory.VirtualAddress, imageBase + dataDirectory.VirtualAddress, dataDirectory.Size, dataDirectory.Size, section);
            var stream     = image.GetStream();

            stream.Seek(fileOffset.ToInt64(), SeekOrigin.Begin);

            var blockOffset = fileOffset;
            var blockSize   = 0u;
            var blocks      = new List <RelocationBlock>();

            while (true)
            {
                IMAGE_BASE_RELOCATION baseRelocation;

                try
                {
                    baseRelocation = await stream.ReadStructAsync <IMAGE_BASE_RELOCATION>().ConfigureAwait(false);

                    blockSize += sizeof(ulong);
                }
                catch (Exception ex)
                {
                    throw new PortableExecutableImageException(image, "Could not read base relocation block from stream.", ex);
                }

                var count           = (baseRelocation.SizeOfBlock - sizeof(ulong)) / sizeof(ushort);
                var baseRelocations = new ushort[count];

                for (var i = 0; i < count; i++)
                {
                    try
                    {
                        baseRelocations[i] = await stream.ReadUInt16Async().ConfigureAwait(false);

                        blockSize += sizeof(ushort);
                    }
                    catch (Exception ex)
                    {
                        throw new PortableExecutableImageException(image, "Could not read base relocation from stream.", ex);
                    }
                }

                var blockRVA      = calc.OffsetToRVA(blockOffset);
                var blockLocation = new Location(image, blockOffset, blockRVA, imageBase + blockRVA, blockSize, blockSize);
                var block         = new RelocationBlock(image, blockLocation, baseRelocation.VirtualAddress, baseRelocation.SizeOfBlock, baseRelocations);

                blocks.Add(block);

                if (blockSize >= dataDirectory.Size)
                {
                    break;
                }

                blockOffset += sizeof(ulong);
                blockOffset += sizeof(ushort) * count;
            }

            return(new RelocationTable(image, dataDirectory, location, blocks.ToArray()));
        }
Example #22
0
        internal static async Task <ExceptionTable> GetAsync(PortableExecutableImage image, DataDirectory dataDirectory, Location location)
        {
            var calc   = image.GetCalculator();
            var stream = image.GetStream();
            var offset = calc.RVAToOffset(dataDirectory.VirtualAddress);
            var rva    = dataDirectory.VirtualAddress;

            stream.Seek(offset.ToInt64(), SeekOrigin.Begin);

            var entrySize = Utils.SizeOf <IMAGE_RUNTIME_FUNCTION_64>();
            var entries   = new List <ExceptionTableEntry>();

            while (true)
            {
                var entryData = await stream.ReadStructAsync <IMAGE_RUNTIME_FUNCTION_64>(entrySize).ConfigureAwait(false);

                if (entryData.StartAddress == 0 && entryData.EndAddress == 0)
                {
                    break;
                }

                var entryLocation = new Location(image, offset, rva, image.NTHeaders.OptionalHeader.ImageBase + rva, entrySize.ToUInt32(), entrySize.ToUInt32());
                var entry         = new ExceptionTableEntry64(image, entryLocation, entryData);

                entries.Add(entry);

                offset += entrySize.ToUInt32();
                rva    += entrySize.ToUInt32();
            }

            var table = new ExceptionTable64(image, dataDirectory, location, entries.ToArray());

            return(table);
        }
Example #23
0
 private ExceptionTable64(PortableExecutableImage image, DataDirectory dataDirectory, Location location, ExceptionTableEntry[] entries) : base(image, dataDirectory, location, entries)
 {
 }
Example #24
0
 internal ResourceData(DataDirectory dataDirectory, Location dataLocation, ResourceDataEntry dataEntry)
     : base(dataDirectory,dataLocation)
 {
     data_entry = dataEntry;
 }
Example #25
0
        protected internal ExceptionTable(PortableExecutableImage image, DataDirectory dataDirectory, Location location, ExceptionTableEntry[] entries) : base(image, dataDirectory, location)
        {
            _entries = entries;

            Count = _entries.Length;
        }
        public static void Write()
        {
            BuildTarget              qfBuildTarget = BuildTargetFactory.Construct(BuildTargetFactory.QFName, new Build(DataDirectory.GetBuildPath()));
            string                   sourcePath    = qfBuildTarget.GetSourcePath();
            TES4Collection           collection    = TES4CollectionFactory.CreateForQUSTStageMapExportingFromESM(DataDirectory.GetESMDirectoryPath(), DataDirectory.TES4GameFileName);
            IEnumerable <TES4Record> qusts         = collection.GetGrupRecords(TES4RecordType.QUST);

            foreach (TES4Record qust in qusts)
            {
                string fileNameNoExt  = BuildTargetsWriter.GetFileNameNoExt(TES5ReferenceFactory.qf_Prefix, qust, true, null);
                string fileName       = fileNameNoExt + ".map";
                string mapFilePath    = sourcePath + Path.DirectorySeparatorChar + fileName;
                string contentsString = StageMapFromESMBuilder.BuildString(qust);
                FileWriter.WriteAllTextOrThrowIfExists(mapFilePath, contentsString);
            }
        }
        public void Execute(string targets)
        {
            if (!PreExecutionChecks(true, true, false, false))
            {
                return;
            }
            Directory.CreateDirectory(DataDirectory.GetGraphDirectoryPath());
            Build build = new Build(Build.DEFAULT_BUILD_PATH); //This argument might well not be important in this case

            BuildTarget[]       buildTargets       = BuildTargetFactory.ParseCollection(targets, build);
            BuildTargetSimple[] buildTargetsSimple = BuildTargetFactory.GetCollection(buildTargets);
            ProgressWriter?     progressWriter     = null;
            Dictionary <string, List <string> > dependencyGraph = new Dictionary <string, List <string> >();
            Dictionary <string, List <string> > usageGraph      = new Dictionary <string, List <string> >();

            using (ESMAnalyzer esmAnalyzer = ESMAnalyzer.Load())
            {
                progressWriter = new ProgressWriter("Building Interoperable Compilation Graph", buildTargets.GetTotalSourceFiles());
                BuildSourceFilesCollection <BuildTargetSimple> sourceFiles = buildTargetsSimple.GetSourceFiles();
                using (StreamWriter errorLog = new StreamWriter(TES5ScriptDependencyGraph.ErrorLogPath, false))
                {
                    using (StreamWriter debugLog = new StreamWriter(TES5ScriptDependencyGraph.DebugLogPath, false))
                    {
                        foreach (var kvp in sourceFiles)
                        {
                            BuildTargetSimple buildTarget = kvp.Key;
                            var sourceBuildFiles          = kvp.Value;
                            foreach (var sourceFile in sourceBuildFiles)
                            {
                                string scriptName = sourceFile.Substring(0, sourceFile.Length - 4);//remove extension
                                string source     = buildTarget.GetSourceFromPath(scriptName);
                                ITES4CodeFilterable ast;
                                try
                                {
                                    ast = buildTarget.GetAST(source);
                                }
                                catch (EOFOnlyException) { continue; }//Ignore files that are only whitespace or comments.

                                /*catch (UnexpectedTokenException ex)
                                 * {//UnexpectedTokenExceptions no longer occur, so this code should not be invoked.
                                 *  errorLog.WriteLine(sourceFile + ":  " + ex.Message + Environment.NewLine);
                                 *  continue;
                                 * }*/
                                List <TES4ObjectProperty> propertiesAccesses = new List <TES4ObjectProperty>();
                                ast.Filter((data) =>
                                {
                                    TES4ObjectProperty?property = data as TES4ObjectProperty;
                                    if (property == null)
                                    {
                                        return(false);
                                    }
                                    propertiesAccesses.Add(property);
                                    return(true);
                                });
                                Dictionary <string, ITES5Type> preparedProperties = new Dictionary <string, ITES5Type>();
                                foreach (var property in propertiesAccesses)
                                {
                                    Match  match           = TES5ReferenceFactory.ReferenceAndPropertyNameRegex.Match(property.StringValue);
                                    string propertyName    = match.Groups[1].Value;
                                    string propertyKeyName = propertyName.ToLower();
                                    preparedProperties.AddIfNotContainsKey(propertyKeyName, () => esmAnalyzer.GetScriptTypeByEDID(propertyName));
                                }

                                debugLog.WriteLine(scriptName + " - " + preparedProperties.Count + " prepared");
                                string lowerScriptType = scriptName.ToLower();
                                foreach (var kvp2 in preparedProperties)
                                {
                                    var    preparedPropertyKey = kvp2.Key;
                                    string propertyTypeName    = preparedProperties[preparedPropertyKey].OriginalName;
                                    //Only keys are lowercased.
                                    string lowerPropertyType = propertyTypeName.ToLower();
                                    dependencyGraph.AddNewListIfNotContainsKeyAndAddValueToList(lowerPropertyType, lowerScriptType);
                                    usageGraph.AddNewListIfNotContainsKeyAndAddValueToList(lowerScriptType, lowerPropertyType);
                                    debugLog.WriteLine("Registering a dependency from " + scriptName + " to " + propertyTypeName);
                                }

                                progressWriter.IncrementAndWrite();
                            }
                        }
                    }
                }
            }
            progressWriter.Write("Saving");
            TES5ScriptDependencyGraph graph = new TES5ScriptDependencyGraph(dependencyGraph, usageGraph);

            buildTargets.WriteGraph(graph);
            progressWriter.WriteLast();
        }
Example #28
0
 internal ManagedDataWriter(PEWriter writer)
 {
     Writer = writer;
     clrDirectory = Writer.OriginalAssembly.NTHeader.OptionalHeader.DataDirectories[(int)DataDirectoryName.Clr];
 }
Example #29
0
 internal TLSContent(DataDirectory dataDirectory, Section section) : base(dataDirectory,section)
 {
     long offset = section.RVAToOffset(dataDirectory.VirtualAddress);
     location = new StreamLocation(offset,dataDirectory.Size);
 }
Example #30
0
 void MoveTo(DataDirectory directory)
 {
     stream.Position = ResolveVirtualAddress(directory.VirtualAddress);
 }
Example #31
0
        public ESMAnalyzer(string dataFile = DataDirectory.TES4GameFileName)
        {
            if (esm == null)
            {
                TES4Collection collection = new TES4Collection(DataDirectory.GetESMDirectoryPath());
                collection.Add(dataFile);
                //NOTE - SCRI record load scheme is a copypasta, as in, i didnt check which records do actually might have SCRI
                //Doesnt really matter for other purposes than cleaniness
                TES4FileLoadScheme fileScheme = new TES4FileLoadScheme();
                TES4GrupLoadScheme grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.GMST, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.GMST, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.GLOB, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.GLOB, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.CLAS, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.CLAS, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.FACT, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.FACT, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.HAIR, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.HAIR, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.EYES, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.EYES, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.RACE, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.RACE, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.SOUN, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.SOUN, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.SKIL, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.SKIL, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.MGEF, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.MGEF, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.SCPT, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI", "SCHR" }));
                fileScheme.add(TES4RecordType.SCPT, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.LTEX, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.LTEX, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.ENCH, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.ENCH, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.SPEL, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.SPEL, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.BSGN, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.BSGN, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.ACTI, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.ACTI, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.APPA, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.APPA, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.ARMO, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.ARMO, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.BOOK, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.BOOK, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.CLOT, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.CLOT, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.CONT, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.CONT, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.DOOR, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.DOOR, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.INGR, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.INGR, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.LIGH, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.LIGH, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.MISC, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.MISC, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.STAT, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.STAT, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.GRAS, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.GRAS, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.TREE, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.TREE, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.FLOR, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.FLOR, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.FURN, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.FURN, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.WEAP, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.WEAP, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.AMMO, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.AMMO, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.NPC_, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.NPC_, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.CREA, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.CREA, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.LVLC, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.LVLC, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.SLGM, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.SLGM, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.KEYM, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.KEYM, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.ALCH, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.ALCH, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.SBSP, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.SBSP, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.SGST, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.SGST, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.LVLI, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.LVLI, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.WTHR, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.WTHR, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.CLMT, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.CLMT, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.REGN, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.REGN, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.CELL, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI", "FULL" }));//WTM:  Change:  Added "Full" for use from GetInCellFactory.cs.
                grupScheme.Add(TES4RecordType.REFR, new TES4RecordLoadScheme(new string[] { "EDID", "NAME" }));
                grupScheme.Add(TES4RecordType.ACHR, new TES4RecordLoadScheme(new string[] { "EDID", "NAME" }));
                grupScheme.Add(TES4RecordType.ACRE, new TES4RecordLoadScheme(new string[] { "EDID", "NAME" }));
                fileScheme.add(TES4RecordType.CELL, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.WRLD, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                grupScheme.Add(TES4RecordType.CELL, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                grupScheme.Add(TES4RecordType.REFR, new TES4RecordLoadScheme(new string[] { "EDID", "NAME" }));
                grupScheme.Add(TES4RecordType.ACHR, new TES4RecordLoadScheme(new string[] { "EDID", "NAME" }));
                grupScheme.Add(TES4RecordType.ACRE, new TES4RecordLoadScheme(new string[] { "EDID", "NAME" }));
                fileScheme.add(TES4RecordType.WRLD, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.DIAL, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.DIAL, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.QUST, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.QUST, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.IDLE, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.IDLE, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.PACK, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.PACK, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.CSTY, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.CSTY, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.LSCR, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.LSCR, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.LVSP, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.LVSP, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.ANIO, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.ANIO, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.WATR, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.WATR, grupScheme);
                grupScheme = new TES4GrupLoadScheme();
                grupScheme.Add(TES4RecordType.EFSH, new TES4RecordLoadScheme(new string[] { "EDID", "SCRI" }));
                fileScheme.add(TES4RecordType.EFSH, grupScheme);
                collection.Load(fileScheme);
                esm = collection;
            }

            if (this.scriptTypes == null)
            {
                this.scriptTypes = new Dictionary <string, ITES5Type>();
                List <TES4Grup> scpts = esm.GetGrup(TES4RecordType.SCPT);
                foreach (ITES4Record scpt in scpts.SelectMany(s => s.Select(r => r)))
                {
                    string schr = scpt.GetSubrecordString("SCHR");
                    string edid = scpt.GetSubrecordTrimLower("EDID");
                    if (string.IsNullOrWhiteSpace(schr) || string.IsNullOrWhiteSpace(edid))
                    {
                        continue;
                    }

                    TES5BasicType scriptType;
                    if (edid == "dark09skeletonsuicidescript" || edid == "xpebroccabossscript")//WTM:  Change:  Added special condition
                    {
                        scriptType = TES5BasicType.T_ACTOR;
                    }
                    else
                    {
                        bool isQuest             = ((int)schr.Substring(16, 1)[0]) != 0;
                        bool isActiveMagicEffect = ((int)schr.Substring(17, 1)[0]) != 0;
                        if (isQuest)
                        {
                            scriptType = TES5BasicType.T_QUEST;
                        }
                        else if (isActiveMagicEffect)
                        {
                            scriptType = TES5BasicType.T_ACTIVEMAGICEFFECT;
                        }
                        else
                        {
                            scriptType = TES5BasicType.T_OBJECTREFERENCE;
                        }
                    }

                    this.scriptTypes.Add(edid, scriptType);
                }
            }

            if (this.GlobalVariables == null)
            {
                List <TES4Grup>           globals     = esm.GetGrup(TES4RecordType.GLOB);
                List <TES5GlobalVariable> globalArray = new List <TES5GlobalVariable>();
                foreach (ITES4Record global in globals.SelectMany(g => g.Select(r => r)))
                {
                    string edid = global.GetSubrecordTrim("EDID");
                    if (string.IsNullOrWhiteSpace(edid))
                    {
                        continue;
                    }

                    globalArray.Add(new TES5GlobalVariable(edid));
                }

                /*
                 * Hacky - add infamy into the globals array
                 * Probably we should extract this from this class and put this into other place
                 */
                globalArray.Add(new TES5GlobalVariable("Infamy"));
                this.GlobalVariables = new TES5GlobalVariables(globalArray);
            }

            if (instance == null)
            {
                instance = this;
            }
        }
Example #32
0
    void ReadOptionalHeaders(out ushort subsystem)
    {
        // - PEOptionalHeader
        //   - StandardFieldsHeader

        // Magic				2
        var pe64 = binaryReader.ReadUInt16() == 0x20b;

        //						pe32 || pe64

        // LMajor				1
        // LMinor				1
        // CodeSize				4
        // InitializedDataSize	4
        // UninitializedDataSize4
        // EntryPointRVA		4
        // BaseOfCode			4
        // BaseOfData			4 || 0

        //   - NTSpecificFieldsHeader

        // ImageBase			4 || 8
        // SectionAlignment		4
        // FileAlignement		4
        // OSMajor				2
        // OSMinor				2
        // UserMajor			2
        // UserMinor			2
        // SubSysMajor			2
        // SubSysMinor			2
        // Reserved				4
        // ImageSize			4
        // HeaderSize			4
        // FileChecksum			4
        Advance(66);

        // SubSystem			2
        subsystem = binaryReader.ReadUInt16();

        // DLLFlags				2
        // StackReserveSize		4 || 8
        // StackCommitSize		4 || 8
        // HeapReserveSize		4 || 8
        // HeapCommitSize		4 || 8
        // LoaderFlags			4
        // NumberOfDataDir		4

        //   - DataDirectoriesHeader

        // ExportTable			8
        // ImportTable			8
        // ResourceTable		8
        // ExceptionTable		8
        // CertificateTable		8
        // BaseRelocationTable	8

        Advance(pe64 ? 90 : 74);

        // Debug				8
        imageDefinition.Debug = ReadDataDirectory();

        // Copyright			8
        // GlobalPtr			8
        // TLSTable				8
        // LoadConfigTable		8
        // BoundImport			8
        // IAT					8
        // DelayImportDescriptor8
        Advance(56);

        // CLIHeader			8
        cli = ReadDataDirectory();

        if (cli.IsZero)
        {
            throw new BadImageFormatException();
        }

        // Reserved				8
        Advance(8);
    }
Example #33
0
        private DebugDirectory(PortableExecutableImage image, DataDirectory dataDirectory, Location location, DebugDirectoryEntry[] entries) : base(image, dataDirectory, location)
        {
            _entries = entries;

            Count = _entries.Length;
        }
Example #34
0
 internal SectionContent(DataDirectory directory, Section section)
 {
     _data_directory = directory;
     _section = section;
 }
Example #35
0
 protected ExportTable(PortableExecutableImage image, DataDirectory dataDirectory, Location location) : base(image, dataDirectory, location)
 {
 }
Example #36
0
        internal ResourceDataEntry(PortableExecutableImage image, DataDirectory dataDirectory, Location location, ResourceDirectoryEntry directoryEntry) : base(image, dataDirectory, location)
        {
            _data = null;

            DirectoryEntry = directoryEntry;
        }
Example #37
0
        Boolean ReadCLIHeader(BinaryReader reader)
        {
            var stream = reader.BaseStream;

            var addr = ResolveVirtualAddress(cli.VirtualAddress);
            if (addr < 0) return false;
            stream.Position = addr;

            // - CLIHeader

            // Cb						4
            // MajorRuntimeVersion		2
            // MinorRuntimeVersion		2
            stream.Seek(8, SeekOrigin.Current);

            // Metadata					8
            metadata = new DataDirectory(reader);
            // Flags					4
            ExecutableKind = (PortableExecutableKinds)reader.ReadUInt32();
            // EntryPointToken			4
            //image.EntryPointToken = ReadUInt32();
            // Resources				8
            //image.Resources = ReadDataDirectory();
            // StrongNameSignature		8
            // CodeManagerTable			8
            // VTableFixups				8
            // ExportAddressTableJumps	8
            // ManagedNativeHeader		8

            return true;
        }
 private static TES4Collection GetESM()
 {
     return(TES4CollectionFactory.Create(DataDirectory.GetESMDirectoryPath(), DataDirectory.TES4GameFileName));
 }
Example #39
0
        void ReadOptionalHeaders(BinaryReader reader)
        {
            var stream = reader.BaseStream;
            // - PEOptionalHeader
            //   - StandardFieldsHeader

            // pe32 = 0x10b     pe64 = 0x20b
            // Magic				2
            bool pe64 = reader.ReadUInt16() == 0x20b;

            //						pe32 || pe64

            // LMajor				1
            // LMinor				1
            // CodeSize				4
            // InitializedDataSize	4
            // UninitializedDataSize4
            // EntryPointRVA		4
            // BaseOfCode			4
            // BaseOfData			4 || 0

            //   - NTSpecificFieldsHeader

            // ImageBase			4 || 8
            // SectionAlignment		4
            // FileAlignement		4
            // OSMajor				2
            // OSMinor				2
            // UserMajor			2
            // UserMinor			2
            // SubSysMajor			2
            // SubSysMinor			2
            // Reserved				4
            // ImageSize			4
            // HeaderSize			4
            // FileChecksum			4
            stream.Seek(66, SeekOrigin.Current);

            // SubSystem			2
            var subsystem = reader.ReadUInt16();

            if ((Characteristics & 0x2000) != 0)
            {
                Kind = PEFileKinds.Dll;
            }
            else
            {
                switch (subsystem)
                {
                case 1:
                    Kind = PEFileKinds.Dll;
                    break;

                case 2:
                case 9:     // WinCE
                    Kind = PEFileKinds.WindowApplication;
                    break;

                case 3:
                    Kind = PEFileKinds.ConsoleApplication;
                    break;

                default:
                    Kind = (PEFileKinds)subsystem;
                    break;
                }
            }

            // DLLFlags				2
            // StackReserveSize		4 || 8
            // StackCommitSize		4 || 8
            // HeapReserveSize		4 || 8
            // HeapCommitSize		4 || 8
            // LoaderFlags			4
            // NumberOfDataDir		4

            //   - DataDirectoriesHeader

            // ExportTable			8
            // ImportTable			8
            // ResourceTable		8
            // ExceptionTable		8
            // CertificateTable		8
            // BaseRelocationTable	8

            stream.Seek(pe64 ? 90 : 74, SeekOrigin.Current);

            // Debug				8
            //image.Debug = new DataDirectory(reader.ReadUInt32(), reader.ReadUInt32());
            stream.Seek(8, SeekOrigin.Current);

            // Copyright			8
            // GlobalPtr			8
            // TLSTable				8
            // LoadConfigTable		8
            // BoundImport			8
            // IAT					8
            // DelayImportDescriptor8
            stream.Seek(56, SeekOrigin.Current);

            // CLIHeader			8
            cli = new DataDirectory(reader);
            //stream.Seek(8, SeekOrigin.Current);

            //if (cli.IsZero)
            //    throw new BadImageFormatException();

            // Reserved				8
            stream.Seek(8, SeekOrigin.Current);
        }
Example #40
0
 /// <summary>
 /// Prepares a new lazy-initialized list of base relocations.
 /// </summary>
 /// <param name="context">The reader context.</param>
 /// <param name="relocDirectory">The directory that contains the base relocations.</param>
 public SerializedRelocationList(PEReaderContext context, DataDirectory relocDirectory)
 {
     _context        = context ?? throw new ArgumentNullException(nameof(context));
     _relocDirectory = relocDirectory;
 }
Example #41
0
 public DataContent(PortableExecutableImage image, DataDirectory dataDirectory, Location location)
 {
     DataDirectory = dataDirectory;
     Location      = location;
     Image         = image;
 }
Example #42
0
 internal ResourceWriter(PEWriter writer)
 {
     Writer = writer;
     resourceDirectory = Writer.OriginalAssembly.NTHeader.OptionalHeader.DataDirectories[(int)DataDirectoryName.Resource];
 }
Example #43
0
			public bool Read(CLIFile pFile)
			{
				Magic = pFile.ReadUInt16();
				MajorLinkerVersion = pFile.ReadByte();
				MinorLinkerVersion = pFile.ReadByte();
				SizeOfCode = pFile.ReadUInt32();
				SizeOfInitializedData = pFile.ReadUInt32();
				SizeOfUninitializedData = pFile.ReadUInt32();
				AddressOfEntryPoint = pFile.ReadUInt32();
				BaseOfCode = pFile.ReadUInt32();
				BaseOfData = pFile.ReadUInt32();
				ImageBase = pFile.ReadUInt32();
				SectionAlignment = pFile.ReadUInt32();
				FileAlignment = pFile.ReadUInt32();
				MajorOperatingSystemVersion = pFile.ReadUInt16();
				MinorOperatingSystemVersion = pFile.ReadUInt16();
				MajorImageVersion = pFile.ReadUInt16();
				MinorImageVersion = pFile.ReadUInt16();
				MajorSubsystemVersion = pFile.ReadUInt16();
				MinorSubsystemVersion = pFile.ReadUInt16();
				Reserved = pFile.ReadUInt32();
				SizeOfImage = pFile.ReadUInt32();
				SizeOfHeaders = pFile.ReadUInt32();
				Checksum = pFile.ReadUInt32();
				Subsystem = pFile.ReadUInt16();
				DllCharacteristics = pFile.ReadUInt16();
				SizeOfStackReserve = pFile.ReadUInt32();
				SizeOfStackCommit = pFile.ReadUInt32();
				SizeOfHeapReserve = pFile.ReadUInt32();
				SizeOfHeapCommit = pFile.ReadUInt32();
				LoaderFlags = pFile.ReadUInt32();
				NumberOfRVAAndSizes = pFile.ReadUInt32();
				for (int index = 0; index < DataDirectories.Length; ++index)
				{
					DataDirectories[index] = new DataDirectory();
					DataDirectories[index].Read(pFile);
				}
				return true;
			}
 /// <summary>
 /// Prepares a new lazy-initialized list of module import entries.
 /// </summary>
 /// <param name="peFile">The PE file containing the list of modules.</param>
 /// <param name="dataDirectory">The import data directory.</param>
 public SerializedImportedModuleList(IPEFile peFile, DataDirectory dataDirectory)
 {
     _peFile        = peFile ?? throw new ArgumentNullException(nameof(peFile));
     _dataDirectory = dataDirectory;
 }
 public InMemoryFileSystem(string originalPath, string name, DataDirectory dic)
     : base(null, originalPath, name, dic)
 {
 }
Example #46
0
 internal DelayedImportHintNameTable(PortableExecutableImage image, DataDirectory dataDirectory, Location location, Tuple <ulong, uint, ushort, string, bool>[] entries) : base(image, dataDirectory, location, entries, true)
 {
 }
Example #47
0
 internal Certificate(DataDirectory dataDirectory, Location certLocation, WIN_CERTIFICATE winCert)
     : base(dataDirectory,certLocation)
 {
     cert = winCert;
 }
Example #48
0
 public SectionContent Create(DataDirectory directory, Section section)
 {
     return new CLRContent(directory,section);
 }
        private DataDirectory GetOverlappingDirectory(DataDirectory[] parentDirectories, DataDirectory directory)
        {
            int currentIndex = Array.IndexOf(parentDirectories, directory);

            for (int i = 0; i < parentDirectories.Length; i++)
            {
                if (parentDirectories[i].TargetOffset.FileOffset != 0)
                {
                    if (parentDirectories[i].Name == DataDirectoryName.Clr)
                    {
                        DataDirectory dir = GetOverlappingDirectory(Writer.OriginalAssembly.NETHeader.DataDirectories, directory);
                        if (dir != null)
                        {
                            return(dir);
                        }
                    }

                    if (currentIndex != i &&
                        (((parentDirectories[i].TargetOffset.FileOffset >= directory.TargetOffset.FileOffset) &&
                          (parentDirectories[i].TargetOffset.FileOffset < directory.TargetOffset.FileOffset + directory.Size)) ||
                         ((directory.TargetOffset.FileOffset >= parentDirectories[i].TargetOffset.FileOffset) &&
                          (directory.TargetOffset.FileOffset < parentDirectories[i].TargetOffset.FileOffset + parentDirectories[i].Size))))
                    {
                        return(parentDirectories[i]);
                    }
                }
            }
            return(null);
        }
        private void LoadImports()
        {
            importDataDir = header.OptionalHeader.DataDirectories[(int)DataDirectoryName.Import];

            if (importDataDir.TargetOffset.FileOffset != 0)
            {
                offsetConverter = new OffsetConverter(importDataDir.Section);
                image.SetOffset(importDataDir.TargetOffset.FileOffset);

                LibraryReference libraryRef = null;
                while (true)
                {
                    libraryRef = ReadLibraryImport();

                    if (libraryRef == null)
                        break;
                    else
                    {
                        foreach (ImportMethod method in libraryRef.ImportMethods)
                            method.ParentLibrary = libraryRef;
                        imports.Add(libraryRef);
                    }
                }
            }
        }
Example #51
0
 public void SetDefaultValues()
 {
     ExportTable = DataDirectory.Zero;
     ResourceTable = DataDirectory.Zero;
     ExceptionTable = DataDirectory.Zero;
     CertificateTable = DataDirectory.Zero;
     Debug = DataDirectory.Zero;
     Copyright = DataDirectory.Zero;
     GlobalPtr = DataDirectory.Zero;
     TLSTable = DataDirectory.Zero;
     LoadConfigTable = DataDirectory.Zero;
     BoundImport = DataDirectory.Zero;
     IAT = new DataDirectory (new RVA (0x2000), 8);
     DelayImportDescriptor = DataDirectory.Zero;
     CLIHeader = new DataDirectory (new RVA (0x2008), 0x48);
     Reserved = DataDirectory.Zero;
 }
Example #52
0
        private RelocationTable(PortableExecutableImage image, DataDirectory dataDirectory, Location location, RelocationBlock[] blocks) : base(image, dataDirectory, location)
        {
            _blocks = blocks;

            Count = _blocks.Length;
        }
Example #53
0
        public static void Write()
        {
            TES4Collection           collection    = TES4CollectionFactory.CreateForQUSTReferenceAliasExporting(DataDirectory.GetESMDirectoryPath(), DataDirectory.TES4GameFileName);
            BuildTarget              qfBuildTarget = BuildTargetFactory.Construct(BuildTargetFactory.QFName, new Build(DataDirectory.GetBuildPath()));
            string                   sourcePath    = qfBuildTarget.GetSourcePath();
            IEnumerable <TES4Record> qustRecords   = collection.GetGrupRecords(TES4RecordType.QUST);

            foreach (TES4Record qust in qustRecords)
            {
                Write(sourcePath, qust);
            }
        }
Example #54
0
        public static async Task <ImportDirectory> GetAsync(PortableExecutableImage image)
        {
            if (!image.NTHeaders.DataDirectories.Exists(DataDirectoryType.ImportTable))
            {
                return(null);
            }

            DataDirectory dataDirectory = image.NTHeaders.DataDirectories[DataDirectoryType.ImportTable];

            if (DataDirectory.IsNullOrEmpty(dataDirectory))
            {
                return(null);
            }

            var calc       = image.GetCalculator();
            var section    = calc.RVAToSection(dataDirectory.VirtualAddress);
            var fileOffset = calc.RVAToOffset(section, dataDirectory.VirtualAddress);
            var stream     = image.GetStream();

            stream.Seek(fileOffset.ToInt64(), SeekOrigin.Begin);

            var size        = Utils.SizeOf <IMAGE_IMPORT_DESCRIPTOR>();
            var descriptors = new List <Tuple <ulong, IMAGE_IMPORT_DESCRIPTOR> >();

            try
            {
                ulong offset = 0;

                while (true)
                {
                    var descriptor = await stream.ReadStructAsync <IMAGE_IMPORT_DESCRIPTOR>(size).ConfigureAwait(false);

                    if (descriptor.OriginalFirstThunk == 0 && descriptor.FirstThunk == 0)
                    {
                        break;
                    }

                    var tuple = new Tuple <ulong, IMAGE_IMPORT_DESCRIPTOR>(offset, descriptor);

                    offset += size.ToUInt32();

                    descriptors.Add(tuple);
                }
            }
            catch (Exception ex)
            {
                throw new PortableExecutableImageException(image, "Could not read import descriptor from stream.", ex);
            }

            var imageBase = image.NTHeaders.OptionalHeader.ImageBase;
            var totalSize = (descriptors.Count + 1) * size;
            var location  = new Location(image, fileOffset, dataDirectory.VirtualAddress, imageBase + dataDirectory.VirtualAddress, totalSize.ToUInt32(), totalSize.ToUInt32(), section);
            var entries   = new ImportDirectoryEntry[descriptors.Count];

            for (var i = 0; i < descriptors.Count; i++)
            {
                try
                {
                    var entryOffset   = fileOffset + descriptors[i].Item1;
                    var entryRVA      = calc.OffsetToRVA(entryOffset);
                    var entryVA       = imageBase + entryRVA;
                    var entryLocation = new Location(image, entryOffset, entryRVA, entryVA, size.ToUInt32(), size.ToUInt32());
                    var name          = await GetNameAsync(calc, stream, descriptors[i].Item2.Name).ConfigureAwait(false);

                    entries[i] = new ImportDirectoryEntry(image, entryLocation, descriptors[i].Item2, name);
                }
                catch (Exception ex)
                {
                    throw new PortableExecutableImageException(image, "Could not read import library name from stream.", ex);
                }
            }

            var result = new ImportDirectory(image, dataDirectory, location, entries);

            return(result);
        }
Example #55
0
 private CLR(PortableExecutableImage image, DataDirectory dataDirectory, Location location, CLRHeader header, CLRMetaData metaData) : base(image, dataDirectory, location)
 {
     Header   = header;
     MetaData = metaData;
 }
Example #56
0
 private string GetRootBuildTargetPath()
 {
     return(Path.Combine(DataDirectory.GetBuildTargetsPath(), this.GetTargetName()) + Path.DirectorySeparatorChar);
 }
Example #57
0
 private ImportDirectory(PortableExecutableImage image, DataDirectory dataDirectory, Location location, ImportDirectoryEntry[] entries) : base(image, dataDirectory, location, entries)
 {
 }
Example #58
0
 internal DelayedImportAddressTables(PortableExecutableImage image, DataDirectory dataDirectory, Location location, Tuple <uint, ulong[], ImportDirectoryEntryBase>[] tables) : base(image, dataDirectory, location, tables, false)
 {
 }
Example #59
0
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args)
        // Default loads host configuration from DOTNET_ and command line,
        // app configuration from appsettings.json, user secrets, environment variables, and command line,
        // configure logging to console, debug, and event source,
        // and, when 'Development', enables scope validation on the dependency injection container.
        .UseWindowsService()
        .ConfigureHostConfiguration(config => {
            config.SetBasePath(AppDomain.CurrentDomain.BaseDirectory);
            config.AddJsonFile("hostsettings.json");
            config.AddCommandLine(args);
        })
        .ConfigureLogging((hostContext, configureLogging) =>
        {
            if (hostContext.Configuration.GetSection("Logging:Console").Exists())
            {
                configureLogging.AddConsole();
            }
            if (hostContext.Configuration.GetSection("Logging:Elasticsearch").Exists())
            {
                configureLogging.AddElasticsearch();
            }
        })
        .ConfigureAppConfiguration((hostContext, config) =>
        {
            //var entryAssemblyDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            //config.SetBasePath(entryAssemblyDirectory);
            config.SetBasePath(AppDomain.CurrentDomain.BaseDirectory);

            // Base JSON settings
            config.AddJsonFile("appsettings.json");

            // Other settings are based on data directory; can be relative, or start with a special folder token,
            // e.g. "{CommonApplicationData}/Nethermind/BeaconHost/Production"
            DataDirectory dataDirectory = new DataDirectory(hostContext.Configuration.GetValue <string>(DataDirectory.Key));

            // Support standard YAML config files, if specified
            string yamlConfig = hostContext.Configuration[_yamlConfigKey];
            if (!string.IsNullOrWhiteSpace(yamlConfig))
            {
                string yamlPath = Path.Combine(dataDirectory.ResolvedPath, $"{yamlConfig}.yaml");
                config.AddYamlFile(yamlPath, true, true);
            }

            // Override with environment specific JSON files
            string settingsPath = Path.Combine(dataDirectory.ResolvedPath, $"appsettings.json");
            config.AddJsonFile(settingsPath, true, true);

            config.AddCommandLine(args);
        })
        .ConfigureServices((hostContext, services) =>
        {
            services.ConfigureBeaconChain(hostContext.Configuration);
            services.AddBeaconNode(hostContext.Configuration);
            services.AddBeaconNodeStorage(hostContext.Configuration);
            services.AddBeaconNodePeering(hostContext.Configuration);
            services.AddBeaconNodeEth1Bridge(hostContext.Configuration);
            services.AddCryptographyService(hostContext.Configuration);

            if (hostContext.Configuration.GetValue <ulong>("QuickStart:GenesisTime") > 0)
            {
                services.AddBeaconNodeQuickStart(hostContext.Configuration);
            }

            // TODO: Add non-quickstart validator check
            if (hostContext.Configuration.GetSection("QuickStart:ValidatorStartIndex").Exists())
            {
                services.AddHonestValidator(hostContext.Configuration);
                services.AddHonestValidatorQuickStart(hostContext.Configuration);
            }
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup <Startup>();
        });
Example #60
0
 private string FromDirectory(DataDirectory dir)
 {
     return($"Offset: {ToDecHex((uint)dir.VirtualAddress)}, Size:{ToDecHex((uint)dir.Size)}");
 }