Ejemplo n.º 1
0
def load_file(li, neflags, format):
    
    # Select the PC processor module
    idaapi.set_processor_type("BPF", SETPROC_ALL|SETPROC_FATAL)
    
    buf = read_whole_file(li, 8)
    if not buf:
        return 0

    start = 0x0
    seg = idaapi.segment_t()
    size = len(buf)
    end  = start + size
    
    # Create the segment
    seg.startEA = start
    seg.endEA   = end
    seg.bitness = 1 # 32-bit
    idaapi.add_segm_ex(seg, "bpf_c", "CODE", 0)

    # Copy the bytes
    idaapi.mem2base(buf, start, end)

    # add entry point
    idaapi.add_entry(start, start, "start", 1) 

    # add comment to beginning of disassembly
    idaapi.describe(start, True, "BPF bytecode disassembly")

    # Mark for analysis
    AutoMark(start, AU_CODE)

    setup_enums()
    return 1
Ejemplo n.º 2
0
def load_file(li, neflags, format):
    
    """
    Load the file into database

    @param li: a file-like object which can be used to access the input data
    @param neflags: options selected by the user, see loader.hpp
    @return: 0-failure, 1-ok
    """
    
    if format == RomFormatName:
        jump = dwordAt(li, 0)
        if jump & 0xFF000000 == 0xEA000000: # looks like an ARM branch?
            idaapi.set_processor_type("arm", SETPROC_ALL|SETPROC_FATAL)
        
        li.seek(0, idaapi.SEEK_END)
        size = li.tell()

        #next dword after signature is a pointer to ROMHDR
        romhdr  = dwordAt(li, ROM_SIGNATURE_OFFSET + 4)
        
        # let's try to find such imagebase that potential ROMHDR's "physfirst" value matches it
        imgbase = (romhdr-size) & ~0xfff
        bases = []
        maxbase = 0
        while imgbase < romhdr+8:
            physfirst = dwordAt(li, romhdr - imgbase + 8)
            if physfirst == imgbase:
                bases.append(imgbase)
            imgbase += 0x1000

        if len(bases) == 1:
            start = bases[0]
        elif len(bases) > 1:
            print "Warning: several potential imagebases detemined: " + ", ".join("%08X"%i for i in bases)
            start = bases[-1]
        else:
            Warning("Unable to determine load image base.")
            start = 0x80000000
        print "Using imagebase %08X" % start
        
        physlast = dwordAt(li, romhdr - start + 12)
        if physlast <= start:
            Warning("Internal error")
            return 0
        size = physlast - start

        AddSeg(start, start+size, 0, 1, idaapi.saRelPara, idaapi.scPub)

        # copy bytes to the database
        li.seek(0)
        li.file2base(0, start, start+size, 0)

        idaapi.add_entry(start, start, "start", 1)
        print "Load OK"
        return 1

    Warning("Unknown format name: '%s'" % format)
    return 0
Ejemplo n.º 3
0
def load_file(li, neflags, format):
    """
    Load the file into database

    @param li: a file-like object which can be used to access the input data
    @param neflags: options selected by the user, see loader.hpp
    @return: 0-failure, 1-ok
    """

    if format == RomFormatName:
        jump = dwordAt(li, 0)
        if jump & 0xFF000000 == 0xEA000000:  # looks like an ARM branch?
            idaapi.set_processor_type("arm", SETPROC_ALL | SETPROC_FATAL)

        li.seek(0, idaapi.SEEK_END)
        size = li.tell()

        #next dword after signature is a pointer to ROMHDR
        romhdr = dwordAt(li, ROM_SIGNATURE_OFFSET + 4)

        # let's try to find such imagebase that potential ROMHDR's "physfirst" value matches it
        imgbase = (romhdr - size) & ~0xfff
        bases = []
        maxbase = 0
        while imgbase < romhdr + 8:
            physfirst = dwordAt(li, romhdr - imgbase + 8)
            if physfirst == imgbase:
                bases.append(imgbase)
            imgbase += 0x1000

        if len(bases) == 1:
            start = bases[0]
        elif len(bases) > 1:
            print "Warning: several potential imagebases detemined: " + ", ".join(
                "%08X" % i for i in bases)
            start = bases[-1]
        else:
            Warning("Unable to determine load image base.")
            start = 0x80000000
        print "Using imagebase %08X" % start

        physlast = dwordAt(li, romhdr - start + 12)
        if physlast <= start:
            Warning("Internal error")
            return 0
        size = physlast - start

        AddSeg(start, start + size, 0, 1, idaapi.saRelPara, idaapi.scPub)

        # copy bytes to the database
        li.seek(0)
        li.file2base(0, start, start + size, 0)

        idaapi.add_entry(start, start, "start", 1)
        print "Load OK"
        return 1

    Warning("Unknown format name: '%s'" % format)
    return 0
Ejemplo n.º 4
0
def load_file_sbl(li, neflags, format):

    # set the processor type and enable 'metaarm' so ida disassembles all instructions
    idaapi.set_processor_type("arm:ARMv7-A&R",
                              idaapi.SETPROC_ALL | idaapi.SETPROC_FATAL)
    idc.ChangeConfig('ARM_DEFAULT_ARCHITECTURE = metaarm')

    # rewind the input file and read its contents
    li.seek(0)
    init_val = li.read(li.size())

    # Load the file data (sans header) into IDA
    rom = SblImage(init_val)

    AddSeg(rom.header.image_dest_ptr,
           rom.header.image_dest_ptr + rom.header.image_size, 0, 1,
           idaapi.saRelPara, idaapi.scPub)
    SetSegmentType(rom.header.image_dest_ptr, idaapi.SEG_CODE)
    RenameSeg(rom.header.image_dest_ptr, "CODE")
    # li.file2base(file_offset, seg1, seg1 + code_seg_size, 0)
    # Load the file data (sans header) into IDA
    li.file2base(80, rom.header.image_dest_ptr,
                 rom.header.image_dest_ptr + rom.header.code_size, 0)

    # Define the .text .data and .bss segments
    #AddSegEx(0, rom.header.image_dest_ptr, rom.header.image_dest_ptr + rom.header.code_size, s, ".code", "CODE", ADDSEG_OR_DIE)
    # AddSegment(0, data_start, data_end, ".data", "DATA")
    # AddSegment(0, data_end, bss_end, ".bss", "BSS")
    image_base = rom.header.image_dest_ptr
    entry = rom.header.image_src
    #if DEBUG:
    #        print "Created File Segments: "
    #        print "\t.text   0x%.8X - 0x%.8X" % (entry, data_start)
    #        print "\t.data   0x%.8X - 0x%.8X" % (data_start, data_end)
    #        print "\t.bss    0x%.8X - 0x%.8X" % (data_end, bss_end)

    # mark the entry point as being the first byte of the loaded image
    idaapi.add_entry(rom.header.image_dest_ptr, rom.header.image_dest_ptr,
                     "HEADER", 1)

    AddIdbComment(image_base, 'Codeword:            ', rom.header.codeword)
    AddIdbComment(image_base, 'Magic No.:           ', rom.header.magic)
    AddIdbComment(image_base, 'Source Location:     ', rom.header.image_src)
    AddIdbComment(image_base, 'Destination Address: ',
                  rom.header.image_dest_ptr)
    AddIdbComment(image_base, 'Image Size:          ', rom.header.image_size)
    AddIdbComment(image_base, 'Code Size:           ', rom.header.code_size)
    AddIdbComment(image_base, 'Signature Ptr:       ', rom.header.sig_ptr)
    AddIdbComment(image_base, 'Signature Size:      ', rom.header.sig_size)
    AddIdbComment(image_base, 'Cert Chain Ptr:      ',
                  rom.header.cert_chain_ptr)
    AddIdbComment(image_base, 'Cert Chain Size:     ',
                  rom.header.cert_chain_size)
    AddIdbComment(image_base, 'OEM Cert Sel:        ',
                  rom.header.oem_root_cert_sel)
    AddIdbComment(image_base, 'OEM Cert Num:        ',
                  rom.header.oem_num_root_certs)

    return 1
Ejemplo n.º 5
0
def load_file(li, neflags, format):
    
    # set the processor type and enable 'metaarm' so ida disassembles all instructions
    idaapi.set_processor_type('arm', idaapi.SETPROC_ALL | idaapi.SETPROC_FATAL)
    idc.ChangeConfig('ARM_DEFAULT_ARCHITECTURE = metaarm')

    # rewind the input file and read its contents
    li.seek(0)
    rom_data = li.read(li.size())
    
    # for some reason this doesnt work, so we end up with this
    #rom_name = li.filename().split('.')[0]
    rom_name = ''
    while rom_name == '':
        rom_name = AskStr('', "Enter the input file's basename:")
    if rom_name is None: rom_name = 'rom'

    while True:
        rom_name = os.path.basename(rom_name).split('.')[0]

        # read the rom, letting exceptions fall through to ida's exception handler
        rom = MbnRom(rom_data)

        # for convenience
        image_base = rom.header.image_virtual_address

        # create the segments
        AddSegment('%s_code' % rom_name, rom.code_base, rom.code_data)
        if rom.sig_data is not None: AddSegment('%s_sig' % rom_name, rom.sig_base, rom.sig_data)
        if rom.cert_data is not None: AddSegment('%s_cert' % rom_name, rom.cert_base, rom.cert_data)
        if rom.tail_data is not None: AddSegment('%s_tail' % rom_name, rom.tail_base, rom.tail_data)
        if rom.overlay_data is not None: AddSegment('%s_overlay' % rom_name, rom.overlay_base, rom.overlay_data)

        # mark the entry point as being the first byte of the loaded image
        idaapi.add_entry(rom.code_base, rom.code_base, '%s_start' % rom_name, 1)

        # make some comments for usability
        AddIdbComment(image_base, 'ROM: %s' % rom_name)
        AddIdbComment(image_base, '')
        AddIdbComment(image_base, 'Load Index', rom.header.load_index)
        AddIdbComment(image_base, 'Flash Partition Version', rom.header.flash_partition_version)
        AddIdbComment(image_base, 'Image File Offset', rom.header.image_offset + MbnHeader.SBL_HEADER_SIZE)
        AddIdbComment(image_base, 'Image VA', rom.header.image_virtual_address)
        AddIdbComment(image_base, 'Image Size', rom.header.image_size)
        AddIdbComment(image_base, 'Code VA', rom.header.code_size)
        AddIdbComment(image_base, 'Signature VA', rom.header.signature_virtual_address)
        AddIdbComment(image_base, 'Signature Size', rom.header.signature_size)
        AddIdbComment(image_base, 'Cert Chain VA', rom.header.cert_chain_virtual_address)
        AddIdbComment(image_base, 'Cert Chain Size', rom.header.cert_chain_size)

        # give the opportunity to keep loading mbn files into the address space
        rom_name = AskFile(0, '*.mbn', 'Choose the next ROM filename to load, or click Cancel to continue')
        if rom_name is None:
            break
        else:
            rom_data = open(rom_name, 'rb').read()

    return 1
Ejemplo n.º 6
0
def load_file(f, neflags, format):
    idaapi.set_processor_type("arm:armv8", idaapi.SETPROC_LOADER)

    f.seek(-0x20, os.SEEK_END)
    nseg, = struct.unpack("<12xI16x", f.read(0x20))
    print(f"Number of segments: {nseg}")

    for sno in range(nseg):
        f.seek(-0x20-0x20*(nseg-sno), os.SEEK_END)
        mem_addr, file_addr, size, name = struct.unpack("<QII8x8s", f.read(0x20))
        name, _, _ = name.partition(b'\0')
        name = name.decode()
        print(f"Segment {sno}: {name} at mem={hex(mem_addr)} file={hex(file_addr)} size={hex(size)}")

        ida_seg_type = None
        if name == "__TEXT":
            ida_seg_type = "CODE"
        if name == "__DATA":
            ida_seg_type = "DATA"

        idaapi.add_segm(0, mem_addr, mem_addr + size, name, ida_seg_type)
        f.file2base(file_addr, mem_addr, mem_addr + size, True)

    f.seek(-0x20-0x20*nseg, os.SEEK_END)
    footer_start = f.tell()
    footer_end = footer_start + 0x20 + 0x20 * nseg
    idaapi.add_segm(0, footer_start, footer_end, "__FOOTER", "DATA")
    f.file2base(footer_start, footer_start, footer_end, True)

    header_start = footer_start + 0x20 * nseg
    idaapi.add_extra_line(header_start, True, "")
    idaapi.add_extra_cmt(header_start, True, f"File Header")
    idaapi.create_strlit(header_start, 4, 0)
    idaapi.set_cmt(header_start, "Magic", False)
    idaapi.create_dword(header_start + 4, 4)
    idaapi.set_cmt(header_start + 4, "Version?", False)
    idaapi.create_dword(header_start + 8, 4)
    idaapi.set_cmt(header_start + 8, "File length minus headers", False)
    idaapi.create_dword(header_start + 12, 4)
    idaapi.set_cmt(header_start + 12, "Section count", False)
    for sno in range(nseg):
        header_start = footer_start + 0x20 * sno
        idaapi.add_extra_line(header_start, True, "")
        idaapi.add_extra_cmt(header_start, True, f"Segment {sno + 1}")
        idaapi.create_qword(header_start, 8)
        idaapi.set_cmt(header_start, "Memory Address", False)
        idaapi.create_dword(header_start + 8, 4)
        idaapi.set_cmt(header_start + 8, "File Offset", False)
        idaapi.create_dword(header_start + 12, 4)
        idaapi.create_qword(header_start + 16, 8)
        idaapi.set_cmt(header_start + 12, "Segment Length", False)
        idaapi.create_strlit(header_start + 24, 8, 0)
        idaapi.set_cmt(header_start + 24, "Segment Name", False)

    idaapi.add_entry(0, 0, "start", 1)

    return 1
Ejemplo n.º 7
0
def load_file(li, neflags, format):

    # Select the PC processor module
    idaapi.set_processor_type("EVM", SETPROC_ALL | SETPROC_FATAL)

    # TODO: detect and emulate contract creation code
    li.seek(0)
    buf = li.read(li.size())
    if not buf:
        return 0

    if buf[0:2] == '0x':
        print "Detected hex"
        new_buf = buf[2:].strip().rstrip()
        buf_set = set()
        for c in new_buf:
            buf_set.update(c)
        hex_set = set(list('0123456789abcdef'))
        if buf_set <= hex_set:  # subset
            print "Replacing original buffer with hex decoded version"
            buf = new_buf.decode('hex')

    # Load all shellcode into different segments
    start = 0x0
    seg = idaapi.segment_t()
    size = len(buf)
    end = start + size

    # Create the segment
    seg.startEA = start
    seg.endEA = end
    seg.bitness = 1  # 32-bit
    idaapi.add_segm_ex(seg, "evm", "CODE", 0)

    # TODO: make segments for stack, memory, storage

    # Copy the bytes
    idaapi.mem2base(buf, start, end)

    # check for swarm hash and make it data instead of code
    swarm_hash_address = buf.find('ebzzr0')
    if swarm_hash_address != -1:
        print "Swarm hash detected, making it data"
        for i in range(swarm_hash_address - 1, swarm_hash_address + 42):
            MakeByte(i)
        ida_bytes.set_cmt(swarm_hash_address - 1, "swarm hash", True)
    # add entry point
    idaapi.add_entry(start, start, "start", 1)

    # add comment to beginning of disassembly
    idaapi.describe(start, True, "EVM bytecode disassembly")

    # Mark for analysis
    AutoMark(start, AU_CODE)

    #setup_enums()
    return 1
