Pages: [1] 2 3
Author Topic: IDA Pro helper functions  (Read 50919 times)
prj
Hero Member
*****

Karma: +1072/-480
Offline Offline

Posts: 6034


« on: January 25, 2018, 03:14:28 AM »

Convert range to code (e.g. processrom(0x10000, 0x20000))

Code:
import idc
import idaapi

def processrom(min, max):
if min > 0:
min = min - 1
curaddr = idc.FindUnexplored(min, idc.SEARCH_DOWN)
while curaddr < max:
if idc.MakeFunction(curaddr) != True:
idc.MakeCode(curaddr)
curaddr = idc.FindUnexplored(curaddr, idc.SEARCH_DOWN)

return

Load a2l (e.g. a2l("C:\my.a2l")):
Code:
def a2l(filename):
lastvarname = ""
lastaddress = ""
with open(filename) as fp:
measurements = fp.read().split("/begin MEASUREMENT")
measurements.pop(0)
print("Found: %d measurement(s)" % len(measurements))
for m in measurements:
namefound = 0
addrfound = 0
name = ""
addr = ""
for l in m.split("\n"):
l = l.strip()
if (len(l) > 0):
if (namefound == 0):
name = l
namefound = 1
elif (l.startswith("ECU_ADDRESS")):
addr = l[12:]
addrfound = 1
break
if (addrfound != 1):
print("ERROR")
else:
idc.MakeNameEx(int(addr, 0), name, 1)
return

Parse tricore indirect registers. Will replace ram+offset with actual value, so it can be crossreferenced and maps to a2l (e.g. indirect("a0", 0xDA80)):
Code:
def indirect(register, address):
print("Loading assembly...")
counter = 0
heads = list(idautils.Heads())
total = len(heads)
last = 0
replaced = 0
print("Parsing assembly...")
for line in idautils.Heads():
if (idc.Byte(line) == 0xD9 or idc.Byte(line) == 0x19 or idc.Byte(line) == 0x59 or idc.Byte(line) == 0x99):
dis = idc.GetDisasm(line)
pos = dis.find("[" + register + "]0x")
if (pos == -1):
pos = dis.find("[" + register + "]-0x")
if pos != -1:
replaced += 1
idc.OpOffEx(line, 1, idc.REF_OFF32, -1, address, 0x0)
cur = math.floor(counter*100/total)
if (cur >= (last+10)):
print("%d" % cur, end="%...")
last = cur
counter += 1

print("100%")
print("All done, %d entries replaced." % replaced)
return

Should be useful to those who know what they are doing.
« Last Edit: February 05, 2018, 08:00:25 AM by prj » Logged

PM's will not be answered, so don't even try.
Log your car properly - WinOLS database - Tools/patches
_nameless
Hero Member
*****

Karma: +342/-466
Offline Offline

Posts: 2800



« Reply #1 on: January 25, 2018, 06:25:57 AM »

Thanks
Logged

Giving your mom a tuneup
gt-innovation
Sr. Member
****

Karma: +60/-91
Offline Offline

Posts: 449


« Reply #2 on: January 25, 2018, 08:03:29 AM »

This will save so much time. Thanks PRJ. Will this work on any Ida ? 6.8? 7?
Logged
prj
Hero Member
*****

Karma: +1072/-480
Offline Offline

Posts: 6034


« Reply #3 on: January 25, 2018, 10:37:34 AM »

It's python, so ... I think pretty much any version.
Logged

PM's will not be answered, so don't even try.
Log your car properly - WinOLS database - Tools/patches
superglitch
Jr. Member
**

Karma: +4/-0
Offline Offline

Posts: 45


« Reply #4 on: January 25, 2018, 11:18:23 AM »

This will help greatly!  Thank you.
Logged
IamwhoIam
Hero Member
*****

Karma: +52/-114
Offline Offline

Posts: 1070


« Reply #5 on: January 25, 2018, 01:43:27 PM »

wow!
Logged

I have no logs because I have a boost gauge (makes things easier)
vwaudiguy
Hero Member
*****

Karma: +53/-37
Offline Offline

Posts: 2024



« Reply #6 on: January 25, 2018, 02:56:46 PM »

Thanks, D!
Logged

