1from xnu import * 2from utils import * 3from process import * 4from misc import * 5from memory import * 6from ipc import * 7 8 9# Macro: showallprocrunqcount 10 11@lldb_command('showallprocrunqcount') 12def ShowAllProcRunQCount(cmd_args=None): 13 """ Prints out the runq count for all processors 14 """ 15 out_str = "Processor\t# Runnable\n" 16 processor_itr = kern.globals.processor_list 17 while processor_itr: 18 out_str += "{:d}\t\t{:d}\n".format(processor_itr.cpu_id, processor_itr.runq.count) 19 processor_itr = processor_itr.processor_list 20 # out_str += "RT:\t\t{:d}\n".format(kern.globals.rt_runq.count) 21 print(out_str) 22 23# EndMacro: showallprocrunqcount 24 25# Macro: showinterrupts 26 27@lldb_command('showinterrupts') 28def ShowInterrupts(cmd_args=None): 29 """ Prints IRQ, IPI and TMR counts for each CPU 30 """ 31 32 if not kern.arch.startswith('arm64'): 33 print("showinterrupts is only supported on arm64") 34 return 35 36 base_address = kern.GetLoadAddressForSymbol('CpuDataEntries') 37 struct_size = 16 38 x = 0 39 y = 0 40 while x < unsigned(kern.globals.machine_info.physical_cpu): 41 element = kern.GetValueFromAddress(base_address + (y * struct_size), 'uintptr_t *')[1] 42 if element: 43 cpu_data_entry = Cast(element, 'cpu_data_t *') 44 print("CPU {} IRQ: {:d}\n".format(y, cpu_data_entry.cpu_stat.irq_ex_cnt)) 45 print("CPU {} IPI: {:d}\n".format(y, cpu_data_entry.cpu_stat.ipi_cnt)) 46 print("CPU {} PMI: {:d}\n".format(y, cpu_data_entry.cpu_monotonic.mtc_npmis)) 47 print("CPU {} TMR: {:d}\n".format(y, cpu_data_entry.cpu_stat.timer_cnt)) 48 x = x + 1 49 y = y + 1 50 51# EndMacro: showinterrupts 52 53# Macro: showactiveinterrupts 54 55@lldb_command('showactiveinterrupts') 56def ShowActiveInterrupts(cmd_args=None): 57 """ Prints the interrupts that are unmasked & active with the Interrupt Controller 58 Usage: showactiveinterrupts <address of Interrupt Controller object> 59 """ 60 if not cmd_args: 61 print("No arguments passed") 62 print(ShowActiveInterrupts.__doc__) 63 return False 64 aic = kern.GetValueFromAddress(cmd_args[0], 'AppleInterruptController *') 65 if not aic: 66 print("unknown arguments:", str(cmd_args)) 67 return False 68 69 aic_base = unsigned(aic._aicBaseAddress) 70 current_interrupt = 0 71 aic_imc_base = aic_base + 0x4180 72 aic_him_offset = 0x80 73 current_pointer = aic_imc_base 74 unmasked = dereference(kern.GetValueFromAddress(current_pointer, 'uintptr_t *')) 75 active = dereference(kern.GetValueFromAddress(current_pointer + aic_him_offset, 'uintptr_t *')) 76 group_count = 0 77 mask = 1 78 while current_interrupt < 192: 79 if (((unmasked & mask) == 0) and (active & mask)): 80 print("Interrupt {:d} unmasked and active\n".format(current_interrupt)) 81 current_interrupt = current_interrupt + 1 82 if (current_interrupt % 32 == 0): 83 mask = 1 84 group_count = group_count + 1 85 unmasked = dereference(kern.GetValueFromAddress(current_pointer + (4 * group_count), 'uintptr_t *')) 86 active = dereference(kern.GetValueFromAddress((current_pointer + aic_him_offset) + (4 * group_count), 'uintptr_t *')) 87 else: 88 mask = mask << 1 89# EndMacro: showactiveinterrupts 90 91# Macro: showirqbyipitimerratio 92@lldb_command('showirqbyipitimerratio') 93def ShowIrqByIpiTimerRatio(cmd_args=None): 94 """ Prints the ratio of IRQ by sum of IPI & TMR counts for each CPU 95 """ 96 if kern.arch == "x86_64": 97 print("This macro is not supported on x86_64 architecture") 98 return 99 100 out_str = "IRQ-IT Ratio: " 101 base_address = kern.GetLoadAddressForSymbol('CpuDataEntries') 102 struct_size = 16 103 x = 0 104 y = 0 105 while x < unsigned(kern.globals.machine_info.physical_cpu): 106 element = kern.GetValueFromAddress(base_address + (y * struct_size), 'uintptr_t *')[1] 107 if element: 108 cpu_data_entry = Cast(element, 'cpu_data_t *') 109 out_str += " CPU {} [{:.2f}]".format(y, float(cpu_data_entry.cpu_stat.irq_ex_cnt)/(cpu_data_entry.cpu_stat.ipi_cnt + cpu_data_entry.cpu_stat.timer_cnt)) 110 x = x + 1 111 y = y + 1 112 print(out_str) 113 114# EndMacro: showirqbyipitimerratio 115 116#Macro: showinterruptsourceinfo 117@lldb_command('showinterruptsourceinfo') 118def showinterruptsourceinfo(cmd_args = None): 119 """ Extract information of interrupt source causing interrupt storms. 120 """ 121 if not cmd_args: 122 print("No arguments passed") 123 return False 124 #Dump IOInterruptVector object 125 print("--- Dumping IOInterruptVector object ---\n") 126 object_info = lldb_run_command("dumpobject {:s} IOInterruptVector".format(cmd_args[0])) 127 print(object_info) 128 print("--- Dumping IOFilterInterruptEventSource object ---\n") 129 #Dump the IOFilterInterruptEventSource object. 130 target_info=re.search('target =\s+(.*)',object_info) 131 target= target_info.group() 132 target= target.split() 133 #Dump the Object pointer of the source who is triggering the Interrupts. 134 vector_info=lldb_run_command("dumpobject {:s} ".format(target[2])) 135 print(vector_info) 136 owner_info= re.search('owner =\s+(.*)',vector_info) 137 owner= owner_info.group() 138 owner= owner.split() 139 print("\n\n") 140 out=lldb_run_command(" dumpobject {:s}".format(owner[2])) 141 print(out) 142 143# EndMacro: showinterruptsourceinfo 144 145@lldb_command('showcurrentabstime') 146def ShowCurrentAbsTime(cmd_args=None): 147 """ Routine to print latest absolute time known to system before being stopped. 148 Usage: showcurrentabstime 149 """ 150 151 print("Last dispatch time known: %d MATUs" % GetRecentTimestamp()) 152 153bucketStr = ["FIXPRI (>UI)", "TIMESHARE_FG", "TIMESHARE_IN", "TIMESHARE_DF", "TIMESHARE_UT", "TIMESHARE_BG"] 154 155@header("{:<18s} | {:>20s} | {:>20s} | {:>10s} | {:>10s}".format('Thread Group', 'Pending (us)', 'Interactivity Score', 'TG Boost', 'Highest Thread Pri')) 156def GetSchedClutchBucketSummary(clutch_bucket): 157 tg_boost = 0 158 pending_delta = kern.GetNanotimeFromAbstime(GetRecentTimestamp() - clutch_bucket.scb_group.scbg_pending_data.scct_timestamp) // 1000 159 if (int)(clutch_bucket.scb_group.scbg_pending_data.scct_timestamp) == 18446744073709551615: 160 pending_delta = 0 161 return "0x{:<16x} | {:>20d} | {:>20d} | {:>10d} | {:>10d}".format( 162 clutch_bucket.scb_group.scbg_clutch.sc_tg, pending_delta, 163 clutch_bucket.scb_group.scbg_interactivity_data.scct_count, 164 tg_boost, clutch_bucket.scb_thread_runq.pq_root.key >> 8) 165 166def ShowSchedClutchForPset(pset): 167 root_clutch = pset.pset_clutch_root 168 print("\n{:s} : {:d}\n\n".format("Current Timestamp", GetRecentTimestamp())) 169 print("{:>10s} | {:>20s} | {:>30s} | {:>25s} | {:<18s} | {:>10s} | {:>10s} | {:>15s} | ".format("Root", "Root Buckets", "Clutch Buckets", "Threads", "Address", "Pri (Base)", "Count", "Deadline (us)") + GetSchedClutchBucketSummary.header) 170 print("=" * 300) 171 print("{:>10s} | {:>20s} | {:>30s} | {:>25s} | 0x{:<16x} | {:>10d} | {:>10d} | {:>15s} | ".format("Root", "*", "*", "*", addressof(root_clutch), (root_clutch.scr_priority if root_clutch.scr_thr_count > 0 else -1), root_clutch.scr_thr_count, "*")) 172 print("-" * 300) 173 174 for i in range(0, 6): 175 root_bucket = root_clutch.scr_unbound_buckets[i] 176 root_bucket_deadline = 0 177 if root_bucket.scrb_clutch_buckets.scbrq_count != 0 and i != 0: 178 root_bucket_deadline = kern.GetNanotimeFromAbstime(root_bucket.scrb_pqlink.deadline - GetRecentTimestamp()) // 1000 179 print("{:>10s} | {:>20s} | {:>30s} | {:>25s} | 0x{:<16x} | {:>10s} | {:>10s} | {:>15d} | ".format("*", bucketStr[int(root_bucket.scrb_bucket)], "*", "*", addressof(root_bucket), "*", "*", root_bucket_deadline)) 180 clutch_bucket_runq = root_bucket.scrb_clutch_buckets 181 clutch_bucket_list = [] 182 for pri in range(0,128): 183 clutch_bucket_circleq = clutch_bucket_runq.scbrq_queues[pri] 184 for clutch_bucket in IterateCircleQueue(clutch_bucket_circleq, 'struct sched_clutch_bucket', 'scb_runqlink'): 185 clutch_bucket_list.append(clutch_bucket) 186 if len(clutch_bucket_list) > 0: 187 clutch_bucket_list.sort(key=lambda x: x.scb_priority, reverse=True) 188 for clutch_bucket in clutch_bucket_list: 189 print("{:>10s} | {:>20s} | {:>30s} | {:>25s} | {:<18s} | {:>10s} | {:>10s} | {:>15s} | ".format("", "", "", "", "", "", "", "")) 190 print("{:>10s} | {:>20s} | {:>30s} | {:>25s} | 0x{:<16x} | {:>10d} | {:>10d} | {:>15s} | ".format("*", "*", clutch_bucket.scb_group.scbg_clutch.sc_tg.tg_name, "*", clutch_bucket, clutch_bucket.scb_priority, clutch_bucket.scb_thr_count, "*") + GetSchedClutchBucketSummary(clutch_bucket)) 191 runq = clutch_bucket.scb_clutchpri_prioq 192 for thread in IterateSchedPriorityQueue(runq, 'struct thread', 'th_clutch_pri_link'): 193 thread_name = GetThreadName(thread)[-24:] 194 if len(thread_name) == 0: 195 thread_name = "<unnamed thread>" 196 print("{:>10s} | {:>20s} | {:>30s} | {:<25s} | 0x{:<16x} | {:>10d} | {:>10s} | {:>15s} | ".format("*", "*", "*", thread_name, thread, thread.base_pri, "*", "*")) 197 print("-" * 300) 198 root_bucket = root_clutch.scr_bound_buckets[i] 199 root_bucket_deadline = 0 200 if root_bucket.scrb_bound_thread_runq.count != 0: 201 root_bucket_deadline = kern.GetNanotimeFromAbstime(root_bucket.scrb_pqlink.deadline - GetRecentTimestamp()) // 1000 202 print("{:>10s} | {:>20s} | {:>30s} | {:>25s} | 0x{:<16x} | {:>10s} | {:>10d} | {:>15d} | ".format("*", bucketStr[int(root_bucket.scrb_bucket)] + " [Bound]", "*", "*", addressof(root_bucket), "*", root_bucket.scrb_bound_thread_runq.count, root_bucket_deadline)) 203 if root_bucket.scrb_bound_thread_runq.count == 0: 204 print("-" * 300) 205 continue 206 thread_runq = root_bucket.scrb_bound_thread_runq 207 for pri in range(0, 128): 208 thread_circleq = thread_runq.queues[pri] 209 for thread in IterateCircleQueue(thread_circleq, 'struct thread', 'runq_links'): 210 thread_name = GetThreadName(thread)[-24:] 211 if len(thread_name) == 0: 212 thread_name = "<unnamed thread>" 213 print("{:>10s} | {:>20s} | {:>30s} | {:<25s} | 0x{:<16x} | {:>10d} | {:>10s} | {:>15s} | ".format("*", "*", "*", thread_name, thread, thread.base_pri, "*", "*")) 214 print("-" * 300) 215 216@lldb_command('showschedclutch') 217def ShowSchedClutch(cmd_args=[]): 218 """ Routine to print the clutch scheduler hierarchy. 219 Usage: showschedclutch <pset> 220 """ 221 if not cmd_args: 222 raise ArgumentError("Invalid argument") 223 pset = kern.GetValueFromAddress(cmd_args[0], "processor_set_t") 224 ShowSchedClutchForPset(pset) 225 226@lldb_command('showschedclutchroot') 227def ShowSchedClutchRoot(cmd_args=[]): 228 """ show information about the root of the sched clutch hierarchy 229 Usage: showschedclutchroot <root> 230 """ 231 if not cmd_args: 232 raise ArgumentError("Invalid argument") 233 root = kern.GetValueFromAddress(cmd_args[0], "struct sched_clutch_root *") 234 if not root: 235 print("unknown arguments:", str(cmd_args)) 236 return False 237 print("{:>30s} : 0x{:<16x}".format("Root", root)) 238 print("{:>30s} : 0x{:<16x}".format("Pset", root.scr_pset)) 239 print("{:>30s} : {:d}".format("Priority", (root.scr_priority if root.scr_thr_count > 0 else -1))) 240 print("{:>30s} : {:d}".format("Urgency", root.scr_urgency)) 241 print("{:>30s} : {:d}".format("Threads", root.scr_thr_count)) 242 print("{:>30s} : {:d}".format("Current Timestamp", GetRecentTimestamp())) 243 print("{:>30s} : {:b} (BG/UT/DF/IN/FG/FIX/NULL)".format("Runnable Root Buckets Bitmap", int(root.scr_runnable_bitmap[0]))) 244 245@lldb_command('showschedclutchrootbucket') 246def ShowSchedClutchRootBucket(cmd_args=[]): 247 """ show information about a root bucket in the sched clutch hierarchy 248 Usage: showschedclutchrootbucket <root_bucket> 249 """ 250 if not cmd_args: 251 raise ArgumentError("Invalid argument") 252 root_bucket = kern.GetValueFromAddress(cmd_args[0], "struct sched_clutch_root_bucket *") 253 if not root_bucket: 254 print("unknown arguments:", str(cmd_args)) 255 return False 256 print("{:<30s} : 0x{:<16x}".format("Root Bucket", root_bucket)) 257 print("{:<30s} : {:s}".format("Bucket Name", bucketStr[int(root_bucket.scrb_bucket)])) 258 print("{:<30s} : {:d}".format("Deadline", (root_bucket.scrb_pqlink.deadline if root_bucket.scrb_clutch_buckets.scbrq_count != 0 else 0))) 259 print("{:<30s} : {:d}".format("Current Timestamp", GetRecentTimestamp())) 260 print("\n") 261 clutch_bucket_runq = root_bucket.scrb_clutch_buckets 262 clutch_bucket_list = [] 263 for pri in range(0,128): 264 clutch_bucket_circleq = clutch_bucket_runq.scbrq_queues[pri] 265 for clutch_bucket in IterateCircleQueue(clutch_bucket_circleq, 'struct sched_clutch_bucket', 'scb_runqlink'): 266 clutch_bucket_list.append(clutch_bucket) 267 if len(clutch_bucket_list) > 0: 268 print("=" * 240) 269 print("{:>30s} | {:>18s} | {:>20s} | {:>20s} | ".format("Name", "Clutch Bucket", "Priority", "Count") + GetSchedClutchBucketSummary.header) 270 print("=" * 240) 271 clutch_bucket_list.sort(key=lambda x: x.scb_priority, reverse=True) 272 for clutch_bucket in clutch_bucket_list: 273 print("{:>30s} | 0x{:<16x} | {:>20d} | {:>20d} | ".format(clutch_bucket.scb_group.scbg_clutch.sc_tg.tg_name, clutch_bucket, clutch_bucket.scb_priority, clutch_bucket.scb_thr_count) + GetSchedClutchBucketSummary(clutch_bucket)) 274 275def SchedClutchBucketDetails(clutch_bucket): 276 print("{:<30s} : 0x{:<16x}".format("Clutch Bucket", clutch_bucket)) 277 print("{:<30s} : {:s}".format("Scheduling Bucket", bucketStr[(int)(clutch_bucket.scb_bucket)])) 278 print("{:<30s} : 0x{:<16x}".format("Clutch Bucket Group", clutch_bucket.scb_group)) 279 print("{:<30s} : {:s}".format("TG Name", clutch_bucket.scb_group.scbg_clutch.sc_tg.tg_name)) 280 print("{:<30s} : {:d}".format("Priority", clutch_bucket.scb_priority)) 281 print("{:<30s} : {:d}".format("Thread Count", clutch_bucket.scb_thr_count)) 282 print("{:<30s} : 0x{:<16x}".format("Thread Group", clutch_bucket.scb_group.scbg_clutch.sc_tg)) 283 print("{:<30s} : {:6d} (inherited from clutch bucket group)".format("Interactivity Score", clutch_bucket.scb_group.scbg_interactivity_data.scct_count)) 284 print("{:<30s} : {:6d} (inherited from clutch bucket group)".format("Last Timeshare Update Tick", clutch_bucket.scb_group.scbg_timeshare_tick)) 285 print("{:<30s} : {:6d} (inherited from clutch bucket group)".format("Priority Shift", clutch_bucket.scb_group.scbg_pri_shift)) 286 print("\n") 287 runq = clutch_bucket.scb_clutchpri_prioq 288 thread_list = [] 289 for thread in IterateSchedPriorityQueue(runq, 'struct thread', 'th_clutch_pri_link'): 290 thread_list.append(thread) 291 if len(thread_list) > 0: 292 print("=" * 240) 293 print(GetThreadSummary.header + "{:s}".format("Process Name")) 294 print("=" * 240) 295 for thread in thread_list: 296 proc = thread.t_tro.tro_proc 297 print(GetThreadSummary(thread) + "{:s}".format(GetProcName(proc))) 298 299@lldb_command('showschedclutchbucket') 300def ShowSchedClutchBucket(cmd_args=[]): 301 """ show information about a clutch bucket in the sched clutch hierarchy 302 Usage: showschedclutchbucket <clutch_bucket> 303 """ 304 if not cmd_args: 305 raise ArgumentError("Invalid argument") 306 clutch_bucket = kern.GetValueFromAddress(cmd_args[0], "struct sched_clutch_bucket *") 307 if not clutch_bucket: 308 print("unknown arguments:", str(cmd_args)) 309 return False 310 SchedClutchBucketDetails(clutch_bucket) 311 312@lldb_command('abs2nano') 313def ShowAbstimeToNanoTime(cmd_args=[]): 314 """ convert mach_absolute_time units to nano seconds 315 Usage: (lldb) abs2nano <timestamp in MATUs> 316 """ 317 if not cmd_args: 318 raise ArgumentError("Invalid argument") 319 timedata = ArgumentStringToInt(cmd_args[0]) 320 ns = kern.GetNanotimeFromAbstime(timedata) 321 us = float(ns) / 1000 322 ms = us / 1000 323 s = ms / 1000 324 325 if s > 60 : 326 m = s // 60 327 h = m // 60 328 d = h // 24 329 330 print("{:d} ns, {:f} us, {:f} ms, {:f} s, {:f} m, {:f} h, {:f} d".format(ns, us, ms, s, m, h, d)) 331 else: 332 print("{:d} ns, {:f} us, {:f} ms, {:f} s".format(ns, us, ms, s)) 333 334 # Macro: showschedhistory 335 336def GetRecentTimestamp(): 337 """ 338 Return a recent timestamp. 339 TODO: on x86, if not in the debugger, then look at the scheduler 340 """ 341 if kern.arch == 'x86_64': 342 most_recent_dispatch = GetSchedMostRecentDispatch(False) 343 if most_recent_dispatch > kern.globals.debugger_entry_time : 344 return most_recent_dispatch 345 else : 346 return kern.globals.debugger_entry_time 347 else : 348 return GetSchedMostRecentDispatch(False) 349 350def GetSchedMostRecentDispatch(show_processor_details=False): 351 """ Return the most recent dispatch on the system, printing processor 352 details if argument is true. 353 """ 354 355 most_recent_dispatch = 0 356 357 for current_processor in IterateLinkedList(kern.globals.processor_list, 'processor_list') : 358 active_thread = current_processor.active_thread 359 thread_id = 0 360 361 if unsigned(active_thread) != 0 : 362 task_val = active_thread.t_tro.tro_task 363 proc_val = active_thread.t_tro.tro_proc 364 proc_name = "<unknown>" if unsigned(proc_val) == 0 else GetProcName(proc_val) 365 thread_id = active_thread.thread_id 366 367 last_dispatch = unsigned(current_processor.last_dispatch) 368 369 if kern.arch == 'x86_64': 370 cpu_data = kern.globals.cpu_data_ptr[current_processor.cpu_id] 371 if (cpu_data != 0) : 372 cpu_debugger_time = max(cpu_data.debugger_entry_time, cpu_data.debugger_ipi_time) 373 time_since_dispatch = unsigned(cpu_debugger_time - last_dispatch) 374 time_since_dispatch_us = kern.GetNanotimeFromAbstime(time_since_dispatch) / 1000.0 375 time_since_debugger = unsigned(cpu_debugger_time - kern.globals.debugger_entry_time) 376 time_since_debugger_us = kern.GetNanotimeFromAbstime(time_since_debugger) / 1000.0 377 378 if show_processor_details: 379 print("Processor last dispatch: {:16d} Entered debugger: {:16d} ({:8.3f} us after dispatch, {:8.3f} us after debugger) Active thread: 0x{t:<16x} 0x{thread_id:<8x} {proc_name:s}".format(last_dispatch, cpu_debugger_time, 380 time_since_dispatch_us, time_since_debugger_us, t=active_thread, thread_id=thread_id, proc_name=proc_name)) 381 else: 382 if show_processor_details: 383 print("Processor last dispatch: {:16d} Active thread: 0x{t:<16x} 0x{thread_id:<8x} {proc_name:s}".format(last_dispatch, t=active_thread, thread_id=thread_id, proc_name=proc_name)) 384 385 if last_dispatch > most_recent_dispatch: 386 most_recent_dispatch = last_dispatch 387 388 return most_recent_dispatch 389 390@header("{:<18s} {:<10s} {:>16s} {:>16s} {:>16s} {:>16s} {:>18s} {:>16s} {:>16s} {:>16s} {:>16s} {:2s} {:2s} {:2s} {:>2s} {:<19s} {:<9s} {:>10s} {:>10s} {:>10s} {:>10s} {:>10s} {:>11s} {:>8s}".format("thread", "id", "on-core", "off-core", "runnable", "prichange", "last-duration (us)", "since-off (us)", "since-on (us)", "pending (us)", "pri-change (us)", "BP", "SP", "TP", "MP", "sched-mode", "state", "cpu-usage", "delta", "sch-usage", "stamp", "shift", "task", "thread-name")) 391def ShowThreadSchedHistory(thread, most_recent_dispatch): 392 """ Given a thread and the most recent dispatch time of a thread on the 393 system, print out details about scheduler history for the thread. 394 """ 395 396 thread_name = "" 397 398 uthread = GetBSDThread(thread) 399 # Doing the straightforward thing blows up weirdly, so use some indirections to get back on track 400 if unsigned(uthread.pth_name) != 0 : 401 thread_name = str(kern.GetValueFromAddress(unsigned(uthread.pth_name), 'char*')) 402 403 task = thread.t_tro.tro_task 404 405 task_name = "unknown" 406 p = GetProcFromTask(task) 407 if task and p: 408 task_name = GetProcName(p) 409 410 sched_mode = "" 411 412 mode = str(thread.sched_mode) 413 if "TIMESHARE" in mode: 414 sched_mode+="timeshare" 415 elif "FIXED" in mode: 416 sched_mode+="fixed" 417 elif "REALTIME" in mode: 418 sched_mode+="realtime" 419 420 if (unsigned(thread.bound_processor) != 0): 421 sched_mode+="-bound" 422 423 # TH_SFLAG_THROTTLED 424 if (unsigned(thread.sched_flags) & 0x0004): 425 sched_mode+="-BG" 426 427 state = thread.state 428 429 thread_state_chars = {0x0:'', 0x1:'W', 0x2:'S', 0x4:'R', 0x8:'U', 0x10:'H', 0x20:'A', 0x40:'P', 0x80:'I'} 430 state_str = '' 431 mask = 0x1 432 while mask <= 0x80 : 433 state_str += thread_state_chars[int(state & mask)] 434 mask = mask << 1 435 436 last_on = thread.computation_epoch 437 last_off = thread.last_run_time 438 last_runnable = thread.last_made_runnable_time 439 last_prichange = thread.last_basepri_change_time 440 441 if int(last_runnable) == 18446744073709551615 : 442 last_runnable = 0 443 444 if int(last_prichange) == 18446744073709551615 : 445 last_prichange = 0 446 447 time_on_abs = unsigned(last_off - last_on) 448 time_on_us = kern.GetNanotimeFromAbstime(time_on_abs) / 1000.0 449 450 time_pending_abs = unsigned(most_recent_dispatch - last_runnable) 451 time_pending_us = kern.GetNanotimeFromAbstime(time_pending_abs) / 1000.0 452 453 if int(last_runnable) == 0 : 454 time_pending_us = 0 455 456 last_prichange_abs = unsigned(most_recent_dispatch - last_prichange) 457 last_prichange_us = kern.GetNanotimeFromAbstime(last_prichange_abs) / 1000.0 458 459 if int(last_prichange) == 0 : 460 last_prichange_us = 0 461 462 time_since_off_abs = unsigned(most_recent_dispatch - last_off) 463 time_since_off_us = kern.GetNanotimeFromAbstime(time_since_off_abs) / 1000.0 464 time_since_on_abs = unsigned(most_recent_dispatch - last_on) 465 time_since_on_us = kern.GetNanotimeFromAbstime(time_since_on_abs) / 1000.0 466 467 fmt = "0x{t:<16x} 0x{t.thread_id:<8x} {t.computation_epoch:16d} {t.last_run_time:16d} {last_runnable:16d} {last_prichange:16d} {time_on_us:18.3f} {time_since_off_us:16.3f} {time_since_on_us:16.3f} {time_pending_us:16.3f} {last_prichange_us:16.3f}" 468 fmt2 = " {t.base_pri:2d} {t.sched_pri:2d} {t.task_priority:2d} {t.max_priority:2d} {sched_mode:19s}" 469 fmt3 = " {state:9s} {t.cpu_usage:10d} {t.cpu_delta:10d} {t.sched_usage:10d} {t.sched_stamp:10d} {t.pri_shift:10d} {name:s} {thread_name:s}" 470 471 out_str = fmt.format(t=thread, time_on_us=time_on_us, time_since_off_us=time_since_off_us, time_since_on_us=time_since_on_us, last_runnable=last_runnable, time_pending_us=time_pending_us, last_prichange=last_prichange, last_prichange_us=last_prichange_us) 472 out_str += fmt2.format(t=thread, sched_mode=sched_mode) 473 out_str += fmt3.format(t=thread, state=state_str, name=task_name, thread_name=thread_name) 474 475 print(out_str) 476 477def SortThreads(threads, column): 478 if column != 'on-core' and column != 'off-core' and column != 'last-duration': 479 raise ArgumentError("unsupported sort column") 480 if column == 'on-core': 481 threads.sort(key=lambda t: t.computation_epoch) 482 elif column == 'off-core': 483 threads.sort(key=lambda t: t.last_run_time) 484 else: 485 threads.sort(key=lambda t: t.last_run_time - t.computation_epoch) 486 487@lldb_command('showschedhistory', 'S:') 488def ShowSchedHistory(cmd_args=None, cmd_options=None): 489 """ Routine to print out thread scheduling history, optionally sorted by a 490 column. 491 492 Usage: showschedhistory [-S on-core|off-core|last-duration] [<thread-ptr> ...] 493 """ 494 495 sort_column = None 496 if '-S' in cmd_options: 497 sort_column = cmd_options['-S'] 498 499 if cmd_args: 500 most_recent_dispatch = GetSchedMostRecentDispatch(False) 501 502 print(ShowThreadSchedHistory.header) 503 504 if sort_column: 505 threads = [] 506 for thread_ptr in cmd_args: 507 threads.append(kern.GetValueFromAddress(ArgumentStringToInt(thread_ptr), 'thread *')) 508 509 SortThreads(threads, sort_column) 510 511 for thread in threads: 512 ShowThreadSchedHistory(thread, most_recent_dispatch) 513 else: 514 for thread_ptr in cmd_args: 515 thread = kern.GetValueFromAddress(ArgumentStringToInt(thread_ptr), 'thread *') 516 ShowThreadSchedHistory(thread, most_recent_dispatch) 517 518 return 519 520 run_buckets = kern.globals.sched_run_buckets 521 522 run_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_RUN')] 523 fixpri_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_FIXPRI')] 524 share_fg_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_FG')] 525 share_df_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_DF')] 526 share_ut_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_UT')] 527 share_bg_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_BG')] 528 529 sched_pri_shifts = kern.globals.sched_run_buckets 530 531 share_fg_shift = sched_pri_shifts[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_FG')] 532 share_df_shift = sched_pri_shifts[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_DF')] 533 share_ut_shift = sched_pri_shifts[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_UT')] 534 share_bg_shift = sched_pri_shifts[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_BG')] 535 536 537 print("Processors: {g.processor_avail_count:d} Runnable threads: {:d} Fixpri threads: {:d}\n".format(run_count, fixpri_count, g=kern.globals)) 538 print("FG Timeshare threads: {:d} DF Timeshare threads: {:d} UT Timeshare threads: {:d} BG Timeshare threads: {:d}\n".format(share_fg_count, share_df_count, share_ut_count, share_bg_count)) 539 print("Mach factor: {g.sched_mach_factor:d} Load factor: {g.sched_load_average:d} Sched tick: {g.sched_tick:d} timestamp: {g.sched_tick_last_abstime:d} interval:{g.sched_tick_interval:d}\n".format(g=kern.globals)) 540 print("Fixed shift: {g.sched_fixed_shift:d} FG shift: {:d} DF shift: {:d} UT shift: {:d} BG shift: {:d}\n".format(share_fg_shift, share_df_shift, share_ut_shift, share_bg_shift, g=kern.globals)) 541 print("sched_pri_decay_band_limit: {g.sched_pri_decay_band_limit:d} sched_decay_usage_age_factor: {g.sched_decay_usage_age_factor:d}\n".format(g=kern.globals)) 542 543 if kern.arch == 'x86_64': 544 print("debugger_entry_time: {g.debugger_entry_time:d}\n".format(g=kern.globals)) 545 546 most_recent_dispatch = GetSchedMostRecentDispatch(True) 547 print("Most recent dispatch: " + str(most_recent_dispatch)) 548 549 print(ShowThreadSchedHistory.header) 550 551 if sort_column: 552 threads = [t for t in IterateQueue(kern.globals.threads, 'thread *', 'threads')] 553 554 SortThreads(threads, sort_column) 555 556 for thread in threads: 557 ShowThreadSchedHistory(thread, most_recent_dispatch) 558 else: 559 for thread in IterateQueue(kern.globals.threads, 'thread *', 'threads'): 560 ShowThreadSchedHistory(thread, most_recent_dispatch) 561 562 563# EndMacro: showschedhistory 564 565def int32(n): 566 n = n & 0xffffffff 567 return (n ^ 0x80000000) - 0x80000000 568 569# Macro: showallprocessors 570 571def ShowGroupSetSummary(runq, task_map): 572 """ Internal function to print summary of group run queue 573 params: runq - value representing struct run_queue * 574 """ 575 576 print(" runq: count {: <10d} highq: {: <10d} urgency {: <10d}\n".format(runq.count, int32(runq.highq), runq.urgency)) 577 578 runq_queue_i = 0 579 runq_queue_count = sizeof(runq.queues) // sizeof(runq.queues[0]) 580 581 for runq_queue_i in range(runq_queue_count) : 582 runq_queue_head = addressof(runq.queues[runq_queue_i]) 583 runq_queue_p = runq_queue_head.next 584 585 if unsigned(runq_queue_p) != unsigned(runq_queue_head): 586 runq_queue_this_count = 0 587 588 for entry in ParanoidIterateLinkageChain(runq_queue_head, "sched_entry_t", "entry_links", circleQueue=True): 589 runq_queue_this_count += 1 590 591 print(" Queue [{: <#012x}] Priority {: <3d} count {:d}\n".format(runq_queue_head, runq_queue_i, runq_queue_this_count)) 592 for entry in ParanoidIterateLinkageChain(runq_queue_head, "sched_entry_t", "entry_links", circleQueue=True): 593 group_addr = unsigned(entry) - (sizeof(dereference(entry)) * unsigned(entry.sched_pri)) 594 group = kern.GetValueFromAddress(unsigned(group_addr), 'sched_group_t') 595 task = task_map.get(unsigned(group), 0x0) 596 if task == 0x0 : 597 print("Cannot find task for group: {: <#012x}".format(group)) 598 print("\tEntry [{: <#012x}] Priority {: <3d} Group {: <#012x} Task {: <#012x}\n".format(unsigned(entry), entry.sched_pri, unsigned(group), unsigned(task))) 599 600@lldb_command('showrunq') 601def ShowRunq(cmd_args=None): 602 """ Routine to print information of a runq 603 Usage: showrunq <runq> 604 """ 605 606 if not cmd_args: 607 print("No arguments passed") 608 print(ShowRunq.__doc__) 609 return False 610 611 runq = kern.GetValueFromAddress(cmd_args[0], 'struct run_queue *') 612 ShowRunQSummary(runq) 613 614def ShowRunQSummary(runq): 615 """ Internal function to print summary of run_queue 616 params: runq - value representing struct run_queue * 617 """ 618 619 print(" runq: count {: <10d} highq: {: <10d} urgency {: <10d}\n".format(runq.count, int32(runq.highq), runq.urgency)) 620 621 runq_queue_i = 0 622 runq_queue_count = sizeof(runq.queues) // sizeof(runq.queues[0]) 623 624 for runq_queue_i in range(runq_queue_count) : 625 runq_queue_head = addressof(runq.queues[runq_queue_i]) 626 runq_queue_p = runq_queue_head.head 627 628 if unsigned(runq_queue_p): 629 runq_queue_this_count = 0 630 631 for thread in ParanoidIterateLinkageChain(runq_queue_head, "thread_t", "runq_links", circleQueue=True): 632 runq_queue_this_count += 1 633 634 print(" Queue [{: <#012x}] Priority {: <3d} count {:d}\n".format(runq_queue_head, runq_queue_i, runq_queue_this_count)) 635 print("\t" + GetThreadSummary.header + "\n") 636 for thread in ParanoidIterateLinkageChain(runq_queue_head, "thread_t", "runq_links", circleQueue=True): 637 print("\t" + GetThreadSummary(thread) + "\n") 638 if config['verbosity'] > vHUMAN : 639 print("\t" + GetThreadBackTrace(thread, prefix="\t\t") + "\n") 640 641def ShowRTRunQSummary(rt_runq): 642 if (hex(rt_runq.count) == hex(0xfdfdfdfd)) : 643 print(" Realtime Queue ({:<#012x}) uninitialized\n".format(rt_runq)) 644 return 645 print(" Realtime Queue ({:<#012x}) Count {:d}\n".format(rt_runq, rt_runq.count)) 646 if rt_runq.count != 0: 647 rt_pri_bitmap = int(rt_runq.bitmap[0]) 648 for rt_index in IterateBitmap(rt_pri_bitmap): 649 rt_pri_rq = addressof(rt_runq.rt_queue_pri[rt_index]) 650 print(" Realtime Queue Index {:d} ({:<#012x}) Count {:d}\n".format(rt_index, rt_pri_rq, rt_pri_rq.pri_count)) 651 print("\t" + GetThreadSummary.header + "\n") 652 for rt_runq_thread in ParanoidIterateLinkageChain(rt_pri_rq.pri_queue, "thread_t", "runq_links", circleQueue=False): 653 print("\t" + GetThreadSummary(rt_runq_thread) + "\n") 654 655def ShowGrrrSummary(grrr_runq): 656 """ Internal function to print summary of grrr_run_queue 657 params: grrr_runq - value representing struct grrr_run_queue * 658 """ 659 print(" GRRR Info: Count {: <10d} Weight {: <10d} Current Group {: <#012x}\n".format(grrr_runq.count, 660 grrr_runq.weight, grrr_runq.current_group)) 661 grrr_group_i = 0 662 grrr_group_count = sizeof(grrr_runq.groups) // sizeof(grrr_runq.groups[0]) 663 for grrr_group_i in range(grrr_group_count) : 664 grrr_group = addressof(grrr_runq.groups[grrr_group_i]) 665 if grrr_group.count > 0: 666 print(" Group {: <3d} [{: <#012x}] ".format(grrr_group.index, grrr_group)) 667 print("Count {:d} Weight {:d}\n".format(grrr_group.count, grrr_group.weight)) 668 grrr_group_client_head = addressof(grrr_group.clients) 669 print(GetThreadSummary.header) 670 for thread in ParanoidIterateLinkageChain(grrr_group_client_head, "thread_t", "runq_links", circleQueue=True): 671 print("\t" + GetThreadSummary(thread) + "\n") 672 if config['verbosity'] > vHUMAN : 673 print("\t" + GetThreadBackTrace(thread, prefix="\t\t") + "\n") 674 675def ShowActiveThread(processor): 676 if (processor.active_thread != 0) : 677 print("\t" + GetThreadSummary.header + "\n") 678 print("\t" + GetThreadSummary(processor.active_thread) + "\n") 679 680@lldb_command('showallprocessors') 681@lldb_command('showscheduler') 682def ShowScheduler(cmd_args=None): 683 """ Routine to print information of all psets and processors 684 Usage: showscheduler 685 """ 686 node = addressof(kern.globals.pset_node0) 687 show_grrr = 0 688 show_priority_runq = 0 689 show_priority_pset_runq = 0 690 show_group_pset_runq = 0 691 show_clutch = 0 692 show_edge = 0 693 sched_string = str(kern.globals.sched_string) 694 695 if sched_string == "traditional": 696 show_priority_runq = 1 697 elif sched_string == "traditional_with_pset_runqueue": 698 show_priority_pset_runq = 1 699 elif sched_string == "grrr": 700 show_grrr = 1 701 elif sched_string == "multiq": 702 show_priority_runq = 1 703 show_group_pset_runq = 1 704 elif sched_string == "dualq": 705 show_priority_pset_runq = 1 706 show_priority_runq = 1 707 elif sched_string == "amp": 708 show_priority_pset_runq = 1 709 show_priority_runq = 1 710 elif sched_string == "clutch": 711 show_clutch = 1 712 elif sched_string == "edge": 713 show_edge = 1 714 else : 715 print("Unknown sched_string {:s}".format(sched_string)) 716 717 print("Scheduler: {:s}\n".format(sched_string)) 718 719 if show_clutch == 0 and show_edge == 0: 720 run_buckets = kern.globals.sched_run_buckets 721 run_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_RUN')] 722 fixpri_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_FIXPRI')] 723 share_fg_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_FG')] 724 share_df_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_DF')] 725 share_ut_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_UT')] 726 share_bg_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_BG')] 727 print("Processors: {g.processor_avail_count:d} Runnable threads: {:d} Fixpri threads: {:d}\n".format(run_count, fixpri_count, g=kern.globals)) 728 print("FG Timeshare threads: {:d} DF Timeshare threads: {:d} UT Timeshare threads: {:d} BG Timeshare threads: {:d}\n".format(share_fg_count, share_df_count, share_ut_count, share_bg_count)) 729 730 processor_offline = GetEnumValue('processor_state_t::PROCESSOR_OFF_LINE') 731 processor_idle = GetEnumValue('processor_state_t::PROCESSOR_IDLE') 732 processor_dispatching = GetEnumValue('processor_state_t::PROCESSOR_DISPATCHING') 733 processor_running = GetEnumValue('processor_state_t::PROCESSOR_RUNNING') 734 735 if show_group_pset_runq: 736 if hasattr(kern.globals, "multiq_sanity_check"): 737 print("multiq scheduler config: deep-drain {g.deep_drain:d}, ceiling {g.drain_ceiling:d}, depth limit {g.drain_depth_limit:d}, band limit {g.drain_band_limit:d}, sanity check {g.multiq_sanity_check:d}\n".format(g=kern.globals)) 738 else: 739 print("multiq scheduler config: deep-drain {g.deep_drain:d}, ceiling {g.drain_ceiling:d}, depth limit {g.drain_depth_limit:d}, band limit {g.drain_band_limit:d}\n".format(g=kern.globals)) 740 741 # Create a group->task mapping 742 task_map = {} 743 for task in kern.tasks: 744 task_map[unsigned(task.sched_group)] = task 745 for task in kern.terminated_tasks: 746 task_map[unsigned(task.sched_group)] = task 747 748 print() 749 750 while node != 0: 751 pset = node.psets 752 pset = kern.GetValueFromAddress(unsigned(pset), 'struct processor_set *') 753 754 while pset != 0: 755 print("Processor Set {: <#012x} Count {:d} (cpu_id {:<#x}-{:<#x})\n".format(pset, 756 unsigned(pset.cpu_set_count), pset.cpu_set_low, pset.cpu_set_hi)) 757 758 rt_runq = kern.GetValueFromAddress(unsigned(addressof(pset.rt_runq)), 'struct rt_queue *') 759 ShowRTRunQSummary(rt_runq) 760 761 if show_priority_pset_runq: 762 runq = kern.GetValueFromAddress(unsigned(addressof(pset.pset_runq)), 'struct run_queue *') 763 ShowRunQSummary(runq) 764 765 if show_group_pset_runq: 766 print("Main Runq:\n") 767 runq = kern.GetValueFromAddress(unsigned(addressof(pset.pset_runq)), 'struct run_queue *') 768 ShowGroupSetSummary(runq, task_map) 769 print("All Groups:\n") 770 # TODO: Possibly output task header for each group 771 for group in IterateQueue(kern.globals.sched_groups, "sched_group_t", "sched_groups"): 772 if (group.runq.count != 0) : 773 task = task_map.get(unsigned(group), "Unknown task!") 774 print("Group {: <#012x} Task {: <#012x}\n".format(unsigned(group), unsigned(task))) 775 ShowRunQSummary(group.runq) 776 print() 777 778 processor_array = kern.globals.processor_array 779 780 print("Active Processors:\n") 781 active_bitmap = int(pset.cpu_state_map[processor_dispatching]) | int(pset.cpu_state_map[processor_running]) 782 for cpuid in IterateBitmap(active_bitmap): 783 processor = processor_array[cpuid] 784 if processor != 0: 785 print(" " + GetProcessorSummary(processor)) 786 ShowActiveThread(processor) 787 788 if show_priority_runq: 789 runq = processor.runq 790 ShowRunQSummary(runq) 791 if show_grrr: 792 grrr_runq = processor.grrr_runq 793 ShowGrrrSummary(grrr_runq) 794 print() 795 796 797 print("Idle Processors:\n") 798 idle_bitmap = int(pset.cpu_state_map[processor_idle]) & int(pset.primary_map) 799 for cpuid in IterateBitmap(idle_bitmap): 800 processor = processor_array[cpuid] 801 if processor != 0: 802 print(" " + GetProcessorSummary(processor)) 803 ShowActiveThread(processor) 804 805 if show_priority_runq: 806 ShowRunQSummary(processor.runq) 807 print() 808 809 810 print("Idle Secondary Processors:\n") 811 idle_bitmap = int(pset.cpu_state_map[processor_idle]) & ~(int(pset.primary_map)) 812 for cpuid in IterateBitmap(idle_bitmap): 813 processor = processor_array[cpuid] 814 if processor != 0: 815 print(" " + GetProcessorSummary(processor)) 816 ShowActiveThread(processor) 817 818 if show_priority_runq: 819 print(ShowRunQSummary(processor.runq)) 820 print() 821 822 823 print("Other Processors:\n") 824 other_bitmap = 0 825 for i in range(processor_offline, processor_idle): 826 other_bitmap |= int(pset.cpu_state_map[i]) 827 other_bitmap &= int(pset.cpu_bitmask) 828 for cpuid in IterateBitmap(other_bitmap): 829 processor = processor_array[cpuid] 830 if processor != 0: 831 print(" " + GetProcessorSummary(processor)) 832 ShowActiveThread(processor) 833 834 if show_priority_runq: 835 ShowRunQSummary(processor.runq) 836 print() 837 838 if show_clutch or show_edge: 839 cluster_type = "SMP" 840 if pset.pset_type == 1: 841 cluster_type = "E" 842 elif pset.pset_type == 2: 843 cluster_type = "P" 844 print("=== Clutch Scheduler Hierarchy Pset{:d} (Type: {:s}) ] ===\n\n".format(pset.pset_cluster_id, cluster_type)) 845 ShowSchedClutchForPset(pset) 846 847 pset = pset.pset_list 848 849 node = node.node_list 850 851 print("\nCrashed Threads Queue: ({:<#012x})\n".format(addressof(kern.globals.crashed_threads_queue))) 852 first = True 853 for thread in ParanoidIterateLinkageChain(kern.globals.crashed_threads_queue, "thread_t", "runq_links"): 854 if first: 855 print("\t" + GetThreadSummary.header) 856 first = False 857 print("\t" + GetThreadSummary(thread)) 858 859 def dump_mpsc_thread_queue(name, head): 860 head = addressof(head) 861 print("\n{:s}: ({:<#012x})\n".format(name, head)) 862 first = True 863 for thread in IterateMPSCQueue(head.mpd_queue, 'struct thread', 'mpsc_links'): 864 if first: 865 print("\t" + GetThreadSummary.header) 866 first = False 867 print("\t" + GetThreadSummary(thread)) 868 869 dump_mpsc_thread_queue("Terminate Queue", kern.globals.thread_terminate_queue) 870 dump_mpsc_thread_queue("Waiting For Kernel Stacks Queue", kern.globals.thread_stack_queue) 871 dump_mpsc_thread_queue("Thread Exception Queue", kern.globals.thread_exception_queue) 872 dump_mpsc_thread_queue("Thread Deallocate Queue", kern.globals.thread_deallocate_queue) 873 874 print() 875 876# EndMacro: showallprocessors 877 878 879def ParanoidIterateLinkageChain(queue_head, element_type, field_name, field_ofst=0, circleQueue=False): 880 """ Iterate over a Linkage Chain queue in kernel of type queue_head_t or circle_queue_head_t. (osfmk/kern/queue.h method 1 or circle_queue.h) 881 This is equivalent to the qe_foreach_element() macro 882 Blows up aggressively and descriptively when something goes wrong iterating a queue. 883 Prints correctness errors, and throws exceptions on 'cannot proceed' errors 884 If this is annoying, set the global 'enable_paranoia' to false. 885 886 params: 887 queue_head - value : Value object for queue_head. 888 element_type - lldb.SBType : pointer type of the element which contains the queue_chain_t. Typically its structs like thread, task etc.. 889 - str : OR a string describing the type. ex. 'task *' 890 field_name - str : Name of the field (in element) which holds a queue_chain_t 891 field_ofst - int : offset from the 'field_name' (in element) which holds a queue_chain_t 892 This is mostly useful if a particular element contains an array of queue_chain_t 893 returns: 894 A generator does not return. It is used for iterating. 895 value : An object thats of type (element_type). Always a pointer object 896 example usage: 897 for thread in IterateQueue(kern.globals.threads, 'thread *', 'threads'): 898 print thread.thread_id 899 """ 900 901 if isinstance(element_type, str): 902 element_type = gettype(element_type) 903 904 # Some ways of constructing a queue head seem to end up with the 905 # struct object as the value and not a pointer to the struct head 906 # In that case, addressof will give us a pointer to the struct, which is what we need 907 if not queue_head.GetSBValue().GetType().IsPointerType() : 908 queue_head = addressof(queue_head) 909 910 if circleQueue: 911 # Mosh the value into a brand new value, to really get rid of its old cvalue history 912 queue_head = kern.GetValueFromAddress(unsigned(queue_head), 'struct circle_queue_head *').head 913 else: 914 # Mosh the value into a brand new value, to really get rid of its old cvalue history 915 queue_head = kern.GetValueFromAddress(unsigned(queue_head), 'struct queue_entry *') 916 917 if unsigned(queue_head) == 0: 918 if not circleQueue and ParanoidIterateLinkageChain.enable_paranoia: 919 print("bad queue_head_t: {:s}".format(queue_head)) 920 return 921 922 if element_type.IsPointerType(): 923 struct_type = element_type.GetPointeeType() 924 else: 925 struct_type = element_type 926 927 elem_ofst = struct_type.xGetFieldOffset(field_name) + field_ofst 928 929 try: 930 link = queue_head.next 931 last_link = queue_head 932 try_read_next = unsigned(queue_head.next) 933 except: 934 print("Exception while looking at queue_head: {:>#18x}".format(unsigned(queue_head))) 935 raise 936 937 if ParanoidIterateLinkageChain.enable_paranoia: 938 if unsigned(queue_head.next) == 0: 939 raise ValueError("NULL next pointer on head: queue_head {:>#18x} next: {:>#18x} prev: {:>#18x}".format(queue_head, queue_head.next, queue_head.prev)) 940 if unsigned(queue_head.prev) == 0: 941 print("NULL prev pointer on head: queue_head {:>#18x} next: {:>#18x} prev: {:>#18x}".format(queue_head, queue_head.next, queue_head.prev)) 942 if unsigned(queue_head.next) == unsigned(queue_head) and unsigned(queue_head.prev) != unsigned(queue_head): 943 print("corrupt queue_head {:>#18x} next: {:>#18x} prev: {:>#18x}".format(queue_head, queue_head.next, queue_head.prev)) 944 945 if ParanoidIterateLinkageChain.enable_debug : 946 print("starting at queue_head {:>#18x} next: {:>#18x} prev: {:>#18x}".format(queue_head, queue_head.next, queue_head.prev)) 947 948 addr = 0 949 obj = 0 950 951 try: 952 while True: 953 if not circleQueue and unsigned(queue_head) == unsigned(link): 954 break; 955 if ParanoidIterateLinkageChain.enable_paranoia: 956 if unsigned(link.next) == 0: 957 raise ValueError("NULL next pointer: queue_head {:>#18x} link: {:>#18x} next: {:>#18x} prev: {:>#18x}".format(queue_head, link, link.next, link.prev)) 958 if unsigned(link.prev) == 0: 959 print("NULL prev pointer: queue_head {:>#18x} link: {:>#18x} next: {:>#18x} prev: {:>#18x}".format(queue_head, link, link.next, link.prev)) 960 if unsigned(last_link) != unsigned(link.prev): 961 print("Corrupt prev pointer: queue_head {:>#18x} link: {:>#18x} next: {:>#18x} prev: {:>#18x} prev link: {:>#18x} ".format( 962 queue_head, link, link.next, link.prev, last_link)) 963 964 addr = unsigned(link) - unsigned(elem_ofst); 965 obj = kern.GetValueFromAddress(addr, element_type) 966 if ParanoidIterateLinkageChain.enable_debug : 967 print("yielding link: {:>#18x} next: {:>#18x} prev: {:>#18x} addr: {:>#18x} obj: {:>#18x}".format(link, link.next, link.prev, addr, obj)) 968 yield obj 969 last_link = link 970 link = link.next 971 if circleQueue and unsigned(queue_head) == unsigned(link): 972 break; 973 except: 974 try: 975 print("Exception while iterating queue: {:>#18x} link: {:>#18x} addr: {:>#18x} obj: {:>#18x} last link: {:>#18x}".format(queue_head, link, addr, obj, last_link)) 976 except: 977 import traceback 978 traceback.print_exc() 979 raise 980 981ParanoidIterateLinkageChain.enable_paranoia = True 982ParanoidIterateLinkageChain.enable_debug = False 983 984def LinkageChainEmpty(queue_head): 985 if not queue_head.GetSBValue().GetType().IsPointerType() : 986 queue_head = addressof(queue_head) 987 988 # Mosh the value into a brand new value, to really get rid of its old cvalue history 989 # avoid using GetValueFromAddress 990 queue_head = value(queue_head.GetSBValue().CreateValueFromExpression(None,'(void *)'+str(unsigned(queue_head)))) 991 queue_head = cast(queue_head, 'struct queue_entry *') 992 993 link = queue_head.next 994 995 return unsigned(queue_head) == unsigned(link) 996 997def bit_first(bitmap): 998 return bitmap.bit_length() - 1 999 1000def lsb_first(bitmap): 1001 bitmap = bitmap & -bitmap 1002 return bit_first(bitmap) 1003 1004def IterateBitmap(bitmap): 1005 """ Iterate over a bitmap, returning the index of set bits starting from 0 1006 1007 params: 1008 bitmap - value : bitmap 1009 returns: 1010 A generator does not return. It is used for iterating. 1011 value : index of a set bit 1012 example usage: 1013 for cpuid in IterateBitmap(running_bitmap): 1014 print processor_array[cpuid] 1015 """ 1016 i = lsb_first(bitmap) 1017 while (i >= 0): 1018 yield i 1019 bitmap = bitmap & ~((1 << (i + 1)) - 1) 1020 i = lsb_first(bitmap) 1021 1022 1023# Macro: showallcallouts 1024 1025from kevent import GetKnoteKqueue 1026 1027def ShowThreadCall(prefix, call, recent_timestamp, pqueue, is_pending=False): 1028 """ 1029 Print a description of a thread_call_t and its relationship to its expected fire time 1030 """ 1031 func = call.tc_func 1032 param0 = call.tc_param0 1033 param1 = call.tc_param1 1034 1035 is_iotes = False 1036 1037 func_name = kern.Symbolicate(func) 1038 1039 extra_string = "" 1040 1041 strip_func = kern.StripKernelPAC(unsigned(func)) 1042 1043 func_syms = kern.SymbolicateFromAddress(strip_func) 1044 # returns an array of SBSymbol 1045 1046 if func_syms and func_syms[0] : 1047 func_name = func_syms[0].GetName() 1048 1049 try : 1050 if ("IOTimerEventSource::timeoutAndRelease" in func_name or 1051 "IOTimerEventSource::timeoutSignaled" in func_name) : 1052 iotes = Cast(call.tc_param0, 'IOTimerEventSource*') 1053 try: 1054 func = iotes.action 1055 param0 = iotes.owner 1056 param1 = unsigned(iotes) 1057 except AttributeError: 1058 # This is horrible, horrible, horrible. But it works. Needed because IOEventSource hides the action member in an 1059 # anonymous union when XNU_PRIVATE_SOURCE is set. To grab it, we work backwards from the enabled member. 1060 func = dereference(kern.GetValueFromAddress(addressof(iotes.enabled) - sizeof('IOEventSource::Action'), 'uint64_t *')) 1061 param0 = iotes.owner 1062 param1 = unsigned(iotes) 1063 1064 workloop = iotes.workLoop 1065 thread = workloop.workThread 1066 1067 is_iotes = True 1068 1069 # re-symbolicate the func we found inside the IOTES 1070 strip_func = kern.StripKernelPAC(unsigned(func)) 1071 func_syms = kern.SymbolicateFromAddress(strip_func) 1072 if func_syms and func_syms[0] : 1073 func_name = func_syms[0].GetName() 1074 else : 1075 func_name = str(FindKmodNameForAddr(func)) 1076 1077 # cast from IOThread to thread_t, because IOThread is sometimes opaque 1078 thread = Cast(thread, 'thread_t') 1079 thread_id = thread.thread_id 1080 thread_name = GetThreadName(thread) 1081 1082 extra_string += "workloop thread: {:#x} ({:#x}) {:s}".format(thread, thread_id, thread_name) 1083 1084 if "filt_timerexpire" in func_name : 1085 knote = Cast(call.tc_param0, 'struct knote *') 1086 kqueue = GetKnoteKqueue(knote) 1087 proc = kqueue.kq_p 1088 proc_name = GetProcName(proc) 1089 proc_pid = GetProcPID(proc) 1090 1091 extra_string += "kq: {:#018x} {:s}[{:d}]".format(kqueue, proc_name, proc_pid) 1092 1093 if "mk_timer_expire" in func_name : 1094 timer = Cast(call.tc_param0, 'struct mk_timer *') 1095 port = timer.port 1096 1097 extra_string += "port: {:#018x} {:s}".format(port, GetPortDestinationSummary(port)) 1098 1099 if "workq_kill_old_threads_call" in func_name : 1100 workq = Cast(call.tc_param0, 'struct workqueue *') 1101 proc = workq.wq_proc 1102 proc_name = GetProcName(proc) 1103 proc_pid = GetProcPID(proc) 1104 1105 extra_string += "{:s}[{:d}]".format(proc_name, proc_pid) 1106 1107 if ("workq_add_new_threads_call" in func_name or 1108 "realitexpire" in func_name): 1109 proc = Cast(call.tc_param0, 'struct proc *') 1110 proc_name = GetProcName(proc) 1111 proc_pid = GetProcPID(proc) 1112 1113 extra_string += "{:s}[{:d}]".format(proc_name, proc_pid) 1114 1115 except: 1116 print("exception generating extra_string for call: {:#018x}".format(call)) 1117 if ShowThreadCall.enable_debug : 1118 raise 1119 1120 if (func_name == "") : 1121 func_name = FindKmodNameForAddr(func) 1122 1123 # e.g. func may be 0 if there is a bug 1124 if func_name is None : 1125 func_name = "No func_name!" 1126 1127 if (call.tc_flags & GetEnumValue('thread_call_flags_t::THREAD_CALL_FLAG_CONTINUOUS')) : 1128 timer_fire = call.tc_pqlink.deadline - (recent_timestamp + kern.globals.mach_absolutetime_asleep) 1129 soft_timer_fire = call.tc_soft_deadline - (recent_timestamp + kern.globals.mach_absolutetime_asleep) 1130 else : 1131 timer_fire = call.tc_pqlink.deadline - recent_timestamp 1132 soft_timer_fire = call.tc_soft_deadline - recent_timestamp 1133 1134 timer_fire_s = kern.GetNanotimeFromAbstime(timer_fire) / 1000000000.0 1135 soft_timer_fire_s = kern.GetNanotimeFromAbstime(soft_timer_fire) / 1000000000.0 1136 1137 hardtogo = "" 1138 softtogo = "" 1139 1140 if call.tc_pqlink.deadline != 0 : 1141 hardtogo = "{:18.06f}".format(timer_fire_s); 1142 1143 if call.tc_soft_deadline != 0 : 1144 softtogo = "{:18.06f}".format(soft_timer_fire_s); 1145 1146 leeway = call.tc_pqlink.deadline - call.tc_soft_deadline 1147 leeway_s = kern.GetNanotimeFromAbstime(leeway) / 1000000000.0 1148 1149 ttd_s = kern.GetNanotimeFromAbstime(call.tc_ttd) / 1000000000.0 1150 1151 if (is_pending) : 1152 pending_time = call.tc_pending_timestamp - recent_timestamp 1153 pending_time = kern.GetNanotimeFromAbstime(pending_time) / 1000000000.0 1154 1155 flags = int(call.tc_flags) 1156 # TODO: extract this out of the thread_call_flags_t enum 1157 thread_call_flags = {0x0:'', 0x1:'A', 0x2:'W', 0x4:'D', 0x8:'R', 0x10:'S', 0x20:'O', 1158 0x40:'P', 0x80:'L', 0x100:'C', 0x200:'V'} 1159 1160 flags_str = '' 1161 mask = 0x1 1162 while mask <= 0x200 : 1163 flags_str += thread_call_flags[int(flags & mask)] 1164 mask = mask << 1 1165 1166 if is_iotes : 1167 flags_str += 'I' 1168 1169 colon = ":" 1170 1171 if pqueue is not None : 1172 if addressof(call.tc_pqlink) == pqueue.pq_root : 1173 colon = "*" 1174 1175 if (is_pending) : 1176 print(("{:s}{:#018x}{:s} {:18d} {:18d} {:18s} {:18s} {:18.06f} {:18.06f} {:18.06f} {:9s} " + 1177 "{:#018x} ({:#018x}, {:#018x}) ({:s}) {:s}").format(prefix, 1178 unsigned(call), colon, call.tc_soft_deadline, call.tc_pqlink.deadline, 1179 softtogo, hardtogo, pending_time, ttd_s, leeway_s, flags_str, 1180 func, param0, param1, func_name, extra_string)) 1181 else : 1182 print(("{:s}{:#018x}{:s} {:18d} {:18d} {:18s} {:18s} {:18.06f} {:18.06f} {:9s} " + 1183 "{:#018x} ({:#018x}, {:#018x}) ({:s}) {:s}").format(prefix, 1184 unsigned(call), colon, call.tc_soft_deadline, call.tc_pqlink.deadline, 1185 softtogo, hardtogo, ttd_s, leeway_s, flags_str, 1186 func, param0, param1, func_name, extra_string)) 1187 1188ShowThreadCall.enable_debug = False 1189 1190@header("{:>18s} {:>18s} {:>18s} {:>18s} {:>18s} {:>18s} {:>18s} {:9s} {:>18s}".format( 1191 "entry", "soft_deadline", "deadline", 1192 "soft to go (s)", "hard to go (s)", "duration (s)", "leeway (s)", "flags", "(*func) (param0, param1)")) 1193def PrintThreadGroup(group): 1194 header = PrintThreadGroup.header 1195 pending_header = "{:>18s} {:>18s} {:>18s} {:>18s} {:>18s} {:>18s} {:>18s} {:9s} {:>18s}".format( 1196 "entry", "soft_deadline", "deadline", 1197 "soft to go (s)", "hard to go (s)", "pending", "duration (s)", "leeway (s)", "flags", "(*func) (param0, param1)") 1198 1199 recent_timestamp = GetRecentTimestamp() 1200 1201 idle_timestamp_distance = group.idle_timestamp - recent_timestamp 1202 idle_timestamp_distance_s = kern.GetNanotimeFromAbstime(idle_timestamp_distance) / 1000000000.0 1203 1204 is_parallel = "" 1205 1206 if (group.tcg_flags & GetEnumValue('thread_call_group_flags_t::TCG_PARALLEL')) : 1207 is_parallel = " (parallel)" 1208 1209 print("Group: {g.tcg_name:s} ({:#18x}){:s}".format(unsigned(group), is_parallel, g=group)) 1210 print("\t" +"Thread Priority: {g.tcg_thread_pri:d}\n".format(g=group)) 1211 print(("\t" +"Active: {g.active_count:<3d} Idle: {g.idle_count:<3d} " + 1212 "Blocked: {g.blocked_count:<3d} Pending: {g.pending_count:<3d} " + 1213 "Target: {g.target_thread_count:<3d}\n").format(g=group)) 1214 1215 if unsigned(group.idle_timestamp) != 0 : 1216 print("\t" +"Idle Timestamp: {g.idle_timestamp:d} ({:03.06f})\n".format(idle_timestamp_distance_s, 1217 g=group)) 1218 1219 print("\t" +"Pending Queue: ({:>#18x})\n".format(addressof(group.pending_queue))) 1220 if not LinkageChainEmpty(group.pending_queue) : 1221 print("\t\t" + pending_header) 1222 for call in ParanoidIterateLinkageChain(group.pending_queue, "thread_call_t", "tc_qlink"): 1223 ShowThreadCall("\t\t", call, recent_timestamp, None, is_pending=True) 1224 1225 print("\t" +"Delayed Queue (Absolute Time): ({:>#18x}) timer: ({:>#18x})\n".format( 1226 addressof(group.delayed_queues[0]), addressof(group.delayed_timers[0]))) 1227 if not LinkageChainEmpty(group.delayed_queues[0]) : 1228 print("\t\t" + header) 1229 for call in ParanoidIterateLinkageChain(group.delayed_queues[0], "thread_call_t", "tc_qlink"): 1230 ShowThreadCall("\t\t", call, recent_timestamp, group.delayed_pqueues[0]) 1231 1232 print("\t" +"Delayed Queue (Continuous Time): ({:>#18x}) timer: ({:>#18x})\n".format( 1233 addressof(group.delayed_queues[1]), addressof(group.delayed_timers[1]))) 1234 if not LinkageChainEmpty(group.delayed_queues[1]) : 1235 print("\t\t" + header) 1236 for call in ParanoidIterateLinkageChain(group.delayed_queues[1], "thread_call_t", "tc_qlink"): 1237 ShowThreadCall("\t\t", call, recent_timestamp, group.delayed_pqueues[1]) 1238 1239def PrintThreadCallThreads() : 1240 callout_flag = GetEnumValue('thread_tag_t::THREAD_TAG_CALLOUT') 1241 recent_timestamp = GetRecentTimestamp() 1242 1243 for thread in IterateQueue(kern.globals.kernel_task.threads, 'thread *', 'task_threads'): 1244 if (thread.thread_tag & callout_flag) : 1245 print(" {:#20x} {:#12x} {:s}".format(thread, thread.thread_id, GetThreadName(thread))) 1246 state = thread.thc_state 1247 if state and state.thc_call : 1248 print("\t" + PrintThreadGroup.header) 1249 ShowThreadCall("\t", state.thc_call, recent_timestamp, None) 1250 soft_deadline = state.thc_call_soft_deadline 1251 slop_time = state.thc_call_hard_deadline - soft_deadline 1252 slop_time = kern.GetNanotimeFromAbstime(slop_time) / 1000000000.0 1253 print("\t original soft deadline {:d}, hard deadline {:d} (leeway {:.06f}s)".format( 1254 soft_deadline, state.thc_call_hard_deadline, slop_time)) 1255 enqueue_time = state.thc_call_pending_timestamp - soft_deadline 1256 enqueue_time = kern.GetNanotimeFromAbstime(enqueue_time) / 1000000000.0 1257 print("\t time to enqueue after deadline: {:.06f}s (enqueued at: {:d})".format( 1258 enqueue_time, state.thc_call_pending_timestamp)) 1259 wait_time = state.thc_call_start - state.thc_call_pending_timestamp 1260 wait_time = kern.GetNanotimeFromAbstime(wait_time) / 1000000000.0 1261 print("\t time to start executing after enqueue: {:.06f}s (executing at: {:d})".format( 1262 wait_time, state.thc_call_start)) 1263 1264 if (state.thc_IOTES_invocation_timestamp) : 1265 iotes_acquire_time = state.thc_IOTES_invocation_timestamp - state.thc_call_start 1266 iotes_acquire_time = kern.GetNanotimeFromAbstime(iotes_acquire_time) / 1000000000.0 1267 print("\t IOTES acquire time: {:.06f}s (acquired at: {:d})".format( 1268 iotes_acquire_time, state.thc_IOTES_invocation_timestamp)) 1269 1270 1271@lldb_command('showcalloutgroup') 1272def ShowCalloutGroup(cmd_args=None): 1273 """ Prints out the pending and delayed thread calls for a specific group 1274 1275 Pass 'threads' to show the thread call threads themselves. 1276 1277 Callout flags: 1278 1279 A - Allocated memory owned by thread_call.c 1280 W - Wait - thread waiting for call to finish running 1281 D - Delayed - deadline based 1282 R - Running - currently executing on a thread 1283 S - Signal - call from timer interrupt instead of thread 1284 O - Once - pend the enqueue if re-armed while running 1285 P - Reschedule pending - enqueue is pending due to re-arm while running 1286 L - Rate-limited - (App Nap) 1287 C - Continuous time - Timeout is in mach_continuous_time 1288 I - Callout is an IOTimerEventSource 1289 """ 1290 if not cmd_args: 1291 print("No arguments passed") 1292 print(ShowCalloutGroup.__doc__) 1293 return False 1294 1295 if "threads" in cmd_args[0] : 1296 PrintThreadCallThreads() 1297 return 1298 1299 group = kern.GetValueFromAddress(cmd_args[0], 'struct thread_call_group *') 1300 if not group: 1301 print("unknown arguments:", str(cmd_args)) 1302 return False 1303 1304 PrintThreadGroup(group) 1305 1306@lldb_command('showallcallouts') 1307def ShowAllCallouts(cmd_args=None): 1308 """ Prints out the pending and delayed thread calls for the thread call groups 1309 1310 Callout flags: 1311 1312 A - Allocated memory owned by thread_call.c 1313 W - Wait - thread waiting for call to finish running 1314 D - Delayed - deadline based 1315 R - Running - currently executing on a thread 1316 S - Signal - call from timer interrupt instead of thread 1317 O - Once - pend the enqueue if re-armed while running 1318 P - Reschedule pending - enqueue is pending due to re-arm while running 1319 L - Rate-limited - (App Nap) 1320 C - Continuous time - Timeout is in mach_continuous_time 1321 I - Callout is an IOTimerEventSource 1322 V - Callout is validly initialized 1323 """ 1324 index_max = GetEnumValue('thread_call_index_t::THREAD_CALL_INDEX_MAX') 1325 1326 for i in range (1, index_max) : 1327 group = addressof(kern.globals.thread_call_groups[i]) 1328 PrintThreadGroup(group) 1329 1330 print("Thread Call Threads:") 1331 PrintThreadCallThreads() 1332 1333# EndMacro: showallcallouts 1334 1335