Ejemplo n.º 8
0
def load_file(li, neflags, format):
    # pydevd_pycharm.settrace('localhost', port=1234, stdoutToServer=True, stderrToServer=True)

    fname = idaapi.get_input_file_path()
    psx = PsxExe(os.path.basename(fname), ONLY_FIRST, MIN_ENTROPY)
    psx.parse(li, True)

    idaapi.set_processor_type('mipsl', ida_idp.SETPROC_LOADER)

    idaapi.cvar.inf.af = \
        idaapi.AF_CODE | idaapi.AF_JUMPTBL | idaapi.AF_USED | idaapi.AF_UNK | idaapi.AF_PROC | idaapi.AF_STKARG | \
        idaapi.AF_REGARG | idaapi.AF_TRACE | idaapi.AF_VERSP | idaapi.AF_ANORET | idaapi.AF_MEMFUNC | \
        idaapi.AF_TRFUNC | idaapi.AF_FIXUP | idaapi.AF_JFUNC | idaapi.AF_IMMOFF | idaapi.AF_STRLIT | \
        idaapi.AF_MARKCODE | idaapi.AF_LVAR | idaapi.AF_PROCPTR | idaapi.AF_FLIRT

    psx.create_segments(li)

    im = idaapi.compiler_info_t()
    idaapi.inf_get_cc(im)
    im.id = idaapi.COMP_GNU
    im.cm = idaapi.CM_N32_F48 | idaapi.CM_M_NN | idaapi.CM_CC_CDECL
    im.defalign = 4
    im.size_i = 4
    im.size_b = 1
    im.size_e = 4
    im.size_s = 2
    im.size_l = 4
    im.size_ll = 8
    im.size_ldbl = 8
    idaapi.inf_set_cc(im)
    # Replace predefined macros and included directories by id
    # from IDA.CFG (see 'CC_PARMS' in Built-in C parser parameters)
    idaapi.set_c_macros(ida_idp.cfg_get_cc_predefined_macros(im.id))
    idaapi.set_c_header_path(ida_idp.cfg_get_cc_header_path(im.id))
    # Resetting new settings :)
    idc.set_inf_attr(idc.INF_COMPILER, im.id)

    idc.process_config_line("MIPS_DEFAULT_ABI=o32")

    detect = DetectPsyQ(psx.get_exe_name(), ONLY_FIRST, MIN_ENTROPY)
    version = detect.get_psyq_version(psx.rom_addr,
                                      psx.rom_addr + psx.rom_size)

    if len(version) > 0:
        psx.apply_psyq_signatures_by_version(version)

    idaapi.add_entry(psx.init_pc, psx.init_pc, 'start', 1)

    PsxExe.apply_til(version)

    psx.update_gp()

    return 1
Ejemplo n.º 9
0
def load_segment(li, file_ofs, code_size, load_addr, seg_name = "CODE", seg_class = "CODE", entry_name = None):
    load_end = load_addr + code_size

    AddSeg(load_addr, load_end, 0, 1, idaapi.saRelPara, idaapi.scPub)
    SetSegClass(load_addr, seg_class)
    RenameSeg(load_addr, seg_name)

    # copy bytes to the database
    li.file2base(file_ofs, load_addr, load_end, 0)

    if entry_name is not None:
        idaapi.add_entry(load_addr, load_addr, entry_name, 1)

    return 1
Ejemplo n.º 10
0
def load_segment(li, file_ofs, code_size, load_addr, seg_name="CODE", seg_class="CODE", entry_name=None):
    load_end = load_addr + code_size

    AddSeg(load_addr, load_end, 0, 1, idaapi.saRelPara, idaapi.scPub)
    SetSegClass(load_addr, seg_class)
    RenameSeg(load_addr, seg_name)

    # copy bytes to the database
    li.file2base(file_ofs, load_addr, load_end, 0)

    if entry_name is not None:
        idaapi.add_entry(load_addr, load_addr, entry_name, 1)

    return 1
def load_file_sbl(li, neflags, format):
    
    # set the processor type and enable 'metaarm' so ida disassembles all instructions
	idaapi.set_processor_type("arm:ARMv7-A&R", idaapi.SETPROC_ALL | idaapi.SETPROC_FATAL)
	idc.ChangeConfig('ARM_DEFAULT_ARCHITECTURE = metaarm')
    
    # rewind the input file and read its contents
	li.seek(0)
	init_val = li.read(li.size())

        # Load the file data (sans header) into IDA
        rom = SblImage(init_val)
        
        AddSeg(rom.header.image_dest_ptr, rom.header.image_dest_ptr + rom.header.image_size, 0, 1, idaapi.saRelPara, idaapi.scPub)
        SetSegmentType(rom.header.image_dest_ptr, idaapi.SEG_CODE)
        RenameSeg(rom.header.image_dest_ptr, "CODE")        
       # li.file2base(file_offset, seg1, seg1 + code_seg_size, 0)
        # Load the file data (sans header) into IDA
        li.file2base(80, rom.header.image_dest_ptr, rom.header.image_dest_ptr + rom.header.code_size, 0)
        

        # Define the .text .data and .bss segments
        #AddSegEx(0, rom.header.image_dest_ptr, rom.header.image_dest_ptr + rom.header.code_size, s, ".code", "CODE", ADDSEG_OR_DIE)
       # AddSegment(0, data_start, data_end, ".data", "DATA")
       # AddSegment(0, data_end, bss_end, ".bss", "BSS")
        image_base = rom.header.image_dest_ptr
        entry = rom.header.image_src
        #if DEBUG:
        #        print "Created File Segments: "
        #        print "\t.text   0x%.8X - 0x%.8X" % (entry, data_start)
        #        print "\t.data   0x%.8X - 0x%.8X" % (data_start, data_end)
        #        print "\t.bss    0x%.8X - 0x%.8X" % (data_end, bss_end)

        # mark the entry point as being the first byte of the loaded image
        idaapi.add_entry(rom.header.image_dest_ptr, rom.header.image_dest_ptr, "HEADER", 1)
        
        AddIdbComment(image_base, 'Codeword:            ', rom.header.codeword)
        AddIdbComment(image_base, 'Magic No.:           ', rom.header.magic)
        AddIdbComment(image_base, 'Source Location:     ', rom.header.image_src)
        AddIdbComment(image_base, 'Destination Address: ', rom.header.image_dest_ptr)
        AddIdbComment(image_base, 'Image Size:          ', rom.header.image_size)
        AddIdbComment(image_base, 'Code Size:           ', rom.header.code_size)
        AddIdbComment(image_base, 'Signature Ptr:       ', rom.header.sig_ptr)
        AddIdbComment(image_base, 'Signature Size:      ', rom.header.sig_size)
        AddIdbComment(image_base, 'Cert Chain Ptr:      ', rom.header.cert_chain_ptr)
        AddIdbComment(image_base, 'Cert Chain Size:     ', rom.header.cert_chain_size)
        AddIdbComment(image_base, 'OEM Cert Sel:        ', rom.header.oem_root_cert_sel)
        AddIdbComment(image_base, 'OEM Cert Num:        ', rom.header.oem_num_root_certs)

	return 1
Ejemplo n.º 12
0
def load_file(li, neflags, format):
    """
    Load the file into database

    @param li: a file-like object which can be used to access the input data
    @param neflags: options selected by the user, see loader.hpp
    @return: 0-failure, 1-ok
    """

    if format.startswith(RomFormatName):
        li.seek(0)
        header = read_struct(li, image_header)
        c = header.ih_arch
        cname = IDACPUNames[c]
        if cname == "":
            warning("Unsupported CPU")
            return

        if not header.ih_comp in (IH_COMP_NONE, IH_COMP_GZIP):
            warning("Can only handle uncompressed or gzip-compressed images")
            return

        idaapi.set_processor_type(cname, SETPROC_LOADER)

        AddSeg(header.ih_load, header.ih_load + header.ih_size, 0, 1,
               idaapi.saRelPara, idaapi.scPub)

        # copy bytes to the database

        if header.ih_comp == IH_COMP_NONE:
            li.file2base(ctypes.sizeof(header), header.ih_load,
                         header.ih_load + header.ih_size, 0)
        else:
            cdata = li.read(header.ih_size)
            d = zlib.decompressobj(zlib.MAX_WBITS | 32)
            udata = d.decompress(cdata)
            udata += d.flush()
            # expand segment to fit uncompressed data
            set_segment_bounds(header.ih_load, header.ih_load,
                               header.ih_load + len(udata), SEGMOD_KEEP)
            idaapi.put_bytes(header.ih_load, udata)

        if cname == "ARM" and (header.ih_ep & 1) != 0:
            # Thumb entry point
            header.ih_ep -= 1
            split_sreg_range(header.ih_ep, "T", 1)
        idaapi.add_entry(header.ih_ep, header.ih_ep, "start", 1)
        print "Load OK"
        return 1
Ejemplo n.º 13
0
def load_file(li, neflags, format):
    """
    Load the SEGA Master System ROM
    :param li: Loader input
    :param neflags:
    :param format:
    :return: 1 on success, otherwise 0
    """

    idaapi.set_processor_type('z80', idaapi.SETPROC_LOADER)
    is_reload = (neflags & idaapi.NEF_RELOAD) != 0
    if is_reload:
        return 1

    # Create ROM segment
    rom_seg = idaapi.segment_t()
    rom_seg.start_ea = 0x0000
    rom_seg.end_ea = 0xbfff
    rom_seg.bitness = 0
    idaapi.add_segm_ex(rom_seg, 'ROM', 'CODE', idaapi.ADDSEG_OR_DIE)

    # Read file into ROM segment
    li.seek(0)
    li.file2base(0, 0, li.size(), False)

    # Create RAM Segment
    ram_seg = idaapi.segment_t()
    ram_seg.start_ea = 0xc000
    ram_seg.end_ea = 0xdfff
    ram_seg.bitness = 0
    idaapi.add_segm_ex(ram_seg, 'RAM', 'DATA', idaapi.ADDSEG_OR_DIE)

    # Create RAM mirror segment
    ram_mirror_seg = idaapi.segment_t()
    ram_mirror_seg.start_ea = 0xe000
    ram_mirror_seg.end_ea = 0xffff
    ram_mirror_seg.bitness = 0
    idaapi.add_segm_ex(ram_mirror_seg, 'RAM_MIRROR', 'DATA',
                       idaapi.ADDSEG_OR_DIE)

    # Define the I/O ports
    create_io_ports()

    # Disassemble reset vectors
    create_reset_vectors()

    # Specify entry
    idaapi.add_entry(0x0000, 0x0000, 'RST0', 1)
    return 1
Ejemplo n.º 14
0
def load_file(li, neflags, format):
    """
    Load the file into database

    @param li: a file-like object which can be used to access the input data
    @param neflags: options selected by the user, see loader.hpp
    @return: 0-failure, 1-ok
    """

    li.seek(0)
    vmlinux = li.read(li.size())

    do_get_bits(kallsyms, vmlinux)
    do_kallsyms(kallsyms, vmlinux)
    # print_kallsyms(kallsyms, vmlinux)
    if kallsyms['arch'] == 'arm':
        idaapi.set_processor_type('arm',
                                  idaapi.SETPROC_ALL | idaapi.SETPROC_FATAL)
    elif kallsyms['arch'] == 'mips' and not kallsyms['is_big_endian']:
        idaapi.set_processor_type('mipsl',
                                  idaapi.SETPROC_ALL | idaapi.SETPROC_FATAL)
    elif kallsyms['arch'] == 'mips' and not kallsyms['is_big_endian']:
        idaapi.set_processor_type('mipsb',
                                  idaapi.SETPROC_ALL | idaapi.SETPROC_FATAL)
    elif kallsyms['arch'] == 'x86':
        idaapi.set_processor_type('metapc', idaapi.SETPROC_ALL
                                  | idaapi.SETPROC_FATAL)  #NOT tested

    if kallsyms['bits'] == 64:
        idaapi.get_inf_structure().lflags |= idaapi.LFLG_64BIT

    li.file2base(0, kallsyms['_start'], kallsyms['_start'] + li.size(), True)

    s = idaapi.segment_t()
    s.bitness = kallsyms['bits'] / 32
    s.startEA = kallsyms['_start']
    s.endEA = kallsyms['_start'] + li.size()
    idaapi.add_segm_ex(s, ".text", "CODE", idaapi.ADDSEG_OR_DIE)

    for i in xrange(kallsyms['numsyms']):
        if kallsyms['type'][i] in ['t', 'T']:
            idaapi.add_entry(kallsyms['address'][i], kallsyms['address'][i],
                             kallsyms['name'][i], 1)
        else:
            idaapi.add_entry(kallsyms['address'][i], kallsyms['address'][i],
                             kallsyms['name'][i], 0)

    print "Android/Linux vmlinux loaded..."
    return 1
Ejemplo n.º 15
0
def load_file(f, neflags, format):

    idaapi.set_processor_type('yara', idaapi.SETPROC_ALL)

    f.seek(0x0, os.SEEK_END)
    flen = f.tell()
    f.seek(0)

    hdr = parse_hdr(f)
    file_hdr = parse_file_hdr(f)
    # mark the proc type, so IDA can invoke the correct disassembler/processor.

    mapsize = hdr.size

    # map 0..mapsize from file at offset 0xc into idb (without relocation data)
    # this makes all pointers relative offsets to this mapping's start
    f.file2base(0xc, 0, flen - 0x0c, True)  # true makes it patchable
    f.seek(hdr.size + 0x0c)

    code_end = find_code_end(file_hdr) or hdr.size

    # list head shoule come right after (except some CC paddings. weirdly  t4.yara compiles some extra garbage between the code and rules_list_head)
    # note specifying CODE since it will force decoding of data that's in the section for padding
    idaapi.add_segm(0, file_hdr.code_start, code_end, ".text", "")
    # this will allow string references to work later
    idaapi.add_segm(0, 0, file_hdr.code_start, ".data", "DATA")
    idaapi.add_segm(0, code_end, mapsize, ".data", "DATA")
    idaapi.add_segm(0, mapsize, flen - 0x0c, ".reloc", "RELOC")

    parse_data_seg(hdr, file_hdr, f)
    define_consts()
    # set up entry point
    idaapi.add_entry(file_hdr.code_start, file_hdr.code_start, "start",
                     1)  # 1 means make code
    # some comments
    idaapi.describe(file_hdr.code_start, True,
                    "Compiled YARA rule disassembly")
    yaraver = '(yara {})'.format(YARA_ARENA_TO_VERSION[
        hdr.arena_ver]) if hdr.arena_ver in YARA_ARENA_TO_VERSION else ''
    idaapi.describe(file_hdr.code_start, True, "Arena version {} {}".format(
        hdr.arena_ver,
        yaraver))  # T TODO: check changes between arena versions

    idaapi.describe(file_hdr.code_start, True,
                    "max_threads: {}".format(hdr.max_threads))

    return 1
Ejemplo n.º 16
0
def load_file(li, neflags, format):
    """
    Load the file into database

    @param li: a file-like object which can be used to access the input data
    @param neflags: options selected by the user, see loader.hpp
    @return: 0-failure, 1-ok
    """

    # Select the PC processor module
    idaapi.set_processor_type("metapc", ida_idp.SETPROC_LOADER)

    # read MBR into buffer
    li.seek(0, os.SEEK_SET)
    buf = li.read(li.size())

    seg = idaapi.segment_t()
    start = 0x7C00

    size = len(buf)
    end = start + size

    # Create the segment
    seg.start_ea = start
    seg.end_ea = end
    seg.bitness = 0  # 16-bit
    idaapi.add_segm_ex(seg, "seg0", "CODE", 0)

    # Copy the bytes
    idaapi.mem2base(buf, start, end)

    # add entry point
    idaapi.add_entry(start, start, "start", 1)

    strid = add_struct_def()
    idaapi.set_name(start + 0x1BE, "MBR_PARTITION_TABLE", idaapi.SN_CHECK)
    str_size = idaapi.get_struc_size(strid)
    idaapi.create_struct(start + 0x1BE, str_size, strid)

    idaapi.set_name(510, "MBR_SIGN", idaapi.SN_CHECK)

    # Mark for analysis
    AutoMark(start, AU_CODE)

    load_debugger("bochs", 0)

    return 1
