-5

As far as I know, a memory address like 0x0 of a program is the beginning of its code segment in its virtual address space. Is it possible to simply read what's in there from within a program? What about checking things like the size of the stack/heap? If not possible in C/++ programs, is it possible in assembly?

Edit: I find memory allocation and management interesting. I'm asking out of curiosity. I like the idea of being able to see what's in every address of my program's virtual address space. When I mentioned stack/heap size, I meant those of the program, too.

Tomer
  • 131
  • 1
  • 5
  • 1
    `memory address like 0x0 of a program is the beginning of its code segment in its virtual address space` - where did you get it? – qrdl Jul 23 '20 at 07:05
  • This is highly OS- and architecture -specific. Please specify OS and CPU architecture. The heap and stack limits depend on the OS, so you can read them using the appropriate OS API, but probably won't need Assembly. Most OSes probably don't allocate address 0 to anything (i.e. not even code), such that accessing it will result in a guaranteed MMU fault. – Erlkoenig Jul 23 '20 at 07:06
  • Even if you specify an OS/CPU/compiler vendor/... what do you really want to achieve. On most systems you can read from own program space if you have access rights for it like debuggers typically have. To get heap and stack size, you should ask your OS or read the standard conventions for your compiler tools. – Klaus Jul 23 '20 at 07:34
  • Updated OP. Does it require a debugger? I might make a project of a program that can display its own virtual address space addresses and values. – Tomer Jul 23 '20 at 07:49
  • No, it did not need a debugger. have you read "like a debugger". If you are interested in the way a OS is dealing with all the linking/memory management/allocation stuff and so on, please read a documentation for your OS. Nobody will repeat all that stuff in a SO answer. – Klaus Jul 23 '20 at 08:07

1 Answers1

1

First, check /proc/<pid>/maps, assuming that you are running Linux. This will show you a list of allocated regions, and the permissions for each region (or VMA, technically). Check out this answer. The permissions are 'rwx' or a subset of these, representing readable, writable and executable. For regions which are readable, you can craft a pointer in C/C++ using a uintptr_t. Thereafter, you can read it.

Basically, you can dump all of your readable regions using simple pointers.

Btw, in virtually all C binaries, the region starting at address 0x0 will be unmapped, so that using a NULL pointer leads to a SEGFAULT.

TSG
  • 877
  • 1
  • 6
  • 23