#!/bin/sh
if [ $# != 1 -a $# != 2 ]; then
	echo "Usage: $0 <pid> [dir]" >&2
	exit 1
fi

PID="$1"

if [ ! -z "`echo "$1" | tr -d '[0-9]'`" ]; then
	echo "error: '$1' does not look like a process id!" >&2
	exit 1
fi

PTRACE_ERROR=`gdb --batch --pid="$1" 2>&1 | grep '^ptrace: '`

if [ ! -z "$PTRACE_ERROR" ]; then
	echo "error: can't attach to pid '$1': `echo $PTRACE_ERROR | cut -d' ' -f2-`" >&2
	exit 1
fi

if [ ! -r "/proc/$PID/maps" ]; then
	echo "error: can't read maps for pid '$1'" >&2
	exit 1
fi

if [ $# = 2 ]; then
	OUTDIR="$2"
else
	OUTDIR="memdump-$1"
fi

if [ -d "$OUTDIR" ]; then
	echo "Output directory $OUTDIR already exists, aborting..." >&2
	exit 1
fi
mkdir $OUTDIR || exit 1


echo "Dumping memory maps from pid $PID to $OUTDIR..."
export OUTDIR

cut -d' ' -f1 "/proc/$PID/maps" | mawk -F- '
BEGIN {
	print "set height 0"
}
{
	if (("0x"$2) - ("0x"$1) < 128*1024*1024) {
		print "echo Dumping 0x"$1" - 0x"$2"...\\n"
		print "dump memory "ENVIRON["OUTDIR"]"/"$0" 0x"$1" 0x"$2
	} else {
		print "echo Skipping 0x"$1" - 0x"$2"...\\n"
	}
}' > /tmp/FIXME.gdb
gdb --quiet --batch --pid="$1" -x /tmp/FIXME.gdb
rm /tmp/FIXME.gdb

cp "/proc/$PID/maps" $OUTDIR

echo "Done!"
