Skip to content

Fix incorrect bitshifting and masking in ffi bitfield #10403

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions ext/ffi/ffi.c
Original file line number Diff line number Diff line change
Expand Up @@ -592,22 +592,22 @@ static uint64_t zend_ffi_bit_field_read(void *ptr, zend_ffi_field *field) /* {{{
/* Read partial prefix byte */
if (pos != 0) {
size_t num_bits = 8 - pos;
mask = ((1U << num_bits) - 1U) << pos;
mask = (1U << num_bits) - 1U;
val = (*p++ >> pos) & mask;
insert_pos += num_bits;
}

/* Read full bytes */
while (p < last_p) {
val |= *p++ << insert_pos;
val |= (uint64_t) *p++ << insert_pos;
insert_pos += 8;
}

/* Read partial suffix byte */
if (p == last_p) {
size_t num_bits = last_bit % 8 + 1;
mask = (1U << num_bits) - 1U;
val |= (*p & mask) << insert_pos;
val |= (uint64_t) (*p & mask) << insert_pos;
}

return val;
Expand Down
30 changes: 30 additions & 0 deletions ext/ffi/tests/gh10403.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
--TEST--
GH-10403: Fix incorrect bitshifting and masking in ffi bitfield
--EXTENSIONS--
ffi
--SKIPIF--
<?php if (PHP_INT_SIZE != 8) echo "skip this test is for 64-bit only"; ?>
--FILE--
<?php
$ffi = FFI::cdef(<<<EOF
struct MyStruct {
uint64_t x : 10;
uint64_t y : 54;
};
EOF);

$test_struct = $ffi->new('struct MyStruct');
$test_struct->x = 1023;
$test_values = [0x3fafbfcfdfefff, 0x01020304050607, 0, 0x3fffffffffffff, 0x2ffffffffffff5];
foreach ($test_values as $test_value) {
$test_struct->y = $test_value;
var_dump($test_struct->y === $test_value);
}
var_dump($test_struct->x);
--EXPECT--
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
int(1023)