Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast void pointer to uint64_t array in C

I'm currently working with a Linux kernel module and I need to access some 64-bit values stored in an array, however I first need to cast from a void pointer.

I'm using the kernel function phys_to_virt which is returning a void pointer, and I'm not entirely sure how to actually use this void pointer to access elements within the array that it points to.

Currently I'm doing this:

void *ptr;
uint64_t test;

ptr = phys_to_virt(physAddr);
test = *(uint64_t*)ptr;
printk("Test: %llx\n", test);

The value I'm getting from test isn't what I expected to see within the array, so I'm fairly sure I'm doing something wrong. I need to access the first three elements in the array, so I need to cast the void pointer to a uint64_t[] but I'm not quite sure how to do that.

Any advice would be greatly appreciated.

Thanks

like image 669
Tony Avatar asked Oct 22 '22 14:10

Tony


1 Answers

I'm using the kernel function phys_to_virt which is returning a void pointer, and I'm not entirely sure how to actually use this void pointer to access elements within the array that it points to.

Yup, phys_to_virt() does indeed return a void *. The concept of the void * is that it's typeless, so you can store anything to it, and yes you need to typecast it to something to extract information from it.

ptr = phys_to_virt(physAddr); // void * returned and saved to a void *, that's fine

test = *(uint64_t*)ptr; // so: (uint64_t*)ptr is a typecast saying "ptr is now a 
                        //      uint64_t pointer", no issues there
                        // adding the "*" to the front deferences the pointer, and 
                        // deferencing a pointer (decayed from an array) gives you the
                        // first element of it.

So yes, test = *(uint64_t*)ptr; will correctly typecast and give you the first element of the array. Note you can also write it like this:

test = ((uint64_t *)ptr)[0];

Which you might find a little bit clearer and means the same thing.

like image 114
Mike Avatar answered Oct 30 '22 02:10

Mike