]>
git.saurik.com Git - apple/xnu.git/blob - tools/lldbmacros/core/kernelcore.py
ec6295dff78cb752e33b7c823c731e930e063363
2 """ Please make sure you read the README COMPLETELY BEFORE reading anything below.
3 It is very critical that you read coding guidelines in Section E in README file.
7 from lazytarget
import *
8 from configuration
import *
12 def IterateTAILQ_HEAD(headval
, element_name
):
13 """ iterate over a TAILQ_HEAD in kernel. refer to bsd/sys/queue.h
15 headval - value : value object representing the head of the list
16 element_name- str : string name of the field which holds the list links.
18 A generator does not return. It is used for iterating.
19 value : an object that is of type as headval->tqh_first. Always a pointer object
21 list_head = kern.GetGlobalVariable('mountlist')
22 for entryobj in IterateTAILQ_HEAD(list_head, 'mnt_list'):
23 print GetEntrySummary(entryobj)
25 iter_val
= headval
.tqh_first
26 while unsigned(iter_val
) != 0 :
28 iter_val
= iter_val
.__getattr
__(element_name
).tqe_next
31 def IterateLinkedList(element
, field_name
):
32 """ iterate over a linked list.
33 This is equivalent to elt = element; while(elt) { do_work(elt); elt = elt-><field_name>; }
35 element - value : value object representing element in the list.
36 field_name - str : name of field that holds pointer to next element
37 returns: Nothing. This is used as iterable
39 first_zone = kern.GetGlobalVariable('first_zone')
40 for zone in IterateLinkedList(first_zone, 'next_zone'):
41 print GetZoneSummary(zone)
44 while unsigned(elt
) != 0:
46 elt
= elt
.__getattr
__(field_name
)
49 def IterateListEntry(element
, element_type
, field_name
):
50 """ iterate over a list as defined with LIST_HEAD in bsd/sys/queue.h
52 element - value : Value object for lh_first
53 element_type - str : Type of the next element
54 field_name - str : Name of the field in next element's structure
56 A generator does not return. It is used for iterating
57 value : an object thats of type (element_type) head->le_next. Always a pointer object
59 headp = kern.globals.initproc.p_children
60 for pp in IterateListEntry(headp, 'struct proc *', 'p_sibling'):
63 elt
= element
.lh_first
64 if type(element_type
) == str:
65 element_type
= gettype(element_type
)
66 while unsigned(elt
) != 0:
68 next_el
= elt
.__getattr
__(field_name
).le_next
69 elt
= cast(next_el
, element_type
)
71 def IterateLinkageChain(queue_head
, element_type
, field_name
, field_ofst
=0):
72 """ Iterate over a Linkage Chain queue in kernel of type queue_head_t. (osfmk/kern/queue.h method 1)
73 This is equivalent to the qe_foreach_element() macro
75 queue_head - value : Value object for queue_head.
76 element_type - lldb.SBType : pointer type of the element which contains the queue_chain_t. Typically its structs like thread, task etc..
77 - str : OR a string describing the type. ex. 'task *'
78 field_name - str : Name of the field (in element) which holds a queue_chain_t
79 field_ofst - int : offset from the 'field_name' (in element) which holds a queue_chain_t
80 This is mostly useful if a particular element contains an array of queue_chain_t
82 A generator does not return. It is used for iterating.
83 value : An object thats of type (element_type). Always a pointer object
85 coalq = kern.GetGlobalVariable('coalitions_q')
86 for coal in IterateLinkageChain(coalq, 'struct coalition *', 'coalitions'):
87 print GetCoalitionInfo(coal)
90 if type(element_type
) == str:
91 element_type
= gettype(element_type
)
93 if unsigned(queue_head
) == 0:
96 if element_type
.IsPointerType():
97 elem_ofst
= getfieldoffset(element_type
.GetPointeeType(), field_name
) + field_ofst
99 elem_ofst
= getfieldoffset(element_type
, field_name
) + field_ofst
101 link
= queue_head
.next
102 while (unsigned(link
) != unsigned(queue_head
)):
103 addr
= unsigned(link
) - elem_ofst
;
104 # I can't use the GetValueFromAddress function of the kernel class
105 # because I have no instance of that class!
106 obj
= value(link
.GetSBValue().CreateValueFromExpression(None,'(void *)'+str(addr
)))
107 obj
= cast(obj
, element_type
)
112 def IterateQueue(queue_head
, element_ptr_type
, element_field_name
, backwards
=False):
113 """ Iterate over an Element Chain queue in kernel of type queue_head_t. (osfmk/kern/queue.h method 2)
115 queue_head - value : Value object for queue_head.
116 element_ptr_type - lldb.SBType : a pointer type of the element 'next' points to. Typically its structs like thread, task etc..
117 - str : OR a string describing the type. ex. 'task *'
118 element_field_name - str : name of the field in target struct.
119 backwards - backwards : traverse the queue backwards
121 A generator does not return. It is used for iterating.
122 value : an object thats of type (element_type) queue_head->next. Always a pointer object
124 for page_meta in IterateQueue(kern.globals.first_zone.pages.all_free, 'struct zone_page_metadata *', 'pages'):
127 if type(element_ptr_type
) == str :
128 element_ptr_type
= gettype(element_ptr_type
)
130 queue_head
= queue_head
.GetSBValue()
131 queue_head_addr
= 0x0
132 if queue_head
.TypeIsPointerType():
133 queue_head_addr
= queue_head
.GetValueAsUnsigned()
135 queue_head_addr
= queue_head
.GetAddress().GetLoadAddress(LazyTarget
.GetTarget())
137 cur_elt
= queue_head
.GetChildMemberWithName('prev')
139 cur_elt
= queue_head
.GetChildMemberWithName('next')
143 if not cur_elt
.IsValid() or cur_elt
.GetValueAsUnsigned() == 0 or cur_elt
.GetValueAsUnsigned() == queue_head_addr
:
145 elt
= cur_elt
.Cast(element_ptr_type
)
148 cur_elt
= elt
.GetChildMemberWithName(element_field_name
).GetChildMemberWithName('prev')
150 cur_elt
= elt
.GetChildMemberWithName(element_field_name
).GetChildMemberWithName('next')
152 class KernelTarget(object):
153 """ A common kernel object that provides access to kernel objects and information.
154 The class holds global lists for task, terminated_tasks, procs, zones, zombroc etc.
155 It also provides a way to symbolicate an address or create a value from an address.
157 def __init__(self
, debugger
):
158 """ Initialize the kernel debugging environment.
159 Target properties like architecture and connectedness are lazy-evaluted.
161 self
._debugger
= debugger
# This holds an lldb.SBDebugger object for debugger state
162 self
._threads
_list
= []
163 self
._tasks
_list
= []
164 self
._coalitions
_list
= []
166 self
._terminated
_tasks
_list
= []
167 self
._zones
_list
= []
168 self
._zombproc
_list
= []
169 self
._kernel
_types
_cache
= {} #this will cache the Type objects as and when requested.
172 self
._ptrsize
= None # pointer size of kernel, not userspace
173 self
.symbolicator
= None
174 class _GlobalVariableFind(object):
175 def __init__(self
, kern
):
176 self
._xnu
_kernobj
_12obscure
12 = kern
177 def __getattr__(self
, name
):
178 v
= self
._xnu
_kernobj
_12obscure
12.GetGlobalVariable(name
)
179 if not v
.GetSBValue().IsValid():
180 raise ValueError('No such global variable by name: %s '%str
(name
))
182 self
.globals = _GlobalVariableFind(self
)
183 LazyTarget
.Initialize(debugger
)
185 def _GetSymbolicator(self
):
186 """ Internal function: To initialize the symbolication from lldb.utils
188 if not self
.symbolicator
is None:
189 return self
.symbolicator
191 from lldb
.utils
import symbolication
192 symbolicator
= symbolication
.Symbolicator()
193 symbolicator
.target
= LazyTarget
.GetTarget()
194 self
.symbolicator
= symbolicator
195 return self
.symbolicator
197 def Symbolicate(self
, addr
):
198 """ simple method to get name of function/variable from an address. this is equivalent of gdb 'output /a 0xaddress'
200 addr - int : typically hex value like 0xffffff80002c0df0
202 str - '' if no symbol found else the symbol name.
203 Note: this function only finds the first symbol. If you expect multiple symbol conflict please use SymbolicateFromAddress()
206 syms
= self
.SymbolicateFromAddress(addr
)
208 ret_str
+=syms
[0].GetName()
211 def SymbolicateFromAddress(self
, addr
):
212 """ symbolicates any given address based on modules loaded in the target.
214 addr - int : typically hex value like 0xffffff80002c0df0
216 [] of SBSymbol: In case we don't find anything than empty array is returned.
217 Note: a type of symbol can be figured out by gettype() function of SBSymbol.
219 syms = kern.Symbolicate(0xffffff80002c0df0)
221 if s.GetType() == lldb.eSymbolTypeCode:
222 print "Function", s.GetName()
223 if s.GetType() == lldb.eSymbolTypeData:
224 print "Variable", s.GetName()
226 if type(int(1)) != type(addr
):
227 if str(addr
).strip().find("0x") == 0 :
232 symbolicator
= self
._GetSymbolicator
()
233 syms
= symbolicator
.symbolicate(addr
)
237 ret_array
.append(s
.get_symbol_context().symbol
)
240 def IsDebuggerConnected(self
):
241 proc_state
= LazyTarget
.GetProcess().state
242 if proc_state
== lldb
.eStateInvalid
: return False
243 if proc_state
in [lldb
.eStateStopped
, lldb
.eStateSuspended
] : return True
245 def GetGlobalVariable(self
, name
):
246 """ Get the value object representation for a kernel global variable
248 name : str - name of the variable. ex. version
249 returns: value - python object representing global variable.
250 raises : Exception in case the variable is not found.
252 self
._globals
_cache
_dict
= caching
.GetDynamicCacheData("kern._globals_cache_dict", {})
253 if name
not in self
._globals
_cache
_dict
:
254 self
._globals
_cache
_dict
[name
] = value(LazyTarget
.GetTarget().FindGlobalVariables(name
, 1).GetValueAtIndex(0))
255 return self
._globals
_cache
_dict
[name
]
257 def GetLoadAddressForSymbol(self
, name
):
258 """ Get the load address of a symbol in the kernel.
260 name : str - name of the symbol to lookup
261 returns: int - the load address as an integer. Use GetValueFromAddress to cast to a value.
262 raises : LookupError - if the symbol is not found.
265 target
= LazyTarget
.GetTarget()
266 syms_arr
= target
.FindSymbols(name
)
267 if syms_arr
.IsValid() and len(syms_arr
) > 0:
268 symbol
= syms_arr
[0].GetSymbol()
270 return int(symbol
.GetStartAddress().GetLoadAddress(target
))
272 raise LookupError("Symbol not found: " + name
)
274 def GetValueFromAddress(self
, addr
, type_str
= 'void *'):
275 """ convert a address to value
277 addr - int : typically hex value like 0xffffff80008dc390
278 type_str - str: type to cast to. Default type will be void *
280 value : a value object which has address as addr and type is type_str
282 obj
= value(self
.globals.version
.GetSBValue().CreateValueFromExpression(None,'(void *)'+str(addr
)))
283 obj
= cast(obj
, type_str
)
286 def GetValueAsType(self
, v
, t
):
287 """ Retrieves a global variable 'v' of type 't' wrapped in a vue object.
288 If 'v' is an address, creates a vue object of the appropriate type.
289 If 'v' is a name, looks for the global variable and asserts its type.
291 NameError - If 'v' cannot be found
292 TypeError - If 'v' is of the wrong type
295 return self
.GetValueFromAddress(v
, t
)
297 var
= LazyTarget
.GetTarget().FindGlobalVariables(v
, 1)[0]
299 raise NameError("Failed to find global variable '{0}'".format(v
))
300 if var
.GetTypeName() != t
:
301 raise TypeError("{0} must be of type '{1}', not '{2}'".format(v
, t
, var
.GetTypeName()))
304 def _GetIterator(self
, iter_head_name
, next_element_name
='next', iter_head_type
=None):
305 """ returns an iterator for a collection in kernel memory.
307 iter_head_name - str : name of queue_head or list head variable.
308 next_element_name - str : name of the element that leads to next element.
309 for ex. in struct zone list 'next_zone' is the linking element.
311 iterable : typically used in conjunction with "for varname in iterable:"
313 head_element
= self
.GetGlobalVariable(iter_head_name
)
314 return head_element
.GetSBValue().linked_list_iter(next_element_name
)
316 def TruncPage(self
, addr
):
317 return (addr
& ~
(unsigned(self
.GetGlobalVariable("page_size")) - 1))
319 def RoundPage(self
, addr
):
320 return trunc_page(addr
+ unsigned(self
.GetGlobalVariable("page_size")) - 1)
322 def StraddlesPage(self
, addr
, size
):
323 if size
> unsigned(self
.GetGlobalVariable("page_size")):
325 val
= ((addr
+ size
) & (unsigned(self
.GetGlobalVariable("page_size"))-1))
326 return (val
< size
and val
> 0)
328 def PhysToKernelVirt(self
, addr
):
329 if self
.arch
== 'x86_64':
330 return (addr
+ unsigned(self
.GetGlobalVariable('physmap_base')))
331 elif self
.arch
== 'arm' or self
.arch
== 'arm64':
332 return (addr
- unsigned(self
.GetGlobalVariable("gPhysBase")) + unsigned(self
.GetGlobalVariable("gVirtBase")))
334 raise ValueError("PhysToVirt does not support {0}".format(arch
))
336 def GetNanotimeFromAbstime(self
, abstime
):
337 """ convert absolute time (which is in MATUs) to nano seconds.
338 Since based on architecture the conversion may differ.
340 abstime - int absolute time as shown by mach_absolute_time
342 int - nanosecs of time
344 usec_divisor
= caching
.GetStaticCacheData("kern.rtc_usec_divisor", None)
346 if self
.arch
== 'x86_64':
349 rtclockdata_addr
= self
.GetLoadAddressForSymbol('RTClockData')
350 rtc
= self
.GetValueFromAddress(rtclockdata_addr
, 'struct _rtclock_data_ *')
351 usec_divisor
= unsigned(rtc
.rtc_usec_divisor
)
352 usec_divisor
= int(usec_divisor
)
353 caching
.SaveStaticCacheData('kern.rtc_usec_divisor', usec_divisor
)
354 nsecs
= (abstime
* 1000)/usec_divisor
357 def __getattribute__(self
, name
):
359 self
._zones
_list
= caching
.GetDynamicCacheData("kern._zones_list", [])
360 if len(self
._zones
_list
) > 0: return self
._zones
_list
361 first_zone
= self
.GetGlobalVariable('first_zone')
362 for z
in IterateLinkedList(first_zone
, 'next_zone'):
363 self
._zones
_list
.append(z
)
364 caching
.SaveDynamicCacheData("kern._zones_list", self
._zones
_list
)
365 return self
._zones
_list
367 if name
== 'threads' :
368 self
._threads
_list
= caching
.GetDynamicCacheData("kern._threads_list", [])
369 if len(self
._threads
_list
) > 0 : return self
._threads
_list
370 thread_queue_head
= self
.GetGlobalVariable('threads')
371 thread_type
= LazyTarget
.GetTarget().FindFirstType('thread')
372 thread_ptr_type
= thread_type
.GetPointerType()
373 for th
in IterateQueue(thread_queue_head
, thread_ptr_type
, 'threads'):
374 self
._threads
_list
.append(th
)
375 caching
.SaveDynamicCacheData("kern._threads_list", self
._threads
_list
)
376 return self
._threads
_list
379 self
._tasks
_list
= caching
.GetDynamicCacheData("kern._tasks_list", [])
380 if len(self
._tasks
_list
) > 0 : return self
._tasks
_list
381 task_queue_head
= self
.GetGlobalVariable('tasks')
382 task_type
= LazyTarget
.GetTarget().FindFirstType('task')
383 task_ptr_type
= task_type
.GetPointerType()
384 for tsk
in IterateQueue(task_queue_head
, task_ptr_type
, 'tasks'):
385 self
._tasks
_list
.append(tsk
)
386 caching
.SaveDynamicCacheData("kern._tasks_list", self
._tasks
_list
)
387 return self
._tasks
_list
389 if name
== 'coalitions' :
390 self
._coalitions
_list
= caching
.GetDynamicCacheData("kern._coalitions_list", [])
391 if len(self
._coalitions
_list
) > 0 : return self
._coalitions
_list
392 coalition_queue_head
= self
.GetGlobalVariable('coalitions_q')
393 coalition_type
= LazyTarget
.GetTarget().FindFirstType('coalition')
394 coalition_ptr_type
= coalition_type
.GetPointerType()
395 for coal
in IterateLinkageChain(addressof(coalition_queue_head
), coalition_ptr_type
, 'coalitions'):
396 self
._coalitions
_list
.append(coal
)
397 caching
.SaveDynamicCacheData("kern._coalitions_list", self
._coalitions
_list
)
398 return self
._coalitions
_list
400 if name
== 'terminated_tasks' :
401 self
._terminated
_tasks
_list
= caching
.GetDynamicCacheData("kern._terminated_tasks_list", [])
402 if len(self
._terminated
_tasks
_list
) > 0 : return self
._terminated
_tasks
_list
403 task_queue_head
= self
.GetGlobalVariable('terminated_tasks')
404 task_type
= LazyTarget
.GetTarget().FindFirstType('task')
405 task_ptr_type
= task_type
.GetPointerType()
406 for tsk
in IterateQueue(task_queue_head
, task_ptr_type
, 'tasks'):
407 self
._terminated
_tasks
_list
.append(tsk
)
408 caching
.SaveDynamicCacheData("kern._terminated_tasks_list", self
._terminated
_tasks
_list
)
409 return self
._terminated
_tasks
_list
412 self
._allproc
= caching
.GetDynamicCacheData("kern._allproc", [])
413 if len(self
._allproc
) > 0 : return self
._allproc
414 all_proc_head
= self
.GetGlobalVariable('allproc')
415 proc_val
= cast(all_proc_head
.lh_first
, 'proc *')
417 self
._allproc
.append(proc_val
)
418 proc_val
= cast(proc_val
.p_list
.le_next
, 'proc *')
419 caching
.SaveDynamicCacheData("kern._allproc", self
._allproc
)
422 if name
== 'interrupt_stats' :
423 self
._interrupt
_stats
_list
= caching
.GetDynamicCacheData("kern._interrupt_stats_list", [])
424 if len(self
._interrupt
_stats
_list
) > 0 : return self
._interrupt
_stats
_list
425 interrupt_stats_head
= self
.GetGlobalVariable('gInterruptAccountingDataList')
426 interrupt_stats_type
= LazyTarget
.GetTarget().FindFirstType('IOInterruptAccountingData')
427 interrupt_stats_ptr_type
= interrupt_stats_type
.GetPointerType()
428 for interrupt_stats_obj
in IterateQueue(interrupt_stats_head
, interrupt_stats_ptr_type
, 'chain'):
429 self
._interrupt
_stats
_list
.append(interrupt_stats_obj
)
430 caching
.SaveDynamicCacheData("kern._interrupt_stats", self
._interrupt
_stats
_list
)
431 return self
._interrupt
_stats
_list
433 if name
== 'zombprocs' :
434 self
._zombproc
_list
= caching
.GetDynamicCacheData("kern._zombproc_list", [])
435 if len(self
._zombproc
_list
) > 0 : return self
._zombproc
_list
436 zproc_head
= self
.GetGlobalVariable('zombproc')
437 proc_val
= cast(zproc_head
.lh_first
, 'proc *')
439 self
._zombproc
_list
.append(proc_val
)
440 proc_val
= cast(proc_val
.p_list
.le_next
, 'proc *')
441 caching
.SaveDynamicCacheData("kern._zombproc_list", self
._zombproc
_list
)
442 return self
._zombproc
_list
444 if name
== 'version' :
445 self
._version
= caching
.GetStaticCacheData("kern.version", None)
446 if self
._version
!= None : return self
._version
447 self
._version
= str(self
.GetGlobalVariable('version'))
448 caching
.SaveStaticCacheData("kern.version", self
._version
)
452 self
._arch
= caching
.GetStaticCacheData("kern.arch", None)
453 if self
._arch
!= None : return self
._arch
454 arch
= LazyTarget
.GetTarget().triple
.split('-')[0]
455 if arch
in ('armv7', 'armv7s', 'armv7k'):
459 caching
.SaveStaticCacheData("kern.arch", self
._arch
)
462 if name
== 'ptrsize' :
463 self
._ptrsize
= caching
.GetStaticCacheData("kern.ptrsize", None)
464 if self
._ptrsize
!= None : return self
._ptrsize
465 arch
= LazyTarget
.GetTarget().triple
.split('-')[0]
466 if arch
in ('x86_64', 'arm64'):
470 caching
.SaveStaticCacheData("kern.ptrsize", self
._ptrsize
)
473 return object.__getattribute
__(self
, name
)