forked from apple/darwin-xnu
-
Notifications
You must be signed in to change notification settings - Fork 1
/
process.py
executable file
·2069 lines (1824 loc) · 80.7 KB
/
process.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
""" Please make sure you read the README file COMPLETELY BEFORE reading anything below.
It is very critical that you read coding guidelines in Section E in README file.
"""
from xnu import *
import sys, shlex
from utils import *
from core.lazytarget import *
import time
import xnudefines
import memory
def GetProcNameForTask(task):
""" returns a string name of the process. if proc is not valid "unknown" is returned
params:
task: value object represeting a task in the kernel.
returns:
str : A string name of the process linked to the task
"""
if not task or not unsigned(task.bsd_info):
return "unknown"
p = Cast(task.bsd_info, 'proc *')
return str(p.p_comm)
def GetProcPIDForTask(task):
""" returns a int pid of the process. if the proc is not valid, val[5] from audit_token is returned.
params:
task: value object representing a task in the kernel
returns:
int : pid of the process or -1 if not found
"""
if task and unsigned(task.bsd_info):
p = Cast(task.bsd_info, 'proc *')
return unsigned(p.p_pid)
if task :
return unsigned(task.audit_token.val[5])
return -1
def GetProcInfo(proc):
""" returns a string name, pid, parent and task for a proc_t. Decodes cred, flag and p_stat fields.
params:
proc : value object representing a proc in the kernel
returns:
str : A string describing various information for process.
"""
out_string = ""
out_string += ("Process {p: <#020x}\n\tname {p.p_comm: <20s}\n\tpid:{p.p_pid: <6d} " +
"task:{p.task: <#020x} p_stat:{p.p_stat: <6d} parent pid: {p.p_ppid: <6d}\n"
).format(p=proc)
#print the Creds
ucred = proc.p_ucred
if ucred:
out_string += "Cred: euid {:d} ruid {:d} svuid {:d}\n".format(ucred.cr_posix.cr_uid,
ucred.cr_posix.cr_ruid,
ucred.cr_posix.cr_svuid )
#print the flags
flags = int(proc.p_flag)
out_string += "Flags: {0: <#020x}\n".format(flags)
i = 1
num = 1
while num <= flags:
if flags & num:
out_string += "\t" + xnudefines.proc_flag_explain_strings[i] + "\n"
elif num == 0x4: #special case for 32bit flag
out_string += "\t" + xnudefines.proc_flag_explain_strings[0] + "\n"
i += 1
num = num << 1
out_string += "State: "
state_val = proc.p_stat
if state_val < 1 or state_val > len(xnudefines.proc_state_strings) :
out_string += "(Unknown)"
else:
out_string += xnudefines.proc_state_strings[int(state_val)]
return out_string
def GetProcNameForPid(pid):
""" Finds the name of the process corresponding to a given pid
params:
pid : int, pid you want to find the procname for
returns
str : Name of the process corresponding to the pid, "Unknown" if not found
"""
for p in kern.procs:
if int(p.p_pid) == int(pid):
return str(p.p_comm)
return "Unknown"
def GetProcForPid(search_pid):
""" Finds the value object representing a proc in the kernel based on its pid
params:
search_pid : int, pid whose proc structure you want to find
returns:
value : The value object representing the proc, if a proc corresponding
to the given pid is found. Returns None otherwise
"""
if search_pid == 0:
return kern.globals.initproc
else:
headp = kern.globals.allproc
for proc in IterateListEntry(headp, 'struct proc *', 'p_list'):
if proc.p_pid == search_pid:
return proc
return None
@lldb_command('allproc')
def AllProc(cmd_args=None):
""" Walk through the allproc structure and print procinfo for each process structure.
params:
cmd_args - [] : array of strings passed from lldb command prompt
"""
for proc in kern.procs :
print GetProcInfo(proc)
@lldb_command('zombproc')
def ZombProc(cmd_args=None):
""" Routine to print out all procs in the zombie list
params:
cmd_args - [] : array of strings passed from lldb command prompt
"""
if len(kern.zombprocs) != 0:
print "\nZombie Processes:"
for proc in kern.zombprocs:
print GetProcInfo(proc) + "\n\n"
@lldb_command('zombtasks')
def ZombTasks(cmd_args=None):
""" Routine to print out all tasks in the zombie list
params: None
"""
out_str = ""
if len(kern.zombprocs) != 0:
header = "\nZombie Tasks:\n"
header += GetTaskSummary.header + " " + GetProcSummary.header
for proc in kern.zombprocs:
if proc.p_stat != 5:
t = Cast(proc.task, 'task *')
out_str += GetTaskSummary(t) +" "+ GetProcSummary(proc) + "\n"
if out_str != "":
print header
print out_str
@lldb_command('zombstacks')
def ZombStacks(cmd_args=None):
""" Routine to print out all stacks of tasks that are exiting
"""
header_flag = 0
for proc in kern.zombprocs:
if proc.p_stat != 5:
if header_flag == 0:
print "\nZombie Stacks:"
header_flag = 1
t = Cast(proc.task, 'task *')
ShowTaskStacks(t)
#End of Zombstacks
def GetASTSummary(ast):
""" Summarizes an AST field
Flags:
P - AST_PREEMPT
Q - AST_QUANTUM
U - AST_URGENT
H - AST_HANDOFF
Y - AST_YIELD
A - AST_APC
L - AST_LEDGER
B - AST_BSD
K - AST_KPERF
M - AST_MACF
C - AST_CHUD
C - AST_CHUD_URGENT
G - AST_GUARD
T - AST_TELEMETRY_USER
T - AST_TELEMETRY_KERNEL
T - AST_TELEMETRY_WINDOWED
S - AST_SFI
D - AST_DTRACE
I - AST_TELEMETRY_IO
E - AST_KEVENT
"""
out_string = ""
state = int(ast)
thread_state_chars = {0x0:'', 0x1:'P', 0x2:'Q', 0x4:'U', 0x8:'H', 0x10:'Y', 0x20:'A',
0x40:'L', 0x80:'B', 0x100:'K', 0x200:'M', 0x400:'C', 0x800:'C',
0x1000:'G', 0x2000:'T', 0x4000:'T', 0x8000:'T', 0x10000:'S',
0x20000: 'D', 0x40000: 'I', 0x80000: 'E'}
state_str = ''
mask = 0x1
while mask <= 0x80000:
state_str += thread_state_chars[int(state & mask)]
mask = mask << 1
return state_str
@lldb_type_summary(['kcdata_descriptor *', 'kcdata_descriptor_t'])
@header("{0: <20s} {1: <20s} {2: <20s} {3: <10s} {4: <5s}".format("kcdata_descriptor", "begin_addr", "cur_pos", "size", "flags"))
def GetKCDataSummary(kcdata):
""" Summarizes kcdata_descriptor structure
params: kcdata: value - value object representing kcdata_descriptor
returns: str - summary of the kcdata object
"""
format_string = "{0: <#020x} {1: <#020x} {2: <#020x} {3: <10d} {4: <#05x}"
return format_string.format(kcdata, kcdata.kcd_addr_begin, kcdata.kcd_addr_end, kcdata.kcd_length, kcdata.kcd_flags)
@lldb_type_summary(['task', 'task_t'])
@header("{0: <20s} {1: <20s} {2: <20s} {3: >5s} {4: <5s}".format("task","vm_map", "ipc_space", "#acts", "flags"))
def GetTaskSummary(task, showcorpse=False):
""" Summarizes the important fields in task structure.
params: task: value - value object representing a task in kernel
returns: str - summary of the task
"""
out_string = ""
format_string = '{0: <#020x} {1: <#020x} {2: <#020x} {3: >5d} {4: <5s}'
thread_count = int(task.thread_count)
task_flags = ''
if hasattr(task, "suppression_generation") and (int(task.suppression_generation) & 0x1) == 0x1:
task_flags += 'P'
if hasattr(task, "effective_policy") and int(task.effective_policy.tep_sup_active) == 1:
task_flags += 'N'
if hasattr(task, "suspend_count") and int(task.suspend_count) > 0:
task_flags += 'S'
if hasattr(task, 'task_imp_base') and unsigned(task.task_imp_base):
tib = task.task_imp_base
if int(tib.iit_receiver) == 1:
task_flags += 'R'
if int(tib.iit_donor) == 1:
task_flags += 'D'
if int(tib.iit_assertcnt) > 0:
task_flags += 'B'
# check if corpse flag is set
if unsigned(task.t_flags) & 0x20:
task_flags += 'C'
if unsigned(task.t_flags) & 0x40:
task_flags += 'P'
out_string += format_string.format(task, task.map, task.itk_space, thread_count, task_flags)
if showcorpse is True and unsigned(task.corpse_info) != 0:
out_string += " " + GetKCDataSummary(task.corpse_info)
return out_string
def GetThreadName(thread):
""" Get the name of a thread, if possible. Returns the empty string
otherwise.
"""
if int(thread.uthread) != 0:
uthread = Cast(thread.uthread, 'uthread *')
if int(uthread.pth_name) != 0 :
th_name_strval = Cast(uthread.pth_name, 'char *')
if len(str(th_name_strval)) > 0 :
return str(th_name_strval)
return ''
@lldb_type_summary(['thread *', 'thread_t'])
@header("{0: <24s} {1: <10s} {2: <20s} {3: <6s} {4: <6s} {5: <15s} {6: <15s} {7: <8s} {8: <12s} {9: <32s} {10: <20s} {11: <20s} {12: <20s}".format('thread', 'thread_id', 'processor', 'base', 'pri', 'sched_mode', 'io_policy', 'state', 'ast', 'waitq', 'wait_event', 'wmesg', 'thread_name'))
def GetThreadSummary(thread):
""" Summarize the thread structure. It decodes the wait state and waitevents from the data in the struct.
params: thread: value - value objecte representing a thread in kernel
returns: str - summary of a thread
State flags:
W - WAIT
S - SUSP
R - RUN
U - Uninterruptible
H - Terminated
A - Terminated and on termination queue
I - Idle thread
C - Crashed thread
policy flags:
B - darwinbg
T - IO throttle
P - IO passive
D - Terminated
"""
out_string = ""
format_string = "{0: <24s} {1: <10s} {2: <20s} {3: <6s} {4: <6s} {5: <15s} {6: <15s} {7: <8s} {8: <12s} {9: <32s} {10: <20s} {11: <20s} {12: <20s}"
thread_ptr_str = str("{0: <#020x}".format(thread))
if int(thread.static_param) :
thread_ptr_str+="[WQ]"
thread_id = hex(thread.thread_id)
processor = hex(thread.last_processor)
base_priority = str(int(thread.base_pri))
sched_priority = str(int(thread.sched_pri))
sched_mode = ''
mode = str(thread.sched_mode)
if "TIMESHARE" in mode:
sched_mode+="timeshare"
elif "FIXED" in mode:
sched_mode+="fixed"
elif "REALTIME" in mode:
sched_mode+="realtime"
if (unsigned(thread.bound_processor) != 0):
sched_mode+=" bound"
# TH_SFLAG_THROTTLED
if (unsigned(thread.sched_flags) & 0x0004):
sched_mode+=" BG"
io_policy_str = ""
thread_name = GetThreadName(thread)
if int(thread.uthread) != 0:
uthread = Cast(thread.uthread, 'uthread *')
#check for io_policy flags
if int(uthread.uu_flag) & 0x400:
io_policy_str+='RAGE '
#now flags for task_policy
io_policy_str = ""
if int(thread.effective_policy.thep_darwinbg) != 0:
io_policy_str += "B"
if int(thread.effective_policy.thep_io_tier) != 0:
io_policy_str += "T"
if int(thread.effective_policy.thep_io_passive) != 0:
io_policy_str += "P"
if int(thread.effective_policy.thep_terminated) != 0:
io_policy_str += "D"
state = int(thread.state)
thread_state_chars = {0x0:'', 0x1:'W', 0x2:'S', 0x4:'R', 0x8:'U', 0x10:'H', 0x20:'A', 0x40:'P', 0x80:'I'}
state_str = ''
mask = 0x1
while mask <= 0x80 :
state_str += thread_state_chars[int(state & mask)]
mask = mask << 1
if int(thread.inspection):
state_str += 'C'
ast = int(thread.ast) | int(thread.reason)
ast_str = GetASTSummary(ast)
#wait queue information
wait_queue_str = ''
wait_event_str = ''
wait_message = ''
if ( state & 0x1 ) != 0:
#we need to look at the waitqueue as well
wait_queue_str = str("{0: <#020x}".format(int(hex(thread.waitq), 16)))
wait_event_str = str("{0: <#020x}".format(int(hex(thread.wait_event), 16)))
wait_event_str_sym = kern.Symbolicate(int(hex(thread.wait_event), 16))
if len(wait_event_str_sym) > 0:
wait_event_str = wait_event_str.strip() + " <" + wait_event_str_sym + ">"
if int(thread.uthread) != 0 :
uthread = Cast(thread.uthread, 'uthread *')
if int(uthread.uu_wmesg) != 0:
wait_message = str(Cast(uthread.uu_wmesg, 'char *'))
out_string += format_string.format(thread_ptr_str, thread_id, processor, base_priority, sched_priority, sched_mode, io_policy_str, state_str, ast_str, wait_queue_str, wait_event_str, wait_message, thread_name)
return out_string
def GetTaskRoleString(role):
role_strs = {
0 : "TASK_UNSPECIFIED",
1 : "TASK_FOREGROUND_APPLICATION",
2 : "TASK_BACKGROUND_APPLICATION",
3 : "TASK_CONTROL_APPLICATION",
4 : "TASK_GRAPHICS_SERVER",
5 : "TASK_THROTTLE_APPLICATION",
6 : "TASK_NONUI_APPLICATION",
7 : "TASK_DEFAULT_APPLICATION",
}
return role_strs[int(role)]
def GetCoalitionFlagString(coal):
flags = []
if (coal.privileged):
flags.append('privileged')
if (coal.termrequested):
flags.append('termrequested')
if (coal.terminated):
flags.append('terminated')
if (coal.reaped):
flags.append('reaped')
if (coal.notified):
flags.append('notified')
if (coal.efficient):
flags.append('efficient')
return "|".join(flags)
def GetCoalitionTasks(queue, coal_type, thread_details=False):
sfi_strs = {
0x0 : "SFI_CLASS_UNSPECIFIED",
0x1 : "SFI_CLASS_DARWIN_BG",
0x2 : "SFI_CLASS_APP_NAP",
0x3 : "SFI_CLASS_MANAGED_FOCAL",
0x4 : "SFI_CLASS_MANAGED_NONFOCAL",
0x5 : "SFI_CLASS_DEFAULT_FOCAL",
0x6 : "SFI_CLASS_DEFAULT_NONFOCAL",
0x7 : "SFI_CLASS_KERNEL",
0x8 : "SFI_CLASS_OPTED_OUT",
0x9 : "SFI_CLASS_UTILITY",
0xA : "SFI_CLASS_LEGACY_FOCAL",
0xB : "SFI_CLASS_LEGACY_NONFOCAL",
0xC : "SFI_CLASS_USER_INITIATED_FOCAL",
0xD : "SFI_CLASS_USER_INITIATED_NONFOCAL",
0xE : "SFI_CLASS_USER_INTERACTIVE_FOCAL",
0xF : "SFI_CLASS_USER_INTERACTIVE_NONFOCAL",
0x10 : "SFI_CLASS_MAINTENANCE",
}
tasks = []
field_name = 'task_coalition'
for task in IterateLinkageChain(queue, 'task *', field_name, coal_type * sizeof('queue_chain_t')):
task_str = "({0: <d},{1: #x}, {2: <s}, {3: <s})".format(GetProcPIDForTask(task),task,GetProcNameForTask(task),GetTaskRoleString(task.effective_policy.tep_role))
if thread_details:
for thread in IterateQueue(task.threads, "thread_t", "task_threads"):
task_str += "\n\t\t\t|-> thread:" + hex(thread) + ", " + sfi_strs[int(thread.sfi_class)]
tasks.append(task_str)
return tasks
def GetCoalitionTypeString(type):
""" Convert a coalition type field into a string
Currently supported types (from <mach/coalition.h>):
COALITION_TYPE_RESOURCE
COALITION_TYPE_JETSAM
"""
if type == 0: # COALITION_TYPE_RESOURCE
return 'RESOURCE'
if type == 1:
return 'JETSAM'
return '<unknown>'
def GetResourceCoalitionSummary(coal, verbose=False):
""" Summarize a resource coalition
"""
out_string = "Resource Coalition:\n\t Ledger:\n"
thread_details = False
if config['verbosity'] > vSCRIPT:
thread_details = True
ledgerp = coal.r.ledger
if verbose and unsigned(ledgerp) != 0:
i = 0
while i != ledgerp.l_template.lt_cnt:
out_string += "\t\t"
out_string += GetLedgerEntrySummary(kern.globals.task_ledger_template, ledgerp.l_entries[i], i)
i = i + 1
out_string += "\t bytesread {0: <d}\n\t byteswritten {1: <d}\n\t gpu_time {2: <d}".format(coal.r.bytesread, coal.r.byteswritten, coal.r.gpu_time)
out_string += "\n\t total_tasks {0: <d}\n\t dead_tasks {1: <d}\n\t active_tasks {2: <d}".format(coal.r.task_count, coal.r.dead_task_count, coal.r.task_count - coal.r.dead_task_count)
out_string += "\n\t last_became_nonempty_time {0: <d}\n\t time_nonempty {1: <d}".format(coal.r.last_became_nonempty_time, coal.r.time_nonempty)
out_string += "\n\t cpu_ptime {0: <d}".format(coal.r.cpu_ptime)
out_string += "\n\t Tasks:\n\t\t"
tasks = GetCoalitionTasks(addressof(coal.r.tasks), 0, thread_details)
out_string += "\n\t\t".join(tasks)
return out_string
def GetJetsamCoalitionSummary(coal, verbose=False):
out_string = "Jetsam Coalition:"
thread_details = False
if config['verbosity'] > vSCRIPT:
thread_details = True
if unsigned(coal.j.leader) == 0:
out_string += "\n\t NO Leader!"
else:
out_string += "\n\t Leader:\n\t\t"
out_string += "({0: <d},{1: #x}, {2: <s}, {3: <s})".format(GetProcPIDForTask(coal.j.leader),coal.j.leader,GetProcNameForTask(coal.j.leader),GetTaskRoleString(coal.j.leader.effective_policy.tep_role))
out_string += "\n\t Extensions:\n\t\t"
tasks = GetCoalitionTasks(addressof(coal.j.extensions), 1, thread_details)
out_string += "\n\t\t".join(tasks)
out_string += "\n\t XPC Services:\n\t\t"
tasks = GetCoalitionTasks(addressof(coal.j.services), 1, thread_details)
out_string += "\n\t\t".join(tasks)
out_string += "\n\t Other Tasks:\n\t\t"
tasks = GetCoalitionTasks(addressof(coal.j.other), 1, thread_details)
out_string += "\n\t\t".join(tasks)
out_string += "\n\t Thread Group: {0: <#020x}\n".format(coal.j.thread_group)
return out_string
@lldb_type_summary(['coalition_t', 'coalition *'])
@header("{0: <20s} {1: <15s} {2: <10s} {3: <10s} {4: <10s} {5: <12s} {6: <12s} {7: <20s}".format("coalition", "type", "id", "ref count", "act count", "focal cnt", "nonfocal cnt","flags"))
def GetCoalitionSummary(coal):
if unsigned(coal) == 0:
return '{0: <#020x} {1: <15s} {2: <10d} {3: <10d} {4: <10d} {5: <12d} {6: <12d} {7: <s}'.format(0, "", -1, -1, -1, -1, -1, "")
out_string = ""
format_string = '{0: <#020x} {1: <15s} {2: <10d} {3: <10d} {4: <10d} {5: <12d} {6: <12d} {7: <s}'
type_string = GetCoalitionTypeString(coal.type)
flag_string = GetCoalitionFlagString(coal)
out_string += format_string.format(coal, type_string, coal.id, coal.ref_count, coal.active_count, coal.focal_task_count, coal.nonfocal_task_count, flag_string)
return out_string
def GetCoalitionInfo(coal, verbose=False):
""" returns a string describing a coalition, including details about the particular coalition type.
params:
coal : value object representing a coalition in the kernel
returns:
str : A string describing the coalition.
"""
if unsigned(coal) == 0:
return "<null coalition>"
typestr = GetCoalitionTypeString(coal.type)
flagstr = GetCoalitionFlagString(coal)
out_string = ""
out_string += "Coalition {c: <#020x}\n\tID {c.id: <d}\n\tType {c.type: <d} ({t: <s})\n\tRefCount {c.ref_count: <d}\n\tActiveCount {c.active_count: <d}\n\tFocal Tasks: {c.focal_task_count: <d}\n\tNon-Focal Tasks: {c.nonfocal_task_count: <d}\n\tFlags {f: <s}\n\t".format(c=coal,t=typestr,f=flagstr)
if coal.type == 0: # COALITION_TYPE_RESOURCE
out_string += GetResourceCoalitionSummary(coal, verbose)
elif coal.type == 1: # COALITION_TYPE_JETSAM
out_string += GetJetsamCoalitionSummary(coal, verbose)
else:
out_string += "Unknown Type"
return out_string
# Macro: showcoalitioninfo
@lldb_command('showcoalitioninfo')
def ShowCoalitionInfo(cmd_args=None, cmd_options={}):
""" Display more detailed information about a coalition
Usage: showcoalitioninfo <address of coalition>
"""
verbose = False
if config['verbosity'] > vHUMAN:
verbose = True
if not cmd_args:
raise ArgumentError("No arguments passed")
coal = kern.GetValueFromAddress(cmd_args[0], 'coalition *')
if not coal:
print "unknown arguments:", str(cmd_args)
return False
print GetCoalitionInfo(coal, verbose)
# EndMacro: showcoalitioninfo
# Macro: showallcoalitions
@lldb_command('showallcoalitions')
def ShowAllCoalitions(cmd_args=None):
""" Print a summary listing of all the coalitions
"""
global kern
print GetCoalitionSummary.header
for c in kern.coalitions:
print GetCoalitionSummary(c)
# EndMacro: showallcoalitions
# Macro: showallthreadgroups
@lldb_type_summary(['thread_group_t', 'thread_group *'])
@header("{0: <20s} {1: <5s} {2: <16s} {3: <5s} {4: <8s} {5: <20s}".format("thread_group", "id", "name", "refc", "flags", "recommendation"))
def GetThreadGroupSummary(tg):
if unsigned(tg) == 0:
return '{0: <#020x} {1: <5d} {2: <16s} {3: <5d} {4: <8s} {5: <20d}'.format(0, -1, "", -1, "", -1)
out_string = ""
format_string = '{0: <#020x} {1: <5d} {2: <16s} {3: <5d} {4: <8s} {5: <20d}'
tg_flags = ''
if (tg.tg_flags & 0x1):
tg_flags += 'E'
if (tg.tg_flags & 0x2):
tg_flags += 'U'
out_string += format_string.format(tg, tg.tg_id, tg.tg_name, tg.tg_refcount, tg_flags, tg.tg_recommendation)
return out_string
@lldb_command('showallthreadgroups')
def ShowAllThreadGroups(cmd_args=None):
""" Print a summary listing of all thread groups
"""
global kern
print GetThreadGroupSummary.header
for tg in kern.thread_groups:
print GetThreadGroupSummary(tg)
# EndMacro: showallthreadgroups
# Macro: showtaskcoalitions
@lldb_command('showtaskcoalitions', 'F:')
def ShowTaskCoalitions(cmd_args=None, cmd_options={}):
"""
"""
task_list = []
if "-F" in cmd_options:
task_list = FindTasksByName(cmd_options["-F"])
elif cmd_args:
t = kern.GetValueFromAddress(cmd_args[0], 'task *')
task_list.append(t)
else:
raise ArgumentError("No arguments passed")
if len(task_list) > 0:
print GetCoalitionSummary.header
for task in task_list:
print GetCoalitionSummary(task.coalition[0])
print GetCoalitionSummary(task.coalition[1])
# EndMacro: showtaskcoalitions
@lldb_type_summary(['proc', 'proc *'])
@header("{0: >6s} {1: ^20s} {2: >14s} {3: ^10s} {4: <20s}".format("pid", "process", "io_policy", "wq_state", "command"))
def GetProcSummary(proc):
""" Summarize the process data.
params:
proc : value - value representaitng a proc * in kernel
returns:
str - string summary of the process.
"""
out_string = ""
format_string= "{0: >6d} {1: >#020x} {2: >14s} {3: >2d} {4: >2d} {5: >2d} {6: <20s}"
pval = proc.GetSBValue()
#code.interact(local=locals())
if str(pval.GetType()) != str(gettype('proc *')) :
return "Unknown type " + str(pval.GetType()) + " " + str(hex(proc))
if not proc:
out_string += "Process " + hex(proc) + " is not valid."
return out_string
pid = int(proc.p_pid)
proc_addr = int(hex(proc), 16)
proc_rage_str = ""
if int(proc.p_lflag) & 0x400000 :
proc_rage_str = "RAGE"
task = Cast(proc.task, 'task *')
io_policy_str = ""
if int(task.effective_policy.tep_darwinbg) != 0:
io_policy_str += "B"
if int(task.effective_policy.tep_lowpri_cpu) != 0:
io_policy_str += "L"
if int(task.effective_policy.tep_io_tier) != 0:
io_policy_str += "T"
if int(task.effective_policy.tep_io_passive) != 0:
io_policy_str += "P"
if int(task.effective_policy.tep_terminated) != 0:
io_policy_str += "D"
if int(task.effective_policy.tep_latency_qos) != 0:
io_policy_str += "Q"
if int(task.effective_policy.tep_sup_active) != 0:
io_policy_str += "A"
try:
work_queue = Cast(proc.p_wqptr, 'workqueue *')
if proc.p_wqptr != 0 :
wq_num_threads = int(work_queue.wq_nthreads)
wq_idle_threads = int(work_queue.wq_thidlecount)
wq_req_threads = int(work_queue.wq_reqcount)
else:
wq_num_threads = 0
wq_idle_threads = 0
wq_req_threads = 0
except:
wq_num_threads = -1
wq_idle_threads = -1
wq_req_threads = -1
process_name = str(proc.p_comm)
if process_name == 'xpcproxy':
for thread in IterateQueue(task.threads, 'thread *', 'task_threads'):
thread_name = GetThreadName(thread)
if thread_name:
process_name += ' (' + thread_name + ')'
break
out_string += format_string.format(pid, proc_addr, " ".join([proc_rage_str, io_policy_str]), wq_num_threads, wq_idle_threads, wq_req_threads, process_name)
return out_string
@lldb_type_summary(['tty_dev_t', 'tty_dev_t *'])
@header("{0: <20s} {1: <10s} {2: <10s} {3: <15s} {4: <15s} {5: <15s} {6: <15s}".format("tty_dev","master", "slave", "open", "free", "name", "revoke"))
def GetTTYDevSummary(tty_dev):
""" Summarizes the important fields in tty_dev_t structure.
params: tty_dev: value - value object representing a tty_dev_t in kernel
returns: str - summary of the tty_dev
"""
out_string = ""
format_string = "{0: <#020x} {1: <#010x} {2: <#010x} {3: <15s} {4: <15s} {5: <15s} {6: <15s}"
open_fn = kern.Symbolicate(int(hex(tty_dev.open), 16))
free_fn = kern.Symbolicate(int(hex(tty_dev.free), 16))
name_fn = kern.Symbolicate(int(hex(tty_dev.name), 16))
revoke_fn = kern.Symbolicate(int(hex(tty_dev.revoke), 16))
out_string += format_string.format(tty_dev, tty_dev.master, tty_dev.slave, open_fn, free_fn, name_fn, revoke_fn)
return out_string
# Macro: showtask
@lldb_command('showtask', 'F:')
def ShowTask(cmd_args=None, cmd_options={}):
""" Routine to print a summary listing of given task
Usage: showtask <address of task>
or : showtask -F <name of task>
"""
task_list = []
if "-F" in cmd_options:
task_list = FindTasksByName(cmd_options['-F'])
else:
if not cmd_args:
raise ArgumentError("Invalid arguments passed.")
tval = kern.GetValueFromAddress(cmd_args[0], 'task *')
if not tval:
raise ("Unknown arguments: %r" % cmd_args)
task_list.append(tval)
for tval in task_list:
print GetTaskSummary.header + " " + GetProcSummary.header
pval = Cast(tval.bsd_info, 'proc *')
print GetTaskSummary(tval) +" "+ GetProcSummary(pval)
# EndMacro: showtask
# Macro: showpid
@lldb_command('showpid')
def ShowPid(cmd_args=None):
""" Routine to print a summary listing of task corresponding to given pid
Usage: showpid <pid value>
"""
if not cmd_args:
raise ArgumentError("No arguments passed")
pidval = ArgumentStringToInt(cmd_args[0])
for t in kern.tasks:
pval = Cast(t.bsd_info, 'proc *')
if pval and pval.p_pid == pidval:
print GetTaskSummary.header + " " + GetProcSummary.header
print GetTaskSummary(t) + " " + GetProcSummary(pval)
break
# EndMacro: showpid
# Macro: showproc
@lldb_command('showproc')
def ShowProc(cmd_args=None):
""" Routine to print a summary listing of task corresponding to given proc
Usage: showproc <address of proc>
"""
if not cmd_args:
raise ArgumentError("No arguments passed")
pval = kern.GetValueFromAddress(cmd_args[0], 'proc *')
if not pval:
print "unknown arguments:", str(cmd_args)
return False
print GetTaskSummary.header + " " + GetProcSummary.header
tval = Cast(pval.task, 'task *')
print GetTaskSummary(tval) +" "+ GetProcSummary(pval)
# EndMacro: showproc
# Macro: showprocinfo
@lldb_command('showprocinfo')
def ShowProcInfo(cmd_args=None):
""" Routine to display name, pid, parent & task for the given proc address
It also shows the Cred, Flags and state of the process
Usage: showprocinfo <address of proc>
"""
if not cmd_args:
raise ArgumentError("No arguments passed")
pval = kern.GetValueFromAddress(cmd_args[0], 'proc *')
if not pval:
print "unknown arguments:", str(cmd_args)
return False
print GetProcInfo(pval)
# EndMacro: showprocinfo
#Macro: showprocfiles
@lldb_command('showprocfiles')
def ShowProcFiles(cmd_args=None):
""" Given a proc_t pointer, display the list of open file descriptors for the referenced process.
Usage: showprocfiles <proc_t>
"""
if not cmd_args:
print ShowProcFiles.__doc__
return
proc = kern.GetValueFromAddress(cmd_args[0], 'proc_t')
proc_filedesc = proc.p_fd
proc_lastfile = unsigned(proc_filedesc.fd_lastfile)
proc_ofiles = proc_filedesc.fd_ofiles
if unsigned(proc_ofiles) == 0:
print 'No open files for proc {0: <s}'.format(cmd_args[0])
return
print "{0: <5s} {1: <18s} {2: <10s} {3: <8s} {4: <18s} {5: <64s}".format('FD', 'FILEGLOB', 'FG_FLAGS', 'FG_TYPE', 'FG_DATA','INFO')
print "{0:-<5s} {0:-<18s} {0:-<10s} {0:-<8s} {0:-<18s} {0:-<64s}".format("")
count = 0
while count <= proc_lastfile:
if unsigned(proc_ofiles[count]) != 0:
out_str = ''
proc_fd_flags = proc_ofiles[count].f_flags
proc_fd_fglob = proc_ofiles[count].f_fglob
out_str += "{0: <5d} ".format(count)
out_str += "{0: <#18x} ".format(unsigned(proc_fd_fglob))
out_str += "0x{0:0>8x} ".format(unsigned(proc_fd_flags))
proc_fd_ftype = unsigned(proc_fd_fglob.fg_ops.fo_type)
if proc_fd_ftype in xnudefines.filetype_strings:
out_str += "{0: <8s} ".format(xnudefines.filetype_strings[proc_fd_ftype])
else:
out_str += "?: {0: <5d} ".format(proc_fd_ftype)
out_str += "{0: <#18x} ".format(unsigned(proc_fd_fglob.fg_data))
if proc_fd_ftype == 1:
fd_name = Cast(proc_fd_fglob.fg_data, 'struct vnode *').v_name
out_str += "{0: <64s}".format(fd_name)
out_str += "\n"
print out_str
count += 1
#EndMacro: showprocfiles
#Macro: showtty
@lldb_command('showtty')
def ShowTTY(cmd_args=None):
""" Display information about a struct tty
Usage: showtty <tty struct>
"""
if not cmd_args:
print ShowTTY.__doc__
return
tty = kern.GetValueFromAddress(cmd_args[0], 'struct tty *')
print "TTY structure at: {0: <s}".format(cmd_args[0])
print "Last input to raw queue: {0: <#18x} \"{1: <s}\"".format(unsigned(tty.t_rawq.c_cs), tty.t_rawq.c_cs)
print "Last input to canonical queue: {0: <#18x} \"{1: <s}\"".format(unsigned(tty.t_canq.c_cs), tty.t_canq.c_cs)
print "Last output data: {0: <#18x} \"{1: <s}\"".format(unsigned(tty.t_outq.c_cs), tty.t_outq.c_cs)
tty_state_info = [
['', 'TS_SO_OLOWAT (Wake up when output <= low water)'],
['- (synchronous I/O mode)', 'TS_ASYNC (async I/O mode)'],
['', 'TS_BUSY (Draining output)'],
['- (Carrier is NOT present)', 'TS_CARR_ON (Carrier is present)'],
['', 'TS_FLUSH (Outq has been flushed during DMA)'],
['- (Open has NOT completed)', 'TS_ISOPEN (Open has completed)'],
['', 'TS_TBLOCK (Further input blocked)'],
['', 'TS_TIMEOUT (Wait for output char processing)'],
['', 'TS_TTSTOP (Output paused)'],
['', 'TS_WOPEN (Open in progress)'],
['', 'TS_XCLUDE (Tty requires exclusivity)'],
['', 'TS_BKSL (State for lowercase \\ work)'],
['', 'TS_CNTTB (Counting tab width, ignore FLUSHO)'],
['', 'TS_ERASE (Within a \\.../ for PRTRUB)'],
['', 'TS_LNCH (Next character is literal)'],
['', 'TS_TYPEN (Retyping suspended input (PENDIN))'],
['', 'TS_CAN_BYPASS_L_RINT (Device in "raw" mode)'],
['- (Connection NOT open)', 'TS_CONNECTED (Connection open)'],
['', 'TS_SNOOP (Device is being snooped on)'],
['', 'TS_SO_OCOMPLETE (Wake up when output completes)'],
['', 'TS_ZOMBIE (Connection lost)'],
['', 'TS_CAR_OFLOW (For MDMBUF - handle in driver)'],
['', 'TS_CTS_OFLOW (For CCTS_OFLOW - handle in driver)'],
['', 'TS_DSR_OFLOW (For CDSR_OFLOW - handle in driver)']
]
index = 0
mask = 0x1
tty_state = unsigned(tty.t_state)
print "State:"
while index < 24:
if tty_state & mask != 0:
if len(tty_state_info[index][1]) > 0:
print '\t' + tty_state_info[index][1]
else:
if len(tty_state_info[index][0]) > 0:
print '\t' + tty_state_info[index][0]
index += 1
mask = mask << 1
print "Flags: 0x{0:0>8x}".format(unsigned(tty.t_flags))
print "Foreground Process Group: 0x{0:0>16x}".format(unsigned(tty.t_pgrp))
print "Enclosing session: 0x{0:0>16x}".format(unsigned(tty.t_session))
print "Termios:"
print "\tInput Flags: 0x{0:0>8x}".format(unsigned(tty.t_termios.c_iflag))
print "\tOutput Flags: 0x{0:0>8x}".format(unsigned(tty.t_termios.c_oflag))
print "\tControl Flags: 0x{0:0>8x}".format(unsigned(tty.t_termios.c_cflag))
print "\tLocal Flags: 0x{0:0>8x}".format(unsigned(tty.t_termios.c_lflag))
print "\tInput Speed: {0: <8d}".format(tty.t_termios.c_ispeed)
print "\tOutput Speed: {0: <8d}".format(tty.t_termios.c_ospeed)
print "High Watermark: {0: <d} bytes".format(tty.t_hiwat)
print "Low Watermark : {0: <d} bytes".format(tty.t_lowat)
#EndMacro: showtty
#Macro showallttydevs
@lldb_command('showallttydevs')
def ShowAllTTYDevs(cmd_args=[], cmd_options={}):
""" Show a list of ttydevs registered in the system.
Usage:
(lldb)showallttydevs
"""
tty_dev_head = kern.globals.tty_dev_head
tty_dev = tty_dev_head
print GetTTYDevSummary.header
while unsigned(tty_dev) != 0:
print GetTTYDevSummary(tty_dev)
tty_dev = tty_dev.next
return ""
#EndMacro: showallttydevs
#Macro: dumpthread_terminate_queue
@lldb_command('dumpthread_terminate_queue')
def DumpThreadTerminateQueue(cmd_args=None):
""" Displays the contents of the specified call_entry queue.
Usage: dumpthread_terminate_queue
"""
count = 0
print GetThreadSummary.header
for th in IterateQueue(addressof(kern.globals.thread_terminate_queue), 'struct thread *', 'q_link'):
print GetThreadSummary(th)
count += 1
print "{0: <d} entries!".format(count)
#EndMacro: dumpthread_terminate_queue
#Macro: dumpcrashed_thread_queue
@lldb_command('dumpcrashed_thread_queue')
def DumpCrashedThreadsQueue(cmd_args=None):
""" Displays the contents of the specified call_entry queue.
Usage: dumpcrashed_thread_queue
"""
count = 0
print GetThreadSummary.header
for th in IterateQueue(addressof(kern.globals.crashed_threads_queue), 'struct thread *', 'q_link'):
print GetThreadSummary(th)
count += 1
print "{0: <d} entries!".format(count)
#EndMacro: dumpcrashed_thread_queue
#Macro: dumpcallqueue
@lldb_command('dumpcallqueue')
def DumpCallQueue(cmd_args=None):
""" Displays the contents of the specified call_entry queue.
Usage: dumpcallqueue <queue_head_t *>
"""
if not cmd_args:
raise ArgumentError("Invalid arguments")
print "{0: <18s} {1: <18s} {2: <18s} {3: <64s} {4: <18s}".format('CALL_ENTRY', 'PARAM0', 'PARAM1', 'DEADLINE', 'FUNC')
callhead = kern.GetValueFromAddress(cmd_args[0], 'queue_head_t *')
count = 0
for callentry in IterateQueue(callhead, 'struct call_entry *', 'q_link'):
print "{0: <#18x} {1: <#18x} {2: <#18x} {3: <64d} {4: <#18x}".format(
unsigned(callentry), unsigned(callentry.param0), unsigned(callentry.param1),
unsigned(callentry.deadline), unsigned(callentry.func))
count += 1
print "{0: <d} entries!".format(count)
#EndMacro: dumpcallqueue
@lldb_command('showalltasklogicalwrites')
def ShowAllTaskIOStats(cmd_args=None):
""" Commad to print I/O stats for all tasks
"""
print "{0: <20s} {1: <20s} {2: <20s} {3: <20s} {4: <20s} {5: <20s}".format("task", "Immediate Writes", "Deferred Writes", "Invalidated Writes", "Metadata Writes", "name")
for t in kern.tasks:
pval = Cast(t.bsd_info, 'proc *')
print "{0: <#18x} {1: >20d} {2: >20d} {3: >20d} {4: >20d} {5: <20s}".format(t,
t.task_immediate_writes,
t.task_deferred_writes,
t.task_invalidated_writes,
t.task_metadata_writes,
str(pval.p_comm))
@lldb_command('showalltasks','C')
def ShowAllTasks(cmd_args=None, cmd_options={}):
""" Routine to print a summary listing of all the tasks
wq_state -> reports "number of workq threads", "number of scheduled workq threads", "number of pending work items"
if "number of pending work items" seems stuck at non-zero, it may indicate that the workqueue mechanism is hung
io_policy -> RAGE - rapid aging of vnodes requested
NORM - normal I/O explicitly requested (this is the default)
PASS - passive I/O requested (i.e. I/Os do not affect throttling decisions)
THROT - throttled I/O requested (i.e. thread/task may be throttled after each I/O completes)
Usage: (lldb) showalltasks -C : describe the corpse structure
"""
global kern
extra_hdr = ''
showcorpse = False
if '-C' in cmd_options:
showcorpse = True
extra_hdr += " " + GetKCDataSummary.header
print GetTaskSummary.header + extra_hdr + " " + GetProcSummary.header
for t in kern.tasks:
pval = Cast(t.bsd_info, 'proc *')
out_str = GetTaskSummary(t, showcorpse) + " " + GetProcSummary(pval)
print out_str
ZombTasks()
@lldb_command('taskforpmap')
def TaskForPmap(cmd_args=None):
""" Find the task whose pmap corresponds to <pmap>.
Syntax: (lldb) taskforpmap <pmap>
Multiple -v's can be specified for increased verbosity