Search code examples
c#pythonida

Converting C# to Python


I am trying to convert a idc script(ida pro)from c# to python.Python dont give me any errors, but i recon it must be the for loops.

idc scripts

#include "common.idh"

static FindEmbeddedElfs() {
  auto ea, header, header2, elf_header, cont1, cont2, seg , num, addrname, segTag;
  elf_header=0x7F454C46;
  cont1=0;
  for (seg = FirstSeg(); NextSeg(seg) != seg; seg = NextSeg(seg)) {
    ea = SegStart(seg);
    header = Dword(ea);
    if (header == elf_header) {
        cont1=cont1+1;
        num=ltoa(cont1, 10);
        segTag="EmbElfSeg" + num;
        RenameSeg(seg, segTag);
        Message("Found Embedded Elf Segment");
        Message("Embedded Seg Start at: 0x%X\n", SegStart(seg));
        Message("Embedded Seg End at: 0x%X\n", SegEnd(seg));
        cont2=0;
        //The elfs I have seen, have a bigger elf that contains many spu elfs. This part gives
        //information about sub-embedded elfs, but this is only inteded to be informative.
        //The whole segment should be analysed separatelly
        for (ea=ea+4; ea + 4 < SegEnd(seg); ea = ea + 4) {
            header2 = Dword(ea);
            if (header2 == elf_header) {
                cont2=cont2+1;
                num=ltoa(cont2, 10);
                addrname=segTag+"-Elf" + num;
                MakeName(ea, addrname);
                Message("%s at: 0x%X\n",addrname ,ea);
            }   
        }
      }

  }

  }

static main() {

  FindEmbeddedElfs();

  Message("Done");
}

So far in python

import idc
import idaapi
import idautils
import re


def FindEmbeddedElfs(ea, header, header2, elfheader, cont1, cont2, seg, num, addrname, segtag):
    "Done"
    elfheader = 0x7F454C46
    cont1 = 0
    seg = FirstSeg()
    NextSeg() != seg
    seg = NextSeg()
    ea = SegStart()
    header = Dword()
    if header == elfheader:
        cont1 = cont1 + 1
        num = ltoa(cont1, 10)
        segtag = "EmbElfSeg" + num
        RenameSeg(seg, segtag)
        Message("Found Embedded Elf Segment")
        Message("Embedded Seg Start at: 0x%X\n", segStart(seg))
        Message("Embedded Seg End at: 0x%X\n", segEnd(seg))
        cont2 = 0

        ea = ea + 4
        ea + 4 < SegEnd()
        ea = ea + 4
        header2 = Dword()
    if header2 == elfheader:
        cont2 = cont2 + 1
        num = ltoa(cont2, 10)
        addrname = segTag + "-Elf" + num
        MakeName(ea, addrname)
        Message("%s at: 0x%X\n", addrname, ea)

        return FindEmbeddedElfs()


    Message("DONE")

Any ideas ?


Solution

  • So what you are having difficulty with is converting a C style for loop into Python. If you have a C style for loop like this:

    for (seg = FirstSeg(); NextSeg(seg) != seg; seg = NextSeg(seg)) {
        // do something
    }
    

    In Python, you can do:

    seg = FirstSeg()
    while NextSeg(seg) != seg:
        # do something
        seg = NextSeg(seg)