-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharch_utils.py
More file actions
648 lines (559 loc) · 26.1 KB
/
arch_utils.py
File metadata and controls
648 lines (559 loc) · 26.1 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
# A Python LLDB script implementing "follow <addr> [debug]"
# by CheeWee Chua, Dec 2025
# settings set target.x86-disassembly-flavor intel / default / att
# command script import "C:\\Program Files (x86)\\Embarcadero\\Studio\\37.0\\bin\\windows\\lldb\\arch_utils.py"
# process launch
# Read 4 bytes (--size), format (--format) x (hex), at address 0xaa214 count (-c) of 1
# memory read --size 4 --format x 0xaa214 -c 1
import lldb
import os
import re
debug_mode = False
# Constants for architecture grouping
ARCH_X86 = ("i386", "x86", "x86_64", "amd64")
ARCH_ARM = ("arm", "thumb", "armv7")
ARCH_ARM64 = ("aarch64", "arm64")
ARCH_ALL_ARM = ARCH_ARM + ARCH_ARM64
def load_command(debugger, func_name, cmd_name):
module_name = __name__
cmd_line = f'command script add -f {module_name}.{func_name} {cmd_name} --overwrite'
debugger.HandleCommand(cmd_line)
print(f'Custom "{cmd_name}" command loaded.')
def __lldb_init_module(debugger, internal_dict):
load_command(debugger, "cmd_is_branch_or_call", "is_branch_or_call")
load_command(debugger, "cmd_follow", "follow")
load_command(debugger, "cmd_get_operands", "get_operands")
print(f'lldb pid is: {os.getpid()}')
def get_x86_flavor(debugger):
res = lldb.SBCommandReturnObject()
debugger.GetCommandInterpreter().HandleCommand("settings show target.x86-disassembly-flavor", res)
if res.Succeeded():
# Output looks like: "target.x86-disassembly-flavor (enum) = intel"
output = res.GetOutput().strip()
# Parse the value after " = "
if " = " in output:
return output.split(" = ")[-1]
return "default" # Fallback
def get_arch_name(target):
triple = target.GetTriple()
return triple.split("-")[0].lower() if triple else ""
# Accepts: 123, -42, 0x1a2b, -0XFF, $1A2B, -$FF
_INT_DEC_RE = re.compile(r"^[+-]?\d+$")
_INT_HEX_C_RE = re.compile(r"^[+-]?0[xX][0-9a-fA-F]+$")
_INT_HEX_DELPHI_RE = re.compile(r"^[+-]?\$[0-9a-fA-F]+$")
def is_int_literal(s: str) -> bool:
if s is None:
return False
t = s.strip()
return bool(
_INT_DEC_RE.match(t) or _INT_HEX_C_RE.match(t) or _INT_HEX_DELPHI_RE.match(t)
)
def parse_int_literal(s: str):
"""Parse decimal, 0x-hex, or Delphi $-hex into int; returns None on failure."""
if s is None:
return None
t = s.strip()
if _INT_DEC_RE.match(t):
return int(t, 10)
if _INT_HEX_C_RE.match(t):
return int(t, 16)
if _INT_HEX_DELPHI_RE.match(t):
sign = -1 if t.startswith('-') else 1
# remove leading sign and leading '$'
body = t.lstrip('+-')
assert body.startswith('$')
return sign * int(body[1:], 16)
return None
def x86_cond_jump_target_from_inst(target: lldb.SBTarget,
inst: lldb.SBInstruction,
*,
prefer_file_addr: bool = False) -> int:
"""
If `inst` is an x86 conditional jump (Jcc), return its resolved target address.
Computes the target from the instruction bytes (rel8/rel32), not from GetOperands().
Args:
target: SBTarget (needed for address resolution / memory reads).
inst: SBInstruction to analyze.
prefer_file_addr: If True, compute using file addresses (SBAddress.GetFileAddress()).
Otherwise compute using load addresses (SBAddress.GetLoadAddress()).
Returns:
int target address, or None if not a conditional jump or cannot decode.
"""
if not target or not target.IsValid() or not inst or not inst.IsValid():
return None
# Fast gate: LLDB already classifies cond jumps for most targets.
if inst.GetControlFlowKind(target) != lldb.eInstructionControlFlowKindCondJump:
return None
addr = inst.GetAddress()
if not addr or not addr.IsValid():
return None
pc = addr.GetFileAddress() if prefer_file_addr else addr.GetLoadAddress(target)
if pc in (None, lldb.LLDB_INVALID_ADDRESS):
return None
# Read enough bytes to cover both encodings:
# - short Jcc: 2 bytes
# - near Jcc: 6 bytes (0F 8x + imm32)
err = lldb.SBError()
insn_bytes = target.ReadMemory(addr, 6, err)
if not err.Success() or not insn_bytes:
return None
# Ensure we can index bytes (ReadMemory returns a Python bytes/bytearray on most builds)
b = insn_bytes if isinstance(insn_bytes, (bytes, bytearray)) else bytes(insn_bytes)
op0 = b[0]
# short Jcc rel8: 70..7F (je=74, jne=75, etc.)
if 0x70 <= op0 <= 0x7F:
if len(b) < 2:
return None
disp = int.from_bytes(b[1:2], byteorder="little", signed=True)
insn_len = 2
return pc + insn_len + disp
# near Jcc rel32: 0F 80..8F
if op0 == 0x0F:
if len(b) < 6:
return None
op1 = b[1]
if 0x80 <= op1 <= 0x8F:
disp = int.from_bytes(b[2:6], byteorder="little", signed=True)
insn_len = 6
return pc + insn_len + disp
# Some other conditional form or we couldn't decode it here.
return None
def cmd_get_operands(debugger, command, exe_ctx, result, internal_dict):
global debug_mode
target = exe_ctx.target
frame = exe_ctx.frame
if not target or not target.IsValid():
result.PutCString("No valid target.")
return
cmd = command.strip()
USAGE_STR = "Usage: get_operands <address> [debug]"
if not cmd:
result.PutCString(USAGE_STR)
return
cmd_args = command.strip().split()
if len(cmd_args) < 1:
result.PutCString(USAGE_STR)
return
debug_mode = len(cmd_args) > 1 and cmd_args[1] == "debug"
addr = parse_int_literal(cmd_args[0])
if addr is None:
result.PutCString("Invalid address: %s" % cmd_args[0])
return
sb_addr = target.ResolveFileAddress(addr)
# Read raw bytes from memory; this returns a Python bytes object on your build
err = lldb.SBError()
buf = target.ReadMemory(sb_addr, 32, err) # 32 bytes is enough for one instruction
inst_list = target.GetInstructions(sb_addr, buf)
if inst_list.GetSize() == 0:
return
inst = inst_list.GetInstructionAtIndex(0)
if debug_mode:
result.PutCString("DEBUG: cmd_get_operands inst: %s" % inst)
if not inst or not inst.IsValid():
return
operands_str = inst.GetOperands(target)
result.PutCString("cmd_get_operands Operands: %s" % operands_str)
def cmd_get_arch_name(debugger, command, exe_ctx, result, internal_dict):
target = exe_ctx.target
arch = get_arch_name(target)
result.PutCString("Architecture: %s" % arch)
def _resolve_register_value(frame, reg_name, result_out=None):
"""
Return integer value of register reg_name in this frame, or None.
Handles common register name variations (edx/EDX/%edx, rax/RAX/%rax, etc.).
"""
if not frame or not frame.IsValid():
return None
# Normalize register name: strip % prefix, try original/capitalized/lowercase
reg_name_norm = reg_name.lstrip('%').strip()
if result_out:
result_out.PutCString("reg_name_norm: %s" % reg_name_norm)
reg_variants = [reg_name_norm, reg_name_norm.upper(), reg_name_norm.lower()]
if result_out:
result_out.PutCString("reg_variants: %s" % reg_variants)
for reg_candidate in reg_variants:
reg = frame.FindRegister(reg_candidate)
if result_out:
result_out.PutCString("_resolve_register_value reg: %s" % reg)
if reg and reg.IsValid():
if result_out:
result_out.PutCString("Inside reg and reg.IsValid()")
val = reg.GetValue()
if result_out:
result_out.PutCString("_resolve_register_value val: %s" % val)
if val is not None:
if result_out:
result_out.PutCString("_resolve_register_value if val is not None: val: %s" % val)
try:
actual_value = parse_int_literal(val) # auto-detects hex/decimal
if result_out:
result_out.PutCString("_resolve_register_value return: %s" % actual_value)
return actual_value
except (ValueError, TypeError):
continue
return None
def is_branch_or_call_kind(control_flow_kind):
kind = control_flow_kind in (
lldb.eInstructionControlFlowKindCall,
lldb.eInstructionControlFlowKindJump,
lldb.eInstructionControlFlowKindCondJump,
lldb.eInstructionControlFlowKindFarJump,
)
return kind
def is_branch_or_call_at_addr(target, addr_load, frame=None, result_out=None):
"""
Given an lldb.SBTarget and a load address (integer),
return (is_branch_or_call, target_addr_or_None).
If 'frame' is provided (SBFrame), it will be used to resolve
register-indirect targets like:
- x86/x64: call dword ptr [edx], jmp dword ptr [edx], jmp [rax], jmp edx
- ARM: blx r3, bx r4
- ARM64: bl x3, br x4 (when LLDB prints reg as operand)
"""
if debug_mode and result_out:
result_out.PutCString("DEBUG: is_branch_or_call_at_addr checking 0x%x" % addr_load)
if not target or not target.IsValid():
return False, None
arch = get_arch_name(target)
if debug_mode and result_out:
result_out.PutCString("DEBUG: is_branch_or_call_at_addr arch: %s" % arch)
# sb_addr = target.ResolveLoadAddress(addr_load)
sb_addr = target.ResolveFileAddress(addr_load)
if debug_mode and result_out:
result_out.PutCString("DEBUG: is_branch_or_call_at_addr sb_addr %s" % str(sb_addr))
if not sb_addr or not sb_addr.IsValid():
return False, None
# Read raw bytes from memory; this returns a Python bytes object on your build
err = lldb.SBError()
buf = target.ReadMemory(sb_addr, 32, err) # 32 bytes is enough for one instruction
if not err.Success() or not buf:
return False, None
inst_list = target.GetInstructions(sb_addr, buf)
if inst_list.GetSize() == 0:
return False, None
inst = inst_list.GetInstructionAtIndex(0)
if debug_mode and result_out:
result_out.PutCString("DEBUG: is_branch_or_call_at_addr inst: %s" % inst)
if not inst or not inst.IsValid():
return False, None
controlFlowKind = inst.GetControlFlowKind(target)
if debug_mode and result_out:
kind_name_map = {
lldb.eInstructionControlFlowKindUnknown: "Unknown",
lldb.eInstructionControlFlowKindCall: "Call",
lldb.eInstructionControlFlowKindReturn: "Return",
lldb.eInstructionControlFlowKindJump: "Jump",
lldb.eInstructionControlFlowKindCondJump: "CondJump",
lldb.eInstructionControlFlowKindFarCall: "FarCall",
lldb.eInstructionControlFlowKindFarReturn: "FarReturn",
lldb.eInstructionControlFlowKindFarJump: "FarJump",
}
result_out.PutCString("DEBUG: %s" % kind_name_map.get(controlFlowKind, str(controlFlowKind)))
mnemonic = inst.GetMnemonic(target)
result_out.PutCString("mnemonic: %s" % mnemonic)
# if not _is_branch_or_call_mnemonic(mnemonic, arch):
# return False, None
if not is_branch_or_call_kind(controlFlowKind):
return False, None
operands_str = inst.GetOperands(target)
if debug_mode and result_out:
result_out.PutCString("Operands: %s" % operands_str)
tokens = operands_str.replace(",", " ").split()
if not tokens:
# Branch/call with no parsable operands
return (True, None)
# Full operand string (for x86 "[edx]" or "dword ptr [edx]",
# ARM/ARM64 "r3", "x4", etc.)
op_full = operands_str
cand = tokens[0].split(";")[0].strip()
target_addr = None
if debug_mode and result_out:
result_out.PutCString("DEBUG: op_full: %s" % op_full)
# --- 1) Register-indirect forms ---
# x86/x64 example: "dword ptr [edx]" or "[edx]" or "qword ptr [rax]"
if arch in ARCH_X86:
if debug_mode and result_out:
result_out.PutCString("arch in ARCH_X86")
ptr_addr = None
indirect = False
target_addr = None
# Intel syntax: "dword ptr [edx]" or "[edx]", which appears not to be used, even
# though disassembly flavor is set to Intel
if "[" in op_full and "]" in op_full:
if debug_mode and result_out:
result_out.PutCString("Intel disassembly mode")
indirect = True
inside = op_full[op_full.find("[") + 1: op_full.find("]")]
inside = inside.strip()
# Case A: Absolute address "[0x5c15a0]"
try:
if debug_mode and result_out:
result_out.PutCString("DEBUG: Intel syntax, inside: %s" % inside)
ptr_addr = parse_int_literal(inside)
if debug_mode and result_out:
result_out.PutCString("DEBUG: Intel syntax, absolute addr: 0x%x" % ptr_addr)
except ValueError:
# Case B: Register + Offset "[ebp - 0x8]" or "[ebp + 0x10]" or Just Register "[ebp]"
# Simple parser: look for '+' or '-'
import re
# Split by + or - but keep the delimiter
parts = re.split(r'(\+|\-)', inside)
base_val = 0
# 1. Resolve Base (first part)
base_str = parts[0].strip()
reg_val = _resolve_register_value(frame, base_str)
if reg_val is not None:
base_val = reg_val
else:
# Maybe the base is a number? (unlikely for Intel syntax usually [reg+off])
try:
base_val = parse_int_literal(base_str)
except ValueError:
base_val = None
if base_val is not None:
ptr_addr = base_val
# 2. Process Offset if exists
if len(parts) >= 3:
operator = parts[1].strip()
offset_str = parts[2].strip()
try:
offset_val = parse_int_literal(offset_str)
if operator == '+':
ptr_addr += offset_val
elif operator == '-':
ptr_addr -= offset_val
except ValueError:
# Failed to parse offset, abort
ptr_addr = None
if debug_mode and result_out:
result_out.PutCString(
"DEBUG: Intel syntax, resolved ptr_addr: %s" % (hex(ptr_addr) if ptr_addr is not None else "None"))
# New updated AT&T syntax: "*(%edx)" or "*-0x8(%ebp)" or "*0xb15a0" or "*%rax"
elif op_full.startswith("*"):
if debug_mode and result_out:
result_out.PutCString("AT&T disassembly mode")
expr = op_full[1:].strip() # Strip '*'
if debug_mode and result_out:
result_out.PutCString("expr: %s" % expr)
# Case 1: Register-indirect with optional displacement "*(%edx)", "*-0x8(%ebp)"
# equivalent to [EDX], [EBP-8]
if "(%" in expr and expr.endswith(")"):
indirect = True
idx_open = expr.rfind("(")
# part before '(' is displacement
offset_str = expr[:idx_open].strip()
if len(offset_str) == 0:
offset_str = '0'
# part inside '(%...)' is register
inside = expr[idx_open + 1:-1].strip()
reg_name = inside.lstrip("%")
if debug_mode and result_out:
result_out.PutCString("DEBUG: AT&T syntax, reg_name: %s, offset: %s" % (reg_name, offset_str))
base_val = _resolve_register_value(frame, reg_name, result_out)
if debug_mode and result_out:
result_out.PutCString("Result after calling _resolve_register_value, value: %s" % (base_val if base_val is not None else "None"))
if base_val is not None:
ptr_addr = base_val
if debug_mode and result_out:
result_out.PutCString("DEBUG: AT&T syntax, reg_name: %s, value: %s" % (reg_name, hex(ptr_addr)))
if offset_str:
try:
offset_val = parse_int_literal(offset_str)
ptr_addr += offset_val
except ValueError:
ptr_addr = None
# Case 2: Absolute indirect "*0xb15a0" -> read memory at 0xb15a0
elif expr.startswith("0x") or (len(expr) > 0 and expr[0].isdigit()) or expr.startswith("-"):
if debug_mode and result_out:
result_out.PutCString("DEBUG: AT&T syntax, absolute indirect: %s" % expr)
indirect = True
try:
ptr_addr = parse_int_literal(expr)
if debug_mode and result_out:
result_out.PutCString("DEBUG: AT&T syntax, absolute addr: 0x%x" % ptr_addr)
except ValueError:
ptr_addr = None
# Case 3: Direct register "*%eax" -> equivalent to Intel "call eax" (not [eax])
elif expr.startswith("%"):
indirect = False
reg_name = expr.lstrip("%")
if debug_mode and result_out:
result_out.PutCString("DEBUG: AT&T syntax, direct register: %s" % reg_name)
val = _resolve_register_value(frame, reg_name)
if val is not None:
target_addr = val
else:
# jmp edx, call edx, je 0x123456
if debug_mode and result_out:
result_out.PutCString("Direct register / direct address / relative address")
indirect = False
inside = op_full
if debug_mode and result_out:
result_out.PutCString("Direct register / direct address, inside: %s" % inside)
reg_token = inside.strip().split()[0]
if not is_int_literal(reg_token):
if debug_mode and result_out:
result_out.PutCString("DEBUG: Direct register / indirect address, reg_token: %s" % reg_token)
reg_name = reg_token.lstrip('*').strip()
if debug_mode and result_out:
result_out.PutCString("DEBUG: Direct register, reg_name: %s" % reg_name)
ptr_addr = _resolve_register_value(frame, reg_name)
target_addr = ptr_addr
if debug_mode and result_out:
result_out.PutCString("target_addr = %s" % target_addr)
if ptr_addr is not None and indirect:
err = lldb.SBError()
target_addr_size = target.GetAddressByteSize() # 32-bit vs 64-bit
sb_mem_addr = target.ResolveLoadAddress(ptr_addr)
if debug_mode and result_out:
result_out.PutCString("DEBUG: Indirect, sb_mem_addr: %s" % str(sb_mem_addr))
target_bytes = target.ReadMemory(sb_mem_addr, target_addr_size, err)
if debug_mode and result_out:
result_out.PutCString("DEBUG: Indirect, target_bytes: %s" % target_bytes)
if err.Success() and target_bytes and len(target_bytes) == target_addr_size:
is_little = target.GetByteOrder() == lldb.eByteOrderLittle
target_addr = int.from_bytes(target_bytes, byteorder='little' if is_little else 'big')
if debug_mode and result_out:
result_out.PutCString("DEBUG: target_addr: %s" % hex(target_addr))
# ARM / ARM64 example: "blx r3", "bx r4", "br x5", "bl x6"
if target_addr is None and arch in ARCH_ALL_ARM and frame is not None:
# LLDB usually prints just the register as operand, e.g. "r3" or "x5"
reg_name = cand # first token (e.g. "r3", "x5")
# Strip possible condition codes or punctuation (unlikely here)
reg_name = reg_name.strip()
# Try direct register resolution
ptr_val = _resolve_register_value(frame, reg_name)
if ptr_val is not None:
target_addr = ptr_val
# --- 2) Direct hex address (all archs) ---
if target_addr is None and cand.startswith("0x"):
if debug_mode and result_out:
result_out.PutCString("Handling case 2)")
try:
target_addr = parse_int_literal(cand)
except ValueError:
target_addr = None
# --- 3) Symbol name (all archs) ---
if target_addr is None and not cand.startswith("0x"):
if debug_mode and result_out:
result_out.PutCString("Handling case 3)")
syms = target.FindSymbols(cand)
if syms.GetSize() > 0:
sym = syms.GetContextAtIndex(0).GetSymbol()
if sym and sym.IsValid():
sa = sym.GetStartAddress()
if sa and sa.IsValid():
target_addr = sa.GetLoadAddress(target)
# --- 4) Simple PC-relative handling ---
# This appears to be handled under Case 2) already...
if target_addr is None and controlFlowKind == lldb.eInstructionControlFlowKindCondJump:
if debug_mode and result_out:
result_out.PutCString("Handling case 4)")
inst_addr = inst.GetAddress()
if inst_addr and inst_addr.IsValid():
pc = inst_addr.GetLoadAddress(target)
if arch in ARCH_X86:
try:
target_addr = x86_cond_jump_target_from_inst(target, inst)
if debug_mode and result_out:
result_out.PutCString("target_addr: %s" % hex(target_addr))
except ValueError:
pass
else:
# Untested branch for non-x86/x64 targets
target_addr = pc
# --- 5) Register-direct handling for x86/x64 (e.g. "jmp rax") ---
if target_addr is None and arch in ARCH_X86 and frame is not None:
# Try resolving 'cand' as a register name directly
val = _resolve_register_value(frame, cand)
if val is not None:
target_addr = val
return (True, target_addr)
def branch_call_follow(debugger, command, exe_ctx, result, internal_dict, USAGE_STR):
"""
Usage:
cmd <address> [debug]
"""
global debug_mode
target = exe_ctx.target
frame = exe_ctx.frame
if not target or not target.IsValid():
result.PutCString("No valid target.")
return
cmd = command.strip()
if not cmd:
result.PutCString(USAGE_STR)
return
cmd_args = command.strip().split()
if len(cmd_args) < 1:
result.PutCString(USAGE_STR)
return
try:
addr = parse_int_literal(cmd_args[0])
except ValueError:
result.PutCString("Invalid address: %s" % cmd_args[0])
return
debug_mode = len(cmd_args) > 1 and cmd_args[1] == "debug"
current_flavor = get_x86_flavor(debugger)
if debug_mode:
result.PutCString("=== DEBUG: Analyzing 0x%x ===" % addr)
result.PutCString("Disassembly flavor = %s" % current_flavor)
result.PutCString("Arch: %s" % get_arch_name(target))
result.PutCString("Frame valid: %s" % frame.IsValid())
result.PutCString("Target: %s" % str(target))
is_br, tgt = is_branch_or_call_at_addr(target, addr, frame, result)
return is_br, addr, tgt
def cmd_is_branch_or_call(debugger, command, exe_ctx, result, internal_dict):
"""
Usage:
is_branch_or_call <address> [debug]
"""
is_br, addr, tgt = branch_call_follow(debugger, command, exe_ctx, result, internal_dict,
"is_branch_or_call <address> [debug]")
if debug_mode:
result.PutCString("Raw result: is_branch=%s, target=%s" % (is_br, hex(tgt) if tgt else "None"))
if not is_br:
result.PutCString("Instruction at 0x%x is NOT a branch/call." % addr)
elif tgt is None:
result.PutCString(
"Instruction at 0x%x IS a branch/call, but target could not be resolved."
% addr
)
else:
result.PutCString(
"Instruction at 0x%x IS a branch/call; target = 0x%x." % (addr, tgt)
)
def cmd_follow(debugger, command, exe_ctx, result, internal_dict):
"""
Usage:
is_branch_or_call <address> [debug]
"""
is_br, addr, tgt = branch_call_follow(debugger, command, exe_ctx, result, internal_dict,
"Usage: follow <address> [debug]")
if debug_mode:
result.PutCString("Raw result: is_branch=%s, target=%s" % (is_br, hex(tgt) if tgt else "None"))
if not is_br:
result.PutCString("Instruction at 0x%x is NOT a branch/call." % addr)
elif tgt is None:
result.PutCString(
"Instruction at 0x%x IS a branch/call, but target could not be resolved."
% addr
)
else:
di_sent = False
ci = debugger.GetCommandInterpreter()
cmd_line = f"di -s 0x{addr:x} -c 1"
res = lldb.SBCommandReturnObject()
ci.HandleCommand(cmd_line, res)
if res.Succeeded():
result.PutCString("Following %s" % hex(tgt))
di_sent = True
if res.GetError():
result.PutCString("DEBUG: di error: " + res.GetError())
if di_sent:
cmd_line = f"di -s 0x{tgt:x}"
ci.HandleCommand(cmd_line, res)
if res.GetOutput():
result.PutCString(res.GetOutput())
if res.GetError():
result.PutCString("DEBUG: di error: " + res.GetError())