Commits

Anonymous committed 10d5c3d

convention, replace string.atoi() with int()

Comments (0)

Files changed (3)

 #!/usr/bin/python -tt
 '''Library to parse and analyse summer'87 DOS executables'''
 __revision__ = '$Rev: 104 $'
-import string, sys, re
+import sys, re
 import pcodedata
 from pcodedata import binformat, OP_MNEMON, OP_WPAR, OP_PUSH, OP_POP, OP_STRING
 
 #####################################################
 
-_format_list = ['hex', 'hex-wide', 'mnemonic', 'disass', 'declip']
-_linker_list = ['plink86', 'blinker']
-
-def FormatList():
-  '''export format list'''
-  return _format_list
-
-def LinkerList():
-  '''export linker list'''
-  return _linker_list
+FORMAT_LIST = ['hex', 'hex-wide', 'mnemonic', 'disass', 'declip']
+LINKER_LIST = ['plink86', 'blinker']
 
 class StackCorrupted(Exception):
   '''exception for the situation, when expression stack gets broken'''
 
     self.smbnum = num
 
-  def mkMnemoLine(self, pos, format="disass"):
+  def mkMnemoLine(self, pos, fmt="disass"):
     '''one line of output in disass and declip formats'''
     self.fp.seek(pos)
     cc = self.fp.read(1)
       return prm[0], prm[1], prm[1]
     opc_data = pcodedata.op_dict[op_code]
     mnemonic = opc_data[OP_MNEMON].rstrip()
-    disass_line = "%i : 0x%02x %3d %-15s %s" % ( pos, op_code, op_code, mnemonic, prm[1])
+    disass_line = "%i : 0x%02x %3d %-15s %s" % (
+        pos, op_code, op_code, mnemonic, prm[1])
     disass_line += " ( s: %d w: %d r: %d)" % ( 
-      opc_data[OP_POP], opc_data[OP_WPAR], opc_data[OP_PUSH])
+        opc_data[OP_POP], opc_data[OP_WPAR], opc_data[OP_PUSH])
     if opc_data[OP_WPAR] == -6:
       disass_line += " flt(len: %d, dec: %d)" % (prm[2], prm[3])
     elif opc_data[OP_WPAR] == -5:
       disass_line += " [" + prm[2] + "]"
     elif opc_data[OP_WPAR] == -4:
-      jmpto = pos + string.atoi( prm[1] ) + 3
+      jmpto = pos + int( prm[1] ) + 3
       # jump code + jump length is 3 bytes
       disass_line += " -> " + str( jmpto )
 #    elif opc_data[OP_MNEMON] == 'CM_DB_OP':
-#      # this is extended database operation - use, indexed use, set index to ...
+# # this is extended database operation - use, indexed use, set index to ...
 #      disass_line += " " + prm[1]['DB_CMD']
     else: pass
     
     declip_line = ''
-    if format == 'declip':
+    if fmt == 'declip':
       res = None
       if self.expstack: # IF ELSE ENDIF syntax
         stacktop = self.expstack[-1]
             raise StackCorrupted("stack: %d ; pos: %d" % (stacktop[2], pos))
           else:
             break
-            
-      if mnemonic in ("FC_SUBPROC","FC_DOPROC","FC_CALL"): # subproc call syntax
+
+      if mnemonic in ("FC_SUBPROC", "FC_DOPROC", "FC_CALL"): # subproc call
         called_func = self.expstack.pop()
-        parcnt = string.atoi(self.expstack.pop())
-        if parcnt>0:
+        parcnt = int(self.expstack.pop())
+        if parcnt > 0:
           pars = self.expstack[-parcnt:]
         else:
           pars = []
         #print "DEBUG st after", self.expstack
 
       elif mnemonic == 'SP_INDEX_END':
-         self.indstack = []
+        self.indstack = []
       elif mnemonic == 'SP_INDEX_ADD':
