Skip to content

Commit

Permalink
[endedness] Fix problem on bigendians with 'capture_parameter'
Browse files Browse the repository at this point in the history
On bigendian architectures a value with fewer bytes, if stored in a
value, or as in this case a union, are stored towards the upper end of
the larger value. This is in contrast to little-endians which will
store them at the lower end.
  • Loading branch information
thoni56 committed Sep 25, 2023
1 parent a338906 commit affdd93
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
16 changes: 14 additions & 2 deletions src/constraint.c
Original file line number Diff line number Diff line change
Expand Up @@ -601,15 +601,27 @@ static void execute_sideeffect(Constraint *constraint, const char *function, Cgr
(constraint->side_effect_callback)(constraint->side_effect_data);
}

#define IS_BIG_ENDIAN (!*(unsigned char *)&(uint16_t){1})
static bool bigendian(void) { return IS_BIG_ENDIAN; }

static void capture_parameter(Constraint *constraint, const char *function, CgreenValue actual,
const char *test_file, int test_line, TestReporter *reporter) {
(void)function;
(void)test_file;
(void)test_line;
(void)reporter;

memmove(constraint->expected_value.value.pointer_value, &actual.value, constraint->size_of_expected_value);
}
if ((sizeof(intptr_t) != constraint->size_of_expected_value) && bigendian()) {
// Then the beginning of a smaller value is not stored at the beginning of the actual.value union
size_t offset = sizeof(intptr_t) - constraint->size_of_expected_value;
// Offset is in bytes so we need to cast &actual.value to that before adding the offset
void *start_address = (unsigned char *)&actual.value + offset;
memmove(constraint->expected_value.value.pointer_value, start_address, constraint->size_of_expected_value);

} else
memmove(constraint->expected_value.value.pointer_value, &actual.value,
constraint->size_of_expected_value);
}


void test_want(Constraint *constraint, const char *function, CgreenValue actual,
Expand Down
9 changes: 6 additions & 3 deletions tests/mocks_tests.c
Original file line number Diff line number Diff line change
Expand Up @@ -437,12 +437,15 @@ Ensure(Mocks, can_capture_parameter) {
int captured_first = 0;
int captured_second = 0;

fprintf(stderr, "DEBUG: address to captured_first = %p\n", &captured_first);
fprintf(stderr, "DEBUG: address to captured_second = %p\n", &captured_second);

expect(simple_mocked_function,
will_capture_parameter(first, captured_first),
will_capture_parameter(second, captured_second));
simple_mocked_function(1, 2);
assert_that(captured_first, is_equal_to(1));
assert_that(captured_second, is_equal_to(2));
simple_mocked_function(0x12345678, 0x76543210);
assert_that(captured_first, is_equal_to_hex(0x12345678));
assert_that(captured_second, is_equal_to_hex(0x76543210));
}

static int changed_by_sideeffect = 1;
Expand Down

0 comments on commit affdd93

Please sign in to comment.