├── Old_IDA_version ├── IDAMagicStrings.py ├── README ├── basicutils_7x.py ├── cc_base.py ├── cc_main.py ├── codecut_gui.py ├── dataset │ ├── README-DATASET │ ├── free_rtos_lpc1768_webserver_thumb.elf │ ├── free_rtos_lpc1768_webserver_thumb.map │ ├── gnuchess-6.2.4.elf │ ├── gnuchess-6.2.4.map │ ├── gnuchess-6.2.4_trim.map │ ├── goodfet.elf │ ├── goodfet.map │ ├── px4.elf │ ├── px4.map │ ├── px4_trim.map │ ├── sky-contiki-build.map │ └── sky-shell-webserver.elf ├── evm-CodePiratesCutlass-RECON2018.pdf ├── evm-CodePiratesCutlass-Shmoocon2019.pdf ├── example_gui.py ├── lfa.py ├── map_read.py ├── maxcut.py ├── modnaming.py ├── module.py └── snap_cg.py ├── README.md ├── codecut-gui ├── Module.manifest ├── README.md ├── build.gradle ├── data │ ├── README.txt │ └── modnaming.py ├── extension.properties ├── ghidra_scripts │ ├── OutputObjFile.py │ ├── README.txt │ ├── decomprange.py │ ├── funcsig.py │ ├── generate_c.py │ ├── globalvars.py │ ├── pyelftools-0.28 │ │ ├── CHANGES │ │ ├── LICENSE │ │ ├── MANIFEST.in │ │ ├── README.rst │ │ ├── TODO │ │ ├── elftools │ │ │ ├── __init__.py │ │ │ ├── common │ │ │ │ ├── __init__.py │ │ │ │ ├── construct_utils.py │ │ │ │ ├── exceptions.py │ │ │ │ ├── py3compat.py │ │ │ │ └── utils.py │ │ │ ├── construct │ │ │ │ ├── LICENSE │ │ │ │ ├── README │ │ │ │ ├── __init__.py │ │ │ │ ├── adapters.py │ │ │ │ ├── core.py │ │ │ │ ├── debug.py │ │ │ │ ├── lib │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── binary.py │ │ │ │ │ ├── bitstream.py │ │ │ │ │ ├── container.py │ │ │ │ │ ├── hex.py │ │ │ │ │ └── py3compat.py │ │ │ │ └── macros.py │ │ │ ├── dwarf │ │ │ │ ├── __init__.py │ │ │ │ ├── abbrevtable.py │ │ │ │ ├── aranges.py │ │ │ │ ├── callframe.py │ │ │ │ ├── compileunit.py │ │ │ │ ├── constants.py │ │ │ │ ├── descriptions.py │ │ │ │ ├── die.py │ │ │ │ ├── dwarf_expr.py │ │ │ │ ├── dwarfinfo.py │ │ │ │ ├── enums.py │ │ │ │ ├── lineprogram.py │ │ │ │ ├── locationlists.py │ │ │ │ ├── namelut.py │ │ │ │ ├── ranges.py │ │ │ │ └── structs.py │ │ │ ├── ehabi │ │ │ │ ├── __init__.py │ │ │ │ ├── constants.py │ │ │ │ ├── decoder.py │ │ │ │ ├── ehabiinfo.py │ │ │ │ └── structs.py │ │ │ └── elf │ │ │ │ ├── __init__.py │ │ │ │ ├── constants.py │ │ │ │ ├── descriptions.py │ │ │ │ ├── dynamic.py │ │ │ │ ├── elffile.py │ │ │ │ ├── enums.py │ │ │ │ ├── gnuversions.py │ │ │ │ ├── hash.py │ │ │ │ ├── notes.py │ │ │ │ ├── relocation.py │ │ │ │ ├── sections.py │ │ │ │ ├── segments.py │ │ │ │ └── structs.py │ │ ├── examples │ │ │ ├── dwarf_decode_address.py │ │ │ ├── dwarf_die_tree.py │ │ │ ├── dwarf_lineprogram_filenames.py │ │ │ ├── dwarf_location_info.py │ │ │ ├── dwarf_pubnames_types.py │ │ │ ├── dwarf_range_lists.py │ │ │ ├── elf_low_high_api.py │ │ │ ├── elf_notes.py │ │ │ ├── elf_relocations.py │ │ │ ├── elf_show_debug_sections.py │ │ │ ├── elfclass_address_size.py │ │ │ ├── examine_dwarf_info.py │ │ │ ├── reference_output │ │ │ │ ├── dwarf_decode_address.out │ │ │ │ ├── dwarf_die_tree.out │ │ │ │ ├── dwarf_lineprogram_filenames.out │ │ │ │ ├── dwarf_location_info.out │ │ │ │ ├── dwarf_pubnames_types.out │ │ │ │ ├── dwarf_range_lists.out │ │ │ │ ├── elf_low_high_api.out │ │ │ │ ├── elf_notes.out │ │ │ │ ├── elf_relocations.out │ │ │ │ ├── elf_show_debug_sections.out │ │ │ │ ├── elfclass_address_size.out │ │ │ │ └── examine_dwarf_info.out │ │ │ └── sample_exe64.elf │ │ ├── pyelftools.sublime-project │ │ ├── scripts │ │ │ └── readelf.py │ │ ├── setup.cfg │ │ ├── setup.py │ │ ├── tox.ini │ │ └── z.py │ ├── range.py │ └── std.py ├── lib │ └── README.txt ├── os │ ├── linux64 │ │ └── README.txt │ ├── osx64 │ │ └── README.txt │ └── win64 │ │ └── README.txt └── src │ ├── main │ ├── help │ │ └── help │ │ │ ├── TOC_Source.xml │ │ │ ├── shared │ │ │ └── Frontpage.css │ │ │ └── topics │ │ │ └── skeleton │ │ │ └── help.html │ ├── java │ │ ├── codecutguiv2 │ │ │ ├── CCTableFilterPanel.java │ │ │ ├── ChecklistProvider.java │ │ │ ├── CodeCutGUIPlugin.java │ │ │ ├── CodeCutTransferHandler.java │ │ │ ├── CodecutUtils.java │ │ │ ├── CombineProvider.java │ │ │ ├── CreateProvider.java │ │ │ ├── DecompileRangeProvider.java │ │ │ ├── FilterDialog.java │ │ │ ├── ModNamingPython.java │ │ │ ├── NamespacePanel.java │ │ │ ├── NewSymbolFilter.java │ │ │ ├── ReferencePanel.java │ │ │ ├── ReferenceProvider.java │ │ │ ├── RenameProvider.java │ │ │ ├── RowPanel.java │ │ │ ├── SharedListSelectionListener.java │ │ │ ├── SymbolEditor.java │ │ │ ├── SymbolFilter.java │ │ │ ├── SymbolPanel.java │ │ │ ├── SymbolPlaceholder.java │ │ │ ├── SymbolProvider.java │ │ │ ├── SymbolReferenceModel.java │ │ │ ├── SymbolRenderer.java │ │ │ ├── SymbolRowObjectToAddressTableRowMapper.java │ │ │ ├── SymbolRowObjectToProgramLocationTableRowMapper.java │ │ │ ├── SymbolTableAddRemoveStrategy.java │ │ │ └── SymbolTableModel.java │ │ └── graphcut │ │ │ ├── EmptyGraphCutData.java │ │ │ ├── GraphCutComponent.java │ │ │ ├── GraphCutData.java │ │ │ ├── GraphCutDataFactory.java │ │ │ ├── GraphCutEdge.java │ │ │ ├── GraphCutEdgePaintTransformer.java │ │ │ ├── GraphCutEmphasizeEdgesJob.java │ │ │ ├── GraphCutExpandingVertexCollection.java │ │ │ ├── GraphCutExpansionListener.java │ │ │ ├── GraphCutGraph.java │ │ │ ├── GraphCutLayout.java │ │ │ ├── GraphCutLayoutExpandVerticesJob.java │ │ │ ├── GraphCutLayoutProvider.java │ │ │ ├── GraphCutLevel.java │ │ │ ├── GraphCutProvider.java │ │ │ ├── GraphCutTooltipProvider.java │ │ │ ├── GraphCutVertex.java │ │ │ ├── GraphCutVertexPaintTransformer.java │ │ │ ├── GraphCutView.java │ │ │ ├── NamespaceEdge.java │ │ │ ├── NamespaceEdgeCache.java │ │ │ └── ValidGraphCutData.java │ └── resources │ │ └── images │ │ └── README.txt │ └── test │ └── java │ └── README.test.txt ├── deepcut-ghidra ├── Module.manifest ├── README.md ├── build.gradle ├── data │ ├── GNN_Net.py │ ├── README.txt │ ├── deepcut.py │ └── model_weights_1.p ├── extension.properties ├── ghidra_scripts │ └── README.txt ├── gradle │ └── wrapper │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── os │ ├── linux64 │ │ └── README.txt │ ├── osx64 │ │ └── README.txt │ └── win64 │ │ └── README.txt ├── requirements-torch_geometric.txt └── src │ ├── main │ ├── help │ │ └── help │ │ │ ├── TOC_Source.xml │ │ │ └── shared │ │ │ └── Frontpage.css │ ├── java │ │ └── deepcut │ │ │ ├── Cut.java │ │ │ ├── DeepCutAnalyzer.java │ │ │ ├── DeepCutPython.java │ │ │ ├── EdgeInfo.java │ │ │ ├── EdgeInfoSerializer.java │ │ │ ├── FunctionCallGraph.java │ │ │ ├── FunctionInfo.java │ │ │ └── FunctionInfoSerializer.java │ └── resources │ │ └── images │ │ └── README.txt │ └── test │ └── java │ └── README.test.txt └── img ├── codecut-config.png ├── codecut-run.png ├── deepcut-config.png └── graph-pic.png /Old_IDA_version/cc_main.py: -------------------------------------------------------------------------------- 1 | ############################################################################################## 2 | # Copyright 2019 The Johns Hopkins University Applied Physics Laboratory LLC 3 | # All rights reserved. 4 | # Permission is hereby granted, free of charge, to any person obtaining a copy of this 5 | # software and associated documentation files (the "Software"), to deal in the Software 6 | # without restriction, including without limitation the rights to use, copy, modify, 7 | # merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 8 | # permit persons to whom the Software is furnished to do so. 9 | # 10 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 11 | # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR 12 | # PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 13 | # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 14 | # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 15 | # OR OTHER DEALINGS IN THE SOFTWARE. 16 | # 17 | # HAVE A NICE DAY. 18 | 19 | import maxcut 20 | import lfa 21 | import module 22 | import modnaming 23 | import cc_base 24 | import basicutils_7x as basicutils 25 | import snap_cg 26 | import imp 27 | 28 | def go(): 29 | 30 | #Do LFA and MaxCut Analysis to find module boundaries 31 | lfa_funclist, lfa_modlist = lfa.analyze() 32 | merge_flist,maxcut_modlist = maxcut.analyze(lfa_funclist) 33 | 34 | #Guess names for the modules using NLP 35 | lfa_modlist = modnaming.guess_module_names(lfa_modlist) 36 | maxcut_modlist = modnaming.guess_module_names(maxcut_modlist) 37 | 38 | #Output all results as .csv 39 | cc_base.print_results(merge_flist, lfa_modlist, maxcut_modlist) 40 | 41 | #Output module-to-module call graph as a Graphviz .gv file 42 | cc_base.gen_mod_graph(lfa_modlist, "lfa") 43 | cc_base.gen_mod_graph(maxcut_modlist, "mc") 44 | 45 | #Output a Python script that will rename modules 46 | cc_base.gen_rename_script(lfa_modlist, "lfa") 47 | cc_base.gen_rename_script(maxcut_modlist, "mc") 48 | 49 | #Output .map file (for comparison against ground truth, when available) 50 | cc_base.gen_map_file(lfa_modlist, "lfa") 51 | cc_base.gen_map_file(maxcut_modlist, "mc") 52 | 53 | return True 54 | 55 | if __name__ == "__main__": 56 | imp.reload(modnaming) 57 | imp.reload(module) 58 | imp.reload(cc_base) 59 | imp.reload(lfa) 60 | imp.reload(maxcut) 61 | imp.reload(snap_cg) 62 | imp.reload(basicutils) 63 | go() -------------------------------------------------------------------------------- /Old_IDA_version/codecut_gui.py: -------------------------------------------------------------------------------- 1 | 2 | import idc 3 | import ida_kernwin 4 | 5 | import imp 6 | import snap_cg 7 | 8 | import lfa 9 | import maxcut 10 | import module 11 | import cc_base 12 | import modnaming 13 | import basicutils_7x as basicutils 14 | 15 | from PyQt5 import QtCore, QtGui, QtWidgets 16 | 17 | from IDAMagicStrings import get_source_strings 18 | 19 | #------------------------------------------------------------------------------- 20 | def handler(item, column_no): 21 | if item.ignore: 22 | return 23 | 24 | ea = item.ea 25 | if is_mapped(ea): 26 | jumpto(ea) 27 | 28 | #------------------------------------------------------------------------------- 29 | class CBaseTreeViewer(ida_kernwin.PluginForm): 30 | def populate_tree(self): 31 | # Clear previous items 32 | self.tree.clear() 33 | 34 | # Get source file names 35 | self.dict, _ = get_source_strings() 36 | module_names = {} 37 | for key in self.dict: 38 | for values in self.dict[key]: 39 | ea, module_name = values[0], values[2] 40 | module_names[ea] = module_name 41 | 42 | self.modules_cache = {} 43 | #Do LFA and MaxCut Analysis to find module boundaries 44 | _, lfa_modlist = lfa.analyze() 45 | for module_data in lfa_modlist: 46 | module_name = "Module 0x%08x:0x%08x" % (module_data.start, module_data.end) 47 | for ea in module_names: 48 | if ea >= module_data.start and ea <= module_data.end: 49 | module_name = module_names[ea] 50 | break 51 | 52 | if module_name in self.modules_cache: 53 | item = self.modules_cache[module_name] 54 | else: 55 | item = QtWidgets.QTreeWidgetItem(self.tree) 56 | item.setText(0, module_name) 57 | item.ea = module_data.start 58 | item.ignore = True 59 | self.modules_cache[module_name] = item 60 | 61 | for func in Functions(module_data.start, module_data.end): 62 | node = QtWidgets.QTreeWidgetItem(item) 63 | node.setText(0, "0x%08x: %s" % (func, idc.get_func_name(func))) 64 | node.ea = func 65 | node.ignore = False 66 | 67 | self.tree.itemDoubleClicked.connect(handler) 68 | 69 | def OnCreate(self, form): 70 | # Get parent widget 71 | self.parent = ida_kernwin.PluginForm.FormToPyQtWidget(form) 72 | 73 | # Create tree control 74 | self.tree = QtWidgets.QTreeWidget() 75 | self.tree.setHeaderLabels(("Names",)) 76 | self.tree.setColumnWidth(0, 100) 77 | 78 | # Create layout 79 | layout = QtWidgets.QVBoxLayout() 80 | layout.addWidget(self.tree) 81 | self.populate_tree() 82 | 83 | # Populate PluginForm 84 | self.parent.setLayout(layout) 85 | 86 | def Show(self, title): 87 | return ida_kernwin.PluginForm.Show(self, title, options = ida_kernwin.PluginForm.WOPN_PERSIST) 88 | 89 | #------------------------------------------------------------------------------- 90 | def main(): 91 | tree_frm = CBaseTreeViewer() 92 | tree_frm.Show("Object Files") 93 | 94 | if __name__ == "__main__": 95 | imp.reload(modnaming) 96 | imp.reload(module) 97 | imp.reload(cc_base) 98 | imp.reload(lfa) 99 | imp.reload(maxcut) 100 | imp.reload(snap_cg) 101 | imp.reload(basicutils) 102 | main() 103 | 104 | -------------------------------------------------------------------------------- /Old_IDA_version/dataset/README-DATASET: -------------------------------------------------------------------------------- 1 | This is a dataset for exploring other solutions to the CodeCut problem or 2 | improving LFA. 3 | 4 | Each of the targets is an ELF file with DWARF debug information, as well as 5 | a .map file that was produced by ld at link time (showing object file 6 | boundaries). Some of the larger targets have a trimmed .map file 7 | (with "_trim") in the filename - this is basically just the object file 8 | boundaries to make parsing faster. 9 | 10 | You can use map_read.py to test LFA output (or any other solution to the 11 | CodeCut problem) 12 | 13 | Syntax: 14 | map_read.py 15 | 16 | This will output a 3 part score: match %, gap %, and underlap % 17 | 18 | Expected results for LFA: 19 | 20 | Gnuchess - Linux binary (x86) 76.1 3.2 20.7 21 | PX4 Firmware / NuttX (ARM) 82.2 13.6 4.2 22 | GoodFET 41 Firmware (msp430) 76.1 0 23.9 23 | Tmote Sky Firmware / Contiki (msp430) 93.3 0 6.7 24 | NXP Httpd Demo / FreeRTOS (ARM) 86.7 1.4 11.9 25 | 26 | A perfect result would be 100% match with no gap and no underlap. 27 | -------------------------------------------------------------------------------- /Old_IDA_version/dataset/free_rtos_lpc1768_webserver_thumb.elf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JHUAPL/CodeCut/22c0a93da468f14e4498599b1a4f7aa5f58b4779/Old_IDA_version/dataset/free_rtos_lpc1768_webserver_thumb.elf -------------------------------------------------------------------------------- /Old_IDA_version/dataset/gnuchess-6.2.4.elf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JHUAPL/CodeCut/22c0a93da468f14e4498599b1a4f7aa5f58b4779/Old_IDA_version/dataset/gnuchess-6.2.4.elf -------------------------------------------------------------------------------- /Old_IDA_version/dataset/goodfet.elf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JHUAPL/CodeCut/22c0a93da468f14e4498599b1a4f7aa5f58b4779/Old_IDA_version/dataset/goodfet.elf -------------------------------------------------------------------------------- /Old_IDA_version/dataset/px4.elf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JHUAPL/CodeCut/22c0a93da468f14e4498599b1a4f7aa5f58b4779/Old_IDA_version/dataset/px4.elf -------------------------------------------------------------------------------- /Old_IDA_version/dataset/sky-shell-webserver.elf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JHUAPL/CodeCut/22c0a93da468f14e4498599b1a4f7aa5f58b4779/Old_IDA_version/dataset/sky-shell-webserver.elf -------------------------------------------------------------------------------- /Old_IDA_version/evm-CodePiratesCutlass-RECON2018.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JHUAPL/CodeCut/22c0a93da468f14e4498599b1a4f7aa5f58b4779/Old_IDA_version/evm-CodePiratesCutlass-RECON2018.pdf -------------------------------------------------------------------------------- /Old_IDA_version/evm-CodePiratesCutlass-Shmoocon2019.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JHUAPL/CodeCut/22c0a93da468f14e4498599b1a4f7aa5f58b4779/Old_IDA_version/evm-CodePiratesCutlass-Shmoocon2019.pdf -------------------------------------------------------------------------------- /Old_IDA_version/example_gui.py: -------------------------------------------------------------------------------- 1 | 2 | import idc 3 | import ida_kernwin 4 | 5 | import imp 6 | import snap_cg 7 | 8 | import lfa 9 | import maxcut 10 | import module 11 | import cc_base 12 | import modnaming 13 | import basicutils_7x as basicutils 14 | 15 | from PyQt5 import QtCore, QtGui, QtWidgets 16 | 17 | #------------------------------------------------------------------------------- 18 | def handler(item, column_no): 19 | ea = item.ea 20 | if is_mapped(ea): 21 | jumpto(ea) 22 | 23 | #------------------------------------------------------------------------------- 24 | class CBaseTreeViewer(ida_kernwin.PluginForm): 25 | def populate_tree(self): 26 | # Clear previous items 27 | self.tree.clear() 28 | 29 | #Do LFA and MaxCut Analysis to find module boundaries 30 | _, lfa_modlist = lfa.analyze() 31 | for module_data in lfa_modlist: 32 | module_name = "Module 0x%08x:0x%08x" % (module_data.start, module_data.end) 33 | item = QtWidgets.QTreeWidgetItem(self.tree) 34 | item.setText(0, module_name) 35 | item.ea = module_data.start 36 | 37 | for func in Functions(module_data.start, module_data.end): 38 | node = QtWidgets.QTreeWidgetItem(item) 39 | node.setText(0, "0x%08x: %s" % (func, idc.get_func_name(func))) 40 | node.ea = func 41 | 42 | self.tree.itemDoubleClicked.connect(handler) 43 | 44 | def OnCreate(self, form): 45 | # Get parent widget 46 | self.parent = ida_kernwin.PluginForm.FormToPyQtWidget(form) 47 | 48 | # Create tree control 49 | self.tree = QtWidgets.QTreeWidget() 50 | self.tree.setHeaderLabels(("Names",)) 51 | self.tree.setColumnWidth(0, 100) 52 | 53 | # Create layout 54 | layout = QtWidgets.QVBoxLayout() 55 | layout.addWidget(self.tree) 56 | self.populate_tree() 57 | 58 | # Populate PluginForm 59 | self.parent.setLayout(layout) 60 | 61 | def Show(self, title): 62 | return ida_kernwin.PluginForm.Show(self, title, options = ida_kernwin.PluginForm.WOPN_PERSIST) 63 | 64 | #------------------------------------------------------------------------------- 65 | def main(): 66 | tree_frm = CBaseTreeViewer() 67 | tree_frm.Show("Object Files") 68 | 69 | if __name__ == "__main__": 70 | imp.reload(modnaming) 71 | imp.reload(module) 72 | imp.reload(cc_base) 73 | imp.reload(lfa) 74 | imp.reload(maxcut) 75 | imp.reload(snap_cg) 76 | imp.reload(basicutils) 77 | main() 78 | 79 | -------------------------------------------------------------------------------- /Old_IDA_version/module.py: -------------------------------------------------------------------------------- 1 | ############################################################################################## 2 | # Copyright 2019 The Johns Hopkins University Applied Physics Laboratory LLC 3 | # All rights reserved. 4 | # Permission is hereby granted, free of charge, to any person obtaining a copy of this 5 | # software and associated documentation files (the "Software"), to deal in the Software 6 | # without restriction, including without limitation the rights to use, copy, modify, 7 | # merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 8 | # permit persons to whom the Software is furnished to do so. 9 | # 10 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 11 | # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR 12 | # PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 13 | # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 14 | # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 15 | # OR OTHER DEALINGS IN THE SOFTWARE. 16 | # 17 | # HAVE A NICE DAY. 18 | 19 | #This represents the information we want to record about an individual function 20 | #The function lists returned by LFA and MaxCut are made up of these 21 | class func_info(): 22 | def __init__(self,loc,score1,score2): 23 | self.loc = loc #the effective address of the function 24 | self.score1=score1 #"Calls from" local function affinity score 25 | self.score2=score2 #"Calls to" local function affinity score 26 | self.total_score=score1+score2 27 | self.lfa_skip=0 #Set to 1 if "skipped" (not scored) by LFA 28 | self.edge=[0,0] #Set by edge_detect() - if 1, this is the start of a new module 29 | #index 0 for LFA, 1 for MaxCut 30 | 31 | def __repr__(self): 32 | return "Function: 0x%08x" % (self.loc) 33 | 34 | def __str__(self): 35 | return self.__repr__() 36 | 37 | #This represents the object files (aka modules) identified by LFA and MaxCut 38 | class bin_module(): 39 | def __init__(self,start,end,score,name): 40 | self.start=start 41 | self.end=end 42 | self.score=score #Currently unused 43 | self.name=name 44 | 45 | def __repr__(self): 46 | line = "Module at 0x%08x:0x%08x" % (self.start, self.end) 47 | if self.name != "" and self.name is not None: 48 | line += " (name %s)" % self.name 49 | return line 50 | 51 | def __str__(self): 52 | return self.__repr__() 53 | -------------------------------------------------------------------------------- /Old_IDA_version/snap_cg.py: -------------------------------------------------------------------------------- 1 | ############################################################################################## 2 | # Copyright 2019 The Johns Hopkins University Applied Physics Laboratory LLC 3 | # All rights reserved. 4 | # Permission is hereby granted, free of charge, to any person obtaining a copy of this 5 | # software and associated documentation files (the "Software"), to deal in the Software 6 | # without restriction, including without limitation the rights to use, copy, modify, 7 | # merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 8 | # permit persons to whom the Software is furnished to do so. 9 | # 10 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 11 | # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR 12 | # PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 13 | # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 14 | # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 15 | # OR OTHER DEALINGS IN THE SOFTWARE. 16 | # 17 | # HAVE A NICE DAY. 18 | 19 | ## This code creates a Snap PNGraph object that represents the call graph of a binary 20 | ## (the .text section) 21 | 22 | import snap 23 | import sys 24 | 25 | import idc 26 | import struct 27 | import idautils 28 | import basicutils_7x as basicutils 29 | 30 | MAX_DIST = 0 31 | 32 | 33 | UGraph = [] 34 | 35 | def add_edge(f, t): 36 | global UGraph 37 | n = basicutils.GetFunctionName(f) 38 | if n != "": 39 | #since we're only doing one edge for each xref, we'll do weight based on distance from the middle of the caller to the callee 40 | f_start = idc.get_func_attr(f, idc.FUNCATTR_START) 41 | 42 | if (not UGraph.IsNode(f_start)): 43 | print("Error: had to add node (to): %08x" % f_start) 44 | UGraph.AddNode(f_start) 45 | 46 | print("%08x -> %08x" % (f_start, t)) 47 | UGraph.AddEdge(t,f_start) 48 | 49 | #print "s_%#x -> s_%#x" % (f_start,t)," [len = ",get_weight(func_mid, t), "]" 50 | 51 | 52 | def add_node(f): 53 | basicutils.ForEveryXrefToD(f, add_edge) 54 | 55 | def create_snap_cg(): 56 | global UGraph 57 | UGraph= snap.PNGraph.New() 58 | 59 | #Add every function linearly, this makes sure the nodes are in order 60 | basicutils.ForEveryFuncInSeg(".text",UGraph.AddNode) 61 | basicutils.ForEveryFuncInSeg(".text",add_node) 62 | 63 | for NI in UGraph.Nodes(): 64 | print("node id 0x%x with out-degree %d and in-degree %d" %( 65 | NI.GetId(), NI.GetOutDeg(), NI.GetInDeg())) 66 | 67 | return UGraph 68 | -------------------------------------------------------------------------------- /codecut-gui/Module.manifest: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JHUAPL/CodeCut/22c0a93da468f14e4498599b1a4f7aa5f58b4779/codecut-gui/Module.manifest -------------------------------------------------------------------------------- /codecut-gui/README.md: -------------------------------------------------------------------------------- 1 | 2 | # Ghidra Plugin for CodeCut GUI 3 | 4 | ## Building and Installation 5 | 6 | Requirements are the same as the Ghidra build requirements, currently JDK 17 (or newer) is required for Ghidra 10.2. 7 | 8 | Ghidra's standard Gradle build system is used. Set the `GHIDRA_INSTALL_DIR` environment variable before building, or set it as a Gradle property (useful for building in an IDE). 9 | 10 | ### Environment Variable 11 | 12 | ``` 13 | export GHIDRA_INSTALL_DIR="/path/to/ghidra" 14 | gradle 15 | ``` 16 | 17 | ### Gradle property 18 | 19 | ``` 20 | echo GHIDRA_INSTALL_DIR="/path/to/ghidra" > gradle.properties 21 | ``` 22 | 23 | ### Python 3 24 | 25 | The CodeCut GUI's Module Name Guessing tool requires Python 3. Before running the tool, you may need to modify the Python Path of the tool. To do this, **Edit -> Tool Options -> Python Executable**. Insert path to your Python 3 executable. Click apply and ok. 26 | 27 | ### Install nltk 28 | This module depends on the Python 3 dependency `nltk`. Run the following command to install: 29 | ``` 30 | pip install nltk 31 | ``` 32 | 33 | ### Build Output 34 | 35 | The module ZIP will be output to `dist/`. Use **File > Install Extensions** and select the green plus to browse to the extension. Restart Ghidra when prompted. 36 | 37 | For proper functionality, the plugin should be built with the same JRE used by your Ghidra installation. if you have multiple Java runtime environments installed, select the correct JRe by setting the `JAVA_HOME` environment variable before building. 38 | 39 | ### Running the Plugin 40 | 41 | After using **File > Install Extensions** to install the plugin and restarting Ghidra, you may be prompted the next time Ghidra opens to enable the newly-detected plugin. In this case, simply check the box next to **CodeCutGUIPlugin**. 42 | 43 | To enable the plugin normally, you can use **File > Configure...**. Click **Experimental** and check the box next to **CodeCutGUIPlugin**. 44 | 45 | Once the plugin is enabled, use **Window > CodeCut Table** to open it. Note that it is intendend to be used after running the **CodeCut** or **DeepCut** analyzers. 46 | 47 | Open the CodeCutGUI Window by clicking **Windows->CodeCut Table**. Alternatively use the hot key Ctrl-m. 48 | 49 | The Module Name Guessing tool can be started by clicking **Analysis -> Guess Module Names**. 50 | -------------------------------------------------------------------------------- /codecut-gui/build.gradle: -------------------------------------------------------------------------------- 1 | // Builds a Ghidra Extension for a given Ghidra installation. 2 | // 3 | // An absolute path to the Ghidra installation directory must be supplied either by setting the 4 | // GHIDRA_INSTALL_DIR environment variable or Gradle project property: 5 | // 6 | // > export GHIDRA_INSTALL_DIR= 7 | // > gradle 8 | // 9 | // or 10 | // 11 | // > gradle -PGHIDRA_INSTALL_DIR= 12 | // 13 | // Gradle should be invoked from the directory of the project to build. Please see the 14 | // application.gradle.version property in /Ghidra/application.properties 15 | // for the correction version of Gradle to use for the Ghidra installation you specify. 16 | 17 | //----------------------START "DO NOT MODIFY" SECTION------------------------------ 18 | def ghidraInstallDir 19 | 20 | if (System.env.GHIDRA_INSTALL_DIR) { 21 | ghidraInstallDir = System.env.GHIDRA_INSTALL_DIR 22 | } 23 | else if (project.hasProperty("GHIDRA_INSTALL_DIR")) { 24 | ghidraInstallDir = project.getProperty("GHIDRA_INSTALL_DIR") 25 | } 26 | 27 | if (ghidraInstallDir) { 28 | apply from: new File(ghidraInstallDir).getCanonicalPath() + "/support/buildExtension.gradle" 29 | } 30 | else { 31 | throw new GradleException("GHIDRA_INSTALL_DIR is not defined!") 32 | } 33 | //----------------------END "DO NOT MODIFY" SECTION------------------------------- 34 | -------------------------------------------------------------------------------- /codecut-gui/data/README.txt: -------------------------------------------------------------------------------- 1 | The "data" directory is intended to hold data files that will be used by this module and will 2 | not end up in the .jar file, but will be present in the zip or tar file. Typically, data 3 | files are placed here rather than in the resources directory if the user may need to edit them. 4 | 5 | An optional data/languages directory can exist for the purpose of containing various Sleigh language 6 | specification files and importer opinion files. 7 | 8 | The data/buildLanguage.xml is used for building the contents of the data/languages directory. 9 | 10 | The skel language definition has been commented-out within the skel.ldefs file so that the 11 | skeleton language does not show-up within Ghidra. 12 | 13 | See the Sleigh language documentation (docs/languages/index.html) for details Sleigh language 14 | specification syntax. 15 | -------------------------------------------------------------------------------- /codecut-gui/extension.properties: -------------------------------------------------------------------------------- 1 | name=@extname@ 2 | description=CodeCut / DeepCut GUI 3 | author=JHU/APL 4 | createdOn= 5 | version=@extversion@ 6 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/README.txt: -------------------------------------------------------------------------------- 1 | Java source directory to hold module-specific Ghidra scripts. 2 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/decomprange.py: -------------------------------------------------------------------------------- 1 | from ghidra.app.decompiler import DecompInterface 2 | from ghidra.util.task import ConsoleTaskMonitor 3 | 4 | 5 | def decompile_user_functions_in_range( 6 | current_program, 7 | start_address_str, 8 | end_address_str, 9 | standard_library_namespaces=None, 10 | ): 11 | if standard_library_namespaces is None: 12 | standard_library_namespaces = ['libc', 'libm', 'libpthread', 13 | 'libdl', 'std'] 14 | 15 | def is_user_written_function(function): 16 | namespace = function.getParentNamespace().getName() 17 | return namespace not in standard_library_namespaces 18 | 19 | #doesn't quite work right if you have overlapping functions 20 | #we should rewrite to use FunctionManager/getFunctionsAt functionality 21 | def getFunctions(start_address, end_address): 22 | current_addr = start_address 23 | while current_addr < end_address: 24 | function = \ 25 | current_program.getFunctionManager().getFunctionContaining(current_addr) 26 | if function is not None: 27 | yield function 28 | current_addr = function.getBody().getMaxAddress().add(1) 29 | else: 30 | current_addr = current_addr.add(1) 31 | 32 | start_address = \ 33 | current_program.getAddressFactory().getAddress(start_address_str) 34 | end_address = \ 35 | current_program.getAddressFactory().getAddress(end_address_str) 36 | 37 | if start_address is None or end_address is None: 38 | print 'Invalid address range specified.' 39 | return 40 | 41 | if start_address >= end_address: 42 | print 'Invalid address range: start address should be less than end address.' 43 | return 44 | 45 | decompiler = DecompInterface() 46 | decompiler.openProgram(current_program) 47 | monitor = ConsoleTaskMonitor() 48 | 49 | functions = list(getFunctions(start_address, end_address)) 50 | user_written_functions = list(filter(is_user_written_function, 51 | functions)) 52 | 53 | decompiled_functions = {} 54 | for function in user_written_functions: 55 | decomp_result = decompiler.decompileFunction(function, 0, 56 | monitor) 57 | if decomp_result is not None: 58 | decompiled_functions[function.getName()] = \ 59 | {'address': function.getEntryPoint(), 60 | 'code': decomp_result.getDecompiledFunction().getC()} 61 | 62 | return decompiled_functions 63 | 64 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/funcsig.py: -------------------------------------------------------------------------------- 1 | from ghidra.program.model.listing import Function 2 | from ghidra.program.model.symbol import SourceType 3 | 4 | 5 | def get_referenced_function_signatures(program, function_address, 6 | monitor): 7 | if function_address is None: 8 | popup('No address entered') 9 | return 10 | 11 | function = \ 12 | program.getFunctionManager().getFunctionAt(function_address) 13 | if function is None: 14 | popup('No function found at the given address') 15 | return 16 | 17 | function_signatures = \ 18 | get_referenced_function_signatures_base(function, monitor) 19 | 20 | sigs = '\n/* Refereneced Signatures for: ' + function.getName() \ 21 | + ' */\n' 22 | for signature in function_signatures: 23 | sigs += signature 24 | 25 | return sigs 26 | 27 | 28 | def get_referenced_function_signatures_base(function, monitor): 29 | if function is None: 30 | raise ValueError('function is none') 31 | 32 | funcRefs = getFunctionReferences(function, monitor) 33 | 34 | signatures = [] 35 | for refFunc in funcRefs: 36 | if isUserDefinedFunction(refFunc): 37 | signatures.append(getFunctionSignature(refFunc) + ';\n') 38 | 39 | return signatures 40 | 41 | 42 | def getFunctionReferences(function, monitor): 43 | refs = set() 44 | instructions = \ 45 | function.getProgram().getListing().getInstructions(function.getBody(), 46 | True) 47 | for instr in instructions: 48 | flowType = instr.getFlowType() 49 | if flowType.isCall(): 50 | target = instr.getOperandReferences(0)[0].getToAddress() 51 | func = \ 52 | function.getProgram().getFunctionManager().getFunctionAt(target) 53 | if func is not None: 54 | refs.add(func) 55 | return refs 56 | 57 | 58 | def getFunctionSignature(function): 59 | sig = function.getPrototypeString(False, False) 60 | return sig 61 | 62 | 63 | def isUserDefinedFunction(function): 64 | symbol = function.getSymbol() 65 | namespace = symbol.getParentNamespace().getName() 66 | standard_libraries = ['libc', 'libm', 'libpthread', 'libdl', 'std'] 67 | return not any(namespace.startswith(lib) for lib in 68 | standard_libraries) 69 | 70 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/generate_c.py: -------------------------------------------------------------------------------- 1 | from globalvars import get_global_variables 2 | from funcsig import get_referenced_function_signatures 3 | from decomprange import decompile_user_functions_in_range 4 | import re 5 | 6 | 7 | def fixCasting(code_str): 8 | pattern = re.compile(r"\b([a-zA-Z0-9._]+)\._(\d{0,4})_(\d{0,4})_") 9 | matches = pattern.finditer(code_str) 10 | 11 | for match in matches: 12 | name = match.group(1) 13 | offset = match.group(2) 14 | size = match.group(3) 15 | 16 | if size == '4': 17 | fixedref = '((int*)' + name + ')[' + offset + ']' 18 | code_str = code_str.replace(match.group(), fixedref) 19 | 20 | if size == '1': 21 | fixedref = '*(uint8_t *)&' + name 22 | code_str = code_str.replace(match.group(), fixedref) 23 | 24 | return code_str 25 | 26 | 27 | def generate_recompilable_c_code( 28 | start_addr, 29 | end_addr, 30 | currentProgram, 31 | monitor, 32 | ): 33 | header_prefix = \ 34 | '''/* Ghidra type resolution */ 35 | #include "ghidra.h" 36 | 37 | ''' 38 | 39 | referenced_funcs = '' 40 | in_range_c_code = \ 41 | ''' 42 | 43 | /* Decompiled functions within address range: %s - %s */''' \ 44 | % (start_addr, end_addr) 45 | 46 | global_vars = get_global_variables(currentProgram, start_addr, end_addr) 47 | print('Global vars:') 48 | print(global_vars) 49 | 50 | decompiled_functions = \ 51 | decompile_user_functions_in_range(currentProgram, start_addr, 52 | end_addr) 53 | 54 | for (function_name, function_data) in decompiled_functions.items(): 55 | referenced_funcs += \ 56 | get_referenced_function_signatures(currentProgram, 57 | function_data['address'], monitor) 58 | in_range_c_code += function_data['code'] 59 | 60 | c_code = header_prefix + global_vars + referenced_funcs \ 61 | + in_range_c_code 62 | c_code = fixCasting(c_code) 63 | return c_code 64 | 65 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/globalvars.py: -------------------------------------------------------------------------------- 1 | from ghidra.program.model.symbol import SourceType 2 | from ghidra.program.model.symbol import SymbolType 3 | from ghidra.program.model.address import AddressSet 4 | #from ghidra.program.flatapi.FlatProgramAPI import getFunctionAt, getDataAt 5 | from ghidra.program.model.data import Array, FloatDataType, \ 6 | DoubleDataType 7 | 8 | 9 | def get_global_variables(program, start_addr, end_addr): 10 | global_vars = [] 11 | symbol_table = program.getSymbolTable() 12 | start_address = \ 13 | program.getAddressFactory().getAddress(start_addr) 14 | end_address = \ 15 | program.getAddressFactory().getAddress(end_addr) 16 | addrset = AddressSet(start_address,end_address) 17 | #set.addRange(start_addr, end_addr) 18 | print(start_address, end_address) 19 | print(addrset) 20 | 21 | #for symbol in symbol_table.getAllSymbols(False): 22 | for symbol in symbol_table.getSymbols(addrset,SymbolType.LABEL,True): 23 | print(symbol) 24 | if (symbol.getSymbolType() == SymbolType.LABEL): 25 | if (symbol.isGlobal()): 26 | if (not program.getListing().getFunctionAt(symbol.getAddress())): 27 | if (program.getListing().getDataAt(symbol.getAddress())): 28 | global_vars.append(symbol) 29 | 30 | ''' 31 | def is_user_defined(var): 32 | var_name = var.getName() 33 | var_addr = var.getAddress() 34 | 35 | if var_name.startswith('__') or var_name.startswith('_'): 36 | return False 37 | 38 | if var_name.startswith('imp_') or var_name.startswith('thunk_'): 39 | return False 40 | 41 | if var_name.startswith('fde_') or var_name.startswith('cie_'): 42 | return False 43 | 44 | if var_name.startswith('completed.0') \ 45 | or var_name.startswith('data_start'): 46 | return False 47 | 48 | if var_addr.toString().startswith('EXTERNAL:'): 49 | return False 50 | section_name = program.getMemory().getBlock(var_addr).getName() 51 | #if section_name not in ['.data', '.bss']: 52 | # return False 53 | 54 | return True 55 | ''' 56 | 57 | 58 | #global_vars = list(filter(is_user_defined, global_vars)) 59 | #global_vars = list(filter(is_global_var, global_vars)) 60 | 61 | print("G vars first pass:") 62 | print(global_vars) 63 | 64 | output = '/* Global Variables */\n' 65 | for var in global_vars: 66 | var_addr = var.getAddress() 67 | var_name = var.getName() 68 | 69 | data = program.getListing().getDataAt(var_addr) 70 | if data is None: 71 | continue 72 | 73 | dt = data.getDataType() 74 | dt_name = dt.getDisplayName() 75 | value = data.getValue() 76 | 77 | pointer_count = 0 78 | while dt_name.endswith('*'): 79 | pointer_count += 1 80 | dt_name = dt_name[:-1].strip() 81 | 82 | if isinstance(dt, Array): 83 | value = '{' + ', '.join(str(value[i]) for i in 84 | range(len(value))) + '}' 85 | elif isinstance(dt, FloatDataType) or isinstance(dt, 86 | DoubleDataType): 87 | value = '{:.6f}'.format(value) 88 | elif value is not None: 89 | value = str(value) 90 | else: 91 | value = '' 92 | 93 | output += '{}{} {}{}{};\n'.format(dt_name, (' ' 94 | if not dt_name.endswith('*') else ''), var_name, '*' 95 | * pointer_count, (' = {}'.format(value) if value else '' 96 | )) 97 | 98 | return output 99 | 100 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/LICENSE: -------------------------------------------------------------------------------- 1 | pyelftools is in the public domain (see below if you need more details). 2 | 3 | pyelftools uses the construct library for structured parsing of a binary 4 | stream. construct is packaged in pyelftools/construct - see its LICENSE 5 | file for the license. 6 | 7 | ------------------------------------------------------------------------------- 8 | 9 | This is free and unencumbered software released into the public domain. 10 | 11 | Anyone is free to copy, modify, publish, use, compile, sell, or 12 | distribute this software, either in source code form or as a compiled 13 | binary, for any purpose, commercial or non-commercial, and by any 14 | means. 15 | 16 | In jurisdictions that recognize copyright laws, the author or authors 17 | of this software dedicate any and all copyright interest in the 18 | software to the public domain. We make this dedication for the benefit 19 | of the public at large and to the detriment of our heirs and 20 | successors. We intend this dedication to be an overt act of 21 | relinquishment in perpetuity of all present and future rights to this 22 | software under copyright law. 23 | 24 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 25 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 26 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 27 | IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR 28 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 29 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 30 | OTHER DEALINGS IN THE SOFTWARE. 31 | 32 | For more information, please refer to 33 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/MANIFEST.in: -------------------------------------------------------------------------------- 1 | recursive-include elftools *.py 2 | recursive-include scripts *.py 3 | recursive-include examples *.py *.elf *.out 4 | recursive-include test *.py *.elf *.arm *.mips *.o 5 | include README.rst 6 | include LICENSE 7 | include CHANGES 8 | include tox.ini 9 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/README.rst: -------------------------------------------------------------------------------- 1 | ========== 2 | pyelftools 3 | ========== 4 | 5 | .. image:: https://github.com/eliben/pyelftools/workflows/pyelftools-tests/badge.svg 6 | :align: center 7 | :target: https://github.com/eliben/pyelftools/actions 8 | 9 | **pyelftools** is a pure-Python library for parsing and analyzing ELF files 10 | and DWARF debugging information. See the 11 | `User's guide `_ 12 | for more details. 13 | 14 | Pre-requisites 15 | -------------- 16 | 17 | As a user of **pyelftools**, one only needs Python to run. It works with 18 | Python versions 2.7 and 3.x (x >= 5). For hacking on **pyelftools** the 19 | requirements are a bit more strict, please see the 20 | `hacking guide `_. 21 | 22 | Installing 23 | ---------- 24 | 25 | **pyelftools** can be installed from PyPI (Python package index):: 26 | 27 | > pip install pyelftools 28 | 29 | Alternatively, you can download the source distribution for the most recent and 30 | historic versions from the *Downloads* tab on the `pyelftools project page 31 | `_ (by going to *Tags*). Then, you can 32 | install from source, as usual:: 33 | 34 | > python setup.py install 35 | 36 | Since **pyelftools** is a work in progress, it's recommended to have the most 37 | recent version of the code. This can be done by downloading the `master zip 38 | file `_ or just 39 | cloning the Git repository. 40 | 41 | Since **pyelftools** has no external dependencies, it's also easy to use it 42 | without installing, by locally adjusting ``PYTHONPATH``. 43 | 44 | How to use it? 45 | -------------- 46 | 47 | **pyelftools** is a regular Python library: you import and invoke it from your 48 | own code. For a detailed usage guide and links to examples, please consult the 49 | `user's guide `_. 50 | 51 | License 52 | ------- 53 | 54 | **pyelftools** is open source software. Its code is in the public domain. See 55 | the ``LICENSE`` file for more details. 56 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/TODO: -------------------------------------------------------------------------------- 1 | New version 2 | ----------- 3 | 4 | * Update elftools/__init__.py 5 | * Update setup.py 6 | * Update CHANGES 7 | * Tag in git (v0.xx) 8 | 9 | construct 10 | --------- 11 | 12 | construct seems to be maintained again - they also backported my Python 3 fixes. 13 | Theoretically, I can remove construct from pyelftools and use it as a dependency 14 | instead. I don't really have time to play with this now, but may do so in the 15 | future. 16 | 17 | Preparing a new release 18 | ----------------------- 19 | 20 | * Run 'tox' tests (with '-r' to create new venvs) 21 | * Make sure new version was updated everywhere appropriate 22 | * Run ``python setup.py build sdist bdist_wheel`` (no 'upload' yet) 23 | * Untar the created ``dist/pyelftools-x.y.tar.gz`` and make sure 24 | everything looks ok 25 | * Now build with upload to send it to PyPi 26 | * Tag new version in git 27 | * Test with pip install from some new virtualenv 28 | 29 | Distribution 30 | ------------ 31 | 32 | 1. First install Twine (https://packaging.python.org/tutorials/packaging-projects/) 33 | 2. python3 -m twine upload dist/*, but make sure ``setup.py`` was already run 34 | and the updated whl and tarbal are in dist/. 35 | 36 | Credentials for PyPI are stored in ~/.pypirc 37 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/elftools/__init__.py: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------- 2 | # elftools 3 | # 4 | # Eli Bendersky (eliben@gmail.com) 5 | # This code is in the public domain 6 | #------------------------------------------------------------------------------- 7 | __version__ = '0.28' 8 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/elftools/common/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JHUAPL/CodeCut/22c0a93da468f14e4498599b1a4f7aa5f58b4779/codecut-gui/ghidra_scripts/pyelftools-0.28/elftools/common/__init__.py -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/elftools/common/construct_utils.py: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------- 2 | # elftools: common/construct_utils.py 3 | # 4 | # Some complementary construct utilities 5 | # 6 | # Eli Bendersky (eliben@gmail.com) 7 | # This code is in the public domain 8 | #------------------------------------------------------------------------------- 9 | from ..construct import ( 10 | Subconstruct, ConstructError, ArrayError, Adapter, Field, RepeatUntil, 11 | Rename, SizeofError 12 | ) 13 | 14 | 15 | class RepeatUntilExcluding(Subconstruct): 16 | """ A version of construct's RepeatUntil that doesn't include the last 17 | element (which casued the repeat to exit) in the return value. 18 | 19 | Only parsing is currently implemented. 20 | 21 | P.S. removed some code duplication 22 | """ 23 | __slots__ = ["predicate"] 24 | def __init__(self, predicate, subcon): 25 | Subconstruct.__init__(self, subcon) 26 | self.predicate = predicate 27 | self._clear_flag(self.FLAG_COPY_CONTEXT) 28 | self._set_flag(self.FLAG_DYNAMIC) 29 | def _parse(self, stream, context): 30 | obj = [] 31 | try: 32 | context_for_subcon = context 33 | if self.subcon.conflags & self.FLAG_COPY_CONTEXT: 34 | context_for_subcon = context.__copy__() 35 | 36 | while True: 37 | subobj = self.subcon._parse(stream, context_for_subcon) 38 | if self.predicate(subobj, context): 39 | break 40 | obj.append(subobj) 41 | except ConstructError as ex: 42 | raise ArrayError("missing terminator", ex) 43 | return obj 44 | def _build(self, obj, stream, context): 45 | raise NotImplementedError('no building') 46 | def _sizeof(self, context): 47 | raise SizeofError("can't calculate size") 48 | 49 | 50 | def _LEB128_reader(): 51 | """ Read LEB128 variable-length data from the stream. The data is terminated 52 | by a byte with 0 in its highest bit. 53 | """ 54 | return RepeatUntil( 55 | lambda obj, ctx: ord(obj) < 0x80, 56 | Field(None, 1)) 57 | 58 | 59 | class _ULEB128Adapter(Adapter): 60 | """ An adapter for ULEB128, given a sequence of bytes in a sub-construct. 61 | """ 62 | def _decode(self, obj, context): 63 | value = 0 64 | for b in reversed(obj): 65 | value = (value << 7) + (ord(b) & 0x7F) 66 | return value 67 | 68 | 69 | class _SLEB128Adapter(Adapter): 70 | """ An adapter for SLEB128, given a sequence of bytes in a sub-construct. 71 | """ 72 | def _decode(self, obj, context): 73 | value = 0 74 | for b in reversed(obj): 75 | value = (value << 7) + (ord(b) & 0x7F) 76 | if ord(obj[-1]) & 0x40: 77 | # negative -> sign extend 78 | value |= - (1 << (7 * len(obj))) 79 | return value 80 | 81 | 82 | def ULEB128(name): 83 | """ A construct creator for ULEB128 encoding. 84 | """ 85 | return Rename(name, _ULEB128Adapter(_LEB128_reader())) 86 | 87 | 88 | def SLEB128(name): 89 | """ A construct creator for SLEB128 encoding. 90 | """ 91 | return Rename(name, _SLEB128Adapter(_LEB128_reader())) 92 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/elftools/common/exceptions.py: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------- 2 | # elftools: common/exceptions.py 3 | # 4 | # Exception classes for elftools 5 | # 6 | # Eli Bendersky (eliben@gmail.com) 7 | # This code is in the public domain 8 | #------------------------------------------------------------------------------- 9 | class ELFError(Exception): 10 | pass 11 | 12 | class ELFRelocationError(ELFError): 13 | pass 14 | 15 | class ELFParseError(ELFError): 16 | pass 17 | 18 | class ELFCompressionError(ELFError): 19 | pass 20 | 21 | class DWARFError(Exception): 22 | pass 23 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/elftools/common/py3compat.py: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------- 2 | # elftools: common/py3compat.py 3 | # 4 | # Python 2/3 compatibility code 5 | # 6 | # Eli Bendersky (eliben@gmail.com) 7 | # This code is in the public domain 8 | #------------------------------------------------------------------------------- 9 | import sys 10 | PY3 = sys.version_info[0] == 3 11 | 12 | 13 | if PY3: 14 | import io 15 | StringIO = io.StringIO 16 | BytesIO = io.BytesIO 17 | 18 | # Functions for acting on bytestrings and strings. In Python 2 and 3, 19 | # strings and bytes are the same and chr/ord can be used to convert between 20 | # numeric byte values and their string pepresentations. In Python 3, bytes 21 | # and strings are different types and bytes hold numeric values when 22 | # iterated over. 23 | 24 | def bytes2hex(b, sep=''): 25 | if not sep: 26 | return b.hex() 27 | return sep.join(map('{:02x}'.format, b)) 28 | 29 | def bytes2str(b): return b.decode('latin-1') 30 | def str2bytes(s): return s.encode('latin-1') 31 | def int2byte(i): return bytes((i,)) 32 | def byte2int(b): return b 33 | 34 | def iterbytes(b): 35 | """Return an iterator over the elements of a bytes object. 36 | 37 | For example, for b'abc' yields b'a', b'b' and then b'c'. 38 | """ 39 | for i in range(len(b)): 40 | yield b[i:i+1] 41 | 42 | ifilter = filter 43 | 44 | maxint = sys.maxsize 45 | else: 46 | import cStringIO 47 | StringIO = BytesIO = cStringIO.StringIO 48 | 49 | def bytes2hex(b, sep=''): 50 | res = b.encode('hex') 51 | if not sep: 52 | return res 53 | return sep.join(res[i:i+2] for i in range(0, len(res), 2)) 54 | 55 | def bytes2str(b): return b 56 | def str2bytes(s): return s 57 | int2byte = chr 58 | byte2int = ord 59 | def iterbytes(b): 60 | return iter(b) 61 | 62 | from itertools import ifilter 63 | 64 | maxint = sys.maxint 65 | 66 | 67 | def iterkeys(d): 68 | """Return an iterator over the keys of a dictionary.""" 69 | return getattr(d, 'keys' if PY3 else 'iterkeys')() 70 | 71 | def itervalues(d): 72 | """Return an iterator over the values of a dictionary.""" 73 | return getattr(d, 'values' if PY3 else 'itervalues')() 74 | 75 | def iteritems(d): 76 | """Return an iterator over the items of a dictionary.""" 77 | return getattr(d, 'items' if PY3 else 'iteritems')() 78 | 79 | try: 80 | from collections.abc import Mapping # python >= 3.3 81 | except ImportError: 82 | from collections import Mapping # python < 3.3 83 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/elftools/common/utils.py: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------- 2 | # elftools: common/utils.py 3 | # 4 | # Miscellaneous utilities for elftools 5 | # 6 | # Eli Bendersky (eliben@gmail.com) 7 | # This code is in the public domain 8 | #------------------------------------------------------------------------------- 9 | from contextlib import contextmanager 10 | from .exceptions import ELFParseError, ELFError, DWARFError 11 | from .py3compat import int2byte 12 | from ..construct import ConstructError, ULInt8 13 | 14 | 15 | def merge_dicts(*dicts): 16 | "Given any number of dicts, merges them into a new one.""" 17 | result = {} 18 | for d in dicts: 19 | result.update(d) 20 | return result 21 | 22 | 23 | def bytelist2string(bytelist): 24 | """ Convert a list of byte values (e.g. [0x10 0x20 0x00]) to a bytes object 25 | (e.g. b'\x10\x20\x00'). 26 | """ 27 | return b''.join(int2byte(b) for b in bytelist) 28 | 29 | 30 | def struct_parse(struct, stream, stream_pos=None): 31 | """ Convenience function for using the given struct to parse a stream. 32 | If stream_pos is provided, the stream is seeked to this position before 33 | the parsing is done. Otherwise, the current position of the stream is 34 | used. 35 | Wraps the error thrown by construct with ELFParseError. 36 | """ 37 | try: 38 | if stream_pos is not None: 39 | stream.seek(stream_pos) 40 | return struct.parse_stream(stream) 41 | except ConstructError as e: 42 | raise ELFParseError(str(e)) 43 | 44 | 45 | def parse_cstring_from_stream(stream, stream_pos=None): 46 | """ Parse a C-string from the given stream. The string is returned without 47 | the terminating \x00 byte. If the terminating byte wasn't found, None 48 | is returned (the stream is exhausted). 49 | If stream_pos is provided, the stream is seeked to this position before 50 | the parsing is done. Otherwise, the current position of the stream is 51 | used. 52 | Note: a bytes object is returned here, because this is what's read from 53 | the binary file. 54 | """ 55 | if stream_pos is not None: 56 | stream.seek(stream_pos) 57 | CHUNKSIZE = 64 58 | chunks = [] 59 | found = False 60 | while True: 61 | chunk = stream.read(CHUNKSIZE) 62 | end_index = chunk.find(b'\x00') 63 | if end_index >= 0: 64 | chunks.append(chunk[:end_index]) 65 | found = True 66 | break 67 | else: 68 | chunks.append(chunk) 69 | if len(chunk) < CHUNKSIZE: 70 | break 71 | return b''.join(chunks) if found else None 72 | 73 | 74 | def elf_assert(cond, msg=''): 75 | """ Assert that cond is True, otherwise raise ELFError(msg) 76 | """ 77 | _assert_with_exception(cond, msg, ELFError) 78 | 79 | 80 | def dwarf_assert(cond, msg=''): 81 | """ Assert that cond is True, otherwise raise DWARFError(msg) 82 | """ 83 | _assert_with_exception(cond, msg, DWARFError) 84 | 85 | 86 | @contextmanager 87 | def preserve_stream_pos(stream): 88 | """ Usage: 89 | # stream has some position FOO (return value of stream.tell()) 90 | with preserve_stream_pos(stream): 91 | # do stuff that manipulates the stream 92 | # stream still has position FOO 93 | """ 94 | saved_pos = stream.tell() 95 | yield 96 | stream.seek(saved_pos) 97 | 98 | 99 | def roundup(num, bits): 100 | """ Round up a number to nearest multiple of 2^bits. The result is a number 101 | where the least significant bits passed in bits are 0. 102 | """ 103 | return (num - 1 | (1 << bits) - 1) + 1 104 | 105 | def read_blob(stream, length): 106 | """Read length bytes from stream, return a list of ints 107 | """ 108 | return [struct_parse(ULInt8(''), stream) for i in range(length)] 109 | 110 | #------------------------- PRIVATE ------------------------- 111 | 112 | def _assert_with_exception(cond, msg, exception_type): 113 | if not cond: 114 | raise exception_type(msg) 115 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/elftools/construct/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (C) 2009 Tomer Filiba, 2010-2011 Corbin Simpson 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/elftools/construct/README: -------------------------------------------------------------------------------- 1 | construct is a Python library for declarative parsing and building of binary 2 | data. This is my fork of construct 2, with some modifications for Python 3 3 | and bug fixes. The construct website is http://construct.readthedocs.org 4 | 5 | pyelftools carries construct around because construct has been abandoned for 6 | a long time and didn't get bugfixes; it also didn't work with Python 3. 7 | 8 | These days (Feb 2018) construct is maintained again, but its APIs have 9 | underwent extensive changes that would require rewriting all of the 10 | construct-facing code in pyelftools. I'm still evaluating the pros/cons of 11 | this effort. See https://github.com/eliben/pyelftools/issues/180 for details. 12 | 13 | LICENSE is the original license. 14 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/elftools/construct/lib/__init__.py: -------------------------------------------------------------------------------- 1 | from .binary import ( 2 | int_to_bin, bin_to_int, swap_bytes, encode_bin, decode_bin) 3 | from .bitstream import BitStreamReader, BitStreamWriter 4 | from .container import (Container, FlagsContainer, ListContainer, 5 | LazyContainer) 6 | from .hex import HexString, hexdump 7 | 8 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/elftools/construct/lib/binary.py: -------------------------------------------------------------------------------- 1 | from .py3compat import int2byte 2 | 3 | 4 | def int_to_bin(number, width=32): 5 | r""" 6 | Convert an integer into its binary representation in a bytes object. 7 | Width is the amount of bits to generate. If width is larger than the actual 8 | amount of bits required to represent number in binary, sign-extension is 9 | used. If it's smaller, the representation is trimmed to width bits. 10 | Each "bit" is either '\x00' or '\x01'. The MSBit is first. 11 | 12 | Examples: 13 | 14 | >>> int_to_bin(19, 5) 15 | b'\x01\x00\x00\x01\x01' 16 | >>> int_to_bin(19, 8) 17 | b'\x00\x00\x00\x01\x00\x00\x01\x01' 18 | """ 19 | if number < 0: 20 | number += 1 << width 21 | i = width - 1 22 | bits = bytearray(width) 23 | while number and i >= 0: 24 | bits[i] = number & 1 25 | number >>= 1 26 | i -= 1 27 | return bytes(bits) 28 | 29 | 30 | _bit_values = { 31 | 0: 0, 32 | 1: 1, 33 | 48: 0, # '0' 34 | 49: 1, # '1' 35 | 36 | # The following are for Python 2, in which iteration over a bytes object 37 | # yields single-character bytes and not integers. 38 | '\x00': 0, 39 | '\x01': 1, 40 | '0': 0, 41 | '1': 1, 42 | } 43 | 44 | def bin_to_int(bits, signed=False): 45 | r""" 46 | Logical opposite of int_to_bin. Both '0' and '\x00' are considered zero, 47 | and both '1' and '\x01' are considered one. Set sign to True to interpret 48 | the number as a 2-s complement signed integer. 49 | """ 50 | number = 0 51 | bias = 0 52 | ptr = 0 53 | if signed and _bit_values[bits[0]] == 1: 54 | bits = bits[1:] 55 | bias = 1 << len(bits) 56 | for b in bits: 57 | number <<= 1 58 | number |= _bit_values[b] 59 | return number - bias 60 | 61 | 62 | def swap_bytes(bits, bytesize=8): 63 | r""" 64 | Bits is a b'' object containing a binary representation. Assuming each 65 | bytesize bits constitute a bytes, perform a endianness byte swap. Example: 66 | 67 | >>> swap_bytes(b'00011011', 2) 68 | b'11100100' 69 | """ 70 | i = 0 71 | l = len(bits) 72 | output = [b""] * ((l // bytesize) + 1) 73 | j = len(output) - 1 74 | while i < l: 75 | output[j] = bits[i : i + bytesize] 76 | i += bytesize 77 | j -= 1 78 | return b"".join(output) 79 | 80 | 81 | _char_to_bin = {} 82 | _bin_to_char = {} 83 | for i in range(256): 84 | ch = int2byte(i) 85 | bin = int_to_bin(i, 8) 86 | # Populate with for both keys i and ch, to support Python 2 & 3 87 | _char_to_bin[ch] = bin 88 | _char_to_bin[i] = bin 89 | _bin_to_char[bin] = ch 90 | 91 | 92 | def encode_bin(data): 93 | """ 94 | Create a binary representation of the given b'' object. Assume 8-bit 95 | ASCII. Example: 96 | 97 | >>> encode_bin('ab') 98 | b"\x00\x01\x01\x00\x00\x00\x00\x01\x00\x01\x01\x00\x00\x00\x01\x00" 99 | """ 100 | return b"".join(_char_to_bin[ch] for ch in data) 101 | 102 | 103 | def decode_bin(data): 104 | """ 105 | Locical opposite of decode_bin. 106 | """ 107 | if len(data) & 7: 108 | raise ValueError("Data length must be a multiple of 8") 109 | i = 0 110 | j = 0 111 | l = len(data) // 8 112 | chars = [b""] * l 113 | while j < l: 114 | chars[j] = _bin_to_char[data[i:i+8]] 115 | i += 8 116 | j += 1 117 | return b"".join(chars) 118 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/elftools/construct/lib/bitstream.py: -------------------------------------------------------------------------------- 1 | from .binary import encode_bin, decode_bin 2 | 3 | class BitStreamReader(object): 4 | 5 | __slots__ = ["substream", "buffer", "total_size"] 6 | 7 | def __init__(self, substream): 8 | self.substream = substream 9 | self.total_size = 0 10 | self.buffer = "" 11 | 12 | def close(self): 13 | if self.total_size % 8 != 0: 14 | raise ValueError("total size of read data must be a multiple of 8", 15 | self.total_size) 16 | 17 | def tell(self): 18 | return self.substream.tell() 19 | 20 | def seek(self, pos, whence = 0): 21 | self.buffer = "" 22 | self.total_size = 0 23 | self.substream.seek(pos, whence) 24 | 25 | def read(self, count): 26 | if count < 0: 27 | raise ValueError("count cannot be negative") 28 | 29 | l = len(self.buffer) 30 | if count == 0: 31 | data = "" 32 | elif count <= l: 33 | data = self.buffer[:count] 34 | self.buffer = self.buffer[count:] 35 | else: 36 | data = self.buffer 37 | count -= l 38 | bytes = count // 8 39 | if count & 7: 40 | bytes += 1 41 | buf = encode_bin(self.substream.read(bytes)) 42 | data += buf[:count] 43 | self.buffer = buf[count:] 44 | self.total_size += len(data) 45 | return data 46 | 47 | class BitStreamWriter(object): 48 | 49 | __slots__ = ["substream", "buffer", "pos"] 50 | 51 | def __init__(self, substream): 52 | self.substream = substream 53 | self.buffer = [] 54 | self.pos = 0 55 | 56 | def close(self): 57 | self.flush() 58 | 59 | def flush(self): 60 | bytes = decode_bin("".join(self.buffer)) 61 | self.substream.write(bytes) 62 | self.buffer = [] 63 | self.pos = 0 64 | 65 | def tell(self): 66 | return self.substream.tell() + self.pos // 8 67 | 68 | def seek(self, pos, whence = 0): 69 | self.flush() 70 | self.substream.seek(pos, whence) 71 | 72 | def write(self, data): 73 | if not data: 74 | return 75 | if type(data) is not str: 76 | raise TypeError("data must be a string, not %r" % (type(data),)) 77 | self.buffer.append(data) 78 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/elftools/construct/lib/hex.py: -------------------------------------------------------------------------------- 1 | from .py3compat import byte2int, int2byte, bytes2str 2 | 3 | 4 | # Map an integer in the inclusive range 0-255 to its string byte representation 5 | _printable = dict((i, ".") for i in range(256)) 6 | _printable.update((i, bytes2str(int2byte(i))) for i in range(32, 128)) 7 | 8 | 9 | def hexdump(data, linesize): 10 | """ 11 | data is a bytes object. The returned result is a string. 12 | """ 13 | prettylines = [] 14 | if len(data) < 65536: 15 | fmt = "%%04X %%-%ds %%s" 16 | else: 17 | fmt = "%%08X %%-%ds %%s" 18 | fmt = fmt % (3 * linesize - 1,) 19 | for i in range(0, len(data), linesize): 20 | line = data[i : i + linesize] 21 | hextext = " ".join('%02x' % byte2int(b) for b in line) 22 | rawtext = "".join(_printable[byte2int(b)] for b in line) 23 | prettylines.append(fmt % (i, str(hextext), str(rawtext))) 24 | return prettylines 25 | 26 | 27 | class HexString(bytes): 28 | """ 29 | Represents bytes that will be hex-dumped to a string when its string 30 | representation is requested. 31 | """ 32 | def __init__(self, data, linesize = 16): 33 | self.linesize = linesize 34 | 35 | def __new__(cls, data, *args, **kwargs): 36 | return bytes.__new__(cls, data) 37 | 38 | def __str__(self): 39 | if not self: 40 | return "''" 41 | sep = "\n" 42 | return sep + sep.join( 43 | hexdump(self, self.linesize)) 44 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/elftools/construct/lib/py3compat.py: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------- 2 | # py3compat.py 3 | # 4 | # Some Python2&3 compatibility code 5 | #------------------------------------------------------------------------------- 6 | import sys 7 | PY3 = sys.version_info[0] == 3 8 | 9 | try: 10 | from collections.abc import MutableMapping # python >= 3.3 11 | except ImportError: 12 | from collections import MutableMapping # python < 3.3 13 | 14 | 15 | if PY3: 16 | import io 17 | StringIO = io.StringIO 18 | BytesIO = io.BytesIO 19 | 20 | def bchr(i): 21 | """ When iterating over b'...' in Python 2 you get single b'_' chars 22 | and in Python 3 you get integers. Call bchr to always turn this 23 | to single b'_' chars. 24 | """ 25 | return bytes((i,)) 26 | 27 | def u(s): 28 | return s 29 | 30 | def int2byte(i): 31 | return bytes((i,)) 32 | 33 | def byte2int(b): 34 | return b 35 | 36 | def str2bytes(s): 37 | return s.encode("latin-1") 38 | 39 | def str2unicode(s): 40 | return s 41 | 42 | def bytes2str(b): 43 | return b.decode('latin-1') 44 | 45 | def decodebytes(b, encoding): 46 | return bytes(b, encoding) 47 | 48 | advance_iterator = next 49 | 50 | else: 51 | import cStringIO 52 | StringIO = BytesIO = cStringIO.StringIO 53 | 54 | int2byte = chr 55 | byte2int = ord 56 | bchr = lambda i: i 57 | 58 | def u(s): 59 | return unicode(s, "unicode_escape") 60 | 61 | def str2bytes(s): 62 | return s 63 | 64 | def str2unicode(s): 65 | return unicode(s, "unicode_escape") 66 | 67 | def bytes2str(b): 68 | return b 69 | 70 | def decodebytes(b, encoding): 71 | return b.decode(encoding) 72 | 73 | def advance_iterator(it): 74 | return it.next() 75 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/elftools/dwarf/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JHUAPL/CodeCut/22c0a93da468f14e4498599b1a4f7aa5f58b4779/codecut-gui/ghidra_scripts/pyelftools-0.28/elftools/dwarf/__init__.py -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/elftools/dwarf/abbrevtable.py: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------- 2 | # elftools: dwarf/abbrevtable.py 3 | # 4 | # DWARF abbreviation table 5 | # 6 | # Eli Bendersky (eliben@gmail.com) 7 | # This code is in the public domain 8 | #------------------------------------------------------------------------------- 9 | from ..common.utils import struct_parse, dwarf_assert 10 | 11 | 12 | class AbbrevTable(object): 13 | """ Represents a DWARF abbreviation table. 14 | """ 15 | def __init__(self, structs, stream, offset): 16 | """ Create new abbreviation table. Parses the actual table from the 17 | stream and stores it internally. 18 | 19 | structs: 20 | A DWARFStructs instance for parsing the data 21 | 22 | stream, offset: 23 | The stream and offset into the stream where this abbreviation 24 | table lives. 25 | """ 26 | self.structs = structs 27 | self.stream = stream 28 | self.offset = offset 29 | 30 | self._abbrev_map = self._parse_abbrev_table() 31 | 32 | def get_abbrev(self, code): 33 | """ Get the AbbrevDecl for a given code. Raise KeyError if no 34 | declaration for this code exists. 35 | """ 36 | return self._abbrev_map[code] 37 | 38 | def _parse_abbrev_table(self): 39 | """ Parse the abbrev table from the stream 40 | """ 41 | map = {} 42 | self.stream.seek(self.offset) 43 | while True: 44 | decl_code = struct_parse( 45 | struct=self.structs.Dwarf_uleb128(''), 46 | stream=self.stream) 47 | if decl_code == 0: 48 | break 49 | declaration = struct_parse( 50 | struct=self.structs.Dwarf_abbrev_declaration, 51 | stream=self.stream) 52 | map[decl_code] = AbbrevDecl(decl_code, declaration) 53 | return map 54 | 55 | 56 | class AbbrevDecl(object): 57 | """ Wraps a parsed abbreviation declaration, exposing its fields with 58 | dict-like access, and adding some convenience methods. 59 | 60 | The abbreviation declaration represents an "entry" that points to it. 61 | """ 62 | def __init__(self, code, decl): 63 | self.code = code 64 | self.decl = decl 65 | 66 | def has_children(self): 67 | """ Does the entry have children? 68 | """ 69 | return self['children_flag'] == 'DW_CHILDREN_yes' 70 | 71 | def iter_attr_specs(self): 72 | """ Iterate over the attribute specifications for the entry. Yield 73 | (name, form) pairs. 74 | """ 75 | for attr_spec in self['attr_spec']: 76 | yield attr_spec.name, attr_spec.form 77 | 78 | def __getitem__(self, entry): 79 | return self.decl[entry] 80 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/elftools/dwarf/ranges.py: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------- 2 | # elftools: dwarf/ranges.py 3 | # 4 | # DWARF ranges section decoding (.debug_ranges) 5 | # 6 | # Eli Bendersky (eliben@gmail.com) 7 | # This code is in the public domain 8 | #------------------------------------------------------------------------------- 9 | import os 10 | from collections import namedtuple 11 | 12 | from ..common.utils import struct_parse 13 | 14 | 15 | RangeEntry = namedtuple('RangeEntry', 'begin_offset end_offset') 16 | BaseAddressEntry = namedtuple('BaseAddressEntry', 'base_address') 17 | 18 | 19 | class RangeLists(object): 20 | """ A single range list is a Python list consisting of RangeEntry or 21 | BaseAddressEntry objects. 22 | """ 23 | def __init__(self, stream, structs): 24 | self.stream = stream 25 | self.structs = structs 26 | self._max_addr = 2 ** (self.structs.address_size * 8) - 1 27 | 28 | def get_range_list_at_offset(self, offset): 29 | """ Get a range list at the given offset in the section. 30 | """ 31 | self.stream.seek(offset, os.SEEK_SET) 32 | return self._parse_range_list_from_stream() 33 | 34 | def iter_range_lists(self): 35 | """ Yield all range lists found in the section. 36 | """ 37 | # Just call _parse_range_list_from_stream until the stream ends 38 | self.stream.seek(0, os.SEEK_END) 39 | endpos = self.stream.tell() 40 | 41 | self.stream.seek(0, os.SEEK_SET) 42 | while self.stream.tell() < endpos: 43 | yield self._parse_range_list_from_stream() 44 | 45 | #------ PRIVATE ------# 46 | 47 | def _parse_range_list_from_stream(self): 48 | lst = [] 49 | while True: 50 | begin_offset = struct_parse( 51 | self.structs.Dwarf_target_addr(''), self.stream) 52 | end_offset = struct_parse( 53 | self.structs.Dwarf_target_addr(''), self.stream) 54 | if begin_offset == 0 and end_offset == 0: 55 | # End of list - we're done. 56 | break 57 | elif begin_offset == self._max_addr: 58 | # Base address selection entry 59 | lst.append(BaseAddressEntry(base_address=end_offset)) 60 | else: 61 | # Range entry 62 | lst.append(RangeEntry( 63 | begin_offset=begin_offset, 64 | end_offset=end_offset)) 65 | return lst 66 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/elftools/ehabi/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JHUAPL/CodeCut/22c0a93da468f14e4498599b1a4f7aa5f58b4779/codecut-gui/ghidra_scripts/pyelftools-0.28/elftools/ehabi/__init__.py -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/elftools/ehabi/constants.py: -------------------------------------------------------------------------------- 1 | EHABI_INDEX_ENTRY_SIZE = 8 2 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/elftools/ehabi/structs.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------- 2 | # elftools: ehabi/structs.py 3 | # 4 | # Encapsulation of Construct structs for parsing an EHABI, adjusted for 5 | # correct endianness and word-size. 6 | # 7 | # LeadroyaL (leadroyal@qq.com) 8 | # This code is in the public domain 9 | # ------------------------------------------------------------------------------- 10 | 11 | from ..construct import UBInt32, ULInt32, Struct 12 | 13 | 14 | class EHABIStructs(object): 15 | """ Accessible attributes: 16 | 17 | EH_index_struct: 18 | Struct of item in section .ARM.exidx. 19 | 20 | EH_table_struct: 21 | Struct of item in section .ARM.extab. 22 | """ 23 | 24 | def __init__(self, little_endian): 25 | self._little_endian = little_endian 26 | self._create_structs() 27 | 28 | def _create_structs(self): 29 | if self._little_endian: 30 | self.EHABI_uint32 = ULInt32 31 | else: 32 | self.EHABI_uint32 = UBInt32 33 | self._create_exception_handler_index() 34 | self._create_exception_handler_table() 35 | 36 | def _create_exception_handler_index(self): 37 | self.EH_index_struct = Struct( 38 | 'EH_index', 39 | self.EHABI_uint32('word0'), 40 | self.EHABI_uint32('word1') 41 | ) 42 | 43 | def _create_exception_handler_table(self): 44 | self.EH_table_struct = Struct( 45 | 'EH_table', 46 | self.EHABI_uint32('word0'), 47 | ) 48 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/elftools/elf/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JHUAPL/CodeCut/22c0a93da468f14e4498599b1a4f7aa5f58b4779/codecut-gui/ghidra_scripts/pyelftools-0.28/elftools/elf/__init__.py -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/elftools/elf/notes.py: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------- 2 | # elftools: elf/notes.py 3 | # 4 | # ELF notes 5 | # 6 | # Eli Bendersky (eliben@gmail.com) 7 | # This code is in the public domain 8 | #------------------------------------------------------------------------------- 9 | from ..common.py3compat import bytes2hex, bytes2str 10 | from ..common.utils import struct_parse, roundup 11 | from ..construct import CString 12 | 13 | 14 | def iter_notes(elffile, offset, size): 15 | """ Yield all the notes in a section or segment. 16 | """ 17 | end = offset + size 18 | while offset < end: 19 | note = struct_parse( 20 | elffile.structs.Elf_Nhdr, 21 | elffile.stream, 22 | stream_pos=offset) 23 | note['n_offset'] = offset 24 | offset += elffile.structs.Elf_Nhdr.sizeof() 25 | elffile.stream.seek(offset) 26 | # n_namesz is 4-byte aligned. 27 | disk_namesz = roundup(note['n_namesz'], 2) 28 | note['n_name'] = bytes2str( 29 | CString('').parse(elffile.stream.read(disk_namesz))) 30 | offset += disk_namesz 31 | 32 | desc_data = elffile.stream.read(note['n_descsz']) 33 | note['n_descdata'] = desc_data 34 | if note['n_type'] == 'NT_GNU_ABI_TAG': 35 | note['n_desc'] = struct_parse(elffile.structs.Elf_abi, 36 | elffile.stream, 37 | offset) 38 | elif note['n_type'] == 'NT_GNU_BUILD_ID': 39 | note['n_desc'] = bytes2hex(desc_data) 40 | elif note['n_type'] == 'NT_GNU_GOLD_VERSION': 41 | note['n_desc'] = bytes2str(desc_data) 42 | elif note['n_type'] == 'NT_PRPSINFO': 43 | note['n_desc'] = struct_parse(elffile.structs.Elf_Prpsinfo, 44 | elffile.stream, 45 | offset) 46 | elif note['n_type'] == 'NT_FILE': 47 | note['n_desc'] = struct_parse(elffile.structs.Elf_Nt_File, 48 | elffile.stream, 49 | offset) 50 | elif note['n_type'] == 'NT_GNU_PROPERTY_TYPE_0': 51 | off = offset 52 | props = [] 53 | while off < end: 54 | p = struct_parse(elffile.structs.Elf_Prop, elffile.stream, off) 55 | off += roundup(p.pr_datasz + 8, 2 if elffile.elfclass == 32 else 3) 56 | props.append(p) 57 | note['n_desc'] = props 58 | else: 59 | note['n_desc'] = desc_data 60 | offset += roundup(note['n_descsz'], 2) 61 | note['n_size'] = offset - note['n_offset'] 62 | yield note 63 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/examples/dwarf_die_tree.py: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------- 2 | # elftools example: dwarf_die_tree.py 3 | # 4 | # In the .debug_info section, Dwarf Information Entries (DIEs) form a tree. 5 | # pyelftools provides easy access to this tree, as demonstrated here. 6 | # 7 | # Eli Bendersky (eliben@gmail.com) 8 | # This code is in the public domain 9 | #------------------------------------------------------------------------------- 10 | from __future__ import print_function 11 | import sys 12 | 13 | # If pyelftools is not installed, the example can also run from the root or 14 | # examples/ dir of the source distribution. 15 | sys.path[0:0] = ['.', '..'] 16 | 17 | from elftools.elf.elffile import ELFFile 18 | 19 | 20 | def process_file(filename): 21 | print('Processing file:', filename) 22 | with open(filename, 'rb') as f: 23 | elffile = ELFFile(f) 24 | 25 | if not elffile.has_dwarf_info(): 26 | print(' file has no DWARF info') 27 | return 28 | 29 | # get_dwarf_info returns a DWARFInfo context object, which is the 30 | # starting point for all DWARF-based processing in pyelftools. 31 | dwarfinfo = elffile.get_dwarf_info() 32 | 33 | for CU in dwarfinfo.iter_CUs(): 34 | # DWARFInfo allows to iterate over the compile units contained in 35 | # the .debug_info section. CU is a CompileUnit object, with some 36 | # computed attributes (such as its offset in the section) and 37 | # a header which conforms to the DWARF standard. The access to 38 | # header elements is, as usual, via item-lookup. 39 | print(' Found a compile unit at offset %s, length %s' % ( 40 | CU.cu_offset, CU['unit_length'])) 41 | 42 | # Start with the top DIE, the root for this CU's DIE tree 43 | top_DIE = CU.get_top_DIE() 44 | print(' Top DIE with tag=%s' % top_DIE.tag) 45 | 46 | # We're interested in the filename... 47 | print(' name=%s' % top_DIE.get_full_path()) 48 | 49 | # Display DIEs recursively starting with top_DIE 50 | die_info_rec(top_DIE) 51 | 52 | 53 | def die_info_rec(die, indent_level=' '): 54 | """ A recursive function for showing information about a DIE and its 55 | children. 56 | """ 57 | print(indent_level + 'DIE tag=%s' % die.tag) 58 | child_indent = indent_level + ' ' 59 | for child in die.iter_children(): 60 | die_info_rec(child, child_indent) 61 | 62 | 63 | if __name__ == '__main__': 64 | if sys.argv[1] == '--test': 65 | for filename in sys.argv[2:]: 66 | process_file(filename) 67 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/examples/dwarf_lineprogram_filenames.py: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------- 2 | # elftools example: dwarf_lineprogram_filenames.py 3 | # 4 | # In the .debug_line section, the Dwarf line program generates a matrix 5 | # of address-source references. This example demonstrates accessing the state 6 | # of each line program entry to retrieve the underlying filenames. 7 | # 8 | # William Woodruff (william@yossarian.net) 9 | # This code is in the public domain 10 | #------------------------------------------------------------------------------- 11 | from __future__ import print_function 12 | from collections import defaultdict 13 | import os 14 | import sys 15 | 16 | # If pyelftools is not installed, the example can also run from the root or 17 | # examples/ dir of the source distribution. 18 | sys.path[0:0] = ['.', '..'] 19 | 20 | from elftools.elf.elffile import ELFFile 21 | 22 | 23 | def process_file(filename): 24 | print('Processing file:', filename) 25 | with open(filename, 'rb') as f: 26 | elffile = ELFFile(f) 27 | 28 | if not elffile.has_dwarf_info(): 29 | print(' file has no DWARF info') 30 | return 31 | 32 | dwarfinfo = elffile.get_dwarf_info() 33 | for CU in dwarfinfo.iter_CUs(): 34 | print(' Found a compile unit at offset %s, length %s' % ( 35 | CU.cu_offset, CU['unit_length'])) 36 | 37 | # Every compilation unit in the DWARF information may or may not 38 | # have a corresponding line program in .debug_line. 39 | line_program = dwarfinfo.line_program_for_CU(CU) 40 | if line_program is None: 41 | print(' DWARF info is missing a line program for this CU') 42 | continue 43 | 44 | # Print a reverse mapping of filename -> #entries 45 | line_entry_mapping(line_program) 46 | 47 | 48 | def line_entry_mapping(line_program): 49 | filename_map = defaultdict(int) 50 | 51 | # The line program, when decoded, returns a list of line program 52 | # entries. Each entry contains a state, which we'll use to build 53 | # a reverse mapping of filename -> #entries. 54 | lp_entries = line_program.get_entries() 55 | for lpe in lp_entries: 56 | # We skip LPEs that don't have an associated file. 57 | # This can happen if instructions in the compiled binary 58 | # don't correspond directly to any original source file. 59 | if not lpe.state or lpe.state.file == 0: 60 | continue 61 | filename = lpe_filename(line_program, lpe.state.file) 62 | filename_map[filename] += 1 63 | 64 | for filename, lpe_count in filename_map.items(): 65 | print(" filename=%s -> %d entries" % (filename, lpe_count)) 66 | 67 | 68 | def lpe_filename(line_program, file_index): 69 | # Retrieving the filename associated with a line program entry 70 | # involves two levels of indirection: we take the file index from 71 | # the LPE to grab the file_entry from the line program header, 72 | # then take the directory index from the file_entry to grab the 73 | # directory name from the line program header. Finally, we 74 | # join the (base) filename from the file_entry to the directory 75 | # name to get the absolute filename. 76 | lp_header = line_program.header 77 | file_entries = lp_header["file_entry"] 78 | 79 | # File and directory indices are 1-indexed. 80 | file_entry = file_entries[file_index - 1] 81 | dir_index = file_entry["dir_index"] 82 | 83 | # A dir_index of 0 indicates that no absolute directory was recorded during 84 | # compilation; return just the basename. 85 | if dir_index == 0: 86 | return file_entry.name.decode() 87 | 88 | directory = lp_header["include_directory"][dir_index - 1] 89 | return os.path.join(directory, file_entry.name).decode() 90 | 91 | 92 | if __name__ == '__main__': 93 | if sys.argv[1] == '--test': 94 | for filename in sys.argv[2:]: 95 | process_file(filename) 96 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/examples/dwarf_range_lists.py: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------- 2 | # elftools example: dwarf_range_lists.py 3 | # 4 | # Examine DIE entries which have range list values, and decode these range 5 | # lists. 6 | # 7 | # Eli Bendersky (eliben@gmail.com) 8 | # This code is in the public domain 9 | #------------------------------------------------------------------------------- 10 | from __future__ import print_function 11 | import sys 12 | 13 | # If pyelftools is not installed, the example can also run from the root or 14 | # examples/ dir of the source distribution. 15 | sys.path[0:0] = ['.', '..'] 16 | 17 | from elftools.common.py3compat import itervalues 18 | from elftools.elf.elffile import ELFFile 19 | from elftools.dwarf.descriptions import ( 20 | describe_DWARF_expr, set_global_machine_arch) 21 | from elftools.dwarf.ranges import RangeEntry 22 | 23 | 24 | def process_file(filename): 25 | print('Processing file:', filename) 26 | with open(filename, 'rb') as f: 27 | elffile = ELFFile(f) 28 | 29 | if not elffile.has_dwarf_info(): 30 | print(' file has no DWARF info') 31 | return 32 | 33 | # get_dwarf_info returns a DWARFInfo context object, which is the 34 | # starting point for all DWARF-based processing in pyelftools. 35 | dwarfinfo = elffile.get_dwarf_info() 36 | 37 | # The range lists are extracted by DWARFInfo from the .debug_ranges 38 | # section, and returned here as a RangeLists object. 39 | range_lists = dwarfinfo.range_lists() 40 | if range_lists is None: 41 | print(' file has no .debug_ranges section') 42 | return 43 | 44 | for CU in dwarfinfo.iter_CUs(): 45 | # DWARFInfo allows to iterate over the compile units contained in 46 | # the .debug_info section. CU is a CompileUnit object, with some 47 | # computed attributes (such as its offset in the section) and 48 | # a header which conforms to the DWARF standard. The access to 49 | # header elements is, as usual, via item-lookup. 50 | print(' Found a compile unit at offset %s, length %s' % ( 51 | CU.cu_offset, CU['unit_length'])) 52 | 53 | # A CU provides a simple API to iterate over all the DIEs in it. 54 | for DIE in CU.iter_DIEs(): 55 | # Go over all attributes of the DIE. Each attribute is an 56 | # AttributeValue object (from elftools.dwarf.die), which we 57 | # can examine. 58 | for attr in itervalues(DIE.attributes): 59 | if attribute_has_range_list(attr): 60 | # This is a range list. Its value is an offset into 61 | # the .debug_ranges section, so we can use the range 62 | # lists object to decode it. 63 | rangelist = range_lists.get_range_list_at_offset( 64 | attr.value) 65 | 66 | print(' DIE %s. attr %s.\n%s' % ( 67 | DIE.tag, 68 | attr.name, 69 | rangelist)) 70 | 71 | 72 | def attribute_has_range_list(attr): 73 | """ Only some attributes can have range list values, if they have the 74 | required DW_FORM (rangelistptr "class" in DWARF spec v3) 75 | """ 76 | if attr.name == 'DW_AT_ranges': 77 | if attr.form in ('DW_FORM_data4', 'DW_FORM_data8'): 78 | return True 79 | return False 80 | 81 | 82 | if __name__ == '__main__': 83 | if sys.argv[1] == '--test': 84 | for filename in sys.argv[2:]: 85 | process_file(filename) 86 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/examples/elf_low_high_api.py: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------- 2 | # elftools example: elf_low_high_api.py 3 | # 4 | # A simple example that shows some usage of the low-level API pyelftools 5 | # provides versus the high-level API while inspecting an ELF file's symbol 6 | # table. 7 | # 8 | # Eli Bendersky (eliben@gmail.com) 9 | # This code is in the public domain 10 | #------------------------------------------------------------------------------- 11 | from __future__ import print_function 12 | import sys 13 | 14 | # If pyelftools is not installed, the example can also run from the root or 15 | # examples/ dir of the source distribution. 16 | sys.path[0:0] = ['.', '..'] 17 | 18 | from elftools.elf.elffile import ELFFile 19 | from elftools.elf.sections import SymbolTableSection 20 | 21 | 22 | def process_file(filename): 23 | print('Processing file:', filename) 24 | with open(filename, 'rb') as f: 25 | section_info_lowlevel(f) 26 | f.seek(0) 27 | section_info_highlevel(f) 28 | 29 | 30 | def section_info_lowlevel(stream): 31 | print('Low level API...') 32 | # We'll still be using the ELFFile context object. It's just too 33 | # convenient to give up, even in the low-level API demonstation :-) 34 | elffile = ELFFile(stream) 35 | 36 | # The e_shnum ELF header field says how many sections there are in a file 37 | print(' %s sections' % elffile['e_shnum']) 38 | 39 | # Try to find the symbol table 40 | for i in range(elffile['e_shnum']): 41 | section_offset = elffile['e_shoff'] + i * elffile['e_shentsize'] 42 | # Parse the section header using structs.Elf_Shdr 43 | stream.seek(section_offset) 44 | section_header = elffile.structs.Elf_Shdr.parse_stream(stream) 45 | if section_header['sh_type'] == 'SHT_SYMTAB': 46 | # Some details about the section. Note that the section name is a 47 | # pointer to the object's string table, so it's only a number 48 | # here. To get to the actual name one would need to parse the string 49 | # table section and extract the name from there (or use the 50 | # high-level API!) 51 | print(' Section name: %s, type: %s' % ( 52 | section_header['sh_name'], section_header['sh_type'])) 53 | break 54 | else: 55 | print(' No symbol table found. Perhaps this ELF has been stripped?') 56 | 57 | 58 | def section_info_highlevel(stream): 59 | print('High level API...') 60 | elffile = ELFFile(stream) 61 | 62 | # Just use the public methods of ELFFile to get what we need 63 | # Note that section names are strings. 64 | print(' %s sections' % elffile.num_sections()) 65 | section = elffile.get_section_by_name('.symtab') 66 | 67 | if not section: 68 | print(' No symbol table found. Perhaps this ELF has been stripped?') 69 | return 70 | 71 | # A section type is in its header, but the name was decoded and placed in 72 | # a public attribute. 73 | print(' Section name: %s, type: %s' %( 74 | section.name, section['sh_type'])) 75 | 76 | # But there's more... If this section is a symbol table section (which is 77 | # the case in the sample ELF file that comes with the examples), we can 78 | # get some more information about it. 79 | if isinstance(section, SymbolTableSection): 80 | num_symbols = section.num_symbols() 81 | print(" It's a symbol section with %s symbols" % num_symbols) 82 | print(" The name of the last symbol in the section is: %s" % ( 83 | section.get_symbol(num_symbols - 1).name)) 84 | 85 | 86 | if __name__ == '__main__': 87 | if sys.argv[1] == '--test': 88 | for filename in sys.argv[2:]: 89 | process_file(filename) 90 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/examples/elf_notes.py: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------- 2 | # elftools example: elf_notes.py 3 | # 4 | # An example of obtaining note sections from an ELF file and examining 5 | # the notes it contains. 6 | # 7 | # Eli Bendersky (eliben@gmail.com) 8 | # This code is in the public domain 9 | #------------------------------------------------------------------------------- 10 | from __future__ import print_function 11 | import sys 12 | 13 | # If pyelftools is not installed, the example can also run from the root or 14 | # examples/ dir of the source distribution. 15 | sys.path[0:0] = ['.', '..'] 16 | 17 | from elftools.elf.elffile import ELFFile 18 | from elftools.elf.sections import NoteSection 19 | from elftools.common.py3compat import bytes2hex 20 | 21 | 22 | def process_file(filename): 23 | print('Processing file:', filename) 24 | with open(filename, 'rb') as f: 25 | for sect in ELFFile(f).iter_sections(): 26 | if not isinstance(sect, NoteSection): 27 | continue 28 | print(' Note section "%s" at offset 0x%.8x with size %d' % ( 29 | sect.name, sect.header['sh_offset'], sect.header['sh_size'])) 30 | for note in sect.iter_notes(): 31 | print(' Name:', note['n_name']) 32 | print(' Type:', note['n_type']) 33 | desc = note['n_desc'] 34 | if note['n_type'] == 'NT_GNU_ABI_TAG': 35 | print(' Desc: %s, ABI: %d.%d.%d' % ( 36 | desc['abi_os'], 37 | desc['abi_major'], 38 | desc['abi_minor'], 39 | desc['abi_tiny'])) 40 | elif note['n_type'] in {'NT_GNU_BUILD_ID', 'NT_GNU_GOLD_VERSION'}: 41 | print(' Desc:', desc) 42 | else: 43 | print(' Desc:', bytes2hex(desc)) 44 | 45 | 46 | if __name__ == '__main__': 47 | if sys.argv[1] == '--test': 48 | for filename in sys.argv[2:]: 49 | process_file(filename) 50 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/examples/elf_relocations.py: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------- 2 | # elftools example: elf_relocations.py 3 | # 4 | # An example of obtaining a relocation section from an ELF file and examining 5 | # the relocation entries it contains. 6 | # 7 | # Eli Bendersky (eliben@gmail.com) 8 | # This code is in the public domain 9 | #------------------------------------------------------------------------------- 10 | from __future__ import print_function 11 | import sys 12 | 13 | # If pyelftools is not installed, the example can also run from the root or 14 | # examples/ dir of the source distribution. 15 | sys.path[0:0] = ['.', '..'] 16 | 17 | from elftools.elf.elffile import ELFFile 18 | from elftools.elf.relocation import RelocationSection 19 | 20 | 21 | def process_file(filename): 22 | print('Processing file:', filename) 23 | with open(filename, 'rb') as f: 24 | elffile = ELFFile(f) 25 | 26 | # Read the .rela.dyn section from the file, by explicitly asking 27 | # ELFFile for this section 28 | # The section names are strings 29 | reladyn_name = '.rela.dyn' 30 | reladyn = elffile.get_section_by_name(reladyn_name) 31 | 32 | if not isinstance(reladyn, RelocationSection): 33 | print(' The file has no %s section' % reladyn_name) 34 | 35 | print(' %s section with %s relocations' % ( 36 | reladyn_name, reladyn.num_relocations())) 37 | 38 | for reloc in reladyn.iter_relocations(): 39 | print(' Relocation (%s)' % 'RELA' if reloc.is_RELA() else 'REL') 40 | # Relocation entry attributes are available through item lookup 41 | print(' offset = %s' % reloc['r_offset']) 42 | 43 | 44 | if __name__ == '__main__': 45 | if sys.argv[1] == '--test': 46 | for filename in sys.argv[2:]: 47 | process_file(filename) 48 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/examples/elf_show_debug_sections.py: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------- 2 | # elftools example: elf_show_debug_sections.py 3 | # 4 | # Show the names of all .debug_* sections in ELF files. 5 | # 6 | # Eli Bendersky (eliben@gmail.com) 7 | # This code is in the public domain 8 | #------------------------------------------------------------------------------- 9 | from __future__ import print_function 10 | import sys 11 | 12 | # If pyelftools is not installed, the example can also run from the root or 13 | # examples/ dir of the source distribution. 14 | sys.path[0:0] = ['.', '..'] 15 | 16 | from elftools.elf.elffile import ELFFile 17 | 18 | 19 | def process_file(filename): 20 | print('In file:', filename) 21 | with open(filename, 'rb') as f: 22 | elffile = ELFFile(f) 23 | 24 | for section in elffile.iter_sections(): 25 | if section.name.startswith('.debug'): 26 | print(' ' + section.name) 27 | 28 | 29 | if __name__ == '__main__': 30 | if sys.argv[1] == '--test': 31 | for filename in sys.argv[2:]: 32 | process_file(filename) 33 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/examples/elfclass_address_size.py: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------- 2 | # elftools example: elfclass_address_size.py 3 | # 4 | # This example explores the ELF class (32 or 64-bit) and address size in each 5 | # of the CUs in the DWARF information. 6 | # 7 | # Eli Bendersky (eliben@gmail.com) 8 | # This code is in the public domain 9 | #------------------------------------------------------------------------------- 10 | from __future__ import print_function 11 | import sys 12 | 13 | # If pyelftools is not installed, the example can also run from the root or 14 | # examples/ dir of the source distribution. 15 | sys.path[0:0] = ['.', '..'] 16 | 17 | from elftools.elf.elffile import ELFFile 18 | 19 | 20 | def process_file(filename): 21 | with open(filename, 'rb') as f: 22 | elffile = ELFFile(f) 23 | # elfclass is a public attribute of ELFFile, read from its header 24 | print('%s: elfclass is %s' % (filename, elffile.elfclass)) 25 | 26 | if elffile.has_dwarf_info(): 27 | dwarfinfo = elffile.get_dwarf_info() 28 | for CU in dwarfinfo.iter_CUs(): 29 | # cu_offset is a public attribute of CU 30 | # address_size is part of the CU header 31 | print(' CU at offset 0x%x. address_size is %s' % ( 32 | CU.cu_offset, CU['address_size'])) 33 | 34 | 35 | if __name__ == '__main__': 36 | if sys.argv[1] == '--test': 37 | for filename in sys.argv[2:]: 38 | process_file(filename) 39 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/examples/examine_dwarf_info.py: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------- 2 | # elftools example: examine_dwarf_info.py 3 | # 4 | # An example of examining information in the .debug_info section of an ELF file. 5 | # 6 | # Eli Bendersky (eliben@gmail.com) 7 | # This code is in the public domain 8 | #------------------------------------------------------------------------------- 9 | from __future__ import print_function 10 | import sys 11 | 12 | # If pyelftools is not installed, the example can also run from the root or 13 | # examples/ dir of the source distribution. 14 | sys.path[0:0] = ['.', '..'] 15 | 16 | from elftools.elf.elffile import ELFFile 17 | 18 | 19 | def process_file(filename): 20 | print('Processing file:', filename) 21 | with open(filename, 'rb') as f: 22 | elffile = ELFFile(f) 23 | 24 | if not elffile.has_dwarf_info(): 25 | print(' file has no DWARF info') 26 | return 27 | 28 | # get_dwarf_info returns a DWARFInfo context object, which is the 29 | # starting point for all DWARF-based processing in pyelftools. 30 | dwarfinfo = elffile.get_dwarf_info() 31 | 32 | for CU in dwarfinfo.iter_CUs(): 33 | # DWARFInfo allows to iterate over the compile units contained in 34 | # the .debug_info section. CU is a CompileUnit object, with some 35 | # computed attributes (such as its offset in the section) and 36 | # a header which conforms to the DWARF standard. The access to 37 | # header elements is, as usual, via item-lookup. 38 | print(' Found a compile unit at offset %s, length %s' % ( 39 | CU.cu_offset, CU['unit_length'])) 40 | 41 | # The first DIE in each compile unit describes it. 42 | top_DIE = CU.get_top_DIE() 43 | print(' Top DIE with tag=%s' % top_DIE.tag) 44 | 45 | # We're interested in the filename... 46 | print(' name=%s' % top_DIE.get_full_path()) 47 | 48 | if __name__ == '__main__': 49 | if sys.argv[1] == '--test': 50 | for filename in sys.argv[2:]: 51 | process_file(filename) 52 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/examples/reference_output/dwarf_decode_address.out: -------------------------------------------------------------------------------- 1 | Processing file: ./examples/sample_exe64.elf 2 | Function: main 3 | File: z.c 4 | Line: 3 5 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/examples/reference_output/dwarf_die_tree.out: -------------------------------------------------------------------------------- 1 | Processing file: ./examples/sample_exe64.elf 2 | Found a compile unit at offset 0, length 115 3 | Top DIE with tag=DW_TAG_compile_unit 4 | name=/usr/src/packages/BUILD/glibc-2.11.1/csu/../sysdeps/x86_64/elf/start.S 5 | DIE tag=DW_TAG_compile_unit 6 | Found a compile unit at offset 119, length 135 7 | Top DIE with tag=DW_TAG_compile_unit 8 | name=/usr/src/packages/BUILD/glibc-2.11.1/csu/init.c 9 | DIE tag=DW_TAG_compile_unit 10 | DIE tag=DW_TAG_base_type 11 | DIE tag=DW_TAG_base_type 12 | DIE tag=DW_TAG_base_type 13 | DIE tag=DW_TAG_base_type 14 | DIE tag=DW_TAG_base_type 15 | DIE tag=DW_TAG_base_type 16 | DIE tag=DW_TAG_base_type 17 | DIE tag=DW_TAG_base_type 18 | DIE tag=DW_TAG_base_type 19 | DIE tag=DW_TAG_base_type 20 | DIE tag=DW_TAG_variable 21 | DIE tag=DW_TAG_const_type 22 | Found a compile unit at offset 258, length 156 23 | Top DIE with tag=DW_TAG_compile_unit 24 | name=/tmp/ebenders/z.c 25 | DIE tag=DW_TAG_compile_unit 26 | DIE tag=DW_TAG_subprogram 27 | DIE tag=DW_TAG_formal_parameter 28 | DIE tag=DW_TAG_formal_parameter 29 | DIE tag=DW_TAG_base_type 30 | DIE tag=DW_TAG_pointer_type 31 | DIE tag=DW_TAG_pointer_type 32 | DIE tag=DW_TAG_base_type 33 | DIE tag=DW_TAG_variable 34 | Found a compile unit at offset 418, length 300 35 | Top DIE with tag=DW_TAG_compile_unit 36 | name=/usr/src/packages/BUILD/glibc-2.11.1/csu/elf-init.c 37 | DIE tag=DW_TAG_compile_unit 38 | DIE tag=DW_TAG_base_type 39 | DIE tag=DW_TAG_typedef 40 | DIE tag=DW_TAG_base_type 41 | DIE tag=DW_TAG_base_type 42 | DIE tag=DW_TAG_subprogram 43 | DIE tag=DW_TAG_subprogram 44 | DIE tag=DW_TAG_formal_parameter 45 | DIE tag=DW_TAG_formal_parameter 46 | DIE tag=DW_TAG_formal_parameter 47 | DIE tag=DW_TAG_variable 48 | DIE tag=DW_TAG_lexical_block 49 | DIE tag=DW_TAG_variable 50 | DIE tag=DW_TAG_pointer_type 51 | DIE tag=DW_TAG_pointer_type 52 | DIE tag=DW_TAG_base_type 53 | DIE tag=DW_TAG_const_type 54 | DIE tag=DW_TAG_array_type 55 | DIE tag=DW_TAG_subrange_type 56 | DIE tag=DW_TAG_subroutine_type 57 | DIE tag=DW_TAG_formal_parameter 58 | DIE tag=DW_TAG_formal_parameter 59 | DIE tag=DW_TAG_formal_parameter 60 | DIE tag=DW_TAG_pointer_type 61 | DIE tag=DW_TAG_variable 62 | DIE tag=DW_TAG_variable 63 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/examples/reference_output/dwarf_lineprogram_filenames.out: -------------------------------------------------------------------------------- 1 | Processing file: ./examples/sample_exe64.elf 2 | Found a compile unit at offset 0, length 115 3 | filename=../sysdeps/x86_64/elf/start.S -> 13 entries 4 | Found a compile unit at offset 119, length 135 5 | Found a compile unit at offset 258, length 156 6 | filename=z.c -> 5 entries 7 | Found a compile unit at offset 418, length 300 8 | filename=elf-init.c -> 15 entries 9 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/examples/reference_output/dwarf_location_info.out: -------------------------------------------------------------------------------- 1 | Processing file: ./examples/sample_exe64.elf 2 | Found a compile unit at offset 0, length 115 3 | Found a compile unit at offset 119, length 135 4 | DIE DW_TAG_variable. attr DW_AT_location. 5 | (DW_OP_addr: 400608) 6 | Found a compile unit at offset 258, length 156 7 | DIE DW_TAG_subprogram. attr DW_AT_frame_base. 8 | LocationEntry(entry_offset=0, begin_offset=0, end_offset=1, loc_expr=[119, 8]) <<(DW_OP_breg7 (rsp): 8)>> 9 | LocationEntry(entry_offset=20, begin_offset=1, end_offset=4, loc_expr=[119, 16]) <<(DW_OP_breg7 (rsp): 16)>> 10 | LocationEntry(entry_offset=40, begin_offset=4, end_offset=43, loc_expr=[118, 16]) <<(DW_OP_breg6 (rbp): 16)>> 11 | DIE DW_TAG_formal_parameter. attr DW_AT_location. 12 | (DW_OP_fbreg: -20) 13 | DIE DW_TAG_formal_parameter. attr DW_AT_location. 14 | (DW_OP_fbreg: -32) 15 | DIE DW_TAG_variable. attr DW_AT_location. 16 | (DW_OP_addr: 601018) 17 | Found a compile unit at offset 418, length 300 18 | DIE DW_TAG_subprogram. attr DW_AT_frame_base. 19 | (DW_OP_breg7 (rsp): 8) 20 | DIE DW_TAG_subprogram. attr DW_AT_frame_base. 21 | LocationEntry(entry_offset=76, begin_offset=16, end_offset=64, loc_expr=[119, 8]) <<(DW_OP_breg7 (rsp): 8)>> 22 | LocationEntry(entry_offset=96, begin_offset=64, end_offset=153, loc_expr=[119, 192, 0]) <<(DW_OP_breg7 (rsp): 64)>> 23 | DIE DW_TAG_formal_parameter. attr DW_AT_location. 24 | LocationEntry(entry_offset=133, begin_offset=16, end_offset=85, loc_expr=[85]) <<(DW_OP_reg5 (rdi))>> 25 | LocationEntry(entry_offset=152, begin_offset=85, end_offset=143, loc_expr=[94]) <<(DW_OP_reg14 (r14))>> 26 | DIE DW_TAG_formal_parameter. attr DW_AT_location. 27 | LocationEntry(entry_offset=187, begin_offset=16, end_offset=85, loc_expr=[84]) <<(DW_OP_reg4 (rsi))>> 28 | LocationEntry(entry_offset=206, begin_offset=85, end_offset=138, loc_expr=[93]) <<(DW_OP_reg13 (r13))>> 29 | DIE DW_TAG_formal_parameter. attr DW_AT_location. 30 | LocationEntry(entry_offset=241, begin_offset=16, end_offset=85, loc_expr=[81]) <<(DW_OP_reg1 (rdx))>> 31 | LocationEntry(entry_offset=260, begin_offset=85, end_offset=133, loc_expr=[92]) <<(DW_OP_reg12 (r12))>> 32 | DIE DW_TAG_variable. attr DW_AT_location. 33 | LocationEntry(entry_offset=295, begin_offset=92, end_offset=123, loc_expr=[83]) <<(DW_OP_reg3 (rbx))>> 34 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/examples/reference_output/dwarf_pubnames_types.out: -------------------------------------------------------------------------------- 1 | Processing file: ./examples/sample_exe64.elf 2 | 5 entries found in .debug_pubnames 3 | Trying pubnames example ... 4 | _IO_stdin_used: cu_ofs = 119, die_ofs = 230 5 | Fetching the actual die for _IO_stdin_used ... 6 | Die Name: _IO_stdin_used 7 | main: cu_ofs = 258, die_ofs = 303 8 | Fetching the actual die for main ... 9 | Die Name: main 10 | glob: cu_ofs = 258, die_ofs = 395 11 | Fetching the actual die for glob ... 12 | Die Name: glob 13 | __libc_csu_fini: cu_ofs = 418, die_ofs = 495 14 | Fetching the actual die for __libc_csu_fini ... 15 | Die Name: __libc_csu_fini 16 | __libc_csu_init: cu_ofs = 418, die_ofs = 523 17 | Fetching the actual die for __libc_csu_init ... 18 | Die Name: __libc_csu_init 19 | Dumping .debug_pubnames table ... 20 | ------------------------------------------------------------------ 21 | Symbol CU_OFS DIE_OFS 22 | ------------------------------------------------------------------ 23 | _IO_stdin_used 119 230 24 | main 258 303 25 | glob 258 395 26 | __libc_csu_fini 418 495 27 | __libc_csu_init 418 523 28 | ------------------------------------------------------------------ 29 | ERROR: No .debug_pubtypes section found in ELF 30 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/examples/reference_output/dwarf_range_lists.out: -------------------------------------------------------------------------------- 1 | Processing file: ./examples/sample_exe64.elf 2 | Found a compile unit at offset 0, length 115 3 | Found a compile unit at offset 119, length 135 4 | Found a compile unit at offset 258, length 156 5 | Found a compile unit at offset 418, length 300 6 | DIE DW_TAG_lexical_block. attr DW_AT_ranges. 7 | [RangeEntry(begin_offset=26, end_offset=40), RangeEntry(begin_offset=85, end_offset=118), RangeEntry(begin_offset=73, end_offset=77), RangeEntry(begin_offset=64, end_offset=67)] 8 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/examples/reference_output/elf_low_high_api.out: -------------------------------------------------------------------------------- 1 | Processing file: ./examples/sample_exe64.elf 2 | Low level API... 3 | 42 sections 4 | Section name: 1, type: SHT_SYMTAB 5 | High level API... 6 | 42 sections 7 | Section name: .symtab, type: SHT_SYMTAB 8 | It's a symbol section with 80 symbols 9 | The name of the last symbol in the section is: _init 10 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/examples/reference_output/elf_notes.out: -------------------------------------------------------------------------------- 1 | Processing file: ./examples/sample_exe64.elf 2 | Note section ".note.ABI-tag" at offset 0x00000254 with size 32 3 | Name: GNU 4 | Type: NT_GNU_ABI_TAG 5 | Desc: ELF_NOTE_OS_LINUX, ABI: 2.6.4 6 | Note section ".note.SuSE" at offset 0x00000274 with size 24 7 | Name: SuSE 8 | Type: 1163097427 9 | Desc: 01000a02 10 | Note section ".note.gnu.build-id" at offset 0x0000028c with size 36 11 | Name: GNU 12 | Type: NT_GNU_BUILD_ID 13 | Desc: 8e50cda8e25993499ac4aa2d8deaf58d0949d47d 14 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/examples/reference_output/elf_relocations.out: -------------------------------------------------------------------------------- 1 | Processing file: ./examples/sample_exe64.elf 2 | .rela.dyn section with 1 relocations 3 | Relocation (RELA) 4 | offset = 6295520 5 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/examples/reference_output/elf_show_debug_sections.out: -------------------------------------------------------------------------------- 1 | In file: ./examples/sample_exe64.elf 2 | .debug_aranges 3 | .debug_pubnames 4 | .debug_info 5 | .debug_abbrev 6 | .debug_line 7 | .debug_frame 8 | .debug_str 9 | .debug_loc 10 | .debug_ranges 11 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/examples/reference_output/elfclass_address_size.out: -------------------------------------------------------------------------------- 1 | ./examples/sample_exe64.elf: elfclass is 64 2 | CU at offset 0x0. address_size is 8 3 | CU at offset 0x77. address_size is 8 4 | CU at offset 0x102. address_size is 8 5 | CU at offset 0x1a2. address_size is 8 6 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/examples/reference_output/examine_dwarf_info.out: -------------------------------------------------------------------------------- 1 | Processing file: ./examples/sample_exe64.elf 2 | Found a compile unit at offset 0, length 115 3 | Top DIE with tag=DW_TAG_compile_unit 4 | name=/usr/src/packages/BUILD/glibc-2.11.1/csu/../sysdeps/x86_64/elf/start.S 5 | Found a compile unit at offset 119, length 135 6 | Top DIE with tag=DW_TAG_compile_unit 7 | name=/usr/src/packages/BUILD/glibc-2.11.1/csu/init.c 8 | Found a compile unit at offset 258, length 156 9 | Top DIE with tag=DW_TAG_compile_unit 10 | name=/tmp/ebenders/z.c 11 | Found a compile unit at offset 418, length 300 12 | Top DIE with tag=DW_TAG_compile_unit 13 | name=/usr/src/packages/BUILD/glibc-2.11.1/csu/elf-init.c 14 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/examples/sample_exe64.elf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JHUAPL/CodeCut/22c0a93da468f14e4498599b1a4f7aa5f58b4779/codecut-gui/ghidra_scripts/pyelftools-0.28/examples/sample_exe64.elf -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/pyelftools.sublime-project: -------------------------------------------------------------------------------- 1 | { 2 | "folders": 3 | [ 4 | { 5 | "path": ".", 6 | "folder_exclude_patterns": ["build", "dist", ".tox", ".hg"] 7 | } 8 | ] 9 | } 10 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_wheel] 2 | universal = 1 3 | 4 | [metadata] 5 | license_file = LICENSE 6 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/setup.py: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------- 2 | # pyelftools: setup.py 3 | # 4 | # Setup/installation script. 5 | # 6 | # Eli Bendersky (eliben@gmail.com) 7 | # This code is in the public domain 8 | #------------------------------------------------------------------------------- 9 | import os, sys 10 | from setuptools import setup 11 | 12 | 13 | try: 14 | with open('README', 'rt') as readme: 15 | description = '\n' + readme.read() 16 | except IOError: 17 | # maybe running setup.py from some other dir 18 | description = '' 19 | 20 | 21 | setup( 22 | # metadata 23 | name='pyelftools', 24 | description='Library for analyzing ELF files and DWARF debugging information', 25 | long_description=description, 26 | license='Public domain', 27 | version='0.28', 28 | author='Eli Bendersky', 29 | maintainer='Eli Bendersky', 30 | author_email='eliben@gmail.com', 31 | url='https://github.com/eliben/pyelftools', 32 | platforms='Cross Platform', 33 | classifiers = [ 34 | 'Programming Language :: Python :: 2', 35 | 'Programming Language :: Python :: 3', 36 | ], 37 | 38 | # All packages and sub-packages must be listed here 39 | packages=[ 40 | 'elftools', 41 | 'elftools.elf', 42 | 'elftools.common', 43 | 'elftools.dwarf', 44 | 'elftools.ehabi', 45 | 'elftools.construct', 'elftools.construct.lib', 46 | ], 47 | 48 | scripts=['scripts/readelf.py'] 49 | ) 50 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py27,py38 3 | 4 | [testenv] 5 | setenv = 6 | LC_ALL = en_US.utf-8 7 | commands = 8 | python test/run_all_unittests.py 9 | python test/run_examples_test.py 10 | python test/run_readelf_tests.py --parallel 11 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/pyelftools-0.28/z.py: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------- 2 | # elftools 3 | # 4 | # Eli Bendersky (eliben@gmail.com) 5 | # This code is in the public domain 6 | #------------------------------------------------------------------------------- 7 | 8 | # Just a script for playing around with pyelftools during testing 9 | # please ignore it! 10 | # 11 | from __future__ import print_function 12 | 13 | import sys, pprint 14 | from elftools.elf.structs import ELFStructs 15 | from elftools.elf.elffile import ELFFile 16 | from elftools.elf.sections import * 17 | 18 | from elftools.elf.relocation import * 19 | 20 | 21 | stream = open('test/testfiles/exe_simple64.elf', 'rb') 22 | 23 | efile = ELFFile(stream) 24 | print('elfclass', efile.elfclass) 25 | print('===> %s sections!' % efile.num_sections()) 26 | print(efile.header) 27 | 28 | dinfo = efile.get_dwarf_info() 29 | from elftools.dwarf.locationlists import LocationLists 30 | from elftools.dwarf.descriptions import describe_DWARF_expr 31 | llists = LocationLists(dinfo.debug_loc_sec.stream, dinfo.structs) 32 | for loclist in llists.iter_location_lists(): 33 | print('----> loclist!') 34 | for li in loclist: 35 | print(li) 36 | print(describe_DWARF_expr(li.loc_expr, dinfo.structs)) 37 | 38 | 39 | -------------------------------------------------------------------------------- /codecut-gui/ghidra_scripts/range.py: -------------------------------------------------------------------------------- 1 | #@category AMP-Improved 2 | from generate_c import generate_recompilable_c_code 3 | import os 4 | from ghidra.util.task import TaskMonitor 5 | 6 | 7 | def write_c_code_to_file(c_code, output_file_path): 8 | with open(output_file_path, 'w') as f: 9 | f.write(c_code) 10 | 11 | 12 | if __name__ == '__main__': 13 | 14 | args = getScriptArgs() 15 | start_addr = args[0] 16 | end_addr = args[1] 17 | 18 | file_name = args[2] 19 | output_dir = file_name.rsplit("/", 1)[0] + "/" 20 | 21 | println("Recomp C Range Entry: %s - %s" % (start_addr, end_addr)) 22 | c_code = generate_recompilable_c_code(start_addr, end_addr, 23 | currentProgram, monitor) 24 | 25 | #file_name = currentProgram.getName() 26 | 27 | #output_dir = askDirectory('Output Directory', 28 | # 'Save C code output' 29 | # ).getPath() 30 | 31 | #output_file_path = os.path.join(output_dir, file_name) 32 | 33 | write_c_code_to_file(c_code, file_name) 34 | 35 | println('C code has been saved to %s' % file_name) 36 | 37 | -------------------------------------------------------------------------------- /codecut-gui/lib/README.txt: -------------------------------------------------------------------------------- 1 | The "lib" directory is intended to hold Jar files which this module 2 | is dependent upon. This directory may be eliminated from a specific 3 | module if no other Jar files are needed. 4 | -------------------------------------------------------------------------------- /codecut-gui/os/linux64/README.txt: -------------------------------------------------------------------------------- 1 | The "os/linux64" directory is intended to hold Linux native binaries 2 | which this module is dependent upon. This directory may be eliminated for a specific 3 | module if native binaries are not provided for the corresponding platform. 4 | -------------------------------------------------------------------------------- /codecut-gui/os/osx64/README.txt: -------------------------------------------------------------------------------- 1 | The "os/osx64" directory is intended to hold macOS (OS X) native binaries 2 | which this module is dependent upon. This directory may be eliminated for a specific 3 | module if native binaries are not provided for the corresponding platform. 4 | -------------------------------------------------------------------------------- /codecut-gui/os/win64/README.txt: -------------------------------------------------------------------------------- 1 | The "os/win64" directory is intended to hold MS Windows native binaries (.exe) 2 | which this module is dependent upon. This directory may be eliminated for a specific 3 | module if native binaries are not provided for the corresponding platform. 4 | -------------------------------------------------------------------------------- /codecut-gui/src/main/help/help/TOC_Source.xml: -------------------------------------------------------------------------------- 1 | 2 | 49 | 50 | 51 | 52 | 57 | 58 | -------------------------------------------------------------------------------- /codecut-gui/src/main/help/help/shared/Frontpage.css: -------------------------------------------------------------------------------- 1 | /* ### 2 | * IP: GHIDRA 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | /* 17 | WARNING! 18 | This file is copied to all help directories. If you change this file, you must copy it 19 | to each src/main/help/help/shared directory. 20 | 21 | 22 | Java Help Note: JavaHelp does not accept sizes (like in 'margin-top') in anything but 23 | px (pixel) or with no type marking. 24 | 25 | */ 26 | 27 | body { margin-bottom: 50px; margin-left: 10px; margin-right: 10px; margin-top: 10px; } /* some padding to improve readability */ 28 | li { font-family:times new roman; font-size:14pt; } 29 | h1 { color:#000080; font-family:times new roman; font-size:36pt; font-style:italic; font-weight:bold; text-align:center; } 30 | h2 { margin: 10px; margin-top: 20px; color:#984c4c; font-family:times new roman; font-size:18pt; font-weight:bold; } 31 | h3 { margin-left: 10px; margin-top: 20px; color:#0000ff; font-family:times new roman; `font-size:14pt; font-weight:bold; } 32 | h4 { margin-left: 10px; margin-top: 20px; font-family:times new roman; font-size:14pt; font-style:italic; } 33 | 34 | /* 35 | P tag code. Most of the help files nest P tags inside of blockquote tags (the was the 36 | way it had been done in the beginning). The net effect is that the text is indented. In 37 | modern HTML we would use CSS to do this. We need to support the Ghidra P tags, nested in 38 | blockquote tags, as well as naked P tags. The following two lines accomplish this. Note 39 | that the 'blockquote p' definition will inherit from the first 'p' definition. 40 | */ 41 | p { margin-left: 40px; font-family:times new roman; font-size:14pt; } 42 | blockquote p { margin-left: 10px; } 43 | 44 | p.providedbyplugin { color:#7f7f7f; margin-left: 10px; font-size:14pt; margin-top:100px } 45 | p.ProvidedByPlugin { color:#7f7f7f; margin-left: 10px; font-size:14pt; margin-top:100px } 46 | p.relatedtopic { color:#800080; margin-left: 10px; font-size:14pt; } 47 | p.RelatedTopic { color:#800080; margin-left: 10px; font-size:14pt; } 48 | 49 | /* 50 | We wish for a tables to have space between it and the preceding element, so that text 51 | is not too close to the top of the table. Also, nest the table a bit so that it is clear 52 | the table relates to the preceding text. 53 | */ 54 | table { margin-left: 20px; margin-top: 10px; width: 80%;} 55 | td { font-family:times new roman; font-size:14pt; vertical-align: top; } 56 | th { font-family:times new roman; font-size:14pt; font-weight:bold; background-color: #EDF3FE; } 57 | 58 | /* 59 | Code-like formatting for things such as file system paths and proper names of classes, 60 | methods, etc. To apply this to a file path, use this syntax: 61 | ... 62 | */ 63 | code { color: black; font-weight: bold; font-family: courier new, monospace; font-size: 14pt; white-space: nowrap; } 64 | code.path { color: #4682B4; font-weight: bold; font-family: courier new, monospace; font-size: 14pt; white-space: nowrap; } 65 | -------------------------------------------------------------------------------- /codecut-gui/src/main/help/help/topics/skeleton/help.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 7 | 8 | 9 | 10 | 11 | 12 | Skeleton Help File for a Module 13 | 14 | 15 | 16 | 17 |

