Dumping process memory: Difference between revisions

From Leo's Notes
This page was last edited on 2 October 2022, at 17:28.
mNo edit summary
No edit summary
 
Line 4: Line 4:


== Dumping process memory using Bash ==
== Dumping process memory using Bash ==
{{Highlight
Here's a quick script that dumps all readable pages for a particular process using bash and dd. This script assumes 4K pages (<code>0x1000</code>).{{Highlight
| code = # PID=$pid cat /proc/$PID/maps \
| code = ## Define your target PID
# export PID=$target-pid
 
## Dump memory
# cat /proc/$PID/maps \
   {{!}} grep -ohE '[a-f0-9]+-[a-f0-9]+ r' \
   {{!}} grep -ohE '[a-f0-9]+-[a-f0-9]+ r' \
   {{!}} tr - ' ' \
   {{!}} tr - ' ' \
   {{!}} while read s e foo ; do  
   {{!}} while read s e foo ; do  
       echo "Dumping $s to $e"
       echo "Dumping $s to $e"
       dd if=/proc/$PID/mem bs=1 skip=$((0x$s)) count=$((0x$e - 0x$s)) >> /tmp/dump
       dd if=/proc/$PID/mem bs=$((0x1000)) skip=$((0x$s / 0x1000)) count=$(((0x$e - 0x$s) / 0x1000)) >> /tmp/dump
   done
   done
| lang = terminal
| lang = terminal
}}
}}

Latest revision as of 17:28, 2 October 2022

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

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