# -*- coding: utf-8 -*-
"""

    Script resolve problem with .debug_frame, this section
    is generated incorrect at vendors.
    Section of the ELF file.


 Copyright 2023 NXP

 NXP Confidential. This software is owned or controlled by NXP and may only be
 used strictly in accordance with the applicable license terms. By expressly
 accepting such terms or by downloading, installing, activating and/or otherwise
 using the software, you are agreeing that you have read, and that you agree to
 comply with and are bound by, such license terms. If you do not agree to be
 bound by the applicable license terms, then you may not retain, install,
 activate or otherwise use the software.
"""

import gdb


from flash.scripts.elfparser import ElfFile, ElfMachine

# We expect the message 'Green Hills' to be present in the .comment or to be present section .ghrettbl
def is_ghs_build(elf):
    
    comment = elf.get_section_header_by_name(".comment")
    if comment:
        data = str(comment.read_data())

        if "Green Hills" in data:
            return True

    ghrettbl = elf.get_section_header_by_name(".ghrettbl")
    if ghrettbl:
        return True

    return False

# We expect the message 'IAR' to be present in the .comment and Risc-V architecture
def is_iar_riscv_build(elf):
    comment = elf.get_section_header_by_name(".comment")

    if comment:
        data = str(comment.read_data())
        if (ElfMachine.EM_RISCV == elf.elf_header.machine) and ("IAR" in data):
            return True

    return False


# Check if the .debug_frame section
def is_debug_frame_available(elf):
    return elf.get_section_header_by_name(".debug_frame")


# DWARF information is not available
def ignore_stack_unwinders():
    gdb.write("Disable the DWARF stack unwinders\n")
    gdb.execute("maint set dwarf unwinders off", False, True).unwrap().rstrip()

# 
def check_vendors(elf):
    if is_ghs_build(elf) or is_iar_riscv_build(elf):
        return True   
    
    return False

# Check if the ELF file was built with Problem compiler and
# the debug_frame section is present
def handle_objfile_event(ev):
    try:
        if not ev.new_objfile.is_valid():
            return

        elf = ElfFile(ev.new_objfile.filename)

        if is_debug_frame_available(elf):
            if check_vendors(elf):
                # Send command to disable the DWARF stack unwinders
                ignore_stack_unwinders()
    except:
        pass


def register_symbol_load():
    gdb.events.new_objfile.connect(handle_objfile_event)
