Defining a memory region as Little Endian in order to provide a way to deal with byte swapping (endian conversion).
Here is the idea: mprotect a memory region with lock access for reading/writing. As soon as there is a memory
access to this region, a signal will be raised. We handle the signal, and do the byte swapping at this moment.
Pros :
- Simple to implement.
- Don't have to know about the data/no conversion accross calls.
Cons :
Heavily depends on how the program exepects the data.
For example a Big Endian program access to a Little Endian memory zone which is in fact a string:
char *buffer = {'a','b','c','\0'};
define_le_zone(buffer, 4); // mprotect a memory region using our technics.
Accessing it byte per byte will give a correct output:
for( i = 0; i < 4; i++ )
printf("buffer[%d] is %c\n",buffer[i]);
gives:
buffer[0] is a
buffer[1] is b
buffer[2] is c
buffer[3] is \0
But accessing to this buffer int by int assuming that we are on a BE system won't be good:
uint32_t a_int32 = *((uint32_t *)buffer); // This instruction causes the trouble
char *buffer2 = {'\0','\0','\0','\0'}; // this buffer is not declared as little endian zone
memcpy(buffer2, &a_int32, 4);
for( i = 0; i < 4; i++ )
printf("buffer2[%d] is %c\n",buffer2[i]);
gives:
buffer2[0] is \0
buffer2[1] is c
buffer2[2] is b
buffer2[3] is a
Whereas it should give the same output as before.
|