Advertisement
joxeankoret

Python script to show the cyclomatic complexity of each func

Jan 11th, 2019
502
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.88 KB | None | 0 0
  1. """
  2. Script to calculate the Cyclomatic Complexity of every function.
  3.  
  4. Joxean Koret, 2019
  5. Public Domain
  6. """
  7.  
  8. import idaapi
  9.  
  10. #-------------------------------------------------------------------------------
  11. class CCyclomaticComplexityChooser(idaapi.Choose2):
  12.   def __init__(self, title, items):
  13.     idaapi.Choose2.__init__(self,
  14.                      title,
  15.                      [ ["Address", 8], ["Name", 50], ["Nodes", 8],
  16.                      ["Edges", 8], ["CC", 8], ])
  17.     self.items = []
  18.     for item in items:
  19.       element = ["0x%08x" % item[0], item[1],
  20.                  "%04d" % item[2], "%04d" % item[3], "%04d" % item[4]]
  21.       self.items.append(element)
  22.  
  23.   def OnSelectLine(self, n):
  24.     ea = int(self.items[n][0], 16)
  25.     jumpto(ea)
  26.  
  27.   def OnGetLine(self, n):
  28.     return self.items[n]
  29.  
  30.   def OnGetSize(self):
  31.     return len(self.items)
  32.  
  33. #-------------------------------------------------------------------------------
  34. def calc_cc(ea):
  35.   func = idaapi.get_func(ea)
  36.   if func is not None:
  37.  
  38.     nodes = 0
  39.     edges = 0
  40.     flow = idaapi.FlowChart(func)
  41.     for block in flow:
  42.       nodes += 1
  43.       for succ in block.succs():
  44.         edges += 1
  45.      
  46.       for pred in block.preds():
  47.         edges += 1
  48.  
  49.   cc = edges - nodes + 2
  50.   return nodes, edges, cc
  51.  
  52. #-------------------------------------------------------------------------------
  53. def main():
  54.   vals = []
  55.   items = []
  56.   for ea in Functions():
  57.     nodes, edges, cc = calc_cc(ea)
  58.     name = GetFunctionName(ea)
  59.     tmp = Demangle(name, INF_SHORT_DN)
  60.     if tmp != "" and tmp is not None:
  61.       name = tmp
  62.     items.append([ea, name, nodes, edges, cc])
  63.     vals.append(cc)
  64.  
  65.   line = "Cyclomatic complexity: Max %d, Avg %d"
  66.   print(line % (max(vals), sum(vals)/len(vals)))
  67.  
  68.   ch = CCyclomaticComplexityChooser("Cyclomatic Complexity", items)
  69.   ch.Show()
  70.  
  71. if __name__ == "__main__":
  72.   main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement