Exemple #1
0
def declare(program, file):
    tree = ET.parse(file)
    root = tree.getroot()

    api = FlatProgramAPI(program)
    aspace = api.getAddressFactory().getDefaultAddressSpace()

    periph_map = {}

    for periph in root.findall('.//peripheral'):
        periph_name = get_text(periph, 'name', 'UNK')
        periph_base = get_int(periph, 'baseAddress')

        derived_from = periph.get('derivedFrom')
        if derived_from:
            regs = periph_map[derived_from]
        else:
            regs = periph.findall('./registers/register')

        periph_map[periph_name] = regs

        for reg in regs:
            reg_name = get_text(reg, 'name', 'UNK')
            reg_addr = periph_base + get_int(reg, 'addressOffset')
            reg_size = get_int(reg, 'size')

            addr = aspace.getAddress(reg_addr)
            try:
                api.createLabel(addr, "%s_%s" % (periph_name, reg_name), True)

                if reg_size == 8:
                    api.createByte(addr)
                elif reg_size == 16:
                    api.createWord(addr)
                elif reg_size == 32:
                    api.createDWord(addr)
            except:
                print("skipping address 0x%08x" % reg_addr)
Exemple #2
0
def main():
    fapi = FlatProgramAPI(currentProgram)

    te_list = fapi.getDataTypes("TraceEntry")

    if len(te_list) == 0:
        create_trace_entry()
        te_list = fapi.getDataTypes("TraceEntry")

        if len(te_list) == 0:
            print("ERROR: failed to create TraceEntry data type")
            return

    te = te_list[0]

    caddr = fapi.toAddr(0)

    monitor.setCancelEnabled(True)
    monitor.setIndeterminate(True)

    trace_entry_addrs = []
    while caddr is not None and not monitor.isCancelled():
        caddrs = fapi.findBytes(caddr, "DBT:", 1000)

        if not caddrs:
            break

        trace_entry_addrs += caddrs

        caddr = caddrs[-1].add(1)
        monitor.setMessage("Found %d TraceEntries" % len(trace_entry_addrs))

        if DEBUG_FIND and len(trace_entry_addrs) > DEBUG_FIND_MAX_ENTRIES:
            break

    print("Found %d TraceEntry structures" % len(trace_entry_addrs))

    # Uncomment if you just want to dump the entries
    #dump_trace_entries(fapi, "trace-entries.txt", trace_entry_addrs); return

    maximum = len(trace_entry_addrs)
    monitor.setIndeterminate(False)
    monitor.initialize(maximum)
    monitor.setCancelEnabled(True)

    monitor.setProgress(0)
    monitor.setMessage("Typing TraceEntries...")

    for cur, caddr in enumerate(trace_entry_addrs):
        if monitor.isCancelled():
            break

        monitor.incrementProgress(1)

        if DEBUG_RETYPE and cur < DEBUG_RETYPE_SKIP:
            continue

        try:
            fapi.clearListing(caddr, caddr.add(te.getLength()))

            trace_entry = fapi.createData(caddr, te)
            message_field = trace_entry.getComponent(4)
            file_field = trace_entry.getComponent(6)

            message_addr = message_field.getValue()
            message_str = getDataAt(message_addr)

            file_addr = file_field.getValue()
            file_str = getDataAt(file_addr)

            if message_str is None or not isinstance(message_str.getValue(),
                                                     unicode):
                message_str = force_create_string(fapi, message_addr, 1024)
                if message_str is None:
                    continue
                if SHOW_OUTPUT:
                    print("[%d/%d] Created missing message string @ %s" %
                          (cur + 1, maximum, message_addr))

            if file_str is None or not isinstance(file_str.getValue(),
                                                  unicode):
                file_str = force_create_string(fapi, file_addr, 1024)
                if file_str is None:
                    continue
                if SHOW_OUTPUT:
                    print("[%d/%d] Created missing file string @ %s" %
                          (cur + 1, maximum, file_addr))

            #print(type(message_str.getValue()), message_str.getValue())

            message_str = message_str.getValue()
            file_str = file_str.getValue()

            message_str_fixed = fixup_format_string(message_str)

            #print("[%s] %s" % (file_str, message_str_fixed))
            base_file = os.path.basename(file_str).split(".")[0]
            symbol_name = "TraceEntry::%s::%s" % (base_file, message_str_fixed)
            # limit the length
            symbol_name_assign = symbol_name[:min(len(symbol_name), 60)]
            fapi.createLabel(caddr, symbol_name_assign, True,
                             SourceType.USER_DEFINED)

            if SHOW_OUTPUT:
                print("[%d/%d] [%s] %s" %
                      (cur + 1, maximum, caddr, symbol_name))
        except ghidra.program.model.mem.MemoryAccessException:
            # this happens with the false positive match of "DBT:String too long"
            print("[%d/%d] [%s] Invalid TraceEntry signature!" %
                  (cur + 1, maximum, caddr))
        except ghidra.program.model.util.CodeUnitInsertionException:
            print("[%d/%d] Something else already at %s" %
                  (cur + 1, maximum, caddr))
            # Uncomment this raise, if you want to catch all strangeness
            # raise

    print('Done!')