-         self.indstack.append(self.expstack.pop())
+        self.indstack.append(self.expstack.pop())
       elif mnemonic == 'CM_DB_OP':
-        # this is extended database operation - use, indexed use, set index to ...
-        p = []
-        for ii in range(prm[1]['DB_STACK']):
-          p.append(self.expstack.pop())
-        if prm[1]['DB_IND']==1:
+        # this is extended database operation - use, indexed use, set index
+        ii = prm[1]['DB_STACK']
+        p = self.expstack[-ii:]
+        p.reverse()
+        del(self.expstack[-ii:])
+        
+        if prm[1]['DB_IND'] == 1:
           p.append(','.join(self.indstack))
         declip_line += prm[1]['DB_CMD'] % tuple(p)
         
         param2 = self.expstack.pop()
         res = opc_data[OP_STRING] % (param1, param2)
         
-      elif opc_data[OP_POP] >=2 :
+      elif opc_data[OP_POP] >= 2 :
         a = opc_data[OP_POP]
         #print "DEBUG a", a
         #print "DEBUG stack", self.expstack
         p = self.expstack[-a:]
         #print "DEBUG p", p
         p = tuple(p)
-        format=opc_data[OP_STRING]
-        if opc_data[OP_WPAR]==-9:
-          format=format+prm[1]
+        format_string = opc_data[OP_STRING]
+        if opc_data[OP_WPAR] == -9:
+          format_string = format_string+prm[1]
         del(self.expstack[-a:])
         #print "DEBUG del params", self.expstack
-        #print "DEBUG format[", format,"]"
-        res = format % p
+        #print "DEBUG format[", format_string,"]"
+        res = format_string % p
         
       else:
         print opc_data
         self.expstack.append(res.rstrip())
         #print "DEBUG append res", self.expstack
       if mnemonic == "FC_JMPIFFALSE":
-        self.expstack.append(["FC_JMPIFFALSE", pos, pos+string.atoi(prm[1])+3])
+        self.expstack.append(["FC_JMPIFFALSE", pos, pos+int(prm[1])+3])
     return 1+prm[0], disass_line, declip_line
 
   def mkPrm(self, op_code):
       wrd_prm = pcodedata.op_dict[op_code][OP_WPAR]
     except KeyError:
       #print "OPCODE [%d] NOT IMPLEMENTED, SWITCHING TO MNEMONIC\n" % (op_code)
-      return (-1, "OPCODE [%d] NOT IMPLEMENTED, SWITCHING TO MNEMONIC" % (op_code))
+      return (-1, "OPCODE [%d] NOT IMPLEMENTED" % (op_code))
     if wrd_prm == 0: # no word params
       return (0,"")
     if wrd_prm == 1: # integer
       dateformat = pcodedata.date_dict[datnum]["DT_OPT"]
       return (2, dateformat)
     if wrd_prm == -8: # database operation
-      res = self.readInt16(0,1)
+      res = self.readInt16(0, 1)
       cmd = pcodedata.dbext_dict[res]
       return (2, cmd)
     if wrd_prm == -9: # option for dv_block
-      optnum = self.readInt16(0,1)
+      optnum = self.readInt16(0, 1)
       opt = pcodedata.dev_dict[optnum]["DV_OPT"]
       return (2, opt)
     return 0
       return "<NULL>", "<NULL>"
     symbols = self.symbdict
     modules = {}
-    for ii in symbols.keys():
-      modules[(symbols[ii][0]["off1"],symbols[ii][0]["off2"])] = symbols[ii][0]
+    for i in symbols.keys():
+      modules[(symbols[i][0]["off1"], symbols[i][0]["off2"])] = symbols[i][0]
     module_list = modules.keys()
     module_list.sort()
     #import pprint
         result.append([ord(ii), mn])
     print result
     
-  def parseProcedure(self, procname, format):
+  def parseProcedure(self, procname, fmt):
     print "LOOKING FOR:", procname, "..."
     sd = self.symbdict
     procdata = None
           procdata = sd[ii][jj]
           # print "DEBUG procdata", procdata
           # TODO: too many times the same condition is evaluated
