How to find all read-write memory address of a process in Linux/UNIX with C/C++ language?

4.9k views Asked by At

Through /proc file system , it's probable to read memory mappings with /proc/PID_PROCESS/maps , but is there any native APIs that dedicated for this function in C/C++ ?

i.e to find out memory address that are writable and readable for process with PID 9322:

%> awk -F "-| " '$3 ~ /rw/ { print $1 " " $2}' /proc/9322/maps
0804e000 0804f000
085ed000 0860e000
b7707000 b7708000
b7864000 b7865000
b7865000 b7868000
b7897000 b7898000
b78b6000 b78b7000
bfd2e000 bfd50000

And those address are passed into my program , but now i want to integrate this function directly into my C++ program.

For most effectiveness , if i want to support for other *BSD system , i would not be able to take advantage of /proc system , and i think there should some method to generate e.g /proc/1/maps directly without reading them again there , correct if i'm wrong ^_^

4

There are 4 answers

3
Zimbabao On BEST ANSWER

Read the proc file like you read normal file.

eg.

  FILE *filep = fopen("/proc/9322/maps","r");
  char ch;
  while (ch != EOF){
    ch = fgetc(filep);
    printf("%c", ch);
  }
0
jwir3 On

Well, you could grab the PID of the process using:

pid_t pid = getpid();

Then, you could open the file /proc/PID/maps to and parse it into an array to determine which sets of memory are read-write.

Edit: The getpid() function requires #include <unistd.h>.

1
bdonlan On

Unfortunately, there is no full library (to my knowledge) to do what you want here. There is a libproc as part of procps, however this is an internal API, and moreover probably only implements the functionality used by procps. It would certainly be nice if there was such a library - feel free to release one! - but for now you'll have to conditional-compile for each OS you're targetting, and use OS-specific APIs (for Linux, directly opening and reading the appropriate procfiles) directly.

0
Matt Joiner On