CasualX / pelite

Lightweight, memory-safe, zero-allocation library for reading and navigating PE binaries.
MIT License
280 stars 42 forks source link

Get &[u8] or Vec<u8>. #272

Closed Paradist closed 12 months ago

Paradist commented 12 months ago

I want to get back &[u8] or Vec containing the .exe binary code from pe and then save that to a file..

let file = FileMap::open("./name.exe").unwrap();
let mut pe = PeFile::from_bytes(file.as_ref()).unwrap();

I tried:

pe.image()

But it produces a value 900 +- bytes larger than the original.

Help me, please. Thank you in advance.

Paradist commented 12 months ago

And how can I edit the certificate, versions, and resources?

CasualX commented 12 months ago

This library is not designed to let you edit the file conveniently.

To get the original bytes, just go back to the original file:

let file = FileMap::open("./name.exe").unwrap();
let mut pe = PeFile::from_bytes(file.as_ref()).unwrap();
// Do things with pe...
let bytes = file.as_ref();

PeFile and friends just lightly wrap a &[u8], you are not meant to store these types long term (recreate them if necessary). Simply access the underlying storage.

FileMap is a readonly view over the file, so if you wish to modify the bytes you have to use std::fs::read to read the contents into a Vec then process that. After you have done your processing, collect all the edits you wish to make and apply them after the wrappers (like PeFile) are no longer used then save the resulting Vec back to disk with std::fs::write.

I wish to put emphasis on the fact that you cannot edit the data while you have a PeFile instance live. Instead collect the edits (eg. a Vec<FileOffset, Vec<u8>>) and after you are done loop over this and apply the patches directly to the file.