-          if procdata["class"]=="subprogram" or procdata["class"]=="module:main":
+          if (procdata["class"] == "subprogram" or
+              procdata["class"] == "module:main"):
             break
-      if procdata and (procdata["class"]=="subprogram" or procdata["class"]=="module:main"):
+      if procdata and (procdata["class"] == "subprogram" or
+          procdata["class"] == "module:main"):
         break
-    if procdata and (procdata["class"]=="subprogram" or procdata["class"]=="module:main"):
+    if procdata and (procdata["class"] == "subprogram" or
+        procdata["class"] == "module:main"):
       print "FOUND:", procdata
       ii = 0
       stopnow = None
-      startpos = self.firstfun + procdata["off1"] + procdata["off2"] + (0 if self.linker=='plink86' else -16)
+      startpos = self.firstfun + procdata["off1"] + procdata["off2"] + (0 if 
+          self.linker == 'plink86' else -16)
       while not stopnow:
-        delta, disass_line, declip_line = self.mkMnemoLine(startpos+ii, format)
+        delta, disass_line, declip_line = self.mkMnemoLine(startpos+ii, fmt)
         stopnow = (re.search("FC_ENDSUB", disass_line))
         if delta == -1:
-          self.closeFile() # MATUSZ: ??? closing file prematurely ?
+          self.closeFile() # TODO: ??? closing file prematurely ?
           return startpos+ii
         print disass_line
         if declip_line != '':
           print "  " + declip_line
-        ii+=delta
+        ii += delta
     else:
       print "NOT FOUND"
 
 ########################################################################
 def isprint(ch):
-    if (32<=ord(ch)<=126) or (161<=ord(ch)<=255) :
-        return True
-    else:
-        return False
+  if (32<=ord(ch)<=126) or (161<=ord(ch)<=255) :
+    return True
+  else:
+    return False
 
-def dumpHex(input_file, startpos, bytecount, format="hex", width=16):
+def dumpHex(input_file, startpos, bytecount, fmt="hex", width=16):
   '''generate hex and mnemonic format output'''
   input_file.seek(startpos)
   buf = input_file.read(bytecount)
   result = ""
-  cnt = 0
-  if format == "hex-wide":
+  if fmt == "hex-wide":
     ii = 0
     while ii < len(buf):
       result += "%7d |" % (startpos+ii, )
       subbuf = buf[ii:ii+width]
       ascbuf = ""
-      for jj in range(0, len(subbuf)):
-          result += " %02X" % (ord(subbuf[jj]))
-          #ascbuf += subbuf[jj] if isprint(subbuf[jj]) else "." # needs python2.5
-          ascbuf += ( ".", subbuf[jj])[ isprint(subbuf[jj]) ] # isprint(...) ? subbuf[jj] : "."
-      while jj < width-1:
-          result += "   "
-          jj += 1
+      jj = 0
+      while jj < len(subbuf):
+        result += " %02X" % (ord(subbuf[jj]))
+        ascbuf += subbuf[jj] if isprint(subbuf[jj]) else "."
+        jj += 1
+      while jj < width:
+        result += " - "
+        jj += 1
       result += " | %s\n" % (ascbuf, )
-      ii+=width
+      ii += width
 
   else:
     for ii in range(0, len(buf)):
         char = buf[ii]
       else:
         char = "."
-      result += "%d %s 0x%02X %03u %#04o" % (startpos+ii, char, ord(buf[ii]), ord(buf[ii]), ord(buf[ii]))
-      if format == "mnemonic":
+      result += "%d %s 0x%02X %03u %#04o" % (
+          startpos+ii, char, ord(buf[ii]), ord(buf[ii]), ord(buf[ii]))
+      if fmt == "mnemonic":
         cc = ord(buf[ii])
         if cc in pcodedata.op_dict.keys():
           result += " %s\n" % pcodedata.op_dict[cc][OP_MNEMON]
 def quoteString(val):
   '''put a string into quotes'''
   if type(val) == type(""):
