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