Ejemplo n.º 17
0
def load_file(f, neflags, format):
    f.seek(0)

    magic = f.read(4)
    version = struct.unpack("<I", f.read(4))[0]
    flags = struct.unpack("<I", f.read(4))[0]
    memType = struct.unpack("<I", f.read(4))[0]
    serviceType = struct.unpack("<I", f.read(4))[0]
    numInstances = struct.unpack("<I", f.read(4))[0]
    uuid = struct.unpack("<IIII", f.read(16))
    driverId = struct.unpack("<I", f.read(4))[0]
    numThreads = struct.unpack("<I", f.read(4))[0]
    textVA = struct.unpack("<I", f.read(4))[0]
    textLen = struct.unpack("<I", f.read(4))[0]
    dataVA = struct.unpack("<I", f.read(4))[0]
    dataLen = struct.unpack("<I", f.read(4))[0]
    bssLen = struct.unpack("<I", f.read(4))[0]
    entry = struct.unpack("<I", f.read(4))[0]

    f.seek(MCLF_TEXT_INFO_OFFSET)

    idaapi.set_processor_type("arm", ida_idp.SETPROC_LOADER_NON_FATAL)

    # Set VA for .text and add the segment
    f.file2base(0, textVA, textVA + textLen, True)
    idaapi.add_segm(0, textVA, textVA + textLen, ".text", "CODE")

    # Set VA for .data and add the segment
    f.file2base(textLen, dataVA, dataVA + dataLen, True)
    idaapi.add_segm(0, dataVA, dataVA + dataLen, ".data", "DATA")

    # Add BSS segment after .text and .data
    idaapi.add_segm(0, dataVA + dataLen, dataVA + dataLen + bssLen, ".bss",
                    "BSS")

    if entry % 4 == 1:
        #Thumb address is always +1 to set the T bit
        idaapi.add_entry(entry - 1, entry - 1, "_entry", 1)
        idc.split_sreg_range(entry - 1, "T", 0x1, ida_segregs.SR_user)
    else:
        idaapi.add_entry(entry, entry, "_entry", 1)
        idc.split_sreg_range(entry, "T", 0x0, ida_segregs.SR_user)

    ida_bytes.create_data(tlApiLibEntry, idaapi.FF_DWORD, 4, idaapi.BADADDR)
    idc.set_name(tlApiLibEntry, "tlApiLibEntry", ida_name.SN_CHECK)
    return 1
Ejemplo n.º 18
0
def load_file(f, neflags, format):
    f.seek(0)

    magic = f.read(4)
    version = struct.unpack("<I", f.read(4))[0]
    flags = struct.unpack("<I", f.read(4))[0]
    memType = struct.unpack("<I", f.read(4))[0]
    serviceType = struct.unpack("<I", f.read(4))[0]
    numInstances = struct.unpack("<I", f.read(4))[0]
    uuid = struct.unpack("<IIII", f.read(16))
    driverId = struct.unpack("<I", f.read(4))[0]
    numThreads = struct.unpack("<I", f.read(4))[0]
    textVA = struct.unpack("<I", f.read(4))[0]
    textLen = struct.unpack("<I", f.read(4))[0]
    dataVA = struct.unpack("<I", f.read(4))[0]
    dataLen = struct.unpack("<I", f.read(4))[0]
    bssLen = struct.unpack("<I", f.read(4))[0]
    entry = struct.unpack("<I", f.read(4))[0]

    f.seek(MCLF_TEXT_INFO_OFFSET)

    idaapi.set_processor_type("arm", SETPROC_ALL)

    # Set VA for .text and add the segment
    f.file2base(0, textVA, textVA + textLen, True)
    idaapi.add_segm(0, textVA, textVA + textLen, ".text", "CODE")

    # Set VA for .data and add the segment
    f.file2base(MCLF_HEADER_SIZE_V23 + textLen, dataVA, dataVA + dataLen, True)
    idaapi.add_segm(0, dataVA, dataVA + dataLen, ".data", "DATA")

    # Add BSS segment after .text and .data
    idaapi.add_segm(0, dataVA + dataLen, dataVA + dataLen + bssLen, ".bss",
                    "BSS")

    if entry % 4 == 1:
        #Thumb address is always +1 to set the T bit
        idaapi.add_entry(entry - 1, entry - 1, "_entry", 1)
        SetRegEx(entry - 1, "T", 0x1, SR_user)
    else:
        idaapi.add_entry(entry, entry, "_entry", 1)
        SetRegEx(entry, "T", 0x0, SR_user)

    MakeDword(tlApiLibEntry)
    MakeName(tlApiLibEntry, "tlApiLibEntry")
    return 1
Ejemplo n.º 19
0
def find_aboot_segs(image_dest):

    inst = DecodeInstruction(image_dest)
    reset_func = image_dest
    if inst.get_canon_mnem() == "B":
        reset_func = inst.Op1.addr

    search_start = reset_func
    search_end = search_start + 0x100

    data_insts = FindBinary(search_start, SEARCH_DOWN, "4C 00 ?? ?? 4C 10 ?? ?? 4C 20 ?? ??")
    if data_insts == BADADDR or data_insts > search_end:
        return False

    data_start = Dword(DecodeInstruction(data_insts + 4).Op2.addr)
    data_end = Dword(DecodeInstruction(data_insts + 8).Op2.addr)
    data_end = (data_end + 3) & ~3

    AddSeg(data_start, data_end, 0, 1, idaapi.saRelPara, idaapi.scPub)
    SetSegClass(data_start, "DATA")
    RenameSeg(data_start, "DATA")

    bss_insts = FindBinary(data_insts, SEARCH_DOWN, "34 00 ?? ?? 34 10 ?? ??")
    if bss_insts == BADADDR or bss_insts > search_end:
        return False

    bss_start = Dword(DecodeInstruction(bss_insts + 0).Op2.addr)
    bss_end = Dword(DecodeInstruction(bss_insts + 4).Op2.addr)

    AddSeg(bss_start, bss_end, 0, 1, idaapi.saRelPara, idaapi.scPub)
    SetSegClass(bss_start, "BSS")
    RenameSeg(bss_start, "BSS")

    kmain_addr = FindBinary(bss_insts, SEARCH_DOWN, "?? ?? 00 FA")
    if kmain_addr == BADADDR or kmain_addr > search_end:
        return False

    kmain_addr = DecodeInstruction(kmain_addr).Op1.addr
    MakeName(kmain_addr, "kmain")
    idaapi.add_entry(kmain_addr, kmain_addr, "kmain", 1)
    return True
Ejemplo n.º 20
0
def find_aboot_segs(image_dest):

    inst = DecodeInstruction(image_dest)
    reset_func = image_dest
    if inst.get_canon_mnem() == 'B':
        reset_func = inst.Op1.addr

    search_start = reset_func
    search_end = search_start + 0x100

    data_insts = FindBinary(search_start, SEARCH_DOWN, "4C 00 ?? ?? 4C 10 ?? ?? 4C 20 ?? ??")
    if data_insts == BADADDR or data_insts > search_end:
        return False

    data_start = Dword(DecodeInstruction(data_insts + 4).Op2.addr)
    data_end = Dword(DecodeInstruction(data_insts + 8).Op2.addr)
    data_end = (data_end + 3) & ~3

    AddSeg(data_start, data_end, 0, 1, idaapi.saRelPara, idaapi.scPub)
    SetSegClass(data_start, "DATA")
    RenameSeg(data_start, "DATA")

    bss_insts = FindBinary(data_insts, SEARCH_DOWN, "34 00 ?? ?? 34 10 ?? ??")
    if bss_insts == BADADDR or bss_insts > search_end:
        return False

    bss_start = Dword(DecodeInstruction(bss_insts + 0).Op2.addr)
    bss_end = Dword(DecodeInstruction(bss_insts + 4).Op2.addr)

    AddSeg(bss_start, bss_end, 0, 1, idaapi.saRelPara, idaapi.scPub)
    SetSegClass(bss_start, "BSS")
    RenameSeg(bss_start, "BSS")

    kmain_addr = FindBinary(bss_insts, SEARCH_DOWN, "?? ?? 00 FA")
    if kmain_addr == BADADDR or kmain_addr > search_end:
        return False

    kmain_addr = DecodeInstruction(kmain_addr).Op1.addr
    MakeName(kmain_addr, "kmain")
    idaapi.add_entry(kmain_addr, kmain_addr, "kmain", 1)
    return True
Ejemplo n.º 21
0
def load_file(li, neflags, format):
    """
    Load the file into database

    @param li: a file-like object which can be used to access the input data
    @param neflags: options selected by the user, see loader.hpp
    @return: 0-failure, 1-ok
    """

    li.seek(0)
    vmlinux = li.read(li.size())

    do_get_arch(kallsyms, vmlinux)
    do_kallsyms(kallsyms, vmlinux)
    # print_kallsyms(kallsyms, vmlinux)
    
    if kallsyms['numsyms'] == 0:
        print '[!]get kallsyms error...'
        return 0
    
    idaapi.set_processor_type("arm", SETPROC_ALL|SETPROC_FATAL)
    if kallsyms['arch'] == 64:
        idaapi.get_inf_structure().lflags |= idaapi.LFLG_64BIT

    li.file2base(0, kallsyms['_start'], kallsyms['_start']+li.size(), True)

    s = idaapi.segment_t()
    s.bitness = kallsyms['arch'] / 32
    s.startEA = kallsyms['_start']
    s.endEA = kallsyms['_start']+li.size()
    idaapi.add_segm_ex(s,".text","CODE",ADDSEG_OR_DIE)
    
    for i in xrange(kallsyms['numsyms']):
        if kallsyms['type'][i] in ['t','T']:
            idaapi.add_entry(kallsyms['address'][i], kallsyms['address'][i], kallsyms['name'][i], 1)
        else:
            idaapi.add_entry(kallsyms['address'][i], kallsyms['address'][i], kallsyms['name'][i], 0)

    print "Android vmlinux loaded..."
    return 1
Ejemplo n.º 22
0
def load_file(li, neflags, format):

    """
    Load the file into database

    @param li: a file-like object which can be used to access the input data
    @param neflags: options selected by the user, see loader.hpp
    @return: 0-failure, 1-ok
    """

    if format.startswith(RomFormatName):
        li.seek(0)
        header = read_struct(li, image_header)
        c = header.ih_arch
        cname = IDACPUNames[c]
        if cname == "":
          Warning("Unsupported CPU")
          return

        if header.ih_comp != IH_COMP_NONE:
          Warning("Cannot load compressed images")
          return

        idaapi.set_processor_type(cname, SETPROC_ALL|SETPROC_FATAL)

        AddSeg(header.ih_load, header.ih_load + header.ih_size, 0, 1, idaapi.saRelPara, idaapi.scPub)

        # copy bytes to the database
        li.file2base(ctypes.sizeof(header), header.ih_load, header.ih_load + header.ih_size, 0)

        if cname == "ARM" and (header.ih_ep & 1) != 0:
          # Thumb entry point
          header.ih_ep -= 1
          SetReg(header.ih_ep, "T", 1)
        idaapi.add_entry(header.ih_ep, header.ih_ep, "start", 1)
        print "Load OK"
        return 1
Ejemplo n.º 23
0
 def addIDA_entry(self):
     idaapi.add_entry(self.PC, self.PC, '_start', 1)
Ejemplo n.º 24
0
def load_file(li, neflags, format):
    if format != ROM_FORMAT_NAME:
        Warning("Unknown format name: '%s'" % format)
        return 0
    idaapi.set_processor_type("M6502", SETPROC_ALL | SETPROC_FATAL)
    li.seek(0, idaapi.SEEK_END)
    size = li.tell()

    # RAM
    idc.AddSeg(RAM_START, RAM_START + RAM_SIZE, 0, 0, idaapi.saRelPara,
               idaapi.scPub)
    idc.RenameSeg(RAM_START, "RAM")

    li.seek(0x6)
    CartTypeLSB = struct.unpack("<B", li.read(1))[0]
    # SRAM
    if (((CartTypeLSB & 0x2) >> 1) == 1):
        idc.AddSeg(SRAM_START, SRAM_START + SRAM_SIZE, 0, 0, idaapi.saRelPara,
                   idaapi.scPub)
        idc.RenameSeg(SRAM_START, "SRAM")

    # EXPROM
    idc.AddSeg(EXPROM_START, EXPROM_START + EXPROM_SIZE, 0, 0,
               idaapi.saRelPara, idaapi.scPub)
    idc.RenameSeg(EXPROM_START, "EXPROM")

    # TRAINER
    if (((CartTypeLSB & 0x4) >> 2) == 1):
        idc.AddSeg(TRAINER_START, TRAINER_START + TRAINER_SIZE, 0, 0,
                   idaapi.saRelPara, idaapi.scPub)
        idc.RenameSeg(TRAINER_START, "TRAINER")

    # ROM
    idc.AddSeg(ROM_START, ROM_START + ROM_SIZE, 0, 0, idaapi.saRelPara,
               idaapi.scPub)
    idc.RenameSeg(ROM_START, "ROM")
    idc.SetSegmentType(ROM_START, idc.SEG_CODE)

    CartTypeMSB = struct.unpack("<B", li.read(1))[0]
    mapper_version = (((CartTypeLSB & 0xF0) >> 4) | (CartTypeMSB & 0xF0))
    if (mapper_version == MAPPER_NONE or mapper_version == MAPPER_MMC1
            or mapper_version == MAPPER_UxROM or mapper_version == MAPPER_CNROM
            or mapper_version == MAPPER_MMC3 or mapper_version == MAPPER_MMC5
            or mapper_version == MAPPER_CAMERIC
            or mapper_version == MAPPER_GNROM):
        li.seek(0x4)
        prg_rom_size = struct.unpack("<B", li.read(1))[0]
        if (prg_rom_size != 0):
            offset = HEADER_SIZE
            if (((CartTypeLSB & 0x4) >> 2) == 1):
                offset += TRAINER_SIZE
            li.seek(offset)
            li.file2base(0, ROM_START, ROM_START + PRG_PAGE_SIZE, 0)
            offset = HEADER_SIZE + (prg_rom_size - 1) * PRG_PAGE_SIZE
            if (((CartTypeLSB & 0x4) >> 2) == 1):
                offset += TRAINER_SIZE
            li.seek(offset)
            li.file2base(0, ROM_START + PRG_PAGE_SIZE,
                         ROM_START + PRG_PAGE_SIZE + PRG_PAGE_SIZE, 0)

    elif (mapper_version == MAPPER_MMC2):
        print("Second case mapper")
    elif (mapper_version == MAPPER_AxROM
          or mapper_version == MAPPER_COLOR_DREAMS
          or mapper_version == MAPPER_BxROM):
        print("Third case mapper")
    else:
        print("Mapper %d is not supported" % mapper_version)

    naming()
    idaapi.add_entry(Word(0xFFFC), Word(0xFFFC), "start", 1)
    idaapi.cvar.inf.startIP = Word(0xFFFC)
    idaapi.cvar.inf.beginEA = Word(0xFFFC)
    header_info(li, 0xFFEF)

    print("[+] Load OK")
    return 1