-    format = " '%s' : %-21s,"
+    fmt = " '%s' : %-21s,"
     val = val.rstrip()
     val = "'"+val+"'"
   else:
-    format = " '%s' : %3s,"
-  return val, format
+    fmt = " '%s' : %3s,"
+  return val, fmt
 
 ########################################################################
 
 #import sys
 #import os.path
 import wx
-#from string import atoi
 import declip
 from parameters import Parameters
 
     wx.EVT_SPINCTRL(self, self.byteCountSpin.GetId(), self.UpdateParams)
     
     self.linkerRadioBox = wx.RadioBox(self, -1, "Linker", wx.Point(-1, -1), wx.DefaultSize,
-                              declip.LinkerList(), 1, wx.RA_SPECIFY_COLS)
+                              declip.LINKER_LIST, 1, wx.RA_SPECIFY_COLS)
     self.linkerRadioBox.SetStringSelection(self.params.get("Linker")) 
     main_gridsizer.Add(self.linkerRadioBox, 0, wx.EXPAND)
     wx.EVT_RADIOBOX(self, self.linkerRadioBox.GetId(), self.EvtLinkerRadioBox)
     
     self.formatRadioBox = wx.RadioBox(self, -1, "Format of the output", wx.Point(-1, -1), wx.DefaultSize,
-                              declip.FormatList(), 2, wx.RA_SPECIFY_COLS)
+                              declip.FORMAT_LIST, 2, wx.RA_SPECIFY_COLS)
     self.formatRadioBox.SetStringSelection(self.params.get("Format")) 
     main_gridsizer.Add(self.formatRadioBox, 0, wx.EXPAND)
     wx.EVT_RADIOBOX(self, self.formatRadioBox.GetId(), self.EvtRadioBox)
       self.InitExeFile( params)
 
   def EvtLinkerRadioBox(self, event):
-    self.params.set( "Linker", declip.LinkerList()[event.GetInt()] )
+    self.params.set( "Linker", declip.LINKER_LIST[event.GetInt()] )
     self.InitExeFile(self.params)
 
   def EvtRadioBox(self, event):
-    self.params.set( "Format", declip.FormatList()[event.GetInt()] )
+    self.params.set( "Format", declip.FORMAT_LIST[event.GetInt()] )
 
   def OnClick(self, event):
     self.fillDecomp()
 __revision__ = '$Rev: 65 $'
 
 import sys
-from declip import FormatList, LinkerList
+from declip import FORMAT_LIST, LINKER_LIST
 from optparse import OptionParser
 
 class Parameters:
   def parse(self):
     self.parser = OptionParser(usage="usage: %prog [options] <exe file>")
     parser=self.parser
-    linkers=['p', 'b']+LinkerList()
+    linkers=['p', 'b']+LINKER_LIST
 
 #    parser.add_option("-x", "--exe-file", dest="FileName") # redundant, remove?
     parser.add_option("-l", "--linker", type="choice", choices=linkers, dest="Linker", help=repr(linkers))
     parser.add_option("-s", "--startpos", dest="StartPos", type="long")
     parser.add_option("-c", "--count", dest="ByteCount", type="long")
     parser.add_option("-e", "--endpos", dest="EndPos", type="long")
-    parser.add_option("-f", "--format", type="choice", choices=FormatList(), dest="Format", help=repr(FormatList()))
+    parser.add_option("-f", "--format", type="choice", choices=FORMAT_LIST, dest="Format", help=repr(FORMAT_LIST))
     parser.add_option("-p", "--procedure", dest="ProcToParse", help="try to parse whole procedure")
     parser.add_option("--list-subprograms", action="store_true", dest="ListSubprograms")
     parser.add_option("--sort-subprograms-by-off2", action="store_true", dest="AltSortSubs")