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