unicorn-engine / unicorn

Unicorn CPU emulator framework (ARM, AArch64, M68K, Mips, Sparc, PowerPC, RiscV, S390x, TriCore, X86)
http://www.unicorn-engine.org
GNU General Public License v2.0
7.66k stars 1.35k forks source link

Using `uc_ctl` to set page size results in a wrong value #2025

Closed elicn closed 1 month ago

elicn commented 1 month ago

Setting a custom page size using uc_ctl with UC_CTL_UC_PAGE_SIZE ends up setting a value double the size. When setting the size, the code counts the bits: https://github.com/unicorn-engine/unicorn/blob/78580ca8f91027cafc741f65c78c7650103b6683/uc.c#L2526-L2531

However, this value is used later to set the highest bit for the page size: https://github.com/unicorn-engine/unicorn/blob/78580ca8f91027cafc741f65c78c7650103b6683/qemu/exec-vary.c#L75

This is a simple off-by-one issue so the result value is shifted by an additional position, hence doubling the value (e.g. setting page size to 0x1000 results in 0x2000). Fixing the existing code with minimal modification is possible, yet making the code hard to follow. Suggesting to fix this by moving the bits counting loop to the function its result is being used eventually and fix it there.

[Found by a new unittest test case]

wtdcode commented 1 month ago

omg... I can't believe me writing this code when checking git blame

elicn commented 1 month ago

Don't be so hard on yourself (:

wtdcode commented 1 month ago

Fixed in fbf34af81ca959b16f4b744667742842e41be56a