Section 10/161 menit

10. Python Scripting di LLDB

10. Python Scripting di LLDB

LLDB memiliki Python API penuh — developer bisa menulis script untuk mengotomasi tugas debugging yang repetitif.

Script Python Sederhana

swift
# ~/lldb_scripts/swift_helpers.py

import lldb

def print_view_hierarchy(debugger, command, result, internal_dict):
    """Cetak view hierarchy UIKit dari LLDB."""
    target = debugger.GetSelectedTarget()
    process = target.GetProcess()
    thread = process.GetSelectedThread()
    frame = thread.GetSelectedFrame()

    # Evaluasi ekspresi Swift
    expr = """
    import UIKit
    let $hierarchy = UIApplication.shared.keyWindow?.perform(
        Selector(("recursiveDescription"))
    )?.takeUnretainedValue() as? String ?? "No window"
    $hierarchy
    """
    value = frame.EvaluateExpression(expr)
    result.AppendMessage(value.GetSummary() or "Could not get hierarchy")


def format_user(debugger, command, result, internal_dict):
    """Format dan tampilkan User model dengan informasi lengkap."""
    target = debugger.GetSelectedTarget()
    frame = target.GetProcess().GetSelectedThread().GetSelectedFrame()

    var_name = command.strip() or "self"
    value = frame.FindVariable(var_name)

    if not value.IsValid():
        result.AppendMessage(f"Variable '{var_name}' tidak ditemukan")
        return

    output = []
    output.append(f"=== {var_name} ===")
    for i in range(value.GetNumChildren()):
        child = value.GetChildAtIndex(i)
        output.append(f"  {child.GetName()}: {child.GetValue() or child.GetSummary()}")

    result.AppendMessage("\n".join(output))


def __lldb_init_module(debugger, internal_dict):
    """Dipanggil saat module di-load — daftarkan semua commands."""
    debugger.HandleCommand(
        'command script add -f swift_helpers.print_view_hierarchy pvh'
    )
    debugger.HandleCommand(
        'command script add -f swift_helpers.format_user fu'
    )
    print("Swift helpers loaded: pvh (view hierarchy), fu (format user)")
swift
# Setelah import script:
(lldb) pvh          → cetak view hierarchy
(lldb) fu myUser    → format User variable
(lldb) fu           → format 'self'

Script untuk Debugging Core Data / SwiftData

swift
# ~/lldb_scripts/swiftdata_debug.py

import lldb

def count_model_objects(debugger, command, result, internal_dict):
    """Hitung jumlah object SwiftData di context."""
    frame = debugger.GetSelectedTarget().GetProcess()\
                    .GetSelectedThread().GetSelectedFrame()

    model_name = command.strip()
    if not model_name:
        result.AppendMessage("Usage: sdcount <ModelTypeName>")
        return

    expr = f"""
    import SwiftData
    let $descriptor = FetchDescriptor<{model_name}>()
    let $count = try? modelContext.fetchCount($descriptor)
    $count ?? -1
    """
    value = frame.EvaluateExpression(expr)
    result.AppendMessage(f"{model_name} count: {value.GetValue()}")


def __lldb_init_module(debugger, internal_dict):
    debugger.HandleCommand(
        'command script add -f swiftdata_debug.count_model_objects sdcount'
    )
    print("SwiftData debug helpers loaded: sdcount")