Ejemplo n.º 25
0
def load_file(fd, neflags, format):
    global prologues
    global br_flag
    size = 0
    base_addr = 0
    ea = 0
    nfunc = 0

    idaapi.set_processor_type("arm", ida_idp.SETPROC_LOADER_NON_FATAL)
    idaapi.get_inf_structure().lflags |= idaapi.LFLG_64BIT

    if (neflags & idaapi.NEF_RELOAD) != 0:
        return 1

    fd.seek(0, idaapi.SEEK_END)
    size = fd.tell()

    segm = idaapi.segment_t()
    segm.bitness = 2  # 64-bit
    segm.start_ea = 0
    segm.end_ea = size

    if br_flag == false:
        idaapi.add_segm_ex(segm, "iBoot", "CODE", idaapi.ADDSEG_OR_DIE)
    else:
        idaapi.add_segm_ex(segm, "SecureROM", "CODE", idaapi.ADDSEG_OR_DIE)

    fd.seek(0)
    fd.file2base(0, 0, size, false)

    idaapi.add_entry(0, 0, "start", 1)
    ida_funcs.add_func(ea)

    print("[+] Marked as code")

    # heuristic
    while (true):
        mnemonic = idc.print_insn_mnem(ea)

        if "LDR" in mnemonic:
            base_str = idc.print_operand(ea, 1)
            base_addr = int(base_str.split("=")[1], 16)

            break

        ea += 4

    print("[+] Rebasing to address 0x%x" % (base_addr))
    idaapi.rebase_program(base_addr, idc.MSF_NOFIX)

    segment_start = base_addr
    segment_end = idc.get_segm_attr(segment_start, idc.SEGATTR_END)

    ea = segment_start

    print("[+] Searching and defining functions")

    for prologue in prologues:
        while ea != ida_idaapi.BADADDR:
            ea = ida_search.find_binary(ea, segment_end, prologue, 16,
                                        ida_search.SEARCH_DOWN)

            if ea != ida_idaapi.BADADDR:
                if len(prologue) < 8:
                    ea = ea - 2

                if (ea % 4) == 0 and ida_bytes.get_full_flags(ea) < 0x200:
                    # print("[+] Defining a function at 0x%x" % (ea))
                    ida_funcs.add_func(ea)
                    nfunc = nfunc + 1

                ea = ea + 4

    idc.plan_and_wait(segment_start, segment_end)

    print("[+] Identified %d new functions" % (nfunc))

    print("[+] Looking for interesting functions")
    find_interesting(segment_start, segment_end)

    return 1
Ejemplo n.º 26
0
def load_file(fd, neflags, format):
    size = 0
    base_addr = 0
    ea = 0

    idaapi.set_processor_type("arm", idaapi.SETPROC_ALL)
    idaapi.get_inf_structure().lflags |= idaapi.LFLG_64BIT

    if (neflags & idaapi.NEF_RELOAD) != 0:
        return 1

    fd.seek(0, idaapi.SEEK_END)
    size = fd.tell()

    segm = idaapi.segment_t()
    segm.bitness = 2  # 64-bit
    segm.start_ea = 0
    segm.end_ea = size
    idaapi.add_segm_ex(segm, "iBoot", "CODE", idaapi.ADDSEG_OR_DIE)

    fd.seek(0)
    fd.file2base(0, 0, size, false)

    idaapi.add_entry(0, 0, "start", 1)
    idc.MakeFunction(ea)

    print("[+] Marked as code")

    # heuristic
    while (true):
        mnemonic = idc.GetMnem(ea)

        if "LDR" in mnemonic:
            base_str = idc.GetOpnd(ea, 1)
            base_addr = int(base_str.split("=")[1], 16)

            break

        ea += 4

    print("[+] Rebasing to address 0x%x" % (base_addr))
    idaapi.rebase_program(base_addr, idc.MSF_NOFIX)
    idaapi.autoWait()

    segment_start = base_addr
    segment_end = idc.GetSegmentAttr(segment_start, idc.SEGATTR_END)

    ea = segment_start

    print("[+] Searching and defining functions")

    while ea != idc.BADADDR:
        ea = idc.FindBinary(ea, idc.SEARCH_DOWN, "BF A9", 16)

        if ea != idc.BADADDR:
            ea = ea - 2

            if (ea % 4) == 0 and idc.GetFlags(ea) < 0x200:
                # print("[+] Defining a function at 0x%x" % (ea))
                idc.MakeFunction(ea)

            ea = ea + 4

    idc.AnalyzeArea(segment_start, segment_end)
    idaapi.autoWait()

    return 1


# EOF
Ejemplo n.º 27
0
def load_file(li, neflags, format):
    if format != ROM_FORMAT_NAME:
        Warning("Unknown format name: '%s'" % format)
        return 0
    jump = dwordAt(li, 0)
    # Test ARM branch
    if jump & 0xFF000000 != 0xEA000000:
        Warning("Unknown format name: '%s'" % format)
        return 0
    idaapi.set_processor_type("arm", SETPROC_ALL | SETPROC_FATAL)
    li.seek(0, idaapi.SEEK_END)
    size = li.tell()

    # Adding Header Section
    idc.AddSeg(ROM_START, ROM_START + SIZE_HEADER, 0, 1, idaapi.saRelPara,
               idaapi.scPub)
    idc.RenameSeg(ROM_START, "HEADER")
    idc.SetSegmentType(ROM_START, idc.SEG_CODE)
    li.seek(0)
    li.file2base(0, ROM_START, ROM_START + SIZE_HEADER, 0)

    # Adding OEP
    idaapi.add_entry(ROM_START, ROM_START, "start", 1)
    idaapi.cvar.inf.startIP = ROM_START
    idaapi.cvar.inf.beginEA = ROM_START

    # Adding ROM Section
    idc.AddSeg(ROM_START + SIZE_HEADER, ROM_START + (ROM_SIZE - SIZE_HEADER),
               0, 1, idaapi.saRelPara, idaapi.scPub)
    idc.RenameSeg(ROM_START + SIZE_HEADER, "ROM")
    idc.SetSegmentType(ROM_START + SIZE_HEADER, idc.SEG_CODE)
    li.seek(SIZE_HEADER)
    li.file2base(0, ROM_START + SIZE_HEADER, ROM_START + size, 0)

    # Adding EWRAM
    idc.AddSeg(0x02000000, 0x02040000, 0, 1, idaapi.saRelPara, idaapi.scPub)
    idc.RenameSeg(0x02000000, "EWRAM")
    memset_seg(0x02000000, 0x40000)

    # Adding IWRAM
    idc.AddSeg(0x03000000, 0x03008000, 0, 1, idaapi.saRelPara, idaapi.scPub)
    idc.RenameSeg(0x03000000, "IWRAM")
    memset_seg(0x03000000, 0x8000)

    # Adding IO / Registers
    idc.AddSeg(0x04000000, 0x04000400, 0, 1, idaapi.saRelPara, idaapi.scPub)
    idc.RenameSeg(0x04000000, "IOregisters")
    memset_seg(0x04000000, 0x400)

    # Adding BIOS System ROM
    idc.AddSeg(0x00000000, 0x00004000, 0, 1, idaapi.saRelPara, idaapi.scPub)
    idc.RenameSeg(0x00000000, "BIOS")
    memset_seg(0x00000000, 0x4000)
    idc.SetSegmentType(0x0000000, idc.SEG_CODE)

    idaapi.add_long_cmt(ROM_START, True, "ROM HEADER")
    li.seek(0xA0)
    idc.ExtLinA(ROM_START, 1, "; Game Title : %s" % li.read(12))
    idc.ExtLinA(ROM_START, 2, "; Game Code : %s" % li.read(4))
    idc.ExtLinA(ROM_START, 3, "; Marker Code : %s" % li.read(2))
    idc.ExtLinA(ROM_START, 4,
                "; Fixed value : %02X" % struct.unpack("<B", li.read(1))[0])
    idc.ExtLinA(ROM_START, 5,
                "; Main unit code : %02X" % struct.unpack("<B", li.read(1))[0])
    idc.ExtLinA(ROM_START, 6,
                "; Device type : %02X" % struct.unpack("<B", li.read(1))[0])
    idc.ExtLinA(ROM_START, 7, "; Reserved Area : db 7 dup(0)")
    li.read(7)
    idc.ExtLinA(ROM_START, 8,
                "; Software version %02X" % struct.unpack("<B", li.read(1))[0])
    idc.ExtLinA(ROM_START, 9,
                "; Complement Check %02X" % struct.unpack("<B", li.read(1))[0])
    idc.ExtLinA(ROM_START, 10, "; Reserved Area : db 2 dup(0)")

    io_naming()
    print("[+] Load OK")
    return 1
Ejemplo n.º 28
0
def load_file(li, neflags, format):
    '''
    Load the file into database

    @param li: a file-like object which can be used to access the input data
    @param neflags: options selected by the user, see loader.hpp
    @return: 0-failure, 1-ok
    '''
    idaapi.set_processor_type('cLEMENCy',
                              idaapi.SETPROC_USER | idaapi.SETPROC_FATAL)
    li.seek(0)
    fileLen = li.size()
    data = convert(li.read(fileLen))
    if len(data) > 0x4000000:
        # program too large
        return 0

    idaname = "ida64" if __EA64__ else "ida"
    if sys.platform == "win32":
        _mod = ctypes.windll[idaname + ".wll"]
    elif sys.platform == "linux2":
        _mod = ctypes.cdll["lib" + idaname + ".so"]
    elif sys.platform == "darwin":
        _mod = ctypes.cdll["lib" + idaname + ".dylib"]
    create_bytearray_linput = _mod.create_bytearray_linput
    create_bytearray_linput.argtypes = (idaapi.POINTER(ctypes.c_ubyte),
                                        ctypes.c_int)
    create_bytearray_linput.restype = ctypes.c_int
    bufPointer = idaapi.cast(data, idaapi.POINTER(ctypes.c_ubyte))
    retlinput = create_bytearray_linput(bufPointer,
                                        int(fileLen * 8 / 9 * 16 / 8))
    file2base = _mod.file2base
    file2base.argtypes = (ctypes.c_int, ctypes.c_int, ctypes.c_int,
                          ctypes.c_int, ctypes.c_int)
    file2base.restype = ctypes.c_int
    file2base(retlinput, 0, 0, int(fileLen * 8 / 9), idaapi.FILEREG_PATCHABLE)

    seg = idaapi.segment_t()
    seg.startEA = 0
    seg.endEA = 0x4000000
    # seg.bitness = 1
    idaapi.add_segm_ex(seg, "PROGRAM", "CODE", idaapi.ADDSEG_SPARSE)
    seg = idaapi.segment_t()
    seg.startEA = 0x4000000
    seg.endEA = 0x400001e
    idaapi.add_segm_ex(seg, "CLOCKIO", "RAM", idaapi.ADDSEG_SPARSE)
    seg = idaapi.segment_t()
    seg.startEA = 0x4010000
    seg.endEA = 0x4011000
    idaapi.add_segm_ex(seg, "FLAGIO", "RAM", idaapi.ADDSEG_SPARSE)
    seg = idaapi.segment_t()
    seg.startEA = 0x5000000
    seg.endEA = 0x5002000
    idaapi.add_segm_ex(seg, "RDATA", "RAM", idaapi.ADDSEG_SPARSE)
    seg = idaapi.segment_t()
    seg.startEA = 0x5002000
    seg.endEA = 0x5002003
    idaapi.add_segm_ex(seg, "RDATASZ", "RAM", idaapi.ADDSEG_SPARSE)
    seg = idaapi.segment_t()
    seg.startEA = 0x5010000
    seg.endEA = 0x5012000
    idaapi.add_segm_ex(seg, "SDATA", "RAM", idaapi.ADDSEG_SPARSE)
    seg = idaapi.segment_t()
    seg.startEA = 0x5012000
    seg.endEA = 0x5012003
    idaapi.add_segm_ex(seg, "SDATASZ", "RAM", idaapi.ADDSEG_SPARSE)
    seg = idaapi.segment_t()
    seg.startEA = 0x6000000
    seg.endEA = 0x6800000
    idaapi.add_segm_ex(seg, "SHMEM", "RAM", idaapi.ADDSEG_SPARSE)
    seg = idaapi.segment_t()
    seg.startEA = 0x6800000
    seg.endEA = 0x7000000
    idaapi.add_segm_ex(seg, "NVRAM", "RAM", idaapi.ADDSEG_SPARSE)
    seg = idaapi.segment_t()
    seg.startEA = 0x7FFFF00
    seg.endEA = 0x7FFFF1C
    idaapi.add_segm_ex(seg, "IVEC", "RAM", idaapi.ADDSEG_SPARSE)
    seg = idaapi.segment_t()
    seg.startEA = 0x7FFFF80
    seg.endEA = 0x8000000
    idaapi.add_segm_ex(seg, "PROCID", "RAM", idaapi.ADDSEG_SPARSE)
    idaapi.add_entry(0, 0, "_start", True)
    # idc.AutoMark( 0, AU_CODE )
    idaapi.cvar.inf.tribyte_order = idaapi.tbo_213
    return 1
Ejemplo n.º 29
0
def load_file(li, neflags, format):
    
    """
    Load the file into database

    @param li: a file-like object which can be used to access the input data
    @param neflags: options selected by the user, see loader.hpp
    @return: 0-failure, 1-ok
    """

    if format == _3DSX_FORMAT_NAME:
    
        idaapi.set_processor_type("arm", SETPROC_ALL|SETPROC_FATAL)
        
        li.seek(0)

        (magic, header_size, reloc_header_size, format_ver, flags, code_seg_size, rodata_seg_size, data_seg_size, bss_seg_size) = struct.unpack("<IHHIIIIII", li.read(4*8))
        
        #print(hex(header_size))
        #print(hex(reloc_header_size))
        #print(hex(code_seg_size))
        #print(hex(rodata_seg_size))
        #print(hex(data_seg_size))
        #print(hex(bss_seg_size))
        
        #CODE SEGMENT
        seg1 = CN_3DSX_LOADADR
        seg1_size = (code_seg_size + 0xFFF) &(~0xFFF)
        file_offset = header_size + reloc_header_size*3
        
        AddSeg(seg1, seg1 + seg1_size, 0, 1, idaapi.saRelPara, idaapi.scPub)
        SetSegmentType(seg1, idaapi.SEG_CODE)
        RenameSeg(seg1, "CODE")        
        li.file2base(file_offset, seg1, seg1 + code_seg_size, 0)

        
        #RO_DATA SEGMENT
        seg2 = seg1 + seg1_size
        seg2_size = (rodata_seg_size + 0xFFF) &(~0xFFF)
        file_offset += code_seg_size
        
        AddSeg(seg2, seg2 + seg2_size, 0, 1, idaapi.saRelPara, idaapi.scPub)
        SetSegmentType(seg2, idaapi.SEG_DATA)
        RenameSeg(seg2, "RODATA")
        li.file2base(file_offset, seg2, seg2 + rodata_seg_size, 0)
        
        #DATA SEGMENT
        seg3 = seg2 + seg2_size
        seg3_size = (data_seg_size + 0xFFF) &(~0xFFF)
        file_offset += rodata_seg_size
        
        AddSeg(seg3, seg3 + seg3_size, 0, 1, idaapi.saRelPara, idaapi.scPub)
        SetSegmentType(seg3, idaapi.SEG_DATA)
        RenameSeg(seg3, "DATA")
        li.file2base(file_offset, seg3, seg3 + (data_seg_size - bss_seg_size), 0)
        
        #relocations
        relocs_ptr = file_offset + (data_seg_size - bss_seg_size)
        
        segments = [seg1, seg2, seg3]
        
        for rel_table in range(3):
        
            li.seek(header_size + rel_table * 8)
            (abs_count, rel_count) = struct.unpack("<II", li.read(4*2))
        
            li.seek(relocs_ptr)
            relocs_ptr = relocs_ptr + (abs_count * 4 + rel_count * 4)

            pos = segments[rel_table]
            
            #absolute relocations
            for i in range(abs_count):
                (skip, patches) = struct.unpack("<HH", li.read(2*2))
                
                pos += skip * 4
                for x in range(patches):
                    
                    addr = Dword(pos)
                    if addr < seg1_size:
                        addr = seg1 + addr
                    elif addr < (seg1_size + seg2_size):
                        addr = seg2 + addr - seg1_size
                    else:
                        addr = seg3 + addr - (seg1_size + seg2_size)

                    PatchDword(pos, addr)
                    SetFixup(pos, idaapi.FIXUP_OFF32 or idaapi.FIXUP_CREATED, 0, addr, 0)
                    pos += 4
                    
            # cross-segment relative relocations
            for i in range(rel_count):
                (skip, patches) = struct.unpack("<HH", li.read(2*2))
                
                pos += skip * 4
                for x in range(patches):
                    
                    addr = Dword(pos)
                    if addr < seg1_size:
                        addr = seg1 + addr
                    elif addr < (seg1_size + seg2_size):
                        addr = seg2 + addr - seg1_size
                    else:
                        addr = seg3 + addr - (seg1_size + seg2_size)
                    
                    PatchDword(pos, addr - pos)
                    SetFixup(pos, idaapi.FIXUP_OFF32 or idaapi.FIXUP_CREATED, 0, addr - pos, 0)
                    pos += 4                    
        
        idaapi.add_entry(CN_3DSX_LOADADR, CN_3DSX_LOADADR, "start", 1)
        idaapi.analyze_area(seg1, seg1 + seg1_size)
        
        print "Load OK"
        return 1
    
    return 0
