Skip to content

Commit 64192f1

Browse files
committed
Fix rel jump for 32-bit and adjust tiny test for 32-bit
1 parent d9d424c commit 64192f1

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed

src/lib.rs

+12-7
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ const JMP_MAX_SIZE: usize = 12;
6262
#[cfg(target_arch = "x86")]
6363
#[inline]
6464
fn assemble_jmp_to_address(address: usize, mut relative: isize) -> ([u8; JMP_MAX_SIZE], usize) {
65-
use core::{i16, i8};
65+
use core::{i32, i8};
6666
if (relative - 2 >= (i8::MIN as isize)) && (relative - 2 <= (i8::MAX as isize)) {
6767
relative -= 2;
6868
(
@@ -78,20 +78,20 @@ fn assemble_jmp_to_address(address: usize, mut relative: isize) -> ([u8; JMP_MAX
7878
],
7979
2,
8080
)
81-
} else if (relative - 3 >= (i16::MIN as isize)) && (relative - 3 <= (i16::MAX as isize)) {
81+
} else if (relative - 5 >= (i32::MIN as isize)) && (relative - 5 <= (i32::MAX as isize)) {
8282
relative -= 5;
8383
(
8484
[
85-
// jmp rel16
85+
// jmp rel32
8686
0xE9,
8787
relative as u8,
8888
(relative >> 8) as u8,
89-
0,
90-
0,
89+
(relative >> 16) as u8,
90+
(relative >> 24) as u8,
9191
0,
9292
0,
9393
],
94-
3,
94+
5,
9595
)
9696
} else {
9797
(
@@ -294,16 +294,21 @@ mod tests {
294294
assert_eq!(the_ultimate_question(), 42);
295295
}
296296

297+
// Test smallest possible function (in debug mode)
298+
// In 32-bit this should panic and properly detect we cannot patch a 1-byte function
297299
#[test]
300+
#[cfg_attr(target_arch = "x86", should_panic)]
298301
fn test_tiny() {
299302
assert_eq!(tiny(), ());
300303

301-
{
304+
if let Err(err) = std::panic::catch_unwind(|| {
302305
let _guard = patch0(tiny, || ());
303306

304307
assert_eq!(tiny(), ());
305308
assert_eq!(the_ultimate_question(), 42);
306309
assert_eq!(other_question(), 23);
310+
}) {
311+
assert_eq!(err.downcast().unwrap(), "target function is too small (1 byte) to patch");
307312
}
308313

309314
assert_eq!(tiny(), ());

0 commit comments

Comments
 (0)