#!/bin/sh
#
# prints commands to flag the process sections into radare
#
# pancake <youterm.com>

P=$1
[ -z "$P" ] && \
  echo "Usage: rsc map [pid]" && exit

parse() {
	b=0 # old value for a
	inc=0

	echo "fs maps"
	while : ; do
	read A
	[ -z "$A" ] && break
	i=0
	for a in $A ; do
		i=$(($i+1))
		#[ $i = 1 ] && addr=`echo $a|sed -e s/-/,/ |cut -d , -f 1`
		[ $i = 1 ] && addr=`echo $a|tr -- '-]/[+' ',____' | cut -d , -f 1`
		if [ $i = 6 ]; then
			if [ $a = $b ]; then
				inc=$(($inc+1))
			else
				b="$a"
				inc=0
			fi
			a=`basename $a`
			echo "f maps.${a}_${inc} @ 0x$addr" | tr -- '-][/+' ',____'
		fi
	done
	done
}

# For BSD
parse2() {
	b=0 # old value for a
	inc=0

	while : ; do
	read A
	[ -z "$A" ] && break
	i=0
	for a in $A ; do
		i=$(($i+1))
		[ $i = 1 ] && addr=`echo $a|tr -- '-]/[+' ',____' | cut -d , -f 1`
		if [ $i = 13 ]; then
			if [ $a = $b ]; then
				inc=$(($inc+1))
			else
				b="$a"
				inc=0
			fi
			a=`basename $a`
			echo "f maps.${a}_${inc} @ 0x$addr" |  tr -- '-][/+' ',____'
		fi
	done
	done
}

echo "fs maps"

echo|column >/dev/null 2>&1
if [ $? = 0 ]; then
	CAT="column -t"
else
	CAT="cat"
fi
if [ -e "/proc/$P/maps" ] ; then
	$CAT /proc/$P/maps | parse 
else
	if [ -e "/proc/$P/map" ] ; then
		$CAT /proc/$P/map | parse2
	#	cut -d ' ' -f 1,13 /proc/$P/map
	else
		# do not print anything
		:
		#echo "oops. no /proc found?" > /dev/stderr
	fi
fi

# FreeBSD
ps_strings=`sysctl kern.ps_strings 2>/dev/null | cut -d : -f 2`
usrstack=`sysctl kern.usrstack 2>/dev/null | cut -d : -f 2`
[ -n "${ps_strings}" ] && echo "f kern_ps_strings @ ${ps_strings}"
[ -n "${usrstack}" ] && echo "f kern_usrstack @ ${usrstack}"
