#!/usr/bin/python

"""

   BLIS
   An object-based framework for developing high-performance BLAS-like
   libraries.

   Copyright (C) 2014, The University of Texas at Austin
   Copyright (C) 2018 - 2019, Advanced Micro Devices, Inc.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are
   met:
    - Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    - Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    - Neither the name(s) of the copyright holder(s) nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
   HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""

import argparse
import subprocess
import re
import os

binary_filename = ""
trace_filename = ""
missing_symbols = 0
call_only = False
lookup = {}


def check_args():
    global binary_filename, call_only, trace_filename
    parser = argparse.ArgumentParser(description='Decoder for BLIS execution trace. '\
        "Before running this utility ensure that BLIS library is built with execution trace enabled. "
        "Run the application to create the trace data, after that only run this decoder")
    parser.add_argument("--rawfile", required=True, type=str, help="Path to auto trace file generated by application")
    parser.add_argument("--binary", required=True, type=str, help="Path to application binary")
    parser.add_argument("--calls", action="store_true", help="Display only calls (no returns)")

    args = parser.parse_args()

    binary_filename = args.binary
    trace_filename = args.rawfile
    call_only = args.calls

def check_files():
    binary_path = os.path.join(os.getcwd(), binary_filename)
    trace_path = os.path.join(os.getcwd(), trace_filename)

    if not os.path.isfile(binary_path):
        print ("\nBinary %s not found" % binary_path)
        exit()
    
    if not os.path.isfile(trace_path):
        print ("\nExecutation trace data (file blis.etrace) not found in current dirctory \
                \nPlease check the directory and ensure that application is built and ran  \
                \nwith execution traces enabled.")
        exit()


    binary_mtime = os.path.getmtime(binary_path)
    trace_mtime = os.path.getmtime(trace_path)

    if binary_mtime > trace_mtime:
        print ("\n************************************************************************")
        print ("\n* WARNING: Binary is latest than trace file, trace data may not match. *")
        print ("\n************************************************************************")

    print ("Using binary file: %s" % binary_path)
    print ("Using trace file: %s" % trace_path)


def create_symbol_table_lookup():
    temp = subprocess.Popen(["objdump", "-t" , binary_filename], stdout = subprocess.PIPE)

    output = str(temp.communicate())

    output = output.split('\\n')
    regex_lookup = re.compile(r'.text')

    for line in range(len(output)):
        count = regex_lookup.findall(output[line])
        if len(count) > 0:
            current_line = output[line].split()
            key, value = int(current_line[0], 16), current_line[4]
            lookup[key] = value

def decode_symbols_from_trace():
    global missing_symbols
    raw_contents = []
    with open(trace_filename, "r") as f:
        raw_contents = f.read()

    raw_contents = raw_contents.split("\n")

    level = []
    first_timestamp = 0
    last_timestamp = 0


    for line in range(len(raw_contents)):
        current_line = raw_contents[line].split(":")
        if len(current_line) != 3:
            continue

        print_string = ""

        if current_line[1] == "+":
            last_level = "+"
            level.append(1)
        else:
            last_level = "-"
            if len(level) > 0:
                level.pop()

        if last_level == "-":
            for i in range(len(level) + 1) :
                print_string += "."
        else:
            for i in range(len(level)) :
                print_string += "."

        try:
            print_string += lookup[int(current_line[2], 16)]
        except KeyError:
            missing_symbols += 1
            print_string += current_line[2]

        if line == 1:
            first_timestamp = int(current_line[0])
            print_string += "(+0us)"
        else:
            delta_last = int(current_line[0]) - last_timestamp
            delta_total = int(current_line[0]) - first_timestamp
            print_string += "(+" + str(delta_last) + "us, " + str(delta_total) + "us)"


        if last_level == "-" and call_only:
            continue
        else:
            last_timestamp = int(current_line[0])

        print (print_string)
    
if __name__ == "__main__":

    check_args()
    check_files()
    create_symbol_table_lookup()
    decode_symbols_from_trace()

    if missing_symbols > 0:
        print("\nWARNING: Some symbols are not found, this can happen if binary is not matching \
            \nor symbols are stripped from it.")

