1#!/usr/bin/env bash
2# SPDX-License-Identifier: GPL-2.0
3# (c) 2014, Sasha Levin <[email protected]>
4#set -x
5
6usage() {
7	echo "Usage:"
8	echo "	$0 -r <release>"
9	echo "	$0 [<vmlinux> [<base_path>|auto [<modules_path>]]]"
10}
11
12# Try to find a Rust demangler
13if type llvm-cxxfilt >/dev/null 2>&1 ; then
14	cppfilt=llvm-cxxfilt
15elif type c++filt >/dev/null 2>&1 ; then
16	cppfilt=c++filt
17	cppfilt_opts=-i
18fi
19
20UTIL_SUFFIX=
21if [[ -z ${LLVM:-} ]]; then
22	UTIL_PREFIX=${CROSS_COMPILE:-}
23else
24	UTIL_PREFIX=llvm-
25	if [[ ${LLVM} == */ ]]; then
26		UTIL_PREFIX=${LLVM}${UTIL_PREFIX}
27	elif [[ ${LLVM} == -* ]]; then
28		UTIL_SUFFIX=${LLVM}
29	fi
30fi
31
32READELF=${UTIL_PREFIX}readelf${UTIL_SUFFIX}
33ADDR2LINE=${UTIL_PREFIX}addr2line${UTIL_SUFFIX}
34NM=${UTIL_PREFIX}nm${UTIL_SUFFIX}
35
36if [[ $1 == "-r" ]] ; then
37	vmlinux=""
38	basepath="auto"
39	modpath=""
40	release=$2
41
42	for fn in {,/usr/lib/debug}/boot/vmlinux-$release{,.debug} /lib/modules/$release{,/build}/vmlinux ; do
43		if [ -e "$fn" ] ; then
44			vmlinux=$fn
45			break
46		fi
47	done
48
49	if [[ $vmlinux == "" ]] ; then
50		echo "ERROR! vmlinux image for release $release is not found" >&2
51		usage
52		exit 2
53	fi
54else
55	vmlinux=$1
56	basepath=${2-auto}
57	modpath=$3
58	release=""
59	debuginfod=
60
61	# Can we use debuginfod-find?
62	if type debuginfod-find >/dev/null 2>&1 ; then
63		debuginfod=${1-only}
64	fi
65
66	if [[ $vmlinux == "" && -z $debuginfod ]] ; then
67		echo "ERROR! vmlinux image must be specified" >&2
68		usage
69		exit 1
70	fi
71fi
72
73declare aarray_support=true
74declare -A cache 2>/dev/null
75if [[ $? != 0 ]]; then
76	aarray_support=false
77else
78	declare -A modcache
79fi
80
81find_module() {
82	if [[ -n $debuginfod ]] ; then
83		if [[ -n $modbuildid ]] ; then
84			debuginfod-find debuginfo $modbuildid && return
85		fi
86
87		# Only using debuginfod so don't try to find vmlinux module path
88		if [[ $debuginfod == "only" ]] ; then
89			return
90		fi
91	fi
92
93	if [ -z $release ] ; then
94		release=$(gdb -ex 'print init_uts_ns.name.release' -ex 'quit' -quiet -batch "$vmlinux" 2>/dev/null | sed -n 's/\$1 = "\(.*\)".*/\1/p')
95	fi
96	if [ -n "${release}" ] ; then
97		release_dirs="/usr/lib/debug/lib/modules/$release /lib/modules/$release"
98	fi
99
100	found_without_debug_info=false
101	for dir in "$modpath" "$(dirname "$vmlinux")" ${release_dirs}; do
102		if [ -n "${dir}" ] && [ -e "${dir}" ]; then
103			for fn in $(find "$dir" -name "${module//_/[-_]}.ko*") ; do
104				if ${READELF} -WS "$fn" | grep -qwF .debug_line ; then
105					echo $fn
106					return
107				fi
108				found_without_debug_info=true
109			done
110		fi
111	done
112
113	if [[ ${found_without_debug_info} == true ]]; then
114		echo "WARNING! No debugging info in module ${module}, rebuild with DEBUG_KERNEL and DEBUG_INFO" >&2
115	else
116		echo "WARNING! Cannot find .ko for module ${module}, please pass a valid module path" >&2
117	fi
118
119	return 1
120}
121
122parse_symbol() {
123	# The structure of symbol at this point is:
124	#   ([name]+[offset]/[total length])
125	#
126	# For example:
127	#   do_basic_setup+0x9c/0xbf
128
129	if [[ $module == "" ]] ; then
130		local objfile=$vmlinux
131	elif [[ $aarray_support == true && "${modcache[$module]+isset}" == "isset" ]]; then
132		local objfile=${modcache[$module]}
133	else
134		local objfile=$(find_module)
135		if [[ $objfile == "" ]] ; then
136			return
137		fi
138		if [[ $aarray_support == true ]]; then
139			modcache[$module]=$objfile
140		fi
141	fi
142
143	# Remove the englobing parenthesis
144	symbol=${symbol#\(}
145	symbol=${symbol%\)}
146
147	# Strip segment
148	local segment
149	if [[ $symbol == *:* ]] ; then
150		segment=${symbol%%:*}:
151		symbol=${symbol#*:}
152	fi
153
154	# Strip the symbol name so that we could look it up
155	local name=${symbol%+*}
156
157	# Use 'nm vmlinux' to figure out the base address of said symbol.
158	# It's actually faster to call it every time than to load it
159	# all into bash.
160	if [[ $aarray_support == true && "${cache[$module,$name]+isset}" == "isset" ]]; then
161		local base_addr=${cache[$module,$name]}
162	else
163		local base_addr=$(${NM} "$objfile" 2>/dev/null | awk '$3 == "'$name'" && ($2 == "t" || $2 == "T") {print $1; exit}')
164		if [[ $base_addr == "" ]] ; then
165			# address not found
166			return
167		fi
168		if [[ $aarray_support == true ]]; then
169			cache[$module,$name]="$base_addr"
170		fi
171	fi
172	# Let's start doing the math to get the exact address into the
173	# symbol. First, strip out the symbol total length.
174	local expr=${symbol%/*}
175
176	# Now, replace the symbol name with the base address we found
177	# before.
178	expr=${expr/$name/0x$base_addr}
179
180	# Evaluate it to find the actual address
181	expr=$((expr))
182	local address=$(printf "%x\n" "$expr")
183
184	# Pass it to addr2line to get filename and line number
185	# Could get more than one result
186	if [[ $aarray_support == true && "${cache[$module,$address]+isset}" == "isset" ]]; then
187		local code=${cache[$module,$address]}
188	else
189		local code=$(${ADDR2LINE} -i -e "$objfile" "$address" 2>/dev/null)
190		if [[ $aarray_support == true ]]; then
191			cache[$module,$address]=$code
192		fi
193	fi
194
195	# addr2line doesn't return a proper error code if it fails, so
196	# we detect it using the value it prints so that we could preserve
197	# the offset/size into the function and bail out
198	if [[ $code == "??:0" ]]; then
199		return
200	fi
201
202	# Strip out the base of the path on each line
203	code=$(while read -r line; do echo "${line#$basepath/}"; done <<< "$code")
204
205	# In the case of inlines, move everything to same line
206	code=${code//$'\n'/' '}
207
208	# Demangle if the name looks like a Rust symbol and if
209	# we got a Rust demangler
210	if [[ $name =~ ^_R && $cppfilt != "" ]] ; then
211		name=$("$cppfilt" "$cppfilt_opts" "$name")
212	fi
213
214	# Replace old address with pretty line numbers
215	symbol="$segment$name ($code)"
216}
217
218debuginfod_get_vmlinux() {
219	local vmlinux_buildid=${1##* }
220
221	if [[ $vmlinux != "" ]]; then
222		return
223	fi
224
225	if [[ $vmlinux_buildid =~ ^[0-9a-f]+ ]]; then
226		vmlinux=$(debuginfod-find debuginfo $vmlinux_buildid)
227		if [[ $? -ne 0 ]] ; then
228			echo "ERROR! vmlinux image not found via debuginfod-find" >&2
229			usage
230			exit 2
231		fi
232		return
233	fi
234	echo "ERROR! Build ID for vmlinux not found. Try passing -r or specifying vmlinux" >&2
235	usage
236	exit 2
237}
238
239decode_code() {
240	local scripts=`dirname "${BASH_SOURCE[0]}"`
241
242	echo "$1" | $scripts/decodecode
243}
244
245handle_line() {
246	if [[ $basepath == "auto" && $vmlinux != "" ]] ; then
247		module=""
248		symbol="kernel_init+0x0/0x0"
249		parse_symbol
250		basepath=${symbol#kernel_init (}
251		basepath=${basepath%/init/main.c:*)}
252	fi
253
254	local words
255
256	# Tokenize
257	read -a words <<<"$1"
258
259	# Remove hex numbers. Do it ourselves until it happens in the
260	# kernel
261
262	# We need to know the index of the last element before we
263	# remove elements because arrays are sparse
264	local last=$(( ${#words[@]} - 1 ))
265
266	for i in "${!words[@]}"; do
267		# Remove the address
268		if [[ ${words[$i]} =~ \[\<([^]]+)\>\] ]]; then
269			unset words[$i]
270		fi
271
272		# Format timestamps with tabs
273		if [[ ${words[$i]} == \[ && ${words[$i+1]} == *\] ]]; then
274			unset words[$i]
275			words[$i+1]=$(printf "[%13s\n" "${words[$i+1]}")
276		fi
277	done
278
279	if [[ ${words[$last]} =~ ^[0-9a-f]+\] ]]; then
280		words[$last-1]="${words[$last-1]} ${words[$last]}"
281		unset words[$last]
282		last=$(( $last - 1 ))
283	fi
284
285	if [[ ${words[$last]} =~ \[([^]]+)\] ]]; then
286		module=${words[$last]}
287		# some traces format is "(%pS)", which like "(foo+0x0/0x1 [bar])"
288		# so $module may like "[bar])". Strip the right parenthesis firstly
289		module=${module%\)}
290		module=${module#\[}
291		module=${module%\]}
292		modbuildid=${module#* }
293		module=${module% *}
294		if [[ $modbuildid == $module ]]; then
295			modbuildid=
296		fi
297		symbol=${words[$last-1]}
298		unset words[$last-1]
299	else
300		# The symbol is the last element, process it
301		symbol=${words[$last]}
302		module=
303		modbuildid=
304	fi
305
306	unset words[$last]
307	parse_symbol # modifies $symbol
308
309	# Add up the line number to the symbol
310	echo "${words[@]}" "$symbol $module"
311}
312
313while read line; do
314	# Strip unexpected carriage return at end of line
315	line=${line%$'\r'}
316
317	# Let's see if we have an address in the line
318	if [[ $line =~ \[\<([^]]+)\>\] ]] ||
319	   [[ $line =~ [^+\ ]+\+0x[0-9a-f]+/0x[0-9a-f]+ ]]; then
320		# Translate address to line numbers
321		handle_line "$line"
322	# Is it a code line?
323	elif [[ $line == *Code:* ]]; then
324		decode_code "$line"
325	# Is it a version line?
326	elif [[ -n $debuginfod && $line =~ PID:\ [0-9]+\ Comm: ]]; then
327		debuginfod_get_vmlinux "$line"
328	else
329		# Nothing special in this line, show it as is
330		echo "$line"
331	fi
332done
333