├── .gitignore ├── img └── demo.gif ├── decompiler.py ├── README.md ├── plugin.json ├── Decompile_TEMPLATE.txt ├── highlighter.py ├── LICENSE └── __init__.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | -------------------------------------------------------------------------------- /img/demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Martyx00/ghinja/HEAD/img/demo.gif -------------------------------------------------------------------------------- /decompiler.py: -------------------------------------------------------------------------------- 1 | from binaryninja import * 2 | from pathlib import Path 3 | import hashlib 4 | import os 5 | import subprocess 6 | 7 | class Decompiler(BackgroundTaskThread): 8 | def __init__(self,file_name,current_path): 9 | #self.progress_banner = f"[Ghinja] Running the decompiler job ... Ghinja decompiler output not available until finished." 10 | BackgroundTaskThread.__init__(self, "", True) 11 | self.file_name = str(Path(file_name).name) 12 | self.file_path = file_name 13 | self.current_path = current_path 14 | self.decompile_result_path = Path(self.current_path / "decomp_") 15 | 16 | 17 | def run(self): 18 | self.progress = f"[Ghinja] Running the decompiler job ... Ghinja decompiler output not available until finished." 19 | with open(os.path.dirname(os.path.realpath(__file__)) + "/Decompile_TEMPLATE.txt",'r') as decomp_file: 20 | data = decomp_file.read() 21 | with open(os.path.dirname(os.path.realpath(__file__)) + "/Decompile.java",'w') as tmp_decomp_file: 22 | tmp_decomp_file.write(data.replace("PLACEHOLDER_OUTPUT",str(self.decompile_result_path).replace("\\","\\\\"))) 23 | os.system(f"{Settings().get_string('ghinja.ghidra_install_path')} \"{str(self.current_path)}\" \"{self.file_name}\" -import \"{self.file_path}\" -postscript Decompile.java -scriptPath \"{os.path.dirname(os.path.realpath(__file__))}\"") 24 | #log_info(f"{Settings().get_string('ghinja.ghidra_install_path')} \"{str(self.current_path)}\" \"{self.file_name}\" -import \"{self.file_path}\" -postscript \"{os.path.dirname(os.path.realpath(__file__)) + '/Decompile.java'}\" -scriptPath \"{os.path.dirname(os.path.realpath(__file__))}\"") 25 | 26 | os.remove(os.path.dirname(os.path.realpath(__file__)) + "/Decompile.java") 27 | show_message_box("Ghidra Decompiler", "Decompiler process is done. Please select function to continue.", buttons=0, icon=1) 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Ghinja (1.10) 2 | Author: **Martin Petran** 3 | 4 | _Plugin to embed Ghidra Decompiler into Binary Ninja_ 5 | 6 | ## Description: 7 | This plugin allows you to enable a dock in the UI that will show a result of the Ghidra decompiler for the given function. There is basic syntax highlighting and selected text highlighting (something missing in Ghidra). Renaming functions and variables in the Binary Ninja view is refleced in the Ghinja view as well. The plugin will prompt you for pointing it to the path of the `analyzeHeadless` file which is relevant for your operating system. When chosen it will automatically start ghidra decompilation whenever a new file is opened. The decompile results are stored in the `user_plugin_path() + "/ghinja_projects"` folder. 8 | 9 | For users of BinaryNinja 2.x please use version 1.8. 10 | 11 | ![Sample](https://github.com/Martyx00/ghinja/blob/master/img/demo.gif?raw=true "Sample") 12 | 13 | **Available Hotkeys:** 14 | * ***N*** - When Ghinja window has focus you can use this hotkey to rename the variable that does not have equivalent in the Binary Ninja view. This function allows you to rename anything, however all labels (functions, variables, etc.) that are are avialable in Binary Ninja view should be renamed there rather than in Ghinja as that is string replace only. 15 | * ***F*** - When Ghinja window has focus you can use this hotkey to perform a simple text seatch in the decompiler result. 16 | 17 | 18 | ## Minimum Version 19 | 20 | This plugin requires the following minimum version of Binary Ninja: 21 | 22 | * 3233 23 | 24 | ## Required Dependencies 25 | 26 | The following dependencies are required for this plugin: 27 | 28 | * other - https://ghidra-sre.org/ 29 | 30 | ## Disclaimer 31 | 32 | I have nothing in common with development of Ghidra decompiler. 33 | 34 | **If you have used versions prior to 1.0, it will be better if you remove all old ghinja projects and start from scratch. Sorry ... :(** 35 | 36 | ## License 37 | 38 | This plugin is released under a Apache license. 39 | ## Metadata Version 40 | 41 | 2 42 | -------------------------------------------------------------------------------- /plugin.json: -------------------------------------------------------------------------------- 1 | { 2 | "pluginmetadataversion" : 2, 3 | "name": "Ghinja", 4 | "type": ["ui"], 5 | "api": ["python3"], 6 | "description": "Plugin to embed Ghidra Decompiler into Binary Ninja", 7 | "longdescription": "This plugin allows you to enable a dock in the UI that will show a result of the Ghidra decompiler for the given function. There is basic syntax highlighting and renaming functions and variables in the Binary Ninja view is refleced in the Ghinja view as well. The plugin will prompt you for pointing it to the path of the `analyzeHeadless` file which is relevant for your operating system. When chosen it will automatically start ghidra decompilation whenever a new file is opened. The decompile results are stored in the `~/.ghinja_projects` folder.\n\n ![Sample](https://github.com/Martyx00/ghinja/blob/master/img/demo.gif?raw=true \"Sample\")\n\n **Available Hotkeys:**\n\n* ***N*** - When Ghinja window has focus you can use this hotkey to rename the variable that does not have equivalent in the Binary Ninja view. This function allows you to rename anything, however all labels (functions, variables, etc.) that are are avialable in Binary Ninja view should be renamed there rather than in Ghinja as that is string replace only.\n* ***F*** - When Ghinja window has focus you can use this hotkey to perform a simple text seatch in the decompiler result.\n", 8 | "license": { 9 | "name": "Apache-2.0", 10 | "text": "Copyright 2020 Martin Petran\n\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at\n\n\thttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License." 11 | }, 12 | "platforms" : ["Darwin", "Linux", "Windows"], 13 | "installinstructions" : { 14 | "Darwin" : "N/A", 15 | "Linux" : "N/A", 16 | "Windows" : "N/A" 17 | }, 18 | "dependencies": { 19 | "other": ["This plugin requires a working install of Ghidra (https://ghidra-sre.org/)."] 20 | }, 21 | "version": "1.10", 22 | "author": "Martin Petran", 23 | "minimumbinaryninjaversion": 3233 24 | } 25 | -------------------------------------------------------------------------------- /Decompile_TEMPLATE.txt: -------------------------------------------------------------------------------- 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 | //Decompile an entire program 17 | 18 | import java.io.File; 19 | import java.util.ArrayList; 20 | import java.util.List; 21 | //import ghidra.app.plugin.core.script.Ingredient; 22 | //import ghidra.app.plugin.core.script.IngredientDescription; 23 | import ghidra.app.script.GatherParamPanel; 24 | import ghidra.app.script.GhidraScript; 25 | import ghidra.app.util.Option; 26 | import ghidra.program.model.address.AddressSet; 27 | import ghidra.program.model.address.Address; 28 | import ghidra.app.decompiler.DecompInterface; 29 | import ghidra.app.decompiler.DecompileResults; 30 | import ghidra.app.decompiler.DecompiledFunction; 31 | import ghidra.app.util.headless.HeadlessScript; 32 | import ghidra.program.model.address.Address; 33 | import ghidra.program.model.listing.Function; 34 | import ghidra.program.model.listing.FunctionIterator; 35 | import ghidra.program.model.listing.Listing; 36 | import java.util.ArrayList; 37 | import java.io.FileWriter; 38 | 39 | public class Decompile extends HeadlessScript { 40 | 41 | @Override 42 | public void run() throws Exception { 43 | 44 | setHeadlessContinuationOption(HeadlessContinuationOption.ABORT); 45 | DecompInterface decompiler = new DecompInterface(); 46 | boolean first = true; 47 | Listing listing = currentProgram.getListing(); 48 | FunctionIterator iter = listing.getFunctions(true); 49 | Function function = iter.next(); 50 | decompiler.openProgram(function.getProgram()); 51 | while (iter.hasNext() && !monitor.isCancelled()) { 52 | if (function.isExternal()) { 53 | function = iter.next(); 54 | continue; 55 | } 56 | Address entryPoint = function.getEntryPoint(); 57 | 58 | if (entryPoint != null) { 59 | if (first) { 60 | FileWriter myWriter = new FileWriter("PLACEHOLDER_OUTPUT"+"offset"); 61 | myWriter.write(String.valueOf(entryPoint.getOffset())); 62 | myWriter.close(); 63 | first = false; 64 | } 65 | DecompileResults decompilerResult = decompiler.decompileFunction(function, 5, null); 66 | DecompiledFunction decompiledFunction = decompilerResult.getDecompiledFunction(); 67 | if (decompiledFunction == null) { 68 | function = iter.next(); 69 | continue; 70 | } 71 | FileWriter myWriter = new FileWriter("PLACEHOLDER_OUTPUT"+String.valueOf(entryPoint.getOffset())); 72 | myWriter.write(decompiledFunction.getC()); 73 | myWriter.close(); 74 | } 75 | function = iter.next(); 76 | } 77 | } 78 | } 79 | 80 | 81 | -------------------------------------------------------------------------------- /highlighter.py: -------------------------------------------------------------------------------- 1 | from PySide6 import QtCore 2 | import re 3 | from PySide6.QtCore import Qt 4 | from PySide6.QtGui import QSyntaxHighlighter, QTextCharFormat, QFont, QColor 5 | from binaryninja import * 6 | from binaryninjaui import getThemeColor 7 | 8 | class Highlighter(QSyntaxHighlighter): 9 | def __init__(self,doc,selected,args): 10 | super(Highlighter,self).__init__(doc) 11 | self.selected = selected 12 | self.args = args 13 | 14 | def highlightBlock(self, text): 15 | # Highlight keywords 16 | keywords = ["(?<=\\W\\()\\w+(?=[ *&]*\\))","\\w+ (?=.*\\)$)","^ +\\w+ (?=[*&_A-Za-z0-9\\[\\] ]+;)","^\w+","\\bin_addr\\b","\\bssize_t\\b","\\bsocklen_t\\b","\\bsa_family_t\\b","\\b__int32_t\\b","\\b__int8_t\\b","\\b__int16_t\\b","\\b__uint32_t\\b","\\b__uint8_t\\b","\\b__uint16_t\\b","\\bpid_t\\b","\\bcode\\b","\\bLPSTR\\b","\\bSIZE_T\\b","\\bLPVOID\\b","\\bDWORD\\b","\\bclock_t\\b","\\bthis\\b","\\bUINT\\b","\\bHANDLE\\b","\\blonglong\\b","\\bushort\\b","\\bFILE\\b","\\bulong\\b","\\bbyte\\b","\\bfalse\\b","\\btrue\\b","\\buint\\b","\\bsize_t\\b","\\bundefined\\d*\\b","\\bchar\\b", "\\bclass\\b", "\\bconst\\b", "\\bdouble\\b", "\\benum\\b", "\\bexplicit\\b","\\bfriend\\b", "\\binline\\b", "\\bint\\b","\\blong\\b", "\\bnamespace\\b", "\\boperator\\b","\\bprivate\\b", "\\bprotected\\b", "\\bpublic\\b","\\bshort\\b", "\\bsignals\\b", "\\bsigned\\b","\\bslots\\b", "\\bstatic\\b", "\\bstruct\\b","\\btemplate\\b", "\\btypedef\\b", "\\btypename\\b","\\bunion\\b", "\\bunsigned\\b", "\\bvirtual\\b","\\bvoid\\b", "\\bvolatile\\b", "\\bbool\\b"] 17 | keyword_format = QTextCharFormat() 18 | keyword_format.setForeground(getThemeColor(enums.ThemeColor.KeywordColor)) 19 | for keyword in keywords: 20 | for match in re.finditer(keyword, text): 21 | self.setFormat(match.start(), match.end() - match.start(), keyword_format) 22 | # Highlight flow words 23 | flow_words = ["\\breturn\\b","\\bif\\b","\\belse\\b","\\bswitch\\b","\\bcase\\b","\\bwhile\\b","\\bfor\\b","\\bdo\\b","\\bgoto\\b"] 24 | flow_format = QTextCharFormat() 25 | flow_format.setForeground(getThemeColor(enums.ThemeColor.TokenHighlightColor)) 26 | for flow in flow_words: 27 | for match in re.finditer(flow, text): 28 | self.setFormat(match.start(), match.end() - match.start(), flow_format) 29 | # Highlight functions 30 | function_format = QTextCharFormat() 31 | function_format.setForeground(getThemeColor(enums.ThemeColor.CodeSymbolColor)) 32 | function_pattern = "\\b\\w+(?=\\()" 33 | for match in re.finditer(function_pattern, text): 34 | self.setFormat(match.start(), match.end() - match.start(), function_format) 35 | # Highlight comments 36 | comment_format = QTextCharFormat() 37 | comment_format.setForeground(getThemeColor(enums.ThemeColor.CommentColor)) 38 | comment_pattern = "\/\/.*$" 39 | for match in re.finditer(comment_pattern, text): 40 | self.setFormat(match.start(), match.end() - match.start(), comment_format) 41 | multi_comment_pattern = "(?s)\\/\\*.*?\\*\\/" 42 | for match in re.finditer(multi_comment_pattern, text): 43 | self.setFormat(match.start(), match.end() - match.start(), comment_format) 44 | # Highlight string constants 45 | const_format = QTextCharFormat() 46 | const_format.setForeground(getThemeColor(enums.ThemeColor.StringColor)) 47 | string_consts = "\"(.*?)\"" 48 | for match in re.finditer(string_consts, text): 49 | self.setFormat(match.start(), match.end() - match.start(), const_format) 50 | # Highlight numeric constants 51 | num_const_format = QTextCharFormat() 52 | num_const_format.setForeground(getThemeColor(enums.ThemeColor.NumberColor)) 53 | num_consts = "\\b\\d+\\b" 54 | for match in re.finditer(num_consts, text): 55 | self.setFormat(match.start(), match.end() - match.start(), num_const_format) 56 | hex_const = "0x[0-9a-f]+\\b" 57 | for match in re.finditer(hex_const, text): 58 | self.setFormat(match.start(), match.end() - match.start(), num_const_format) 59 | # Highlight data 60 | data_format = QTextCharFormat() 61 | data_format.setForeground(getThemeColor(enums.ThemeColor.DataSymbolColor)) 62 | data_consts = "\\b(PTR)?_?DAT_[0-9a-zA-Z]+\\b" 63 | for match in re.finditer(data_consts, text): 64 | self.setFormat(match.start(), match.end() - match.start(), data_format) 65 | # Highlight CPP Class paths 66 | cpp_format = QTextCharFormat() 67 | cpp_format.setForeground(getThemeColor(enums.ThemeColor.NameSpaceColor)) 68 | cpp_path = "\\b\\w*(?=::)" 69 | for match in re.finditer(cpp_path, text): 70 | self.setFormat(match.start(), match.end() - match.start(), cpp_format) 71 | # Params 72 | params_format = QTextCharFormat() 73 | params_format.setForeground(getThemeColor(enums.ThemeColor.FieldNameColor)) 74 | for arg in self.args: 75 | params_pattern = "\\b" + arg + "\\b" 76 | for match in re.finditer(params_pattern, text): 77 | self.setFormat(match.start(), match.end() - match.start(), params_format) 78 | # Highlight selection 79 | if self.selected: 80 | selection_format = QTextCharFormat() 81 | #selection_format.setBackground(getThemeColor(enums.ThemeColor.Highlight)) 82 | selection_format.setBackground(QColor.fromRgb(121,195,231)) 83 | selection_format.setForeground(QColor.fromRgb(42,42,42)) 84 | try: 85 | selection_pattern = self.selected 86 | for match in re.finditer(selection_pattern, text): 87 | self.setFormat(match.start(), match.end() - match.start(), selection_format) 88 | except: 89 | pass 90 | 91 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2020 Martin Petran 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | from binaryninja import * 2 | from binaryninjaui import DockHandler, DockContextHandler, UIActionHandler 3 | from PySide6 import QtCore 4 | from .highlighter import Highlighter 5 | from .decompiler import Decompiler 6 | from PySide6.QtCore import Qt 7 | from PySide6.QtGui import QTextCursor 8 | from PySide6.QtWidgets import QApplication, QHBoxLayout, QVBoxLayout, QLabel, QWidget, QTextEdit 9 | import json 10 | import os, sys 11 | import hashlib 12 | from pathlib import Path 13 | import shutil 14 | import re 15 | 16 | instance_id = 0 17 | class GhinjaDockWidget(QWidget, DockContextHandler): 18 | def __init__(self, parent, name, data): 19 | # Read the configuration 20 | settings = Settings() 21 | settings.register_group("ghinja", "Ghinja") 22 | settings.register_setting("ghinja.ghidra_install_path", """ 23 | { 24 | "title" : "Ghidra Installation Path", 25 | "type" : "string", 26 | "default" : "", 27 | "description" : "Path to analyzeHeadless file in Ghidra installation dir." 28 | } 29 | """) 30 | if not os.path.exists(settings.get_string("ghinja.ghidra_install_path")): 31 | show_message_box("Path to Ghidra headless was not found!", "To allow the Ghinja plugin to work, you will be prompted to specify the path to the \"analyzeHeadless(.bat)\" file.", buttons=0, icon=2) 32 | settings.set_string("ghinja.ghidra_install_path",get_open_filename_input("Provide Path to Ghidra \"analyzeHeadless(.bat)\" file (Usually: /support/analyzeHeadless)")) 33 | 34 | self.rename_settings = Settings() 35 | self.rename_settings.register_group("ghinja_rename","Rename") 36 | self.rename_settings.register_setting("ghinja_rename.ghinja_rename_struct", """ 37 | { 38 | "title" : "Ghidra Rename Struct", 39 | "type" : "string", 40 | "default" : "{}", 41 | "description" : "Settings to hold renames for variables." 42 | } 43 | """) 44 | 45 | global instance_id 46 | self.binja_renames = {} # {"function_name":[{"original":"new"})]} 47 | self.current_function = None 48 | self.current_offset = None 49 | self.decomp = None 50 | self.current_view = None 51 | self.function_output = None 52 | self.decompile_result_path = None 53 | self.decompile_offset_path = None 54 | self.decompiler_done = False 55 | self.function_args = [] 56 | QWidget.__init__(self, parent) 57 | DockContextHandler.__init__(self, self, name) 58 | self.actionHandler = UIActionHandler() 59 | self.actionHandler.setupActionHandler(self) 60 | layout = QVBoxLayout() 61 | self.editor = QTextEdit(self) 62 | self.editor.setReadOnly(True) 63 | self.editor.installEventFilter(self) 64 | self.editor.setStyleSheet("QTextEdit { font-family: Consolas }") 65 | self.editor.setPlainText(" Click anywhere in the dock to start decompiler") 66 | self.editor.selectionChanged.connect(self.onSelect) 67 | highlighter = Highlighter(self.editor.document(),"",self.function_args) 68 | layout.addWidget(self.editor) 69 | layout.setAlignment(QtCore.Qt.AlignLeft) 70 | self.setLayout(layout) 71 | instance_id += 1 72 | self.data = data 73 | self.filename = None 74 | 75 | def onSelect(self): 76 | cursor = self.editor.textCursor() 77 | if cursor.selectedText(): 78 | ch = Highlighter(self.editor.document(),"\\b" + cursor.selectedText() + "\\b",self.function_args) 79 | else: 80 | ch = Highlighter(self.editor.document(),"",self.function_args) 81 | 82 | def notifyOffsetChanged(self, offset): 83 | if self.decompiler_done: 84 | #if not self.current_function or not (self.current_function.lowest_address < offset and self.current_function.highest_address > offset): 85 | scrollbar_value = self.editor.verticalScrollBar().value() 86 | self.current_offset = offset 87 | try: 88 | self.editor.setPlainText(self.find_function(offset)) 89 | ch = Highlighter(self.editor.document(),"",self.function_args) 90 | self.editor.verticalScrollBar().setValue(scrollbar_value) 91 | except: 92 | pass 93 | 94 | def shouldBeVisible(self, view_frame): 95 | if view_frame is None: 96 | return False 97 | else: 98 | return True 99 | 100 | def eventFilter(self, obj, event): 101 | if event.type() == QtCore.QEvent.FocusIn and self.editor.hasFocus() and not self.decompiler_done and self.filename: 102 | self.decomp = Decompiler(self.filename,self.current_path) 103 | self.editor.setPlainText(" ... ") 104 | self.decomp.start() 105 | self.decompiler_done = True 106 | 107 | if event.type() == QtCore.QEvent.KeyPress and obj is self.editor: 108 | cursor = self.editor.textCursor() 109 | if event.key() == QtCore.Qt.Key_F and self.editor.hasFocus(): 110 | # Find TODO 111 | search_string = get_text_line_input("Find: ","Find") 112 | if search_string: 113 | ch = Highlighter(self.editor.document(),search_string.decode("UTF-8"),self.function_args) 114 | if event.key() == QtCore.Qt.Key_N and self.editor.hasFocus(): 115 | if self.current_view.file.has_database == False: 116 | show_message_box("Project not saved", "To enable renaming, make sure that the current project is saved to a BNDB file.", buttons=0, icon=2) 117 | return False 118 | # Handle rename action 119 | selected = cursor.selectedText() 120 | if selected != "": 121 | #self.binja_renames = json.loads(self.rename_settings.get_string("ghinja_rename.ghinja_rename_struct",self.current_view)) 122 | # Get selected text 123 | new_name = get_text_line_input(f"Rename {selected}: ","Rename") 124 | if new_name and not re.match(b"^\\w+$", new_name): 125 | show_message_box("Name not valid", "Please use only 'word' characters (A-Z, a-z, 0-9 and _)", buttons=0, icon=2) 126 | return False 127 | if re.search(f"\\b{new_name.decode('UTF-8')}\\b",self.function_output): 128 | show_message_box("Name not unique", "Please use only unique name to avoid conflicts.", buttons=0, icon=2) 129 | return False 130 | found = False 131 | for key in self.binja_renames[hex(self.current_function.start)]: 132 | if key["original"] == selected: 133 | # Was already renamed so just reassign to avoid accumulating tons of data 134 | key["new"] = new_name.decode("UTF-8") 135 | found = True 136 | if key["new"] == selected: 137 | key["new"] = new_name.decode("UTF-8") 138 | found = True 139 | if not found: 140 | self.binja_renames[hex(self.current_function.start)].append({"original":selected,"new":new_name.decode("UTF-8")}) 141 | self.rename_settings.set_string("ghinja_rename.ghinja_rename_struct",json.dumps(self.binja_renames),self.current_view,SettingsScope.SettingsResourceScope) 142 | self.notifyOffsetChanged(self.current_offset) 143 | return False 144 | 145 | 146 | def notifyViewChanged(self, view_frame): 147 | if view_frame is None: 148 | pass 149 | else: 150 | self.current_view = view_frame.actionContext().binaryView 151 | self.binja_renames = json.loads(self.rename_settings.get_string("ghinja_rename.ghinja_rename_struct",self.current_view)) 152 | md5 = hashlib.md5() 153 | try: 154 | with open(view_frame.actionContext().binaryView.file.original_filename,'rb') as binary: 155 | file_content = binary.read() 156 | md5.update(file_content) 157 | self.current_path = Path(Path(user_plugin_path()) / ".." / f"ghinja_projects/{str(Path(view_frame.actionContext().binaryView.file.original_filename).name) + '_' + md5.hexdigest()}") 158 | self.filename = view_frame.actionContext().binaryView.file.original_filename 159 | self.current_path.mkdir(parents=True, exist_ok=True) 160 | except: 161 | # File does not exist 162 | tmp_path = Path(user_plugin_path()) / ".." / f"ghinja_projects/{str(Path(view_frame.actionContext().binaryView.file.original_filename).name)}" 163 | self.current_view.save(str(tmp_path)) 164 | while not os.path.exists(str(tmp_path)): 165 | pass 166 | with open(str(tmp_path),'rb') as binary: 167 | file_content = binary.read() 168 | md5.update(file_content) 169 | self.current_path = Path(Path(user_plugin_path()) / ".." / f"ghinja_projects/{str(Path(view_frame.actionContext().binaryView.file.original_filename).name) + '_' + md5.hexdigest()}") 170 | self.current_path.mkdir(parents=True, exist_ok=True) 171 | shutil.move(tmp_path, self.current_path / tmp_path.name) 172 | self.filename = str(self.current_path / tmp_path.name) 173 | # Create relevant_folder 174 | #current_path = Path(Path.home() / f".ghinja_projects/{str(Path(view_frame.actionContext().binaryView.file.original_filename).name) + '_' + md5.hexdigest()}") 175 | self.decompile_result_path = Path(self.current_path / "decomp_") 176 | self.decompile_offset_path = Path(self.current_path / "decomp_offset") 177 | 178 | if os.path.exists(str(self.decompile_offset_path)): 179 | # Already decompiled we dont have to do anything 180 | self.decompiler_done = True 181 | 182 | 183 | 184 | def contextMenuEvent(self, event): 185 | self.m_contextMenuManager.show(self.m_menu, self.actionHandler) 186 | 187 | @staticmethod 188 | def create_widget(name, parent, data = None): 189 | return GhinjaDockWidget(parent, name, data) 190 | 191 | def myroundup(self,n, step): 192 | return ((n - 1) // step + 1) * step 193 | 194 | def find_function(self, offset): 195 | function_output = "DECOMPILER OUTPUT FOR THIS FUNCTION WAS NOT FOUND" 196 | try: 197 | self.current_function = self.current_view.get_functions_containing(offset)[0] 198 | try: 199 | self.binja_renames[hex(self.current_function.start)] 200 | except: 201 | self.binja_renames[hex(self.current_function.start)] = [] 202 | except: 203 | return "DECOMPILER OUTPUT FOR THIS FUNCTION WAS NOT FOUND" 204 | # Get different offset functions os.listdir() 205 | offset = 0 206 | with open(str(self.decompile_offset_path),"r") as offset_file: 207 | ghidra_offset = int(offset_file.read()) 208 | # find min start as in some cases the functions might not be ordered 209 | binja_offset = sys.maxsize 210 | for f in self.current_view.functions: 211 | if f.start < binja_offset: 212 | binja_offset = f.start 213 | offset_diff = ghidra_offset - binja_offset 214 | if abs(offset_diff) > 0x100 and not os.path.exists(str(self.decompile_result_path) + str(offset_diff)): 215 | offset_diff = self.myroundup(offset_diff,0x100) 216 | else: 217 | offset_diff = 0 218 | #log_info(f"GHIDRA OFFSET: {hex(ghidra_offset)} DIFF: {hex(offset_diff)} ROUND: {hex(self.myroundup(offset_diff,0x100))}") 219 | if offset_diff == 0: 220 | offset = self.current_function.start 221 | else: 222 | offset = self.current_function.start + offset_diff 223 | if os.path.exists(str(self.decompile_result_path) + str(offset)): 224 | with open(str(self.decompile_result_path) + str(offset),"r") as function_file: 225 | function_output = function_file.read() 226 | # Replace function name 227 | function_output = re.sub("\\b\\w*\\(", self.current_function.name + "(", function_output, 1) 228 | # Rename functions 229 | for callee in self.current_function.callees: 230 | if offset_diff == 0: 231 | look_for = f'FUN_{callee.start:08x}' 232 | else: 233 | look_for = f'FUN_{callee.start + offset_diff:08x}' 234 | function_output = function_output.replace(look_for,callee.name) 235 | 236 | #for ghinja_rename in self.binja_renames[hex(self.current_function.start)]: 237 | js = json.loads(self.rename_settings.get_string("ghinja_rename.ghinja_rename_struct",self.current_view)) 238 | if js: 239 | try: 240 | for ghinja_rename in js[hex(self.current_function.start)]: 241 | function_output = re.sub('\\b'+ghinja_rename["original"]+'\\b',ghinja_rename["new"],function_output) 242 | except: 243 | pass 244 | # Searching in frist 300 chars is enough 245 | self.function_args = [] 246 | for arg in re.findall("\\w+ [*&]?(\\w+),|\\w+ [*&]?(\\w+)\\)", function_output[:300]): 247 | if arg[0]: 248 | self.function_args.append(arg[0]) 249 | elif arg[1]: 250 | self.function_args.append(arg[1]) 251 | # Rename locals - quite buggy actually 252 | for local in self.current_function.stack_layout: 253 | if local.storage < 0: 254 | look_for = f"local_{hex(local.storage)[3:]}" 255 | function_output = re.sub(look_for,local.name,function_output) 256 | self.function_output = function_output 257 | return function_output 258 | 259 | 260 | def addStaticDockWidget(): 261 | dock_handler = DockHandler.getActiveDockHandler() 262 | parent = dock_handler.parent() 263 | dock_widget = GhinjaDockWidget.create_widget("Ghinja Decompiler", parent) 264 | dock_handler.addDockWidget(dock_widget, Qt.TopDockWidgetArea, Qt.Horizontal, True, False) 265 | 266 | addStaticDockWidget() 267 | --------------------------------------------------------------------------------