forked from CX330Blake/Shellcode-IDE
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_window.py
More file actions
2376 lines (2273 loc) · 93.6 KB
/
Copy pathmain_window.py
File metadata and controls
2376 lines (2273 loc) · 93.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import traceback
from typing import Optional, Tuple
# Qt compatibility: prefer PySide6 (Qt6), fallback to PySide2 (Qt5)
_QT_LIB = None
try:
from PySide6.QtCore import Qt, QTimer, QEvent, QSize # type: ignore
from PySide6.QtGui import (
QFont,
QAction,
QPalette,
QColor,
QIcon,
QPixmap,
QPainter,
QKeySequence,
QShortcut,
) # type: ignore # QAction is in QtGui on Qt6
from PySide6.QtWidgets import ( # type: ignore
QApplication,
QComboBox,
QGridLayout,
QGroupBox,
QHBoxLayout,
QLabel,
QMainWindow,
QMessageBox,
QPushButton,
QPlainTextEdit,
QSizePolicy,
QSplitter,
QStatusBar,
QFrame,
QTabWidget,
QToolBar,
QVBoxLayout,
QWidget,
)
_QT_LIB = "PySide6"
except Exception:
try:
from PySide2.QtCore import Qt, QTimer, QEvent, QSize # type: ignore
from PySide2.QtGui import QFont, QPalette, QColor, QIcon, QPixmap, QPainter, QKeySequence # type: ignore
from PySide2.QtWidgets import ( # type: ignore
QAction, # QAction is in QtWidgets on Qt5
QApplication,
QComboBox,
QGridLayout,
QGroupBox,
QHBoxLayout,
QLabel,
QMainWindow,
QMessageBox,
QPushButton,
QPlainTextEdit,
QSizePolicy,
QSplitter,
QStatusBar,
QFrame,
QTabWidget,
QToolBar,
QVBoxLayout,
QWidget,
QShortcut,
)
_QT_LIB = "PySide2"
except Exception as exc: # pragma: no cover
raise ImportError("Qt (PySide6/PySide2) is required to run Shellcode IDE") from exc
from ..backends.bn_adapter import BNAdapter
from ..backends.validator import BadPatternManager, validate_all
from ..utils.config import load_config, save_config
from .patterns_dialog import PatternsDialog
from .settings_dialog import SettingsDialog
from .patterns_panel import PatternsPanel
from .highlighters import (
create_disassembly_highlighter,
create_code_highlighter,
create_inline_highlighter,
HexBadByteHighlighter,
AsmObjdumpBadByteHighlighter,
InlineBadByteHighlighter,
_good_bad_colors,
)
from .optimize_panel import OptimizePanel
from .file_tab import FileDropTab
from .syscalls_panel import SyscallsPanel
from .shellstorm_panel import ShellstormPanel
from ..backends.syscalls import canonical_arch
from ..formatters.base import (
bytes_to_c_array,
bytes_to_c_stub,
bytes_to_hex,
bytes_to_inline,
bytes_to_python_bytes,
bytes_to_python_stub,
bytes_to_zig_array,
bytes_to_zig_stub,
bytes_to_rust_array,
bytes_to_rust_stub,
bytes_to_go_slice,
bytes_to_go_stub,
)
from ..utils.hexbytes import parse_hex_input, count_nulls
MONO_FONT = "Menlo, Consolas, monospace"
class ShellcodeIDEWindow(QMainWindow):
def __init__(self, parent: Optional[QWidget] = None, bn_api=None):
super().__init__(parent)
self.setWindowTitle("Shellcode IDE")
# Slightly narrower default width for better fit on smaller screens
self.resize(900, 700)
# Compute centered geometry before the window is shown (best-effort),
# and then finalize exact centering synchronously in showEvent using
# frameGeometry so decorations are accounted for without a visible move.
self._did_center_after_show = True # disable any delayed re-centering
self._did_first_show_center = False # will center once in showEvent
try:
self._set_initial_center_geometry()
except Exception:
pass
self.adapter = BNAdapter(bn_api=bn_api)
# Load config and patterns
cfg = load_config()
if isinstance(cfg.get("bad_patterns"), list):
self.bpm = BadPatternManager.deserialize(cfg.get("bad_patterns") or [])
else:
self.bpm = BadPatternManager()
# One-time migration: ensure 0x00 is enabled by default.
# If user previously disabled it, they can disable again; we only flip once.
try:
if not bool(cfg.get("migrated_00_default", False)):
pats = list(getattr(self.bpm, 'patterns', []) or [])
def _is_null_pat(p) -> bool:
try:
v = (p.value or "").strip().lower()
if v.startswith('0x'):
v = v[2:]
return p.type == 'hex' and v == '00'
except Exception:
return False
found = False
for p in pats:
if _is_null_pat(p):
found = True
p.enabled = True
break
if not found:
from ..backends.validator import Pattern as _Pat
pats.insert(0, _Pat(type='hex', value='00', name='NULL byte', enabled=True))
self.bpm.patterns = pats
cfg["bad_patterns"] = self.bpm.serialize()
cfg["migrated_00_default"] = True
save_config(cfg)
except Exception:
pass
# Toolbar
tb = QToolBar("Main")
tb.setMovable(False)
self.addToolBar(tb)
# Keep a handle for later padding sync with editors
self._toolbar = tb
# Left spacer to align toolbar content (Mode, Arch) with the Assembly editor text
# Width is updated later once we compute editor padding from the Syscalls tab.
try:
self._toolbar_left_spacer = QWidget()
# Default to 0; will be set in _sync_shellcode_padding_to_syscalls
self._toolbar_left_spacer.setFixedWidth(0)
tb.addWidget(self._toolbar_left_spacer)
except Exception:
self._toolbar_left_spacer = None
# Mode switcher (Dev/Analysis)
self.mode_combo = QComboBox()
try:
self.mode_combo.addItems(["Dev", "Analysis"]) # Dev = assemble, Analysis = disassemble
except Exception:
pass
self.arch_combo = QComboBox()
self._populate_arch_platform()
self.act_assemble = QAction("Assemble 🛠️", self)
self.act_disassemble = QAction("Disassemble ⏪", self)
tb.addWidget(QLabel("Mode:"))
tb.addWidget(self.mode_combo)
tb.addSeparator()
tb.addWidget(QLabel("Arch:"))
tb.addWidget(self.arch_combo)
# Labels are always allowed (block assembly mode enabled)
# Checkbox removed; always assemble with labels preserved.
tb.addSeparator()
tb.addAction(self.act_assemble)
tb.addAction(self.act_disassemble)
# Push Settings button to the far right within the same title bar
try:
self._toolbar_right_spacer = QWidget()
self._toolbar_right_spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
tb.addWidget(self._toolbar_right_spacer)
except Exception:
self._toolbar_right_spacer = None
try:
self.btn_settings = QPushButton("Settings")
self.btn_settings.setToolTip("Open Settings")
tb.addWidget(self.btn_settings)
self.btn_settings.clicked.connect(self.on_open_settings)
except Exception:
self.btn_settings = None
# Central layout
splitter = QSplitter()
splitter.setOrientation(Qt.Horizontal)
self.setCentralWidget(splitter)
# Left side - Input tabs
left = QWidget()
left_layout = QVBoxLayout(left)
self.input_tabs = QTabWidget()
self.hex_edit = QPlainTextEdit()
self.asm_edit = QPlainTextEdit()
self._apply_mono(self.hex_edit)
self._apply_mono(self.asm_edit)
# Editor behavior: 4-space tab stops and macOS-like shortcuts
try:
self._configure_text_editor(self.hex_edit)
self._configure_text_editor(self.asm_edit)
except Exception:
pass
# Apply borderless style to both editors; padding will be synced to Syscalls
# Add comfortable inner padding to the Assembly editor so it matches
# the feel of the right-side output panes.
# Padding set later to match Syscalls panel once it's created
# Ensure the Assembly editor aligns flush with the tab pane edges (no extra inner frame),
# while keeping internal padding via document margins above.
try:
self.hex_edit.setContentsMargins(0, 0, 0, 0)
except Exception:
pass
try:
self.asm_edit.setContentsMargins(0, 0, 0, 0)
except Exception:
pass
try:
self.hex_edit.setFrameShape(QFrame.NoFrame)
except Exception:
pass
try:
self.asm_edit.setFrameShape(QFrame.NoFrame)
except Exception:
pass
self.input_tabs.addTab(self.hex_edit, "Hex/Bytes")
self.input_tabs.addTab(self.asm_edit, "Assembly")
# Drag & Drop File tab: lets user drop or open a file, routing
# assembly-like files to the Assembly editor and others to Hex.
def _filetab_insert_hex(b: bytes) -> None:
try:
self.hex_edit.setPlainText(bytes_to_hex(b, sep=" "))
self._update_formats(b)
self._update_stats(b)
self._last_bytes = b
# Stay on File tab; do not switch editors
except Exception:
pass
def _filetab_insert_asm_text(s: str) -> None:
try:
self.asm_edit.setPlainText(s)
# Stay on File tab; do not switch editors
except Exception:
pass
# Provide a mode provider so the File tab can enforce Analysis-only-bytes
def _mode_provider() -> str:
try:
return (self.mode_combo.currentText() or "").strip()
except Exception:
return "Dev"
self.file_tab = FileDropTab(on_hex=_filetab_insert_hex, on_asm=_filetab_insert_asm_text, parent=self, mode_provider=_mode_provider)
self.input_tabs.addTab(self.file_tab, "File")
# Fill space so editor borders align top and bottom with right
left_layout.addWidget(self.input_tabs, 1)
splitter.addWidget(left)
# Install event filters to auto-trim trailing blank lines on focus loss
try:
self.hex_edit.installEventFilter(self)
self.asm_edit.installEventFilter(self)
except Exception:
pass
# Right side - Output tabs and bad-chars controls
right = QWidget()
right_layout = QVBoxLayout(right)
# keep a handle to right layout for later visibility toggles
self._right_layout = right_layout
# Bad-chars controls will be placed into the tab bar corner below
# load setting
self._last_bytes = b""
self.output_tabs = QTabWidget()
# Disassembly view (used in analysis mode)
self.output_text = QPlainTextEdit()
self._apply_mono(self.output_text)
self.output_text.setReadOnly(True)
# Use default padding to match Optimize tab appearance (no extra viewport margins)
try:
self._apply_inner_padding(self.output_text, margin_px=4, viewport_pad=(0, 0, 0, 0))
except Exception:
pass
# Header row with "Send to Dev mode" action
self.disasm_header = QWidget()
_dh_lay = QHBoxLayout(self.disasm_header)
try:
_def_h = QHBoxLayout()
_m = _def_h.contentsMargins()
_dh_lay.setContentsMargins(_m.left(), _m.top(), _m.right(), _m.bottom())
_dh_lay.setSpacing(_def_h.spacing())
except Exception:
pass
_dh_lay.addWidget(QLabel("Disassembly"))
_dh_lay.addStretch(1)
# Copy button for disassembly view
self.btn_disasm_copy = QPushButton("Copy")
try:
self.btn_disasm_copy.setFixedWidth(60)
except Exception:
pass
try:
def _copy_disasm():
try:
QApplication.clipboard().setText(self.output_text.toPlainText())
except Exception:
return
try:
self._flash_copied(self.btn_disasm_copy)
except Exception:
pass
self.btn_disasm_copy.clicked.connect(_copy_disasm)
except Exception:
pass
_dh_lay.addWidget(self.btn_disasm_copy)
# Send-to-dev action
self.btn_send_to_dev = QPushButton("Send to Dev mode")
try:
self.btn_send_to_dev.setToolTip("Copy disassembly to Assembly editor and switch to Dev mode")
except Exception:
pass
_dh_lay.addWidget(self.btn_send_to_dev)
try:
self.btn_send_to_dev.clicked.connect(self._send_disassembly_to_dev)
except Exception:
pass
# Wrap header + view in a container for the Disassembly tab
self.disasm_container = QWidget()
_dv = QVBoxLayout(self.disasm_container)
try:
_m = _dv.contentsMargins()
_dv.setContentsMargins(_m.left(), _m.top(), _m.right(), _m.bottom())
except Exception:
pass
_dv.addWidget(self.disasm_header)
_dv.addWidget(self.output_text)
self.disasm_highlighter = None
self._refresh_disasm_highlighter()
self.output_tabs.addTab(self.disasm_container, "Disassembly")
# Debug tab for assemble mode: Opcode + Assembly (objdump-like)
self.debug_widget = QWidget()
dbg_layout = QVBoxLayout(self.debug_widget)
# Opcode block
self.opcode_text = QPlainTextEdit()
self._apply_mono(self.opcode_text)
self.opcode_text.setReadOnly(True)
dbg_layout.addWidget(self._labeled_box("Opcode", target=self.opcode_text))
dbg_layout.addWidget(self.opcode_text)
# Disable coloring in Debug tab: keep original text color
self.op_hl = None
# Assembly block
self.debug_asm_text = QPlainTextEdit()
self._apply_mono(self.debug_asm_text)
self.debug_asm_text.setReadOnly(True)
dbg_layout.addWidget(self._labeled_box("Assembly", target=self.debug_asm_text))
dbg_layout.addWidget(self.debug_asm_text)
try:
self.debug_asm_bad_hl = AsmObjdumpBadByteHighlighter(self.debug_asm_text.document())
except Exception:
self.debug_asm_bad_hl = None
# Do not use assembly token highlighter in Debug pane; only bad-char highlighting
self.debug_asm_token_hl = None
self.output_tabs.addTab(self.debug_widget, "Debug")
# Optimize panel (Dev mode)
self.optimize_widget = OptimizePanel(
get_asm=lambda: self.asm_edit.toPlainText(),
set_asm=lambda s: self.asm_edit.setPlainText(s),
get_arch=lambda: (self.arch_combo.currentText() or "x86_64"),
assemble_cb=self.on_assemble,
parent=self,
)
self.output_tabs.addTab(self.optimize_widget, "Optimize")
# Apply optimize defaults from config
try:
cfg = load_config()
self.optimize_widget.chk_rule1.setChecked(bool(cfg.get("opt_rule_push_zero", True)))
self.optimize_widget.chk_rule2.setChecked(bool(cfg.get("opt_rule_mov_imm8", True)))
except Exception:
pass
# Formats view (Shellcode output pane)
fmt_widget = QWidget()
fmt_layout = QGridLayout(fmt_widget)
# Keep a handle for later syncing with Syscalls padding style
self.formats_layout = fmt_layout
# Match default padding style (like Syscalls tab)
try:
_def_v = QVBoxLayout()
_m = _def_v.contentsMargins()
fmt_layout.setContentsMargins(_m.left(), _m.top(), _m.right(), _m.bottom())
except Exception:
pass
try:
_def_v = QVBoxLayout()
_sp = _def_v.spacing()
fmt_layout.setHorizontalSpacing(_sp)
fmt_layout.setVerticalSpacing(_sp)
except Exception:
pass
# Ensure header rows stay compact and do not expand vertically
try:
fmt_layout.setRowStretch(0, 0)
fmt_layout.setRowStretch(2, 0)
fmt_layout.setRowStretch(1, 1) # let text areas take extra space
fmt_layout.setRowStretch(3, 2)
except Exception:
pass
self.inline_text = QPlainTextEdit(); self._setup_output_box(self.inline_text)
self.hex_text = QPlainTextEdit(); self._setup_output_box(self.hex_text)
# Copy As Code pane (single area with language selector)
self.hll_text = QPlainTextEdit(); self._setup_output_box(self.hll_text)
self.hll_lang_combo = QComboBox()
try:
# supported generators (label C emits the runnable C stub)
self.hll_lang_combo.addItems(["C", "Python", "Zig", "Rust", "Go"]) # supported generators
except Exception:
pass
# Load default HLL language from config
try:
cfg = load_config()
def_lang = (cfg.get("default_hll_lang") or "C")
idx = max(0, self.hll_lang_combo.findText(def_lang))
self.hll_lang_combo.setCurrentIndex(idx)
except Exception:
pass
try:
# Prevent Enter/Return from leaking to the Assembly editor when changing selection
self.hll_lang_combo.installEventFilter(self)
# After a selection, move focus to the read-only output box to avoid editing ASM
self.hll_lang_combo.activated.connect(lambda *_: self.hll_text.setFocus())
except Exception:
pass
self.inline_header = self._labeled_box("Inline")
fmt_layout.addWidget(self.inline_header, 0, 0)
fmt_layout.addWidget(self.inline_text, 1, 0)
self.hex_header = self._labeled_box("Hex")
fmt_layout.addWidget(self.hex_header, 0, 1)
fmt_layout.addWidget(self.hex_text, 1, 1)
# Copy As Code row with selector and copy button (compact)
hll_row = QWidget(); hll_row_layout = QHBoxLayout(hll_row)
try:
# Use default margins/spacing to mirror Syscalls panel
_def_h = QHBoxLayout()
_m = _def_h.contentsMargins()
hll_row_layout.setContentsMargins(_m.left(), _m.top(), _m.right(), _m.bottom())
hll_row_layout.setSpacing(_def_h.spacing())
except Exception:
pass
lbl_hll = QLabel("Copy As Code")
try:
lbl_hll.setAlignment(Qt.AlignVCenter | Qt.AlignLeft)
lbl_hll.setMargin(0)
except Exception:
pass
hll_row_layout.addWidget(lbl_hll)
# Push language selector + copy to the right
hll_row_layout.addStretch(1)
hll_row_layout.addWidget(QLabel("Language:"))
# Use default widget height for combo to match Optimize tab
hll_row_layout.addWidget(self.hll_lang_combo)
hll_copy = QPushButton("Copy");
try:
hll_copy.setFixedWidth(60)
except Exception:
pass
hll_row_layout.addWidget(hll_copy)
# Default height mirrors standard toolbar-like rows
def _copy_hll():
try:
QApplication.clipboard().setText(self.hll_text.toPlainText())
try:
self._flash_copied(hll_copy)
except Exception:
pass
except Exception:
pass
try:
hll_copy.clicked.connect(_copy_hll)
except Exception:
pass
fmt_layout.addWidget(hll_row, 2, 0, 1, 2)
self.hll_header_row = hll_row
fmt_layout.addWidget(self.hll_text, 3, 0, 1, 2)
# Keep formats packed to top
# No extra stretch; the tab widget fills the height
self.output_tabs.addTab(fmt_widget, "Shellcode")
self.formats_widget = fmt_widget
# Tabs fill space so borders align
right_layout.addWidget(self.output_tabs, 1)
# Syntax highlighting for Output tab code blocks using Qt-only highlighters
try:
# Inline: custom highlighter that colors only [0-9a-f]
self.inline_code_hl = create_inline_highlighter(self.inline_text.document())
except Exception:
self.inline_code_hl = None
# High-level language code highlighter; depends on selected language
self.hll_code_hl = None
try:
self._apply_hll_highlighter()
except Exception:
self.hll_code_hl = None
try:
self.hll_lang_combo.currentTextChanged.connect(lambda _t: self._on_hll_lang_changed())
except Exception:
pass
# Bad-byte highlighters for Inline and Hex panes (attached in analysis mode)
self.hex_bad_hl = None
self.inline_bad_hl = None
# Bad-chars editor as its own tab (Dev mode)
self.patterns_widget = PatternsPanel(self.bpm, self)
self.output_tabs.addTab(self.patterns_widget, "Bad Chars")
# Syscalls tab (visible in both modes)
def _insert_snippet(snippet: str) -> None:
try:
cursor = self.asm_edit.textCursor() # type: ignore[attr-defined]
try:
cursor.insertText(snippet)
except Exception:
# Fallback: append
self.asm_edit.appendPlainText(snippet)
except Exception:
# final fallback
self.asm_edit.appendPlainText(snippet)
self.syscalls_widget = SyscallsPanel(
get_arch_cb=lambda: (self.arch_combo.currentText() or "x86_64"),
insert_asm_cb=_insert_snippet,
parent=self,
)
self.output_tabs.addTab(self.syscalls_widget, "Syscalls")
# Apply Syscalls default style from config
try:
cfg = load_config()
def_style = (cfg.get("syscalls_style_default") or "Commented")
idx = max(0, self.syscalls_widget.style_combo.findText(def_style))
self.syscalls_widget.style_combo.setCurrentIndex(idx)
except Exception:
pass
# Now that Syscalls tab exists, sync Shellcode pane and editors padding to match it
try:
self._sync_shellcode_padding_to_syscalls()
except Exception:
pass
# Also align the toolbar's left padding with the editors once paddings are known
try:
self._sync_toolbar_padding_to_editors()
except Exception:
pass
# Preload Syscalls table once after UI is shown so users don't need to Refresh
try:
QTimer.singleShot(0, self._refresh_syscalls_tab)
except Exception:
try:
# Fallback: attempt immediately
self._refresh_syscalls_tab()
except Exception:
pass
# Shell-Storm tab (search/import online shellcodes)
def _insert_hex_bytes(b: bytes) -> None:
try:
# Insert into Hex editor and switch to Analysis mode to show disassembly
self.hex_edit.setPlainText(bytes_to_hex(b, sep=" "))
self._update_formats(b)
self._update_stats(b)
self._last_bytes = b
self._set_mode("disassemble")
except Exception:
pass
def _insert_asm_text(s: str) -> None:
try:
self.asm_edit.setPlainText(s)
self._set_mode("assemble")
except Exception:
pass
self.shellstorm_widget = ShellstormPanel(
get_arch_cb=lambda: (self.arch_combo.currentText() or "x86_64"),
insert_hex_cb=_insert_hex_bytes,
insert_asm_cb=_insert_asm_text,
parent=self,
)
self.output_tabs.addTab(self.shellstorm_widget, "Shell-Storm")
# Apply Shell-Storm default preview language
try:
cfg = load_config()
def_ss_lang = (cfg.get("shellstorm_default_lang") or "C")
if getattr(self.shellstorm_widget, 'lang_combo', None) is not None:
idx = max(0, self.shellstorm_widget.lang_combo.findText(def_ss_lang))
self.shellstorm_widget.lang_combo.setCurrentIndex(idx)
except Exception:
pass
# Validation tab (container with a button bar and text)
val_container = QWidget()
val_layout = QVBoxLayout(val_container)
self.btn_patterns = QPushButton("Patterns…")
self.btn_patterns.setFixedWidth(100)
bar = QHBoxLayout()
bar.addWidget(self.btn_patterns)
bar.addStretch(1)
val_layout.addLayout(bar)
self.validation_text = QPlainTextEdit()
self._apply_mono(self.validation_text)
self.validation_text.setReadOnly(True)
val_layout.addWidget(self.validation_text)
self.output_tabs.addTab(val_container, "Validation")
self.validation_container = val_container
# Ensure Shellcode tab appears before Debug tab
try:
dbg_idx = self.output_tabs.indexOf(self.debug_widget)
sh_idx = self.output_tabs.indexOf(self.formats_widget)
if dbg_idx != -1 and sh_idx != -1 and sh_idx > dbg_idx:
dbg_text = self.output_tabs.tabText(dbg_idx)
sh_text = self.output_tabs.tabText(sh_idx)
# Remove in descending order to avoid index shifts
self.output_tabs.removeTab(sh_idx)
self.output_tabs.removeTab(dbg_idx)
# Insert swapped
self.output_tabs.insertTab(dbg_idx, self.formats_widget, sh_text)
self.output_tabs.insertTab(sh_idx, self.debug_widget, dbg_text)
except Exception:
pass
# output_tabs already added with stretch above
splitter.addWidget(right)
# Status bar
sb = QStatusBar()
self.setStatusBar(sb)
self.status_arch = QLabel("Arch: -")
self.status_len = QLabel("Len: 0")
self.status_bad = QLabel("Bad Chars: 0")
sb.addPermanentWidget(self.status_arch)
sb.addPermanentWidget(self._status_separator())
sb.addPermanentWidget(self.status_len)
sb.addPermanentWidget(self._status_separator())
sb.addPermanentWidget(self.status_bad)
# Keep grip visible for resizing
try:
sb.setSizeGripEnabled(True)
except Exception:
pass
# Wire actions
self.act_assemble.triggered.connect(self.on_assemble)
self.act_disassemble.triggered.connect(self.on_disassemble)
# No Disassembly control bar; keep simple padded text view
self.btn_patterns.clicked.connect(self.on_patterns)
# No "New" toolbar action per request
splitter.setStretchFactor(0, 1)
splitter.setStretchFactor(1, 1)
# Initialize toolbar mode based on current tab
try:
self.input_tabs.currentChanged.connect(self.on_input_tab_changed)
except Exception:
pass
# Mode switcher handler
try:
self.mode_combo.currentIndexChanged.connect(self.on_mode_changed)
except Exception:
pass
# Also nudge File tab to re-apply restrictions when mode changes
try:
self.mode_combo.currentIndexChanged.connect(lambda _i: getattr(self.file_tab, '_enforce_analysis_restrictions', lambda: None)())
except Exception:
pass
# Default to Dev (assemble) mode regardless of initial tab
try:
self._update_toolbar_for_mode("assemble")
try:
self.mode_combo.blockSignals(True)
self.mode_combo.setCurrentIndex(0) # Dev
self.mode_combo.blockSignals(False)
except Exception:
pass
# Enforce initial tab visibility based on current mode
try:
self.on_mode_changed(0)
except Exception:
pass
except Exception:
self._update_toolbar_for_mode("assemble")
try:
self.mode_combo.setCurrentIndex(0)
except Exception:
pass
# Update highlighter when arch changes
try:
self.arch_combo.currentTextChanged.connect(lambda _t: self._refresh_disasm_highlighter())
except Exception:
pass
# Also refresh/hide syscalls tab on arch change
try:
self.arch_combo.currentTextChanged.connect(lambda _t: self._refresh_syscalls_tab())
except Exception:
pass
# Add Qt-only highlighter to Assembly editor
try:
self.asm_highlighter = create_disassembly_highlighter(
self.asm_edit.document(), arch_name=self.arch_combo.currentText() or "x86_64"
)
except Exception:
self.asm_highlighter = None
# Keep Optimize preview live on arch/asm changes
try:
self.arch_combo.currentTextChanged.connect(lambda _t: self.optimize_widget.on_preview())
except Exception:
pass
try:
self.asm_edit.textChanged.connect(self.optimize_widget.on_preview)
except Exception:
pass
# Patterns panel change hook (refresh highlighting and persist)
try:
self.patterns_widget.on_changed = lambda: self.on_badchars_toggled(self.patterns_widget.is_highlight_enabled())
except Exception:
pass
# Patterns panel change hook (refresh highlights + persist)
try:
self.patterns_widget.on_changed = lambda: self.on_badchars_toggled(self.patterns_widget.is_highlight_enabled())
except Exception:
pass
# Final centering happens once after the window is shown.
def showEvent(self, event): # type: ignore[override]
# Center synchronously before the first paint using frameGeometry
# so the window appears already centered without a post-show jump.
try:
if not getattr(self, '_did_first_show_center', False):
center_point = None
# Prefer parent window center when available
try:
p = self.parentWidget()
if p and p.isWindow():
center_point = p.frameGeometry().center()
except Exception:
center_point = None
if center_point is None:
try:
# Use the screen that will show this window
from PySide6.QtGui import QGuiApplication # type: ignore
scr = getattr(self, 'screen', lambda: None)() or QGuiApplication.primaryScreen()
ag = scr.availableGeometry() if scr else None
center_point = ag.center() if ag else None
except Exception:
center_point = None
if center_point is None:
try:
# Qt5 fallback
desk = QApplication.desktop() # type: ignore[attr-defined]
ag = desk.availableGeometry(self)
center_point = ag.center()
except Exception:
center_point = None
if center_point is not None:
try:
fg = self.frameGeometry()
fg.moveCenter(center_point)
self.move(fg.topLeft())
except Exception:
pass
self._did_first_show_center = True
except Exception:
pass
try:
super().showEvent(event)
except Exception:
pass
def _center_after_show(self) -> None:
if getattr(self, '_did_center_after_show', False):
return
ag = None
# If we have a top-level parent window, center relative to it
try:
p = self.parentWidget()
if p and p.isWindow():
pg = p.frameGeometry()
fg = self.frameGeometry()
fg.moveCenter(pg.center())
self.move(fg.topLeft())
self._did_center_after_show = True
return
except Exception:
pass
# Prefer the screen where the window resides (Qt6)
try:
from PySide6.QtGui import QGuiApplication # type: ignore
scr = getattr(self, 'screen', lambda: None)() or QGuiApplication.primaryScreen()
ag = scr.availableGeometry() if scr else None
except Exception:
ag = None
if ag is None:
# Qt5 fallback: use the screen for this window if possible
try:
desk = QApplication.desktop() # type: ignore[attr-defined]
idx = desk.screenNumber(self) if hasattr(desk, 'screenNumber') else -1
if isinstance(idx, int) and idx >= 0:
ag = desk.availableGeometry(idx)
else:
ag = desk.availableGeometry(self)
except Exception:
ag = None
if ag is None:
return
try:
fg = self.frameGeometry()
fg.moveCenter(ag.center())
self.move(fg.topLeft())
self._did_center_after_show = True
except Exception:
# As a last resort, setGeometry using current size
try:
w, h = self.width(), self.height()
x = ag.x() + max(0, (ag.width() - w) // 2)
y = ag.y() + max(0, (ag.height() - h) // 2)
self.setGeometry(x, y, w, h)
self._did_center_after_show = True
except Exception:
pass
def _set_tab_visible(self, tabs: QTabWidget, widget: QWidget, visible: bool):
try:
idx = tabs.indexOf(widget)
if idx >= 0:
tabs.setTabVisible(idx, visible) # Qt 5.15+/Qt6
except Exception:
# Fallback: disable when we cannot hide
try:
idx = tabs.indexOf(widget)
if idx >= 0:
tabs.setTabEnabled(idx, visible)
except Exception:
pass
def _update_toolbar_for_mode(self, mode: str):
# assemble mode: show Assemble; analysis mode: show Disassemble
if mode == "assemble":
try:
self.act_assemble.setVisible(True)
self.act_disassemble.setVisible(False)
except Exception:
pass
elif mode == "disassemble":
try:
self.act_assemble.setVisible(False)
self.act_disassemble.setVisible(True)
except Exception:
pass
else:
try:
self.act_assemble.setVisible(True)
self.act_disassemble.setVisible(True)
except Exception:
pass
def _status_separator(self) -> QFrame:
frm = QFrame()
try:
frm.setFrameShape(QFrame.VLine)
frm.setFrameShadow(QFrame.Sunken)
try:
frm.setLineWidth(1)
frm.setMidLineWidth(0)
except Exception:
pass
# Give the separator breathing room
try:
frm.setFixedWidth(10)
except Exception:
pass
except Exception:
# Fallback to a simple label if QFrame isn't available
try:
lb = QLabel("|")
return lb # type: ignore[return-value]
except Exception:
pass
return frm
def eventFilter(self, obj, event): # type: ignore[override]
try:
# Swallow Enter/Return keys on the Copy As Code language combo to avoid inserting\n
# unintended newlines in the Assembly editor when users confirm selection.
if obj is getattr(self, 'hll_lang_combo', None):
if event and hasattr(event, 'type'):
t = event.type()
try:
key = event.key() if hasattr(event, 'key') else None
except Exception:
key = None
if t in (QEvent.KeyPress, QEvent.KeyRelease) and key in (Qt.Key_Return, Qt.Key_Enter):
try:
event.accept()
except Exception:
pass
return True
except Exception:
pass
try:
if event and hasattr(event, 'type') and event.type() == QEvent.FocusOut:
if obj is self.asm_edit or obj is self.hex_edit:
try:
self._strip_editor_blank_lines(obj)
except Exception:
pass
except Exception:
pass
try:
return super().eventFilter(obj, event)
except Exception:
return False
def _strip_editor_blank_lines(self, edit: QPlainTextEdit) -> None:
"""Remove trailing blank lines and whitespace from the end of the editor text."""
try:
text = edit.toPlainText()
except Exception:
return
try:
stripped = text.rstrip()
except Exception:
stripped = text
if stripped != text:
try:
edit.blockSignals(True)
except Exception:
pass
try:
edit.setPlainText(stripped)
# Move cursor to end
cur = edit.textCursor() # type: ignore[attr-defined]
cur.movePosition(cur.End)
edit.setTextCursor(cur)
except Exception:
pass
try:
edit.blockSignals(False)
except Exception:
pass
def _set_initial_center_geometry(self) -> None:
"""Compute and set a centered geometry prior to show()."""
# Prefer centering relative to a parent window if available (e.g., BN main window)
try:
p = self.parentWidget()
if p and p.isWindow():
w, h = self.width(), self.height()
try:
pg = p.frameGeometry()
cx, cy = pg.center().x(), pg.center().y()
except Exception:
pg = p.geometry()
cx = pg.x() + pg.width() // 2
cy = pg.y() + pg.height() // 2
x = int(cx - w // 2)
y = int(cy - h // 2)
self.setGeometry(x, y, w, h)
return