Difference between %llx and %p while printing a pointer inside driver code [duplicate]
Asked Answered
S

1

4

It seems that casting a void* pointer (allocated by kmalloc) to unsigned long long changes it. Printing them with %p and %llx gives different values. Why is it so? Can anyone explain?

Following is a simple repro for that:

#include <linux/module.h>
#include <linux/slab.h>
#include <linux/init.h>

void* kbuff;
int init_module(void)
{

    kbuff = kzalloc(sizeof(char), GFP_KERNEL);
    pr_info("%p %llx\n",kbuff, (unsigned long long)kbuff);
    return 0;
}

void cleanup_module(void)
{
    kfree(kbuff);
}

The dmesg output comes out to be as follows

[67355.673465] 000000003aeb0247 ffff9ef657a58c00
Salpinx answered 26/2, 2020 at 10:19 Comment(5)
Because when you pass a pointer to %llx you are passing the wrong datatype which invokes UB. This is because the format of pointers can differ much between platforms, you cannot assume, that it can be well represented by a long long int. Did you even bother to cast it? If not, casting it explicitly to (unsigned long long) might improve your results.Baddie
I tried that as well. But still they are different.Salpinx
It might help to show the exact code and the output(s) you observe.Baddie
@Baddie Thanks for the quick response. I have edited the question with relevant code.Salpinx
Pointers are hashed by security reasons. Try %px instead. I'll write an answer later on. Ah, somebody beat me to it.Arielariela
B
5

From the documentation of printk() (which pr_info calls):

Pointer Types

Pointers printed without a specifier extension (i.e unadorned %p) are hashed to give a unique identifier without leaking kernel addresses to user space. On 64 bit machines the first 32 bits are zeroed. If you really want the address see %px below.

So, this is a security measure. Use the %px format specifier to print the real address (which should match now)

Baddie answered 26/2, 2020 at 11:15 Comment(1)
The documentation is available at www.kernel.org/../printk-formats.htmlJohanson

© 2022 - 2024 — McMap. All rights reserved.