I'm saving a size_t
type of data in a raw memory block in kernel land, then I send the entire memory block to user land and I try to get that size_t
value back.
The type isn't guarantied to be equal-sized on both kernel and user land, so I'm wondering what's the best way to save the value and then restore it.
Edit:
Or, maybe just save another type of data than has the same size on both sides and that can the converted (or casted without data loss) to/from size_t
Edit 2:
I'm saving my data in the following format:
(size_of_data_chunk)(data_chunk)(size_of_data_chunk)(data_chunk)...
Common code:
Code in kernel land:
void add_chunk(membuffer *buffer, void *chunk, size_t size){
if(buffer->data != NULL){
buffer->data = krealloc(buffer->data, buffer->len + sizeof(size_t) + size, GFP_KERNEL);
buffer->len += sizeof(size_t) + size;
memcpy(buffer->data + buffer->len, &size, sizeof(size_t));
memcpy(buffer->data + buffer->len + sizeof(size_t), chunk, size);
}else{
buffer->data = kmalloc(sizeof(size_t) + size, GFP_KERNEL);
buffer->len = sizeof(size_t) + size;
memcpy(buffer->data, &size, sizeof(size_t));
memcpy(buffer->data + sizeof(size_t), chunk, size);
}
}
Code in user land:
void *get_chunk(membuffer *buffer){
size_t *size;
void *new_buffer;
void *chunk = NULL;
size = malloc(sizeof(size_t));
memcpy(size, buffer->data, sizeof(size_t));
chunk = malloc(*size);
memcpy(chunk, buffer->data + sizeof(size_t), *size);
buffer->data = malloc(buffer->len - sizeof(size_t) - *size);
memcpy(buffer->data, buffer->data + sizeof(size_t) + *size, buffer->len - sizeof(size_t) - *size);
free(size);
return chunk;
}
Note that I know what type of data will be contained on each chunk, so I don't need to save the type nor any other information, just the size of the chunk, and the chunk per-se.
Also note that this is my not-yet-finished (aka test) code. Maybe some free
's are missing.