Skeleton Help File for a Module

18 | 19 |

This is a simple skeleton help topic. For a better description of what should and should not 20 | go in here, see the "sample" Ghidra extension in the Extensions/Ghidra directory, or see your 21 | favorite help topic. In general, language modules do not have their own help topics.

22 | 23 | 24 | -------------------------------------------------------------------------------- /codecut-gui/src/main/java/codecutguiv2/ModNamingPython.java: -------------------------------------------------------------------------------- 1 | /* ### 2 | * © 2022 The Johns Hopkins University Applied Physics Laboratory LLC (JHU/APL). 3 | * All Rights Reserved. 4 | * 5 | * This material may be only be used, modified, or reproduced by or for the U.S. 6 | * Government pursuant to the license rights granted under the clauses at 7 | * DFARS 252.227-7013/7014 or FAR 52.227-14. For any other permission, please 8 | * contact the Office of Technology Transfer at JHU/APL. 9 | * 10 | * NO WARRANTY, NO LIABILITY. THIS MATERIAL IS PROVIDED “AS IS.” JHU/APL MAKES 11 | * NO REPRESENTATION OR WARRANTY WITH RESPECT TO THE PERFORMANCE OF THE MATERIALS, 12 | * INCLUDING THEIR SAFETY, EFFECTIVENESS, OR COMMERCIAL VIABILITY, AND DISCLAIMS 13 | * ALL WARRANTIES IN THE MATERIAL, WHETHER EXPRESS OR IMPLIED, INCLUDING 14 | * (BUT NOT LIMITED TO) ANY AND ALL IMPLIED WARRANTIES OF PERFORMANCE, 15 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF 16 | * INTELLECTUAL PROPERTY OR OTHER THIRD PARTY RIGHTS. ANY USER OF THE MATERIAL 17 | * ASSUMES THE ENTIRE RISK AND LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL 18 | * JHU/APL BE LIABLE TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT, 19 | * CONSEQUENTIAL, SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR INABILITY TO 20 | * USE, THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES FOR LOST PROFITS. 21 | * 22 | * HAVE A NICE DAY. 23 | */ 24 | 25 | /* This material is based upon work supported by the Defense Advanced Research 26 | * Projects Agency (DARPA) and Naval Information Warfare Center Pacific (NIWC Pacific) 27 | * under Contract Number N66001-20-C-4024. 28 | */ 29 | 30 | package codecutguiv2; 31 | 32 | import java.io.BufferedReader; 33 | import java.io.IOException; 34 | import java.io.InputStream; 35 | import java.io.InputStreamReader; 36 | import java.io.OutputStream; 37 | import java.util.stream.Collectors; 38 | import docking.widgets.dialogs.MultiLineMessageDialog; 39 | import ghidra.framework.Application; 40 | 41 | public class ModNamingPython { 42 | public Runtime runtime; 43 | public String pythonExec; 44 | 45 | public Process process; 46 | public OutputStream stdin; 47 | public InputStream stdout; 48 | public InputStream stderr; 49 | 50 | public ModNamingPython(String pythonExec) { 51 | this.pythonExec = pythonExec; 52 | this.runtime = Runtime.getRuntime(); 53 | } 54 | 55 | public int startProcess() throws IOException { 56 | String pythonFile = Application.getModuleDataFile("modnaming.py").toString(); 57 | 58 | String[] exec = {pythonExec, pythonFile}; 59 | 60 | try { 61 | process = runtime.exec(exec); 62 | } 63 | catch (IOException e) { 64 | // show message about invalid python executable path 65 | MultiLineMessageDialog.showMessageDialog(null, "Invalid Python Path", 66 | "Python Error! Please check path under " + 67 | "\n Edit -> Tool Options -> Python Executable.", 68 | e.getMessage(), MultiLineMessageDialog.WARNING_MESSAGE); 69 | return -1; 70 | 71 | } 72 | 73 | // Yes this is confusing. stdin is a Java OutputStream, stdin is an InputStream 74 | stdin = process.getOutputStream(); 75 | stdout = process.getInputStream(); 76 | stderr = process.getErrorStream(); 77 | return 0; 78 | } 79 | 80 | public void waitFor() throws InterruptedException { 81 | process.waitFor(); 82 | } 83 | 84 | public void writeProcess(String data) throws IOException { 85 | writeProcess(data.getBytes()); 86 | } 87 | 88 | public void writeProcess(byte[] data) throws IOException { 89 | stdin.write(data); 90 | stdin.flush(); 91 | } 92 | 93 | public String readProcessOutput() { 94 | return readProcess(stdout); 95 | } 96 | 97 | public String readProcessError() { 98 | return readProcess(stderr); 99 | } 100 | 101 | public String readProcess(InputStream stream) { 102 | String result = ""; 103 | 104 | try { 105 | if (stream != null && stream.available() > 0) { 106 | result = new BufferedReader(new InputStreamReader(stream)) 107 | .lines().collect(Collectors.joining("\n")); 108 | } 109 | } catch (IOException e) { 110 | return result; 111 | } 112 | 113 | return result; 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /codecut-gui/src/main/java/codecutguiv2/ReferencePanel.java: -------------------------------------------------------------------------------- 1 | /* ### 2 | * © 2022 The Johns Hopkins University Applied Physics Laboratory LLC (JHU/APL). 3 | * All Rights Reserved. 4 | * 5 | * This material may be only be used, modified, or reproduced by or for the U.S. 6 | * Government pursuant to the license rights granted under the clauses at 7 | * DFARS 252.227-7013/7014 or FAR 52.227-14. For any other permission, please 8 | * contact the Office of Technology Transfer at JHU/APL. 9 | * 10 | * NO WARRANTY, NO LIABILITY. THIS MATERIAL IS PROVIDED “AS IS.” JHU/APL MAKES 11 | * NO REPRESENTATION OR WARRANTY WITH RESPECT TO THE PERFORMANCE OF THE MATERIALS, 12 | * INCLUDING THEIR SAFETY, EFFECTIVENESS, OR COMMERCIAL VIABILITY, AND DISCLAIMS 13 | * ALL WARRANTIES IN THE MATERIAL, WHETHER EXPRESS OR IMPLIED, INCLUDING 14 | * (BUT NOT LIMITED TO) ANY AND ALL IMPLIED WARRANTIES OF PERFORMANCE, 15 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF 16 | * INTELLECTUAL PROPERTY OR OTHER THIRD PARTY RIGHTS. ANY USER OF THE MATERIAL 17 | * ASSUMES THE ENTIRE RISK AND LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL 18 | * JHU/APL BE LIABLE TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT, 19 | * CONSEQUENTIAL, SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR INABILITY TO 20 | * USE, THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES FOR LOST PROFITS. 21 | * 22 | * HAVE A NICE DAY. 23 | */ 24 | 25 | /* This material is based upon work supported by the Defense Advanced Research 26 | * Projects Agency (DARPA) and Naval Information Warfare Center Pacific (NIWC Pacific) 27 | * under Contract Number N66001-20-C-4024. 28 | */ 29 | 30 | package codecutguiv2; 31 | 32 | import java.awt.BorderLayout; 33 | import java.awt.Dimension; 34 | 35 | import javax.swing.JPanel; 36 | import javax.swing.ListSelectionModel; 37 | import javax.swing.event.TableModelListener; 38 | import javax.swing.table.TableColumn; 39 | import javax.swing.table.TableModel; 40 | 41 | import ghidra.app.services.GoToService; 42 | import ghidra.program.model.symbol.Reference; 43 | import ghidra.util.table.GhidraTable; 44 | import ghidra.util.table.GhidraThreadedTablePanel; 45 | 46 | /** 47 | * 48 | * 49 | */ 50 | class ReferencePanel extends JPanel { 51 | 52 | private ReferenceProvider referenceProvider; 53 | private GhidraTable refTable; 54 | private TableModelListener listener; 55 | private GhidraThreadedTablePanel threadedTablePanel; 56 | 57 | ReferencePanel(ReferenceProvider provider, SymbolReferenceModel model, SymbolRenderer renderer, 58 | GoToService gotoService) { 59 | 60 | super(new BorderLayout()); 61 | 62 | referenceProvider = provider; 63 | 64 | threadedTablePanel = new GhidraThreadedTablePanel<>(model); 65 | 66 | refTable = threadedTablePanel.getTable(); 67 | refTable.setAutoLookupColumn(SymbolReferenceModel.LABEL_COL); 68 | refTable.setName("ReferenceTable");//used by JUnit... 69 | refTable.setPreferredScrollableViewportSize(new Dimension(250, 200)); 70 | refTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 71 | refTable.installNavigation(gotoService, gotoService.getDefaultNavigatable()); 72 | 73 | this.listener = e -> referenceProvider.updateTitle(); 74 | refTable.getModel().addTableModelListener(listener); 75 | 76 | for (int i = 0; i < refTable.getColumnCount(); i++) { 77 | TableColumn column = refTable.getColumnModel().getColumn(i); 78 | if (column.getModelIndex() == SymbolReferenceModel.LABEL_COL) { 79 | column.setCellRenderer(renderer); 80 | } 81 | } 82 | 83 | add(threadedTablePanel, BorderLayout.CENTER); 84 | } 85 | 86 | GhidraTable getTable() { 87 | return refTable; 88 | } 89 | 90 | void dispose() { 91 | TableModel model = refTable.getModel(); 92 | model.removeTableModelListener(listener); 93 | threadedTablePanel.dispose(); 94 | refTable.dispose(); 95 | referenceProvider = null; 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /codecut-gui/src/main/java/codecutguiv2/RowPanel.java: -------------------------------------------------------------------------------- 1 | /* ### 2 | * © 2022 The Johns Hopkins University Applied Physics Laboratory LLC (JHU/APL). 3 | * All Rights Reserved. 4 | * 5 | * This material may be only be used, modified, or reproduced by or for the U.S. 6 | * Government pursuant to the license rights granted under the clauses at 7 | * DFARS 252.227-7013/7014 or FAR 52.227-14. For any other permission, please 8 | * contact the Office of Technology Transfer at JHU/APL. 9 | * 10 | * NO WARRANTY, NO LIABILITY. THIS MATERIAL IS PROVIDED “AS IS.” JHU/APL MAKES 11 | * NO REPRESENTATION OR WARRANTY WITH RESPECT TO THE PERFORMANCE OF THE MATERIALS, 12 | * INCLUDING THEIR SAFETY, EFFECTIVENESS, OR COMMERCIAL VIABILITY, AND DISCLAIMS 13 | * ALL WARRANTIES IN THE MATERIAL, WHETHER EXPRESS OR IMPLIED, INCLUDING 14 | * (BUT NOT LIMITED TO) ANY AND ALL IMPLIED WARRANTIES OF PERFORMANCE, 15 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF 16 | * INTELLECTUAL PROPERTY OR OTHER THIRD PARTY RIGHTS. ANY USER OF THE MATERIAL 17 | * ASSUMES THE ENTIRE RISK AND LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL 18 | * JHU/APL BE LIABLE TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT, 19 | * CONSEQUENTIAL, SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR INABILITY TO 20 | * USE, THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES FOR LOST PROFITS. 21 | * 22 | * HAVE A NICE DAY. 23 | */ 24 | 25 | /* This material is based upon work supported by the Defense Advanced Research 26 | * Projects Agency (DARPA) and Naval Information Warfare Center Pacific (NIWC Pacific) 27 | * under Contract Number N66001-20-C-4024. 28 | */ 29 | 30 | package codecutguiv2; 31 | 32 | import java.awt.LayoutManager; 33 | 34 | import javax.swing.JPanel; 35 | 36 | import ghidra.program.model.symbol.Namespace; 37 | 38 | public class RowPanel extends JPanel { 39 | 40 | private Namespace namespace; 41 | 42 | RowPanel(LayoutManager layout, Namespace ns) { 43 | super(layout); 44 | this.namespace = ns; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /codecut-gui/src/main/java/codecutguiv2/SharedListSelectionListener.java: -------------------------------------------------------------------------------- 1 | /* ### 2 | * © 2022 The Johns Hopkins University Applied Physics Laboratory LLC (JHU/APL). 3 | * All Rights Reserved. 4 | * 5 | * This material may be only be used, modified, or reproduced by or for the U.S. 6 | * Government pursuant to the license rights granted under the clauses at 7 | * DFARS 252.227-7013/7014 or FAR 52.227-14. For any other permission, please 8 | * contact the Office of Technology Transfer at JHU/APL. 9 | * 10 | * NO WARRANTY, NO LIABILITY. THIS MATERIAL IS PROVIDED “AS IS.” JHU/APL MAKES 11 | * NO REPRESENTATION OR WARRANTY WITH RESPECT TO THE PERFORMANCE OF THE MATERIALS, 12 | * INCLUDING THEIR SAFETY, EFFECTIVENESS, OR COMMERCIAL VIABILITY, AND DISCLAIMS 13 | * ALL WARRANTIES IN THE MATERIAL, WHETHER EXPRESS OR IMPLIED, INCLUDING 14 | * (BUT NOT LIMITED TO) ANY AND ALL IMPLIED WARRANTIES OF PERFORMANCE, 15 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF 16 | * INTELLECTUAL PROPERTY OR OTHER THIRD PARTY RIGHTS. ANY USER OF THE MATERIAL 17 | * ASSUMES THE ENTIRE RISK AND LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL 18 | * JHU/APL BE LIABLE TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT, 19 | * CONSEQUENTIAL, SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR INABILITY TO 20 | * USE, THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES FOR LOST PROFITS. 21 | * 22 | * HAVE A NICE DAY. 23 | */ 24 | 25 | /* This material is based upon work supported by the Defense Advanced Research 26 | * Projects Agency (DARPA) and Naval Information Warfare Center Pacific (NIWC Pacific) 27 | * under Contract Number N66001-20-C-4024. 28 | */ 29 | 30 | package codecutguiv2; 31 | 32 | import javax.swing.event.ListSelectionEvent; 33 | import javax.swing.event.ListSelectionListener; 34 | 35 | import ghidra.program.model.symbol.Namespace; 36 | 37 | public class SharedListSelectionListener implements ListSelectionListener { 38 | 39 | private Namespace namespace; 40 | private SymbolProvider provider; 41 | 42 | SharedListSelectionListener(Namespace namespace, SymbolProvider provider) { 43 | this.namespace = namespace; 44 | this.provider = provider; 45 | } 46 | 47 | public void valueChanged(ListSelectionEvent e) { 48 | //ListSelectionModel lsm = (ListSelectionModel)e.getSource(); 49 | provider.clearOtherSelections(this.namespace); 50 | 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /codecut-gui/src/main/java/codecutguiv2/SymbolEditor.java: -------------------------------------------------------------------------------- 1 | /* ### 2 | * © 2022 The Johns Hopkins University Applied Physics Laboratory LLC (JHU/APL). 3 | * All Rights Reserved. 4 | * 5 | * This material may be only be used, modified, or reproduced by or for the U.S. 6 | * Government pursuant to the license rights granted under the clauses at 7 | * DFARS 252.227-7013/7014 or FAR 52.227-14. For any other permission, please 8 | * contact the Office of Technology Transfer at JHU/APL. 9 | * 10 | * NO WARRANTY, NO LIABILITY. THIS MATERIAL IS PROVIDED “AS IS.” JHU/APL MAKES 11 | * NO REPRESENTATION OR WARRANTY WITH RESPECT TO THE PERFORMANCE OF THE MATERIALS, 12 | * INCLUDING THEIR SAFETY, EFFECTIVENESS, OR COMMERCIAL VIABILITY, AND DISCLAIMS 13 | * ALL WARRANTIES IN THE MATERIAL, WHETHER EXPRESS OR IMPLIED, INCLUDING 14 | * (BUT NOT LIMITED TO) ANY AND ALL IMPLIED WARRANTIES OF PERFORMANCE, 15 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF 16 | * INTELLECTUAL PROPERTY OR OTHER THIRD PARTY RIGHTS. ANY USER OF THE MATERIAL 17 | * ASSUMES THE ENTIRE RISK AND LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL 18 | * JHU/APL BE LIABLE TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT, 19 | * CONSEQUENTIAL, SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR INABILITY TO 20 | * USE, THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES FOR LOST PROFITS. 21 | * 22 | * HAVE A NICE DAY. 23 | */ 24 | 25 | /* This material is based upon work supported by the Defense Advanced Research 26 | * Projects Agency (DARPA) and Naval Information Warfare Center Pacific (NIWC Pacific) 27 | * under Contract Number N66001-20-C-4024. 28 | */ 29 | 30 | package codecutguiv2; 31 | 32 | 33 | import java.awt.Component; 34 | 35 | import javax.swing.*; 36 | 37 | import ghidra.program.model.symbol.Symbol; 38 | 39 | class SymbolEditor extends DefaultCellEditor { 40 | 41 | private JTextField symbolField = null; 42 | 43 | SymbolEditor() { 44 | super(new JTextField()); 45 | symbolField = (JTextField) super.getComponent(); 46 | symbolField.setBorder(BorderFactory.createEmptyBorder()); 47 | } 48 | 49 | @Override 50 | public Object getCellEditorValue() { 51 | return symbolField.getText().trim(); 52 | } 53 | 54 | @Override 55 | public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, 56 | int row, int column) { 57 | 58 | Symbol symbol = (Symbol) value; 59 | if (symbol != null) { 60 | symbolField.setText(symbol.getName()); 61 | } 62 | else { 63 | symbolField.setText(""); 64 | } 65 | return symbolField; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /codecut-gui/src/main/java/codecutguiv2/SymbolFilter.java: -------------------------------------------------------------------------------- 1 | /* ### 2 | * © 2022 The Johns Hopkins University Applied Physics Laboratory LLC (JHU/APL). 3 | * All Rights Reserved. 4 | * 5 | * This material may be only be used, modified, or reproduced by or for the U.S. 6 | * Government pursuant to the license rights granted under the clauses at 7 | * DFARS 252.227-7013/7014 or FAR 52.227-14. For any other permission, please 8 | * contact the Office of Technology Transfer at JHU/APL. 9 | * 10 | * NO WARRANTY, NO LIABILITY. THIS MATERIAL IS PROVIDED “AS IS.” JHU/APL MAKES 11 | * NO REPRESENTATION OR WARRANTY WITH RESPECT TO THE PERFORMANCE OF THE MATERIALS, 12 | * INCLUDING THEIR SAFETY, EFFECTIVENESS, OR COMMERCIAL VIABILITY, AND DISCLAIMS 13 | * ALL WARRANTIES IN THE MATERIAL, WHETHER EXPRESS OR IMPLIED, INCLUDING 14 | * (BUT NOT LIMITED TO) ANY AND ALL IMPLIED WARRANTIES OF PERFORMANCE, 15 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF 16 | * INTELLECTUAL PROPERTY OR OTHER THIRD PARTY RIGHTS. ANY USER OF THE MATERIAL 17 | * ASSUMES THE ENTIRE RISK AND LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL 18 | * JHU/APL BE LIABLE TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT, 19 | * CONSEQUENTIAL, SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR INABILITY TO 20 | * USE, THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES FOR LOST PROFITS. 21 | * 22 | * HAVE A NICE DAY. 23 | */ 24 | 25 | /* This material is based upon work supported by the Defense Advanced Research 26 | * Projects Agency (DARPA) and Naval Information Warfare Center Pacific (NIWC Pacific) 27 | * under Contract Number N66001-20-C-4024. 28 | */ 29 | 30 | package codecutguiv2; 31 | 32 | import ghidra.program.model.listing.Program; 33 | import ghidra.program.model.symbol.Symbol; 34 | 35 | public interface SymbolFilter { 36 | 37 | public boolean accepts(Symbol s, Program p); 38 | 39 | public boolean acceptsOnlyCodeSymbols(); 40 | 41 | public boolean acceptsDefaultLabelSymbols(); 42 | 43 | public boolean acceptsAll(); 44 | 45 | } 46 | -------------------------------------------------------------------------------- /codecut-gui/src/main/java/codecutguiv2/SymbolRowObjectToAddressTableRowMapper.java: -------------------------------------------------------------------------------- 1 | /* ### 2 | * © 2022 The Johns Hopkins University Applied Physics Laboratory LLC (JHU/APL). 3 | * All Rights Reserved. 4 | * 5 | * This material may be only be used, modified, or reproduced by or for the U.S. 6 | * Government pursuant to the license rights granted under the clauses at 7 | * DFARS 252.227-7013/7014 or FAR 52.227-14. For any other permission, please 8 | * contact the Office of Technology Transfer at JHU/APL. 9 | * 10 | * NO WARRANTY, NO LIABILITY. THIS MATERIAL IS PROVIDED “AS IS.” JHU/APL MAKES 11 | * NO REPRESENTATION OR WARRANTY WITH RESPECT TO THE PERFORMANCE OF THE MATERIALS, 12 | * INCLUDING THEIR SAFETY, EFFECTIVENESS, OR COMMERCIAL VIABILITY, AND DISCLAIMS 13 | * ALL WARRANTIES IN THE MATERIAL, WHETHER EXPRESS OR IMPLIED, INCLUDING 14 | * (BUT NOT LIMITED TO) ANY AND ALL IMPLIED WARRANTIES OF PERFORMANCE, 15 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF 16 | * INTELLECTUAL PROPERTY OR OTHER THIRD PARTY RIGHTS. ANY USER OF THE MATERIAL 17 | * ASSUMES THE ENTIRE RISK AND LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL 18 | * JHU/APL BE LIABLE TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT, 19 | * CONSEQUENTIAL, SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR INABILITY TO 20 | * USE, THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES FOR LOST PROFITS. 21 | * 22 | * HAVE A NICE DAY. 23 | */ 24 | 25 | /* This material is based upon work supported by the Defense Advanced Research 26 | * Projects Agency (DARPA) and Naval Information Warfare Center Pacific (NIWC Pacific) 27 | * under Contract Number N66001-20-C-4024. 28 | */ 29 | 30 | package codecutguiv2; 31 | 32 | import ghidra.framework.plugintool.ServiceProvider; 33 | import ghidra.program.model.address.Address; 34 | import ghidra.program.model.listing.Program; 35 | import ghidra.program.model.symbol.Symbol; 36 | import ghidra.util.table.ProgramLocationTableRowMapper; 37 | 38 | public class SymbolRowObjectToAddressTableRowMapper 39 | extends ProgramLocationTableRowMapper { 40 | 41 | @Override 42 | public Address map(Symbol rowObject, Program data, ServiceProvider serviceProvider) { 43 | if (rowObject == null) { 44 | return null; 45 | } 46 | return rowObject.getAddress(); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /codecut-gui/src/main/java/codecutguiv2/SymbolRowObjectToProgramLocationTableRowMapper.java: -------------------------------------------------------------------------------- 1 | /* ### 2 | * © 2022 The Johns Hopkins University Applied Physics Laboratory LLC (JHU/APL). 3 | * All Rights Reserved. 4 | * 5 | * This material may be only be used, modified, or reproduced by or for the U.S. 6 | * Government pursuant to the license rights granted under the clauses at 7 | * DFARS 252.227-7013/7014 or FAR 52.227-14. For any other permission, please 8 | * contact the Office of Technology Transfer at JHU/APL. 9 | * 10 | * NO WARRANTY, NO LIABILITY. THIS MATERIAL IS PROVIDED “AS IS.” JHU/APL MAKES 11 | * NO REPRESENTATION OR WARRANTY WITH RESPECT TO THE PERFORMANCE OF THE MATERIALS, 12 | * INCLUDING THEIR SAFETY, EFFECTIVENESS, OR COMMERCIAL VIABILITY, AND DISCLAIMS 13 | * ALL WARRANTIES IN THE MATERIAL, WHETHER EXPRESS OR IMPLIED, INCLUDING 14 | * (BUT NOT LIMITED TO) ANY AND ALL IMPLIED WARRANTIES OF PERFORMANCE, 15 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF 16 | * INTELLECTUAL PROPERTY OR OTHER THIRD PARTY RIGHTS. ANY USER OF THE MATERIAL 17 | * ASSUMES THE ENTIRE RISK AND LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL 18 | * JHU/APL BE LIABLE TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT, 19 | * CONSEQUENTIAL, SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR INABILITY TO 20 | * USE, THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES FOR LOST PROFITS. 21 | * 22 | * HAVE A NICE DAY. 23 | */ 24 | 25 | /* This material is based upon work supported by the Defense Advanced Research 26 | * Projects Agency (DARPA) and Naval Information Warfare Center Pacific (NIWC Pacific) 27 | * under Contract Number N66001-20-C-4024. 28 | */ 29 | 30 | package codecutguiv2; 31 | 32 | import ghidra.framework.plugintool.ServiceProvider; 33 | import ghidra.program.model.listing.Program; 34 | import ghidra.program.model.symbol.Symbol; 35 | import ghidra.program.util.ProgramLocation; 36 | import ghidra.util.table.ProgramLocationTableRowMapper; 37 | 38 | public class SymbolRowObjectToProgramLocationTableRowMapper 39 | extends ProgramLocationTableRowMapper { 40 | 41 | @Override 42 | public ProgramLocation map(Symbol rowObject, Program data, ServiceProvider serviceProvider) { 43 | return rowObject.getProgramLocation(); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /codecut-gui/src/main/java/graphcut/EmptyGraphCutData.java: -------------------------------------------------------------------------------- 1 | /* ### 2 | * © 2021 The Johns Hopkins University Applied Physics Laboratory LLC (JHU/APL). 3 | * All Rights Reserved. 4 | * 5 | * This material may be only be used, modified, or reproduced by or for the U.S. 6 | * Government pursuant to the license rights granted under the clauses at 7 | * DFARS 252.227-7013/7014 or FAR 52.227-14. For any other permission, please 8 | * contact the Office of Technology Transfer at JHU/APL. 9 | * 10 | * NO WARRANTY, NO LIABILITY. THIS MATERIAL IS PROVIDED “AS IS.” JHU/APL MAKES 11 | * NO REPRESENTATION OR WARRANTY WITH RESPECT TO THE PERFORMANCE OF THE MATERIALS, 12 | * INCLUDING THEIR SAFETY, EFFECTIVENESS, OR COMMERCIAL VIABILITY, AND DISCLAIMS 13 | * ALL WARRANTIES IN THE MATERIAL, WHETHER EXPRESS OR IMPLIED, INCLUDING 14 | * (BUT NOT LIMITED TO) ANY AND ALL IMPLIED WARRANTIES OF PERFORMANCE, 15 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF 16 | * INTELLECTUAL PROPERTY OR OTHER THIRD PARTY RIGHTS. ANY USER OF THE MATERIAL 17 | * ASSUMES THE ENTIRE RISK AND LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL 18 | * JHU/APL BE LIABLE TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT, 19 | * CONSEQUENTIAL, SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR INABILITY TO 20 | * USE, THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES FOR LOST PROFITS. 21 | * 22 | * HAVE A NICE DAY. 23 | */ 24 | 25 | /* This material is based upon work supported by the Defense Advanced Research 26 | * Projects Agency (DARPA) and Naval Information Warfare Center Pacific (NIWC Pacific) 27 | * under Contract Number N66001-20-C-4024. 28 | */ 29 | 30 | /* 31 | * Borrows from Ghidra file /Features Graph FunctionCalls/src/main/java/functioncalls/plugin/EmptyFcgData.java 32 | */ 33 | 34 | package graphcut; 35 | 36 | import ghidra.graph.viewer.GraphPerspectiveInfo; 37 | import ghidra.program.model.symbol.Namespace; 38 | 39 | /** 40 | * empty data used to avoid null checks 41 | */ 42 | public class EmptyGraphCutData implements GraphCutData { 43 | 44 | @Override 45 | public Namespace getNamespace() { 46 | throw new UnsupportedOperationException("Empty data has no namespace"); 47 | } 48 | 49 | @Override 50 | public boolean isNamespace(Namespace ns) { 51 | return false; 52 | } 53 | 54 | @Override 55 | public GraphCutGraph getGraph() { 56 | throw new UnsupportedOperationException("Empty data has no graph"); 57 | } 58 | 59 | @Override 60 | public NamespaceEdgeCache getNamespaceEdgeCache() { 61 | throw new UnsupportedOperationException("Empty data has no namespace edge cache"); 62 | } 63 | 64 | @Override 65 | public boolean hasResults() { 66 | return false; 67 | } 68 | 69 | @Override 70 | public void dispose() { 71 | //nothing 72 | } 73 | 74 | @Override 75 | public boolean isInitialized() { 76 | return false; 77 | } 78 | 79 | @Override 80 | public GraphPerspectiveInfo getGraphPerspective(){ 81 | throw new UnsupportedOperationException("Empty data does not need view information"); 82 | } 83 | 84 | @Override 85 | public void setGraphPerspective(GraphPerspectiveInfo info) { 86 | throw new UnsupportedOperationException("Empty data does not need view information"); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /codecut-gui/src/main/java/graphcut/GraphCutData.java: -------------------------------------------------------------------------------- 1 | /* ### 2 | * © 2021 The Johns Hopkins University Applied Physics Laboratory LLC (JHU/APL). 3 | * All Rights Reserved. 4 | * 5 | * This material may be only be used, modified, or reproduced by or for the U.S. 6 | * Government pursuant to the license rights granted under the clauses at 7 | * DFARS 252.227-7013/7014 or FAR 52.227-14. For any other permission, please 8 | * contact the Office of Technology Transfer at JHU/APL. 9 | * 10 | * NO WARRANTY, NO LIABILITY. THIS MATERIAL IS PROVIDED “AS IS.” JHU/APL MAKES 11 | * NO REPRESENTATION OR WARRANTY WITH RESPECT TO THE PERFORMANCE OF THE MATERIALS, 12 | * INCLUDING THEIR SAFETY, EFFECTIVENESS, OR COMMERCIAL VIABILITY, AND DISCLAIMS 13 | * ALL WARRANTIES IN THE MATERIAL, WHETHER EXPRESS OR IMPLIED, INCLUDING 14 | * (BUT NOT LIMITED TO) ANY AND ALL IMPLIED WARRANTIES OF PERFORMANCE, 15 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF 16 | * INTELLECTUAL PROPERTY OR OTHER THIRD PARTY RIGHTS. ANY USER OF THE MATERIAL 17 | * ASSUMES THE ENTIRE RISK AND LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL 18 | * JHU/APL BE LIABLE TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT, 19 | * CONSEQUENTIAL, SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR INABILITY TO 20 | * USE, THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES FOR LOST PROFITS. 21 | * 22 | * HAVE A NICE DAY. 23 | */ 24 | 25 | /* This material is based upon work supported by the Defense Advanced Research 26 | * Projects Agency (DARPA) and Naval Information Warfare Center Pacific (NIWC Pacific) 27 | * under Contract Number N66001-20-C-4024. 28 | */ 29 | 30 | /* 31 | * Borrows from Ghidra file /Features Graph FunctionCalls/src/main/java/functioncalls/plugin/FcgData.java 32 | */ 33 | 34 | 35 | package graphcut; 36 | 37 | import ghidra.graph.viewer.GraphPerspectiveInfo; 38 | import ghidra.program.model.symbol.Namespace; 39 | 40 | /** 41 | * Allows us to retrieve and work on the graph. Makes caching data simple 42 | */ 43 | public interface GraphCutData { 44 | 45 | /** 46 | * The namespace of this data 47 | * @return the namespace 48 | */ 49 | Namespace getNamespace(); 50 | 51 | /** 52 | * The graph of this data 53 | * @return the graph 54 | */ 55 | GraphCutGraph getGraph(); 56 | 57 | /** 58 | * Returns the cache of edges. Not in the graph but used to track existing edges that are not yet in the graph. 59 | * @return 60 | */ 61 | NamespaceEdgeCache getNamespaceEdgeCache(); 62 | 63 | /** 64 | * True if this data has a valid namespace 65 | * @return true if this data has a valid namespace 66 | */ 67 | boolean hasResults(); 68 | 69 | /** 70 | * False if the graph in this data has not yet been loaded 71 | */ 72 | boolean isInitialized(); 73 | 74 | /** 75 | * Dispose the contents of this data 76 | */ 77 | void dispose(); 78 | 79 | /** 80 | * Returns the view's graph perspective. this is used by the view to restore itself. 81 | * @return the view's graph perspective 82 | */ 83 | GraphPerspectiveInfo getGraphPerspective(); 84 | 85 | /** 86 | * Set the view information for this graph data 87 | * @param info the perspective to set 88 | */ 89 | void setGraphPerspective(GraphPerspectiveInfo info); 90 | 91 | /** 92 | * Returns true if this data's namespace is equal to the given one 93 | * @param ns the namespace to test 94 | * @return true if this data's namespace is equal to the given one 95 | */ 96 | boolean isNamespace(Namespace ns); 97 | } 98 | -------------------------------------------------------------------------------- /codecut-gui/src/main/java/graphcut/GraphCutDataFactory.java: -------------------------------------------------------------------------------- 1 | /* ### 2 | * © 2021 The Johns Hopkins University Applied Physics Laboratory LLC (JHU/APL). 3 | * All Rights Reserved. 4 | * 5 | * This material may be only be used, modified, or reproduced by or for the U.S. 6 | * Government pursuant to the license rights granted under the clauses at 7 | * DFARS 252.227-7013/7014 or FAR 52.227-14. For any other permission, please 8 | * contact the Office of Technology Transfer at JHU/APL. 9 | * 10 | * NO WARRANTY, NO LIABILITY. THIS MATERIAL IS PROVIDED “AS IS.” JHU/APL MAKES 11 | * NO REPRESENTATION OR WARRANTY WITH RESPECT TO THE PERFORMANCE OF THE MATERIALS, 12 | * INCLUDING THEIR SAFETY, EFFECTIVENESS, OR COMMERCIAL VIABILITY, AND DISCLAIMS 13 | * ALL WARRANTIES IN THE MATERIAL, WHETHER EXPRESS OR IMPLIED, INCLUDING 14 | * (BUT NOT LIMITED TO) ANY AND ALL IMPLIED WARRANTIES OF PERFORMANCE, 15 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF 16 | * INTELLECTUAL PROPERTY OR OTHER THIRD PARTY RIGHTS. ANY USER OF THE MATERIAL 17 | * ASSUMES THE ENTIRE RISK AND LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL 18 | * JHU/APL BE LIABLE TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT, 19 | * CONSEQUENTIAL, SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR INABILITY TO 20 | * USE, THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES FOR LOST PROFITS. 21 | * 22 | * HAVE A NICE DAY. 23 | */ 24 | 25 | /* This material is based upon work supported by the Defense Advanced Research 26 | * Projects Agency (DARPA) and Naval Information Warfare Center Pacific (NIWC Pacific) 27 | * under Contract Number N66001-20-C-4024. 28 | */ 29 | 30 | /* 31 | * Borrows from /Features Graph FunctionCalls/src/main/java/functioncalls/plugin/FcgDataFactory.java 32 | */ 33 | 34 | 35 | package graphcut; 36 | 37 | import com.google.common.cache.*; 38 | 39 | import ghidra.program.model.symbol.Namespace; 40 | 41 | /** 42 | * A factory that will create GraphCutGraph data objects for a given namespace 43 | */ 44 | public class GraphCutDataFactory { 45 | 46 | private LoadingCache cache; 47 | 48 | GraphCutDataFactory(RemovalListener listener){ 49 | 50 | cache = CacheBuilder 51 | .newBuilder() 52 | .maximumSize(5) 53 | .removalListener(listener) 54 | .build(new CacheLoader () { 55 | @Override 56 | public GraphCutData load(Namespace ns) throws Exception { 57 | return new ValidGraphCutData(ns, new GraphCutGraph()); 58 | } 59 | }); 60 | } 61 | 62 | GraphCutData create(Namespace ns) { 63 | if (ns == null) { 64 | return new EmptyGraphCutData(); 65 | } 66 | 67 | GraphCutData data = cache.getUnchecked(ns); 68 | return data; 69 | } 70 | 71 | void remove(Namespace ns) { 72 | cache.invalidate(ns); 73 | } 74 | 75 | void dispose() { 76 | cache.invalidateAll(); 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /codecut-gui/src/main/java/graphcut/GraphCutEdge.java: -------------------------------------------------------------------------------- 1 | /* ### 2 | * © 2021 The Johns Hopkins University Applied Physics Laboratory LLC (JHU/APL). 3 | * All Rights Reserved. 4 | * 5 | * This material may be only be used, modified, or reproduced by or for the U.S. 6 | * Government pursuant to the license rights granted under the clauses at 7 | * DFARS 252.227-7013/7014 or FAR 52.227-14. For any other permission, please 8 | * contact the Office of Technology Transfer at JHU/APL. 9 | * 10 | * NO WARRANTY, NO LIABILITY. THIS MATERIAL IS PROVIDED “AS IS.” JHU/APL MAKES 11 | * NO REPRESENTATION OR WARRANTY WITH RESPECT TO THE PERFORMANCE OF THE MATERIALS, 12 | * INCLUDING THEIR SAFETY, EFFECTIVENESS, OR COMMERCIAL VIABILITY, AND DISCLAIMS 13 | * ALL WARRANTIES IN THE MATERIAL, WHETHER EXPRESS OR IMPLIED, INCLUDING 14 | * (BUT NOT LIMITED TO) ANY AND ALL IMPLIED WARRANTIES OF PERFORMANCE, 15 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF 16 | * INTELLECTUAL PROPERTY OR OTHER THIRD PARTY RIGHTS. ANY USER OF THE MATERIAL 17 | * ASSUMES THE ENTIRE RISK AND LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL 18 | * JHU/APL BE LIABLE TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT, 19 | * CONSEQUENTIAL, SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR INABILITY TO 20 | * USE, THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES FOR LOST PROFITS. 21 | * 22 | * HAVE A NICE DAY. 23 | */ 24 | 25 | /* This material is based upon work supported by the Defense Advanced Research 26 | * Projects Agency (DARPA) and Naval Information Warfare Center Pacific (NIWC Pacific) 27 | * under Contract Number N66001-20-C-4024. 28 | */ 29 | 30 | package graphcut; 31 | 32 | import ghidra.graph.viewer.edge.AbstractVisualEdge; 33 | import graphcut.GraphCutVertex; 34 | /** 35 | * A GraphCut Edge 36 | */ 37 | 38 | public class GraphCutEdge extends AbstractVisualEdge { 39 | 40 | public GraphCutEdge(GraphCutVertex start, GraphCutVertex end) { 41 | super(start, end); 42 | } 43 | 44 | @SuppressWarnings("unchecked") 45 | 46 | @Override 47 | public GraphCutEdge cloneEdge(GraphCutVertex start, GraphCutVertex end) { 48 | return new GraphCutEdge(start, end); 49 | } 50 | 51 | /** 52 | * Returns true if an edge is direct from a lower level. 53 | * @return true if this edge is a direct edge 54 | */ 55 | public boolean isDirectEdge() { 56 | GraphCutLevel startLevel = getStart().getLevel(); 57 | GraphCutLevel endLevel = getEnd().getLevel(); 58 | if(startLevel.isSource() || endLevel.isSource()) { 59 | return true; 60 | } 61 | 62 | GraphCutLevel parent = startLevel.parent(); 63 | if (parent.equals(endLevel)) { 64 | return true; 65 | } 66 | 67 | GraphCutLevel child = startLevel.child(); 68 | return child.equals(endLevel); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /codecut-gui/src/main/java/graphcut/GraphCutEdgePaintTransformer.java: -------------------------------------------------------------------------------- 1 | /* ### 2 | * © 2021 The Johns Hopkins University Applied Physics Laboratory LLC (JHU/APL). 3 | * All Rights Reserved. 4 | * 5 | * This material may be only be used, modified, or reproduced by or for the U.S. 6 | * Government pursuant to the license rights granted under the clauses at 7 | * DFARS 252.227-7013/7014 or FAR 52.227-14. For any other permission, please 8 | * contact the Office of Technology Transfer at JHU/APL. 9 | * 10 | * NO WARRANTY, NO LIABILITY. THIS MATERIAL IS PROVIDED “AS IS.” JHU/APL MAKES 11 | * NO REPRESENTATION OR WARRANTY WITH RESPECT TO THE PERFORMANCE OF THE MATERIALS, 12 | * INCLUDING THEIR SAFETY, EFFECTIVENESS, OR COMMERCIAL VIABILITY, AND DISCLAIMS 13 | * ALL WARRANTIES IN THE MATERIAL, WHETHER EXPRESS OR IMPLIED, INCLUDING 14 | * (BUT NOT LIMITED TO) ANY AND ALL IMPLIED WARRANTIES OF PERFORMANCE, 15 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF 16 | * INTELLECTUAL PROPERTY OR OTHER THIRD PARTY RIGHTS. ANY USER OF THE MATERIAL 17 | * ASSUMES THE ENTIRE RISK AND LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL 18 | * JHU/APL BE LIABLE TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT, 19 | * CONSEQUENTIAL, SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR INABILITY TO 20 | * USE, THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES FOR LOST PROFITS. 21 | * 22 | * HAVE A NICE DAY. 23 | */ 24 | 25 | /* This material is based upon work supported by the Defense Advanced Research 26 | * Projects Agency (DARPA) and Naval Information Warfare Center Pacific (NIWC Pacific) 27 | * under Contract Number N66001-20-C-4024. 28 | */ 29 | 30 | /* 31 | * Heavily borrows from Ghidra file /Features Graph FunctionCalls/src/main/java/functioncalls/graph/renderer/FcgEdgePaintTransformer.java 32 | */ 33 | 34 | 35 | package graphcut; 36 | 37 | import com.google.common.base.Function; 38 | import java.awt.Color; 39 | import ghidra.util.ColorUtils; 40 | 41 | public class GraphCutEdgePaintTransformer implements Function { 42 | private Color directColor; 43 | private Color indirectColor; 44 | 45 | private Color[] directColorWithAlpha = new Color[10]; 46 | 47 | public GraphCutEdgePaintTransformer(Color directColor, Color indirectColor) { 48 | this.directColor = directColor; 49 | this.indirectColor = indirectColor; 50 | 51 | directColorWithAlpha = alphatize(directColor); 52 | } 53 | 54 | private Color[] alphatize(Color c) { 55 | Color[] alphad = new Color[10]; 56 | alphad[0] = c; 57 | for (int i = 1; i < 10; i++) { 58 | double newAlpha = 255 - (i * 25.5); 59 | alphad[i] = ColorUtils.withAlpha(c, (int) newAlpha); 60 | } 61 | return alphad; 62 | } 63 | 64 | @Override 65 | public Color apply(GraphCutEdge e) { 66 | if (e.isDirectEdge()) { 67 | return getDirectEdgeColor(e); 68 | } 69 | 70 | return indirectColor; 71 | } 72 | 73 | private Color getDirectEdgeColor(GraphCutEdge e) { 74 | return directColor; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /codecut-gui/src/main/java/graphcut/GraphCutEmphasizeEdgesJob.java: -------------------------------------------------------------------------------- 1 | /* ### 2 | * © 2021 The Johns Hopkins University Applied Physics Laboratory LLC (JHU/APL). 3 | * All Rights Reserved. 4 | * 5 | * This material may be only be used, modified, or reproduced by or for the U.S. 6 | * Government pursuant to the license rights granted under the clauses at 7 | * DFARS 252.227-7013/7014 or FAR 52.227-14. For any other permission, please 8 | * contact the Office of Technology Transfer at JHU/APL. 9 | * 10 | * NO WARRANTY, NO LIABILITY. THIS MATERIAL IS PROVIDED “AS IS.” JHU/APL MAKES 11 | * NO REPRESENTATION OR WARRANTY WITH RESPECT TO THE PERFORMANCE OF THE MATERIALS, 12 | * INCLUDING THEIR SAFETY, EFFECTIVENESS, OR COMMERCIAL VIABILITY, AND DISCLAIMS 13 | * ALL WARRANTIES IN THE MATERIAL, WHETHER EXPRESS OR IMPLIED, INCLUDING 14 | * (BUT NOT LIMITED TO) ANY AND ALL IMPLIED WARRANTIES OF PERFORMANCE, 15 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF 16 | * INTELLECTUAL PROPERTY OR OTHER THIRD PARTY RIGHTS. ANY USER OF THE MATERIAL 17 | * ASSUMES THE ENTIRE RISK AND LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL 18 | * JHU/APL BE LIABLE TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT, 19 | * CONSEQUENTIAL, SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR INABILITY TO 20 | * USE, THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES FOR LOST PROFITS. 21 | * 22 | * HAVE A NICE DAY. 23 | */ 24 | 25 | /* This material is based upon work supported by the Defense Advanced Research 26 | * Projects Agency (DARPA) and Naval Information Warfare Center Pacific (NIWC Pacific) 27 | * under Contract Number N66001-20-C-4024. 28 | */ 29 | 30 | /* 31 | * Borrows from Ghidra file /Features Graph FunctionCalls/src/main/java/functioncalls/graph/job/FcgEmphasizeEdgesJob.java 32 | */ 33 | 34 | 35 | package graphcut; 36 | 37 | import java.util.Set; 38 | 39 | import ghidra.graph.job.AbstractGraphVisibilityTransitionJob; 40 | import ghidra.graph.viewer.GraphViewer; 41 | 42 | public class GraphCutEmphasizeEdgesJob extends AbstractGraphVisibilityTransitionJob { 43 | 44 | private Set edges; 45 | 46 | public GraphCutEmphasizeEdgesJob(GraphViewer viewer, Set edges) { 47 | super(viewer, true); 48 | this.edges = edges; 49 | } 50 | 51 | @Override 52 | protected void updateOpacity(double percentComplete) { 53 | 54 | double remaining = percentComplete; 55 | if(percentComplete > 0.5){ 56 | remaining = 1 - percentComplete; 57 | } 58 | 59 | double modified = remaining * 10; 60 | 61 | for (GraphCutEdge e : edges) { 62 | e.setEmphasis(modified); 63 | } 64 | 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /codecut-gui/src/main/java/graphcut/GraphCutExpansionListener.java: -------------------------------------------------------------------------------- 1 | /* ### 2 | * © 2021 The Johns Hopkins University Applied Physics Laboratory LLC (JHU/APL). 3 | * All Rights Reserved. 4 | * 5 | * This material may be only be used, modified, or reproduced by or for the U.S. 6 | * Government pursuant to the license rights granted under the clauses at 7 | * DFARS 252.227-7013/7014 or FAR 52.227-14. For any other permission, please 8 | * contact the Office of Technology Transfer at JHU/APL. 9 | * 10 | * NO WARRANTY, NO LIABILITY. THIS MATERIAL IS PROVIDED “AS IS.” JHU/APL MAKES 11 | * NO REPRESENTATION OR WARRANTY WITH RESPECT TO THE PERFORMANCE OF THE MATERIALS, 12 | * INCLUDING THEIR SAFETY, EFFECTIVENESS, OR COMMERCIAL VIABILITY, AND DISCLAIMS 13 | * ALL WARRANTIES IN THE MATERIAL, WHETHER EXPRESS OR IMPLIED, INCLUDING 14 | * (BUT NOT LIMITED TO) ANY AND ALL IMPLIED WARRANTIES OF PERFORMANCE, 15 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF 16 | * INTELLECTUAL PROPERTY OR OTHER THIRD PARTY RIGHTS. ANY USER OF THE MATERIAL 17 | * ASSUMES THE ENTIRE RISK AND LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL 18 | * JHU/APL BE LIABLE TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT, 19 | * CONSEQUENTIAL, SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR INABILITY TO 20 | * USE, THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES FOR LOST PROFITS. 21 | * 22 | * HAVE A NICE DAY. 23 | */ 24 | 25 | /* This material is based upon work supported by the Defense Advanced Research 26 | * Projects Agency (DARPA) and Naval Information Warfare Center Pacific (NIWC Pacific) 27 | * under Contract Number N66001-20-C-4024. 28 | */ 29 | 30 | 31 | package graphcut; 32 | 33 | 34 | public interface GraphCutExpansionListener { 35 | 36 | /** 37 | * Show or hide those vertices that are on incoming edges to v 38 | * 39 | * @param v the vertex 40 | */ 41 | public void toggleIncomingVertices(GraphCutVertex v); 42 | 43 | /** 44 | * Show or hide those vertices that are on outgoing edges to v 45 | * 46 | * @param v the vertex 47 | */ 48 | public void toggleOutgoingVertices(GraphCutVertex v); 49 | 50 | } 51 | -------------------------------------------------------------------------------- /codecut-gui/src/main/java/graphcut/GraphCutLayoutProvider.java: -------------------------------------------------------------------------------- 1 | /* ### 2 | * © 2021 The Johns Hopkins University Applied Physics Laboratory LLC (JHU/APL). 3 | * All Rights Reserved. 4 | * 5 | * This material may be only be used, modified, or reproduced by or for the U.S. 6 | * Government pursuant to the license rights granted under the clauses at 7 | * DFARS 252.227-7013/7014 or FAR 52.227-14. For any other permission, please 8 | * contact the Office of Technology Transfer at JHU/APL. 9 | * 10 | * NO WARRANTY, NO LIABILITY. THIS MATERIAL IS PROVIDED “AS IS.” JHU/APL MAKES 11 | * NO REPRESENTATION OR WARRANTY WITH RESPECT TO THE PERFORMANCE OF THE MATERIALS, 12 | * INCLUDING THEIR SAFETY, EFFECTIVENESS, OR COMMERCIAL VIABILITY, AND DISCLAIMS 13 | * ALL WARRANTIES IN THE MATERIAL, WHETHER EXPRESS OR IMPLIED, INCLUDING 14 | * (BUT NOT LIMITED TO) ANY AND ALL IMPLIED WARRANTIES OF PERFORMANCE, 15 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF 16 | * INTELLECTUAL PROPERTY OR OTHER THIRD PARTY RIGHTS. ANY USER OF THE MATERIAL 17 | * ASSUMES THE ENTIRE RISK AND LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL 18 | * JHU/APL BE LIABLE TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT, 19 | * CONSEQUENTIAL, SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR INABILITY TO 20 | * USE, THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES FOR LOST PROFITS. 21 | * 22 | * HAVE A NICE DAY. 23 | */ 24 | 25 | /* This material is based upon work supported by the Defense Advanced Research 26 | * Projects Agency (DARPA) and Naval Information Warfare Center Pacific (NIWC Pacific) 27 | * under Contract Number N66001-20-C-4024. 28 | */ 29 | 30 | /* 31 | * Borrows from Ghidra file /Features Graph FunctionCalls/src/main/java/functioncalls/graph/layout/BowTieLayoutProvider.java 32 | */ 33 | 34 | package graphcut; 35 | 36 | import javax.swing.Icon; 37 | 38 | import generic.theme.GIcon; 39 | import ghidra.graph.viewer.layout.AbstractLayoutProvider; 40 | import ghidra.graph.viewer.layout.VisualGraphLayout; 41 | import ghidra.util.exception.CancelledException; 42 | import ghidra.util.task.TaskMonitor; 43 | 44 | /** 45 | * A layout provider for GraphCut 46 | */ 47 | public class GraphCutLayoutProvider extends AbstractLayoutProvider { 48 | public static final String NAME = "GraphCut Layout"; 49 | private static final Icon DEFAULT_ICON = new GIcon("icon.plugin.fcg.layout.bow.tie"); 50 | 51 | @Override 52 | public VisualGraphLayout getLayout(GraphCutGraph graph, TaskMonitor taskMonitor) throws CancelledException{ 53 | 54 | GraphCutLayout layout = new GraphCutLayout(graph, NAME); 55 | initVertexLocations(graph, layout); 56 | return layout; 57 | } 58 | 59 | @Override 60 | public String getLayoutName() { 61 | return NAME; 62 | } 63 | 64 | @Override 65 | public Icon getActionIcon() { 66 | return DEFAULT_ICON; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /codecut-gui/src/main/java/graphcut/GraphCutTooltipProvider.java: -------------------------------------------------------------------------------- 1 | /* ### 2 | * © 2021 The Johns Hopkins University Applied Physics Laboratory LLC (JHU/APL). 3 | * All Rights Reserved. 4 | * 5 | * This material may be only be used, modified, or reproduced by or for the U.S. 6 | * Government pursuant to the license rights granted under the clauses at 7 | * DFARS 252.227-7013/7014 or FAR 52.227-14. For any other permission, please 8 | * contact the Office of Technology Transfer at JHU/APL. 9 | * 10 | * NO WARRANTY, NO LIABILITY. THIS MATERIAL IS PROVIDED “AS IS.” JHU/APL MAKES 11 | * NO REPRESENTATION OR WARRANTY WITH RESPECT TO THE PERFORMANCE OF THE MATERIALS, 12 | * INCLUDING THEIR SAFETY, EFFECTIVENESS, OR COMMERCIAL VIABILITY, AND DISCLAIMS 13 | * ALL WARRANTIES IN THE MATERIAL, WHETHER EXPRESS OR IMPLIED, INCLUDING 14 | * (BUT NOT LIMITED TO) ANY AND ALL IMPLIED WARRANTIES OF PERFORMANCE, 15 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF 16 | * INTELLECTUAL PROPERTY OR OTHER THIRD PARTY RIGHTS. ANY USER OF THE MATERIAL 17 | * ASSUMES THE ENTIRE RISK AND LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL 18 | * JHU/APL BE LIABLE TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT, 19 | * CONSEQUENTIAL, SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR INABILITY TO 20 | * USE, THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES FOR LOST PROFITS. 21 | * 22 | * HAVE A NICE DAY. 23 | */ 24 | 25 | /* This material is based upon work supported by the Defense Advanced Research 26 | * Projects Agency (DARPA) and Naval Information Warfare Center Pacific (NIWC Pacific) 27 | * under Contract Number N66001-20-C-4024. 28 | */ 29 | 30 | /* 31 | * Heavily Borrows from Ghidra file /Features Graph FunctionCalls/src/main/java/functioncalls/graph/renderer/FcgTooltipProvider.java 32 | */ 33 | 34 | 35 | package graphcut; 36 | 37 | import java.awt.Component; 38 | import java.awt.event.MouseEvent; 39 | 40 | import javax.swing.JComponent; 41 | import javax.swing.*; 42 | 43 | import ghidra.graph.viewer.event.mouse.VertexTooltipProvider; 44 | 45 | public class GraphCutTooltipProvider implements VertexTooltipProvider { 46 | 47 | @Override 48 | public JComponent getTooltip(GraphCutVertex v) { 49 | JToolTip tip = new JToolTip(); 50 | tip.setTipText(v.getName()); 51 | return tip; 52 | } 53 | 54 | @Override 55 | public JComponent getTooltip(GraphCutVertex v, GraphCutEdge e) { 56 | return null; 57 | } 58 | 59 | @Override 60 | public String getTooltipText(GraphCutVertex v, MouseEvent e) { 61 | Component child = e.getComponent(); 62 | if(child instanceof JButton) { 63 | return ((JButton) child).getToolTipText(); 64 | } 65 | return v.getName(); 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /codecut-gui/src/main/java/graphcut/GraphCutVertexPaintTransformer.java: -------------------------------------------------------------------------------- 1 | /* ### 2 | * © 2021 The Johns Hopkins University Applied Physics Laboratory LLC (JHU/APL). 3 | * All Rights Reserved. 4 | * 5 | * This material may be only be used, modified, or reproduced by or for the U.S. 6 | * Government pursuant to the license rights granted under the clauses at 7 | * DFARS 252.227-7013/7014 or FAR 52.227-14. For any other permission, please 8 | * contact the Office of Technology Transfer at JHU/APL. 9 | * 10 | * NO WARRANTY, NO LIABILITY. THIS MATERIAL IS PROVIDED “AS IS.” JHU/APL MAKES 11 | * NO REPRESENTATION OR WARRANTY WITH RESPECT TO THE PERFORMANCE OF THE MATERIALS, 12 | * INCLUDING THEIR SAFETY, EFFECTIVENESS, OR COMMERCIAL VIABILITY, AND DISCLAIMS 13 | * ALL WARRANTIES IN THE MATERIAL, WHETHER EXPRESS OR IMPLIED, INCLUDING 14 | * (BUT NOT LIMITED TO) ANY AND ALL IMPLIED WARRANTIES OF PERFORMANCE, 15 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF 16 | * INTELLECTUAL PROPERTY OR OTHER THIRD PARTY RIGHTS. ANY USER OF THE MATERIAL 17 | * ASSUMES THE ENTIRE RISK AND LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL 18 | * JHU/APL BE LIABLE TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT, 19 | * CONSEQUENTIAL, SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR INABILITY TO 20 | * USE, THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES FOR LOST PROFITS. 21 | * 22 | * HAVE A NICE DAY. 23 | */ 24 | 25 | /* This material is based upon work supported by the Defense Advanced Research 26 | * Projects Agency (DARPA) and Naval Information Warfare Center Pacific (NIWC Pacific) 27 | * under Contract Number N66001-20-C-4024. 28 | */ 29 | 30 | /* 31 | * Heavily Borrows from Ghidra file /Features Graph FunctionCalls/src/main/java/functioncalls/graph/renderer/FcgVertexPaintTransformer.java 32 | */ 33 | 34 | 35 | package graphcut; 36 | 37 | import com.google.common.base.Function; 38 | import java.awt.Color; 39 | import java.awt.Paint; 40 | 41 | import ghidra.util.ColorUtils; 42 | /** 43 | * A class that takes a GraphCutVertex and determines which color to paint it with 44 | */ 45 | public class GraphCutVertexPaintTransformer implements Function { 46 | private Color color; 47 | 48 | public GraphCutVertexPaintTransformer(Color color) { 49 | this.color = color; 50 | } 51 | 52 | @Override 53 | public Paint apply(GraphCutVertex v) { 54 | return color; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /codecut-gui/src/main/java/graphcut/GraphCutView.java: -------------------------------------------------------------------------------- 1 | /* ### 2 | * © 2021 The Johns Hopkins University Applied Physics Laboratory LLC (JHU/APL). 3 | * All Rights Reserved. 4 | * 5 | * This material may be only be used, modified, or reproduced by or for the U.S. 6 | * Government pursuant to the license rights granted under the clauses at 7 | * DFARS 252.227-7013/7014 or FAR 52.227-14. For any other permission, please 8 | * contact the Office of Technology Transfer at JHU/APL. 9 | * 10 | * NO WARRANTY, NO LIABILITY. THIS MATERIAL IS PROVIDED “AS IS.” JHU/APL MAKES 11 | * NO REPRESENTATION OR WARRANTY WITH RESPECT TO THE PERFORMANCE OF THE MATERIALS, 12 | * INCLUDING THEIR SAFETY, EFFECTIVENESS, OR COMMERCIAL VIABILITY, AND DISCLAIMS 13 | * ALL WARRANTIES IN THE MATERIAL, WHETHER EXPRESS OR IMPLIED, INCLUDING 14 | * (BUT NOT LIMITED TO) ANY AND ALL IMPLIED WARRANTIES OF PERFORMANCE, 15 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF 16 | * INTELLECTUAL PROPERTY OR OTHER THIRD PARTY RIGHTS. ANY USER OF THE MATERIAL 17 | * ASSUMES THE ENTIRE RISK AND LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL 18 | * JHU/APL BE LIABLE TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT, 19 | * CONSEQUENTIAL, SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR INABILITY TO 20 | * USE, THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES FOR LOST PROFITS. 21 | * 22 | * HAVE A NICE DAY. 23 | */ 24 | 25 | /* This material is based upon work supported by the Defense Advanced Research 26 | * Projects Agency (DARPA) and Naval Information Warfare Center Pacific (NIWC Pacific) 27 | * under Contract Number N66001-20-C-4024. 28 | */ 29 | 30 | /* 31 | * Heavily Borrows from Ghidra file /Features Graph FunctionCalls/src/main/java/functioncalls/graph/view/FcgView.java 32 | */ 33 | 34 | 35 | package graphcut; 36 | 37 | import ghidra.graph.viewer.VisualGraphView; 38 | import ghidra.graph.viewer.options.VisualGraphOptions; 39 | 40 | public class GraphCutView extends VisualGraphView { 41 | private VisualGraphOptions options; 42 | public GraphCutView(VisualGraphOptions options) { 43 | this.options = options; 44 | } 45 | 46 | @Override 47 | protected void installGraphViewer() { 48 | 49 | GraphCutComponent component = createGraphComponent(); 50 | component.setGraphOptions(options); 51 | setGraphComponent(component); 52 | } 53 | 54 | private GraphCutComponent createGraphComponent() { 55 | GraphCutComponent component = new GraphCutComponent(getVisualGraph()); 56 | return component; 57 | } 58 | 59 | @Override 60 | public GraphCutComponent getGraphComponent() { 61 | return (GraphCutComponent) super.getGraphComponent(); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /codecut-gui/src/main/java/graphcut/NamespaceEdge.java: -------------------------------------------------------------------------------- 1 | /* ### 2 | * © 2021 The Johns Hopkins University Applied Physics Laboratory LLC (JHU/APL). 3 | * All Rights Reserved. 4 | * 5 | * This material may be only be used, modified, or reproduced by or for the U.S. 6 | * Government pursuant to the license rights granted under the clauses at 7 | * DFARS 252.227-7013/7014 or FAR 52.227-14. For any other permission, please 8 | * contact the Office of Technology Transfer at JHU/APL. 9 | * 10 | * NO WARRANTY, NO LIABILITY. THIS MATERIAL IS PROVIDED “AS IS.” JHU/APL MAKES 11 | * NO REPRESENTATION OR WARRANTY WITH RESPECT TO THE PERFORMANCE OF THE MATERIALS, 12 | * INCLUDING THEIR SAFETY, EFFECTIVENESS, OR COMMERCIAL VIABILITY, AND DISCLAIMS 13 | * ALL WARRANTIES IN THE MATERIAL, WHETHER EXPRESS OR IMPLIED, INCLUDING 14 | * (BUT NOT LIMITED TO) ANY AND ALL IMPLIED WARRANTIES OF PERFORMANCE, 15 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF 16 | * INTELLECTUAL PROPERTY OR OTHER THIRD PARTY RIGHTS. ANY USER OF THE MATERIAL 17 | * ASSUMES THE ENTIRE RISK AND LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL 18 | * JHU/APL BE LIABLE TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT, 19 | * CONSEQUENTIAL, SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR INABILITY TO 20 | * USE, THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES FOR LOST PROFITS. 21 | * 22 | * HAVE A NICE DAY. 23 | */ 24 | 25 | /* This material is based upon work supported by the Defense Advanced Research 26 | * Projects Agency (DARPA) and Naval Information Warfare Center Pacific (NIWC Pacific) 27 | * under Contract Number N66001-20-C-4024. 28 | */ 29 | 30 | 31 | package graphcut; 32 | 33 | import java.util.Objects; 34 | import ghidra.program.model.symbol.Namespace; 35 | 36 | 37 | public class NamespaceEdge { 38 | 39 | private Namespace start; 40 | private Namespace end; 41 | 42 | NamespaceEdge(Namespace start, Namespace end){ 43 | this.start = start; 44 | this.end = end; 45 | } 46 | 47 | Namespace getStart() { 48 | return start; 49 | } 50 | 51 | Namespace getEnd() { 52 | return end; 53 | } 54 | 55 | @Override 56 | public String toString() { 57 | return "[" + start + ", " + end + "]"; 58 | } 59 | 60 | @Override 61 | public int hashCode() { 62 | final int prime = 31; 63 | int result = 1; 64 | result = prime*result + ((end == null) ? 0 : end.hashCode()); 65 | result = prime * result + ((start == null) ? 0 : start.hashCode()); 66 | return result; 67 | } 68 | 69 | @Override 70 | public boolean equals(Object obj) { 71 | if (this == obj) { 72 | return true; 73 | } 74 | if (obj == null) { 75 | return false; 76 | } 77 | if (getClass() != obj.getClass()) { 78 | return false; 79 | } 80 | 81 | NamespaceEdge other = (NamespaceEdge) obj; 82 | if(!Objects.equals(end, other.end)) { 83 | return false; 84 | } 85 | 86 | if(!Objects.equals(start, other.start)) { 87 | return false; 88 | } 89 | return true; 90 | } 91 | 92 | } 93 | -------------------------------------------------------------------------------- /codecut-gui/src/main/java/graphcut/NamespaceEdgeCache.java: -------------------------------------------------------------------------------- 1 | /* ### 2 | * © 2021 The Johns Hopkins University Applied Physics Laboratory LLC (JHU/APL). 3 | * All Rights Reserved. 4 | * 5 | * This material may be only be used, modified, or reproduced by or for the U.S. 6 | * Government pursuant to the license rights granted under the clauses at 7 | * DFARS 252.227-7013/7014 or FAR 52.227-14. For any other permission, please 8 | * contact the Office of Technology Transfer at JHU/APL. 9 | * 10 | * NO WARRANTY, NO LIABILITY. THIS MATERIAL IS PROVIDED “AS IS.” JHU/APL MAKES 11 | * NO REPRESENTATION OR WARRANTY WITH RESPECT TO THE PERFORMANCE OF THE MATERIALS, 12 | * INCLUDING THEIR SAFETY, EFFECTIVENESS, OR COMMERCIAL VIABILITY, AND DISCLAIMS 13 | * ALL WARRANTIES IN THE MATERIAL, WHETHER EXPRESS OR IMPLIED, INCLUDING 14 | * (BUT NOT LIMITED TO) ANY AND ALL IMPLIED WARRANTIES OF PERFORMANCE, 15 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF 16 | * INTELLECTUAL PROPERTY OR OTHER THIRD PARTY RIGHTS. ANY USER OF THE MATERIAL 17 | * ASSUMES THE ENTIRE RISK AND LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL 18 | * JHU/APL BE LIABLE TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT, 19 | * CONSEQUENTIAL, SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR INABILITY TO 20 | * USE, THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES FOR LOST PROFITS. 21 | * 22 | * HAVE A NICE DAY. 23 | */ 24 | 25 | /* This material is based upon work supported by the Defense Advanced Research 26 | * Projects Agency (DARPA) and Naval Information Warfare Center Pacific (NIWC Pacific) 27 | * under Contract Number N66001-20-C-4024. 28 | */ 29 | 30 | 31 | package graphcut; 32 | 33 | import java.util.HashMap; 34 | import java.util.HashSet; 35 | import java.util.Map; 36 | import java.util.Set; 37 | 38 | import org.apache.commons.collections4.map.LazyMap; 39 | 40 | import ghidra.program.model.symbol.Namespace; 41 | 42 | /** 43 | * A class to cache known namespace edges 44 | */ 45 | public class NamespaceEdgeCache { 46 | 47 | //contains all known edges, even those not shown in the graph 48 | private Map> allEdgesByNamespace = 49 | LazyMap.lazyMap(new HashMap<>(), () -> new HashSet<>()); 50 | 51 | // track processed namespaces 52 | private Set tracked = new HashSet<>(); 53 | 54 | public Set get(Namespace ns){ 55 | return allEdgesByNamespace.get(ns); 56 | } 57 | 58 | public boolean isTracked(Namespace ns) { 59 | return tracked.contains(ns); 60 | } 61 | 62 | public void setTracked(Namespace ns) { 63 | tracked.add(ns); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /codecut-gui/src/main/java/graphcut/ValidGraphCutData.java: -------------------------------------------------------------------------------- 1 | /* ### 2 | * © 2021 The Johns Hopkins University Applied Physics Laboratory LLC (JHU/APL). 3 | * All Rights Reserved. 4 | * 5 | * This material may be only be used, modified, or reproduced by or for the U.S. 6 | * Government pursuant to the license rights granted under the clauses at 7 | * DFARS 252.227-7013/7014 or FAR 52.227-14. For any other permission, please 8 | * contact the Office of Technology Transfer at JHU/APL. 9 | * 10 | * NO WARRANTY, NO LIABILITY. THIS MATERIAL IS PROVIDED “AS IS.” JHU/APL MAKES 11 | * NO REPRESENTATION OR WARRANTY WITH RESPECT TO THE PERFORMANCE OF THE MATERIALS, 12 | * INCLUDING THEIR SAFETY, EFFECTIVENESS, OR COMMERCIAL VIABILITY, AND DISCLAIMS 13 | * ALL WARRANTIES IN THE MATERIAL, WHETHER EXPRESS OR IMPLIED, INCLUDING 14 | * (BUT NOT LIMITED TO) ANY AND ALL IMPLIED WARRANTIES OF PERFORMANCE, 15 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF 16 | * INTELLECTUAL PROPERTY OR OTHER THIRD PARTY RIGHTS. ANY USER OF THE MATERIAL 17 | * ASSUMES THE ENTIRE RISK AND LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL 18 | * JHU/APL BE LIABLE TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT, 19 | * CONSEQUENTIAL, SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR INABILITY TO 20 | * USE, THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES FOR LOST PROFITS. 21 | * 22 | * HAVE A NICE DAY. 23 | */ 24 | 25 | /* This material is based upon work supported by the Defense Advanced Research 26 | * Projects Agency (DARPA) and Naval Information Warfare Center Pacific (NIWC Pacific) 27 | * under Contract Number N66001-20-C-4024. 28 | */ 29 | 30 | /* 31 | * Borrows from /Features Graph FunctionCalls/src/main/java/functioncalls/plugin/ValidFcgData.java 32 | */ 33 | 34 | 35 | package graphcut; 36 | 37 | import java.util.Objects; 38 | 39 | import ghidra.graph.viewer.GraphPerspectiveInfo; 40 | import ghidra.program.model.symbol.Namespace; 41 | 42 | public class ValidGraphCutData implements GraphCutData { 43 | 44 | private Namespace namespace; 45 | private GraphCutGraph graph; 46 | private GraphPerspectiveInfo perspectiveInfo; 47 | 48 | private NamespaceEdgeCache allEdgesByNamespace = new NamespaceEdgeCache(); 49 | 50 | ValidGraphCutData(Namespace namespace, GraphCutGraph graph){ 51 | this.namespace = Objects.requireNonNull(namespace); 52 | this.graph = Objects.requireNonNull(graph); 53 | } 54 | 55 | @Override 56 | public Namespace getNamespace() { 57 | return namespace; 58 | } 59 | 60 | @Override 61 | public boolean isNamespace(Namespace ns) { 62 | return namespace.equals(ns); 63 | } 64 | 65 | @Override 66 | public GraphCutGraph getGraph() { 67 | return graph; 68 | } 69 | 70 | @Override 71 | public NamespaceEdgeCache getNamespaceEdgeCache() { 72 | return allEdgesByNamespace; 73 | } 74 | 75 | @Override 76 | public boolean hasResults() { 77 | return true; 78 | } 79 | 80 | @Override 81 | public boolean isInitialized() { 82 | return !graph.isEmpty(); 83 | } 84 | 85 | @Override 86 | public void dispose() { 87 | graph.dispose(); 88 | } 89 | 90 | @Override 91 | public GraphPerspectiveInfo getGraphPerspective(){ 92 | return perspectiveInfo; 93 | } 94 | 95 | @Override 96 | public void setGraphPerspective( GraphPerspectiveInfo info) { 97 | this.perspectiveInfo = info; 98 | } 99 | 100 | 101 | } 102 | -------------------------------------------------------------------------------- /codecut-gui/src/main/resources/images/README.txt: -------------------------------------------------------------------------------- 1 | The "src/resources/images" directory is intended to hold all image/icon files used by 2 | this module. 3 | -------------------------------------------------------------------------------- /codecut-gui/src/test/java/README.test.txt: -------------------------------------------------------------------------------- 1 | The "test" directory is intended to hold unit test cases. The package structure within 2 | this folder should correspond to that found in the "src" folder. 3 | -------------------------------------------------------------------------------- /deepcut-ghidra/Module.manifest: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JHUAPL/CodeCut/22c0a93da468f14e4498599b1a4f7aa5f58b4779/deepcut-ghidra/Module.manifest -------------------------------------------------------------------------------- /deepcut-ghidra/README.md: -------------------------------------------------------------------------------- 1 | Ghidra Deepcut Analyzer 2 | ======================= 3 | 4 | Implementation of Deepcut as a Ghidra one-shot analyzer. 5 | 6 | ## Building and Installation 7 | Requirements are the same as Ghidra. Currently JDK 17 (or newer) is required (for Ghidra 10.2). 8 | 9 | Ghidra's standard Gradle build system is used. Set the 10 | `GHIDRA_INSTALL_DIR` environment variable before building, or set it as 11 | a Gradle property (useful for building in an IDE): 12 | 13 | ### Environment variable 14 | ```bash 15 | $ export GHIDRA_INSTALL_DIR="/path/to/ghidra" 16 | $ ./gradle 17 | ``` 18 | 19 | ### Gradle property 20 | ```bash 21 | echo GHIDRA_INSTALL_DIR=/path/to/ghidra > gradle.properties 22 | ``` 23 | 24 | The module ZIP will be output to `dist/`. Use **File > Install 25 | Extensions** and select the green plus to browse to the 26 | extension. Restart Ghidra when prompted. 27 | 28 | For proper functionality, the plugin should be built with the same JRE 29 | used by your Ghidra installation. If you have multiple Java runtime 30 | environments installed, select the correct JRE by setting the 31 | `JAVA_HOME` environment variable before building. 32 | 33 | ### Native Python 3 34 | The Deepcut graph based machine learning model needs Python 3 to 35 | execute (outside of Ghidra). The analyzer calls an external Python 36 | process to execute the model on a graph representation of the binary. 37 | There are no GPU requirements since the model converge quickly even 38 | running in CPU mode. 39 | 40 | #### Python 3 Path 41 | By default the analyzer use the command `/usr/local/bin/python3` to 42 | execute the deepcut python script. This setting can be changed in the 43 | Analysis Options menu **Analysis -> Analyze All Open...** To change the 44 | setting you need to click the checkbox next to **Deepcut (Prototype)** 45 | first. 46 | 47 | #### Dependencies 48 | Deepcut has the following Python 3 dependencies: 49 | 50 | - torch 1.7.1 51 | - torch-geometric 1.6.3 52 | - torch-cluster 1.5.8 53 | - torch-sparse 0.6.8 54 | - torch-scatter 2.0.5 55 | - torch-spline-conv 1.2.0 56 | 57 | To install the dependencies: 58 | 59 | ```bash 60 | pip install torch==1.7.1+cpu -f https://download.pytorch.org/whl/torch_stable.html 61 | pip install -r requirements-torch_geometric.txt 62 | ``` 63 | 64 | The torch-cluster dependency can take a significant amount of time to 65 | build and install. 66 | 67 | ## Running the Analyzer 68 | The Deepcut analyzer will not run during auto-analysis. Once the binary 69 | is loaded and the auto-analyzer is finish use the menu item **Analysis 70 | -> One Shot -> Deepcut** 71 | 72 | Once complete each function will include a `moduleX` value in the 73 | Namespace field. 74 | 75 | If there are any errors please make sure you are using the proper path 76 | to Python 3 and the requirement dependencies installed. 77 | 78 | ## Troubleshooting 79 | You can verify that dependencies are correct by navigating to: 80 | `~/.ghidra/.ghidra_${VERSION}/Extensions/deepcut-ghidra/data` 81 | and running `./python3 deepcut.py`. Python will throw errors if it 82 | can't find dependencies. If the process runs and sits there waiting 83 | for input, then the dependencies should be correct. -------------------------------------------------------------------------------- /deepcut-ghidra/build.gradle: -------------------------------------------------------------------------------- 1 | // Builds a Ghidra Extension for a given Ghidra installation. 2 | // 3 | // An absolute path to the Ghidra installation directory must be supplied either by setting the 4 | // GHIDRA_INSTALL_DIR environment variable or Gradle project property: 5 | // 6 | // > export GHIDRA_INSTALL_DIR= 7 | // > gradle 8 | // 9 | // or 10 | // 11 | // > gradle -PGHIDRA_INSTALL_DIR= 12 | // 13 | // Gradle should be invoked from the directory of the project to build. Please see the 14 | // application.gradle.version property in /Ghidra/application.properties 15 | // for the correction version of Gradle to use for the Ghidra installation you specify. 16 | 17 | //----------------------START "DO NOT MODIFY" SECTION------------------------------ 18 | def ghidraInstallDir 19 | 20 | if (System.env.GHIDRA_INSTALL_DIR) { 21 | ghidraInstallDir = System.env.GHIDRA_INSTALL_DIR 22 | } 23 | else if (project.hasProperty("GHIDRA_INSTALL_DIR")) { 24 | ghidraInstallDir = project.getProperty("GHIDRA_INSTALL_DIR") 25 | } 26 | 27 | if (ghidraInstallDir) { 28 | apply from: new File(ghidraInstallDir).getCanonicalPath() + "/support/buildExtension.gradle" 29 | } 30 | else { 31 | throw new GradleException("GHIDRA_INSTALL_DIR is not defined!") 32 | } 33 | //----------------------END "DO NOT MODIFY" SECTION------------------------------- 34 | -------------------------------------------------------------------------------- /deepcut-ghidra/data/README.txt: -------------------------------------------------------------------------------- 1 | The "data" directory is intended to hold data files that will be used by this module and will 2 | not end up in the .jar file, but will be present in the zip or tar file. Typically, data 3 | files are placed here rather than in the resources directory if the user may need to edit them. 4 | 5 | An optional data/languages directory can exist for the purpose of containing various Sleigh language 6 | specification files and importer opinion files. 7 | 8 | The data/buildLanguage.xml is used for building the contents of the data/languages directory. 9 | 10 | The skel language definition has been commented-out within the skel.ldefs file so that the 11 | skeleton language does not show-up within Ghidra. 12 | 13 | See the Sleigh language documentation (docs/languages/index.html) for details Sleigh language 14 | specification syntax. 15 | -------------------------------------------------------------------------------- /deepcut-ghidra/data/model_weights_1.p: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JHUAPL/CodeCut/22c0a93da468f14e4498599b1a4f7aa5f58b4779/deepcut-ghidra/data/model_weights_1.p -------------------------------------------------------------------------------- /deepcut-ghidra/extension.properties: -------------------------------------------------------------------------------- 1 | name=@extname@ 2 | description=Use the deepcut algorithm to find module boundaries. 3 | author=JHU/APL 4 | createdOn= 5 | version=@extversion@ 6 | -------------------------------------------------------------------------------- /deepcut-ghidra/ghidra_scripts/README.txt: -------------------------------------------------------------------------------- 1 | Java source directory to hold module-specific Ghidra scripts. 2 | -------------------------------------------------------------------------------- /deepcut-ghidra/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.6.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /deepcut-ghidra/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /deepcut-ghidra/os/linux64/README.txt: -------------------------------------------------------------------------------- 1 | The "os/linux64" directory is intended to hold Linux native binaries 2 | which this module is dependent upon. This directory may be eliminated for a specific 3 | module if native binaries are not provided for the corresponding platform. 4 | -------------------------------------------------------------------------------- /deepcut-ghidra/os/osx64/README.txt: -------------------------------------------------------------------------------- 1 | The "os/osx64" directory is intended to hold macOS (OS X) native binaries 2 | which this module is dependent upon. This directory may be eliminated for a specific 3 | module if native binaries are not provided for the corresponding platform. 4 | -------------------------------------------------------------------------------- /deepcut-ghidra/os/win64/README.txt: -------------------------------------------------------------------------------- 1 | The "os/win64" directory is intended to hold MS Windows native binaries (.exe) 2 | which this module is dependent upon. This directory may be eliminated for a specific 3 | module if native binaries are not provided for the corresponding platform. 4 | -------------------------------------------------------------------------------- /deepcut-ghidra/requirements-torch_geometric.txt: -------------------------------------------------------------------------------- 1 | torch-geometric==1.6.3 2 | 3 | --find-links https://pytorch-geometric.com/whl/torch-1.7.0+cpu.html 4 | torch-sparse==0.6.8 5 | torch-scatter==2.0.5 6 | torch-cluster==1.5.8 7 | torch-spline-conv==1.2.0 8 | -------------------------------------------------------------------------------- /deepcut-ghidra/src/main/help/help/TOC_Source.xml: -------------------------------------------------------------------------------- 1 | 2 | 49 | 50 | 51 | 52 | 57 | 58 | -------------------------------------------------------------------------------- /deepcut-ghidra/src/main/help/help/shared/Frontpage.css: -------------------------------------------------------------------------------- 1 | /* ### 2 | * IP: GHIDRA 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | /* 17 | WARNING! 18 | This file is copied to all help directories. If you change this file, you must copy it 19 | to each src/main/help/help/shared directory. 20 | 21 | 22 | Java Help Note: JavaHelp does not accept sizes (like in 'margin-top') in anything but 23 | px (pixel) or with no type marking. 24 | 25 | */ 26 | 27 | body { margin-bottom: 50px; margin-left: 10px; margin-right: 10px; margin-top: 10px; } /* some padding to improve readability */ 28 | li { font-family:times new roman; font-size:14pt; } 29 | h1 { color:#000080; font-family:times new roman; font-size:36pt; font-style:italic; font-weight:bold; text-align:center; } 30 | h2 { margin: 10px; margin-top: 20px; color:#984c4c; font-family:times new roman; font-size:18pt; font-weight:bold; } 31 | h3 { margin-left: 10px; margin-top: 20px; color:#0000ff; font-family:times new roman; `font-size:14pt; font-weight:bold; } 32 | h4 { margin-left: 10px; margin-top: 20px; font-family:times new roman; font-size:14pt; font-style:italic; } 33 | 34 | /* 35 | P tag code. Most of the help files nest P tags inside of blockquote tags (the was the 36 | way it had been done in the beginning). The net effect is that the text is indented. In 37 | modern HTML we would use CSS to do this. We need to support the Ghidra P tags, nested in 38 | blockquote tags, as well as naked P tags. The following two lines accomplish this. Note 39 | that the 'blockquote p' definition will inherit from the first 'p' definition. 40 | */ 41 | p { margin-left: 40px; font-family:times new roman; font-size:14pt; } 42 | blockquote p { margin-left: 10px; } 43 | 44 | p.providedbyplugin { color:#7f7f7f; margin-left: 10px; font-size:14pt; margin-top:100px } 45 | p.ProvidedByPlugin { color:#7f7f7f; margin-left: 10px; font-size:14pt; margin-top:100px } 46 | p.relatedtopic { color:#800080; margin-left: 10px; font-size:14pt; } 47 | p.RelatedTopic { color:#800080; margin-left: 10px; font-size:14pt; } 48 | 49 | /* 50 | We wish for a tables to have space between it and the preceding element, so that text 51 | is not too close to the top of the table. Also, nest the table a bit so that it is clear 52 | the table relates to the preceding text. 53 | */ 54 | table { margin-left: 20px; margin-top: 10px; width: 80%;} 55 | td { font-family:times new roman; font-size:14pt; vertical-align: top; } 56 | th { font-family:times new roman; font-size:14pt; font-weight:bold; background-color: #EDF3FE; } 57 | 58 | /* 59 | Code-like formatting for things such as file system paths and proper names of classes, 60 | methods, etc. To apply this to a file path, use this syntax: 61 | ... 62 | */ 63 | code { color: black; font-weight: bold; font-family: courier new, monospace; font-size: 14pt; white-space: nowrap; } 64 | code.path { color: #4682B4; font-weight: bold; font-family: courier new, monospace; font-size: 14pt; white-space: nowrap; } 65 | -------------------------------------------------------------------------------- /deepcut-ghidra/src/main/java/deepcut/Cut.java: -------------------------------------------------------------------------------- 1 | /* ### 2 | * © 2022 The Johns Hopkins University Applied Physics Laboratory LLC 3 | * (JHU/APL). 4 | * 5 | * NO WARRANTY, NO LIABILITY. THIS MATERIAL IS PROVIDED “AS IS.” JHU/APL 6 | * MAKES NO REPRESENTATION OR WARRANTY WITH RESPECT TO THE PERFORMANCE OF 7 | * THE MATERIALS, INCLUDING THEIR SAFETY, EFFECTIVENESS, OR COMMERCIAL 8 | * VIABILITY, AND DISCLAIMS ALL WARRANTIES IN THE MATERIAL, WHETHER 9 | * EXPRESS OR IMPLIED, INCLUDING (BUT NOT LIMITED TO) ANY AND ALL IMPLIED 10 | * WARRANTIES OF PERFORMANCE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 11 | * PURPOSE, AND NON-INFRINGEMENT OF INTELLECTUAL PROPERTY OR OTHER THIRD 12 | * PARTY RIGHTS. ANY USER OF THE MATERIAL ASSUMES THE ENTIRE RISK AND 13 | * LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL JHU/APL BE LIABLE 14 | * TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT, CONSEQUENTIAL, 15 | * SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR INABILITY TO USE, 16 | * THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES FOR LOST 17 | * PROFITS. 18 | * 19 | * This material is based upon work supported by the Defense Advanced Research 20 | * Projects Agency (DARPA) and Naval Information Warfare Center Pacific (NIWC Pacific) 21 | * under Contract Number N66001-20-C-4024. 22 | * 23 | * HAVE A NICE DAY. 24 | */ 25 | 26 | package deepcut; 27 | 28 | import ghidra.program.model.listing.Program; 29 | 30 | class Cut { 31 | public String address; 32 | public String name; 33 | 34 | public Cut(Program program, String address, String name) { 35 | this.address = address; 36 | this.name = name; 37 | } 38 | 39 | @Override 40 | public String toString() { 41 | return this.address.toString() + ":" + this.name; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /deepcut-ghidra/src/main/java/deepcut/DeepCutPython.java: -------------------------------------------------------------------------------- 1 | /* ### 2 | * © 2022 The Johns Hopkins University Applied Physics Laboratory LLC 3 | * (JHU/APL). 4 | * 5 | * NO WARRANTY, NO LIABILITY. THIS MATERIAL IS PROVIDED “AS IS.” JHU/APL 6 | * MAKES NO REPRESENTATION OR WARRANTY WITH RESPECT TO THE PERFORMANCE OF 7 | * THE MATERIALS, INCLUDING THEIR SAFETY, EFFECTIVENESS, OR COMMERCIAL 8 | * VIABILITY, AND DISCLAIMS ALL WARRANTIES IN THE MATERIAL, WHETHER 9 | * EXPRESS OR IMPLIED, INCLUDING (BUT NOT LIMITED TO) ANY AND ALL IMPLIED 10 | * WARRANTIES OF PERFORMANCE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 11 | * PURPOSE, AND NON-INFRINGEMENT OF INTELLECTUAL PROPERTY OR OTHER THIRD 12 | * PARTY RIGHTS. ANY USER OF THE MATERIAL ASSUMES THE ENTIRE RISK AND 13 | * LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL JHU/APL BE LIABLE 14 | * TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT, CONSEQUENTIAL, 15 | * SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR INABILITY TO USE, 16 | * THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES FOR LOST 17 | * PROFITS. 18 | * 19 | * This material is based upon work supported by the Defense Advanced Research 20 | * Projects Agency (DARPA) and Naval Information Warfare Center Pacific (NIWC Pacific) 21 | * under Contract Number N66001-20-C-4024. 22 | * 23 | * HAVE A NICE DAY. 24 | */ 25 | 26 | package deepcut; 27 | 28 | import java.io.BufferedReader; 29 | import java.io.IOException; 30 | import java.io.InputStream; 31 | import java.io.InputStreamReader; 32 | import java.io.OutputStream; 33 | import java.util.stream.Collectors; 34 | 35 | import ghidra.framework.Application; 36 | 37 | public class DeepCutPython { 38 | public Runtime runtime; 39 | public String pythonExec; 40 | 41 | public Process process; 42 | public OutputStream stdin; 43 | public InputStream stdout; 44 | public InputStream stderr; 45 | 46 | public DeepCutPython(String pythonExec) { 47 | this.pythonExec = pythonExec; 48 | this.runtime = Runtime.getRuntime(); 49 | } 50 | 51 | public void startProcess() throws IOException { 52 | String pythonFile = Application.getModuleDataFile("deepcut.py").toString(); 53 | String modelFile = Application.getModuleDataFile("model_weights_1.p").toString(); 54 | 55 | //pythonFile = "/Users/desteaj1/Programs/AMP/deepcut/src/deepcut"; 56 | String[] exec = {pythonExec, pythonFile, modelFile}; 57 | 58 | process = runtime.exec(exec); 59 | 60 | // Yes this is confusing. stdin is a Java OutputStream, stdout is an InputStream 61 | stdin = process.getOutputStream(); 62 | stdout = process.getInputStream(); 63 | stderr = process.getErrorStream(); 64 | } 65 | 66 | public void waitFor() throws InterruptedException { 67 | process.waitFor(); 68 | } 69 | 70 | public void writeProcess(String data) throws IOException { 71 | writeProcess(data.getBytes()); 72 | } 73 | 74 | public void writeProcess(byte[] data) throws IOException { 75 | stdin.write(data); 76 | } 77 | 78 | public String readProcessOutput() { 79 | return readProcess(stdout); 80 | 81 | } 82 | 83 | public String readProcessError() { 84 | return readProcess(stderr); 85 | 86 | } 87 | 88 | private String readProcess(InputStream stream) { 89 | String result = ""; 90 | 91 | try { 92 | if (stream.available() > 0 ) { 93 | result = new BufferedReader(new InputStreamReader(stream)) 94 | .lines().collect(Collectors.joining("\n")); 95 | } 96 | } catch (IOException e) { 97 | return result; 98 | } 99 | 100 | return result; 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /deepcut-ghidra/src/main/java/deepcut/EdgeInfo.java: -------------------------------------------------------------------------------- 1 | /* ### 2 | * © 2022 The Johns Hopkins University Applied Physics Laboratory LLC 3 | * (JHU/APL). 4 | * 5 | * NO WARRANTY, NO LIABILITY. THIS MATERIAL IS PROVIDED “AS IS.” JHU/APL 6 | * MAKES NO REPRESENTATION OR WARRANTY WITH RESPECT TO THE PERFORMANCE OF 7 | * THE MATERIALS, INCLUDING THEIR SAFETY, EFFECTIVENESS, OR COMMERCIAL 8 | * VIABILITY, AND DISCLAIMS ALL WARRANTIES IN THE MATERIAL, WHETHER 9 | * EXPRESS OR IMPLIED, INCLUDING (BUT NOT LIMITED TO) ANY AND ALL IMPLIED 10 | * WARRANTIES OF PERFORMANCE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 11 | * PURPOSE, AND NON-INFRINGEMENT OF INTELLECTUAL PROPERTY OR OTHER THIRD 12 | * PARTY RIGHTS. ANY USER OF THE MATERIAL ASSUMES THE ENTIRE RISK AND 13 | * LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL JHU/APL BE LIABLE 14 | * TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT, CONSEQUENTIAL, 15 | * SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR INABILITY TO USE, 16 | * THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES FOR LOST 17 | * PROFITS. 18 | * 19 | * This material is based upon work supported by the Defense Advanced Research 20 | * Projects Agency (DARPA) and Naval Information Warfare Center Pacific (NIWC Pacific) 21 | * under Contract Number N66001-20-C-4024. 22 | * 23 | * HAVE A NICE DAY. 24 | */ 25 | 26 | package deepcut; 27 | 28 | class EdgeInfo { 29 | private FunctionInfo src; 30 | private FunctionInfo dst; 31 | 32 | private int multiplicity; 33 | 34 | /* 35 | distance between the two functions, 36 | either in terms of address 37 | or number of functions in between. 38 | */ 39 | private double addressDistance; 40 | private double indexDistance; 41 | 42 | private boolean isSelfCall; 43 | 44 | public EdgeInfo(FunctionInfo src, FunctionInfo dst, int multiplicity) { 45 | this.src = src; 46 | this.dst = dst; 47 | 48 | this.multiplicity = multiplicity; 49 | 50 | this.addressDistance = (double) dst.getAddress().subtract(src.getAddress()); 51 | this.indexDistance = (double) dst.getAddressIndex() - src.getAddressIndex(); 52 | } 53 | 54 | public FunctionInfo getSrc() { 55 | return src; 56 | } 57 | 58 | public FunctionInfo getDst() { 59 | return dst; 60 | } 61 | 62 | public int getMultiplicity() { 63 | return multiplicity; 64 | } 65 | 66 | public double getAddressDistance() { 67 | return addressDistance; 68 | } 69 | 70 | public double getIndexDistance() { 71 | return indexDistance; 72 | } 73 | 74 | public boolean getisSelfCall() { 75 | return isSelfCall; 76 | } 77 | 78 | public long getSrcAddressIndex() { 79 | return src.getAddressIndex(); 80 | } 81 | 82 | public long getDstAddressIndex() { 83 | return dst.getAddressIndex(); 84 | } 85 | 86 | @Override 87 | public String toString() { 88 | return String.format("%-20s -> %20-s\t#%d", src.getName(), 89 | dst.getName(), multiplicity); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /deepcut-ghidra/src/main/java/deepcut/EdgeInfoSerializer.java: -------------------------------------------------------------------------------- 1 | /* ### 2 | * © 2022 The Johns Hopkins University Applied Physics Laboratory LLC 3 | * (JHU/APL). 4 | * 5 | * NO WARRANTY, NO LIABILITY. THIS MATERIAL IS PROVIDED “AS IS.” JHU/APL 6 | * MAKES NO REPRESENTATION OR WARRANTY WITH RESPECT TO THE PERFORMANCE OF 7 | * THE MATERIALS, INCLUDING THEIR SAFETY, EFFECTIVENESS, OR COMMERCIAL 8 | * VIABILITY, AND DISCLAIMS ALL WARRANTIES IN THE MATERIAL, WHETHER 9 | * EXPRESS OR IMPLIED, INCLUDING (BUT NOT LIMITED TO) ANY AND ALL IMPLIED 10 | * WARRANTIES OF PERFORMANCE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 11 | * PURPOSE, AND NON-INFRINGEMENT OF INTELLECTUAL PROPERTY OR OTHER THIRD 12 | * PARTY RIGHTS. ANY USER OF THE MATERIAL ASSUMES THE ENTIRE RISK AND 13 | * LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL JHU/APL BE LIABLE 14 | * TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT, CONSEQUENTIAL, 15 | * SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR INABILITY TO USE, 16 | * THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES FOR LOST 17 | * PROFITS. 18 | * 19 | * This material is based upon work supported by the Defense Advanced Research 20 | * Projects Agency (DARPA) and Naval Information Warfare Center Pacific (NIWC Pacific) 21 | * under Contract Number N66001-20-C-4024. 22 | * 23 | * HAVE A NICE DAY. 24 | */ 25 | 26 | package deepcut; 27 | 28 | import java.lang.reflect.Type; 29 | 30 | import com.google.gson.JsonElement; 31 | import com.google.gson.JsonObject; 32 | import com.google.gson.JsonSerializationContext; 33 | import com.google.gson.JsonSerializer; 34 | 35 | class EdgeInfoSerializer implements JsonSerializer { 36 | @Override 37 | public JsonElement serialize(EdgeInfo src, Type typeOfSrc, JsonSerializationContext context) { 38 | JsonObject obj = new JsonObject(); 39 | 40 | obj.addProperty("src_index", src.getSrcAddressIndex()); 41 | obj.addProperty("dst_index", src.getDstAddressIndex()); 42 | obj.addProperty("multiplicity", src.getMultiplicity()); 43 | obj.addProperty("addr_distance", src.getAddressDistance()); 44 | obj.addProperty("index_distance", src.getIndexDistance()); 45 | 46 | return obj; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /deepcut-ghidra/src/main/java/deepcut/FunctionInfo.java: -------------------------------------------------------------------------------- 1 | /* ### 2 | * © 2022 The Johns Hopkins University Applied Physics Laboratory LLC 3 | * (JHU/APL). 4 | * 5 | * NO WARRANTY, NO LIABILITY. THIS MATERIAL IS PROVIDED “AS IS.” JHU/APL 6 | * MAKES NO REPRESENTATION OR WARRANTY WITH RESPECT TO THE PERFORMANCE OF 7 | * THE MATERIALS, INCLUDING THEIR SAFETY, EFFECTIVENESS, OR COMMERCIAL 8 | * VIABILITY, AND DISCLAIMS ALL WARRANTIES IN THE MATERIAL, WHETHER 9 | * EXPRESS OR IMPLIED, INCLUDING (BUT NOT LIMITED TO) ANY AND ALL IMPLIED 10 | * WARRANTIES OF PERFORMANCE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 11 | * PURPOSE, AND NON-INFRINGEMENT OF INTELLECTUAL PROPERTY OR OTHER THIRD 12 | * PARTY RIGHTS. ANY USER OF THE MATERIAL ASSUMES THE ENTIRE RISK AND 13 | * LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL JHU/APL BE LIABLE 14 | * TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT, CONSEQUENTIAL, 15 | * SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR INABILITY TO USE, 16 | * THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES FOR LOST 17 | * PROFITS. 18 | * 19 | * This material is based upon work supported by the Defense Advanced Research 20 | * Projects Agency (DARPA) and Naval Information Warfare Center Pacific (NIWC Pacific) 21 | * under Contract Number N66001-20-C-4024. 22 | * 23 | * HAVE A NICE DAY. 24 | */ 25 | 26 | package deepcut; 27 | 28 | import java.util.ArrayList; 29 | import java.util.List; 30 | 31 | import ghidra.program.model.address.Address; 32 | import ghidra.program.model.listing.Function; 33 | 34 | class FunctionInfo { 35 | private Function function; 36 | 37 | private Address address; 38 | private long addressIndex; 39 | 40 | private String name; 41 | 42 | // `true` if the function is either external or a thunk function. 43 | private boolean isExternalThunk; 44 | 45 | private List incomingEdges; 46 | private List outgoingEdges; 47 | 48 | // `true` if the function ever calls itself 49 | private boolean isRecursive; 50 | 51 | public FunctionInfo(Function function) { 52 | this.function = function; 53 | address = function.getEntryPoint(); 54 | name = function.getName(); 55 | 56 | // will be set in a later pass 57 | addressIndex = -1; 58 | isRecursive = false; 59 | 60 | isExternalThunk = function.isThunk() || function.isExternal() || 61 | (!function.getParentNamespace().isGlobal()); 62 | 63 | incomingEdges = new ArrayList(); 64 | outgoingEdges = new ArrayList(); 65 | } 66 | 67 | public void addIncomingEdge(EdgeInfo edge) { 68 | incomingEdges.add(edge); 69 | } 70 | 71 | public List getIncomingEdges() { 72 | return incomingEdges; 73 | } 74 | 75 | public int getIncomingEdgeSize() { 76 | return incomingEdges.size(); 77 | } 78 | 79 | public void addOutgoingEdge(EdgeInfo edge) { 80 | outgoingEdges.add(edge); 81 | } 82 | 83 | public List getOutgoingEdges() { 84 | return outgoingEdges; 85 | } 86 | 87 | public int getOutgoingEdgeSize() { 88 | return outgoingEdges.size(); 89 | } 90 | 91 | public Function getFunction() { 92 | return function; 93 | } 94 | 95 | public void setIsRecursive(boolean val) { 96 | isRecursive = val; 97 | } 98 | 99 | public boolean getIsRecursive() { 100 | return isRecursive; 101 | } 102 | 103 | public void setAddress(Address address) { 104 | this.address = address; 105 | } 106 | 107 | public Address getAddress() { 108 | return address; 109 | } 110 | 111 | public void setAddressIndex(int index) { 112 | this.addressIndex = index; 113 | } 114 | 115 | public long getAddressIndex() { 116 | return addressIndex; 117 | } 118 | 119 | public String getName() { 120 | return name; 121 | } 122 | 123 | @Override 124 | public String toString() { 125 | return getFunction().getName() + " " + address + 126 | " (" + addressIndex + ")"; 127 | } 128 | 129 | } 130 | -------------------------------------------------------------------------------- /deepcut-ghidra/src/main/java/deepcut/FunctionInfoSerializer.java: -------------------------------------------------------------------------------- 1 | /* ### 2 | * © 2022 The Johns Hopkins University Applied Physics Laboratory LLC 3 | * (JHU/APL). 4 | * 5 | * NO WARRANTY, NO LIABILITY. THIS MATERIAL IS PROVIDED “AS IS.” JHU/APL 6 | * MAKES NO REPRESENTATION OR WARRANTY WITH RESPECT TO THE PERFORMANCE OF 7 | * THE MATERIALS, INCLUDING THEIR SAFETY, EFFECTIVENESS, OR COMMERCIAL 8 | * VIABILITY, AND DISCLAIMS ALL WARRANTIES IN THE MATERIAL, WHETHER 9 | * EXPRESS OR IMPLIED, INCLUDING (BUT NOT LIMITED TO) ANY AND ALL IMPLIED 10 | * WARRANTIES OF PERFORMANCE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 11 | * PURPOSE, AND NON-INFRINGEMENT OF INTELLECTUAL PROPERTY OR OTHER THIRD 12 | * PARTY RIGHTS. ANY USER OF THE MATERIAL ASSUMES THE ENTIRE RISK AND 13 | * LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL JHU/APL BE LIABLE 14 | * TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT, CONSEQUENTIAL, 15 | * SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR INABILITY TO USE, 16 | * THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES FOR LOST 17 | * PROFITS. 18 | * 19 | * This material is based upon work supported by the Defense Advanced Research 20 | * Projects Agency (DARPA) and Naval Information Warfare Center Pacific (NIWC Pacific) 21 | * under Contract Number N66001-20-C-4024. 22 | * 23 | * HAVE A NICE DAY. 24 | */ 25 | 26 | package deepcut; 27 | 28 | import java.lang.reflect.Type; 29 | 30 | import com.google.gson.JsonElement; 31 | import com.google.gson.JsonObject; 32 | import com.google.gson.JsonSerializationContext; 33 | import com.google.gson.JsonSerializer; 34 | 35 | class FunctionInfoSerializer implements JsonSerializer { 36 | @Override 37 | public JsonElement serialize(FunctionInfo src, Type typeOfSrc, JsonSerializationContext context) { 38 | JsonObject obj = new JsonObject(); 39 | obj.addProperty("name", src.getName()); 40 | obj.addProperty("addr", src.getAddress().toString()); 41 | obj.addProperty("index", src.getAddressIndex()); 42 | obj.addProperty("num_incoming_edges", src.getIncomingEdges().size()); 43 | obj.addProperty("num_outgoing_edges", src.getOutgoingEdges().size()); 44 | 45 | return obj; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /deepcut-ghidra/src/main/resources/images/README.txt: -------------------------------------------------------------------------------- 1 | The "src/resources/images" directory is intended to hold all image/icon files used by 2 | this module. 3 | -------------------------------------------------------------------------------- /deepcut-ghidra/src/test/java/README.test.txt: -------------------------------------------------------------------------------- 1 | The "test" directory is intended to hold unit test cases. The package structure within 2 | this folder should correspond to that found in the "src" folder. 3 | -------------------------------------------------------------------------------- /img/codecut-config.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JHUAPL/CodeCut/22c0a93da468f14e4498599b1a4f7aa5f58b4779/img/codecut-config.png -------------------------------------------------------------------------------- /img/codecut-run.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JHUAPL/CodeCut/22c0a93da468f14e4498599b1a4f7aa5f58b4779/img/codecut-run.png -------------------------------------------------------------------------------- /img/deepcut-config.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JHUAPL/CodeCut/22c0a93da468f14e4498599b1a4f7aa5f58b4779/img/deepcut-config.png -------------------------------------------------------------------------------- /img/graph-pic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JHUAPL/CodeCut/22c0a93da468f14e4498599b1a4f7aa5f58b4779/img/graph-pic.png --------------------------------------------------------------------------------