Linux – how to see the contents in the RAM when a program is executed in Linux

linuxramrhel

I want to see the contents of a program being stored in RAM when the program is executed . I have used cat /proc/[pid]/meminfo but it gave only address and permission mode details .
I also tried pmaps -X pid , it gave too many details but the data . How to see the content loaded on RAM ?

Best Answer

/proc/[pid]/mem lets you access the virtual memory of a process.

Offsets in that file correspond to virtual addresses. /proc/[pid]/maps tells you which address ranges are backed by actual memory (and where the memory itself is backed by files).

All this is documented in the proc(5) manpage.

A process can only access the memory of processes which are run under the same user as itself, and which are not setgid/uid. It used to be the case that you had to ptrace() a process in order to access its memory via /proc/[pid]/mem, but this is NO LONGER TRUE since quite a while (more precisely, since this commit from January 2012 (v3.2+), whose purpose was to fix a security bug, also editorialized in a lwn article).

Practical example

In a terminal window:

% echo $$ # show our pid
6744
% read -sp 'secret pasword: '; echo
secret pasword:
%

Then in another terminal window:

% grep heap /proc/6744/maps
01bb7000-01c3e000 rw-p 00000000 00:00 0                                  [heap]
% dd if=/proc/6744/mem bs=1 skip=$((0x01bb7000)) count=$((0x01c3e000-0x01bb7000)) status=none |
    strings | less
...
% dd if=/proc/6744/mem bs=1 skip=$((0x01bb7000)) count=$((0x01c3e000-0x01bb7000)) status=none |
    strings | grep qwerty
qwertyuiop # here is the "secret password"

People generally use a debugger like gdb to peek at the memory of a running process instead of rudimentary ways like this (a debugger knows the format of the structures used by a process, can follow pointers, lists, etc), but the principle is basically the same.

Recent linux kernels also have nicer interfaces instead of /proc/[pid]/mem, like process_vm_readv. Just as with /proc/[pid]/mem or PTRACE_PEEK, etc. you need root-like privileges (CAP_SYS_PTRACE) in order to read the memory of a process you don't own.

Related Question