-
Notifications
You must be signed in to change notification settings - Fork 3
/
listing1.html
executable file
·1483 lines (1246 loc) · 53.7 KB
/
listing1.html
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
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
<html>
<head>
<!-- BEGIN META TAG INFO -->
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="home" href="http://developer.apple.com/">
<link rel="find" href="http://developer.apple.com/search/">
<link rel="stylesheet" type="text/css" href="../../documentation/css/adcstyle.css" title="fonts">
<script language="JavaScript" src="../../documentation/js/adc.js" type="text/javascript"></script>
<!-- END META TAG INFO -->
<!-- BEGIN TITLE -->
<title>BootstrapDump - /BootstrapDump.c</title>
<!-- END TITLE -->
<script language="JavaScript">
function JumpToNewPage() {
window.location=document.scpopupmenu.gotop.value;
return true;
}
</script>
</head>
<!-- BEGIN BODY OPEN -->
<body>
<!--END BODY OPEN -->
<!-- START CENTER OPEN -->
<center>
<!-- END CENTER OPEN -->
<!-- BEGIN LOGO AND SEARCH -->
<!--#include virtual="/includes/adcnavbar"-->
<!-- END LOGO AND SEARCH -->
<!-- START BREADCRUMB -->
<div id="breadcrumb">
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr>
<td scope="row"><img width="340" height="10" src="images/1dot.gif" alt=""></td>
<td><img width="340" height="10" src="images/1dot.gif" alt=""></td>
</tr>
<tr valign="middle">
<td align="left" colspan="2">
<a href="http://developer.apple.com/">ADC Home</a> > <a href="../../referencelibrary/index.html#//apple_ref/doc/uid/TP30000943" target="_top">Reference Library</a> > <a href="../index.html#//apple_ref/doc/uid/TP30000925" target="_top">Sample Code</a> > <a href="../Darwin/index.html#//apple_ref/doc/uid/TP30000925-TP30000422" target="_top">Darwin</a> > <a href="../Darwin/idxProcessManagement-date.html#//apple_ref/doc/uid/TP30000925-TP30000422-TP30000456">Process Management</a> > <A HREF="javascript:location.replace('index.html');">BootstrapDump</A> >
</td>
</tr>
<tr>
<td colspan="2" scope="row"><img width="680" height="35" src="images/1dot.gif" alt=""></td>
</tr>
</table>
</div>
<!-- END BREADCRUMB -->
<!-- START MAIN CONTENT -->
<!-- START TITLE GRAPHIC AND INTRO-->
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr align="left" valign="top">
<td><h1><div id="pagehead">BootstrapDump</div></h1></td>
</tr>
</table>
<!-- END TITLE GRAPHIC AND INTRO -->
<!-- START WIDE COLUMN -->
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr align="left" valign="top">
<td id="scdetails">
<h2>/BootstrapDump.c</h2>
<form name="scpopupmenu" onSubmit="return false;" method=post>
<p><strong>View Source Code:</strong>
<select name="gotop" onChange="JumpToNewPage();" style="width:340px"><option selected value="ingnore">Select File</option>
<option value="listing1.html">/BootstrapDump.c</option>
<option value="listing2.html">/Read Me About BootstrapDump.txt</option></select>
</p>
</form>
<p><strong><a href="BootstrapDump.zip">Download Sample</a></strong> (“BootstrapDump.zip”, 30.1K)<BR>
<strong><a href="BootstrapDump.dmg">Download Sample</a></strong> (“BootstrapDump.dmg”, 42.9K)</p>
<!--
<p><strong><a href="#">Download Sample</a></strong> (“filename.sit”, 500K)</p>
-->
</td>
</tr>
<tr>
<td scope="row"><img width="680" height="10" src="images/1dot.gif" alt=""><br>
<img height="1" width="680" src="images/1dot_919699.gif" alt=""><br>
<img width="680" height="20" src="images/1dot.gif" alt=""></td>
</tr>
<tr>
<td scope="row">
<!--googleon: index -->
<pre class="sourcecodebox">/*
File: BootstrapDump.c
Contains: A program to dump the Mach bootstrap port namespace.
Written by: DTS
Copyright: Copyright (c) 2007 Apple Inc. All Rights Reserved.
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc.
("Apple") in consideration of your agreement to the following
terms, and your use, installation, modification or
redistribution of this Apple software constitutes acceptance of
these terms. If you do not agree with these terms, please do
not use, install, modify or redistribute this Apple software.
In consideration of your agreement to abide by the following
terms, and subject to these terms, Apple grants you a personal,
non-exclusive license, under Apple's copyrights in this
original Apple software (the "Apple Software"), to use,
reproduce, modify and redistribute the Apple Software, with or
without modifications, in source and/or binary forms; provided
that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the
following text and disclaimers in all such redistributions of
the Apple Software. Neither the name, trademarks, service marks
or logos of Apple Inc. may be used to endorse or promote
products derived from the Apple Software without specific prior
written permission from Apple. Except as expressly stated in
this notice, no other rights or licenses, express or implied,
are granted by Apple herein, including but not limited to any
patent rights that may be infringed by your derivative works or
by other works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis.
APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING
WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT,
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING
THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT,
INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY
OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION
OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY
OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR
OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/
#include <assert.h>
#include <errno.h>
#include <pwd.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <strhash.h>
#include <sys/sysctl.h>
#include <sys/utsname.h>
#include <unistd.h>
#include <servers/bootstrap.h>
#include <mach/mach.h>
/////////////////////////////////////////////////////////////////
#pragma mark ***** Infrastructure
typedef struct kinfo_proc kinfo_proc;
static int GetBSDProcessList(kinfo_proc **procList, size_t *procCount)
// Returns a list of all BSD processes on the system. This routine
// allocates the list and puts it in *procList and a count of the
// number of entries in *procCount. You are responsible for freeing
// this list (use "free" from System framework).
// On success, the function returns 0.
// On error, the function returns a BSD errno value.
{
int err;
kinfo_proc * result;
bool done;
static const int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };
// Declaring name as const requires us to cast it when passing it to
// sysctl because the prototype doesn't include the const modifier.
size_t length;
assert( procList != NULL);
assert(*procList == NULL);
assert(procCount != NULL);
*procCount = 0;
// We start by calling sysctl with result == NULL and length == 0.
// That will succeed, and set length to the appropriate length.
// We then allocate a buffer of that size and call sysctl again
// with that buffer. If that succeeds, we're done. If that fails
// with ENOMEM, we have to throw away our buffer and loop. Note
// that the loop causes use to call sysctl with NULL again; this
// is necessary because the ENOMEM failure case sets length to
// the amount of data returned, not the amount of data that
// could have been returned.
result = NULL;
done = false;
do {
assert(result == NULL);
// Call sysctl with a NULL buffer.
length = 0;
err = sysctl( (int *) name, (sizeof(name) / sizeof(*name)) - 1,
NULL, &length,
NULL, 0);
if (err == -1) {
err = errno;
}
// Allocate an appropriately sized buffer based on the results
// from the previous call.
if (err == 0) {
result = malloc(length);
if (result == NULL) {
err = ENOMEM;
}
}
// Call sysctl again with the new buffer. If we get an ENOMEM
// error, toss away our buffer and start again.
if (err == 0) {
err = sysctl( (int *) name, (sizeof(name) / sizeof(*name)) - 1,
result, &length,
NULL, 0);
if (err == -1) {
err = errno;
}
if (err == 0) {
done = true;
} else if (err == ENOMEM) {
assert(result != NULL);
free(result);
result = NULL;
err = 0;
}
}
} while (err == 0 && ! done);
// Clean up and establish post conditions.
if ( (err != 0) && (result != NULL) ) {
free(result);
result = NULL;
}
*procList = result;
if (err == 0) {
*procCount = length / sizeof(kinfo_proc);
}
assert( (err == 0) == (*procList != NULL) );
return err;
}
static int FindProcessByName(const char *processName, pid_t *pid)
// Find the process that best matches processName and return
// its PID. It first tries to find an exact match; if that fails
// it tries to find a substring match; if that fails it checks
// whether processName is a number and returns that as the PID.
//
// On entry, processName must not be NULL, and it must not be the
// empty string. pid must not be NULL.
// On success, *pid will be the process ID of the found process.
// On error, *pid is undefined.
{
int err;
int foundCount;
kinfo_proc * processList;
size_t processCount;
size_t processIndex;
assert(processName != NULL);
assert(processName[0] != 0); // needed for strstr to behave
assert(pid != NULL);
processList = NULL;
foundCount = 0;
// Get the list of all processes.
err = GetBSDProcessList(&processList, &processCount);
if (err == 0) {
// Count the exact matches.
for (processIndex = 0; processIndex < processCount; processIndex++) {
if ( strcmp(processList[processIndex].kp_proc.p_comm, processName) == 0 ) {
*pid = processList[processIndex].kp_proc.p_pid;
foundCount += 1;
}
}
// If we got nothing, count the substring matches.
if (foundCount == 0) {
for (processIndex = 0; processIndex < processCount; processIndex++) {
if ( strstr(processList[processIndex].kp_proc.p_comm, processName) != NULL ) {
*pid = processList[processIndex].kp_proc.p_pid;
foundCount += 1;
}
}
}
// If we found more than 1, that's ambiguous and we error out.
if (foundCount > 1) {
err = EEXIST;
}
}
// If still not found, try processName as a PID.
if ( (err == 0) && (foundCount == 0) ) {
char * firstInvalid;
*pid = (pid_t) strtol(processName, &firstInvalid, 10);
if ( (processName[0] == 0) || (*firstInvalid != 0) ) {
err = ESRCH;
}
}
free(processList);
return err;
}
/////////////////////////////////////////////////////////////////
#pragma mark ***** Bootstrap Forest Dump
static int gDebug = 0;
// The Bootstrap structure records all of the information about a single
// bootstrap namespace. It is primarily tracked by a hash table, stored
// in the BootstrapContext with nodes linked by the hashLink field. This
// allows us to quickly determine if we've seen a given bootstrap namespace
// before and avoid doing any work in that case. The Bootstrap structures
// are also linked into a tree, rooted at one of the entries in the rootBootstraps
// array of the BootstrapContext, and connected the siblings and firstChild links.
typedef struct Bootstrap Bootstrap;
struct Bootstrap {
mach_port_t port; // send right for bootstrap namespace
size_t procCount; // number of valid entries in procs
const kinfo_proc * * procs; // processes using this namespace, always
// has space for context->procCount elements
Bootstrap * sibling; // next bootstrap namespace at this level
Bootstrap * firstChild; // first child namespace of this namespace
Bootstrap * hashLink; // link for hash table
};
// The BootstrapContext structures stores all of the information needed to
// anchor the hash table and forest of Bootstrap tree structures.
struct BootstrapContext {
size_t procCount; // upper bound on number of processes
size_t rootBootstrapCount; // number of valid entries in rootBootstraps
Bootstrap * * rootBootstraps; // Bootstrap tree roots
Bootstrap * portToBootstrapMap[256]; // hash table contain all Bootstraps,
// indexed by bootstrap mach_port_t hash
size_t bootstrapCount; // count of allocated Bootstraps,
// for debugging only
size_t hashCollisions; // number of hash collisions,
// for debugging only
};
typedef struct BootstrapContext BootstrapContext;
static void FreeBootstrap(BootstrapContext * context, Bootstrap *bootstrap);
// foward declaration
static int GetOrAddBootstrap(
BootstrapContext * context,
mach_port_t bootstrapPort,
Bootstrap ** bootstrapPtr
)
// For the given bootstrapPort, return a pointer to the associated Bootstrap
// structure. If we haven't seen bootstrapPort before, this creates the
// Bootstrap structure. If we have seen bootstrapPort before, this just
// returns a pointer to a previously allocated Bootstrap structure. Existing
// Bootstrap structures are tracked by a hash table in the BootstrapContext.
//
// This routine also creates (by calling itself recursively) Bootstrap
// structures for the parent bootstrap namespace of bootstrapPort (if any).
// It then links any newly created Bootstrap into the child list of the
// parent.
//
// OTOH, if there is no parent bootstrap, this sets up an entry in rootBootstrap
// array of the BootstrapContext to indicate that this is the root of a bootstrap
// tree.
{
int err;
kern_return_t kr;
kern_return_t krJunk;
size_t hash;
Bootstrap * value;
assert(context != NULL);
// We allow bootstrapPort to be null because on Mac OS X 10.5 and later every instance
// of launchd has a null bootstrap port. If we disallowed a null bootstrap port, these
// processes wouldn't show up anywhere in the forest. Allowing this does mean we have
// to be careful, later in this routine, not to assume that bootstrapPort is not null.
//
// assert(bootstrapPort != MACH_PORT_NULL);
assert(bootstrapPtr != NULL);
err = 0;
// See if we have this bootstrap in the hash table already.
hash = (bootstrapPort & 0x0FF)
^ ((bootstrapPort >> 8) & 0x0FF)
^ ((bootstrapPort >> 16) & 0x0FF)
^ ((bootstrapPort >> 24) & 0x0FF);
assert(hash < (sizeof(context->portToBootstrapMap) / sizeof(context->portToBootstrapMap[0])));
value = context->portToBootstrapMap[hash];
while ( (value != NULL) && (value->port != bootstrapPort) ) {
value = value->hashLink;
}
if (value == NULL) {
Bootstrap * parentBootstrap;
mach_port_t parentBootstrapPort;
// We don't currently know about this bootstrap; create it. We take a
// reference to the bootstrap port (assuming it's not MACH_PORT_NULL)
// so that our caller doesn't have to retain their reference.
parentBootstrapPort = MACH_PORT_NULL;
value = (Bootstrap *) calloc(1, sizeof(*value));
if (value == NULL) {
err = ENOMEM;
}
if (err == 0) {
context->bootstrapCount += 1;
value->procs = calloc(context->procCount, sizeof(*value->procs));
if (value->procs == NULL) {
err = ENOMEM;
}
}
if (err == 0) {
if (bootstrapPort != MACH_PORT_NULL) {
kr = mach_port_mod_refs(mach_task_self(), bootstrapPort, MACH_PORT_RIGHT_SEND, 1);
if (kr == KERN_SUCCESS) {
value->port = bootstrapPort;
} else {
err = EINVAL;
}
}
}
// Now process the bootstrap's parent, if any, and so on up the chain
// recursively.
if (err == 0) {
kr = bootstrap_parent(bootstrapPort, &parentBootstrapPort);
if ( (kr != KERN_SUCCESS) || (parentBootstrapPort == bootstrapPort) ) {
// There is no parent bootstrap. This must be a root bootstrap.
// Let's tag it as such. The rootBootstraps array has procCount
// entries, which is a safe, if excessive, upper bound.
assert(context->rootBootstrapCount < context->procCount);
context->rootBootstraps[context->rootBootstrapCount] = value;
context->rootBootstrapCount += 1;
} else {
// There /is/ a parent bootstrap port; call ourselves recursively to
// get its tree node.
err = GetOrAddBootstrap(context, parentBootstrapPort, &parentBootstrap);
if (err == 0) {
assert(parentBootstrapPort == parentBootstrap->port);
if (gDebug >= 1) {
fprintf(
stderr,
" parent of 0x%x [%p] is 0x%x [%p]\n",
bootstrapPort,
value,
parentBootstrapPort,
parentBootstrap
);
}
// Add ourselves to the parent's list of children. We add to the end
// because it produces a nicer output (contexts associated with higher
// PIDs appear later).
if (true) {
if (gDebug >= 1) {
fprintf(
stderr,
" adding 0x%x [%p] as child of 0x%x [%p]\n",
bootstrapPort,
value,
parentBootstrap->port,
parentBootstrap
);
if (parentBootstrap->firstChild != NULL) {
fprintf(
stderr,
" replacing 0x%x [%p] as first child\n",
parentBootstrap->firstChild->port,
parentBootstrap->firstChild
);
}
}
assert(value->sibling == NULL);
value->sibling = parentBootstrap->firstChild;
parentBootstrap->firstChild = value;
} else {
if (parentBootstrap->firstChild == NULL) {
if (gDebug >= 1) {
fprintf(
stderr,
" adding 0x%x [%p] as first child of 0x%x [%p]\n",
bootstrapPort,
value,
parentBootstrap->port,
parentBootstrap
);
}
parentBootstrap->firstChild = value;
} else {
Bootstrap * cursor;
cursor = parentBootstrap->firstChild;
while (cursor->sibling != NULL) {
cursor = cursor->sibling;
}
if (gDebug >= 1) {
fprintf(
stderr,
" adding 0x%x [%p] as child of 0x%x [%p] after 0x%x [%p]\n",
bootstrapPort,
value,
parentBootstrap->port,
parentBootstrap,
cursor->port,
cursor
);
}
cursor->sibling = value;
}
}
}
}
// Finally, add it to the hash table. We do this last so that, if
// anything above errors, we don't end up with junk in the hash.
if (err == 0) {
if (gDebug >= 1) {
fprintf(stderr, " adding 0x%x [%p] to hash\n", bootstrapPort, value);
}
value->hashLink = context->portToBootstrapMap[hash];
context->portToBootstrapMap[hash] = value;
if (value->hashLink != NULL) {
context->hashCollisions += 1;
}
} else if (value != NULL) {
// If we created a bootstrap, but failed to add it to a tree,
// clean it up.
assert(value->firstChild == NULL);
assert(value->sibling == NULL);
assert(value->hashLink == NULL);
FreeBootstrap(context, value);
value = NULL;
}
}
// Clean up. We can release our reference to parentBootstrapPort because,
// when we called ourselves recursively, the nested instance will have
// taken its own reference.
if (parentBootstrapPort != MACH_PORT_NULL) {
krJunk = mach_port_deallocate(mach_task_self(), parentBootstrapPort);
assert(krJunk == KERN_SUCCESS);
}
}
// Return result to caller.
if (err == 0) {
*bootstrapPtr = value;
}
assert( (err == 0) == (*bootstrapPtr != NULL) );
assert( (*bootstrapPtr == NULL) || ((*bootstrapPtr)->port == bootstrapPort) );
return err;
}
static int AddProcessToBootstrapForest(BootstrapContext *context, const kinfo_proc *proc)
// Adds a process to the bootstrap forest. This first finds (or creates)
// the (Bootstrap *) associated with the process's bootstrap namespace, then
// adds a reference to the process to the list of processes in that bootstrap.
{
int err;
kern_return_t kr;
kern_return_t krJunk;
task_t task;
mach_port_t bootstrapPort;
Bootstrap * bootstrap;
assert(context != NULL);
assert(context->procCount > 0);
assert(context->portToBootstrapMap != NULL);
assert(proc != NULL);
assert(proc->kp_proc.p_pid > 0);
task = MACH_PORT_NULL;
bootstrapPort = MACH_PORT_NULL;
err = 0;
// Starting off in the kern_return_t error domain.
// Get the bootstrap port for the process.
kr = task_for_pid(mach_task_self(), proc->kp_proc.p_pid, &task);
if ( true && (kr == KERN_FAILURE) ) {
fflush(stdout);
if ( geteuid() == 0 ) {
fprintf(
stderr,
"%s: Could not get task control port for '%s' (%d)\n",
getprogname(),
proc->kp_proc.p_comm,
(int) proc->kp_proc.p_pid
);
} else {
fprintf(
stderr,
"%s: Could not get task control port for '%s' (%d); try again as root\n",
getprogname(),
proc->kp_proc.p_comm,
(int) proc->kp_proc.p_pid
);
}
err = ECANCELED;
}
if (kr == KERN_SUCCESS) {
kr = task_get_bootstrap_port(task, &bootstrapPort);
}
// Switch to the errno error domain.
if ( (kr != KERN_SUCCESS) && (err == 0) ) {
err = EINVAL;
}
// Get or create a bootstrap context for this bootstrap port.
if (err == 0) {
err = GetOrAddBootstrap(context, bootstrapPort, &bootstrap);
}
// Add this process to the list of processes in that context.
if (err == 0) {
assert(bootstrap->port == bootstrapPort);
if (gDebug >= 1) {
fprintf(
stderr,
"pid %d has bootstrap 0x%x [%p]\n",
(int) proc->kp_proc.p_pid,
bootstrapPort,
bootstrap
);
}
// The bootstrap->procs array is always allocated with enough entries
// to hold all of the processes, which is a colossal waste of memory
// but makes things very easy. However, just to be sure, this assert
// checks that we don't run past the end of the array.
assert(bootstrap->procCount < context->procCount);
bootstrap->procs[bootstrap->procCount] = proc;
bootstrap->procCount += 1;
}
// Clean up.
if (bootstrapPort != MACH_PORT_NULL) {
// It is save to dispose bootstrapPort now because GetOrAddBootstrap
// has added a reference count to it.
krJunk = mach_port_deallocate(mach_task_self(), bootstrapPort);
assert(krJunk == KERN_SUCCESS);
}
if (task != MACH_PORT_NULL) {
krJunk = mach_port_deallocate(mach_task_self(), task);
assert(krJunk == KERN_SUCCESS);
}
return err;
}
static void PrintBootstrapTree(Bootstrap *bootstrap, int indent, FILE *f)
// Recursively print the bootstrap tree rooted at bootstrap.
{
size_t procIndex;
Bootstrap * cursor;
assert(bootstrap != NULL);
assert(f != NULL);
// Print the header for this bootstrap.
if (gDebug >= 1) {
fprintf(f, "%*s0x%x [%p]\n", indent, "", bootstrap->port, bootstrap);
} else {
fprintf(f, "%*s0x%x\n", indent, "", bootstrap->port);
}
// Print the list of processes for this context.
for (procIndex = 0; procIndex < bootstrap->procCount; procIndex++) {
uid_t ruid;
char ruidStr[32];
uid_t euid;
char euidStr[32];
struct passwd * pw;
euid = bootstrap->procs[procIndex]->kp_eproc.e_ucred.cr_uid;
ruid = bootstrap->procs[procIndex]->kp_eproc.e_pcred.p_ruid;
pw = getpwuid(euid);
if (pw == NULL) {
snprintf(euidStr, sizeof(euidStr), "%ld", (long) euid);
} else {
strlcpy(euidStr, pw->pw_name, sizeof(euidStr));
}
if (euid == ruid) {
fprintf(
f,
"%*s%s (%s, %ld->%ld)\n",
indent + 2, "",
bootstrap->procs[procIndex]->kp_proc.p_comm,
euidStr,
(long) bootstrap->procs[procIndex]->kp_proc.p_pid,
(long) bootstrap->procs[procIndex]->kp_eproc.e_ppid
);
} else {
pw = getpwuid(ruid);
if (pw == NULL) {
snprintf(ruidStr, sizeof(ruidStr), "%ld", (long) ruid);
} else {
strlcpy(ruidStr, pw->pw_name, sizeof(ruidStr));
}
fprintf(
f,
"%*s%s (%s/%s, %ld->%ld)\n",
indent + 2, "",
bootstrap->procs[procIndex]->kp_proc.p_comm,
euidStr,
ruidStr,
(long) bootstrap->procs[procIndex]->kp_proc.p_pid,
(long) bootstrap->procs[procIndex]->kp_eproc.e_ppid
);
}
}
// If we're in debug mode, print the two lists in a compact format.
if (gDebug >= 1) {
fprintf(f, "%*schildren =", indent + 2, "");
cursor = bootstrap->firstChild;
while (cursor != NULL) {
fprintf(f, " 0x%x [%p]", cursor->port, cursor);
cursor = cursor->sibling;
}
fprintf(f, "\n");
fprintf(f, "%*ssiblings =", indent + 2, "");
cursor = bootstrap->sibling;
while (cursor != NULL) {
fprintf(f, " 0x%x [%p]", cursor->port, cursor);
cursor = cursor->sibling;
}
fprintf(f, "\n");
}
// Recursively print any child contexts indented.
if (bootstrap->firstChild != NULL) {
PrintBootstrapTree(bootstrap->firstChild, indent + 2, f);
}
// Recursively print any sibling contexts at the same indent.
if (bootstrap->sibling != NULL) {
PrintBootstrapTree(bootstrap->sibling, indent, f);
}
}
static void FreeBootstrap(BootstrapContext *context, Bootstrap *bootstrap)
// Free a single bootstrap hash node.
{
kern_return_t krJunk;
assert(context != NULL);
assert(bootstrap != NULL);
if (bootstrap->port != MACH_PORT_NULL) {
krJunk = mach_port_deallocate(mach_task_self(), bootstrap->port);
assert(krJunk == KERN_SUCCESS);
}
free(bootstrap->procs);
free(bootstrap);
assert(context->bootstrapCount > 0);
context->bootstrapCount -= 1;
}
static void FreeAllBootstraps(BootstrapContext *context)
// Free all of the Bootstrap nodes referenced by the hash. We free via the
// hash rather than the forest of trees because... well, in earlier versions
// it was necessary because we didn't support more than one root, and this
// approach is inherited from that.
{
static const size_t kHashCount = (sizeof(context->portToBootstrapMap) / sizeof(context->portToBootstrapMap[0]));
size_t hashIndex;
Bootstrap * cursor;
Bootstrap * bootstrap;
for (hashIndex = 0; hashIndex < kHashCount; hashIndex++) {
cursor = context->portToBootstrapMap[hashIndex];
while (cursor != NULL) {
bootstrap = cursor;
cursor = cursor->hashLink;
FreeBootstrap(context, bootstrap);
}
}
}
static int ProcSorter(const void *p1, const void *p2)
// Sort two (const kinfo_proc *) by their process ID.
{
return ((const kinfo_proc *) p1)->kp_proc.p_pid - ((const kinfo_proc *) p2)->kp_proc.p_pid;
}
static void PrintRoots(const BootstrapContext *context, FILE *f)
// Print the forest of bootstrap trees that represented by context.
{
size_t rootIndex;
assert(context != NULL);
assert(f != NULL);
for (rootIndex = 0; rootIndex < context->rootBootstrapCount; rootIndex++) {
PrintBootstrapTree(context->rootBootstraps[rootIndex], 0, f);
}
}
static int PrintBootstrapMap(FILE *f)
// Print a forest of the bootstrap namespaces and the processes within each
// namespace. Sneaky.
{
int err;
kinfo_proc * procs;
size_t procCount;
size_t procIndex;
BootstrapContext context;
// f may be NULL during leak testing
procs = NULL;
memset(&context, 0, sizeof(context));
// Get the list of processes.
err = GetBSDProcessList(&procs, &procCount);
// We sort the process list by pid (smallest to highest) at this point.
// This has two effects:
//
// o Within a bootstrap, the processes are listed in pid order.
//
// o Within a bootstrap, the child bootstraps are sorted by the lowest
// pid of the processes within each bootstrap.
if (err == 0) {
qsort(procs, procCount, sizeof(*procs), ProcSorter);
}
// Set up the forest context.
if (err == 0) {
context.procCount = procCount;
context.rootBootstraps = (Bootstrap **) calloc(context.procCount, sizeof(*context.rootBootstraps));
if (context.rootBootstraps == NULL) {
err = ENOMEM;
}
}
// Get the bootstrap port for every process and place them into the forest.
if (err == 0) {
for (procIndex = 0; procIndex < procCount; procIndex++) {
if (procs[procIndex].kp_proc.p_pid == 0) {
// Skip process 0, which isn't a real, user-visible process.
} else if (procs[procIndex].kp_proc.p_stat == SZOMB) {
// Even though we print this message to stderr, we still don't
// want to print it if there's no output specified. This happens
// when we're leak testing, and without this check a single zombie
// will result in a whole bunch of these messages.
if (f != NULL) {
fprintf(
stderr,
"%s: Skipping zombie process '%s' (%d)\n",
getprogname(),
procs[procIndex].kp_proc.p_comm,
(int) procs[procIndex].kp_proc.p_pid
);
}
} else {
err = AddProcessToBootstrapForest(&context, &procs[procIndex]);
}
if ( (err == 0) && (f != NULL) && (gDebug >= 2) ) {
PrintRoots(&context, stderr);
}
if (err != 0) {
break;
}
}
}
// Print the resulting forest.
if ( (err == 0) && (f != NULL) ) {
PrintRoots(&context, f);
if ( (gDebug >= 1) && (f != NULL) ) {
fprintf(f, "hashCollisions = %zd\n", context.hashCollisions);
}
}
// Clean up.
FreeAllBootstraps(&context);
assert(context.bootstrapCount == 0);
free(context.rootBootstraps);
free(procs);
return err;
}
/////////////////////////////////////////////////////////////////
#pragma mark ***** Bootstrap Namespace Dump
static int GetDarwinOSRelease(int *majorPtr, int *minorPtr, int *bugPtr)
// Get the major, minor and bug fix release version of the Darwin OS.
{
int err;
struct utsname names;
int scanResult;
static int sMajor;
static int sMinor;
static int sBug;
// If we haven't already got the OS release, get it now.
err = 0;
if (sMajor == 0) {
err = uname(&names);
if (err < 0) {
err = errno;
}
if (err == 0) {
// Parse the three dot separated components of the release string.
// If we don't get exactly three, we've confused and we error.
scanResult = sscanf(names.release, "%d.%d.%d", &sMajor, &sMinor, &sBug);
if (scanResult != 3) {
err = EINVAL;
}
}
}
// Return it to our caller.