#!/bin/sh

# Copyright (c) 2003-2014 Aleksey Cheusov <vle@gmx.net>
# 
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

set -e

LC_ALL=C
export LC_ALL

: ${LMDBG_S2M_DIR:=/usr/pkg/libexec/lmdbg}
: ${LMDBG_M2S_DIR:=/usr/pkg/libexec/lmdbg}

s2m_cmd=${LMDBG_S2M_DIR}/lmdbg-s2m
m2s_cmd=${LMDBG_M2S_DIR}/lmdbg-m2s

usage (){
    cat <<'EOF'
This program analyses lmdbg-run's or lmdbg-sym's output and
produces information about memory leaks.

usage:
    lmdbg-leaks [OPTIONS] [files...]
OPTIONS:
    -h        displays this screen
    -V        display version
EOF
}

version () {
    cat <<'EOF'
lmdbg-leaks 1.3.0
EOF
}

while getopts hV f; do
    case $f in
	h)
	    usage
	    exit 0;;
	V)
	    version
	    exit 0;;
	'?')
	    usage 1>&2
	    exit 1;;
	*)
	    break;;
    esac
done
shift $(expr $OPTIND - 1)

leaks () {
    /usr/bin/awk '
    $1 == "malloc" {
	h [$6] = $0
	next
    }

    $1 == "calloc" || $1 == "memalign" || $1 == "posix_memalign" || $1 == "aligned_alloc" {
	h [$8] = $0
	next
    }

    $1 == "free" {
	delete h [$3]
	next
    }

    $1 == "realloc" {
	if ($3 == "NULL" || $3 == $8){
	    h [$8] = $0
	}else{
	    h [$8] = $0
	    delete h [$3]
	}
	next
    }

    /^info / {
	print $0
	next
    }

    { print "unexpected input: " $0 > "/dev/stderr" }

    END {
	for (addr in h){
	    print h [addr]
	}
    }' "$@"
}

"$m2s_cmd" "$@" | leaks | sort | "$s2m_cmd"
