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