def load_file_mbn(li, neflags, format):
    
    # set the processor type and enable 'metaarm' so ida disassembles all instructions
	idaapi.set_processor_type("arm:ARMv7-A&R", idaapi.SETPROC_ALL | idaapi.SETPROC_FATAL)
	idc.ChangeConfig('ARM_DEFAULT_ARCHITECTURE = metaarm')

    # rewind the input file and read its contents
	li.seek(0)
	init_val = li.read(li.size())

        # Load the file data (sans header) into IDA
        rom = MbnImage(init_val)
        
        #CODE SEGMENT
        #seg1_size = (rom.header.image_dest_ptr + 0xFFF) &(~0xFFF)
        #file_offset = header_size + reloc_header_size*3
        
        AddSeg(rom.header.image_dest_ptr, rom.header.image_dest_ptr + rom.header.image_size, 0, 1, idaapi.saRelPara, idaapi.scPub)
        SetSegmentType(rom.header.image_dest_ptr, idaapi.SEG_CODE)
        RenameSeg(rom.header.image_dest_ptr, "CODE")

       # li.file2base(file_offset, seg1, seg1 + code_seg_size, 0)
        # Load the file data (sans header) into IDA
        li.file2base(40, rom.header.image_dest_ptr, rom.header.image_dest_ptr + rom.header.code_size, 0)
        #AddSegment('%s_code' % rom, rom.code_base, rom.code_data)
        #if rom.sig_data is not None: AddSegment('%s_sig' % rom, rom.sig_base, rom.sig_data) RenameSeg(rom.header.image_dest_ptr, "CODE")
        #if rom.cert_data is not None: AddSegment('%s_cert' % rom, rom.cert_base, rom.cert_data)
        #if rom.tail_data is not None: AddSegment('%s_tail' % rom, rom.tail_base, rom.tail_data)
        
        
        #dataseg = rom.header.image_dest_ptr
        #dataseg_size = init_val
        #filofs = rom.header.code_size
        #AddSeg(dataseg, rom.header.image_dest_ptr + rom.header.image_size, 0, 1, idaapi.saRelPara, idaapi.scPub)
        #SetSegmentType(dataseg, idaapi.SEG_DATA)
        #RenameSeg(dataseg, "DATA")
        #li.file2base(rom.header.image_dest_ptr, dataseg, dataseg + rom.header.image_dest_ptr + rom.header.image_size, 0)
        # Define the .text .data and .bss segments
        #AddSegEx(rom.header.image_dest_ptr, rom.header.image_dest_ptr + rom.header.code_size, 0, 1, ".code", "CODE", ADDSEG_OR_DIE)
        #AddSegment(0, data_start, data_end, ".data", "DATA")
        #AddSegment(0, data_end, bss_end, ".bss", "BSS")
        image_base = rom.header.image_dest_ptr
        entry = image_base - rom.header.image_src
            #if DEBUG:
            #        print "Created File Segments: "
            #   print "\t.text   0x%.8X - 0x%.8X" % (entry, data_start)
            #   print "\t.data   0x%.8X - 0x%.8X" % (data_start, data_end)
            #   print "\t.bss    0x%.8X - 0x%.8X" % (data_end, bss_end)

        # mark the entry point as being the first byte of the loaded image
        idaapi.add_entry(rom.header.image_dest_ptr, rom.header.image_dest_ptr, "HEADER", 1)
        
        AddIdbComment(image_base, 'Flash Part Version:  ', rom.header.flash_parti_ver)
        AddIdbComment(image_base, 'Source Location:     ', rom.header.image_src)
        AddIdbComment(image_base, 'Destination Address: ', rom.header.image_dest_ptr)
        AddIdbComment(image_base, 'Image Size:          ', rom.header.image_size)
        AddIdbComment(image_base, 'Code Size:           ', rom.header.code_size)
        AddIdbComment(image_base, 'Signature Ptr:       ', rom.header.sig_ptr)
        AddIdbComment(image_base, 'Signature Size:      ', rom.header.sig_size)
        AddIdbComment(image_base, 'Cert Chain Ptr:      ', rom.header.cert_chain_ptr)
        AddIdbComment(image_base, 'Cert Chain Size:     ', rom.header.cert_chain_size)

	return 1
Ejemplo n.º 31
0
def load_file(li, neflags, format):

    """
    Load the file into database

    @param li: a file-like object which can be used to access the input data
    @param neflags: options selected by the user, see loader.hpp
    @return: 0-failure, 1-ok
    """

    if format == FormatName:
        idaapi.set_processor_type("dsp56k", SETPROC_ALL | SETPROC_FATAL)
        li.seek(0)
        s = gets(li)
        minprog = BADADDR
        maxprog = 0
        start_addr = 0
        chunk = ""
        clist = ChunkList()
        while True:
            if s == None:
                break
            s = s.strip()
            if len(s) == 0 or s.startswith(" "):
                s = gets(li)
                continue
            words = s.split()
            if s.startswith("_START "):
                # skip
                s = gets(li)
                continue
            elif s.startswith("_DATA"):
                # _DATA <Memory space> <Address> <Code/data> ...
                if len(words) < 3:
                    idaapi.error("Bad _DATA record: %s" % s)
                # we handle only P (program) memory
                if not words[1] in ("P", "X", "Y"):
                    idaapi.error("Unhandled _DATA memory space: %s" % words[1])
                if not ishex(words[2]):
                    idaapi.error("Bad _DATA starting address: %s" % words[2])

                if len(chunk):
                    # append current chunk to the list
                    clist.add_chunk(start_addr, chunk, cur_mem)

                # start a new chunk
                cur_mem = words[1]
                start_addr = int(words[2], 16)
                chunk = make_chunk(words[3:], cur_mem)

                s = gets(li)
                continue
            elif s.startswith("_END"):
                if len(words) < 2 or not ishex(words[1]):
                    idaapi.error("Bad _END record: %s" % s)

                # append current chunk to the list
                clist.add_chunk(start_addr, chunk, cur_mem)

                # load all
                clist.load_to_idb()

                # add the entrypoint
                entry_ea = int(words[1], 16)
                idaapi.add_entry(entry_ea, entry_ea, "start", 1)
                break
            elif s.startswith("_"):
                idaapi.error("Unhandled record type: %s" % words[0])

            # we're inside a _DATA record
            chunk += make_chunk(words, cur_mem)
            s = gets(li)

        print "Load OK"
        return 1

    Warning("Unknown format name: '%s'" % format)
    return 0
Ejemplo n.º 32
0
def load_file(li, neflags, format):
    """
    Load the file into database

    @param li: a file-like object which can be used to access the input data
    @param neflags: options selected by the user, see loader.hpp
    @return: 0-failure, 1-ok
    """

    li.seek(0)
    vmlinux = li.read(li.size())

    do_get_arch(kallsyms, vmlinux)
    do_kallsyms(kallsyms, vmlinux)

    if kallsyms['numsyms'] == 0:
        print_log('[!]get kallsyms error...')
        return 0

    idaapi.set_processor_type("arm", idaapi.SETPROC_ALL | idaapi.SETPROC_FATAL)
    if kallsyms['arch'] == 64:
        idaapi.get_inf_structure().lflags |= idaapi.LFLG_64BIT

    li.file2base(0, kallsyms['_start'], kallsyms['_start'] + li.size(), True)

    sinittext_addr = 0
    max_sym_addr = 0
    for i in range(kallsyms['numsyms']):
        if kallsyms['arch'] == 32:
            if kallsyms['address'][i] > 0xd0000000:
                continue

        if kallsyms['name'][i] == '_sinittext':
            sinittext_addr = kallsyms['address'][i]
        if kallsyms['address'][i] > max_sym_addr:
            max_sym_addr = kallsyms['address'][i]
    max_sym_addr = max_sym_addr + 1024
    print_log("max_sym_addr = ", hex(max_sym_addr))

    if (kallsyms['_start'] + li.size()) > max_sym_addr:
        max_sym_addr = kallsyms['_start'] + li.size()

    s = idaapi.segment_t()
    s.bitness = kallsyms['arch'] // 32
    s.startEA = kallsyms['_start']
    if sinittext_addr == 0:
        s.endEA = max_sym_addr
    else:
        s.endEA = sinittext_addr
    s.perm = 5
    idaapi.add_segm_ex(s, ".text", "CODE", idaapi.ADDSEG_OR_DIE)

    if sinittext_addr > 0:
        s = idaapi.segment_t()
        s.bitness = kallsyms['arch'] // 32
        s.startEA = sinittext_addr
        s.endEA = max_sym_addr
        s.perm = 7
        idaapi.add_segm_ex(s, ".data", "DATA", idaapi.ADDSEG_OR_DIE)

    for i in range(kallsyms['numsyms']):
        if kallsyms['type'][i] in ['t', 'T']:
            idaapi.add_entry(kallsyms['address'][i], kallsyms['address'][i],
                             kallsyms['name'][i], 1)
        else:
            idaapi.add_entry(kallsyms['address'][i], kallsyms['address'][i],
                             kallsyms['name'][i], 0)

    print_log("Android/Linux vmlinux loaded...")
    return 1
Ejemplo n.º 33
0
def load_file(li, neflags, format):
    if format != ROM_FORMAT_NAME:
        Warning("Unknown format name: '%s'" % format)
        return 0
    idaapi.set_processor_type("M6502", SETPROC_ALL | SETPROC_FATAL)

    li.seek(0, idaapi.SEEK_END)
    size = li.tell()

    li.seek(0, idaapi.SEEK_SET)
    nheader = NES_HEADER.from_buffer_copy(li.read(LEN_NES_HEADER))

    # RAM SEGMENT
    idc.AddSeg(RAM_START, RAM_START + RAM_SIZE, 0, 0, idaapi.saRelPara, idaapi.scPub)
    idc.RenameSeg(RAM_START, "RAM")
    zeromemory(RAM_START, RAM_SIZE)

    # IOREG SEGMENT
    idc.AddSeg(IOREG_START, IOREG_START + IOREG_SIZE, 0, 0, idaapi.saRelPara, idaapi.scPub)
    idc.RenameSeg(IOREG_START, "IOREG")
    zeromemory(IOREG_START, IOREG_SIZE)

    # SRAM SEGMENT
    # bit 1 : Cartridge contains battery-backed PRG RAM ($6000-7FFF) or other persistent memory
    if (nheader.rom_control_byte_0 & 0x02) != 0x00:
        idc.AddSeg(SRAM_START, SRAM_START + SRAM_SIZE, 0, 0, idaapi.saRelPara, idaapi.scPub)
        idc.RenameSeg(SRAM_START, "SRAM")
        zeromemory(SRAM_START, SRAM_SIZE)

    # EXPROM SEGMENT
    idc.AddSeg(EXPROM_START, EXPROM_START + EXPROM_SIZE, 0, 0, idaapi.saRelPara, idaapi.scPub)
    idc.RenameSeg(EXPROM_START, "EXPROM")
    zeromemory(EXPROM_START, EXPROM_SIZE)

    # TRAINER SEGMENT
    # bit 2 : 512-byte trainer at $7000-$71FF (stored before PRG data)
    if (nheader.rom_control_byte_0 & 0x04) != 0x00:
        idc.AddSeg(TRAINER_START, TRAINER_START + TRAINER_SIZE, 0, 0, idaapi.saRelPara, idaapi.scPub)
        idc.RenameSeg(TRAINER_START, "TRAINER")
        zeromemory(TRAINER_START, TRAINER_SIZE)

    # ROM SEGMENT
    idc.AddSeg(ROM_START, ROM_START + ROM_SIZE, 0, 0, idaapi.saRelPara, idaapi.scPub)
    idc.RenameSeg(ROM_START, "ROM")
    idc.SetSegmentType(ROM_START, idc.SEG_CODE | idc.SEG_DATA)
    zeromemory(ROM_START, ROM_SIZE)

    describe_header_info(li)

    mapper_version = (((nheader.rom_control_byte_0 & 0xF0) >> 4) | (nheader.rom_control_byte_1 & 0xF0))
    if (mapper_version == MAPPER_NONE or
        mapper_version == MAPPER_MMC1 or
        mapper_version == MAPPER_UxROM or
        mapper_version == MAPPER_CNROM or
        mapper_version == MAPPER_MMC3 or
        mapper_version == MAPPER_MMC5 or
        mapper_version == MAPPER_CAMERIC or
        mapper_version == MAPPER_GNROM):
            offset = LEN_NES_HEADER
            if (nheader.rom_control_byte_0 & 0x04) != 0x00:
                offset = offset + TRAINER_SIZE
            offset = offset
            li.file2base(offset, ROM_START, ROM_START + PRG_PAGE_SIZE, 0)
            offset = LEN_NES_HEADER
            if (nheader.rom_control_byte_0 & 0x04) != 0x00:
                offset = offset + TRAINER_SIZE
            offset = offset + (nheader.nb_prg_page_16k - 1) * PRG_PAGE_SIZE
            li.file2base(offset, ROM_START + PRG_PAGE_SIZE, ROM_START + PRG_PAGE_SIZE + PRG_PAGE_SIZE, 0)
            offset = LEN_NES_HEADER
            if (nheader.rom_control_byte_0 & 0x04) != 0x00:
                offset = offset + TRAINER_SIZE
            offset = offset + PRG_PAGE_SIZE * nheader.nb_prg_page_16k
            li.file2base(offset, RAM_START, RAM_START + CHR_PAGE_SIZE, 0)
    elif (mapper_version == MAPPER_MMC2):
        Warning("Second case mapper")
    elif (mapper_version == MAPPER_AxROM or
        mapper_version == MAPPER_COLOR_DREAMS or
        mapper_version == MAPPER_BxROM):
        Warning("Third case mapper")
    else:
        Warning("Mapper %d is not supported" % mapper_version)

    naming()

    idaapi.add_entry(Word(0xFFFC), Word(0xFFFC), "start", 1)
    idaapi.cvar.inf.startIP = Word(0xFFFC)
    idaapi.cvar.inf.beginEA = Word(0xFFFC)
    return 1
