Compare commits

..

288 Commits
1.7.0 ... 2.0.0

Author SHA1 Message Date
Matt Nadareski
35acb77bf7 Bump version to 2.0.0 2022-03-27 20:43:49 -07:00
Matt Nadareski
e970a7b4d9 Clean up SafeDisc a little more 2022-03-18 21:05:09 -07:00
Matt Nadareski
f155291139 Update comments after confirmation of existence 2022-03-17 12:18:08 -07:00
Matt Nadareski
b0293419e1 Add note to Tages for future research 2022-03-17 12:16:41 -07:00
Matt Nadareski
09db225929 Simplify TAGES version checking 2022-03-17 12:13:11 -07:00
Matt Nadareski
0c52b4e236 Update to UnshieldSharp 1.6.7 2022-03-17 10:03:39 -07:00
Matt Nadareski
5dc30942ff Add missing TAGES version byte 2022-03-15 23:04:10 -07:00
Matt Nadareski
cab200e893 Add Shrinker PE detection 2022-03-15 22:44:10 -07:00
Matt Nadareski
c349f3a3c4 Add Gentee Installer detection (fixes #93) 2022-03-15 22:35:44 -07:00
Matt Nadareski
0acb29f2e9 Add Steam Client Engine check 2022-03-15 22:23:23 -07:00
Matt Nadareski
b66e01f7b4 Fix SLL comment 2022-03-15 22:11:37 -07:00
Matt Nadareski
8d6d215e57 Remove commented debug code 2022-03-15 22:10:13 -07:00
Matt Nadareski
d54a90a034 Add some missing SecuROM checks 2022-03-15 22:09:28 -07:00
Matt Nadareski
e1e7172561 Make ReadArbitraryRange safer 2022-03-15 21:30:46 -07:00
Matt Nadareski
6606b388f6 Remove duplicate comment 2022-03-15 15:48:05 -07:00
Matt Nadareski
b6c6c01358 Slightly rearrange generic content check invocation 2022-03-15 15:47:37 -07:00
Matt Nadareski
6886c5a4a2 Convert SVKP to PE content check 2022-03-15 15:39:35 -07:00
Matt Nadareski
87546a3dc8 Remove lingering unconfirmed TAGES check 2022-03-15 15:37:13 -07:00
Matt Nadareski
6e3028639a Fix one TAGES PE check 2022-03-15 15:05:08 -07:00
Matt Nadareski
386da02e27 Convert CExe to PE content check 2022-03-15 13:19:06 -07:00
Matt Nadareski
ec8c395ffa Streams 2022-03-15 12:39:22 -07:00
Matt Nadareski
9b98215fc9 Make SourceArray private in NE 2022-03-15 11:18:53 -07:00
Matt Nadareski
40e037fb2a Make SourceStream private 2022-03-15 11:11:54 -07:00
Matt Nadareski
17f8569a7e Only read resource in WinZipSFX 2022-03-15 11:11:44 -07:00
Matt Nadareski
1105f36cee Add hacky thing for Inno for now 2022-03-15 11:11:22 -07:00
Matt Nadareski
f9fcd8749b Add arbitrary reads to NE 2022-03-15 10:50:40 -07:00
Matt Nadareski
eef76d362a Fix arbitrary reads, update SecuROM check 2022-03-15 10:39:06 -07:00
Matt Nadareski
3b0e3693eb Add arbitrary range reading 2022-03-15 10:26:29 -07:00
Matt Nadareski
ba4c56997a Add Relocation section skeleton 2022-03-15 10:15:05 -07:00
Matt Nadareski
ca4d08567d Fix resetting position for DebugSection 2022-03-15 10:02:10 -07:00
Matt Nadareski
3211149996 Remove NE Inno check from PE path 2022-03-15 09:01:54 -07:00
Matt Nadareski
5a7e60cabb Use backward read for UPX 2022-03-15 00:30:33 -07:00
Matt Nadareski
46ff4b6ef9 Remove one use of SourceArray in SecuROM 2022-03-14 23:44:17 -07:00
Matt Nadareski
dc252e8d86 Add comments around remaining SourceArray usages 2022-03-14 23:32:19 -07:00
Matt Nadareski
133e29dc2e Add NameString to SectionHeader 2022-03-14 23:28:31 -07:00
Matt Nadareski
368cec4fc6 Remove more explicit content array usages 2022-03-14 23:17:45 -07:00
Matt Nadareski
65eea4301d Hide section complexity from content checks 2022-03-14 23:01:06 -07:00
Matt Nadareski
ceae505f4d Switch order of interface parameters 2022-03-14 22:51:17 -07:00
Matt Nadareski
a7e9164f4f Use SourceArray for PE checks 2022-03-14 22:49:35 -07:00
Matt Nadareski
3820546c07 Use SourceArray for NE checks 2022-03-14 22:43:26 -07:00
Matt Nadareski
0fa6673d21 Add debug section (nw) 2022-03-14 15:27:42 -07:00
Matt Nadareski
0a486c2195 Add another Uplay check, note 2022-03-14 15:08:27 -07:00
Matt Nadareski
a723fbefc3 Add some resource checks for WTM 2022-03-14 15:00:20 -07:00
Matt Nadareski
70e64e57dd Add PE content checks for Uplay 2022-03-14 14:56:41 -07:00
Matt Nadareski
edfc3c6c5d Add PE checks for Steam 2022-03-14 12:16:38 -07:00
Matt Nadareski
c4447fc505 Modernize path check for SolidShield a little 2022-03-14 12:09:03 -07:00
Matt Nadareski
a1d2292381 Add content checks for key2AudioXS 2022-03-14 12:08:35 -07:00
Matt Nadareski
033fb0c1ac Add utility checks to ImpulseReactor 2022-03-14 11:56:18 -07:00
Matt Nadareski
e80034abf1 Simplify CDS code a bit 2022-03-14 11:52:49 -07:00
Matt Nadareski
27e4a6c452 Add comment to old interface 2022-03-14 11:31:57 -07:00
Matt Nadareski
914497b76f Slightly safer checks before invoking 2022-03-14 11:26:10 -07:00
Matt Nadareski
513e799aa3 Migrate protections to new interfaces 2022-03-14 11:20:11 -07:00
Matt Nadareski
fcbf006e4e Migrate packers to new interfaces 2022-03-14 11:00:17 -07:00
Matt Nadareski
bef26e0fd7 Add more helpers for NE/PE 2022-03-14 10:49:02 -07:00
Matt Nadareski
3dde84f683 Add new helpers for NE/PE specific 2022-03-14 10:45:01 -07:00
Matt Nadareski
74c6aa06e0 Add new interfaces 2022-03-14 10:43:08 -07:00
Matt Nadareski
ffb529edb3 Granularly separate out executable types 2022-03-14 10:40:44 -07:00
Matt Nadareski
d1279a471c Add NE Resident Name table structures 2022-03-14 10:01:01 -07:00
Matt Nadareski
a7f406537e Add more SecuROM checks (fixes #70) 2022-03-14 09:03:43 -07:00
Matt Nadareski
df7d5150c1 Add yet another Steam exe (fixes #92) 2022-03-14 08:54:58 -07:00
Matt Nadareski
73e4569b3b Clean up recent TAGES change 2022-03-09 14:35:38 -08:00
SilasLaspada
30c249ce74 Massively overhaul TAGES detection (#87)
* Massively overhaul TAGES detection

* Address TAGES PR comments

* Address further PR comments
2022-03-09 14:00:33 -08:00
Matt Nadareski
ec83669d7d Create Executable constructors 2022-03-08 23:03:26 -08:00
Matt Nadareski
e765fb6c0b Simplify PSX Anti-Modchip a little 2022-03-08 22:33:39 -08:00
Matt Nadareski
76465d30ec Change fileContent to sectionContent in SmartE 2022-03-08 22:30:12 -08:00
Matt Nadareski
71d3771c1d Add "check disc" to LaserLok 2022-03-07 13:44:10 -08:00
Matt Nadareski
bfd9c12163 Update nuget packages 2022-03-07 13:39:04 -08:00
Matt Nadareski
eb57065562 Aggregate paths instead of relying on breaking 2022-03-03 16:36:32 -08:00
Matt Nadareski
3875f3b8fb Fix potential off-by-one error 2022-03-02 14:58:29 -08:00
Matt Nadareski
8c2bedd21e Add test program parameters 2022-03-02 10:17:50 -08:00
Matt Nadareski
b199a6aa54 Update README 2022-03-02 09:12:59 -08:00
Matt Nadareski
1b1f64c2de Lock unknown checks behind debug flag
This also re-enables some previously commented out checks that could not be verified.
2022-03-02 08:56:26 -08:00
Matt Nadareski
7b73cc9d9b Add alternate checks for StarForce (fixes #79) 2022-02-10 11:06:35 -08:00
Matt Nadareski
d9d84a01e5 Fix crash in SolidShield scanning (fixes #76) 2022-02-10 10:37:57 -08:00
Matt Nadareski
56f009ac56 Fail slower on resource parsing (fixes #81) 2022-02-10 10:28:59 -08:00
Matt Nadareski
96daf90ae8 Update protection notes in README 2022-02-04 15:24:41 -08:00
Matt Nadareski
b581cb3124 Disable content checks for RPT/ProRing 2022-02-04 15:24:05 -08:00
Matt Nadareski
4b0e39b950 Add Steam API DLLs to detection 2022-02-04 15:19:24 -08:00
Matt Nadareski
3a1c476edc Remove StarForce directory checks for now (fixes #77) 2022-01-30 21:07:35 -08:00
Matt Nadareski
0d62d5336c Add older Uplay installer to file list 2022-01-15 11:46:38 -08:00
Matt Nadareski
cf87279dfc Add content notes to SafeLock 2021-11-24 21:59:54 -08:00
Matt Nadareski
0006f7932a Remove overly-broad CDS checks 2021-11-22 20:30:58 -08:00
Matt Nadareski
841a39c6c7 Overhaul SafeLock checks 2021-11-21 21:18:56 -08:00
Matt Nadareski
60b12f25a6 Disable SafeLock content check for now 2021-11-21 14:04:16 -08:00
SilasLaspada
f2b96b6c50 Fix InstallAnywhere reporting (#71)
* Fix InstallAnywhere reporting

* Fix formatting

* Fix formatting again
2021-11-20 23:22:10 -08:00
Matt Nadareski
d2fad1ab29 Fix Alpha-ROM... again (fixes #69) 2021-10-29 15:19:50 -07:00
Matt Nadareski
6f6755b218 Remove over-matching TAGES check 2021-10-27 23:08:16 -07:00
SilasLaspada
9a2f2e6f17 Add initial detection for InstallAnywhere (#67) 2021-10-26 10:23:08 -07:00
Matt Nadareski
d9ca550e3b Add ProRing path checks; add note (fixes #68) 2021-10-26 10:12:21 -07:00
Matt Nadareski
ec66e87ee6 Remove one note from Alpha-ROM 2021-10-21 21:33:50 -07:00
Matt Nadareski
53ce3aee74 Refine Alpha-ROM checks; add notes 2021-10-20 21:06:43 -07:00
Matt Nadareski
1ecb06f020 Bump AppVeyor version 2021-09-24 10:44:55 -07:00
Matt Nadareski
3ce4ac785e Comment out probable NE-only check 2021-09-23 15:13:57 -07:00
Matt Nadareski
1df157434d Remove debug print 2021-09-23 15:05:46 -07:00
Matt Nadareski
594f001dda Add NE check for CD-Cops; add notes 2021-09-23 15:05:30 -07:00
Matt Nadareski
c2c6bc268e Update README 2021-09-23 13:51:28 -07:00
Matt Nadareski
7aa2207edd Add PEtite detection; add notes 2021-09-23 13:43:57 -07:00
Matt Nadareski
22aa1642a6 Partial cleanup of CD/DVD-Cops; add notes 2021-09-23 13:33:48 -07:00
Matt Nadareski
844a9686af Bump version to 1.8.0 2021-09-22 11:06:34 -07:00
Matt Nadareski
8f929366b3 Merge branch 'master' of https://github.com/mnadareski/BurnOutSharp 2021-09-20 21:02:40 -07:00
Matt Nadareski
dfa0fab979 Update README 2021-09-20 21:02:14 -07:00
dependabot[bot]
415d6c587f Bump SharpCompress from 0.28.3 to 0.29.0 in /BurnOutSharp (#65)
Bumps [SharpCompress](https://github.com/adamhathcock/sharpcompress) from 0.28.3 to 0.29.0.
- [Release notes](https://github.com/adamhathcock/sharpcompress/releases)
- [Commits](https://github.com/adamhathcock/sharpcompress/compare/0.28.3...0.29)

---
updated-dependencies:
- dependency-name: SharpCompress
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-09-20 12:59:41 -07:00
Matt Nadareski
b1034b964e Update success/failure tracking in AppVeyor 2021-09-16 14:40:49 -07:00
Matt Nadareski
85d2382680 Only use extra checks for NE executables in Wise 2021-09-15 15:44:26 -07:00
Matt Nadareski
a6e694fe5d Convert EXE Stealth to section based; add notes 2021-09-15 14:52:11 -07:00
Matt Nadareski
a579bfea1f Fix reading generic sections 2021-09-15 11:47:12 -07:00
Matt Nadareski
ba97abed44 Convert dotFuscator to section based 2021-09-15 11:45:35 -07:00
Matt Nadareski
9fe6b101bd Convert CDSHiELD SE to section-based 2021-09-15 11:01:51 -07:00
Matt Nadareski
1345182eea Update small things about Ring PROTECH 2021-09-14 23:01:44 -07:00
Matt Nadareski
a84ac8d3cc Update CodeLock with a few things; notes 2021-09-14 22:57:17 -07:00
Matt Nadareski
1eb07c52e5 Address comments in SolidShield 2021-09-14 14:31:03 -07:00
Matt Nadareski
0d75ee135c Combine SafeCast into SafeDisc; improvements 2021-09-14 13:56:43 -07:00
Matt Nadareski
c915f29c05 Minor formatting changes 2021-09-14 13:53:30 -07:00
Matt Nadareski
38d35d1991 Convert remaining XCP full content check 2021-09-14 11:51:01 -07:00
Matt Nadareski
dbc841cb7f Clean up formatting of remaining full content checks 2021-09-14 11:33:53 -07:00
Matt Nadareski
46f53221c9 Clean up ActiveMARK 2021-09-14 00:51:44 -07:00
Matt Nadareski
708fd01d1e Clean up CD Check 2021-09-13 23:46:59 -07:00
Matt Nadareski
4aa3ba0545 Disable possibly overly-broad CD Check check 2021-09-13 23:43:24 -07:00
Matt Nadareski
57499002d2 Use beginning seek 2021-09-13 23:16:57 -07:00
Matt Nadareski
630f628598 Update UnshieldSharp to 1.6.6 2021-09-13 11:19:55 -07:00
Matt Nadareski
d66c890b71 Combine SafeDisc and Lite 2021-09-12 16:03:58 -07:00
Matt Nadareski
2b5649588a Remove errant content checks from Bitpool 2021-09-12 13:43:08 -07:00
Matt Nadareski
5425578f78 Clean up Origin 2021-09-12 13:40:29 -07:00
Matt Nadareski
8c39adcc04 Simplify EA checks, add note to Registration 2021-09-11 23:03:56 -07:00
Matt Nadareski
7773b32847 Update comment in Inno 2021-09-11 22:48:05 -07:00
Matt Nadareski
143b261a67 Fix NE reading for Inno 2021-09-11 22:40:01 -07:00
Matt Nadareski
25fc2b9b04 Last easilly-removed fileContent reliance removal 2021-09-11 22:31:06 -07:00
Matt Nadareski
d6fd0c4d2c Reduce reliance on fileContent; add notes 2021-09-11 22:27:52 -07:00
Matt Nadareski
44c44be412 Read MS-DOS stub data directly; use with CExe 2021-09-11 21:54:38 -07:00
Matt Nadareski
7b71d7b4bf Fix resource parsing, fix MS-CAB SFX 2021-09-11 21:41:17 -07:00
Matt Nadareski
2c2aee6797 Add a couple of sections to raw read with notes 2021-09-11 21:10:29 -07:00
Matt Nadareski
afdd032f73 Start using more methods to make life easier 2021-09-11 21:03:36 -07:00
Matt Nadareski
9d52ca4b4c Fix invalid reads 2021-09-11 20:58:44 -07:00
Matt Nadareski
1bc8fe7ff6 Fix version finding for MS-CAB SFX 2021-09-11 16:58:05 -07:00
Matt Nadareski
6ab7a06dd5 Lock stream when reading raw section 2021-09-11 16:54:00 -07:00
Matt Nadareski
7195ed3587 Combine CD-Cops and DVD-Cops 2021-09-11 16:49:54 -07:00
Matt Nadareski
214e8d41c7 Pre-read 3 most commonly-used section data
This also adds comprehensive notes around the sections used in various protections, how they're used, and what we can do with them. It also adds a couple of various notes based on the findings from the protection audit
2021-09-11 16:47:25 -07:00
Matt Nadareski
bd9f583659 Add sections note to PE 2021-09-11 15:22:17 -07:00
Matt Nadareski
abbf0b7ff5 Work on PE export data section 2021-09-11 15:08:58 -07:00
Matt Nadareski
f2b9e3a31b Clean up a significant number of TODOs 2021-09-11 00:32:48 -07:00
Matt Nadareski
73dd669c20 Add and use byte array extension methods 2021-09-10 22:35:32 -07:00
Matt Nadareski
32390149f3 Identify and use .rsrc item for 321 Studios 2021-09-10 22:19:24 -07:00
Matt Nadareski
9e73d8762e Clean up StarForce; add notes 2021-09-10 22:15:49 -07:00
Matt Nadareski
09854b469e Remove redundant .rsrc check in SolidShield 2021-09-10 22:09:03 -07:00
Matt Nadareski
e817063e53 Remove debug write from NSIS 2021-09-10 22:05:43 -07:00
Matt Nadareski
7cdf6a8c79 Identify and use .rsrc item for MediaMax 2021-09-10 22:02:57 -07:00
Matt Nadareski
d87087dcfb Add note to Itenium 2021-09-10 21:58:27 -07:00
Matt Nadareski
7c27fcd8a4 Identify and use .rsrc item for EA 2021-09-10 21:52:31 -07:00
Matt Nadareski
56408ed9f4 Add note and future code in Executable 2021-09-10 21:45:34 -07:00
Matt Nadareski
bf385f0bbf Identify and use .rsrc item for NSIS 2021-09-10 21:45:14 -07:00
Matt Nadareski
2a6a2930c1 Handle some TODOs 2021-09-10 21:42:42 -07:00
Matt Nadareski
9f676732a4 A little extra safety 2021-09-10 20:59:39 -07:00
Matt Nadareski
44fac8cc92 Fix reading resource table from stream 2021-09-10 16:21:55 -07:00
Matt Nadareski
e510915098 Add note about streams 2021-09-10 16:15:20 -07:00
Matt Nadareski
b779f2f546 Only deserialze a file once per round of checks 2021-09-10 16:10:15 -07:00
Matt Nadareski
5344de96b2 Cleanup and bugfixes; additional notes 2021-09-10 15:32:37 -07:00
Matt Nadareski
1e70d960ba Remove unnecessary trims 2021-09-10 13:59:35 -07:00
Matt Nadareski
e03808fbc5 Fix trailing whitespace in resource strings 2021-09-10 13:54:12 -07:00
Matt Nadareski
373268a6a8 Convert resource checks to header checks 2021-09-10 13:51:32 -07:00
Matt Nadareski
905d440367 Process file info resources; cleanup; refactors 2021-09-10 02:58:59 -07:00
Matt Nadareski
5628cf8d73 Add Wix to the solution 2021-09-09 18:51:04 -07:00
Matt Nadareski
4aaea417f0 Make generic resource finding methods 2021-09-09 18:45:50 -07:00
Matt Nadareski
892886b730 Ensure CodePage package is installed 2021-09-09 16:32:24 -07:00
Matt Nadareski
1028050464 Use resource section to find assembly manifest 2021-09-09 16:29:17 -07:00
Matt Nadareski
af79b00bd6 Finalize resource reading 2021-09-09 16:05:17 -07:00
Matt Nadareski
dc9a581e1c Fix resource entry checking 2021-09-09 15:10:22 -07:00
Matt Nadareski
4d800fd644 Fix ResourceDirectoryString reading 2021-09-09 11:25:02 -07:00
Matt Nadareski
126e8827de Move WixToolset to separate folder now that it supports .NET Standard 2021-09-09 10:51:18 -07:00
Matt Nadareski
23c79d4452 Update WixToolset version 2021-09-09 10:44:05 -07:00
Matt Nadareski
173fc69a08 Update UnshieldSharp to 1.6.5 2021-09-09 10:37:51 -07:00
Matt Nadareski
0411278f1d Remove unused and outdated classes 2021-09-08 10:33:28 -07:00
Matt Nadareski
bb1f9bdcdc Remove search result 2021-09-08 10:28:50 -07:00
Matt Nadareski
9d5ab935de Add .txt2 check to SafeDisc 2021-09-08 10:28:35 -07:00
Matt Nadareski
1df9d145e4 Add another note to IContentCheck 2021-09-08 10:22:28 -07:00
Matt Nadareski
fba30949bd Fix one ActiveMARK check; add note 2021-09-08 10:14:02 -07:00
Matt Nadareski
198c320ad8 Convert XCP to section based; add note 2021-09-08 09:58:11 -07:00
Matt Nadareski
e798ba1104 Convert WTM to section based 2021-09-08 00:51:25 -07:00
Matt Nadareski
f8f02a54f6 Combine VOB into ProtectDISC; add notes
This also means that EVORE is no longer relevant to the code and has been fully removed.
2021-09-07 23:53:05 -07:00
Matt Nadareski
da01668cbe Convert 321Studios Activation to section based 2021-09-07 21:08:25 -07:00
Matt Nadareski
95770c63af Convert 3PLock to section based 2021-09-07 21:02:52 -07:00
Matt Nadareski
af6e5d7441 Partially convert TAGES to section based; add notes 2021-09-07 21:02:19 -07:00
Matt Nadareski
ae5bdcc97a Convert Sisiphus to section based 2021-09-06 13:58:16 -07:00
Matt Nadareski
0fc415fb34 Convert SVKP to header based; add note 2021-09-05 23:31:10 -07:00
Matt Nadareski
0fe30392d8 Add note to Steam 2021-09-05 23:29:48 -07:00
Matt Nadareski
77fc11289c Convert StarForce to section-based; add notes 2021-09-05 23:22:48 -07:00
Matt Nadareski
9d3969d4ce Remove debug output 2021-09-05 23:08:41 -07:00
Matt Nadareski
2ba2756a8f Partially convert SolidShield to section based; add notes 2021-09-05 23:02:55 -07:00
Matt Nadareski
53088b4e60 Convert SmartE to section based 2021-09-03 13:26:52 -07:00
Matt Nadareski
0dc83739e7 Add v8 white label notes to SecuROM 2021-09-03 11:16:15 -07:00
Matt Nadareski
e8a205b221 Convert SecuROM to section based; add notes 2021-09-02 22:32:06 -07:00
Matt Nadareski
02c3d3fb4a Add note to SafeLock 2021-09-02 16:09:29 -07:00
Matt Nadareski
2d3d66f077 Convert SafeDisc to section based; add notes 2021-09-02 15:22:33 -07:00
Matt Nadareski
a5f21adeee Add content matches to SafeCast; add notes 2021-09-02 09:30:37 -07:00
Matt Nadareski
cbb4cdddfa Add note to Ring PROTECH 2021-09-02 00:54:36 -07:00
Matt Nadareski
e6b898882d Add notes to PSX Anti-modchip 2021-09-01 23:12:16 -07:00
Matt Nadareski
3bd7f5c890 Convert ProtectDisc to section based 2021-09-01 23:09:01 -07:00
Matt Nadareski
39c20fd0cd Wrap file scanning in try/catch for more safety 2021-09-01 22:22:14 -07:00
Matt Nadareski
21117e81a3 Fix EVORE IsPEExecutable check 2021-09-01 16:10:06 -07:00
Matt Nadareski
df172b49db Add note to Origin 2021-09-01 14:15:38 -07:00
Matt Nadareski
1ae0f694de Convert EReg to fvinfo and section based; add note 2021-09-01 14:10:12 -07:00
Matt Nadareski
040aa8daf6 Convert MediaMax CD-3 to section based 2021-09-01 14:06:19 -07:00
Matt Nadareski
3b9aa2d45c Convert LaserLok to section based; add notes 2021-09-01 13:46:08 -07:00
Matt Nadareski
8705cac648 Convert ImpulseReactor to section based; add notes 2021-09-01 10:27:16 -07:00
Matt Nadareski
5a4e3caea8 Add note to Key-Lock 2021-08-31 22:57:28 -07:00
Matt Nadareski
593d4a35b7 Convert JoWood to section based; add notes 2021-08-31 22:56:57 -07:00
SilasLaspada
801eef5f37 Improve Steam detection (#62) 2021-08-31 22:22:47 -07:00
Matt Nadareski
a0ac0ea189 Convert Itenium to section based 2021-08-31 21:15:56 -07:00
Matt Nadareski
f249455b00 Convert GFWL to fvinfo and section based; add note 2021-08-31 20:53:17 -07:00
Matt Nadareski
8dbb8d9fe1 Disable Valve scanning until further notice 2021-08-31 20:33:32 -07:00
Matt Nadareski
ed698e05d8 Partially convert EA to section based; add notes 2021-08-30 15:08:14 -07:00
Matt Nadareski
47b189bf87 Improve CD-Key matching 2021-08-30 14:24:16 -07:00
Matt Nadareski
460eb78ecd Improve Setup Factory matching 2021-08-30 14:18:15 -07:00
Matt Nadareski
ffcaf4d16b Improve MS-CAB SFX matching 2021-08-30 12:08:17 -07:00
Matt Nadareski
64de357257 Remove debug from IIF again 2021-08-30 12:06:29 -07:00
Matt Nadareski
cc3f6622b4 Improve IIF matching 2021-08-30 11:47:49 -07:00
Matt Nadareski
f0b66d4bfb Improve NSIS matching 2021-08-30 11:40:14 -07:00
Matt Nadareski
9c32f663b0 Add notes to DVD-Cops 2021-08-30 10:02:40 -07:00
Matt Nadareski
e0e22d91e1 Add notes to CopyKiller 2021-08-30 10:00:18 -07:00
Matt Nadareski
dbc72cb4c2 Fix typo in Wise Installer 2021-08-29 22:39:34 -07:00
Matt Nadareski
17d6c6aa6b Have exception dump all info 2021-08-29 22:39:04 -07:00
Matt Nadareski
7be5916041 Partially convert CodeLock to section based; add note 2021-08-29 22:26:58 -07:00
Matt Nadareski
2d8a25178e Fix Cenega naming 2021-08-29 22:20:25 -07:00
Matt Nadareski
5195025849 Remove leftover debug in CD Check 2021-08-29 22:14:46 -07:00
Matt Nadareski
c3c2fc6171 Convert Cenga to section based; add note 2021-08-29 21:51:43 -07:00
Matt Nadareski
6fa5e9a67f Add note to CDSHiELDSE 2021-08-29 21:49:56 -07:00
Matt Nadareski
834018b325 Convert CD-Lock to section based 2021-08-29 21:49:14 -07:00
Matt Nadareski
027388f587 Add fvinfo to CDKey; add note 2021-08-29 21:40:25 -07:00
Matt Nadareski
6452d39de1 Partially convert CD-Cops to section based; add note 2021-08-29 21:38:19 -07:00
Matt Nadareski
6d78e2fff7 Partially convert CD Check to section based; add notes 2021-08-29 21:13:50 -07:00
Matt Nadareski
56ae245305 Partially convert CDS to section based; add note 2021-08-29 21:07:26 -07:00
Matt Nadareski
76b16ca6d4 Add note to Bitpool 2021-08-29 20:58:10 -07:00
Matt Nadareski
d0a174d71c Add note to AlphaROM 2021-08-29 20:56:48 -07:00
Matt Nadareski
8e62f12f61 Add note to ActiveMARK 2021-08-29 20:55:36 -07:00
Matt Nadareski
621bcdf380 Convert Wise to section based; add note 2021-08-29 20:52:00 -07:00
Matt Nadareski
1b54dd92ab Convert WZ-SFX to section and header based 2021-08-29 11:43:43 -07:00
Matt Nadareski
2b0a43ca3e Disable possibility of ReadLine in Valve check 2021-08-29 11:31:17 -07:00
Matt Nadareski
81ce49c219 Fix manifest description finding 2021-08-29 11:15:37 -07:00
Matt Nadareski
b287c7236b Fix NE header deserialization 2021-08-28 15:55:08 -07:00
Matt Nadareski
b63d4a3da0 Update EVORE 2021-08-28 00:13:19 -07:00
Matt Nadareski
e652e43cba Add more NE structures 2021-08-27 23:29:34 -07:00
Matt Nadareski
e6b2be1738 Formalize New Executable classes; renames 2021-08-27 22:34:57 -07:00
Matt Nadareski
d2606e21fe Convert WinRAR SFX to section based 2021-08-27 21:58:05 -07:00
Matt Nadareski
22235cbe84 Add Setup Factory version info checks; add notes 2021-08-27 21:49:14 -07:00
Matt Nadareski
6bd5fae1cd Add TODO on IContentCheck 2021-08-27 21:42:05 -07:00
Matt Nadareski
ebb20bbe5e Fix overmatching on JoWooDX; add note 2021-08-27 21:37:46 -07:00
Matt Nadareski
82d7395b79 Make PE parsing attempts safer 2021-08-27 21:32:12 -07:00
Matt Nadareski
451cb04714 Reduce StarForce over-matching check 2021-08-27 21:12:09 -07:00
Matt Nadareski
15e5feafef Add helper methods to PE class for later 2021-08-27 14:30:03 -07:00
Matt Nadareski
4d19bd27f0 Make MachineType enum values consistent 2021-08-27 14:29:38 -07:00
Matt Nadareski
2400f2d0ad Convert PEC to section based; add notes 2021-08-27 14:28:17 -07:00
Matt Nadareski
ee0193eb71 Clean up some usings, add note to NSIS 2021-08-27 13:30:24 -07:00
Matt Nadareski
eb76acb767 Add note to MS-CAB SFX 2021-08-27 13:13:41 -07:00
Matt Nadareski
6c77cccf53 Clarify and comment out in IIF 2021-08-27 12:03:00 -07:00
Matt Nadareski
b4ab969f88 Reorganize and create Resource-related things 2021-08-27 10:38:42 -07:00
Matt Nadareski
2de4f3f808 Continue exe organization, start IIF migration 2021-08-27 09:42:05 -07:00
Matt Nadareski
4b5d0980f7 Convert Installer VISE to section based 2021-08-26 23:18:55 -07:00
Matt Nadareski
2bdbad1ba6 Convert Inno Setup to section based 2021-08-26 23:07:04 -07:00
Matt Nadareski
3b634877d0 Add note to EXE Stealth 2021-08-26 22:22:15 -07:00
Matt Nadareski
2996bbb18f Add note to dotFuscator 2021-08-26 22:13:14 -07:00
Matt Nadareski
c4ca27608b Convert Advanced Installer to section based 2021-08-26 21:57:56 -07:00
Matt Nadareski
5a85ff2ad3 Clean up Armadillo, fix edge case 2021-08-26 21:47:44 -07:00
Matt Nadareski
a27b3cc43f Add old version UPX detection 2021-08-26 20:43:58 -07:00
Matt Nadareski
ea8f557097 Start converting Armadillo checks 2021-08-26 20:38:01 -07:00
Matt Nadareski
7bbed5985b A little EVORE cleanup 2021-08-26 16:05:38 -07:00
Matt Nadareski
0ec6dfb287 Use UPX as a guinea pig for new exe handling 2021-08-26 15:50:38 -07:00
Matt Nadareski
3b753c137b Fill out and fix way more executable stuff 2021-08-26 15:48:56 -07:00
Matt Nadareski
6cde7b8bef Reduce redundant code in content matchers now 2021-08-25 20:26:43 -07:00
Matt Nadareski
d26a89b8ab Add time elapsed to debug output 2021-08-25 20:25:45 -07:00
Matt Nadareski
3ab0bcc0ae ContentMatchSets are now expected in IContentCheck 2021-08-25 19:37:32 -07:00
Matt Nadareski
7548646ba2 Create and use the Tools namespace 2021-08-25 15:09:42 -07:00
Matt Nadareski
0b75c6f046 What I like about EVORE... 2021-08-25 14:23:11 -07:00
SilasLaspada
958d306f42 Fix NullReferenceExceptions (#59) 2021-08-24 23:13:27 -07:00
Matt Nadareski
742b25e4dd Split manifest reading into helper methods 2021-08-24 15:28:23 -07:00
Matt Nadareski
43845cf722 Rename position flag -> debug flag 2021-08-24 15:19:23 -07:00
Matt Nadareski
a2a0e5c2ee Clean up TODOs in IContentCheck 2021-08-24 15:19:10 -07:00
Matt Nadareski
93e8322ba5 Add skeleton code to MS-CAB SFX 2021-08-24 14:29:30 -07:00
Matt Nadareski
8a07c9cf4e Add byte array checks for IIF 2021-08-24 09:26:27 -07:00
Matt Nadareski
6049eda580 Add byte array checks for MS-CAB SFX 2021-08-24 09:13:58 -07:00
Matt Nadareski
177641894e Clean up MS-CAB SFX a little 2021-08-23 23:09:05 -07:00
Matt Nadareski
dc49335ace Add notes for later 2021-08-23 23:04:01 -07:00
SilasLaspada
3dcce8a8ac Add support for Intel Installation Framework detection (#57)
* Add support for Intel Installation Framework detection

* Address reviews
2021-08-23 22:56:31 -07:00
Matt Nadareski
04651d46d8 Clean up usings 2021-08-23 22:07:24 -07:00
Matt Nadareski
56aeded8eb String and EVORE cleanups 2021-08-23 22:05:18 -07:00
SilasLaspada
97c9c7e5ed Add support for Microsoft SFX CAB detection (#56)
* Add support for Microsoft SFX CAB detection

* Address reviews

* Simplify GetVersion

* Fix GetVersion
2021-08-23 22:03:28 -07:00
Matt Nadareski
a891391879 Merge branch 'master' of https://github.com/mnadareski/BurnOutSharp 2021-08-23 20:58:24 -07:00
Matt Nadareski
5aae9b01d4 Make file version finding safer 2021-08-23 20:45:13 -07:00
SilasLaspada
b74a370b11 Fix WTM false positive (#55) 2021-08-16 21:58:36 -07:00
Matt Nadareski
5e560661d4 Add extra try/catch around Valve archives 2021-07-31 21:41:06 -07:00
183 changed files with 12245 additions and 5801 deletions

2
.gitmodules vendored
View File

@@ -11,5 +11,5 @@
path = BurnOutSharp/External/stormlibsharp
url = https://github.com/robpaveza/stormlibsharp.git
[submodule "BurnOutSharp/External/WixToolset"]
path = BurnOutSharp/External/WixToolset
path = WixToolset
url = https://github.com/wixtoolset/Dtf.git

View File

@@ -13,6 +13,12 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
README.md = README.md
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "WixToolset", "WixToolset", "{09D405CA-CF15-4929-8408-C970F0656C62}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{182E02A8-5E8E-4140-9C9B-61049C33E921}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WixToolset.Dtf.WindowsInstaller", "WixToolset\src\WixToolset.Dtf.WindowsInstaller\WixToolset.Dtf.WindowsInstaller.csproj", "{B3537EB7-CEF6-4D90-A041-47626442A656}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -27,6 +33,10 @@ Global
{88735BA2-778D-4192-8EB2-FFF6843719E2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{88735BA2-778D-4192-8EB2-FFF6843719E2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{88735BA2-778D-4192-8EB2-FFF6843719E2}.Release|Any CPU.Build.0 = Release|Any CPU
{B3537EB7-CEF6-4D90-A041-47626442A656}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B3537EB7-CEF6-4D90-A041-47626442A656}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B3537EB7-CEF6-4D90-A041-47626442A656}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B3537EB7-CEF6-4D90-A041-47626442A656}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -34,4 +44,8 @@ Global
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {0B343DD2-8852-47B0-9647-DFCFBEDF933C}
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{182E02A8-5E8E-4140-9C9B-61049C33E921} = {09D405CA-CF15-4929-8408-C970F0656C62}
{B3537EB7-CEF6-4D90-A041-47626442A656} = {182E02A8-5E8E-4140-9C9B-61049C33E921}
EndGlobalSection
EndGlobal

View File

@@ -8,12 +8,12 @@
<Description>Port of BurnOut to C#, with additions</Description>
<Authors>Matt Nadareski;Gernot Knippen</Authors>
<Product>BurnOutSharp</Product>
<Copyright>Copyright (c)2005-2010 Gernot Knippen, Copyright (c)2018-2021 Matt Nadareski</Copyright>
<Copyright>Copyright (c)2005-2010 Gernot Knippen, Copyright (c)2018-2022 Matt Nadareski</Copyright>
<PackageLicenseFile>LICENSE.txt</PackageLicenseFile>
<RepositoryUrl>https://github.com/mnadareski/BurnOutSharp</RepositoryUrl>
<Version>1.7.0</Version>
<AssemblyVersion>1.7.0</AssemblyVersion>
<FileVersion>1.7.0</FileVersion>
<Version>2.0.0</Version>
<AssemblyVersion>2.0.0</AssemblyVersion>
<FileVersion>2.0.0</FileVersion>
<IncludeSource>true</IncludeSource>
<IncludeSymbols>true</IncludeSymbols>
</PropertyGroup>
@@ -23,8 +23,13 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="SharpCompress" Version="0.28.3" />
<PackageReference Include="UnshieldSharp" Version="1.6.0" />
<PackageReference Include="SharpCompress" Version="0.30.1" />
<PackageReference Include="System.Text.Encoding.CodePages" Version="6.0.0" />
<PackageReference Include="Teronis.MSBuild.Packaging.ProjectBuildInPackage" Version="1.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="UnshieldSharp" Version="1.6.7" />
<PackageReference Include="WiseUnpacker" Version="1.0.2" />
</ItemGroup>
@@ -40,12 +45,7 @@
External\libmspack4n\lib\**\*;
External\libmspack4n\libmspack4ntest\**\*;
External\stormlibsharp\lib\**;
External\stormlibsharp\TestConsole\**;
External\WixToolset\src\Samples\**;
External\WixToolset\src\Tools\**;
External\WixToolset\src\WixToolset.Dtf.MSBuild\**;
External\WixToolset\src\WixToolset.Dtf.Resources\**;
External\WixToolset\src\WixToolsetTests.*\**
External\stormlibsharp\TestConsole\**
</DefaultItemExcludes>
</PropertyGroup>
@@ -61,4 +61,10 @@
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\WixToolset\src\WixToolset.Dtf.WindowsInstaller\WixToolset.Dtf.WindowsInstaller.csproj">
<PrivateAssets>all</PrivateAssets>
</ProjectReference>
</ItemGroup>
</Project>

View File

@@ -1,245 +0,0 @@
//this file is part of BurnOut
//Copyright (C)2005-2010 Gernot Knippen
//Ported code with augments Copyright (C)2018 Matt Nadareski
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You can get a copy of the GNU General Public License
//by writing to the Free Software
//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using BurnOutSharp.ExecutableType.Microsoft;
namespace BurnOutSharp
{
internal static class EVORE
{
/// <summary>
/// Checks if the file contents that represent a PE is a DLL or an EXE
/// </summary>
/// <param name="fileContent">File contents to check</param>
/// <returns>True if the file is an EXE, false if it's a DLL</returns>
internal static bool IsEXE(byte[] fileContent)
{
int PEHeaderOffset = BitConverter.ToInt32(fileContent, 60);
short Characteristics = BitConverter.ToInt16(fileContent, PEHeaderOffset + 22);
// Check if file is dll
return (Characteristics & 0x2000) != 0x2000;
}
/// <summary>
/// Writes the file contents to a temporary file, if possible
/// </summary>
/// <param name="fileContent">File contents to write</param>
/// <param name="sExtension">Optional extension for the temproary file, defaults to ".exe"</param>
/// <returns>Name of the new temporary file, null on error</returns>
internal static string MakeTempFile(byte[] fileContent, string sExtension = ".exe")
{
string filei = Guid.NewGuid().ToString();
string tempPath = Path.Combine(Path.GetTempPath(), "tmp", $"{filei}{sExtension}");
try
{
File.Delete(tempPath);
}
catch { }
try
{
Directory.CreateDirectory(Path.GetDirectoryName(tempPath));
using (BinaryWriter bw = new BinaryWriter(File.OpenWrite(tempPath)))
{
bw.Write(fileContent);
}
return Path.GetFullPath(tempPath);
}
catch { }
return null;
}
/// <summary>
/// Copies all required DLLs for a given executable
/// </summary>
/// <param name="file">Temporary file path</param>
/// <param name="fileContent">File contents to read</param>
/// <returns>Paths for all of the copied DLLs, null on error</returns>
internal static string[] CopyDependentDlls(string file, byte[] fileContent)
{
var sections = ReadSections(fileContent);
long lastPosition;
string[] saDependentDLLs = null;
int index = 60;
int PEHeaderOffset = BitConverter.ToInt32(fileContent, index);
index = PEHeaderOffset + 120 + 8; //120 Bytes till IMAGE_DATA_DIRECTORY array,8 Bytes=size of IMAGE_DATA_DIRECTORY
uint ImportTableRVA = BitConverter.ToUInt32(fileContent, index);
index += 4;
uint ImportTableSize = BitConverter.ToUInt32(fileContent, index);
index = (int)RVA2Offset(ImportTableRVA, sections);
index += 12;
uint DllNameRVA = BitConverter.ToUInt32(fileContent, index);
index += 4;
while (DllNameRVA != 0)
{
string sDllName = "";
byte bChar;
lastPosition = index;
uint DLLNameOffset = RVA2Offset(DllNameRVA, sections);
if (DLLNameOffset > 0)
{
index = (int)DLLNameOffset;
if ((char)fileContent[index] > -1)
{
do
{
bChar = fileContent[index];
index++;
sDllName += (char)bChar;
} while (bChar != 0 && (char)fileContent[index] > -1);
sDllName = sDllName.Remove(sDllName.Length - 1, 1);
if (File.Exists(Path.Combine(Path.GetDirectoryName(file), sDllName)))
{
if (saDependentDLLs == null)
saDependentDLLs = new string[0];
else
saDependentDLLs = new string[saDependentDLLs.Length];
FileInfo fiDLL = new FileInfo(Path.Combine(Path.GetDirectoryName(file), sDllName));
saDependentDLLs[saDependentDLLs.Length - 1] = fiDLL.CopyTo(Path.GetTempPath() + sDllName, true).FullName;
}
}
index = (int)lastPosition;
}
index += 4 + 12;
DllNameRVA = BitConverter.ToUInt32(fileContent, index);
index += 4;
}
return saDependentDLLs;
}
/// <summary>
/// Attempt to run an executable
/// </summary>
/// <param name="file">Executable to attempt to run</param>
/// <returns>Process representing the running executable, null on error</returns>
internal static Process StartSafe(string file)
{
if (file == null || !File.Exists(file))
return null;
Process startingprocess = new Process();
startingprocess.StartInfo.FileName = file;
startingprocess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
startingprocess.StartInfo.CreateNoWindow = true;
startingprocess.StartInfo.ErrorDialog = false;
try
{
startingprocess.Start();
}
catch
{
return null;
}
return startingprocess;
}
private static IMAGE_SECTION_HEADER[] ReadSections(byte[] fileContent)
{
if (fileContent == null)
return null;
uint PEHeaderOffset = BitConverter.ToUInt32(fileContent, 60);
ushort NumberOfSections = BitConverter.ToUInt16(fileContent, (int)PEHeaderOffset + 6);
var sections = new IMAGE_SECTION_HEADER[NumberOfSections];
int index = (int)PEHeaderOffset + 120 + 16 * 8;
for (int i = 0; i < NumberOfSections; i++)
{
sections[i] = ReadSection(fileContent, index);
}
return sections;
}
private static IMAGE_SECTION_HEADER ReadSection(byte[] fileContent, int ptr)
{
try
{
// Get the size of a section header for later
int sectionSize = Marshal.SizeOf<IMAGE_SECTION_HEADER>();
// If the contents are null or the wrong size, we can't read a section
if (fileContent == null || fileContent.Length < sectionSize)
return null;
// Create a new section and try our best to read one
IMAGE_SECTION_HEADER section = null;
IntPtr tempPtr = IntPtr.Zero;
try
{
// Get the pointer to where the section will go
tempPtr = Marshal.AllocHGlobal(sectionSize);
// If we couldn't get the space, just return null
if (tempPtr == IntPtr.Zero)
return null;
// Copy from the array to the new space
Marshal.Copy(fileContent, ptr, tempPtr, sectionSize);
// Get the new section and return
section = Marshal.PtrToStructure<IMAGE_SECTION_HEADER>(tempPtr);
}
catch
{
// We don't care what the error was
return null;
}
finally
{
if (tempPtr != IntPtr.Zero)
Marshal.FreeHGlobal(tempPtr);
}
return section;
}
catch
{
return null;
}
}
private static uint RVA2Offset(uint RVA, IMAGE_SECTION_HEADER[] sections)
{
for (int i = 0; i < sections.Length; i++)
{
if (sections[i] == null)
continue;
var section = sections[i];
if (section.VirtualAddress <= RVA && section.VirtualAddress + section.PhysicalAddress > RVA)
return RVA - section.VirtualAddress + section.PointerToRawData;
}
return 0;
}
}
}

View File

@@ -56,31 +56,6 @@ namespace BurnOutSharp.ExecutableType.Microsoft
public const ushort IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16;
/* Directory Entries */
/* Export Directory */
public const byte IMAGE_DIRECTORY_ENTRY_EXPORT = 0;
/* Import Directory */
public const byte IMAGE_DIRECTORY_ENTRY_IMPORT = 1;
/* Resource Directory */
public const byte IMAGE_DIRECTORY_ENTRY_RESOURCE = 2;
/* Exception Directory */
public const byte IMAGE_DIRECTORY_ENTRY_EXCEPTION = 3;
/* Security Directory */
public const byte IMAGE_DIRECTORY_ENTRY_SECURITY = 4;
/* Base Relocation Table */
public const byte IMAGE_DIRECTORY_ENTRY_BASERELOC = 5;
/* Debug Directory */
public const byte IMAGE_DIRECTORY_ENTRY_DEBUG = 6;
/* Description String */
public const byte IMAGE_DIRECTORY_ENTRY_COPYRIGHT = 7;
/* Machine Value (MIPS GP) */
public const byte IMAGE_DIRECTORY_ENTRY_GLOBALPTR = 8;
/* TLS Directory */
public const byte IMAGE_DIRECTORY_ENTRY_TLS = 9;
/* Load Configuration Directory */
public const byte IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG = 10;
#endregion
#region IMAGE_SECTION_HEADER

File diff suppressed because it is too large Load Diff

View File

@@ -1,34 +0,0 @@
/*
* NEWEXE.H (C) Copyright Microsoft Corp 1984-1987
*
* Data structure definitions for the OS/2 & Windows
* executable file format.
*
* Modified by IVS on 24-Jan-1991 for Resource DeCompiler
* (C) Copyright IVS 1991
*
* http://csn.ul.ie/~caolan/pub/winresdump/winresdump/newexe.h
*/
using System.IO;
using System.Runtime.InteropServices;
namespace BurnOutSharp.ExecutableType.Microsoft
{
[StructLayout(LayoutKind.Sequential)]
internal class IMAGE_DATA_DIRECTORY
{
public uint VirtualAddress;
public uint Size;
public static IMAGE_DATA_DIRECTORY Deserialize(Stream stream)
{
var idd = new IMAGE_DATA_DIRECTORY();
idd.VirtualAddress = stream.ReadUInt32();
idd.Size = stream.ReadUInt32();
return idd;
}
}
}

View File

@@ -1,81 +0,0 @@
/*
* NEWEXE.H (C) Copyright Microsoft Corp 1984-1987
*
* Data structure definitions for the OS/2 & Windows
* executable file format.
*
* Modified by IVS on 24-Jan-1991 for Resource DeCompiler
* (C) Copyright IVS 1991
*
* http://csn.ul.ie/~caolan/pub/winresdump/winresdump/newexe.h
*/
using System.IO;
using System.Runtime.InteropServices;
namespace BurnOutSharp.ExecutableType.Microsoft
{
/// <summary>
/// DOS 1, 2, 3 .EXE header
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal class IMAGE_DOS_HEADER
{
public ushort Magic; // 00 Magic number
public ushort LastPageBytes; // 02 Bytes on last page of file
public ushort Pages; // 04 Pages in file
public ushort Relocations; // 06 Relocations
public ushort HeaderParagraphSize; // 08 Size of header in paragraphs
public ushort MinimumExtraParagraphs; // 0A Minimum extra paragraphs needed
public ushort MaximumExtraParagraphs; // 0C Maximum extra paragraphs needed
public ushort InitialSSValue; // 0E Initial (relative) SS value
public ushort InitialSPValue; // 10 Initial SP value
public ushort Checksum; // 12 Checksum
public ushort InitialIPValue; // 14 Initial IP value
public ushort InitialCSValue; // 16 Initial (relative) CS value
public ushort RelocationTableAddr; // 18 File address of relocation table
public ushort OverlayNumber; // 1A Overlay number
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Constants.ERES1WDS)]
public ushort[] Reserved1; // 1C Reserved words
public ushort OEMIdentifier; // 24 OEM identifier (for e_oeminfo)
public ushort OEMInformation; // 26 OEM information; e_oemid specific
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Constants.ERES2WDS)]
public ushort[] Reserved2; // 28 Reserved words
public int NewExeHeaderAddr; // 3C File address of new exe header
public static IMAGE_DOS_HEADER Deserialize(Stream stream)
{
IMAGE_DOS_HEADER idh = new IMAGE_DOS_HEADER();
idh.Magic = stream.ReadUInt16();
idh.LastPageBytes = stream.ReadUInt16();
idh.Pages = stream.ReadUInt16();
idh.Relocations = stream.ReadUInt16();
idh.HeaderParagraphSize = stream.ReadUInt16();
idh.MinimumExtraParagraphs = stream.ReadUInt16();
idh.MaximumExtraParagraphs = stream.ReadUInt16();
idh.InitialSSValue = stream.ReadUInt16();
idh.InitialSPValue = stream.ReadUInt16();
idh.Checksum = stream.ReadUInt16();
idh.InitialIPValue = stream.ReadUInt16();
idh.InitialCSValue = stream.ReadUInt16();
idh.RelocationTableAddr = stream.ReadUInt16();
idh.OverlayNumber = stream.ReadUInt16();
idh.Reserved1 = new ushort[Constants.ERES1WDS];
for (int i = 0; i < Constants.ERES1WDS; i++)
{
idh.Reserved1[i] = stream.ReadUInt16();
}
idh.OEMIdentifier = stream.ReadUInt16();
idh.OEMInformation = stream.ReadUInt16();
idh.Reserved2 = new ushort[Constants.ERES2WDS];
for (int i = 0; i < Constants.ERES2WDS; i++)
{
idh.Reserved2[i] = stream.ReadUInt16();
}
idh.NewExeHeaderAddr = stream.ReadInt32();
return idh;
}
}
}

View File

@@ -1,44 +0,0 @@
/*
* NEWEXE.H (C) Copyright Microsoft Corp 1984-1987
*
* Data structure definitions for the OS/2 & Windows
* executable file format.
*
* Modified by IVS on 24-Jan-1991 for Resource DeCompiler
* (C) Copyright IVS 1991
*
* http://csn.ul.ie/~caolan/pub/winresdump/winresdump/newexe.h
*/
using System.IO;
using System.Runtime.InteropServices;
namespace BurnOutSharp.ExecutableType.Microsoft
{
[StructLayout(LayoutKind.Sequential)]
internal class IMAGE_FILE_HEADER
{
public ushort Machine;
public ushort NumberOfSections;
public uint TimeDateStamp;
public uint PointerToSymbolTable;
public uint NumberOfSymbols;
public ushort SizeOfOptionalHeader;
public ushort Characteristics;
public static IMAGE_FILE_HEADER Deserialize(Stream stream)
{
var ifh = new IMAGE_FILE_HEADER();
ifh.Machine = stream.ReadUInt16();
ifh.NumberOfSections = stream.ReadUInt16();
ifh.TimeDateStamp = stream.ReadUInt32();
ifh.PointerToSymbolTable = stream.ReadUInt32();
ifh.NumberOfSymbols = stream.ReadUInt32();
ifh.SizeOfOptionalHeader = stream.ReadUInt16();
ifh.Characteristics = stream.ReadUInt16();
return ifh;
}
}
}

View File

@@ -1,103 +0,0 @@
/*
* NEWEXE.H (C) Copyright Microsoft Corp 1984-1987
*
* Data structure definitions for the OS/2 & Windows
* executable file format.
*
* Modified by IVS on 24-Jan-1991 for Resource DeCompiler
* (C) Copyright IVS 1991
*
* http://csn.ul.ie/~caolan/pub/winresdump/winresdump/newexe.h
*/
using System.IO;
using System.Runtime.InteropServices;
namespace BurnOutSharp.ExecutableType.Microsoft
{
[StructLayout(LayoutKind.Sequential)]
internal class IMAGE_OPTIONAL_HEADER
{
// Standard fields
public ushort Magic;
public byte MajorLinkerVersion;
public byte MinorLinkerVersion;
public uint SizeOfCode;
public uint SizeOfInitializedData;
public uint SizeOfUninitializedData;
public uint AddressOfEntryPoint;
public uint BaseOfCode;
public uint BaseOfData;
// NT additional fields.
public uint ImageBase;
public uint SectionAlignment;
public uint FileAlignment;
public ushort MajorOperatingSystemVersion;
public ushort MinorOperatingSystemVersion;
public ushort MajorImageVersion;
public ushort MinorImageVersion;
public ushort MajorSubsystemVersion;
public ushort MinorSubsystemVersion;
public uint Reserved1;
public uint SizeOfImage;
public uint SizeOfHeaders;
public uint CheckSum;
public ushort Subsystem;
public ushort DllCharacteristics;
public uint SizeOfStackReserve;
public uint SizeOfStackCommit;
public uint SizeOfHeapReserve;
public uint SizeOfHeapCommit;
public uint LoaderFlags;
public uint NumberOfRvaAndSizes;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Constants.IMAGE_NUMBEROF_DIRECTORY_ENTRIES)]
public IMAGE_DATA_DIRECTORY[] DataDirectory;
public static IMAGE_OPTIONAL_HEADER Deserialize(Stream stream)
{
var ioh = new IMAGE_OPTIONAL_HEADER();
ioh.Magic = stream.ReadUInt16();
ioh.MajorLinkerVersion = stream.ReadByteValue();
ioh.MinorLinkerVersion = stream.ReadByteValue();
ioh.SizeOfCode = stream.ReadUInt32();
ioh.SizeOfInitializedData = stream.ReadUInt32();
ioh.SizeOfUninitializedData = stream.ReadUInt32();
ioh.AddressOfEntryPoint = stream.ReadUInt32();
ioh.BaseOfCode = stream.ReadUInt32();
ioh.BaseOfData = stream.ReadUInt32();
ioh.ImageBase = stream.ReadUInt32();
ioh.SectionAlignment = stream.ReadUInt32();
ioh.FileAlignment = stream.ReadUInt32();
ioh.MajorOperatingSystemVersion = stream.ReadUInt16();
ioh.MinorOperatingSystemVersion = stream.ReadUInt16();
ioh.MajorImageVersion = stream.ReadUInt16();
ioh.MinorImageVersion = stream.ReadUInt16();
ioh.MajorSubsystemVersion = stream.ReadUInt16();
ioh.MinorSubsystemVersion = stream.ReadUInt16();
ioh.Reserved1 = stream.ReadUInt32();
ioh.SizeOfImage = stream.ReadUInt32();
ioh.SizeOfHeaders = stream.ReadUInt32();
ioh.CheckSum = stream.ReadUInt32();
ioh.Subsystem = stream.ReadUInt16();
ioh.DllCharacteristics = stream.ReadUInt16();
ioh.SizeOfStackReserve = stream.ReadUInt32();
ioh.SizeOfStackCommit = stream.ReadUInt32();
ioh.SizeOfHeapReserve = stream.ReadUInt32();
ioh.SizeOfHeapCommit = stream.ReadUInt32();
ioh.LoaderFlags = stream.ReadUInt32();
ioh.NumberOfRvaAndSizes = stream.ReadUInt32();
ioh.DataDirectory = new IMAGE_DATA_DIRECTORY[Constants.IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
for (int i = 0; i < Constants.IMAGE_NUMBEROF_DIRECTORY_ENTRIES; i++)
{
ioh.DataDirectory[i] = IMAGE_DATA_DIRECTORY.Deserialize(stream);
}
return ioh;
}
}
}

View File

@@ -1,96 +0,0 @@
/*
* NEWEXE.H (C) Copyright Microsoft Corp 1984-1987
*
* Data structure definitions for the OS/2 & Windows
* executable file format.
*
* Modified by IVS on 24-Jan-1991 for Resource DeCompiler
* (C) Copyright IVS 1991
*
* http://csn.ul.ie/~caolan/pub/winresdump/winresdump/newexe.h
*/
using System.IO;
using System.Runtime.InteropServices;
namespace BurnOutSharp.ExecutableType.Microsoft
{
/// <summary>
/// New .EXE header
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal class IMAGE_OS2_HEADER
{
public ushort Magic; // 00 Magic number NE_MAGIC
public byte LinkerVersion; // 02 Linker Version number
public byte LinkerRevision; // 03 Linker Revision number
public ushort EntryTableOffset; // 04 Offset of Entry Table
public ushort EntryTableSize; // 06 Number of bytes in Entry Table
public uint CrcChecksum; // 08 Checksum of whole file
public ushort Flags; // 0C Flag word
public ushort Autodata; // 0E Automatic data segment number
public ushort InitialHeapAlloc; // 10 Initial heap allocation
public ushort InitialStackAlloc; // 12 Initial stack allocation
public uint InitialCSIPSetting; // 14 Initial CS:IP setting
public uint InitialSSSPSetting; // 18 Initial SS:SP setting
public ushort FileSegmentCount; // 1C Count of file segments
public ushort ModuleReferenceTableSize; // 1E Entries in Module Reference Table
public ushort NonResidentNameTableSize; // 20 Size of non-resident name table
public ushort SegmentTableOffset; // 22 Offset of Segment Table
public ushort ResourceTableOffset; // 24 Offset of Resource Table
public ushort ResidentNameTableOffset; // 26 Offset of resident name table
public ushort ModuleReferenceTableOffset; // 28 Offset of Module Reference Table
public ushort ImportedNamesTableOffset; // 2A Offset of Imported Names Table
public uint NonResidentNamesTableOffset; // 2C Offset of Non-resident Names Table
public ushort MovableEntriesCount; // 30 Count of movable entries
public ushort SegmentAlignmentShiftCount; // 32 Segment alignment shift count
public ushort ResourceEntriesCount; // 34 Count of resource entries
public byte TargetOperatingSystem; // 36 Target operating system
public byte AdditionalFlags; // 37 Additional flags
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Constants.NERESWORDS)]
public ushort[] Reserved; // 38 3 reserved words
public byte WindowsSDKRevision; // 3E Windows SDK revison number
public byte WindowsSDKVersion; // 3F Windows SDK version number
public static IMAGE_OS2_HEADER Deserialize(Stream stream)
{
var ioh = new IMAGE_OS2_HEADER();
ioh.Magic = stream.ReadUInt16();
ioh.LinkerVersion = stream.ReadByteValue();
ioh.LinkerRevision = stream.ReadByteValue();
ioh.EntryTableOffset = stream.ReadUInt16();
ioh.EntryTableSize = stream.ReadUInt16();
ioh.CrcChecksum = stream.ReadUInt32();
ioh.Flags = stream.ReadUInt16();
ioh.Autodata = stream.ReadUInt16();
ioh.InitialHeapAlloc = stream.ReadUInt16();
ioh.InitialStackAlloc = stream.ReadUInt16();
ioh.InitialCSIPSetting = stream.ReadUInt32();
ioh.InitialSSSPSetting = stream.ReadUInt32();
ioh.FileSegmentCount = stream.ReadUInt16();
ioh.ModuleReferenceTableSize = stream.ReadUInt16();
ioh.NonResidentNameTableSize = stream.ReadUInt16();
ioh.SegmentTableOffset = stream.ReadUInt16();
ioh.ResourceTableOffset = stream.ReadUInt16();
ioh.ResidentNameTableOffset = stream.ReadUInt16();
ioh.ModuleReferenceTableOffset = stream.ReadUInt16();
ioh.ImportedNamesTableOffset = stream.ReadUInt16();
ioh.NonResidentNamesTableOffset = stream.ReadUInt32();
ioh.MovableEntriesCount = stream.ReadUInt16();
ioh.SegmentAlignmentShiftCount = stream.ReadUInt16();
ioh.ResourceEntriesCount = stream.ReadUInt16();
ioh.TargetOperatingSystem = stream.ReadByteValue();
ioh.AdditionalFlags = stream.ReadByteValue();
ioh.Reserved = new ushort[Constants.NERESWORDS];
for (int i = 0; i < Constants.NERESWORDS; i++)
{
ioh.Reserved[i] = stream.ReadUInt16();
}
ioh.WindowsSDKRevision = stream.ReadByteValue();
ioh.WindowsSDKVersion = stream.ReadByteValue();
return ioh;
}
}
}

View File

@@ -1,38 +0,0 @@
/*
* NEWEXE.H (C) Copyright Microsoft Corp 1984-1987
*
* Data structure definitions for the OS/2 & Windows
* executable file format.
*
* Modified by IVS on 24-Jan-1991 for Resource DeCompiler
* (C) Copyright IVS 1991
*
* http://csn.ul.ie/~caolan/pub/winresdump/winresdump/newexe.h
*/
using System.IO;
using System.Runtime.InteropServices;
namespace BurnOutSharp.ExecutableType.Microsoft
{
[StructLayout(LayoutKind.Sequential)]
internal class IMAGE_RESOURCE_DATA_ENTRY
{
public uint OffsetToData;
public uint Size;
public uint CodePage;
public uint Reserved;
public static IMAGE_RESOURCE_DATA_ENTRY Deserialize(Stream stream)
{
var irde = new IMAGE_RESOURCE_DATA_ENTRY();
irde.OffsetToData = stream.ReadUInt32();
irde.Size = stream.ReadUInt32();
irde.CodePage = stream.ReadUInt32();
irde.Reserved = stream.ReadUInt32();
return irde;
}
}
}

View File

@@ -1,42 +0,0 @@
/*
* NEWEXE.H (C) Copyright Microsoft Corp 1984-1987
*
* Data structure definitions for the OS/2 & Windows
* executable file format.
*
* Modified by IVS on 24-Jan-1991 for Resource DeCompiler
* (C) Copyright IVS 1991
*
* http://csn.ul.ie/~caolan/pub/winresdump/winresdump/newexe.h
*/
using System.IO;
using System.Runtime.InteropServices;
namespace BurnOutSharp.ExecutableType.Microsoft
{
[StructLayout(LayoutKind.Sequential)]
internal class IMAGE_RESOURCE_DIRECTORY
{
public uint Characteristics;
public uint TimeDateStamp;
public ushort MajorVersion;
public ushort MinorVersion;
public ushort NumberOfNamedEntries;
public ushort NumberOfIdEntries;
public static IMAGE_RESOURCE_DIRECTORY Deserialize(Stream stream)
{
var ird = new IMAGE_RESOURCE_DIRECTORY();
ird.Characteristics = stream.ReadUInt32();
ird.TimeDateStamp = stream.ReadUInt32();
ird.MajorVersion = stream.ReadUInt16();
ird.MinorVersion = stream.ReadUInt16();
ird.NumberOfNamedEntries = stream.ReadUInt16();
ird.NumberOfIdEntries = stream.ReadUInt16();
return ird;
}
}
}

View File

@@ -1,34 +0,0 @@
/*
* NEWEXE.H (C) Copyright Microsoft Corp 1984-1987
*
* Data structure definitions for the OS/2 & Windows
* executable file format.
*
* Modified by IVS on 24-Jan-1991 for Resource DeCompiler
* (C) Copyright IVS 1991
*
* http://csn.ul.ie/~caolan/pub/winresdump/winresdump/newexe.h
*/
using System.IO;
using System.Runtime.InteropServices;
namespace BurnOutSharp.ExecutableType.Microsoft
{
[StructLayout(LayoutKind.Sequential)]
internal class IMAGE_RESOURCE_DIRECTORY_ENTRY
{
public uint Name;
public uint OffsetToData;
public static IMAGE_RESOURCE_DIRECTORY_ENTRY Deserialize(Stream stream)
{
var irde = new IMAGE_RESOURCE_DIRECTORY_ENTRY();
irde.Name = stream.ReadUInt32();
irde.OffsetToData = stream.ReadUInt32();
return irde;
}
}
}

View File

@@ -1,34 +0,0 @@
/*
* NEWEXE.H (C) Copyright Microsoft Corp 1984-1987
*
* Data structure definitions for the OS/2 & Windows
* executable file format.
*
* Modified by IVS on 24-Jan-1991 for Resource DeCompiler
* (C) Copyright IVS 1991
*
* http://csn.ul.ie/~caolan/pub/winresdump/winresdump/newexe.h
*/
using System.IO;
using System.Runtime.InteropServices;
namespace BurnOutSharp.ExecutableType.Microsoft
{
[StructLayout(LayoutKind.Sequential)]
internal class IMAGE_RESOURCE_DIR_STRING_U
{
public ushort Length;
public char[] NameString;
public static IMAGE_RESOURCE_DIR_STRING_U Deserialize(Stream stream)
{
var irdsu = new IMAGE_RESOURCE_DIR_STRING_U();
irdsu.Length = stream.ReadUInt16();
irdsu.NameString = stream.ReadChars(irdsu.Length);
return irdsu;
}
}
}

View File

@@ -1,59 +0,0 @@
/*
* NEWEXE.H (C) Copyright Microsoft Corp 1984-1987
*
* Data structure definitions for the OS/2 & Windows
* executable file format.
*
* Modified by IVS on 24-Jan-1991 for Resource DeCompiler
* (C) Copyright IVS 1991
*
* http://csn.ul.ie/~caolan/pub/winresdump/winresdump/newexe.h
*/
using System.IO;
using System.Runtime.InteropServices;
namespace BurnOutSharp.ExecutableType.Microsoft
{
[StructLayout(LayoutKind.Sequential)]
internal class IMAGE_SECTION_HEADER
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Constants.IMAGE_SIZEOF_SHORT_NAME)]
public byte[] Name;
// Misc
public uint PhysicalAddress;
public uint VirtualSize;
public uint VirtualAddress;
public uint SizeOfRawData;
public uint PointerToRawData;
public uint PointerToRelocations;
public uint PointerToLinenumbers;
public ushort NumberOfRelocations;
public ushort NumberOfLinenumbers;
public SectionCharacteristics Characteristics;
public static IMAGE_SECTION_HEADER Deserialize(Stream stream)
{
var ish = new IMAGE_SECTION_HEADER();
ish.Name = stream.ReadBytes(Constants.IMAGE_SIZEOF_SHORT_NAME);
// Misc
ish.PhysicalAddress = stream.ReadUInt32();
ish.VirtualSize = ish.PhysicalAddress;
ish.VirtualAddress = stream.ReadUInt32();
ish.SizeOfRawData = stream.ReadUInt32();
ish.PointerToRawData = stream.ReadUInt32();
ish.PointerToRelocations = stream.ReadUInt32();
ish.PointerToLinenumbers = stream.ReadUInt32();
ish.NumberOfRelocations = stream.ReadUInt16();
ish.NumberOfLinenumbers = stream.ReadUInt16();
ish.Characteristics = (SectionCharacteristics)stream.ReadUInt32();
return ish;
}
}
}

View File

@@ -0,0 +1,217 @@
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.MZ.Headers
{
/// <summary>
/// The MS-DOS EXE format, also known as MZ after its signature (the initials of Microsoft engineer Mark Zbykowski),
/// was introduced with MS-DOS 2.0 (version 1.0 only sported the simple COM format). It is designed as a relocatable
/// executable running under real mode. As such, only DOS and Windows 9x can use this format natively, but there are
/// several free DOS emulators (e.g., DOSBox) that support it and that run under various operating systems (e.g.,
/// Linux, Amiga, Windows NT, etc.). Although they can exist on their own, MZ executables are embedded in all NE, LE,
/// and PE executables, usually as stubs so that when they are ran under DOS, they display a warning.
/// </summary>
/// <remarks>https://wiki.osdev.org/MZ</remarks>
public class MSDOSExecutableHeader
{
#region Standard Fields
/// <summary>
/// 0x5A4D (ASCII for 'M' and 'Z') [00]
/// </summary>
public ushort Magic;
/// <summary>
/// Number of bytes in the last page. [02]
/// </summary>
public ushort LastPageBytes;
/// <summary>
/// Number of whole/partial pages. [04]
/// </summary>
public ushort Pages;
/// <summary>
/// Number of entries in the relocation table. [06]
/// </summary>
public ushort Relocations;
/// <summary>
/// The number of paragraphs taken up by the header.It can be any value, as the loader
/// just uses it to find where the actual executable data starts. It may be larger than
/// what the "standard" fields take up, and you may use it if you want to include your
/// own header metadata, or put the relocation table there, or use it for any other purpose. [08]
/// </summary>
public ushort HeaderParagraphSize;
/// <summary>
/// The number of paragraphs required by the program, excluding the PSP and program image.
/// If no free block is big enough, the loading stops. [0A]
/// </summary>
public ushort MinimumExtraParagraphs;
/// <summary>
/// The number of paragraphs requested by the program.
/// If no free block is big enough, the biggest one possible is allocated. [0C]
/// </summary>
public ushort MaximumExtraParagraphs;
/// <summary>
/// Relocatable segment address for SS. [0E]
/// </summary>
public ushort InitialSSValue;
/// <summary>
/// Initial value for SP. [10]
/// </summary>
public ushort InitialSPValue;
/// <summary>
/// When added to the sum of all other words in the file, the result should be zero. [12]
/// </summary>
public ushort Checksum;
/// <summary>
/// Initial value for IP. [14]
/// </summary>
public ushort InitialIPValue;
/// <summary>
/// Relocatable segment address for CS. [16]
/// </summary>
public ushort InitialCSValue;
/// <summary>
/// The (absolute) offset to the relocation table. [18]
/// </summary>
public ushort RelocationTableAddr;
/// <summary>
/// Value used for overlay management.
/// If zero, this is the main executable. [1A]
/// </summary>
public ushort OverlayNumber;
#endregion
#region PE Extensions
/// <summary>
/// Reserved words [1C]
/// </summary>
public ushort[] Reserved1;
/// <summary>
/// Defined by name but no other information is given; typically zeroes [24]
/// </summary>
public ushort OEMIdentifier;
/// <summary>
/// Defined by name but no other information is given; typically zeroes [26]
/// </summary>
public ushort OEMInformation;
/// <summary>
/// Reserved words [28]
/// </summary>
public ushort[] Reserved2;
/// <summary>
/// Starting address of the PE header [3C]
/// </summary>
public int NewExeHeaderAddr;
#endregion
/// <summary>
/// All data after the last item in the header but before the new EXE header address
/// </summary>
public byte[] ExecutableData;
public static MSDOSExecutableHeader Deserialize(Stream stream, bool asStub = true)
{
MSDOSExecutableHeader idh = new MSDOSExecutableHeader();
idh.Magic = stream.ReadUInt16();
idh.LastPageBytes = stream.ReadUInt16();
idh.Pages = stream.ReadUInt16();
idh.Relocations = stream.ReadUInt16();
idh.HeaderParagraphSize = stream.ReadUInt16();
idh.MinimumExtraParagraphs = stream.ReadUInt16();
idh.MaximumExtraParagraphs = stream.ReadUInt16();
idh.InitialSSValue = stream.ReadUInt16();
idh.InitialSPValue = stream.ReadUInt16();
idh.Checksum = stream.ReadUInt16();
idh.InitialIPValue = stream.ReadUInt16();
idh.InitialCSValue = stream.ReadUInt16();
idh.RelocationTableAddr = stream.ReadUInt16();
idh.OverlayNumber = stream.ReadUInt16();
// If we're not reading as a stub, return now
if (!asStub)
return idh;
idh.Reserved1 = new ushort[Constants.ERES1WDS];
for (int i = 0; i < Constants.ERES1WDS; i++)
{
idh.Reserved1[i] = stream.ReadUInt16();
}
idh.OEMIdentifier = stream.ReadUInt16();
idh.OEMInformation = stream.ReadUInt16();
idh.Reserved2 = new ushort[Constants.ERES2WDS];
for (int i = 0; i < Constants.ERES2WDS; i++)
{
idh.Reserved2[i] = stream.ReadUInt16();
}
idh.NewExeHeaderAddr = stream.ReadInt32();
idh.ExecutableData = stream.ReadBytes(idh.NewExeHeaderAddr - (int)stream.Position);
return idh;
}
public static MSDOSExecutableHeader Deserialize(byte[] content, ref int offset, bool asStub = true)
{
MSDOSExecutableHeader idh = new MSDOSExecutableHeader();
idh.Magic = content.ReadUInt16(ref offset);
idh.LastPageBytes = content.ReadUInt16(ref offset);
idh.Pages = content.ReadUInt16(ref offset);
idh.Relocations = content.ReadUInt16(ref offset);
idh.HeaderParagraphSize = content.ReadUInt16(ref offset);
idh.MinimumExtraParagraphs = content.ReadUInt16(ref offset);
idh.MaximumExtraParagraphs = content.ReadUInt16(ref offset);
idh.InitialSSValue = content.ReadUInt16(ref offset);
idh.InitialSPValue = content.ReadUInt16(ref offset);
idh.Checksum = content.ReadUInt16(ref offset);
idh.InitialIPValue = content.ReadUInt16(ref offset);
idh.InitialCSValue = content.ReadUInt16(ref offset);
idh.RelocationTableAddr = content.ReadUInt16(ref offset);
idh.OverlayNumber = content.ReadUInt16(ref offset);
// If we're not reading as a stub, return now
if (!asStub)
return idh;
idh.Reserved1 = new ushort[Constants.ERES1WDS];
for (int i = 0; i < Constants.ERES1WDS; i++)
{
idh.Reserved1[i] = content.ReadUInt16(ref offset);
}
idh.OEMIdentifier = content.ReadUInt16(ref offset);
idh.OEMInformation = content.ReadUInt16(ref offset);
idh.Reserved2 = new ushort[Constants.ERES2WDS];
for (int i = 0; i < Constants.ERES2WDS; i++)
{
idh.Reserved2[i] = content.ReadUInt16(ref offset);
}
idh.NewExeHeaderAddr = content.ReadInt32(ref offset);
idh.ExecutableData = content.ReadBytes(ref offset, idh.NewExeHeaderAddr - offset);
return idh;
}
}
}

View File

@@ -1,42 +0,0 @@
/*
* NEWEXE.H (C) Copyright Microsoft Corp 1984-1987
*
* Data structure definitions for the OS/2 & Windows
* executable file format.
*
* Modified by IVS on 24-Jan-1991 for Resource DeCompiler
* (C) Copyright IVS 1991
*
* http://csn.ul.ie/~caolan/pub/winresdump/winresdump/newexe.h
*/
using System.IO;
using System.Runtime.InteropServices;
namespace BurnOutSharp.ExecutableType.Microsoft
{
[StructLayout(LayoutKind.Sequential)]
internal class NAMEINFO
{
public ushort Offset;
public ushort Length;
public ushort Flags;
public ushort ID;
public ushort Handle;
public ushort Usage;
public static NAMEINFO Deserialize(Stream stream)
{
var ni = new NAMEINFO();
ni.Offset = stream.ReadUInt16();
ni.Length = stream.ReadUInt16();
ni.Flags = stream.ReadUInt16();
ni.ID = stream.ReadUInt16();
ni.Handle = stream.ReadUInt16();
ni.Usage = stream.ReadUInt16();
return ni;
}
}
}

View File

@@ -0,0 +1,79 @@
using System.IO;
using System.Text;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.NE.Entries
{
/// <summary>
/// These name strings are case-sensitive and are not null-terminated
/// </summary>
public class ResidentNameTableEntry
{
/// <summary>
/// Length of the name string that follows.
/// A zero value indicates the end of the name table.
/// </summary>
public byte Length;
/// <summary>
/// ASCII text of the name string.
/// </summary>
public byte[] Data;
/// <summary>
/// Ordinal number (index into entry table).
/// This value is ignored for the module name.
/// </summary>
public ushort OrdinalNumber;
/// <summary>
/// ASCII text of the name string
/// </summary>
public string DataAsString
{
get
{
if (Data == null)
return string.Empty;
// Try to read direct as ASCII
try
{
return Encoding.ASCII.GetString(Data);
}
catch { }
// If ASCII encoding fails, then just return an empty string
return string.Empty;
}
}
public static ResidentNameTableEntry Deserialize(Stream stream)
{
var rnte = new ResidentNameTableEntry();
rnte.Length = stream.ReadByteValue();
if (rnte.Length == 0)
return rnte;
rnte.Data = stream.ReadBytes(rnte.Length);
rnte.OrdinalNumber = stream.ReadUInt16();
return rnte;
}
public static ResidentNameTableEntry Deserialize(byte[] content, ref int offset)
{
var rnte = new ResidentNameTableEntry();
rnte.Length = content.ReadByte(ref offset);
if (rnte.Length == 0)
return rnte;
rnte.Data = content.ReadBytes(ref offset, rnte.Length);
rnte.OrdinalNumber = content.ReadUInt16(ref offset);
return rnte;
}
}
}

View File

@@ -0,0 +1,44 @@
using System.IO;
using System.Text;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.NE.Entries
{
/// <summary>
/// Resource type and name strings
/// </summary>
public class ResourceNameString
{
/// <summary>
/// Length of the type or name string that follows. A zero value
/// indicates the end of the resource type and name string, also
/// the end of the resource table.
/// </summary>
public byte Length;
/// <summary>
/// ASCII text of the type or name string.
/// </summary>
public char[] Value;
public static ResourceNameString Deserialize(Stream stream)
{
var rns = new ResourceNameString();
rns.Length = stream.ReadByteValue();
rns.Value = stream.ReadChars(rns.Length, Encoding.ASCII);
return rns;
}
public static ResourceNameString Deserialize(byte[] content, ref int offset)
{
var rns = new ResourceNameString();
rns.Length = content.ReadByte(ref offset);
rns.Value = Encoding.ASCII.GetChars(content, offset, rns.Length); offset += rns.Length;
return rns;
}
}
}

View File

@@ -0,0 +1,75 @@
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.NE.Entries
{
/// <summary>
/// A table of resources for this type
/// </summary>
public class ResourceTableEntry
{
/// <summary>
/// File offset to the contents of the resource data,
/// relative to beginning of file. The offset is in terms
/// of the alignment shift count value specified at
/// beginning of the resource table.
/// </summary>
public ushort Offset;
/// <summary>
/// Length of the resource in the file (in bytes).
/// </summary>
public ushort Length;
/// <summary>
/// Resource flags
/// </summary>
public ResourceTableEntryFlags Flags;
/// <summary>
/// This is an integer type if the high-order
/// bit is set (8000h), otherwise it is the offset to the
/// resource string, the offset is relative to the
/// beginning of the resource table.
/// </summary>
public ushort ResourceID;
/// <summary>
/// Reserved.
/// </summary>
public ushort Handle;
/// <summary>
/// Reserved.
/// </summary>
public ushort Usage;
public static ResourceTableEntry Deserialize(Stream stream)
{
var ni = new ResourceTableEntry();
ni.Offset = stream.ReadUInt16();
ni.Length = stream.ReadUInt16();
ni.Flags = (ResourceTableEntryFlags)stream.ReadUInt16();
ni.ResourceID = stream.ReadUInt16();
ni.Handle = stream.ReadUInt16();
ni.Usage = stream.ReadUInt16();
return ni;
}
public static ResourceTableEntry Deserialize(byte[] content, ref int offset)
{
var ni = new ResourceTableEntry();
ni.Offset = content.ReadUInt16(ref offset);
ni.Length = content.ReadUInt16(ref offset);
ni.Flags = (ResourceTableEntryFlags)content.ReadUInt16(ref offset);
ni.ResourceID = content.ReadUInt16(ref offset);
ni.Handle = content.ReadUInt16(ref offset);
ni.Usage = content.ReadUInt16(ref offset);
return ni;
}
}
}

View File

@@ -0,0 +1,69 @@
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.NE.Entries
{
/// <summary>
/// Resource type information block
/// </summary>
public class ResourceTypeInformationBlock
{
/// <summary>
/// Type ID. This is an integer type if the high-order bit is
/// set (8000h); otherwise, it is an offset to the type string,
/// the offset is relative to the beginning of the resource
/// table. A zero type ID marks the end of the resource type
/// information blocks.
/// </summary>
public ushort TypeID;
/// <summary>
/// Number of resources for this type.
/// </summary>
public ushort ResourceCount;
/// <summary>
/// Reserved.
/// </summary>
public uint Reserved;
/// <summary>
/// Reserved.
/// </summary>
public ResourceTableEntry[] ResourceTable;
public static ResourceTypeInformationBlock Deserialize(Stream stream)
{
var rtib = new ResourceTypeInformationBlock();
rtib.TypeID = stream.ReadUInt16();
rtib.ResourceCount = stream.ReadUInt16();
rtib.Reserved = stream.ReadUInt32();
rtib.ResourceTable = new ResourceTableEntry[rtib.ResourceCount];
for (int i = 0; i < rtib.ResourceCount; i++)
{
rtib.ResourceTable[i] = ResourceTableEntry.Deserialize(stream);
}
return rtib;
}
public static ResourceTypeInformationBlock Deserialize(byte[] content, ref int offset)
{
var rtib = new ResourceTypeInformationBlock();
rtib.TypeID = content.ReadUInt16(ref offset);
rtib.ResourceCount = content.ReadUInt16(ref offset);
rtib.Reserved = content.ReadUInt32(ref offset);
rtib.ResourceTable = new ResourceTableEntry[rtib.ResourceCount];
for (int i = 0; i < rtib.ResourceCount; i++)
{
rtib.ResourceTable[i] = ResourceTableEntry.Deserialize(content, ref offset);
}
return rtib;
}
}
}

View File

@@ -0,0 +1,61 @@
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.NE.Entries
{
/// <summary>
/// The segment table contains an entry for each segment in the executable
/// file. The number of segment table entries are defined in the segmented
/// EXE header. The first entry in the segment table is segment number 1.
/// The following is the structure of a segment table entry.
/// </summary>
public class SegmentTableEntry
{
/// <summary>
/// Logical-sector offset (n byte) to the contents of the segment
/// data, relative to the beginning of the file. Zero means no
/// file data.
/// </summary>
public ushort StartFileSector;
/// <summary>
/// Length of the segment in the file, in bytes. Zero means 64K.
/// </summary>
public ushort BytesInFile;
/// <summary>
/// Attribute flags
/// </summary>
public SegmentTableEntryFlags Flags;
/// <summary>
/// Minimum allocation size of the segment, in bytes.
/// Total size of the segment. Zero means 64K
/// </summary>
public ushort MinimumAllocation;
public static SegmentTableEntry Deserialize(Stream stream)
{
var nste = new SegmentTableEntry();
nste.StartFileSector = stream.ReadUInt16();
nste.BytesInFile = stream.ReadUInt16();
nste.Flags = (SegmentTableEntryFlags)stream.ReadUInt16();
nste.MinimumAllocation = stream.ReadUInt16();
return nste;
}
public static SegmentTableEntry Deserialize(byte[] content, ref int offset)
{
var nste = new SegmentTableEntry();
nste.StartFileSector = content.ReadUInt16(ref offset);
nste.BytesInFile = content.ReadUInt16(ref offset);
nste.Flags = (SegmentTableEntryFlags)content.ReadUInt16(ref offset);
nste.MinimumAllocation = content.ReadUInt16(ref offset);
return nste;
}
}
}

View File

@@ -0,0 +1,256 @@
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.NE.Headers
{
/// <summary>
/// The NE header is a relatively large structure with multiple characteristics.
/// Because of the age of the format some items are unclear in meaning.
/// </summary>
/// <remarks>http://bytepointer.com/resources/win16_ne_exe_format_win3.0.htm</remarks>
public class NewExecutableHeader
{
/// <summary>
/// Signature word. [00]
/// "N" is low-order byte.
/// "E" is high-order byte.
/// </summary>
public ushort Magic;
/// <summary>
/// Version number of the linker. [02]
/// </summary>
public byte LinkerVersion;
/// <summary>
/// Revision number of the linker. [03]
/// </summary>
public byte LinkerRevision;
/// <summary>
/// Entry Table file offset, relative to the beginning of the segmented EXE header. [04]
/// </summary>
public ushort EntryTableOffset;
/// <summary>
/// Number of bytes in the entry table. [06]
/// </summary>
public ushort EntryTableSize;
/// <summary>
/// 32-bit CRC of entire contents of file. [08]
/// These words are taken as 00 during the calculation.
/// </summary>
public uint CrcChecksum;
/// <summary>
/// Program flags, bitmapped [0C]
/// </summary>
public byte ProgramFlags;
/// <summary>
/// Application flags, bitmapped [0D]
/// </summary>
public byte ApplicationFlags;
/// <summary>
/// Automatic data segment number [0E]
/// </summary>
public ushort Autodata;
/// <summary>
/// Initial heap allocation [10]
/// </summary>
public ushort InitialHeapAlloc;
/// <summary>
/// Initial stack allocation [12]
/// </summary>
public ushort InitialStackAlloc;
/// <summary>
/// CS:IP entry point, CS is index into segment table [14]
/// </summary>
public uint InitialCSIPSetting;
/// <summary>
/// SS:SP inital stack pointer, SS is index into segment table [18]
/// </summary>
public uint InitialSSSPSetting;
/// <summary>
/// Number of segments in segment table [1C]
/// </summary>
public ushort FileSegmentCount;
/// <summary>
/// Entries in Module Reference Table [1E]
/// </summary>
public ushort ModuleReferenceTableSize;
/// <summary>
/// Size of non-resident name table [20]
/// </summary>
public ushort NonResidentNameTableSize;
/// <summary>
/// Offset of Segment Table [22]
/// </summary>
public ushort SegmentTableOffset;
/// <summary>
/// Offset of Resource Table [24]
/// </summary>
public ushort ResourceTableOffset;
/// <summary>
/// Offset of resident name table [26]
/// </summary>
public ushort ResidentNameTableOffset;
/// <summary>
/// Offset of Module Reference Table [28]
/// </summary>
public ushort ModuleReferenceTableOffset;
/// <summary>
/// Offset of Imported Names Table [2A]
/// </summary>
public ushort ImportedNamesTableOffset;
/// <summary>
/// Offset of Non-resident Names Table [2C]
/// </summary>
public uint NonResidentNamesTableOffset;
/// <summary>
/// Count of moveable entry points listed in entry table [30]
/// </summary>
public ushort MovableEntriesCount;
/// <summary>
/// File allignment size shift count (0-9 (default 512 byte pages)) [32]
/// </summary>
public ushort SegmentAlignmentShiftCount;
/// <summary>
/// Count of resource table entries [34]
/// </summary>
public ushort ResourceEntriesCount;
/// <summary>
/// Target operating system [36]
/// </summary>
public byte TargetOperatingSystem;
/// <summary>
/// Other OS/2 flags [37]
/// </summary>
public byte AdditionalFlags;
/// <summary>
/// Offset to return thunks or start of gangload area [38]
/// </summary>
public ushort ReturnThunkOffset;
/// <summary>
/// Offset to segment reference thunks or size of gangload area [3A]
/// </summary>
public ushort SegmentReferenceThunkOffset;
/// <summary>
/// Minimum code swap area size [3C]
/// </summary>
public ushort MinCodeSwapAreaSize;
/// <summary>
/// Windows SDK revison number [3E]
/// </summary>
public byte WindowsSDKRevision;
/// <summary>
/// Windows SDK version number [3F]
/// </summary>
public byte WindowsSDKVersion;
public static NewExecutableHeader Deserialize(Stream stream)
{
var neh = new NewExecutableHeader();
neh.Magic = stream.ReadUInt16();
neh.LinkerVersion = stream.ReadByteValue();
neh.LinkerRevision = stream.ReadByteValue();
neh.EntryTableOffset = stream.ReadUInt16();
neh.EntryTableSize = stream.ReadUInt16();
neh.CrcChecksum = stream.ReadUInt32();
neh.ProgramFlags = stream.ReadByteValue();
neh.ApplicationFlags = stream.ReadByteValue();
neh.Autodata = stream.ReadUInt16();
neh.InitialHeapAlloc = stream.ReadUInt16();
neh.InitialStackAlloc = stream.ReadUInt16();
neh.InitialCSIPSetting = stream.ReadUInt32();
neh.InitialSSSPSetting = stream.ReadUInt32();
neh.FileSegmentCount = stream.ReadUInt16();
neh.ModuleReferenceTableSize = stream.ReadUInt16();
neh.NonResidentNameTableSize = stream.ReadUInt16();
neh.SegmentTableOffset = stream.ReadUInt16();
neh.ResourceTableOffset = stream.ReadUInt16();
neh.ResidentNameTableOffset = stream.ReadUInt16();
neh.ModuleReferenceTableOffset = stream.ReadUInt16();
neh.ImportedNamesTableOffset = stream.ReadUInt16();
neh.NonResidentNamesTableOffset = stream.ReadUInt32();
neh.MovableEntriesCount = stream.ReadUInt16();
neh.SegmentAlignmentShiftCount = stream.ReadUInt16();
neh.ResourceEntriesCount = stream.ReadUInt16();
neh.TargetOperatingSystem = stream.ReadByteValue();
neh.AdditionalFlags = stream.ReadByteValue();
neh.ReturnThunkOffset = stream.ReadUInt16();
neh.SegmentReferenceThunkOffset = stream.ReadUInt16();
neh.MinCodeSwapAreaSize = stream.ReadUInt16();
neh.WindowsSDKRevision = stream.ReadByteValue();
neh.WindowsSDKVersion = stream.ReadByteValue();
return neh;
}
public static NewExecutableHeader Deserialize(byte[] content, ref int offset)
{
var neh = new NewExecutableHeader();
neh.Magic = content.ReadUInt16(ref offset);
neh.LinkerVersion = content.ReadByte(ref offset);
neh.LinkerRevision = content.ReadByte(ref offset);
neh.EntryTableOffset = content.ReadUInt16(ref offset);
neh.EntryTableSize = content.ReadUInt16(ref offset);
neh.CrcChecksum = content.ReadUInt32(ref offset);
neh.ProgramFlags = content.ReadByte(ref offset);
neh.ApplicationFlags = content.ReadByte(ref offset);
neh.Autodata = content.ReadUInt16(ref offset);
neh.InitialHeapAlloc = content.ReadUInt16(ref offset);
neh.InitialStackAlloc = content.ReadUInt16(ref offset);
neh.InitialCSIPSetting = content.ReadUInt32(ref offset);
neh.InitialSSSPSetting = content.ReadUInt32(ref offset);
neh.FileSegmentCount = content.ReadUInt16(ref offset);
neh.ModuleReferenceTableSize = content.ReadUInt16(ref offset);
neh.NonResidentNameTableSize = content.ReadUInt16(ref offset);
neh.SegmentTableOffset = content.ReadUInt16(ref offset);
neh.ResourceTableOffset = content.ReadUInt16(ref offset);
neh.ResidentNameTableOffset = content.ReadUInt16(ref offset);
neh.ModuleReferenceTableOffset = content.ReadUInt16(ref offset);
neh.ImportedNamesTableOffset = content.ReadUInt16(ref offset);
neh.NonResidentNamesTableOffset = content.ReadUInt32(ref offset);
neh.MovableEntriesCount = content.ReadUInt16(ref offset);
neh.SegmentAlignmentShiftCount = content.ReadUInt16(ref offset);
neh.ResourceEntriesCount = content.ReadUInt16(ref offset);
neh.TargetOperatingSystem = content.ReadByte(ref offset);
neh.AdditionalFlags = content.ReadByte(ref offset);
neh.ReturnThunkOffset = content.ReadUInt16(ref offset);
neh.SegmentReferenceThunkOffset = content.ReadUInt16(ref offset);
neh.MinCodeSwapAreaSize = content.ReadUInt16(ref offset);
neh.WindowsSDKRevision = content.ReadByte(ref offset);
neh.WindowsSDKVersion = content.ReadByte(ref offset);
return neh;
}
}
}

View File

@@ -0,0 +1,233 @@
using System;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.MZ.Headers;
using BurnOutSharp.ExecutableType.Microsoft.NE.Headers;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.NE
{
/// <summary>
/// The WIN-NE executable format, designed for Windows 3.x, was the "NE", or "New Executable" format.
/// Again, a 16bit format, it alleviated the maximum size restrictions that the MZ format had.
/// </summary>
public class NewExecutable
{
/// <summary>
/// Value determining if the executable is initialized or not
/// </summary>
public bool Initialized { get; } = false;
/// <summary>
/// Source array that the executable was parsed from
/// </summary>
private readonly byte[] _sourceArray = null;
/// <summary>
/// Source stream that the executable was parsed from
/// </summary>
private readonly Stream _sourceStream = null;
#region Headers
/// <summary>
/// he DOS stub is a valid MZ exe.
/// This enables the develper to package both an MS-DOS and Win16 version of the program,
/// but normally just prints "This Program requires Microsoft Windows".
/// The e_lfanew field (offset 0x3C) points to the NE header.
// </summary>
public MSDOSExecutableHeader DOSStubHeader;
/// <summary>
/// The NE header is a relatively large structure with multiple characteristics.
/// Because of the age of the format some items are unclear in meaning.
/// </summary>
public NewExecutableHeader NewExecutableHeader;
#endregion
#region Tables
#endregion
#region Constructors
// TODO: Add more and more parts of a standard NE executable, not just the header
// TODO: Tables? What about the tables?
// TODO: Implement the rest of the structures found at http://bytepointer.com/resources/win16_ne_exe_format_win3.0.htm
// (Left off at RESIDENT-NAME TABLE)
/// <summary>
/// Create a NewExecutable object from a stream
/// </summary>
/// <param name="stream">Stream representing a file</param>
/// <remarks>
/// This constructor assumes that the stream is already in the correct position to start parsing
/// </remarks>
public NewExecutable(Stream stream)
{
if (stream == null || !stream.CanRead || !stream.CanSeek)
return;
this.Initialized = Deserialize(stream);
this._sourceStream = stream;
}
/// <summary>
/// Create a NewExecutable object from a byte array
/// </summary>
/// <param name="fileContent">Byte array representing a file</param>
/// <param name="offset">Positive offset representing the current position in the array</param>
public NewExecutable(byte[] fileContent, int offset)
{
if (fileContent == null || fileContent.Length == 0 || offset < 0)
return;
this.Initialized = Deserialize(fileContent, offset);
this._sourceArray = fileContent;
}
/// <summary>
/// Deserialize a NewExecutable object from a stream
/// </summary>
/// <param name="stream">Stream representing a file</param>
private bool Deserialize(Stream stream)
{
try
{
// Attempt to read the DOS header first
this.DOSStubHeader = MSDOSExecutableHeader.Deserialize(stream);
stream.Seek(this.DOSStubHeader.NewExeHeaderAddr, SeekOrigin.Begin);
if (this.DOSStubHeader.Magic != Constants.IMAGE_DOS_SIGNATURE)
return false;
// If the new header address is invalid for the file, it's not a NE
if (this.DOSStubHeader.NewExeHeaderAddr >= stream.Length)
return false;
// Then attempt to read the NE header
this.NewExecutableHeader = NewExecutableHeader.Deserialize(stream);
if (this.NewExecutableHeader.Magic != Constants.IMAGE_OS2_SIGNATURE)
return false;
}
catch (Exception ex)
{
//Console.WriteLine($"Errored out on a file: {ex}");
return false;
}
return true;
}
/// <summary>
/// Deserialize a NewExecutable object from a byte array
/// </summary>
/// <param name="fileContent">Byte array representing a file</param>
/// <param name="offset">Positive offset representing the current position in the array</param>
private bool Deserialize(byte[] content, int offset)
{
try
{
// Attempt to read the DOS header first
this.DOSStubHeader = MSDOSExecutableHeader.Deserialize(content, ref offset);
offset = this.DOSStubHeader.NewExeHeaderAddr;
if (this.DOSStubHeader.Magic != Constants.IMAGE_DOS_SIGNATURE)
return false;
// If the new header address is invalid for the file, it's not a PE
if (this.DOSStubHeader.NewExeHeaderAddr >= content.Length)
return false;
// Then attempt to read the NE header
this.NewExecutableHeader = NewExecutableHeader.Deserialize(content, ref offset);
if (this.NewExecutableHeader.Magic != Constants.IMAGE_OS2_SIGNATURE)
return false;
}
catch (Exception ex)
{
//Console.WriteLine($"Errored out on a file: {ex}");
return false;
}
return true;
}
#endregion
#region Helpers
/// <summary>
/// Read an arbitrary range from the source
/// </summary>
/// <param name="rangeStart">The start of where to read data from, -1 means start of source</param>
/// <param name="length">How many bytes to read, -1 means read until end</param>
/// <returns></returns>
public byte[] ReadArbitraryRange(int rangeStart = -1, int length = -1)
{
try
{
// If we have a source stream, use that
if (this._sourceStream != null)
return ReadArbitraryRangeFromSourceStream(rangeStart, length);
// If we have a source array, use that
if (this._sourceArray != null)
return ReadArbitraryRangeFromSourceArray(rangeStart, length);
// Otherwise, return null
return null;
}
catch (Exception ex)
{
// TODO: How to handle this differently?
return null;
}
}
/// <summary>
/// Read an arbitrary range from the stream source, if possible
/// </summary>
/// <param name="rangeStart">The start of where to read data from, -1 means start of source</param>
/// <param name="length">How many bytes to read, -1 means read until end</param>
/// <returns></returns>
private byte[] ReadArbitraryRangeFromSourceStream(int rangeStart, int length)
{
lock (this._sourceStream)
{
int startingIndex = (int)Math.Max(rangeStart, 0);
int readLength = (int)Math.Min(length == -1 ? length = Int32.MaxValue : length, this._sourceStream.Length);
long originalPosition = this._sourceStream.Position;
this._sourceStream.Seek(startingIndex, SeekOrigin.Begin);
byte[] sectionData = this._sourceStream.ReadBytes(readLength);
this._sourceStream.Seek(originalPosition, SeekOrigin.Begin);
return sectionData;
}
}
/// <summary>
/// Read an arbitrary range from the array source, if possible
/// </summary>
/// <param name="rangeStart">The start of where to read data from, -1 means start of source</param>
/// <param name="length">How many bytes to read, -1 means read until end</param>
/// <returns></returns>
private byte[] ReadArbitraryRangeFromSourceArray(int rangeStart, int length)
{
int startingIndex = (int)Math.Max(rangeStart, 0);
int readLength = (int)Math.Min(length == -1 ? length = Int32.MaxValue : length, this._sourceArray.Length);
try
{
return this._sourceArray.ReadBytes(ref startingIndex, readLength);
}
catch
{
// Just absorb errors for now
// TODO: Investigate why and when this would be hit
return null;
}
}
#endregion
}
}

View File

@@ -0,0 +1,59 @@
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.NE.Entries;
namespace BurnOutSharp.ExecutableType.Microsoft.NE.Tables
{
/// <summary>
/// The resident-name table follows the resource table, and contains this
/// module's name string and resident exported procedure name strings. The
/// first string in this table is this module's name. These name strings
/// are case-sensitive and are not null-terminated.
/// </summary>
public class ResidentNameTable
{
/// <summary>
/// The first string in this table is this module's name.
/// These name strings are case-sensitive and are not null-terminated.
/// </summary>
public ResidentNameTableEntry[] NameTableEntries;
public static ResidentNameTable Deserialize(Stream stream)
{
var rnt = new ResidentNameTable();
var nameTableEntries = new List<ResidentNameTableEntry>();
while (true)
{
var rnte = ResidentNameTableEntry.Deserialize(stream);
if (rnte == null || rnte.Length == 0)
break;
nameTableEntries.Add(rnte);
}
rnt.NameTableEntries = nameTableEntries.ToArray();
return rnt;
}
public static ResidentNameTable Deserialize(byte[] content, ref int offset)
{
var rnt = new ResidentNameTable();
var nameTableEntries = new List<ResidentNameTableEntry>();
while (true)
{
var rnte = ResidentNameTableEntry.Deserialize(content, ref offset);
if (rnte == null || rnte.Length == 0)
break;
nameTableEntries.Add(rnte);
}
rnt.NameTableEntries = nameTableEntries.ToArray();
return rnt;
}
}
}

View File

@@ -0,0 +1,101 @@
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.NE.Entries;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.NE.Tables
{
/// <summary>
/// The resource table follows the segment table and contains entries for
/// each resource in the executable file. The resource table consists of
/// an alignment shift count, followed by a table of resource records. The
/// resource records define the type ID for a set of resources. Each
/// resource record contains a table of resource entries of the defined
/// type. The resource entry defines the resource ID or name ID for the
/// resource. It also defines the location and size of the resource.
/// </summary>
/// <remarks>http://bytepointer.com/resources/win16_ne_exe_format_win3.0.htm</remarks>
public class ResourceTable
{
/// <summary>
/// Alignment shift count for resource data.
/// </summary>
public ushort AlignmentShiftCount;
/// <summary>
/// A table of resource type information blocks.
/// </summary>
public ResourceTypeInformationBlock[] TypeInformationBlocks;
/// <summary>
/// Resource type and name strings are stored at the end of the
/// resource table. Note that these strings are NOT null terminated and
/// are case sensitive.
/// </summary>
public ResourceNameString[] TypeAndNameStrings;
public static ResourceTable Deserialize(Stream stream)
{
var rt = new ResourceTable();
rt.AlignmentShiftCount = stream.ReadUInt16();
var typeInformationBlocks = new List<ResourceTypeInformationBlock>();
while (true)
{
var block = ResourceTypeInformationBlock.Deserialize(stream);
if (block.TypeID == 0)
break;
typeInformationBlocks.Add(block);
}
rt.TypeInformationBlocks = typeInformationBlocks.ToArray();
var typeAndNameStrings = new List<ResourceNameString>();
while (true)
{
var str = ResourceNameString.Deserialize(stream);
if (str.Length == 0)
break;
typeAndNameStrings.Add(str);
}
rt.TypeAndNameStrings = typeAndNameStrings.ToArray();
return rt;
}
public static ResourceTable Deserialize(byte[] content, ref int offset)
{
var rt = new ResourceTable();
rt.AlignmentShiftCount = content.ReadUInt16(ref offset);
var typeInformationBlocks = new List<ResourceTypeInformationBlock>();
while (true)
{
var block = ResourceTypeInformationBlock.Deserialize(content, ref offset);
if (block.TypeID == 0)
break;
typeInformationBlocks.Add(block);
}
rt.TypeInformationBlocks = typeInformationBlocks.ToArray();
var typeAndNameStrings = new List<ResourceNameString>();
while (true)
{
var str = ResourceNameString.Deserialize(content, ref offset);
if (str.Length == 0)
break;
typeAndNameStrings.Add(str);
}
rt.TypeAndNameStrings = typeAndNameStrings.ToArray();
return rt;
}
}
}

View File

@@ -1,67 +0,0 @@
/*
* NEWEXE.H (C) Copyright Microsoft Corp 1984-1987
*
* Data structure definitions for the OS/2 & Windows
* executable file format.
*
* Modified by IVS on 24-Jan-1991 for Resource DeCompiler
* (C) Copyright IVS 1991
*
* http://csn.ul.ie/~caolan/pub/winresdump/winresdump/newexe.h
*/
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace BurnOutSharp.ExecutableType.Microsoft
{
/// <summary>
/// Relocation item
/// </summary>
/// TODO: Fix this because Marshal will not work since it's not a direct read
[StructLayout(LayoutKind.Sequential)]
internal class NewRlc
{
public char SourceType; // Source type
public char Flags; // Flag byte
public ushort SourceOffset; // Source offset
// nr_intref - Internal Reference
public char TargetSegmentNumber; // Target segment number
public char Reserved1; // Reserved
public ushort TargetEntryTableOffset; // Target Entry Table offset
// nr_import - Import
public ushort ModuleReferenceTableIndex; // Index into Module Reference Table
public ushort ProcedureOffset; // Procedure ordinal or name offset
// nr_osfix - Operating system fixup
public ushort OperatingSystemFixupType; // OSFIXUP type
public ushort Reserved2; // Reserved
public static NewRlc Deserialize(Stream stream)
{
var nr = new NewRlc();
nr.SourceType = stream.ReadChar();
nr.Flags = stream.ReadChar();
nr.SourceOffset = stream.ReadUInt16();
// nr_intref
nr.TargetSegmentNumber = stream.ReadChar();
nr.Reserved1 = stream.ReadChar();
nr.TargetEntryTableOffset = stream.ReadUInt16();
// nr_import
nr.ModuleReferenceTableIndex = BitConverter.ToUInt16(new byte[] { (byte)nr.SourceType, (byte)nr.Flags }, 0);
nr.ProcedureOffset = nr.TargetEntryTableOffset;
// nr_osfix
nr.OperatingSystemFixupType = nr.ModuleReferenceTableIndex;
nr.Reserved2 = nr.ProcedureOffset;
return nr;
}
}
}

View File

@@ -1,38 +0,0 @@
/*
* NEWEXE.H (C) Copyright Microsoft Corp 1984-1987
*
* Data structure definitions for the OS/2 & Windows
* executable file format.
*
* Modified by IVS on 24-Jan-1991 for Resource DeCompiler
* (C) Copyright IVS 1991
*
* http://csn.ul.ie/~caolan/pub/winresdump/winresdump/newexe.h
*/
using System.IO;
using System.Runtime.InteropServices;
namespace BurnOutSharp.ExecutableType.Microsoft
{
/// <summary>
/// Relocation info
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal class NewRlcInfo
{
/// <summary>
/// Number of relocation items that follow
/// </summary>
public ushort RelocationItemCount;
public static NewRlcInfo Deserialize(Stream stream)
{
var nri = new NewRlcInfo();
nri.RelocationItemCount = stream.ReadUInt16();
return nri;
}
}
}

View File

@@ -1,40 +0,0 @@
/*
* NEWEXE.H (C) Copyright Microsoft Corp 1984-1987
*
* Data structure definitions for the OS/2 & Windows
* executable file format.
*
* Modified by IVS on 24-Jan-1991 for Resource DeCompiler
* (C) Copyright IVS 1991
*
* http://csn.ul.ie/~caolan/pub/winresdump/winresdump/newexe.h
*/
using System.IO;
using System.Runtime.InteropServices;
namespace BurnOutSharp.ExecutableType.Microsoft
{
/// <summary>
/// Resource table
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal class NewRsrc
{
/// <summary>
/// Alignment shift count for resources
/// </summary>
public ushort AlignmentShiftCount;
public RsrcTypeInfo TypeInfo;
public static NewRsrc Deserialize(Stream stream)
{
var nr = new NewRsrc();
nr.AlignmentShiftCount = stream.ReadUInt16();
nr.TypeInfo = RsrcTypeInfo.Deserialize(stream);
return nr;
}
}
}

View File

@@ -1,56 +0,0 @@
/*
* NEWEXE.H (C) Copyright Microsoft Corp 1984-1987
*
* Data structure definitions for the OS/2 & Windows
* executable file format.
*
* Modified by IVS on 24-Jan-1991 for Resource DeCompiler
* (C) Copyright IVS 1991
*
* http://csn.ul.ie/~caolan/pub/winresdump/winresdump/newexe.h
*/
using System.IO;
using System.Runtime.InteropServices;
namespace BurnOutSharp.ExecutableType.Microsoft
{
/// <summary>
/// New .EXE segment table entry
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal class NewSeg
{
/// <summary>
/// File sector of start of segment
/// </summary>
public ushort StartFileSector;
/// <summary>
/// Number of bytes in file
/// </summary>
public ushort BytesInFile;
/// <summary>
/// Attribute flags
/// </summary>
public ushort Flags;
/// <summary>
/// Minimum allocation in bytes
/// </summary>
public ushort MinimumAllocation;
public static NewSeg Deserialize(Stream stream)
{
var ns = new NewSeg();
ns.StartFileSector = stream.ReadUInt16();
ns.BytesInFile = stream.ReadUInt16();
ns.Flags = stream.ReadUInt16();
ns.MinimumAllocation = stream.ReadUInt16();
return ns;
}
}
}

View File

@@ -1,66 +0,0 @@
/*
* NEWEXE.H (C) Copyright Microsoft Corp 1984-1987
*
* Data structure definitions for the OS/2 & Windows
* executable file format.
*
* Modified by IVS on 24-Jan-1991 for Resource DeCompiler
* (C) Copyright IVS 1991
*
* http://csn.ul.ie/~caolan/pub/winresdump/winresdump/newexe.h
*/
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace BurnOutSharp.ExecutableType.Microsoft
{
/// <summary>
/// Segment data
/// </summary>
/// TODO: Fix this because Marshal will not work since it's not a direct read
[StructLayout(LayoutKind.Sequential)]
internal class NewSegdata
{
#region ns_iter
/// <summary>
/// Number of iterations
/// </summary>
public ushort Iterations;
/// <summary>
/// Number of bytes
/// </summary>
public ushort TotalBytes;
/// <summary>
/// Iterated data bytes
/// </summary>
public char IteratedDataBytes;
#endregion
#region ns_noiter
/// <summary>
/// Data bytes
/// </summary>
public char DataBytes;
#endregion
public static NewSegdata Deserialize(Stream stream)
{
var nsd = new NewSegdata();
nsd.Iterations = stream.ReadUInt16();
nsd.TotalBytes = stream.ReadUInt16();
nsd.IteratedDataBytes = stream.ReadChar();
nsd.DataBytes = (char)BitConverter.GetBytes(nsd.Iterations)[0];
return nsd;
}
}
}

View File

@@ -0,0 +1,48 @@
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Entries
{
/// <summary>
/// The base relocation table is divided into blocks.
/// Each block represents the base relocations for a 4K page.
/// Each block must start on a 32-bit boundary.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#base-relocation-block</remarks>
public class BaseRelocationBlock
{
/// <summary>
/// The image base plus the page RVA is added to each offset to create the VA where the base relocation must be applied.
/// </summary>
public uint PageRVA;
/// <summary>
/// The total number of bytes in the base relocation block, including the Page RVA and Block Size fields and the Type/Offset fields that follow.
/// </summary>
public uint BlockSize;
public static BaseRelocationBlock Deserialize(Stream stream)
{
var brb = new BaseRelocationBlock();
brb.PageRVA = stream.ReadUInt32();
brb.BlockSize = stream.ReadUInt32();
// TODO: Read in the type/offset field entries
return brb;
}
public static BaseRelocationBlock Deserialize(byte[] content, ref int offset)
{
var brb = new BaseRelocationBlock();
brb.PageRVA = content.ReadUInt32(ref offset);
brb.BlockSize = content.ReadUInt32(ref offset);
// TODO: Read in the type/offset field entries
return brb;
}
}
}

View File

@@ -0,0 +1,69 @@
using System.IO;
using System.Text;
using BurnOutSharp.Tools;
using BurnOutSharp.ExecutableType.Microsoft.PE.Headers;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Entries
{
/// <summary>
/// Each entry in the export address table is a field that uses one of two formats in the following table.
/// If the address specified is not within the export section (as defined by the address and length that are indicated in the optional header), the field is an export RVA, which is an actual address in code or data.
/// Otherwise, the field is a forwarder RVA, which names a symbol in another DLL.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#export-address-table</remarks>
public class ExportAddressTableEntry
{
/// <summary>
/// The address of the exported symbol when loaded into memory, relative to the image base.
/// For example, the address of an exported function.
/// </summary>
public uint ExportRVA;
/// <summary>
/// The pointer to a null-terminated ASCII string in the export section.
/// This string must be within the range that is given by the export table data directory entry.
/// This string gives the DLL name and the name of the export (for example, "MYDLL.expfunc") or the DLL name and the ordinal number of the export (for example, "MYDLL.#27").
/// </summary>
public uint ForwarderRVA; // TODO: Read this into a separate field
/// <summary>
/// A null-terminated ASCII string in the export section.
/// This string must be within the range that is given by the export table data directory entry.
/// This string gives the DLL name and the name of the export (for example, "MYDLL.expfunc") or the DLL name and the ordinal number of the export (for example, "MYDLL.#27").
/// </summary>
public string Forwarder;
public static ExportAddressTableEntry Deserialize(Stream stream, SectionHeader[] sections)
{
var eate = new ExportAddressTableEntry();
eate.ExportRVA = stream.ReadUInt32();
eate.ForwarderRVA = eate.ExportRVA;
int forwarderAddress = (int)PortableExecutable.ConvertVirtualAddress(eate.ForwarderRVA, sections);
if (forwarderAddress > -1 && forwarderAddress < stream.Length)
{
long originalPosition = stream.Position;
stream.Seek(forwarderAddress, SeekOrigin.Begin);
eate.Forwarder = stream.ReadString(Encoding.ASCII);
stream.Seek(originalPosition, SeekOrigin.Begin);
}
return eate;
}
public static ExportAddressTableEntry Deserialize(byte[] content, ref int offset, SectionHeader[] sections)
{
var eate = new ExportAddressTableEntry();
eate.ExportRVA = content.ReadUInt32(ref offset);
eate.ForwarderRVA = eate.ExportRVA;
int forwarderAddress = (int)PortableExecutable.ConvertVirtualAddress(eate.ForwarderRVA, sections);
if (forwarderAddress > -1 && forwarderAddress < content.Length)
eate.Forwarder = content.ReadString(ref forwarderAddress, Encoding.ASCII);
return eate;
}
}
}

View File

@@ -0,0 +1,78 @@
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Entries
{
/// <summary>
/// Each entry in the export address table is a field that uses one of two formats in the following table.
/// If the address specified is not within the export section (as defined by the address and length that are indicated in the optional header), the field is an export RVA, which is an actual address in code or data.
/// Otherwise, the field is a forwarder RVA, which names a symbol in another DLL.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#the-pdata-section</remarks>
public class FunctionTableEntry
{
#region 32-bit MIPS
/// <summary>
/// The VA of the corresponding function.
/// </summary>
public uint MIPSBeginAddress;
/// <summary>
/// The VA of the end of the function.
/// </summary>
public uint MIPSEndAddress;
/// <summary>
/// The pointer to the exception handler to be executed.
/// </summary>
public uint MIPSExceptionHandler;
/// <summary>
/// The pointer to additional information to be passed to the handler.
/// </summary>
public uint MIPSHandlerData;
/// <summary>
/// The VA of the end of the function's prolog.
/// </summary>
public uint MIPSPrologEndAddress;
#endregion
#region ARM, PowerPC, SH3 and SH4 Windows CE
/// <summary>
/// The VA of the corresponding function.
/// </summary>
public uint ARMBeginAddress;
/// <summary>
/// The VA of the end of the function.
///
/// 8 bits Prolog Length The number of instructions in the function's prolog.
/// 22 bits Function Length The number of instructions in the function.
/// 1 bit 32-bit Flag If set, the function consists of 32-bit instructions. If clear, the function consists of 16-bit instructions.
/// 1 bit Exception Flag If set, an exception handler exists for the function. Otherwise, no exception handler exists.
/// </summary>
public uint ARMLengthsAndFlags;
#endregion
#region x64 and Itanium
/// <summary>
/// The RVA of the corresponding function.
/// </summary>
public uint X64BeginAddress;
/// <summary>
/// The RVA of the end of the function.
/// </summary>
public uint X64EndAddress;
/// <summary>
/// The RVA of the unwind information.
/// </summary>
public uint X64UnwindInformation;
#endregion
}
}

View File

@@ -0,0 +1,89 @@
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Entries
{
/// <summary>
/// Each entry in the hint/name table has the following format
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#hintname-table</remarks>
public class HintNameTableEntry
{
/// <summary>
/// An index into the export name pointer table.
/// A match is attempted first with this value.
/// If it fails, a binary search is performed on the DLL's export name pointer table.
/// </summary>
public ushort Hint;
/// <summary>
/// An ASCII string that contains the name to import.
/// This is the string that must be matched to the public name in the DLL.
/// This string is case sensitive and terminated by a null byte.
/// </summary>
public string Name;
/// <summary>
/// A trailing zero-pad byte that appears after the trailing null byte, if necessary, to align the next entry on an even boundary.
/// </summary>
public byte Pad;
public static HintNameTableEntry Deserialize(Stream stream)
{
var hnte = new HintNameTableEntry();
hnte.Hint = stream.ReadUInt16();
hnte.Name = string.Empty;
while (true)
{
char c = stream.ReadChar();
if (c == (char)0x00)
break;
hnte.Name += c;
}
// If the name length is not even, read and pad
if (hnte.Name.Length % 2 != 0)
{
stream.ReadByte();
hnte.Pad = 1;
}
else
{
hnte.Pad = 0;
}
return hnte;
}
public static HintNameTableEntry Deserialize(byte[] content, ref int offset)
{
var hnte = new HintNameTableEntry();
hnte.Hint = content.ReadUInt16(ref offset);
hnte.Name = string.Empty;
while (true)
{
char c = (char)content[offset]; offset += 1;
if (c == (char)0x00)
break;
hnte.Name += c;
}
// If the name length is not even, read and pad
if (hnte.Name.Length % 2 != 0)
{
offset += 1;
hnte.Pad = 1;
}
else
{
hnte.Pad = 0;
}
return hnte;
}
}
}

View File

@@ -0,0 +1,81 @@
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Entries
{
/// <summary>
/// Each import address entry has the following format
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#import-address-table</remarks>
public class ImportAddressTableEntry
{
/// <summary>
/// The RVA of the import lookup table.
/// This table contains a name or ordinal for each import.
/// (The name "Characteristics" is used in Winnt.h, but no longer describes this field.)
/// </summary>
public uint ImportLookupTableRVA;
/// <summary>
/// The stamp that is set to zero until the image is bound.
/// After the image is bound, this field is set to the time/data stamp of the DLL.
/// </summary>
public uint TimeDateStamp;
/// <summary>
/// The index of the first forwarder reference.
/// </summary>
public uint ForwarderChain;
/// <summary>
/// The address of an ASCII string that contains the name of the DLL.
/// This address is relative to the image base.
/// </summary>
public uint NameRVA;
/// <summary>
/// The RVA of the import address table.
/// The contents of this table are identical to the contents of the import lookup table until the image is bound.
/// </summary>
public uint ImportAddressTableRVA;
/// <summary>
/// Determine if the entry is null or not
/// This indicates the last entry in a table
/// </summary>
public bool IsNull()
{
return ImportLookupTableRVA == 0
&& TimeDateStamp == 0
&& ForwarderChain == 0
&& NameRVA == 0
&& ImportAddressTableRVA == 0;
}
public static ImportAddressTableEntry Deserialize(Stream stream)
{
var iate = new ImportAddressTableEntry();
iate.ImportLookupTableRVA = stream.ReadUInt32();
iate.TimeDateStamp = stream.ReadUInt32();
iate.ForwarderChain = stream.ReadUInt32();
iate.NameRVA = stream.ReadUInt32();
iate.ImportAddressTableRVA = stream.ReadUInt32();
return iate;
}
public static ImportAddressTableEntry Deserialize(byte[] content, ref int offset)
{
var iate = new ImportAddressTableEntry();
iate.ImportLookupTableRVA = content.ReadUInt32(ref offset);
iate.TimeDateStamp = content.ReadUInt32(ref offset);
iate.ForwarderChain = content.ReadUInt32(ref offset);
iate.NameRVA = content.ReadUInt32(ref offset);
iate.ImportAddressTableRVA = content.ReadUInt32(ref offset);
return iate;
}
}
}

View File

@@ -0,0 +1,81 @@
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Entries
{
/// <summary>
/// Each import directory entry has the following format
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#import-directory-table</remarks>
public class ImportDirectoryTableEntry
{
/// <summary>
/// The RVA of the import lookup table.
/// This table contains a name or ordinal for each import.
/// (The name "Characteristics" is used in Winnt.h, but no longer describes this field.)
/// </summary>
public uint ImportLookupTableRVA;
/// <summary>
/// The stamp that is set to zero until the image is bound.
/// After the image is bound, this field is set to the time/data stamp of the DLL.
/// </summary>
public uint TimeDateStamp;
/// <summary>
/// The index of the first forwarder reference.
/// </summary>
public uint ForwarderChain;
/// <summary>
/// The address of an ASCII string that contains the name of the DLL.
/// This address is relative to the image base.
/// </summary>
public uint NameRVA;
/// <summary>
/// The RVA of the import address table.
/// The contents of this table are identical to the contents of the import lookup table until the image is bound.
/// </summary>
public uint ImportAddressTableRVA;
/// <summary>
/// Determine if the entry is null or not
/// This indicates the last entry in a table
/// </summary>
public bool IsNull()
{
return ImportLookupTableRVA == 0
&& TimeDateStamp == 0
&& ForwarderChain == 0
&& NameRVA == 0
&& ImportAddressTableRVA == 0;
}
public static ImportDirectoryTableEntry Deserialize(Stream stream)
{
var idte = new ImportDirectoryTableEntry();
idte.ImportLookupTableRVA = stream.ReadUInt32();
idte.TimeDateStamp = stream.ReadUInt32();
idte.ForwarderChain = stream.ReadUInt32();
idte.NameRVA = stream.ReadUInt32();
idte.ImportAddressTableRVA = stream.ReadUInt32();
return idte;
}
public static ImportDirectoryTableEntry Deserialize(byte[] content, ref int offset)
{
var idte = new ImportDirectoryTableEntry();
idte.ImportLookupTableRVA = content.ReadUInt32(ref offset);
idte.TimeDateStamp = content.ReadUInt32(ref offset);
idte.ForwarderChain = content.ReadUInt32(ref offset);
idte.NameRVA = content.ReadUInt32(ref offset);
idte.ImportAddressTableRVA = content.ReadUInt32(ref offset);
return idte;
}
}
}

View File

@@ -0,0 +1,111 @@
using System;
using System.IO;
using System.Linq;
using System.Text;
using BurnOutSharp.ExecutableType.Microsoft.PE.Headers;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Entries
{
/// <summary>
/// Each Resource Data entry describes an actual unit of raw data in the Resource Data area.
/// </summary>
public class ResourceDataEntry
{
/// <summary>
/// The address of a unit of resource data in the Resource Data area.
/// </summary>
public uint OffsetToData;
/// <summary>
/// A unit of resource data in the Resource Data area.
/// </summary>
public byte[] Data;
/// <summary>
/// A unit of resource data in the Resource Data area.
/// </summary>
public string DataAsUTF8String
{
get
{
int codePage = (int)CodePage;
if (Data == null || codePage < 0)
return string.Empty;
// Try to convert to UTF-8 first
try
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var originalEncoding = Encoding.GetEncoding(codePage);
byte[] convertedData = Encoding.Convert(originalEncoding, Encoding.UTF8, Data);
return Encoding.UTF8.GetString(convertedData);
}
catch { }
// Then try to read direct as ASCII
try
{
return Encoding.ASCII.GetString(Data);
}
catch { }
// If both encodings fail, then just return an empty string
return string.Empty;
}
}
/// <summary>
/// The size, in bytes, of the resource data that is pointed to by the Data RVA field.
/// </summary>
public uint Size;
/// <summary>
/// The code page that is used to decode code point values within the resource data.
/// Typically, the code page would be the Unicode code page.
/// </summary>
public uint CodePage;
/// <summary>
/// Reserved, must be 0.
/// </summary>
public uint Reserved;
public static ResourceDataEntry Deserialize(Stream stream, SectionHeader[] sections)
{
var rde = new ResourceDataEntry();
rde.OffsetToData = stream.ReadUInt32();
rde.Size = stream.ReadUInt32();
rde.CodePage = stream.ReadUInt32();
rde.Reserved = stream.ReadUInt32();
int realOffsetToData = (int)PortableExecutable.ConvertVirtualAddress(rde.OffsetToData, sections);
if (realOffsetToData > -1 && realOffsetToData < stream.Length && (int)rde.Size > 0 && realOffsetToData + (int)rde.Size < stream.Length)
{
long lastPosition = stream.Position;
stream.Seek(realOffsetToData, SeekOrigin.Begin);
rde.Data = stream.ReadBytes((int)rde.Size);
stream.Seek(lastPosition, SeekOrigin.Begin);
}
return rde;
}
public static ResourceDataEntry Deserialize(byte[] content, ref int offset, SectionHeader[] sections)
{
var rde = new ResourceDataEntry();
rde.OffsetToData = content.ReadUInt32(ref offset);
rde.Size = content.ReadUInt32(ref offset);
rde.CodePage = content.ReadUInt32(ref offset);
rde.Reserved = content.ReadUInt32(ref offset);
int realOffsetToData = (int)PortableExecutable.ConvertVirtualAddress(rde.OffsetToData, sections);
if (realOffsetToData > -1 && realOffsetToData < content.Length && (int)rde.Size > 0 && realOffsetToData + (int)rde.Size < content.Length)
rde.Data = new ArraySegment<byte>(content, realOffsetToData, (int)rde.Size).ToArray();
return rde;
}
}
}

View File

@@ -0,0 +1,50 @@
using System.IO;
using System.Text;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Entries
{
/// <summary>
/// The resource directory string area consists of Unicode strings, which are word-aligned.
/// These strings are stored together after the last Resource Directory entry and before the first Resource Data entry.
/// This minimizes the impact of these variable-length strings on the alignment of the fixed-size directory entries.
/// </summary>
public class ResourceDirectoryString
{
/// <summary>
/// The size of the string, not including length field itself.
/// </summary>
public ushort Length;
/// <summary>
/// The variable-length Unicode string data, word-aligned.
/// </summary>
public string UnicodeString;
public static ResourceDirectoryString Deserialize(Stream stream)
{
var rds = new ResourceDirectoryString();
rds.Length = stream.ReadUInt16();
if (rds.Length + stream.Position > stream.Length)
return null;
rds.UnicodeString = new string(stream.ReadChars(rds.Length, Encoding.Unicode));
return rds;
}
public static ResourceDirectoryString Deserialize(byte[] content, ref int offset)
{
var rds = new ResourceDirectoryString();
rds.Length = content.ReadUInt16(ref offset);
if (rds.Length + offset > content.Length)
return null;
rds.UnicodeString = Encoding.Unicode.GetString(content, offset, rds.Length); offset += rds.Length;
return rds;
}
}
}

View File

@@ -0,0 +1,140 @@
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE.Headers;
using BurnOutSharp.ExecutableType.Microsoft.PE.Tables;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Entries
{
/// <summary>
/// The directory entries make up the rows of a table.
/// Each resource directory entry has the following format.
/// Whether the entry is a Name or ID entry is indicated by the
/// resource directory table, which indicates how many Name and
/// ID entries follow it (remember that all the Name entries
/// precede all the ID entries for the table). All entries for
/// the table are sorted in ascending order: the Name entries
/// by case-sensitive string and the ID entries by numeric value.
/// Offsets are relative to the address in the IMAGE_DIRECTORY_ENTRY_RESOURCE DataDirectory.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#resource-directory-entries</remarks>
public class ResourceDirectoryTableEntry
{
/// <summary>
/// The offset of a string that gives the Type, Name, or Language ID entry, depending on level of table.
/// </summary>
public uint NameOffset => (uint)(IntegerId ^ (1 << 31));
/// <summary>
/// The string that gives the Type, Name, or Language ID entry, depending on level of table pointed to by NameOffset
/// </summary>
public ResourceDirectoryString Name;
/// <summary>
/// A 32-bit integer that identifies the Type, Name, or Language ID entry.
/// </summary>
public uint IntegerId;
/// <summary>
/// High bit 0. Address of a Resource Data entry (a leaf).
/// </summary>
public uint DataEntryOffset;
/// <summary>
/// High bit 1. The lower 31 bits are the address of another resource directory table (the next level down).
/// </summary>
public uint SubdirectoryOffset => (uint)(DataEntryOffset ^ (1 << 31));
/// <summary>
/// Resource Data entry (a leaf).
/// </summary>
public ResourceDataEntry DataEntry;
/// <summary>
/// Another resource directory table (the next level down).
/// </summary>
public ResourceDirectoryTable Subdirectory;
/// <summary>
/// Determine if an entry has a name or integer identifier
/// </summary>
public bool IsIntegerIDEntry() => (IntegerId & (1 << 31)) == 0;
/// <summary>
/// Determine if an entry represents a leaf or another directory table
/// </summary>
public bool IsResourceDataEntry() => (DataEntryOffset & (1 << 31)) == 0;
public static ResourceDirectoryTableEntry Deserialize(Stream stream, long sectionStart, SectionHeader[] sections)
{
var rdte = new ResourceDirectoryTableEntry();
rdte.IntegerId = stream.ReadUInt32();
if (!rdte.IsIntegerIDEntry())
{
int nameAddress = (int)(rdte.NameOffset + sectionStart);
if (nameAddress >= 0 && nameAddress < stream.Length)
{
long lastPosition = stream.Position;
stream.Seek(nameAddress, SeekOrigin.Begin);
rdte.Name = ResourceDirectoryString.Deserialize(stream);
stream.Seek(lastPosition, SeekOrigin.Begin);
}
}
rdte.DataEntryOffset = stream.ReadUInt32();
if (rdte.IsResourceDataEntry())
{
int dataEntryAddress = (int)(rdte.DataEntryOffset + sectionStart);
if (dataEntryAddress > 0 && dataEntryAddress < stream.Length)
{
long lastPosition = stream.Position;
stream.Seek(dataEntryAddress, SeekOrigin.Begin);
rdte.DataEntry = ResourceDataEntry.Deserialize(stream, sections);
stream.Seek(lastPosition, SeekOrigin.Begin);
}
}
else
{
int subdirectoryAddress = (int)(rdte.SubdirectoryOffset + sectionStart);
if (subdirectoryAddress > 0 && subdirectoryAddress < stream.Length)
{
long lastPosition = stream.Position;
stream.Seek(subdirectoryAddress, SeekOrigin.Begin);
rdte.Subdirectory = ResourceDirectoryTable.Deserialize(stream, sectionStart, sections);
stream.Seek(lastPosition, SeekOrigin.Begin);
}
}
return rdte;
}
public static ResourceDirectoryTableEntry Deserialize(byte[] content, ref int offset, long sectionStart, SectionHeader[] sections)
{
var rdte = new ResourceDirectoryTableEntry();
rdte.IntegerId = content.ReadUInt32(ref offset);
if (!rdte.IsIntegerIDEntry())
{
int nameAddress = (int)(rdte.NameOffset + sectionStart);
if (nameAddress >= 0 && nameAddress < content.Length)
rdte.Name = ResourceDirectoryString.Deserialize(content, ref nameAddress);
}
rdte.DataEntryOffset = content.ReadUInt32(ref offset);
if (rdte.IsResourceDataEntry())
{
int dataEntryAddress = (int)(rdte.DataEntryOffset + sectionStart);
if (dataEntryAddress > 0 && dataEntryAddress < content.Length)
rdte.DataEntry = ResourceDataEntry.Deserialize(content, ref dataEntryAddress, sections);
}
else
{
int subdirectoryAddress = (int)(rdte.SubdirectoryOffset + sectionStart);
if (subdirectoryAddress > 0 && subdirectoryAddress < content.Length)
rdte.Subdirectory = ResourceDirectoryTable.Deserialize(content, ref subdirectoryAddress, sectionStart, sections);
}
return rdte;
}
}
}

View File

@@ -0,0 +1,88 @@
using System;
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Headers
{
public class CommonObjectFileFormatHeader
{
/// <summary>
/// After the MS-DOS stub, at the file offset specified at offset 0x3c, is a 4-byte signature that identifies the file as a PE format image file.
// This signature is "PE\0\0" (the letters "P" and "E" followed by two null bytes).
/// </summary>
public uint Signature;
/// <summary>
/// The number that identifies the type of target machine.
/// </summary>
public MachineType Machine;
/// <summary>
/// The number of sections.
/// This indicates the size of the section table, which immediately follows the headers.
/// </summary>
public ushort NumberOfSections;
/// <summary>
/// The low 32 bits of the number of seconds since 00:00 January 1, 1970 (a C run-time time_t value), which indicates when the file was created.
/// </summary>
public uint TimeDateStamp;
/// <summary>
/// The file offset of the COFF symbol table, or zero if no COFF symbol table is present.
/// This value should be zero for an image because COFF debugging information is deprecated.
/// </summary>
[Obsolete]
public uint PointerToSymbolTable;
/// <summary>
/// The number of entries in the symbol table. This data can be used to locate the string table, which immediately follows the symbol table.
/// This value should be zero for an image because COFF debugging information is deprecated.
/// </summary>
[Obsolete]
public uint NumberOfSymbols;
/// <summary>
/// The size of the optional header, which is required for executable files but not for object files.
// This value should be zero for an object file.
/// </summary>
public ushort SizeOfOptionalHeader;
/// <summary>
/// The flags that indicate the attributes of the file.
/// </summary>
public ImageObjectCharacteristics Characteristics;
public static CommonObjectFileFormatHeader Deserialize(Stream stream)
{
var ifh = new CommonObjectFileFormatHeader();
ifh.Signature = stream.ReadUInt32();
ifh.Machine = (MachineType)stream.ReadUInt16();
ifh.NumberOfSections = stream.ReadUInt16();
ifh.TimeDateStamp = stream.ReadUInt32();
ifh.PointerToSymbolTable = stream.ReadUInt32();
ifh.NumberOfSymbols = stream.ReadUInt32();
ifh.SizeOfOptionalHeader = stream.ReadUInt16();
ifh.Characteristics = (ImageObjectCharacteristics)stream.ReadUInt16();
return ifh;
}
public static CommonObjectFileFormatHeader Deserialize(byte[] content, ref int offset)
{
var ifh = new CommonObjectFileFormatHeader();
ifh.Signature = content.ReadUInt32(ref offset);
ifh.Machine = (MachineType)content.ReadUInt16(ref offset);
ifh.NumberOfSections = content.ReadUInt16(ref offset);
ifh.TimeDateStamp = content.ReadUInt32(ref offset);
ifh.PointerToSymbolTable = content.ReadUInt32(ref offset);
ifh.NumberOfSymbols = content.ReadUInt32(ref offset);
ifh.SizeOfOptionalHeader = content.ReadUInt16(ref offset);
ifh.Characteristics = (ImageObjectCharacteristics)content.ReadUInt16(ref offset);
return ifh;
}
}
}

View File

@@ -0,0 +1,39 @@
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Headers
{
public class DataDirectoryHeader
{
/// <summary>
/// The first field, VirtualAddress, is actually the RVA of the table.
/// The RVA is the address of the table relative to the base address of the image when the table is loaded.
/// </summary>
public uint VirtualAddress;
/// <summary>
/// The second field gives the size in bytes.
/// </summary>
public uint Size;
public static DataDirectoryHeader Deserialize(Stream stream)
{
var ddh = new DataDirectoryHeader();
ddh.VirtualAddress = stream.ReadUInt32();
ddh.Size = stream.ReadUInt32();
return ddh;
}
public static DataDirectoryHeader Deserialize(byte[] content, ref int offset)
{
var ddh = new DataDirectoryHeader();
ddh.VirtualAddress = content.ReadUInt32(ref offset);
ddh.Size = content.ReadUInt32(ref offset);
return ddh;
}
}
}

View File

@@ -0,0 +1,369 @@
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Headers
{
/// <summary>
/// Every image file has an optional header that provides information to the loader.
/// This header is optional in the sense that some files (specifically, object files) do not have it.
/// For image files, this header is required. An object file can have an optional header, but generally
/// this header has no function in an object file except to increase its size.
///
/// Note that the size of the optional header is not fixed.
/// The SizeOfOptionalHeader field in the COFF header must be used to validate that a probe into the file
/// for a particular data directory does not go beyond SizeOfOptionalHeader.
///
/// The NumberOfRvaAndSizes field of the optional header should also be used to ensure that no probe for
/// a particular data directory entry goes beyond the optional header.
/// In addition, it is important to validate the optional header magic number for format compatibility.
/// </summary>
public class OptionalHeader
{
#region Standard Fields
/// <summary>
/// The unsigned integer that identifies the state of the image file.
/// The most common number is 0x10B, which identifies it as a normal executable file.
/// 0x107 identifies it as a ROM image, and 0x20B identifies it as a PE32+ executable.
/// </summary>
public OptionalHeaderType Magic;
/// <summary>
/// The linker major version number.
/// </summary>
public byte MajorLinkerVersion;
/// <summary>
/// The linker minor version number.
/// </summary>
public byte MinorLinkerVersion;
/// <summary>
/// The size of the code (text) section, or the sum of all code sections if there are multiple sections.
/// </summary>
public uint SizeOfCode;
/// <summary>
/// The size of the initialized data section, or the sum of all such sections if there are multiple data sections.
/// </summary>
public uint SizeOfInitializedData;
/// <summary>
/// The size of the uninitialized data section (BSS), or the sum of all such sections if there are multiple BSS sections.
/// </summary>
public uint SizeOfUninitializedData;
/// <summary>
/// The address of the entry point relative to the image base when the executable file is loaded into memory.
/// For program images, this is the starting address.
/// For device drivers, this is the address of the initialization function.
// An entry point is optional for DLLs.
/// When no entry point is present, this field must be zero.
/// </summary>
public uint AddressOfEntryPoint;
/// <summary>
/// The address that is relative to the image base of the beginning-of-code section when it is loaded into memory.
/// </summary>
public uint BaseOfCode;
/// <summary>
/// The address that is relative to the image base of the beginning-of-data section when it is loaded into memory.
/// </summary>
public uint BaseOfData;
#endregion
#region Windows-Specific Fields
/// <summary>
/// The preferred address of the first byte of image when loaded into memory; must be a multiple of 64 K.
/// The default for DLLs is 0x10000000.
/// The default for Windows CE EXEs is 0x00010000.
/// The default for Windows NT, Windows 2000, Windows XP, Windows 95, Windows 98, and Windows Me is 0x00400000.
/// </summary>
public uint ImageBasePE32;
/// <summary>
/// The preferred address of the first byte of image when loaded into memory; must be a multiple of 64 K.
/// The default for DLLs is 0x10000000.
/// The default for Windows CE EXEs is 0x00010000.
/// The default for Windows NT, Windows 2000, Windows XP, Windows 95, Windows 98, and Windows Me is 0x00400000.
/// </summary>
public ulong ImageBasePE32Plus;
/// <summary>
/// The alignment (in bytes) of sections when they are loaded into memory.
/// It must be greater than or equal to FileAlignment.
/// The default is the page size for the architecture.
/// </summary>
public uint SectionAlignment;
/// <summary>
/// The alignment factor (in bytes) that is used to align the raw data of sections in the image file.
/// The value should be a power of 2 between 512 and 64 K, inclusive.
/// The default is 512.
/// If the SectionAlignment is less than the architecture's page size, then FileAlignment must match SectionAlignment.
/// </summary>
public uint FileAlignment;
/// <summary>
/// The major version number of the required operating system.
/// </summary>
public ushort MajorOperatingSystemVersion;
/// <summary>
/// The minor version number of the required operating system.
/// </summary>
public ushort MinorOperatingSystemVersion;
/// <summary>
/// The major version number of the image.
/// </summary>
public ushort MajorImageVersion;
/// <summary>
/// The minor version number of the image.
/// </summary>
public ushort MinorImageVersion;
/// <summary>
/// The major version number of the subsystem.
/// </summary>
public ushort MajorSubsystemVersion;
/// <summary>
/// The minor version number of the subsystem.
/// </summary>
public ushort MinorSubsystemVersion;
/// <summary>
/// Reserved, must be zero.
/// </summary>
public uint Reserved1;
/// <summary>
/// The size (in bytes) of the image, including all headers, as the image is loaded in memory.
/// It must be a multiple of SectionAlignment.
/// </summary>
public uint SizeOfImage;
/// <summary>
/// The combined size of an MS-DOS stub, PE header, and section headers rounded up to a multiple of FileAlignment.
/// </summary>
public uint SizeOfHeaders;
/// <summary>
/// The image file checksum.
/// The algorithm for computing the checksum is incorporated into IMAGHELP.DLL.
/// The following are checked for validation at load time: all drivers, any DLL loaded at boot time, and any DLL that is loaded into a critical Windows process.
/// </summary>
public uint CheckSum;
/// <summary>
/// The subsystem that is required to run this image.
/// </summary>
public WindowsSubsystem Subsystem;
/// <summary>
/// DLL Characteristics
/// </summary>
public DllCharacteristics DllCharacteristics;
/// <summary>
/// The size of the stack to reserve.
/// Only SizeOfStackCommit is committed; the rest is made available one page at a time until the reserve size is reached.
/// </summary>
public uint SizeOfStackReservePE32;
/// <summary>
/// The size of the stack to reserve.
/// Only SizeOfStackCommit is committed; the rest is made available one page at a time until the reserve size is reached.
/// </summary>
public ulong SizeOfStackReservePE32Plus;
/// <summary>
/// The size of the stack to commit.
/// </summary>
public uint SizeOfStackCommitPE32;
/// <summary>
/// The size of the stack to commit.
/// </summary>
public ulong SizeOfStackCommitPE32Plus;
/// <summary>
/// The size of the local heap space to reserve.
/// Only SizeOfHeapCommit is committed; the rest is made available one page at a time until the reserve size is reached.
/// </summary>
public uint SizeOfHeapReservePE32;
/// <summary>
/// The size of the local heap space to reserve.
/// Only SizeOfHeapCommit is committed; the rest is made available one page at a time until the reserve size is reached.
/// </summary>
public ulong SizeOfHeapReservePE32Plus;
/// <summary>
/// The size of the local heap space to commit.
/// </summary>
public uint SizeOfHeapCommitPE32;
/// <summary>
/// The size of the local heap space to commit.
/// </summary>
public ulong SizeOfHeapCommitPE32Plus;
/// <summary>
/// Reserved, must be zero.
/// </summary>
public uint LoaderFlags;
/// <summary>
/// The number of data-directory entries in the remainder of the optional header.
/// Each describes a location and size.
/// </summary>
public uint NumberOfRvaAndSizes;
/// <summary>
/// Data-directory entries following the optional header
/// </summary>
public DataDirectoryHeader[] DataDirectories;
#endregion
public static OptionalHeader Deserialize(Stream stream)
{
var ioh = new OptionalHeader();
ioh.Magic = (OptionalHeaderType)stream.ReadUInt16();
ioh.MajorLinkerVersion = stream.ReadByteValue();
ioh.MinorLinkerVersion = stream.ReadByteValue();
ioh.SizeOfCode = stream.ReadUInt32();
ioh.SizeOfInitializedData = stream.ReadUInt32();
ioh.SizeOfUninitializedData = stream.ReadUInt32();
ioh.AddressOfEntryPoint = stream.ReadUInt32();
ioh.BaseOfCode = stream.ReadUInt32();
// Only standard PE32 has this value
if (ioh.Magic == OptionalHeaderType.PE32)
ioh.BaseOfData = stream.ReadUInt32();
// PE32+ has an 8-byte value here
if (ioh.Magic == OptionalHeaderType.PE32Plus)
ioh.ImageBasePE32Plus = stream.ReadUInt64();
else
ioh.ImageBasePE32 = stream.ReadUInt32();
ioh.SectionAlignment = stream.ReadUInt32();
ioh.FileAlignment = stream.ReadUInt32();
ioh.MajorOperatingSystemVersion = stream.ReadUInt16();
ioh.MinorOperatingSystemVersion = stream.ReadUInt16();
ioh.MajorImageVersion = stream.ReadUInt16();
ioh.MinorImageVersion = stream.ReadUInt16();
ioh.MajorSubsystemVersion = stream.ReadUInt16();
ioh.MinorSubsystemVersion = stream.ReadUInt16();
ioh.Reserved1 = stream.ReadUInt32();
ioh.SizeOfImage = stream.ReadUInt32();
ioh.SizeOfHeaders = stream.ReadUInt32();
ioh.CheckSum = stream.ReadUInt32();
ioh.Subsystem = (WindowsSubsystem)stream.ReadUInt16();
ioh.DllCharacteristics = (DllCharacteristics)stream.ReadUInt16();
// PE32+ uses 8-byte values
if (ioh.Magic == OptionalHeaderType.PE32Plus)
{
ioh.SizeOfStackReservePE32Plus = stream.ReadUInt64();
ioh.SizeOfStackCommitPE32Plus = stream.ReadUInt64();
ioh.SizeOfHeapReservePE32Plus = stream.ReadUInt64();
ioh.SizeOfHeapCommitPE32Plus = stream.ReadUInt64();
}
else
{
ioh.SizeOfStackReservePE32 = stream.ReadUInt32();
ioh.SizeOfStackCommitPE32 = stream.ReadUInt32();
ioh.SizeOfHeapReservePE32 = stream.ReadUInt32();
ioh.SizeOfHeapCommitPE32 = stream.ReadUInt32();
}
ioh.LoaderFlags = stream.ReadUInt32();
ioh.NumberOfRvaAndSizes = stream.ReadUInt32();
ioh.DataDirectories = new DataDirectoryHeader[Constants.IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
for (int i = 0; i < Constants.IMAGE_NUMBEROF_DIRECTORY_ENTRIES; i++)
{
ioh.DataDirectories[i] = DataDirectoryHeader.Deserialize(stream);
}
return ioh;
}
public static OptionalHeader Deserialize(byte[] content, ref int offset)
{
var ioh = new OptionalHeader();
ioh.Magic = (OptionalHeaderType)content.ReadUInt16(ref offset);
ioh.MajorLinkerVersion = content[offset]; offset++;
ioh.MinorLinkerVersion = content[offset]; offset++;
ioh.SizeOfCode = content.ReadUInt32(ref offset);
ioh.SizeOfInitializedData = content.ReadUInt32(ref offset);
ioh.SizeOfUninitializedData = content.ReadUInt32(ref offset);
ioh.AddressOfEntryPoint = content.ReadUInt32(ref offset);
ioh.BaseOfCode = content.ReadUInt32(ref offset);
// Only standard PE32 has this value
if (ioh.Magic == OptionalHeaderType.PE32)
ioh.BaseOfData = content.ReadUInt32(ref offset);
// PE32+ has an 8-bit value here
if (ioh.Magic == OptionalHeaderType.PE32Plus)
{
ioh.ImageBasePE32Plus = content.ReadUInt64(ref offset);
}
else
{
ioh.ImageBasePE32 = content.ReadUInt32(ref offset);
}
ioh.SectionAlignment = content.ReadUInt32(ref offset);
ioh.FileAlignment = content.ReadUInt32(ref offset);
ioh.MajorOperatingSystemVersion = content.ReadUInt16(ref offset);
ioh.MinorOperatingSystemVersion = content.ReadUInt16(ref offset);
ioh.MajorImageVersion = content.ReadUInt16(ref offset);
ioh.MinorImageVersion = content.ReadUInt16(ref offset);
ioh.MajorSubsystemVersion = content.ReadUInt16(ref offset);
ioh.MinorSubsystemVersion = content.ReadUInt16(ref offset);
ioh.Reserved1 = content.ReadUInt32(ref offset);
ioh.SizeOfImage = content.ReadUInt32(ref offset);
ioh.SizeOfHeaders = content.ReadUInt32(ref offset);
ioh.CheckSum = content.ReadUInt32(ref offset);
ioh.Subsystem = (WindowsSubsystem)content.ReadUInt16(ref offset);
ioh.DllCharacteristics = (DllCharacteristics)content.ReadUInt16(ref offset);
// PE32+ uses 8-byte values
if (ioh.Magic == OptionalHeaderType.PE32Plus)
{
ioh.SizeOfStackReservePE32Plus = content.ReadUInt64(ref offset);
ioh.SizeOfStackCommitPE32Plus = content.ReadUInt64(ref offset);
ioh.SizeOfHeapReservePE32Plus = content.ReadUInt64(ref offset);
ioh.SizeOfHeapCommitPE32Plus = content.ReadUInt64(ref offset);
}
else
{
ioh.SizeOfStackReservePE32 = content.ReadUInt32(ref offset);
ioh.SizeOfStackCommitPE32 = content.ReadUInt32(ref offset);
ioh.SizeOfHeapReservePE32 = content.ReadUInt32(ref offset);
ioh.SizeOfHeapCommitPE32 = content.ReadUInt32(ref offset);
}
ioh.LoaderFlags = content.ReadUInt32(ref offset);
ioh.NumberOfRvaAndSizes = content.ReadUInt32(ref offset);
ioh.DataDirectories = new DataDirectoryHeader[Constants.IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
for (int i = 0; i < Constants.IMAGE_NUMBEROF_DIRECTORY_ENTRIES; i++)
{
ioh.DataDirectories[i] = DataDirectoryHeader.Deserialize(content, ref offset);
}
return ioh;
}
}
}

View File

@@ -0,0 +1,159 @@
using System;
using System.IO;
using System.Text;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Headers
{
/// <summary>
/// Each row of the section table is, in effect, a section header.
/// This table immediately follows the optional header, if any.
/// This positioning is required because the file header does not contain a direct pointer to the section table.
/// Instead, the location of the section table is determined by calculating the location of the first byte after the headers.
/// Make sure to use the size of the optional header as specified in the file header.
/// </summary>
public class SectionHeader
{
/// <summary>
/// An 8-byte, null-padded UTF-8 encoded string.
/// If the string is exactly 8 characters long, there is no terminating null.
/// For longer names, this field contains a slash (/) that is followed by an ASCII representation of a decimal number
/// that is an offset into the string table.
/// Executable images do not use a string table and do not support section names longer than 8 characters.
/// Long names in object files are truncated if they are emitted to an executable file.
/// </summary>
public byte[] Name;
/// <summary>
/// Section name as a string, trimming any trailing null bytes
/// </summary>
public string NameString
{
get
{
if (this.Name == null || this.Name.Length == 0)
return null;
// First try decoding as UTF-8
try
{
return Encoding.UTF8.GetString(this.Name).TrimEnd('\0');
}
catch { }
// Then try decoding as ASCII
try
{
return Encoding.ASCII.GetString(this.Name).TrimEnd('\0');
}
catch { }
// If it fails, return null
return null;
}
}
/// <summary>
/// The total size of the section when loaded into memory.
/// If this value is greater than SizeOfRawData, the section is zero-padded.
/// This field is valid only for executable images and should be set to zero for object files.
/// </summary>
public uint VirtualSize;
/// <summary>
/// For executable images, the address of the first byte of the section relative to the image base when the section
/// is loaded into memory.
/// For object files, this field is the address of the first byte before relocation is applied; for simplicity,
/// compilers should set this to zero.
/// Otherwise, it is an arbitrary value that is subtracted from offsets during relocation.
/// </summary>
public uint VirtualAddress;
/// <summary>
/// The size of the section (for object files) or the size of the initialized data on disk (for image files).
/// For executable images, this must be a multiple of FileAlignment from the optional header.
/// If this is less than VirtualSize, the remainder of the section is zero-filled.
/// Because the SizeOfRawData field is rounded but the VirtualSize field is not, it is possible for SizeOfRawData
/// to be greater than VirtualSize as well.
/// When a section contains only uninitialized data, this field should be zero.
/// </summary>
public uint SizeOfRawData;
/// <summary>
/// The file pointer to the first page of the section within the COFF file.
/// For executable images, this must be a multiple of FileAlignment from the optional header.
/// For object files, the value should be aligned on a 4-byte boundary for best performance.
/// When a section contains only uninitialized data, this field should be zero.
/// </summary>
public uint PointerToRawData;
/// <summary>
/// The file pointer to the beginning of relocation entries for the section.
/// This is set to zero for executable images or if there are no relocations.
/// </summary>
public uint PointerToRelocations;
/// <summary>
/// The file pointer to the beginning of line-number entries for the section.
/// This is set to zero if there are no COFF line numbers.
/// This value should be zero for an image because COFF debugging information is deprecated.
/// </summary>
[Obsolete]
public uint PointerToLinenumbers;
/// <summary>
/// The number of relocation entries for the section.
/// This is set to zero for executable images.
/// </summary>
public ushort NumberOfRelocations;
/// <summary>
/// The number of line-number entries for the section.
/// This value should be zero for an image because COFF debugging information is deprecated.
/// </summary>
[Obsolete]
public ushort NumberOfLinenumbers;
/// <summary>
/// The flags that describe the characteristics of the section.
/// </summary>
public SectionCharacteristics Characteristics;
public static SectionHeader Deserialize(Stream stream)
{
var ish = new SectionHeader();
ish.Name = stream.ReadBytes(Constants.IMAGE_SIZEOF_SHORT_NAME);
ish.VirtualSize = stream.ReadUInt32();
ish.VirtualAddress = stream.ReadUInt32();
ish.SizeOfRawData = stream.ReadUInt32();
ish.PointerToRawData = stream.ReadUInt32();
ish.PointerToRelocations = stream.ReadUInt32();
ish.PointerToLinenumbers = stream.ReadUInt32();
ish.NumberOfRelocations = stream.ReadUInt16();
ish.NumberOfLinenumbers = stream.ReadUInt16();
ish.Characteristics = (SectionCharacteristics)stream.ReadUInt32();
return ish;
}
public static SectionHeader Deserialize(byte[] content, ref int offset)
{
var ish = new SectionHeader();
ish.Name = new byte[Constants.IMAGE_SIZEOF_SHORT_NAME];
Array.Copy(content, offset, ish.Name, 0, Constants.IMAGE_SIZEOF_SHORT_NAME); offset += Constants.IMAGE_SIZEOF_SHORT_NAME;
ish.VirtualSize = content.ReadUInt32(ref offset);
ish.VirtualAddress = content.ReadUInt32(ref offset);
ish.SizeOfRawData = content.ReadUInt32(ref offset);
ish.PointerToRawData = content.ReadUInt32(ref offset);
ish.PointerToRelocations = content.ReadUInt32(ref offset);
ish.PointerToLinenumbers = content.ReadUInt32(ref offset);
ish.NumberOfRelocations = content.ReadUInt16(ref offset);
ish.NumberOfLinenumbers = content.ReadUInt16(ref offset);
ish.Characteristics = (SectionCharacteristics)content.ReadUInt32(ref offset);
return ish;
}
}
}

View File

@@ -0,0 +1,661 @@
using System;
using System.IO;
using System.Linq;
using BurnOutSharp.ExecutableType.Microsoft.MZ.Headers;
using BurnOutSharp.ExecutableType.Microsoft.PE.Headers;
using BurnOutSharp.ExecutableType.Microsoft.PE.Sections;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE
{
/// <summary>
/// The PE file header consists of a Microsoft MS-DOS stub, the PE signature, the COFF file header, and an optional header.
/// A COFF object file header consists of a COFF file header and an optional header.
/// In both cases, the file headers are followed immediately by section headers.
/// </summary>
public class PortableExecutable
{
/// <summary>
/// Value determining if the executable is initialized or not
/// </summary>
public bool Initialized { get; } = false;
/// <summary>
/// Source array that the executable was parsed from
/// </summary>
private readonly byte[] _sourceArray = null;
/// <summary>
/// Source stream that the executable was parsed from
/// </summary>
private readonly Stream _sourceStream = null;
#region Headers
/// <summary>
/// The MS-DOS stub is a valid application that runs under MS-DOS.
/// It is placed at the front of the EXE image.
/// The linker places a default stub here, which prints out the message "This program cannot be run in DOS mode" when the image is run in MS-DOS.
/// The user can specify a different stub by using the /STUB linker option.
/// At location 0x3c, the stub has the file offset to the PE signature.
/// This information enables Windows to properly execute the image file, even though it has an MS-DOS stub.
/// This file offset is placed at location 0x3c during linking.
/// </summary>
public MSDOSExecutableHeader DOSStubHeader;
/// <summary>
/// At the beginning of an object file, or immediately after the signature of an image file, is a standard COFF file header in the following format.
/// Note that the Windows loader limits the number of sections to 96.
/// </summary>
public CommonObjectFileFormatHeader ImageFileHeader;
/// <summary>
/// Every image file has an optional header that provides information to the loader.
/// This header is optional in the sense that some files (specifically, object files) do not have it.
/// For image files, this header is required.
/// An object file can have an optional header, but generally this header has no function in an object file except to increase its size.
/// </summary>
public OptionalHeader OptionalHeader;
/// <summary>
/// Each row of the section table is, in effect, a section header.
/// This table immediately follows the optional header, if any.
/// This positioning is required because the file header does not contain a direct pointer to the section table.
/// Instead, the location of the section table is determined by calculating the location of the first byte after the headers.
/// Make sure to use the size of the optional header as specified in the file header.
/// </summary>
public SectionHeader[] SectionTable;
#endregion
#region Tables
/// <summary>
/// The .debug section is used in object files to contain compiler-generated debug information and in image files to contain
/// all of the debug information that is generated.
/// This section describes the packaging of debug information in object and image files.
/// </summary>
public DebugSection DebugDirectory;
/// <summary>
/// The export data section, named .edata, contains information about symbols that other images can access through dynamic linking.
/// Exported symbols are generally found in DLLs, but DLLs can also import symbols.
/// </summary>
public ExportDataSection ExportTable;
/// <summary>
/// All image files that import symbols, including virtually all executable (EXE) files, have an .idata section.
/// </summary>
public ImportDataSection ImportTable;
/// <summary>
/// The base relocation table contains entries for all base relocations in the image.
/// The Base Relocation Table field in the optional header data directories gives the number of bytes in the base relocation table.
/// </summary>
public RelocationSection RelocationTable;
/// <summary>
/// Resources are indexed by a multiple-level binary-sorted tree structure.
/// The general design can incorporate 2**31 levels.
/// By convention, however, Windows uses three levels
/// </summary>
public ResourceSection ResourceSection;
// TODO: Add more and more parts of a standard PE executable, not just the header
// TODO: Add data directory table information here instead of in IMAGE_OPTIONAL_HEADER
#endregion
#region Raw Section Data
// https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#special-sections
// Here is a list of standard sections that are used in various protections:
// Y - .bss *1 protection Uninitialized data (free format)
// X - .data 14 protections Initialized data (free format)
// X - .edata *1 protection Export tables
// X - .idata *1 protection Import tables
// X - .rdata 11 protections Read-only initialized data
// - .rsrc *1 protection Resource directory [TODO: Mostly taken care of, last protection needs research]
// X - .text 6 protections Executable code (free format)
// Y - .tls *1 protection Thread-local storage (object only)
//
// Here is a list of non-standard sections whose contents are read by various protections:
// X - CODE 2 protections SafeDisc, WTM CD Protect
// X - .dcrtext *1 protection JoWood
// X - .grand *1 protection CD-Cops / DVD-Cops
// X - .init *1 protection SolidShield
// - .pec2 *1 protection PE Compact [Unconfirmed]
// - .NOS0 *1 protection UPX (NOS Variant)
// - .NOS1 *1 protection UPX (NOS Variant)
// X - .txt2 *1 protection SafeDisc
// - .UPX0 *1 protection UPX
// - .UPX1 *1 protection UPX
//
// Here is a list of non-standard sections whose data is not read by various protections:
// - .brick 1 protection StarForce
// - .cenega 1 protection Cenega ProtectDVD
// - .ext 1 protection JoWood
// - HC09 1 protection JoWood
// - .icd* 1 protection CodeLock
// - .ldr 1 protection 3PLock
// - .ldt 1 protection 3PLock
// - .nicode 1 protection Armadillo
// - .pec1 1 protection PE Compact
// - .securom 1 protection SecuROM
// - .sforce 1 protection StarForce
// - stxt371 1 protection SafeDisc
// - stxt774 1 protection SafeDisc
// - .vob.pcd 1 protection VOB ProtectCD
// - _winzip_ 1 protection WinZip SFX
// - XPROT 1 protection JoWood
//
// * => Only used by 1 protection so it may be read in by that protection specifically
/// <summary>
/// .data/DATA - Initialized data (free format)
/// </summary>
public byte[] DataSectionRaw;
/// <summary>
/// .edata - Export tables
/// </summary>
/// <remarks>Replace with ExportDataSection</remarks>
public byte[] ExportDataSectionRaw;
/// <summary>
/// .idata - Import tables
/// </summary>
/// <remarks>Replace with ImportDataSection</remarks>
public byte[] ImportDataSectionRaw;
/// <summary>
/// .rdata - Read-only initialized data
/// </summary>
public byte[] ResourceDataSectionRaw;
/// <summary>
/// .text - Executable code (free format)
/// </summary>
public byte[] TextSectionRaw;
#endregion
#region Constructors
/// <summary>
/// Create a PortableExecutable object from a stream
/// </summary>
/// <param name="stream">Stream representing a file</param>
/// <remarks>
/// This constructor assumes that the stream is already in the correct position to start parsing
/// </remarks>
public PortableExecutable(Stream stream)
{
if (stream == null || !stream.CanRead || !stream.CanSeek)
return;
this._sourceStream = stream;
this.Initialized = Deserialize(stream);
}
/// <summary>
/// Create a PortableExecutable object from a byte array
/// </summary>
/// <param name="fileContent">Byte array representing a file</param>
/// <param name="offset">Positive offset representing the current position in the array</param>
public PortableExecutable(byte[] fileContent, int offset)
{
if (fileContent == null || fileContent.Length == 0 || offset < 0)
return;
this._sourceArray = fileContent;
this.Initialized = Deserialize(fileContent, offset);
}
/// <summary>
/// Deserialize a PortableExecutable object from a stream
/// </summary>
/// <param name="stream">Stream representing a file</param>
private bool Deserialize(Stream stream)
{
try
{
// Attempt to read the DOS header first
this.DOSStubHeader = MSDOSExecutableHeader.Deserialize(stream); stream.Seek(this.DOSStubHeader.NewExeHeaderAddr, SeekOrigin.Begin);
if (this.DOSStubHeader.Magic != Constants.IMAGE_DOS_SIGNATURE)
return false;
// If the new header address is invalid for the file, it's not a PE
if (this.DOSStubHeader.NewExeHeaderAddr >= stream.Length)
return false;
// Then attempt to read the PE header
this.ImageFileHeader = CommonObjectFileFormatHeader.Deserialize(stream);
if (this.ImageFileHeader.Signature != Constants.IMAGE_NT_SIGNATURE)
return false;
// If the optional header is supposed to exist, read that as well
if (this.ImageFileHeader.SizeOfOptionalHeader > 0)
this.OptionalHeader = OptionalHeader.Deserialize(stream);
// Then read in the section table
this.SectionTable = new SectionHeader[this.ImageFileHeader.NumberOfSections];
for (int i = 0; i < this.ImageFileHeader.NumberOfSections; i++)
{
this.SectionTable[i] = SectionHeader.Deserialize(stream);
}
#region Structured Tables
// // Debug Section
// var table = this.GetLastSection(".debug", true);
// if (table != null && table.VirtualSize > 0)
// {
// stream.Seek((int)table.PointerToRawData, SeekOrigin.Begin);
// this.DebugSection = DebugSection.Deserialize(stream, this.SectionTable);
// }
// // Export Table
// var table = this.GetLastSection(".edata", true);
// if (table != null && table.VirtualSize > 0)
// {
// stream.Seek((int)table.PointerToRawData, SeekOrigin.Begin);
// this.ExportTable = ExportDataSection.Deserialize(stream, this.SectionTable);
// }
// // Import Table
// table = this.GetSection(".idata", true);
// if (table != null && table.VirtualSize > 0)
// {
// stream.Seek((int)table.PointerToRawData, SeekOrigin.Begin);
// this.ImportTable = ImportDataSection.Deserialize(stream, this.OptionalHeader.Magic == OptionalHeaderType.PE32Plus, hintCount: 0);
// }
// // Relocation Section
// var table = this.GetLastSection(".reloc", true);
// if (table != null && table.VirtualSize > 0)
// {
// stream.Seek((int)table.PointerToRawData, SeekOrigin.Begin);
// this.RelocationTable = RelocationSection.Deserialize(stream);
// }
// Resource Table
var table = this.GetLastSection(".rsrc", true);
if (table != null && table.VirtualSize > 0)
{
stream.Seek((int)table.PointerToRawData, SeekOrigin.Begin);
this.ResourceSection = ResourceSection.Deserialize(stream, this.SectionTable);
}
#endregion
#region Freeform Sections
// Data Section
this.DataSectionRaw = this.ReadRawSection(".data", force: true, first: false) ?? this.ReadRawSection("DATA", force: true, first: false);
// Export Table
this.ExportDataSectionRaw = this.ReadRawSection(".edata", force: true, first: false);
// Import Table
this.ImportDataSectionRaw = this.ReadRawSection(".idata", force: true, first: false);
// Resource Data Section
this.ResourceDataSectionRaw = this.ReadRawSection(".rdata", force: true, first: false);
// Text Section
this.TextSectionRaw = this.ReadRawSection(".text", force: true, first: false);
#endregion
}
catch (Exception ex)
{
//Console.WriteLine($"Errored out on a file: {ex}");
return false;
}
return true;
}
/// <summary>
/// Deserialize a PortableExecutable object from a byte array
/// </summary>
/// <param name="fileContent">Byte array representing a file</param>
/// <param name="offset">Positive offset representing the current position in the array</param>
private bool Deserialize(byte[] content, int offset)
{
try
{
// Attempt to read the DOS header first
this.DOSStubHeader = MSDOSExecutableHeader.Deserialize(content, ref offset);
offset = this.DOSStubHeader.NewExeHeaderAddr;
if (this.DOSStubHeader.Magic != Constants.IMAGE_DOS_SIGNATURE)
return false;
// If the new header address is invalid for the file, it's not a PE
if (this.DOSStubHeader.NewExeHeaderAddr >= content.Length)
return false;
// Then attempt to read the PE header
this.ImageFileHeader = CommonObjectFileFormatHeader.Deserialize(content, ref offset);
if (this.ImageFileHeader.Signature != Constants.IMAGE_NT_SIGNATURE)
return false;
// If the optional header is supposed to exist, read that as well
if (this.ImageFileHeader.SizeOfOptionalHeader > 0)
this.OptionalHeader = OptionalHeader.Deserialize(content, ref offset);
// Then read in the section table
this.SectionTable = new SectionHeader[this.ImageFileHeader.NumberOfSections];
for (int i = 0; i < this.ImageFileHeader.NumberOfSections; i++)
{
this.SectionTable[i] = SectionHeader.Deserialize(content, ref offset);
}
#region Structured Tables
// // Debug Section
// var table = this.GetLastSection(".debug", true);
// if (table != null && table.VirtualSize > 0)
// {
// int tableAddress = (int)table.PointerToRawData;
// this.DebugSection = DebugSection.Deserialize(content, ref tableAddress, this.SectionTable);
// }
// // Export Table
// var table = this.GetLastSection(".edata", true);
// if (table != null && table.VirtualSize > 0)
// {
// int tableAddress = (int)table.PointerToRawData;
// this.ExportTable = ExportDataSection.Deserialize(content, ref tableAddress, this.SectionTable);
// }
// // Import Table
// table = this.GetSection(".idata", true);
// if (table != null && table.VirtualSize > 0)
// {
// int tableAddress = (int)table.PointerToRawData;
// this.ImportTable = ImportDataSection.Deserialize(content, ref tableAddress, this.OptionalHeader.Magic == OptionalHeaderType.PE32Plus, hintCount: 0);
// }
// // Relocation Section
// var table = this.GetLastSection(".reloc", true);
// if (table != null && table.VirtualSize > 0)
// {
// int tableAddress = (int)table.PointerToRawData;
// this.RelocationTable = RelocationSection.Deserialize(content, ref tableAddress);
// }
// Resource Table
var table = this.GetLastSection(".rsrc", true);
if (table != null && table.VirtualSize > 0)
{
int tableAddress = (int)table.PointerToRawData;
this.ResourceSection = ResourceSection.Deserialize(content, ref tableAddress, this.SectionTable);
}
#endregion
#region Freeform Sections
// Data Section
this.DataSectionRaw = this.ReadRawSection(".data", force: true, first: false) ?? this.ReadRawSection("DATA", force: true, first: false);
// Export Table
this.ExportDataSectionRaw = this.ReadRawSection(".edata", force: true, first: false);
// Import Table
this.ImportDataSectionRaw = this.ReadRawSection(".idata", force: true, first: false);
// Resource Data Section
this.ResourceDataSectionRaw = this.ReadRawSection(".rdata", force: true, first: false);
// Text Section
this.TextSectionRaw = this.ReadRawSection(".text", force: true, first: false);
#endregion
}
catch (Exception ex)
{
//Console.WriteLine($"Errored out on a file: {ex}");
return false;
}
return true;
}
#endregion
#region Helpers
/// <summary>
/// Determine if a section is contained within the section table
/// </summary>
/// <param name="sectionName">Name of the section to check for</param>
/// <param name="exact">True to enable exact matching of names, false for starts-with</param>
/// <returns>True if the section is in the executable, false otherwise</returns>
public bool ContainsSection(string sectionName, bool exact = false)
{
// Get all section names first
string[] sectionNames = GetSectionNames();
if (sectionNames == null)
return false;
// If we're checking exactly, return only exact matches
if (exact)
return sectionNames.Any(n => n.Equals(sectionName));
// Otherwise, check if section name starts with the value
else
return sectionNames.Any(n => n.StartsWith(sectionName));
}
/// <summary>
/// Convert a virtual address to a physical one
/// </summary>
/// <param name="virtualAddress">Virtual address to convert</param>
/// <param name="sections">Array of sections to check against</param>
/// <returns>Physical address, 0 on error</returns>
public static uint ConvertVirtualAddress(uint virtualAddress, SectionHeader[] sections)
{
// Loop through all of the sections
for (int i = 0; i < sections.Length; i++)
{
// If the section is invalid, just skip it
if (sections[i] == null)
continue;
// If the section "starts" at 0, just skip it
if (sections[i].PointerToRawData == 0)
continue;
// Attempt to derive the physical address from the current section
var section = sections[i];
if (virtualAddress >= section.VirtualAddress && virtualAddress <= section.VirtualAddress + section.VirtualSize)
return section.PointerToRawData + virtualAddress - section.VirtualAddress;
}
return 0;
}
/// <summary>
/// Get the first section based on name, if possible
/// </summary>
/// <param name="sectionName">Name of the section to check for</param>
/// <param name="exact">True to enable exact matching of names, false for starts-with</param>
/// <returns>Section data on success, null on error</returns>
public SectionHeader GetFirstSection(string sectionName, bool exact = false)
{
// If we have no sections, we can't do anything
if (SectionTable == null || !SectionTable.Any())
return null;
// If we're checking exactly, return only exact matches
if (exact)
return SectionTable.FirstOrDefault(s => s.NameString.Equals(sectionName));
// Otherwise, check if section name starts with the value
else
return SectionTable.FirstOrDefault(s => s.NameString.StartsWith(sectionName));
}
/// <summary>
/// Get the last section based on name, if possible
/// </summary>
/// <param name="sectionName">Name of the section to check for</param>
/// <param name="exact">True to enable exact matching of names, false for starts-with</param>
/// <returns>Section data on success, null on error</returns>
public SectionHeader GetLastSection(string sectionName, bool exact = false)
{
// If we have no sections, we can't do anything
if (SectionTable == null || !SectionTable.Any())
return null;
// If we're checking exactly, return only exact matches (with nulls trimmed)
if (exact)
return SectionTable.LastOrDefault(s => s.NameString.Equals(sectionName));
// Otherwise, check if section name starts with the value
else
return SectionTable.LastOrDefault(s => s.NameString.StartsWith(sectionName));
}
/// <summary>
/// Get the list of section names
/// </summary>
public string[] GetSectionNames()
{
// Invalid table means no names are accessible
if (SectionTable == null || SectionTable.Length == 0)
return null;
return SectionTable.Select(s => s.NameString).ToArray();
}
/// <summary>
/// Print all sections, including their start and end addresses
/// </summary>
public void PrintAllSections()
{
foreach (var section in SectionTable)
{
string sectionName = section.NameString;
int sectionAddr = (int)section.PointerToRawData;
int sectionEnd = sectionAddr + (int)section.VirtualSize;
Console.WriteLine($"{sectionName}: {sectionAddr} -> {sectionEnd}");
}
}
/// <summary>
/// Read an arbitrary range from the source
/// </summary>
/// <param name="rangeStart">The start of where to read data from, -1 means start of source</param>
/// <param name="length">How many bytes to read, -1 means read until end</param>
/// <returns></returns>
public byte[] ReadArbitraryRange(int rangeStart = -1, int length = -1)
{
try
{
// If we have a source stream, use that
if (this._sourceStream != null)
return ReadArbitraryRangeFromSourceStream(rangeStart, length);
// If we have a source array, use that
if (this._sourceArray != null)
return ReadArbitraryRangeFromSourceArray(rangeStart, length);
// Otherwise, return null
return null;
}
catch (Exception ex)
{
// TODO: How to handle this differently?
return null;
}
}
/// <summary>
/// Read an arbitrary range from the stream source, if possible
/// </summary>
/// <param name="rangeStart">The start of where to read data from, -1 means start of source</param>
/// <param name="length">How many bytes to read, -1 means read until end</param>
/// <returns></returns>
private byte[] ReadArbitraryRangeFromSourceStream(int rangeStart, int length)
{
lock (this._sourceStream)
{
int startingIndex = (int)Math.Max(rangeStart, 0);
int readLength = (int)Math.Min(length == -1 ? length = Int32.MaxValue : length, this._sourceStream.Length);
long originalPosition = this._sourceStream.Position;
this._sourceStream.Seek(startingIndex, SeekOrigin.Begin);
byte[] sectionData = this._sourceStream.ReadBytes(readLength);
this._sourceStream.Seek(originalPosition, SeekOrigin.Begin);
return sectionData;
}
}
/// <summary>
/// Read an arbitrary range from the array source, if possible
/// </summary>
/// <param name="rangeStart">The start of where to read data from, -1 means start of source</param>
/// <param name="length">How many bytes to read, -1 means read until end</param>
/// <returns></returns>
private byte[] ReadArbitraryRangeFromSourceArray(int rangeStart, int length)
{
int startingIndex = (int)Math.Max(rangeStart, 0);
int readLength = (int)Math.Min(length == -1 ? length = Int32.MaxValue : length, this._sourceArray.Length);
try
{
return this._sourceArray.ReadBytes(ref startingIndex, readLength);
}
catch
{
// Just absorb errors for now
// TODO: Investigate why and when this would be hit
return null;
}
}
/// <summary>
/// Get the raw bytes from a section, if possible
/// </summary>
/// <param name="sectionName">The name of the section to attempt to read</param>
/// <param name="force">True to force reading the section from the underlying source, false to use cached values, if possible</param>
/// <param name="first">True to use the first section with a matching name, false to use the last section</param>
/// <param name="offset">Offset to start reading at, default is 0</param>
public byte[] ReadRawSection(string sectionName, bool force = false, bool first = true, int offset = 0)
{
// Special cases for non-forced, non-offset data
if (!force && offset == 0)
{
switch (sectionName)
{
case ".data":
return DataSectionRaw;
case ".edata":
return ExportDataSectionRaw;
case ".idata":
return ImportDataSectionRaw;
case ".rdata":
return ResourceDataSectionRaw;
case ".text":
return TextSectionRaw;
}
}
// Get the section, if possible
var section = first ? GetFirstSection(sectionName, true) : GetLastSection(sectionName, true);
if (section == null)
return null;
// Return the raw data from that section
int rangeStart = (int)(section.PointerToRawData + offset);
int rangeEnd = (int)(section.VirtualSize - offset);
return ReadArbitraryRange(rangeStart, rangeEnd);
}
#endregion
}
}

View File

@@ -0,0 +1,46 @@
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE.Tables;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Sections
{
/// <summary>
/// The .debug section is used in object files to contain compiler-generated debug information and in image files to contain
/// all of the debug information that is generated.
/// This section describes the packaging of debug information in object and image files.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#the-debug-section</remarks>
public class DebugSection
{
/// <summary>
/// Image files contain an optional debug directory that indicates what form of debug information is present and where it is.
/// This directory consists of an array of debug directory entries whose location and size are indicated in the image optional header.
/// </summary>
public DebugDirectory DebugDirectory;
public static DebugSection Deserialize(Stream stream)
{
long originalPosition = stream.Position;
var ds = new DebugSection();
ds.DebugDirectory = DebugDirectory.Deserialize(stream);
// TODO: Read in raw debug data
stream.Seek(originalPosition, SeekOrigin.Begin);
return ds;
}
public static DebugSection Deserialize(byte[] content, ref int offset)
{
int originalPosition = offset;
var ds = new DebugSection();
ds.DebugDirectory = DebugDirectory.Deserialize(content, ref offset);
// TODO: Read in raw debug data
offset = originalPosition;
return ds;
}
}
}

View File

@@ -0,0 +1,19 @@
using BurnOutSharp.ExecutableType.Microsoft.PE.Tables;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Sections
{
/// <summary>
/// The .pdata section contains an array of function table entries that are used for exception handling.
/// It is pointed to by the exception table entry in the image data directory.
/// The entries must be sorted according to the function addresses (the first field in each structure) before being emitted into the final image.
/// The target platform determines which of the three function table entry format variations described below is used.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#the-edata-section-image-only</remarks>
public class ExceptionHandlingSection
{
/// <summary>
/// Array of function table entries that are used for exception handling
/// </summary>
public FunctionTable FunctionTable;
}
}

View File

@@ -0,0 +1,95 @@
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE.Entries;
using BurnOutSharp.ExecutableType.Microsoft.PE.Headers;
using BurnOutSharp.ExecutableType.Microsoft.PE.Tables;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Sections
{
/// <summary>
/// The export data section, named .edata, contains information about symbols that other images can access through dynamic linking.
/// Exported symbols are generally found in DLLs, but DLLs can also import symbols.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#the-edata-section-image-only</remarks>
public class ExportDataSection
{
/// <summary>
/// A table with just one row (unlike the debug directory).
/// This table indicates the locations and sizes of the other export tables.
/// </summary>
public ExportDirectoryTable ExportDirectoryTable;
/// <summary>
/// An array of RVAs of exported symbols.
/// These are the actual addresses of the exported functions and data within the executable code and data sections.
/// Other image files can import a symbol by using an index to this table (an ordinal) or, optionally, by using the public name that corresponds to the ordinal if a public name is defined.
/// </summary>
public ExportAddressTableEntry[] ExportAddressTable;
/// <summary>
/// An array of pointers to the public export names, sorted in ascending order.
/// </summary>
public uint[] ExportNamePointerTable;
/// <summary>
/// An array of the ordinals that correspond to members of the name pointer table.
/// The correspondence is by position; therefore, the name pointer table and the ordinal table must have the same number of members.
/// Each ordinal is an index into the export address table.
/// </summary>
public ExportOrdinalTable OrdinalTable;
public static ExportDataSection Deserialize(Stream stream, SectionHeader[] sections)
{
long originalPosition = stream.Position;
var eds = new ExportDataSection();
eds.ExportDirectoryTable = ExportDirectoryTable.Deserialize(stream);
stream.Seek((int)PortableExecutable.ConvertVirtualAddress(eds.ExportDirectoryTable.ExportAddressTableRVA, sections), SeekOrigin.Begin);
eds.ExportAddressTable = new ExportAddressTableEntry[(int)eds.ExportDirectoryTable.AddressTableEntries];
for (int i = 0; i < eds.ExportAddressTable.Length; i++)
{
eds.ExportAddressTable[i] = ExportAddressTableEntry.Deserialize(stream, sections);
}
stream.Seek((int)PortableExecutable.ConvertVirtualAddress(eds.ExportDirectoryTable.NamePointerRVA, sections), SeekOrigin.Begin);
eds.ExportNamePointerTable = new uint[(int)eds.ExportDirectoryTable.NumberOfNamePointers];
for (int i = 0; i < eds.ExportNamePointerTable.Length; i++)
{
eds.ExportNamePointerTable[i] = stream.ReadUInt32();
}
stream.Seek((int)PortableExecutable.ConvertVirtualAddress(eds.ExportDirectoryTable.OrdinalTableRVA, sections), SeekOrigin.Begin);
// eds.OrdinalTable = ExportOrdinalTable.Deserialize(stream, count: 0); // TODO: Figure out where this count comes from
return eds;
}
public static ExportDataSection Deserialize(byte[] content, ref int offset, SectionHeader[] sections)
{
int originalPosition = offset;
var eds = new ExportDataSection();
eds.ExportDirectoryTable = ExportDirectoryTable.Deserialize(content, ref offset);
offset = (int)PortableExecutable.ConvertVirtualAddress(eds.ExportDirectoryTable.ExportAddressTableRVA, sections);
eds.ExportAddressTable = new ExportAddressTableEntry[(int)eds.ExportDirectoryTable.AddressTableEntries];
for (int i = 0; i < eds.ExportAddressTable.Length; i++)
{
eds.ExportAddressTable[i] = ExportAddressTableEntry.Deserialize(content, ref offset, sections);
}
offset = (int)PortableExecutable.ConvertVirtualAddress(eds.ExportDirectoryTable.NamePointerRVA, sections);
eds.ExportNamePointerTable = new uint[(int)eds.ExportDirectoryTable.NumberOfNamePointers];
for (int i = 0; i < eds.ExportNamePointerTable.Length; i++)
{
eds.ExportNamePointerTable[i] = content.ReadUInt32(ref offset);
}
offset = (int)PortableExecutable.ConvertVirtualAddress(eds.ExportDirectoryTable.OrdinalTableRVA, sections);
// eds.OrdinalTable = ExportOrdinalTable.Deserialize(content, ref offset, count: 0); // TODO: Figure out where this count comes from
return eds;
}
}
}

View File

@@ -0,0 +1,80 @@
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE.Tables;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Sections
{
/// <summary>
/// All image files that import symbols, including virtually all executable (EXE) files, have an .idata section.
/// A typical file layout for the import information follows:
/// Directory Table
/// Null Directory Entry
/// DLL1 Import Lookup Table
/// Null
/// DLL2 Import Lookup Table
/// Null
/// DLL3 Import Lookup Table
/// Null
/// Hint-Name Table
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#the-idata-section</remarks>
public class ImportDataSection
{
/// <summary>
/// Import directory table
/// </summary>
public ImportDirectoryTable ImportDirectoryTable;
/// <summary>
/// Import lookup tables
/// </summary>
public ImportLookupTable[] ImportLookupTables;
/// <summary>
/// Hint/Name table
/// </summary>
public HintNameTable HintNameTable;
public static ImportDataSection Deserialize(Stream stream, bool pe32plus, int hintCount)
{
var ids = new ImportDataSection();
ids.ImportDirectoryTable = ImportDirectoryTable.Deserialize(stream);
List<ImportLookupTable> tempLookupTables = new List<ImportLookupTable>();
while (true)
{
var tempLookupTable = ImportLookupTable.Deserialize(stream, pe32plus);
if (tempLookupTable.EntriesPE32 == null && tempLookupTable.EntriesPE32Plus == null)
break;
tempLookupTables.Add(tempLookupTable);
}
ids.HintNameTable = HintNameTable.Deserialize(stream, hintCount);
return ids;
}
public static ImportDataSection Deserialize(byte[] content, ref int offset, bool pe32plus, int hintCount)
{
var ids = new ImportDataSection();
ids.ImportDirectoryTable = ImportDirectoryTable.Deserialize(content, ref offset);
List<ImportLookupTable> tempLookupTables = new List<ImportLookupTable>();
while (true)
{
var tempLookupTable = ImportLookupTable.Deserialize(content, ref offset, pe32plus);
if (tempLookupTable.EntriesPE32 == null && tempLookupTable.EntriesPE32Plus == null)
break;
tempLookupTables.Add(tempLookupTable);
}
ids.HintNameTable = HintNameTable.Deserialize(content, ref offset, hintCount);
return ids;
}
}
}

View File

@@ -0,0 +1,51 @@
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE.Entries;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Sections
{
/// <summary>
/// The base relocation table contains entries for all base relocations in the image.
/// The Base Relocation Table field in the optional header data directories gives the number of bytes in the base relocation table.
/// The base relocation table is divided into blocks.
/// Each block represents the base relocations for a 4K page.
/// Each block must start on a 32-bit boundary.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#the-reloc-section-image-only</remarks>
public class RelocationSection
{
/// <summary>
/// The base relocation table is divided into blocks.
/// </summary>
public BaseRelocationBlock[] BaseRelocationTable;
public static RelocationSection Deserialize(Stream stream, int blockCount)
{
long originalPosition = stream.Position;
var rs = new RelocationSection();
rs.BaseRelocationTable = new BaseRelocationBlock[blockCount];
for (int i = 0; i < blockCount; i++)
{
rs.BaseRelocationTable[i] = BaseRelocationBlock.Deserialize(stream);
}
stream.Seek(originalPosition, SeekOrigin.Begin);
return rs;
}
public static RelocationSection Deserialize(byte[] content, ref int offset, int blockCount)
{
int originalPosition = offset;
var rs = new RelocationSection();
rs.BaseRelocationTable = new BaseRelocationBlock[blockCount];
for (int i = 0; i < blockCount; i++)
{
rs.BaseRelocationTable[i] = BaseRelocationBlock.Deserialize(content, ref offset);
}
offset = originalPosition;
return rs;
}
}
}

View File

@@ -0,0 +1,44 @@
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE.Headers;
using BurnOutSharp.ExecutableType.Microsoft.PE.Tables;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Sections
{
/// <summary>
/// A series of resource directory tables relates all of the levels in the following way:
// Each directory table is followed by a series of directory entries that give the name or
// identifier (ID) for that level (Type, Name, or Language level) and an address of either
// a data description or another directory table. If the address points to a data description,
// then the data is a leaf in the tree. If the address points to another directory table,
// then that table lists directory entries at the next level down
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#the-rsrc-section</remarks>
public class ResourceSection
{
/// <summary>
/// A table with just one row (unlike the debug directory).
/// This table indicates the locations and sizes of the other export tables.
/// </summary>
public ResourceDirectoryTable ResourceDirectoryTable;
public static ResourceSection Deserialize(Stream stream, SectionHeader[] sections)
{
var rs = new ResourceSection();
long sectionStart = stream.Position;
rs.ResourceDirectoryTable = ResourceDirectoryTable.Deserialize(stream, sectionStart, sections);
return rs;
}
public static ResourceSection Deserialize(byte[] content, ref int offset, SectionHeader[] sections)
{
var rs = new ResourceSection();
long sectionStart = offset;
rs.ResourceDirectoryTable = ResourceDirectoryTable.Deserialize(content, ref offset, sectionStart, sections);
return rs;
}
}
}

View File

@@ -0,0 +1,85 @@
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Tables
{
/// <summary>
/// Image files contain an optional debug directory that indicates what form of debug information is present and where it is.
/// This directory consists of an array of debug directory entries whose location and size are indicated in the image optional header.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#debug-directory-image-only</remarks>
public class DebugDirectory
{
/// <summary>
/// Reserved, must be 0.
/// </summary>
public uint Characteristics;
/// <summary>
/// The time and date that the debug data was created.
/// </summary>
public uint TimeDateStamp;
/// <summary>
/// The major version number of the debug data format.
/// </summary>
public ushort MajorVersion;
/// <summary>
/// The minor version number of the debug data format.
/// </summary>
public ushort MinorVersion;
/// <summary>
/// The format of debugging information. This field enables support of multiple debuggers.
/// </summary>
public DebugType DebugType;
/// <summary>
/// The size of the debug data (not including the debug directory itself).
/// </summary>
public uint SizeOfData;
/// <summary>
/// The address of the debug data when loaded, relative to the image base.
/// </summary>
public uint AddressOfRawData;
/// <summary>
/// The file pointer to the debug data.
/// </summary>
public uint PointerToRawData;
public static DebugDirectory Deserialize(Stream stream)
{
var dd = new DebugDirectory();
dd.Characteristics = stream.ReadUInt32();
dd.TimeDateStamp = stream.ReadUInt32();
dd.MajorVersion = stream.ReadUInt16();
dd.MinorVersion = stream.ReadUInt16();
dd.DebugType = (DebugType)stream.ReadUInt32();
dd.SizeOfData = stream.ReadUInt32();
dd.AddressOfRawData = stream.ReadUInt32();
dd.PointerToRawData = stream.ReadUInt32();
return dd;
}
public static DebugDirectory Deserialize(byte[] content, ref int offset)
{
var dd = new DebugDirectory();
dd.Characteristics = content.ReadUInt32(ref offset);
dd.TimeDateStamp = content.ReadUInt32(ref offset);
dd.MajorVersion = content.ReadUInt16(ref offset);
dd.MinorVersion = content.ReadUInt16(ref offset);
dd.DebugType = (DebugType)content.ReadUInt32(ref offset);
dd.SizeOfData = content.ReadUInt32(ref offset);
dd.AddressOfRawData = content.ReadUInt32(ref offset);
dd.PointerToRawData = content.ReadUInt32(ref offset);
return dd;
}
}
}

View File

@@ -0,0 +1,111 @@
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Tables
{
/// <summary>
/// The export symbol information begins with the export directory table, which describes the remainder of the export symbol information.
/// The export directory table contains address information that is used to resolve imports to the entry points within this image.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#export-directory-table</remarks>
public class ExportDirectoryTable
{
/// <summary>
/// Reserved, must be 0.
/// </summary>
public uint ExportFlags;
/// <summary>
/// The time and date that the export data was created.
/// </summary>
public uint TimeDateStamp;
/// <summary>
/// The major version number. The major and minor version numbers can be set by the user.
/// </summary>
public ushort MajorVersion;
/// <summary>
/// The minor version number.
/// </summary>
public ushort MinorVersion;
/// <summary>
/// The address of the ASCII string that contains the name of the DLL.
/// This address is relative to the image base.
/// </summary>
public uint NameRVA; // TODO: Read this into a separate field
/// <summary>
/// The starting ordinal number for exports in this image.
/// This field specifies the starting ordinal number for the export address table.
/// It is usually set to 1.
/// </summary>
public uint OrdinalBase;
/// <summary>
/// The number of entries in the export address table.
/// </summary>
public uint AddressTableEntries;
/// <summary>
/// The number of entries in the name pointer table.
/// This is also the number of entries in the ordinal table.
/// </summary>
public uint NumberOfNamePointers;
/// <summary>
/// The address of the export address table, relative to the image base.
/// </summary>
public uint ExportAddressTableRVA;
/// <summary>
/// The address of the export name pointer table, relative to the image base.
/// The table size is given by the Number of Name Pointers field.
/// </summary>
public uint NamePointerRVA;
/// <summary>
/// The address of the ordinal table, relative to the image base.
/// </summary>
public uint OrdinalTableRVA;
public static ExportDirectoryTable Deserialize(Stream stream)
{
var edt = new ExportDirectoryTable();
edt.ExportFlags = stream.ReadUInt32();
edt.TimeDateStamp = stream.ReadUInt32();
edt.MajorVersion = stream.ReadUInt16();
edt.MinorVersion = stream.ReadUInt16();
edt.NameRVA = stream.ReadUInt32();
edt.OrdinalBase = stream.ReadUInt32();
edt.AddressTableEntries = stream.ReadUInt32();
edt.NumberOfNamePointers = stream.ReadUInt32();
edt.ExportAddressTableRVA = stream.ReadUInt32();
edt.NamePointerRVA = stream.ReadUInt32();
edt.OrdinalTableRVA = stream.ReadUInt32();
return edt;
}
public static ExportDirectoryTable Deserialize(byte[] content, ref int offset)
{
var edt = new ExportDirectoryTable();
edt.ExportFlags = content.ReadUInt32(ref offset);
edt.TimeDateStamp = content.ReadUInt32(ref offset);
edt.MajorVersion = content.ReadUInt16(ref offset);
edt.MinorVersion = content.ReadUInt16(ref offset);
edt.NameRVA = content.ReadUInt32(ref offset);
edt.OrdinalBase = content.ReadUInt32(ref offset);
edt.AddressTableEntries = content.ReadUInt32(ref offset);
edt.NumberOfNamePointers = content.ReadUInt32(ref offset);
edt.ExportAddressTableRVA = content.ReadUInt32(ref offset);
edt.NamePointerRVA = content.ReadUInt32(ref offset);
edt.OrdinalTableRVA = content.ReadUInt32(ref offset);
return edt;
}
}
}

View File

@@ -0,0 +1,44 @@
using System;
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Tables
{
/// <summary>
/// The export ordinal table is an array of 16-bit unbiased indexes into the export address table.
/// Ordinals are biased by the Ordinal Base field of the export directory table.
/// In other words, the ordinal base must be subtracted from the ordinals to obtain true indexes into the export address table.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#export-ordinal-table</remarks>
public class ExportOrdinalTable
{
/// <remarks>Number of entries is defined externally</remarks>
public ushort[] Entries;
public static ExportOrdinalTable Deserialize(Stream stream, int count)
{
var edt = new ExportOrdinalTable();
edt.Entries = new ushort[count];
for (int i = 0; i < count; i++)
{
edt.Entries[i] = stream.ReadUInt16();
}
return edt;
}
public static ExportOrdinalTable Deserialize(byte[] content, ref int offset, int count)
{
var edt = new ExportOrdinalTable();
edt.Entries = new ushort[count];
for (int i = 0; i < count; i++)
{
edt.Entries[i] = content.ReadUInt16(ref offset);
}
return edt;
}
}
}

View File

@@ -0,0 +1,17 @@
using BurnOutSharp.ExecutableType.Microsoft.PE.Entries;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Tables
{
/// <summary>
/// The .pdata section contains an array of function table entries that are used for exception handling.
/// It is pointed to by the exception table entry in the image data directory.
/// The entries must be sorted according to the function addresses (the first field in each structure) before being emitted into the final image.
/// The target platform determines which of the three function table entry format variations described below is used.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#the-pdata-section</remarks>
public class FunctionTable
{
/// <remarks>Number of entries is defined externally</remarks>
public FunctionTableEntry[] Entries;
}
}

View File

@@ -0,0 +1,42 @@
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE.Entries;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Tables
{
/// <summary>
/// One hint/name table suffices for the entire import section.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#hintname-table</remarks>
public class HintNameTable
{
/// <remarks>Number of entries is defined externally</remarks>
public HintNameTableEntry[] Entries;
public static HintNameTable Deserialize(Stream stream, int count)
{
var hnt = new HintNameTable();
hnt.Entries = new HintNameTableEntry[count];
for (int i = 0; i < count; i++)
{
hnt.Entries[i] = HintNameTableEntry.Deserialize(stream);
}
return hnt;
}
public static HintNameTable Deserialize(byte[] content, ref int offset, int count)
{
var hnt = new HintNameTable();
hnt.Entries = new HintNameTableEntry[count];
for (int i = 0; i < count; i++)
{
hnt.Entries[i] = HintNameTableEntry.Deserialize(content, ref offset);
offset += 2 + hnt.Entries[i].Name.Length + hnt.Entries[i].Pad;
}
return hnt;
}
}
}

View File

@@ -0,0 +1,53 @@
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE.Entries;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Tables
{
/// <summary>
/// The structure and content of the import address table are identical to those of the import lookup table, until the file is bound.
/// During binding, the entries in the import address table are overwritten with the 32-bit (for PE32) or 64-bit (for PE32+) addresses of the symbols that are being imported.
/// These addresses are the actual memory addresses of the symbols, although technically they are still called "virtual addresses."
/// The loader typically processes the binding.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#import-address-table</remarks>
public class ImportAddressTable
{
/// <remarks>Number of entries is known after parsing</remarks>
public ImportAddressTableEntry[] Entries;
public static ImportAddressTable Deserialize(Stream stream)
{
var iat = new ImportAddressTable();
List<ImportAddressTableEntry> tempEntries = new List<ImportAddressTableEntry>();
while (true)
{
var entry = ImportAddressTableEntry.Deserialize(stream);
tempEntries.Add(entry);
if (entry.IsNull())
break;
}
iat.Entries = tempEntries.ToArray();
return iat;
}
public static ImportAddressTable Deserialize(byte[] content, ref int offset)
{
var iat = new ImportAddressTable();
List<ImportAddressTableEntry> tempEntries = new List<ImportAddressTableEntry>();
while (true)
{
var entry = ImportAddressTableEntry.Deserialize(content, ref offset);
tempEntries.Add(entry);
if (entry.IsNull())
break;
}
iat.Entries = tempEntries.ToArray();
return iat;
}
}
}

View File

@@ -0,0 +1,53 @@
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE.Entries;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Tables
{
/// <summary>
/// The import information begins with the import directory table, which describes the remainder of the import information.
/// The import directory table contains address information that is used to resolve fixup references to the entry points within a DLL image.
/// The import directory table consists of an array of import directory entries, one entry for each DLL to which the image refers.
/// The last directory entry is empty (filled with null values), which indicates the end of the directory table.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#import-directory-table</remarks>
public class ImportDirectoryTable
{
/// <remarks>Number of entries is known after parsing</remarks>
public ImportDirectoryTableEntry[] Entries;
public static ImportDirectoryTable Deserialize(Stream stream)
{
var idt = new ImportDirectoryTable();
List<ImportDirectoryTableEntry> tempEntries = new List<ImportDirectoryTableEntry>();
while (true)
{
var entry = ImportDirectoryTableEntry.Deserialize(stream);
tempEntries.Add(entry);
if (entry.IsNull())
break;
}
idt.Entries = tempEntries.ToArray();
return idt;
}
public static ImportDirectoryTable Deserialize(byte[] content, ref int offset)
{
var idt = new ImportDirectoryTable();
List<ImportDirectoryTableEntry> tempEntries = new List<ImportDirectoryTableEntry>();
while (true)
{
var entry = ImportDirectoryTableEntry.Deserialize(content, ref offset);
tempEntries.Add(entry);
if (entry.IsNull())
break;
}
idt.Entries = tempEntries.ToArray();
return idt;
}
}
}

View File

@@ -0,0 +1,98 @@
using System;
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Tables
{
/// <summary>
/// An import lookup table is an array of 32-bit numbers for PE32 or an array of 64-bit numbers for PE32+.
/// Each entry uses the bit-field format that is described in the following table.
/// In this format, bit 31 is the most significant bit for PE32 and bit 63 is the most significant bit for PE32+.
/// The collection of these entries describes all imports from a given DLL.
/// The last entry is set to zero (NULL) to indicate the end of the table.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#import-lookup-table</remarks>
public class ImportLookupTable
{
/// <remarks>Number of entries is known after parsing</remarks>
public uint[] EntriesPE32;
/// <remarks>Number of entries is known after parsing</remarks>
public ulong[] EntriesPE32Plus;
public static ImportLookupTable Deserialize(Stream stream, bool pe32plus)
{
var ilt = new ImportLookupTable();
// PE32+ has 8-byte values
if (pe32plus)
{
List<ulong> tempEntries = new List<ulong>();
while (true)
{
ulong bitfield = stream.ReadUInt64();
tempEntries.Add(bitfield);
if (bitfield == 0)
break;
}
if (tempEntries.Count > 0)
ilt.EntriesPE32Plus = tempEntries.ToArray();
}
else
{
List<uint> tempEntries = new List<uint>();
while (true)
{
uint bitfield = stream.ReadUInt32();
tempEntries.Add(bitfield);
if (bitfield == 0)
break;
}
if (tempEntries.Count > 0)
ilt.EntriesPE32 = tempEntries.ToArray();
}
return ilt;
}
public static ImportLookupTable Deserialize(byte[] content, ref int offset, bool pe32plus)
{
var ilt = new ImportLookupTable();
// PE32+ has 8-byte values
if (pe32plus)
{
List<ulong> tempEntries = new List<ulong>();
while (true)
{
ulong bitfield = content.ReadUInt64(ref offset);
tempEntries.Add(bitfield);
if (bitfield == 0)
break;
}
if (tempEntries.Count > 0)
ilt.EntriesPE32Plus = tempEntries.ToArray();
}
else
{
List<uint> tempEntries = new List<uint>();
while (true)
{
uint bitfield = content.ReadUInt32(ref offset);
tempEntries.Add(bitfield);
if (bitfield == 0)
break;
}
if (tempEntries.Count > 0)
ilt.EntriesPE32 = tempEntries.ToArray();
}
return ilt;
}
}
}

View File

@@ -0,0 +1,118 @@
using System;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE.Entries;
using BurnOutSharp.ExecutableType.Microsoft.PE.Headers;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Tables
{
/// <summary>
/// Each resource directory table has the following format.
/// This data structure should be considered the heading of a table
/// because the table actually consists of directory entries and this structure
/// </summary>
public class ResourceDirectoryTable
{
/// <summary>
/// Resource flags.
/// This field is reserved for future use.
/// It is currently set to zero.
/// </summary>
public uint Characteristics;
/// <summary>
/// The time that the resource data was created by the resource compiler.
/// </summary>
public uint TimeDateStamp;
/// <summary>
/// The major version number, set by the user.
/// </summary>
public ushort MajorVersion;
/// <summary>
/// The minor version number, set by the user.
/// </summary>
public ushort MinorVersion;
/// <summary>
/// The number of directory entries immediately following
/// the table that use strings to identify Type, Name, or
/// Language entries (depending on the level of the table).
/// </summary>
public ushort NumberOfNamedEntries;
/// <summary>
/// The number of directory entries immediately following
/// the Name entries that use numeric IDs for Type, Name,
/// or Language entries.
/// </summary>
public ushort NumberOfIdEntries;
/// <summary>
/// The directory entries immediately following
/// the table that use strings to identify Type, Name, or
/// Language entries (depending on the level of the table).
/// </summary>
public ResourceDirectoryTableEntry[] NamedEntries;
/// <summary>
/// The directory entries immediately following
/// the Name entries that use numeric IDs for Type, Name,
/// or Language entries.
/// </summary>
public ResourceDirectoryTableEntry[] IdEntries;
public static ResourceDirectoryTable Deserialize(Stream stream, long sectionStart, SectionHeader[] sections)
{
var rdt = new ResourceDirectoryTable();
rdt.Characteristics = stream.ReadUInt32();
rdt.TimeDateStamp = stream.ReadUInt32();
rdt.MajorVersion = stream.ReadUInt16();
rdt.MinorVersion = stream.ReadUInt16();
rdt.NumberOfNamedEntries = stream.ReadUInt16();
rdt.NumberOfIdEntries = stream.ReadUInt16();
rdt.NamedEntries = new ResourceDirectoryTableEntry[rdt.NumberOfNamedEntries];
for (int i = 0; i < rdt.NumberOfNamedEntries; i++)
{
rdt.NamedEntries[i] = ResourceDirectoryTableEntry.Deserialize(stream, sectionStart, sections);
}
rdt.IdEntries = new ResourceDirectoryTableEntry[rdt.NumberOfIdEntries];
for (int i = 0; i < rdt.NumberOfIdEntries; i++)
{
rdt.IdEntries[i] = ResourceDirectoryTableEntry.Deserialize(stream, sectionStart, sections);
}
return rdt;
}
public static ResourceDirectoryTable Deserialize(byte[] content, ref int offset, long sectionStart, SectionHeader[] sections)
{
var rdt = new ResourceDirectoryTable();
rdt.Characteristics = content.ReadUInt32(ref offset);
rdt.TimeDateStamp = content.ReadUInt32(ref offset);
rdt.MajorVersion = content.ReadUInt16(ref offset);
rdt.MinorVersion = content.ReadUInt16(ref offset);
rdt.NumberOfNamedEntries = content.ReadUInt16(ref offset);
rdt.NumberOfIdEntries = content.ReadUInt16(ref offset);
rdt.NamedEntries = new ResourceDirectoryTableEntry[rdt.NumberOfNamedEntries];
for (int i = 0; i < rdt.NumberOfNamedEntries; i++)
{
rdt.NamedEntries[i] = ResourceDirectoryTableEntry.Deserialize(content, ref offset, sectionStart, sections);
}
rdt.IdEntries = new ResourceDirectoryTableEntry[rdt.NumberOfIdEntries];
for (int i = 0; i < rdt.NumberOfIdEntries; i++)
{
rdt.IdEntries[i] = ResourceDirectoryTableEntry.Deserialize(content, ref offset, sectionStart, sections);
}
return rdt;
}
}
}

View File

@@ -1,41 +0,0 @@
/*
* NEWEXE.H (C) Copyright Microsoft Corp 1984-1987
*
* Data structure definitions for the OS/2 & Windows
* executable file format.
*
* Modified by IVS on 24-Jan-1991 for Resource DeCompiler
* (C) Copyright IVS 1991
*
* http://csn.ul.ie/~caolan/pub/winresdump/winresdump/newexe.h
*/
using System.IO;
using System.Runtime.InteropServices;
namespace BurnOutSharp.ExecutableType.Microsoft
{
[StructLayout(LayoutKind.Sequential)]
internal class ResourceTable
{
public ushort rscAlignShift;
public TYPEINFO TypeInfo;
public ushort rscEndTypes;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 0)]
public sbyte[][] rscResourceNames;
public byte rscEndNames;
public static ResourceTable Deserialize(Stream stream)
{
var rt = new ResourceTable();
rt.rscAlignShift = stream.ReadUInt16();
rt.TypeInfo = TYPEINFO.Deserialize(stream);
rt.rscEndTypes = stream.ReadUInt16();
rt.rscResourceNames = null; // TODO: Figure out size
rt.rscEndNames = stream.ReadByteValue();
return rt;
}
}
}

View File

@@ -0,0 +1,147 @@
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.Resources
{
public class FixedFileInfo
{
/// <summary>
/// Contains the value 0xFEEF04BD.
/// This is used with the szKey member of the VS_VERSIONINFO structure when searching a file for the VS_FIXEDFILEINFO structure.
/// </summary>
public uint Signature;
/// <summary>
/// The binary version number of this structure.
/// The high-order word of this member contains the major version number, and the low-order word contains the minor version number.
/// </summary>
public uint StrucVersion;
/// <summary>
/// The most significant 32 bits of the file's binary version number.
/// This member is used with dwFileVersionLS to form a 64-bit value used for numeric comparisons.
/// </summary>
public uint FileVersionMS;
/// <summary>
/// The least significant 32 bits of the file's binary version number.
/// This member is used with dwFileVersionMS to form a 64-bit value used for numeric comparisons.
/// </summary>
public uint FileVersionLS;
/// <summary>
/// The most significant 32 bits of the binary version number of the product with which this file was distributed.
/// This member is used with dwProductVersionLS to form a 64-bit value used for numeric comparisons.
/// </summary>
public uint ProductVersionMS;
/// <summary>
/// The least significant 32 bits of the binary version number of the product with which this file was distributed.
/// This member is used with dwProductVersionMS to form a 64-bit value used for numeric comparisons.
/// </summary>
public uint ProductVersionLS;
/// <summary>
/// Contains a bitmask that specifies the valid bits in dwFileFlags.
/// A bit is valid only if it was defined when the file was created.
/// </summary>
public uint FileFlagsMask;
/// <summary>
/// Contains a bitmask that specifies the Boolean attributes of the file. This member can include one or more of the following values.
/// </summary>
public FileInfoFileFlags FileFlags;
/// <summary>
/// The operating system for which this file was designed. This member can be one of the following values.
///
/// An application can combine these values to indicate that the file was designed for one operating system running on another.
/// The following dwFileOS values are examples of this, but are not a complete list.
/// </summary>
public FileInfoOS FileOS;
/// <summary>
/// The general type of file. This member can be one of the following values. All other values are reserved.
/// </summary>
public FileInfoFileType FileType;
/// <summary>
/// The function of the file. The possible values depend on the value of dwFileType.
/// For all values of dwFileType not described in the following list, dwFileSubtype is zero.
///
/// If dwFileType is VFT_DRV, dwFileSubtype can be one of the following values.
///
/// If dwFileType is VFT_FONT, dwFileSubtype can be one of the following values.
///
/// If dwFileType is VFT_VXD, dwFileSubtype contains the virtual device identifier included in the virtual device control block.
/// All dwFileSubtype values not listed here are reserved.
/// </summary>
public FileInfoFileSubtype FileSubtype;
/// <summary>
/// The most significant 32 bits of the file's 64-bit binary creation date and time stamp.
/// </summary>
public uint FileDateMS;
/// <summary>
/// The least significant 32 bits of the file's 64-bit binary creation date and time stamp.
/// </summary>
public uint FileDateLS;
public static FixedFileInfo Deserialize(Stream stream)
{
FixedFileInfo ffi = new FixedFileInfo();
ushort temp;
while ((temp = stream.ReadUInt16()) == 0x0000);
stream.Seek(-2, SeekOrigin.Current);
ffi.Signature = stream.ReadUInt32();
ffi.StrucVersion = stream.ReadUInt32();
ffi.FileVersionMS = stream.ReadUInt32();
ffi.FileVersionLS = stream.ReadUInt32();
ffi.ProductVersionMS = stream.ReadUInt32();
ffi.ProductVersionLS = stream.ReadUInt32();
ffi.FileFlagsMask = stream.ReadUInt32();
ffi.FileFlags = (FileInfoFileFlags)stream.ReadUInt32();
ffi.FileOS = (FileInfoOS)stream.ReadUInt32();
ffi.FileType = (FileInfoFileType)stream.ReadUInt32();
ffi.FileSubtype = (FileInfoFileSubtype)stream.ReadUInt32();
ffi.FileDateMS = stream.ReadUInt32();
ffi.FileDateLS = stream.ReadUInt32();
return ffi;
}
public static FixedFileInfo Deserialize(byte[] content, ref int offset)
{
FixedFileInfo ffi = new FixedFileInfo();
ushort temp;
bool padded = false;
while ((temp = content.ReadUInt16(ref offset)) == 0x0000)
{
padded = true;
}
if (padded)
offset -= 2;
ffi.Signature = content.ReadUInt32(ref offset);
ffi.StrucVersion = content.ReadUInt32(ref offset);
ffi.FileVersionMS = content.ReadUInt32(ref offset);
ffi.FileVersionLS = content.ReadUInt32(ref offset);
ffi.ProductVersionMS = content.ReadUInt32(ref offset);
ffi.ProductVersionLS = content.ReadUInt32(ref offset);
ffi.FileFlagsMask = content.ReadUInt32(ref offset);
ffi.FileFlags = (FileInfoFileFlags)content.ReadUInt32(ref offset);
ffi.FileOS = (FileInfoOS)content.ReadUInt32(ref offset);
ffi.FileType = (FileInfoFileType)content.ReadUInt32(ref offset);
ffi.FileSubtype = (FileInfoFileSubtype)content.ReadUInt32(ref offset);
ffi.FileDateMS = content.ReadUInt32(ref offset);
ffi.FileDateLS = content.ReadUInt32(ref offset);
return ffi;
}
}
}

View File

@@ -0,0 +1,46 @@
using System;
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.Resources
{
/// <summary>
/// If you use the Var structure to list the languages your application or DLL supports instead of using multiple version resources,
/// use the Value member to contain an array of DWORD values indicating the language and code page combinations supported by this file.
/// The low-order word of each DWORD must contain a Microsoft language identifier, and the high-order word must contain the IBM code page number.
/// Either high-order or low-order word can be zero, indicating that the file is language or code page independent.
/// If the Var structure is omitted, the file will be interpreted as both language and code page independent.
/// </summary>
public class LanguageCodePage
{
/// <summary>
/// The low-order word of each DWORD must contain a Microsoft language identifier
/// </summary>
public ushort MicrosoftLanguageIdentifier;
/// <summary>
/// The high-order word must contain the IBM code page number
/// </summary>
public ushort IBMCodePageNumber;
public static LanguageCodePage Deserialize(Stream stream)
{
LanguageCodePage lcp = new LanguageCodePage();
lcp.MicrosoftLanguageIdentifier = stream.ReadUInt16();
lcp.IBMCodePageNumber = stream.ReadUInt16();
return lcp;
}
public static LanguageCodePage Deserialize(byte[] content, ref int offset)
{
LanguageCodePage lcp = new LanguageCodePage();
lcp.MicrosoftLanguageIdentifier = content.ReadUInt16(ref offset);
lcp.IBMCodePageNumber = content.ReadUInt16(ref offset);
return lcp;
}
}
}

View File

@@ -0,0 +1,58 @@
using System.IO;
using System.Text;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.Resources
{
public class Resource
{
/// <summary>
/// The length, in bytes, of the resource structure.
/// This length does not include any padding that aligns any subsequent version resource data on a 32-bit boundary.
/// </summary>
public ushort Length;
/// <summary>
/// The length, in bytes, of the Value member.
/// This value is zero if there is no Value member associated with the current version structure.
/// </summary>
public ushort ValueLength;
/// <summary>
/// The type of data in the version resource.
/// This member is 1 if the version resource contains text data and 0 if the version resource contains binary data.
/// </summary>
public ushort Type;
/// <summary>
/// A Unicode string representing the key
/// </summary>
public string Key;
public static Resource Deserialize(Stream stream)
{
Resource r = new Resource();
while ((r.Length = stream.ReadUInt16()) == 0x0000);
r.ValueLength = stream.ReadUInt16();
r.Type = stream.ReadUInt16();
r.Key = stream.ReadString(Encoding.Unicode);
return r;
}
public static Resource Deserialize(byte[] content, ref int offset)
{
Resource r = new Resource();
while ((r.Length = content.ReadUInt16(ref offset)) == 0x0000);
r.ValueLength = content.ReadUInt16(ref offset);
r.Type = content.ReadUInt16(ref offset);
r.Key = content.ReadString(ref offset, Encoding.Unicode);
return r;
}
}
}

View File

@@ -0,0 +1,45 @@
using System.IO;
namespace BurnOutSharp.ExecutableType.Microsoft.Resources
{
public class StringFileInfo : Resource
{
/// <summary>
/// An array of one or more StringTable structures.
/// Each StringTable structure's szKey member indicates the appropriate language and code page for displaying the text in that StringTable structure.
/// </summary>
public StringTable Children;
public StringFileInfo(Resource resource)
{
this.Length = resource?.Length ?? default;
this.ValueLength = resource?.ValueLength ?? default;
this.Type = resource?.Type ?? default;
this.Key = resource?.Key ?? default;
}
public static new StringFileInfo Deserialize(Stream stream)
{
Resource resource = Resource.Deserialize(stream);
if (resource.Key != "StringFileInfo")
return null;
StringFileInfo sfi = new StringFileInfo(resource);
sfi.Children = StringTable.Deserialize(stream);
return sfi;
}
public static new StringFileInfo Deserialize(byte[] content, ref int offset)
{
Resource resource = Resource.Deserialize(content, ref offset);
if (resource.Key != "StringFileInfo")
return null;
StringFileInfo sfi = new StringFileInfo(resource);
sfi.Children = StringTable.Deserialize(content, ref offset);
return sfi;
}
}
}

View File

@@ -0,0 +1,42 @@
using System.IO;
using System.Text;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.Resources
{
public class StringStruct : Resource
{
/// <summary>
/// Typically contains a list of languages that the application or DLL supports.
/// </summary>
public string Value;
public StringStruct(Resource resource)
{
this.Length = resource?.Length ?? default;
this.ValueLength = resource?.ValueLength ?? default;
this.Type = resource?.Type ?? default;
this.Key = resource?.Key ?? default;
}
public static new StringStruct Deserialize(Stream stream)
{
Resource resource = Resource.Deserialize(stream);
StringStruct s = new StringStruct(resource);
stream.Seek(stream.Position % 4 == 0 ? 0 : 4 - (stream.Position % 4), SeekOrigin.Current);
s.Value = new string(stream.ReadChars(s.ValueLength));
return s;
}
public static new StringStruct Deserialize(byte[] content, ref int offset)
{
Resource resource = Resource.Deserialize(content, ref offset);
StringStruct s = new StringStruct(resource);
offset += offset % 4 == 0 ? 0 : 4 - (offset % 4);
s.Value = Encoding.Unicode.GetString(content, offset, s.ValueLength * 2); offset += s.ValueLength * 2;
return s;
}
}
}

View File

@@ -0,0 +1,61 @@
using System.Collections.Generic;
using System.IO;
namespace BurnOutSharp.ExecutableType.Microsoft.Resources
{
public class StringTable : Resource
{
/// <summary>
/// An array of one or more String structures.
/// </summary>
public StringStruct[] Children;
public StringTable(Resource resource)
{
this.Length = resource?.Length ?? default;
this.ValueLength = resource?.ValueLength ?? default;
this.Type = resource?.Type ?? default;
this.Key = resource?.Key ?? default;
}
public static new StringTable Deserialize(Stream stream)
{
long originalPosition = stream.Position;
Resource resource = Resource.Deserialize(stream);
if (resource.Key.Length != 8)
return null;
StringTable st = new StringTable(resource);
var tempValue = new List<StringStruct>();
while (stream.Position - originalPosition < st.Length)
{
tempValue.Add(StringStruct.Deserialize(stream));
}
st.Children = tempValue.ToArray();
return st;
}
public static new StringTable Deserialize(byte[] content, ref int offset)
{
int originalPosition = offset;
Resource resource = Resource.Deserialize(content, ref offset);
if (resource.Key.Length != 8)
return null;
StringTable st = new StringTable(resource);
var tempValue = new List<StringStruct>();
while (offset - originalPosition < st.Length)
{
tempValue.Add(StringStruct.Deserialize(content, ref offset));
}
st.Children = tempValue.ToArray();
return st;
}
}
}

View File

@@ -0,0 +1,67 @@
using System.Collections.Generic;
using System.IO;
namespace BurnOutSharp.ExecutableType.Microsoft.Resources
{
public class Var : Resource
{
/// <summary>
/// An array of one or more values that are language and code page identifier pairs.
///
/// If you use the Var structure to list the languages your application or DLL supports instead of using multiple version resources,
/// use the Value member to contain an array of DWORD values indicating the language and code page combinations supported by this file.
/// The low-order word of each DWORD must contain a Microsoft language identifier, and the high-order word must contain the IBM code page number.
/// Either high-order or low-order word can be zero, indicating that the file is language or code page independent.
/// If the Var structure is omitted, the file will be interpreted as both language and code page independent.
/// </summary>
public LanguageCodePage[] Value;
public Var(Resource resource)
{
this.Length = resource?.Length ?? default;
this.ValueLength = resource?.ValueLength ?? default;
this.Type = resource?.Type ?? default;
this.Key = resource?.Key ?? default;
}
public static new Var Deserialize(Stream stream)
{
long originalPosition = stream.Position;
Resource resource = Resource.Deserialize(stream);
if (resource.Key != "Translation")
return null;
Var v = new Var(resource);
var tempValue = new List<LanguageCodePage>();
while (stream.Position - originalPosition < v.Length)
{
tempValue.Add(LanguageCodePage.Deserialize(stream));
}
v.Value = tempValue.ToArray();
return v;
}
public static new Var Deserialize(byte[] content, ref int offset)
{
int originalPosition = offset;
Resource resource = Resource.Deserialize(content, ref offset);
if (resource.Key != "Translation")
return null;
Var v = new Var(resource);
var tempValue = new List<LanguageCodePage>();
while (offset - originalPosition < v.Length)
{
tempValue.Add(LanguageCodePage.Deserialize(content, ref offset));
}
v.Value = tempValue.ToArray();
return v;
}
}
}

View File

@@ -0,0 +1,44 @@
using System.IO;
namespace BurnOutSharp.ExecutableType.Microsoft.Resources
{
public class VarFileInfo : Resource
{
/// <summary>
/// Typically contains a list of languages that the application or DLL supports.
/// </summary>
public Var Children;
public VarFileInfo(Resource resource)
{
this.Length = resource?.Length ?? default;
this.ValueLength = resource?.ValueLength ?? default;
this.Type = resource?.Type ?? default;
this.Key = resource?.Key ?? default;
}
public static new VarFileInfo Deserialize(Stream stream)
{
Resource resource = Resource.Deserialize(stream);
if (resource.Key != "VarFileInfo")
return null;
VarFileInfo vfi = new VarFileInfo(resource);
vfi.Children = Var.Deserialize(stream);
return vfi;
}
public static new VarFileInfo Deserialize(byte[] content, ref int offset)
{
Resource resource = Resource.Deserialize(content, ref offset);
if (resource.Key != "VarFileInfo")
return null;
VarFileInfo vfi = new VarFileInfo(resource);
vfi.Children = Var.Deserialize(content, ref offset);
return vfi;
}
}
}

View File

@@ -0,0 +1,129 @@
using System.IO;
namespace BurnOutSharp.ExecutableType.Microsoft.Resources
{
public class VersionInfo : Resource
{
/// <summary>
/// Arbitrary data associated with this VS_VERSIONINFO structure.
/// The wValueLength member specifies the length of this member;
/// if wValueLength is zero, this member does not exist.
/// </summary>
public FixedFileInfo Value;
/// <summary>
/// An array of zero or one StringFileInfo structures, and zero or one VarFileInfo structures
/// that are children of the current VS_VERSIONINFO structure.
/// </summary>
public StringFileInfo ChildrenStringFileInfo;
/// <summary>
/// An array of zero or one StringFileInfo structures, and zero or one VarFileInfo structures
/// that are children of the current VS_VERSIONINFO structure.
/// </summary>
public VarFileInfo ChildrenVarFileInfo;
public VersionInfo(Resource resource)
{
this.Length = resource?.Length ?? default;
this.ValueLength = resource?.ValueLength ?? default;
this.Type = resource?.Type ?? default;
this.Key = resource?.Key ?? default;
}
public static new VersionInfo Deserialize(Stream stream)
{
long originalPosition = stream.Position;
Resource resource = Resource.Deserialize(stream);
if (resource.Key != "VS_VERSION_INFO")
return null;
VersionInfo vi = new VersionInfo(resource);
if (vi.ValueLength > 0)
vi.Value = FixedFileInfo.Deserialize(stream);
if (stream.Position - originalPosition > vi.Length)
return vi;
long preChildOffset = stream.Position;
Resource firstChild = Resource.Deserialize(stream);
if (firstChild.Key == "StringFileInfo")
{
stream.Seek(preChildOffset, SeekOrigin.Begin);
vi.ChildrenStringFileInfo = StringFileInfo.Deserialize(stream);
}
else if (firstChild.Key == "VarFileInfo")
{
stream.Seek(preChildOffset, SeekOrigin.Begin);
vi.ChildrenVarFileInfo = VarFileInfo.Deserialize(stream);
}
if (stream.Position - originalPosition > vi.Length)
return vi;
preChildOffset = stream.Position;
Resource secondChild = Resource.Deserialize(stream);
if (secondChild.Key == "StringFileInfo")
{
stream.Seek(preChildOffset, SeekOrigin.Begin);
vi.ChildrenStringFileInfo = StringFileInfo.Deserialize(stream);
}
else if (secondChild.Key == "VarFileInfo")
{
stream.Seek(preChildOffset, SeekOrigin.Begin);
vi.ChildrenVarFileInfo = VarFileInfo.Deserialize(stream);
}
return vi;
}
public static new VersionInfo Deserialize(byte[] content, ref int offset)
{
int originalOffset = offset;
Resource resource = Resource.Deserialize(content, ref offset);
if (resource.Key != "VS_VERSION_INFO")
return null;
VersionInfo vi = new VersionInfo(resource);
if (vi.ValueLength > 0)
vi.Value = FixedFileInfo.Deserialize(content, ref offset);
if (offset - originalOffset > vi.Length)
return vi;
int preChildOffset = offset;
Resource firstChild = Resource.Deserialize(content, ref offset);
if (firstChild.Key == "StringFileInfo")
{
offset = preChildOffset;
vi.ChildrenStringFileInfo = StringFileInfo.Deserialize(content, ref offset);
}
else if (firstChild.Key == "VarFileInfo")
{
offset = preChildOffset;
vi.ChildrenVarFileInfo = VarFileInfo.Deserialize(content, ref offset);
}
if (offset - originalOffset > vi.Length)
return vi;
preChildOffset = offset;
Resource secondChild = Resource.Deserialize(content, ref offset);
if (secondChild.Key == "StringFileInfo")
{
offset = preChildOffset;
vi.ChildrenStringFileInfo = StringFileInfo.Deserialize(content, ref offset);
}
else if (secondChild.Key == "VarFileInfo")
{
offset = preChildOffset;
vi.ChildrenVarFileInfo = VarFileInfo.Deserialize(content, ref offset);
}
return vi;
}
}
}

View File

@@ -1,75 +0,0 @@
/*
* NEWEXE.H (C) Copyright Microsoft Corp 1984-1987
*
* Data structure definitions for the OS/2 & Windows
* executable file format.
*
* Modified by IVS on 24-Jan-1991 for Resource DeCompiler
* (C) Copyright IVS 1991
*
* http://csn.ul.ie/~caolan/pub/winresdump/winresdump/newexe.h
*/
using System.IO;
using System.Runtime.InteropServices;
namespace BurnOutSharp.ExecutableType.Microsoft
{
/// <summary>
/// Resource name information block
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal class RsrcNameInfo
{
/*
* The following two fields must be shifted left by the value of
* the rs_align field to compute their actual value. This allows
* resources to be larger than 64k, but they do not need to be
* aligned on 512 byte boundaries, the way segments are.
*/
/// <summary>
/// File offset to resource data
/// </summary>
public ushort Offset;
/// <summary>
/// Length of resource data
/// </summary>
public ushort Length;
/// <summary>
/// Resource flags
/// </summary>
public ushort Flags;
/// <summary>
/// Resource name id
/// </summary>
public ushort NameID;
/// <summary>
/// If loaded, then global handle
/// </summary>
public ushort Handle;
/// <summary>
/// Initially zero. Number of times the handle for this resource has been given out
/// </summary>
public ushort UsageCount;
public static RsrcNameInfo Deserialize(Stream stream)
{
var rni = new RsrcNameInfo();
rni.Offset = stream.ReadUInt16();
rni.Length = stream.ReadUInt16();
rni.Flags = stream.ReadUInt16();
rni.NameID = stream.ReadUInt16();
rni.Handle = stream.ReadUInt16();
rni.UsageCount = stream.ReadUInt16();
return rni;
}
}
}

View File

@@ -1,46 +0,0 @@
/*
* NEWEXE.H (C) Copyright Microsoft Corp 1984-1987
*
* Data structure definitions for the OS/2 & Windows
* executable file format.
*
* Modified by IVS on 24-Jan-1991 for Resource DeCompiler
* (C) Copyright IVS 1991
*
* http://csn.ul.ie/~caolan/pub/winresdump/winresdump/newexe.h
*/
using System.IO;
using System.Runtime.InteropServices;
namespace BurnOutSharp.ExecutableType.Microsoft
{
/// <summary>
/// Resource type or name string
/// </summary>
/// TODO: Fix this because SizeConst = 0 is not valid
[StructLayout(LayoutKind.Sequential)]
internal class RsrcString
{
/// <summary>
/// Number of bytes in string
/// </summary>
public byte Length;
/// <summary>
/// Next of string
/// </summary>
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 0)]
public char[] Text;
public static RsrcString Deserialize(Stream stream)
{
var rs = new RsrcString();
rs.Length = stream.ReadByteValue();
rs.Text = stream.ReadChars(rs.Length);
return rs;
}
}
}

View File

@@ -1,39 +0,0 @@
/*
* NEWEXE.H (C) Copyright Microsoft Corp 1984-1987
*
* Data structure definitions for the OS/2 & Windows
* executable file format.
*
* Modified by IVS on 24-Jan-1991 for Resource DeCompiler
* (C) Copyright IVS 1991
*
* http://csn.ul.ie/~caolan/pub/winresdump/winresdump/newexe.h
*/
using System.IO;
using System.Runtime.InteropServices;
namespace BurnOutSharp.ExecutableType.Microsoft
{
/// <summary>
/// Resource type information block
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal class RsrcTypeInfo
{
public ushort ID;
public ushort rt_nres;
public uint rt_proc;
public static RsrcTypeInfo Deserialize(Stream stream)
{
var rti = new RsrcTypeInfo();
rti.ID = stream.ReadUInt16();
rti.rt_nres = stream.ReadUInt16();
rti.rt_proc = stream.ReadUInt32();
return rti;
}
}
}

View File

@@ -1,38 +0,0 @@
/*
* NEWEXE.H (C) Copyright Microsoft Corp 1984-1987
*
* Data structure definitions for the OS/2 & Windows
* executable file format.
*
* Modified by IVS on 24-Jan-1991 for Resource DeCompiler
* (C) Copyright IVS 1991
*
* http://csn.ul.ie/~caolan/pub/winresdump/winresdump/newexe.h
*/
using System.IO;
using System.Runtime.InteropServices;
namespace BurnOutSharp.ExecutableType.Microsoft
{
[StructLayout(LayoutKind.Sequential)]
internal class TYPEINFO
{
public ushort TypeID;
public ushort ResourceCount;
public uint Reserved;
public NAMEINFO NameInfo;
public static TYPEINFO Deserialize(Stream stream)
{
var ti = new TYPEINFO();
ti.TypeID = stream.ReadUInt16();
ti.ResourceCount = stream.ReadUInt16();
ti.Reserved = stream.ReadUInt32();
ti.NameInfo = NAMEINFO.Deserialize(stream);
return ti;
}
}
}

View File

@@ -1,109 +0,0 @@
using System;
using System.IO;
using System.Text;
namespace BurnOutSharp
{
internal static class Ebuffertensions
{
/// <summary>
/// Read a byte from the stream
/// </summary>
public static byte ReadByteValue(this Stream stream)
{
byte[] buffer = new byte[1];
stream.Read(buffer, 0, 1);
return buffer[0];
}
/// <summary>
/// Read a byte array from the stream
/// </summary>
public static byte[] ReadBytes(this Stream stream, int count)
{
byte[] buffer = new byte[count];
stream.Read(buffer, 0, count);
return buffer;
}
/// <summary>
/// Read a character from the stream
/// </summary>
public static char ReadChar(this Stream stream)
{
byte[] buffer = new byte[1];
stream.Read(buffer, 0, 1);
return (char)buffer[0];
}
/// <summary>
/// Read a character array from the stream
/// </summary>
public static char[] ReadChars(this Stream stream, int count)
{
byte[] buffer = new byte[count];
stream.Read(buffer, 0, count);
return Encoding.Default.GetString(buffer).ToCharArray();
}
/// <summary>
/// Read a short from the stream
/// </summary>
public static short ReadInt16(this Stream stream)
{
byte[] buffer = new byte[2];
stream.Read(buffer, 0, 2);
return BitConverter.ToInt16(buffer, 0);
}
/// <summary>
/// Read a ushort from the stream
/// </summary>
public static ushort ReadUInt16(this Stream stream)
{
byte[] buffer = new byte[2];
stream.Read(buffer, 0, 2);
return BitConverter.ToUInt16(buffer, 0);
}
/// <summary>
/// Read an int from the stream
/// </summary>
public static int ReadInt32(this Stream stream)
{
byte[] buffer = new byte[4];
stream.Read(buffer, 0, 4);
return BitConverter.ToInt32(buffer, 0);
}
/// <summary>
/// Read a uint from the stream
/// </summary>
public static uint ReadUInt32(this Stream stream)
{
byte[] buffer = new byte[4];
stream.Read(buffer, 0, 4);
return BitConverter.ToUInt32(buffer, 0);
}
/// <summary>
/// Read a long from the stream
/// </summary>
public static long ReadInt64(this Stream stream)
{
byte[] buffer = new byte[8];
stream.Read(buffer, 0, 8);
return BitConverter.ToInt64(buffer, 0);
}
/// <summary>
/// Read a ulong from the stream
/// </summary>
public static ulong ReadUInt64(this Stream stream)
{
byte[] buffer = new byte[8];
stream.Read(buffer, 0, 8);
return BitConverter.ToUInt64(buffer, 0);
}
}
}

View File

@@ -2,12 +2,13 @@
using System.Collections.Concurrent;
using System.IO;
using System.Text;
using BurnOutSharp.Tools;
using SharpCompress.Compressors;
using SharpCompress.Compressors.Deflate;
namespace BurnOutSharp.FileType
{
internal class BFPK : IScannable
public class BFPK : IScannable
{
/// <inheritdoc/>
public bool ShouldScan(byte[] magic)

View File

@@ -1,13 +1,13 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.Tools;
using SharpCompress.Compressors;
using SharpCompress.Compressors.BZip2;
namespace BurnOutSharp.FileType
{
internal class BZip2 : IScannable
public class BZip2 : IScannable
{
/// <inheritdoc/>
public bool ShouldScan(byte[] magic)

View File

@@ -6,16 +6,29 @@ using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using BurnOutSharp.ExecutableType.Microsoft.NE;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Tools;
namespace BurnOutSharp.FileType
{
internal class Executable : IScannable
public class Executable : IScannable
{
/// <summary>
/// Cache for all IContentCheck types
/// </summary>
private static readonly IEnumerable<IContentCheck> contentCheckClasses = InitContentCheckClasses();
/// <summary>
/// Cache for all INEContentCheck types
/// </summary>
private static readonly IEnumerable<INEContentCheck> neContentCheckClasses = InitNEContentCheckClasses();
/// <summary>
/// Cache for all IPEContentCheck types
/// </summary>
private static readonly IEnumerable<IPEContentCheck> peContentCheckClasses = InitPEContentCheckClasses();
/// <inheritdoc/>
public bool ShouldScan(byte[] magic)
{
@@ -68,53 +81,104 @@ namespace BurnOutSharp.FileType
// Files can be protected in multiple ways
var protections = new ConcurrentDictionary<string, ConcurrentQueue<string>>();
// Load the current file content
// Load the current file content for debug only
byte[] fileContent = null;
try
if (scanner.IncludeDebug)
{
using (BinaryReader br = new BinaryReader(stream, Encoding.Default, true))
try
{
fileContent = br.ReadBytes((int)stream.Length);
}
}
catch
{
Utilities.AppendToDictionary(protections, file, "[File too large to be scanned]");
return protections;
}
// If we can, seek to the beginning of the stream
if (stream.CanSeek)
stream.Seek(0, SeekOrigin.Begin);
// Iterate through all content checks
Parallel.ForEach(contentCheckClasses, contentCheckClass =>
{
string protection = contentCheckClass.CheckContents(file, fileContent, scanner.IncludePosition);
// If we have a valid content check based on settings
if (!contentCheckClass.GetType().Namespace.ToLowerInvariant().Contains("packertype") || scanner.ScanPackers)
{
if (!string.IsNullOrWhiteSpace(protection))
Utilities.AppendToDictionary(protections, file, protection);
}
// If we have an IScannable implementation
if (contentCheckClass is IScannable)
{
IScannable scannable = contentCheckClass as IScannable;
if (file != null && !string.IsNullOrEmpty(protection))
using (BinaryReader br = new BinaryReader(stream, Encoding.Default, true))
{
var subProtections = scannable.Scan(scanner, null, file);
Utilities.PrependToKeys(subProtections, file);
Utilities.AppendToDictionary(protections, subProtections);
fileContent = br.ReadBytes((int)stream.Length);
}
}
});
catch
{
Utilities.AppendToDictionary(protections, file, "[Out of memory attempting to open]");
return protections;
}
}
// Create PortableExecutable and NewExecutable objects for use in the checks
stream.Seek(0, SeekOrigin.Begin);
PortableExecutable pex = new PortableExecutable(stream);
stream.Seek(0, SeekOrigin.Begin);
NewExecutable nex = new NewExecutable(stream);
stream.Seek(0, SeekOrigin.Begin);
// Iterate through all generic content checks
if (fileContent != null)
{
Parallel.ForEach(contentCheckClasses, contentCheckClass =>
{
string protection = contentCheckClass.CheckContents(file, fileContent, scanner.IncludeDebug, pex, nex);
if (ShouldAddProtection(contentCheckClass, scanner, protection))
Utilities.AppendToDictionary(protections, file, protection);
// If we have an IScannable implementation
if (contentCheckClass is IScannable scannable)
{
if (file != null && !string.IsNullOrEmpty(protection))
{
var subProtections = scannable.Scan(scanner, null, file);
Utilities.PrependToKeys(subProtections, file);
Utilities.AppendToDictionary(protections, subProtections);
}
}
});
}
// If we have a NE executable, iterate through all NE content checks
if (nex?.Initialized == true)
{
Parallel.ForEach(neContentCheckClasses, contentCheckClass =>
{
// Check using custom content checks first
string protection = contentCheckClass.CheckNEContents(file, nex, scanner.IncludeDebug);
if (ShouldAddProtection(contentCheckClass, scanner, protection))
Utilities.AppendToDictionary(protections, file, protection);
// If we have an IScannable implementation
if (contentCheckClass is IScannable scannable)
{
if (file != null && !string.IsNullOrEmpty(protection))
{
var subProtections = scannable.Scan(scanner, null, file);
Utilities.PrependToKeys(subProtections, file);
Utilities.AppendToDictionary(protections, subProtections);
}
}
});
}
// If we have a PE executable, iterate through all PE content checks
if (pex?.Initialized == true)
{
Parallel.ForEach(peContentCheckClasses, contentCheckClass =>
{
// Check using custom content checks first
string protection = contentCheckClass.CheckPEContents(file, pex, scanner.IncludeDebug);
if (ShouldAddProtection(contentCheckClass, scanner, protection))
Utilities.AppendToDictionary(protections, file, protection);
// If we have an IScannable implementation
if (contentCheckClass is IScannable scannable)
{
if (file != null && !string.IsNullOrEmpty(protection))
{
var subProtections = scannable.Scan(scanner, null, file);
Utilities.PrependToKeys(subProtections, file);
Utilities.AppendToDictionary(protections, subProtections);
}
}
});
}
return protections;
}
#region Helpers
/// <summary>
/// Initialize all IContentCheck implementations
/// </summary>
@@ -124,5 +188,81 @@ namespace BurnOutSharp.FileType
.Where(t => t.IsClass && t.GetInterface(nameof(IContentCheck)) != null)
.Select(t => Activator.CreateInstance(t) as IContentCheck);
}
/// <summary>
/// Initialize all INEContentCheck implementations
/// </summary>
private static IEnumerable<INEContentCheck> InitNEContentCheckClasses()
{
return Assembly.GetExecutingAssembly().GetTypes()
.Where(t => t.IsClass && t.GetInterface(nameof(INEContentCheck)) != null)
.Select(t => Activator.CreateInstance(t) as INEContentCheck);
}
/// <summary>
/// Initialize all IPEContentCheck implementations
/// </summary>
private static IEnumerable<IPEContentCheck> InitPEContentCheckClasses()
{
return Assembly.GetExecutingAssembly().GetTypes()
.Where(t => t.IsClass && t.GetInterface(nameof(IPEContentCheck)) != null)
.Select(t => Activator.CreateInstance(t) as IPEContentCheck);
}
/// <summary>
/// Check to see if a protection should be added or not
/// </summary>
/// <param name="contentCheckClass">Class that was last used to check</param>
/// <param name="scanner">Scanner object for state tracking</param>
/// <param name="protection">The protection result to be checked</param>
private bool ShouldAddProtection(IContentCheck contentCheckClass, Scanner scanner, string protection)
{
// If we have a valid content check based on settings
if (!contentCheckClass.GetType().Namespace.ToLowerInvariant().Contains("packertype") || scanner.ScanPackers)
{
if (!string.IsNullOrWhiteSpace(protection))
return true;
}
return false;
}
/// <summary>
/// Check to see if a protection should be added or not
/// </summary>
/// <param name="neContentCheckClass">Class that was last used to check</param>
/// <param name="scanner">Scanner object for state tracking</param>
/// <param name="protection">The protection result to be checked</param>
private bool ShouldAddProtection(INEContentCheck neContentCheckClass, Scanner scanner, string protection)
{
// If we have a valid content check based on settings
if (!neContentCheckClass.GetType().Namespace.ToLowerInvariant().Contains("packertype") || scanner.ScanPackers)
{
if (!string.IsNullOrWhiteSpace(protection))
return true;
}
return false;
}
/// <summary>
/// Check to see if a protection should be added or not
/// </summary>
/// <param name="peContentCheckClass">Class that was last used to check</param>
/// <param name="scanner">Scanner object for state tracking</param>
/// <param name="protection">The protection result to be checked</param>
private bool ShouldAddProtection(IPEContentCheck peContentCheckClass, Scanner scanner, string protection)
{
// If we have a valid content check based on settings
if (!peContentCheckClass.GetType().Namespace.ToLowerInvariant().Contains("packertype") || scanner.ScanPackers)
{
if (!string.IsNullOrWhiteSpace(protection))
return true;
}
return false;
}
#endregion
}
}

View File

@@ -1,13 +1,13 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.Tools;
using SharpCompress.Archives;
using SharpCompress.Archives.GZip;
namespace BurnOutSharp.FileType
{
internal class GZIP : IScannable
public class GZIP : IScannable
{
/// <inheritdoc/>
public bool ShouldScan(byte[] magic)

View File

@@ -3,11 +3,12 @@ using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using BurnOutSharp.Tools;
using UnshieldSharp.Archive;
namespace BurnOutSharp.FileType
{
internal class InstallShieldArchiveV3 : IScannable
public class InstallShieldArchiveV3 : IScannable
{
/// <inheritdoc/>
public bool ShouldScan(byte[] magic)

View File

@@ -2,11 +2,12 @@
using System.Collections.Concurrent;
using System.IO;
using System.Text.RegularExpressions;
using BurnOutSharp.Tools;
using UnshieldSharp.Cabinet;
namespace BurnOutSharp.FileType
{
internal class InstallShieldCAB : IScannable
public class InstallShieldCAB : IScannable
{
/// <inheritdoc/>
public bool ShouldScan(byte[] magic)

View File

@@ -1,12 +1,12 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.Tools;
using StormLibSharp;
namespace BurnOutSharp.FileType
{
internal class MPQ : IScannable
public class MPQ : IScannable
{
/// <inheritdoc/>
public bool ShouldScan(byte[] magic)

View File

@@ -1,12 +1,12 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.Tools;
using WixToolset.Dtf.WindowsInstaller;
namespace BurnOutSharp.FileType
{
internal class MSI : IScannable
public class MSI : IScannable
{
/// <inheritdoc/>
public bool ShouldScan(byte[] magic)

View File

@@ -1,13 +1,13 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.Tools;
using LibMSPackN;
namespace BurnOutSharp.FileType
{
// Specification available at http://download.microsoft.com/download/5/0/1/501ED102-E53F-4CE0-AA6B-B0F93629DDC6/Exchange/%5BMS-CAB%5D.pdf
internal class MicrosoftCAB : IScannable
public class MicrosoftCAB : IScannable
{
/// <inheritdoc/>
public bool ShouldScan(byte[] magic)

View File

@@ -1,13 +1,13 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.Tools;
using SharpCompress.Archives;
using SharpCompress.Archives.Zip;
namespace BurnOutSharp.FileType
{
internal class PKZIP : IScannable
public class PKZIP : IScannable
{
/// <inheritdoc/>
public bool ShouldScan(byte[] magic)

View File

@@ -1,13 +1,13 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.Tools;
using SharpCompress.Archives;
using SharpCompress.Archives.Rar;
namespace BurnOutSharp.FileType
{
internal class RAR : IScannable
public class RAR : IScannable
{
/// <inheritdoc/>
public bool ShouldScan(byte[] magic)

View File

@@ -1,13 +1,13 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.Tools;
using SharpCompress.Archives;
using SharpCompress.Archives.SevenZip;
namespace BurnOutSharp.FileType
{
internal class SevenZip : IScannable
public class SevenZip : IScannable
{
/// <inheritdoc/>
public bool ShouldScan(byte[] magic)

View File

@@ -1,13 +1,13 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.Tools;
using SharpCompress.Archives;
using SharpCompress.Archives.Tar;
namespace BurnOutSharp.FileType
{
internal class TapeArchive : IScannable
public class TapeArchive : IScannable
{
/// <inheritdoc/>
public bool ShouldScan(byte[] magic)

View File

@@ -1,12 +1,12 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Text;
using BurnOutSharp.Tools;
namespace BurnOutSharp.FileType
{
internal class Textfile : IScannable
public class Textfile : IScannable
{
/// <inheritdoc/>
public bool ShouldScan(byte[] magic)
@@ -82,6 +82,16 @@ namespace BurnOutSharp.FileType
if (fileContent.Contains("MediaMax technology"))
Utilities.AppendToDictionary(protections, file, "MediaMax CD-3");
// The full line from a sample is as follows:
//
// The files securom_v7_01.dat and securom_v7_01.bak have been created during the installation of a SecuROM protected application.
//
// TODO: Use the filenames in this line to get the version out of it
// SecuROM
if (fileContent.Contains("SecuROM protected application"))
Utilities.AppendToDictionary(protections, file, "SecuROM");
// XCP
if (fileContent.Contains("http://cp.sonybmg.com/xcp/"))
Utilities.AppendToDictionary(protections, file, "XCP");

File diff suppressed because it is too large Load Diff

View File

@@ -1,12 +1,12 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.Tools;
using SharpCompress.Compressors.Xz;
namespace BurnOutSharp.FileType
{
internal class XZ : IScannable
public class XZ : IScannable
{
/// <inheritdoc/>
public bool ShouldScan(byte[] magic)

View File

@@ -1,15 +1,21 @@
namespace BurnOutSharp
using BurnOutSharp.ExecutableType.Microsoft.NE;
using BurnOutSharp.ExecutableType.Microsoft.PE;
namespace BurnOutSharp
{
// TODO: This should either include an override that takes a Stream instead of the byte[]
// TODO: This should be retired in lieu of the I*ContentCheck interfaces
internal interface IContentCheck
{
/// <summary>
/// Check a path for protections based on file contents
/// </summary>
/// <param name="pex">PortableExecutable representing the read-in file</param>
/// <param name="file">File to check for protection indicators</param>
/// <param name="fileContent">Byte array representing the file contents</param>
/// <param name="includePosition">True to include positional data, false otherwise</param>
/// <param name="includeDebug">True to include debug data, false otherwise</param>
/// <returns>String containing any protections found in the file</returns>
/// TODO: This should be replaced with a "GenerateMatchers" that produces a list of matchers to be run instead
string CheckContents(string file, byte[] fileContent, bool includePosition);
/// <remarks>This still includes PE and NE because this is primarily used for debug testing</remarks>
string CheckContents(string file, byte[] fileContent, bool includeDebug, PortableExecutable pex, NewExecutable nex);
}
}

View File

@@ -0,0 +1,17 @@
using BurnOutSharp.ExecutableType.Microsoft.NE;
namespace BurnOutSharp
{
// TODO: This should either include an override that takes a Stream instead of the byte[]
internal interface INEContentCheck
{
/// <summary>
/// Check a path for protections based on file contents
/// </summary>
/// <param name="file">File to check for protection indicators</param>
/// <param name="nex">NewExecutable representing the read-in file</param>
/// <param name="includeDebug">True to include debug data, false otherwise</param>
/// <returns>String containing any protections found in the file</returns>
string CheckNEContents(string file, NewExecutable nex, bool includeDebug);
}
}

View File

@@ -0,0 +1,17 @@
using BurnOutSharp.ExecutableType.Microsoft.PE;
namespace BurnOutSharp
{
// TODO: This should either include an override that takes a Stream instead of the byte[]
internal interface IPEContentCheck
{
/// <summary>
/// Check a path for protections based on file contents
/// </summary>
/// <param name="file">File to check for protection indicators</param>
/// <param name="includeDebug">True to include debug data, false otherwise</param>
/// <param name="pex">PortableExecutable representing the read-in file</param>
/// <returns>String containing any protections found in the file</returns>
string CheckPEContents(string file, PortableExecutable pex, bool includeDebug);
}
}

View File

@@ -3,7 +3,7 @@ namespace BurnOutSharp.Matching
/// <summary>
/// Content matching criteria
/// </summary>
internal class ContentMatch : IMatch<byte?[]>
public class ContentMatch : IMatch<byte?[]>
{
/// <summary>
/// Content to match

View File

@@ -7,7 +7,7 @@ namespace BurnOutSharp.Matching
/// <summary>
/// A set of content matches that work together
/// </summary>
internal class ContentMatchSet : MatchSet<ContentMatch, byte?[]>
public class ContentMatchSet : MatchSet<ContentMatch, byte?[]>
{
/// <summary>
/// Function to get a content version

View File

@@ -1,6 +1,6 @@
namespace BurnOutSharp.Matching
{
internal interface IMatch<T>
public interface IMatch<T>
{
T Needle { get; set; }
}

View File

@@ -5,7 +5,7 @@ namespace BurnOutSharp.Matching
/// <summary>
/// Wrapper for a single set of matching criteria
/// </summary>
internal abstract class MatchSet<T, U> where T : IMatch<U>
public abstract class MatchSet<T, U> where T : IMatch<U>
{
/// <summary>
/// Set of all matchers

Some files were not shown because too many files have changed in this diff Show More