#!/usr/bin/env python

import sys
import re
import subprocess
import os.path

def usage():
    sys.stderr.write("usage: %s symboldir crashfile\n" % sys.argv[0])
    sys.exit(1)

if len(sys.argv) != 3:
    usage()
build_path = sys.argv[1]
crash_filename = sys.argv[2]

def addr2line(lib, addr):
    lib_name = os.path.basename(lib)
    if os.path.isdir(build_path):
        lib_path = "%s/%s" % (build_path, lib_name)
    elif os.path.isfile(build_path) and lib_name == os.path.basename(build_path):
        lib_path = build_path
    else:
        return ""
    command = "addr2line -C -f -e %s %s" % (lib_path, addr)
    process = subprocess.Popen(command,
                               shell=True,
                               stdout=subprocess.PIPE)
    lines = process.stdout.readlines()
    process.wait()
    if lines:
        function = lines[0].strip()
        file_and_line = os.path.basename(lines[1].strip())
        return " (%s %s)" % (function, file_and_line)
    else:
        return ""

error_re = re.compile(r"^BROWSER ERROR:.*\(\d+\): ?")
pc_re = re.compile(r"#\d\d +pc +([0-9a-f]+) +([A-Za-z0-9+_\-/.]+)")

with open(crash_filename) as file:
    for line in file:
        line = error_re.sub("", line)

        m = pc_re.search(line)
        if m:
            pc = m.group(1)
            lib = m.group(2)
            annotation = addr2line(lib, pc)
            line = line.strip() + annotation + "\n"

        sys.stdout.write(line)
