1

Based upon my understanding, a C/C++ program looks something like this in the memory:

Memory Layout of C programs. Source : Internet

I wanted to know the following :

  1. Can I access the "text section" of the running program? By accessing I mean printing the start and end addresses and examining the contents.
  2. Can I relocate the "text section" to some other address in the memory at runtime?

Thanks,

sud03r
  • 19,109
  • 16
  • 77
  • 96
  • If you want a specific function you can just directly access its pointer for reading and copying to another space. Mind you that there's a huge performance impact for handling code as data. – Leeor Nov 08 '13 at 06:06
  • **Why** exactly do you ask? **What do you want to do**, really? – Basile Starynkevitch Nov 08 '13 at 06:10
  • @BasileStarynkevitch Actually, I want to compute the impact of accessing code from a node other than the one running the current program on a NUMA machine. I know there are other alternatives, but was curious if one can access the text section and modify it to point to some other address at runtime. – sud03r Nov 08 '13 at 06:30
  • Well, processors have caches, so the impact (for hot code used often) should not be significant. And even without NUMA, cache misses have a huge cost (that matters mostly for *cold* code used rarely). And NUMA systems have a complex MMU (code is in virtual memory!). So hot code is always "on the current node". Don't care that much about code, care about data! – Basile Starynkevitch Nov 08 '13 at 06:37

1 Answers1

9

It is operating system specific; I am answering for Linux only.

First your figure is grossly incorrect in practice, since most programs are dynamically linked to several shared object libraries (including libc6.so...). See also ld.so(8), elf(5), execve(2). There is no single text section (but many "text" like segments). Read about the pmap and objdump commands.

Then, you can understand the address space of a process of pid 1234 with cat /proc/1234/maps ; read more about proc(5)... From inside the program, read /proc/self/maps; for instance try cat /proc/$$/maps in a shell to show the address space of the shell process, and cat /proc/self/maps for the address space of the process running that cat command. See also mmap(2).

You cannot really "relocate" (you actually mean "move") the text section. Some addresses are built inside the code. However, read about the -fPIE option of gcc (for position independent executable ....).

Of course, you can access the symbols of a program (from inside) if you link it with the -rdynamic flag and if you use dlopen(3) (and dlsym and even perhaps dladdr....) with a NULL first filename argument.

See also wikipages about address space, virtual memory, ASLR, position independent code, relocation, ABI, JIT compilation, name mangling and the x86-64 ABI spec and the Advanced Linux Programming book.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547