1""" Please make sure you read the README file COMPLETELY BEFORE reading anything below. 2 It is very critical that you read coding guidelines in Section E in README file. 3""" 4from __future__ import absolute_import, division, print_function 5 6from builtins import hex 7from builtins import range 8 9import sys 10from xnu import * 11from utils import * 12from process import * 13from bank import * 14from waitq import * 15from ioreg import * 16from memory import * 17import xnudefines 18import kmemory 19 20@lldb_type_summary(['struct ipc_entry_table *', 'ipc_entry_table_t']) 21def PrintIpcEntryTable(array): 22 t, s = kalloc_array_decode(array, 'struct ipc_entry') 23 return "ptr = {:#x}, size = {:d}, elem_type = struct ipc_entry".format(unsigned(t), s) 24 25@lldb_type_summary(['struct ipc_port_requests_table *', 'ipc_port_requests_table_t']) 26def PrintIpcPortRequestTable(array): 27 t, s = kalloc_array_decode(array, 'struct ipc_port_requests') 28 return "ptr = {:#x}, size = {:d}, elem_type = struct ipc_port_requests".format(unsigned(t), s) 29 30def GetSpaceTable(space): 31 """ Return the tuple of (entries, size) of the table for a space 32 """ 33 table = space.is_table.__smr_ptr 34 if table: 35 return kalloc_array_decode(table, 'struct ipc_entry') 36 return (None, 0) 37 38def GetSpaceEntriesWithBits(is_tableval, num_entries, mask): 39 base = is_tableval.GetSBValue().Dereference() 40 return ( 41 (index, iep) 42 for index, iep in enumerate(base.xIterSiblings(1, num_entries), 1) 43 if iep.xGetIntegerByName('ie_bits') & mask 44 ) 45 46def GetSpaceObjectsWithBits(is_tableval, num_entries, mask, ty): 47 base = is_tableval.GetSBValue().Dereference() 48 return ( 49 iep.xCreateValueFromAddress( 50 None, 51 iep.xGetIntegerByName('ie_object'), 52 ty, 53 ) 54 for iep in base.xIterSiblings(1, num_entries) 55 if iep.xGetIntegerByName('ie_bits') & mask 56 ) 57 58 59@header("{0: <20s} {1: <6s} {2: <6s} {3: <10s} {4: <32s}".format("task", "pid", '#acts', "tablesize", "command")) 60def GetTaskIPCSummary(task, show_busy = False): 61 """ Display a task's ipc summary. 62 params: 63 task : core.value represeting a Task in kernel 64 returns 65 str - string of ipc info for the task 66 """ 67 out_string = '' 68 format_string = "{0: <#20x} {1: <6d} {2: <6d} {3: <10d} {4: <32s}" 69 busy_format = " {0: <10d} {1: <6d}" 70 proc_name = '' 71 if not task.active: 72 proc_name = 'terminated: ' 73 if task.halting: 74 proc_name += 'halting: ' 75 proc_name += GetProcNameForTask(task) 76 _, table_size = GetSpaceTable(task.itk_space) 77 out_string += format_string.format(task, GetProcPIDForTask(task), task.thread_count, table_size, proc_name) 78 if show_busy: 79 nbusy, nmsgs = GetTaskBusyPortsSummary(task) 80 out_string += busy_format.format(nbusy, nmsgs) 81 return (out_string, table_size, nbusy, nmsgs) 82 return (out_string, table_size) 83 84@header("{0: <20s} {1: <6s} {2: <6s} {3: <10s} {4: <32s} {5: <10s} {6: <6s}".format("task", "pid", '#acts', "tablesize", "command", "#busyports", "#kmsgs")) 85def GetTaskBusyIPCSummary(task): 86 return GetTaskIPCSummary(task, True) 87 88def GetTaskBusyPortsSummary(task): 89 is_tableval, num_entries = GetSpaceTable(task.itk_space) 90 port_ty = gettype('struct ipc_port') 91 nbusy = 0 92 nmsgs = 0 93 94 if is_tableval: 95 ports = GetSpaceObjectsWithBits(is_tableval, num_entries, 0x00020000, 96 gettype('struct ipc_port')) 97 98 for port in ports: 99 if not port or port == xnudefines.MACH_PORT_DEAD: 100 continue 101 count = port.xGetIntegerByPath('.ip_messages.imq_msgcount') 102 if count: 103 nbusy += 1 104 nmsgs += count 105 106 return (nbusy, nmsgs) 107 108 109@header("{:<20s} {:<20s} {:<10s} {:>6s} {:<20s} {:>8s} {:<20s} {:s}".format( 110 "port", "waitqueue", "recvname", "refs", "receiver", "nmsgs", "service", "dest/kobject")) 111def PrintPortSummary(port, show_kmsg_summary=True, show_sets=False, prefix="", O=None): 112 """ Display a port's summary 113 params: 114 port : core.value representing a port in the kernel 115 returns 116 str : string of ipc info for the given port 117 """ 118 119 format_string = "{:<#20x} {:<#20x} {:#010x} {:>6d} {:<#20x} {:>8d} {:<20s} {:<s}" 120 ip_messages = port.ip_messages 121 receiver_name = ip_messages.imq_receiver_name 122 splabel_name = 'N/A' 123 space = 0 124 refs = 0 125 ip_object = port.ip_object 126 if ip_object.io_bits & 0x80000000: 127 if receiver_name: 128 space = unsigned(port.ip_receiver) 129 130 try: 131 if port.ip_service_port: 132 splabel = Cast(port.ip_splabel, 'struct ipc_service_port_label *') 133 splabel_name = str(splabel.ispl_service_name) # Not on RELEASE kernel 134 except: 135 splabel_name = 'unknown' 136 137 dest_str = GetPortDestProc(port)[1] 138 else: 139 dest_str = "inactive-port" 140 141 ip_waitq = port.ip_waitq 142 print(prefix + format_string.format(unsigned(port), addressof(ip_waitq), 143 unsigned(receiver_name), ip_object.io_references, space, 144 ip_messages.imq_msgcount, splabel_name, dest_str)) 145 146 if show_kmsg_summary: 147 with O.table(prefix + GetKMsgSummary.header): 148 for kmsgp in IterateCircleQueue(ip_messages.imq_messages, 'ipc_kmsg', 'ikm_link'): 149 print(prefix + GetKMsgSummary(kmsgp, prefix)) 150 151 wq = Waitq(addressof(ip_waitq)) 152 if show_sets and wq.hasSets(): 153 def doit(wq): 154 for wqs in wq.iterateSets(): 155 PrintPortSetSummary(wqs.asPset(), space=port.ip_receiver, verbose=False, O=O) 156 157 if O is None: 158 print(PrintPortSetSummary.header) 159 doit(wq) 160 else: 161 with O.table(PrintPortSetSummary.header, indent=True): 162 doit(wq) 163 print("") 164 165def GetPortDispositionString(disp): 166 if disp < 0: ## use negative numbers for request ports 167 portname = 'notify' 168 if disp == -1: 169 disp_str = 'reqNS' 170 elif disp == -2: 171 disp_str = 'reqPD' 172 elif disp == -3: 173 disp_str = 'reqSPa' 174 elif disp == -4: 175 disp_str = 'reqSPr' 176 elif disp == -5: 177 disp_str = 'reqSPra' 178 else: 179 disp_str = '-X' 180 ## These dispositions should match those found in osfmk/mach/message.h 181 elif disp == 16: 182 disp_str = 'R' ## receive 183 elif disp == 24: 184 disp_str = 'dR' ## dispose receive 185 elif disp == 17: 186 disp_str = 'S' ## (move) send 187 elif disp == 19: 188 disp_str = 'cS' ## copy send 189 elif disp == 20: 190 disp_str = 'mS' ## make send 191 elif disp == 25: 192 disp_str = 'dS' ## dispose send 193 elif disp == 18: 194 disp_str = 'O' ## send-once 195 elif disp == 21: 196 disp_str = 'mO' ## make send-once 197 elif disp == 26: 198 disp_str = 'dO' ## dispose send-once 199 ## faux dispositions used to string-ify IPC entry types 200 elif disp == 100: 201 disp_str = 'PS' ## port set 202 elif disp == 101: 203 disp_str = 'dead' ## dead name 204 elif disp == 102: 205 disp_str = 'L' ## LABELH 206 elif disp == 103: 207 disp_str = 'V' ## Thread voucher (thread->ith_voucher->iv_port) 208 ## Catch-all 209 else: 210 disp_str = 'X' ## invalid 211 return disp_str 212 213def GetPortPDRequest(port): 214 """ Returns the port-destroyed notification port if any 215 """ 216 if port.ip_has_watchport: 217 return port.ip_twe.twe_pdrequest 218 if not port.ip_specialreply: 219 return port.ip_pdrequest 220 return 0 221 222def GetKmsgHeader(kmsgp): 223 """ Helper to get mach message header of a kmsg. 224 Assumes the kmsg has not been put to user. 225 params: 226 kmsgp : core.value representing the given ipc_kmsg_t struct 227 returns: 228 Mach message header for kmsgp 229 """ 230 if kmsgp.ikm_type == GetEnumValue('ipc_kmsg_type_t', 'IKM_TYPE_ALL_INLINED'): 231 return kern.GetValueFromAddress(int(addressof(kmsgp.ikm_big_data)), 'mach_msg_header_t *') 232 if kmsgp.ikm_type == GetEnumValue('ipc_kmsg_type_t', 'IKM_TYPE_UDATA_OOL'): 233 return kern.GetValueFromAddress(int(addressof(kmsgp.ikm_small_data)), 'mach_msg_header_t *') 234 return kern.GetValueFromAddress(unsigned(kmsgp.ikm_kdata), 'mach_msg_header_t *') 235 236@header("{:<20s} {:<20s} {:<20s} {:<10s} {:>6s} {:<20s} {:<8s} {:<26s} {:<26s}".format( 237 "", "kmsg", "header", "msgid", "size", "reply-port", "disp", "source", "destination")) 238def GetKMsgSummary(kmsgp, prefix_str=""): 239 """ Display a summary for type ipc_kmsg_t 240 params: 241 kmsgp : core.value representing the given ipc_kmsg_t struct 242 returns: 243 str : string of summary info for the given ipc_kmsg_t instance 244 """ 245 kmsghp = GetKmsgHeader(kmsgp) 246 kmsgh = dereference(kmsghp) 247 out_string = "" 248 out_string += "{:<20s} {:<#20x} {:<#20x} {kmsgh.msgh_id:#010x} {kmsgh.msgh_size:>6d} {kmsgh.msgh_local_port:<#20x} ".format( 249 '', unsigned(kmsgp), unsigned(kmsghp), kmsgh=kmsghp) 250 prefix_str = "{:<20s} ".format(' ') + prefix_str 251 disposition = "" 252 bits = kmsgh.msgh_bits & 0xff 253 254 # remote port 255 if bits == 17: 256 disposition = "rS" 257 elif bits == 18: 258 disposition = "rO" 259 else : 260 disposition = "rX" # invalid 261 262 out_string += "{:<2s}".format(disposition) 263 264 # local port 265 disposition = "" 266 bits = (kmsgh.msgh_bits & 0xff00) >> 8 267 268 if bits == 17: 269 disposition = "lS" 270 elif bits == 18: 271 disposition = "lO" 272 elif bits == 0: 273 disposition = "l-" 274 else: 275 disposition = "lX" # invalid 276 277 out_string += "{:<2s}".format(disposition) 278 279 # voucher 280 disposition = "" 281 bits = (kmsgh.msgh_bits & 0xff0000) >> 16 282 283 if bits == 17: 284 disposition = "vS" 285 elif bits == 0: 286 disposition = "v-" 287 else: 288 disposition = "vX" 289 290 out_string += "{:<2s}".format(disposition) 291 292 # complex message 293 if kmsgh.msgh_bits & 0x80000000: 294 out_string += "{0: <1s}".format("c") 295 else: 296 out_string += "{0: <1s}".format("s") 297 298 # importance boost 299 if kmsgh.msgh_bits & 0x20000000: 300 out_string += "{0: <1s}".format("I") 301 else: 302 out_string += "{0: <1s}".format("-") 303 304 dest_proc_name = "" 305 if GetKmsgHeader(kmsgp).msgh_remote_port: 306 dest_proc_name = GetPortDestinationSummary(GetKmsgHeader(kmsgp).msgh_remote_port) 307 308 out_string += " {:<26s} {:<26s}\n".format(GetKMsgSrc(kmsgp), dest_proc_name) 309 310 if kmsgh.msgh_bits & 0x80000000: 311 out_string += prefix_str + "\t" + GetKMsgComplexBodyDesc.header + "\n" 312 out_string += prefix_str + "\t" + GetKMsgComplexBodyDesc(kmsgp, prefix_str + "\t") + "\n" 313 314 return out_string 315 316@header("{: <20s} {: <20s} {: <10s}".format("descriptor", "address", "size")) 317def GetMachMsgOOLDescriptorSummary(desc): 318 """ Returns description for mach_msg_ool_descriptor_t * object 319 """ 320 format_string = "{: <#20x} {: <#20x} {:#010x}" 321 out_string = format_string.format(desc, desc.address, desc.size) 322 return out_string 323 324 325def GetKmsgDescriptors(kmsgp): 326 """ Get a list of descriptors in a complex message 327 """ 328 kmsghp = GetKmsgHeader(kmsgp) 329 kmsgh = dereference(kmsghp) 330 if not (kmsgh.msgh_bits & 0x80000000): # pragma pylint: disable=superfluous-parens 331 return [] 332 ## Something in the python/lldb types is not getting alignment correct here. 333 ## I'm grabbing a pointer to the body manually, and using tribal knowledge 334 ## of the location of the descriptor count to get this correct 335 body = Cast(addressof(Cast(addressof(kmsgh), 'char *')[sizeof(kmsgh)]), 'mach_msg_body_t *') 336 #dsc_count = body.msgh_descriptor_count 337 dsc_count = dereference(Cast(body, 'uint32_t *')) 338 #dschead = Cast(addressof(body[1]), 'mach_msg_descriptor_t *') 339 dschead = Cast(addressof(Cast(addressof(body[0]), 'char *')[sizeof('uint32_t')]), 'mach_msg_descriptor_t *') 340 dsc_list = [] 341 for i in range(dsc_count): 342 dsc_list.append(dschead[i]) 343 return (body, dschead, dsc_list) 344 345def GetKmsgTotalDescSize(kmsgp): 346 """ Helper to get total descriptor size of a kmsg. 347 Assumes the kmsg has full kernel representation (header and descriptors) 348 params: 349 kmsgp : core.value representing the given ipc_kmsg_t struct 350 returns: 351 Total descriptor size 352 """ 353 kmsghp = GetKmsgHeader(kmsgp) 354 kmsgh = dereference(kmsghp) 355 dsc_count = 0 356 357 if kmsgh.msgh_bits & 0x80000000: # MACH_MSGH_BITS_COMPLEX 358 (body, _, _) = GetKmsgDescriptors(kmsgp) 359 dsc_count = dereference(Cast(body, 'uint32_t *')) 360 361 return dsc_count * sizeof('mach_msg_descriptor_t') 362 363@header("{: <20s} {: <8s} {: <20s} {: <10s} {: <20s}".format("kmsgheader", "size", "body", "ds_count", "dsc_head")) 364def GetKMsgComplexBodyDesc(kmsgp, prefix_str=""): 365 """ Routine that prints a complex kmsg's body 366 """ 367 kmsghp = GetKmsgHeader(kmsgp) 368 kmsgh = dereference(kmsghp) 369 if not (kmsgh.msgh_bits & 0x80000000): # pragma pylint: disable=superfluous-parens 370 return "" 371 format_string = "{: <#20x} {: <#8x} {: <#20x} {:#010x} {: <#20x}" 372 out_string = "" 373 374 (body, dschead, dsc_list) = GetKmsgDescriptors(kmsgp) 375 out_string += format_string.format(kmsghp, sizeof(dereference(kmsghp)), body, len(dsc_list), dschead) 376 for dsc in dsc_list: 377 try: 378 dsc_type = unsigned(dsc.type.type) 379 out_string += "\n" + prefix_str + "Descriptor: " + xnudefines.mach_msg_type_descriptor_strings[dsc_type] 380 if dsc_type == 0: 381 # its a port. 382 p = dsc.port.name 383 dstr = GetPortDispositionString(dsc.port.disposition) 384 out_string += " disp:{:s}, name:{: <#20x}".format(dstr, p) 385 elif unsigned(dsc.type.type) in (1,3): 386 # its OOL DESCRIPTOR or OOL VOLATILE DESCRIPTOR 387 ool = dsc.out_of_line 388 out_string += " " + GetMachMsgOOLDescriptorSummary(addressof(ool)) 389 except: 390 out_string += "\n" + prefix_str + "Invalid Descriptor: {}".format(dsc) 391 return out_string 392 393def GetKmsgTrailer(kmsgp): 394 """ Helper to get trailer address of a kmsg 395 params: 396 kmsgp : core.value representing the given ipc_kmsg_t struct 397 returns: 398 Trailer address 399 """ 400 kmsghp = GetKmsgHeader(kmsgp) 401 kmsgh = dereference(kmsghp) 402 403 if (kmsgp.ikm_type == int(GetEnumValue('ipc_kmsg_type_t', 'IKM_TYPE_ALL_INLINED')) or 404 kmsgp.ikm_type == int(GetEnumValue('ipc_kmsg_type_t', 'IKM_TYPE_KDATA_OOL'))): 405 return kern.GetValueFromAddress(unsigned(kmsghp) + kmsgh.msgh_size, 'mach_msg_max_trailer_t *') 406 else: 407 if kmsgh.msgh_bits & 0x80000000: # MACH_MSGH_BITS_COMPLEX 408 content_size = kmsgh.msgh_size - sizeof('mach_msg_base_t') - GetKmsgTotalDescSize(kmsgp) 409 else: 410 content_size = kmsgh.msgh_size - sizeof('mach_msg_header_t') 411 return kern.GetValueFromAddress(unsigned(kmsgp.ikm_udata) + content_size, 'mach_msg_max_trailer_t *') 412 413def GetKMsgSrc(kmsgp): 414 """ Routine that prints a kmsg's source process and pid details 415 params: 416 kmsgp : core.value representing the given ipc_kmsg_t struct 417 returns: 418 str : string containing the name and pid of the kmsg's source proc 419 """ 420 trailer = GetKmsgTrailer(kmsgp) 421 kmsgpid = Cast(trailer, 'uint *')[10] # audit_token.val[5] 422 return "{0:s} ({1:d})".format(GetProcNameForPid(kmsgpid), kmsgpid) 423 424@header("{:<20s} {:<20s} {:<10s} {:>6s} {:<6s}".format( 425 "portset", "waitqueue", "name", "refs", "flags")) 426def PrintPortSetSummary(pset, space=0, verbose=True, O=None): 427 """ Display summary for a given struct ipc_pset * 428 params: 429 pset : core.value representing a pset in the kernel 430 returns: 431 str : string of summary information for the given pset 432 """ 433 show_kmsg_summary = False 434 if config['verbosity'] > vHUMAN : 435 show_kmsg_summary = True 436 437 ips_wqset = pset.ips_wqset 438 wqs = Waitq(addressof(ips_wqset)) 439 440 local_name = unsigned(ips_wqset.wqset_index) << 8 441 dest = "-" 442 if space: 443 is_tableval, _ = GetSpaceTable(space) 444 if is_tableval: 445 entry_val = GetObjectAtIndexFromArray(is_tableval, local_name >> 8) 446 local_name |= unsigned(entry_val.ie_bits) >> 24 447 dest = GetSpaceProcDesc(space) 448 else: 449 for wq in wqs.iterateMembers(): 450 dest = GetSpaceProcDesc(wq.asPort().ip_receiver) 451 452 ips_object = pset.ips_object 453 if ips_object.io_bits & 0x80000000: 454 state = "ASet" 455 else: 456 state = "DSet" 457 458 print("{:<#20x} {:<#20x} {:#010x} {:>6d} {:<6s} {:<20s}".format( 459 unsigned(pset), addressof(ips_wqset), local_name, 460 ips_object.io_references, "ASet", dest)) 461 462 if verbose and wqs.hasThreads(): 463 with O.table("{:<20s} {:<20s}".format('waiter', 'event'), indent=True): 464 for thread in wqs.iterateThreads(): 465 print("{:<#20x} {:<#20x}".format(unsigned(thread), thread.wait_event)) 466 print("") 467 468 if verbose and wqs.hasMembers(): 469 with O.table(PrintPortSummary.header, indent=True): 470 for wq in wqs.iterateMembers(): 471 PrintPortSummary(wq.asPort(), show_kmsg_summary=show_kmsg_summary, O=O) 472 print("") 473 474 475 476# Macro: showipc 477 478@lldb_command('showipc') 479def ShowIPC(cmd_args=None): 480 """ Routine to print data for the given IPC space 481 Usage: showipc <address of ipc space> 482 """ 483 if cmd_args is None or len(cmd_args) == 0: 484 raise ArgumentError("No arguments passed") 485 486 ipc = kern.GetValueFromAddress(cmd_args[0], 'ipc_space *') 487 if not ipc: 488 print("unknown arguments:", str(cmd_args)) 489 return False 490 print(PrintIPCInformation.header) 491 PrintIPCInformation(ipc, False, False) 492 return True 493 494# EndMacro: showipc 495 496# Macro: showtaskipc 497 498@lldb_command('showtaskipc') 499def ShowTaskIPC(cmd_args=None): 500 """ Routine to print IPC summary of given task 501 Usage: showtaskipc <address of task> 502 """ 503 if cmd_args is None or len(cmd_args) == 0: 504 raise ArgumentError("No arguments passed") 505 506 tval = kern.GetValueFromAddress(cmd_args[0], 'task *') 507 if not tval: 508 print("unknown arguments:", str(cmd_args)) 509 return False 510 print(GetTaskSummary.header + " " + GetProcSummary.header) 511 pval = GetProcFromTask(tval) 512 print(GetTaskSummary(tval) + " " + GetProcSummary(pval)) 513 print(GetTaskBusyIPCSummary.header) 514 summary, _, _, _ = GetTaskBusyIPCSummary(tval) 515 print(summary) 516 return True 517 518# EndMacro: showtaskipc 519 520# Macro: showallipc 521 522@lldb_command('showallipc') 523def ShowAllIPC(cmd_args=None): 524 """ Routine to print IPC summary of all tasks 525 Usage: showallipc 526 """ 527 for t in kern.tasks: 528 print(GetTaskSummary.header + " " + GetProcSummary.header) 529 pval = GetProcFromTask(t) 530 print(GetTaskSummary(t) + " " + GetProcSummary(pval)) 531 print(PrintIPCInformation.header) 532 PrintIPCInformation(t.itk_space, False, False) 533 print("\n\n") 534 535# EndMacro: showallipc 536 537@lldb_command('showipcsummary', fancy=True) 538def ShowIPCSummary(cmd_args=None, cmd_options={}, O=None): 539 """ Summarizes the IPC state of all tasks. 540 This is a convenient way to dump some basic clues about IPC messaging. You can use the output to determine 541 tasks that are candidates for further investigation. 542 """ 543 with O.table(GetTaskIPCSummary.header): 544 ipc_table_size = 0 545 546 l = [ GetTaskIPCSummary(t) for t in kern.tasks ] 547 l.sort(key = lambda e: e[1], reverse=True) 548 549 for e in l: 550 print(e[0]) 551 ipc_table_size += e[1] 552 553 for t in kern.terminated_tasks: 554 ipc_table_size += GetTaskIPCSummary(t)[1] 555 556 print("Total Table size: {:d}".format(ipc_table_size)) 557 558def GetKObjectFromPort(portval): 559 """ Get Kobject description from the port. 560 params: portval - core.value representation of 'ipc_port *' object 561 returns: str - string of kobject information 562 """ 563 if not portval or portval == xnudefines.MACH_PORT_DEAD: 564 return "MACH_PORT_DEAD" 565 io_bits = unsigned(portval.ip_object.io_bits) 566 objtype_index = io_bits & 0x3ff 567 568 if not objtype_index: 569 return "not a kobject" 570 571 kobject_addr = kern.StripKernelPAC(unsigned(portval.ip_kobject)) 572 objtype_str = GetEnumName('ipc_kotype_t', objtype_index, "IKOT_") 573 574 desc_str = "{:<#20x} {:<16s}".format(kobject_addr, objtype_str) 575 576 if not kobject_addr: 577 pass 578 579 elif objtype_str == 'IOKIT_OBJECT': 580 iokit_classnm = GetObjectTypeStr(portval.ip_kobject) 581 if not iokit_classnm: 582 desc_str += " <unknown class>" 583 else: 584 desc_str += re.sub(r'vtable for ', r' ', iokit_classnm) 585 586 elif objtype_str[:5] == 'TASK_' and objtype_str != 'TASK_ID_TOKEN': 587 task = value(portval.GetSBValue().xCreateValueFromAddress( 588 None, kobject_addr, gettype('struct task')).AddressOf()) 589 if GetProcFromTask(task) is not None: 590 desc_str += " {:s}({:d})".format(GetProcNameForTask(task), GetProcPIDForTask(task)) 591 592 return desc_str 593 594def GetSpaceProcDesc(space): 595 """ Display the name and pid of a space's task 596 params: 597 space: core.value representing a pointer to a space 598 returns: 599 str : string containing receiver's name and pid 600 """ 601 task = space.is_task 602 if GetProcFromTask(task) is None: 603 return "task {:<#20x}".format(unsigned(task)) 604 return "{:s}({:d})".format(GetProcNameForTask(task), GetProcPIDForTask(task)) 605 606def GetPortDestProc(port): 607 """ Display the name and pid of a given port's receiver 608 params: 609 port : core.value representing a pointer to a port in the kernel 610 returns: 611 str : string containing receiver's name and pid 612 """ 613 614 bits = unsigned(port.ip_object.io_bits) # osfmk/ipc/ipc_object.h 615 name = unsigned(port.ip_messages.imq_receiver_name) 616 617 port_is_kobject_port = bits & xnudefines.IO_BITS_KOTYPE 618 619 if bits & xnudefines.IO_BITS_ACTIVE == 0: 620 if port_is_kobject_port: 621 return ('', 'inactive-kobject-port') 622 623 return ('', 'inactive-port') 624 625 if port_is_kobject_port: 626 return ('', GetKObjectFromPort(port)) 627 628 if name == 0: 629 return ('{:<#20x}'.format(port.ip_destination), 'in-transit') 630 631 return ('{:<#20x}'.format(name), GetSpaceProcDesc(port.ip_receiver)) 632 633@header("{:<20s} {:<20s}".format("destname", "destination") ) 634def GetPortDestinationSummary(port): 635 """ Get destination information for a port. 636 params: port - core.value representation of 'ipc_port *' object 637 returns: str - string of info about ports destination 638 """ 639 if not port or port == xnudefines.MACH_PORT_DEAD: 640 return "MACH_PORT_DEAD" 641 a, b = GetPortDestProc(port) 642 return "{:<20s} {:<20s}".format(a, b) 643 644@lldb_type_summary(['ipc_entry_t']) 645@header("{: <20s} {: <12s} {: <8s} {: <8s} {: <8s} {: <8s} {: <20s} {: <20s}".format("object", "name", "rite", "urefs", "nsets", "nmsgs", "destname", "destination")) 646def GetIPCEntrySummary(entry, ipc_name='', rights_filter=0): 647 """ Get summary of a ipc entry. 648 params: 649 entry - core.value representing ipc_entry_t in the kernel 650 ipc_name - str of format '0x0123' for display in summary. 651 returns: 652 str - string of ipc entry related information 653 654 types of rights: 655 'Dead' : Dead name 656 'Set' : Port set 657 'S' : Send right 658 'R' : Receive right 659 'O' : Send-once right 660 'm' : Immovable send port 661 'i' : Immovable receive port 662 'g' : No grant port 663 types of notifications: 664 'd' : Dead-Name notification requested 665 's' : Send-Possible notification armed 666 'r' : Send-Possible notification requested 667 'n' : No-Senders notification requested 668 'x' : Port-destroy notification requested 669 """ 670 out_str = '' 671 entry_ptr = int(hex(entry), 16) 672 format_string = "{: <#20x} {: <12s} {: <8s} {: <8d} {: <8d} {: <8d} {: <20s} {: <20s}" 673 right_str = '' 674 destname_str = '' 675 destination_str = '' 676 677 ie_object = entry.ie_object 678 ie_bits = int(entry.ie_bits) 679 io_bits = int(ie_object.io_bits) if ie_object else 0 680 urefs = int(ie_bits & 0xffff) 681 nsets = 0 682 nmsgs = 0 683 if ie_bits & 0x00100000 : 684 right_str = 'Dead' 685 elif ie_bits & 0x00080000: 686 right_str = 'Set' 687 psetval = kern.CreateTypedPointerFromAddress(unsigned(ie_object), 'struct ipc_pset') 688 wqs = Waitq(addressof(psetval.ips_wqset)) 689 members = 0 690 for m in wqs.iterateMembers(): members += 1 691 destname_str = "{:d} Members".format(members) 692 else: 693 if ie_bits & 0x00010000: 694 if ie_bits & 0x00020000: 695 # SEND + RECV 696 right_str = 'SR' 697 else: 698 # SEND only 699 right_str = 'S' 700 elif ie_bits & 0x00020000: 701 # RECV only 702 right_str = 'R' 703 elif ie_bits & 0x00040000: 704 # SEND_ONCE 705 right_str = 'O' 706 portval = kern.CreateTypedPointerFromAddress(unsigned(ie_object), 'struct ipc_port') 707 if int(entry.ie_request) != 0: 708 requestsval, _ = kalloc_array_decode(portval.ip_requests, 'struct ipc_port_request') 709 sorightval = requestsval[int(entry.ie_request)].ipr_soright 710 soright_ptr = unsigned(sorightval) 711 if soright_ptr != 0: 712 # dead-name notification requested 713 right_str += 'd' 714 # send-possible armed 715 if soright_ptr & 0x1: 716 right_str +='s' 717 # send-possible requested 718 if soright_ptr & 0x2: 719 right_str +='r' 720 # No-senders notification requested 721 if portval.ip_nsrequest != 0: 722 right_str += 'n' 723 # port-destroy notification requested 724 if GetPortPDRequest(portval): 725 right_str += 'x' 726 # Immovable receive rights 727 if portval.ip_immovable_receive != 0: 728 right_str += 'i' 729 # Immovable send rights 730 if portval.ip_immovable_send != 0: 731 right_str += 'm' 732 # No-grant Port 733 if portval.ip_no_grant != 0: 734 right_str += 'g' 735 # Port with SB filtering on 736 if io_bits & 0x00001000 != 0: 737 right_str += 'f' 738 739 # early-out if the rights-filter doesn't match 740 if rights_filter != 0 and rights_filter != right_str: 741 return '' 742 743 # now show the port destination part 744 destname_str = GetPortDestinationSummary(portval) 745 # Get the number of sets to which this port belongs 746 nsets = len([s for s in Waitq(addressof(portval.ip_waitq)).iterateSets()]) 747 nmsgs = portval.ip_messages.imq_msgcount 748 749 # append the generation to the name value 750 # (from osfmk/ipc/ipc_entry.h) 751 # bits rollover period 752 # 0 0 64 753 # 0 1 48 754 # 1 0 32 755 # 1 1 16 756 ie_gen_roll = { 0:'.64', 1:'.48', 2:'.32', 3:'.16' } 757 ipc_name = '{:s}{:s}'.format(ipc_name.strip(), ie_gen_roll[(ie_bits & 0x00c00000) >> 22]) 758 759 if rights_filter == 0 or rights_filter == right_str: 760 out_str = format_string.format(ie_object, ipc_name, right_str, urefs, nsets, nmsgs, destname_str, destination_str) 761 return out_str 762 763@header("{0: >20s}".format("user bt") ) 764def GetPortUserStack(port, task): 765 """ Get UserStack information for the given port & task. 766 params: port - core.value representation of 'ipc_port *' object 767 task - value representing 'task *' object 768 returns: str - string information on port's userstack 769 """ 770 out_str = '' 771 if not port or port == xnudefines.MACH_PORT_DEAD: 772 return out_str 773 pid = port.ip_made_pid 774 proc_val = GetProcFromTask(task) 775 if port.ip_made_bt: 776 btlib = kmemory.BTLibrary.get_shared() 777 out_str += "\n".join(btlib.get_stack(port.ip_made_bt).symbolicated_frames()) + "\n" 778 if pid != GetProcPID(proc_val): 779 out_str += " ({:<10d})\n".format(pid) 780 return out_str 781 782@lldb_type_summary(['ipc_space *']) 783@header("{0: <20s} {1: <20s} {2: <20s} {3: <8s} {4: <10s} {5: >8s} {6: <8s}".format('ipc_space', 'is_task', 'is_table', 'flags', 'ports', 'low_mod', 'high_mod')) 784def PrintIPCInformation(space, show_entries=False, show_userstack=False, rights_filter=0): 785 """ Provide a summary of the ipc space 786 """ 787 out_str = '' 788 format_string = "{0: <#20x} {1: <#20x} {2: <#20x} {3: <8s} {4: <10d} {5: >8d} {6: <8d}" 789 is_tableval, num_entries = GetSpaceTable(space) 790 flags ='' 791 if is_tableval: 792 flags += 'A' 793 else: 794 flags += ' ' 795 if (space.is_grower) != 0: 796 flags += 'G' 797 print(format_string.format(space, space.is_task, is_tableval if is_tableval else 0, flags, 798 num_entries, space.is_low_mod, space.is_high_mod)) 799 800 #should show the each individual entries if asked. 801 if show_entries and is_tableval: 802 print("\t" + GetIPCEntrySummary.header) 803 804 entries = ( 805 (index, value(iep.AddressOf())) 806 for index, iep 807 in GetSpaceEntriesWithBits(is_tableval, num_entries, 0x001f0000) 808 ) 809 810 for index, entryval in entries: 811 entry_ie_bits = unsigned(entryval.ie_bits) 812 entry_name = "{0: <#20x}".format( (index <<8 | entry_ie_bits >> 24) ) 813 entry_str = GetIPCEntrySummary(entryval, entry_name, rights_filter) 814 if not entry_str: 815 continue 816 817 print("\t" + entry_str) 818 if show_userstack: 819 entryport = Cast(entryval.ie_object, 'ipc_port *') 820 if entryval.ie_object and (int(entry_ie_bits) & 0x00070000) and entryport.ip_made_bt: 821 print(GetPortUserStack.header + GetPortUserStack(entryport, space.is_task)) 822 823 #done with showing entries 824 return out_str 825 826# Macro: showrights 827 828@lldb_command('showrights', 'R:') 829def ShowRights(cmd_args=None, cmd_options={}): 830 """ Routine to print rights information for the given IPC space 831 Usage: showrights [-R rights_type] <address of ipc space> 832 -R rights_type : only display rights matching the string 'rights_type' 833 834 types of rights: 835 'Dead' : Dead name 836 'Set' : Port set 837 'S' : Send right 838 'R' : Receive right 839 'O' : Send-once right 840 types of notifications: 841 'd' : Dead-Name notification requested 842 's' : Send-Possible notification armed 843 'r' : Send-Possible notification requested 844 'n' : No-Senders notification requested 845 'x' : Port-destroy notification requested 846 """ 847 if cmd_args is None or len(cmd_args) == 0: 848 raise ArgumentError("No arguments passed") 849 850 ipc = kern.GetValueFromAddress(cmd_args[0], 'ipc_space *') 851 if not ipc: 852 print("unknown arguments:", str(cmd_args)) 853 return False 854 rights_type = 0 855 if "-R" in cmd_options: 856 rights_type = cmd_options["-R"] 857 print(PrintIPCInformation.header) 858 PrintIPCInformation(ipc, True, False, rights_type) 859 860# EndMacro: showrights 861 862@lldb_command('showtaskrights','R:') 863def ShowTaskRights(cmd_args=None, cmd_options={}): 864 """ Routine to ipc rights information for a task 865 Usage: showtaskrights [-R rights_type] <task address> 866 -R rights_type : only display rights matching the string 'rights_type' 867 868 types of rights: 869 'Dead' : Dead name 870 'Set' : Port set 871 'S' : Send right 872 'R' : Receive right 873 'O' : Send-once right 874 'm' : Immovable send port 875 'i' : Immovable receive port 876 'g' : No grant port 877 'f' : Port with SB filtering on 878 types of notifications: 879 'd' : Dead-Name notification requested 880 's' : Send-Possible notification armed 881 'r' : Send-Possible notification requested 882 'n' : No-Senders notification requested 883 'x' : Port-destroy notification requested 884 """ 885 if cmd_args is None or len(cmd_args) == 0: 886 raise ArgumentError("No arguments passed") 887 888 tval = kern.GetValueFromAddress(cmd_args[0], 'task *') 889 if not tval: 890 print("unknown arguments:", str(cmd_args)) 891 return False 892 rights_type = 0 893 if "-R" in cmd_options: 894 rights_type = cmd_options["-R"] 895 print(GetTaskSummary.header + " " + GetProcSummary.header) 896 pval = GetProcFromTask(tval) 897 print(GetTaskSummary(tval) + " " + GetProcSummary(pval)) 898 print(PrintIPCInformation.header) 899 PrintIPCInformation(tval.itk_space, True, False, rights_type) 900 901# Count the vouchers in a given task's ipc space 902@header("{: <20s} {: <6s} {: <20s} {: <8s}".format("task", "pid", "name", "#vouchers")) 903def GetTaskVoucherCount(t): 904 is_tableval, num_entries = GetSpaceTable(t.itk_space) 905 count = 0 906 voucher_kotype = int(GetEnumValue('ipc_kotype_t', 'IKOT_VOUCHER')) 907 908 if is_tableval: 909 ports = GetSpaceObjectsWithBits(is_tableval, num_entries, 0x00070000, 910 gettype('struct ipc_port')) 911 912 for port in ports: 913 io_bits = port.xGetIntegerByPath('.ip_object.io_bits') 914 if io_bits & 0x3ff == voucher_kotype: 915 count += 1 916 917 format_str = "{: <#20x} {: <6d} {: <20s} {: <8d}" 918 pval = GetProcFromTask(t) 919 return format_str.format(t, GetProcPID(pval), GetProcNameForTask(t), count) 920 921# Macro: countallvouchers 922@lldb_command('countallvouchers', fancy=True) 923def CountAllVouchers(cmd_args=None, cmd_options={}, O=None): 924 """ Routine to count the number of vouchers by task. Useful for finding leaks. 925 Usage: countallvouchers 926 """ 927 928 with O.table(GetTaskVoucherCount.header): 929 for t in kern.tasks: 930 print(GetTaskVoucherCount(t)) 931 932# Macro: showataskrightsbt 933 934@lldb_command('showtaskrightsbt', 'R:') 935def ShowTaskRightsBt(cmd_args=None, cmd_options={}): 936 """ Routine to ipc rights information with userstacks for a task 937 Usage: showtaskrightsbt [-R rights_type] <task address> 938 -R rights_type : only display rights matching the string 'rights_type' 939 940 types of rights: 941 'Dead' : Dead name 942 'Set' : Port set 943 'S' : Send right 944 'R' : Receive right 945 'O' : Send-once right 946 'm' : Immovable send port 947 'i' : Immovable receive port 948 'g' : No grant port 949 types of notifications: 950 'd' : Dead-Name notification requested 951 's' : Send-Possible notification armed 952 'r' : Send-Possible notification requested 953 'n' : No-Senders notification requested 954 'x' : Port-destroy notification requested 955 """ 956 if cmd_args is None or len(cmd_args) == 0: 957 raise ArgumentError("No arguments passed") 958 959 tval = kern.GetValueFromAddress(cmd_args[0], 'task *') 960 if not tval: 961 print("unknown arguments:", str(cmd_args)) 962 return False 963 rights_type = 0 964 if "-R" in cmd_options: 965 rights_type = cmd_options["-R"] 966 print(GetTaskSummary.header + " " + GetProcSummary.header) 967 pval = GetProcFromTask(tval) 968 print(GetTaskSummary(tval) + " " + GetProcSummary(pval)) 969 print(PrintIPCInformation.header) 970 PrintIPCInformation(tval.itk_space, True, True, rights_type) 971 972# EndMacro: showtaskrightsbt 973 974# Macro: showallrights 975 976@lldb_command('showallrights', 'R:') 977def ShowAllRights(cmd_args=None, cmd_options={}): 978 """ Routine to print rights information for IPC space of all tasks 979 Usage: showallrights [-R rights_type] 980 -R rights_type : only display rights matching the string 'rights_type' 981 982 types of rights: 983 'Dead' : Dead name 984 'Set' : Port set 985 'S' : Send right 986 'R' : Receive right 987 'O' : Send-once right 988 'm' : Immovable send port 989 'i' : Immovable receive port 990 'g' : No grant port 991 types of notifications: 992 'd' : Dead-Name notification requested 993 's' : Send-Possible notification armed 994 'r' : Send-Possible notification requested 995 'n' : No-Senders notification requested 996 'x' : Port-destroy notification requested 997 """ 998 rights_type = 0 999 if "-R" in cmd_options: 1000 rights_type = cmd_options["-R"] 1001 for t in kern.tasks: 1002 print(GetTaskSummary.header + " " + GetProcSummary.header) 1003 pval = GetProcFromTask(t) 1004 print(GetTaskSummary(t) + " " + GetProcSummary(pval)) 1005 try: 1006 print(PrintIPCInformation.header) 1007 PrintIPCInformation(t.itk_space, True, False, rights_type) + "\n\n" 1008 except (KeyboardInterrupt, SystemExit): 1009 raise 1010 except: 1011 print("Failed to get IPC information. Do individual showtaskrights <task> to find the error. \n\n") 1012 1013# EndMacro: showallrights 1014 1015 1016def GetInTransitPortSummary(port, disp, holding_port, holding_kmsg): 1017 """ String-ify the in-transit dispostion of a port. 1018 """ 1019 ## This should match the summary generated by GetIPCEntrySummary 1020 ## "object" "name" "rite" "urefs" "nsets" "nmsgs" "destname" "destination" 1021 format_str = "\t{: <#20x} {: <12} {: <8s} {: <8d} {: <8d} {: <8d} p:{: <#19x} k:{: <#19x}" 1022 portname = 'intransit' 1023 1024 disp_str = GetPortDispositionString(disp) 1025 1026 out_str = format_str.format(unsigned(port), 'in-transit', disp_str, 0, 0, port.ip_messages.imq_msgcount, unsigned(holding_port), unsigned(holding_kmsg)) 1027 return out_str 1028 1029 1030def GetDispositionFromEntryType(entry_bits): 1031 """ Translate an IPC entry type into an in-transit disposition. This allows 1032 the GetInTransitPortSummary function to be re-used to string-ify IPC 1033 entry types. 1034 """ 1035 ebits = int(entry_bits) 1036 if (ebits & 0x003f0000) == 0: 1037 return 0 1038 1039 if (ebits & 0x00010000) != 0: 1040 return 17 ## MACH_PORT_RIGHT_SEND 1041 elif (ebits & 0x00020000) != 0: 1042 return 16 ## MACH_PORT_RIGHT_RECEIVE 1043 elif (ebits & 0x00040000) != 0: 1044 return 18 ## MACH_PORT_RIGHT_SEND_ONCE 1045 elif (ebits & 0x00080000) != 0: 1046 return 100 ## MACH_PORT_RIGHT_PORT_SET 1047 elif (ebits & 0x00100000) != 0: 1048 return 101 ## MACH_PORT_RIGHT_DEAD_NAME 1049 elif (ebits & 0x00200000) != 0: 1050 return 102 ## MACH_PORT_RIGHT_LABELH 1051 else: 1052 return 0 1053 1054def GetDispositionFromVoucherPort(th_vport): 1055 """ Translate a thread's voucher port into a 'disposition' 1056 """ 1057 if unsigned(th_vport) > 0: 1058 return 103 ## Voucher type 1059 return 0 1060 1061 1062g_kmsg_prog = 0 1063g_progmeter = { 1064 0 : '*', 1065 1 : '-', 1066 2 : '\\', 1067 3 : '|', 1068 4 : '/', 1069 5 : '-', 1070 6 : '\\', 1071 7 : '|', 1072 8 : '/', 1073} 1074 1075def PrintProgressForKmsg(): 1076 global g_kmsg_prog 1077 global g_progmeter 1078 sys.stderr.write(" {:<1s}\r".format(g_progmeter[g_kmsg_prog % 9])) 1079 g_kmsg_prog += 1 1080 1081 1082def CollectPortsForAnalysis(port, disposition): 1083 """ 1084 """ 1085 if not port or port == xnudefines.MACH_PORT_DEAD: 1086 return 1087 p = Cast(port, 'struct ipc_port *') 1088 yield (p, disposition) 1089 1090 # no-senders notification port 1091 if unsigned(p.ip_nsrequest) not in (0, 1): # 1 is IP_KOBJECT_NSREQUEST_ARMED 1092 PrintProgressForKmsg() 1093 yield (p.ip_nsrequest, -1) 1094 1095 # port-death notification port 1096 pdrequest = GetPortPDRequest(p) 1097 if pdrequest: 1098 PrintProgressForKmsg() 1099 yield (pdrequest, -2) 1100 1101 ## ports can have many send-possible notifications armed: go through the table! 1102 if unsigned(p.ip_requests) != 0: 1103 table, table_sz = kalloc_array_decode(p.ip_requests, 'struct ipc_port_request') 1104 for i in range(table_sz): 1105 if i == 0: 1106 continue 1107 ipr = table[i] 1108 if unsigned(ipr.ipr_name) in (0, 0xfffffffe): 1109 # 0xfffffffe is a host notify request 1110 continue 1111 ipr_bits = unsigned(ipr.ipr_soright) & 3 1112 ipr_port = kern.GetValueFromAddress(int(ipr.ipr_soright) & ~3, 'struct ipc_port *') 1113 # skip unused entries in the ipc table to avoid null dereferences 1114 if not ipr_port: 1115 continue 1116 ipr_disp = 0 1117 if ipr_bits & 3: ## send-possible armed and requested 1118 ipr_disp = -5 1119 elif ipr_bits & 2: ## send-possible requested 1120 ipr_disp = -4 1121 elif ipr_bits & 1: ## send-possible armed 1122 ipr_disp = -3 1123 PrintProgressForKmsg() 1124 yield (ipr_port, ipr_disp) 1125 return 1126 1127def CollectKmsgPorts(task, task_port, kmsgp): 1128 """ Look through a message, 'kmsgp' destined for 'task' 1129 (enqueued on task_port). Collect any port descriptors, 1130 remote, local, voucher, or other port references 1131 into a (ipc_port_t, disposition) list. 1132 """ 1133 kmsgh = dereference(GetKmsgHeader(kmsgp)) 1134 1135 p_list = [] 1136 1137 PrintProgressForKmsg() 1138 if kmsgh.msgh_remote_port and unsigned(kmsgh.msgh_remote_port) != unsigned(task_port): 1139 disp = kmsgh.msgh_bits & 0x1f 1140 p_list += list(CollectPortsForAnalysis(kmsgh.msgh_remote_port, disp)) 1141 1142 if kmsgh.msgh_local_port and unsigned(kmsgh.msgh_local_port) != unsigned(task_port) \ 1143 and unsigned(kmsgh.msgh_local_port) != unsigned(kmsgh.msgh_remote_port): 1144 disp = (kmsgh.msgh_bits & 0x1f00) >> 8 1145 p_list += list(CollectPortsForAnalysis(kmsgh.msgh_local_port, disp)) 1146 1147 if kmsgp.ikm_voucher_port: 1148 p_list += list(CollectPortsForAnalysis(kmsgp.ikm_voucher_port, 0)) 1149 1150 if kmsgh.msgh_bits & 0x80000000: 1151 ## Complex message - look for descriptors 1152 PrintProgressForKmsg() 1153 (body, dschead, dsc_list) = GetKmsgDescriptors(kmsgp) 1154 for dsc in dsc_list: 1155 PrintProgressForKmsg() 1156 dsc_type = unsigned(dsc.type.type) 1157 if dsc_type == 0 or dsc_type == 2: ## 0 == port, 2 == ool port 1158 if dsc_type == 0: 1159 ## its a port descriptor 1160 dsc_disp = dsc.port.disposition 1161 p_list += list(CollectPortsForAnalysis(dsc.port.name, dsc_disp)) 1162 else: 1163 ## it's an ool_ports descriptor which is an array of ports 1164 dsc_disp = dsc.ool_ports.disposition 1165 dispdata = Cast(dsc.ool_ports.address, 'struct ipc_port *') 1166 for pidx in range(dsc.ool_ports.count): 1167 PrintProgressForKmsg() 1168 p_list += list(CollectPortsForAnalysis(dispdata[pidx], dsc_disp)) 1169 return p_list 1170 1171def CollectKmsgPortRefs(task, task_port, kmsgp, p_refs): 1172 """ Recursively collect all references to ports inside the kmsg 'kmsgp' 1173 into the set 'p_refs' 1174 """ 1175 p_list = CollectKmsgPorts(task, task_port, kmsgp) 1176 1177 ## Iterate over each ports we've collected, to see if they 1178 ## have messages on them, and then recurse! 1179 for p, pdisp in p_list: 1180 ptype = (p.ip_object.io_bits & 0x7fff0000) >> 16 1181 p_refs.add((p, pdisp, ptype)) 1182 if ptype != 0: ## don't bother with port sets 1183 continue 1184 ## If the port that's in-transit has messages already enqueued, 1185 ## go through each of those messages and look for more ports! 1186 for p_kmsgp in IterateCircleQueue(p.ip_messages.imq_messages, 'ipc_kmsg', 'ikm_link'): 1187 CollectKmsgPortRefs(task, p, p_kmsgp, p_refs) 1188 1189 1190def FindKmsgPortRefs(instr, task, task_port, kmsgp, qport): 1191 """ Look through a message, 'kmsgp' destined for 'task'. If we find 1192 any port descriptors, remote, local, voucher, or other port that 1193 matches 'qport', return a short description 1194 which should match the format of GetIPCEntrySummary. 1195 """ 1196 1197 out_str = instr 1198 p_list = CollectKmsgPorts(task, task_port, kmsgp) 1199 1200 ## Run through all ports we've collected looking for 'qport' 1201 for p, pdisp in p_list: 1202 PrintProgressForKmsg() 1203 if unsigned(p) == unsigned(qport): 1204 ## the port we're looking for was found in this message! 1205 if len(out_str) > 0: 1206 out_str += '\n' 1207 out_str += GetInTransitPortSummary(p, pdisp, task_port, kmsgp) 1208 1209 ptype = (p.ip_object.io_bits & 0x7fff0000) >> 16 1210 if ptype != 0: ## don't bother with port sets 1211 continue 1212 1213 ## If the port that's in-transit has messages already enqueued, 1214 ## go through each of those messages and look for more ports! 1215 for p_kmsgp in IterateCircleQueue(p.ip_messages.imq_messages, 'ipc_kmsg', 'ikm_link'): 1216 out_str = FindKmsgPortRefs(out_str, task, p, p_kmsgp, qport) 1217 1218 return out_str 1219 1220 1221port_iteration_do_print_taskname = False 1222registeredport_idx = -10 1223excports_idx = -20 1224intransit_idx = -1000 1225taskports_idx = -2000 1226thports_idx = -3000 1227 1228def IterateAllPorts(tasklist, func, ctx, include_psets, follow_busyports, should_log): 1229 """ Iterate over all ports in the system, calling 'func' 1230 for each entry in 1231 """ 1232 global port_iteration_do_print_taskname 1233 global intransit_idx, taskports_idx, thports_idx, registeredport_idx, excports_idx 1234 1235 ## XXX: also host special ports 1236 1237 entry_port_type_mask = 0x00070000 1238 if include_psets: 1239 entry_port_type_mask = 0x000f0000 1240 1241 if tasklist is None: 1242 tasklist = list(kern.tasks) 1243 tasklist += list(kern.terminated_tasks) 1244 1245 tidx = 1 1246 1247 for t in tasklist: 1248 # Write a progress line. Using stderr avoids automatic newline when 1249 # writing to stdout from lldb. Blank spaces at the end clear out long 1250 # lines. 1251 if should_log: 1252 procname = "" 1253 if not t.active: 1254 procname = 'terminated: ' 1255 if t.halting: 1256 procname += 'halting: ' 1257 procname += GetProcNameForTask(t) 1258 sys.stderr.write(" checking {:s} ({}/{})...{:50s}\r".format(procname, tidx, len(tasklist), '')) 1259 tidx += 1 1260 1261 port_iteration_do_print_taskname = True 1262 space = t.itk_space 1263 is_tableval, num_entries = GetSpaceTable(space) 1264 1265 if not is_tableval: 1266 continue 1267 1268 base = is_tableval.GetSBValue().Dereference() 1269 entries = ( 1270 value(iep.AddressOf()) 1271 for iep in base.xIterSiblings(1, num_entries) 1272 ) 1273 1274 for idx, entry_val in enumerate(entries, 1): 1275 entry_bits= unsigned(entry_val.ie_bits) 1276 entry_obj = 0 1277 entry_str = '' 1278 entry_name = "{:x}".format( (idx << 8 | entry_bits >> 24) ) 1279 1280 entry_disp = GetDispositionFromEntryType(entry_bits) 1281 1282 ## If the entry in the table represents a port of some sort, 1283 ## then make the callback provided 1284 if int(entry_bits) & entry_port_type_mask: 1285 eport = kern.CreateTypedPointerFromAddress(unsigned(entry_val.ie_object), 'struct ipc_port') 1286 ## Make the callback 1287 func(t, space, ctx, idx, entry_val, eport, entry_disp) 1288 1289 ## if the port has pending messages, look through 1290 ## each message for ports (and recurse) 1291 if follow_busyports and unsigned(eport) > 0 and eport.ip_messages.imq_msgcount > 0: 1292 ## collect all port references from all messages 1293 for kmsgp in IterateCircleQueue(eport.ip_messages.imq_messages, 'ipc_kmsg', 'ikm_link'): 1294 p_refs = set() 1295 CollectKmsgPortRefs(t, eport, kmsgp, p_refs) 1296 for (port, pdisp, ptype) in p_refs: 1297 func(t, space, ctx, intransit_idx, None, port, pdisp) 1298 ## for idx in xrange(1, num_entries) 1299 1300 ## Task ports (send rights) 1301 if getattr(t, 'itk_settable_self', 0) > 0: 1302 func(t, space, ctx, taskports_idx, 0, t.itk_settable_self, 17) 1303 if unsigned(t.itk_host) > 0: 1304 func(t, space, ctx, taskports_idx, 0, t.itk_host, 17) 1305 if unsigned(t.itk_bootstrap) > 0: 1306 func(t, space, ctx, taskports_idx, 0, t.itk_bootstrap, 17) 1307 if unsigned(t.itk_debug_control) > 0: 1308 func(t, space, ctx, taskports_idx, 0, t.itk_debug_control, 17) 1309 if unsigned(t.itk_task_access) > 0: 1310 func(t, space, ctx, taskports_idx, 0, t.itk_task_access, 17) 1311 if unsigned(t.itk_task_ports[1]) > 0: ## task read port 1312 func(t, space, ctx, taskports_idx, 0, t.itk_task_ports[1], 17) 1313 if unsigned(t.itk_task_ports[2]) > 0: ## task inspect port 1314 func(t, space, ctx, taskports_idx, 0, t.itk_task_ports[2], 17) 1315 1316 ## Task name port (not a send right, just a naked ref); TASK_FLAVOR_NAME = 3 1317 if unsigned(t.itk_task_ports[3]) > 0: 1318 func(t, space, ctx, taskports_idx, 0, t.itk_task_ports[3], 0) 1319 1320 ## task resume port is a receive right to resume the task 1321 if unsigned(t.itk_resume) > 0: 1322 func(t, space, ctx, taskports_idx, 0, t.itk_resume, 16) 1323 1324 ## registered task ports (all send rights) 1325 tr_idx = 0 1326 tr_max = sizeof(t.itk_registered) // sizeof(t.itk_registered[0]) 1327 while tr_idx < tr_max: 1328 tport = t.itk_registered[tr_idx] 1329 if unsigned(tport) > 0: 1330 try: 1331 func(t, space, ctx, registeredport_idx, 0, tport, 17) 1332 except Exception as e: 1333 print("\texception looking through registered port {:d}/{:d} in {:s}".format(tr_idx,tr_max,t)) 1334 pass 1335 tr_idx += 1 1336 1337 ## Task exception ports 1338 exidx = 0 1339 exmax = sizeof(t.exc_actions) // sizeof(t.exc_actions[0]) 1340 while exidx < exmax: ## see: osfmk/mach/[arm|i386]/exception.h 1341 export = t.exc_actions[exidx].port ## send right 1342 if unsigned(export) > 0: 1343 try: 1344 func(t, space, ctx, excports_idx, 0, export, 17) 1345 except Exception as e: 1346 print("\texception looking through exception port {:d}/{:d} in {:s}".format(exidx,exmax,t)) 1347 pass 1348 exidx += 1 1349 1350 ## XXX: any ports still valid after clearing IPC space?! 1351 1352 for thval in IterateQueue(t.threads, 'thread *', 'task_threads'): 1353 ## XXX: look at block reason to see if it's in mach_msg_receive - then look at saved state / message 1354 1355 ## Thread port (send right) 1356 if getattr(thval.t_tro, 'tro_settable_self_port', 0) > 0: 1357 thport = thval.t_tro.tro_settable_self_port 1358 func(t, space, ctx, thports_idx, 0, thport, 17) ## see: osfmk/mach/message.h 1359 ## Thread special reply port (send-once right) 1360 if unsigned(thval.ith_special_reply_port) > 0: 1361 thport = thval.ith_special_reply_port 1362 func(t, space, ctx, thports_idx, 0, thport, 18) ## see: osfmk/mach/message.h 1363 ## Thread voucher port 1364 if unsigned(thval.ith_voucher) > 0: 1365 vport = thval.ith_voucher.iv_port 1366 if unsigned(vport) > 0: 1367 vdisp = GetDispositionFromVoucherPort(vport) 1368 func(t, space, ctx, thports_idx, 0, vport, vdisp) 1369 ## Thread exception ports 1370 if unsigned(thval.t_tro.tro_exc_actions) > 0: 1371 exidx = 0 1372 while exidx < exmax: ## see: osfmk/mach/[arm|i386]/exception.h 1373 export = thval.t_tro.tro_exc_actions[exidx].port ## send right 1374 if unsigned(export) > 0: 1375 try: 1376 func(t, space, ctx, excports_idx, 0, export, 17) 1377 except Exception as e: 1378 print("\texception looking through exception port {:d}/{:d} in {:s}".format(exidx,exmax,t)) 1379 pass 1380 exidx += 1 1381 ## XXX: the message on a thread (that's currently being received) 1382 ## for (thval in t.threads) 1383 ## for (t in tasklist) 1384 1385 1386# Macro: findportrights 1387def FindPortRightsCallback(task, space, ctx, entry_idx, ipc_entry, ipc_port, port_disp): 1388 """ Callback which uses 'ctx' as the (port,rights_types) tuple for which 1389 a caller is seeking references. This should *not* be used from a 1390 recursive call to IterateAllPorts. 1391 """ 1392 global port_iteration_do_print_taskname 1393 1394 (qport, rights_type) = ctx 1395 entry_name = '' 1396 entry_str = '' 1397 if unsigned(ipc_entry) != 0: 1398 entry_bits = unsigned(ipc_entry.ie_bits) 1399 entry_name = "{:x}".format( (entry_idx << 8 | entry_bits >> 24) ) 1400 if (int(entry_bits) & 0x001f0000) != 0 and unsigned(ipc_entry.ie_object) == unsigned(qport): 1401 ## it's a valid entry, and it points to the port 1402 entry_str = '\t' + GetIPCEntrySummary(ipc_entry, entry_name, rights_type) 1403 1404 procname = GetProcNameForTask(task) 1405 if ipc_port and ipc_port != xnudefines.MACH_PORT_DEAD and ipc_port.ip_messages.imq_msgcount > 0: 1406 sys.stderr.write(" checking {:s} busy-port {}:{:#x}...{:30s}\r".format(procname, entry_name, unsigned(ipc_port), '')) 1407 ## Search through busy ports to find descriptors which could 1408 ## contain the only reference to this port! 1409 for kmsgp in IterateCircleQueue(ipc_port.ip_messages.imq_messages, 'ipc_kmsg', 'ikm_link'): 1410 entry_str = FindKmsgPortRefs(entry_str, task, ipc_port, kmsgp, qport) 1411 1412 if len(entry_str) > 0: 1413 sys.stderr.write("{:80s}\r".format('')) 1414 if port_iteration_do_print_taskname: 1415 print("Task: {0: <#x} {1: <s}".format(task, procname)) 1416 print('\t' + GetIPCEntrySummary.header) 1417 port_iteration_do_print_taskname = False 1418 print(entry_str) 1419 1420@lldb_command('findportrights', 'R:S:') 1421def FindPortRights(cmd_args=None, cmd_options={}): 1422 """ Routine to locate and print all extant rights to a given port 1423 Usage: findportrights [-R rights_type] [-S <ipc_space_t>] <ipc_port_t> 1424 -S ipc_space : only search the specified ipc space 1425 -R rights_type : only display rights matching the string 'rights_type' 1426 1427 types of rights: 1428 'Dead' : Dead name 1429 'Set' : Port set 1430 'S' : Send right 1431 'R' : Receive right 1432 'O' : Send-once right 1433 types of notifications: 1434 'd' : Dead-Name notification requested 1435 's' : Send-Possible notification armed 1436 'r' : Send-Possible notification requested 1437 'n' : No-Senders notification requested 1438 'x' : Port-destroy notification requested 1439 """ 1440 if cmd_args is None or len(cmd_args) == 0: 1441 raise ArgumentError("no port address provided") 1442 port = kern.GetValueFromAddress(cmd_args[0], 'struct ipc_port *') 1443 1444 rights_type = 0 1445 if "-R" in cmd_options: 1446 rights_type = cmd_options["-R"] 1447 1448 tasklist = None 1449 if "-S" in cmd_options: 1450 space = kern.GetValueFromAddress(cmd_options["-S"], 'struct ipc_space *') 1451 tasklist = [ space.is_task ] 1452 1453 ## Don't include port sets 1454 ## Don't recurse on busy ports (we do that manually) 1455 ## DO log progress 1456 IterateAllPorts(tasklist, FindPortRightsCallback, (port, rights_type), False, False, True) 1457 sys.stderr.write("{:120s}\r".format(' ')) 1458 1459 print("Done.") 1460# EndMacro: findportrights 1461 1462# Macro: countallports 1463 1464def CountPortsCallback(task, space, ctx, entry_idx, ipc_entry, ipc_port, port_disp): 1465 """ Callback which uses 'ctx' as the set of all ports found in the 1466 iteration. This should *not* be used from a recursive 1467 call to IterateAllPorts. 1468 """ 1469 global intransit_idx 1470 1471 (p_set, p_intransit, p_bytask) = ctx 1472 1473 ## Add the port address to the set of all port addresses 1474 ipc_port_addr = unsigned(ipc_port) 1475 p_set.add(ipc_port_addr) 1476 1477 if entry_idx == intransit_idx: 1478 p_intransit.add(ipc_port_addr) 1479 1480 if task.active or (task.halting and not task.active): 1481 if not task in p_bytask: 1482 p_bytask[task] = { 'transit':0, 'table':0, 'other':0 } 1483 if entry_idx == intransit_idx: 1484 p_bytask[task]['transit'] += 1 1485 elif entry_idx >= 0: 1486 p_bytask[task]['table'] += 1 1487 else: 1488 p_bytask[task]['other'] += 1 1489 1490@header(f"{'#ports': <10s} {'in transit': <10s} {'Special': <10s}") 1491@lldb_command('countallports', 'P', fancy=True) 1492def CountAllPorts(cmd_args=None, cmd_options={}, O=None): 1493 """ Routine to search for all as many references to ipc_port structures in the kernel 1494 that we can find. 1495 Usage: countallports [-P] 1496 -P : include port sets in the count (default: NO) 1497 """ 1498 p_set = set() 1499 p_intransit = set() 1500 p_bytask = {} 1501 1502 find_psets = False 1503 if "-P" in cmd_options: 1504 find_psets = True 1505 1506 ## optionally include port sets 1507 ## DO recurse on busy ports 1508 ## DO log progress 1509 IterateAllPorts(None, CountPortsCallback, (p_set, p_intransit, p_bytask), find_psets, True, True) 1510 sys.stderr.write(f"{' ':120s}\r") 1511 1512 # sort by ipc table size 1513 with O.table(GetTaskIPCSummary.header + ' ' + CountAllPorts.header): 1514 for task, port_summary in sorted(p_bytask.items(), key=lambda item: item[1]['table'], reverse=True): 1515 outstring, _ = GetTaskIPCSummary(task) 1516 outstring += f" {port_summary['table']: <10d} {port_summary['transit']: <10d} {port_summary['other']: <10d}" 1517 print(outstring) 1518 1519 print(f"\nTotal ports found: {len(p_set)}") 1520 print(f"Number of ports In Transit: {len(p_intransit)}") 1521 1522# EndMacro: countallports 1523# Macro: showpipestats 1524 1525@lldb_command('showpipestats') 1526def ShowPipeStats(cmd_args=None): 1527 """ Display pipes usage information in the kernel 1528 """ 1529 print("Number of pipes: {: d}".format(kern.globals.amountpipes)) 1530 print("Memory used by pipes: {:s}".format(sizeof_fmt(int(kern.globals.amountpipekva)))) 1531 print("Max memory allowed for pipes: {:s}".format(sizeof_fmt(int(kern.globals.maxpipekva)))) 1532 1533# EndMacro: showpipestats 1534# Macro: showtaskbusyports 1535 1536@lldb_command('showtaskbusyports', fancy=True) 1537def ShowTaskBusyPorts(cmd_args=None, cmd_options={}, O=None): 1538 """ Routine to print information about receive rights belonging to this task that 1539 have enqueued messages. This is often a sign of a blocked or hung process 1540 Usage: showtaskbusyports <task address> 1541 """ 1542 if cmd_args is None or len(cmd_args) == 0: 1543 raise ArgumentError("No arguments passed. Please pass in the address of a task") 1544 1545 task = kern.GetValueFromAddress(cmd_args[0], 'task_t') 1546 is_tableval, num_entries = GetSpaceTable(task.itk_space) 1547 1548 if is_tableval: 1549 ports = GetSpaceObjectsWithBits(is_tableval, num_entries, 0x00020000, 1550 gettype('struct ipc_port')) 1551 1552 with O.table(PrintPortSummary.header): 1553 for port in ports: 1554 if port.xGetIntegerByPath('.ip_messages.imq_msgcount'): 1555 PrintPortSummary(value(port.AddressOf()), O=O) 1556 1557# EndMacro: showtaskbusyports 1558# Macro: showallbusyports 1559 1560@lldb_command('showallbusyports', fancy=True) 1561def ShowAllBusyPorts(cmd_args=None, cmd_options={}, O=None): 1562 """ Routine to print information about all receive rights on the system that 1563 have enqueued messages. 1564 """ 1565 with O.table(PrintPortSummary.header): 1566 port_ty = gettype("struct ipc_port") 1567 for port in kmemory.Zone("ipc ports").iter_allocated(port_ty): 1568 if port.xGetIntegerByPath('.ip_messages.imq_msgcount') > 0: 1569 PrintPortSummary(value(port.AddressOf()), O=O) 1570 1571# EndMacro: showallbusyports 1572# Macro: showallports 1573 1574@lldb_command('showallports', fancy=True) 1575def ShowAllPorts(cmd_args=None, cmd_options={}, O=None): 1576 """ Routine to print information about all allocated ports in the system 1577 1578 usage: showallports 1579 """ 1580 with O.table(PrintPortSummary.header): 1581 port_ty = gettype("struct ipc_port") 1582 for port in kmemory.Zone("ipc ports").iter_allocated(port_ty): 1583 PrintPortSummary(value(port.AddressOf()), show_kmsg_summary=False, O=O) 1584 1585# EndMacro: showallports 1586# Macro: findkobjectport 1587 1588@lldb_command('findkobjectport', fancy=True) 1589def FindKobjectPort(cmd_args=None, cmd_options={}, O=None): 1590 """ Locate all ports pointing to a given kobject 1591 1592 usage: findkobjectport <kobject-addr> 1593 """ 1594 if cmd_args is None or len(cmd_args) == 0: 1595 raise ArgumentError() 1596 1597 kobj_addr = unsigned(kern.GetValueFromAddress(cmd_args[0])) 1598 kmem = kmemory.KMem.get_shared() 1599 port_ty = gettype("struct ipc_port") 1600 1601 with O.table(PrintPortSummary.header): 1602 for port in kmemory.Zone("ipc ports").iter_allocated(port_ty): 1603 if port.xGetIntegerByPath('.ip_object.io_bits') & 0x3ff == 0: 1604 continue 1605 1606 ip_kobject = kmem.make_address(port.xGetScalarByName('ip_kobject')) 1607 if ip_kobject == kobj_addr: 1608 PrintPortSummary(value(port.AddressOf()), show_kmsg_summary=False, O=O) 1609 1610# EndMacro: findkobjectport 1611# Macro: showtaskbusypsets 1612 1613@lldb_command('showtaskbusypsets', fancy=True) 1614def ShowTaskBusyPortSets(cmd_args=None, cmd_options={}, O=None): 1615 """ Routine to print information about port sets belonging to this task that 1616 have enqueued messages. This is often a sign of a blocked or hung process 1617 Usage: showtaskbusypsets <task address> 1618 """ 1619 if cmd_args is None or len(cmd_args) == 0: 1620 raise ArgumentError("No arguments passed. Please pass in the address of a task") 1621 1622 task = kern.GetValueFromAddress(cmd_args[0], 'task_t') 1623 is_tableval, num_entries = GetSpaceTable(task.itk_space) 1624 1625 if is_tableval: 1626 psets = GetSpaceObjectsWithBits(is_tableval, num_entries, 0x00080000, 1627 gettype('struct ipc_pset')) 1628 1629 with O.table(PrintPortSetSummary.header): 1630 for pset in (value(v.AddressOf()) for v in psets): 1631 for wq in Waitq(addressof(pset.ips_wqset)).iterateMembers(): 1632 if wq.asPort().ip_messages.imq_msgcount > 0: 1633 PrintPortSetSummary(pset, space=task.itk_space, O=O) 1634 1635# EndMacro: showtaskbusyports 1636# Macro: showallbusypsets 1637 1638@lldb_command('showallbusypsets', fancy=True) 1639def ShowAllBusyPortSets(cmd_args=None, cmd_options={}, O=None): 1640 """ Routine to print information about all port sets on the system that 1641 have enqueued messages. 1642 """ 1643 with O.table(PrintPortSetSummary.header): 1644 pset_ty = gettype("struct ipc_pset") 1645 for pset in kmemory.Zone("ipc port sets").iter_allocated(pset_ty): 1646 pset = value(pset.AddressOf()) 1647 for wq in Waitq(addressof(pset.ips_wqset)).iterateMembers(): 1648 port = wq.asPort() 1649 if port.ip_messages.imq_msgcount > 0: 1650 PrintPortSetSummary(pset, space=port.ip_receiver, O=O) 1651 1652# EndMacro: showallbusyports 1653# Macro: showallpsets 1654 1655@lldb_command('showallpsets', fancy=True) 1656def ShowAllPortSets(cmd_args=None, cmd_options={}, O=None): 1657 """ Routine to print information about all allocated psets in the system 1658 1659 usage: showallpsets 1660 """ 1661 with O.table(PrintPortSetSummary.header): 1662 pset_ty = gettype("struct ipc_pset") 1663 for pset in kmemory.Zone("ipc port sets").iter_allocated(pset_ty): 1664 PrintPortSetSummary(value(pset.AddressOf()), O=O) 1665 1666# EndMacro: showallports 1667# Macro: showbusyportsummary 1668 1669@lldb_command('showbusyportsummary') 1670def ShowBusyPortSummary(cmd_args=None): 1671 """ Routine to print a summary of information about all receive rights 1672 on the system that have enqueued messages. 1673 """ 1674 task_queue_head = kern.globals.tasks 1675 1676 ipc_table_size = 0 1677 ipc_busy_ports = 0 1678 ipc_msgs = 0 1679 1680 print(GetTaskBusyIPCSummary.header) 1681 for tsk in kern.tasks: 1682 (summary, table_size, nbusy, nmsgs) = GetTaskBusyIPCSummary(tsk) 1683 ipc_table_size += table_size 1684 ipc_busy_ports += nbusy 1685 ipc_msgs += nmsgs 1686 print(summary) 1687 for tsk in kern.terminated_tasks: 1688 (summary, table_size, nbusy, nmsgs) = GetTaskBusyIPCSummary(tsk) 1689 ipc_table_size += table_size 1690 ipc_busy_ports += nbusy 1691 ipc_msgs += nmsgs 1692 print(summary) 1693 print("Total Table Size: {:d}, Busy Ports: {:d}, Messages in-flight: {:d}".format(ipc_table_size, ipc_busy_ports, ipc_msgs)) 1694 return 1695 1696# EndMacro: showbusyportsummary 1697# Macro: showport / showpset 1698 1699def ShowPortOrPset(obj, space=0, O=None): 1700 """ Routine that lists details about a given IPC port or pset 1701 Syntax: (lldb) showport 0xaddr 1702 """ 1703 if not obj or obj == xnudefines.IPC_OBJECT_DEAD: 1704 print("IPC_OBJECT_DEAD") 1705 return 1706 1707 otype = (obj.io_bits & 0x7fff0000) >> 16 1708 if otype == 0: # IOT_PORT 1709 with O.table(PrintPortSummary.header): 1710 PrintPortSummary(cast(obj, 'ipc_port_t'), show_sets=True, O=O) 1711 elif otype == 1: # IOT_PSET 1712 with O.table(PrintPortSetSummary.header): 1713 PrintPortSetSummary(cast(obj, 'ipc_pset_t'), space, O=O) 1714 1715@lldb_command('showport', 'K', fancy=True) 1716def ShowPort(cmd_args=None, cmd_options={}, O=None): 1717 """ Routine that lists details about a given IPC port 1718 1719 usage: showport <address> 1720 """ 1721 # -K is default and kept for backward compat, it used to mean "show kmsg queue" 1722 if cmd_args is None or len(cmd_args) == 0: 1723 raise ArgumentError("Missing port argument") 1724 1725 obj = kern.GetValueFromAddress(cmd_args[0], 'struct ipc_object *') 1726 ShowPortOrPset(obj, O=O) 1727 1728 1729@lldb_command('showpset', "S:", fancy=True) 1730def ShowPSet(cmd_args=None, cmd_options={}, O=None): 1731 """ Routine that prints details for a given ipc_pset * 1732 1733 usage: showpset [-S <space>] <address> 1734 """ 1735 if cmd_args is None or len(cmd_args) == 0: 1736 raise ArgumentError("Missing port argument") 1737 1738 space = 0 1739 if "-S" in cmd_options: 1740 space = kern.GetValueFromAddress(cmd_options["-S"], 'struct ipc_space *') 1741 obj = kern.GetValueFromAddress(cmd_args[0], 'struct ipc_object *') 1742 ShowPortOrPset(obj, space=space, O=O) 1743 1744# EndMacro: showport / showpset 1745# Macro: showkmsg: 1746 1747@lldb_command('showkmsg') 1748def ShowKMSG(cmd_args=[]): 1749 """ Show detail information about a <ipc_kmsg_t> structure 1750 Usage: (lldb) showkmsg <ipc_kmsg_t> 1751 """ 1752 if cmd_args is None or len(cmd_args) == 0: 1753 raise ArgumentError('Invalid arguments') 1754 1755 kmsg = kern.GetValueFromAddress(cmd_args[0], 'ipc_kmsg_t') 1756 print(GetKMsgSummary.header) 1757 print(GetKMsgSummary(kmsg)) 1758 1759# EndMacro: showkmsg 1760# IPC importance inheritance related macros. 1761 1762@lldb_command('showalliits') 1763def ShowAllIITs(cmd_args=[], cmd_options={}): 1764 """ Development only macro. Show list of all iits allocated in the system. """ 1765 try: 1766 iit_queue = kern.globals.global_iit_alloc_queue 1767 except ValueError: 1768 print("This debug macro is only available in development or debug kernels") 1769 return 1770 1771 print(GetIPCImportantTaskSummary.header) 1772 for iit in IterateQueue(iit_queue, 'struct ipc_importance_task *', 'iit_allocation'): 1773 print(GetIPCImportantTaskSummary(iit)) 1774 return 1775 1776@header("{: <18s} {: <3s} {: <18s} {: <32s} {: <18s} {: <8s}".format("ipc_imp_inherit", "don", "to_task", "proc_name", "from_elem", "depth")) 1777@lldb_type_summary(['ipc_importance_inherit *', 'ipc_importance_inherit_t']) 1778def GetIPCImportanceInheritSummary(iii): 1779 """ describes iii object of type ipc_importance_inherit_t * """ 1780 out_str = "" 1781 fmt = "{o: <#18x} {don: <3s} {o.iii_to_task.iit_task: <#18x} {task_name: <20s} {o.iii_from_elem: <#18x} {o.iii_depth: <#8x}" 1782 donating_str = "" 1783 if unsigned(iii.iii_donating): 1784 donating_str = "DON" 1785 taskname = GetProcNameForTask(iii.iii_to_task.iit_task) 1786 if hasattr(iii.iii_to_task, 'iit_bsd_pid'): 1787 taskname = "({:d}) {:s}".format(iii.iii_to_task.iit_bsd_pid, iii.iii_to_task.iit_procname) 1788 out_str += fmt.format(o=iii, task_name = taskname, don=donating_str) 1789 return out_str 1790 1791@static_var('recursion_count', 0) 1792@header("{: <18s} {: <4s} {: <8s} {: <8s} {: <18s} {: <18s}".format("iie", "type", "refs", "made", "#kmsgs", "#inherits")) 1793@lldb_type_summary(['ipc_importance_elem *']) 1794def GetIPCImportanceElemSummary(iie): 1795 """ describes an ipc_importance_elem * object """ 1796 1797 if GetIPCImportanceElemSummary.recursion_count > 500: 1798 GetIPCImportanceElemSummary.recursion_count = 0 1799 return "Recursion of 500 reached" 1800 1801 out_str = '' 1802 fmt = "{: <#18x} {: <4s} {: <8d} {: <8d} {: <#18x} {: <#18x}" 1803 if unsigned(iie.iie_bits) & xnudefines.IIE_TYPE_MASK: 1804 type_str = "INH" 1805 inherit_count = 0 1806 else: 1807 type_str = 'TASK' 1808 iit = Cast(iie, 'struct ipc_importance_task *') 1809 inherit_count = sum(1 for i in IterateQueue(iit.iit_inherits, 'struct ipc_importance_inherit *', 'iii_inheritance')) 1810 1811 refs = unsigned(iie.iie_bits) >> xnudefines.IIE_TYPE_BITS 1812 made_refs = unsigned(iie.iie_made) 1813 kmsg_count = sum(1 for i in IterateQueue(iie.iie_kmsgs, 'struct ipc_kmsg *', 'ikm_inheritance')) 1814 out_str += fmt.format(iie, type_str, refs, made_refs, kmsg_count, inherit_count) 1815 if config['verbosity'] > vHUMAN: 1816 if kmsg_count > 0: 1817 out_str += "\n\t"+ GetKMsgSummary.header 1818 for k in IterateQueue(iie.iie_kmsgs, 'struct ipc_kmsg *', 'ikm_inheritance'): 1819 out_str += "\t" + "{: <#18x}".format(GetKmsgHeader(k).msgh_remote_port) + ' ' + GetKMsgSummary(k, "\t").lstrip() 1820 out_str += "\n" 1821 if inherit_count > 0: 1822 out_str += "\n\t" + GetIPCImportanceInheritSummary.header + "\n" 1823 for i in IterateQueue(iit.iit_inherits, 'struct ipc_importance_inherit *', 'iii_inheritance'): 1824 out_str += "\t" + GetIPCImportanceInheritSummary(i) + "\n" 1825 out_str += "\n" 1826 if type_str == "INH": 1827 iii = Cast(iie, 'struct ipc_importance_inherit *') 1828 out_str += "Inherit from: " + GetIPCImportanceElemSummary(iii.iii_from_elem) 1829 1830 return out_str 1831 1832@header("{: <18s} {: <18s} {: <32}".format("iit", "task", "name")) 1833@lldb_type_summary(['ipc_importance_task *']) 1834def GetIPCImportantTaskSummary(iit): 1835 """ iit is a ipc_importance_task value object. 1836 """ 1837 fmt = "{: <#18x} {: <#18x} {: <32}" 1838 out_str='' 1839 pname = GetProcNameForTask(iit.iit_task) 1840 if hasattr(iit, 'iit_bsd_pid'): 1841 pname = "({:d}) {:s}".format(iit.iit_bsd_pid, iit.iit_procname) 1842 out_str += fmt.format(iit, iit.iit_task, pname) 1843 return out_str 1844 1845@lldb_command('showallimportancetasks') 1846def ShowIPCImportanceTasks(cmd_args=[], cmd_options={}): 1847 """ display a list of all tasks with ipc importance information. 1848 Usage: (lldb) showallimportancetasks 1849 Tip: add "-v" to see detailed information on each kmsg or inherit elems 1850 """ 1851 print(' ' + GetIPCImportantTaskSummary.header + ' ' + GetIPCImportanceElemSummary.header) 1852 for t in kern.tasks: 1853 s = "" 1854 if unsigned(t.task_imp_base): 1855 s += ' ' + GetIPCImportantTaskSummary(t.task_imp_base) 1856 s += ' ' + GetIPCImportanceElemSummary(addressof(t.task_imp_base.iit_elem)) 1857 print(s) 1858 1859@lldb_command('showipcimportance', '') 1860def ShowIPCImportance(cmd_args=[], cmd_options={}): 1861 """ Describe an importance from <ipc_importance_elem_t> argument. 1862 Usage: (lldb) showimportance <ipc_importance_elem_t> 1863 """ 1864 if cmd_args is None or len(cmd_args) == 0: 1865 raise ArgumentError("Please provide valid argument") 1866 1867 elem = kern.GetValueFromAddress(cmd_args[0], 'ipc_importance_elem_t') 1868 print(GetIPCImportanceElemSummary.header) 1869 print(GetIPCImportanceElemSummary(elem)) 1870 1871@header("{: <18s} {: <18s} {: <8s} {: <5s} {: <5s} {: <8s}".format("ivac", "tbl", "tblsize", "index", "Grow", "freelist")) 1872@lldb_type_summary(['ipc_voucher_attr_control *', 'ipc_voucher_attr_control_t']) 1873def GetIPCVoucherAttrControlSummary(ivac): 1874 """ describes a voucher attribute control settings """ 1875 out_str = "" 1876 fmt = "{c: <#18x} {c.ivac_table: <#18x} {c.ivac_table_size: <8d} {c.ivac_key_index: <5d} {growing: <5s} {c.ivac_freelist: <8d}" 1877 growing_str = "" 1878 1879 if ivac == 0: 1880 return "{: <#18x}".format(ivac) 1881 1882 growing_str = "Y" if unsigned(ivac.ivac_is_growing) else "N" 1883 out_str += fmt.format(c=ivac, growing = growing_str) 1884 return out_str 1885 1886@lldb_command('showivac','') 1887def ShowIPCVoucherAttributeControl(cmd_args=[], cmd_options={}): 1888 """ Show summary of voucher attribute contols. 1889 Usage: (lldb) showivac <ipc_voucher_attr_control_t> 1890 """ 1891 if cmd_args is None or len(cmd_args) == 0: 1892 raise ArgumentError("Please provide correct arguments.") 1893 ivac = kern.GetValueFromAddress(cmd_args[0], 'ipc_voucher_attr_control_t') 1894 print(GetIPCVoucherAttrControlSummary.header) 1895 print(GetIPCVoucherAttrControlSummary(ivac)) 1896 if config['verbosity'] > vHUMAN: 1897 cur_entry_index = 0 1898 last_entry_index = unsigned(ivac.ivac_table_size) 1899 print("index " + GetIPCVoucherAttributeEntrySummary.header) 1900 while cur_entry_index < last_entry_index: 1901 print("{: <5d} ".format(cur_entry_index) + GetIPCVoucherAttributeEntrySummary(addressof(ivac.ivac_table[cur_entry_index]))) 1902 cur_entry_index += 1 1903 1904 1905 1906 1907@header("{: <18s} {: <30s} {: <30s} {: <30s} {: <30s}".format("ivam", "get_value_fn", "extract_fn", "release_value_fn", "command_fn")) 1908@lldb_type_summary(['ipc_voucher_attr_manager *', 'ipc_voucher_attr_manager_t']) 1909def GetIPCVoucherAttrManagerSummary(ivam): 1910 """ describes a voucher attribute manager settings """ 1911 out_str = "" 1912 fmt = "{: <#18x} {: <30s} {: <30s} {: <30s} {: <30s}" 1913 1914 if unsigned(ivam) == 0 : 1915 return "{: <#18x}".format(ivam) 1916 1917 get_value_fn = kern.Symbolicate(unsigned(ivam.ivam_get_value)) 1918 extract_fn = kern.Symbolicate(unsigned(ivam.ivam_extract_content)) 1919 release_value_fn = kern.Symbolicate(unsigned(ivam.ivam_release_value)) 1920 command_fn = kern.Symbolicate(unsigned(ivam.ivam_command)) 1921 out_str += fmt.format(ivam, get_value_fn, extract_fn, release_value_fn, command_fn) 1922 return out_str 1923 1924def iv_key_to_index(key): 1925 """ ref: osfmk/ipc/ipc_voucher.c: iv_key_to_index """ 1926 if (key == xnudefines.MACH_VOUCHER_ATTR_KEY_ALL) or (key > xnudefines.MACH_VOUCHER_ATTR_KEY_NUM): 1927 return xnudefines.IV_UNUSED_KEYINDEX 1928 return key - 1 1929 1930def iv_index_to_key(index): 1931 """ ref: osfmk/ipc/ipc_voucher.c: iv_index_to_key """ 1932 if index < xnudefines.MACH_VOUCHER_ATTR_KEY_NUM_WELL_KNOWN: 1933 return index + 1 1934 return xnudefines.MACH_VOUCHER_ATTR_KEY_NONE 1935 1936@header("{: <3s} {: <3s} {:s} {:s}".format("idx", "key", GetIPCVoucherAttrControlSummary.header.strip(), GetIPCVoucherAttrManagerSummary.header.strip())) 1937@lldb_type_summary(['ipc_voucher_global_table_element *', 'ipc_voucher_global_table_element_t']) 1938def GetIPCVoucherGlobalTableElementSummary(idx, ivac, ivam): 1939 """ describes a ipc_voucher_global_table_element object """ 1940 out_str = "" 1941 fmt = "{idx: <3d} {key: <3d} {ctrl_s:s} {mgr_s:s}" 1942 out_str += fmt.format(idx=idx, key=iv_index_to_key(idx), ctrl_s=GetIPCVoucherAttrControlSummary(addressof(ivac)), mgr_s=GetIPCVoucherAttrManagerSummary(ivam)) 1943 return out_str 1944 1945@lldb_command('showglobalvouchertable', '') 1946def ShowGlobalVoucherTable(cmd_args=[], cmd_options={}): 1947 """ show detailed information of all voucher attribute managers registered with vouchers system 1948 Usage: (lldb) showglobalvouchertable 1949 """ 1950 entry_size = sizeof(kern.globals.ivac_global_table[0]) 1951 elems = sizeof(kern.globals.ivac_global_table) // entry_size 1952 print(GetIPCVoucherGlobalTableElementSummary.header) 1953 for i in range(elems): 1954 ivac = kern.globals.ivac_global_table[i] 1955 ivam = kern.globals.ivam_global_table[i] 1956 if unsigned(ivam) == 0: 1957 continue 1958 print(GetIPCVoucherGlobalTableElementSummary(i, ivac, ivam)) 1959 1960# Type summaries for Bag of Bits. 1961 1962@lldb_type_summary(['user_data_value_element', 'user_data_element_t']) 1963@header("{0: <20s} {1: <16s} {2: <20s} {3: <20s} {4: <16s} {5: <20s}".format("user_data_ve", "maderefs", "checksum", "hash value", "size", "data")) 1964def GetBagofBitsElementSummary(data_element): 1965 """ Summarizes the Bag of Bits element 1966 params: data_element = value of the object of type user_data_value_element_t 1967 returns: String with summary of the type. 1968 """ 1969 format_str = "{0: <#20x} {1: <16d} {2: <#20x} {3: <#20x} {4: <16d}" 1970 out_string = format_str.format(data_element, unsigned(data_element.e_made), data_element.e_sum, data_element.e_hash, unsigned(data_element.e_size)) 1971 out_string += " 0x" 1972 1973 for i in range(0, (unsigned(data_element.e_size) - 1)): 1974 out_string += "{:02x}".format(int(data_element.e_data[i])) 1975 return out_string 1976 1977def GetIPCHandleSummary(handle_ptr): 1978 """ converts a handle value inside a voucher attribute table to ipc element and returns appropriate summary. 1979 params: handle_ptr - uint64 number stored in handle of voucher. 1980 returns: str - string summary of the element held in internal structure 1981 """ 1982 elem = kern.GetValueFromAddress(handle_ptr, 'ipc_importance_elem_t') 1983 if elem.iie_bits & xnudefines.IIE_TYPE_MASK: 1984 iie = Cast(elem, 'struct ipc_importance_inherit *') 1985 return GetIPCImportanceInheritSummary(iie) 1986 else: 1987 iit = Cast(elem, 'struct ipc_importance_task *') 1988 return GetIPCImportantTaskSummary(iit) 1989 1990def GetATMHandleSummary(handle_ptr): 1991 """ Convert a handle value to atm value and returns corresponding summary of its fields. 1992 params: handle_ptr - uint64 number stored in handle of voucher 1993 returns: str - summary of atm value 1994 """ 1995 return "???" 1996 1997def GetBankHandleSummary(handle_ptr): 1998 """ converts a handle value inside a voucher attribute table to bank element and returns appropriate summary. 1999 params: handle_ptr - uint64 number stored in handle of voucher. 2000 returns: str - summary of bank element 2001 """ 2002 if handle_ptr == 1 : 2003 return "Bank task of Current task" 2004 elem = kern.GetValueFromAddress(handle_ptr, 'bank_element_t') 2005 if elem.be_type & 1 : 2006 ba = Cast(elem, 'struct bank_account *') 2007 return GetBankAccountSummary(ba) 2008 else: 2009 bt = Cast(elem, 'struct bank_task *') 2010 return GetBankTaskSummary(bt) 2011 2012def GetBagofBitsHandleSummary(handle_ptr): 2013 """ Convert a handle value to bag of bits value and returns corresponding summary of its fields. 2014 params: handle_ptr - uint64 number stored in handle of voucher 2015 returns: str - summary of bag of bits element 2016 """ 2017 elem = kern.GetValueFromAddress(handle_ptr, 'user_data_element_t') 2018 return GetBagofBitsElementSummary(elem) 2019 2020@static_var('attr_managers',{1: GetATMHandleSummary, 2: GetIPCHandleSummary, 3: GetBankHandleSummary, 7: GetBagofBitsHandleSummary}) 2021def GetHandleSummaryForKey(handle_ptr, key_num): 2022 """ Get a summary of handle pointer from the voucher attribute manager. 2023 For example key 2 -> ipc and it puts either ipc_importance_inherit_t or ipc_important_task_t. 2024 key 3 -> Bank and it puts either bank_task_t or bank_account_t. 2025 key 7 -> Bag of Bits and it puts user_data_element_t in handle. So summary of it would be Bag of Bits content and refs etc. 2026 """ 2027 key_num = int(key_num) 2028 if key_num not in GetHandleSummaryForKey.attr_managers: 2029 return "Unknown key %d" % key_num 2030 return GetHandleSummaryForKey.attr_managers[key_num](handle_ptr) 2031 2032 2033@header("{: <18s} {: <18s} {: <10s} {: <4s} {: <18s} {: <18s}".format("ivace", "value_handle", "#refs", "rel?", "maderefs", "next_layer")) 2034@lldb_type_summary(['ivac_entry *', 'ivac_entry_t']) 2035def GetIPCVoucherAttributeEntrySummary(ivace, manager_key_num = 0): 2036 """ Get summary for voucher attribute entry. 2037 """ 2038 out_str = "" 2039 fmt = "{e: <#18x} {e.ivace_value: <#18x} {e.ivace_refs: <10d} {release: <4s} {made_refs: <18s} {next_layer: <18s}" 2040 release_str = "" 2041 free_str = "" 2042 made_refs = "" 2043 next_layer = "" 2044 2045 if unsigned(ivace.ivace_releasing): 2046 release_str = "Y" 2047 if unsigned(ivace.ivace_free): 2048 free_str = 'F' 2049 if unsigned(ivace.ivace_layered): 2050 next_layer = "{: <#18x}".format(ivace.ivace_u.ivaceu_layer) 2051 else: 2052 made_refs = "{: <18d}".format(ivace.ivace_u.ivaceu_made) 2053 2054 out_str += fmt.format(e=ivace, release=release_str, made_refs=made_refs, next_layer=next_layer) 2055 if config['verbosity'] > vHUMAN and manager_key_num > 0: 2056 out_str += " " + GetHandleSummaryForKey(unsigned(ivace.ivace_value), manager_key_num) 2057 if config['verbosity'] > vHUMAN : 2058 out_str += ' {: <2s} {: <4d} {: <4d}'.format(free_str, ivace.ivace_next, ivace.ivace_index) 2059 return out_str 2060 2061@lldb_command('showivacfreelist','') 2062def ShowIVACFreeList(cmd_args=[], cmd_options={}): 2063 """ Walk the free list and print every entry in the list. 2064 usage: (lldb) showivacfreelist <ipc_voucher_attr_control_t> 2065 """ 2066 if cmd_args is None or len(cmd_args) == 0: 2067 raise ArgumentError('Please provide <ipc_voucher_attr_control_t>') 2068 2069 ivac = kern.GetValueFromAddress(cmd_args[0], 'ipc_voucher_attr_control_t') 2070 print(GetIPCVoucherAttrControlSummary.header) 2071 print(GetIPCVoucherAttrControlSummary(ivac)) 2072 if unsigned(ivac.ivac_freelist) == 0: 2073 print("ivac table is full") 2074 return 2075 print("index " + GetIPCVoucherAttributeEntrySummary.header) 2076 next_free = unsigned(ivac.ivac_freelist) 2077 while next_free != 0: 2078 print("{: <5d} ".format(next_free) + GetIPCVoucherAttributeEntrySummary(addressof(ivac.ivac_table[next_free]))) 2079 next_free = unsigned(ivac.ivac_table[next_free].ivace_next) 2080 2081 2082 2083@header('{: <18s} {: <8s} {: <18s} {: <18s}'.format("ipc_voucher", "refs", "table", "voucher_port")) 2084@lldb_type_summary(['ipc_voucher *', 'ipc_voucher_t']) 2085def GetIPCVoucherSummary(voucher, show_entries=False): 2086 """ describe a voucher from its ipc_voucher * object """ 2087 out_str = "" 2088 fmt = "{v: <#18x} {v.iv_refs: <8d} {table_addr: <#18x} {v.iv_port: <#18x}" 2089 out_str += fmt.format(v = voucher, table_addr = addressof(voucher.iv_table)) 2090 entries_str = '' 2091 if show_entries or config['verbosity'] > vHUMAN: 2092 elems = sizeof(voucher.iv_table) // sizeof(voucher.iv_table[0]) 2093 entries_header_str = "\n\t" + "{: <5s} {: <3s} {: <16s} {: <30s}".format("index", "key", "value_index", "manager") + " " + GetIPCVoucherAttributeEntrySummary.header 2094 fmt = "{: <5d} {: <3d} {: <16d} {: <30s}" 2095 for i in range(elems): 2096 voucher_entry_index = unsigned(voucher.iv_table[i]) 2097 if voucher_entry_index: 2098 s = fmt.format(i, GetVoucherManagerKeyForIndex(i), voucher_entry_index, GetVoucherAttributeManagerNameForIndex(i)) 2099 e = GetVoucherValueHandleFromVoucherForIndex(voucher, i) 2100 if e is not None: 2101 s += " " + GetIPCVoucherAttributeEntrySummary(addressof(e), GetVoucherManagerKeyForIndex(i) ) 2102 if entries_header_str : 2103 entries_str = entries_header_str 2104 entries_header_str = '' 2105 entries_str += "\n\t" + s 2106 if not entries_header_str: 2107 entries_str += "\n\t" 2108 out_str += entries_str 2109 return out_str 2110 2111def GetVoucherManagerKeyForIndex(idx): 2112 """ Returns key number for index based on global table. Will raise index error if value is incorrect 2113 """ 2114 ret = iv_index_to_key(idx) 2115 if ret == xnudefines.MACH_VOUCHER_ATTR_KEY_NONE: 2116 raise IndexError("invalid voucher key") 2117 return ret 2118 2119def GetVoucherAttributeManagerForKey(k): 2120 """ Return the attribute manager name for a given key 2121 params: k - int key number of the manager 2122 return: cvalue - the attribute manager object. 2123 None - if not found 2124 """ 2125 idx = iv_key_to_index(k) 2126 if idx == xnudefines.IV_UNUSED_KEYINDEX: 2127 return None 2128 return kern.globals.ivam_global_table[idx] 2129 2130def GetVoucherAttributeControllerForKey(k): 2131 """ Return the attribute controller for a given key 2132 params: k - int key number of the controller 2133 return: cvalue - the attribute controller object. 2134 None - if not found 2135 """ 2136 idx = iv_key_to_index(k) 2137 if idx == xnudefines.IV_UNUSED_KEYINDEX: 2138 return None 2139 return kern.globals.ivac_global_table[idx] 2140 2141 2142def GetVoucherAttributeManagerName(ivam): 2143 """ find the name of the ivam object 2144 param: ivam - cvalue object of type ipc_voucher_attr_manager_t 2145 returns: str - name of the manager 2146 """ 2147 return kern.Symbolicate(unsigned(ivam)) 2148 2149def GetVoucherAttributeManagerNameForIndex(idx): 2150 """ get voucher attribute manager name for index 2151 return: str - name of the attribute manager object 2152 """ 2153 return GetVoucherAttributeManagerName(GetVoucherAttributeManagerForKey(GetVoucherManagerKeyForIndex(idx))) 2154 2155def GetVoucherValueHandleFromVoucherForIndex(voucher, idx): 2156 """ traverse the voucher attrs and get value_handle in the voucher attr controls table 2157 params: 2158 voucher - cvalue object of type ipc_voucher_t 2159 idx - int index in the entries for which you wish to get actual handle for 2160 returns: cvalue object of type ivac_entry_t 2161 None if no handle found. 2162 """ 2163 manager_key = GetVoucherManagerKeyForIndex(idx) 2164 voucher_num_elems = sizeof(voucher.iv_table) // sizeof(voucher.iv_table[0]) 2165 if idx >= voucher_num_elems: 2166 debuglog("idx %d is out of range max: %d" % (idx, voucher_num_elems)) 2167 return None 2168 voucher_entry_value = unsigned(voucher.iv_table[idx]) 2169 debuglog("manager_key %d" % manager_key) 2170 ivac = GetVoucherAttributeControllerForKey(manager_key) 2171 if ivac is None or addressof(ivac) == 0: 2172 debuglog("No voucher attribute controller for idx %d" % idx) 2173 return None 2174 2175 ivace_table = ivac.ivac_table 2176 if voucher_entry_value >= unsigned(ivac.ivac_table_size): 2177 print("Failed to get ivace for value %d in table of size %d" % (voucher_entry_value, unsigned(ivac.ivac_table_size))) 2178 return None 2179 return ivace_table[voucher_entry_value] 2180 2181 2182 2183@lldb_command('showallvouchers') 2184def ShowAllVouchers(cmd_args=[], cmd_options={}): 2185 """ Display a list of all vouchers in the global voucher hash table 2186 Usage: (lldb) showallvouchers 2187 """ 2188 print(GetIPCVoucherSummary.header) 2189 voucher_ty = gettype("struct ipc_voucher") 2190 for v in kmemory.Zone("ipc vouchers").iter_allocated(voucher_ty): 2191 print(GetIPCVoucherSummary(value(v.AddressOf()))) 2192 2193@lldb_command('showvoucher', '') 2194def ShowVoucher(cmd_args=[], cmd_options={}): 2195 """ Describe a voucher from <ipc_voucher_t> argument. 2196 Usage: (lldb) showvoucher <ipc_voucher_t> 2197 """ 2198 if cmd_args is None or len(cmd_args) == 0: 2199 raise ArgumentError("Please provide valid argument") 2200 2201 voucher = kern.GetValueFromAddress(cmd_args[0], 'ipc_voucher_t') 2202 print(GetIPCVoucherSummary.header) 2203 print(GetIPCVoucherSummary(voucher, show_entries=True)) 2204 2205@lldb_command('showportsendrights') 2206def ShowPortSendRights(cmd_args=[], cmd_options={}): 2207 """ Display a list of send rights across all tasks for a given port. 2208 Usage: (lldb) showportsendrights <ipc_port_t> 2209 """ 2210 if cmd_args is None or len(cmd_args) == 0: 2211 raise ArgumentError("no port address provided") 2212 2213 port = kern.GetValueFromAddress(cmd_args[0], 'struct ipc_port *') 2214 if not port or port == xnudefines.MACH_PORT_DEAD: 2215 return 2216 2217 return FindPortRights(cmd_args=[unsigned(port)], cmd_options={'-R':'S'}) 2218 2219 2220@lldb_command('showtasksuspenders') 2221def ShowTaskSuspenders(cmd_args=[], cmd_options={}): 2222 """ Display the tasks and send rights that are holding a target task suspended. 2223 Usage: (lldb) showtasksuspenders <task_t> 2224 """ 2225 if cmd_args is None or len(cmd_args) == 0: 2226 raise ArgumentError("no task address provided") 2227 2228 task = kern.GetValueFromAddress(cmd_args[0], 'task_t') 2229 2230 if task.suspend_count == 0: 2231 print("task {:#x} ({:s}) is not suspended".format(unsigned(task), GetProcNameForTask(task))) 2232 return 2233 2234 # If the task has been suspended by the kernel (potentially by 2235 # kperf, using task_suspend_internal) or a client of task_suspend2 2236 # that does not convert its task suspension token to a port using 2237 # convert_task_suspension_token_to_port, then it's impossible to determine 2238 # which task did the suspension. 2239 port = task.itk_resume 2240 if task.pidsuspended: 2241 print("task {:#x} ({:s}) has been `pid_suspend`ed. (Probably runningboardd's fault. Go look at the syslog for \"Suspending task.\")".format(unsigned(task), GetProcNameForTask(task))) 2242 return 2243 elif not port: 2244 print("task {:#x} ({:s}) is suspended but no resume port exists".format(unsigned(task), GetProcNameForTask(task))) 2245 return 2246 2247 return FindPortRights(cmd_args=[unsigned(port)], cmd_options={'-R':'S'}) 2248 2249 2250# Macro: showmqueue: 2251@lldb_command('showmqueue', fancy=True) 2252def ShowMQueue(cmd_args=None, cmd_options={}, O=None): 2253 """ Routine that lists details about a given mqueue. 2254 An mqueue is directly tied to a mach port, so it just shows the details of that port. 2255 Syntax: (lldb) showmqueue <address> 2256 """ 2257 if cmd_args is None or len(cmd_args) == 0: 2258 raise ArgumentError("Missing mqueue argument") 2259 2260 space = 0 2261 mqueue = kern.GetValueFromAddress(cmd_args[0], 'struct ipc_mqueue *') 2262 portoff = getfieldoffset('struct ipc_port', 'ip_messages') 2263 port = unsigned(ArgumentStringToInt(cmd_args[0])) - unsigned(portoff) 2264 obj = kern.GetValueFromAddress(port, 'struct ipc_object *') 2265 ShowPortOrPset(obj, O=O) 2266# EndMacro: showmqueue 2267