Dumping process memory

From Leo's Notes
Last edited on 2 October 2022, at 17:28.

Every Linux process has a pseudo mem device which can be used to read the process's memory pages. This mem file is found under /proc/$pid/mem. In order to properly use this file, you have to read the readable sections as outlined by its corresponding maps file.

Simply dd if=/proc/$pid/mem would not work as you will end up reading invalid or non-readable pages, resulting in a Input/output error. Instead, you should opt to use gdb to create a a core dump (using gcore $pid). On systems without gdb (think embedded systems), you may try to do this with the following bash-only solution.

Dumping process memory using Bash[edit | edit source]

Here's a quick script that dumps all readable pages for a particular process using bash and dd. This script assumes 4K pages (0x1000).

## Define your target PID
# export PID=$target-pid

## Dump memory
# cat /proc/$PID/maps \
  | grep -ohE '[a-f0-9]+-[a-f0-9]+ r' \
  | tr - ' ' \
  | while read s e foo ; do 
       echo "Dumping $s to $e"
       dd if=/proc/$PID/mem bs=$((0x1000)) skip=$((0x$s / 0x1000)) count=$(((0x$e - 0x$s) / 0x1000)) >> /tmp/dump
   done