Ejemplo n.º 34
0
def pe_load(li):
    global directory_entry_headers
    global base_address
    global entry_point
    global xex_magic

    # Get size of the PE
    li.seek(0, 2)  # seek to end
    pe_size = li.tell()

    # Read DOS & NT headers
    li.seek(0)
    dos_header = read_struct(li, ImageDOSHeader)
    if dos_header.MZSignature != 0x5A4D:
        print("[+] PE has invalid ImageDOSHeader.MZSignature! (0x%x)" %
              dos_header.MZSignature)
        return 0

    li.seek(dos_header.AddressOfNewExeHeader)
    nt_header = read_struct(li, ImageNTHeaders)
    if nt_header.Signature != 0x4550:
        print("[+] PE has invalid ImageNTHeaders.Signature! (0x%x)" %
              nt_header.Signature)
        return 0

    # Skip past PE data directories (for now? will we ever need them?)
    li.seek(nt_header.OptionalHeader.NumberOfRvaAndSizes * 8, os.SEEK_CUR)

    # Use base address from optionalheader if we don't already have one
    if base_address <= 0:
        base_address = nt_header.OptionalHeader.ImageBase

    # If no EP passed we'll use EP from the optionalheader
    if entry_point <= 0:
        entry_point = base_address + nt_header.OptionalHeader.AddressOfEntryPoint

    # Read in & map our section headers
    # (todo: fix loading more sections than needed, seems sections like .reloc shouldn't be loaded in?)
    section_headers = []
    for i in range(0, nt_header.FileHeader.NumberOfSections):
        section_headers.append(read_struct(li, ImageSectionHeader))

    for section in section_headers:
        sec_addr = section.VirtualAddress if xex_magic != _MAGIC_XEX3F else section.PointerToRawData
        sec_size = min(section.VirtualSize, section.SizeOfRawData)

        if sec_addr + sec_size > pe_size:
            sec_size = pe_size - sec_addr

        # Load em if you got em
        if sec_size <= 0:
            continue

        pe_add_section(section)

        # Load data into IDB
        li.seek(sec_addr)
        ida_loader.mem2base(li.read(sec_size),
                            base_address + section.VirtualAddress)

    # Name the EP if we have one
    if entry_point > 0:
        idaapi.add_entry(entry_point, entry_point, "start", 1)

    # PE load complete :)
    return 1
Ejemplo n.º 35
0
def addEntry(name, ea, ordinal=None):
    '''addEntry(name, ea, index?) -> adds an entry point to the database'''
    return idaapi.add_entry(idaapi.get_entry_qty() if ordinal is None else ordinal, ea, name, 0)
Ejemplo n.º 36
0
def load_cro(li, is_crs):
    if is_crs:
        base = 0
    else:
        base = 0x00100000 # arbitrary

    li.seek(0x80)
    (Magic,
    NameOffset,
    NextCRO,
    PreviousCRO,
    FileSize,
    BssSize,
    FixedSize,
    UnknownZero,
    UnkSegmentTag,
    OnLoadSegmentTag,
    OnExitSegmentTag,
    OnUnresolvedSegmentTag,

    CodeOffset,
    CodeSize,
    DataOffset,
    DataSize,
    ModuleNameOffset,
    ModuleNameSize,
    SegmentTableOffset,
    SegmentNum,

    ExportNamedSymbolTableOffset,
    ExportNamedSymbolNum,
    ExportIndexedSymbolTableOffset,
    ExportIndexedSymbolNum,
    ExportStringsOffset,
    ExportStringsSize,
    ExportTreeTableOffset,
    ExportTreeNum,

    ImportModuleTableOffset,
    ImportModuleNum,
    ExternalPatchTableOffset,
    ExternalPatchNum,
    ImportNamedSymbolTableOffset,
    ImportNamedSymbolNum,
    ImportIndexedSymbolTableOffset,
    ImportIndexedSymbolNum,
    ImportAnonymousSymbolTableOffset,
    ImportAnonymousSymbolNum,
    ImportStringsOffset,
    ImportStringsSize,

    StaticAnonymousSymbolTableOffset,
    StaticAnonymousSymbolNum,
    InternalPatchTableOffset,
    InternalPatchNum,
    StaticPatchTableOffset,
    StaticPatchNum) = struct.unpack("<IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII", li.read(0x138 - 0x80))

    if not is_crs:
        li.file2base(0, base, base + FileSize, 0)

    # set segments
    li.seek(SegmentTableOffset)
    segmentDic = [
        ("CODE", ".text"),
        ("DATA", ".rodata"),
        ("DATA", ".data"),
        ("BSS", ".bss")
    ]
    segmentAddress = []
    for i in range(SegmentNum):
        SegmentOffset, SegmentSize, SegmentType = struct.unpack("<III", li.read(12))
        if SegmentType == 3:
            SegmentOffset = 0x08000000
            idaapi.enable_flags(base + SegmentOffset, base + SegmentOffset + SegmentSize, idaapi.STT_VA)

        segmentAddress.append(base + SegmentOffset)
        if SegmentSize :
            idaapi.add_segm(0, segmentAddress[i], segmentAddress[i] + SegmentSize, segmentDic[SegmentType][1], segmentDic[SegmentType][0])

    # do internal relocations
    li.seek(InternalPatchTableOffset)
    for i in range(InternalPatchNum):
        target, patch_type, source, _, _, shift = struct.unpack("<IBBBBI", li.read(12))
        target_offset = DecodeTag(segmentAddress, target)
        source_offset = segmentAddress[source] + shift
        if patch_type == 2:
            value = source_offset
        elif patch_type == 3:
            rel = source_offset - target_offset
            if rel < 0:
                rel += 0x100000000
            value = rel
        idaapi.patch_long(target_offset, value)
        f = idaapi.fixup_data_t()
        f.type = idaapi.FIXUP_OFF32
        f.off = value
        idaapi.set_fixup(target_offset, f)

    # import
    li.seek(ImportNamedSymbolTableOffset)
    importNamedSymbolTable = []
    for i in range(ImportNamedSymbolNum):
        importNamedSymbolTable.append(struct.unpack('<II', li.read(8)))

    for importNamedSymbol in importNamedSymbolTable:
        nameOffset, batchOffset = importNamedSymbol
        li.seek(nameOffset)
        name = ""
        while True:
            c = li.read(1)
            if c == '\0':
                break
            name += c
        do_import_batch(li, segmentAddress, batchOffset, name)

    li.seek(ImportModuleTableOffset)
    module = []
    for i in range(ImportModuleNum):
        module.append(struct.unpack('<IIIII', li.read(20)))

    for m in module:
        moduleNameOffset, indexed, indexedNum, anonymous, anonymousNum = m
        li.seek(moduleNameOffset)
        mname = ""
        while True:
            c = li.read(1)
            if c == '\0':
                break
            mname += c

        indexeds = []
        li.seek(indexed)
        for i in range(indexedNum):
            indexeds.append(struct.unpack('<II', li.read(8)))

        anonymouses = []
        li.seek(anonymous)
        for i in range(anonymousNum):
            anonymouses.append(struct.unpack('<II', li.read(8)))

        for i in indexeds:
            index, batchOffset = i
            do_import_batch(li, segmentAddress, batchOffset, "%s_%d"%(mname, index))

        for i in anonymouses:
            tag, batchOffset = i
            do_import_batch(li, segmentAddress, batchOffset, "%s_%08X"%(mname, tag))

    # export
    li.seek(ExportNamedSymbolTableOffset)
    exportNamedSymbolTable = []
    for i in range(ExportNamedSymbolNum):
        exportNamedSymbolTable.append(struct.unpack('<II', li.read(8)))

    for exportNamedSymbol in exportNamedSymbolTable:
        nameOffset, target = exportNamedSymbol
        target_offset = DecodeTag(segmentAddress, target)
        li.seek(nameOffset)
        name = ""
        while True:
            c = li.read(1)
            if c == '\0':
                break
            name += c
        idaapi.add_entry(target_offset, target_offset, name, idaapi.segtype(target_offset) == idaapi.SEG_CODE)
        idaapi.make_name_public(target_offset)

    li.seek(ExportIndexedSymbolTableOffset)
    for i in range(ExportIndexedSymbolNum):
        target, = struct.unpack('<I', li.read(4))
        target_offset = DecodeTag(segmentAddress, target)
        idaapi.add_entry(i, target_offset, "indexedExport_%d" % i, idaapi.segtype(target_offset) == idaapi.SEG_CODE)
        idaapi.make_name_public(target_offset)
Ejemplo n.º 37
0
    def load_one_file(li, options, idx, basename=None):
        bypass_plt = OPT_BYPASS_PLT in options

        f = load_nxo(li)

        if idx == 0:
            if f.armv7:
                idc.SetShortPrm(idc.INF_LFLAGS, idc.GetShortPrm(idc.INF_LFLAGS) | idc.LFLG_PC_FLAT)
            else:
                idc.SetShortPrm(idc.INF_LFLAGS, idc.GetShortPrm(idc.INF_LFLAGS) | idc.LFLG_64BIT)

            idc.SetCharPrm(idc.INF_DEMNAMES, idaapi.DEMNAM_GCC3)
            idaapi.set_compiler_id(idaapi.COMP_GNU)
            idaapi.add_til2('gnulnx_arm' if f.armv7 else 'gnulnx_arm64', 1)
            # don't create tails
            idc.set_inf_attr(idc.INF_AF, idc.get_inf_attr(idc.INF_AF) & ~idc.AF_FTAIL)

        if OPT_LOAD_31_BIT in options:
            loadbase = 0x8000000
            step = 0x1000000
        elif f.armv7:
            loadbase = 0x60000000
            step = 0x10000000
        else:
            loadbase = 0x7100000000
            step = 0x100000000
        loadbase += idx * step

        f.binfile.seek(0)
        as_string = f.binfile.read(f.bssoff)
        idaapi.mem2base(as_string, loadbase)

        seg_prefix = basename if basename is not None else ''
        for start, end, name, kind in f.sections:
            if name.startswith('.got'):
                kind = 'CONST'
            idaapi.add_segm(0, loadbase+start, loadbase+end, seg_prefix+name, kind)
            segm = idaapi.get_segm_by_name(seg_prefix+name)
            if kind == 'CONST':
                segm.perm = idaapi.SEGPERM_READ
            elif kind == 'CODE':
                segm.perm = idaapi.SEGPERM_READ | idaapi.SEGPERM_EXEC
            elif kind == 'DATA':
                segm.perm = idaapi.SEGPERM_READ | idaapi.SEGPERM_WRITE
            elif kind == 'BSS':
                segm.perm = idaapi.SEGPERM_READ | idaapi.SEGPERM_WRITE
            idaapi.update_segm(segm)
            idaapi.set_segm_addressing(segm, 1 if f.armv7 else 2)

        # do imports
        # TODO: can we make imports show up in "Imports" window?
        undef_count = 0
        for s in f.symbols:
            if not s.shndx and s.name:
                undef_count += 1
        last_ea = max(loadbase + end for start, end, name, kind in f.sections)
        undef_entry_size = 8
        undef_ea = ((last_ea + 0xFFF) & ~0xFFF) + undef_entry_size # plus 8 so we don't end up on the "end" symbol

        undef_seg = basename + '.UNDEF' if basename is not None else 'UNDEF'
        idaapi.add_segm(0, undef_ea, undef_ea+undef_count*undef_entry_size, undef_seg, 'XTRN')
        segm = idaapi.get_segm_by_name(undef_seg)
        segm.type = idaapi.SEG_XTRN
        idaapi.update_segm(segm)
        for i,s in enumerate(f.symbols):
            if not s.shndx and s.name:
                idc.MakeQword(undef_ea)
                idaapi.do_name_anyway(undef_ea, s.name)
                s.resolved = undef_ea
                undef_ea += undef_entry_size
            elif i != 0:
                assert s.shndx
                s.resolved = loadbase + s.value
                if s.name:
                    if s.type == STT_FUNC:
                        idaapi.add_entry(s.resolved, s.resolved, s.name, 0)
                    else:
                        idaapi.do_name_anyway(s.resolved, s.name)

            else:
                # NULL symbol
                s.resolved = 0

        funcs = set()
        for s in f.symbols:
            if s.name and s.shndx and s.value:
                if s.type == STT_FUNC:
                    funcs.add(loadbase+s.value)
                    symend = loadbase+s.value+s.size
                    if Dword(symend) != 0:
                        funcs.add(symend)

        got_name_lookup = {}
        for offset, r_type, sym, addend in f.relocations:
            target = offset + loadbase
            if r_type in (R_ARM_GLOB_DAT, R_ARM_JUMP_SLOT, R_ARM_ABS32):
                if not sym:
                    print 'error: relocation at %X failed' % target
                else:
                    idaapi.put_long(target, sym.resolved)
            elif r_type == R_ARM_RELATIVE:
                idaapi.put_long(target, idaapi.get_long(target) + loadbase)
            elif r_type in (R_AARCH64_GLOB_DAT, R_AARCH64_JUMP_SLOT, R_AARCH64_ABS64):
                idaapi.put_qword(target, sym.resolved + addend)
                if addend == 0:
                    got_name_lookup[offset] = sym.name
            elif r_type == R_AARCH64_RELATIVE:
                idaapi.put_qword(target, loadbase + addend)
                if addend < f.textsize:
                    funcs.add(loadbase + addend)
            else:
                print 'TODO r_type %d' % (r_type,)
            ida_make_offset(f, target)

        for func, target in f.plt_entries:
            if target in got_name_lookup:
                addr = loadbase + func
                funcs.add(addr)
                idaapi.do_name_anyway(addr, got_name_lookup[target])

        if not f.armv7:
            funcs |= find_bl_targets(loadbase, loadbase+f.textsize)

            if bypass_plt:
                plt_lookup = f.plt_lookup
                for pco in xrange(0, f.textsize, 4):
                    pc = loadbase + pco
                    d = Dword(pc)
                    if (d & 0x7c000000) == (0x94000000 & 0x7c000000):
                        imm = d & 0x3ffffff
                        if imm & 0x2000000:
                            imm |= ~0x1ffffff
                        if 0 <= imm <= 2:
                            continue
                        target = (pc + imm * 4) - loadbase
                        if target in plt_lookup:
                            new_target = plt_lookup[target] + loadbase
                            new_instr = (d & ~0x3ffffff) | (((new_target - pc) / 4) & 0x3ffffff)
                            idaapi.put_long(pc, new_instr)

            for pco in xrange(0, f.textsize, 4):
                pc = loadbase + pco
                d = Dword(pc)
                if d == 0x14000001:
                    funcs.add(pc + 4)

        for pc, _ in f.eh_table:
            funcs.add(loadbase + pc)

        for addr in sorted(funcs, reverse=True):
            idaapi.auto_make_proc(addr)

        return 1
