Skip to content

Commit

Permalink
Readd endianness check in x86 byteswap routine
Browse files Browse the repository at this point in the history
  • Loading branch information
caseif committed Apr 18, 2024
1 parent 10f1ec9 commit d221bc6
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 15 deletions.
2 changes: 1 addition & 1 deletion src/unpack/load.c
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ static int _parse_package_header(arp_package_meta_t *meta, const unsigned char h
}

uint16_t major_version;
_copy_str_to_field(&major_version, header_data, PACKAGE_VERSION_LEN, PACKAGE_VERSION_OFF);
_copy_int_to_field(&major_version, header_data, PACKAGE_VERSION_LEN, PACKAGE_VERSION_OFF);

if (major_version != 1) {
arp_set_error("Package version is not supported");
Expand Down
35 changes: 21 additions & 14 deletions src/util/common.c
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@
void copy_int_as_le(void *dst, void *src, size_t len) {
memcpy(dst, src, len);

int x = 1;
if (((unsigned char*) &x)[0] == 1) {
// system is little-endian, so no need to do any conversion
return;
}

#ifdef _WIN32
if (len == 2) {
*((uint16_t*) dst) = _byteswap_ushort(*((uint16_t*) dst));
Expand All @@ -44,7 +50,6 @@ void copy_int_as_le(void *dst, void *src, size_t len) {
#else
if (len == 2) {
*((uint16_t*) dst) = __builtin_bswap16(*((uint16_t*) dst));
((uint8_t*) dst)[0] ^= ((uint8_t*) dst)[1];
} else if (len == 3 || len == 4) {
*((uint32_t*) dst) = __builtin_bswap32(*((uint32_t*) dst));
} else if (len == 8) {
Expand All @@ -64,19 +69,21 @@ void copy_int_as_le(void *dst, void *src, size_t len) {
memcpy(dst, src, len);

int x = 1;
if (((unsigned char*) &x)[0] == 0) {
// system is big-endian, so we need to convert to little
if (len == 2) {
_swap_bytes(&dst, 0, 1);
} else if (len == 3 || len == 4) {
_swap_bytes(&dst, 0, 3);
_swap_bytes(&dst, 1, 2);
} else if (len == 8) {
_swap_bytes(&dst, 0, 7);
_swap_bytes(&dst, 1, 6);
_swap_bytes(&dst, 2, 5);
_swap_bytes(&dst, 3, 4);
}
if (((unsigned char*) &x)[0] == 1) {
// system is little-endian, so no need to do any conversion
return;
}

if (len == 2) {
_swap_bytes(&dst, 0, 1);
} else if (len == 3 || len == 4) {
_swap_bytes(&dst, 0, 3);
_swap_bytes(&dst, 1, 2);
} else if (len == 8) {
_swap_bytes(&dst, 0, 7);
_swap_bytes(&dst, 1, 6);
_swap_bytes(&dst, 2, 5);
_swap_bytes(&dst, 3, 4);
}
}
#endif
Expand Down

0 comments on commit d221bc6

Please sign in to comment.