]> git.saurik.com Git - apple/xnu.git/blame - tools/lldbmacros/userspace.py
xnu-4570.20.62.tar.gz
[apple/xnu.git] / tools / lldbmacros / userspace.py
CommitLineData
39236c6e
A
1from xnu import *
2from utils import *
3from process import *
4from pmap import *
fe8ab488 5import struct
39236c6e
A
6
7def GetBinaryNameForPC(pc_val, user_lib_info = None):
8 """ find the binary in user_lib_info that the passed pc_val falls in range of.
9 params:
fe8ab488 10 pc_val : int - integer form of the pc address
39236c6e
A
11 user_lib_info: [] of [] which hold start, end, binary name
12 returns:
13 str - Name of binary or "unknown" if not found.
14 """
15 retval = "unknown"
16 if not user_lib_info:
17 return retval
18 matches = []
19 for info in user_lib_info:
20 if pc_val >= info[0] and pc_val <= info[1]:
21 matches.append((pc_val - info[0], info[2]))
22 matches.sort()
23 if matches:
24 retval = matches[0][1]
25 return retval
26
27def ShowX86UserStack(thread, user_lib_info = None):
28 """ Display user space stack frame and pc addresses.
29 params:
30 thread: obj referencing thread value
31 returns:
32 Nothing
33 """
34 iss = Cast(thread.machine.iss, 'x86_saved_state_t *')
35 abi = int(iss.flavor)
36 user_ip = 0
37 user_frame = 0
38 user_abi_ret_offset = 0
39 if abi == 0xf:
40 debuglog("User process is 64 bit")
41 user_ip = iss.uss.ss_64.isf.rip
42 user_frame = iss.uss.ss_64.rbp
43 user_abi_ret_offset = 8
fe8ab488 44 user_abi_type = "uint64_t"
39236c6e
A
45 else:
46 debuglog("user process is 32 bit")
47 user_ip = iss.uss.ss_32.eip
48 user_frame = iss.uss.ss_32.ebp
49 user_abi_ret_offset = 4
fe8ab488
A
50 user_abi_type = "uint32_t"
51
39236c6e
A
52 if user_ip == 0:
53 print "This activation does not appear to have a valid user context."
54 return False
55
56 cur_ip = user_ip
57 cur_frame = user_frame
58 debuglog("ip= 0x%x , fr = 0x%x " % (cur_ip, cur_frame))
39236c6e
A
59
60 frameformat = "{0:d} FP: 0x{1:x} PC: 0x{2:x}"
61 if user_lib_info is not None:
62 frameformat = "{0:d} {3: <30s} 0x{2:x}"
63 print frameformat.format(0, cur_frame, cur_ip, GetBinaryNameForPC(cur_ip, user_lib_info))
64
65 print kern.Symbolicate(cur_ip)
fe8ab488
A
66
67 frameno = 0
68 while True:
69 frameno = frameno + 1
70 frame = GetUserDataAsString(thread.task, unsigned(cur_frame), user_abi_ret_offset*2)
71 cur_ip = _ExtractDataFromString(frame, user_abi_ret_offset, user_abi_type)
72 cur_frame = _ExtractDataFromString(frame, 0, user_abi_type)
73 if not cur_frame or cur_frame == 0x0000000800000008:
74 break
75 print frameformat.format(frameno, cur_frame, cur_ip, GetBinaryNameForPC(cur_ip, user_lib_info))
76 print kern.Symbolicate(cur_ip)
39236c6e
A
77 return
78
79def _PrintARMUserStack(task, cur_pc, cur_fp, framesize, frametype, frameformat, user_lib_info=None):
80 if cur_pc == 0:
81 "No valid user context for this activation."
82 return
83 frameno = 0
84 print frameformat.format(frameno, cur_fp, cur_pc, GetBinaryNameForPC(cur_pc, user_lib_info))
85 while True:
86 frameno = frameno + 1
87 frame = GetUserDataAsString(task, cur_fp, framesize)
88 cur_fp = _ExtractDataFromString(frame, 0, frametype)
89 cur_pc = _ExtractDataFromString(frame, (framesize / 2), frametype)
90 if not cur_fp:
91 break
92 print frameformat.format(frameno, cur_fp, cur_pc, GetBinaryNameForPC(cur_pc, user_lib_info))
93
94def ShowARMUserStack(thread, user_lib_info = None):
95 cur_pc = unsigned(thread.machine.PcbData.pc)
96 cur_fp = unsigned(thread.machine.PcbData.r[7])
97 frameformat = "{0:>2d} FP: 0x{1:x} PC: 0x{2:x}"
98 if user_lib_info is not None:
99 frameformat = "{0:>2d} {3: <30s} 0x{2:0>8x}"
100 framesize = 8
101 frametype = "uint32_t"
102 _PrintARMUserStack(thread.task, cur_pc, cur_fp, framesize, frametype, frameformat, user_lib_info=user_lib_info)
103
fe8ab488
A
104def ShowARM64UserStack(thread, user_lib_info = None):
105 SAVED_STATE_FLAVOR_ARM=20
106 SAVED_STATE_FLAVOR_ARM64=21
107 upcb = thread.machine.upcb
108 flavor = upcb.ash.flavor
109 frameformat = "{0:>2d} FP: 0x{1:x} PC: 0x{2:x}"
110 if flavor == SAVED_STATE_FLAVOR_ARM64:
111 cur_pc = unsigned(upcb.uss.ss_64.pc)
112 cur_fp = unsigned(upcb.uss.ss_64.fp)
113 if user_lib_info is not None:
114 frameformat = "{0:>2d} {3: <30s} 0x{2:x}"
115 framesize = 16
116 frametype = "uint64_t"
117 elif flavor == SAVED_STATE_FLAVOR_ARM:
118 cur_pc = unsigned(upcb.uss.ss_32.pc)
119 cur_fp = unsigned(upcb.uss.ss_32.r[7])
120 if user_lib_info is not None:
121 frameformat = "{0:>2d}: {3: <30s} 0x{2:x}"
122 framesize = 8
123 frametype = "uint32_t"
124 else:
125 raise RuntimeError("Thread {0} has an invalid flavor {1}".format(unsigned(thread), flavor))
126
127 _PrintARMUserStack(thread.task, cur_pc, cur_fp, framesize, frametype, frameformat, user_lib_info=user_lib_info)
128
39236c6e
A
129
130@lldb_command('showthreaduserstack')
131def ShowThreadUserStack(cmd_args=None):
132 """ Show user stack for a given thread.
133 Syntax: (lldb) showthreaduserstack <thread_ptr>
134 """
135 if not cmd_args:
136 raise ArgumentError("Insufficient arguments")
137
138 thread = kern.GetValueFromAddress(ArgumentStringToInt(cmd_args[0]), 'thread *')
139 if kern.arch == "x86_64":
140 ShowX86UserStack(thread)
141 elif kern.arch == "arm":
142 ShowARMUserStack(thread)
5ba3f43e 143 elif kern.arch.startswith("arm64"):
fe8ab488
A
144 ShowARM64UserStack(thread)
145 return True
146
3e170ce0 147@lldb_command('printuserdata','XO:')
fe8ab488
A
148def PrintUserspaceData(cmd_args=None, cmd_options={}):
149 """ Read userspace data for given task and print based on format provided.
150 Syntax: (lldb) printuserdata <task_t> <uspace_address> <format_specifier>
151 params:
152 <task_t> : pointer to task
153 <uspace_address> : address to user space memory
154 <format_specifier> : String representation for processing the data and printing it.
3e170ce0
A
155 e.g Q -> unsigned long long, q -> long long, I -> unsigned int, i -> int
156 10i -> 10 ints, 20s -> 20 character string, s -> null terminated string
157 See: https://docs.python.org/2/library/struct.html#format-characters
fe8ab488
A
158 options:
159 -X : print all values in hex.
3e170ce0 160 -O <file path>: Save data to file
fe8ab488
A
161 """
162
163 if not cmd_args or len(cmd_args) < 3:
164 raise ArgumentError("Insufficient arguments")
165 task = kern.GetValueFromAddress(cmd_args[0], 'task *')
166 uspace_addr = ArgumentStringToInt(cmd_args[1])
167 format_specifier_str = cmd_args[2]
168 user_data_len = 0
3e170ce0
A
169 if format_specifier_str == "s":
170 print "0x%x: " % uspace_addr + GetUserspaceString(task, uspace_addr)
171 return True
172
fe8ab488
A
173 try:
174 user_data_len = struct.calcsize(format_specifier_str)
175 except Exception, e:
176 raise ArgumentError("Invalid format specifier provided.")
177
178 user_data_string = GetUserDataAsString(task, uspace_addr, user_data_len)
179 if not user_data_string:
180 print "Could not read any data from userspace address."
181 return False
3e170ce0
A
182 if "-O" in cmd_options:
183 fh = open(cmd_options["-O"],"w")
184 fh.write(user_data_string)
185 fh.close()
186 print "Written %d bytes to %s." % (user_data_len, cmd_options['-O'])
187 return True
fe8ab488 188 upacked_data = struct.unpack(format_specifier_str, user_data_string)
3e170ce0 189 element_size = user_data_len / len(upacked_data)
fe8ab488
A
190 for i in range(len(upacked_data)):
191 if "-X" in cmd_options:
3e170ce0 192 print "0x%x: " % (uspace_addr + i*element_size) + hex(upacked_data[i])
fe8ab488 193 else:
3e170ce0 194 print "0x%x: " % (uspace_addr + i*element_size) + str(upacked_data[i])
fe8ab488 195
39236c6e
A
196 return True
197
3e170ce0
A
198
199@lldb_command('showtaskuserargs')
200def ShowTaskUserArgs(cmd_args=None, cmd_options={}):
201 """ Read the process argv, env, and apple strings from the user stack
202 Syntax: (lldb) showtaskuserargs <task_t>
203 params:
204 <task_t> : pointer to task
205 """
206 if not cmd_args or len(cmd_args) != 1:
207 raise ArgumentError("Insufficient arguments")
208
209 task = kern.GetValueFromAddress(cmd_args[0], 'task *')
210 proc = Cast(task.bsd_info, 'proc *')
211
212 format_string = "Q" if kern.ptrsize == 8 else "I"
213
214 string_area_size = proc.p_argslen
215 string_area_addr = proc.user_stack - string_area_size
216
217 string_area = GetUserDataAsString(task, string_area_addr, string_area_size)
218 if not string_area:
219 print "Could not read any data from userspace address."
220 return False
221
222 i = 0
223 pos = string_area_addr - kern.ptrsize
224
225 for name in ["apple", "env", "argv"] :
226 while True:
227 if name == "argv" :
228 if i == proc.p_argc:
229 break
230 i += 1
231
232 pos -= kern.ptrsize
233
234 user_data_string = GetUserDataAsString(task, pos, kern.ptrsize)
235 ptr = struct.unpack(format_string, user_data_string)[0]
236
237 if ptr == 0:
238 break
239
240 if string_area_addr <= ptr and ptr < string_area_addr+string_area_size :
241 string_offset = ptr - string_area_addr
242 string = string_area[string_offset:];
243 else:
244 string = GetUserspaceString(task, ptr)
245
246 print name + "[]: " + string
247
248 return True
249
d190cdc3 250def ShowTaskUserStacks(task):
39236c6e
A
251 #print GetTaskSummary.header + " " + GetProcSummary.header
252 pval = Cast(task.bsd_info, 'proc *')
253 #print GetTaskSummary(task) + " " + GetProcSummary(pval) + "\n \n"
254 crash_report_format_string = """\
d190cdc3 255Process: {pname:s} [{pid:d}]
39236c6e 256Path: {path: <50s}
fe8ab488 257Identifier: {pname: <30s}
39236c6e
A
258Version: ??? (???)
259Code Type: {parch: <20s}
d190cdc3 260Parent Process: {ppname:s} [{ppid:d}]
39236c6e
A
261
262Date/Time: {timest:s}.000 -0800
263OS Version: {osversion: <20s}
264Report Version: 8
265
266Exception Type: n/a
267Exception Codes: n/a
268Crashed Thread: 0
269
270Application Specific Information:
271Synthetic crash log generated from Kernel userstacks
272
273"""
274 user_lib_rex = re.compile("([0-9a-fx]+)\s-\s([0-9a-fx]+)\s+(.*?)\s", re.IGNORECASE|re.MULTILINE)
275 from datetime import datetime
5ba3f43e
A
276 if pval:
277 ts = datetime.fromtimestamp(int(pval.p_start.tv_sec))
278 date_string = ts.strftime('%Y-%m-%d %H:%M:%S')
279 else:
280 date_string = "none"
281 is_64 = True
282 if pval and (pval.p_flag & 0x4) == 0 :
283 is_64 = False
fe8ab488 284
39236c6e
A
285 parch_s = ""
286 if kern.arch == "x86_64" or kern.arch == "i386":
287 osversion = "Mac OS X 10.8"
288 parch_s = "I386 (32 bit)"
289 if is_64:
290 parch_s = "X86-64 (Native)"
291 else:
292 parch_s = kern.arch
293 osversion = "iOS"
294 osversion += " ({:s})".format(kern.globals.osversion)
5ba3f43e
A
295 if pval:
296 pid = pval.p_pid
297 pname = pval.p_comm
298 path = pval.p_comm
299 ppid = pval.p_ppid
300 else:
301 pid = 0
302 pname = "unknown"
303 path = "unknown"
304 ppid = 0
305
306 print crash_report_format_string.format(pid = pid,
307 pname = pname,
308 path = path,
309 ppid = ppid,
310 ppname = GetProcNameForPid(ppid),
39236c6e
A
311 timest = date_string,
312 parch = parch_s,
313 osversion = osversion
39236c6e
A
314 )
315 print "Binary Images:"
316 ShowTaskUserLibraries([hex(task)])
317 usertask_lib_info = [] # will host [startaddr, endaddr, lib_name] entries
318 for entry in ShowTaskUserLibraries.found_images:
319 #print "processing line %s" % line
320 arr = user_lib_rex.findall(entry[3])
321 #print "%r" % arr
322 if len(arr) == 0 :
323 continue
324 usertask_lib_info.append([int(arr[0][0],16), int(arr[0][1],16), str(arr[0][2]).strip()])
325
326 printthread_user_stack_ptr = ShowX86UserStack
327 if kern.arch == "arm":
328 printthread_user_stack_ptr = ShowARMUserStack
5ba3f43e 329 elif kern.arch.startswith("arm64"):
fe8ab488
A
330 printthread_user_stack_ptr = ShowARM64UserStack
331
39236c6e
A
332 counter = 0
333 for thval in IterateQueue(task.threads, 'thread *', 'task_threads'):
334 print "\nThread {0:d} name:0x{1:x}\nThread {0:d}:".format(counter, thval)
335 counter += 1
336 try:
337 printthread_user_stack_ptr(thval, usertask_lib_info)
338 except Exception as exc_err:
339 print "Failed to show user stack for thread 0x{0:x}".format(thval)
340 if config['debug']:
341 raise exc_err
342 else:
343 print "Enable debugging ('(lldb) xnudebug debug') to see detailed trace."
344 return
345
d190cdc3
A
346@lldb_command('showtaskuserstacks', "P:F:")
347def ShowTaskUserStacksCmdHelper(cmd_args=None, cmd_options={}):
348 """ Print out the user stack for each thread in a task, followed by the user libraries.
349 Syntax: (lldb) showtaskuserstacks <task_t>
350 or: (lldb) showtaskuserstacks -P <pid>
351 or: (lldb) showtaskuserstacks -F <task_name>
352 The format is compatible with CrashTracer. You can also use the speedtracer plugin as follows
353 (lldb) showtaskuserstacks <task_t> -p speedtracer
354
355 Note: the address ranges are approximations. Also the list may not be completely accurate. This command expects memory read failures
356 and hence will skip a library if unable to read information. Please use your good judgement and not take the output as accurate
357 """
358 task_list = []
359 if "-F" in cmd_options:
360 task_list = FindTasksByName(cmd_options["-F"])
361 elif "-P" in cmd_options:
362 pidval = ArgumentStringToInt(cmd_options["-P"])
363 for t in kern.tasks:
364 pval = Cast(t.bsd_info, 'proc *')
365 if pval and pval.p_pid == pidval:
366 task_list.append(t)
367 break
368 elif cmd_args:
369 t = kern.GetValueFromAddress(cmd_args[0], 'task *')
370 task_list.append(t)
371 else:
372 raise ArgumentError("Insufficient arguments")
373
374 for task in task_list:
375 ShowTaskUserStacks(task)
39236c6e
A
376
377def GetUserDataAsString(task, addr, size):
378 """ Get data from task's address space as a string of bytes
379 params:
380 task: task object from which to extract information
381 addr: int - start address to get data from.
382 size: int - no of bytes to read.
383 returns:
384 str - a stream of bytes. Empty string if read fails.
385 """
386 err = lldb.SBError()
387 if GetConnectionProtocol() == "kdp":
388 kdp_pmap_addr = unsigned(addressof(kern.globals.kdp_pmap))
389 if not WriteInt64ToMemoryAddress(unsigned(task.map.pmap), kdp_pmap_addr):
390 debuglog("Failed to write in kdp_pmap from GetUserDataAsString.")
391 return ""
392 content = LazyTarget.GetProcess().ReadMemory(addr, size, err)
393 if not err.Success():
394 debuglog("Failed to read process memory. Error: " + err.description)
395 return ""
396 if not WriteInt64ToMemoryAddress(0, kdp_pmap_addr):
397 debuglog("Failed to reset in kdp_pmap from GetUserDataAsString.")
398 return ""
5ba3f43e 399 elif (kern.arch == 'x86_64' or kern.arch.startswith('arm')) and (long(size) < (2 * kern.globals.page_size)):
39236c6e
A
400 # Without the benefit of a KDP stub on the target, try to
401 # find the user task's physical mapping and memcpy the data.
402 # If it straddles a page boundary, copy in two passes
403 range1_addr = long(addr)
404 range1_size = long(size)
405 if kern.StraddlesPage(range1_addr, range1_size):
406 range2_addr = long(kern.TruncPage(range1_addr + range1_size))
407 range2_size = long(range1_addr + range1_size - range2_addr)
408 range1_size = long(range2_addr - range1_addr)
409 else:
410 range2_addr = 0
411 range2_size = 0
412 range2_in_kva = 0
413
414 paddr_range1 = PmapWalk(task.map.pmap, range1_addr, vSILENT)
415 if not paddr_range1:
416 debuglog("Not mapped task 0x{:x} address 0x{:x}".format(task, addr))
417 return ""
418
419 range1_in_kva = kern.PhysToKernelVirt(paddr_range1)
420 content = LazyTarget.GetProcess().ReadMemory(range1_in_kva, range1_size, err)
421 if not err.Success():
422 raise RuntimeError("Failed to read process memory. Error: " + err.description)
423
424 if range2_addr:
425 paddr_range2 = PmapWalk(task.map.pmap, range2_addr, vSILENT)
426 if not paddr_range2:
427 debuglog("Not mapped task 0x{:x} address 0x{:x}".format(task, addr))
428 return ""
429 range2_in_kva = kern.PhysToKernelVirt(paddr_range2)
fe8ab488 430 content += LazyTarget.GetProcess().ReadMemory(range2_in_kva, range2_size, err)
39236c6e
A
431 if not err.Success():
432 raise RuntimeError("Failed to read process memory. Error: " + err.description)
433 else:
434 raise NotImplementedError("GetUserDataAsString does not support this configuration")
435
436 return content
437
438def _ExtractDataFromString(strdata, offset, data_type, length=0):
439 """ Extract specific data from string buffer
440 params:
441 strdata: str - string data give from GetUserDataAsString
442 offset: int - 0 based offset into the data.
443 data_type: str - defines what type to be read as. Supported values are:
444 'uint64_t', 'uint32_t', 'string'
445 length: int - used when data_type=='string'
446 returns
447 None - if extraction failed.
448 obj - based on what is requested in data_type
449 """
450 unpack_str = "s"
451 if data_type == 'uint64_t':
452 length = 8
453 unpack_str = "Q"
454 elif data_type == "uint32_t":
455 length = 4
456 unpack_str = "I"
457 else:
458 unpack_str= "%ds" % length
459
460 data_len = len(strdata)
461 if offset > data_len or (offset + length) > data_len or offset < 0:
462 debuglog("Invalid arguments to _ExtractDataFromString.")
463 return 0
464 return struct.unpack(unpack_str, strdata[offset:(offset + length)])[0]
465
3e170ce0 466def GetUserspaceString(task, string_address):
fe8ab488 467 """ Maps 32 bytes at a time and packs as string
39236c6e
A
468 params:
469 task: obj - referencing task to read data from
3e170ce0 470 string_address: int - address where the image path is stored
39236c6e
A
471 returns:
472 str - string path of the file. "" if failed to read.
473 """
474 done = False
475 retval = ""
476
3e170ce0 477 if string_address == 0:
39236c6e
A
478 done = True
479
480 while not done:
3e170ce0
A
481 str_data = GetUserDataAsString(task, string_address, 32)
482 if len(str_data) == 0:
39236c6e
A
483 break
484 i = 0
485 while i < 32:
3e170ce0
A
486 if ord(str_data[i]):
487 retval += str_data[i]
39236c6e
A
488 else:
489 break
490 i += 1
491 if i < 32:
492 done = True
493 else:
3e170ce0 494 string_address += 32
39236c6e
A
495 return retval
496
497def GetImageInfo(task, mh_image_address, mh_path_address, approx_end_address=None):
498 """ Print user library informaiton.
499 params:
500 task : obj referencing the task for which Image info printed
501 mh_image_address : int - address which has image info
502 mh_path_address : int - address which holds path name string
503 approx_end_address: int - address which lldbmacros think is end address.
504 returns:
505 str - string representing image info. "" if failure to read data.
506 """
507 if approx_end_address:
508 image_end_load_address = int(approx_end_address) -1
509 else:
510 image_end_load_address = int(mh_image_address) + 0xffffffff
511
512 print_format = "0x{0:x} - 0x{1:x} {2: <50s} (??? - ???) <{3: <36s}> {4: <50s}"
513 # 32 bytes enough for mach_header/mach_header_64
514 mh_data = GetUserDataAsString(task, mh_image_address, 32)
515 if len(mh_data) == 0:
516 debuglog("unable to get userdata for task 0x{:x} img_addr 0x{:x} path_address 0x{:x}".format(
517 task, mh_image_address, mh_path_address))
518 return ""
519 mh_magic = _ExtractDataFromString(mh_data, (4 * 0), "uint32_t")
520 mh_cputype = _ExtractDataFromString(mh_data,(4 * 1), "uint32_t")
521 mh_cpusubtype = _ExtractDataFromString(mh_data,(4 * 2), "uint32_t")
522 mh_filetype = _ExtractDataFromString(mh_data,(4 * 3), "uint32_t")
523 mh_ncmds = _ExtractDataFromString(mh_data,(4 * 4), "uint32_t")
524 mh_sizeofcmds = _ExtractDataFromString(mh_data,(4 * 5), "uint32_t")
525 mh_flags = _ExtractDataFromString(mh_data,(4 * 6), "uint32_t")
526
527 if mh_magic == 0xfeedfacf:
528 mh_64 = True
529 lc_address = mh_image_address + 32
530 else:
531 mh_64 = False
532 lc_address = mh_image_address + 28
533
534 lc_idx = 0
535 uuid_data = 0
536 found_uuid_data = False
537 retval = None
538 while lc_idx < mh_ncmds:
539 # 24 bytes is the size of uuid_command
fe8ab488 540 lcmd_data = GetUserDataAsString(task, lc_address, 24)
39236c6e
A
541 lc_cmd = _ExtractDataFromString(lcmd_data, 4 * 0, "uint32_t")
542 lc_cmd_size = _ExtractDataFromString(lcmd_data, 4 * 1, "uint32_t")
543 lc_data = _ExtractDataFromString(lcmd_data, 4*2, "string", 16)
544
545 uuid_out_string = ""
546 path_out_string = ""
547
548 if lc_cmd == 0x1b:
549 # need to print the uuid now.
550 uuid_data = [ord(x) for x in lc_data]
551 found_uuid_data = True
fe8ab488 552 uuid_out_string = "{a[0]:02X}{a[1]:02X}{a[2]:02X}{a[3]:02X}-{a[4]:02X}{a[5]:02X}-{a[6]:02X}{a[7]:02X}-{a[8]:02X}{a[9]:02X}-{a[10]:02X}{a[11]:02X}{a[12]:02X}{a[13]:02X}{a[14]:02X}{a[15]:02X}".format(a=uuid_data)
39236c6e 553 #also print image path
3e170ce0 554 path_out_string = GetUserspaceString(task, mh_path_address)
39236c6e
A
555 path_base_name = path_out_string.split("/")[-1]
556 retval = print_format.format(mh_image_address, image_end_load_address, path_base_name, uuid_out_string, path_out_string)
557 elif lc_cmd == 0xe:
558 ShowTaskUserLibraries.exec_load_path = lc_address + _ExtractDataFromString(lcmd_data, 4*2, "uint32_t")
fe8ab488 559 debuglog("Found load command to be 0xe for address %s" % hex(ShowTaskUserLibraries.exec_load_path))
39236c6e
A
560 lc_address = lc_address + lc_cmd_size
561 lc_idx += 1
562
563 if not found_uuid_data:
3e170ce0 564 path_out_string = GetUserspaceString(task, mh_path_address)
39236c6e
A
565 path_base_name = path_out_string.split("/")[-1]
566 uuid_out_string = ""
567
568 retval = print_format.format(mh_image_address, image_end_load_address, path_base_name, uuid_out_string, path_out_string)
569 return retval
570
571@static_var("found_images", []) # holds entries of format (startaddr, endaddr, image_path_addr, infostring)
572@static_var("exec_load_path", 0)
573@lldb_command("showtaskuserlibraries")
574def ShowTaskUserLibraries(cmd_args=None):
575 """ Show binary images known by dyld in target task
576 For a given user task, inspect the dyld shared library state and print information about all Mach-O images.
577 Syntax: (lldb)showtaskuserlibraries <task_t>
578 Note: the address ranges are approximations. Also the list may not be completely accurate. This command expects memory read failures
579 and hence will skip a library if unable to read information. Please use your good judgement and not take the output as accurate
580 """
581 if not cmd_args:
582 raise ArgumentError("Insufficient arguments")
583
584 #reset the found_images array
585 ShowTaskUserLibraries.found_images = []
586
587 task = kern.GetValueFromAddress(cmd_args[0], 'task_t')
588 is_task_64 = int(task.t_flags) & 0x1
589 dyld_all_image_infos_address = unsigned(task.all_image_info_addr)
fe8ab488
A
590 debuglog("dyld_all_image_infos_address = %s" % hex(dyld_all_image_infos_address))
591
39236c6e
A
592 cur_data_offset = 0
593 if dyld_all_image_infos_address == 0:
594 print "No dyld shared library information available for task"
595 return False
fe8ab488
A
596
597 debuglog("Extracting version information.")
39236c6e
A
598 vers_info_data = GetUserDataAsString(task, dyld_all_image_infos_address, 112)
599 version = _ExtractDataFromString(vers_info_data, cur_data_offset, "uint32_t")
600 cur_data_offset += 4
fe8ab488 601 if version > 14:
39236c6e
A
602 print "Unknown dyld all_image_infos version number %d" % version
603 image_info_count = _ExtractDataFromString(vers_info_data, cur_data_offset, "uint32_t")
fe8ab488
A
604 debuglog("version = %d count = %d is_task_64 = %s" % (version, image_info_count, repr(is_task_64)))
605
39236c6e
A
606 ShowTaskUserLibraries.exec_load_path = 0
607 if is_task_64:
608 image_info_size = 24
609 image_info_array_address = _ExtractDataFromString(vers_info_data, 8, "uint64_t")
610 dyld_load_address = _ExtractDataFromString(vers_info_data, 8*4, "uint64_t")
611 dyld_all_image_infos_address_from_struct = _ExtractDataFromString(vers_info_data, 8*13, "uint64_t")
612 else:
613 image_info_size = 12
614 image_info_array_address = _ExtractDataFromString(vers_info_data, 4*2, "uint32_t")
615 dyld_load_address = _ExtractDataFromString(vers_info_data, 4*5, "uint32_t")
616 dyld_all_image_infos_address_from_struct = _ExtractDataFromString(vers_info_data, 4*14, "uint32_t")
617 # Account for ASLR slide before dyld can fix the structure
618 dyld_load_address = dyld_load_address + (dyld_all_image_infos_address - dyld_all_image_infos_address_from_struct)
619
620 i = 0
621 image_info_list = []
622 while i < image_info_count:
623 image_info_address = image_info_array_address + i * image_info_size
fe8ab488 624 debuglog("i = %d, image_info_address = %s, image_info_size = %d" % (i, hex(image_info_address), image_info_size))
39236c6e
A
625 n_im_info_addr = None
626 img_data = ""
627 try:
628 img_data = GetUserDataAsString(task, image_info_address, image_info_size)
629 except Exception, e:
630 debuglog("Failed to read user data for task 0x{:x} addr 0x{:x}, exception {:s}".format(task, image_info_address, str(e)))
631 pass
fe8ab488 632
39236c6e
A
633 if is_task_64:
634 image_info_addr = _ExtractDataFromString(img_data, 0, "uint64_t")
635 image_info_path = _ExtractDataFromString(img_data, 8, "uint64_t")
636 else:
637 image_info_addr = _ExtractDataFromString(img_data, 0, "uint32_t")
638 image_info_path = _ExtractDataFromString(img_data, 4, "uint32_t")
fe8ab488 639
39236c6e 640 if image_info_addr :
fe8ab488 641 debuglog("Found image: image_info_addr = %s, image_info_path= %s" % (hex(image_info_addr), hex(image_info_path)))
39236c6e
A
642 image_info_list.append((image_info_addr, image_info_path))
643 i += 1
fe8ab488 644
39236c6e 645 image_info_list.sort()
fe8ab488
A
646 num_images_found = len(image_info_list)
647
39236c6e
A
648 for ii in range(num_images_found):
649 n_im_info_addr = dyld_load_address
650 if ii + 1 < num_images_found:
651 n_im_info_addr = image_info_list[ii+1][0]
652
653 image_info_addr = image_info_list[ii][0]
654 image_info_path = image_info_list[ii][1]
655 try:
656 image_print_s = GetImageInfo(task, image_info_addr, image_info_path, approx_end_address=n_im_info_addr)
657 if len(image_print_s) > 0:
658 print image_print_s
659 ShowTaskUserLibraries.found_images.append((image_info_addr, n_im_info_addr, image_info_path, image_print_s))
660 else:
661 debuglog("Failed to print image info for task 0x{:x} image_info 0x{:x}".format(task, image_info_addr))
662 except Exception,e:
663 if config['debug']:
664 raise e
fe8ab488
A
665
666 # load_path might get set when the main executable is processed.
667 if ShowTaskUserLibraries.exec_load_path != 0:
668 debuglog("main executable load_path is set.")
39236c6e
A
669 image_print_s = GetImageInfo(task, dyld_load_address, ShowTaskUserLibraries.exec_load_path)
670 if len(image_print_s) > 0:
671 print image_print_s
672 ShowTaskUserLibraries.found_images.append((dyld_load_address, dyld_load_address + 0xffffffff,
673 ShowTaskUserLibraries.exec_load_path, image_print_s))
674 else:
675 debuglog("Failed to print image for main executable for task 0x{:x} dyld_load_addr 0x{:x}".format(task, dyld_load_address))
fe8ab488
A
676 else:
677 debuglog("Falling back to vm entry method for finding executable load address")
678 print "# NOTE: Failed to find executable using all_image_infos. Using fuzzy match to find best possible load address for executable."
679 ShowTaskLoadInfo([cmd_args[0]])
39236c6e
A
680 return
681
fe8ab488
A
682@lldb_command("showtaskuserdyldinfo")
683def ShowTaskUserDyldInfo(cmd_args=None):
684 """ Inspect the dyld global info for the given user task & print out all fields including error messages
685 Syntax: (lldb)showtaskuserdyldinfo <task_t>
686 """
687 if cmd_args == None or len(cmd_args) < 1:
688 print "No arguments passed"
689 print ShowTaskUserDyldInfo.__doc__.strip()
690 return
691
692 out_str = ""
693 task = kern.GetValueFromAddress(cmd_args[0], 'task_t')
694 is_task_64 = int(task.t_flags) & 0x1
695 dyld_all_image_infos_address = unsigned(task.all_image_info_addr)
696 if dyld_all_image_infos_address == 0:
697 print "No dyld shared library information available for task"
698 return False
699 vers_info_data = GetUserDataAsString(task, dyld_all_image_infos_address, 112)
700 dyld_all_image_infos_version = _ExtractDataFromString(vers_info_data, 0, "uint32_t")
701 if dyld_all_image_infos_version > 14:
702 out_str += "Unknown dyld all_image_infos version number %d" % dyld_all_image_infos_version
703
704 # Find fields by byte offset. We assume at least version 9 is supported
705 if is_task_64:
706 dyld_all_image_infos_infoArrayCount = _ExtractDataFromString(vers_info_data, 4, "uint32_t")
707 dyld_all_image_infos_infoArray = _ExtractDataFromString(vers_info_data, 8, "uint64_t")
708 dyld_all_image_infos_notification = _ExtractDataFromString(vers_info_data, 16, "uint64_t")
709 dyld_all_image_infos_processDetachedFromSharedRegion = _ExtractDataFromString(vers_info_data, 24, "string")
710 dyld_all_image_infos_libSystemInitialized = _ExtractDataFromString(vers_info_data, 25, "string")
711 dyld_all_image_infos_dyldImageLoadAddress = _ExtractDataFromString(vers_info_data, 32, "uint64_t")
712 dyld_all_image_infos_jitInfo = _ExtractDataFromString(vers_info_data, 40, "uint64_t")
713 dyld_all_image_infos_dyldVersion = _ExtractDataFromString(vers_info_data, 48, "uint64_t")
714 dyld_all_image_infos_errorMessage = _ExtractDataFromString(vers_info_data, 56, "uint64_t")
715 dyld_all_image_infos_terminationFlags = _ExtractDataFromString(vers_info_data, 64, "uint64_t")
716 dyld_all_image_infos_coreSymbolicationShmPage = _ExtractDataFromString(vers_info_data, 72, "uint64_t")
717 dyld_all_image_infos_systemOrderFlag = _ExtractDataFromString(vers_info_data, 80, "uint64_t")
718 dyld_all_image_infos_uuidArrayCount = _ExtractDataFromString(vers_info_data, 88, "uint64_t")
719 dyld_all_image_infos_uuidArray = _ExtractDataFromString(vers_info_data, 96, "uint64_t")
720 dyld_all_image_infos_dyldAllImageInfosAddress = _ExtractDataFromString(vers_info_data, 104, "uint64_t")
721 else:
722 dyld_all_image_infos_infoArrayCount = _ExtractDataFromString(vers_info_data, 4, "uint32_t")
723 dyld_all_image_infos_infoArray = _ExtractDataFromString(vers_info_data, 8, "uint32_t")
724 dyld_all_image_infos_notification = _ExtractDataFromString(vers_info_data, 12, "uint32_t")
725 dyld_all_image_infos_processDetachedFromSharedRegion = _ExtractDataFromString(vers_info_data, 16, "string")
726 dyld_all_image_infos_libSystemInitialized = _ExtractDataFromString(vers_info_data, 17, "string")
727 dyld_all_image_infos_dyldImageLoadAddress = _ExtractDataFromString(vers_info_data, 20, "uint32_t")
728 dyld_all_image_infos_jitInfo = _ExtractDataFromString(vers_info_data, 24, "uint32_t")
729 dyld_all_image_infos_dyldVersion = _ExtractDataFromString(vers_info_data, 28, "uint32_t")
730 dyld_all_image_infos_errorMessage = _ExtractDataFromString(vers_info_data, 32, "uint32_t")
731 dyld_all_image_infos_terminationFlags = _ExtractDataFromString(vers_info_data, 36, "uint32_t")
732 dyld_all_image_infos_coreSymbolicationShmPage = _ExtractDataFromString(vers_info_data, 40, "uint32_t")
733 dyld_all_image_infos_systemOrderFlag = _ExtractDataFromString(vers_info_data, 44, "uint32_t")
734 dyld_all_image_infos_uuidArrayCount = _ExtractDataFromString(vers_info_data, 48, "uint32_t")
735 dyld_all_image_infos_uuidArray = _ExtractDataFromString(vers_info_data, 52, "uint32_t")
736 dyld_all_image_infos_dyldAllImageInfosAddress = _ExtractDataFromString(vers_info_data, 56, "uint32_t")
737
738 dyld_all_imfo_infos_slide = (dyld_all_image_infos_address - dyld_all_image_infos_dyldAllImageInfosAddress)
739 dyld_all_image_infos_dyldVersion_postslide = (dyld_all_image_infos_dyldVersion + dyld_all_imfo_infos_slide)
740
3e170ce0 741 path_out = GetUserspaceString(task, dyld_all_image_infos_dyldVersion_postslide)
fe8ab488
A
742 out_str += "[dyld-{:s}]\n".format(path_out)
743 out_str += "version \t\t\t\t: {:d}\n".format(dyld_all_image_infos_version)
744 out_str += "infoArrayCount \t\t\t\t: {:d}\n".format(dyld_all_image_infos_infoArrayCount)
745 out_str += "infoArray \t\t\t\t: {:#x}\n".format(dyld_all_image_infos_infoArray)
746 out_str += "notification \t\t\t\t: {:#x}\n".format(dyld_all_image_infos_notification)
747
748 out_str += "processDetachedFromSharedRegion \t: "
749 if dyld_all_image_infos_processDetachedFromSharedRegion != "":
750 out_str += "TRUE\n".format(dyld_all_image_infos_processDetachedFromSharedRegion)
751 else:
752 out_str += "FALSE\n"
753
754 out_str += "libSystemInitialized \t\t\t: "
755 if dyld_all_image_infos_libSystemInitialized != "":
756 out_str += "TRUE\n".format(dyld_all_image_infos_libSystemInitialized)
757 else:
758 out_str += "FALSE\n"
759
760 out_str += "dyldImageLoadAddress \t\t\t: {:#x}\n".format(dyld_all_image_infos_dyldImageLoadAddress)
761 out_str += "jitInfo \t\t\t\t: {:#x}\n".format(dyld_all_image_infos_jitInfo)
762 out_str += "\ndyldVersion \t\t\t\t: {:#x}".format(dyld_all_image_infos_dyldVersion)
763 if (dyld_all_imfo_infos_slide != 0):
764 out_str += " (currently {:#x})\n".format(dyld_all_image_infos_dyldVersion_postslide)
765 else:
766 out_str += "\n"
767
768 out_str += "errorMessage \t\t\t\t: {:#x}\n".format(dyld_all_image_infos_errorMessage)
769 if dyld_all_image_infos_errorMessage != 0:
3e170ce0 770 out_str += GetUserspaceString(task, dyld_all_image_infos_errorMessage)
fe8ab488
A
771
772 out_str += "terminationFlags \t\t\t: {:#x}\n".format(dyld_all_image_infos_terminationFlags)
773 out_str += "coreSymbolicationShmPage \t\t: {:#x}\n".format(dyld_all_image_infos_coreSymbolicationShmPage)
774 out_str += "systemOrderFlag \t\t\t: {:#x}\n".format(dyld_all_image_infos_systemOrderFlag)
775 out_str += "uuidArrayCount \t\t\t\t: {:#x}\n".format(dyld_all_image_infos_uuidArrayCount)
776 out_str += "uuidArray \t\t\t\t: {:#x}\n".format(dyld_all_image_infos_uuidArray)
777 out_str += "dyldAllImageInfosAddress \t\t: {:#x}".format(dyld_all_image_infos_dyldAllImageInfosAddress)
778 if (dyld_all_imfo_infos_slide != 0):
779 out_str += " (currently {:#x})\n".format(dyld_all_image_infos_address)
780 else:
781 out_str += "\n"
782
783 if is_task_64:
784 dyld_all_image_infos_address = dyld_all_image_infos_address + 112
785 dyld_all_image_infos_v10 = GetUserDataAsString(task, dyld_all_image_infos_address, 64)
786 dyld_all_image_infos_initialImageCount = _ExtractDataFromString(dyld_all_image_infos_v10, 112-112, "uint64_t")
787 dyld_all_image_infos_errorKind = _ExtractDataFromString(dyld_all_image_infos_v10, 120-112, "uint64_t")
788 dyld_all_image_infos_errorClientOfDylibPath = _ExtractDataFromString(dyld_all_image_infos_v10, 128-112, "uint64_t")
789 dyld_all_image_infos_errorTargetDylibPath = _ExtractDataFromString(dyld_all_image_infos_v10, 136-112, "uint64_t")
790 dyld_all_image_infos_errorSymbol = _ExtractDataFromString(dyld_all_image_infos_v10, 144-112, "uint64_t")
791 dyld_all_image_infos_sharedCacheSlide = _ExtractDataFromString(dyld_all_image_infos_v10, 152-112, "uint64_t")
792 dyld_all_image_infos_sharedCacheUUID = _ExtractDataFromString(dyld_all_image_infos_v10, 160-112, "string")
793 else:
794 dyld_all_image_infos_address = dyld_all_image_infos_address + 60
795 dyld_all_image_infos_v10 = GetUserDataAsString(task, dyld_all_image_infos_address, 40)
796 dyld_all_image_infos_initialImageCount = _ExtractDataFromString(dyld_all_image_infos_v10, 60-60, "uint32_t")
797 dyld_all_image_infos_errorKind = _ExtractDataFromString(dyld_all_image_infos_v10, 64-60, "uint32_t")
798 dyld_all_image_infos_errorClientOfDylibPath = _ExtractDataFromString(dyld_all_image_infos_v10, 68-60, "uint32_t")
799 dyld_all_image_infos_errorTargetDylibPath = _ExtractDataFromString(dyld_all_image_infos_v10, 72-60, "uint32_t")
800 dyld_all_image_infos_errorSymbol = _ExtractDataFromString(dyld_all_image_infos_v10, 76-60, "uint32_t")
801 dyld_all_image_infos_sharedCacheSlide = _ExtractDataFromString(dyld_all_image_infos_v10, 80-60, "uint32_t")
802 dyld_all_image_infos_sharedCacheUUID = _ExtractDataFromString(dyld_all_image_infos_v10, 84-60, "string")
803
804 if dyld_all_image_infos_version >= 10:
805 out_str += "\ninitialImageCount \t\t\t: {:#x}\n".format(dyld_all_image_infos_initialImageCount)
806
807 if dyld_all_image_infos_version >= 11:
808 out_str += "errorKind \t\t\t\t: {:#x}\n".format(dyld_all_image_infos_errorKind)
809 out_str += "errorClientOfDylibPath \t\t\t: {:#x}\n".format(dyld_all_image_infos_errorClientOfDylibPath)
810 if dyld_all_image_infos_errorClientOfDylibPath != 0:
811 out_str += "\t\t\t\t"
3e170ce0 812 out_str += GetUserspaceString(task, dyld_all_image_infos_errorClientOfDylibPath)
fe8ab488
A
813 out_str += "\n"
814 out_str += "errorTargetDylibPath \t\t\t: {:#x}\n".format(dyld_all_image_infos_errorTargetDylibPath)
815 if dyld_all_image_infos_errorTargetDylibPath != 0:
816 out_str += "\t\t\t\t"
3e170ce0 817 out_str += GetUserspaceString(task, dyld_all_image_infos_errorTargetDylibPath)
fe8ab488
A
818 out_str += "\n"
819 out_str += "errorSymbol \t\t\t\t: {:#x}\n".format(dyld_all_image_infos_errorSymbol)
820 if dyld_all_image_infos_errorSymbol != 0:
821 out_str += "\t\t\t\t"
3e170ce0 822 out_str += GetUserspaceString(task, dyld_all_image_infos_errorSymbol)
fe8ab488
A
823 out_str += "\n"
824
825 if dyld_all_image_infos_version >= 12:
826 out_str += "sharedCacheSlide \t\t\t: {:#x}\n".format(dyld_all_image_infos_sharedCacheSlide)
827 if dyld_all_image_infos_version >= 13 and dyld_all_image_infos_sharedCacheUUID != "":
828 out_str += "sharedCacheUUID \t\t\t: {:s}\n".format(dyld_all_image_infos_sharedCacheUUID)
829 else:
830 out_str += "No dyld information available for task\n"
831 print out_str
832
833# Macro: showosmalloc
834@lldb_type_summary(['OSMallocTag'])
835@header("{0: <20s} {1: >5s} {2: ^16s} {3: <5s} {4: <40s}".format("TAG", "COUNT", "STATE", "ATTR", "NAME"))
836def GetOSMallocTagSummary(malloc_tag):
837 """ Summarize the given OSMalloc tag.
838 params:
839 malloc_tag : value - value representing a _OSMallocTag_ * in kernel
840 returns:
841 out_str - string summary of the OSMalloc tag.
842 """
843 if not malloc_tag:
844 return "Invalid malloc tag value: 0x0"
845
846 out_str = "{: <#20x} {: >5d} {: ^#16x} {: <5d} {: <40s}\n".format(malloc_tag,
847 malloc_tag.OSMT_refcnt, malloc_tag.OSMT_state, malloc_tag.OSMT_attr, malloc_tag.OSMT_name)
848 return out_str
849
850@lldb_command('showosmalloc')
851def ShowOSMalloc(cmd_args=None):
852 """ Print the outstanding allocation count of OSMalloc tags
853 Usage: showosmalloc
854 """
855 summary_str = ""
856 tag_headp = Cast(addressof(kern.globals.OSMalloc_tag_list), 'struct _OSMallocTag_ *')
857 tagp = Cast(tag_headp.OSMT_link.next, 'struct _OSMallocTag_ *')
858 summary_str += GetOSMallocTagSummary.header + "\n"
859 while tagp != tag_headp:
860 summary_str += GetOSMallocTagSummary(tagp)
861 tagp = Cast(tagp.OSMT_link.next, 'struct _OSMallocTag_ *')
862
863 print summary_str
864
865# EndMacro: showosmalloc
866
867
3e170ce0
A
868@lldb_command('savekcdata', 'T:O:')
869def SaveKCDataToFile(cmd_args=None, cmd_options={}):
870 """ Save the data referred by the kcdata_descriptor structure.
871 options:
872 -T: <task_t> pointer to task if memory referenced is in userstask.
873 -O: <output file path> path to file to save data. default: /tmp/kcdata.<timestamp>.bin
874 Usage: (lldb) savekcdata <kcdata_descriptor_t> -T <task_t> -O /path/to/outputfile.bin
875 """
876 if not cmd_args:
877 raise ArgumentError('Please provide the kcdata descriptor.')
878
879 kcdata = kern.GetValueFromAddress(cmd_args[0], 'kcdata_descriptor_t')
880
881 outputfile = '/tmp/kcdata.{:s}.bin'.format(str(time.time()))
882 task = None
883 if '-O' in cmd_options:
884 outputfile = cmd_options['-O']
885 if '-T' in cmd_options:
886 task = kern.GetValueFromAddress(cmd_options['-T'], 'task_t')
887
888 memory_begin_address = unsigned(kcdata.kcd_addr_begin)
889 memory_size = 16 + unsigned(kcdata.kcd_addr_end) - memory_begin_address
890 flags_copyout = unsigned(kcdata.kcd_flags)
891 if flags_copyout:
892 if not task:
893 raise ArgumentError('Invalid task pointer provided.')
894 memory_data = GetUserDataAsString(task, memory_begin_address, memory_size)
895 else:
896 data_ptr = kern.GetValueFromAddress(memory_begin_address, 'uint8_t *')
5ba3f43e
A
897 if data_ptr == 0:
898 print "Kcdata descriptor is NULL"
899 return False
3e170ce0
A
900 memory_data = []
901 for i in range(memory_size):
902 memory_data.append(chr(data_ptr[i]))
903 if i % 50000 == 0:
904 print "%d of %d \r" % (i, memory_size),
905 memory_data = ''.join(memory_data)
906
907 if len(memory_data) != memory_size:
908 print "Failed to read {:d} bytes from address {: <#020x}".format(memory_size, memory_begin_address)
909 return False
910
911 fh = open(outputfile, 'w')
912 fh.write(memory_data)
913 fh.close()
914 print "Saved {:d} bytes to file {:s}".format(memory_size, outputfile)
915 return True
916
39236c6e
A
917
918