]> git.saurik.com Git - apple/xnu.git/blame - tools/lldbmacros/kcdata.py
xnu-4903.241.1.tar.gz
[apple/xnu.git] / tools / lldbmacros / kcdata.py
CommitLineData
3e170ce0
A
1#!/usr/bin/env python
2import sys
3import struct
4import mmap
5import json
6import cgitb
7import copy
8import re
9import base64
10import argparse
11import os
12import shlex
13import subprocess
39037602
A
14import logging
15import contextlib
16import base64
3e170ce0 17
5ba3f43e
A
18class Globals(object):
19 pass
20G = Globals()
21G.accept_incomplete_data = False
22G.data_was_incomplete = False
23
3e170ce0
A
24kcdata_type_def = {
25 'KCDATA_TYPE_INVALID': 0x0,
26 'KCDATA_TYPE_STRING_DESC': 0x1,
27 'KCDATA_TYPE_UINT32_DESC': 0x2,
28 'KCDATA_TYPE_UINT64_DESC': 0x3,
29 'KCDATA_TYPE_INT32_DESC': 0x4,
30 'KCDATA_TYPE_INT64_DESC': 0x5,
31 'KCDATA_TYPE_BINDATA_DESC': 0x6,
32 'KCDATA_TYPE_ARRAY': 0x11,
d9a64523 33 'KCDATA_TYPE_TYPEDEFINITION': 0x12,
3e170ce0 34 'KCDATA_TYPE_CONTAINER_BEGIN': 0x13,
d9a64523 35 'KCDATA_TYPE_CONTAINER_END': 0x14,
39037602
A
36
37 'KCDATA_TYPE_ARRAY_PAD0': 0x20,
38 'KCDATA_TYPE_ARRAY_PAD1': 0x21,
39 'KCDATA_TYPE_ARRAY_PAD2': 0x22,
40 'KCDATA_TYPE_ARRAY_PAD3': 0x23,
41 'KCDATA_TYPE_ARRAY_PAD4': 0x24,
42 'KCDATA_TYPE_ARRAY_PAD5': 0x25,
43 'KCDATA_TYPE_ARRAY_PAD6': 0x26,
44 'KCDATA_TYPE_ARRAY_PAD7': 0x27,
45 'KCDATA_TYPE_ARRAY_PAD8': 0x28,
46 'KCDATA_TYPE_ARRAY_PAD9': 0x29,
47 'KCDATA_TYPE_ARRAY_PADa': 0x2a,
48 'KCDATA_TYPE_ARRAY_PADb': 0x2b,
49 'KCDATA_TYPE_ARRAY_PADc': 0x2c,
50 'KCDATA_TYPE_ARRAY_PADd': 0x2d,
51 'KCDATA_TYPE_ARRAY_PADe': 0x2e,
52 'KCDATA_TYPE_ARRAY_PADf': 0x2f,
53
3e170ce0
A
54 'KCDATA_TYPE_LIBRARY_LOADINFO': 0x30,
55 'KCDATA_TYPE_LIBRARY_LOADINFO64': 0x31,
56 'KCDATA_TYPE_TIMEBASE': 0x32,
39037602 57 'KCDATA_TYPE_MACH_ABSOLUTE_TIME': 0x33,
3e170ce0
A
58 'KCDATA_TYPE_TIMEVAL': 0x34,
59 'KCDATA_TYPE_USECS_SINCE_EPOCH': 0x35,
39037602
A
60 'KCDATA_TYPE_PID': 0x36,
61 'KCDATA_TYPE_PROCNAME': 0x37,
62 'KCDATA_TYPE_NESTED_KCDATA': 0x38,
63
3e170ce0
A
64 'STACKSHOT_KCCONTAINER_TASK': 0x903,
65 'STACKSHOT_KCCONTAINER_THREAD': 0x904,
39037602
A
66 'STACKSHOT_KCTYPE_DONATING_PIDS': 0x907,
67 'STACKSHOT_KCTYPE_SHAREDCACHE_LOADINFO': 0x908,
3e170ce0
A
68 'STACKSHOT_KCTYPE_KERN_STACKFRAME': 0x90A,
69 'STACKSHOT_KCTYPE_KERN_STACKFRAME64': 0x90B,
70 'STACKSHOT_KCTYPE_USER_STACKFRAME': 0x90C,
71 'STACKSHOT_KCTYPE_USER_STACKFRAME64': 0x90D,
72 'STACKSHOT_KCTYPE_BOOTARGS': 0x90E,
73 'STACKSHOT_KCTYPE_OSVERSION': 0x90F,
74 'STACKSHOT_KCTYPE_KERN_PAGE_SIZE': 0x910,
75 'STACKSHOT_KCTYPE_JETSAM_LEVEL': 0x911,
39037602 76 'STACKSHOT_KCTYPE_DELTA_SINCE_TIMESTAMP': 0x912,
39037602
A
77 'STACKSHOT_KCTYPE_KERN_STACKLR': 0x913,
78 'STACKSHOT_KCTYPE_KERN_STACKLR64': 0x914,
79 'STACKSHOT_KCTYPE_USER_STACKLR': 0x915,
80 'STACKSHOT_KCTYPE_USER_STACKLR64': 0x916,
81 'STACKSHOT_KCTYPE_NONRUNNABLE_TIDS': 0x917,
82 'STACKSHOT_KCTYPE_NONRUNNABLE_TASKS': 0x918,
83 'STACKSHOT_KCTYPE_CPU_TIMES': 0x919,
84 'STACKSHOT_KCTYPE_STACKSHOT_DURATION': 0x91a,
85 'STACKSHOT_KCTYPE_STACKSHOT_FAULT_STATS': 0x91b,
86 'STACKSHOT_KCTYPE_KERNELCACHE_LOADINFO': 0x91c,
813fb2f6 87 'STACKSHOT_KCTYPE_THREAD_WAITINFO' : 0x91d,
5ba3f43e
A
88 'STACKSHOT_KCTYPE_THREAD_GROUP_SNAPSHOT' : 0x91e,
89 'STACKSHOT_KCTYPE_THREAD_GROUP' : 0x91f,
90 'STACKSHOT_KCTYPE_JETSAM_COALITION_SNAPSHOT' : 0x920,
91 'STACKSHOT_KCTYPE_JETSAM_COALITION' : 0x921,
d9a64523 92 'STACKSHOT_KCTYPE_THREAD_POLICY_VERSION': 0x922,
5ba3f43e 93 'STACKSHOT_KCTYPE_INSTRS_CYCLES' : 0x923,
d9a64523
A
94 'STACKSHOT_KCTYPE_USER_STACKTOP' : 0x924,
95 'STACKSHOT_KCTYPE_ASID' : 0x925,
96 'STACKSHOT_KCTYPE_PAGE_TABLES' : 0x926,
97 'STACKSHOT_KCTYPE_SYS_SHAREDCACHE_LAYOUT' : 0x927,
98
99 'STACKSHOT_KCTYPE_TASK_DELTA_SNAPSHOT': 0x940,
100 'STACKSHOT_KCTYPE_THREAD_DELTA_SNAPSHOT': 0x941,
5ba3f43e 101
5ba3f43e 102
39037602 103
3e170ce0
A
104 'KCDATA_TYPE_BUFFER_END': 0xF19158ED,
105
106
107 'TASK_CRASHINFO_EXTMODINFO': 0x801,
108 'TASK_CRASHINFO_BSDINFOWITHUNIQID': 0x802,
109 'TASK_CRASHINFO_TASKDYLD_INFO': 0x803,
110 'TASK_CRASHINFO_UUID': 0x804,
111 'TASK_CRASHINFO_PID': 0x805,
112 'TASK_CRASHINFO_PPID': 0x806,
39037602
A
113
114 # Don't want anyone using this. It's struct rusage from whatever machine generated the data
115 #'TASK_CRASHINFO_RUSAGE': 0x807,
116 'Type_0x807': 0x807,
117
3e170ce0
A
118 'TASK_CRASHINFO_RUSAGE_INFO': 0x808,
119 'TASK_CRASHINFO_PROC_NAME': 0x809,
120 'TASK_CRASHINFO_PROC_STARTTIME': 0x80B,
121 'TASK_CRASHINFO_USERSTACK': 0x80C,
122 'TASK_CRASHINFO_ARGSLEN': 0x80D,
123 'TASK_CRASHINFO_EXCEPTION_CODES': 0x80E,
124 'TASK_CRASHINFO_PROC_PATH': 0x80F,
125 'TASK_CRASHINFO_PROC_CSFLAGS': 0x810,
126 'TASK_CRASHINFO_PROC_STATUS': 0x811,
127 'TASK_CRASHINFO_UID': 0x812,
128 'TASK_CRASHINFO_GID': 0x813,
129 'TASK_CRASHINFO_PROC_ARGC': 0x814,
130 'TASK_CRASHINFO_PROC_FLAGS': 0x815,
131 'TASK_CRASHINFO_CPUTYPE': 0x816,
132 'TASK_CRASHINFO_WORKQUEUEINFO': 0x817,
133 'TASK_CRASHINFO_RESPONSIBLE_PID': 0x818,
134 'TASK_CRASHINFO_DIRTY_FLAGS': 0x819,
135 'TASK_CRASHINFO_CRASHED_THREADID': 0x81A,
39037602
A
136 'TASK_CRASHINFO_COALITION_ID': 0x81B,
137 'EXIT_REASON_SNAPSHOT': 0x1001,
138 'EXIT_REASON_USER_DESC': 0x1002,
139 'EXIT_REASON_USER_PAYLOAD': 0x1003,
140 'EXIT_REASON_CODESIGNING_INFO': 0x1004,
5ba3f43e
A
141 'EXIT_REASON_WORKLOOP_ID': 0x1005,
142 'EXIT_REASON_DISPATCH_QUEUE_NO': 0x1006,
39037602
A
143 'KCDATA_BUFFER_BEGIN_CRASHINFO': 0xDEADF157,
144 'KCDATA_BUFFER_BEGIN_DELTA_STACKSHOT': 0xDE17A59A,
145 'KCDATA_BUFFER_BEGIN_STACKSHOT': 0x59a25807,
146 'KCDATA_BUFFER_BEGIN_OS_REASON': 0x53A20900,
147 'KCDATA_BUFFER_BEGIN_XNUPOST_CONFIG': 0x1E21C09F
3e170ce0
A
148}
149kcdata_type_def_rev = dict((v, k) for k, v in kcdata_type_def.iteritems())
150
151KNOWN_TYPES_COLLECTION = {}
152
39037602 153KNOWN_TOPLEVEL_CONTAINER_TYPES = ()
3e170ce0
A
154
155def enum(**args):
156 return type('enum', (), args)
157
158KCSUBTYPE_TYPE = enum(KC_ST_CHAR=1, KC_ST_INT8=2, KC_ST_UINT8=3, KC_ST_INT16=4, KC_ST_UINT16=5, KC_ST_INT32=6, KC_ST_UINT32=7, KC_ST_INT64=8, KC_ST_UINT64=9)
159
160
39037602
A
161LEGAL_OLD_STYLE_ARRAY_TYPE_NAMES = ['KCDATA_TYPE_LIBRARY_LOADINFO',
162 'KCDATA_TYPE_LIBRARY_LOADINFO64',
163 'STACKSHOT_KCTYPE_KERN_STACKFRAME',
164 'STACKSHOT_KCTYPE_USER_STACKFRAME',
165 'STACKSHOT_KCTYPE_KERN_STACKFRAME64',
166 'STACKSHOT_KCTYPE_USER_STACKFRAME64',
167 'STACKSHOT_KCTYPE_DONATING_PIDS',
168 'STACKSHOT_KCTYPE_THREAD_DELTA_SNAPSHOT']
169
170KCDATA_FLAGS_STRUCT_PADDING_MASK = 0xf
171KCDATA_FLAGS_STRUCT_HAS_PADDING = 0x80
172
3e170ce0
A
173class KCSubTypeElement(object):
174 """convert kcdata_subtype_descriptor to """
175 _unpack_formats = (None, 'c', 'b', 'B', 'h', 'H', 'i', 'I', 'q', 'Q')
176 _ctypes = ('Unknown', 'char', 'int8_t', 'uint8_t', 'int16_t', 'uint16_t', 'int32_t', 'uint32_t', 'int64_t', 'uint64_t')
177
178 def __init__(self, st_name, st_type, st_size, st_offset=0, st_flag=0, custom_repr=None):
179 self.name = st_name
180 self.offset = st_offset
181 self.type_id = st_type
182 if st_type <= 0 or st_type > KCSUBTYPE_TYPE.KC_ST_UINT64:
183 raise ValueError("Invalid type passed %d" % st_type)
184 self.unpack_fmt = KCSubTypeElement._unpack_formats[self.type_id]
185 self.size = st_size
186 self.totalsize = st_size
187 self.count = 1
188 self.is_array_type = False
189 self.custom_JsonRepr = custom_repr
190 if (st_flag & 0x1) == 0x1:
191 self.is_array_type = True
192 self.size = st_size & 0xffff
193 self.count = (st_size >> 16) & 0xffff
194 self.totalsize = self.size * self.count
195
196 @staticmethod
197 def GetSizeForArray(el_count, el_size):
198 return ((el_count & 0xffff) << 16) | (el_size & 0xffff)
199
200 @staticmethod
201 def FromBinaryTypeData(byte_data):
202 (st_flag, st_type, st_offset, st_size, st_name) = struct.unpack_from('=BBHI32s', byte_data)
203 st_name = st_name.rstrip('\x00')
204 return KCSubTypeElement(st_name, st_type, st_size, st_offset, st_flag)
205
206 @staticmethod
a39ff7e2 207 def FromBasicCtype(st_name, st_type, st_offset=0, legacy_size=None):
3e170ce0
A
208 if st_type <= 0 or st_type > KCSUBTYPE_TYPE.KC_ST_UINT64:
209 raise ValueError("Invalid type passed %d" % st_type)
210 st_size = struct.calcsize(KCSubTypeElement._unpack_formats[st_type])
211 st_flag = 0
212 retval = KCSubTypeElement(st_name, st_type, st_size, st_offset, st_flag, KCSubTypeElement._get_naked_element_value)
a39ff7e2
A
213 if legacy_size:
214 retval.legacy_size = legacy_size
3e170ce0
A
215 return retval
216
217 @staticmethod
218 def FromKCSubTypeElement(other, name_override=''):
219 _copy = copy.copy(other)
220 if name_override:
221 _copy.name = name_override
222 return copy
223
224 def GetName(self):
225 return self.name
226
227 def GetTotalSize(self):
228 return self.totalsize
229
230 def GetValueAsString(self, base_data, array_pos=0):
231 return str(self.GetValue(base_data, array_pos))
232
233 def GetValue(self, base_data, array_pos=0):
234 return struct.unpack_from(self.unpack_fmt, base_data[self.offset + (array_pos * self.size):])[0]
235
236 @staticmethod
237 def _get_naked_element_value(elementValue, elementName):
238 return json.dumps(elementValue)
239
240 def __str__(self):
241 if self.is_array_type:
242 return '[%d,%d] %s %s[%d];' % (self.offset, self.totalsize, self.GetCTypeDesc(), self.name, self.count)
243 return '[%d,%d] %s %s;' % (self.offset, self.totalsize, self.GetCTypeDesc(), self.name)
244
245 def __repr__(self):
246 return str(self)
247
248 def GetCTypeDesc(self):
249 return KCSubTypeElement._ctypes[self.type_id]
250
251 def GetStringRepr(self, base_data):
252 if not self.is_array_type:
253 return self.GetValueAsString(base_data)
254 if self.type_id == KCSUBTYPE_TYPE.KC_ST_CHAR:
255 str_len = self.count
256 if len(base_data) < str_len:
257 str_len = len(base_data)
258 str_arr = []
259 for i in range(str_len):
260 _v = self.GetValue(base_data, i)
261 if ord(_v) == 0:
262 break
263 str_arr.append(self.GetValueAsString(base_data, i))
5ba3f43e 264 return json.dumps(''.join(str_arr))
39037602
A
265
266 count = self.count
267 if count > len(base_data)/self.size:
268 count = len(base_data)/self.size
269
270 o = '[' + ','.join([self.GetValueAsString(base_data, i) for i in range(count)]) + ']'
271
3e170ce0
A
272 return o
273
39037602
A
274 def GetJsonRepr(self, base_data, flags=0):
275 if (flags & (KCDATA_FLAGS_STRUCT_HAS_PADDING | KCDATA_FLAGS_STRUCT_PADDING_MASK)) != 0:
276 padding = (flags & KCDATA_FLAGS_STRUCT_PADDING_MASK)
277 if padding:
278 base_data = base_data[:-padding]
3e170ce0
A
279 if self.custom_JsonRepr:
280 if self.is_array_type:
281 e_data = [self.GetValue(base_data, i) for i in range(self.count)]
282 else:
283 e_data = self.GetValue(base_data)
284 return self.custom_JsonRepr(e_data, self.name)
285 return self.GetStringRepr(base_data)
286
39037602
A
287 def sizeof(self):
288 return self.totalsize
289
290 def ShouldSkip(self, data):
291 return len(data) < self.offset + self.totalsize
292
293 def ShouldMerge(self):
294 return False
295
3e170ce0
A
296
297class KCTypeDescription(object):
d9a64523 298 def __init__(self, t_type_id, t_elements=[], t_name='anon', custom_repr=None, legacy_size=None, merge=False, naked=False):
3e170ce0
A
299 self.type_id = t_type_id
300 self.elements = t_elements
301 self.name = t_name
302 self.totalsize = 0
303 self.custom_JsonRepr = custom_repr
a39ff7e2
A
304 if legacy_size:
305 self.legacy_size = legacy_size
39037602 306 self.merge = merge
d9a64523 307 self.naked = naked
3e170ce0
A
308 for e in self.elements:
309 self.totalsize += e.GetTotalSize()
310
311 def ValidateData(self, base_data):
312 if len(base_data) >= self.totalsize:
313 return True
314 return False
315
316 def GetTypeID(self):
317 return self.type_id
318
319 def GetName(self):
320 return self.name
321
322 def __str__(self):
323 o = '%s {\n\t' % self.name + "\n\t".join([str(e) for e in self.elements]) + '\n};'
324 return o
325
326 @staticmethod
327 def FromKCTypeDescription(other, t_type_id, t_name):
a39ff7e2
A
328 retval = KCTypeDescription(t_type_id, other.elements, t_name, other.custom_JsonRepr,
329 legacy_size=getattr(other, 'legacy_size', None))
3e170ce0
A
330 return retval
331
39037602
A
332 def ShouldMerge(self):
333 return self.merge
334
335 def GetJsonRepr(self, base_data, flags):
336 if (flags & (KCDATA_FLAGS_STRUCT_HAS_PADDING | KCDATA_FLAGS_STRUCT_PADDING_MASK)) != 0:
337 padding = (flags & KCDATA_FLAGS_STRUCT_PADDING_MASK)
338 if padding:
339 base_data = base_data[:-padding]
a39ff7e2 340 elif hasattr(self, 'legacy_size') and len(base_data) == self.legacy_size + ((-self.legacy_size) & 0xf):
39037602 341 base_data = base_data[:self.legacy_size]
3e170ce0
A
342 if self.custom_JsonRepr:
343 return self.custom_JsonRepr([e.GetValue(base_data) for e in self.elements])
d9a64523
A
344 if self.naked:
345 o = ", ".join([e.GetJsonRepr(base_data) for e in self.elements if not e.ShouldSkip(base_data)])
346 else:
347 o = ", ".join(['"%s": %s' % (e.GetName(), e.GetJsonRepr(base_data)) for e in self.elements if not e.ShouldSkip(base_data)])
39037602
A
348 if not self.merge:
349 o = '{' + o + '}'
3e170ce0
A
350 return o
351
39037602
A
352 def sizeof(self):
353 return max(st.totalsize + st.offset for st in self.elements)
354
3e170ce0
A
355
356def GetTypeNameForKey(k):
357 retval = "0x%x" % k
358 if k in KNOWN_TYPES_COLLECTION:
359 retval = KNOWN_TYPES_COLLECTION[k].GetName()
360 elif k in kcdata_type_def_rev:
361 retval = kcdata_type_def_rev[k]
362 return retval
363
364
365def GetTypeForName(n):
366 ret = 0
367 if n in kcdata_type_def:
368 ret = kcdata_type_def[n]
369 return ret
370
371
39037602
A
372LEGAL_OLD_STYLE_ARRAY_TYPES = map(GetTypeForName, LEGAL_OLD_STYLE_ARRAY_TYPE_NAMES)
373
374kcdata_type_def_rev[GetTypeForName('KCDATA_BUFFER_BEGIN_STACKSHOT')] = 'kcdata_stackshot'
375kcdata_type_def_rev[GetTypeForName('KCDATA_BUFFER_BEGIN_DELTA_STACKSHOT')] = 'kcdata_delta_stackshot'
376kcdata_type_def_rev[GetTypeForName('KCDATA_BUFFER_BEGIN_CRASHINFO')] = 'kcdata_crashinfo'
377kcdata_type_def_rev[GetTypeForName('KCDATA_BUFFER_BEGIN_OS_REASON')] = 'kcdata_reason'
378kcdata_type_def_rev[GetTypeForName('STACKSHOT_KCCONTAINER_TASK')] = 'task_snapshots'
379kcdata_type_def_rev[GetTypeForName('STACKSHOT_KCCONTAINER_THREAD')] = 'thread_snapshots'
380kcdata_type_def_rev[GetTypeForName('KCDATA_BUFFER_BEGIN_XNUPOST_CONFIG')] = 'xnupost_testconfig'
381
382class Indent(object):
383 def __init__(self):
384 self.n = 0
385 def __call__(self, end=False):
386 if end:
387 return " " * (self.n-4)
388 else:
389 return " " * self.n
390 @contextlib.contextmanager
391 def indent(self):
392 self.n += 4
393 try:
394 yield
395 finally:
396 self.n -= 4
397
398INDENT = Indent()
399
3e170ce0 400class KCObject(object):
39037602
A
401
402 def __init__(self, type_code, data, offset, flags=0):
403
3e170ce0
A
404 self.i_type = type_code
405 self.i_data = data
39037602 406 self.offset = offset
3e170ce0 407 self.i_size = len(data)
3e170ce0
A
408 self.i_flags = flags
409 self.obj_collection = []
410 self.obj = {}
411 self.is_container_type = False
412 self.is_array_type = False
413 self.is_naked_type = False
39037602
A
414 self.nested_kcdata = None
415 self.i_name = GetTypeNameForKey(type_code)
416
3e170ce0
A
417 self.ParseData()
418
39037602
A
419 if self.i_type == GetTypeForName('KCDATA_TYPE_CONTAINER_BEGIN'):
420 self.__class__ = KCContainerObject
421
422 if self.i_type in KNOWN_TOPLEVEL_CONTAINER_TYPES:
423 self.__class__ = KCBufferObject
424
425 self.InitAfterParse()
426
5ba3f43e
A
427 def __str__(self):
428 return "<KCObject at 0x%x>" % self.offset
429
39037602
A
430 def InitAfterParse(self):
431 pass
432
3e170ce0
A
433 @staticmethod
434 def FromKCItem(kcitem):
39037602 435 return KCObject(kcitem.i_type, kcitem.i_data, kcitem.i_offset, kcitem.i_flags)
3e170ce0
A
436
437 def IsContainerEnd(self):
d9a64523 438 return self.i_type == GetTypeForName('KCDATA_TYPE_CONTAINER_END')
39037602
A
439
440 def IsBufferEnd(self):
441 return self.i_type == GetTypeForName('KCDATA_TYPE_BUFFER_END')
442
443 def IsArray(self):
444 return self.is_array_type
445
446 def ShouldMerge(self):
447 if self.nested_kcdata:
3e170ce0 448 return True
39037602
A
449 elif not self.is_array_type and self.i_type in KNOWN_TYPES_COLLECTION:
450 return KNOWN_TYPES_COLLECTION[self.i_type].ShouldMerge()
451 else:
452 return False
3e170ce0
A
453
454 def GetJsonRepr(self):
455 if self.is_array_type:
456 return '[' + ', '.join([i.GetJsonRepr() for i in self.obj_collection]) + ']'
3e170ce0 457 if self.i_type in KNOWN_TYPES_COLLECTION:
39037602 458 return KNOWN_TYPES_COLLECTION[self.i_type].GetJsonRepr(self.i_data, self.i_flags)
3e170ce0
A
459 if self.is_naked_type:
460 return json.dumps(self.obj)
39037602
A
461 if self.nested_kcdata:
462 return self.nested_kcdata.GetJsonRepr()
3e170ce0
A
463
464 raise NotImplementedError("Broken GetJsonRepr implementation")
465
466 def ParseData(self):
39037602
A
467
468
3e170ce0 469 if self.i_type == GetTypeForName('KCDATA_TYPE_CONTAINER_BEGIN'):
3e170ce0
A
470 self.obj['uniqID'] = self.i_flags
471 self.i_name = str(self.obj['uniqID'])
472 self.obj['typeID'] = struct.unpack_from('I', self.i_data)[0]
39037602 473 logging.info("0x%08x: %sCONTAINER: %s(%x)" % (self.offset, INDENT(), GetTypeNameForKey(self.obj['typeID']), self.i_flags))
3e170ce0 474
39037602 475 elif self.i_type in (KNOWN_TOPLEVEL_CONTAINER_TYPES):
3e170ce0
A
476 self.obj['uniqID'] = self.i_name
477 self.obj['typeID'] = self.i_type
39037602 478 logging.info("0x%08x: %s%s" % (self.offset, INDENT(), self.i_name))
3e170ce0 479
d9a64523 480 elif self.i_type == GetTypeForName('KCDATA_TYPE_CONTAINER_END'):
3e170ce0 481 self.obj['uniqID'] = self.i_flags
39037602 482 logging.info("0x%08x: %sEND" % (self.offset, INDENT(end=True)))
3e170ce0
A
483
484 elif self.i_type == GetTypeForName('KCDATA_TYPE_BUFFER_END'):
485 self.obj = ''
39037602 486 logging.info("0x%08x: %sEND_BUFFER" % (self.offset, INDENT(end=True)))
3e170ce0
A
487
488 elif self.i_type == GetTypeForName('KCDATA_TYPE_UINT32_DESC'):
489 self.is_naked_type = True
490 u_d = struct.unpack_from('32sI', self.i_data)
491 self.i_name = u_d[0].strip(chr(0))
492 self.obj = u_d[1]
39037602 493 logging.info("0x%08x: %s%s" % (self.offset, INDENT(), self.i_name))
3e170ce0
A
494
495 elif self.i_type == GetTypeForName('KCDATA_TYPE_UINT64_DESC'):
496 self.is_naked_type = True
497 u_d = struct.unpack_from('32sQ', self.i_data)
498 self.i_name = u_d[0].strip(chr(0))
499 self.obj = u_d[1]
39037602 500 logging.info("0x%08x: %s%s" % (self.offset, INDENT(), self.i_name))
3e170ce0 501
d9a64523 502 elif self.i_type == GetTypeForName('KCDATA_TYPE_TYPEDEFINITION'):
3e170ce0
A
503 self.is_naked_type = True
504 u_d = struct.unpack_from('II32s', self.i_data)
39037602
A
505 self.obj['name'] = u_d[2].split(chr(0))[0]
506 self.i_name = "typedef[%s]" % self.obj['name']
3e170ce0
A
507 self.obj['typeID'] = u_d[0]
508 self.obj['numOfFields'] = u_d[1]
509 element_arr = []
510 for i in range(u_d[1]):
511 e = KCSubTypeElement.FromBinaryTypeData(self.i_data[40+(i*40):])
3e170ce0
A
512 element_arr.append(e)
513 type_desc = KCTypeDescription(u_d[0], element_arr, self.obj['name'])
3e170ce0
A
514 self.obj['fields'] = [str(e) for e in element_arr]
515 KNOWN_TYPES_COLLECTION[type_desc.GetTypeID()] = type_desc
39037602 516 logging.info("0x%08x: %s%s" % (self.offset, INDENT(), self.i_name))
3e170ce0
A
517
518 elif self.i_type == GetTypeForName('KCDATA_TYPE_ARRAY'):
519 self.is_array_type = True
520 e_t = (self.i_flags >> 32) & 0xffffffff
39037602
A
521 if e_t not in LEGAL_OLD_STYLE_ARRAY_TYPES:
522 raise Exception, "illegal old-style array type: %s (0x%x)" % (GetTypeNameForKey(e_t), e_t)
3e170ce0 523 e_c = self.i_flags & 0xffffffff
a39ff7e2 524 e_s = KNOWN_TYPES_COLLECTION[e_t].legacy_size
39037602 525 if e_s * e_c > self.i_size:
a39ff7e2 526 raise Exception("array too small for its count")
3e170ce0
A
527 self.obj['typeID'] = e_t
528 self.i_name = GetTypeNameForKey(e_t)
529 self.i_type = e_t
530 self.obj['numOfElements'] = e_c
531 self.obj['sizeOfElement'] = e_s
39037602 532 logging.info("0x%08x: %sARRAY: %s" % (self.offset, INDENT(), self.i_name))
3e170ce0 533 #populate the array here by recursive creation of KCObject
39037602
A
534 with INDENT.indent():
535 for _i in range(e_c):
536 _o = KCObject(e_t, self.i_data[(_i * e_s):(_i * e_s) + e_s], self.offset + _i*e_s)
537 self.obj_collection.append(_o)
538
539 elif self.i_type >= GetTypeForName('KCDATA_TYPE_ARRAY_PAD0') and self.i_type <= GetTypeForName('KCDATA_TYPE_ARRAY_PADf'):
540 self.is_array_type = True
541 e_t = (self.i_flags >> 32) & 0xffffffff
542 e_c = self.i_flags & 0xffffffff
543 e_s = (self.i_size - (self.i_type & 0xf)) / e_c if e_c != 0 else None
544 self.obj['typeID'] = e_t
545 self.i_name = GetTypeNameForKey(e_t)
546 self.i_type = e_t
547 self.obj['numOfElements'] = e_c
548 self.obj['sizeOfElement'] = e_s
549 logging.info("0x%08x: %sARRAY: %s" % (self.offset, INDENT(), self.i_name))
550 #populate the array here by recursive creation of KCObject
551 with INDENT.indent():
552 for _i in range(e_c):
553 _o = KCObject(e_t, self.i_data[(_i * e_s):(_i * e_s) + e_s], self.offset + _i*e_s)
554 self.obj_collection.append(_o)
555
556 elif self.i_type == GetTypeForName('KCDATA_TYPE_NESTED_KCDATA'):
557 logging.info("0x%08x: %sNESTED_KCDATA" % (self.offset, INDENT()))
558 with INDENT.indent():
559 nested_iterator = kcdata_item_iterator(self.i_data[:self.i_size])
560 nested_buffer = KCObject.FromKCItem(nested_iterator.next())
561 if not isinstance(nested_buffer, KCBufferObject):
562 raise Exception, "nested buffer isn't a KCBufferObject"
563 nested_buffer.ReadItems(nested_iterator)
564 self.nested_kcdata = nested_buffer
565
3e170ce0
A
566 elif self.i_type in KNOWN_TYPES_COLLECTION:
567 self.i_name = KNOWN_TYPES_COLLECTION[self.i_type].GetName()
568 self.is_naked_type = True
39037602 569 logging.info("0x%08x: %s%s" % (self.offset, INDENT(), self.i_name))
3e170ce0
A
570 else:
571 self.is_naked_type = True
572 #self.obj = "data of len %d" % len(self.i_data)
573 #self.obj = ''.join(["%x" % ki for ki in struct.unpack('%dB' % len(self.i_data), self.i_data)])
39037602
A
574 self.obj = map(ord, self.i_data)
575 logging.info("0x%08x: %s%s" % (self.offset, INDENT(), self.i_name))
3e170ce0
A
576
577
578class KCContainerObject(KCObject):
579 def __init__(self, *args, **kwargs):
39037602
A
580 assert False
581
582 def InitAfterParse(self):
3e170ce0
A
583 self.obj_container_dict = {}
584 self.obj_nested_objs = {}
585
39037602
A
586 def ShouldMerge(self):
587 return True
588
3e170ce0 589 def GetJsonRepr(self):
39037602
A
590 # o = '"%s"' % self.obj['uniqID'] + ' : { "typeID" : %d ,' % self.obj['typeID']
591 o = '"%s"' % self.obj['uniqID'] + ' : { '
3e170ce0 592 for (k, v) in self.obj_container_dict.items():
39037602 593 if v.ShouldMerge():
3e170ce0
A
594 o += v.GetJsonRepr() + ","
595 else:
596 o += ' "%s" : ' % k + v.GetJsonRepr() + ","
597
598 for (k, v) in self.obj_nested_objs.items():
599 o += '"%s" : {' % k + ",".join([vi.GetJsonRepr() for vi in v.values()]) + "} ,"
600
601 o = o.rstrip(',') + "}"
602
603 return o
604
605 def AddObject(self, kco):
39037602
A
606 assert not kco.IsContainerEnd()
607 if isinstance(kco, KCContainerObject):
3e170ce0
A
608 type_name = GetTypeNameForKey(kco.obj['typeID'])
609 if type_name not in self.obj_nested_objs:
610 self.obj_nested_objs[type_name] = {}
611 self.obj_nested_objs[type_name][kco.i_name] = kco
612 return
39037602
A
613 if kco.i_name in self.obj_container_dict:
614 if kco.IsArray() and self.obj_container_dict[kco.i_name].IsArray():
615 self.obj_container_dict[kco.i_name].obj_collection.extend( kco.obj_collection )
616 else:
617 self.obj_container_dict[kco.i_name] = kco
618
619 def IsEndMarker(self, o):
620 if not o.IsContainerEnd():
621 return False
622 if o.i_flags != self.i_flags:
623 raise Exception, "container end marker doesn't match"
624 return True
625
626 no_end_message = "could not find container end marker"
627
628 def ReadItems(self, iterator):
629 found_end = False
630 with INDENT.indent():
631 for i in iterator:
632 o = KCObject.FromKCItem(i)
633 if self.IsEndMarker(o):
634 found_end = True
635 break
5ba3f43e
A
636 if o.IsBufferEnd():
637 break
39037602
A
638 if isinstance(o, KCContainerObject):
639 o.ReadItems(iterator)
640 self.AddObject(o)
641 if not found_end:
5ba3f43e
A
642 if G.accept_incomplete_data:
643 if not G.data_was_incomplete:
644 print >>sys.stderr, "kcdata.py WARNING: data is incomplete!"
645 G.data_was_incomplete = True
646 else:
647 raise Exception, self.no_end_message
648
39037602
A
649
650
651class KCBufferObject(KCContainerObject):
652
653 def IsEndMarker(self,o):
654 if o.IsContainerEnd():
655 raise Exception, "container end marker at the toplevel"
656 return o.IsBufferEnd()
657
658 no_end_message = "could not find buffer end marker"
3e170ce0
A
659
660
661class KCData_item:
662 """ a basic kcdata_item type object.
663 """
664 header_size = 16 # (uint32_t + uint32_t + uint64_t)
665
666 def __init__(self, item_type, item_size, item_flags, item_data):
667 self.i_type = item_type
668 self.i_size = item_size
669 self.i_flags = item_flags
670 self.i_data = item_data
39037602 671 self.i_offset = None
3e170ce0
A
672
673 def __init__(self, barray, pos=0):
674 """ create an object by parsing data from bytes array
675 returns : obj - if data is readable
676 raises ValueError if something is not ok.
677 """
678 self.i_type = struct.unpack('I', barray[pos:pos+4])[0] # int.from_bytes(barray[pos:pos+4])
679 self.i_size = struct.unpack('I', barray[pos+4:pos+8])[0] # int.from_bytes(barray[pos+4:pos+8])
680 self.i_flags = struct.unpack('Q', barray[pos+8:pos+16])[0] # int.from_bytes(barray[pos+8:pos+16])
681 self.i_data = barray[pos+16: (pos + 16 + self.i_size)]
39037602 682 self.i_offset = pos
3e170ce0
A
683
684 def __len__(self):
685 return self.i_size + KCData_item.header_size
686
687 def GetHeaderDescription(self):
39037602
A
688 outs = "type: 0x%x size: 0x%x flags: 0x%x (%s)" % (self.i_type, self.i_size, self.i_flags, GetTypeNameForKey(self.i_type))
689 if not self.i_offset is None:
690 outs = "pos: 0x%x" % self.i_offset + outs
3e170ce0
A
691 return outs
692
693 def __str__(self):
694 return self.GetHeaderDescription()
695
39037602
A
696def kcdata_item_iterator(data):
697 file_len = len(data)
698 curpos = 0
699 while curpos < file_len:
700 item = KCData_item(data, curpos)
701 yield item
702 curpos += len(item)
3e170ce0
A
703
704def _get_data_element(elementValues):
705 return json.dumps(elementValues[-1])
706
39037602
A
707KNOWN_TOPLEVEL_CONTAINER_TYPES = map(GetTypeForName, ('KCDATA_BUFFER_BEGIN_CRASHINFO', 'KCDATA_BUFFER_BEGIN_STACKSHOT', 'KCDATA_BUFFER_BEGIN_DELTA_STACKSHOT', 'KCDATA_BUFFER_BEGIN_OS_REASON','KCDATA_BUFFER_BEGIN_XNUPOST_CONFIG'))
708
3e170ce0
A
709KNOWN_TYPES_COLLECTION[GetTypeForName('KCDATA_TYPE_UINT32_DESC')] = KCTypeDescription(GetTypeForName('KCDATA_TYPE_UINT32_DESC'), (
710 KCSubTypeElement('desc', KCSUBTYPE_TYPE.KC_ST_CHAR, KCSubTypeElement.GetSizeForArray(32, 1), 0, 1),
711 KCSubTypeElement('data', KCSUBTYPE_TYPE.KC_ST_UINT32, 4, 32, 0)
712),
713 'KCDATA_TYPE_UINT32_DESC',
714 _get_data_element
715)
716
717KNOWN_TYPES_COLLECTION[GetTypeForName('KCDATA_TYPE_UINT64_DESC')] = KCTypeDescription(GetTypeForName('KCDATA_TYPE_UINT64_DESC'), (
718 KCSubTypeElement('desc', KCSUBTYPE_TYPE.KC_ST_CHAR, KCSubTypeElement.GetSizeForArray(32, 1), 0, 1),
719 KCSubTypeElement('data', KCSUBTYPE_TYPE.KC_ST_UINT64, 8, 32, 0)
720),
721 'KCDATA_TYPE_UINT64_DESC',
722 _get_data_element
723)
724
725KNOWN_TYPES_COLLECTION[GetTypeForName('KCDATA_TYPE_TIMEBASE')] = KCTypeDescription(GetTypeForName('KCDATA_TYPE_TIMEBASE'), (
39037602
A
726 KCSubTypeElement('numer', KCSUBTYPE_TYPE.KC_ST_UINT32, 4, 0, 0),
727 KCSubTypeElement('denom', KCSUBTYPE_TYPE.KC_ST_UINT32, 4, 4, 0)
3e170ce0 728),
39037602 729 'mach_timebase_info'
3e170ce0
A
730)
731
732
733STACKSHOT_IO_NUM_PRIORITIES = 4
734KNOWN_TYPES_COLLECTION[0x901] = KCTypeDescription(0x901, (
39037602
A
735 KCSubTypeElement.FromBasicCtype('ss_disk_reads_count', KCSUBTYPE_TYPE.KC_ST_UINT64, 0),
736 KCSubTypeElement.FromBasicCtype('ss_disk_reads_size', KCSUBTYPE_TYPE.KC_ST_UINT64, 8),
737 KCSubTypeElement.FromBasicCtype('ss_disk_writes_count', KCSUBTYPE_TYPE.KC_ST_UINT64, 16),
738 KCSubTypeElement.FromBasicCtype('ss_disk_writes_size', KCSUBTYPE_TYPE.KC_ST_UINT64, 24),
739 KCSubTypeElement('ss_io_priority_count', KCSUBTYPE_TYPE.KC_ST_UINT64, KCSubTypeElement.GetSizeForArray(STACKSHOT_IO_NUM_PRIORITIES, 8), 32, 1),
740 KCSubTypeElement('ss_io_priority_size', KCSUBTYPE_TYPE.KC_ST_UINT64, KCSubTypeElement.GetSizeForArray(STACKSHOT_IO_NUM_PRIORITIES, 8), 32 + (STACKSHOT_IO_NUM_PRIORITIES * 8), 1),
741 KCSubTypeElement.FromBasicCtype('ss_paging_count', KCSUBTYPE_TYPE.KC_ST_UINT64, 32 + 2 * (STACKSHOT_IO_NUM_PRIORITIES * 8)),
742 KCSubTypeElement.FromBasicCtype('ss_paging_size', KCSUBTYPE_TYPE.KC_ST_UINT64, 40 + 2 * (STACKSHOT_IO_NUM_PRIORITIES * 8)),
743 KCSubTypeElement.FromBasicCtype('ss_non_paging_count', KCSUBTYPE_TYPE.KC_ST_UINT64, 48 + 2 * (STACKSHOT_IO_NUM_PRIORITIES * 8)),
744 KCSubTypeElement.FromBasicCtype('ss_non_paging_size', KCSUBTYPE_TYPE.KC_ST_UINT64, 56 + 2 * (STACKSHOT_IO_NUM_PRIORITIES * 8)),
745 KCSubTypeElement.FromBasicCtype('ss_data_count', KCSUBTYPE_TYPE.KC_ST_UINT64, 64 + 2 * (STACKSHOT_IO_NUM_PRIORITIES * 8)),
746 KCSubTypeElement.FromBasicCtype('ss_data_size', KCSUBTYPE_TYPE.KC_ST_UINT64, 72 + 2 * (STACKSHOT_IO_NUM_PRIORITIES * 8)),
747 KCSubTypeElement.FromBasicCtype('ss_metadata_count', KCSUBTYPE_TYPE.KC_ST_UINT64, 80 + 2 * (STACKSHOT_IO_NUM_PRIORITIES * 8)),
748 KCSubTypeElement.FromBasicCtype('ss_metadata_size', KCSUBTYPE_TYPE.KC_ST_UINT64, 88 + 2 * (STACKSHOT_IO_NUM_PRIORITIES * 8))
3e170ce0
A
749),
750 'io_statistics'
751)
752
753KNOWN_TYPES_COLLECTION[0x902] = KCTypeDescription(0x902, (
754 KCSubTypeElement('snapshot_magic', KCSUBTYPE_TYPE.KC_ST_UINT32, 4, 4 * 0, 0),
755 KCSubTypeElement('free_pages', KCSUBTYPE_TYPE.KC_ST_UINT32, 4, 4 * 1, 0),
756 KCSubTypeElement('active_pages', KCSUBTYPE_TYPE.KC_ST_UINT32, 4, 4 * 2, 0),
757 KCSubTypeElement('inactive_pages', KCSUBTYPE_TYPE.KC_ST_UINT32, 4, 4 * 3, 0),
758 KCSubTypeElement('purgeable_pages', KCSUBTYPE_TYPE.KC_ST_UINT32, 4, 4 * 4, 0),
759 KCSubTypeElement('wired_pages', KCSUBTYPE_TYPE.KC_ST_UINT32, 4, 4 * 5, 0),
760 KCSubTypeElement('speculative_pages', KCSUBTYPE_TYPE.KC_ST_UINT32, 4, 4 * 6, 0),
761 KCSubTypeElement('throttled_pages', KCSUBTYPE_TYPE.KC_ST_UINT32, 4, 4 * 7, 0),
762 KCSubTypeElement('filebacked_pages', KCSUBTYPE_TYPE.KC_ST_UINT32, 4, 4 * 8, 0),
763 KCSubTypeElement('compressions', KCSUBTYPE_TYPE.KC_ST_UINT32, 4, 4 * 9, 0),
764 KCSubTypeElement('decompressions', KCSUBTYPE_TYPE.KC_ST_UINT32, 4, 4 * 10, 0),
765 KCSubTypeElement('compressor_size', KCSUBTYPE_TYPE.KC_ST_UINT32, 4, 4 * 11, 0),
766 KCSubTypeElement('busy_buffer_count', KCSUBTYPE_TYPE.KC_ST_INT32, 4, 4 * 12, 0),
767 KCSubTypeElement('pages_wanted', KCSUBTYPE_TYPE.KC_ST_UINT32, 4, 4 * 13, 0),
768 KCSubTypeElement('pages_reclaimed', KCSUBTYPE_TYPE.KC_ST_UINT32, 4, 4 * 14, 0),
769 KCSubTypeElement('pages_wanted_reclaimed_valid', KCSUBTYPE_TYPE.KC_ST_UINT8, 1, 4 * 15, 0)
770),
771 'mem_and_io_snapshot'
772)
773
774
775KNOWN_TYPES_COLLECTION[0x905] = KCTypeDescription(0x905, (
39037602
A
776 KCSubTypeElement.FromBasicCtype('ts_unique_pid', KCSUBTYPE_TYPE.KC_ST_UINT64, 0),
777 KCSubTypeElement.FromBasicCtype('ts_ss_flags', KCSUBTYPE_TYPE.KC_ST_UINT64, 8),
778 KCSubTypeElement.FromBasicCtype('ts_user_time_in_terminated_thre', KCSUBTYPE_TYPE.KC_ST_UINT64, 16),
779 KCSubTypeElement.FromBasicCtype('ts_system_time_in_terminated_th', KCSUBTYPE_TYPE.KC_ST_UINT64, 24),
780 KCSubTypeElement.FromBasicCtype('ts_p_start_sec', KCSUBTYPE_TYPE.KC_ST_UINT64, 32),
781 KCSubTypeElement.FromBasicCtype('ts_task_size', KCSUBTYPE_TYPE.KC_ST_UINT64, 40),
782 KCSubTypeElement.FromBasicCtype('ts_max_resident_size', KCSUBTYPE_TYPE.KC_ST_UINT64, 48),
783 KCSubTypeElement.FromBasicCtype('ts_suspend_count', KCSUBTYPE_TYPE.KC_ST_UINT32, 56),
784 KCSubTypeElement.FromBasicCtype('ts_faults', KCSUBTYPE_TYPE.KC_ST_UINT32, 60),
785 KCSubTypeElement.FromBasicCtype('ts_pageins', KCSUBTYPE_TYPE.KC_ST_UINT32, 64),
786 KCSubTypeElement.FromBasicCtype('ts_cow_faults', KCSUBTYPE_TYPE.KC_ST_UINT32, 68),
787 KCSubTypeElement.FromBasicCtype('ts_was_throttled', KCSUBTYPE_TYPE.KC_ST_UINT32, 72),
788 KCSubTypeElement.FromBasicCtype('ts_did_throttle', KCSUBTYPE_TYPE.KC_ST_UINT32, 76),
789 KCSubTypeElement.FromBasicCtype('ts_latency_qos', KCSUBTYPE_TYPE.KC_ST_UINT32, 80),
790 KCSubTypeElement.FromBasicCtype('ts_pid', KCSUBTYPE_TYPE.KC_ST_INT32, 84),
791 KCSubTypeElement('ts_p_comm', KCSUBTYPE_TYPE.KC_ST_CHAR, KCSubTypeElement.GetSizeForArray(32, 1), 88, 1)
3e170ce0 792),
39037602 793 'task_snapshot'
3e170ce0
A
794)
795
796KNOWN_TYPES_COLLECTION[0x906] = KCTypeDescription(0x906, (
39037602
A
797 KCSubTypeElement.FromBasicCtype('ths_thread_id', KCSUBTYPE_TYPE.KC_ST_UINT64, 0),
798 KCSubTypeElement.FromBasicCtype('ths_wait_event', KCSUBTYPE_TYPE.KC_ST_UINT64, 8),
799 KCSubTypeElement.FromBasicCtype('ths_continuation', KCSUBTYPE_TYPE.KC_ST_UINT64, 16),
800 KCSubTypeElement.FromBasicCtype('ths_total_syscalls', KCSUBTYPE_TYPE.KC_ST_UINT64, 24),
801 KCSubTypeElement.FromBasicCtype('ths_voucher_identifier', KCSUBTYPE_TYPE.KC_ST_UINT64, 32),
802 KCSubTypeElement.FromBasicCtype('ths_dqserialnum', KCSUBTYPE_TYPE.KC_ST_UINT64, 40),
803 KCSubTypeElement.FromBasicCtype('ths_user_time', KCSUBTYPE_TYPE.KC_ST_UINT64, 48),
804 KCSubTypeElement.FromBasicCtype('ths_sys_time', KCSUBTYPE_TYPE.KC_ST_UINT64, 56),
805 KCSubTypeElement.FromBasicCtype('ths_ss_flags', KCSUBTYPE_TYPE.KC_ST_UINT64, 64),
806 KCSubTypeElement.FromBasicCtype('ths_last_run_time', KCSUBTYPE_TYPE.KC_ST_UINT64, 72),
807 KCSubTypeElement.FromBasicCtype('ths_last_made_runnable_time', KCSUBTYPE_TYPE.KC_ST_UINT64, 80),
808 KCSubTypeElement.FromBasicCtype('ths_state', KCSUBTYPE_TYPE.KC_ST_UINT32, 88),
809 KCSubTypeElement.FromBasicCtype('ths_sched_flags', KCSUBTYPE_TYPE.KC_ST_UINT32, 92),
810 KCSubTypeElement.FromBasicCtype('ths_base_priority', KCSUBTYPE_TYPE.KC_ST_INT16, 96),
811 KCSubTypeElement.FromBasicCtype('ths_sched_priority', KCSUBTYPE_TYPE.KC_ST_INT16, 98),
812 KCSubTypeElement.FromBasicCtype('ths_eqos', KCSUBTYPE_TYPE.KC_ST_UINT8, 100),
813 KCSubTypeElement.FromBasicCtype('ths_rqos', KCSUBTYPE_TYPE.KC_ST_UINT8, 101),
814 KCSubTypeElement.FromBasicCtype('ths_rqos_override', KCSUBTYPE_TYPE.KC_ST_UINT8, 102),
815 KCSubTypeElement.FromBasicCtype('ths_io_tier', KCSUBTYPE_TYPE.KC_ST_UINT8, 103),
816 KCSubTypeElement.FromBasicCtype('ths_thread_t', KCSUBTYPE_TYPE.KC_ST_UINT64, 104),
5ba3f43e
A
817 KCSubTypeElement.FromBasicCtype('ths_requested_policy', KCSUBTYPE_TYPE.KC_ST_UINT64, 112),
818 KCSubTypeElement.FromBasicCtype('ths_effective_policy', KCSUBTYPE_TYPE.KC_ST_UINT64, 120),
39037602
A
819),
820 'thread_snapshot',
821 legacy_size = 0x68
822)
823
824KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_THREAD_DELTA_SNAPSHOT')] = KCTypeDescription(GetTypeForName('STACKSHOT_KCTYPE_THREAD_DELTA_SNAPSHOT'), (
825 KCSubTypeElement.FromBasicCtype('tds_thread_id', KCSUBTYPE_TYPE.KC_ST_UINT64, 0),
826 KCSubTypeElement.FromBasicCtype('tds_voucher_identifier', KCSUBTYPE_TYPE.KC_ST_UINT64, 8),
827 KCSubTypeElement.FromBasicCtype('tds_ss_flags', KCSUBTYPE_TYPE.KC_ST_UINT64, 16),
828 KCSubTypeElement.FromBasicCtype('tds_last_made_runnable_time', KCSUBTYPE_TYPE.KC_ST_UINT64, 24),
829 KCSubTypeElement.FromBasicCtype('tds_state', KCSUBTYPE_TYPE.KC_ST_UINT32, 32),
830 KCSubTypeElement.FromBasicCtype('tds_sched_flags', KCSUBTYPE_TYPE.KC_ST_UINT32, 36),
831 KCSubTypeElement.FromBasicCtype('tds_base_priority', KCSUBTYPE_TYPE.KC_ST_INT16, 40),
832 KCSubTypeElement.FromBasicCtype('tds_sched_priority', KCSUBTYPE_TYPE.KC_ST_INT16, 42),
833 KCSubTypeElement.FromBasicCtype('tds_eqos', KCSUBTYPE_TYPE.KC_ST_UINT8, 44),
834 KCSubTypeElement.FromBasicCtype('tds_rqos', KCSUBTYPE_TYPE.KC_ST_UINT8, 45),
835 KCSubTypeElement.FromBasicCtype('tds_rqos_override', KCSUBTYPE_TYPE.KC_ST_UINT8, 46),
836 KCSubTypeElement.FromBasicCtype('tds_io_tier', KCSUBTYPE_TYPE.KC_ST_UINT8, 47),
a39ff7e2
A
837 KCSubTypeElement.FromBasicCtype('tds_requested_policy', KCSUBTYPE_TYPE.KC_ST_UINT64, 48),
838 KCSubTypeElement.FromBasicCtype('tds_effective_policy', KCSUBTYPE_TYPE.KC_ST_UINT64, 56),
39037602 839),
a39ff7e2
A
840 'thread_delta_snapshot',
841 legacy_size = 48
39037602
A
842)
843
844KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_TASK_DELTA_SNAPSHOT')] = KCTypeDescription(GetTypeForName('STACKSHOT_KCTYPE_TASK_DELTA_SNAPSHOT'), (
845 KCSubTypeElement.FromBasicCtype('tds_unique_pid', KCSUBTYPE_TYPE.KC_ST_UINT64, 0),
846 KCSubTypeElement.FromBasicCtype('tds_ss_flags', KCSUBTYPE_TYPE.KC_ST_UINT64, 8),
847 KCSubTypeElement.FromBasicCtype('tds_user_time_in_terminated_thr', KCSUBTYPE_TYPE.KC_ST_UINT64, 16),
848 KCSubTypeElement.FromBasicCtype('tds_system_time_in_terminated_t', KCSUBTYPE_TYPE.KC_ST_UINT64, 24),
849 KCSubTypeElement.FromBasicCtype('tds_task_size', KCSUBTYPE_TYPE.KC_ST_UINT64, 32),
850 KCSubTypeElement.FromBasicCtype('tds_max_resident_size', KCSUBTYPE_TYPE.KC_ST_UINT64, 40),
851 KCSubTypeElement.FromBasicCtype('tds_suspend_count', KCSUBTYPE_TYPE.KC_ST_UINT32, 48),
852 KCSubTypeElement.FromBasicCtype('tds_faults', KCSUBTYPE_TYPE.KC_ST_UINT32, 52),
853 KCSubTypeElement.FromBasicCtype('tds_pageins', KCSUBTYPE_TYPE.KC_ST_UINT32, 56),
854 KCSubTypeElement.FromBasicCtype('tds_cow_faults', KCSUBTYPE_TYPE.KC_ST_UINT32, 60),
855 KCSubTypeElement.FromBasicCtype('tds_was_throttled', KCSUBTYPE_TYPE.KC_ST_UINT32, 64),
856 KCSubTypeElement.FromBasicCtype('tds_did_throttle', KCSUBTYPE_TYPE.KC_ST_UINT32, 68),
857 KCSubTypeElement.FromBasicCtype('tds_latency_qos', KCSUBTYPE_TYPE.KC_ST_UINT32, 72),
3e170ce0 858),
39037602 859 'task_delta_snapshot'
3e170ce0
A
860)
861
39037602 862
3e170ce0
A
863KNOWN_TYPES_COLLECTION[0x909] = KCSubTypeElement('pth_name', KCSUBTYPE_TYPE.KC_ST_CHAR, KCSubTypeElement.GetSizeForArray(64, 1), 0, 1)
864
d9a64523
A
865KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_SYS_SHAREDCACHE_LAYOUT')] = KCTypeDescription(GetTypeForName('STACKSHOT_KCTYPE_SYS_SHAREDCACHE_LAYOUT'), (
866 KCSubTypeElement('imageLoadAddress', KCSUBTYPE_TYPE.KC_ST_UINT64, 8, 0, 0),
867 KCSubTypeElement('imageUUID', KCSUBTYPE_TYPE.KC_ST_UINT8, KCSubTypeElement.GetSizeForArray(16, 1), 8, 1)
868),
869 'system_shared_cache_layout'
870)
3e170ce0
A
871
872KNOWN_TYPES_COLLECTION[GetTypeForName('KCDATA_TYPE_LIBRARY_LOADINFO64')] = KCTypeDescription(GetTypeForName('KCDATA_TYPE_LIBRARY_LOADINFO64'), (
39037602
A
873 KCSubTypeElement('imageLoadAddress', KCSUBTYPE_TYPE.KC_ST_UINT64, 8, 0, 0),
874 KCSubTypeElement('imageUUID', KCSUBTYPE_TYPE.KC_ST_UINT8, KCSubTypeElement.GetSizeForArray(16, 1), 8, 1)
3e170ce0 875),
a39ff7e2
A
876 'dyld_load_info',
877 legacy_size = 24
3e170ce0
A
878)
879
880KNOWN_TYPES_COLLECTION[GetTypeForName('KCDATA_TYPE_LIBRARY_LOADINFO')] = KCTypeDescription(GetTypeForName('KCDATA_TYPE_LIBRARY_LOADINFO'), (
39037602
A
881 KCSubTypeElement('imageLoadAddress', KCSUBTYPE_TYPE.KC_ST_UINT32, 4, 0, 0),
882 KCSubTypeElement('imageUUID', KCSUBTYPE_TYPE.KC_ST_UINT8, KCSubTypeElement.GetSizeForArray(16, 1), 4, 1)
3e170ce0 883),
a39ff7e2
A
884 'dyld_load_info',
885 legacy_size = 20
3e170ce0
A
886)
887
39037602
A
888KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_SHAREDCACHE_LOADINFO')] = KCTypeDescription(GetTypeForName('STACKSHOT_KCTYPE_SHAREDCACHE_LOADINFO'), (
889 KCSubTypeElement('imageLoadAddress', KCSUBTYPE_TYPE.KC_ST_UINT64, 8, 0, 0),
890 KCSubTypeElement('imageUUID', KCSUBTYPE_TYPE.KC_ST_UINT8, KCSubTypeElement.GetSizeForArray(16, 1), 8, 1),
891 KCSubTypeElement('imageSlidBaseAddress', KCSUBTYPE_TYPE.KC_ST_UINT64, 8, 24, 0),
892),
893 'shared_cache_dyld_load_info',
894 legacy_size = 0x18
895)
896
897KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_KERNELCACHE_LOADINFO')] = KCTypeDescription(GetTypeForName('STACKSHOT_KCTYPE_KERNELCACHE_LOADINFO'), (
898 KCSubTypeElement('imageLoadAddress', KCSUBTYPE_TYPE.KC_ST_UINT64, 8, 0, 0),
899 KCSubTypeElement('imageUUID', KCSUBTYPE_TYPE.KC_ST_UINT8, KCSubTypeElement.GetSizeForArray(16, 1), 8, 1),
900),
901 'kernelcache_load_info'
902)
3e170ce0
A
903
904KNOWN_TYPES_COLLECTION[0x33] = KCSubTypeElement('mach_absolute_time', KCSUBTYPE_TYPE.KC_ST_UINT64, 8, 0, 0, KCSubTypeElement._get_naked_element_value)
a39ff7e2 905KNOWN_TYPES_COLLECTION[0x907] = KCSubTypeElement.FromBasicCtype('donating_pids', KCSUBTYPE_TYPE.KC_ST_INT32, legacy_size=4)
3e170ce0
A
906
907KNOWN_TYPES_COLLECTION[GetTypeForName('KCDATA_TYPE_USECS_SINCE_EPOCH')] = KCSubTypeElement('usecs_since_epoch', KCSUBTYPE_TYPE.KC_ST_UINT64, 8, 0, 0, KCSubTypeElement._get_naked_element_value)
908
909KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_KERN_STACKFRAME')] = KCTypeDescription(GetTypeForName('STACKSHOT_KCTYPE_KERN_STACKFRAME'), (
910 KCSubTypeElement.FromBasicCtype('lr', KCSUBTYPE_TYPE.KC_ST_UINT32),
911 KCSubTypeElement.FromBasicCtype('sp', KCSUBTYPE_TYPE.KC_ST_UINT32, 4)
912),
a39ff7e2
A
913 'kernel_stack_frames',
914 legacy_size = 8
3e170ce0
A
915)
916
39037602
A
917KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_KERN_STACKLR')] = KCTypeDescription(GetTypeForName('STACKSHOT_KCTYPE_KERN_STACKLR'), (
918 KCSubTypeElement.FromBasicCtype('lr', KCSUBTYPE_TYPE.KC_ST_UINT32),
919),
920 'kernel_stack_frames'
921)
922
923
3e170ce0
A
924KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_USER_STACKFRAME')] = KCTypeDescription.FromKCTypeDescription(
925 KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_KERN_STACKFRAME')],
926 GetTypeForName('STACKSHOT_KCTYPE_USER_STACKFRAME'),
927 'user_stack_frames'
928)
929
39037602
A
930KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_USER_STACKLR')] = KCTypeDescription.FromKCTypeDescription(
931 KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_KERN_STACKLR')],
932 GetTypeForName('STACKSHOT_KCTYPE_USER_STACKLR'),
933 'user_stack_frames'
934)
935
3e170ce0
A
936KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_KERN_STACKFRAME64')] = KCTypeDescription(GetTypeForName('STACKSHOT_KCTYPE_KERN_STACKFRAME64'), (
937 KCSubTypeElement.FromBasicCtype('lr', KCSUBTYPE_TYPE.KC_ST_UINT64),
938 KCSubTypeElement.FromBasicCtype('sp', KCSUBTYPE_TYPE.KC_ST_UINT64, 8)
939),
a39ff7e2
A
940 'kernel_stack_frames',
941 legacy_size = 16
3e170ce0
A
942)
943
944KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_USER_STACKFRAME64')] = KCTypeDescription.FromKCTypeDescription(
945 KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_KERN_STACKFRAME64')],
946 GetTypeForName('STACKSHOT_KCTYPE_USER_STACKFRAME64'),
947 'user_stack_frames'
948)
949
39037602
A
950
951KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_KERN_STACKLR64')] = KCTypeDescription(GetTypeForName('STACKSHOT_KCTYPE_KERN_STACKLR64'), (
952 KCSubTypeElement.FromBasicCtype('lr', KCSUBTYPE_TYPE.KC_ST_UINT64),
953),
954 'kernel_stack_frames'
955)
956
957KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_USER_STACKLR64')] = KCTypeDescription.FromKCTypeDescription(
958 KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_KERN_STACKLR64')],
959 GetTypeForName('STACKSHOT_KCTYPE_USER_STACKLR64'),
960 'user_stack_frames'
961)
962
963
964KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_NONRUNNABLE_TIDS')] = KCSubTypeElement.FromBasicCtype('nonrunnable_threads', KCSUBTYPE_TYPE.KC_ST_INT64)
965
966KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_NONRUNNABLE_TASKS')] = KCSubTypeElement.FromBasicCtype('nonrunnable_tasks', KCSUBTYPE_TYPE.KC_ST_INT64)
967
3e170ce0
A
968KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_OSVERSION')] = KCSubTypeElement('osversion', KCSUBTYPE_TYPE.KC_ST_CHAR,
969 KCSubTypeElement.GetSizeForArray(256, 1), 0, 1)
970
39037602 971KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_BOOTARGS')] = KCSubTypeElement('boot_args', KCSUBTYPE_TYPE.KC_ST_CHAR,
3e170ce0
A
972 KCSubTypeElement.GetSizeForArray(256, 1), 0, 1)
973
974KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_KERN_PAGE_SIZE')] = KCSubTypeElement('kernel_page_size', KCSUBTYPE_TYPE.KC_ST_UINT32, 4, 0, 0, KCSubTypeElement._get_naked_element_value)
975
5ba3f43e
A
976KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_THREAD_POLICY_VERSION')] = KCSubTypeElement('thread_policy_version', KCSUBTYPE_TYPE.KC_ST_UINT32, 4, 0, 0, KCSubTypeElement._get_naked_element_value)
977
3e170ce0
A
978KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_JETSAM_LEVEL')] = KCSubTypeElement('jetsam_level', KCSUBTYPE_TYPE.KC_ST_UINT32, 4, 0, 0, KCSubTypeElement._get_naked_element_value)
979
39037602
A
980KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_DELTA_SINCE_TIMESTAMP')] = KCSubTypeElement("stackshot_delta_since_timestamp", KCSUBTYPE_TYPE.KC_ST_UINT64, 8, 0, 0, KCSubTypeElement._get_naked_element_value)
981
982KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_STACKSHOT_FAULT_STATS')] = KCTypeDescription(GetTypeForName('STACKSHOT_KCTYPE_STACKSHOT_FAULT_STATS'),
983 (
984 KCSubTypeElement.FromBasicCtype('sfs_pages_faulted_in', KCSUBTYPE_TYPE.KC_ST_UINT32, 0),
985 KCSubTypeElement.FromBasicCtype('sfs_time_spent_faulting', KCSUBTYPE_TYPE.KC_ST_UINT64, 4),
986 KCSubTypeElement.FromBasicCtype('sfs_system_max_fault_time', KCSUBTYPE_TYPE.KC_ST_UINT64, 12),
987 KCSubTypeElement.FromBasicCtype('sfs_stopped_faulting', KCSUBTYPE_TYPE.KC_ST_UINT8, 20)
988 ),
989 'stackshot_fault_stats')
3e170ce0 990
813fb2f6
A
991KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_THREAD_WAITINFO')] = KCTypeDescription(GetTypeForName('STACKSHOT_KCTYPE_THREAD_WAITINFO'),
992 (
993 KCSubTypeElement.FromBasicCtype('owner', KCSUBTYPE_TYPE.KC_ST_UINT64, 0),
994 KCSubTypeElement.FromBasicCtype('waiter', KCSUBTYPE_TYPE.KC_ST_UINT64, 8),
995 KCSubTypeElement.FromBasicCtype('context', KCSUBTYPE_TYPE.KC_ST_UINT64, 16),
996 KCSubTypeElement.FromBasicCtype('wait_type', KCSUBTYPE_TYPE.KC_ST_UINT8, 24)
997 ),
998 'thread_waitinfo')
999
5ba3f43e
A
1000KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_THREAD_GROUP_SNAPSHOT')] = KCTypeDescription(GetTypeForName('STACKSHOT_KCTYPE_THREAD_GROUP'),
1001 (
1002 KCSubTypeElement.FromBasicCtype('tgs_id', KCSUBTYPE_TYPE.KC_ST_UINT64, 0),
5c9f4661
A
1003 KCSubTypeElement('tgs_name', KCSUBTYPE_TYPE.KC_ST_CHAR, KCSubTypeElement.GetSizeForArray(16, 1),
1004 8, 1),
1005 KCSubTypeElement.FromBasicCtype('tgs_flags', KCSUBTYPE_TYPE.KC_ST_UINT64, 24),
5ba3f43e
A
1006 ),
1007 'thread_group_snapshot')
1008
1009
1010KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_THREAD_GROUP')] = KCSubTypeElement('thread_group', KCSUBTYPE_TYPE.KC_ST_UINT64, 8, 0, 0, KCSubTypeElement._get_naked_element_value)
1011
1012KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_JETSAM_COALITION_SNAPSHOT')] = KCTypeDescription(GetTypeForName('STACKSHOT_KCTYPE_JETSAM_COALITION_SNAPSHOT'),
1013 (
1014 KCSubTypeElement.FromBasicCtype('jcs_id', KCSUBTYPE_TYPE.KC_ST_UINT64, 0),
1015 KCSubTypeElement.FromBasicCtype('jcs_flags', KCSUBTYPE_TYPE.KC_ST_UINT64, 8),
1016 KCSubTypeElement.FromBasicCtype('jcs_thread_group', KCSUBTYPE_TYPE.KC_ST_UINT64, 16),
1017 KCSubTypeElement.FromBasicCtype('jcs_leader_task_uniqueid', KCSUBTYPE_TYPE.KC_ST_UINT64, 24)
1018 ),
1019 'jetsam_coalition_snapshot')
1020
1021KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_JETSAM_COALITION')] = KCSubTypeElement('jetsam_coalition', KCSUBTYPE_TYPE.KC_ST_UINT64, 8, 0, 0, KCSubTypeElement._get_naked_element_value)
1022
1023KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_INSTRS_CYCLES')] = KCTypeDescription(GetTypeForName('STACKSHOT_KCTYPE_INSTRS_CYCLES'),
1024 (
1025 KCSubTypeElement.FromBasicCtype('ics_instructions', KCSUBTYPE_TYPE.KC_ST_UINT64, 0),
1026 KCSubTypeElement.FromBasicCtype('ics_cycles', KCSUBTYPE_TYPE.KC_ST_UINT64, 8)
1027 ),
1028 'instrs_cycles_snapshot')
1029
d9a64523
A
1030def set_type(name, *args):
1031 typ = GetTypeForName(name)
1032 KNOWN_TYPES_COLLECTION[typ] = KCTypeDescription(GetTypeForName(typ), *args)
1033
1034
1035set_type('STACKSHOT_KCTYPE_USER_STACKTOP',
1036 (
1037 KCSubTypeElement.FromBasicCtype('sp', KCSUBTYPE_TYPE.KC_ST_UINT64, 0),
1038 KCSubTypeElement('stack_contents', KCSUBTYPE_TYPE.KC_ST_UINT8, KCSubTypeElement.GetSizeForArray(8, 1), 8, 1),
1039 ),
1040 'user_stacktop')
1041
3e170ce0
A
1042#KNOWN_TYPES_COLLECTION[0x907] = KCSubTypeElement('donating_pids', KCSUBTYPE_TYPE.KC_ST_UINT32, 4, 0, 0, KCSubTypeElement._get_naked_element_value)
1043KNOWN_TYPES_COLLECTION[GetTypeForName('TASK_CRASHINFO_PID')] = KCSubTypeElement('pid', KCSUBTYPE_TYPE.KC_ST_INT32, 4, 0, 0)
1044KNOWN_TYPES_COLLECTION[GetTypeForName('TASK_CRASHINFO_PPID')] = KCSubTypeElement('ppid', KCSUBTYPE_TYPE.KC_ST_INT32, 4, 0, 0)
1045KNOWN_TYPES_COLLECTION[GetTypeForName('TASK_CRASHINFO_PROC_NAME')] = KCSubTypeElement('p_comm', KCSUBTYPE_TYPE.KC_ST_CHAR,
1046 KCSubTypeElement.GetSizeForArray(32, 1), 0, 1)
1047KNOWN_TYPES_COLLECTION[GetTypeForName('TASK_CRASHINFO_USERSTACK')] = KCSubTypeElement('userstack_ptr', KCSUBTYPE_TYPE.KC_ST_UINT64, 8, 0, 0)
1048KNOWN_TYPES_COLLECTION[GetTypeForName('TASK_CRASHINFO_ARGSLEN')] = KCSubTypeElement('p_argslen', KCSUBTYPE_TYPE.KC_ST_INT32, 4, 0, 0)
1049
1050KNOWN_TYPES_COLLECTION[GetTypeForName('TASK_CRASHINFO_PROC_PATH')] = KCSubTypeElement('p_path', KCSUBTYPE_TYPE.KC_ST_CHAR,
1051 KCSubTypeElement.GetSizeForArray(1024, 1), 0, 1)
1052KNOWN_TYPES_COLLECTION[GetTypeForName('TASK_CRASHINFO_PROC_CSFLAGS')] = KCSubTypeElement('p_csflags', KCSUBTYPE_TYPE.KC_ST_INT32, 4, 0, 0)
1053KNOWN_TYPES_COLLECTION[GetTypeForName('TASK_CRASHINFO_UID')] = KCSubTypeElement('uid', KCSUBTYPE_TYPE.KC_ST_INT32, 4, 0, 0)
1054KNOWN_TYPES_COLLECTION[GetTypeForName('TASK_CRASHINFO_GID')] = KCSubTypeElement('gid', KCSUBTYPE_TYPE.KC_ST_INT32, 4, 0, 0)
1055KNOWN_TYPES_COLLECTION[GetTypeForName('TASK_CRASHINFO_PROC_ARGC')] = KCSubTypeElement('argc', KCSUBTYPE_TYPE.KC_ST_INT32, 4, 0, 0)
1056KNOWN_TYPES_COLLECTION[GetTypeForName('TASK_CRASHINFO_PROC_FLAGS')] = KCSubTypeElement('p_flags', KCSUBTYPE_TYPE.KC_ST_INT32, 4, 0, 0)
1057KNOWN_TYPES_COLLECTION[GetTypeForName('TASK_CRASHINFO_CPUTYPE')] = KCSubTypeElement('cputype', KCSUBTYPE_TYPE.KC_ST_INT32, 4, 0, 0)
1058KNOWN_TYPES_COLLECTION[GetTypeForName('TASK_CRASHINFO_RESPONSIBLE_PID')] = KCSubTypeElement('responsible_pid', KCSUBTYPE_TYPE.KC_ST_INT32, 4, 0, 0)
1059KNOWN_TYPES_COLLECTION[GetTypeForName('TASK_CRASHINFO_DIRTY_FLAGS')] = KCSubTypeElement('dirty_flags', KCSUBTYPE_TYPE.KC_ST_INT32, 4, 0, 0)
1060KNOWN_TYPES_COLLECTION[GetTypeForName('TASK_CRASHINFO_CRASHED_THREADID')] = KCSubTypeElement('crashed_threadid', KCSUBTYPE_TYPE.KC_ST_UINT64, 8, 0, 0)
39037602 1061KNOWN_TYPES_COLLECTION[GetTypeForName('TASK_CRASHINFO_COALITION_ID')] = KCSubTypeElement('coalition_id', KCSUBTYPE_TYPE.KC_ST_UINT64, 8, 0, 0)
3e170ce0
A
1062
1063KNOWN_TYPES_COLLECTION[GetTypeForName('TASK_CRASHINFO_PROC_STATUS')] = KCSubTypeElement('p_status', KCSUBTYPE_TYPE.KC_ST_UINT8, 1, 0, 0)
1064
1065KNOWN_TYPES_COLLECTION[GetTypeForName('TASK_CRASHINFO_BSDINFOWITHUNIQID')] = KCTypeDescription(GetTypeForName('TASK_CRASHINFO_BSDINFOWITHUNIQID'),
1066 ( KCSubTypeElement('p_uuid', KCSUBTYPE_TYPE.KC_ST_UINT8, KCSubTypeElement.GetSizeForArray(16, 1), 0, 1),
1067 KCSubTypeElement.FromBasicCtype('p_uniqueid', KCSUBTYPE_TYPE.KC_ST_UINT64, 16),
1068 KCSubTypeElement.FromBasicCtype('p_puniqueid', KCSUBTYPE_TYPE.KC_ST_UINT64, 24)
1069 ),
1070 'proc_uniqidentifierinfo')
1071
39037602
A
1072KNOWN_TYPES_COLLECTION[GetTypeForName('TASK_CRASHINFO_EXCEPTION_CODES')] = (
1073 KCTypeDescription(GetTypeForName('TASK_CRASHINFO_EXCEPTION_CODES'),
1074 (KCSubTypeElement.FromBasicCtype('code_0', KCSUBTYPE_TYPE.KC_ST_UINT64, 0),
1075 KCSubTypeElement.FromBasicCtype('code_1', KCSUBTYPE_TYPE.KC_ST_UINT64, 8)),
1076 'mach_exception_data_t'))
1077
1078
1079KNOWN_TYPES_COLLECTION[GetTypeForName('TASK_CRASHINFO_PROC_STARTTIME')] = (
1080 KCTypeDescription(GetTypeForName('TASK_CRASHINFO_PROC_STARTTIME'),
1081 (KCSubTypeElement.FromBasicCtype('tv_sec', KCSUBTYPE_TYPE.KC_ST_UINT64, 0),
1082 KCSubTypeElement.FromBasicCtype('tv_usec', KCSUBTYPE_TYPE.KC_ST_UINT64, 8)),
1083 'proc_starttime'))
1084
3e170ce0
A
1085
1086KNOWN_TYPES_COLLECTION[GetTypeForName('TASK_CRASHINFO_RUSAGE_INFO')] = KCTypeDescription(GetTypeForName('TASK_CRASHINFO_RUSAGE_INFO'),
1087 (
1088 KCSubTypeElement('ri_uuid', KCSUBTYPE_TYPE.KC_ST_UINT8, KCSubTypeElement.GetSizeForArray(16, 1), 0, 1),
1089 KCSubTypeElement.FromBasicCtype('ri_user_time', KCSUBTYPE_TYPE.KC_ST_UINT64, 16),
1090 KCSubTypeElement.FromBasicCtype('ri_system_time', KCSUBTYPE_TYPE.KC_ST_UINT64, 24),
1091 KCSubTypeElement.FromBasicCtype('ri_pkg_idle_wkups', KCSUBTYPE_TYPE.KC_ST_UINT64, 32),
1092 KCSubTypeElement.FromBasicCtype('ri_interrupt_wkups', KCSUBTYPE_TYPE.KC_ST_UINT64, 40),
1093 KCSubTypeElement.FromBasicCtype('ri_pageins', KCSUBTYPE_TYPE.KC_ST_UINT64, 48),
1094 KCSubTypeElement.FromBasicCtype('ri_wired_size', KCSUBTYPE_TYPE.KC_ST_UINT64, 56),
1095 KCSubTypeElement.FromBasicCtype('ri_resident_size', KCSUBTYPE_TYPE.KC_ST_UINT64, 64),
1096 KCSubTypeElement.FromBasicCtype('ri_phys_footprint', KCSUBTYPE_TYPE.KC_ST_UINT64, 72),
1097 KCSubTypeElement.FromBasicCtype('ri_proc_start_abstime', KCSUBTYPE_TYPE.KC_ST_UINT64, 80),
1098 KCSubTypeElement.FromBasicCtype('ri_proc_exit_abstime', KCSUBTYPE_TYPE.KC_ST_UINT64, 88),
1099 KCSubTypeElement.FromBasicCtype('ri_child_user_time', KCSUBTYPE_TYPE.KC_ST_UINT64, 96),
1100 KCSubTypeElement.FromBasicCtype('ri_child_system_time', KCSUBTYPE_TYPE.KC_ST_UINT64, 104),
1101 KCSubTypeElement.FromBasicCtype('ri_child_pkg_idle_wkups', KCSUBTYPE_TYPE.KC_ST_UINT64, 112),
1102 KCSubTypeElement.FromBasicCtype('ri_child_interrupt_wkups', KCSUBTYPE_TYPE.KC_ST_UINT64, 120),
1103 KCSubTypeElement.FromBasicCtype('ri_child_pageins', KCSUBTYPE_TYPE.KC_ST_UINT64, 128),
1104 KCSubTypeElement.FromBasicCtype('ri_child_elapsed_abstime', KCSUBTYPE_TYPE.KC_ST_UINT64, 136),
1105 KCSubTypeElement.FromBasicCtype('ri_diskio_bytesread', KCSUBTYPE_TYPE.KC_ST_UINT64, 144),
1106 KCSubTypeElement.FromBasicCtype('ri_diskio_byteswritten', KCSUBTYPE_TYPE.KC_ST_UINT64, 152),
1107 KCSubTypeElement.FromBasicCtype('ri_cpu_time_qos_default', KCSUBTYPE_TYPE.KC_ST_UINT64, 160),
1108 KCSubTypeElement.FromBasicCtype('ri_cpu_time_qos_maintenance', KCSUBTYPE_TYPE.KC_ST_UINT64, 168),
1109 KCSubTypeElement.FromBasicCtype('ri_cpu_time_qos_background', KCSUBTYPE_TYPE.KC_ST_UINT64, 176),
1110 KCSubTypeElement.FromBasicCtype('ri_cpu_time_qos_utility', KCSUBTYPE_TYPE.KC_ST_UINT64, 184),
1111 KCSubTypeElement.FromBasicCtype('ri_cpu_time_qos_legacy', KCSUBTYPE_TYPE.KC_ST_UINT64, 192),
1112 KCSubTypeElement.FromBasicCtype('ri_cpu_time_qos_user_initiated', KCSUBTYPE_TYPE.KC_ST_UINT64, 200),
39037602 1113 KCSubTypeElement.FromBasicCtype('ri_cpu_time_qos_user_interactiv', KCSUBTYPE_TYPE.KC_ST_UINT64, 208),
3e170ce0
A
1114 KCSubTypeElement.FromBasicCtype('ri_billed_system_time', KCSUBTYPE_TYPE.KC_ST_UINT64, 216),
1115 KCSubTypeElement.FromBasicCtype('ri_serviced_system_time', KCSUBTYPE_TYPE.KC_ST_UINT64, 224)
1116 ),
39037602
A
1117 'rusage_info')
1118
1119KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_CPU_TIMES')] = KCTypeDescription(GetTypeForName('STACKSHOT_KCTYPE_CPU_TIMES'),
1120 (
1121 KCSubTypeElement.FromBasicCtype('user_usec', KCSUBTYPE_TYPE.KC_ST_UINT64, 0),
1122 KCSubTypeElement.FromBasicCtype('system_usec', KCSUBTYPE_TYPE.KC_ST_UINT64, 8),
d9a64523 1123 KCSubTypeElement.FromBasicCtype('runnable_usec', KCSUBTYPE_TYPE.KC_ST_UINT64, 16),
39037602
A
1124 ), 'cpu_times')
1125
1126KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_STACKSHOT_DURATION')] = KCTypeDescription(GetTypeForName('STACKSHOT_KCTYPE_STACKSHOT_DURATION'),
1127 (
1128 KCSubTypeElement.FromBasicCtype('stackshot_duration', KCSUBTYPE_TYPE.KC_ST_UINT64, 0),
1129 KCSubTypeElement.FromBasicCtype('stackshot_duration_outer', KCSUBTYPE_TYPE.KC_ST_UINT64, 8),
1130 ), 'stackshot_duration', merge=True
1131)
1132
1133KNOWN_TYPES_COLLECTION[GetTypeForName('KCDATA_TYPE_PROCNAME')] = (
1134 KCSubTypeElement("proc_name", KCSUBTYPE_TYPE.KC_ST_CHAR, KCSubTypeElement.GetSizeForArray(-1, 1), 0, 1))
1135
1136KNOWN_TYPES_COLLECTION[GetTypeForName('KCDATA_TYPE_PID')] = (
1137 KCSubTypeElement('pid', KCSUBTYPE_TYPE.KC_ST_INT32, 4, 0, 0))
1138
1139KNOWN_TYPES_COLLECTION[GetTypeForName('EXIT_REASON_SNAPSHOT')] = KCTypeDescription(GetTypeForName('EXIT_REASON_SNAPSHOT'),
1140 (
1141 KCSubTypeElement.FromBasicCtype('ers_namespace', KCSUBTYPE_TYPE.KC_ST_UINT32, 0),
1142 KCSubTypeElement.FromBasicCtype('ers_code', KCSUBTYPE_TYPE.KC_ST_UINT64, 4),
1143 KCSubTypeElement.FromBasicCtype('ers_flags', KCSUBTYPE_TYPE.KC_ST_UINT64, 12),
1144 ), 'exit_reason_basic_info')
1145
1146KNOWN_TYPES_COLLECTION[GetTypeForName('EXIT_REASON_USER_DESC')] = (
1147 KCSubTypeElement("exit_reason_user_description", KCSUBTYPE_TYPE.KC_ST_CHAR, KCSubTypeElement.GetSizeForArray(-1, 1), 0, 1))
1148
1149KNOWN_TYPES_COLLECTION[GetTypeForName('EXIT_REASON_USER_PAYLOAD')] = KCSubTypeElement('exit_reason_user_payload',
1150 KCSUBTYPE_TYPE.KC_ST_UINT8, KCSubTypeElement.GetSizeForArray(-1, 1), 0, 1)
1151
1152KNOWN_TYPES_COLLECTION[GetTypeForName('EXIT_REASON_CODESIGNING_INFO')] = KCTypeDescription(GetTypeForName('EXIT_REASON_CODESIGNING_INFO'),
1153 (
1154 KCSubTypeElement.FromBasicCtype('ceri_virt_addr', KCSUBTYPE_TYPE.KC_ST_UINT64, 0),
1155 KCSubTypeElement.FromBasicCtype('ceri_file_offset', KCSUBTYPE_TYPE.KC_ST_UINT64, 8),
1156 KCSubTypeElement("ceri_pathname", KCSUBTYPE_TYPE.KC_ST_CHAR, KCSubTypeElement.GetSizeForArray(1024, 1), 16, 1),
1157 KCSubTypeElement("ceri_filename", KCSUBTYPE_TYPE.KC_ST_CHAR, KCSubTypeElement.GetSizeForArray(1024, 1), 1040, 1),
1158 KCSubTypeElement.FromBasicCtype('ceri_codesig_modtime_secs', KCSUBTYPE_TYPE.KC_ST_UINT64, 2064),
1159 KCSubTypeElement.FromBasicCtype('ceri_codesig_modtime_nsecs', KCSUBTYPE_TYPE.KC_ST_UINT64, 2072),
1160 KCSubTypeElement.FromBasicCtype('ceri_page_modtime_secs', KCSUBTYPE_TYPE.KC_ST_UINT64, 2080),
1161 KCSubTypeElement.FromBasicCtype('ceri_page_modtime_nsecs', KCSUBTYPE_TYPE.KC_ST_UINT64, 2088),
1162 KCSubTypeElement.FromBasicCtype('ceri_path_truncated', KCSUBTYPE_TYPE.KC_ST_UINT8, 2096),
1163 KCSubTypeElement.FromBasicCtype('ceri_object_codesigned', KCSUBTYPE_TYPE.KC_ST_UINT8, 2097),
1164 KCSubTypeElement.FromBasicCtype('ceri_page_codesig_validated', KCSUBTYPE_TYPE.KC_ST_UINT8, 2098),
1165 KCSubTypeElement.FromBasicCtype('ceri_page_codesig_tainted', KCSUBTYPE_TYPE.KC_ST_UINT8, 2099),
1166 KCSubTypeElement.FromBasicCtype('ceri_page_codesig_nx', KCSUBTYPE_TYPE.KC_ST_UINT8, 2100),
1167 KCSubTypeElement.FromBasicCtype('ceri_page_wpmapped', KCSUBTYPE_TYPE.KC_ST_UINT8, 2101),
1168 KCSubTypeElement.FromBasicCtype('ceri_page_slid', KCSUBTYPE_TYPE.KC_ST_UINT8, 2102),
1169 KCSubTypeElement.FromBasicCtype('ceri_page_dirty', KCSUBTYPE_TYPE.KC_ST_UINT8, 2103),
1170 KCSubTypeElement.FromBasicCtype('ceri_page_shadow_depth', KCSUBTYPE_TYPE.KC_ST_UINT32, 2104),
1171 ), 'exit_reason_codesigning_info')
1172
5ba3f43e
A
1173KNOWN_TYPES_COLLECTION[GetTypeForName('EXIT_REASON_WORKLOOP_ID')] = (
1174 KCSubTypeElement('exit_reason_workloop_id', KCSUBTYPE_TYPE.KC_ST_UINT64, 8, 0, 0, KCSubTypeElement._get_naked_element_value))
1175
1176KNOWN_TYPES_COLLECTION[GetTypeForName('EXIT_REASON_DISPATCH_QUEUE_NO')] = (
1177 KCSubTypeElement('exit_reason_dispatch_queue_no', KCSUBTYPE_TYPE.KC_ST_UINT64, 8, 0, 0, KCSubTypeElement._get_naked_element_value))
3e170ce0 1178
d9a64523
A
1179KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_ASID')] = (
1180 KCSubTypeElement('ts_asid', KCSUBTYPE_TYPE.KC_ST_UINT32, 4, 0, 0))
1181
1182KNOWN_TYPES_COLLECTION[GetTypeForName('STACKSHOT_KCTYPE_PAGE_TABLES')] = KCTypeDescription(GetTypeForName('STACKSHOT_KCTYPE_PAGE_TABLES'), (
1183 KCSubTypeElement(None, KCSUBTYPE_TYPE.KC_ST_UINT64, 8, 0, 0, KCSubTypeElement._get_naked_element_value), ),
1184 'ts_pagetable',
1185 merge=True,
1186 naked=True
1187)
1188
3e170ce0 1189def GetSecondsFromMATime(mat, tb):
39037602 1190 return (float(mat) * tb['numer']) / tb['denom']
3e170ce0
A
1191
1192def FindLibraryForAddress(liblist, address):
1193 current_lib = None
1194 for l in liblist:
1195 if address >= l[1]:
1196 current_lib = l
1197 return current_lib
1198
1199def FindIndexOfLibInCatalog(catalog, lib):
1200 index = None
1201 i = 0
1202 for l in catalog:
1203 if l[0] == lib[0] and l[1] == lib[1]:
1204 index = i
1205 break
1206 i += 1
1207
1208 if index is None:
1209 catalog.append(lib)
1210 index = len(catalog) - 1
1211
1212 return index
1213
1214def GetOffsetOfAddressForLib(lib, address):
1215 return (address - lib[1])
1216
1217def GetSymbolInfoForFrame(catalog, liblist, address):
1218 lib = FindLibraryForAddress(liblist, address)
1219 if not lib:
1220 lib = ["00000000000000000000000000000000",0,"A"]
1221 offset = GetOffsetOfAddressForLib(lib, address)
1222 index = FindIndexOfLibInCatalog(catalog, lib)
1223 return [index, offset]
1224
1225def GetStateDescription(s):
1226 retval = []
1227 TH_WAIT = 0x01
1228 TH_SUSP = 0x02
1229 TH_RUN = 0x04
1230 TH_UNINT = 0x08
1231 TH_TERMINATE = 0x10
1232 TH_TERMINATE2 = 0x20
d9a64523 1233 TH_WAIT_REPORT = 0x40
3e170ce0
A
1234 TH_IDLE = 0x80
1235 if (s & TH_WAIT):
1236 retval.append("TH_WAIT")
1237 if (s & TH_SUSP):
1238 retval.append("TH_SUSP")
1239 if (s & TH_RUN):
1240 retval.append("TH_RUN")
1241 if (s & TH_UNINT):
1242 retval.append("TH_UNINT")
1243 if (s & TH_TERMINATE):
1244 retval.append("TH_TERMINATE")
1245 if (s & TH_TERMINATE2):
1246 retval.append("TH_TERMINATE2")
d9a64523
A
1247 if (s & TH_WAIT_REPORT):
1248 retval.append("TH_WAIT_REPORT")
3e170ce0
A
1249 if (s & TH_IDLE):
1250 retval.append("TH_IDLE")
1251 return retval
1252
39037602
A
1253
1254def format_uuid(elementValues):
1255 return ''.join("%02x" % i for i in elementValues)
1256
5ba3f43e
A
1257kThreadWaitNone = 0x00
1258kThreadWaitKernelMutex = 0x01
1259kThreadWaitPortReceive = 0x02
1260kThreadWaitPortSetReceive = 0x03
1261kThreadWaitPortSend = 0x04
1262kThreadWaitPortSendInTransit = 0x05
1263kThreadWaitSemaphore = 0x06
1264kThreadWaitKernelRWLockRead = 0x07
1265kThreadWaitKernelRWLockWrite = 0x08
1266kThreadWaitKernelRWLockUpgrade = 0x09
1267kThreadWaitUserLock = 0x0a
1268kThreadWaitPThreadMutex = 0x0b
1269kThreadWaitPThreadRWLockRead = 0x0c
1270kThreadWaitPThreadRWLockWrite = 0x0d
1271kThreadWaitPThreadCondVar = 0x0e
1272kThreadWaitParkedWorkQueue = 0x0f
1273kThreadWaitWorkloopSyncWait = 0x10
d9a64523 1274kThreadWaitOnProcess = 0x11
5ba3f43e
A
1275
1276
1277UINT64_MAX = 0xffffffffffffffff
1278STACKSHOT_WAITOWNER_KERNEL = (UINT64_MAX - 1)
1279STACKSHOT_WAITOWNER_PORT_LOCKED = (UINT64_MAX - 2)
1280STACKSHOT_WAITOWNER_PSET_LOCKED = (UINT64_MAX - 3)
1281STACKSHOT_WAITOWNER_INTRANSIT = (UINT64_MAX - 4)
1282STACKSHOT_WAITOWNER_MTXSPIN = (UINT64_MAX - 5)
1283STACKSHOT_WAITOWNER_THREQUESTED = (UINT64_MAX - 6)
1284STACKSHOT_WAITOWNER_SUSPENDED = (UINT64_MAX - 7)
1285
1286def formatWaitInfo(info):
1287 s = 'thread %d: ' % info['waiter'];
1288 type = info['wait_type']
1289 context = info['context']
1290 owner = info['owner']
1291 if type == kThreadWaitKernelMutex:
1292 s += 'kernel mutex %x' % context
1293 if owner == STACKSHOT_WAITOWNER_MTXSPIN:
1294 s += " in spin mode"
1295 elif owner:
1296 s += " owned by thread %u" % owner
1297 else:
1298 s += "with unknown owner"
1299 elif type == kThreadWaitPortReceive:
1300 s += "mach_msg receive on "
1301 if owner == STACKSHOT_WAITOWNER_PORT_LOCKED:
1302 s += "locked port %x" % context
1303 elif owner == STACKSHOT_WAITOWNER_INTRANSIT:
1304 s += "intransit port %x" % context
1305 elif owner:
1306 s += "port %x name %x" % (context, owner)
1307 else:
1308 s += "port %x" % context
1309 elif type == kThreadWaitPortSetReceive:
1310 if owner == STACKSHOT_WAITOWNER_PSET_LOCKED:
1311 s += "mach_msg receive on locked port set %x" % context
1312 else:
1313 s += "mach_msg receive on port set %x" % context
1314 elif type == kThreadWaitPortSend:
1315 s += "mach_msg send on "
1316 if owner == STACKSHOT_WAITOWNER_PORT_LOCKED:
1317 s += "locked port %x" % context
1318 elif owner == STACKSHOT_WAITOWNER_INTRANSIT:
1319 s += "intransit port %x" % context
1320 elif owner == STACKSHOT_WAITOWNER_KERNEL:
1321 s += "port %x owned by kernel" % context
1322 elif owner:
1323 s += "port %x owned by pid %d" % (context, owner)
1324 else:
1325 s += "port %x with unknown owner" % context
1326 elif type == kThreadWaitPortSendInTransit:
1327 s += "mach_msg send on port %x in transit to " % context
1328 if owner:
1329 s += "port %x" % owner
1330 else:
1331 s += "unknown port"
1332 elif type == kThreadWaitSemaphore:
a39ff7e2 1333 s += "semaphore port %x " % context
5ba3f43e
A
1334 if owner:
1335 s += "owned by pid %d" % owner
1336 else:
1337 s += "with unknown owner"
1338 elif type == kThreadWaitKernelRWLockRead:
1339 s += "krwlock %x for reading" % context
1340 elif type == kThreadWaitKernelRWLockWrite:
1341 s += "krwlock %x for writing" % context
1342 elif type == kThreadWaitKernelRWLockUpgrade:
1343 s += "krwlock %x for upgrading" % context
1344 elif type == kThreadWaitUserLock:
1345 if owner:
a39ff7e2 1346 s += "unfair lock %x owned by thread %d" % (context, owner)
5ba3f43e
A
1347 else:
1348 s += "spin lock %x" % context
1349 elif type == kThreadWaitPThreadMutex:
1350 s += "pthread mutex %x" % context
1351 if owner:
a39ff7e2 1352 s += " owned by thread %d" % owner
5ba3f43e
A
1353 else:
1354 s += " with unknown owner"
1355 elif type == kThreadWaitPThreadRWLockRead:
1356 s += "pthread rwlock %x for reading" % context
1357 elif type == kThreadWaitPThreadRWLockWrite:
1358 s += "pthread rwlock %x for writing" % context
1359 elif type == kThreadWaitPThreadCondVar:
1360 s += "pthread condvar %x" % context
1361 elif type == kThreadWaitWorkloopSyncWait:
1362 s += "workloop sync wait"
1363 if owner == STACKSHOT_WAITOWNER_SUSPENDED:
1364 s += ", suspended"
1365 elif owner == STACKSHOT_WAITOWNER_THREQUESTED:
1366 s += ", thread requested"
1367 elif owner != 0:
1368 s += ", owned by thread %u" % owner
1369 else:
1370 s += ", unknown owner"
1371 s += ", workloop id %x" % context
d9a64523
A
1372 elif type == kThreadWaitOnProcess:
1373 s += "waitpid, for pid %d" % owner
1374
5ba3f43e
A
1375 else:
1376 s += "unknown type %d (owner %d, context %x)" % (type, owner, context)
1377
1378 return s
1379
1380
1381def SaveStackshotReport(j, outfile_name, dsc_uuid, dsc_libs_arr, incomplete):
3e170ce0
A
1382 import time
1383 from operator import itemgetter, attrgetter
39037602 1384 ss = j.get('kcdata_stackshot')
3e170ce0
A
1385 if not ss:
1386 print "No KCDATA_BUFFER_BEGIN_STACKSHOT object found. Skipping writing report."
1387 return
5c9f4661 1388
3e170ce0 1389 timestamp = ss.get('usecs_since_epoch', int(time.time()))
5c9f4661
A
1390 try:
1391 timestamp = time.strftime("%Y-%m-%d %H:%M:%S %z",time.gmtime(timestamp))
1392 except ValueError, e:
1393 print "couldn't convert timestamp:", str(e)
1394 timestamp = None
1395
3e170ce0 1396 os_version = ss.get('osversion', 'Unknown')
39037602
A
1397 timebase = ss.get('mach_timebase_info', {"denom": 1, "numer": 1})
1398 if not dsc_uuid and 'imageSlidBaseAddress' not in ss.get('shared_cache_dyld_load_info'):
1399 print "Stackshot format does not include slid shared cache base address and no UUID provided. Skipping writing report."
1400 return
1401
1402 # If a shared cache UUID is provided, treat the slide as the base address
1403 # for compatibility with existing tools that operate based on this logic
1404 if dsc_uuid:
1405 shared_cache_base_addr = ss.get('shared_cache_dyld_load_info')['imageLoadAddress']
1406 elif 'imageSlidBaseAddress' in ss.get('shared_cache_dyld_load_info'):
1407 shared_cache_base_addr = ss.get('shared_cache_dyld_load_info')['imageSlidBaseAddress']
1408 else:
1409 print "No shared cache UUID provided and data doesn't include imageSlidBaseAddress. Skipping writing report."
1410 return
1411
1412 dsc_common = [format_uuid(ss.get('shared_cache_dyld_load_info')['imageUUID']),
d9a64523
A
1413 shared_cache_base_addr, "S" ]
1414
1415 dsc_layout = ss.get('system_shared_cache_layout')
3e170ce0
A
1416
1417 dsc_libs = []
4bd07ac2 1418 print "Shared cache UUID found from the binary data is <%s> " % str(dsc_common[0])
3e170ce0
A
1419 if dsc_common[0].replace('-', '').lower() == dsc_uuid:
1420 print "SUCCESS: Found Matching dyld shared cache uuid. Loading library load addresses from layout provided."
1421 _load_addr = dsc_common[1]
1422 #print _load_addr
1423 #print dsc_libs_arr
1424 for i in dsc_libs_arr:
1425 _uuid = i[2].lower().replace('-','').strip()
1426 _addr = int(i[0], 16) + _load_addr
d9a64523 1427 dsc_libs.append([_uuid, _addr, "C"])
3e170ce0 1428 #print "adding ", [_uuid, _addr, "C"]
39037602
A
1429 elif dsc_uuid:
1430 print "Provided shared cache UUID does not match. Skipping writing report."
1431 return
d9a64523
A
1432 elif dsc_layout:
1433 print "Found in memory system shared cache layout with {} images".format(len(dsc_layout))
1434 slide = ss.get('shared_cache_dyld_load_info')['imageLoadAddress']
1435
1436 for image in dsc_layout:
1437 dsc_libs.append([format_uuid(image['imageUUID']), image['imageLoadAddress'] + slide, "C"])
3e170ce0
A
1438
1439 AllImageCatalog = []
1440 obj = {}
1441 obj["kernel"] = os_version
5c9f4661
A
1442 if timestamp is not None:
1443 obj["date"] = timestamp
3e170ce0
A
1444 obj["reason"] = "kernel panic stackshot"
1445 obj["incident"] = "ABCDEFGH-1234-56IJ-789K-0LMNOPQRSTUV"
1446 obj["crashReporterKey"] = "12ab34cd45aabbccdd6712ab34cd45aabbccdd67"
39037602 1447 obj["bootArgs"] = ss.get('boot_args','')
3e170ce0
A
1448 obj["frontmostPids"] = [0]
1449 obj["exception"] = "0xDEADF157"
1450 obj["processByPid"] = {}
5ba3f43e
A
1451
1452 if incomplete:
1453 obj["reason"] = "!!!INCOMPLETE!!! kernel panic stackshot"
1454 obj["notes"] = "This stackshot report generated from incomplete data! Some information is missing! "
1455
3e170ce0 1456 processByPid = obj["processByPid"]
39037602 1457 ssplist = ss.get('task_snapshots', {})
3e170ce0
A
1458 kern_load_info = []
1459 if "0" in ssplist:
39037602
A
1460 kc_uuid = ssplist["0"].get('kernelcache_load_info', None)
1461 if kc_uuid:
1462 kernelcache_uuid = [format_uuid(kc_uuid['imageUUID']), kc_uuid['imageLoadAddress'], "U" ]
1463 kern_load_info.append(kernelcache_uuid)
1464
3e170ce0
A
1465 kl_infos = ssplist["0"].get("dyld_load_info", [])
1466 for dlinfo in kl_infos:
39037602 1467 kern_load_info.append([format_uuid(dlinfo['imageUUID']), dlinfo['imageLoadAddress'], "K"])
3e170ce0
A
1468 for pid,piddata in ssplist.iteritems():
1469 processByPid[str(pid)] = {}
1470 tsnap = processByPid[str(pid)]
1471 pr_lib_dsc = dsc_common
39037602
A
1472 if 'shared_cache_dyld_load_info' in tsnap:
1473 if 'imageSlidBaseAddress' in tsnap.get('shared_cache_dyld_load_info'):
1474 shared_cache_base_addr = tsnap.get('shared_cache_dyld_load_info')['imageSlidBaseAddress']
1475 else:
1476 print "Specific task shared cache format does not include slid shared cache base address. Skipping writing report."
1477 return
1478
1479 pr_lib_dsc = [format_uuid(tsnap.get('shared_cache_dyld_load_info')['imageUUID']),
1480 tsnap.get('shared_cache_dyld_load_info')['imageSlidBaseAddress'],
1481 "S"
3e170ce0
A
1482 ]
1483
1484 pr_libs = []
1485 if len(dsc_libs) == 0:
1486 pr_libs.append(pr_lib_dsc)
1487 _lib_type = "P"
1488 if int(pid) == 0:
1489 _lib_type = "K"
1490 pr_libs = []
1491 else:
1492 for dlinfo in piddata.get('dyld_load_info',[]):
39037602 1493 pr_libs.append([format_uuid(dlinfo['imageUUID']), dlinfo['imageLoadAddress'], _lib_type])
3e170ce0
A
1494
1495 pr_libs.extend(kern_load_info)
1496 pr_libs.extend(dsc_libs)
1497
1498 pr_libs.sort(key=itemgetter(1))
1499
5ba3f43e
A
1500 if 'task_snapshot' not in piddata:
1501 continue
39037602
A
1502 tasksnap = piddata['task_snapshot']
1503 tsnap["pid"] = tasksnap["ts_pid"]
d9a64523
A
1504 if 'ts_asid' in piddata:
1505 tsnap["asid"] = piddata["ts_asid"]
1506
1507 if 'ts_pagetable' in piddata:
1508 pagetables = []
1509 for tte in piddata["ts_pagetable"]:
1510 pagetables.append(tte)
1511 tsnap["pageTables"] = pagetables
1512
39037602
A
1513 tsnap["residentMemoryBytes"] = tasksnap["ts_task_size"]
1514 tsnap["timesDidThrottle"] = tasksnap["ts_did_throttle"]
1515 tsnap["systemTimeTask"] = GetSecondsFromMATime(tasksnap["ts_system_time_in_terminated_th"], timebase)
1516 tsnap["pageIns"] = tasksnap["ts_pageins"]
1517 tsnap["pageFaults"] = tasksnap["ts_faults"]
1518 tsnap["userTimeTask"] = GetSecondsFromMATime(tasksnap[ "ts_user_time_in_terminated_thre"], timebase)
1519 tsnap["procname"] = tasksnap["ts_p_comm"]
1520 tsnap["copyOnWriteFaults"] = tasksnap["ts_cow_faults"]
1521 tsnap["timesThrottled"] = tasksnap["ts_was_throttled"]
3e170ce0
A
1522 tsnap["threadById"] = {}
1523 threadByID = tsnap["threadById"]
39037602 1524 thlist = piddata.get('thread_snapshots', {})
3e170ce0
A
1525 for tid,thdata in thlist.iteritems():
1526 threadByID[str(tid)] = {}
1527 thsnap = threadByID[str(tid)]
39037602 1528 if "thread_snapshot" not in thdata:
4bd07ac2
A
1529 print "Found broken thread state for thread ID: %s." % tid
1530 break
39037602
A
1531 threadsnap = thdata["thread_snapshot"]
1532 thsnap["userTime"] = GetSecondsFromMATime(threadsnap["ths_user_time"], timebase)
1533 thsnap["id"] = threadsnap["ths_thread_id"]
1534 thsnap["basePriority"] = threadsnap["ths_base_priority"]
1535 thsnap["systemTime"] = threadsnap["ths_sys_time"]
1536 thsnap["schedPriority"] = threadsnap["ths_sched_priority"]
1537 thsnap["state"] = GetStateDescription(threadsnap['ths_state'])
1538 thsnap["qosEffective"] = threadsnap["ths_eqos"]
1539 thsnap["qosRequested"] = threadsnap["ths_rqos"]
1540
1541 if threadsnap['ths_continuation']:
1542 thsnap["continuation"] = GetSymbolInfoForFrame(AllImageCatalog, pr_libs, threadsnap['ths_continuation'])
3e170ce0
A
1543 if "kernel_stack_frames" in thdata:
1544 kuserframes = []
1545 for f in thdata["kernel_stack_frames"]:
1546 kuserframes.append(GetSymbolInfoForFrame(AllImageCatalog, pr_libs, f['lr']))
1547 thsnap["kernelFrames"] = kuserframes
1548
1549 if "user_stack_frames" in thdata:
1550 uframes = []
1551 for f in thdata["user_stack_frames"]:
1552 uframes.append(GetSymbolInfoForFrame(AllImageCatalog, pr_libs, f['lr']))
1553 thsnap["userFrames"] = uframes
d9a64523
A
1554
1555 if "user_stacktop" in thdata:
1556 (address,) = struct.unpack("<Q", struct.pack("B"*8, *thdata["user_stacktop"]["stack_contents"]))
1557 thsnap["userStacktop"] = GetSymbolInfoForFrame(AllImageCatalog, pr_libs, address)
1558
39037602
A
1559 if threadsnap['ths_wait_event']:
1560 thsnap["waitEvent"] = GetSymbolInfoForFrame(AllImageCatalog, pr_libs, threadsnap['ths_wait_event'])
3e170ce0 1561
5ba3f43e
A
1562 if 'thread_waitinfo' in piddata:
1563 tsnap['waitInfo'] = map(formatWaitInfo, piddata['thread_waitinfo'])
1564
3e170ce0 1565 obj['binaryImages'] = AllImageCatalog
5ba3f43e
A
1566 if outfile_name == '-':
1567 fh = sys.stdout
1568 else:
1569 fh = open(outfile_name, "w")
5c9f4661
A
1570
1571 header = {}
1572 header['bug_type'] = 288
1573 if timestamp is not None:
1574 header['timestamp'] = timestamp
1575 header['os_version'] = os_version
1576 fh.write(json.dumps(header))
1577 fh.write("\n")
1578
3e170ce0
A
1579 fh.write(json.dumps(obj, sort_keys=False, indent=2, separators=(',', ': ')))
1580 fh.close()
1581
1582## Base utils for interacting with shell ##
1583def RunCommand(bash_cmd_string, get_stderr = True):
1584 """
1585 returns: (int,str) : exit_code and output_str
1586 """
1587 print "RUNNING: %s" % bash_cmd_string
1588 cmd_args = shlex.split(bash_cmd_string)
1589 output_str = ""
1590 exit_code = 0
1591 try:
1592 if get_stderr:
1593 output_str = subprocess.check_output(cmd_args, stderr=subprocess.STDOUT)
1594 else:
1595 output_str = subprocess.check_output(cmd_args, stderr=None)
1596 except subprocess.CalledProcessError, e:
1597 exit_code = e.returncode
1598 finally:
1599 return (exit_code, output_str)
1600
1601def ProcessDyldSharedCacheFile(shared_cache_file_path, sdk_str=""):
1602 """ returns (uuid, text_info) output from shared_cache_util.
1603 In case of error None is returned and err message is printed to stdout.
1604 """
1605 if not os.path.exists(shared_cache_file_path):
1606 print "File path: %s does not exists" % shared_cache_file_path
1607 return None
1608 if sdk_str:
1609 sdk_str = ' -sdk "%s" ' % sdk_str
1610 (c, so) = RunCommand("xcrun {} -find dyld_shared_cache_util".format(sdk_str))
1611 if c:
1612 print "Failed to find path to dyld_shared_cache_util. Exit code: %d , message: %s" % (c,so)
1613 return None
1614 dyld_shared_cache_util = so.strip()
1615 (c, so) = RunCommand("{} -info {}".format(dyld_shared_cache_util, shared_cache_file_path))
1616 if c:
1617 print "Failed to get uuid info from %s" % shared_cache_file_path
1618 print so
1619 return None
1620
1621 uuid = so.splitlines()[0].split(": ")[-1].strip().replace("-","").lower()
39037602 1622
3e170ce0
A
1623 (c, so) = RunCommand("{} -text_info {}".format(dyld_shared_cache_util, shared_cache_file_path))
1624 if c:
1625 print "Failed to get text_info from %s" % shared_cache_file_path
1626 print so
1627 return None
39037602 1628
3e170ce0
A
1629 print "Found %s uuid: %s" % (shared_cache_file_path, uuid)
1630 text_info = so
1631
1632 return (uuid, so)
1633
1634parser = argparse.ArgumentParser(description="Decode a kcdata binary file.")
1635parser.add_argument("-l", "--listtypes", action="store_true", required=False, default=False,
1636 help="List all known types",
1637 dest="list_known_types")
1638
1639parser.add_argument("-s", "--stackshot", required=False, default=False,
1640 help="Generate a stackshot report file",
1641 dest="stackshot_file")
1642
39037602
A
1643parser.add_argument("--multiple", help="look for multiple stackshots in a single file", action='store_true')
1644
1645parser.add_argument("-p", "--plist", required=False, default=False,
1646 help="output as plist", action="store_true")
1647
3e170ce0
A
1648parser.add_argument("-U", "--uuid", required=False, default="", help="UUID of dyld shared cache to be analysed and filled in libs of stackshot report", dest="uuid")
1649parser.add_argument("-L", "--layout", required=False, type=argparse.FileType("r"), help="Path to layout file for DyldSharedCache. You can generate one by doing \n\tbash$xcrun -sdk <sdk> dyld_shared_cache_util -text_info </path/to/dyld_shared_cache> ", dest="layout")
1650parser.add_argument("-S", "--sdk", required=False, default="", help="sdk property passed to xcrun command to find the required tools. Default is empty string.", dest="sdk")
1651parser.add_argument("-D", "--dyld_shared_cache", required=False, default="", help="Path to dyld_shared_cache built by B&I", dest="dsc")
5ba3f43e
A
1652parser.add_argument("--pretty", default=False, action='store_true', help="make the output a little more human readable")
1653parser.add_argument("--incomplete", action='store_true', help="accept incomplete data")
3e170ce0
A
1654parser.add_argument("kcdata_file", type=argparse.FileType('r'), help="Path to a kcdata binary file.")
1655
39037602
A
1656class VerboseAction(argparse.Action):
1657 def __call__(self, parser, namespace, values, option_string=None):
1658 logging.basicConfig(level=logging.INFO, stream=sys.stderr, format='%(message)s')
1659parser.add_argument('-v', "--verbose", action=VerboseAction, nargs=0)
1660
1661@contextlib.contextmanager
1662def data_from_stream(stream):
1663 try:
1664 fmap = mmap.mmap(stream.fileno(), 0, mmap.MAP_SHARED, mmap.PROT_READ)
1665 except:
1666 yield stream.read()
1667 else:
1668 try:
1669 yield fmap
1670 finally:
1671 fmap.close()
1672
1673def iterate_kcdatas(kcdata_file):
1674 with data_from_stream(kcdata_file) as data:
1675 iterator = kcdata_item_iterator(data)
1676 kcdata_buffer = KCObject.FromKCItem(iterator.next())
1677 if not isinstance(kcdata_buffer, KCBufferObject):
1678 try:
1679 decoded = base64.b64decode(data)
1680 except:
1681 pass
1682 else:
1683 iterator = kcdata_item_iterator(decoded)
1684 kcdata_buffer = KCObject.FromKCItem(iterator.next())
1685 if not isinstance(kcdata_buffer, KCBufferObject):
1686 import gzip
1687 from io import BytesIO
1688 try:
1689 decompressed = gzip.GzipFile(fileobj=BytesIO(data[:])).read()
1690 except:
1691 pass
1692 else:
1693 iterator = kcdata_item_iterator(decompressed)
1694 kcdata_buffer = KCObject.FromKCItem(iterator.next())
1695 if not isinstance(kcdata_buffer, KCBufferObject):
1696 raise Exception, "unknown file type"
1697
1698 kcdata_buffer.ReadItems(iterator)
1699 yield kcdata_buffer
1700
1701 for magic in iterator:
1702 kcdata_buffer = KCObject.FromKCItem(magic)
1703 if not isinstance(kcdata_buffer, KCBufferObject):
1704 raise Exception, "unknown file type"
1705 kcdata_buffer.ReadItems(iterator)
1706 yield kcdata_buffer
1707
3e170ce0 1708
5ba3f43e
A
1709def prettify(data):
1710 if isinstance(data, list):
1711 return map(prettify, data);
1712
1713 elif isinstance(data, dict):
1714 newdata = dict()
1715 for key, value in data.items():
1716 if 'uuid' in key.lower() and isinstance(value, list) and len(value) == 16:
1717 value = '%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X' % tuple(value)
1718 elif 'address' in key.lower() and isinstance(value, (int, long)):
1719 value = '0x%X' % value
d9a64523
A
1720 elif key == 'lr':
1721 value = '0x%X' % value
a39ff7e2
A
1722 elif key == 'thread_waitinfo':
1723 value = map(formatWaitInfo, value)
d9a64523
A
1724 elif key == 'stack_contents':
1725 print value
1726 (address,) = struct.unpack("<Q", struct.pack("B"*8, *value))
1727 value = '0x%X' % address
5ba3f43e
A
1728 else:
1729 value = prettify(value);
1730 newdata[key] = value
1731
1732 return newdata
1733
1734 else:
1735 return data
1736
3e170ce0
A
1737
1738if __name__ == '__main__':
1739 args = parser.parse_args()
1740
39037602
A
1741 if args.multiple and args.stackshot_file:
1742 raise NotImplementedError
1743
3e170ce0
A
1744 if args.list_known_types:
1745 for (n, t) in KNOWN_TYPES_COLLECTION.items():
1746 print "%d : %s " % (n, str(t))
1747 sys.exit(1)
1748
5ba3f43e
A
1749 if args.incomplete or args.stackshot_file:
1750 G.accept_incomplete_data = True
1751
39037602
A
1752 for i,kcdata_buffer in enumerate(iterate_kcdatas(args.kcdata_file)):
1753 if i > 0 and not args.multiple:
1754 break
3e170ce0 1755
39037602
A
1756 str_data = "{" + kcdata_buffer.GetJsonRepr() + "}"
1757 str_data = str_data.replace("\t", " ")
1758
1759 try:
1760 json_obj = json.loads(str_data)
1761 except:
1762 print >>sys.stderr, "JSON reparsing failed! Printing string data!\n"
1763 import textwrap
1764 print textwrap.fill(str_data, 100)
1765 raise
3e170ce0 1766
5ba3f43e
A
1767 if args.pretty:
1768 json_obj = prettify(json_obj)
1769
3e170ce0
A
1770 dsc_uuid = None
1771 dsc_libs_arr = []
1772 libs_re = re.compile("^\s*(0x[a-fA-F0-9]+)\s->\s(0x[a-fA-F0-9]+)\s+<([a-fA-F0-9\-]+)>\s+.*$", re.MULTILINE)
1773 if args.uuid and args.layout:
1774 dsc_uuid = args.uuid.strip().replace("-",'').lower()
1775 dsc_libs_arr = libs_re.findall(args.layout.read())
1776
1777 if args.dsc:
1778 _ret = ProcessDyldSharedCacheFile(args.dsc, args.sdk)
1779 if _ret:
1780 dsc_uuid = _ret[0]
1781 dsc_libs_arr = libs_re.findall(_ret[1])
1782
1783 if args.stackshot_file:
5ba3f43e 1784 SaveStackshotReport(json_obj, args.stackshot_file, dsc_uuid, dsc_libs_arr, G.data_was_incomplete)
39037602
A
1785 elif args.plist:
1786 import Foundation
1787 plist = Foundation.NSPropertyListSerialization.dataWithPropertyList_format_options_error_(
1788 json_obj, Foundation.NSPropertyListXMLFormat_v1_0, 0, None)[0].bytes().tobytes()
1789 #sigh. on some pythons long integers are getting output with L's in the plist.
1790 plist = re.sub(r'^(\s*<integer>\d+)L(</integer>\s*)$', r"\1\2", plist, flags=re.MULTILINE)
1791 print plist,
3e170ce0
A
1792 else:
1793 print json.dumps(json_obj, sort_keys=True, indent=4, separators=(',', ': '))