xref: /xnu-12377.61.12/tools/lldbmacros/core/xnu_lldb_init.py (revision 4d495c6e23c53686cf65f45067f79024cf5dcee8)
1import os
2import re
3
4def GetSettingsValues(debugger, setting_variable_name):
5    """ Queries the lldb internal settings
6        params:
7            debugger : lldb.SBDebugger instance
8            setting_variable_name: str - string name of the setting(eg prompt)
9        returns:
10            [] : Array of strings. Empty array if setting is not found/set
11    """
12    retval = []
13    settings_val_list = debugger.GetInternalVariableValue(setting_variable_name, debugger.GetInstanceName())
14    for s in settings_val_list:
15        retval.append(str(s))
16    return retval
17
18def GetSymbolsFilePathFromModule(m):
19    """ Get a file path from a module.
20        params: m - lldb.target.module
21        returns:
22            str : path to first file based symbol. Note this might be dir path inside sources.
23    """
24    for s in m.symbols:
25        if s.type == 8:
26            return os.path.dirname(str(s.name))
27    return ""
28
29def GetSourcePathSettings(binary_path, symbols_path):
30    """ Parse the binary path and symbols_path to find if source-map setting is applicable
31        params:
32            binary_path: str path of the kernel module
33            symbols_path: str path of the symbols stored in binary. Use
34        returns:
35            str : string command to set the source-map setting.
36    """
37    retval = ""
38    train_re = re.compile(r"dsyms/([a-zA-Z]+)/")
39    _t_arr = train_re.findall(binary_path)
40    train = ''
41    if _t_arr:
42        train = _t_arr[0]
43    if not train:
44        return retval
45    new_path = "~rc/Software/{}/Projects/".format(train)
46    new_path = os.path.expanduser(new_path)
47    new_path = os.path.normpath(new_path)
48    common_path_re = re.compile("(^.*?Sources/)(xnu.*?)/.*$")
49    _t_arr = common_path_re.findall(symbols_path)
50    srcpath = ""
51    projpath = "xnu"
52    if _t_arr:
53        srcpath = "".join(_t_arr[0])
54        projpath = _t_arr[0][-1]
55    else:
56        return retval
57
58    new_path = new_path + os.path.sep +  projpath
59    cmd = "settings append target.source-map {} {}"
60    retval =  cmd.format(srcpath, new_path)
61    return retval
62
63def CheckMissingLibs(debugger):
64    """ Check that required modules are installed. """
65
66    # Convert LLDB version string to version tuple.
67    # A version string may be of form: lldb_host-1403.2.6.11 (iPhoneOS)
68    # Code below only matches 1403.2.6.11 and ignores rest of the string.
69    ver_str = debugger.GetVersionString()
70    lldb_ver = re.search("^lldb.*-([0-9.]+)", ver_str, re.MULTILINE).group(1)
71    ver = tuple(map(int, lldb_ver.split('.')))
72
73    # Display correct command to install missing packages.
74    if ver[1] == 2:
75        cmd_fmt = "Please install {mod:s}: xcrun --sdk <sdk> python3 -m pip install --user --ignore-installed {mod:s}"
76    else:
77        cmd_fmt = "Please install {mod:s}: xcrun pip3 install --user --ignore-installed {mod:s}"
78
79    try:
80        import macholib
81    except:
82        print(cmd_fmt.format(mod="macholib"))
83        return False
84
85    return True
86
87def __lldb_init_module(debugger, internal_dict):
88
89    if not CheckMissingLibs(debugger):
90        print("Can't load LLDB macros. Please install dependencies first.")
91        return
92
93    debug_session_enabled = False
94    if "DEBUG_XNU_LLDBMACROS" in os.environ and len(os.environ['DEBUG_XNU_LLDBMACROS']) > 0:
95        debug_session_enabled = True
96    prev_os_plugin = "".join(GetSettingsValues(debugger, 'target.process.python-os-plugin-path'))
97    print("Loading kernel debugging from %s" % __file__)
98    print("LLDB version %s" % debugger.GetVersionString())
99    self_path = "{}".format(__file__)
100    base_dir_name = self_path[:self_path.rfind("/")]
101    core_os_plugin = base_dir_name + "/lldbmacros/core/operating_system.py"
102    osplugin_cmd = "settings set target.process.python-os-plugin-path \"%s\"" % core_os_plugin
103    intel_whitelist = ['hndl_allintrs', 'hndl_alltraps', 'trap_from_kernel', 'hndl_double_fault', 'hndl_machine_check']
104    arm_whitelist = ['_fleh_prefabt', '_ExceptionVectorsBase', '_ExceptionVectorsTable', '_fleh_undef', '_fleh_dataabt', '_fleh_irq', '_fleh_decirq', '_fleh_fiq_generic', '_fleh_dec']
105    whitelist_trap_cmd = "settings set target.trap-handler-names %s %s" % (' '.join(intel_whitelist), ' '.join(arm_whitelist))
106    xnu_debug_path = base_dir_name + "/lldbmacros/xnu.py"
107    xnu_load_cmd = "command script import \"%s\"" % xnu_debug_path
108    disable_optimization_warnings_cmd = "settings set target.process.optimization-warnings false"
109
110    # Single stepping support
111    report_all_threads_cmd = "settings set target.process.experimental.os-plugin-reports-all-threads false"
112    step_mode_cmd = "settings set target.process.run-all-threads true"
113
114    source_map_cmd = ""
115    try:
116        source_map_cmd = GetSourcePathSettings(base_dir_name, GetSymbolsFilePathFromModule(debugger.GetTargetAtIndex(0).modules[0]) )
117    except Exception as e:
118        pass
119    if debug_session_enabled :
120        if len(prev_os_plugin) > 0:
121            print("\nDEBUG_XNU_LLDBMACROS is set. Skipping the setting of OS plugin from dSYM.\nYou can manually set the OS plugin by running\n" + osplugin_cmd)
122        else:
123            print(osplugin_cmd)
124            debugger.HandleCommand(osplugin_cmd)
125        print("\nDEBUG_XNU_LLDBMACROS is set. Skipping the load of xnu debug framework.\nYou can manually load the framework by running\n" + xnu_load_cmd)
126    else:
127        print(osplugin_cmd)
128        debugger.HandleCommand(osplugin_cmd)
129        print(whitelist_trap_cmd)
130        debugger.HandleCommand(whitelist_trap_cmd)
131        print(xnu_load_cmd)
132        debugger.HandleCommand(xnu_load_cmd)
133        print(disable_optimization_warnings_cmd)
134        debugger.HandleCommand(disable_optimization_warnings_cmd)
135        print(report_all_threads_cmd)
136        debugger.HandleCommand(report_all_threads_cmd)
137        print(step_mode_cmd)
138        debugger.HandleCommand(step_mode_cmd)
139        if source_map_cmd:
140            print(source_map_cmd)
141            debugger.HandleCommand(source_map_cmd)
142
143        load_kexts = True
144        if "XNU_LLDBMACROS_NOBUILTINKEXTS" in os.environ and len(os.environ['XNU_LLDBMACROS_NOBUILTINKEXTS']) > 0:
145            load_kexts = False
146        builtinkexts_path = os.path.join(os.path.dirname(self_path), "lldbmacros", "builtinkexts")
147        if os.access(builtinkexts_path, os.F_OK):
148            kexts = os.listdir(builtinkexts_path)
149            if len(kexts) > 0:
150                print("\nBuiltin kexts: %s\n" % kexts)
151                if not load_kexts:
152                    print("XNU_LLDBMACROS_NOBUILTINKEXTS is set, not loading:\n")
153                for kextdir in kexts:
154                    # Python does not handle well modules that contain '-' in their names.
155                    # Remap such scripts to use '_' instead.
156                    script_name = kextdir.split('.')[-1].replace('-', '_') + ".py"
157                    script = os.path.join(builtinkexts_path, kextdir, script_name)
158
159                    import_kext_cmd = "command script import \"%s\"" % script
160                    print("%s" % import_kext_cmd)
161                    if load_kexts:
162                        debugger.HandleCommand(import_kext_cmd)
163
164    print("\n")
165
166