简体   繁体   中英

Physical address varies when initializing variable

For some reason, I need to know the physical address of a certain variable. Nonetheless, the physical address changes after initializing the variable. To get the physical address I use this function ( virt_to_phys(..., uint64_t virtaddr) ) , which seems to work properly. Some examples of the behavior:

Before initialization: virtual 0x5632692a3780 physical 0x32b2c7c780

After initialization: virtual 0x5632692a3780 physical 0x342147a780

Using these formatters:

printf("virtual 0x%llx physical 0x%llx\n", &p, virt_to_phys((uint64_t) &p));

I am compiling with -O2 , but I also used -O0 and nothing changed, so I guess this behavior is not an optimization. I am also executing this code in Arch Linux with kernel 4.13.4-1.

This could be a dumb question but I can not understand the reason behind this behavior.

The physical address can change over time unless you lock the memory ( mlock(2) ).

If your variable is uninitialized, it will reside in BSS, and the BSS pages would originally point to a shared page filled with zeroes . As soon as you write to that page, the entire page would probably have to be copied to another page frame (physical page), therefore the different physical address.

Notice that the relative offset within the page remains the same after copying: 0x780 , as would be expected from correct code.

The first thing I'd say, for printing a pointer (address) is to

  • make use of %p format specifier.
  • cast the corresponding argument to (void *) .

Without that, you're causing undefined behavior and the output cannot be justified anyway.

That said, as mentioned in the other answer by @Anti , the physical memory here, which "backs up" the virtual memory need not be fixed. Based on the type (behavior) of the type for which the memory is allocated can cause the physical memory to be altered in background, based on the implementation. That is why, we use the virtual memory in application code and let the OS/MMU handle the mapping and transformation under the hood.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM