diff options
Diffstat (limited to '')
-rw-r--r-- | libsyscalls_to_tracee_endian.c | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/libsyscalls_to_tracee_endian.c b/libsyscalls_to_tracee_endian.c new file mode 100644 index 0000000..94c44eb --- /dev/null +++ b/libsyscalls_to_tracee_endian.c @@ -0,0 +1,60 @@ +/* See LICENSE file for copyright and license details. */ +#include "common.h" + + +/* XXX be smarter if using the same byteorder */ +enum libsyscalls_error +libsyscalls_to_tracee_endian(unsigned long long int value_in, + const struct libsyscalls_datatype_description *type, + void *value_out, size_t out_offset) +{ + const unsigned long long int limit = sizeof(long long int) / sizeof(char) * CHAR_BIT; + unsigned long long int bytebits, bytemask, byte, remmask, valmask; + unsigned long long int offset, offset_byte, offset_bit; + unsigned char *out = value_out; + size_t i; + + if (!type || !value_out || (unsigned long long int)type->width_in_bits > limit) + return LIBSYSCALLS_E_INVAL; + + bytebits = (unsigned long long int)type->width_in_bits; + for (i = 0; !LIBSYSCALLS_IS_BYTEORDER_END_AT(type, i); i++) + if (type->byteorder[i] && (unsigned long long int)type->byteorder[i] < bytebits) + bytebits = (unsigned long long int)type->byteorder[i]; + + if (bytebits > limit) + return LIBSYSCALLS_E_INVAL; + else if (bytebits == limit) + bytemask = ~0ULL; + else + bytemask = (1ULL << bytebits) - 1ULL; + + if ((unsigned long long int)type->width_in_bits == limit) + valmask = ~0ULL; + else + valmask = (1ULL << (unsigned long long int)type->width_in_bits) - 1ULL; + + for (i = 0; !LIBSYSCALLS_IS_BYTEORDER_END_AT(type, i); i++) { + offset = out_offset; + offset_byte = offset / CHAR_BIT; + offset_bit = offset % CHAR_BIT; + out_offset += bytebits; + + byte = value_in >> type->byteorder[i]; + byte &= remmask = bytemask & (valmask >> type->byteorder[i]); + + out[offset_byte] &= (unsigned char)~(remmask << offset_bit); + out[offset_byte] |= (unsigned char)(byte << offset_bit); + if (bytebits != limit && (remmask >>= CHAR_BIT - offset_bit)) { + byte >>= CHAR_BIT - offset_bit; + do { + offset_byte += 1; + out[offset_byte] &= (unsigned char)~remmask; + out[offset_byte] |= (unsigned char)byte; + byte >>= CHAR_BIT; + } while (remmask >>= CHAR_BIT); + } + } + + return LIBSYSCALLS_E_OK; +} |