summaryrefslogtreecommitdiffstats
path: root/libsyscalls_to_tracer_endian.c
blob: ad3b8a4be0c68fc6b1a0ca341c1c56b75efbb130 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/* See LICENSE file for copyright and license details. */
#include "common.h"


/* XXX be smarter if using the same byteorder */
enum libsyscalls_error
libsyscalls_to_tracer_endian(const void *value_in, size_t in_offset,
                             const struct libsyscalls_datatype_description *type,
                             unsigned long long int *value_out)
{
	const unsigned long long int limit = sizeof(long long int) / sizeof(char) * CHAR_BIT;
	unsigned long long int bytebits, bytemask, byte, value, remmask, valmask;
	unsigned long long int offset = in_offset, offset_byte, offset_bit, off;
	const unsigned char *in = value_in;
	size_t i;

	if (!type || !value_in || !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;

	value = 0;
	for (i = 0; !LIBSYSCALLS_IS_BYTEORDER_END_AT(type, i); i++) {
		offset_byte = offset / CHAR_BIT;
		offset_bit = offset % CHAR_BIT;
		offset += bytebits;

		byte = (unsigned long long int)in[offset_byte] >> offset_bit;
		remmask = bytemask & (valmask >> type->byteorder[i]);

		off = CHAR_BIT - offset_bit;
		if (remmask >>= off) {
			do {
				byte |= (unsigned long long int)in[++offset_byte] << off;
				off += CHAR_BIT;
			} while (remmask >>= CHAR_BIT);
		}
		byte &= bytemask & (valmask >> type->byteorder[i]);
		value |= byte << type->byteorder[i];
	}

	*value_out = value;
	return LIBSYSCALLS_E_OK;
}