"If you have a chinese turbo, that you are worried is going to blow up when you floor it, then LOL."
jcsbanks
Full Member
***

Karma: +19/-3
Offline Offline

Posts: 146


« Reply #7 on: January 25, 2018, 04:31:17 PM »

Superb, thanks.

The first one in particular solves a big problem Smiley
Logged
Teitek
Newbie
*

Karma: +1/-0
Offline Offline

Posts: 21


« Reply #8 on: January 29, 2018, 04:32:05 PM »

Great work, thank you prj.
Logged
prj
Hero Member
*****

Karma: +1072/-480
Offline Offline

Posts: 6034


« Reply #9 on: February 05, 2018, 08:00:56 AM »

Realized I posted an old version of the indirect function, updated with newer one - it actually does something now.
Logged

PM's will not be answered, so don't even try.
Log your car properly - WinOLS database - Tools/patches
prj
Hero Member
*****

Karma: +1072/-480
Offline Offline

Posts: 6034


« Reply #10 on: February 07, 2018, 05:33:16 AM »

Needed to load some older stuff, so wrote this:
Code:
def dam(filename):
with open(filename) as fp:
lines = fp.read().split("\n")
lines.pop(0)
print("Found: %d lines" % len(lines))
for line in lines:
if (len(line) > 0):
l = line.split(",")
if (len(l) > 4):
if (l[1].strip() == "/SRC"):
addr = l[-5].replace("$", "0x")
idc.MakeNameEx(int(addr, 0), l[2].strip(), 1)
elif (l[0].strip() == "/UMP"):
addr = l[-7].replace("$", "0x")
idc.MakeNameEx(int(addr, 0), l[2].strip(), 1)
return
Logged

PM's will not be answered, so don't even try.
Log your car properly - WinOLS database - Tools/patches
Polo35580
Newbie
*

Karma: +9/-0
Offline Offline

Posts: 12


« Reply #11 on: March 06, 2019, 04:31:34 AM »

Hello

Great work prj !!

I had a "can't rename tail byte" with some measurements.

So I added a small
Code:
idc.MakeUnKnown(int(addr, 0), 1, idaapi.DOUNK_SIMPLE)
before
Code:
idc.MakeNameEx(int(addr, 0), name, 1)
in a2l script to make sure the byte is not already defined as a word by IDA.

ps: You need to import idaapi also.

Best regards

Polo
Logged
fluke9
Full Member
***

Karma: +26/-1
Offline Offline

Posts: 113


« Reply #12 on: October 17, 2019, 12:55:50 PM »

sorry for threadjacking, dumping my hack also here:

Rudimentary damos parer which will output a python script which can be executed in the ida console,
this thing will label variables, also it will create enums for bitfields and apply them to the correct locations.

Also names the variables with repeatable comments,
your disassembly will then look something like this:
Code:
843214 loc_843214:                             ; CODE XREF: sub_842C26+46E↑j
843214                                         ; sub_842C26+47A↑j
843214                 jnb     word_FD7C.B_sa, loc_8432DC
843218                 mov     r4, ATM_bits
84321C                 and     r4, #100h
843220                 jmpa    cc_NZ, loc_8432DC
843224                 jnb     word_FD20.B_atmtpk, loc_843270
843228                 jnb     word_FD7C.B_sa, loc_843270
84322C                 extp    #206h, #1
843230                 movbz   r4, TATMSAE     ; exotherme Temperaturerh_hung im Schub
843234                 sub     r4, #0Ah
843238                 movbz   r5, tikatm      ; Abgastemperatur im Katalysator aus Modell
84323C                 cmp     r4, #0


script here, which will generate namebytes.py :

Code:
#!/usr/bin/python

import sys

if len(sys.argv) != 2:
    print 'please specify filename'
    exit

f = open(sys.argv[1], "r")
lines = f.readlines()
f.close()

#print 'loaded ' + sys.argv[1] + ' with ' + str(len(lines)) + ' lines'
print '# -*- coding: latin-1 -*-'

