├── .gitignore ├── .vscode └── settings.json ├── LICENSE ├── QCodeEditor.py ├── README.md ├── __init__.py ├── do_release.py ├── generate_plugininfo.py ├── media └── snippets.gif ├── plugin.json ├── requirements.txt └── update_example_snippets.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | __pycache__/ 3 | .vscode 4 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.pythonPath": "/usr/local/bin/python3" 3 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2019 Vector 35 Inc 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /QCodeEditor.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Licensed under the terms of the MIT License 5 | 6 | Re-written for Snippet Editor by Jordan Wiens (https://github.com/psifertex/) 7 | With some original components (line numbers) based on: 8 | 9 | https://github.com/luchko/QCodeEditor 10 | @author: Ivan Luchko (luchko.ivan@gmail.com) 11 | ''' 12 | 13 | import binaryninjaui 14 | from binaryninja import log_warn, bncompleter 15 | if "qt_major_version" in binaryninjaui.__dict__ and binaryninjaui.qt_major_version == 6: 16 | from PySide6.QtCore import Qt, QRect 17 | from PySide6.QtWidgets import QWidget, QPlainTextEdit 18 | from PySide6.QtGui import (QPainter, QFont, QSyntaxHighlighter, QTextCharFormat, QTextCursor) 19 | else: 20 | from PySide2.QtCore import Qt, QRect 21 | from PySide2.QtWidgets import QWidget, QPlainTextEdit 22 | from PySide2.QtGui import (QPainter, QFont, QSyntaxHighlighter, QTextCharFormat, QTextCursor) 23 | from binaryninjaui import (getMonospaceFont, getThemeColor, ThemeColor) 24 | try: 25 | from pygments import highlight 26 | from pygments.lexers import * 27 | from pygments.formatter import Formatter 28 | 29 | class QFormatter(Formatter): 30 | 31 | def __init__(self): 32 | Formatter.__init__(self) 33 | self.pygstyles={} 34 | for token, style in self.style: 35 | tokenname = str(token) 36 | if tokenname in bnstyles.keys(): 37 | self.pygstyles[str(token)]=bnstyles[tokenname] 38 | #log_warn("MATCH: %s with %s" % (tokenname, str(token))) 39 | else: 40 | self.pygstyles[str(token)]=bnstyles['Token.Name'] 41 | #log_warn("NONE: %s with %s" % (tokenname, str(token))) 42 | 43 | def format(self, tokensource, outfile): 44 | self.data=[] 45 | for token, value in tokensource: 46 | self.data.extend([self.pygstyles[str(token)],]*len(value)) 47 | 48 | class Pylighter(QSyntaxHighlighter): 49 | 50 | def __init__(self, parent, lang): 51 | QSyntaxHighlighter.__init__(self, parent) 52 | self.formatter=QFormatter() 53 | self.lexer=get_lexer_by_name(lang) 54 | 55 | def highlightBlock(self, text): 56 | cb = self.currentBlock() 57 | p = cb.position() 58 | text=self.document().toPlainText()+' \n' 59 | highlight(text,self.lexer,self.formatter) 60 | 61 | #dirty, dirty hack 62 | for i in range(len(text)): 63 | try: 64 | self.setFormat(i,1,self.formatter.data[p+i]) 65 | except IndexError: 66 | pass 67 | 68 | except: 69 | log_warn("Pygments not installed, no syntax highlighting enabled.") 70 | Pylighter=None 71 | 72 | 73 | def bnformat(color, style=''): 74 | """Return a QTextCharFormat with the given attributes.""" 75 | color = eval('getThemeColor(ThemeColor.%s)' % color) 76 | 77 | format = QTextCharFormat() 78 | format.setForeground(color) 79 | if 'bold' in style: 80 | format.setFontWeight(QFont.Bold) 81 | if 'italic' in style: 82 | format.setFontItalic(True) 83 | 84 | return format 85 | 86 | # Most of these aren't needed but after fighting pygments for so long I figure they can't hurt. 87 | bnstyles = { 88 | 'Token.Literal.Number': bnformat('NumberColor'), 89 | 'Token.Literal.Number.Bin': bnformat('NumberColor'), 90 | 'Token.Literal.Number.Float': bnformat('NumberColor'), 91 | 'Token.Literal.Number.Integer': bnformat('NumberColor'), 92 | 'Token.Literal.Number.Integer.Long': bnformat('NumberColor'), 93 | 'Token.Literal.Number.Hex': bnformat('NumberColor'), 94 | 'Token.Literal.Number.Oct': bnformat('NumberColor'), 95 | 96 | 'Token.Literal.String': bnformat('StringColor'), 97 | 'Token.Literal.String.Single': bnformat('StringColor'), 98 | 'Token.Literal.String.Char': bnformat('StringColor'), 99 | 'Token.Literal.String.Backtick': bnformat('StringColor'), 100 | 'Token.Literal.String.Delimiter': bnformat('StringColor'), 101 | 'Token.Literal.String.Double': bnformat('StringColor'), 102 | 'Token.Literal.String.Heredoc': bnformat('StringColor'), 103 | 'Token.Literal.String.Affix': bnformat('StringColor'), 104 | 'Token.String': bnformat('StringColor'), 105 | 106 | 'Token.Comment': bnformat('CommentColor', 'italic'), 107 | 'Token.Comment.Hashbang': bnformat('CommentColor', 'italic'), 108 | 'Token.Comment.Single': bnformat('CommentColor', 'italic'), 109 | 'Token.Comment.Special': bnformat('CommentColor', 'italic'), 110 | 'Token.Comment.PreprocFile': bnformat('CommentColor', 'italic'), 111 | 'Token.Comment.Multiline': bnformat('CommentColor', 'italic'), 112 | 113 | 'Token.Keyword': bnformat('StackVariableColor'), 114 | 115 | 'Token.Operator': bnformat('TokenHighlightColor'), 116 | 'Token.Punctuation': bnformat('UncertainColor'), 117 | 118 | #This is the most important and hardest to get right. No way to get theme palettes! 119 | 'Token.Name': bnformat('OutlineColor'), 120 | 121 | 'Token.Name.Namespace': bnformat('OutlineColor'), 122 | 123 | 'Token.Name.Variable': bnformat('DataSymbolColor'), 124 | 'Token.Name.Class': bnformat('DataSymbolColor'), 125 | 'Token.Name.Constant': bnformat('DataSymbolColor'), 126 | 'Token.Name.Entity': bnformat('DataSymbolColor'), 127 | 'Token.Name.Other': bnformat('DataSymbolColor'), 128 | 'Token.Name.Tag': bnformat('DataSymbolColor'), 129 | 'Token.Name.Decorator': bnformat('DataSymbolColor'), 130 | 'Token.Name.Label': bnformat('DataSymbolColor'), 131 | 'Token.Name.Variable.Magic': bnformat('DataSymbolColor'), 132 | 'Token.Name.Variable.Instance': bnformat('DataSymbolColor'), 133 | 'Token.Name.Variable.Class': bnformat('DataSymbolColor'), 134 | 'Token.Name.Variable.Global': bnformat('DataSymbolColor'), 135 | 'Token.Name.Property': bnformat('DataSymbolColor'), 136 | 'Token.Name.Function': bnformat('DataSymbolColor'), 137 | 'Token.Name.Builtin': bnformat('ImportColor'), 138 | 'Token.Name.Builtin.Pseudo': bnformat('ImportColor'), 139 | 140 | 'Token.Escape': bnformat('ImportColor'), 141 | 142 | 'Token.Keyword': bnformat('GotoLabelColor'), 143 | 'Token.Operator.Word': bnformat('GotoLabelColor'), 144 | 145 | 'numberBar': getThemeColor(ThemeColor.BackgroundHighlightDarkColor), 146 | 'blockSelected': getThemeColor(ThemeColor.TokenHighlightColor), 147 | 'blockNormal': getThemeColor(ThemeColor.TokenSelectionColor), 148 | } 149 | 150 | 151 | class QCodeEditor(QPlainTextEdit): 152 | class NumberBar(QWidget): 153 | 154 | def __init__(self, editor): 155 | QWidget.__init__(self, editor) 156 | global bnstyles 157 | 158 | self.editor = editor 159 | self.editor.blockCountChanged.connect(self.updateWidth) 160 | self.editor.updateRequest.connect(self.updateContents) 161 | self.font = editor.currentCharFormat().font() 162 | self.numberBarColor = bnstyles["numberBar"] 163 | self.updateWidth() 164 | 165 | def paintEvent(self, event): 166 | painter = QPainter(self) 167 | painter.fillRect(event.rect(), self.numberBarColor) 168 | 169 | block = self.editor.firstVisibleBlock() 170 | 171 | # Iterate over all visible text blocks in the document. 172 | while block.isValid(): 173 | blockNumber = block.blockNumber() 174 | block_top = self.editor.blockBoundingGeometry(block).translated(self.editor.contentOffset()).top() 175 | 176 | # Check if the position of the block is out side of the visible area. 177 | if not block.isVisible() or block_top >= event.rect().bottom(): 178 | break 179 | 180 | # We want the line number for the selected line to be bold. 181 | if blockNumber == self.editor.textCursor().blockNumber(): 182 | self.font.setBold(True) 183 | painter.setPen(bnstyles["blockSelected"]) 184 | else: 185 | self.font.setBold(False) 186 | painter.setPen(bnstyles["blockNormal"]) 187 | painter.setFont(self.font) 188 | 189 | # Draw the line number left justified at the position of the line. 190 | paint_rect = QRect(0, block_top, self.width(), self.editor.fontMetrics().height()) 191 | painter.drawText(paint_rect, Qt.AlignLeft, str(blockNumber + 3)) # Offset so that the lines are correct to the file 192 | 193 | block = block.next() 194 | 195 | painter.end() 196 | 197 | QWidget.paintEvent(self, event) 198 | 199 | def getWidth(self): 200 | count = self.editor.blockCount() 201 | width = self.fontMetrics().horizontalAdvance(str(count)) + 10 202 | return width 203 | 204 | def updateWidth(self): 205 | width = self.getWidth() 206 | if self.width() != width: 207 | self.setFixedWidth(width) 208 | self.editor.setViewportMargins(width, 0, 0, 0) 209 | 210 | def updateContents(self, rect, scroll): 211 | if scroll: 212 | self.scroll(0, scroll) 213 | else: 214 | self.update(0, rect.y(), self.width(), rect.height()) 215 | 216 | if rect.contains(self.editor.viewport().rect()): 217 | self.updateWidth() 218 | 219 | 220 | def __init__(self, DISPLAY_LINE_NUMBERS=True, HIGHLIGHT_CURRENT_LINE=True, 221 | SyntaxHighlighter=Pylighter, lang="python", font_size=11, delimeter=" ", *args): 222 | super(QCodeEditor, self).__init__() 223 | 224 | font = getMonospaceFont(self) 225 | font.setPointSize(font_size) 226 | self.setFont(font) 227 | self.setLineWrapMode(QPlainTextEdit.NoWrap) 228 | self.completionState = 0 229 | self.completing = False 230 | self.delimeter = delimeter 231 | self.completer = bncompleter.Completer() 232 | self.cursorPositionChanged.connect(self.resetCompletion) 233 | 234 | self.DISPLAY_LINE_NUMBERS = DISPLAY_LINE_NUMBERS 235 | 236 | if DISPLAY_LINE_NUMBERS: 237 | self.number_bar = self.NumberBar(self) 238 | 239 | if SyntaxHighlighter is not None: # add highlighter to textdocument 240 | self.highlighter = SyntaxHighlighter(self.document(), lang) 241 | 242 | def resetCompletion(self): 243 | if not self.completing: 244 | self.completionState = 0 245 | 246 | def isStart(self): 247 | tempCursor = self.textCursor() 248 | if tempCursor.positionInBlock() == 0: 249 | return True 250 | startText = tempCursor.block().text()[0:tempCursor.positionInBlock()] 251 | delim = set(self.delimeter) 252 | if set(startText) - delim == set(): 253 | #only delimeters before cursor, not worrying about varying lengths of spaces for now 254 | return True 255 | return False 256 | 257 | def setDelimeter(self, delimeter): 258 | self.deliemter = delimeter; 259 | 260 | def replaceBlockAtCursor(self, newText): 261 | cursor=self.textCursor() 262 | cursor.select(QTextCursor.BlockUnderCursor) 263 | if cursor.selectionStart() != 0: 264 | newText = "\n" + newText 265 | cursor.removeSelectedText() 266 | cursor.insertText(newText) 267 | 268 | def keyPressEvent(self, event): 269 | if event.key() == Qt.Key_Backtab and self.textCursor().hasSelection(): 270 | startCursor = self.textCursor() 271 | startCursor.beginEditBlock() 272 | startPos = startCursor.selectionStart() 273 | startCursor.setPosition(startPos) 274 | startCursor.movePosition(QTextCursor.StartOfLine, QTextCursor.MoveAnchor) 275 | startCursor.clearSelection() 276 | 277 | endCursor = self.textCursor() 278 | endPos = endCursor.selectionEnd() 279 | endCursor.setPosition(endPos) 280 | endCursor.movePosition(QTextCursor.StartOfLine) 281 | 282 | while startCursor.anchor() != endCursor.position(): 283 | startCursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor, len(self.delimeter)) 284 | if startCursor.selectedText() == self.delimeter: 285 | startCursor.removeSelectedText() 286 | startCursor.movePosition(QTextCursor.NextBlock, QTextCursor.MoveAnchor) 287 | startCursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor, len(self.delimeter)) 288 | if startCursor.selectedText() == self.delimeter: 289 | startCursor.removeSelectedText() 290 | startCursor.endEditBlock() 291 | return 292 | 293 | if event.key() == Qt.Key_Tab and self.textCursor().hasSelection(): 294 | startCursor = self.textCursor() 295 | startCursor.beginEditBlock() 296 | startPos = startCursor.selectionStart() 297 | startCursor.setPosition(startPos) 298 | startCursor.movePosition(QTextCursor.StartOfLine) 299 | 300 | endCursor = self.textCursor() 301 | endPos = endCursor.selectionEnd() 302 | endCursor.setPosition(endPos) 303 | endCursor.movePosition(QTextCursor.StartOfLine) 304 | 305 | while startCursor.position() != endCursor.position(): 306 | startCursor.insertText(self.delimeter) 307 | startCursor.movePosition(QTextCursor.NextBlock) 308 | 309 | startCursor.insertText(self.delimeter) 310 | startCursor.endEditBlock() 311 | return 312 | 313 | if event.key() == Qt.Key_Escape and self.completionState > 0: 314 | self.completionState = 0 315 | cursor = self.textCursor() 316 | cursor.beginEditBlock() 317 | self.replaceBlockAtCursor(self.origText) 318 | cursor.endEditBlock() 319 | self.origText == None 320 | return 321 | 322 | if event.key() == Qt.Key_Tab: 323 | if self.isStart(): 324 | self.textCursor().insertText(self.delimeter) 325 | else: 326 | cursor = self.textCursor() 327 | cursor.beginEditBlock() 328 | self.completing = True 329 | if self.completionState == 0: 330 | self.origText = self.textCursor().block().text() 331 | if self.completionState > 0: 332 | self.replaceBlockAtCursor(self.origText) 333 | newText = self.completer.complete(self.origText, self.completionState) 334 | if newText: 335 | if newText.find("(") > 0: 336 | newText = newText[0:newText.find("(") + 1] 337 | self.completionState += 1 338 | self.replaceBlockAtCursor(newText) 339 | else: 340 | self.completionState = 0 341 | self.replaceBlockAtCursor(self.origText) 342 | self.origText == None 343 | cursor.endEditBlock() 344 | self.completing = False 345 | return 346 | 347 | return super().keyPressEvent(event) 348 | 349 | 350 | def resizeEvent(self, *e): 351 | '''overload resizeEvent handler''' 352 | 353 | if self.DISPLAY_LINE_NUMBERS: # resize number_bar widget 354 | cr = self.contentsRect() 355 | rec = QRect(cr.left(), cr.top(), self.number_bar.getWidth(), cr.height()) 356 | self.number_bar.setGeometry(rec) 357 | 358 | QPlainTextEdit.resizeEvent(self, *e) 359 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Snippet UI Plugin (v1.28) 2 | Author: **Vector 35 Inc** 3 | 4 | _Powerful code-editing plugin for writing and managing python code-snippets with syntax highlighting, hotkey binding and other features_ 5 | 6 | ## Description: 7 | 8 | The snippet editor started as a simple example UI plugin to demonstrate new features available to UI plugins. It has turned into a functionally useful plugin in its own right. The snippet editor allows you to write small bits of code that might not be big enough to warrant the effort of a full plugin but are long enough that you don't want to retype them every time in the python-console! 9 | 10 | As an added bonus, all snippets are added to the snippets menu and hot-keys can be associated with them as they make use of the action system. All action-system items are also available through the command-palette (CTL/CMD-p). 11 | 12 | ![](https://github.com/Vector35/snippets/blob/master/media/snippets.gif?raw=true) 13 | 14 | . 15 | 16 | 17 | ## Installation Instructions 18 | 19 | ### Darwin 20 | 21 | no special instructions, package manager is recommended 22 | 23 | ### Linux 24 | 25 | no special instructions, package manager is recommended 26 | 27 | ### Windows 28 | 29 | no special instructions, package manager is recommended 30 | 31 | ## Minimum Version 32 | 33 | This plugin requires the following minimum version of Binary Ninja: 34 | 35 | * 1528 36 | 37 | 38 | 39 | ## Required Dependencies 40 | 41 | The following dependencies are required for this plugin: 42 | 43 | * pip - pygments>=2.7.0,<2.9.0 44 | 45 | 46 | ## License 47 | 48 | This plugin is released under a MIT license. 49 | ## Metadata Version 50 | 51 | 2 52 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | import sys 4 | import os 5 | import shutil 6 | import codecs 7 | import getpass 8 | from collections import namedtuple 9 | from datetime import datetime 10 | from pathlib import Path 11 | 12 | from binaryninja import user_plugin_path, core_version, execute_on_main_thread_and_wait 13 | from binaryninja.plugin import BackgroundTaskThread 14 | from binaryninja.log import (log_error, log_debug, log_alert, log_warn) 15 | from binaryninja.settings import Settings 16 | from binaryninja.interaction import get_directory_name_input 17 | from binaryninja.variable import Variable 18 | from binaryninja.enums import FunctionGraphType 19 | from binaryninjaui import (getMonospaceFont, UIAction, UIActionHandler, Menu, UIContext) 20 | from PySide6.QtWidgets import (QLineEdit, QPushButton, QApplication, QWidget, 21 | QVBoxLayout, QHBoxLayout, QDialog, QFileSystemModel, QTreeView, QLabel, QSplitter, 22 | QInputDialog, QMessageBox, QHeaderView, QKeySequenceEdit, QCheckBox, QMenu, QAbstractItemView) 23 | from PySide6.QtCore import (QDir, Qt, QFileInfo, QItemSelectionModel, QSettings, QUrl, 24 | QFileSystemWatcher, QObject, Signal, Slot) 25 | from PySide6.QtGui import (QFontMetrics, QDesktopServices, QKeySequence, QIcon, QColor, QAction, 26 | QCursor, QGuiApplication) 27 | from .QCodeEditor import QCodeEditor, Pylighter 28 | 29 | Settings().register_group("snippets", "Snippets") 30 | Settings().register_setting("snippets.syntaxHighlight", """ 31 | { 32 | "title" : "Syntax Highlighting", 33 | "type" : "boolean", 34 | "default" : true, 35 | "description" : "Whether to syntax highlight (may be performance problems with very large snippets and the current highlighting implementation.)", 36 | "ignore" : ["SettingsProjectScope", "SettingsResourceScope"] 37 | } 38 | """) 39 | Settings().register_setting("snippets.indentation", """ 40 | { 41 | "title" : "Indentation Syntax Highlighting", 42 | "type" : "string", 43 | "default" : " ", 44 | "description" : "String to use for indentation in snippets (tip: to use a tab, copy/paste a tab from another text field and paste here)", 45 | "ignore" : ["SettingsProjectScope", "SettingsResourceScope"] 46 | } 47 | """) 48 | 49 | 50 | snippetPath = os.path.realpath(os.path.join(user_plugin_path(), "..", "snippets")) 51 | try: 52 | if not os.path.exists(snippetPath): 53 | os.mkdir(snippetPath) 54 | example_name = "update_example_snippets.py" 55 | dst_examples = os.path.join(snippetPath, example_name) 56 | rm_dst_examples = os.path.join(snippetPath, "." + example_name) 57 | src_examples = os.path.join(os.path.dirname(os.path.realpath(__file__)), example_name) 58 | if not os.path.exists(rm_dst_examples) and not os.path.exists(dst_examples): 59 | shutil.copy(src_examples, dst_examples) 60 | except IOError: 61 | log_error("Unable to create %s or unable to add example updater, please report this bug" % snippetPath) 62 | 63 | 64 | def includeWalk(dir, includeExt): 65 | filePaths = [] 66 | for (root, dirs, files) in os.walk(dir): 67 | for f in files: 68 | if os.path.splitext(f)[1] in includeExt and '.git' not in root: 69 | filePaths.append(os.path.join(root, f)) 70 | return filePaths 71 | 72 | 73 | def loadSnippetFromFile(snippetPath): 74 | try: 75 | with codecs.open(snippetPath, 'r', 'utf-8') as snippetFile: 76 | snippetText = snippetFile.readlines() 77 | except: 78 | return ("", "", "") 79 | if (len(snippetText) < 3): 80 | return ("", "", "") 81 | else: 82 | qKeySequence = QKeySequence(snippetText[1].strip()[1:]) 83 | if qKeySequence.isEmpty(): 84 | qKeySequence = None 85 | return (snippetText[0].strip()[1:].strip(), 86 | qKeySequence, 87 | ''.join(snippetText[2:]) 88 | ) 89 | 90 | 91 | def actionFromSnippet(snippetName, snippetDescription): 92 | if not snippetDescription: 93 | shortName = os.path.basename(snippetName) 94 | if shortName.endswith('.py'): 95 | shortName = shortName[:-3] 96 | return "Snippets\\" + shortName 97 | else: 98 | return "Snippets\\" + snippetDescription 99 | 100 | def setupGlobals(uiactioncontext, uicontext): 101 | snippetGlobals = {} 102 | snippetGlobals['current_view'] = uiactioncontext.binaryView 103 | snippetGlobals['bv'] = uiactioncontext.binaryView 104 | snippetGlobals['current_token'] = None 105 | snippetGlobals['current_hlil'] = None 106 | snippetGlobals['current_mlil'] = None 107 | snippetGlobals['current_function'] = None 108 | snippetGlobals['current_llil'] = None 109 | 110 | action_handler = None 111 | view_frame = None 112 | view = None 113 | if uicontext is not None: 114 | action_handler = uicontext.getCurrentActionHandler() 115 | view_frame = uicontext.getCurrentViewFrame() 116 | view = uicontext.getCurrentView() 117 | 118 | view_location = view_frame.getViewLocation() if view_frame is not None else None 119 | 120 | if view is not None: 121 | snippetGlobals['current_il_index'] = view.getSelectionStartILInstructionIndex() 122 | 123 | view_location = view_frame.getViewLocation() if view_frame is not None else None 124 | 125 | if uiactioncontext.function: 126 | snippetGlobals['current_function'] = uiactioncontext.function 127 | snippetGlobals['current_mlil'] = uiactioncontext.function.mlil_if_available 128 | snippetGlobals['current_hlil'] = uiactioncontext.function.hlil_if_available 129 | snippetGlobals['current_llil'] = uiactioncontext.function.llil_if_available 130 | if uiactioncontext.token: 131 | # Doubly nested because the first token is a HighlightTokenState 132 | snippetGlobals['current_token'] = uiactioncontext.token 133 | snippetGlobals['current_basic_block'] = uiactioncontext.function.get_basic_block_at(uiactioncontext.address) 134 | else: 135 | snippetGlobals['current_basic_block'] = None 136 | 137 | snippetGlobals['current_address'] = uiactioncontext.address 138 | if uiactioncontext.binaryView is not None and uiactioncontext.address is not None: 139 | snippetGlobals['current_raw_offset'] = uiactioncontext.binaryView.get_data_offset_for_address(uiactioncontext.address) 140 | else: 141 | snippetGlobals['current_raw_offset'] = None 142 | 143 | snippetGlobals['here'] = uiactioncontext.address 144 | if uiactioncontext.address is not None and isinstance(uiactioncontext.length, int): 145 | snippetGlobals['current_selection'] = (uiactioncontext.address, uiactioncontext.address+uiactioncontext.length) 146 | else: 147 | snippetGlobals['current_selection'] = None 148 | snippetGlobals['current_ui_action_context'] = uiactioncontext 149 | snippetGlobals['current_ui_context'] = uicontext 150 | 151 | if view_location is not None and view_location.isValid(): 152 | active_il_index = view_location.getInstrIndex() 153 | ilType = view_location.getILViewType() 154 | active_il_function = None 155 | if ilType == FunctionGraphType.LowLevelILFunctionGraph and uiactioncontext.function and uiactioncontext.function.llil_if_available: 156 | active_il_function = uiactioncontext.function.llil_if_available 157 | elif ilType == FunctionGraphType.LowLevelILSSAFormFunctionGraph and uiactioncontext.function and uiactioncontext.function.llil_if_available: 158 | active_il_function = uiactioncontext.function.llil_if_available.ssa_form 159 | elif ilType == FunctionGraphType.MediumLevelILFunctionGraph and uiactioncontext.function and uiactioncontext.function.mlil_if_available: 160 | active_il_function = uiactioncontext.function.mlil_if_available 161 | elif ilType == FunctionGraphType.MediumLevelILSSAFormFunctionGraph and uiactioncontext.function and uiactioncontext.function.mlil_if_available: 162 | active_il_function = uiactioncontext.function.mlil_if_available.ssa_form 163 | elif ilType == FunctionGraphType.HighLevelILFunctionGraph and uiactioncontext.function and uiactioncontext.function.hlil_if_available: 164 | active_il_function = uiactioncontext.function.hlil_if_available 165 | elif ilType == FunctionGraphType.HighLevelILSSAFormFunctionGraph and uiactioncontext.function and uiactioncontext.function.hlil_if_available: 166 | active_il_function = uiactioncontext.function.hlil_if_available.ssa_form 167 | 168 | if active_il_function: 169 | il_start = view.getSelectionStartILInstructionIndex() 170 | 171 | snippetGlobals['current_il_function'] = active_il_function 172 | if active_il_index == 0xffffffffffffffff: 173 | # Invalid index 174 | snippetGlobals['current_il_instruction'] = None 175 | snippetGlobals["current_il_basic_block"] = None 176 | snippetGlobals['current_il_instructions'] = None 177 | else: 178 | snippetGlobals['current_il_instruction'] = active_il_function[active_il_index] 179 | snippetGlobals["current_il_basic_block"] = active_il_function[active_il_index].il_basic_block 180 | snippetGlobals['current_il_instructions'] = (active_il_function[i] for i in range( 181 | min(il_start, active_il_index), 182 | max(il_start, active_il_index) + 1) 183 | ) 184 | else: 185 | snippetGlobals['current_il_function'] = None 186 | snippetGlobals['current_il_instruction'] = None 187 | snippetGlobals["current_il_basic_block"] = None 188 | snippetGlobals['current_il_instructions'] = None 189 | 190 | var = None 191 | if uiactioncontext is not None: 192 | token_state = uiactioncontext.token 193 | token = token_state.token if token_state.valid else None 194 | var = token_state.localVar if token_state.localVarValid else None 195 | if var and uiactioncontext.function: 196 | var = Variable.from_core_variable(uiactioncontext.function, var) 197 | 198 | snippetGlobals['current_variable'] = var 199 | snippetGlobals['current_token'] = token 200 | 201 | return snippetGlobals 202 | 203 | 204 | def executeSnippet(code, description): 205 | #Get UI context, try currently selected otherwise default to the first one if the snippet widget is selected. 206 | ctx = UIContext.activeContext() 207 | dummycontext = {'binaryView': None, 'address': None, 'function': None, 'token': None, 'lowLevelILFunction': None, 'mediumLevelILFunction': None} 208 | if not ctx: 209 | ctx = UIContext.allContexts()[0] 210 | if not ctx: 211 | #There is no tab open at all but we still want other snippest to run that don't rely on context. 212 | context = namedtuple("context", dummycontext.keys())(*dummycontext.values()) 213 | 214 | else: 215 | handler = ctx.contentActionHandler() 216 | if handler: 217 | context = handler.actionContext() 218 | else: 219 | context = namedtuple("context", dummycontext.keys())(*dummycontext.values()) 220 | 221 | snippetGlobals = setupGlobals(context, ctx) 222 | 223 | SnippetTask(code, snippetGlobals, context, snippetName=description).start() 224 | 225 | 226 | lastSnippet = None 227 | def makeSnippetFunction(snippet): 228 | def execute(): 229 | global lastSnippet 230 | lastSnippet = snippet 231 | 232 | (snippetDescription, snippetKeys, snippetCode) = loadSnippetFromFile(snippet) 233 | snippetCode = "# \n# \n" + snippetCode 234 | snippetCode = compile(snippetCode, snippet, 'exec') 235 | actionText = actionFromSnippet(snippet, snippetDescription) 236 | executeSnippet(snippetCode, actionText) 237 | return lambda context: execute() 238 | 239 | 240 | def rerunLastSnippet(context): 241 | global lastSnippet 242 | if lastSnippet is not None: 243 | makeSnippetFunction(lastSnippet)(context) 244 | 245 | 246 | # Global variable to indicate if analysis should be updated after a snippet is run 247 | gUpdateAnalysisOnRun = False 248 | 249 | class SnippetTask(BackgroundTaskThread): 250 | def __init__(self, code, snippetGlobals, context, snippetName="Executing snippet"): 251 | BackgroundTaskThread.__init__(self, f"{snippetName}...", False) 252 | self.code = code 253 | self.globals = snippetGlobals 254 | self.context = context 255 | 256 | def run(self): 257 | if self.context.binaryView: 258 | self.context.binaryView.begin_undo_actions() 259 | snippetGlobals = self.globals 260 | exec("from binaryninja import *", snippetGlobals) 261 | exec(self.code, snippetGlobals) 262 | if gUpdateAnalysisOnRun: 263 | exec("bv.update_analysis_and_wait()", snippetGlobals) 264 | if "here" in snippetGlobals and hasattr(self.context, "address") and snippetGlobals['here'] != self.context.address: 265 | self.context.binaryView.file.navigate(self.context.binaryView.file.view, snippetGlobals['here']) 266 | if "current_address" in snippetGlobals and hasattr(self.context, "address") and snippetGlobals['current_address'] != self.context.address: 267 | self.context.binaryView.file.navigate(self.context.binaryView.file.view, snippetGlobals['current_address']) 268 | if self.context.binaryView is not None and "current_raw_offset" in snippetGlobals and hasattr(self.context, "address") and snippetGlobals['current_raw_offset'] != self.context.binaryView.get_data_offset_for_address(self.context.address): 269 | addr = self.context.binaryView.get_address_for_data_offset(snippetGlobals["current_raw_offset"]) 270 | if addr is not None: 271 | if not self.context.binaryView.file.navigate(self.context.binaryView.file.view, addr): 272 | binaryninja.mainthread.execute_on_main_thread(lambda: self.locals["current_ui_context"].navigateForBinaryView(self.active_view, addr)) 273 | if self.context.binaryView: 274 | self.context.binaryView.commit_undo_actions() 275 | 276 | 277 | class Snippets(QDialog): 278 | 279 | def __init__(self, context, parent=None): 280 | super(Snippets, self).__init__(parent) 281 | # Create widgets 282 | self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint) 283 | self.title = QLabel(self.tr("Snippet Editor")) 284 | self.saveButton = QPushButton(self.tr("&Save")) 285 | self.saveButton.setShortcut(QKeySequence(self.tr("Ctrl+Shift+S"))) 286 | self.exportButton = QPushButton(self.tr("&Export to plugin")) 287 | self.exportButton.setShortcut(QKeySequence(self.tr("Ctrl+E"))) 288 | self.runButton = QPushButton(self.tr("&Run")) 289 | self.runButton.setShortcut(QKeySequence(self.tr("Ctrl+R"))) 290 | self.editButton = QPushButton(self.tr("Open in Editor")) 291 | self.updateAnalysis = QCheckBox(self.tr("Update analysis when run")) 292 | self.clearHotkeyButton = QPushButton(self.tr("Clear Hotkey")) 293 | self.updateAnalysis.stateChanged.connect(self.setGlobalUpdateFlag) 294 | self.setWindowTitle(self.title.text()) 295 | #self.newFolderButton = QPushButton("New Folder") 296 | self.browseButton = QPushButton("Browse Snippets") 297 | self.browseButton.setIcon(QIcon.fromTheme("edit-undo")) 298 | self.deleteSnippetButton = QPushButton("Delete") 299 | self.newSnippetButton = QPushButton("New Snippet") 300 | self.watcher = QFileSystemWatcher() 301 | self.watcher.addPath(snippetPath) 302 | self.watcher.directoryChanged.connect(self.snippetDirectoryChanged) 303 | self.watcher.fileChanged.connect(self.snippetDirectoryChanged) 304 | indentation = Settings().get_string("snippets.indentation") 305 | if Settings().get_bool("snippets.syntaxHighlight"): 306 | self.edit = QCodeEditor(SyntaxHighlighter=Pylighter, delimeter = indentation) 307 | else: 308 | self.edit = QCodeEditor(SyntaxHighlighter=None, delimeter = indentation) 309 | self.edit.setPlaceholderText("python code") 310 | self.resetting = False 311 | self.columns = 3 312 | self.context = context 313 | 314 | self.keySequenceEdit = QKeySequenceEdit(self) 315 | self.currentHotkey = QKeySequence() 316 | self.currentHotkeyLabel = QLabel("") 317 | self.currentFile = "" 318 | self.snippetName = QLineEdit() 319 | self.snippetName.setPlaceholderText("snippet filename") 320 | self.snippetDescription = QLineEdit() 321 | self.snippetDescription.setPlaceholderText("optional description") 322 | 323 | #Make disabled edit boxes visually distinct 324 | self.setStyleSheet("QLineEdit:disabled, QCodeEditor:disabled { background-color: palette(window); }"); 325 | 326 | 327 | #Set Editbox Size 328 | font = getMonospaceFont(self) 329 | self.edit.setFont(font) 330 | font = QFontMetrics(font) 331 | self.edit.setTabStopDistance(4 * font.horizontalAdvance(' ')) #TODO, replace with settings API 332 | self.edit.minimumHeight = font.height() * 20 333 | 334 | #Files 335 | self.files = QFileSystemModel() 336 | self.files.setRootPath(snippetPath) 337 | self.files.setReadOnly(False) 338 | 339 | #Tree 340 | self.tree = QTreeView() 341 | self.tree.setModel(self.files) 342 | self.tree.setDragDropMode(QAbstractItemView.InternalMove) 343 | self.tree.setDragEnabled(True) 344 | self.tree.setDefaultDropAction(Qt.MoveAction) 345 | self.tree.setSortingEnabled(True) 346 | self.tree.setContextMenuPolicy(Qt.CustomContextMenu) 347 | self.tree.customContextMenuRequested.connect(self.contextMenu) 348 | self.tree.hideColumn(2) 349 | self.tree.sortByColumn(0, Qt.AscendingOrder) 350 | self.tree.setRootIndex(self.files.index(snippetPath)) 351 | for x in range(self.columns): 352 | #self.tree.resizeColumnToContents(x) 353 | self.tree.header().setSectionResizeMode(x, QHeaderView.ResizeToContents) 354 | treeLayout = QVBoxLayout() 355 | treeLayout.addWidget(self.tree) 356 | treeButtons = QHBoxLayout() 357 | treeButtons.addWidget(self.browseButton) 358 | treeButtons.addWidget(self.newSnippetButton) 359 | treeButtons.addWidget(self.deleteSnippetButton) 360 | treeLayout.addLayout(treeButtons) 361 | treeWidget = QWidget() 362 | treeWidget.setLayout(treeLayout) 363 | 364 | # Create layout and add widgets 365 | optionsAndButtons = QVBoxLayout() 366 | 367 | options = QHBoxLayout() 368 | options.addWidget(self.clearHotkeyButton) 369 | options.addWidget(self.keySequenceEdit) 370 | options.addWidget(self.currentHotkeyLabel) 371 | options.addWidget(self.updateAnalysis) 372 | 373 | buttons = QHBoxLayout() 374 | buttons.addWidget(self.exportButton) 375 | buttons.addWidget(self.editButton) 376 | buttons.addWidget(self.runButton) 377 | buttons.addWidget(self.saveButton) 378 | 379 | optionsAndButtons.addLayout(options) 380 | optionsAndButtons.addLayout(buttons) 381 | 382 | description = QHBoxLayout() 383 | description.addWidget(QLabel(self.tr("Filename: "))) 384 | description.addWidget(self.snippetName) 385 | description.addWidget(QLabel(self.tr("Description: "))) 386 | description.addWidget(self.snippetDescription) 387 | 388 | vlayoutWidget = QWidget() 389 | vlayout = QVBoxLayout() 390 | vlayout.addLayout(description) 391 | vlayout.addWidget(self.edit) 392 | vlayout.addLayout(optionsAndButtons) 393 | vlayoutWidget.setLayout(vlayout) 394 | 395 | hsplitter = QSplitter() 396 | hsplitter.addWidget(treeWidget) 397 | hsplitter.addWidget(vlayoutWidget) 398 | 399 | hlayout = QHBoxLayout() 400 | hlayout.addWidget(hsplitter) 401 | 402 | self.showNormal() #Fixes bug that maximized windows are "stuck" 403 | #Because you can't trust QT to do the right thing here 404 | if (sys.platform == "darwin"): 405 | self.settings = QSettings("Vector35", "Snippet Editor") 406 | else: 407 | self.settings = QSettings("Vector 35", "Snippet Editor") 408 | if self.settings.contains("ui/snippeteditor/geometry"): 409 | self.restoreGeometry(self.settings.value("ui/snippeteditor/geometry")) 410 | else: 411 | self.edit.setMinimumWidth(80 * font.averageCharWidth()) 412 | self.edit.setMinimumHeight(30 * font.lineSpacing()) 413 | 414 | # Set dialog layout 415 | self.setLayout(hlayout) 416 | 417 | # Add signals 418 | self.saveButton.clicked.connect(self.save) 419 | self.editButton.clicked.connect(self.editor) 420 | self.runButton.clicked.connect(self.run) 421 | self.exportButton.clicked.connect(self.export) 422 | self.clearHotkeyButton.clicked.connect(self.clearHotkey) 423 | self.tree.selectionModel().selectionChanged.connect(self.selectFile) 424 | self.newSnippetButton.clicked.connect(self.newFileDialog) 425 | self.deleteSnippetButton.clicked.connect(self.deleteSnippet) 426 | self.browseButton.clicked.connect(self.browseSnippets) 427 | 428 | if self.settings.contains("ui/snippeteditor/selected"): 429 | selectedName = self.settings.value("ui/snippeteditor/selected") 430 | self.tree.selectionModel().select(self.files.index(selectedName), QItemSelectionModel.ClearAndSelect | QItemSelectionModel.Rows) 431 | if self.tree.selectionModel().hasSelection(): 432 | self.selectFile(self.tree.selectionModel().selection(), None) 433 | self.edit.setFocus() 434 | cursor = self.edit.textCursor() 435 | cursor.setPosition(self.edit.document().characterCount()-1) 436 | self.edit.setTextCursor(cursor) 437 | else: 438 | self.readOnly(True) 439 | else: 440 | self.readOnly(True) 441 | 442 | def setGlobalUpdateFlag(self): 443 | """Update the "update analysis after run?" global variable.""" 444 | global gUpdateAnalysisOnRun 445 | gUpdateAnalysisOnRun = self.updateAnalysis.isChecked() 446 | 447 | @staticmethod 448 | def registerAllSnippets(): 449 | for action in list(filter(lambda x: x.startswith("Snippets\\"), UIAction.getAllRegisteredActions())): 450 | if action in ["Snippets\\Snippet Editor...", "Snippets\\Reload All Snippets"]: 451 | continue 452 | UIActionHandler.globalActions().unbindAction(action) 453 | Menu.mainMenu("Plugins").removeAction(action) 454 | UIAction.unregisterAction(action) 455 | 456 | for snippet in includeWalk(snippetPath, ".py"): 457 | snippetKeys = None 458 | (snippetDescription, snippetKeys, snippetCode) = loadSnippetFromFile(snippet) 459 | actionText = actionFromSnippet(snippet, snippetDescription) 460 | if snippetCode: 461 | if snippetKeys == None: 462 | UIAction.registerAction(actionText) 463 | else: 464 | UIAction.registerAction(actionText, snippetKeys) 465 | UIActionHandler.globalActions().bindAction(actionText, UIAction(makeSnippetFunction(snippet))) 466 | Menu.mainMenu("Plugins").addAction(actionText, "Snippets") 467 | 468 | def clearSelection(self): 469 | self.keySequenceEdit.clear() 470 | self.currentHotkey = QKeySequence() 471 | self.currentHotkeyLabel.setText("") 472 | self.snippetName.setText("") 473 | self.snippetDescription.setText("") 474 | self.edit.clear() 475 | self.watcher.removePath(self.currentFile) 476 | self.currentFile = "" 477 | 478 | def askSave(self): 479 | return QMessageBox.question(self, self.tr("Save?"), self.tr("Do you want to save changes to:\n\n{}?").format(self.snippetName.text()), QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel) 480 | 481 | def reject(self): 482 | self.settings.setValue("ui/snippeteditor/geometry", self.saveGeometry()) 483 | 484 | if self.snippetChanged(): 485 | save = self.askSave() 486 | if save == QMessageBox.Yes: 487 | self.save() 488 | elif save == QMessageBox.No: 489 | self.loadSnippet() 490 | elif save == QMessageBox.Cancel: 491 | return 492 | self.accept() 493 | 494 | def browseSnippets(self): 495 | url = QUrl.fromLocalFile(snippetPath) 496 | QDesktopServices.openUrl(url) 497 | 498 | def newFolder(self): 499 | (folderName, ok) = QInputDialog.getText(self, self.tr("Folder Name"), self.tr("Folder Name: ")) 500 | if ok and folderName: 501 | index = self.tree.selectionModel().currentIndex() 502 | selection = self.files.filePath(index) 503 | if QFileInfo(selection).isDir(): 504 | QDir(selection).mkdir(folderName) 505 | else: 506 | QDir(snippetPath).mkdir(folderName) 507 | 508 | def copyPath(self): 509 | index = self.tree.selectionModel().currentIndex() 510 | selection = self.files.filePath(index) 511 | clip = QGuiApplication.clipboard() 512 | clip.setText(selection) 513 | 514 | def selectFile(self, new, old): 515 | if (self.resetting): 516 | self.resetting = False 517 | return 518 | if len(new.indexes()) == 0: 519 | self.clearSelection() 520 | self.readOnly(True) 521 | return 522 | newSelection = self.files.filePath(new.indexes()[0]) 523 | self.settings.setValue("ui/snippeteditor/selected", newSelection) 524 | if QFileInfo(newSelection).isDir(): 525 | self.clearSelection() 526 | self.readOnly(True) 527 | return 528 | 529 | if old and old.length() > 0: 530 | oldSelection = self.files.filePath(old.indexes()[0]) 531 | if not QFileInfo(oldSelection).isDir() and self.snippetChanged(): 532 | save = self.askSave() 533 | if save == QMessageBox.Yes: 534 | self.save() 535 | elif save == QMessageBox.No: 536 | pass 537 | elif save == QMessageBox.Cancel: 538 | self.resetting = True 539 | self.tree.selectionModel().select(old, QItemSelectionModel.ClearAndSelect | QItemSelectionModel.Rows) 540 | return False 541 | 542 | if self.currentFile: 543 | self.watcher.removePath(self.currentFile) 544 | self.currentFile = newSelection 545 | self.watcher.addPath(self.currentFile) 546 | self.loadSnippet() 547 | 548 | def loadSnippet(self): 549 | (snippetDescription, snippetKeys, snippetCode) = loadSnippetFromFile(self.currentFile) 550 | self.snippetName.setText(os.path.basename(self.currentFile)) 551 | self.snippetDescription.setText(snippetDescription) if snippetDescription else self.snippetDescription.setText("") 552 | self.keySequenceEdit.setKeySequence(snippetKeys) if snippetKeys else self.keySequenceEdit.setKeySequence(QKeySequence("")) 553 | delimeter = " " if snippetCode.count(" ") > snippetCode.count("\t") else "\t" 554 | self.edit.setPlainText(snippetCode) if snippetCode else self.edit.setPlainText("") 555 | self.edit.setDelimeter(delimeter) 556 | self.readOnly(False) 557 | 558 | def newFileDialog(self): 559 | (snippetName, ok) = QInputDialog.getText(self, self.tr("Snippet Name"), self.tr("Snippet Name: "), flags=self.windowFlags()) 560 | if ok and snippetName: 561 | if not snippetName.endswith(".py"): 562 | snippetName += ".py" 563 | index = self.tree.selectionModel().currentIndex() 564 | selection = self.files.filePath(index) 565 | if QFileInfo(selection).isDir(): 566 | path = os.path.join(selection, snippetName) 567 | else: 568 | path = os.path.join(snippetPath, snippetName) 569 | self.readOnly(False) 570 | open(path, "w").close() 571 | self.tree.setCurrentIndex(self.files.index(path)) 572 | log_debug("Snippets: Snippet %s created." % snippetName) 573 | 574 | def readOnly(self, flag): 575 | self.keySequenceEdit.setEnabled(not flag) 576 | self.snippetDescription.setReadOnly(flag) 577 | self.snippetName.setReadOnly(flag) 578 | self.edit.setReadOnly(flag) 579 | if flag: 580 | self.snippetDescription.setDisabled(True) 581 | self.snippetName.setDisabled(True) 582 | self.edit.setDisabled(True) 583 | else: 584 | self.snippetDescription.setEnabled(True) 585 | self.snippetName.setEnabled(True) 586 | self.edit.setEnabled(True) 587 | 588 | def deleteSnippet(self): 589 | selection = self.tree.selectedIndexes()[::self.columns][0] #treeview returns each selected element in the row 590 | snippetName = self.files.fileName(selection) 591 | if self.files.isDir(selection): 592 | questionText = self.tr("Confirm deletion of folder AND ALL CONTENTS: ") 593 | else: 594 | questionText = self.tr("Confirm deletion of snippet: ") 595 | question = QMessageBox.question(self, self.tr("Confirm"), questionText + snippetName) 596 | if (question == QMessageBox.StandardButton.Yes): 597 | log_debug("Snippets: Deleting %s." % snippetName) 598 | self.clearSelection() 599 | if snippetName == example_name: 600 | question = QMessageBox.question(self, self.tr("Confirm"), self.tr("Should snippets prevent this file from being recreated?")) 601 | if (question == QMessageBox.StandardButton.Yes): 602 | Path(rm_dst_examples).touch() 603 | self.files.remove(selection) 604 | self.registerAllSnippets() 605 | 606 | def duplicateSnippet(self): 607 | selection = self.tree.selectedIndexes()[::self.columns][0] #treeview returns each selected element in the row 608 | snippetName = self.files.fileName(selection) 609 | (newname, ok) = QInputDialog.getText(self, self.tr("New Snippet Name"), self.tr("New Snippet Name:")) 610 | if ok and snippetName: 611 | (snippetDescription, snippetKeys, snippetCode) = loadSnippetFromFile(self.currentFile) 612 | if not snippetName.endswith(".py"): 613 | snippetName += ".py" 614 | index = self.tree.selectionModel().currentIndex() 615 | selection = self.files.filePath(index) 616 | if QFileInfo(selection).isDir(): 617 | path = os.path.join(selection, snippetName) 618 | else: 619 | path = os.path.join(snippetPath, snippetName) 620 | self.readOnly(False) 621 | open(path, "w").close() 622 | self.snippetName.setText(os.path.basename(self.currentFile)) 623 | self.snippetDescription.setText(snippetDescription) if snippetDescription else self.snippetDescription.setText("") 624 | self.keySequenceEdit.setKeySequence(snippetKeys) if snippetKeys else self.keySequenceEdit.setKeySequence(QKeySequence("")) 625 | self.edit.setPlainText(snippetCode) if snippetCode else self.edit.setPlainText("") 626 | self.save() 627 | self.tree.setCurrentIndex(self.files.index(path)) 628 | self.registerAllSnippets() 629 | 630 | def snippetDirectoryChanged(self): 631 | # reload UI and reload snippets 632 | self.registerAllSnippets() 633 | self.loadSnippet() 634 | 635 | def snippetChanged(self): 636 | if (self.currentFile == "" or QFileInfo(self.currentFile).isDir()): 637 | return False 638 | (snippetDescription, snippetKeys, snippetCode) = loadSnippetFromFile(self.currentFile) 639 | if os.path.basename(self.currentFile) != self.snippetName.text(): 640 | return True 641 | if snippetKeys == None and not self.keySequenceEdit.keySequence().isEmpty(): 642 | return True 643 | if snippetKeys != None and snippetKeys != self.keySequenceEdit.keySequence().toString(): 644 | return True 645 | return self.edit.toPlainText() != snippetCode or \ 646 | self.snippetDescription.text() != snippetDescription 647 | 648 | def save(self): 649 | if os.path.basename(self.currentFile) != self.snippetName: 650 | #Renamed 651 | if not self.snippetName.text().endswith(".py") and not QMessageBox.question(self, self.tr("Rename?"), self.tr("Are you sure you want to rename?\n\n{} does not end in .py and you will not be able to rename back with snippets.").format(self.snippetName.text()), QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel) == QMessageBox.Yes: 652 | return 653 | os.unlink(self.currentFile) 654 | self.currentFile = os.path.join(os.path.dirname(self.currentFile), self.snippetName.text()) 655 | log_debug("Snippets: Saving snippet %s" % self.currentFile) 656 | outputSnippet = codecs.open(self.currentFile, "w", "utf-8") 657 | outputSnippet.write("#" + self.snippetDescription.text() + "\n") 658 | outputSnippet.write("#" + self.keySequenceEdit.keySequence().toString() + "\n") 659 | outputSnippet.write(self.edit.toPlainText()) 660 | outputSnippet.close() 661 | # Redundant because of file watcher 662 | #self.registerAllSnippets() 663 | 664 | def editor(self): 665 | # Open in external editor 666 | path = QUrl.fromLocalFile(self.currentFile) 667 | QDesktopServices.openUrl(path) 668 | 669 | def run(self): 670 | if self.context == None: 671 | log_warn("Cannot run snippets outside of the UI at this time.") 672 | return 673 | if self.snippetChanged(): 674 | self.save() 675 | actionText = actionFromSnippet(self.currentFile, self.snippetDescription.text()) 676 | UIActionHandler.globalActions().executeAction(actionText, self.context) 677 | 678 | self.save() 679 | self.registerAllSnippets() 680 | 681 | def export(self): 682 | if self.snippetChanged(): 683 | save = self.askSave() 684 | if save == QMessageBox.Yes: 685 | self.save() 686 | elif save == QMessageBox.No: 687 | self.loadSnippet() 688 | elif save == QMessageBox.Cancel: 689 | return 690 | 691 | folder = get_directory_name_input("Where would you like the plugin saved?", user_plugin_path()) 692 | 693 | if self.snippetName.text() == "": 694 | log_alert("Snippets must have a name") 695 | return 696 | 697 | name = self.snippetName.text() 698 | if name.endswith('.py'): 699 | name = name[:-3] 700 | 701 | if self.snippetDescription.text() == "": 702 | description = name 703 | else: 704 | description = self.snippetDescription.text() 705 | 706 | user = getpass.getuser() 707 | version = "2846" 708 | if core_version().count('.') == 2: 709 | version = core_version()[core_version().rfind('.')+1:core_version().rfind('.')+5] 710 | candidate = os.path.join(folder, name) 711 | 712 | if os.path.exists(candidate): 713 | overwrite = QMessageBox.question(self, self.tr("Folder already exists"), self.tr(f"That folder already exists, do you want to remove the folder first?\n{candidate}"), QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel) 714 | if overwrite == QMessageBox.Yes: 715 | log_debug("Snippets: Aborting export due to existing folder.") 716 | shutil.rmtree(candidate) 717 | self.save() 718 | elif overwrite == QMessageBox.Cancel: 719 | log_debug("Snippets: Aborting export due to existing folder.") 720 | return 721 | os.mkdir(candidate) 722 | 723 | #If no, continue just overwriting individual files. 724 | #TODO: License chooser from drop-down 725 | licenseText = f'''Copyright (c) {datetime.now().year} <{user}> 726 | 727 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 728 | 729 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 730 | 731 | THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 732 | ''' 733 | with open(os.path.join(candidate, "plugin.json"), 'w', encoding='utf8') as pluginjson: 734 | #not using f strings 'cause json isn't great for that 735 | pluginjson.write('''{ 736 | "pluginmetadataversion": 2, 737 | "name": "''' + name + '''", 738 | "type": [ 739 | "core", 740 | "ui", 741 | "architecture", 742 | "binaryview", 743 | "helper" 744 | ], 745 | "api": [ 746 | "python3" 747 | ], 748 | "description": "''' + description + '''", 749 | "longdescription": "", 750 | "license": { 751 | "name": "MIT", 752 | "text": "''' + licenseText.replace("\n", "\\n") + '''" 753 | }, 754 | "platforms": [ 755 | "Darwin", 756 | "Linux", 757 | "Windows" 758 | ], 759 | "installinstructions": { 760 | "Darwin": "", 761 | "Linux": "", 762 | "Windows": "" 763 | }, 764 | "dependencies": { 765 | }, 766 | "version": "1.0.0", 767 | "author": "''' + user + '''", 768 | "minimumbinaryninjaversion": ''' + version + ''' 769 | } 770 | ''') 771 | with open(os.path.join(candidate, "LICENSE"), 'w') as license: 772 | license.write(licenseText) 773 | 774 | #TODO: Optionally export plugin as UIPlugin with helpers established if 775 | #current_* appears anywhere in it 776 | with open(os.path.join(candidate, "__init__.py"), 'w', encoding='utf8') as initpy: 777 | if self.edit.toPlainText().count("\t") > self.edit.toPlainText().count(" "): 778 | delim = "\t" 779 | else: 780 | delim = " " #not going to be any fancier than this for now, you get two choices 781 | pluginCode = delim + f'\n{delim}'.join(self.edit.toPlainText().split('\n')) 782 | if self.updateAnalysis.isChecked(): 783 | update = f"{delim}bv.update_analysis_and_wait()" 784 | else: 785 | update = "" 786 | initpy.write(f"""from binaryninja import * 787 | 788 | # Note that this is a sample plugin and you may need to manually edit it with 789 | # additional functionality. In particular, this example only passes in the 790 | # binary view. If you would like to act on an addres or function you should 791 | # consider using other register_for* functions. 792 | 793 | # Add documentation about UI plugin alternatives and potentially getting 794 | # current_* functions 795 | 796 | def main(bv): 797 | {pluginCode} 798 | {update} 799 | 800 | PluginCommand.register('{name}', '{description}', main) 801 | 802 | """) 803 | #TODO: Export README 804 | 805 | longdescription='Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' 806 | with open(os.path.join(candidate, "README.md"), 'w') as readme: 807 | readme.write(f'''# {name} 808 | Author: **{user}** 809 | 810 | _{description}_ 811 | 812 | ## Description: 813 | 814 | {longdescription} 815 | 816 | ## Minimum Version 817 | 818 | {version} 819 | 820 | ## License 821 | 822 | This plugin is released under an [MIT license](./LICENSE). 823 | 824 | ## Metadata Version 825 | 826 | 2''') 827 | 828 | 829 | url = QUrl.fromLocalFile(candidate) 830 | QDesktopServices.openUrl(url) 831 | 832 | def clearHotkey(self): 833 | self.keySequenceEdit.clear() 834 | 835 | def contextMenu(self, position): 836 | menu = QMenu() 837 | delete = menu.addAction("Delete") 838 | delete.triggered.connect(self.deleteSnippet) 839 | duplicate = menu.addAction("Duplicate") 840 | duplicate.triggered.connect(self.duplicateSnippet) 841 | newFolder = menu.addAction("New Folder") 842 | newFolder.triggered.connect(self.newFolder) 843 | copyPath = menu.addAction("Copy Path") 844 | copyPath.triggered.connect(self.copyPath) 845 | menu.exec_(QCursor.pos()) 846 | 847 | 848 | snippets = None 849 | 850 | def reloadActions(_): 851 | Snippets.registerAllSnippets() 852 | 853 | def launchPlugin(context): 854 | global snippets 855 | # Terrible hack to fix Shiboken freeing the object when snippets 856 | # is launched after a binary view is open instead of before 857 | # TODO: Fix this properly 858 | if snippets: 859 | try: 860 | snippets.close() 861 | except: 862 | snippets = Snippets(context, parent=context.widget) 863 | else: 864 | snippets = Snippets(context, parent=context.widget) 865 | snippets.show() 866 | 867 | Snippets.registerAllSnippets() 868 | UIAction.registerAction("Snippets\\Snippet Editor...") 869 | UIAction.registerAction("Snippets\\Rerun Last Snippet") 870 | UIAction.registerAction("Snippets\\Reload All Snippets") 871 | UIActionHandler.globalActions().bindAction("Snippets\\Snippet Editor...", UIAction(launchPlugin)) 872 | UIActionHandler.globalActions().bindAction("Snippets\\Rerun Last Snippet", UIAction(rerunLastSnippet)) 873 | UIActionHandler.globalActions().bindAction("Snippets\\Reload All Snippets", UIAction(reloadActions)) 874 | Menu.mainMenu("Plugins").addAction("Snippets\\Snippet Editor...", "Snippet") 875 | Menu.mainMenu("Plugins").addAction("Snippets\\Rerun Last Snippet", "Snippet") 876 | Menu.mainMenu("Plugins").addAction("Snippets\\Reload All Snippets", "Snippet") 877 | -------------------------------------------------------------------------------- /do_release.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | #Little utility to automatically do a new release. 3 | from git import Repo 4 | from json import load, dump 5 | from github_release import gh_release_create 6 | from sys import exit 7 | from os import path 8 | from argparse import ArgumentParser 9 | from subprocess import run 10 | '''WARNING: IF YOU DO NOT UPDATE YOUR README.md USING generate_plugininfo.py 11 | THIS PLUGIN WILL OVERWRITE IT!''' 12 | 13 | parser = ArgumentParser() 14 | parser.add_argument("-d", "--description", help="Description for the new release", action="store", dest="description", default="") 15 | parser.add_argument("-v", "--version", help="New version string", action="store", dest="new_version", default="") 16 | parser.add_argument("--force", help="Override the repository dirty check", action="store_true", dest="dirtyoverride", default=False) 17 | args = parser.parse_args() 18 | #TODO 19 | 20 | repo = Repo(".") 21 | reponame = list(repo.remotes.origin.urls)[0].split(':')[1].split('.')[0] 22 | if repo.is_dirty() and not args.dirtyoverride: 23 | print("Cowardly refusing to do anything as the plugin repository is currently dirty.") 24 | exit(-1) 25 | 26 | if not path.isfile("./generate_plugininfo.py"): 27 | print("Missing ./generate_plugininfo.py.") 28 | exit(-1) 29 | 30 | with open('plugin.json') as plugin: 31 | data = load(plugin) 32 | 33 | def update_version(data): 34 | print(f"Updating plugin with new version {data['version']}") 35 | with open('plugin.json', 'w') as plugin: 36 | dump(data, plugin) 37 | run(["./generate_plugininfo.py", "-r", "-f"], check=True) 38 | repo.index.add('plugin.json') 39 | repo.index.add('README.md') 40 | if args.description == "": 41 | repo.index.commit(f"Updating to {data['version']}") 42 | else: 43 | repo.index.commit(args.description) 44 | repo.git.push('origin') 45 | 46 | for tag in repo.tags: 47 | if tag.name == data['version']: 48 | if args.new_version == "": 49 | print(f"Current plugin version {data['version']} is already a tag. Shall I increment it for you?") 50 | yn = input("[y/n]: ") 51 | if yn == "Y" or yn == "y": 52 | digits = data['version'].split('.') 53 | newlast = str(int(digits[-1])+1) 54 | digits[-1] = newlast 55 | inc_version = '.'.join(digits) 56 | data['version'] = inc_version 57 | update_version(data) 58 | else: 59 | print("Stopping...") 60 | exit(-1) 61 | else: 62 | data['version'] = args.new_version 63 | update_version(data) 64 | 65 | # Create new tag 66 | new_tag = repo.create_tag(data['version']) 67 | # Push 68 | repo.remotes.origin.push(data['version']) 69 | # Create release 70 | gh_release_create(reponame, data['version'], publish=True, name="%s v%s" % (data['name'], data['version'])) 71 | -------------------------------------------------------------------------------- /generate_plugininfo.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | This script helps in the process of creating required metadata to add a plugin to the Binary Ninja plugin repository 4 | """ 5 | import json 6 | import argparse 7 | import os 8 | import sys 9 | import io 10 | import datetime 11 | import pprint 12 | import tempfile 13 | from builtins import input 14 | import sys, tempfile, os 15 | from subprocess import call 16 | 17 | currentpluginmetadataversion = 2 18 | 19 | # def getEditorData(message): 20 | # EDITOR = os.environ.get('EDITOR','vim') 21 | 22 | # initial_message = message 23 | # edited_message = "" 24 | # with tempfile.NamedTemporaryFile(suffix=".tmp") as tf: 25 | # tf.write(initial_message.encode("utf-8")) 26 | # tf.flush() 27 | # call([EDITOR, tf.name]) 28 | 29 | # tf.seek(0) 30 | # edited_message = tf.read().decode("utf-8") 31 | # return edited_message 32 | 33 | validPluginTypes = ["core", "ui", "binaryview", "architecture", "helper"] 34 | validApis = ["python2", "python3"] 35 | validPlatforms = ["Darwin", "Windows", "Linux"] 36 | requiredLicenseKeys = ["name", "text"] 37 | 38 | def validateList(data, name, validList): 39 | if name not in data: 40 | print("Warning: '{}' field doesn't exist".format(name)) 41 | return False 42 | elif not isinstance(data[name], list): 43 | print("Error: '{}' field isn't a list".format(name)) 44 | return False 45 | 46 | success = True 47 | for item in data[name]: 48 | if item not in validList: 49 | print("Error: plugin {}: {} not one of {}".format(name, item, validList)) 50 | success = False 51 | return success 52 | 53 | def validateString(data, name): 54 | if name not in data: 55 | print("Error: '{}' field doesn't exist".format(name)) 56 | return False 57 | elif type(data[name]).__name__ not in ("unicode", "str"): # a python 2/3 compliant check for string type 58 | print("Error: '{}' field is {} not a string".format(name, type(data[name]))) 59 | return False 60 | return True 61 | 62 | def validateInteger(data, name): 63 | if name not in data: 64 | print("Error: '{}' field doesn't exist.".format(name)) 65 | return False 66 | elif not isinstance(data[name], int): 67 | print("Error: '{}' is {} not an integer value".format(name, type(data[name]))) 68 | return False 69 | return True 70 | 71 | def validateStringMap(data, name, validKeys, requiredKeys=None): 72 | if name not in data: 73 | print("Error: '{}' field doesn't exist.".format(name)) 74 | return False 75 | elif not isinstance(data[name], dict): 76 | print("Error: '{}' is {} not a dict type".format(name, type(data[name]))) 77 | return False 78 | 79 | success = True 80 | if requiredKeys is not None: 81 | for key in requiredKeys: 82 | if key not in data[name]: 83 | print("Error: required subkey '{}' not in {}".format(key, name)) 84 | success = False 85 | 86 | for key in data[name].keys(): 87 | if key not in validKeys: 88 | print("Error: key '{}' not is not in the set of valid keys {}".format(key, validKeys)) 89 | success = False 90 | 91 | return success 92 | 93 | def validateRequiredFields(data): 94 | success = validateInteger(data, "pluginmetadataversion") 95 | if success: 96 | if data["pluginmetadataversion"] != currentpluginmetadataversion: 97 | print("Error: 'pluginmetadataversion' is not the correct version") 98 | success = False 99 | else: 100 | print("Current version is {}".format(currentpluginmetadataversion)) 101 | 102 | success &= validateString(data, "name") 103 | success &= validateList(data, "type", validPluginTypes) 104 | success &= validateList(data, "api", validApis) 105 | success &= validateString(data, "description") 106 | success &= validateString(data, "longdescription") 107 | success &= validateStringMap(data, "license", requiredLicenseKeys, requiredLicenseKeys) 108 | validPlatformList = validateList(data, "platforms", validPlatforms) 109 | success &= validPlatformList 110 | success &= validateStringMap(data, "installinstructions", validPlatforms, list(data["platforms"]) if validPlatformList else None) 111 | success &= validateString(data, "version") 112 | success &= validateString(data, "author") 113 | success &= validateInteger(data, "minimumbinaryninjaversion") 114 | return success 115 | 116 | def getCombinationSelection(validList, prompt, maxItems=None): 117 | if maxItems == None: 118 | maxItems = len(validList) 119 | 120 | prompt2 = "Enter comma separated list of items> " 121 | if maxItems == 1: 122 | prompt2 = "> " 123 | while True: 124 | print(prompt) 125 | for i, item in enumerate(validList): 126 | print("\t{:>3}: {}".format(i, item)) 127 | items = filter(None, input(prompt2).split(",")) 128 | result = [] 129 | success = True 130 | for item in items: 131 | try: 132 | value = int(item.strip()) 133 | except ValueError: 134 | print("Couldn't convert {} to integer".format(item)) 135 | success = False 136 | break 137 | if value < 0 or value >= len(validList): 138 | print("{} is not a valid selection".format(value)) 139 | success = False 140 | break 141 | else: 142 | result.append(validList[value]) 143 | if success: 144 | return result 145 | 146 | licenseTypes = { 147 | "MIT" : """Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.""", 148 | "2-Clause BSD" : """Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.""", 149 | "Apache-2.0" : """Licensed 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.""", 150 | "LGPL-2.0" : """This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA""", 151 | "LGPL-2.1" : """This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA""", 152 | "LGPL-3.0" : """This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA""", 153 | "GPL-2.0" : """This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with this program; if not, see .""", 154 | "GPL-3.0" : """This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with this program. If not, see .""" 155 | } 156 | 157 | def generatepluginmetadata(): 158 | data = {} 159 | data["pluginmetadataversion"] = 2 160 | data["name"] = input("Enter plugin name: ") 161 | data["author"] = input("Enter your name or the name you want this plugin listed under: ") 162 | data["type"] = getCombinationSelection(validPluginTypes, "Which types of plugin is this? ") 163 | data["api"] = getCombinationSelection(validApis, "Which api's are supported? ") 164 | data["description"] = input("Enter a short description of this plugin (50 characters max): ") 165 | data["longdescription"] = input("Enter a full description of this plugin (Markdown formatted): ") 166 | data["license"] = {} 167 | 168 | licenseTypeNames = ["Other"] 169 | licenseTypeNames.extend(licenseTypes.keys()) 170 | data["license"]["name"] = getCombinationSelection(licenseTypeNames, "Enter the license type of this plugin:", 1)[0] 171 | if data["license"]["name"] == "Other": 172 | data["license"]["name"] = input("Enter License Type: ") 173 | data["license"]["text"] = input("Enter License Text: ") 174 | else: 175 | data["license"]["text"] = licenseTypes[data["license"]["name"]] 176 | 177 | year = datetime.datetime.now().year 178 | holder = data["author"] 179 | 180 | answer = input("Is this the correct copyrigtht information?\n\tCopyright {year} {holder}\n[Y/n]: ".format(year=year, holder=holder)) 181 | if answer not in ("Y", "y", ""): 182 | year = input("Enter copyright year: ") 183 | holder = input("Enter copyright holder: ") 184 | 185 | data["license"]["text"] = "Copyright {year} {holder}\n\n".format(year=year, holder=holder) + data["license"]["text"] 186 | data["platforms"] = getCombinationSelection(validPlatforms, "Which platforms are supported? ") 187 | 188 | data["installinstructions"] = {} 189 | for platform in data["platforms"]: 190 | print("Enter Markdown formatted installation directions for the following platform: ") 191 | data["installinstructions"][platform] = input("{}: ".format(platform)) 192 | data["version"] = input("Enter the version string for this plugin. ") 193 | data["minimumbinaryninjaversion"] = int(input("Enter the minimum build number that you've successfully tested this plugin with: ")) 194 | return data 195 | 196 | 197 | readmeTemplate = u"""# {name} (v{version}) 198 | Author: **{author}** 199 | 200 | _{description}_ 201 | 202 | ## Description: 203 | 204 | {longdescription} 205 | {install} 206 | 207 | ## Minimum Version 208 | 209 | This plugin requires the following minimum version of Binary Ninja: 210 | 211 | * {minimum} 212 | 213 | {dependencies} 214 | ## License 215 | 216 | This plugin is released under a {license} license. 217 | ## Metadata Version 218 | 219 | {metadataVersion} 220 | """ 221 | 222 | def generateReadme(plugin): 223 | install = None 224 | if "installinstructions" in plugin: 225 | install = "\n\n## Installation Instructions" 226 | for platform in plugin["installinstructions"]: 227 | install += "\n\n### {}\n\n{}".format(platform, plugin["installinstructions"][platform]) 228 | 229 | if "dependencies" in plugin: 230 | dependencies = u"\n\n## Required Dependencies\n\nThe following dependencies are required for this plugin:\n\n" 231 | for dependency in plugin["dependencies"]: 232 | dependencylist = u", ".join(plugin["dependencies"][dependency]) 233 | dependencies += u" * {dependency} - {dependencylist}\n".format(dependency = dependency, dependencylist = dependencylist) 234 | dependencies += "\n" 235 | else: 236 | dependencies = "" 237 | 238 | return readmeTemplate.format(name=plugin["name"], version=plugin["version"], 239 | author=plugin["author"], description=plugin["description"], 240 | longdescription=plugin["longdescription"], install=install, 241 | minimum=plugin["minimumbinaryninjaversion"], dependencies=dependencies, 242 | license=plugin["license"]["name"], metadataVersion=plugin["pluginmetadataversion"]) 243 | 244 | 245 | def main(): 246 | parser = argparse.ArgumentParser(description="Generate README.md (and optional LICENSE) from plugin.json metadata") 247 | parser.add_argument("-a", "--all", help="Generate all supporting information needed (plugin.json, README.md, LICENSE)", action="store_true") 248 | parser.add_argument("-p", "--plugin", help="Interactively generate plugin.json file", action="store_true") 249 | parser.add_argument("-r", "--readme", help="Automatically generate README.md", action="store_true") 250 | parser.add_argument("-l", "--license", help="Automatically generate LICENSE file", action="store_true") 251 | parser.add_argument("-f", "--force", help="Force overwrite of existing files", action="store_true") 252 | parser.add_argument("-v", "--validate", help="Validate existing plugin.json only", metavar="JSON") 253 | args = parser.parse_args() 254 | 255 | 256 | # Just validate an existing plugin.json 257 | if args.validate is not None: 258 | if validateRequiredFields(json.load(io.open(args.validate, "r", encoding="utf8"))): 259 | print("Successfully validated json file") 260 | else: 261 | print("Error: json validation failed") 262 | return 263 | 264 | pluginjson = "plugin.json" 265 | 266 | # Enable all the options if --all is selected 267 | if args.all: 268 | args.plugin = True 269 | args.readme = True 270 | args.license = True 271 | 272 | if args.plugin: 273 | plugin = generatepluginmetadata() 274 | else: 275 | try: 276 | plugin = json.load(io.open(pluginjson, "r", encoding="utf8")) 277 | except json.JSONDecodeError: 278 | print("File {} doesn't contain valid json".format(pluginjson)) 279 | return 280 | except Exception: 281 | print("File {} doesn't exist".format(pluginjson)) 282 | return 283 | 284 | print("-----------------------------------------------------------------") 285 | if validateRequiredFields(plugin): 286 | print("Successfully validated json file") 287 | else: 288 | print("Error: json validation failed") 289 | return 290 | 291 | if "python2" in plugin["api"] and "python3" not in plugin["api"]: 292 | print("Warning: This python plugin doesn't support python3, python2 support will soon be deprecated.") 293 | print(" Please consider upgrading you plugin to support python3") 294 | 295 | if args.plugin: 296 | skip = False 297 | print("-----------------------------------------------------------------") 298 | if os.path.isfile(pluginjson) and not args.force and args.plugin: 299 | print("{} already exists.".format(pluginjson)) 300 | response = input("Overwrite it? (N,y) ") 301 | if response != "y": 302 | print("Not overwriting plugin.json") 303 | skip = True 304 | if not skip: 305 | print("Creating plugin.json.") 306 | with io.open(pluginjson, "w", encoding="utf8") as pluginfile: 307 | pluginfile.write(json.dumps(plugin, indent=" ")) 308 | 309 | if args.readme: 310 | print("-----------------------------------------------------------------") 311 | readme = os.path.join(os.path.dirname(pluginjson), "README.md") 312 | skip = False 313 | if os.path.isfile(readme) and not args.force: 314 | print("{} already exists.".format(readme)) 315 | response = input("Overwrite it? (N,y) ") 316 | if response != "y": 317 | print("Not overwriting README.md") 318 | skip = True 319 | if not skip: 320 | print("Creating README.md") 321 | with io.open(readme, "w", encoding="utf8") as readmeFile: 322 | readmeFile.write(generateReadme(plugin)) 323 | 324 | if args.license: 325 | print("-----------------------------------------------------------------") 326 | licenseFile = os.path.join(os.path.dirname(pluginjson), "LICENSE") 327 | skip = False 328 | if os.path.isfile(licenseFile) and not args.force: 329 | print("{} already exists.".format(licenseFile)) 330 | response = input("Overwrite it? (N,y) ") 331 | if response != "y": 332 | print("Not overwriting LICENSE") 333 | skip = True 334 | if not skip: 335 | print("Creating LICENSE") 336 | with io.open(licenseFile, "w", encoding="utf8") as lic: 337 | lic.write(plugin["license"]["text"]) 338 | 339 | 340 | if __name__ == "__main__": 341 | main() 342 | -------------------------------------------------------------------------------- /media/snippets.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vector35/snippets/130636ae51c1cacc901e72f63941cbe904087cb6/media/snippets.gif -------------------------------------------------------------------------------- /plugin.json: -------------------------------------------------------------------------------- 1 | { 2 | "pluginmetadataversion": 2, 3 | "name": "Snippet UI Plugin", 4 | "type": [ 5 | "ui" 6 | ], 7 | "api": [ 8 | "python2", 9 | "python3" 10 | ], 11 | "description": "Powerful code-editing plugin for writing and managing python code-snippets with syntax highlighting, hotkey binding and other features", 12 | "longdescription": "The snippet editor started as a simple example UI plugin to demonstrate new features available to UI plugins. It has turned into a functionally useful plugin in its own right. The snippet editor allows you to write small bits of code that might not be big enough to warrant the effort of a full plugin but are long enough that you don't want to retype them every time in the python-console!\n\nAs an added bonus, all snippets are added to the snippets menu and hot-keys can be associated with them as they make use of the action system. All action-system items are also available through the command-palette (CTL/CMD-p).\n\n![](https://github.com/Vector35/snippets/blob/master/media/snippets.gif?raw=true)\n\n.", 13 | "license": { 14 | "name": "MIT", 15 | "text": "Copyright (c) 2019 Vector 35 Inc\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE." 16 | }, 17 | "platforms": [ 18 | "Darwin", 19 | "Linux", 20 | "Windows" 21 | ], 22 | "installinstructions": { 23 | "Darwin": "no special instructions, package manager is recommended", 24 | "Linux": "no special instructions, package manager is recommended", 25 | "Windows": "no special instructions, package manager is recommended" 26 | }, 27 | "dependencies": { 28 | "pip": [ 29 | "pygments>=2.7.0,<2.9.0" 30 | ] 31 | }, 32 | "version": "1.28", 33 | "author": "Vector 35 Inc", 34 | "minimumbinaryninjaversion": 1528 35 | } -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pygments>=2.7.0 2 | -------------------------------------------------------------------------------- /update_example_snippets.py: -------------------------------------------------------------------------------- 1 | # update snippets 2 | # 3 | # Automatically download and update this collection of snippets to your local snippet folder 4 | 5 | from zipfile import ZipFile 6 | from tempfile import TemporaryFile 7 | import os 8 | 9 | #TODO: Merge remote with local description or hotkey changes (AKA: if filename matches, skip the first two lines, truncate, re-write the rest) 10 | 11 | domain = b'https://gist.github.com' 12 | path = b'/psifertex/6fbc7532f536775194edd26290892ef7' # Feel free to adapt to your own setup 13 | archive = path + b'/archive/' 14 | subfolder = 'default' # Change to save the snippets to a different sub-folder 15 | tab2space = False 16 | width = 4 17 | 18 | def download(url): 19 | # Can also use 'CoreDownloadProvider' or 'PythonDownloadProvider' as keys here 20 | provider = DownloadProvider[Settings().get_string('network.downloadProviderName')].create_instance() 21 | code, data = provider.get_response(url) 22 | if code == 0: 23 | return data 24 | else: 25 | raise ConnectionError("Unsuccessful download of %s" % url) 26 | 27 | def update_snippets(): 28 | if not interaction.show_message_box('Warning', "Use at your own risk. Do you want to automatically overwrite local snippets from gist?", buttons=MessageBoxButtonSet.YesNoButtonSet): 29 | return 30 | snippetPath = os.path.realpath(os.path.join(user_plugin_path(), '..', 'snippets', subfolder)) 31 | if not os.path.isdir(snippetPath): 32 | os.makedirs(snippetPath) 33 | url = domain + path 34 | log_info("Downloading from: %s" % url) 35 | source = download(url) 36 | zipPath = [s for s in source.split(b'\"') if s.endswith(b'.zip') and archive in s] 37 | if len(zipPath) != 2: 38 | log_error("Update failed.") 39 | return 40 | url = domain + zipPath[0] 41 | 42 | log_info("Downloading from: %s" % url) 43 | zip = download(url) 44 | with TemporaryFile() as f: 45 | f.write(zip) 46 | with ZipFile(f, 'r') as zip: 47 | for item in zip.infolist(): 48 | if item.filename[-1] == '/': 49 | continue 50 | basename = os.path.basename(item.filename) 51 | with open(os.path.join(snippetPath, basename), 'wb') as f: 52 | if tab2space: 53 | f.write(zip.read(item).replace(b'\t', b' ' * width)) 54 | else: 55 | f.write(zip.read(item)) 56 | log_info("Extracting %s" % item.filename) 57 | 58 | update_snippets() 59 | --------------------------------------------------------------------------------