-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbacktrace.sh
More file actions
69 lines (56 loc) · 1.61 KB
/
backtrace.sh
File metadata and controls
69 lines (56 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#!/usr/bin/env bash
#
# Copyright (c) 2023-2024, Arm Limited and Contributors. All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
#
# Dump the current call stack.
#
# This function takes no arguments, and prints the call stack of the script at
# the point at which it was called.
dump_stack() {(
set +x
for ((i = 1; i < ${#FUNCNAME[@]}; i++)); do
local function="${FUNCNAME[$((i + 1))]:-<unknown>}"
local line="${BASH_LINENO[$i]}"
local source="${BASH_SOURCE[$((i + 1))]:-<unknown>}"
echo -e "[$i]: ${source}:${line} (${function})"
done
)}
# Dump the formatted call stack.
#
# This function takes no arguments, and prefixes the output of `dump_stack()`
# with a section header for inclusion in error backtraces.
dump() {(
set +x
echo "Call stack:"
echo
dump_stack | while IFS= read -r line; do
echo " ${line}"
done
)}
# Generate an error backtrace.
#
# This function dumps the backtrace at the point at which the function is
# called, with additional information about the command that failed.
#
# This is best used as a trap handler (e.g. `trap backtrace ERR`) rather than by
# being called directly. If you want to explicitly dump the script state, prefer
# to use the `dump` function instead.
backtrace() {
local error=$?
local command=${BASH_COMMAND}
(
set +x
echo "" >&2
echo "ERROR: Command at ${BASH_SOURCE[1]:-<unknown>}:${BASH_LINENO[0]} exited with error ${error}:" >&2
echo "ERROR:" >&2
echo "${command}" | while IFS= read -r line; do
echo "ERROR: ${line}" >&2
done
echo "ERROR:" >&2
dump | while IFS= read -r line; do
echo "ERROR: ${line}" >&2
done
)
}