How UPX unpacking works
upx::try_unpack follows UPX’s published source for the format.
- Find the header. Search for
UPX!followed by a plausible 32-byte header: format 9 (32-bit Windows program) or 36 (64-bit), with compressed and unpacked sizes that fit. - Decompress. The method byte chooses the decoder: NRV2B, NRV2D or NRV2E, each in a 32-bit or 8-bit bit-buffer variant, or LZMA. LZMA as stored by UPX is two bytes of settings followed by a raw stream. The Adler-32 checksum of the result is compared with the one in the header.
- Read the saved header. The last four bytes of the unpacked block give the offset of the original program header and section table, which UPX stored at the end.
- Undo the filter. UPX rewrites the relative addresses in
callandjmpinstructions as absolute, big-endian values tagged with a marker byte, because that compresses better. Filters0x11to0x16,0x24to0x26,0x46and0x49are reversed.0x49also covers conditional jumps. - Rebuild imports. UPX keeps a compact list: for each DLL, where its name is, where its address table goes, then the function names. DLL names are read from the packed file’s own small import table.
- Restore addresses. UPX turned every absolute address in the program into an offset stored backwards. Its compact list of positions is walked and each one is turned back into a real address.
- Hand over. The result is laid out as a program whose file layout equals its memory layout and passed to the normal reader, with the rebuilt import list supplied separately.
Not handled: UPX’s --exact mode, files with the marker removed, and restoring resources or exports.