aboutsummaryrefslogtreecommitdiff
path: root/scripts/lib/trace-init.sh
blob: 80f1ab0fd0e96dc60a507573630f1b228cf2a3f3 (plain)
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
# scripts/lib/trace-init.sh
# Instrumentation hook sourced automatically by every non-interactive bash
# invocation via the BASH_ENV environment variable.
#
# The bats suite runs the tool with `bash "$TRBLDOC"`, so exporting
# BASH_ENV=<this file> causes each trbldoc.sh process to enable xtrace at
# startup WITHOUT modifying trbldoc.sh or the test files. The emitted trace is
# consumed by the coverage and hotspot aggregators.
#
# Activated only when TRBLDOC_TRACE_DIR is set, and only for scripts whose
# basename appears in TRBLDOC_TRACE_TARGETS (default: trbldoc.sh). This keeps
# unrelated bash helpers (md2html stub, bats internals) out of the trace.
#
# TRBLDOC_TRACE_MODE selects the PS4 format:
#   cov   -> "<marker> <source>:<lineno>"                 (line coverage)
#   time  -> "<marker> <source>:<lineno> <EPOCHREALTIME>" (line timing; bash>=5)
#
# Every traced line is prefixed with the marker token @@TBL@@. bash repeats the
# FIRST PS4 character once per call-nesting level, so the aggregators match the
# marker with a tolerant pattern rather than a fixed prefix.

if [ -n "${TRBLDOC_TRACE_DIR:-}" ]; then
  __tb_self="$0"
  __tb_base="${__tb_self##*/}"
  case " ${TRBLDOC_TRACE_TARGETS:-trbldoc.sh} " in
    *" ${__tb_base} "*)
      # Dedicated append fd per process; PID keeps parallel xargs workers apart.
      __tb_trace_file="${TRBLDOC_TRACE_DIR}/trace.$$.log"
      # shellcheck disable=SC3023
      exec 7>>"$__tb_trace_file"
      export BASH_XTRACEFD=7
      if [ "${TRBLDOC_TRACE_MODE:-cov}" = "time" ]; then
        # EPOCHREALTIME is bash>=5; used only for the hotspot profiler.
        PS4='@@TBL@@ ${BASH_SOURCE}:${LINENO} ${EPOCHREALTIME} '
      else
        PS4='@@TBL@@ ${BASH_SOURCE}:${LINENO} '
      fi
      export PS4
      set -x
      ;;
  esac
fi