Ejemplo n.º 38
0
def load_file(li, neflags, format):
    if format != ROM_FORMAT_NAME:
        Warning("Unknown format name: '%s'" % format)
        return 0
    jump = dwordAt(li, 0)
    # Test ARM branch
    if jump & 0xFF000000 != 0xEA000000:
        Warning("Unknown format name: '%s'" % format)
        return 0
    idaapi.set_processor_type("arm", SETPROC_ALL | SETPROC_FATAL)
    li.seek(0, idaapi.SEEK_END)
    size = li.tell()

    # Adding Header Section
    idc.AddSeg(ROM_START, ROM_START + SIZE_HEADER, 0, 1, idaapi.saRelPara, idaapi.scPub)
    idc.RenameSeg(ROM_START, "HEADER")
    idc.SetSegmentType(ROM_START, idc.SEG_CODE)
    li.seek(0)
    li.file2base(0, ROM_START, ROM_START + SIZE_HEADER, 0)

    # Adding OEP
    idaapi.add_entry(ROM_START, ROM_START, "start", 1)
    idaapi.cvar.inf.startIP = ROM_START
    idaapi.cvar.inf.beginEA = ROM_START

    # Adding ROM Section
    idc.AddSeg(ROM_START + SIZE_HEADER, ROM_START + (ROM_SIZE - SIZE_HEADER), 0, 1, idaapi.saRelPara, idaapi.scPub)
    idc.RenameSeg(ROM_START + SIZE_HEADER, "ROM")
    idc.SetSegmentType(ROM_START + SIZE_HEADER, idc.SEG_CODE)
    li.seek(SIZE_HEADER)
    li.file2base(0, ROM_START + SIZE_HEADER, ROM_START + size, 0)

    # Adding EWRAM
    idc.AddSeg(0x02000000, 0x02040000, 0, 1, idaapi.saRelPara, idaapi.scPub)
    idc.RenameSeg(0x02000000, "EWRAM")
    memset_seg(0x02000000, 0x40000)

    # Adding IWRAM
    idc.AddSeg(0x03000000, 0x03008000, 0, 1, idaapi.saRelPara, idaapi.scPub)
    idc.RenameSeg(0x03000000, "IWRAM")
    memset_seg(0x03000000, 0x8000)

    # Adding IO / Registers
    idc.AddSeg(0x04000000, 0x04000400, 0, 1, idaapi.saRelPara, idaapi.scPub)
    idc.RenameSeg(0x04000000, "IOregisters")
    memset_seg(0x04000000, 0x400)

    # Adding BIOS System ROM
    idc.AddSeg(0x00000000, 0x00004000, 0, 1, idaapi.saRelPara, idaapi.scPub)
    idc.RenameSeg(0x00000000, "BIOS")
    memset_seg(0x00000000, 0x4000)
    idc.SetSegmentType(0x0000000, idc.SEG_CODE)

    idaapi.add_long_cmt(ROM_START, True, "ROM HEADER")
    li.seek(0xA0)
    idc.ExtLinA(ROM_START, 1, "; Game Title : %s" % li.read(12))
    idc.ExtLinA(ROM_START, 2, "; Game Code : %s" % li.read(4))
    idc.ExtLinA(ROM_START, 3, "; Marker Code : %s" % li.read(2))
    idc.ExtLinA(ROM_START, 4, "; Fixed value : %02X" % struct.unpack("<B", li.read(1))[0])
    idc.ExtLinA(ROM_START, 5, "; Main unit code : %02X" % struct.unpack("<B", li.read(1))[0])
    idc.ExtLinA(ROM_START, 6, "; Device type : %02X" % struct.unpack("<B", li.read(1))[0])
    idc.ExtLinA(ROM_START, 7, "; Reserved Area : db 7 dup(0)")
    li.read(7)
    idc.ExtLinA(ROM_START, 8, "; Software version %02X" % struct.unpack("<B", li.read(1))[0])
    idc.ExtLinA(ROM_START, 9, "; Complement Check %02X" % struct.unpack("<B", li.read(1))[0])
    idc.ExtLinA(ROM_START, 10, "; Reserved Area : db 2 dup(0)")

    io_naming()
    print("[+] Load OK")
    return 1
Ejemplo n.º 39
0
def load_file(li, neflags, format):
    """
    Load the file into database

    @param li: a file-like object which can be used to access the input data
    @param neflags: options selected by the user, see loader.hpp
    @return: 0-failure, 1-ok
    """
    if format == AtariSTTOSImageName:
        idaapi.set_processor_type('68K', ida_idp.SETPROC_LOADER)

        li.seek(0)
        header = read_struct(li, tos_image_header)

        li.seek(0, idaapi.SEEK_END)
        filesize = li.tell()

        idc.add_segm_ex(header.os_beg, header.os_beg + filesize, 0, 1,
                        idaapi.saRelPara, idaapi.scPub, idc.ADDSEG_NOSREG)
        idc.set_segm_name(header.os_beg, 'TOS')

        li.seek(0)
        li.file2base(0, header.os_beg, header.os_beg + filesize, 0)

        idaapi.add_entry(header.os_beg, header.os_beg, "ostext", 1)
        idc.set_cmt(header.os_beg, 'branch to reset handler', 0)
        idc.set_name(header.os_beg + 2, 'os_version')
        idc.create_word(header.os_beg + 2)
        idc.set_cmt(header.os_beg + 2, 'OS version number', 0)
        idc.set_cmt(header.os_beg + 4, '-> system reset handler', 0)
        reseth = ida_bytes.get_dword(header.os_beg + 4)
        idc.set_name(reseth, 'reseth')
        idc.set_name(header.os_beg + 8, 'os_beg')
        idc.set_cmt(header.os_beg + 8, '-> base of OS', 0)
        idc.set_name(header.os_beg + 12, 'os_end')
        idc.set_cmt(header.os_beg + 12, '-> end of OS memory usage', 0)
        os_end = ida_bytes.get_dword(header.os_beg + 12)
        idc.add_segm_ex(0x0, os_end, 0, 1, idaapi.saRelPara, idaapi.scPub,
                        idc.ADDSEG_NOSREG)
        idc.set_segm_name(0x0, 'DOSRAM')
        idc.set_name(os_end, 'endos')
        idc.set_name(header.os_beg + 16, 'os_exec')
        idc.set_cmt(header.os_beg + 16, '-> default shell', 0)
        idc.set_name(header.os_beg + 20, 'os_magic')
        idc.set_cmt(header.os_beg + 20, '-> GEM magic (or NULL)', 0)
        idc.set_name(header.os_beg + 24, 'os_date')
        idc.create_dword(header.os_beg + 24)
        idc.set_cmt(header.os_beg + 24, 'date the system was built', 0)
        idc.set_name(header.os_beg + 28, 'os_conf')
        idc.create_word(header.os_beg + 28)
        idc.set_cmt(header.os_beg + 28, 'configuration bits', 0)
        idc.set_name(header.os_beg + 30, 'os_dosdate')
        idc.create_word(header.os_beg + 30)
        idc.set_cmt(header.os_beg + 30, 'DOS-format date the system was built',
                    0)
        addr = header.os_beg + 32
        while addr < reseth:
            if addr == header.os_beg + 0x20:
                idc.set_cmt(addr, 'base of GEMDOS pool', 0)
                idc.set_name(ida_bytes.get_dword(addr), '_root')
            elif addr == header.os_beg + 0x24:
                idc.set_cmt(addr, '-> keyboard shift-state byte', 0)
                idc.set_name(ida_bytes.get_dword(addr), 'kbshift')
            elif addr == header.os_beg + 0x28:
                idc.set_cmt(addr, '-> current process', 0)
                idc.set_name(ida_bytes.get_dword(addr), '_run')
            elif addr == header.os_beg + 0x2c:
                idc.set_cmt(addr, 'reserved for future use', 0)
            idc.create_dword(addr)
            addr += 4

        the_magic = ida_bytes.get_dword(header.os_beg + 20)
        gem_end = ida_bytes.get_dword(the_magic + 4)
        aes_init = ida_bytes.get_dword(the_magic + 8)
        idc.add_segm_ex(os_end, gem_end + 1, 0, 1, idaapi.saRelPara,
                        idaapi.scPub, idc.ADDSEG_NOSREG)
        idc.set_segm_name(os_end, 'GEMRAM')

        idc.set_name(the_magic, 'the_magic')
        idc.create_dword(the_magic)
        idc.set_cmt(the_magic, '$87654321 if GEM present', 0)
        idc.create_dword(the_magic + 4)
        idc.set_cmt(the_magic + 4, 'End address of OS RAM usage', 0)
        idc.create_dword(the_magic + 8)
        idc.set_cmt(the_magic + 8, 'Execution address of GEM', 0)
        idaapi.add_entry(aes_init, aes_init, "gem_entry", 1)
        idc.set_name(gem_end, 'gem_end')

        idaapi.auto_wait()
        return 1

    elif format == AtariSTProgramName:
        idaapi.set_processor_type('68K', ida_idp.SETPROC_LOADER)

        li.seek(0)
        header = read_struct(li, gemdos_executable_header)

        base_addr = AtariSTBaseAddress

        text_addr = base_addr
        data_addr = text_addr + header.PRG_tsize
        bss_addr = data_addr + header.PRG_dsize
        idc.add_segm_ex(text_addr, text_addr + header.PRG_tsize, 0, 1,
                        idaapi.saRelPara, idaapi.scPub, idc.ADDSEG_NOSREG)
        idc.set_segm_name(text_addr, 'tseg')
        idc.add_segm_ex(data_addr, data_addr + header.PRG_dsize, 0, 1,
                        idaapi.saRelPara, idaapi.scPub, idc.ADDSEG_NOSREG)
        idc.set_segm_name(data_addr, 'dseg')
        idc.add_segm_ex(bss_addr, bss_addr + header.PRG_bsize, 0, 1,
                        idaapi.saRelPara, idaapi.scPub, idc.ADDSEG_SPARSE)
        idc.set_segm_name(bss_addr, 'bseg')
        li.file2base(ctypes.sizeof(gemdos_executable_header), text_addr,
                     text_addr + header.PRG_tsize + header.PRG_dsize, 0)

        # relocate the application
        li.seek(0, idaapi.SEEK_END)
        filesize = li.tell()
        li.seek(0, idaapi.SEEK_SET)
        relocDataOffset = ctypes.sizeof(
            gemdos_executable_header
        ) + header.PRG_tsize + header.PRG_dsize + header.PRG_ssize
        li.seek(relocDataOffset)
        relocData = li.read(filesize - relocDataOffset)
        roffset = 4
        rea = struct.unpack('>I', relocData[:roffset])[0]
        if rea != 0:
            rea = rea + base_addr
            idc.patch_dword(rea, ida_bytes.get_dword(rea) + base_addr)
            if rea >= data_addr:  # in the DATA segment, make sure it is an actual pointer
                idc.create_dword(rea)
            while True:
                offset = ord(relocData[roffset])
                roffset += 1
                if offset == 0:  # end of the relocation table
                    break
                if offset == 1:  # odd numbers are not valid, 1 is a special case to skip 254 bytes without relocating
                    rea += 254
                    continue
                rea += offset
                idc.patch_dword(rea, ida_bytes.get_dword(rea) + base_addr)
                if rea >= data_addr:  # in the DATA segment, make sure it is an actual pointer
                    idc.create_dword(rea)

        # apply a symbol table, if part of the file
        if header.PRG_ssize:
            symboltableDataOffset = ctypes.sizeof(
                gemdos_executable_header) + header.PRG_tsize + header.PRG_dsize
            li.seek(symboltableDataOffset)
            symboltableData = li.read(header.PRG_ssize)
            soffset = 0
            while soffset < header.PRG_ssize:
                entry = symboltableData[soffset:soffset + 14]
                soffset += 14
                name = entry[:8]
                flags, value = struct.unpack('>HL', entry[8:])
                if (
                        flags & 0x0048
                ) and soffset + 14 < header.PRG_ssize:  # GST extended DRI symbol format?
                    entry = symboltableData[soffset:soffset + 14]
                    soffset += 14
                    name += entry[:8]
                if (
                        flags & 0xf000
                ) == 0xa000:  # global defined symbol? (registers, etc are not supported)
                    value += text_addr  # relocate the value
                    if (flags & 0xf00) == 0x0100:  # BSS
                        idc.set_name(value, name)
                    elif (flags & 0xf00) == 0x0200:  # TEXT
                        idaapi.add_entry(value, value, name, 1)
                    elif (flags & 0xf00) == 0x0400:  # DATA
                        idc.set_name(value, name)

        idaapi.add_entry(text_addr, text_addr, "start", 1)
        idaapi.plan_and_wait(text_addr, text_addr + header.PRG_tsize)
        idaapi.auto_wait()
        return 1

    return 0
Ejemplo n.º 40
0
def load_file(li, neflags, format):
    li.seek(0)
    ndsRom = NintendoDSRom(li.read(li.size()))
    retval = 1

    useArm9 = ask_yn(
        1,
        "This ROM potentially contains both ARM9 and ARM7 code\nDo you want to load the ARM9 binary?"
    )
    if (useArm9 == -1):
        useArm9 = 0

    useArm9 = bool(useArm9)

    proc = ""
    startEA = 0
    endEA = 0
    offset = 0
    entryAddr = 0
    size = 0
    name = ""
    rom = ""
    if (useArm9):
        name = "ARM9 ROM"
        proc = "ARM"
        entryAddr = ndsRom.arm9EntryAddress
        startEA = ndsRom.arm9RamAddress
        endEA = ndsRom.arm9RamAddress + ndsRom.arm9Len
        offset = ndsRom.arm9Offset
        size = ndsRom.arm9Len
        rom = ndsRom.arm9
    else:
        name = "ARM7 ROM"
        proc = "ARM710A"
        entryAddr = ndsRom.arm7EntryAddress
        startEA = ndsRom.arm7RamAddress
        endEA = ndsRom.arm7RamAddress + ndsRom.arm7Len
        offset = ndsRom.arm7Offset
        size = ndsRom.arm7Len
        rom = ndsRom.arm7

    idaapi.set_processor_type(
        proc, idaapi.SETPROC_LOADER_NON_FATAL | idaapi.SETPROC_LOADER)

    memory =  \
    [
        [ startEA, endEA, "RAM" ],
        [ 0x04000000, 0x04001056, "General_Regs" ],
        [ 0x05000000, 0x05000600, "VMEM_Regs" ],
    ]

    if ((startEA < memory[0][0] or endEA > memory[0][1])
            and (startEA < memory[1][0] or endEA > memory[1][1])
            and (startEA < memory[2][0] or endEA > memory[2][1])):
        raise Exception("ROM not mapped into valid mem!")

    for segment in memory:
        idc.AddSeg(segment[0], segment[1], 0, 1, idaapi.saRelPara,
                   idaapi.scPub)
        idc.RenameSeg(segment[0], segment[2])

        if "RAM" not in segment[2]:
            for i in xrange(segment[0], segment[1]):
                idc.PatchByte(i, 0)

    idaapi.add_entry(entryAddr, entryAddr, "start", 1)
    idc.MakeNameEx(entryAddr, "start", idc.SN_NOCHECK | idc.SN_NOWARN)
    idaapi.cvar.inf.startIP = entryAddr
    idaapi.cvar.inf.beginEA = entryAddr
    ida_segment.set_selector(1, 0)
    idaapi.cvar.inf.startCS = 1

    li.seek(0)
    li.file2base(offset, startEA, endEA, 1)

    idaapi.cvar.inf.startCS = 0
    idaapi.cvar.inf.startIP = entryAddr

    idc.ExtLinA(startEA, 1, "; Title : " + str(ndsRom.name))
    idc.ExtLinA(startEA, 1, "; Software Version: " + str(ndsRom.version))

    # Add TwlHdr
    MakeVideoRegs()
    MakeVMemRegs()
    MakeJoypadRegs()
    MakeSystemRegs()
    if name == "ARM7 ROM":
        MakeARM7Regs()
    else:
        MakeARM9Regs()

    print("Done! Entry point @ " + hex(entryAddr))
    return 1
Ejemplo n.º 41
0
def load_file(li, neflags, format):
    """
    Load the file into database

    @param li: a file-like object which can be used to access the input data
    @param neflags: options selected by the user, see loader.hpp
    @return: 0-failure, 1-ok
    """

    li.seek(0)
    vmlinux = li.read(li.size())

    do_get_arch(kallsyms, vmlinux)
    do_kallsyms(kallsyms, vmlinux)
    
    if kallsyms['numsyms'] == 0:
        print_log('[!]get kallsyms error...')
        return 0
    
    idaapi.set_processor_type("arm", idaapi.SETPROC_ALL|idaapi.SETPROC_FATAL)
    if kallsyms['arch'] == 64:
        idaapi.get_inf_structure().lflags |= idaapi.LFLG_64BIT

    li.file2base(0, kallsyms['_start'], kallsyms['_start']+li.size(), True)

    sinittext_addr = 0
    max_sym_addr = 0
    for i in range(kallsyms['numsyms']):
        if kallsyms['arch'] == 32:
            if kallsyms['address'][i] > 0xd0000000:
                continue

        if kallsyms['name'][i] == '_sinittext':
            sinittext_addr = kallsyms['address'][i]
        if kallsyms['address'][i] > max_sym_addr:
            max_sym_addr = kallsyms['address'][i]
    max_sym_addr = max_sym_addr + 1024
    print_log("max_sym_addr = ", hex(max_sym_addr))

    if (kallsyms['_start']+li.size()) > max_sym_addr:
        max_sym_addr = kallsyms['_start']+li.size()


    s = idaapi.segment_t()
    s.bitness = kallsyms['arch'] // 32
    s.startEA = kallsyms['_start']
    if sinittext_addr == 0:
        s.endEA = max_sym_addr
    else:
        s.endEA = sinittext_addr
    s.perm = 5
    idaapi.add_segm_ex(s,".text","CODE",idaapi.ADDSEG_OR_DIE)
    
    if sinittext_addr > 0:
        s = idaapi.segment_t()
        s.bitness = kallsyms['arch'] // 32
        s.startEA = sinittext_addr
        s.endEA = max_sym_addr
        s.perm = 7
        idaapi.add_segm_ex(s,".data","DATA",idaapi.ADDSEG_OR_DIE)

    for i in range(kallsyms['numsyms']):
        if kallsyms['type'][i] in ['t','T']:
            idaapi.add_entry(kallsyms['address'][i], kallsyms['address'][i], kallsyms['name'][i], 1)
        else:
            idaapi.add_entry(kallsyms['address'][i], kallsyms['address'][i], kallsyms['name'][i], 0)

    print_log("Android/Linux vmlinux loaded...")
    return 1
