7 def GetBinaryNameForPC(pc_val
, user_lib_info
= None):
8 """ find the binary in user_lib_info that the passed pc_val falls in range of.
10 pc_val : int - integer form of the pc address
11 user_lib_info: [] of [] which hold start, end, binary name
13 str - Name of binary or "unknown" if not found.
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]))
24 retval
= matches
[0][1]
27 def ShowX86UserStack(thread
, user_lib_info
= None):
28 """ Display user space stack frame and pc addresses.
30 thread: obj referencing thread value
34 iss
= Cast(thread
.machine
.iss
, 'x86_saved_state_t *')
38 user_abi_ret_offset
= 0
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
44 user_abi_type
= "uint64_t"
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
50 user_abi_type
= "uint32_t"
53 print "This activation does not appear to have a valid user context."
57 cur_frame
= user_frame
58 debuglog("ip= 0x%x , fr = 0x%x " % (cur_ip
, cur_frame
))
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
))
65 print kern
.Symbolicate(cur_ip
)
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:
75 print frameformat
.format(frameno
, cur_frame
, cur_ip
, GetBinaryNameForPC(cur_ip
, user_lib_info
))
76 print kern
.Symbolicate(cur_ip
)
79 def _PrintARMUserStack(task
, cur_pc
, cur_fp
, framesize
, frametype
, frameformat
, user_lib_info
=None):
81 "No valid user context for this activation."
84 print frameformat
.format(frameno
, cur_fp
, cur_pc
, GetBinaryNameForPC(cur_pc
, user_lib_info
))
87 frame
= GetUserDataAsString(task
, cur_fp
, framesize
)
88 cur_fp
= _ExtractDataFromString(frame
, 0, frametype
)
89 cur_pc
= _ExtractDataFromString(frame
, (framesize
/ 2), frametype
)
92 print frameformat
.format(frameno
, cur_fp
, cur_pc
, GetBinaryNameForPC(cur_pc
, user_lib_info
))
94 def 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}"
101 frametype
= "uint32_t"
102 _PrintARMUserStack(thread
.task
, cur_pc
, cur_fp
, framesize
, frametype
, frameformat
, user_lib_info
=user_lib_info
)
104 def 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}"
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}"
123 frametype
= "uint32_t"
125 raise RuntimeError("Thread {0} has an invalid flavor {1}".format(unsigned(thread
), flavor
))
127 _PrintARMUserStack(thread
.task
, cur_pc
, cur_fp
, framesize
, frametype
, frameformat
, user_lib_info
=user_lib_info
)
130 @lldb_command('showthreaduserstack')
131 def ShowThreadUserStack(cmd_args
=None):
132 """ Show user stack for a given thread.
133 Syntax: (lldb) showthreaduserstack <thread_ptr>
136 raise ArgumentError("Insufficient arguments")
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
)
143 elif kern
.arch
== "arm64":
144 ShowARM64UserStack(thread
)
147 @lldb_command('printuserdata','XO:')
148 def 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>
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.
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
159 -X : print all values in hex.
160 -O <file path>: Save data to file
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]
169 if format_specifier_str
== "s":
170 print "0x%x: " % uspace_addr
+ GetUserspaceString(task
, uspace_addr
)
174 user_data_len
= struct
.calcsize(format_specifier_str
)
176 raise ArgumentError("Invalid format specifier provided.")
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."
182 if "-O" in cmd_options
:
183 fh
= open(cmd_options
["-O"],"w")
184 fh
.write(user_data_string
)
186 print "Written %d bytes to %s." % (user_data_len
, cmd_options
['-O'])
188 upacked_data
= struct
.unpack(format_specifier_str
, user_data_string
)
189 element_size
= user_data_len
/ len(upacked_data
)
190 for i
in range(len(upacked_data
)):
191 if "-X" in cmd_options
:
192 print "0x%x: " % (uspace_addr
+ i
*element_size
) + hex(upacked_data
[i
])
194 print "0x%x: " % (uspace_addr
+ i
*element_size
) + str(upacked_data
[i
])
199 @lldb_command('showtaskuserargs')
200 def 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>
204 <task_t> : pointer to task
206 if not cmd_args
or len(cmd_args
) != 1:
207 raise ArgumentError("Insufficient arguments")
209 task
= kern
.GetValueFromAddress(cmd_args
[0], 'task *')
210 proc
= Cast(task
.bsd_info
, 'proc *')
212 format_string
= "Q" if kern
.ptrsize
== 8 else "I"
214 string_area_size
= proc
.p_argslen
215 string_area_addr
= proc
.user_stack
- string_area_size
217 string_area
= GetUserDataAsString(task
, string_area_addr
, string_area_size
)
219 print "Could not read any data from userspace address."
223 pos
= string_area_addr
- kern
.ptrsize
225 for name
in ["apple", "env", "argv"] :
234 user_data_string
= GetUserDataAsString(task
, pos
, kern
.ptrsize
)
235 ptr
= struct
.unpack(format_string
, user_data_string
)[0]
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
:];
244 string
= GetUserspaceString(task
, ptr
)
246 print name
+ "[]: " + string
251 @lldb_command('showtaskuserstacks')
252 def ShowTaskUserStacks(cmd_args
=None):
253 """ Print out the user stack for each thread in a task, followed by the user libraries.
254 Syntax: (lldb) showtaskuserstacks <task_t>
255 The format is compatible with CrashTracer. You can also use the speedtracer plugin as follows
256 (lldb) showtaskuserstacks <task_t> -p speedtracer
258 Note: the address ranges are approximations. Also the list may not be completely accurate. This command expects memory read failures
259 and hence will skip a library if unable to read information. Please use your good judgement and not take the output as accurate
262 raise ArgumentError("Insufficient arguments")
264 task
= kern
.GetValueFromAddress(cmd_args
[0], 'task *')
265 #print GetTaskSummary.header + " " + GetProcSummary.header
266 pval
= Cast(task
.bsd_info
, 'proc *')
267 #print GetTaskSummary(task) + " " + GetProcSummary(pval) + "\n \n"
268 crash_report_format_string
= """\
271 Identifier: {pname: <30s}
273 Code Type: {parch: <20s}
274 Parent Process: {ppname: >20s}[{ppid:d}]
276 Date/Time: {timest:s}.000 -0800
277 OS Version: {osversion: <20s}
284 Application Specific Information:
285 Synthetic crash log generated from Kernel userstacks
288 user_lib_rex
= re
.compile("([0-9a-fx]+)\s-\s([0-9a-fx]+)\s+(.*?)\s", re
.IGNORECASE|re
.MULTILINE
)
289 from datetime
import datetime
290 ts
= datetime
.fromtimestamp(int(pval
.p_start
.tv_sec
))
291 date_string
= ts
.strftime('%Y-%m-%d %H:%M:%S')
293 if pval
.p_flag
& 0x4 :
297 if kern
.arch
== "x86_64" or kern
.arch
== "i386":
298 osversion
= "Mac OS X 10.8"
299 parch_s
= "I386 (32 bit)"
301 parch_s
= "X86-64 (Native)"
305 osversion
+= " ({:s})".format(kern
.globals.osversion
)
306 print crash_report_format_string
.format(pid
= pval
.p_pid
,
310 ppname
= GetProcNameForPid(pval
.p_ppid
),
311 timest
= date_string
,
313 osversion
= osversion
316 print "Binary Images:"
317 ShowTaskUserLibraries([hex(task
)])
318 usertask_lib_info
= [] # will host [startaddr, endaddr, lib_name] entries
319 for entry
in ShowTaskUserLibraries
.found_images
:
320 #print "processing line %s" % line
321 arr
= user_lib_rex
.findall(entry
[3])
325 usertask_lib_info
.append([int(arr
[0][0],16), int(arr
[0][1],16), str(arr
[0][2]).strip()])
327 printthread_user_stack_ptr
= ShowX86UserStack
328 if kern
.arch
== "arm":
329 printthread_user_stack_ptr
= ShowARMUserStack
330 elif kern
.arch
=="arm64":
331 printthread_user_stack_ptr
= ShowARM64UserStack
334 for thval
in IterateQueue(task
.threads
, 'thread *', 'task_threads'):
335 print "\nThread {0:d} name:0x{1:x}\nThread {0:d}:".format(counter
, thval
)
338 printthread_user_stack_ptr(thval
, usertask_lib_info
)
339 except Exception as exc_err
:
340 print "Failed to show user stack for thread 0x{0:x}".format(thval
)
344 print "Enable debugging ('(lldb) xnudebug debug') to see detailed trace."
348 def GetUserDataAsString(task
, addr
, size
):
349 """ Get data from task's address space as a string of bytes
351 task: task object from which to extract information
352 addr: int - start address to get data from.
353 size: int - no of bytes to read.
355 str - a stream of bytes. Empty string if read fails.
358 if GetConnectionProtocol() == "kdp":
359 kdp_pmap_addr
= unsigned(addressof(kern
.globals.kdp_pmap
))
360 if not WriteInt64ToMemoryAddress(unsigned(task
.map.pmap
), kdp_pmap_addr
):
361 debuglog("Failed to write in kdp_pmap from GetUserDataAsString.")
363 content
= LazyTarget
.GetProcess().ReadMemory(addr
, size
, err
)
364 if not err
.Success():
365 debuglog("Failed to read process memory. Error: " + err
.description
)
367 if not WriteInt64ToMemoryAddress(0, kdp_pmap_addr
):
368 debuglog("Failed to reset in kdp_pmap from GetUserDataAsString.")
370 elif kern
.arch
in ['arm', 'arm64', 'x86_64'] and long(size
) < (2 * kern
.globals.page_size
):
371 # Without the benefit of a KDP stub on the target, try to
372 # find the user task's physical mapping and memcpy the data.
373 # If it straddles a page boundary, copy in two passes
374 range1_addr
= long(addr
)
375 range1_size
= long(size
)
376 if kern
.StraddlesPage(range1_addr
, range1_size
):
377 range2_addr
= long(kern
.TruncPage(range1_addr
+ range1_size
))
378 range2_size
= long(range1_addr
+ range1_size
- range2_addr
)
379 range1_size
= long(range2_addr
- range1_addr
)
385 paddr_range1
= PmapWalk(task
.map.pmap
, range1_addr
, vSILENT
)
387 debuglog("Not mapped task 0x{:x} address 0x{:x}".format(task
, addr
))
390 range1_in_kva
= kern
.PhysToKernelVirt(paddr_range1
)
391 content
= LazyTarget
.GetProcess().ReadMemory(range1_in_kva
, range1_size
, err
)
392 if not err
.Success():
393 raise RuntimeError("Failed to read process memory. Error: " + err
.description
)
396 paddr_range2
= PmapWalk(task
.map.pmap
, range2_addr
, vSILENT
)
398 debuglog("Not mapped task 0x{:x} address 0x{:x}".format(task
, addr
))
400 range2_in_kva
= kern
.PhysToKernelVirt(paddr_range2
)
401 content
+= LazyTarget
.GetProcess().ReadMemory(range2_in_kva
, range2_size
, err
)
402 if not err
.Success():
403 raise RuntimeError("Failed to read process memory. Error: " + err
.description
)
405 raise NotImplementedError("GetUserDataAsString does not support this configuration")
409 def _ExtractDataFromString(strdata
, offset
, data_type
, length
=0):
410 """ Extract specific data from string buffer
412 strdata: str - string data give from GetUserDataAsString
413 offset: int - 0 based offset into the data.
414 data_type: str - defines what type to be read as. Supported values are:
415 'uint64_t', 'uint32_t', 'string'
416 length: int - used when data_type=='string'
418 None - if extraction failed.
419 obj - based on what is requested in data_type
422 if data_type
== 'uint64_t':
425 elif data_type
== "uint32_t":
429 unpack_str
= "%ds" % length
431 data_len
= len(strdata
)
432 if offset
> data_len
or (offset
+ length
) > data_len
or offset
< 0:
433 debuglog("Invalid arguments to _ExtractDataFromString.")
435 return struct
.unpack(unpack_str
, strdata
[offset
:(offset
+ length
)])[0]
437 def GetUserspaceString(task
, string_address
):
438 """ Maps 32 bytes at a time and packs as string
440 task: obj - referencing task to read data from
441 string_address: int - address where the image path is stored
443 str - string path of the file. "" if failed to read.
448 if string_address
== 0:
452 str_data
= GetUserDataAsString(task
, string_address
, 32)
453 if len(str_data
) == 0:
458 retval
+= str_data
[i
]
468 def GetImageInfo(task
, mh_image_address
, mh_path_address
, approx_end_address
=None):
469 """ Print user library informaiton.
471 task : obj referencing the task for which Image info printed
472 mh_image_address : int - address which has image info
473 mh_path_address : int - address which holds path name string
474 approx_end_address: int - address which lldbmacros think is end address.
476 str - string representing image info. "" if failure to read data.
478 if approx_end_address
:
479 image_end_load_address
= int(approx_end_address
) -1
481 image_end_load_address
= int(mh_image_address
) + 0xffffffff
483 print_format
= "0x{0:x} - 0x{1:x} {2: <50s} (??? - ???) <{3: <36s}> {4: <50s}"
484 # 32 bytes enough for mach_header/mach_header_64
485 mh_data
= GetUserDataAsString(task
, mh_image_address
, 32)
486 if len(mh_data
) == 0:
487 debuglog("unable to get userdata for task 0x{:x} img_addr 0x{:x} path_address 0x{:x}".format(
488 task
, mh_image_address
, mh_path_address
))
490 mh_magic
= _ExtractDataFromString(mh_data
, (4 * 0), "uint32_t")
491 mh_cputype
= _ExtractDataFromString(mh_data
,(4 * 1), "uint32_t")
492 mh_cpusubtype
= _ExtractDataFromString(mh_data
,(4 * 2), "uint32_t")
493 mh_filetype
= _ExtractDataFromString(mh_data
,(4 * 3), "uint32_t")
494 mh_ncmds
= _ExtractDataFromString(mh_data
,(4 * 4), "uint32_t")
495 mh_sizeofcmds
= _ExtractDataFromString(mh_data
,(4 * 5), "uint32_t")
496 mh_flags
= _ExtractDataFromString(mh_data
,(4 * 6), "uint32_t")
498 if mh_magic
== 0xfeedfacf:
500 lc_address
= mh_image_address
+ 32
503 lc_address
= mh_image_address
+ 28
507 found_uuid_data
= False
509 while lc_idx
< mh_ncmds
:
510 # 24 bytes is the size of uuid_command
511 lcmd_data
= GetUserDataAsString(task
, lc_address
, 24)
512 lc_cmd
= _ExtractDataFromString(lcmd_data
, 4 * 0, "uint32_t")
513 lc_cmd_size
= _ExtractDataFromString(lcmd_data
, 4 * 1, "uint32_t")
514 lc_data
= _ExtractDataFromString(lcmd_data
, 4*2, "string", 16)
520 # need to print the uuid now.
521 uuid_data
= [ord(x
) for x
in lc_data
]
522 found_uuid_data
= True
523 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
)
524 #also print image path
525 path_out_string
= GetUserspaceString(task
, mh_path_address
)
526 path_base_name
= path_out_string
.split("/")[-1]
527 retval
= print_format
.format(mh_image_address
, image_end_load_address
, path_base_name
, uuid_out_string
, path_out_string
)
529 ShowTaskUserLibraries
.exec_load_path
= lc_address
+ _ExtractDataFromString(lcmd_data
, 4*2, "uint32_t")
530 debuglog("Found load command to be 0xe for address %s" % hex(ShowTaskUserLibraries
.exec_load_path
))
531 lc_address
= lc_address
+ lc_cmd_size
534 if not found_uuid_data
:
535 path_out_string
= GetUserspaceString(task
, mh_path_address
)
536 path_base_name
= path_out_string
.split("/")[-1]
539 retval
= print_format
.format(mh_image_address
, image_end_load_address
, path_base_name
, uuid_out_string
, path_out_string
)
542 @static_var("found_images", []) # holds entries of format (startaddr, endaddr, image_path_addr, infostring)
543 @static_var("exec_load_path", 0)
544 @lldb_command("showtaskuserlibraries")
545 def ShowTaskUserLibraries(cmd_args
=None):
546 """ Show binary images known by dyld in target task
547 For a given user task, inspect the dyld shared library state and print information about all Mach-O images.
548 Syntax: (lldb)showtaskuserlibraries <task_t>
549 Note: the address ranges are approximations. Also the list may not be completely accurate. This command expects memory read failures
550 and hence will skip a library if unable to read information. Please use your good judgement and not take the output as accurate
553 raise ArgumentError("Insufficient arguments")
555 #reset the found_images array
556 ShowTaskUserLibraries
.found_images
= []
558 task
= kern
.GetValueFromAddress(cmd_args
[0], 'task_t')
559 is_task_64
= int(task
.t_flags
) & 0x1
560 dyld_all_image_infos_address
= unsigned(task
.all_image_info_addr
)
561 debuglog("dyld_all_image_infos_address = %s" % hex(dyld_all_image_infos_address
))
564 if dyld_all_image_infos_address
== 0:
565 print "No dyld shared library information available for task"
568 debuglog("Extracting version information.")
569 vers_info_data
= GetUserDataAsString(task
, dyld_all_image_infos_address
, 112)
570 version
= _ExtractDataFromString(vers_info_data
, cur_data_offset
, "uint32_t")
573 print "Unknown dyld all_image_infos version number %d" % version
574 image_info_count
= _ExtractDataFromString(vers_info_data
, cur_data_offset
, "uint32_t")
575 debuglog("version = %d count = %d is_task_64 = %s" % (version
, image_info_count
, repr(is_task_64
)))
577 ShowTaskUserLibraries
.exec_load_path
= 0
580 image_info_array_address
= _ExtractDataFromString(vers_info_data
, 8, "uint64_t")
581 dyld_load_address
= _ExtractDataFromString(vers_info_data
, 8*4, "uint64_t")
582 dyld_all_image_infos_address_from_struct
= _ExtractDataFromString(vers_info_data
, 8*13, "uint64_t")
585 image_info_array_address
= _ExtractDataFromString(vers_info_data
, 4*2, "uint32_t")
586 dyld_load_address
= _ExtractDataFromString(vers_info_data
, 4*5, "uint32_t")
587 dyld_all_image_infos_address_from_struct
= _ExtractDataFromString(vers_info_data
, 4*14, "uint32_t")
588 # Account for ASLR slide before dyld can fix the structure
589 dyld_load_address
= dyld_load_address
+ (dyld_all_image_infos_address
- dyld_all_image_infos_address_from_struct
)
593 while i
< image_info_count
:
594 image_info_address
= image_info_array_address
+ i
* image_info_size
595 debuglog("i = %d, image_info_address = %s, image_info_size = %d" % (i
, hex(image_info_address
), image_info_size
))
596 n_im_info_addr
= None
599 img_data
= GetUserDataAsString(task
, image_info_address
, image_info_size
)
601 debuglog("Failed to read user data for task 0x{:x} addr 0x{:x}, exception {:s}".format(task
, image_info_address
, str(e
)))
605 image_info_addr
= _ExtractDataFromString(img_data
, 0, "uint64_t")
606 image_info_path
= _ExtractDataFromString(img_data
, 8, "uint64_t")
608 image_info_addr
= _ExtractDataFromString(img_data
, 0, "uint32_t")
609 image_info_path
= _ExtractDataFromString(img_data
, 4, "uint32_t")
612 debuglog("Found image: image_info_addr = %s, image_info_path= %s" % (hex(image_info_addr
), hex(image_info_path
)))
613 image_info_list
.append((image_info_addr
, image_info_path
))
616 image_info_list
.sort()
617 num_images_found
= len(image_info_list
)
619 for ii
in range(num_images_found
):
620 n_im_info_addr
= dyld_load_address
621 if ii
+ 1 < num_images_found
:
622 n_im_info_addr
= image_info_list
[ii
+1][0]
624 image_info_addr
= image_info_list
[ii
][0]
625 image_info_path
= image_info_list
[ii
][1]
627 image_print_s
= GetImageInfo(task
, image_info_addr
, image_info_path
, approx_end_address
=n_im_info_addr
)
628 if len(image_print_s
) > 0:
630 ShowTaskUserLibraries
.found_images
.append((image_info_addr
, n_im_info_addr
, image_info_path
, image_print_s
))
632 debuglog("Failed to print image info for task 0x{:x} image_info 0x{:x}".format(task
, image_info_addr
))
637 # load_path might get set when the main executable is processed.
638 if ShowTaskUserLibraries
.exec_load_path
!= 0:
639 debuglog("main executable load_path is set.")
640 image_print_s
= GetImageInfo(task
, dyld_load_address
, ShowTaskUserLibraries
.exec_load_path
)
641 if len(image_print_s
) > 0:
643 ShowTaskUserLibraries
.found_images
.append((dyld_load_address
, dyld_load_address
+ 0xffffffff,
644 ShowTaskUserLibraries
.exec_load_path
, image_print_s
))
646 debuglog("Failed to print image for main executable for task 0x{:x} dyld_load_addr 0x{:x}".format(task
, dyld_load_address
))
648 debuglog("Falling back to vm entry method for finding executable load address")
649 print "# NOTE: Failed to find executable using all_image_infos. Using fuzzy match to find best possible load address for executable."
650 ShowTaskLoadInfo([cmd_args
[0]])
653 @lldb_command("showtaskuserdyldinfo")
654 def ShowTaskUserDyldInfo(cmd_args
=None):
655 """ Inspect the dyld global info for the given user task & print out all fields including error messages
656 Syntax: (lldb)showtaskuserdyldinfo <task_t>
658 if cmd_args
== None or len(cmd_args
) < 1:
659 print "No arguments passed"
660 print ShowTaskUserDyldInfo
.__doc
__.strip()
664 task
= kern
.GetValueFromAddress(cmd_args
[0], 'task_t')
665 is_task_64
= int(task
.t_flags
) & 0x1
666 dyld_all_image_infos_address
= unsigned(task
.all_image_info_addr
)
667 if dyld_all_image_infos_address
== 0:
668 print "No dyld shared library information available for task"
670 vers_info_data
= GetUserDataAsString(task
, dyld_all_image_infos_address
, 112)
671 dyld_all_image_infos_version
= _ExtractDataFromString(vers_info_data
, 0, "uint32_t")
672 if dyld_all_image_infos_version
> 14:
673 out_str
+= "Unknown dyld all_image_infos version number %d" % dyld_all_image_infos_version
675 # Find fields by byte offset. We assume at least version 9 is supported
677 dyld_all_image_infos_infoArrayCount
= _ExtractDataFromString(vers_info_data
, 4, "uint32_t")
678 dyld_all_image_infos_infoArray
= _ExtractDataFromString(vers_info_data
, 8, "uint64_t")
679 dyld_all_image_infos_notification
= _ExtractDataFromString(vers_info_data
, 16, "uint64_t")
680 dyld_all_image_infos_processDetachedFromSharedRegion
= _ExtractDataFromString(vers_info_data
, 24, "string")
681 dyld_all_image_infos_libSystemInitialized
= _ExtractDataFromString(vers_info_data
, 25, "string")
682 dyld_all_image_infos_dyldImageLoadAddress
= _ExtractDataFromString(vers_info_data
, 32, "uint64_t")
683 dyld_all_image_infos_jitInfo
= _ExtractDataFromString(vers_info_data
, 40, "uint64_t")
684 dyld_all_image_infos_dyldVersion
= _ExtractDataFromString(vers_info_data
, 48, "uint64_t")
685 dyld_all_image_infos_errorMessage
= _ExtractDataFromString(vers_info_data
, 56, "uint64_t")
686 dyld_all_image_infos_terminationFlags
= _ExtractDataFromString(vers_info_data
, 64, "uint64_t")
687 dyld_all_image_infos_coreSymbolicationShmPage
= _ExtractDataFromString(vers_info_data
, 72, "uint64_t")
688 dyld_all_image_infos_systemOrderFlag
= _ExtractDataFromString(vers_info_data
, 80, "uint64_t")
689 dyld_all_image_infos_uuidArrayCount
= _ExtractDataFromString(vers_info_data
, 88, "uint64_t")
690 dyld_all_image_infos_uuidArray
= _ExtractDataFromString(vers_info_data
, 96, "uint64_t")
691 dyld_all_image_infos_dyldAllImageInfosAddress
= _ExtractDataFromString(vers_info_data
, 104, "uint64_t")
693 dyld_all_image_infos_infoArrayCount
= _ExtractDataFromString(vers_info_data
, 4, "uint32_t")
694 dyld_all_image_infos_infoArray
= _ExtractDataFromString(vers_info_data
, 8, "uint32_t")
695 dyld_all_image_infos_notification
= _ExtractDataFromString(vers_info_data
, 12, "uint32_t")
696 dyld_all_image_infos_processDetachedFromSharedRegion
= _ExtractDataFromString(vers_info_data
, 16, "string")
697 dyld_all_image_infos_libSystemInitialized
= _ExtractDataFromString(vers_info_data
, 17, "string")
698 dyld_all_image_infos_dyldImageLoadAddress
= _ExtractDataFromString(vers_info_data
, 20, "uint32_t")
699 dyld_all_image_infos_jitInfo
= _ExtractDataFromString(vers_info_data
, 24, "uint32_t")
700 dyld_all_image_infos_dyldVersion
= _ExtractDataFromString(vers_info_data
, 28, "uint32_t")
701 dyld_all_image_infos_errorMessage
= _ExtractDataFromString(vers_info_data
, 32, "uint32_t")
702 dyld_all_image_infos_terminationFlags
= _ExtractDataFromString(vers_info_data
, 36, "uint32_t")
703 dyld_all_image_infos_coreSymbolicationShmPage
= _ExtractDataFromString(vers_info_data
, 40, "uint32_t")
704 dyld_all_image_infos_systemOrderFlag
= _ExtractDataFromString(vers_info_data
, 44, "uint32_t")
705 dyld_all_image_infos_uuidArrayCount
= _ExtractDataFromString(vers_info_data
, 48, "uint32_t")
706 dyld_all_image_infos_uuidArray
= _ExtractDataFromString(vers_info_data
, 52, "uint32_t")
707 dyld_all_image_infos_dyldAllImageInfosAddress
= _ExtractDataFromString(vers_info_data
, 56, "uint32_t")
709 dyld_all_imfo_infos_slide
= (dyld_all_image_infos_address
- dyld_all_image_infos_dyldAllImageInfosAddress
)
710 dyld_all_image_infos_dyldVersion_postslide
= (dyld_all_image_infos_dyldVersion
+ dyld_all_imfo_infos_slide
)
712 path_out
= GetUserspaceString(task
, dyld_all_image_infos_dyldVersion_postslide
)
713 out_str
+= "[dyld-{:s}]\n".format(path_out
)
714 out_str
+= "version \t\t\t\t: {:d}\n".format(dyld_all_image_infos_version
)
715 out_str
+= "infoArrayCount \t\t\t\t: {:d}\n".format(dyld_all_image_infos_infoArrayCount
)
716 out_str
+= "infoArray \t\t\t\t: {:#x}\n".format(dyld_all_image_infos_infoArray
)
717 out_str
+= "notification \t\t\t\t: {:#x}\n".format(dyld_all_image_infos_notification
)
719 out_str
+= "processDetachedFromSharedRegion \t: "
720 if dyld_all_image_infos_processDetachedFromSharedRegion
!= "":
721 out_str
+= "TRUE\n".format(dyld_all_image_infos_processDetachedFromSharedRegion
)
725 out_str
+= "libSystemInitialized \t\t\t: "
726 if dyld_all_image_infos_libSystemInitialized
!= "":
727 out_str
+= "TRUE\n".format(dyld_all_image_infos_libSystemInitialized
)
731 out_str
+= "dyldImageLoadAddress \t\t\t: {:#x}\n".format(dyld_all_image_infos_dyldImageLoadAddress
)
732 out_str
+= "jitInfo \t\t\t\t: {:#x}\n".format(dyld_all_image_infos_jitInfo
)
733 out_str
+= "\ndyldVersion \t\t\t\t: {:#x}".format(dyld_all_image_infos_dyldVersion
)
734 if (dyld_all_imfo_infos_slide
!= 0):
735 out_str
+= " (currently {:#x})\n".format(dyld_all_image_infos_dyldVersion_postslide
)
739 out_str
+= "errorMessage \t\t\t\t: {:#x}\n".format(dyld_all_image_infos_errorMessage
)
740 if dyld_all_image_infos_errorMessage
!= 0:
741 out_str
+= GetUserspaceString(task
, dyld_all_image_infos_errorMessage
)
743 out_str
+= "terminationFlags \t\t\t: {:#x}\n".format(dyld_all_image_infos_terminationFlags
)
744 out_str
+= "coreSymbolicationShmPage \t\t: {:#x}\n".format(dyld_all_image_infos_coreSymbolicationShmPage
)
745 out_str
+= "systemOrderFlag \t\t\t: {:#x}\n".format(dyld_all_image_infos_systemOrderFlag
)
746 out_str
+= "uuidArrayCount \t\t\t\t: {:#x}\n".format(dyld_all_image_infos_uuidArrayCount
)
747 out_str
+= "uuidArray \t\t\t\t: {:#x}\n".format(dyld_all_image_infos_uuidArray
)
748 out_str
+= "dyldAllImageInfosAddress \t\t: {:#x}".format(dyld_all_image_infos_dyldAllImageInfosAddress
)
749 if (dyld_all_imfo_infos_slide
!= 0):
750 out_str
+= " (currently {:#x})\n".format(dyld_all_image_infos_address
)
755 dyld_all_image_infos_address
= dyld_all_image_infos_address
+ 112
756 dyld_all_image_infos_v10
= GetUserDataAsString(task
, dyld_all_image_infos_address
, 64)
757 dyld_all_image_infos_initialImageCount
= _ExtractDataFromString(dyld_all_image_infos_v10
, 112-112, "uint64_t")
758 dyld_all_image_infos_errorKind
= _ExtractDataFromString(dyld_all_image_infos_v10
, 120-112, "uint64_t")
759 dyld_all_image_infos_errorClientOfDylibPath
= _ExtractDataFromString(dyld_all_image_infos_v10
, 128-112, "uint64_t")
760 dyld_all_image_infos_errorTargetDylibPath
= _ExtractDataFromString(dyld_all_image_infos_v10
, 136-112, "uint64_t")
761 dyld_all_image_infos_errorSymbol
= _ExtractDataFromString(dyld_all_image_infos_v10
, 144-112, "uint64_t")
762 dyld_all_image_infos_sharedCacheSlide
= _ExtractDataFromString(dyld_all_image_infos_v10
, 152-112, "uint64_t")
763 dyld_all_image_infos_sharedCacheUUID
= _ExtractDataFromString(dyld_all_image_infos_v10
, 160-112, "string")
765 dyld_all_image_infos_address
= dyld_all_image_infos_address
+ 60
766 dyld_all_image_infos_v10
= GetUserDataAsString(task
, dyld_all_image_infos_address
, 40)
767 dyld_all_image_infos_initialImageCount
= _ExtractDataFromString(dyld_all_image_infos_v10
, 60-60, "uint32_t")
768 dyld_all_image_infos_errorKind
= _ExtractDataFromString(dyld_all_image_infos_v10
, 64-60, "uint32_t")
769 dyld_all_image_infos_errorClientOfDylibPath
= _ExtractDataFromString(dyld_all_image_infos_v10
, 68-60, "uint32_t")
770 dyld_all_image_infos_errorTargetDylibPath
= _ExtractDataFromString(dyld_all_image_infos_v10
, 72-60, "uint32_t")
771 dyld_all_image_infos_errorSymbol
= _ExtractDataFromString(dyld_all_image_infos_v10
, 76-60, "uint32_t")
772 dyld_all_image_infos_sharedCacheSlide
= _ExtractDataFromString(dyld_all_image_infos_v10
, 80-60, "uint32_t")
773 dyld_all_image_infos_sharedCacheUUID
= _ExtractDataFromString(dyld_all_image_infos_v10
, 84-60, "string")
775 if dyld_all_image_infos_version
>= 10:
776 out_str
+= "\ninitialImageCount \t\t\t: {:#x}\n".format(dyld_all_image_infos_initialImageCount
)
778 if dyld_all_image_infos_version
>= 11:
779 out_str
+= "errorKind \t\t\t\t: {:#x}\n".format(dyld_all_image_infos_errorKind
)
780 out_str
+= "errorClientOfDylibPath \t\t\t: {:#x}\n".format(dyld_all_image_infos_errorClientOfDylibPath
)
781 if dyld_all_image_infos_errorClientOfDylibPath
!= 0:
782 out_str
+= "\t\t\t\t"
783 out_str
+= GetUserspaceString(task
, dyld_all_image_infos_errorClientOfDylibPath
)
785 out_str
+= "errorTargetDylibPath \t\t\t: {:#x}\n".format(dyld_all_image_infos_errorTargetDylibPath
)
786 if dyld_all_image_infos_errorTargetDylibPath
!= 0:
787 out_str
+= "\t\t\t\t"
788 out_str
+= GetUserspaceString(task
, dyld_all_image_infos_errorTargetDylibPath
)
790 out_str
+= "errorSymbol \t\t\t\t: {:#x}\n".format(dyld_all_image_infos_errorSymbol
)
791 if dyld_all_image_infos_errorSymbol
!= 0:
792 out_str
+= "\t\t\t\t"
793 out_str
+= GetUserspaceString(task
, dyld_all_image_infos_errorSymbol
)
796 if dyld_all_image_infos_version
>= 12:
797 out_str
+= "sharedCacheSlide \t\t\t: {:#x}\n".format(dyld_all_image_infos_sharedCacheSlide
)
798 if dyld_all_image_infos_version
>= 13 and dyld_all_image_infos_sharedCacheUUID
!= "":
799 out_str
+= "sharedCacheUUID \t\t\t: {:s}\n".format(dyld_all_image_infos_sharedCacheUUID
)
801 out_str
+= "No dyld information available for task\n"
804 # Macro: showosmalloc
805 @lldb_type_summary(['OSMallocTag'])
806 @header("{0: <20s} {1: >5s} {2: ^16s} {3: <5s} {4: <40s}".format("TAG", "COUNT", "STATE", "ATTR", "NAME"))
807 def GetOSMallocTagSummary(malloc_tag
):
808 """ Summarize the given OSMalloc tag.
810 malloc_tag : value - value representing a _OSMallocTag_ * in kernel
812 out_str - string summary of the OSMalloc tag.
815 return "Invalid malloc tag value: 0x0"
817 out_str
= "{: <#20x} {: >5d} {: ^#16x} {: <5d} {: <40s}\n".format(malloc_tag
,
818 malloc_tag
.OSMT_refcnt
, malloc_tag
.OSMT_state
, malloc_tag
.OSMT_attr
, malloc_tag
.OSMT_name
)
821 @lldb_command('showosmalloc')
822 def ShowOSMalloc(cmd_args
=None):
823 """ Print the outstanding allocation count of OSMalloc tags
827 tag_headp
= Cast(addressof(kern
.globals.OSMalloc_tag_list
), 'struct _OSMallocTag_ *')
828 tagp
= Cast(tag_headp
.OSMT_link
.next
, 'struct _OSMallocTag_ *')
829 summary_str
+= GetOSMallocTagSummary
.header
+ "\n"
830 while tagp
!= tag_headp
:
831 summary_str
+= GetOSMallocTagSummary(tagp
)
832 tagp
= Cast(tagp
.OSMT_link
.next
, 'struct _OSMallocTag_ *')
836 # EndMacro: showosmalloc
839 @lldb_command('savekcdata', 'T:O:')
840 def SaveKCDataToFile(cmd_args
=None, cmd_options
={}):
841 """ Save the data referred by the kcdata_descriptor structure.
843 -T: <task_t> pointer to task if memory referenced is in userstask.
844 -O: <output file path> path to file to save data. default: /tmp/kcdata.<timestamp>.bin
845 Usage: (lldb) savekcdata <kcdata_descriptor_t> -T <task_t> -O /path/to/outputfile.bin
848 raise ArgumentError('Please provide the kcdata descriptor.')
850 kcdata
= kern
.GetValueFromAddress(cmd_args
[0], 'kcdata_descriptor_t')
852 outputfile
= '/tmp/kcdata.{:s}.bin'.format(str(time
.time()))
854 if '-O' in cmd_options
:
855 outputfile
= cmd_options
['-O']
856 if '-T' in cmd_options
:
857 task
= kern
.GetValueFromAddress(cmd_options
['-T'], 'task_t')
859 memory_begin_address
= unsigned(kcdata
.kcd_addr_begin
)
860 memory_size
= 16 + unsigned(kcdata
.kcd_addr_end
) - memory_begin_address
861 flags_copyout
= unsigned(kcdata
.kcd_flags
)
864 raise ArgumentError('Invalid task pointer provided.')
865 memory_data
= GetUserDataAsString(task
, memory_begin_address
, memory_size
)
867 data_ptr
= kern
.GetValueFromAddress(memory_begin_address
, 'uint8_t *')
869 for i
in range(memory_size
):
870 memory_data
.append(chr(data_ptr
[i
]))
872 print "%d of %d \r" % (i
, memory_size
),
873 memory_data
= ''.join(memory_data
)
875 if len(memory_data
) != memory_size
:
876 print "Failed to read {:d} bytes from address {: <#020x}".format(memory_size
, memory_begin_address
)
879 fh
= open(outputfile
, 'w')
880 fh
.write(memory_data
)
882 print "Saved {:d} bytes to file {:s}".format(memory_size
, outputfile
)