#!/bin/sh
#
# Helper script for Massifing binaries.
# This file is part of maemo-debug-scripts.
#
# Copyright (C) 2006,2007 by Nokia Corporation
#
# Contact: Eero Tamminen <eero.tamminen@nokia.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License 
# version 2 as published by the Free Software Foundation. 
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
#
# 
# There are several ways to use this script
# - Rename the original binary to <name>.real and
#   put/link this script in place of the original binary
# - If the binary is using "maemo-launcher", this can
#   be linked instead of the "maemo-invoker" and it will
#   automatically call "maemo-summoner"
# - Call the binary with this script, e.g. like this
#   DISPLAY=:1 run-standalone.sh run-with-massif <binary> <arguments>
# 
# This sets all the required environment variables etc.
# before calling Valgrind.  Massif and the program outputs
# are saved into $HOME.

if [ -z $(which valgrind) ]; then
	echo "ERROR: valgrind missing!"
	exit 1
fi
wrapper=/usr/bin/maemo-summoner

if [ -x "$0.real" ]; then
	logapp="$0"
	app="$0.real"
elif [ -x "$1.launch" ] || [ -x "$0.launch" ] || [ "${1##*.}" = "launch" ]; then
	# use launcher wrapper automatically if given binary that needs it
	if [ \! -x "$wrapper" ]; then
		echo "ERROR: '$wrapper' for running .launch binaries is missing!"
		exit 1
	fi
	echo "$0: $*"
	if [ -x "$1.launch" ]; then
		logapp="$1"
		app="$wrapper $1.launch"
		shift
        elif [ -x "$0.launch" ]; then
		logapp="$0"
		app="$wrapper $0.launch"
	else
		logapp="$1"
		app="$wrapper $1"
		shift
	fi
	echo "$0: $*"
elif [ -x "$1" ]; then
	logapp="$1"
	app="$1"
	shift
else
	echo "ERROR: no application given!"
	exit 1
fi
app_opts="$*"
 
# put logs here
cd $HOME

# basic options
massif_opts="--tool=massif --depth=60 --format=html"

# base allocation functions for Glib etc
# (make valgrind go one level up in stack before assigning blame)
for f in posix_memalign g_slice_alloc g_slice_alloc0 g_malloc g_malloc0 g_try_malloc g_realloc g_strdup g_mem_chunk_alloc g_mem_chunk_alloc0 FT_Alloc FT_QAlloc
do
	massif_opts="$massif_opts --alloc-fn=$f"
done

# to get rid of GSlice posix_memalign
export G_SLICE="always-malloc"

echo "Running: valgrind $massif_opts $app $app_opts &"
valgrind $massif_opts $app $app_opts &
