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