|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import logging |
| 4 | +from pathlib import Path |
| 5 | + |
| 6 | +from binaryninja import ( # type: ignore |
| 7 | + BackgroundTaskThread, |
| 8 | + PluginCommand, |
| 9 | + core_ui_enabled, |
| 10 | + execute_on_main_thread, |
| 11 | + log_debug, |
| 12 | + log_error, |
| 13 | + log_info, |
| 14 | + log_warn, |
| 15 | +) |
| 16 | +from binaryninja.enums import MessageBoxIcon # type: ignore |
| 17 | +from binaryninja.interaction import ( # type: ignore |
| 18 | + SaveFileNameField, |
| 19 | + get_form_input, |
| 20 | + show_message_box, |
| 21 | +) |
| 22 | + |
| 23 | +from .bn_quokka.export import ExportCancelled, export_binary_view |
| 24 | + |
| 25 | + |
| 26 | +class _BinaryNinjaLogHandler(logging.Handler): |
| 27 | + """Forward stdlib logging records to the BinaryNinja log. |
| 28 | +
|
| 29 | + bn_quokka deliberately uses Python's logging (so headless runs can |
| 30 | + configure it normally); inside the UI those records would otherwise never |
| 31 | + reach the BinaryNinja log pane. |
| 32 | + """ |
| 33 | + |
| 34 | + def emit(self, record: logging.LogRecord) -> None: |
| 35 | + try: |
| 36 | + message = self.format(record) |
| 37 | + if record.levelno >= logging.ERROR: |
| 38 | + log_error(message) |
| 39 | + elif record.levelno >= logging.WARNING: |
| 40 | + log_warn(message) |
| 41 | + elif record.levelno >= logging.INFO: |
| 42 | + log_info(message) |
| 43 | + else: |
| 44 | + log_debug(message) |
| 45 | + except Exception: |
| 46 | + self.handleError(record) |
| 47 | + |
| 48 | + |
| 49 | +def _install_log_forwarder() -> None: |
| 50 | + """Route this package's loggers to the BinaryNinja log pane (UI only).""" |
| 51 | + if not core_ui_enabled(): |
| 52 | + return |
| 53 | + |
| 54 | + logger = logging.getLogger(__name__) |
| 55 | + if any(isinstance(handler, _BinaryNinjaLogHandler) for handler in logger.handlers): |
| 56 | + return |
| 57 | + |
| 58 | + handler = _BinaryNinjaLogHandler() |
| 59 | + handler.setFormatter(logging.Formatter("%(name)s: %(message)s")) |
| 60 | + logger.addHandler(handler) |
| 61 | + # Surface INFO diagnostics (skipped types, ...) in the log pane; the pane |
| 62 | + # has its own per-level filtering. |
| 63 | + logger.setLevel(logging.INFO) |
| 64 | + |
| 65 | + |
| 66 | +def _default_output_path(bv) -> Path: |
| 67 | + source = bv.file.original_filename or bv.file.filename or "binary" |
| 68 | + return Path(source).with_name(f"{Path(source).name}.quokka") |
| 69 | + |
| 70 | + |
| 71 | +class _ExportTask(BackgroundTaskThread): |
| 72 | + """Run the export off the UI thread, with progress text and cancellation.""" |
| 73 | + |
| 74 | + def __init__(self, bv, output_path: Path, mode: str): |
| 75 | + super().__init__(f"Quokka: exporting {output_path.name} ({mode})", True) |
| 76 | + self.bv = bv |
| 77 | + self.output_path = output_path |
| 78 | + self.mode = mode |
| 79 | + |
| 80 | + def _progress(self, text: str) -> None: |
| 81 | + if self.cancelled: |
| 82 | + raise ExportCancelled(f"Quokka export of {self.output_path} cancelled") |
| 83 | + self.progress = f"Quokka: {text}" |
| 84 | + |
| 85 | + def run(self) -> None: |
| 86 | + try: |
| 87 | + proto = export_binary_view( |
| 88 | + self.bv, self.output_path, self.mode, progress=self._progress |
| 89 | + ) |
| 90 | + except ExportCancelled as exc: |
| 91 | + log_info(str(exc)) |
| 92 | + return |
| 93 | + except Exception as exc: |
| 94 | + message = f"Failed to export {self.output_path}: {exc}" |
| 95 | + log_error(message) |
| 96 | + execute_on_main_thread( |
| 97 | + lambda: show_message_box( |
| 98 | + "Quokka export failed", message, icon=MessageBoxIcon.ErrorIcon |
| 99 | + ) |
| 100 | + ) |
| 101 | + return |
| 102 | + |
| 103 | + message = ( |
| 104 | + f"Exported {self.output_path}\n" |
| 105 | + f"Functions: {len(proto.functions)}\n" |
| 106 | + f"Segments: {len(proto.segments)}\n" |
| 107 | + f"Types: {len(proto.types)}" |
| 108 | + ) |
| 109 | + log_info(message) |
| 110 | + execute_on_main_thread( |
| 111 | + lambda: show_message_box( |
| 112 | + "Quokka export complete", message, icon=MessageBoxIcon.InformationIcon |
| 113 | + ) |
| 114 | + ) |
| 115 | + |
| 116 | + |
| 117 | +def _export_with_dialog(bv, mode: str) -> None: |
| 118 | + default_output = _default_output_path(bv) |
| 119 | + output_field = SaveFileNameField( |
| 120 | + "Output file", |
| 121 | + "Quokka files (*.quokka)", |
| 122 | + str(default_output), |
| 123 | + ) |
| 124 | + |
| 125 | + if not get_form_input([output_field], f"Quokka Export ({mode})"): |
| 126 | + return |
| 127 | + |
| 128 | + output_path = Path(output_field.result or default_output) |
| 129 | + _ExportTask(bv, output_path, mode).start() |
| 130 | + |
| 131 | + |
| 132 | +def export_light(bv) -> None: |
| 133 | + _export_with_dialog(bv, "LIGHT") |
| 134 | + |
| 135 | + |
| 136 | +def export_self_contained(bv) -> None: |
| 137 | + _export_with_dialog(bv, "SELF_CONTAINED") |
| 138 | + |
| 139 | + |
| 140 | +_install_log_forwarder() |
| 141 | + |
| 142 | +PluginCommand.register( |
| 143 | + "Quokka\\Export LIGHT", |
| 144 | + "Export this binary to a light-mode Quokka protobuf", |
| 145 | + export_light, |
| 146 | +) |
| 147 | +# |
| 148 | +# PluginCommand.register( |
| 149 | +# "Quokka\\Export SELF_CONTAINED", |
| 150 | +# "Export this binary to a self-contained Quokka protobuf", |
| 151 | +# export_self_contained, |
| 152 | +# ) |
0 commit comments