1

We could use GetModuleInformation to get the information of a loaded dynamic library on Windows platforms, including its base address and size. And, GetModuleHandleEx can take an address as the input and returns the module's handle. So basically, getting a dynamic library's base and size from an address is accessible.

I don't know enough about UNIX-like platforms (including Linux, macOS, iOS, Android, etc.). How can I do the same on these platforms? dladdr doesn't return the size information.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362
amanjiang
  • 1,213
  • 14
  • 33
  • 1
    Sounds like http://xyproblem.info. Why do you _need_ the size? – Employed Russian Feb 22 '22 at 15:41
  • @EmployedRussian With the Size information, the program can build a segment tree of the address space. Some module information can be cached in the segment tree, and absolute addresses in the backtrace can be efficiently converted to relative addresses. – amanjiang Feb 23 '22 at 14:13

2 Answers2

1

getting a dynamic library's base and size from an address is accessible.

Open /proc/$$/maps and parse it and match the ranges with the address that you have. The first line is the "base address", and last column is the library filename, that you can fstat() on and get the size.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
1

I don't know enough about UNIX-like platforms (including Linux, macOS, iOS, Android, etc.).

Each one is likely to require a different solution.

With the Size information, the program can build a segment tree of the address space. Some module information can be cached in the segment tree, and absolute addresses in the backtrace can be efficiently converted to relative addresses.

Note that due to ASLR, the "segment tree" is only good for the current process (and any children it fork()s) -- unlike on Windows, the location of shared libraries (and possibly the main executable) would change from run to run.

On Linux (and current versions of Android), in addition to already mentioned parsing of /proc/self/maps (which has many gotcha's), you can use dl_iterate_phdr.

Example code. You'll want to modify it so it iterates over all loaded ELF images and doesn't stop after the first one (by making callback always return 0).

Employed Russian
  • 199,314
  • 34
  • 295
  • 362
  • ASLR shouldn't be a problem since the segment tree is updated as dynamic link libraries are loaded and unloaded. Therefore, I also need to intercept the event of dynamic library unloading. Fortunately, this is easy on the Windows platform. – amanjiang Feb 24 '22 at 11:55