This repository was archived by the owner on May 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathkern_fork.c
More file actions
1739 lines (1542 loc) · 52.7 KB
/
kern_fork.c
File metadata and controls
1739 lines (1542 loc) · 52.7 KB
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
/*
* Copyright (c) 2000-2007, 2015 Apple Inc. All rights reserved.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. The rights granted to you under the License
* may not be used to create, or enable the creation or redistribution of,
* unlawful or unlicensed copies of an Apple operating system, or to
* circumvent, violate, or enable the circumvention or violation of, any
* terms of an Apple operating system software license agreement.
*
* Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_END@
*/
/* Copyright (c) 1995, 1997 Apple Computer, Inc. All Rights Reserved */
/*
* Copyright (c) 1982, 1986, 1989, 1991, 1993
* The Regents of the University of California. All rights reserved.
* (c) UNIX System Laboratories, Inc.
* All or some portions of this file are derived from material licensed
* to the University of California by American Telephone and Telegraph
* Co. or Unix System Laboratories, Inc. and are reproduced herein with
* the permission of UNIX System Laboratories, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)kern_fork.c 8.8 (Berkeley) 2/14/95
*/
/*
* NOTICE: This file was modified by McAfee Research in 2004 to introduce
* support for mandatory and extensible security protections. This notice
* is included in support of clause 2.2 (b) of the Apple Public License,
* Version 2.0.
*/
/*
* NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
* support for mandatory and extensible security protections. This notice
* is included in support of clause 2.2 (b) of the Apple Public License,
* Version 2.0.
*/
#include <kern/assert.h>
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/filedesc.h>
#include <sys/kernel.h>
#include <sys/malloc.h>
#include <sys/proc_internal.h>
#include <sys/kauth.h>
#include <sys/user.h>
#include <sys/reason.h>
#include <sys/resourcevar.h>
#include <sys/vnode_internal.h>
#include <sys/file_internal.h>
#include <sys/acct.h>
#include <sys/codesign.h>
#include <sys/sysproto.h>
#if CONFIG_PERSONAS
#include <sys/persona.h>
#endif
#include <sys/doc_tombstone.h>
#if CONFIG_DTRACE
/* Do not include dtrace.h, it redefines kmem_[alloc/free] */
extern void (*dtrace_proc_waitfor_exec_ptr)(proc_t);
extern void dtrace_proc_fork(proc_t, proc_t, int);
/*
* Since dtrace_proc_waitfor_exec_ptr can be added/removed in dtrace_subr.c,
* we will store its value before actually calling it.
*/
static void (*dtrace_proc_waitfor_hook)(proc_t) = NULL;
#include <sys/dtrace_ptss.h>
#endif
#include <security/audit/audit.h>
#include <mach/mach_types.h>
#include <kern/coalition.h>
#include <kern/kern_types.h>
#include <kern/kalloc.h>
#include <kern/mach_param.h>
#include <kern/task.h>
#include <kern/thread.h>
#include <kern/thread_call.h>
#include <kern/zalloc.h>
#include <os/log.h>
#include <os/log.h>
#if CONFIG_MACF
#include <security/mac_framework.h>
#include <security/mac_mach_internal.h>
#endif
#include <vm/vm_map.h>
#include <vm/vm_protos.h>
#include <vm/vm_shared_region.h>
#include <sys/shm_internal.h> /* for shmfork() */
#include <mach/task.h> /* for thread_create() */
#include <mach/thread_act.h> /* for thread_resume() */
#include <sys/sdt.h>
#if CONFIG_MEMORYSTATUS
#include <sys/kern_memorystatus.h>
#endif
/* XXX routines which should have Mach prototypes, but don't */
void thread_set_parent(thread_t parent, int pid);
extern void act_thread_catt(void *ctx);
void thread_set_child(thread_t child, int pid);
void *act_thread_csave(void);
extern boolean_t task_is_exec_copy(task_t);
thread_t cloneproc(task_t, coalition_t *, proc_t, int, int);
proc_t forkproc(proc_t);
void forkproc_free(proc_t);
thread_t fork_create_child(task_t parent_task, coalition_t *parent_coalitions, proc_t child, int inherit_memory, int is64bit, int in_exec);
void proc_vfork_begin(proc_t parent_proc);
void proc_vfork_end(proc_t parent_proc);
#define DOFORK 0x1 /* fork() system call */
#define DOVFORK 0x2 /* vfork() system call */
/*
* proc_vfork_begin
*
* Description: start a vfork on a process
*
* Parameters: parent_proc process (re)entering vfork state
*
* Returns: (void)
*
* Notes: Although this function increments a count, a count in
* excess of 1 is not currently supported. According to the
* POSIX standard, calling anything other than execve() or
* _exit() following a vfork(), including calling vfork()
* itself again, will result in undefined behaviour
*/
void
proc_vfork_begin(proc_t parent_proc)
{
proc_lock(parent_proc);
parent_proc->p_lflag |= P_LVFORK;
parent_proc->p_vforkcnt++;
proc_unlock(parent_proc);
}
/*
* proc_vfork_end
*
* Description: stop a vfork on a process
*
* Parameters: parent_proc process leaving vfork state
*
* Returns: (void)
*
* Notes: Decrements the count; currently, reentrancy of vfork()
* is unsupported on the current process
*/
void
proc_vfork_end(proc_t parent_proc)
{
proc_lock(parent_proc);
parent_proc->p_vforkcnt--;
if (parent_proc->p_vforkcnt < 0)
panic("vfork cnt is -ve");
if (parent_proc->p_vforkcnt == 0)
parent_proc->p_lflag &= ~P_LVFORK;
proc_unlock(parent_proc);
}
/*
* vfork
*
* Description: vfork system call
*
* Parameters: void [no arguments]
*
* Retval: 0 (to child process)
* !0 pid of child (to parent process)
* -1 error (see "Returns:")
*
* Returns: EAGAIN Administrative limit reached
* EINVAL vfork() called during vfork()
* ENOMEM Failed to allocate new process
*
* Note: After a successful call to this function, the parent process
* has its task, thread, and uthread lent to the child process,
* and control is returned to the caller; if this function is
* invoked as a system call, the return is to user space, and
* is effectively running on the child process.
*
* Subsequent calls that operate on process state are permitted,
* though discouraged, and will operate on the child process; any
* operations on the task, thread, or uthread will result in
* changes in the parent state, and, if inheritable, the child
* state, when a task, thread, and uthread are realized for the
* child process at execve() time, will also be effected. Given
* this, it's recemmended that people use the posix_spawn() call
* instead.
*
* BLOCK DIAGRAM OF VFORK
*
* Before:
*
* ,----------------. ,-------------.
* | | task | |
* | parent_thread | ------> | parent_task |
* | | <.list. | |
* `----------------' `-------------'
* uthread | ^ bsd_info | ^
* v | vc_thread v | task
* ,----------------. ,-------------.
* | | | |
* | parent_uthread | <.list. | parent_proc | <-- current_proc()
* | | | |
* `----------------' `-------------'
* uu_proc |
* v
* NULL
*
* After:
*
* ,----------------. ,-------------.
* | | task | |
* ,----> | parent_thread | ------> | parent_task |
* | | | <.list. | |
* | `----------------' `-------------'
* | uthread | ^ bsd_info | ^
* | v | vc_thread v | task
* | ,----------------. ,-------------.
* | | | | |
* | | parent_uthread | <.list. | parent_proc |
* | | | | |
* | `----------------' `-------------'
* | uu_proc | . list
* | v v
* | ,----------------.
* `----- | |
* p_vforkact | child_proc | <-- current_proc()
* | |
* `----------------'
*/
int
vfork(proc_t parent_proc, __unused struct vfork_args *uap, int32_t *retval)
{
thread_t child_thread;
int err;
if ((err = fork1(parent_proc, &child_thread, PROC_CREATE_VFORK, NULL)) != 0) {
retval[1] = 0;
} else {
uthread_t ut = get_bsdthread_info(current_thread());
proc_t child_proc = ut->uu_proc;
retval[0] = child_proc->p_pid;
retval[1] = 1; /* flag child return for user space */
/*
* Drop the signal lock on the child which was taken on our
* behalf by forkproc()/cloneproc() to prevent signals being
* received by the child in a partially constructed state.
*/
proc_signalend(child_proc, 0);
proc_transend(child_proc, 0);
proc_knote(parent_proc, NOTE_FORK | child_proc->p_pid);
DTRACE_PROC1(create, proc_t, child_proc);
ut->uu_flag &= ~UT_VFORKING;
}
return (err);
}
/*
* fork1
*
* Description: common code used by all new process creation other than the
* bootstrap of the initial process on the system
*
* Parameters: parent_proc parent process of the process being
* child_threadp pointer to location to receive the
* Mach thread_t of the child process
* created
* kind kind of creation being requested
* coalitions if spawn, the set of coalitions the
* child process should join, or NULL to
* inherit the parent's. On non-spawns,
* this param is ignored and the child
* always inherits the parent's
* coalitions.
*
* Notes: Permissable values for 'kind':
*
* PROC_CREATE_FORK Create a complete process which will
* return actively running in both the
* parent and the child; the child copies
* the parent address space.
* PROC_CREATE_SPAWN Create a complete process which will
* return actively running in the parent
* only after returning actively running
* in the child; the child address space
* is newly created by an image activator,
* after which the child is run.
* PROC_CREATE_VFORK Creates a partial process which will
* borrow the parent task, thread, and
* uthread to return running in the child;
* the child address space and other parts
* are lazily created at execve() time, or
* the child is terminated, and the parent
* does not actively run until that
* happens.
*
* At first it may seem strange that we return the child thread
* address rather than process structure, since the process is
* the only part guaranteed to be "new"; however, since we do
* not actualy adjust other references between Mach and BSD (see
* the block diagram above the implementation of vfork()), this
* is the only method which guarantees us the ability to get
* back to the other information.
*/
int
fork1(proc_t parent_proc, thread_t *child_threadp, int kind, coalition_t *coalitions)
{
thread_t parent_thread = (thread_t)current_thread();
uthread_t parent_uthread = (uthread_t)get_bsdthread_info(parent_thread);
proc_t child_proc = NULL; /* set in switch, but compiler... */
thread_t child_thread = NULL;
uid_t uid;
int count;
int err = 0;
int spawn = 0;
/*
* Although process entries are dynamically created, we still keep
* a global limit on the maximum number we will create. Don't allow
* a nonprivileged user to use the last process; don't let root
* exceed the limit. The variable nprocs is the current number of
* processes, maxproc is the limit.
*/
uid = kauth_getruid();
proc_list_lock();
if ((nprocs >= maxproc - 1 && uid != 0) || nprocs >= maxproc) {
#if (DEVELOPMENT || DEBUG) && CONFIG_EMBEDDED
/*
* On the development kernel, panic so that the fact that we hit
* the process limit is obvious, as this may very well wedge the
* system.
*/
panic("The process table is full; parent pid=%d", parent_proc->p_pid);
#endif
proc_list_unlock();
tablefull("proc");
return (EAGAIN);
}
proc_list_unlock();
/*
* Increment the count of procs running with this uid. Don't allow
* a nonprivileged user to exceed their current limit, which is
* always less than what an rlim_t can hold.
* (locking protection is provided by list lock held in chgproccnt)
*/
count = chgproccnt(uid, 1);
if (uid != 0 &&
(rlim_t)count > parent_proc->p_rlimit[RLIMIT_NPROC].rlim_cur) {
#if (DEVELOPMENT || DEBUG) && CONFIG_EMBEDDED
/*
* On the development kernel, panic so that the fact that we hit
* the per user process limit is obvious. This may be less dire
* than hitting the global process limit, but we cannot rely on
* that.
*/
panic("The per-user process limit has been hit; parent pid=%d, uid=%d", parent_proc->p_pid, uid);
#endif
err = EAGAIN;
goto bad;
}
#if CONFIG_MACF
/*
* Determine if MAC policies applied to the process will allow
* it to fork. This is an advisory-only check.
*/
err = mac_proc_check_fork(parent_proc);
if (err != 0) {
goto bad;
}
#endif
switch(kind) {
case PROC_CREATE_VFORK:
/*
* Prevent a vfork while we are in vfork(); we should
* also likely preventing a fork here as well, and this
* check should then be outside the switch statement,
* since the proc struct contents will copy from the
* child and the tash/thread/uthread from the parent in
* that case. We do not support vfork() in vfork()
* because we don't have to; the same non-requirement
* is true of both fork() and posix_spawn() and any
* call other than execve() amd _exit(), but we've
* been historically lenient, so we continue to be so
* (for now).
*
* <rdar://6640521> Probably a source of random panics
*/
if (parent_uthread->uu_flag & UT_VFORK) {
printf("fork1 called within vfork by %s\n", parent_proc->p_comm);
err = EINVAL;
goto bad;
}
/*
* Flag us in progress; if we chose to support vfork() in
* vfork(), we would chain our parent at this point (in
* effect, a stack push). We don't, since we actually want
* to disallow everything not specified in the standard
*/
proc_vfork_begin(parent_proc);
/* The newly created process comes with signal lock held */
if ((child_proc = forkproc(parent_proc)) == NULL) {
/* Failed to allocate new process */
proc_vfork_end(parent_proc);
err = ENOMEM;
goto bad;
}
// XXX BEGIN: wants to move to be common code (and safe)
#if CONFIG_MACF
/*
* allow policies to associate the credential/label that
* we referenced from the parent ... with the child
* JMM - this really isn't safe, as we can drop that
* association without informing the policy in other
* situations (keep long enough to get policies changed)
*/
mac_cred_label_associate_fork(child_proc->p_ucred, child_proc);
#endif
/*
* Propogate change of PID - may get new cred if auditing.
*
* NOTE: This has no effect in the vfork case, since
* child_proc->task != current_task(), but we duplicate it
* because this is probably, ultimately, wrong, since we
* will be running in the "child" which is the parent task
* with the wrong token until we get to the execve() or
* _exit() call; a lot of "undefined" can happen before
* that.
*
* <rdar://6640530> disallow everything but exeve()/_exit()?
*/
set_security_token(child_proc);
AUDIT_ARG(pid, child_proc->p_pid);
// XXX END: wants to move to be common code (and safe)
/*
* BORROW PARENT TASK, THREAD, UTHREAD FOR CHILD
*
* Note: this is where we would "push" state instead of setting
* it for nested vfork() support (see proc_vfork_end() for
* description if issues here).
*/
child_proc->task = parent_proc->task;
child_proc->p_lflag |= P_LINVFORK;
child_proc->p_vforkact = parent_thread;
child_proc->p_stat = SRUN;
/*
* Until UT_VFORKING is cleared at the end of the vfork
* syscall, the process identity of this thread is slightly
* murky.
*
* As long as UT_VFORK and it's associated field (uu_proc)
* is set, current_proc() will always return the child process.
*
* However dtrace_proc_selfpid() returns the parent pid to
* ensure that e.g. the proc:::create probe actions accrue
* to the parent. (Otherwise the child magically seems to
* have created itself!)
*/
parent_uthread->uu_flag |= UT_VFORK | UT_VFORKING;
parent_uthread->uu_proc = child_proc;
parent_uthread->uu_userstate = (void *)act_thread_csave();
parent_uthread->uu_vforkmask = parent_uthread->uu_sigmask;
/* temporarily drop thread-set-id state */
if (parent_uthread->uu_flag & UT_SETUID) {
parent_uthread->uu_flag |= UT_WASSETUID;
parent_uthread->uu_flag &= ~UT_SETUID;
}
/* blow thread state information */
/* XXX is this actually necessary, given syscall return? */
thread_set_child(parent_thread, child_proc->p_pid);
child_proc->p_acflag = AFORK; /* forked but not exec'ed */
/*
* Preserve synchronization semantics of vfork. If
* waiting for child to exec or exit, set P_PPWAIT
* on child, and sleep on our proc (in case of exit).
*/
child_proc->p_lflag |= P_LPPWAIT;
pinsertchild(parent_proc, child_proc); /* set visible */
break;
case PROC_CREATE_SPAWN:
/*
* A spawned process differs from a forked process in that
* the spawned process does not carry around the parents
* baggage with regard to address space copying, dtrace,
* and so on.
*/
spawn = 1;
/* FALLSTHROUGH */
case PROC_CREATE_FORK:
/*
* When we clone the parent process, we are going to inherit
* its task attributes and memory, since when we fork, we
* will, in effect, create a duplicate of it, with only minor
* differences. Contrarily, spawned processes do not inherit.
*/
if ((child_thread = cloneproc(parent_proc->task,
spawn ? coalitions : NULL,
parent_proc,
spawn ? FALSE : TRUE,
FALSE)) == NULL) {
/* Failed to create thread */
err = EAGAIN;
goto bad;
}
/* copy current thread state into the child thread (only for fork) */
if (!spawn) {
thread_dup(child_thread);
}
/* child_proc = child_thread->task->proc; */
child_proc = (proc_t)(get_bsdtask_info(get_threadtask(child_thread)));
// XXX BEGIN: wants to move to be common code (and safe)
#if CONFIG_MACF
/*
* allow policies to associate the credential/label that
* we referenced from the parent ... with the child
* JMM - this really isn't safe, as we can drop that
* association without informing the policy in other
* situations (keep long enough to get policies changed)
*/
mac_cred_label_associate_fork(child_proc->p_ucred, child_proc);
#endif
/*
* Propogate change of PID - may get new cred if auditing.
*
* NOTE: This has no effect in the vfork case, since
* child_proc->task != current_task(), but we duplicate it
* because this is probably, ultimately, wrong, since we
* will be running in the "child" which is the parent task
* with the wrong token until we get to the execve() or
* _exit() call; a lot of "undefined" can happen before
* that.
*
* <rdar://6640530> disallow everything but exeve()/_exit()?
*/
set_security_token(child_proc);
AUDIT_ARG(pid, child_proc->p_pid);
// XXX END: wants to move to be common code (and safe)
/*
* Blow thread state information; this is what gives the child
* process its "return" value from a fork() call.
*
* Note: this should probably move to fork() proper, since it
* is not relevent to spawn, and the value won't matter
* until we resume the child there. If you are in here
* refactoring code, consider doing this at the same time.
*/
thread_set_child(child_thread, child_proc->p_pid);
child_proc->p_acflag = AFORK; /* forked but not exec'ed */
#if CONFIG_DTRACE
dtrace_proc_fork(parent_proc, child_proc, spawn);
#endif /* CONFIG_DTRACE */
if (!spawn) {
/*
* Of note, we need to initialize the bank context behind
* the protection of the proc_trans lock to prevent a race with exit.
*/
task_bank_init(get_threadtask(child_thread));
}
break;
default:
panic("fork1 called with unknown kind %d", kind);
break;
}
/* return the thread pointer to the caller */
*child_threadp = child_thread;
bad:
/*
* In the error case, we return a 0 value for the returned pid (but
* it is ignored in the trampoline due to the error return); this
* is probably not necessary.
*/
if (err) {
(void)chgproccnt(uid, -1);
}
return (err);
}
/*
* vfork_return
*
* Description: "Return" to parent vfork thread() following execve/_exit;
* this is done by reassociating the parent process structure
* with the task, thread, and uthread.
*
* Refer to the ASCII art above vfork() to figure out the
* state we're undoing.
*
* Parameters: child_proc Child process
* retval System call return value array
* rval Return value to present to parent
*
* Returns: void
*
* Notes: The caller resumes or exits the parent, as appropriate, after
* calling this function.
*/
void
vfork_return(proc_t child_proc, int32_t *retval, int rval)
{
task_t parent_task = get_threadtask(child_proc->p_vforkact);
proc_t parent_proc = get_bsdtask_info(parent_task);
thread_t th = current_thread();
uthread_t uth = get_bsdthread_info(th);
act_thread_catt(uth->uu_userstate);
/* clear vfork state in parent proc structure */
proc_vfork_end(parent_proc);
/* REPATRIATE PARENT TASK, THREAD, UTHREAD */
uth->uu_userstate = 0;
uth->uu_flag &= ~UT_VFORK;
/* restore thread-set-id state */
if (uth->uu_flag & UT_WASSETUID) {
uth->uu_flag |= UT_SETUID;
uth->uu_flag &= UT_WASSETUID;
}
uth->uu_proc = 0;
uth->uu_sigmask = uth->uu_vforkmask;
proc_lock(child_proc);
child_proc->p_lflag &= ~P_LINVFORK;
child_proc->p_vforkact = 0;
proc_unlock(child_proc);
thread_set_parent(th, rval);
if (retval) {
retval[0] = rval;
retval[1] = 0; /* mark parent */
}
}
/*
* fork_create_child
*
* Description: Common operations associated with the creation of a child
* process
*
* Parameters: parent_task parent task
* parent_coalitions parent's set of coalitions
* child_proc child process
* inherit_memory TRUE, if the parents address space is
* to be inherited by the child
* is64bit TRUE, if the child being created will
* be associated with a 64 bit process
* rather than a 32 bit process
* in_exec TRUE, if called from execve or posix spawn set exec
* FALSE, if called from fork or vfexec
*
* Note: This code is called in the fork() case, from the execve() call
* graph, if implementing an execve() following a vfork(), from
* the posix_spawn() call graph (which implicitly includes a
* vfork() equivalent call, and in the system bootstrap case.
*
* It creates a new task and thread (and as a side effect of the
* thread creation, a uthread) in the parent coalition set, which is
* then associated with the process 'child'. If the parent
* process address space is to be inherited, then a flag
* indicates that the newly created task should inherit this from
* the child task.
*
* As a special concession to bootstrapping the initial process
* in the system, it's possible for 'parent_task' to be TASK_NULL;
* in this case, 'inherit_memory' MUST be FALSE.
*/
thread_t
fork_create_child(task_t parent_task, coalition_t *parent_coalitions, proc_t child_proc, int inherit_memory, int is64bit, int in_exec)
{
thread_t child_thread = NULL;
task_t child_task;
kern_return_t result;
/* Create a new task for the child process */
result = task_create_internal(parent_task,
parent_coalitions,
inherit_memory,
is64bit,
TF_LRETURNWAIT | TF_LRETURNWAITER, /* All created threads will wait in task_wait_to_return */
in_exec ? TPF_EXEC_COPY : TPF_NONE, /* Mark the task exec copy if in execve */
&child_task);
if (result != KERN_SUCCESS) {
printf("%s: task_create_internal failed. Code: %d\n",
__func__, result);
goto bad;
}
if (!in_exec) {
/*
* Set the child process task to the new task if not in exec,
* will set the task for exec case in proc_exec_switch_task after image activation.
*/
child_proc->task = child_task;
}
/* Set child task process to child proc */
set_bsdtask_info(child_task, child_proc);
/* Propagate CPU limit timer from parent */
if (timerisset(&child_proc->p_rlim_cpu))
task_vtimer_set(child_task, TASK_VTIMER_RLIM);
/*
* Set child process BSD visible scheduler priority if nice value
* inherited from parent
*/
if (child_proc->p_nice != 0)
resetpriority(child_proc);
/*
* Create a new thread for the child process
* The new thread is waiting on the event triggered by 'task_clear_return_wait'
*/
result = thread_create_waiting(child_task,
(thread_continue_t)task_wait_to_return,
task_get_return_wait_event(child_task),
&child_thread);
if (result != KERN_SUCCESS) {
printf("%s: thread_create failed. Code: %d\n",
__func__, result);
task_deallocate(child_task);
child_task = NULL;
}
/*
* Tag thread as being the first thread in its task.
*/
thread_set_tag(child_thread, THREAD_TAG_MAINTHREAD);
bad:
thread_yield_internal(1);
return(child_thread);
}
/*
* fork
*
* Description: fork system call.
*
* Parameters: parent Parent process to fork
* uap (void) [unused]
* retval Return value
*
* Returns: 0 Success
* EAGAIN Resource unavailable, try again
*
* Notes: Attempts to create a new child process which inherits state
* from the parent process. If successful, the call returns
* having created an initially suspended child process with an
* extra Mach task and thread reference, for which the thread
* is initially suspended. Until we resume the child process,
* it is not yet running.
*
* The return information to the child is contained in the
* thread state structure of the new child, and does not
* become visible to the child through a normal return process,
* since it never made the call into the kernel itself in the
* first place.
*
* After resuming the thread, this function returns directly to
* the parent process which invoked the fork() system call.
*
* Important: The child thread_resume occurs before the parent returns;
* depending on scheduling latency, this means that it is not
* deterministic as to whether the parent or child is scheduled
* to run first. It is entirely possible that the child could
* run to completion prior to the parent running.
*/
int
fork(proc_t parent_proc, __unused struct fork_args *uap, int32_t *retval)
{
thread_t child_thread;
int err;
retval[1] = 0; /* flag parent return for user space */
if ((err = fork1(parent_proc, &child_thread, PROC_CREATE_FORK, NULL)) == 0) {
task_t child_task;
proc_t child_proc;
/* Return to the parent */
child_proc = (proc_t)get_bsdthreadtask_info(child_thread);
retval[0] = child_proc->p_pid;
/*
* Drop the signal lock on the child which was taken on our
* behalf by forkproc()/cloneproc() to prevent signals being
* received by the child in a partially constructed state.
*/
proc_signalend(child_proc, 0);
proc_transend(child_proc, 0);
/* flag the fork has occurred */
proc_knote(parent_proc, NOTE_FORK | child_proc->p_pid);
DTRACE_PROC1(create, proc_t, child_proc);
#if CONFIG_DTRACE
if ((dtrace_proc_waitfor_hook = dtrace_proc_waitfor_exec_ptr) != NULL)
(*dtrace_proc_waitfor_hook)(child_proc);
#endif
/* "Return" to the child */
task_clear_return_wait(get_threadtask(child_thread));
/* drop the extra references we got during the creation */
if ((child_task = (task_t)get_threadtask(child_thread)) != NULL) {
task_deallocate(child_task);
}
thread_deallocate(child_thread);
}
return(err);
}
/*
* cloneproc
*
* Description: Create a new process from a specified process.
*
* Parameters: parent_task The parent task to be cloned, or
* TASK_NULL is task characteristics
* are not to be inherited
* be cloned, or TASK_NULL if the new
* task is not to inherit the VM
* characteristics of the parent
* parent_proc The parent process to be cloned
* inherit_memory True if the child is to inherit
* memory from the parent; if this is
* non-NULL, then the parent_task must
* also be non-NULL
* memstat_internal Whether to track the process in the
* jetsam priority list (if configured)
*
* Returns: !NULL pointer to new child thread
* NULL Failure (unspecified)
*
* Note: On return newly created child process has signal lock held
* to block delivery of signal to it if called with lock set.
* fork() code needs to explicity remove this lock before
* signals can be delivered
*
* In the case of bootstrap, this function can be called from
* bsd_utaskbootstrap() in order to bootstrap the first process;
* the net effect is to provide a uthread structure for the
* kernel process associated with the kernel task.
*
* XXX: Tristating using the value parent_task as the major key
* and inherit_memory as the minor key is something we should
* refactor later; we owe the current semantics, ultimately,
* to the semantics of task_create_internal. For now, we will
* live with this being somewhat awkward.
*/
thread_t
cloneproc(task_t parent_task, coalition_t *parent_coalitions, proc_t parent_proc, int inherit_memory, int memstat_internal)
{
#if !CONFIG_MEMORYSTATUS
#pragma unused(memstat_internal)
#endif
task_t child_task;
proc_t child_proc;
thread_t child_thread = NULL;
if ((child_proc = forkproc(parent_proc)) == NULL) {
/* Failed to allocate new process */
goto bad;
}
child_thread = fork_create_child(parent_task, parent_coalitions, child_proc, inherit_memory, parent_proc->p_flag & P_LP64, FALSE);
if (child_thread == NULL) {
/*
* Failed to create thread; now we must deconstruct the new
* process previously obtained from forkproc().
*/
forkproc_free(child_proc);
goto bad;
}
child_task = get_threadtask(child_thread);
if (parent_proc->p_flag & P_LP64) {
task_set_64bit(child_task, TRUE);
OSBitOrAtomic(P_LP64, (UInt32 *)&child_proc->p_flag);
} else {
task_set_64bit(child_task, FALSE);
OSBitAndAtomic(~((uint32_t)P_LP64), (UInt32 *)&child_proc->p_flag);
}
#if CONFIG_MEMORYSTATUS
if (memstat_internal) {
proc_list_lock();
child_proc->p_memstat_state |= P_MEMSTAT_INTERNAL;
proc_list_unlock();
}
#endif
/* make child visible */
pinsertchild(parent_proc, child_proc);