#
# Copyright (C) 2023-2023 Intel Corporation.
# SPDX-License-Identifier: MIT
#

# A simple instruction counting PinGlue Service

import json, pin


# Global vars
total = 0


def send_result_callback_message():
    data = {
        "Count": total
    }
    json_string = json.dumps(data)
    print(f"In send_result_callback_message: JSON data: {json_string}")
    # Set the service result (as JSON) to the client
    Glue_SendServiceResultCallback(json_string)
    

total = 0

def docount(c):
    global total
    total += c
    

def trace_instrumentation_cb(trace):
    bbl = pin.TRACE_BblHead(trace)
    while(pin.BBL_Valid(bbl)):
        pin.BBL_InsertCall(bbl, pin.IPOINT_BEFORE, docount, pin.IARG_UINT32, pin.BBL_NumIns(bbl))
        bbl = pin.BBL_Next(bbl)
    
def fini(code):
    global total
    print(f"inscount: The total number of executed instructions is:{total}")
    send_result_callback_message()

pin.TRACE_AddInstrumentFunction(trace_instrumentation_cb)
pin.PIN_AddFiniFunction(fini)
