#!/bin/bash
#
# 
# Copyright (C)  2022  Intel Corporation. 
#
# This software and the related documents are Intel copyrighted materials, and your use of them is governed by the express license under which they were provided to you ("License"). Unless the License provides otherwise, you may not use, modify, copy, publish, distribute, disclose or transmit this software or the related documents without Intel's prior written permission.
# This software and the related documents are provided as is, with no express or implied warranties, other than those that are expressly stated in the License.
#
# SPDX-License-Identifier: MIT
#
# This script strips out absolute kernel paths from a file generated by addr2line

display_help() {
	echo "This script strips out absolute kernel paths from a file generated by addr2line\n"
	echo "Usage: $0 VMLINUX_PATH FILE_TO_STRIP"
}
if [  $# -le 1 ]
then
	display_help
	exit 1
fi

kernel_obj_file=$1
file_to_strip=$2

if [ ! -f "$kernel_obj_file" ]; then
	echo "File '$kernel_obj_file' does not exists."
	exit 1
fi

if [ ! -f "$file_to_strip" ]; then
	echo "File '$file_to_strip' does not exists."
	exit 1
fi

# Hack stolen form Linux faddr2line script. Get known file containing
# the function start_kernel, and strip based on that.

start_kernel_addr=$(readelf -sW $kernel_obj_file | awk '$8 == "start_kernel" {printf "0x%s", $2}')
file_line=$(addr2line -e $kernel_obj_file $start_kernel_addr)
prefix=${file_line%init/main.c:*}
escaped_prefix=$(printf '%s\n' "$prefix" | sed -e 's/[\/&]/\\&/g')
sed -i "s/$escaped_prefix//g" $file_to_strip
