xref: /xnu-12377.41.6/doc/debugging/debugging.md (revision bbb1b6f9e71b8cdde6e5cd6f4841f207dee3d828)
1*bbb1b6f9SApple OSS Distributions# XNU debugging
2*bbb1b6f9SApple OSS Distributions
3*bbb1b6f9SApple OSS DistributionsDebugging XNU through kernel core files or with a live device.
4*bbb1b6f9SApple OSS Distributions
5*bbb1b6f9SApple OSS Distributions## Overview
6*bbb1b6f9SApple OSS Distributions
7*bbb1b6f9SApple OSS DistributionsXNU’s debugging macros are compatible with Python 3.9+. Please be careful about pulling
8*bbb1b6f9SApple OSS Distributionsin the latest language features. Some users are living on older Xcodes and may not have the newest
9*bbb1b6f9SApple OSS DistributionsPython installed.
10*bbb1b6f9SApple OSS Distributions
11*bbb1b6f9SApple OSS Distributions## General coding tips
12*bbb1b6f9SApple OSS Distributions
13*bbb1b6f9SApple OSS Distributions### Imports
14*bbb1b6f9SApple OSS Distributions
15*bbb1b6f9SApple OSS DistributionsThe current implementation re-exports a lot of submodules through the XNU main module. This leads to some
16*bbb1b6f9SApple OSS Distributionssurprising behavior:
17*bbb1b6f9SApple OSS Distributions
18*bbb1b6f9SApple OSS Distributions* Name collisions at the top level may override methods with unexpected results.
19*bbb1b6f9SApple OSS Distributions* New imports may change the order of imports, leading to some surpising side effects.
20*bbb1b6f9SApple OSS Distributions
21*bbb1b6f9SApple OSS DistributionsPlease avoid `from xnu import *` where possible and always explicitly import only what is
22*bbb1b6f9SApple OSS Distributionsrequired from other modules.
23*bbb1b6f9SApple OSS Distributions
24*bbb1b6f9SApple OSS Distributions### Checking the type of an object
25*bbb1b6f9SApple OSS Distributions
26*bbb1b6f9SApple OSS DistributionsAvoid testing for a `type` explicitly like `type(obj) == type`.
27*bbb1b6f9SApple OSS DistributionsInstead, always use the inheritance-sensitive `isinstance(obj, type)`.
28*bbb1b6f9SApple OSS Distributions
29*bbb1b6f9SApple OSS Distributions### Dealing with binary data
30*bbb1b6f9SApple OSS Distributions
31*bbb1b6f9SApple OSS DistributionsIt’s recommended to use **bytearray**, **bytes**, and **memoryviews** instead of a string.
32*bbb1b6f9SApple OSS DistributionsSome LLDB APIs no longer accept a string in place of binary data in Python 3.
33*bbb1b6f9SApple OSS Distributions
34*bbb1b6f9SApple OSS Distributions### Accessing large amounts of binary data (or accessing small amounts frequently)
35*bbb1b6f9SApple OSS Distributions
36*bbb1b6f9SApple OSS DistributionsIn case you're planning on accessing large contiguous blocks of memory (e.g. reading a whole 10KB of memory),
37*bbb1b6f9SApple OSS Distributionsor you're accessing small semi-contiguous chunks (e.g. if you're parsing large structured data), then it might
38*bbb1b6f9SApple OSS Distributionsbe hugely beneficial performance-wise to make use of the `io.SBProcessRawIO` class. Furthermore, if you're in
39*bbb1b6f9SApple OSS Distributionsa hurry and just want to read one specific chunk once, then it might be easier to use `LazyTarget.GetProcess().ReadMemory()`
40*bbb1b6f9SApple OSS Distributionsdirectly.
41*bbb1b6f9SApple OSS Distributions
42*bbb1b6f9SApple OSS DistributionsIn other words, avoid the following:
43*bbb1b6f9SApple OSS Distributions
44*bbb1b6f9SApple OSS Distributions```
45*bbb1b6f9SApple OSS Distributionsdata_ptr = kern.GetValueFromAddress(start_addr, 'uint8_t *')
46*bbb1b6f9SApple OSS Distributionswith open(filepath, 'wb') as f:
47*bbb1b6f9SApple OSS Distributions    f.write(data_ptr[:4096])
48*bbb1b6f9SApple OSS Distributions```
49*bbb1b6f9SApple OSS Distributions
50*bbb1b6f9SApple OSS DistributionsAnd instead use:
51*bbb1b6f9SApple OSS Distributions
52*bbb1b6f9SApple OSS Distributions```
53*bbb1b6f9SApple OSS Distributionsfrom core.io import SBProcessRawIO
54*bbb1b6f9SApple OSS Distributionsimport shutil
55*bbb1b6f9SApple OSS Distributions
56*bbb1b6f9SApple OSS Distributionsio_access = SBProcessRawIO(LazyTarget.GetProcess(), start_addr, 4096)
57*bbb1b6f9SApple OSS Distributionswith open(filepath, 'wb') as f:
58*bbb1b6f9SApple OSS Distributions    shutil.copyfileobj(io_access, f)
59*bbb1b6f9SApple OSS Distributions```
60*bbb1b6f9SApple OSS Distributions
61*bbb1b6f9SApple OSS DistributionsOr, if you're in a hurry:
62*bbb1b6f9SApple OSS Distributions
63*bbb1b6f9SApple OSS Distributions```
64*bbb1b6f9SApple OSS Distributionserr = lldb.SBError()
65*bbb1b6f9SApple OSS Distributionsmy_data = LazyTarget.GetProcess().ReadMemory(start_addr, length, err)
66*bbb1b6f9SApple OSS Distributionsif err.Success():
67*bbb1b6f9SApple OSS Distributions    # Use my precious data
68*bbb1b6f9SApple OSS Distributions    pass
69*bbb1b6f9SApple OSS Distributions```
70*bbb1b6f9SApple OSS Distributions
71*bbb1b6f9SApple OSS DistributionsFor small semi-contiguous chunks, you can map the whole region and access random chunks from it like so:
72*bbb1b6f9SApple OSS Distributions
73*bbb1b6f9SApple OSS Distributions```
74*bbb1b6f9SApple OSS Distributionsfrom core.io import SBProcessRawIO
75*bbb1b6f9SApple OSS Distributions
76*bbb1b6f9SApple OSS Distributionsio_access = SBProcessRawIO(LazyTarget.GetProcess(), start_addr, size)
77*bbb1b6f9SApple OSS Distributionsio_access.seek(my_struct_offset)
78*bbb1b6f9SApple OSS Distributionsmy_struct_contents = io_access.read(my_struct_size)
79*bbb1b6f9SApple OSS Distributions```
80*bbb1b6f9SApple OSS Distributions
81*bbb1b6f9SApple OSS DistributionsNot only that, but you can also tack on a BufferedRandom class on top of the SBProcessRawIO instance, which
82*bbb1b6f9SApple OSS Distributionsprovides you with buffering (aka caching) in case your random small chunk accesses are repeated:
83*bbb1b6f9SApple OSS Distributions
84*bbb1b6f9SApple OSS Distributions```
85*bbb1b6f9SApple OSS Distributionsfrom core.io import SBProcessRawIO
86*bbb1b6f9SApple OSS Distributionsfrom io import BufferedRandom
87*bbb1b6f9SApple OSS Distributions
88*bbb1b6f9SApple OSS Distributionsio_access = SBProcessRawIO(LazyTarget.GetProcess(), start_addr, size)
89*bbb1b6f9SApple OSS Distributionsbuffered_io = BufferedRandom(io_access)
90*bbb1b6f9SApple OSS Distributions# And then use buffered_io for your accesses
91*bbb1b6f9SApple OSS Distributions```
92*bbb1b6f9SApple OSS Distributions
93*bbb1b6f9SApple OSS Distributions### Encoding data to strings and back
94*bbb1b6f9SApple OSS Distributions
95*bbb1b6f9SApple OSS DistributionsAll strings are now `unicode` and must be converted between binary data and strings explicitly.
96*bbb1b6f9SApple OSS DistributionsWhen no explicit encoding is selected then UTF-8 is the default.
97*bbb1b6f9SApple OSS Distributions
98*bbb1b6f9SApple OSS Distributions```
99*bbb1b6f9SApple OSS Distributionsmystring = mybytes.decode()
100*bbb1b6f9SApple OSS Distributionsmybytes = mystring.encode()
101*bbb1b6f9SApple OSS Distributions```
102*bbb1b6f9SApple OSS DistributionsIn most cases **utf-8** will work but be careful to be sure that the encoding matches your data.
103*bbb1b6f9SApple OSS Distributions
104*bbb1b6f9SApple OSS DistributionsThere are two options to consider when trying to get a string out of the raw data without knowing if
105*bbb1b6f9SApple OSS Distributionsthey are valid string or not:
106*bbb1b6f9SApple OSS Distributions
107*bbb1b6f9SApple OSS Distributions* **lossy conversion** - escapes all non-standard characters in form of ‘\xNNN’
108*bbb1b6f9SApple OSS Distributions* **lossless conversion** - maps invalid characters to special unicode range so it can reconstruct
109*bbb1b6f9SApple OSS Distributionsthe string precisely
110*bbb1b6f9SApple OSS Distributions
111*bbb1b6f9SApple OSS DistributionsWhich to use depends on the transformation goals. The lossy conversion produces a printable string
112*bbb1b6f9SApple OSS Distributionswith strange characters in it. The lossless option is meant to be used when a string is only a transport
113*bbb1b6f9SApple OSS Distributionsmechanism and needs to be converted back to original values later.
114*bbb1b6f9SApple OSS Distributions
115*bbb1b6f9SApple OSS DistributionsSwitch the method by using `errors` handler during conversion:
116*bbb1b6f9SApple OSS Distributions
117*bbb1b6f9SApple OSS Distributions```
118*bbb1b6f9SApple OSS Distributions# Lossy escapes invalid chars
119*bbb1b6f9SApple OSS Distributionsb.decode('utf-8', errors='`backslashreplace'`)
120*bbb1b6f9SApple OSS Distributions# Lossy removes invalid chars
121*bbb1b6f9SApple OSS Distributionsb.decode('utf-8', errors='ignore')
122*bbb1b6f9SApple OSS Distributions# Loss-less but may likely fail to print()
123*bbb1b6f9SApple OSS Distributionsb.decode('utf-8', errors='surrogateescape')
124*bbb1b6f9SApple OSS Distributions```
125*bbb1b6f9SApple OSS Distributions
126*bbb1b6f9SApple OSS Distributions### Dealing with signed numbers
127*bbb1b6f9SApple OSS Distributions
128*bbb1b6f9SApple OSS DistributionsPython's int has unlimited precision. This may be surprising for kernel developers who expect
129*bbb1b6f9SApple OSS Distributionsthe behavior follows twos complement.
130*bbb1b6f9SApple OSS Distributions
131*bbb1b6f9SApple OSS DistributionsAlways use **unsigned()** or **signed()** regardless of what the actual underlying type is
132*bbb1b6f9SApple OSS Distributionsto ensure that macros use the correct semantics.
133*bbb1b6f9SApple OSS Distributions
134*bbb1b6f9SApple OSS Distributions## Testing changes
135*bbb1b6f9SApple OSS Distributions
136*bbb1b6f9SApple OSS DistributionsPlease check documentation here: <doc:macro_testing>
137*bbb1b6f9SApple OSS Distributions
138*bbb1b6f9SApple OSS Distributions### Coding style
139*bbb1b6f9SApple OSS Distributions
140*bbb1b6f9SApple OSS DistributionsUse a static analyzer like **pylint** or **flake8** to check the macro source code:
141*bbb1b6f9SApple OSS Distributions
142*bbb1b6f9SApple OSS Distributions```
143*bbb1b6f9SApple OSS Distributions$ python3 -m pip install --user pylint flake8
144*bbb1b6f9SApple OSS Distributions
145*bbb1b6f9SApple OSS Distributions# Run the lint either by setting your path to point to one of the runtimes
146*bbb1b6f9SApple OSS Distributions# or through python
147*bbb1b6f9SApple OSS Distributions$ python3 -m pylint <src files/dirs>
148*bbb1b6f9SApple OSS Distributions$ python3 -m flake8 <src files/dirs>
149*bbb1b6f9SApple OSS Distributions```
150*bbb1b6f9SApple OSS Distributions
151*bbb1b6f9SApple OSS Distributions### Correctness
152*bbb1b6f9SApple OSS Distributions
153*bbb1b6f9SApple OSS DistributionsEnsure the macro matches what LLDB returns from the REPL. For example, compare `showproc(xxx)` with `p/x *(proc_t)xxx`.
154*bbb1b6f9SApple OSS Distributions
155*bbb1b6f9SApple OSS Distributions```
156*bbb1b6f9SApple OSS Distributions# 1. Run LLDB with debug options set
157*bbb1b6f9SApple OSS Distributions$ DEBUG_XNU_LLDBMACROS=1 xcrun -sdk <sdk> lldb -c core <dsympath>/mach_kernel
158*bbb1b6f9SApple OSS Distributions
159*bbb1b6f9SApple OSS Distributions# 2. Optionally load modified operating system plugin
160*bbb1b6f9SApple OSS Distributions(lldb) settings set target.process.python-os-plugin-path <srcpath>/tools/lldbmacros/core/operating_system.py
161*bbb1b6f9SApple OSS Distributions
162*bbb1b6f9SApple OSS Distributions# 3. Load modified scripts
163*bbb1b6f9SApple OSS Distributions(lldb) command script import <srcpath>/tools/lldbmacros/xnu.py
164*bbb1b6f9SApple OSS Distributions
165*bbb1b6f9SApple OSS Distributions# 4. Exercise macros
166*bbb1b6f9SApple OSS Distributions```
167*bbb1b6f9SApple OSS Distributions
168*bbb1b6f9SApple OSS DistributionsDepending on the change, test other targets and architectures (for instance, both Astris and KDP).
169*bbb1b6f9SApple OSS Distributions
170*bbb1b6f9SApple OSS Distributions### Regression
171*bbb1b6f9SApple OSS Distributions
172*bbb1b6f9SApple OSS DistributionsThis is simpler than previous step because the goal is to ensure behavior has not changed.
173*bbb1b6f9SApple OSS DistributionsYou can speed up few things by using local symbols:
174*bbb1b6f9SApple OSS Distributions
175*bbb1b6f9SApple OSS Distributions```
176*bbb1b6f9SApple OSS Distributions# 1. Get a coredump from a device and kernel UUID
177*bbb1b6f9SApple OSS Distributions# 2. Grab symbols with dsymForUUID
178*bbb1b6f9SApple OSS Distributions$ dsymForUUID --nocache --copyExecutable --copyDestination <dsym path>
179*bbb1b6f9SApple OSS Distributions
180*bbb1b6f9SApple OSS Distributions# 3. Run lldb with local symbols to avoid dsymForUUID NFS
181*bbb1b6f9SApple OSS Distributions
182*bbb1b6f9SApple OSS Distributions$ xcrun -sdk <sdk> lldb -c core <dsym_path>/<kernel image>
183*bbb1b6f9SApple OSS Distributions```
184*bbb1b6f9SApple OSS Distributions
185*bbb1b6f9SApple OSS DistributionsThe actual steps are identical to previous testing. Run of a macro to different file with `-o <outfile>`
186*bbb1b6f9SApple OSS Distributionsoption. Then run `diff` on the outputs of the baseline and modified code:
187*bbb1b6f9SApple OSS Distributions
188*bbb1b6f9SApple OSS Distributions* No environment variables to get baseline
189*bbb1b6f9SApple OSS Distributions* Modified dSYM as described above
190*bbb1b6f9SApple OSS Distributions
191*bbb1b6f9SApple OSS DistributionsIt’s difficult to make this automated:
192*bbb1b6f9SApple OSS Distributions
193*bbb1b6f9SApple OSS Distributions* Some macros needs arguments which must be found in a core file.
194*bbb1b6f9SApple OSS Distributions* Some macros take a long time to run against a target (more than 30 minutes). Instead, a core dump
195*bbb1b6f9SApple OSS Distributions  should be taken and then inspected afterwards, but this ties up a lab device for the duration of the
196*bbb1b6f9SApple OSS Distributions  test.
197*bbb1b6f9SApple OSS Distributions* Even with coredumps, testing the macros takes too long in our automation system and triggers the
198*bbb1b6f9SApple OSS Distributions  failsafe timeout.
199*bbb1b6f9SApple OSS Distributions
200*bbb1b6f9SApple OSS Distributions### Code coverage
201*bbb1b6f9SApple OSS Distributions
202*bbb1b6f9SApple OSS DistributionsUse code coverage to check which parts of macros have actually been tested.
203*bbb1b6f9SApple OSS DistributionsInstall **coverage** lib with:
204*bbb1b6f9SApple OSS Distributions
205*bbb1b6f9SApple OSS Distributions```
206*bbb1b6f9SApple OSS Distributions$ python3 -m pip install --user coverage
207*bbb1b6f9SApple OSS Distributions```
208*bbb1b6f9SApple OSS Distributions
209*bbb1b6f9SApple OSS DistributionsThen collect coverage:.
210*bbb1b6f9SApple OSS Distributions
211*bbb1b6f9SApple OSS Distributions```
212*bbb1b6f9SApple OSS Distributions(lldb) xnudebug coverage /tmp/coverage.cov showallstacks
213*bbb1b6f9SApple OSS Distributions
214*bbb1b6f9SApple OSS Distributions...
215*bbb1b6f9SApple OSS Distributions
216*bbb1b6f9SApple OSS DistributionsCoverage info saved to: "/tmp/coverage.cov"
217*bbb1b6f9SApple OSS Distributions```
218*bbb1b6f9SApple OSS Distributions
219*bbb1b6f9SApple OSS DistributionsYou can then run `coverage html --data-file=/tmp/coverage.cov` in your terminal
220*bbb1b6f9SApple OSS Distributionsto generate an HTML report.
221*bbb1b6f9SApple OSS Distributions
222*bbb1b6f9SApple OSS Distributions
223*bbb1b6f9SApple OSS DistributionsCombine coverage from multiple files:
224*bbb1b6f9SApple OSS Distributions
225*bbb1b6f9SApple OSS Distributions```
226*bbb1b6f9SApple OSS Distributions# Point PATH to local python where coverage is installed.
227*bbb1b6f9SApple OSS Distributions$ export PATH="$HOME/Library/Python/3.8/bin:$PATH"
228*bbb1b6f9SApple OSS Distributions
229*bbb1b6f9SApple OSS Distributions# Use --keep to avoid deletion of input files after merge.
230*bbb1b6f9SApple OSS Distributions$ coverage combine --keep <list of .coverage files or dirs to scan>
231*bbb1b6f9SApple OSS Distributions
232*bbb1b6f9SApple OSS Distributions# Get HTML report or use other subcommands to inspect.
233*bbb1b6f9SApple OSS Distributions$ coverage html
234*bbb1b6f9SApple OSS Distributions```
235*bbb1b6f9SApple OSS Distributions
236*bbb1b6f9SApple OSS DistributionsIt is possible to start coverage collection **before** importing the operating system library and
237*bbb1b6f9SApple OSS Distributionsloading macros to check code run during bootstrapping.
238*bbb1b6f9SApple OSS Distributions
239*bbb1b6f9SApple OSS DistributionsFor this, you'll need to run coverage manually:
240*bbb1b6f9SApple OSS Distributions# 1. Start LLDB
241*bbb1b6f9SApple OSS Distributions
242*bbb1b6f9SApple OSS Distributions# 2. Load and start code coverage recording.
243*bbb1b6f9SApple OSS Distributions(lldb) script import coverage
244*bbb1b6f9SApple OSS Distributions(lldb) script cov = coverage.Coverage(data_file=_filepath_)
245*bbb1b6f9SApple OSS Distributions(lldb) script cov.start()
246*bbb1b6f9SApple OSS Distributions
247*bbb1b6f9SApple OSS Distributions# 3. Load macros
248*bbb1b6f9SApple OSS Distributions
249*bbb1b6f9SApple OSS Distributions# 4. Collect the coverage.
250*bbb1b6f9SApple OSS Distributions(lldb) script cov.stop()
251*bbb1b6f9SApple OSS Distributions(lldb) script cov.save()
252*bbb1b6f9SApple OSS Distributions
253*bbb1b6f9SApple OSS Distributions### Performance testing
254*bbb1b6f9SApple OSS Distributions
255*bbb1b6f9SApple OSS DistributionsSome macros can run for a long time. Some code may be costly even if it looks simple because objects
256*bbb1b6f9SApple OSS Distributionsaren’t cached or too many temporary objects are created. Simple profiling is similar to collecting
257*bbb1b6f9SApple OSS Distributionscode coverage.
258*bbb1b6f9SApple OSS Distributions
259*bbb1b6f9SApple OSS DistributionsFirst setup your environment:
260*bbb1b6f9SApple OSS Distributions
261*bbb1b6f9SApple OSS Distributions```
262*bbb1b6f9SApple OSS Distributions# Install gprof2dot
263*bbb1b6f9SApple OSS Distributions$ python3 -m pip install gprof2dot
264*bbb1b6f9SApple OSS Distributions# Install graphviz
265*bbb1b6f9SApple OSS Distributions$ brew install graphviz
266*bbb1b6f9SApple OSS Distributions```
267*bbb1b6f9SApple OSS Distributions
268*bbb1b6f9SApple OSS DistributionsThen to profile commands, follow this sequence:
269*bbb1b6f9SApple OSS Distributions
270*bbb1b6f9SApple OSS Distributions```
271*bbb1b6f9SApple OSS Distributions(lldb) xnudebug profile /tmp/macro.prof showcurrentstacks
272*bbb1b6f9SApple OSS Distributions[... command outputs ...]
273*bbb1b6f9SApple OSS Distributions
274*bbb1b6f9SApple OSS Distributions   Ordered by: cumulative time
275*bbb1b6f9SApple OSS Distributions   List reduced from 468 to 30 due to restriction <30>
276*bbb1b6f9SApple OSS Distributions
277*bbb1b6f9SApple OSS Distributions   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
278*bbb1b6f9SApple OSS Distributions   [... profiling output ...]
279*bbb1b6f9SApple OSS Distributions
280*bbb1b6f9SApple OSS DistributionsProfile info saved to "/tmp/macro.prof"
281*bbb1b6f9SApple OSS Distributions```
282*bbb1b6f9SApple OSS Distributions
283*bbb1b6f9SApple OSS DistributionsThen to visualize callgraphs in context, in a separate shell:
284*bbb1b6f9SApple OSS Distributions
285*bbb1b6f9SApple OSS Distributions```
286*bbb1b6f9SApple OSS Distributions# Now convert the file to a colored SVG call graph
287*bbb1b6f9SApple OSS Distributions$ python3 -m gprof2dot -f pstats /tmp/macro.prof -o /tmp/call.dot
288*bbb1b6f9SApple OSS Distributions$ dot -O -T svg /tmp/call.dot
289*bbb1b6f9SApple OSS Distributions
290*bbb1b6f9SApple OSS Distributions# and view it in your favourite viewer
291*bbb1b6f9SApple OSS Distributions$ open /tmp/call.dot.svg
292*bbb1b6f9SApple OSS Distributions```
293*bbb1b6f9SApple OSS Distributions
294*bbb1b6f9SApple OSS Distributions## Debugging your changes
295*bbb1b6f9SApple OSS Distributions
296*bbb1b6f9SApple OSS Distributions### Get detailed exception report
297*bbb1b6f9SApple OSS Distributions
298*bbb1b6f9SApple OSS DistributionsThe easiest way to debug an exception is to re-run your macro with the `--debug` option.
299*bbb1b6f9SApple OSS DistributionsThis turns on more detailed output for each stack frame that includes source lines
300*bbb1b6f9SApple OSS Distributionsand local variables.
301*bbb1b6f9SApple OSS Distributions
302*bbb1b6f9SApple OSS Distributions### File a radar
303*bbb1b6f9SApple OSS Distributions
304*bbb1b6f9SApple OSS DistributionsTo report an actionable radar, please use re-run your failing macro with `--radar`.
305*bbb1b6f9SApple OSS DistributionsThis will collect additional logs to an archive located in `/tmp`.
306*bbb1b6f9SApple OSS Distributions
307*bbb1b6f9SApple OSS DistributionsUse the link provided to create a new radar.
308*bbb1b6f9SApple OSS Distributions
309*bbb1b6f9SApple OSS Distributions### Debugging with pdb
310*bbb1b6f9SApple OSS Distributions
311*bbb1b6f9SApple OSS DistributionsYES, It is possible to use a debugger to debug your macro!
312*bbb1b6f9SApple OSS Distributions
313*bbb1b6f9SApple OSS DistributionsThe steps are similar to testing techniques described above (use scripting interactive mode). There is no point to
314*bbb1b6f9SApple OSS Distributionsdocument the debugger itself. Lets focus on how to use it on a real life example. The debugger used here is PDB which
315*bbb1b6f9SApple OSS Distributionsis part of Python installation so works out of the box.
316*bbb1b6f9SApple OSS Distributions
317*bbb1b6f9SApple OSS DistributionsProblem: Something wrong is going on with addkext macro. What now?
318*bbb1b6f9SApple OSS Distributions
319*bbb1b6f9SApple OSS Distributions    (lldb) addkext -N com.apple.driver.AppleT8103PCIeC
320*bbb1b6f9SApple OSS Distributions    Failed to read MachO for address 18446741875027613136 errormessage: seek to offset 2169512 is outside window [0, 1310]
321*bbb1b6f9SApple OSS Distributions    Failed to read MachO for address 18446741875033537424 errormessage: seek to offset 8093880 is outside window [0, 1536]
322*bbb1b6f9SApple OSS Distributions    Failed to read MachO for address 18446741875033568304 errormessage: seek to offset 8124208 is outside window [0, 1536]
323*bbb1b6f9SApple OSS Distributions	...
324*bbb1b6f9SApple OSS Distributions	Fetching dSYM for 049b9a29-2efc-32c0-8a7f-5f29c12b870c
325*bbb1b6f9SApple OSS Distributions    Adding dSYM (049b9a29-2efc-32c0-8a7f-5f29c12b870c) for /Library/Caches/com.apple.bni.symbols/bursar.apple.com/dsyms/StarE/AppleEmbeddedPCIE/AppleEmbeddedPCIE-502.100.35~3/049B9A29-2EFC-32C0-8A7F-5F29C12B870C/AppleT8103PCIeC
326*bbb1b6f9SApple OSS Distributions    section '__TEXT' loaded at 0xfffffe001478c780
327*bbb1b6f9SApple OSS Distributions
328*bbb1b6f9SApple OSS DistributionsThere is no exception, lot of errors and no output. So what next?
329*bbb1b6f9SApple OSS DistributionsTry to narrow the problem down to an isolated piece of macro code:
330*bbb1b6f9SApple OSS Distributions
331*bbb1b6f9SApple OSS Distributions  1. Try to get values of globals through regular LLDB commands
332*bbb1b6f9SApple OSS Distributions  2. Use interactive mode and invoke functions with arguments directly.
333*bbb1b6f9SApple OSS Distributions
334*bbb1b6f9SApple OSS DistributionsAfter inspecting addkext macro code and calling few functions with arguments directly we can see that there is an
335*bbb1b6f9SApple OSS Distributionsexception in the end. It was just captured in try/catch block. So the simplified reproducer is:
336*bbb1b6f9SApple OSS Distributions
337*bbb1b6f9SApple OSS Distributions    (lldb) script
338*bbb1b6f9SApple OSS Distributions    >>> import lldb
339*bbb1b6f9SApple OSS Distributions    >>> import xnu
340*bbb1b6f9SApple OSS Distributions    >>> err = lldb.SBError()
341*bbb1b6f9SApple OSS Distributions    >>> data = xnu.LazyTarget.GetProcess().ReadMemory(0xfffffe0014c0f3f0, 0x000000000001b5d0, err)
342*bbb1b6f9SApple OSS Distributions    >>> m = macho.MemMacho(data, len(data))
343*bbb1b6f9SApple OSS Distributions    Traceback (most recent call last):
344*bbb1b6f9SApple OSS Distributions      File "<console>", line 1, in <module>
345*bbb1b6f9SApple OSS Distributions      File ".../lldbmacros/macho.py", line 91, in __init__
346*bbb1b6f9SApple OSS Distributions        self.load(fp)
347*bbb1b6f9SApple OSS Distributions      File ".../site-packages/macholib/MachO.py", line 133, in load
348*bbb1b6f9SApple OSS Distributions        self.load_header(fh, 0, size)
349*bbb1b6f9SApple OSS Distributions      File ".../site-packages/macholib/MachO.py", line 168, in load_header
350*bbb1b6f9SApple OSS Distributions        hdr = MachOHeader(self, fh, offset, size, magic, hdr, endian)
351*bbb1b6f9SApple OSS Distributions      File ".../site-packages/macholib/MachO.py", line 209, in __init__
352*bbb1b6f9SApple OSS Distributions        self.load(fh)
353*bbb1b6f9SApple OSS Distributions      File ".../lldbmacros/macho.py", line 23, in new_load
354*bbb1b6f9SApple OSS Distributions        _old_MachOHeader_load(s, fh)
355*bbb1b6f9SApple OSS Distributions      File ".../site-packages/macholib/MachO.py", line 287, in load
356*bbb1b6f9SApple OSS Distributions        fh.seek(seg.offset)
357*bbb1b6f9SApple OSS Distributions      File ".../site-packages/macholib/util.py", line 91, in seek
358*bbb1b6f9SApple OSS Distributions        self._checkwindow(seekto, "seek")
359*bbb1b6f9SApple OSS Distributions      File ".../site-packages/macholib/util.py", line 76, in _checkwindow
360*bbb1b6f9SApple OSS Distributions        raise IOError(
361*bbb1b6f9SApple OSS Distributions    OSError: seek to offset 9042440 is outside window [0, 112080]
362*bbb1b6f9SApple OSS Distributions
363*bbb1b6f9SApple OSS DistributionsClearly an external library is involved and execution flow jumps between dSYM and the library few times.
364*bbb1b6f9SApple OSS DistributionsLets try to look around with a debugger.
365*bbb1b6f9SApple OSS Distributions
366*bbb1b6f9SApple OSS Distributions    (lldb) script
367*bbb1b6f9SApple OSS Distributions	# Prepare data variable as described above.
368*bbb1b6f9SApple OSS Distributions
369*bbb1b6f9SApple OSS Distributions	# Run last statement with debugger.
370*bbb1b6f9SApple OSS Distributions	>>> import pdb
371*bbb1b6f9SApple OSS Distributions	>>> pdb.run('m = macho.MemMacho(data, len(data))', globals(), locals())
372*bbb1b6f9SApple OSS Distributions	> <string>(1)<module>()
373*bbb1b6f9SApple OSS Distributions
374*bbb1b6f9SApple OSS Distributions	# Show debugger's help
375*bbb1b6f9SApple OSS Distributions	(Pdb) help
376*bbb1b6f9SApple OSS Distributions
377*bbb1b6f9SApple OSS DistributionsIt is not possible to break on exception. Python uses them a lot so it is better to put a breakpoint to source
378*bbb1b6f9SApple OSS Distributionscode. This puts breakpoint on the IOError exception mentioned above.
379*bbb1b6f9SApple OSS Distributions
380*bbb1b6f9SApple OSS Distributions	(Pdb) break ~/Library/Python/3.8/lib/python/site-packages/macholib/util.py:76
381*bbb1b6f9SApple OSS Distributions    Breakpoint 4 at ~/Library/Python/3.8/lib/python/site-packages/macholib/util.py:76
382*bbb1b6f9SApple OSS Distributions
383*bbb1b6f9SApple OSS DistributionsYou can now single step or continue the execution as usuall for a debugger.
384*bbb1b6f9SApple OSS Distributions
385*bbb1b6f9SApple OSS Distributions    (Pdb) cont
386*bbb1b6f9SApple OSS Distributions    > /Users/tjedlicka/Library/Python/3.8/lib/python/site-packages/macholib/util.py(76)_checkwindow()
387*bbb1b6f9SApple OSS Distributions    -> raise IOError(
388*bbb1b6f9SApple OSS Distributions    (Pdb) bt
389*bbb1b6f9SApple OSS Distributions      /Volumes/.../Python3.framework/Versions/3.8/lib/python3.8/bdb.py(580)run()
390*bbb1b6f9SApple OSS Distributions    -> exec(cmd, globals, locals)
391*bbb1b6f9SApple OSS Distributions      <string>(1)<module>()
392*bbb1b6f9SApple OSS Distributions      /Volumes/...dSYM/Contents/Resources/Python/lldbmacros/macho.py(91)__init__()
393*bbb1b6f9SApple OSS Distributions    -> self.load(fp)
394*bbb1b6f9SApple OSS Distributions      /Users/.../Library/Python/3.8/lib/python/site-packages/macholib/MachO.py(133)load()
395*bbb1b6f9SApple OSS Distributions    -> self.load_header(fh, 0, size)
396*bbb1b6f9SApple OSS Distributions      /Users/.../Library/Python/3.8/lib/python/site-packages/macholib/MachO.py(168)load_header()
397*bbb1b6f9SApple OSS Distributions    -> hdr = MachOHeader(self, fh, offset, size, magic, hdr, endian)
398*bbb1b6f9SApple OSS Distributions      /Users/.../Library/Python/3.8/lib/python/site-packages/macholib/MachO.py(209)__init__()
399*bbb1b6f9SApple OSS Distributions    -> self.load(fh)
400*bbb1b6f9SApple OSS Distributions      /Volumes/...dSYM/Contents/Resources/Python/lldbmacros/macho.py(23)new_load()
401*bbb1b6f9SApple OSS Distributions    -> _old_MachOHeader_load(s, fh)
402*bbb1b6f9SApple OSS Distributions      /Users/.../Library/Python/3.8/lib/python/site-packages/macholib/MachO.py(287)load()
403*bbb1b6f9SApple OSS Distributions    -> fh.seek(seg.offset)
404*bbb1b6f9SApple OSS Distributions      /Users/.../Library/Python/3.8/lib/python/site-packages/macholib/util.py(91)seek()
405*bbb1b6f9SApple OSS Distributions    -> self._checkwindow(seekto, "seek")
406*bbb1b6f9SApple OSS Distributions    > /Users/.../Library/Python/3.8/lib/python/site-packages/macholib/util.py(76)_checkwindow()
407*bbb1b6f9SApple OSS Distributions    -> raise IOError(
408*bbb1b6f9SApple OSS Distributions
409*bbb1b6f9SApple OSS Distributions
410*bbb1b6f9SApple OSS DistributionsNow we can move a frame above and inspect stopped target:
411*bbb1b6f9SApple OSS Distributions
412*bbb1b6f9SApple OSS Distributions    # Show current frame arguments
413*bbb1b6f9SApple OSS Distributions    (Pdb) up
414*bbb1b6f9SApple OSS Distributions    (Pdb) a
415*bbb1b6f9SApple OSS Distributions    self = <fileview [0, 112080] <macho.MemFile object at 0x1075cafd0>>
416*bbb1b6f9SApple OSS Distributions    offset = 9042440
417*bbb1b6f9SApple OSS Distributions    whence = 0
418*bbb1b6f9SApple OSS Distributions
419*bbb1b6f9SApple OSS Distributions    # globals, local or expressons
420*bbb1b6f9SApple OSS Distributions    (Pdb) p type(seg.offset)
421*bbb1b6f9SApple OSS Distributions    <class 'macholib.ptypes.p_uint32'>
422*bbb1b6f9SApple OSS Distributions    (Pdb) p hex(seg.offset)
423*bbb1b6f9SApple OSS Distributions    '0x89fa08'
424*bbb1b6f9SApple OSS Distributions
425*bbb1b6f9SApple OSS Distributions    # Find attributes of a Python object.
426*bbb1b6f9SApple OSS Distributions    (Pdb) p dir(section_cls)
427*bbb1b6f9SApple OSS Distributions    ['__class__', '__cmp__', ... ,'reserved3', 'sectname', 'segname', 'size', 'to_fileobj', 'to_mmap', 'to_str']
428*bbb1b6f9SApple OSS Distributions    (Pdb) p section_cls.sectname
429*bbb1b6f9SApple OSS Distributions    <property object at 0x1077bbef0>
430*bbb1b6f9SApple OSS Distributions
431*bbb1b6f9SApple OSS DistributionsUnfortunately everything looks correct but there is actually one ineteresting frame in the stack. The one which
432*bbb1b6f9SApple OSS Distributionsprovides the offset to the seek method. Lets see where we are in the source code.
433*bbb1b6f9SApple OSS Distributions
434*bbb1b6f9SApple OSS Distributions    (Pdb) up
435*bbb1b6f9SApple OSS Distributions    > /Users/tjedlicka/Library/Python/3.8/lib/python/site-packages/macholib/MachO.py(287)load()
436*bbb1b6f9SApple OSS Distributions    -> fh.seek(seg.offset)
437*bbb1b6f9SApple OSS Distributions    (Pdb) list
438*bbb1b6f9SApple OSS Distributions    282  	                        not_zerofill = (seg.flags & S_ZEROFILL) != S_ZEROFILL
439*bbb1b6f9SApple OSS Distributions    283  	                        if seg.offset > 0 and seg.size > 0 and not_zerofill:
440*bbb1b6f9SApple OSS Distributions    284  	                            low_offset = min(low_offset, seg.offset)
441*bbb1b6f9SApple OSS Distributions    285  	                        if not_zerofill:
442*bbb1b6f9SApple OSS Distributions    286  	                            c = fh.tell()
443*bbb1b6f9SApple OSS Distributions    287  ->	                            fh.seek(seg.offset)
444*bbb1b6f9SApple OSS Distributions    288  	                            sd = fh.read(seg.size)
445*bbb1b6f9SApple OSS Distributions    289  	                            seg.add_section_data(sd)
446*bbb1b6f9SApple OSS Distributions    290  	                            fh.seek(c)
447*bbb1b6f9SApple OSS Distributions    291  	                        segs.append(seg)
448*bbb1b6f9SApple OSS Distributions    292  	                # data is a list of segments
449*bbb1b6f9SApple OSS Distributions
450*bbb1b6f9SApple OSS DistributionsRunning debugger on working case and stepping through the load() method shows that this code is not present.
451*bbb1b6f9SApple OSS DistributionsThat means we are broken by a library update! Older versions of library do not load data for a section.
452