blob: 30f0fbed88b809a5b49b23a08f926594bb282d78 [file] [log] [blame] [edit]
From 16b95113bd94a4a722dad1edc55bde645d40dae0 Mon Sep 17 00:00:00 2001
From: Benjamin Pollack <benjamin@bitquabit.com>
Date: Mon, 20 Mar 2017 15:16:08 -0400
Subject: [PATCH] Fix the more egregious PEP-8 violations
---
scripts/ud_itab.py | 118 +++++++++++++++++++++----------------------
scripts/ud_opcode.py | 73 +++++++++++---------------
2 files changed, 86 insertions(+), 105 deletions(-)
diff --git a/scripts/ud_itab.py b/scripts/ud_itab.py
index 31d859e..63de355 100644
--- a/scripts/ud_itab.py
+++ b/scripts/ud_itab.py
@@ -195,8 +195,8 @@ class UdItabGenerator:
"cast" : "P_cast",
}
- MnemonicAliases = ( "invalid", "3dnow", "none", "db", "pause" )
-
+ MnemonicAliases = ("invalid", "3dnow", "none", "db", "pause")
+
def __init__(self, tables):
self.tables = tables
self._insnIndexMap, i = {}, 0
@@ -221,15 +221,15 @@ def getTableName(self, table):
def genOpcodeTable(self, table, isGlobal=False):
"""Emit Opcode Table in C.
"""
- self.ItabC.write( "\n" );
+ self.ItabC.write("\n")
if not isGlobal:
self.ItabC.write('static ')
- self.ItabC.write( "const uint16_t %s[] = {\n" % self.getTableName(table))
+ self.ItabC.write("const uint16_t %s[] = {\n" % self.getTableName(table))
for i in range(table.size()):
- if i > 0 and i % 4 == 0:
- self.ItabC.write( "\n" )
+ if i > 0 and i % 4 == 0:
+ self.ItabC.write("\n")
if i % 4 == 0:
- self.ItabC.write( " /* %2x */" % i)
+ self.ItabC.write(" /* %2x */" % i)
e = table.entryAt(i)
if e is None:
self.ItabC.write("%12s," % "INVALID")
@@ -237,35 +237,32 @@ def genOpcodeTable(self, table, isGlobal=False):
self.ItabC.write("%12s," % ("GROUP(%d)" % self.getTableIndex(e)))
elif isinstance(e, UdInsnDef):
self.ItabC.write("%12s," % self.getInsnIndex(e))
- self.ItabC.write( "\n" )
- self.ItabC.write( "};\n" )
-
+ self.ItabC.write("\n")
+ self.ItabC.write("};\n")
def genOpcodeTables(self):
tables = self.tables.getTableList()
for table in tables:
self.genOpcodeTable(table, table is self.tables.root)
-
def genOpcodeTablesLookupIndex(self):
- self.ItabC.write( "\n\n" );
- self.ItabC.write( "struct ud_lookup_table_list_entry ud_lookup_table_list[] = {\n" )
+ self.ItabC.write("\n\n")
+ self.ItabC.write("struct ud_lookup_table_list_entry ud_lookup_table_list[] = {\n")
for table in self.tables.getTableList():
f0 = self.getTableName(table) + ","
f1 = table.label() + ","
f2 = "\"%s\"" % table.meta()
- self.ItabC.write(" /* %03d */ { %s %s %s },\n" %
+ self.ItabC.write(" /* %03d */ { %s %s %s },\n" %
(self.getTableIndex(table), f0, f1, f2))
- self.ItabC.write( "};" )
+ self.ItabC.write("};")
-
- def genInsnTable( self ):
- self.ItabC.write( "struct ud_itab_entry ud_itab[] = {\n" );
+ def genInsnTable(self):
+ self.ItabC.write("struct ud_itab_entry ud_itab[] = {\n")
for insn in self.tables.getInsnList():
- opr_c = [ "O_NONE", "O_NONE", "O_NONE", "O_NONE" ]
+ opr_c = ["O_NONE", "O_NONE", "O_NONE", "O_NONE"]
pfx_c = []
- opr = insn.operands
- for i in range(len(opr)):
+ opr = insn.operands
+ for i in range(len(opr)):
if not (opr[i] in self.OperandDict.keys()):
print("error: invalid operand declaration: %s\n" % opr[i])
opr_c[i] = "O_" + opr[i]
@@ -273,18 +270,17 @@ def genInsnTable( self ):
opr_c[2] + ",", opr_c[3])
for p in insn.prefixes:
- if not ( p in self.PrefixDict.keys() ):
+ if not (p in self.PrefixDict.keys()):
print("error: invalid prefix specification: %s \n" % pfx)
- pfx_c.append( self.PrefixDict[p] )
+ pfx_c.append(self.PrefixDict[p])
if len(insn.prefixes) == 0:
- pfx_c.append( "P_none" )
- pfx = "|".join( pfx_c )
+ pfx_c.append("P_none")
+ pfx = "|".join(pfx_c)
- self.ItabC.write( " /* %04d */ { UD_I%s %s, %s },\n" \
- % ( self.getInsnIndex(insn), insn.mnemonic + ',', opr, pfx ) )
- self.ItabC.write( "};\n" )
+ self.ItabC.write(" /* %04d */ { UD_I%s %s, %s },\n" \
+ % (self.getInsnIndex(insn), insn.mnemonic + ',', opr, pfx))
+ self.ItabC.write("};\n")
-
def getMnemonicsList(self):
mnemonics = self.tables.getMnemonicsList()
mnemonics.extend(self.MnemonicAliases)
@@ -292,88 +288,88 @@ def getMnemonicsList(self):
def genMnemonicsList(self):
mnemonics = self.getMnemonicsList()
- self.ItabC.write( "\n\n" );
- self.ItabC.write( "const char* ud_mnemonics_str[] = {\n " )
- self.ItabC.write( ",\n ".join( [ "\"%s\"" % m for m in mnemonics ] ) )
- self.ItabC.write( "\n};\n" )
-
+ self.ItabC.write("\n\n")
+ self.ItabC.write("const char* ud_mnemonics_str[] = {\n ")
+ self.ItabC.write(",\n ".join(["\"%s\"" % m for m in mnemonics]))
+ self.ItabC.write("\n};\n")
- def genItabH( self, filePath ):
- self.ItabH = open( filePath, "w" )
+ def genItabH(self, filePath):
+ self.ItabH = open(filePath, "w")
# Generate Table Type Enumeration
- self.ItabH.write( "#ifndef UD_ITAB_H\n" )
- self.ItabH.write( "#define UD_ITAB_H\n\n" )
+ self.ItabH.write("#ifndef UD_ITAB_H\n")
+ self.ItabH.write("#define UD_ITAB_H\n\n")
self.ItabH.write("/* itab.h -- generated by udis86:scripts/ud_itab.py, do no edit */\n\n")
# table type enumeration
- self.ItabH.write( "/* ud_table_type -- lookup table types (see decode.c) */\n" )
- self.ItabH.write( "enum ud_table_type {\n " )
+ self.ItabH.write("/* ud_table_type -- lookup table types (see decode.c) */\n")
+ self.ItabH.write("enum ud_table_type {\n ")
enum = UdOpcodeTable.getLabels()
- self.ItabH.write( ",\n ".join( enum ) )
- self.ItabH.write( "\n};\n\n" );
+ self.ItabH.write(",\n ".join(enum))
+ self.ItabH.write("\n};\n\n")
# mnemonic enumeration
- self.ItabH.write( "/* ud_mnemonic -- mnemonic constants */\n" )
- enum = "enum ud_mnemonic_code {\n "
- enum += ",\n ".join( [ "UD_I%s" % m for m in self.getMnemonicsList() ] )
+ self.ItabH.write("/* ud_mnemonic -- mnemonic constants */\n")
+ enum = "enum ud_mnemonic_code {\n "
+ enum += ",\n ".join(["UD_I%s" % m for m in self.getMnemonicsList()])
enum += ",\n UD_MAX_MNEMONIC_CODE"
enum += "\n};\n"
- self.ItabH.write( enum )
- self.ItabH.write( "\n" )
+ self.ItabH.write(enum)
+ self.ItabH.write("\n")
- self.ItabH.write( "extern const char * ud_mnemonics_str[];\n" )
+ self.ItabH.write("extern const char * ud_mnemonics_str[];\n")
- self.ItabH.write( "\n#endif /* UD_ITAB_H */\n" )
-
- self.ItabH.close()
+ self.ItabH.write("\n#endif /* UD_ITAB_H */\n")
+ self.ItabH.close()
def genItabC(self, filePath):
self.ItabC = open(filePath, "w")
self.ItabC.write("/* itab.c -- generated by udis86:scripts/ud_itab.py, do no edit")
- self.ItabC.write(" */\n");
- self.ItabC.write("#include \"decode.h\"\n\n");
+ self.ItabC.write(" */\n")
+ self.ItabC.write("#include \"decode.h\"\n\n")
self.ItabC.write("#define GROUP(n) (0x8000 | (n))\n")
self.ItabC.write("#define INVALID %d\n\n" % self.getInsnIndex(self.tables.invalidInsn))
- self.genOpcodeTables()
+ self.genOpcodeTables()
self.genOpcodeTablesLookupIndex()
#
# Macros defining short-names for operands
#
- self.ItabC.write("\n\n/* itab entry operand definitions (for readability) */\n");
+ self.ItabC.write("\n\n/* itab entry operand definitions (for readability) */\n")
operands = self.OperandDict.keys()
operands = sorted(operands)
for o in operands:
self.ItabC.write("#define O_%-7s { %-12s %-8s }\n" %
- (o, self.OperandDict[o][0] + ",", self.OperandDict[o][1]));
- self.ItabC.write("\n");
+ (o, self.OperandDict[o][0] + ",", self.OperandDict[o][1]))
+ self.ItabC.write("\n")
self.genInsnTable()
self.genMnemonicsList()
self.ItabC.close()
- def genItab( self, location ):
+ def genItab(self, location):
self.genItabC(os.path.join(location, "itab.c"))
self.genItabH(os.path.join(location, "itab.h"))
+
def usage():
print("usage: ud_itab.py <optable.xml> <output-path>")
-def main():
+def main():
if len(sys.argv) != 3:
usage()
sys.exit(1)
-
+
tables = UdOpcodeTables(xml=sys.argv[1])
- itab = UdItabGenerator(tables)
+ itab = UdItabGenerator(tables)
itab.genItab(sys.argv[2])
+
if __name__ == '__main__':
main()
diff --git a/scripts/ud_opcode.py b/scripts/ud_opcode.py
index fe1833d..4495883 100644
--- a/scripts/ud_opcode.py
+++ b/scripts/ud_opcode.py
@@ -52,7 +52,6 @@ def lookupPrefix(self, pfx):
"""Lookup prefix (if any, None otherwise), by name"""
return True if pfx in self.prefixes else None
-
@property
def vendor(self):
return self._opcexts.get('/vendor', None)
@@ -87,9 +86,9 @@ class IndexError(Exception):
@classmethod
def vendor2idx(cls, v):
- return (0 if v == 'amd'
- else (1 if v == 'intel'
- else 2))
+ return (0 if v == 'amd'
+ else (1 if v == 'intel'
+ else 2))
@classmethod
def vex2idx(cls, v):
@@ -166,13 +165,11 @@ def vex2idx(cls, v):
'/vexl' : { 'label' : 'UD_TAB__OPC_VEX_L', 'size' : 2 },
}
-
def __init__(self, typ):
assert typ in self._TableInfo
- self._typ = typ
+ self._typ = typ
self._entries = {}
-
def size(self):
return self._TableInfo[self._typ]['size']
@@ -191,11 +188,9 @@ def typ(self):
def meta(self):
return self._typ
-
def __str__(self):
return "table-%s" % self._typ
-
def add(self, opc, obj):
typ = UdOpcodeTable.getOpcodeTyp(opc)
idx = UdOpcodeTable.getOpcodeIdx(opc)
@@ -203,7 +198,6 @@ def add(self, opc, obj):
raise CollisionError()
self._entries[idx] = obj
-
def lookup(self, opc):
typ = UdOpcodeTable.getOpcodeTyp(opc)
idx = UdOpcodeTable.getOpcodeIdx(opc)
@@ -211,7 +205,6 @@ def lookup(self, opc):
raise UdOpcodeTable.CollisionError("%s <-> %s" % (self._typ, typ))
return self._entries.get(idx, None)
-
def entryAt(self, index):
"""Returns the entry at a given index of the table,
None if there is none. Raises an exception if the
@@ -234,7 +227,6 @@ def getOpcodeTyp(cls, opc):
else:
return 'opctbl'
-
@classmethod
def getOpcodeIdx(cls, opc):
if opc.startswith('/'):
@@ -244,7 +236,6 @@ def getOpcodeIdx(cls, opc):
# plain opctbl opcode
return int(opc, 16)
-
@classmethod
def getLabels(cls):
"""Returns a list of all labels"""
@@ -282,7 +273,7 @@ def walk(self, tbl, opcodes):
to walk, the object at the leaf otherwise.
"""
opc = opcodes[0]
- e = tbl.lookup(opc)
+ e = tbl.lookup(opc)
if e is None:
return None
elif isinstance(e, UdOpcodeTable) and len(opcodes[1:]):
@@ -295,7 +286,7 @@ def map(self, tbl, opcodes, obj):
needed.
"""
opc = opcodes[0]
- e = tbl.lookup(opc)
+ e = tbl.lookup(opc)
if e is None:
tbl.add(opc, self.mkTrie(opcodes[1:], obj))
else:
@@ -304,16 +295,16 @@ def map(self, tbl, opcodes, obj):
self.map(e, opcodes[1:], obj)
def __init__(self, xml):
- self._tables = []
- self._insns = []
+ self._tables = []
+ self._insns = []
self._mnemonics = {}
# The root table is always a 256 entry opctbl, indexed
# by a plain opcode byte
- self.root = self.newTable('opctbl')
+ self.root = self.newTable('opctbl')
if os.getenv("UD_OPCODE_DEBUG"):
- self._logFh = open("opcodeTables.log", "w")
+ self._logFh = open("opcodeTables.log", "w")
# add an invalid instruction entry without any mapping
# in the opcode tables.
@@ -333,7 +324,6 @@ def log(self, s):
if os.getenv("UD_OPCODE_DEBUG"):
self._logFh.write(s + "\n")
-
def mergeSSENONE(self):
"""Merge sse tables with only one entry for /sse=none
"""
@@ -345,6 +335,7 @@ def mergeSSENONE(self):
if sse:
table.setEntryAt(k, sse)
uniqTables = {}
+
def genTableList(tbl):
if tbl not in uniqTables:
self._tables.append(tbl)
@@ -352,9 +343,9 @@ def genTableList(tbl):
for k, e in tbl.entries():
if isinstance(e, UdOpcodeTable):
genTableList(e)
+
self._tables = []
genTableList(self.root)
-
def patchAvx2byte(self):
# create avx tables
@@ -371,7 +362,6 @@ def patchAvx2byte(self):
table = self.walk(self.root, ('c4', '/vex=' + vex))
self.map(self.root, ('c5', '/vex=' + vex), table)
-
def addInsn(self, **insnDef):
# Canonicalize opcode list
@@ -409,14 +399,13 @@ def addInsn(self, **insnDef):
self._insns.append(insn)
# add to lookup by mnemonic structure
if insn.mnemonic not in self._mnemonics:
- self._mnemonics[insn.mnemonic] = [ insn ]
+ self._mnemonics[insn.mnemonic] = [insn]
else:
self._mnemonics[insn.mnemonic].append(insn)
-
def addInsnDef(self, insnDef):
- opcodes = []
- opcexts = {}
+ opcodes = []
+ opcexts = {}
# pack plain opcodes first, and collect opcode
# extensions
@@ -454,7 +443,7 @@ def addInsnDef(self, insnDef):
# Construct a long-form definition of the avx instruction
opcodes.insert(0, 'c4')
elif (opcodes[0] == '0f' and opcodes[1] != '0f' and
- '/sse' not in opcexts):
+ '/sse' not in opcexts):
# Make all 2-byte opcode form isntructions play nice with sse
# opcode maps.
opcexts['/sse'] = 'none'
@@ -471,7 +460,6 @@ def addInsnDef(self, insnDef):
operands = insnDef['operands'],
cpuid = insnDef['cpuid'])
-
def addSSE2AVXInsn(self, **insnDef):
"""Add an instruction definition containing an avx cpuid bit, but
declared in its legacy SSE form. The function splits the
@@ -481,20 +469,20 @@ def addSSE2AVXInsn(self, **insnDef):
# SSE
ssemnemonic = insnDef['mnemonic']
- sseopcodes = insnDef['opcodes']
+ sseopcodes = insnDef['opcodes']
# remove vex opcode extensions
- sseopcexts = dict([(e, v) for e, v in itemslist(insnDef['opcexts'])
- if not e.startswith('/vex')])
+ sseopcexts = dict([(e, v) for e, v in itemslist(insnDef['opcexts'])
+ if not e.startswith('/vex')])
# strip out avx operands, preserving relative ordering
# of remaining operands
sseoperands = [opr for opr in insnDef['operands']
- if opr not in ('H', 'L')]
+ if opr not in ('H', 'L')]
# strip out avx prefixes
sseprefixes = [pfx for pfx in insnDef['prefixes']
- if not pfx.startswith('vex')]
+ if not pfx.startswith('vex')]
# strip out avx bits from cpuid
- ssecpuid = [flag for flag in insnDef['cpuid']
- if not flag.startswith('avx')]
+ ssecpuid = [flag for flag in insnDef['cpuid']
+ if not flag.startswith('avx')]
self.addInsn(mnemonic = ssemnemonic,
prefixes = sseprefixes,
@@ -521,8 +509,8 @@ def addSSE2AVXInsn(self, **insnDef):
if o in ('V', 'W', 'H', 'U'):
o = o + 'x'
vexoperands.append(o)
- vexcpuid = [flag for flag in insnDef['cpuid']
- if not flag.startswith('sse')]
+ vexcpuid = [flag for flag in insnDef['cpuid']
+ if not flag.startswith('sse')]
self.addInsn(mnemonic = vexmnemonic,
prefixes = vexprefixes,
@@ -535,7 +523,6 @@ def getInsnList(self):
"""Returns a list of all instructions in the collection"""
return self._insns
-
def getTableList(self):
"""Returns a list of all tables in the collection"""
return self._tables
@@ -544,7 +531,6 @@ def getMnemonicsList(self):
"""Returns a sorted list of mnemonics"""
return sorted(self._mnemonics.keys())
-
def pprint(self):
def printWalk(tbl, indent=""):
entries = tbl.entries()
@@ -554,8 +540,8 @@ def printWalk(tbl, indent=""):
printWalk(e, indent + " |")
elif isinstance(e, UdInsnDef):
self.log("%s |-<%02x> %s" % (indent, k, e))
- printWalk(self.root)
+ printWalk(self.root)
def printStats(self):
tables = self.getTableList()
@@ -574,7 +560,6 @@ def printStats(self):
self.pprint()
-
@staticmethod
def parseOptableXML(xml):
"""Parse udis86 optable.xml file and return list of
@@ -584,9 +569,9 @@ def parseOptableXML(xml):
xmlDoc = minidom.parse(xml)
tlNode = xmlDoc.firstChild
- insns = []
+ insns = []
- while tlNode and tlNode.localName != "x86optable":
+ while tlNode and tlNode.localName != "x86optable":
tlNode = tlNode.nextSibling
for insnNode in tlNode.childNodes:
@@ -605,7 +590,7 @@ def parseOptableXML(xml):
for node in insnNode.childNodes:
if node.localName == 'def':
- insnDef = { 'pfx' : [] }
+ insnDef = {'pfx': []}
for node in node.childNodes:
if not node.localName:
continue