zyantific / zydis

Fast and lightweight x86/x86-64 disassembler and code generation library
https://zydis.re
MIT License
3.4k stars 434 forks source link

Encoder fails to enforce predicted instruction size in some scenarios #478

Closed mappzor closed 8 months ago

mappzor commented 8 months ago

ZydisEncoderEncodeInstructionAbsolute correctly predicts instruction sizes but if no relevant hint is provided it does nothing to enforce predicted instruction size. Usually this isn't an issue as size of immediate is enough to enforce correct variant. This however isn't sufficient for some edge cases where change of instruction size causes relative operand to fit into a smaller variant.

Example: jz instruction is meant to be placed at 0x4000 and is supposed to jump to 0x4082. 2-byte instruction (opcode + 8 bits of relative operand) can reach up to 0x4000+2+0x7F=0x4081, so encoder predicts 6 bytes for jump instruction. Relative operand gets adjusted to 0x4082-(0x4000+6)=0x7C but 0x7C <= 0x7F, so encoder will encode 2-byte instruction without a proper hint, therefore resulting instruction doesn't jump where it should.