1#!/bin/bash
2# SPDX-License-Identifier: GPL-2.0
3#
4# Translate stack dump function offsets.
5#
6# addr2line doesn't work with KASLR addresses.  This works similarly to
7# addr2line, but instead takes the 'func+0x123' format as input:
8#
9#   $ ./scripts/faddr2line ~/k/vmlinux meminfo_proc_show+0x5/0x568
10#   meminfo_proc_show+0x5/0x568:
11#   meminfo_proc_show at fs/proc/meminfo.c:27
12#
13# If the address is part of an inlined function, the full inline call chain is
14# printed:
15#
16#   $ ./scripts/faddr2line ~/k/vmlinux native_write_msr+0x6/0x27
17#   native_write_msr+0x6/0x27:
18#   arch_static_branch at arch/x86/include/asm/msr.h:121
19#    (inlined by) static_key_false at include/linux/jump_label.h:125
20#    (inlined by) native_write_msr at arch/x86/include/asm/msr.h:125
21#
22# The function size after the '/' in the input is optional, but recommended.
23# It's used to help disambiguate any duplicate symbol names, which can occur
24# rarely.  If the size is omitted for a duplicate symbol then it's possible for
25# multiple code sites to be printed:
26#
27#   $ ./scripts/faddr2line ~/k/vmlinux raw_ioctl+0x5
28#   raw_ioctl+0x5/0x20:
29#   raw_ioctl at drivers/char/raw.c:122
30#
31#   raw_ioctl+0x5/0xb1:
32#   raw_ioctl at net/ipv4/raw.c:876
33#
34# Multiple addresses can be specified on a single command line:
35#
36#   $ ./scripts/faddr2line ~/k/vmlinux type_show+0x10/45 free_reserved_area+0x90
37#   type_show+0x10/0x2d:
38#   type_show at drivers/video/backlight/backlight.c:213
39#
40#   free_reserved_area+0x90/0x123:
41#   free_reserved_area at mm/page_alloc.c:6429 (discriminator 2)
42
43
44set -o errexit
45set -o nounset
46
47usage() {
48	echo "usage: faddr2line [--list] <object file> <func+offset> <func+offset>..." >&2
49	exit 1
50}
51
52warn() {
53	echo "$1" >&2
54}
55
56die() {
57	echo "ERROR: $1" >&2
58	exit 1
59}
60
61READELF="${CROSS_COMPILE:-}readelf"
62ADDR2LINE="${CROSS_COMPILE:-}addr2line"
63AWK="awk"
64
65command -v ${AWK} >/dev/null 2>&1 || die "${AWK} isn't installed"
66command -v ${READELF} >/dev/null 2>&1 || die "${READELF} isn't installed"
67command -v ${ADDR2LINE} >/dev/null 2>&1 || die "${ADDR2LINE} isn't installed"
68
69# Try to figure out the source directory prefix so we can remove it from the
70# addr2line output.  HACK ALERT: This assumes that start_kernel() is in
71# init/main.c!  This only works for vmlinux.  Otherwise it falls back to
72# printing the absolute path.
73find_dir_prefix() {
74	local objfile=$1
75
76	local start_kernel_addr=$(${READELF} --symbols --wide $objfile | ${AWK} '$8 == "start_kernel" {printf "0x%s", $2}')
77	[[ -z $start_kernel_addr ]] && return
78
79	local file_line=$(${ADDR2LINE} -e $objfile $start_kernel_addr)
80	[[ -z $file_line ]] && return
81
82	local prefix=${file_line%init/main.c:*}
83	if [[ -z $prefix ]] || [[ $prefix = $file_line ]]; then
84		return
85	fi
86
87	DIR_PREFIX=$prefix
88	return 0
89}
90
91__faddr2line() {
92	local objfile=$1
93	local func_addr=$2
94	local dir_prefix=$3
95	local print_warnings=$4
96
97	local sym_name=${func_addr%+*}
98	local func_offset=${func_addr#*+}
99	func_offset=${func_offset%/*}
100	local user_size=
101	local file_type
102	local is_vmlinux=0
103	[[ $func_addr =~ "/" ]] && user_size=${func_addr#*/}
104
105	if [[ -z $sym_name ]] || [[ -z $func_offset ]] || [[ $sym_name = $func_addr ]]; then
106		warn "bad func+offset $func_addr"
107		DONE=1
108		return
109	fi
110
111	# vmlinux uses absolute addresses in the section table rather than
112	# section offsets.
113	local file_type=$(${READELF} --file-header $objfile |
114		${AWK} '$1 == "Type:" { print $2; exit }')
115	if [[ $file_type = "EXEC" ]] || [[ $file_type == "DYN" ]]; then
116		is_vmlinux=1
117	fi
118
119	# Go through each of the object's symbols which match the func name.
120	# In rare cases there might be duplicates, in which case we print all
121	# matches.
122	while read line; do
123		local fields=($line)
124		local sym_addr=0x${fields[1]}
125		local sym_elf_size=${fields[2]}
126		local sym_sec=${fields[6]}
127		local sec_size
128		local sec_name
129
130		# Get the section size:
131		sec_size=$(${READELF} --section-headers --wide $objfile |
132			sed 's/\[ /\[/' |
133			${AWK} -v sec=$sym_sec '$1 == "[" sec "]" { print "0x" $6; exit }')
134
135		if [[ -z $sec_size ]]; then
136			warn "bad section size: section: $sym_sec"
137			DONE=1
138			return
139		fi
140
141		# Get the section name:
142		sec_name=$(${READELF} --section-headers --wide $objfile |
143			sed 's/\[ /\[/' |
144			${AWK} -v sec=$sym_sec '$1 == "[" sec "]" { print $2; exit }')
145
146		if [[ -z $sec_name ]]; then
147			warn "bad section name: section: $sym_sec"
148			DONE=1
149			return
150		fi
151
152		# Calculate the symbol size.
153		#
154		# Unfortunately we can't use the ELF size, because kallsyms
155		# also includes the padding bytes in its size calculation.  For
156		# kallsyms, the size calculation is the distance between the
157		# symbol and the next symbol in a sorted list.
158		local sym_size
159		local cur_sym_addr
160		local found=0
161		while read line; do
162			local fields=($line)
163			cur_sym_addr=0x${fields[1]}
164			local cur_sym_elf_size=${fields[2]}
165			local cur_sym_name=${fields[7]:-}
166
167			if [[ $cur_sym_addr = $sym_addr ]] &&
168			   [[ $cur_sym_elf_size = $sym_elf_size ]] &&
169			   [[ $cur_sym_name = $sym_name ]]; then
170				found=1
171				continue
172			fi
173
174			if [[ $found = 1 ]]; then
175				sym_size=$(($cur_sym_addr - $sym_addr))
176				[[ $sym_size -lt $sym_elf_size ]] && continue;
177				found=2
178				break
179			fi
180		done < <(${READELF} --symbols --wide $objfile | ${AWK} -v sec=$sym_sec '$7 == sec' | sort --key=2)
181
182		if [[ $found = 0 ]]; then
183			warn "can't find symbol: sym_name: $sym_name sym_sec: $sym_sec sym_addr: $sym_addr sym_elf_size: $sym_elf_size"
184			DONE=1
185			return
186		fi
187
188		# If nothing was found after the symbol, assume it's the last
189		# symbol in the section.
190		[[ $found = 1 ]] && sym_size=$(($sec_size - $sym_addr))
191
192		if [[ -z $sym_size ]] || [[ $sym_size -le 0 ]]; then
193			warn "bad symbol size: sym_addr: $sym_addr cur_sym_addr: $cur_sym_addr"
194			DONE=1
195			return
196		fi
197
198		sym_size=0x$(printf %x $sym_size)
199
200		# Calculate the address from user-supplied offset:
201		local addr=$(($sym_addr + $func_offset))
202		if [[ -z $addr ]] || [[ $addr = 0 ]]; then
203			warn "bad address: $sym_addr + $func_offset"
204			DONE=1
205			return
206		fi
207		addr=0x$(printf %x $addr)
208
209		# If the user provided a size, make sure it matches the symbol's size:
210		if [[ -n $user_size ]] && [[ $user_size -ne $sym_size ]]; then
211			[[ $print_warnings = 1 ]] &&
212				echo "skipping $sym_name address at $addr due to size mismatch ($user_size != $sym_size)"
213			continue;
214		fi
215
216		# Make sure the provided offset is within the symbol's range:
217		if [[ $func_offset -gt $sym_size ]]; then
218			[[ $print_warnings = 1 ]] &&
219				echo "skipping $sym_name address at $addr due to size mismatch ($func_offset > $sym_size)"
220			continue
221		fi
222
223		# In case of duplicates or multiple addresses specified on the
224		# cmdline, separate multiple entries with a blank line:
225		[[ $FIRST = 0 ]] && echo
226		FIRST=0
227
228		echo "$sym_name+$func_offset/$sym_size:"
229
230		# Pass section address to addr2line and strip absolute paths
231		# from the output:
232		local args="--functions --pretty-print --inlines --exe=$objfile"
233		[[ $is_vmlinux = 0 ]] && args="$args --section=$sec_name"
234		local output=$(${ADDR2LINE} $args $addr | sed "s; $dir_prefix\(\./\)*; ;")
235		[[ -z $output ]] && continue
236
237		# Default output (non --list):
238		if [[ $LIST = 0 ]]; then
239			echo "$output" | while read -r line
240			do
241				echo $line
242			done
243			DONE=1;
244			continue
245		fi
246
247		# For --list, show each line with its corresponding source code:
248		echo "$output" | while read -r line
249		do
250			echo
251			echo $line
252			n=$(echo $line | sed 's/.*:\([0-9]\+\).*/\1/g')
253			n1=$[$n-5]
254			n2=$[$n+5]
255			f=$(echo $line | sed 's/.*at \(.\+\):.*/\1/g')
256			${AWK} 'NR>=strtonum("'$n1'") && NR<=strtonum("'$n2'") { if (NR=='$n') printf(">%d<", NR); else printf(" %d ", NR); printf("\t%s\n", $0)}' $f
257		done
258
259		DONE=1
260
261	done < <(${READELF} --symbols --wide $objfile | ${AWK} -v fn=$sym_name '$4 == "FUNC" && $8 == fn')
262}
263
264[[ $# -lt 2 ]] && usage
265
266objfile=$1
267
268LIST=0
269[[ "$objfile" == "--list" ]] && LIST=1 && shift && objfile=$1
270
271[[ ! -f $objfile ]] && die "can't find objfile $objfile"
272shift
273
274DIR_PREFIX=supercalifragilisticexpialidocious
275find_dir_prefix $objfile
276
277FIRST=1
278while [[ $# -gt 0 ]]; do
279	func_addr=$1
280	shift
281
282	# print any matches found
283	DONE=0
284	__faddr2line $objfile $func_addr $DIR_PREFIX 0
285
286	# if no match was found, print warnings
287	if [[ $DONE = 0 ]]; then
288		__faddr2line $objfile $func_addr $DIR_PREFIX 1
289		warn "no match for $func_addr"
290	fi
291done
292