xref: /xnu-10002.41.9/doc/debugging.md (revision 699cd48037512bf4380799317ca44ca453c82f57)
1*699cd480SApple OSS Distributions# XNU debugging
2*699cd480SApple OSS Distributions
3*699cd480SApple OSS Distributionsxnu’s debugging macros are compatible with both Python 2 and 3. In practice, this means that Python 3
4*699cd480SApple OSS Distributionsfeatures are unavailable and some Python 2 syntax is not allowed. Unfortunately, any syntax error will
5*699cd480SApple OSS Distributionsprevent use of all the macros, as they’re all imported into the same scripting environment.
6*699cd480SApple OSS Distributions
7*699cd480SApple OSS Distributions## Compatibility
8*699cd480SApple OSS Distributions
9*699cd480SApple OSS DistributionsAvoid introducing specific compatibility shims, as there are a few existing ones that come with
10*699cd480SApple OSS DistributionsPython 2 and 3:
11*699cd480SApple OSS Distributions
12*699cd480SApple OSS Distributions* **six** has helpers that work in both Python 2 and 3, for things like the string type change
13*699cd480SApple OSS Distributions* **future** backports features from Python 3 to Python 2
14*699cd480SApple OSS Distributions
15*699cd480SApple OSS DistributionsFor example, Python 2 contains **range** and **xrange**. Python 3 contains only **range** which has
16*699cd480SApple OSS Distributions**xrange** semantics. The simplest solution is to port your code and use Python 3 way:
17*699cd480SApple OSS Distributions
18*699cd480SApple OSS Distributions```
19*699cd480SApple OSS Distributions# Use backported range from Python 3
20*699cd480SApple OSS Distributionsfrom builtins import range
21*699cd480SApple OSS Distributions
22*699cd480SApple OSS Distributions# Use range on both Python 2/3 runtimes
23*699cd480SApple OSS Distributionsfor x in range(....):
24*699cd480SApple OSS Distributions   ....
25*699cd480SApple OSS Distributions```
26*699cd480SApple OSS Distributions
27*699cd480SApple OSS DistributionsBe very careful about using imports from 'future' library. Some of them are **very invasive** and change
28*699cd480SApple OSS Distributionsbehavior of your code. This may cause strange runtime errors. For example:
29*699cd480SApple OSS Distributions
30*699cd480SApple OSS Distributions```
31*699cd480SApple OSS Distributions# Changes modules handling logic to make your code working with std library reorg (PEP 3108)
32*699cd480SApple OSS Distributionsfrom future import standard_library
33*699cd480SApple OSS Distributionsstandard_library.install_aliases()
34*699cd480SApple OSS Distributions
35*699cd480SApple OSS Distributions# Replaces lot of common types like str with future's Python 3 backports.
36*699cd480SApple OSS Distributionsfrom builtins import *
37*699cd480SApple OSS Distributions```
38*699cd480SApple OSS Distributions
39*699cd480SApple OSS Distributions## Handling strings
40*699cd480SApple OSS Distributions
41*699cd480SApple OSS DistributionsMacros use strings produced from the LLDB runtime. They must use **six** when doing certain operations
42*699cd480SApple OSS Distributionsto avoid exceptions. Until the transition is done, these canonical ways of dealing with strings cannot
43*699cd480SApple OSS Distributionsbe used:
44*699cd480SApple OSS Distributions
45*699cd480SApple OSS Distributions* Using Unicode literals by default:
46*699cd480SApple OSS Distributions   `from __future__ import unicode_literals`
47*699cd480SApple OSS Distributions* **f-strings**
48*699cd480SApple OSS Distributions
49*699cd480SApple OSS DistributionsSome advice:
50*699cd480SApple OSS Distributions
51*699cd480SApple OSS Distributions* Use byte strings explicitly when dealing with memory and not strings:
52*699cd480SApple OSS Distributions  `b'string'`
53*699cd480SApple OSS Distributions* Always properly encode/decode raw data to/from strings before passing it around, with `six.ensure_str` or
54*699cd480SApple OSS Distributions  `six.ensure_bytes`.
55*699cd480SApple OSS Distributions
56*699cd480SApple OSS DistributionsImproperly-typed strings will raise *different* exceptions on each runtime.
57*699cd480SApple OSS Distributions
58*699cd480SApple OSS Distributions* Python 2 raises codec exceptions when printing strings.
59*699cd480SApple OSS Distributions* Python 3 complains about concatenation of objects of incompatible types (bytes and strings).
60*699cd480SApple OSS Distributions
61*699cd480SApple OSS Distributions### No convenient, common string type
62*699cd480SApple OSS Distributions
63*699cd480SApple OSS DistributionsWhile it is possible to use future’s **newstr** to backport new string type to Python 3, there are
64*699cd480SApple OSS Distributionsissues with the Scripting Bridge (SB) API from LLDB. Python 3 will work out of the box but Python 2
65*699cd480SApple OSS Distributionswill complain because **newstr** maps to **unicode**. SB exposes **const char \*** as a native string,
66*699cd480SApple OSS Distributionsor just **str** in Python 2. For Python 2 we would have to explicitly encode all Unicode strings
67*699cd480SApple OSS Distributionsbefore calling the API.
68*699cd480SApple OSS Distributions
69*699cd480SApple OSS DistributionsAnother problem is that literals in form `'string'` are no longer compatible with unicode and need
70*699cd480SApple OSS Distributionsto be switched to `u'string'`. This can be changed with single import at the top of the file, but
71*699cd480SApple OSS Distributionsin some scenarios byte strings are expected. That change would require checking all strings in the
72*699cd480SApple OSS Distributionscode and changing some back to  `b'string'`.
73*699cd480SApple OSS Distributions
74*699cd480SApple OSS DistributionsHere’s an example of just how pervasive a change would be because this code would break in Python 2:
75*699cd480SApple OSS Distributions
76*699cd480SApple OSS Distributions```
77*699cd480SApple OSS Distributionsfrom xnu import *
78*699cd480SApple OSS Distributions
79*699cd480SApple OSS Distributions@lldb_type_summary(['type'])
80*699cd480SApple OSS Distributionsdef print_summary():
81*699cd480SApple OSS Distributions   ....
82*699cd480SApple OSS Distributions```
83*699cd480SApple OSS Distributions
84*699cd480SApple OSS DistributionsThe result is that we have non-unicode literal being registered with unicode API in Python 3.
85*699cd480SApple OSS DistributionsUnfortunately `'type' != b'type'` and thus LLDB will never match the type when printing summaries.
86*699cd480SApple OSS Distributions
87*699cd480SApple OSS DistributionsUsing native strings and literals allows for only minimal code changes to the macros that are still
88*699cd480SApple OSS Distributionscompatible with other projects using Python 2.
89*699cd480SApple OSS Distributions
90*699cd480SApple OSS Distributions### Check that an object is a string
91*699cd480SApple OSS Distributions
92*699cd480SApple OSS DistributionsAvoid testing for `str` explicitly like `type(obj) == str`. This won’t work correctly as Python 2
93*699cd480SApple OSS Distributionshas multiple string types (`unicode`, `str`). Additionally, compatibility shims might introduce new
94*699cd480SApple OSS Distributionsstring types.
95*699cd480SApple OSS Distributions
96*699cd480SApple OSS DistributionsInstead, always use an inheritance-sensitive like like `isinstance(obj, six.string_types)`.
97*699cd480SApple OSS Distributions
98*699cd480SApple OSS Distributions### Dealing with binary data
99*699cd480SApple OSS Distributions
100*699cd480SApple OSS DistributionsPython 2 bytes and strings are the same thing. This was the wrong design decision and Python 3
101*699cd480SApple OSS Distributions(wisely) switched to using a separate type for human text. This lack of distinction in Python 2
102*699cd480SApple OSS Distributionscaused many programming errors, so it’s recommended to use **bytearray**, **bytes**, and
103*699cd480SApple OSS Distributions**memoryviews** instead of a string. If a string is really required, encode the raw data explicitly
104*699cd480SApple OSS Distributionsusing an escape method.
105*699cd480SApple OSS Distributions
106*699cd480SApple OSS Distributions### Accessing large amounts of binary data (or accessing small amounts frequently)
107*699cd480SApple OSS Distributions
108*699cd480SApple OSS DistributionsIn case you're planning on accessing large contiguous blocks of memory (e.g. reading a whole 10KB of memory),
109*699cd480SApple OSS Distributionsor you're accessing small semi-contiguous chunks (e.g. if you're parsing large structured data), then it might
110*699cd480SApple OSS Distributionsbe hugely beneficial performance-wise to make use of the `io.SBProcessRawIO` class. Furthermore, if you're in
111*699cd480SApple OSS Distributionsa hurry and just want to read one specific chunk once, then it might be easier to use `LazyTarget.GetProcess().ReadMemory()`
112*699cd480SApple OSS Distributionsdirectly.
113*699cd480SApple OSS Distributions
114*699cd480SApple OSS DistributionsIn other words, avoid the following:
115*699cd480SApple OSS Distributions
116*699cd480SApple OSS Distributions```
117*699cd480SApple OSS Distributionsdata_ptr = kern.GetValueFromAddress(start_addr, 'uint8_t *')
118*699cd480SApple OSS Distributionswith open(filepath, 'wb') as f:
119*699cd480SApple OSS Distributions    f.write(data_ptr[:4096])
120*699cd480SApple OSS Distributions```
121*699cd480SApple OSS Distributions
122*699cd480SApple OSS DistributionsAnd instead use:
123*699cd480SApple OSS Distributions
124*699cd480SApple OSS Distributions```
125*699cd480SApple OSS Distributionsfrom core.io import SBProcessRawIO
126*699cd480SApple OSS Distributionsimport shutil
127*699cd480SApple OSS Distributions
128*699cd480SApple OSS Distributionsio_access = SBProcessRawIO(LazyTarget.GetProcess(), start_addr, 4096)
129*699cd480SApple OSS Distributionswith open(filepath, 'wb') as f:
130*699cd480SApple OSS Distributions    shutil.copyfileobj(io_access, f)
131*699cd480SApple OSS Distributions```
132*699cd480SApple OSS Distributions
133*699cd480SApple OSS DistributionsOr, if you're in a hurry:
134*699cd480SApple OSS Distributions
135*699cd480SApple OSS Distributions```
136*699cd480SApple OSS Distributionserr = lldb.SBError()
137*699cd480SApple OSS Distributionsmy_data = LazyTarget.GetProcess().ReadMemory(start_addr, length, err)
138*699cd480SApple OSS Distributionsif err.Success():
139*699cd480SApple OSS Distributions    # Use my precious data
140*699cd480SApple OSS Distributions    pass
141*699cd480SApple OSS Distributions```
142*699cd480SApple OSS Distributions
143*699cd480SApple OSS DistributionsFor small semi-contiguous chunks, you can map the whole region and access random chunks from it like so:
144*699cd480SApple OSS Distributions
145*699cd480SApple OSS Distributions```
146*699cd480SApple OSS Distributionsfrom core.io import SBProcessRawIO
147*699cd480SApple OSS Distributions
148*699cd480SApple OSS Distributionsio_access = SBProcessRawIO(LazyTarget.GetProcess(), start_addr, size)
149*699cd480SApple OSS Distributionsio_access.seek(my_struct_offset)
150*699cd480SApple OSS Distributionsmy_struct_contents = io_access.read(my_struct_size)
151*699cd480SApple OSS Distributions```
152*699cd480SApple OSS Distributions
153*699cd480SApple OSS DistributionsNot only that, but you can also tack on a BufferedRandom class on top of the SBProcessRawIO instance, which
154*699cd480SApple OSS Distributionsprovides you with buffering (aka caching) in case your random small chunk accesses are repeated:
155*699cd480SApple OSS Distributions
156*699cd480SApple OSS Distributions```
157*699cd480SApple OSS Distributionsfrom core.io import SBProcessRawIO
158*699cd480SApple OSS Distributionsfrom io import BufferedRandom
159*699cd480SApple OSS Distributions
160*699cd480SApple OSS Distributionsio_access = SBProcessRawIO(LazyTarget.GetProcess(), start_addr, size)
161*699cd480SApple OSS Distributionsbuffered_io = BufferedRandom(io_access)
162*699cd480SApple OSS Distributions# And then use buffered_io for your accesses
163*699cd480SApple OSS Distributions```
164*699cd480SApple OSS Distributions
165*699cd480SApple OSS Distributions### Encoding data to strings and back
166*699cd480SApple OSS Distributions
167*699cd480SApple OSS DistributionsThe simplest solution is to use **six** library and one of the functions like:
168*699cd480SApple OSS Distributions
169*699cd480SApple OSS Distributions```
170*699cd480SApple OSS Distributionsmystring = six.ensure_str(object)
171*699cd480SApple OSS Distributions```
172*699cd480SApple OSS Distributions
173*699cd480SApple OSS DistributionsThis ensures the resulting value is a native string. It deals with Unicode in Python 2 automatically.
174*699cd480SApple OSS DistributionsThe six library is still required even if data is encoding manually, since it converts types.
175*699cd480SApple OSS Distributions
176*699cd480SApple OSS Distributions```
177*699cd480SApple OSS Distributionsfrom builtins import bytes
178*699cd480SApple OSS Distributionsstr = six.ensure_str(bytes.decode('utf-8'))
179*699cd480SApple OSS Distributions```
180*699cd480SApple OSS Distributions
181*699cd480SApple OSS DistributionsWhen converting data to a string, add an encoding type so Python knows how handle raw bytes. In most
182*699cd480SApple OSS Distributionscases **utf-8** will work but be careful to be sure that the encoding matches your data.
183*699cd480SApple OSS Distributions
184*699cd480SApple OSS DistributionsThere are two options to consider when trying to get a string out of the raw data without knowing if
185*699cd480SApple OSS Distributionsthey are valid string or not:
186*699cd480SApple OSS Distributions
187*699cd480SApple OSS Distributions* **lossy conversion** - escapes all non-standard characters in form of ‘\xNNN’
188*699cd480SApple OSS Distributions* **lossless conversion** - maps invalid characters to special unicode range so it can reconstruct
189*699cd480SApple OSS Distributionsthe string precisely
190*699cd480SApple OSS Distributions
191*699cd480SApple OSS DistributionsWhich to use depends on the transformation goals. The lossy conversion produces a printable string
192*699cd480SApple OSS Distributionswith strange characters in it. The lossless option is meant to be used when a string is only a transport
193*699cd480SApple OSS Distributionsmechanism and needs to be converted back to original values later.
194*699cd480SApple OSS Distributions
195*699cd480SApple OSS DistributionsSwitch the method by using `errors` handler during conversion:
196*699cd480SApple OSS Distributions
197*699cd480SApple OSS Distributions```
198*699cd480SApple OSS Distributions# Lossy escapes invalid chars
199*699cd480SApple OSS Distributionsb.decode('utf-8', errors='`backslashreplace'`)
200*699cd480SApple OSS Distributions# Lossy removes invalid chars
201*699cd480SApple OSS Distributionsb.decode('utf-8', errors='ignore')
202*699cd480SApple OSS Distributions# Loss-less but may likely fail to print()
203*699cd480SApple OSS Distributionsb.decode('utf-8', errors='surrogateescape')
204*699cd480SApple OSS Distributions```
205*699cd480SApple OSS Distributions
206*699cd480SApple OSS Distributions## Handling numbers
207*699cd480SApple OSS Distributions
208*699cd480SApple OSS DistributionsNumeric types are incompatible between Python 2 and 3:
209*699cd480SApple OSS Distributions
210*699cd480SApple OSS Distributions* **long** is not available in Python 3.
211*699cd480SApple OSS Distributions* **int** is the only integral type in Python 3 and hasunlimited precission (but 32-bits in Python 2).
212*699cd480SApple OSS Distributions
213*699cd480SApple OSS DistributionsThis creates all sorts of issues with macros. Follow these rules to make integral types compatible
214*699cd480SApple OSS Distributionsin both modes:
215*699cd480SApple OSS Distributions
216*699cd480SApple OSS Distributions* Do not use **long** — replace it with **int**.
217*699cd480SApple OSS Distributions* When using the **value** class, types will be promoted to **long** as there is special number
218*699cd480SApple OSS Distributionshandling in the xnu macro library. Remaining code should be reviewed and fixed, if appropriate.
219*699cd480SApple OSS Distributions* Avoid relying on sign extension.
220*699cd480SApple OSS Distributions* Always switch Python to use Python 3 division, where `/` converts to floating point and does
221*699cd480SApple OSS Distributionsa fractional division `//` is a floor division (like integers in C):
222*699cd480SApple OSS Distributions   `from __future__ import division
223*699cd480SApple OSS Distributions   `
224*699cd480SApple OSS Distributions* Use division operators according to Python 3 rules.
225*699cd480SApple OSS Distributions
226*699cd480SApple OSS Distributions### Common integer representation
227*699cd480SApple OSS Distributions
228*699cd480SApple OSS DistributionsThe goal is to always use Python 3’s integer handling, which means using **int** everywhere.
229*699cd480SApple OSS Distributions
230*699cd480SApple OSS Distributionsxnu’s macros provide a custom integer type called **valueint** that is a replacement for **int**
231*699cd480SApple OSS Distributionsin the Python 2 runtime. That means it behaves almost like **int** from Python 3. When importing
232*699cd480SApple OSS Distributionsfrom macros this type replaces any use of **int**:
233*699cd480SApple OSS Distributions
234*699cd480SApple OSS Distributions```
235*699cd480SApple OSS Distributions# Replaces all int()s to be valueint
236*699cd480SApple OSS Distributionsfrom xnu import *
237*699cd480SApple OSS Distributionsfrom xnu import int
238*699cd480SApple OSS Distributions
239*699cd480SApple OSS Distributions# Does not replace int()s
240*699cd480SApple OSS Distributionsimport xnu
241*699cd480SApple OSS Distributionsfrom xnu import a, b, c
242*699cd480SApple OSS Distributions```
243*699cd480SApple OSS Distributions
244*699cd480SApple OSS DistributionsAvoid using `from builtins import int` suggested on the internet. It does not work correctly with
245*699cd480SApple OSS Distributionsxnu’s **value** class. The **valueint** class inherits from **newint** and fixes problematic behavior.
246*699cd480SApple OSS Distributions
247*699cd480SApple OSS DistributionsThis impacts the way an object is checked for being an integer. Be careful about following constructs:
248*699cd480SApple OSS Distributions
249*699cd480SApple OSS Distributions```
250*699cd480SApple OSS Distributions# BAD: generally not a good way to do type checking in Python
251*699cd480SApple OSS Distributionsif type(obj) is int:
252*699cd480SApple OSS Distributions
253*699cd480SApple OSS Distributions# BAD: int may have been replaced with valueint.
254*699cd480SApple OSS Distributionsif isinstance(obj, int):
255*699cd480SApple OSS Distributions```
256*699cd480SApple OSS Distributions
257*699cd480SApple OSS DistributionsInstead, use the base integral type:
258*699cd480SApple OSS Distributions
259*699cd480SApple OSS Distributions```
260*699cd480SApple OSS Distributionsif isinstance(obj, numbers.Integral):
261*699cd480SApple OSS Distributions```
262*699cd480SApple OSS Distributions
263*699cd480SApple OSS Distributions### Dealing with signed numbers
264*699cd480SApple OSS Distributions
265*699cd480SApple OSS DistributionsOriginal code was using two operators to convert **value** class instance to number:
266*699cd480SApple OSS Distributions
267*699cd480SApple OSS Distributions* **__int__** produced **int** and was either signed or unsigned based on underlying SBType.
268*699cd480SApple OSS Distributions* **__long__** was always signed.
269*699cd480SApple OSS Distributions
270*699cd480SApple OSS DistributionsThis is confusing when dealing with types. Always use **unsigned()** or **signed()** regardless of
271*699cd480SApple OSS Distributionswhat the actual underlying type is to ensure that macros use the correct semantics.
272*699cd480SApple OSS Distributions
273*699cd480SApple OSS Distributions### Dividing numbers
274*699cd480SApple OSS Distributions
275*699cd480SApple OSS DistributionsPython 2’s **/** operator has two behaviors depending on the types of its arguments (**float** vs. **int**).
276*699cd480SApple OSS DistributionsAlways use Python 3’s division operator:
277*699cd480SApple OSS Distributions
278*699cd480SApple OSS Distributions```
279*699cd480SApple OSS Distributions# Switch compiler to use Python 3 semantics
280*699cd480SApple OSS Distributionsfrom __future__ import division
281*699cd480SApple OSS Distributions
282*699cd480SApple OSS Distributionsfloat_val = a / b  # This becomes true, fractional division that yields float
283*699cd480SApple OSS Distributionsfloor_div = a // b # This is floor division, like C
284*699cd480SApple OSS Distributions```
285*699cd480SApple OSS Distributions
286*699cd480SApple OSS DistributionsIf the original behavior is required, use **old_div** to get Python 2 behavior:
287*699cd480SApple OSS Distributions
288*699cd480SApple OSS Distributions```
289*699cd480SApple OSS Distributionsfrom past.utils import old_div
290*699cd480SApple OSS Distributions
291*699cd480SApple OSS Distributionsvalue = old_div(a, b)     # Matches Python 2 semantics
292*699cd480SApple OSS Distributions```
293*699cd480SApple OSS Distributions
294*699cd480SApple OSS DistributionsIf this isn’t handled correctly, `format` will complain that a float value is being passed to
295*699cd480SApple OSS Distributionsa non-float formatting character. Automated scripts that convert from Python 2 to 3 tend to use
296*699cd480SApple OSS Distributions**old_div** during porting. In most cases that is not required. For kernel debugging and integer
297*699cd480SApple OSS Distributionstypes, `//` is used commonly to match the C’s division behavior for integers.
298*699cd480SApple OSS Distributions
299*699cd480SApple OSS Distributions## Testing changes
300*699cd480SApple OSS Distributions
301*699cd480SApple OSS DistributionsThere is no perfect test suite to check that macros are producing a correct value compared to what
302*699cd480SApple OSS Distributionsthe debugger sees in a target.
303*699cd480SApple OSS Distributions
304*699cd480SApple OSS DistributionsBe careful when touching common framework code. For larger changes, ask the Platform Triage team to
305*699cd480SApple OSS Distributionsvalidate that the changes work in their environment before integration.
306*699cd480SApple OSS Distributions
307*699cd480SApple OSS Distributions### Coding style
308*699cd480SApple OSS Distributions
309*699cd480SApple OSS DistributionsUse a static analyzer like **pylint** or **flake8** to check the macro source code:
310*699cd480SApple OSS Distributions
311*699cd480SApple OSS Distributions```
312*699cd480SApple OSS Distributions# Python 2
313*699cd480SApple OSS Distributions$ pip install --user pylint flake8
314*699cd480SApple OSS Distributions
315*699cd480SApple OSS Distributions# Python 3
316*699cd480SApple OSS Distributions$ pip install --user pylint flake8
317*699cd480SApple OSS Distributions
318*699cd480SApple OSS Distributions# Run the lint either by setting your path to point to one of the runtimes
319*699cd480SApple OSS Distributions# or through python
320*699cd480SApple OSS Distributions$ python2 -m pylint <src files/dirs>
321*699cd480SApple OSS Distributions$ python3 -m pylint <src files/dirs>
322*699cd480SApple OSS Distributions$ python2 -m flake8 <src files/dirs>
323*699cd480SApple OSS Distributions$ python3 -m flake8 <src files/dirs>
324*699cd480SApple OSS Distributions```
325*699cd480SApple OSS Distributions
326*699cd480SApple OSS Distributions### Correctness
327*699cd480SApple OSS Distributions
328*699cd480SApple OSS DistributionsEnsure the macro matches what LLDB returns from the REPL. For example, compare `showproc(xxx)` with `p/x *(proc_t)xxx`.
329*699cd480SApple OSS Distributions
330*699cd480SApple OSS Distributions```
331*699cd480SApple OSS Distributions# 1. Run LLDB with debug options set
332*699cd480SApple OSS Distributions$ DEBUG_XNU_LLDBMACROS=1 LLDB_DEFAULT_PYTHON_VERSION=2 xcrun -sdk <sdk> lldb -c core <dsympath>/mach_kernel
333*699cd480SApple OSS Distributions
334*699cd480SApple OSS Distributions# 2. Optionally load modified operating system plugin
335*699cd480SApple OSS Distributions(lldb) settings set target.process.python-os-plugin-path <srcpath>/tools/lldbmacros/core/operating_system.py
336*699cd480SApple OSS Distributions
337*699cd480SApple OSS Distributions# 3. Load modified scripts
338*699cd480SApple OSS Distributions(lldb) command script import <srcpath>/tools/lldbmacros/xnu.py
339*699cd480SApple OSS Distributions
340*699cd480SApple OSS Distributions# 4. Exercise macros
341*699cd480SApple OSS Distributions```
342*699cd480SApple OSS Distributions
343*699cd480SApple OSS DistributionsDepending on the change, test other targets and architectures (for instance, both Astris and KDP).
344*699cd480SApple OSS Distributions
345*699cd480SApple OSS Distributions### Regression
346*699cd480SApple OSS Distributions
347*699cd480SApple OSS DistributionsThis is simpler than previous step because the goal is to ensure behavior has not changed.
348*699cd480SApple OSS DistributionsYou can speed up few things by using local symbols:
349*699cd480SApple OSS Distributions
350*699cd480SApple OSS Distributions```
351*699cd480SApple OSS Distributions# 1. Get a coredump from a device and kernel UUID
352*699cd480SApple OSS Distributions# 2. Grab symbols with dsymForUUID
353*699cd480SApple OSS Distributions$ dsymForUUID --nocache --copyExecutable --copyDestination <dsym path>
354*699cd480SApple OSS Distributions
355*699cd480SApple OSS Distributions# 3. Run lldb with local symbols to avoid dsymForUUID NFS
356*699cd480SApple OSS Distributions
357*699cd480SApple OSS Distributions$ xcrun -sdk <sdk> lldb -c core <dsym_path>/<kernel image>
358*699cd480SApple OSS Distributions```
359*699cd480SApple OSS Distributions
360*699cd480SApple OSS DistributionsThe actual steps are identical to previous testing. Run of a macro to different file with `-o <outfile>`
361*699cd480SApple OSS Distributionsoption. Then run `diff` on the outputs of the baseline and both Python 2 and 3:
362*699cd480SApple OSS Distributions
363*699cd480SApple OSS Distributions* No environment variables to get baseline
364*699cd480SApple OSS Distributions* Python 2 with changes
365*699cd480SApple OSS Distributions* Python 3 with changes
366*699cd480SApple OSS Distributions
367*699cd480SApple OSS DistributionsThere may be different ordering of elements based on internal implementation differences of each
368*699cd480SApple OSS DistributionsPython runtime. Some macros produce files — check the actual file contents.
369*699cd480SApple OSS Distributions
370*699cd480SApple OSS DistributionsIt’s difficult to make this automated:
371*699cd480SApple OSS Distributions
372*699cd480SApple OSS Distributions* Some macros needs arguments which must be found in a core file.
373*699cd480SApple OSS Distributions* Some macros take a long time to run against a target (more than 30 minutes). Instead, a core dump
374*699cd480SApple OSS Distributions  should be taken and then inspected afterwards, but this ties up a lab device for the duration of the
375*699cd480SApple OSS Distributions  test.
376*699cd480SApple OSS Distributions* Even with coredumps, testing the macros takes too long in our automation system and triggers the
377*699cd480SApple OSS Distributions  failsafe timeout.
378*699cd480SApple OSS Distributions
379*699cd480SApple OSS Distributions### Code coverage
380*699cd480SApple OSS Distributions
381*699cd480SApple OSS DistributionsUse code coverage to check which parts of macros have actually been tested.
382*699cd480SApple OSS DistributionsInstall **coverage** lib with:
383*699cd480SApple OSS Distributions
384*699cd480SApple OSS Distributions```
385*699cd480SApple OSS Distributions$ pip install --user coverage
386*699cd480SApple OSS Distributions$ pip3 install --user coverage
387*699cd480SApple OSS Distributions```
388*699cd480SApple OSS Distributions
389*699cd480SApple OSS DistributionsThen collect coverage:.
390*699cd480SApple OSS Distributions
391*699cd480SApple OSS Distributions```
392*699cd480SApple OSS Distributions# 1. Start LLDB with your macros as described above.
393*699cd480SApple OSS Distributions
394*699cd480SApple OSS Distributions# 2. Load and start code coverage recording.
395*699cd480SApple OSS Distributions(lldb) script import coverage
396*699cd480SApple OSS Distributions(lldb) script cov = coverage.Coverage()
397*699cd480SApple OSS Distributions(lldb) script cov.start()
398*699cd480SApple OSS Distributions
399*699cd480SApple OSS Distributions# 3. Do the testing.
400*699cd480SApple OSS Distributions
401*699cd480SApple OSS Distributions# 4. Collect the coverage.
402*699cd480SApple OSS Distributions(lldb) script cov.stop()
403*699cd480SApple OSS Distributions(lldb) script cov.save()
404*699cd480SApple OSS Distributions```
405*699cd480SApple OSS Distributions
406*699cd480SApple OSS DistributionsYou can override the default file (*.coverage*) by adding an additional environment variable to LLDB:
407*699cd480SApple OSS Distributions
408*699cd480SApple OSS Distributions```
409*699cd480SApple OSS Distributions$ env COVERAGE_FILE="${OUTDIR}/.coverage.mytest.py2" # usual LLDB command line
410*699cd480SApple OSS Distributions```
411*699cd480SApple OSS Distributions
412*699cd480SApple OSS DistributionsCombine coverage from multiple files:
413*699cd480SApple OSS Distributions
414*699cd480SApple OSS Distributions```
415*699cd480SApple OSS Distributions# Point PATH to local python where coverage is installed.
416*699cd480SApple OSS Distributions$ export PATH="$HOME/Library/Python/3.8/bin:$PATH"
417*699cd480SApple OSS Distributions
418*699cd480SApple OSS Distributions# Use --keep to avoid deletion of input files after merge.
419*699cd480SApple OSS Distributions$ coverage combine --keep <list of .coverage files or dirs to scan>
420*699cd480SApple OSS Distributions
421*699cd480SApple OSS Distributions# Get HTML report or use other subcommands to inspect.
422*699cd480SApple OSS Distributions$ coverage html
423*699cd480SApple OSS Distributions```
424*699cd480SApple OSS Distributions
425*699cd480SApple OSS DistributionsIt is possible to start coverage collection **before** importing the operating system library and
426*699cd480SApple OSS Distributionsloading macros to check code run during bootstrapping.
427*699cd480SApple OSS Distributions
428*699cd480SApple OSS Distributions### Performance testing
429*699cd480SApple OSS Distributions
430*699cd480SApple OSS DistributionsSome macros can run for a long time. Some code may be costly even if it looks simple because objects
431*699cd480SApple OSS Distributionsaren’t cached or too many temporary objects are created. Simple profiling is similar to collecting
432*699cd480SApple OSS Distributionscode coverage.
433*699cd480SApple OSS Distributions
434*699cd480SApple OSS DistributionsFirst setup your environment:
435*699cd480SApple OSS Distributions
436*699cd480SApple OSS Distributions```
437*699cd480SApple OSS Distributions# Install gprof2dot
438*699cd480SApple OSS Distributions$ python3 -m pip install gprof2dot
439*699cd480SApple OSS Distributions# Install graphviz
440*699cd480SApple OSS Distributions$ brew install graphviz
441*699cd480SApple OSS Distributions```
442*699cd480SApple OSS Distributions
443*699cd480SApple OSS DistributionsThen to profile commands, follow this sequence:
444*699cd480SApple OSS Distributions
445*699cd480SApple OSS Distributions```
446*699cd480SApple OSS Distributions(lldb) xnudebug profile /tmp/macro.prof showcurrentstacks
447*699cd480SApple OSS Distributions[... command outputs ...]
448*699cd480SApple OSS Distributions
449*699cd480SApple OSS Distributions   Ordered by: cumulative time
450*699cd480SApple OSS Distributions   List reduced from 468 to 30 due to restriction <30>
451*699cd480SApple OSS Distributions
452*699cd480SApple OSS Distributions   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
453*699cd480SApple OSS Distributions   [... profiling output ...]
454*699cd480SApple OSS Distributions
455*699cd480SApple OSS DistributionsProfile info saved to "/tmp/macro.prof"
456*699cd480SApple OSS Distributions```
457*699cd480SApple OSS Distributions
458*699cd480SApple OSS DistributionsThen to visualize callgraphs in context, in a separate shell:
459*699cd480SApple OSS Distributions
460*699cd480SApple OSS Distributions```
461*699cd480SApple OSS Distributions# Now convert the file to a colored SVG call graph
462*699cd480SApple OSS Distributions$ python3 -m gprof2dot -f pstats /tmp/macro.prof -o /tmp/call.dot
463*699cd480SApple OSS Distributions$ dot -O -T svg /tmp/call.dot
464*699cd480SApple OSS Distributions
465*699cd480SApple OSS Distributions# and view it in your favourite viewer
466*699cd480SApple OSS Distributions$ open /tmp/call.dot.svg
467*699cd480SApple OSS Distributions```
468*699cd480SApple OSS Distributions
469*699cd480SApple OSS Distributions## Debugging your changes
470*699cd480SApple OSS Distributions
471*699cd480SApple OSS DistributionsYES, It is possible to use a debugger to debug your code!
472*699cd480SApple OSS Distributions
473*699cd480SApple OSS DistributionsThe steps are similar to testing techniques described above (use scripting interactive mode). There is no point to
474*699cd480SApple OSS Distributionsdocument the debugger itself. Lets focus on how to use it on a real life example. The debugger used here is PDB which
475*699cd480SApple OSS Distributionsis part of Python installation so works out of the box.
476*699cd480SApple OSS Distributions
477*699cd480SApple OSS DistributionsProblem: Something wrong is going on with addkext macro. What now?
478*699cd480SApple OSS Distributions
479*699cd480SApple OSS Distributions    (lldb) addkext -N com.apple.driver.AppleT8103PCIeC
480*699cd480SApple OSS Distributions    Failed to read MachO for address 18446741875027613136 errormessage: seek to offset 2169512 is outside window [0, 1310]
481*699cd480SApple OSS Distributions    Failed to read MachO for address 18446741875033537424 errormessage: seek to offset 8093880 is outside window [0, 1536]
482*699cd480SApple OSS Distributions    Failed to read MachO for address 18446741875033568304 errormessage: seek to offset 8124208 is outside window [0, 1536]
483*699cd480SApple OSS Distributions	...
484*699cd480SApple OSS Distributions	Fetching dSYM for 049b9a29-2efc-32c0-8a7f-5f29c12b870c
485*699cd480SApple 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
486*699cd480SApple OSS Distributions    section '__TEXT' loaded at 0xfffffe001478c780
487*699cd480SApple OSS Distributions
488*699cd480SApple OSS DistributionsThere is no exception, lot of errors and no output. So what next?
489*699cd480SApple OSS DistributionsTry to narrow the problem down to an isolated piece of macro code:
490*699cd480SApple OSS Distributions
491*699cd480SApple OSS Distributions  1. Try to get values of globals through regular LLDB commands
492*699cd480SApple OSS Distributions  2. Use interactive mode and invoke functions with arguments directly.
493*699cd480SApple OSS Distributions
494*699cd480SApple OSS DistributionsAfter inspecting addkext macro code and calling few functions with arguments directly we can see that there is an
495*699cd480SApple OSS Distributionsexception in the end. It was just captured in try/catch block. So the simplified reproducer is:
496*699cd480SApple OSS Distributions
497*699cd480SApple OSS Distributions    (lldb) script
498*699cd480SApple OSS Distributions	>>> import lldb
499*699cd480SApple OSS Distributions	>>> import xnu
500*699cd480SApple OSS Distributions	>>> err = lldb.SBError()
501*699cd480SApple OSS Distributions	>>> data = xnu.LazyTarget.GetProcess().ReadMemory(0xfffffe0014c0f3f0, 0x000000000001b5d0, err)
502*699cd480SApple OSS Distributions    >>> m = macho.MemMacho(data, len(data))
503*699cd480SApple OSS Distributions    Traceback (most recent call last):
504*699cd480SApple OSS Distributions      File "<console>", line 1, in <module>
505*699cd480SApple OSS Distributions      File ".../lldbmacros/macho.py", line 91, in __init__
506*699cd480SApple OSS Distributions        self.load(fp)
507*699cd480SApple OSS Distributions      File ".../site-packages/macholib/MachO.py", line 133, in load
508*699cd480SApple OSS Distributions        self.load_header(fh, 0, size)
509*699cd480SApple OSS Distributions      File ".../site-packages/macholib/MachO.py", line 168, in load_header
510*699cd480SApple OSS Distributions        hdr = MachOHeader(self, fh, offset, size, magic, hdr, endian)
511*699cd480SApple OSS Distributions      File ".../site-packages/macholib/MachO.py", line 209, in __init__
512*699cd480SApple OSS Distributions        self.load(fh)
513*699cd480SApple OSS Distributions      File ".../lldbmacros/macho.py", line 23, in new_load
514*699cd480SApple OSS Distributions        _old_MachOHeader_load(s, fh)
515*699cd480SApple OSS Distributions      File ".../site-packages/macholib/MachO.py", line 287, in load
516*699cd480SApple OSS Distributions        fh.seek(seg.offset)
517*699cd480SApple OSS Distributions      File ".../site-packages/macholib/util.py", line 91, in seek
518*699cd480SApple OSS Distributions        self._checkwindow(seekto, "seek")
519*699cd480SApple OSS Distributions      File ".../site-packages/macholib/util.py", line 76, in _checkwindow
520*699cd480SApple OSS Distributions        raise IOError(
521*699cd480SApple OSS Distributions    OSError: seek to offset 9042440 is outside window [0, 112080]
522*699cd480SApple OSS Distributions
523*699cd480SApple OSS DistributionsClearly an external library is involved and execution flow jumps between dSYM and the library few times.
524*699cd480SApple OSS DistributionsLets try to look around with a debugger.
525*699cd480SApple OSS Distributions
526*699cd480SApple OSS Distributions    (lldb) script
527*699cd480SApple OSS Distributions	# Prepare data variable as described above.
528*699cd480SApple OSS Distributions
529*699cd480SApple OSS Distributions	# Run last statement with debugger.
530*699cd480SApple OSS Distributions	>>> import pdb
531*699cd480SApple OSS Distributions	>>> pdb.run('m = macho.MemMacho(data, len(data))', globals(), locals())
532*699cd480SApple OSS Distributions	> <string>(1)<module>()
533*699cd480SApple OSS Distributions
534*699cd480SApple OSS Distributions	# Show debugger's help
535*699cd480SApple OSS Distributions	(Pdb) help
536*699cd480SApple OSS Distributions
537*699cd480SApple OSS DistributionsIt is not possible to break on exception. Python uses them a lot so it is better to put a breakpoint to source
538*699cd480SApple OSS Distributionscode. This puts breakpoint on the IOError exception mentioned above.
539*699cd480SApple OSS Distributions
540*699cd480SApple OSS Distributions	(Pdb) break ~/Library/Python/3.8/lib/python/site-packages/macholib/util.py:76
541*699cd480SApple OSS Distributions    Breakpoint 4 at ~/Library/Python/3.8/lib/python/site-packages/macholib/util.py:76
542*699cd480SApple OSS Distributions
543*699cd480SApple OSS DistributionsYou can now single step or continue the execution as usuall for a debugger.
544*699cd480SApple OSS Distributions
545*699cd480SApple OSS Distributions    (Pdb) cont
546*699cd480SApple OSS Distributions    > /Users/tjedlicka/Library/Python/3.8/lib/python/site-packages/macholib/util.py(76)_checkwindow()
547*699cd480SApple OSS Distributions    -> raise IOError(
548*699cd480SApple OSS Distributions    (Pdb) bt
549*699cd480SApple OSS Distributions      /Volumes/.../Python3.framework/Versions/3.8/lib/python3.8/bdb.py(580)run()
550*699cd480SApple OSS Distributions    -> exec(cmd, globals, locals)
551*699cd480SApple OSS Distributions      <string>(1)<module>()
552*699cd480SApple OSS Distributions      /Volumes/...dSYM/Contents/Resources/Python/lldbmacros/macho.py(91)__init__()
553*699cd480SApple OSS Distributions    -> self.load(fp)
554*699cd480SApple OSS Distributions      /Users/.../Library/Python/3.8/lib/python/site-packages/macholib/MachO.py(133)load()
555*699cd480SApple OSS Distributions    -> self.load_header(fh, 0, size)
556*699cd480SApple OSS Distributions      /Users/.../Library/Python/3.8/lib/python/site-packages/macholib/MachO.py(168)load_header()
557*699cd480SApple OSS Distributions    -> hdr = MachOHeader(self, fh, offset, size, magic, hdr, endian)
558*699cd480SApple OSS Distributions      /Users/.../Library/Python/3.8/lib/python/site-packages/macholib/MachO.py(209)__init__()
559*699cd480SApple OSS Distributions    -> self.load(fh)
560*699cd480SApple OSS Distributions      /Volumes/...dSYM/Contents/Resources/Python/lldbmacros/macho.py(23)new_load()
561*699cd480SApple OSS Distributions    -> _old_MachOHeader_load(s, fh)
562*699cd480SApple OSS Distributions      /Users/.../Library/Python/3.8/lib/python/site-packages/macholib/MachO.py(287)load()
563*699cd480SApple OSS Distributions    -> fh.seek(seg.offset)
564*699cd480SApple OSS Distributions      /Users/.../Library/Python/3.8/lib/python/site-packages/macholib/util.py(91)seek()
565*699cd480SApple OSS Distributions    -> self._checkwindow(seekto, "seek")
566*699cd480SApple OSS Distributions    > /Users/.../Library/Python/3.8/lib/python/site-packages/macholib/util.py(76)_checkwindow()
567*699cd480SApple OSS Distributions    -> raise IOError(
568*699cd480SApple OSS Distributions
569*699cd480SApple OSS Distributions
570*699cd480SApple OSS DistributionsNow we can move a frame above and inspect stopped target:
571*699cd480SApple OSS Distributions
572*699cd480SApple OSS Distributions    # Show current frame arguments
573*699cd480SApple OSS Distributions    (Pdb) up
574*699cd480SApple OSS Distributions    (Pdb) a
575*699cd480SApple OSS Distributions    self = <fileview [0, 112080] <macho.MemFile object at 0x1075cafd0>>
576*699cd480SApple OSS Distributions    offset = 9042440
577*699cd480SApple OSS Distributions    whence = 0
578*699cd480SApple OSS Distributions
579*699cd480SApple OSS Distributions    # globals, local or expressons
580*699cd480SApple OSS Distributions    (Pdb) p type(seg.offset)
581*699cd480SApple OSS Distributions    <class 'macholib.ptypes.p_uint32'>
582*699cd480SApple OSS Distributions    (Pdb) p hex(seg.offset)
583*699cd480SApple OSS Distributions    '0x89fa08'
584*699cd480SApple OSS Distributions
585*699cd480SApple OSS Distributions    # Find attributes of a Python object.
586*699cd480SApple OSS Distributions    (Pdb) p dir(section_cls)
587*699cd480SApple OSS Distributions    ['__class__', '__cmp__', ... ,'reserved3', 'sectname', 'segname', 'size', 'to_fileobj', 'to_mmap', 'to_str']
588*699cd480SApple OSS Distributions    (Pdb) p section_cls.sectname
589*699cd480SApple OSS Distributions    <property object at 0x1077bbef0>
590*699cd480SApple OSS Distributions
591*699cd480SApple OSS DistributionsUnfortunately everything looks correct but there is actually one ineteresting frame in the stack. The one which
592*699cd480SApple OSS Distributionsprovides the offset to the seek method. Lets see where we are in the source code.
593*699cd480SApple OSS Distributions
594*699cd480SApple OSS Distributions    (Pdb) up
595*699cd480SApple OSS Distributions    > /Users/tjedlicka/Library/Python/3.8/lib/python/site-packages/macholib/MachO.py(287)load()
596*699cd480SApple OSS Distributions    -> fh.seek(seg.offset)
597*699cd480SApple OSS Distributions    (Pdb) list
598*699cd480SApple OSS Distributions    282  	                        not_zerofill = (seg.flags & S_ZEROFILL) != S_ZEROFILL
599*699cd480SApple OSS Distributions    283  	                        if seg.offset > 0 and seg.size > 0 and not_zerofill:
600*699cd480SApple OSS Distributions    284  	                            low_offset = min(low_offset, seg.offset)
601*699cd480SApple OSS Distributions    285  	                        if not_zerofill:
602*699cd480SApple OSS Distributions    286  	                            c = fh.tell()
603*699cd480SApple OSS Distributions    287  ->	                            fh.seek(seg.offset)
604*699cd480SApple OSS Distributions    288  	                            sd = fh.read(seg.size)
605*699cd480SApple OSS Distributions    289  	                            seg.add_section_data(sd)
606*699cd480SApple OSS Distributions    290  	                            fh.seek(c)
607*699cd480SApple OSS Distributions    291  	                        segs.append(seg)
608*699cd480SApple OSS Distributions    292  	                # data is a list of segments
609*699cd480SApple OSS Distributions
610*699cd480SApple OSS DistributionsRunning debugger on working case and stepping through the load() method shows that this code is not present.
611*699cd480SApple OSS DistributionsThat means we are broken by a library update! Older versions of library do not load data for a section.
612