What I am trying to do is calculate the size of a PE through it's headers. I am using WinDbg's Javascripting and in this case, it will mostly be for drivers. The idea is to dump a driver from memory through WinDbg and I can do it by dumping the BaseAddress to BaseAddress+ImageSize. The ImageSize isn't really the actual size of it on disk and I would like it to be as similar as possible, almost like copy/pasting.
I found this post: https://stackoverflow.com/questions/29587560/self-inspection-of-the-pe-format I am able to get the full size on one driver, easily:
0: kd> !dh HEVD
--snipped--
SECTION HEADER #7
.reloc name
14 virtual size
8B000 virtual address
200 size of raw data
6E00 file pointer to raw data
0: kd> ? 8b000 + 14
Evaluate expression: 569364 = 00000000`0008b014
0: kd> ? 6e00 + 200
Evaluate expression: 28672 = 00000000`00007000
The person mentioned that you should add the highest value for PointerToRawData against the SizeOfRawData, which is usually the last section. The size for this particular driver is 28,672 bytes but this doesn't always work for all drivers.
Here's an example of where it doesn't work:
0: kd> !dh RTCore64
--snipped--
400 size of headers
--snipped--
SECTION HEADER #5
INIT name
258 virtual size
5000 virtual address
400 size of raw data
1600 file pointer to raw data
0 file pointer to relocation table
0 file pointer to line numbers
0 number of relocations
0 number of line numbers
E2000020 flags
Code
Discardable
(no align specified)
Execute Read Write
0: kd> ? 1600 + 400
Evaluate expression: 6656 = 00000000`00001a00
The file size for this particular driver is 16,384 bytes on disk and 14,024 bytes regular size.
Then I found this post: https://stackoverflow.com/questions/34684660/how-to-determine-the-size-of-an-pe-executable-file-from-headers-and-or-footers It was saying to add the size of headers against the SizeOfRawData for each section. That didn't work.
0: kd> ? 400 + c00 + 200 + 200 + 200 + 400
Evaluate expression: 6656 = 00000000`00001a00
I also tried this answer: https://stackoverflow.com/questions/8197134/how-do-i-determine-exact-pe-image-file-size-using-its-headers Basically it was said to add the VirtualAddress against VirtualSize, but that doesn't work. It actually gives me a number that's higher than what the actual size is.
0: kd> ? 5000 + 258
Evaluate expression: 21080 = 00000000`00005258
I also tried with this post: https://stackoverflow.com/questions/8193862/the-size-of-a-pe-header That also didn't work. There were other posts I looked at, but they all boil down to some variation of those.
Can I get help on why I am unable to? I'm not sure what I'm missing.
Thank you in advance
Also, if you would recommend a better way of doing so, I'm all ears!