0

I want to obtain the beginning of a memory page, a page that contains a function.

In my case I try to achieve the page beginning of main function. Which lies in 0x400a80, I think it is in code section of memory. I would appreciate if you can verify whether it is true or not.

As far as I understood, adress 0x400a80 lies in a page.

When I show memory segments of my process with pmap, it shows a segment starting with 0x400000 with size 8K, and the next portion goes with 0x601000 with size 4K.

I want to obtain adress 0x400000 because it has the address of the main() function. How can I achieve starting adress of a page when I have an adress that resides in that page? Is there any built-in way to do in linux ?

0

Welcome to Unix & Linux StackExchange!

This question might have been better served by Stack Overflow, the StackExchange site dedicated to programming questions. But anyway...

In x86 architecture, a standard memory page is 4 KiB, or 0x1000 bytes. The memory pages start at address 0, and are allocated contiguously with no overlapping.

To find the starting address of a memory page:

beginning of page = memory address AND (NOT page size - 1)

So if you have address 0x400a80, the beginning of that page = 0x400a80 AND (NOT 0x000fff) = 0x400a80 AND 0xfff000 = 0x400000.

0

If you’re looking for the start of a page containing a memory location, you can use sysconf(_SC_PAGE_SIZE) to retrieve the system’s page size, and round down to that:

  void *alloc;
  long pagesz;

  pagesz = sysconf(_SC_PAGESIZE);
  printf("Default page size: %ld\n", pagesz);

  alloc = malloc(512 * 1024 * 1024);
  printf("512MiB allocated at %zx\n", alloc);
  printf("The corresponding page starts at %zx\n", (((off_t) alloc) / pagesz) * pagesz);

This can be misleading in circumstances where page sizes vary, e.g. when using huge mappings on Linux.

If you’re looking for the start of the address space allocation containing a memory location, I’m not aware of a portable way to do so. On Linux, the interface to retrieve mapping information is /proc/self/maps, so you’d need to open and parse that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.