Ejemplo n.º 42
0
def load_file(li, neflags, format):
    """
    Load the SG/SMD ROM

    :param li: Loader input
    :param neflags:
    :param format:
    :return: 1 on success, otherwise 0
    """

    idaapi.set_processor_type('68000', idaapi.SETPROC_LOADER)
    is_reload = (neflags & idaapi.NEF_RELOAD) != 0
    if is_reload:
        return 1

    # Get ROM end
    li.seek(0x1a4)
    rom_end = struct.unpack('>I', li.read(4))[0]

    # Create ROM segment
    rom_seg = idaapi.segment_t()
    rom_seg.start_ea = 0
    rom_seg.end_ea = rom_end
    rom_seg.bitness = 1
    idaapi.add_segm_ex(rom_seg, 'ROM', 'CODE', idaapi.ADDSEG_OR_DIE)

    # Get RAM start/end
    li.seek(0x1a8)
    ram_start = struct.unpack('>I', li.read(4))[0]
    ram_end = struct.unpack('>I', li.read(4))[0]

    # Create RAM segment
    ram_seg = idaapi.segment_t()
    ram_seg.start_ea = ram_start
    ram_seg.end_ea = ram_end
    ram_seg.bitness = 1
    idaapi.add_segm_ex(ram_seg, 'RAM', 'DATA', idaapi.ADDSEG_OR_DIE)

    # Read file into ROM segment
    li.seek(0)
    li.file2base(0, 0, rom_end, False)

    # Create Z80 memory segment
    z80_seg = idaapi.segment_t()
    z80_seg.start_ea = 0xa00000
    z80_seg.end_ea = 0xa1ffff  # Actually ends at 0xa0ffff, but for the sake of applying labels we make it 0xa1ffff
    z80_seg.bitness = 0  # 16 bit
    idaapi.add_segm_ex(z80_seg, 'Z80', 'DATA', idaapi.ADDSEG_OR_DIE)
    label_z80_memory()

    # Create a segment so we can create labels for VDP ports and debug registers
    misc_ports_regs = idaapi.segment_t()
    misc_ports_regs.start_ea = 0xc00000
    misc_ports_regs.end_ea = 0xc00020
    misc_ports_regs.bitness = 1
    idaapi.add_segm_ex(misc_ports_regs, 'MISC', 'DATA', idaapi.ADDSEG_OR_DIE)
    label_misc_regs_ports()

    # Create interrupt vector table
    create_dword_and_name(0, 'StackOffset')
    create_dword_and_name(4, 'ProgramStart')
    create_interrupt_table()
    create_interrupt_handlers(li)

    # Create ROM info
    create_rom_info_block()

    # Set entry
    program_start = get_dword_at(li, 4)
    idaapi.add_entry(program_start, program_start, '_start', 1)
    return 1
Ejemplo n.º 43
0
def load_file(li, neflags, format):
	if format != ROM_FORMAT_NAME:
		Warning("Unknown format name: '%s'" % format)
    		return 0
	idaapi.set_processor_type("M6502", SETPROC_ALL | SETPROC_FATAL)
	li.seek(0, idaapi.SEEK_END)
	size = li.tell()

	# RAM
	idc.AddSeg(RAM_START, RAM_START + RAM_SIZE, 0, 0, idaapi.saRelPara, idaapi.scPub)
	idc.RenameSeg(RAM_START, "RAM")

	li.seek(0x6)
	CartTypeLSB = struct.unpack("<B", li.read(1))[0]
	# SRAM
	if (((CartTypeLSB & 0x2) >> 1) == 1):
		idc.AddSeg(SRAM_START, SRAM_START + SRAM_SIZE, 0, 0, idaapi.saRelPara, idaapi.scPub)
		idc.RenameSeg(SRAM_START, "SRAM")

	# EXPROM
	idc.AddSeg(EXPROM_START, EXPROM_START + EXPROM_SIZE, 0, 0, idaapi.saRelPara, idaapi.scPub)
	idc.RenameSeg(EXPROM_START, "EXPROM")

	# TRAINER
	if (((CartTypeLSB & 0x4) >> 2) == 1):
		idc.AddSeg(TRAINER_START, TRAINER_START + TRAINER_SIZE, 0, 0, idaapi.saRelPara, idaapi.scPub)
		idc.RenameSeg(TRAINER_START, "TRAINER")

	# ROM
	idc.AddSeg(ROM_START, ROM_START + ROM_SIZE, 0, 0, idaapi.saRelPara, idaapi.scPub)
	idc.RenameSeg(ROM_START, "ROM")	
	idc.SetSegmentType(ROM_START, idc.SEG_CODE)

	CartTypeMSB = struct.unpack("<B", li.read(1))[0]
	mapper_version = (((CartTypeLSB & 0xF0) >> 4) | (CartTypeMSB & 0xF0))
	if (mapper_version == MAPPER_NONE or
		mapper_version == MAPPER_MMC1 or
		mapper_version == MAPPER_UxROM or
		mapper_version == MAPPER_CNROM or
		mapper_version == MAPPER_MMC3 or
		mapper_version == MAPPER_MMC5 or
		mapper_version == MAPPER_CAMERIC or
		mapper_version == MAPPER_GNROM):
		li.seek(0x4)
		prg_rom_size = struct.unpack("<B", li.read(1))[0]
		if (prg_rom_size != 0):
			offset = HEADER_SIZE
			if (((CartTypeLSB & 0x4) >> 2) == 1):
				offset += TRAINER_SIZE
			li.seek(offset)
			li.file2base(0, ROM_START, ROM_START + PRG_PAGE_SIZE, 0)
			offset = HEADER_SIZE + (prg_rom_size - 1) * PRG_PAGE_SIZE
			if (((CartTypeLSB & 0x4) >> 2) == 1):
				offset += TRAINER_SIZE
			li.seek(offset)
			li.file2base(0, ROM_START + PRG_PAGE_SIZE, ROM_START + PRG_PAGE_SIZE + PRG_PAGE_SIZE, 0)

	elif (mapper_version == MAPPER_MMC2):
		print("Second case mapper")
	elif (mapper_version == MAPPER_AxROM or
		mapper_version == MAPPER_COLOR_DREAMS or
		mapper_version == MAPPER_BxROM):
		print("Third case mapper")
	else:
		print("Mapper %d is not supported" % mapper_version)

	naming()
	idaapi.add_entry(Word(0xFFFC), Word(0xFFFC), "start", 1)
	idaapi.cvar.inf.startIP = Word(0xFFFC)
	idaapi.cvar.inf.beginEA = Word(0xFFFC)	
	header_info(li, 0xFFEF)

	print("[+] Load OK")
	return 1
Ejemplo n.º 44
0
    def load_file(li, neflags, format):
        idaapi.set_processor_type("arm",
                                  idaapi.SETPROC_ALL | idaapi.SETPROC_FATAL)
        f = load_nxo(li)
        if f.armv7:
            SetShortPrm(INF_LFLAGS, GetShortPrm(INF_LFLAGS) | LFLG_PC_FLAT)
        else:
            SetShortPrm(INF_LFLAGS, GetShortPrm(INF_LFLAGS) | LFLG_64BIT)

        SetCharPrm(INF_DEMNAMES, idaapi.DEMNAM_GCC3)
        idaapi.set_compiler_id(idaapi.COMP_GNU)
        idaapi.add_til2('gnulnx_arm' if f.armv7 else 'gnulnx_arm64', 1)

        loadbase = 0x60000000 if f.armv7 else 0x7100000000

        f.binfile.seek(0)
        as_string = f.binfile.read(f.bssoff)
        idaapi.mem2base(as_string, loadbase)
        if f.text[1] != None:
            li.file2base(f.text[1], loadbase + f.text[2],
                         loadbase + f.text[2] + f.text[3], True)
        if f.ro[1] != None:
            li.file2base(f.ro[1], loadbase + f.ro[2],
                         loadbase + f.ro[2] + f.ro[3], True)
        if f.data[1] != None:
            li.file2base(f.data[1], loadbase + f.data[2],
                         loadbase + f.data[2] + f.data[3], True)

        for start, end, name, kind in f.sections:
            if name.startswith('.got'):
                kind = 'CONST'
            idaapi.add_segm(0, loadbase + start, loadbase + end, name, kind)
            segm = idaapi.get_segm_by_name(name)
            if kind == 'CONST':
                segm.perm = idaapi.SEGPERM_READ
            elif kind == 'CODE':
                segm.perm = idaapi.SEGPERM_READ | idaapi.SEGPERM_EXEC
            elif kind == 'DATA':
                segm.perm = idaapi.SEGPERM_READ | idaapi.SEGPERM_WRITE
            elif kind == 'BSS':
                segm.perm = idaapi.SEGPERM_READ | idaapi.SEGPERM_WRITE
            idaapi.update_segm(segm)
            idaapi.set_segm_addressing(segm, 1 if f.armv7 else 2)

        # do imports
        # TODO: can we make imports show up in "Imports" window?
        undef_count = 0
        for s in f.symbols:
            if not s.shndx and s.name:
                undef_count += 1
        last_ea = max(loadbase + end for start, end, name, kind in f.sections)
        undef_entry_size = 8
        undef_ea = (
            (last_ea + 0xFFF) & ~0xFFF
        ) + undef_entry_size  # plus 8 so we don't end up on the "end" symbol
        idaapi.add_segm(0, undef_ea, undef_ea + undef_count * undef_entry_size,
                        "UNDEF", "XTRN")
        segm = idaapi.get_segm_by_name("UNDEF")
        segm.type = idaapi.SEG_XTRN
        idaapi.update_segm(segm)
        for i, s in enumerate(f.symbols):
            if not s.shndx and s.name:
                MakeQword(undef_ea)
                idaapi.do_name_anyway(undef_ea, s.name)
                s.resolved = undef_ea
                undef_ea += undef_entry_size
            elif i != 0:
                assert s.shndx
                s.resolved = loadbase + s.value
                if s.name:
                    if s.type == STT_FUNC:
                        print hex(s.resolved), s.name
                        idaapi.add_entry(s.resolved, s.resolved, s.name, 0)
                    else:
                        idaapi.do_name_anyway(s.resolved, s.name)

            else:
                # NULL symbol
                s.resolved = 0

        funcs = set()
        for s in f.symbols:
            if s.name and s.shndx and s.value:
                if s.type == STT_FUNC:
                    funcs.add(loadbase + s.value)

        got_name_lookup = {}
        for offset, r_type, sym, addend in f.relocations:
            target = offset + loadbase
            if r_type in (R_ARM_GLOB_DAT, R_ARM_JUMP_SLOT, R_ARM_ABS32):
                if not sym:
                    print 'error: relocation at %X failed' % target
                else:
                    idaapi.put_long(target, sym.resolved)
            elif r_type == R_ARM_RELATIVE:
                idaapi.put_long(target, idaapi.get_long(target) + loadbase)
            elif r_type in (R_AARCH64_GLOB_DAT, R_AARCH64_JUMP_SLOT,
                            R_AARCH64_ABS64):
                idaapi.put_qword(target, sym.resolved + addend)
                if addend == 0:
                    got_name_lookup[offset] = sym.name
            elif r_type == R_AARCH64_RELATIVE:
                idaapi.put_qword(target, loadbase + addend)
                if addend < f.textsize:
                    funcs.add(loadbase + addend)
            else:
                print 'TODO r_type %d' % (r_type, )
            ida_make_offset(f, target)

        for func, target in f.plt_entries:
            if target in got_name_lookup:
                addr = loadbase + func
                funcs.add(addr)
                idaapi.do_name_anyway(addr, got_name_lookup[target])

        funcs |= find_bl_targets(loadbase, loadbase + f.textsize)

        for addr in sorted(funcs, reverse=True):
            AutoMark(addr, AU_CODE)
            AutoMark(addr, AU_PROC)

        return 1
Ejemplo n.º 45
0
def load_file(li, neflags, format):
    '''
    Load the file into database

    @param li: a file-like object which can be used to access the input data
    @param neflags: options selected by the user, see loader.hpp
    @return: 0-failure, 1-ok
    '''
    idaapi.set_processor_type('cLEMENCy',
                              idaapi.SETPROC_USER | idaapi.SETPROC_FATAL)
    li.seek(0)
    data = convert(li.read(li.size()))
    if len(data) > 0x4000000:
        # program too large
        return 0

    idaapi.mem2base(data, 0, len(data))
    seg = idaapi.segment_t()
    seg.startEA = 0
    seg.endEA = 0x4000000
    # seg.bitness = 1
    idaapi.add_segm_ex(seg, "PROGRAM", "CODE", idaapi.ADDSEG_SPARSE)
    seg = idaapi.segment_t()
    seg.startEA = 0x4000000
    seg.endEA = 0x400001e
    idaapi.add_segm_ex(seg, "CLOCKIO", "RAM", idaapi.ADDSEG_SPARSE)
    seg = idaapi.segment_t()
    seg.startEA = 0x4010000
    seg.endEA = 0x4011000
    idaapi.add_segm_ex(seg, "FLAGIO", "RAM", idaapi.ADDSEG_SPARSE)
    seg = idaapi.segment_t()
    seg.startEA = 0x5000000
    seg.endEA = 0x5002000
    idaapi.add_segm_ex(seg, "RDATA", "RAM", idaapi.ADDSEG_SPARSE)
    seg = idaapi.segment_t()
    seg.startEA = 0x5002000
    seg.endEA = 0x5002003
    idaapi.add_segm_ex(seg, "RDATASZ", "RAM", idaapi.ADDSEG_SPARSE)
    seg = idaapi.segment_t()
    seg.startEA = 0x5010000
    seg.endEA = 0x5012000
    idaapi.add_segm_ex(seg, "SDATA", "RAM", idaapi.ADDSEG_SPARSE)
    seg = idaapi.segment_t()
    seg.startEA = 0x5012000
    seg.endEA = 0x5012003
    idaapi.add_segm_ex(seg, "SDATASZ", "RAM", idaapi.ADDSEG_SPARSE)
    seg = idaapi.segment_t()
    seg.startEA = 0x6000000
    seg.endEA = 0x6800000
    idaapi.add_segm_ex(seg, "SHMEM", "RAM", idaapi.ADDSEG_SPARSE)
    seg = idaapi.segment_t()
    seg.startEA = 0x6800000
    seg.endEA = 0x7000000
    idaapi.add_segm_ex(seg, "NVRAM", "RAM", idaapi.ADDSEG_SPARSE)
    seg = idaapi.segment_t()
    seg.startEA = 0x7FFFF00
    seg.endEA = 0x7FFFF1C
    idaapi.add_segm_ex(seg, "IVEC", "RAM", idaapi.ADDSEG_SPARSE)
    seg = idaapi.segment_t()
    seg.startEA = 0x7FFFF80
    seg.endEA = 0x8000000
    idaapi.add_segm_ex(seg, "PROCID", "RAM", idaapi.ADDSEG_SPARSE)
    idaapi.add_entry(0, 0, "_start", True)
    # idc.AutoMark( 0, AU_CODE )

    return 1