1#!/bin/bash
2
3# The lines that we're looking to symbolize look like this:
4  #0 ./a.out(_foo+0x3e6) [0x55a52e64c696]
5# ... which come from the backtrace_symbols() symbolisation function used by
6# default in Scudo's implementation of GWP-ASan.
7
8while read -r line; do
9  # Check that this line needs symbolization.
10  should_symbolize="$(echo $line |\
11     grep -E '^[ ]*\#.*\(.*\+0x[0-9a-f]+\) \[0x[0-9a-f]+\]$')"
12
13  if [ -z "$should_symbolize" ]; then
14    echo "$line"
15    continue
16  fi
17
18  # Carve up the input line into sections.
19  binary_name="$(echo $line | grep -oE ' .*\(' | rev | cut -c2- | rev |\
20      cut -c2-)"
21  function_name="$(echo $line | grep -oE '\([^+]*' | cut -c2-)"
22  function_offset="$(echo $line | grep -oE '\(.*\)' | grep -oE '\+.*\)' |\
23      cut -c2- | rev | cut -c2- | rev)"
24  frame_number="$(echo $line | grep -oE '\#[0-9]+ ')"
25
26  if [ -z "$function_name" ]; then
27    # If the offset is binary-relative, just resolve that.
28    symbolized="$(echo $function_offset | addr2line -e $binary_name)"
29  else
30    # Otherwise, the offset is function-relative. Get the address of the
31    # function, and add it to the offset, then symbolize.
32    function_addr="0x$(echo $function_offset |\
33       nm --defined-only $binary_name 2> /dev/null |\
34       grep -E " $function_name$" | cut -d' ' -f1)"
35
36    # Check that we could get the function address from nm.
37    if [ -z "$function_addr" ]; then
38      echo "$line"
39      continue
40    fi
41
42    # Add the function address and offset to get the offset into the binary.
43    binary_offset="$(printf "0x%X" "$((function_addr+function_offset))")"
44    symbolized="$(echo $binary_offset | addr2line -e $binary_name)"
45  fi
46
47  # Check that it symbolized properly. If it didn't, output the old line.
48  echo $symbolized | grep -E ".*\?.*:" > /dev/null
49  if [ "$?" -eq "0" ]; then
50    echo "$line"
51    continue
52  else
53    echo "${frame_number}${symbolized}"
54  fi
55done
56