for line in lines:

    data = line.split(',')
    if len(data) > 1:
        data[1] = data[1].strip()

        if data[1].startswith('/SPZ'):
            data = line.split(',')
            varname = data[2].strip()
            varcomment = (line[line.find("{")+1 : line.find("}")] )

            temp = line[line.find("}")+1 : -1]
            aftercomment = temp[temp.find("}")+1 : -1]
            dataac = aftercomment.split(',')
            varoffset = int(dataac[2].strip()[1:], 16)

            print("set_name(" + hex(varoffset) +", \"" + varname + "\");")
            if len(varcomment):
                print("set_cmt(" + hex(varoffset) +", \"" + varcomment.replace('"', '\\"') + "\", 1);")


        if data[1].startswith('/SRC'):
            data = line.split(',')
            varname = data[2].strip()
            varcomment = (line[line.find("{")+1 : line.find("}")] )

            temp = line[line.find("}")+1 : -1]
            aftercomment = temp[temp.find("}")+1 : -1]
            dataac = aftercomment.split(',')
            varoffset = int(dataac[1].strip()[1:], 16)

            print("set_name(" + hex(varoffset) +", \"" + varname + "\");")
            if len(varcomment):
                print("set_cmt(" + hex(varoffset) +", \"" + varcomment.replace('"', '\\"') + "\", 1);")


    if line.startswith('/UMP'):
#        /UMP, {}, afnmn, {Bereichsfenster Aussetzer, minimale Drehzahl}, $3830B5, 513, 160, nmot_ub_q40, 3, $FF, K;

        data = line.split(',')

        temp = line[line.find("}")+1 : -1]
        varcomment = (temp[temp.find("{")+1 : temp.find("}")] )

        temp = line[line.find("}")+1 : -1]
        aftercomment = temp[temp.find("}")+1 : -1]
        dataac = aftercomment.split(',')

        varname = data[2].strip()
        varoffset = int(dataac[1].strip()[1:], 16)
        varmask = dataac[6].strip()[1:]

        if varmask == 'FF' or varmask == 'FFFF':
            #print(varname + " | " + hex(varoffset) + " | " + varcomment + " | " + varmask)
            print("set_name(" + hex(varoffset) +", \"" + varname + "\");")
            if len(varcomment):
                print("set_cmt(" + hex(varoffset) +", \"" + varcomment.replace('"', '\\"') + "\", 1);")
            #print(varmask)
        else:
            enumname = "enum_" + str(hex(varoffset))[2:]
            maskstr = hex(int(varmask, 16))
            print("add_enum(-1, \"" + enumname + "\", 0)")
            print("set_enum_bf(get_enum(\"" + enumname + "\"), 1)")
            print("add_enum_member(get_enum(\"" + enumname + "\"), \"" + varname + "\"," + maskstr + ", " + maskstr + ")")


run with:
parsedamos.py file.dam > namebytes.py

After generating the namebytes.py copy to your ida project dir and execute in the ida console with:
execfile("namebytes.py")

« Last Edit: October 17, 2019, 01:13:48 PM by fluke9 » Logged
Chipburn
Newbie
*

Karma: +0/-0
Offline Offline

Posts: 3


« Reply #13 on: October 28, 2019, 10:20:38 AM »

Hello there guys,

Im not so good with IDA and python and im a bit puzzled of how exactly i can run the scripts.

For example for the first one how can i define min and max ? Does IDA support any interactive way where you can type the variables ?

Kind regards.
Logged
nyet
Administrator
Hero Member
*****

Karma: +607/-168
Offline Offline

Posts: 12268


WWW
« Reply #14 on: October 28, 2019, 10:40:13 AM »

Does IDA support any interactive way where you can type the variables ?

Yes, of course you can. But the whole point of the tools is to avoid having to do it via UI because GUIs suck for handling large amounts of data that is best handled by automation.
Logged

ME7.1 tuning guide
ECUx Plot
ME7Sum checksum
Trim heatmap tool

Please do not ask me for tunes. I'm here to help people make their own.

Do not PM me technical questions! Please, ask all questions on the forums! Doing so will ensure the next person with the same issue gets the opportunity to learn from your ex
Pages: [1] 2 3
  Print  
 
Jump to:  

Powered by SMF 1.1.21 | SMF © 2015, Simple Machines Page created in 0.026 seconds with 18 queries. (Pretty URLs adds 0s, 0q)