2 * Copyright (c) 2000-2016 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
28 /* Copyright (c) 1995, 1997 Apple Computer, Inc. All Rights Reserved */
30 * Copyright (c) 1982, 1986, 1989, 1991, 1993
31 * The Regents of the University of California. All rights reserved.
32 * (c) UNIX System Laboratories, Inc.
33 * All or some portions of this file are derived from material licensed
34 * to the University of California by American Telephone and Telegraph
35 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
36 * the permission of UNIX System Laboratories, Inc.
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
41 * 1. Redistributions of source code must retain the above copyright
42 * notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
46 * 3. All advertising materials mentioning features or use of this software
47 * must display the following acknowledgement:
48 * This product includes software developed by the University of
49 * California, Berkeley and its contributors.
50 * 4. Neither the name of the University nor the names of its contributors
51 * may be used to endorse or promote products derived from this software
52 * without specific prior written permission.
54 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
66 * @(#)kern_descrip.c 8.8 (Berkeley) 2/14/95
69 * NOTICE: This file was modified by SPARTA, Inc. in 2006 to introduce
70 * support for mandatory and extensible security protections. This notice
71 * is included in support of clause 2.2 (b) of the Apple Public License,
75 #include <sys/param.h>
76 #include <sys/systm.h>
77 #include <sys/filedesc.h>
78 #include <sys/kernel.h>
79 #include <sys/vnode_internal.h>
80 #include <sys/proc_internal.h>
81 #include <sys/kauth.h>
82 #include <sys/file_internal.h>
83 #include <sys/guarded.h>
85 #include <sys/socket.h>
86 #include <sys/socketvar.h>
88 #include <sys/ioctl.h>
89 #include <sys/fcntl.h>
90 #include <sys/fsctl.h>
91 #include <sys/malloc.h>
93 #include <sys/syslog.h>
94 #include <sys/unistd.h>
95 #include <sys/resourcevar.h>
96 #include <sys/aio_kern.h>
98 #include <kern/locks.h>
99 #include <sys/uio_internal.h>
100 #include <sys/codesign.h>
101 #include <sys/codedir_internal.h>
103 #include <security/audit/audit.h>
105 #include <sys/mount_internal.h>
106 #include <sys/kdebug.h>
107 #include <sys/sysproto.h>
108 #include <sys/pipe.h>
109 #include <sys/spawn.h>
110 #include <sys/cprotect.h>
111 #include <kern/kern_types.h>
112 #include <kern/kalloc.h>
113 #include <kern/waitq.h>
114 #include <libkern/OSAtomic.h>
116 #include <sys/ubc_internal.h>
118 #include <kern/ipc_misc.h>
119 #include <vm/vm_protos.h>
121 #include <mach/mach_port.h>
125 #include <security/mac_framework.h>
128 #define IPC_KMSG_FLAGS_ALLOW_IMMOVABLE_SEND 0x1
129 kern_return_t
ipc_object_copyin(ipc_space_t
, mach_port_name_t
,
130 mach_msg_type_name_t
, ipc_port_t
*, mach_port_context_t
, mach_msg_guard_flags_t
*, uint32_t);
131 void ipc_port_release_send(ipc_port_t
);
136 static int finishdup(proc_t p
,
137 struct filedesc
*fdp
, int old
, int new, int flags
, int32_t *retval
);
139 int falloc_locked(proc_t p
, struct fileproc
**resultfp
, int *resultfd
, vfs_context_t ctx
, int locked
);
140 void fg_drop(struct fileproc
* fp
);
141 void fg_free(struct fileglob
*fg
);
142 void fg_ref(struct fileproc
* fp
);
143 void fileport_releasefg(struct fileglob
*fg
);
145 /* flags for close_internal_locked */
146 #define FD_DUP2RESV 1
148 /* We don't want these exported */
151 int unlink1(vfs_context_t
, vnode_t
, user_addr_t
, enum uio_seg
, int);
153 static void _fdrelse(struct proc
* p
, int fd
);
156 extern void file_lock_init(void);
158 extern kauth_scope_t kauth_scope_fileop
;
160 /* Conflict wait queue for when selects collide (opaque type) */
161 extern struct waitq select_conflict_queue
;
163 #ifndef HFS_GET_BOOT_INFO
164 #define HFS_GET_BOOT_INFO (FCNTL_FS_SPECIFIC_BASE + 0x00004)
167 #ifndef HFS_SET_BOOT_INFO
168 #define HFS_SET_BOOT_INFO (FCNTL_FS_SPECIFIC_BASE + 0x00005)
171 #ifndef APFSIOC_REVERT_TO_SNAPSHOT
172 #define APFSIOC_REVERT_TO_SNAPSHOT _IOW('J', 1, u_int64_t)
175 #define f_flag f_fglob->fg_flag
176 #define f_type f_fglob->fg_ops->fo_type
177 #define f_msgcount f_fglob->fg_msgcount
178 #define f_cred f_fglob->fg_cred
179 #define f_ops f_fglob->fg_ops
180 #define f_offset f_fglob->fg_offset
181 #define f_data f_fglob->fg_data
182 #define CHECK_ADD_OVERFLOW_INT64L(x, y) \
183 (((((x) > 0) && ((y) > 0) && ((x) > LLONG_MAX - (y))) || \
184 (((x) < 0) && ((y) < 0) && ((x) < LLONG_MIN - (y)))) \
187 * Descriptor management.
189 struct fmsglist fmsghead
; /* head of list of open files */
190 struct fmsglist fmsg_ithead
; /* head of list of open files */
191 int nfiles
; /* actual number of open files */
194 lck_grp_attr_t
* file_lck_grp_attr
;
195 lck_grp_t
* file_lck_grp
;
196 lck_attr_t
* file_lck_attr
;
198 lck_mtx_t
* uipc_lock
;
202 * check_file_seek_range
204 * Description: Checks if seek offsets are in the range of 0 to LLONG_MAX.
206 * Parameters: fl Flock structure.
207 * cur_file_offset Current offset in the file.
209 * Returns: 0 on Success.
210 * EOVERFLOW on overflow.
211 * EINVAL on offset less than zero.
215 check_file_seek_range(struct flock
*fl
, off_t cur_file_offset
)
217 if (fl
->l_whence
== SEEK_CUR
) {
218 /* Check if the start marker is beyond LLONG_MAX. */
219 if (CHECK_ADD_OVERFLOW_INT64L(fl
->l_start
, cur_file_offset
)) {
220 /* Check if start marker is negative */
221 if (fl
->l_start
< 0) {
226 /* Check if the start marker is negative. */
227 if (fl
->l_start
+ cur_file_offset
< 0) {
230 /* Check if end marker is beyond LLONG_MAX. */
231 if ((fl
->l_len
> 0) && (CHECK_ADD_OVERFLOW_INT64L(fl
->l_start
+
232 cur_file_offset
, fl
->l_len
- 1))) {
235 /* Check if the end marker is negative. */
236 if ((fl
->l_len
<= 0) && (fl
->l_start
+ cur_file_offset
+
240 } else if (fl
->l_whence
== SEEK_SET
) {
241 /* Check if the start marker is negative. */
242 if (fl
->l_start
< 0) {
245 /* Check if the end marker is beyond LLONG_MAX. */
246 if ((fl
->l_len
> 0) &&
247 CHECK_ADD_OVERFLOW_INT64L(fl
->l_start
, fl
->l_len
- 1)) {
250 /* Check if the end marker is negative. */
251 if ((fl
->l_len
< 0) && fl
->l_start
+ fl
->l_len
< 0) {
262 * Description: Initialize the file lock group and the uipc and flist locks
268 * Notes: Called at system startup from bsd_init().
273 /* allocate file lock group attribute and group */
274 file_lck_grp_attr
= lck_grp_attr_alloc_init();
276 file_lck_grp
= lck_grp_alloc_init("file", file_lck_grp_attr
);
278 /* Allocate file lock attribute */
279 file_lck_attr
= lck_attr_alloc_init();
281 uipc_lock
= lck_mtx_alloc_init(file_lck_grp
, file_lck_attr
);
286 * proc_fdlock, proc_fdlock_spin
288 * Description: Lock to control access to the per process struct fileproc
289 * and struct filedesc
291 * Parameters: p Process to take the lock on
295 * Notes: The lock is initialized in forkproc() and destroyed in
296 * reap_child_process().
299 proc_fdlock(proc_t p
)
301 lck_mtx_lock(&p
->p_fdmlock
);
305 proc_fdlock_spin(proc_t p
)
307 lck_mtx_lock_spin(&p
->p_fdmlock
);
311 proc_fdlock_assert(proc_t p
, int assertflags
)
313 lck_mtx_assert(&p
->p_fdmlock
, assertflags
);
320 * Description: Unlock the lock previously locked by a call to proc_fdlock()
322 * Parameters: p Process to drop the lock on
327 proc_fdunlock(proc_t p
)
329 lck_mtx_unlock(&p
->p_fdmlock
);
334 * System calls on descriptors.
341 * Description: Returns the per process maximum size of the descriptor table
343 * Parameters: p Process being queried
344 * retval Pointer to the call return area
349 * *retval (modified) Size of dtable
352 getdtablesize(proc_t p
, __unused
struct getdtablesize_args
*uap
, int32_t *retval
)
355 *retval
= min((int)p
->p_rlimit
[RLIMIT_NOFILE
].rlim_cur
, maxfiles
);
363 procfdtbl_reservefd(struct proc
* p
, int fd
)
365 p
->p_fd
->fd_ofiles
[fd
] = NULL
;
366 p
->p_fd
->fd_ofileflags
[fd
] |= UF_RESERVED
;
370 procfdtbl_markclosefd(struct proc
* p
, int fd
)
372 p
->p_fd
->fd_ofileflags
[fd
] |= (UF_RESERVED
| UF_CLOSING
);
376 procfdtbl_releasefd(struct proc
* p
, int fd
, struct fileproc
* fp
)
379 p
->p_fd
->fd_ofiles
[fd
] = fp
;
381 p
->p_fd
->fd_ofileflags
[fd
] &= ~UF_RESERVED
;
382 if ((p
->p_fd
->fd_ofileflags
[fd
] & UF_RESVWAIT
) == UF_RESVWAIT
) {
383 p
->p_fd
->fd_ofileflags
[fd
] &= ~UF_RESVWAIT
;
389 procfdtbl_waitfd(struct proc
* p
, int fd
)
391 p
->p_fd
->fd_ofileflags
[fd
] |= UF_RESVWAIT
;
392 msleep(&p
->p_fd
, &p
->p_fdmlock
, PRIBIO
, "ftbl_waitfd", NULL
);
397 procfdtbl_clearfd(struct proc
* p
, int fd
)
401 waiting
= (p
->p_fd
->fd_ofileflags
[fd
] & UF_RESVWAIT
);
402 p
->p_fd
->fd_ofiles
[fd
] = NULL
;
403 p
->p_fd
->fd_ofileflags
[fd
] = 0;
404 if (waiting
== UF_RESVWAIT
) {
412 * Description: Inline utility function to free an fd in a filedesc
414 * Parameters: fdp Pointer to filedesc fd lies in
416 * reserv fd should be reserved
420 * Locks: Assumes proc_fdlock for process pointing to fdp is held by
424 _fdrelse(struct proc
* p
, int fd
)
426 struct filedesc
*fdp
= p
->p_fd
;
429 if (fd
< fdp
->fd_freefile
) {
430 fdp
->fd_freefile
= fd
;
433 if (fd
> fdp
->fd_lastfile
) {
434 panic("fdrelse: fd_lastfile inconsistent");
437 procfdtbl_clearfd(p
, fd
);
439 while ((nfd
= fdp
->fd_lastfile
) > 0 &&
440 fdp
->fd_ofiles
[nfd
] == NULL
&&
441 !(fdp
->fd_ofileflags
[nfd
] & UF_RESERVED
)) {
442 /* JMM - What about files with lingering EV_VANISHED knotes? */
465 char uio_buf
[UIO_SIZEOF(1)];
466 struct vfs_context context
= *(vfs_context_current());
467 bool wrote_some
= false;
471 error
= fp_lookup(p
, fd
, &fp
, 0);
476 if (fp
->f_type
!= DTYPE_VNODE
&& fp
->f_type
!= DTYPE_PIPE
&& fp
->f_type
!= DTYPE_SOCKET
) {
480 if (rw
== UIO_WRITE
&& !(fp
->f_flag
& FWRITE
)) {
485 if (rw
== UIO_READ
&& !(fp
->f_flag
& FREAD
)) {
490 context
.vc_ucred
= fp
->f_fglob
->fg_cred
;
492 if (UIO_SEG_IS_USER_SPACE(segflg
)) {
493 spacetype
= proc_is64bit(p
) ? UIO_USERSPACE64
: UIO_USERSPACE32
;
495 spacetype
= UIO_SYSSPACE
;
498 auio
= uio_createwithbuffer(1, offset
, spacetype
, rw
, &uio_buf
[0], sizeof(uio_buf
));
500 uio_addiov(auio
, base
, len
);
502 if (!(io_flg
& IO_APPEND
)) {
506 if (rw
== UIO_WRITE
) {
507 user_ssize_t orig_resid
= uio_resid(auio
);
508 error
= fo_write(fp
, auio
, flags
, &context
);
509 wrote_some
= uio_resid(auio
) < orig_resid
;
511 error
= fo_read(fp
, auio
, flags
, &context
);
515 *aresid
= uio_resid(auio
);
517 if (uio_resid(auio
) && error
== 0) {
523 fp_drop_written(p
, fd
, fp
);
525 fp_drop(p
, fd
, fp
, 0);
536 * Description: Duplicate a file descriptor.
538 * Parameters: p Process performing the dup
539 * uap->fd The fd to dup
540 * retval Pointer to the call return area
546 * *retval (modified) The new descriptor
549 dup(proc_t p
, struct dup_args
*uap
, int32_t *retval
)
551 struct filedesc
*fdp
= p
->p_fd
;
557 if ((error
= fp_lookup(p
, old
, &fp
, 1))) {
561 if (FP_ISGUARDED(fp
, GUARD_DUP
)) {
562 error
= fp_guard_exception(p
, old
, fp
, kGUARD_EXC_DUP
);
563 (void) fp_drop(p
, old
, fp
, 1);
567 if ((error
= fdalloc(p
, 0, &new))) {
568 fp_drop(p
, old
, fp
, 1);
572 error
= finishdup(p
, fdp
, old
, new, 0, retval
);
573 fp_drop(p
, old
, fp
, 1);
576 if (ENTR_SHOULDTRACE
&& fp
->f_type
== DTYPE_SOCKET
) {
577 KERNEL_ENERGYTRACE(kEnTrActKernSocket
, DBG_FUNC_START
,
578 new, 0, (int64_t)VM_KERNEL_ADDRPERM(fp
->f_data
));
587 * Description: Duplicate a file descriptor to a particular value.
589 * Parameters: p Process performing the dup
590 * uap->from The fd to dup
591 * uap->to The fd to dup it to
592 * retval Pointer to the call return area
598 * *retval (modified) The new descriptor
601 dup2(proc_t p
, struct dup2_args
*uap
, int32_t *retval
)
603 struct filedesc
*fdp
= p
->p_fd
;
604 int old
= uap
->from
, new = uap
->to
;
606 struct fileproc
*fp
, *nfp
;
611 if ((error
= fp_lookup(p
, old
, &fp
, 1))) {
615 if (FP_ISGUARDED(fp
, GUARD_DUP
)) {
616 error
= fp_guard_exception(p
, old
, fp
, kGUARD_EXC_DUP
);
617 (void) fp_drop(p
, old
, fp
, 1);
622 (rlim_t
)new >= p
->p_rlimit
[RLIMIT_NOFILE
].rlim_cur
||
624 fp_drop(p
, old
, fp
, 1);
629 fp_drop(p
, old
, fp
, 1);
634 if (new < 0 || new >= fdp
->fd_nfiles
) {
635 if ((error
= fdalloc(p
, new, &i
))) {
636 fp_drop(p
, old
, fp
, 1);
646 while ((fdp
->fd_ofileflags
[new] & UF_RESERVED
) == UF_RESERVED
) {
647 fp_drop(p
, old
, fp
, 1);
648 procfdtbl_waitfd(p
, new);
650 proc_fdlock_assert(p
, LCK_MTX_ASSERT_OWNED
);
655 if ((fdp
->fd_ofiles
[new] != NULL
) &&
656 ((error
= fp_lookup(p
, new, &nfp
, 1)) == 0)) {
657 fp_drop(p
, old
, fp
, 1);
658 if (FP_ISGUARDED(nfp
, GUARD_CLOSE
)) {
659 error
= fp_guard_exception(p
,
660 new, nfp
, kGUARD_EXC_CLOSE
);
661 (void) fp_drop(p
, new, nfp
, 1);
665 (void)close_internal_locked(p
, new, nfp
, FD_DUP2RESV
);
667 proc_fdlock_assert(p
, LCK_MTX_ASSERT_OWNED
);
669 procfdtbl_clearfd(p
, new);
673 if (fdp
->fd_ofiles
[new] != NULL
) {
674 panic("dup2: no ref on fileproc %d", new);
677 procfdtbl_reservefd(p
, new);
681 proc_fdlock_assert(p
, LCK_MTX_ASSERT_OWNED
);
685 if (fdp
->fd_ofiles
[new] != 0) {
686 panic("dup2: overwriting fd_ofiles with new %d", new);
688 if ((fdp
->fd_ofileflags
[new] & UF_RESERVED
) == 0) {
689 panic("dup2: unreserved fileflags with new %d", new);
692 error
= finishdup(p
, fdp
, old
, new, 0, retval
);
693 fp_drop(p
, old
, fp
, 1);
703 * Description: The file control system call.
705 * Parameters: p Process performing the fcntl
706 * uap->fd The fd to operate against
707 * uap->cmd The command to perform
708 * uap->arg Pointer to the command argument
709 * retval Pointer to the call return area
712 * !0 Errno (see fcntl_nocancel)
715 * *retval (modified) fcntl return value (if any)
717 * Notes: This system call differs from fcntl_nocancel() in that it
718 * tests for cancellation prior to performing a potentially
719 * blocking operation.
722 fcntl(proc_t p
, struct fcntl_args
*uap
, int32_t *retval
)
724 __pthread_testcancel(1);
725 return fcntl_nocancel(p
, (struct fcntl_nocancel_args
*)uap
, retval
);
732 * Description: A non-cancel-testing file control system call.
734 * Parameters: p Process performing the fcntl
735 * uap->fd The fd to operate against
736 * uap->cmd The command to perform
737 * uap->arg Pointer to the command argument
738 * retval Pointer to the call return area
742 * fp_lookup:EBADF Bad file descriptor
754 * vnode_getwithref:???
762 * vnode_getwithref:???
769 * vnode_getwithref:???
771 * [F_SETSIZE,F_RDADVISE]
774 * vnode_getwithref:???
775 * [F_RDAHEAD,F_NOCACHE]
777 * vnode_getwithref:???
781 * *retval (modified) fcntl return value (if any)
784 fcntl_nocancel(proc_t p
, struct fcntl_nocancel_args
*uap
, int32_t *retval
)
787 struct filedesc
*fdp
= p
->p_fd
;
790 struct vnode
*vp
= NULLVP
; /* for AUDIT_ARG() at end */
791 int i
, tmp
, error
, error2
, flg
= 0;
792 struct flock fl
= {};
793 struct flocktimeout fltimeout
;
794 struct timespec
*timeout
= NULL
;
795 struct vfs_context context
;
803 AUDIT_ARG(fd
, uap
->fd
);
804 AUDIT_ARG(cmd
, uap
->cmd
);
807 if ((error
= fp_lookup(p
, fd
, &fp
, 1))) {
811 context
.vc_thread
= current_thread();
812 context
.vc_ucred
= fp
->f_cred
;
814 is64bit
= proc_is64bit(p
);
819 * Since the arg parameter is defined as a long but may be
820 * either a long or a pointer we must take care to handle
821 * sign extension issues. Our sys call munger will sign
822 * extend a long when we are called from a 32-bit process.
823 * Since we can never have an address greater than 32-bits
824 * from a 32-bit process we lop off the top 32-bits to avoid
825 * getting the wrong address
827 argp
= CAST_USER_ADDR_T((uint32_t)uap
->arg
);
830 pop
= &fdp
->fd_ofileflags
[fd
];
833 error
= mac_file_check_fcntl(proc_ucred(p
), fp
->f_fglob
, uap
->cmd
,
842 case F_DUPFD_CLOEXEC
:
843 if (FP_ISGUARDED(fp
, GUARD_DUP
)) {
844 error
= fp_guard_exception(p
, fd
, fp
, kGUARD_EXC_DUP
);
847 newmin
= CAST_DOWN_EXPLICIT(int, uap
->arg
); /* arg is an int, so we won't lose bits */
848 AUDIT_ARG(value32
, newmin
);
849 if ((u_int
)newmin
>= p
->p_rlimit
[RLIMIT_NOFILE
].rlim_cur
||
850 newmin
>= maxfiles
) {
854 if ((error
= fdalloc(p
, newmin
, &i
))) {
857 error
= finishdup(p
, fdp
, fd
, i
,
858 uap
->cmd
== F_DUPFD_CLOEXEC
? UF_EXCLOSE
: 0, retval
);
862 *retval
= (*pop
& UF_EXCLOSE
)? FD_CLOEXEC
: 0;
867 AUDIT_ARG(value32
, uap
->arg
);
868 if (uap
->arg
& FD_CLOEXEC
) {
871 if (FILEPROC_TYPE(fp
) == FTYPE_GUARDED
) {
872 error
= fp_guard_exception(p
,
873 fd
, fp
, kGUARD_EXC_NOCLOEXEC
);
882 *retval
= OFLAGS(fp
->f_flag
);
887 fp
->f_flag
&= ~FCNTLFLAGS
;
888 tmp
= CAST_DOWN_EXPLICIT(int, uap
->arg
); /* arg is an int, so we won't lose bits */
889 AUDIT_ARG(value32
, tmp
);
890 fp
->f_flag
|= FFLAGS(tmp
) & FCNTLFLAGS
;
891 tmp
= fp
->f_flag
& FNONBLOCK
;
892 error
= fo_ioctl(fp
, FIONBIO
, (caddr_t
)&tmp
, &context
);
896 tmp
= fp
->f_flag
& FASYNC
;
897 error
= fo_ioctl(fp
, FIOASYNC
, (caddr_t
)&tmp
, &context
);
901 fp
->f_flag
&= ~FNONBLOCK
;
903 (void)fo_ioctl(fp
, FIONBIO
, (caddr_t
)&tmp
, &context
);
907 if (fp
->f_type
== DTYPE_SOCKET
) {
908 *retval
= ((struct socket
*)fp
->f_data
)->so_pgid
;
912 error
= fo_ioctl(fp
, TIOCGPGRP
, (caddr_t
)retval
, &context
);
917 tmp
= CAST_DOWN_EXPLICIT(pid_t
, uap
->arg
); /* arg is an int, so we won't lose bits */
918 AUDIT_ARG(value32
, tmp
);
919 if (fp
->f_type
== DTYPE_SOCKET
) {
920 ((struct socket
*)fp
->f_data
)->so_pgid
= tmp
;
924 if (fp
->f_type
== DTYPE_PIPE
) {
925 error
= fo_ioctl(fp
, TIOCSPGRP
, (caddr_t
)&tmp
, &context
);
932 proc_t p1
= proc_find(tmp
);
937 tmp
= (int)p1
->p_pgrpid
;
940 error
= fo_ioctl(fp
, TIOCSPGRP
, (caddr_t
)&tmp
, &context
);
944 tmp
= CAST_DOWN_EXPLICIT(int, uap
->arg
);
945 if (fp
->f_type
== DTYPE_SOCKET
) {
947 error
= sock_setsockopt((struct socket
*)fp
->f_data
,
948 SOL_SOCKET
, SO_NOSIGPIPE
, &tmp
, sizeof(tmp
));
953 struct fileglob
*fg
= fp
->f_fglob
;
955 lck_mtx_lock_spin(&fg
->fg_lock
);
957 fg
->fg_lflags
|= FG_NOSIGPIPE
;
959 fg
->fg_lflags
&= ~FG_NOSIGPIPE
;
961 lck_mtx_unlock(&fg
->fg_lock
);
967 if (fp
->f_type
== DTYPE_SOCKET
) {
969 int retsize
= sizeof(*retval
);
970 error
= sock_getsockopt((struct socket
*)fp
->f_data
,
971 SOL_SOCKET
, SO_NOSIGPIPE
, retval
, &retsize
);
976 *retval
= (fp
->f_fglob
->fg_lflags
& FG_NOSIGPIPE
) ?
984 * If this is the only reference to this fglob in the process
985 * and it's already marked as close-on-fork then mark it as
986 * (immutably) "confined" i.e. any fd that points to it will
987 * forever be close-on-fork, and attempts to use an IPC
988 * mechanism to move the descriptor elsewhere will fail.
990 if (CAST_DOWN_EXPLICIT(int, uap
->arg
)) {
991 struct fileglob
*fg
= fp
->f_fglob
;
993 lck_mtx_lock_spin(&fg
->fg_lock
);
994 if (fg
->fg_lflags
& FG_CONFINED
) {
996 } else if (1 != fg
->fg_count
) {
997 error
= EAGAIN
; /* go close the dup .. */
998 } else if (UF_FORKCLOSE
== (*pop
& UF_FORKCLOSE
)) {
999 fg
->fg_lflags
|= FG_CONFINED
;
1002 error
= EBADF
; /* open without O_CLOFORK? */
1004 lck_mtx_unlock(&fg
->fg_lock
);
1007 * Other subsystems may have built on the immutability
1008 * of FG_CONFINED; clearing it may be tricky.
1010 error
= EPERM
; /* immutable */
1015 *retval
= (fp
->f_fglob
->fg_lflags
& FG_CONFINED
) ? 1 : 0;
1019 case F_SETLKWTIMEOUT
:
1021 case F_OFD_SETLKWTIMEOUT
:
1024 /* Fall into F_SETLK */
1028 if (fp
->f_type
!= DTYPE_VNODE
) {
1032 vp
= (struct vnode
*)fp
->f_data
;
1035 offset
= fp
->f_offset
;
1038 /* Copy in the lock structure */
1039 if (F_SETLKWTIMEOUT
== uap
->cmd
||
1040 F_OFD_SETLKWTIMEOUT
== uap
->cmd
) {
1041 error
= copyin(argp
, (caddr_t
) &fltimeout
, sizeof(fltimeout
));
1046 timeout
= &fltimeout
.timeout
;
1048 error
= copyin(argp
, (caddr_t
)&fl
, sizeof(fl
));
1054 /* Check starting byte and ending byte for EOVERFLOW in SEEK_CUR */
1055 /* and ending byte for EOVERFLOW in SEEK_SET */
1056 error
= check_file_seek_range(&fl
, offset
);
1061 if ((error
= vnode_getwithref(vp
))) {
1064 if (fl
.l_whence
== SEEK_CUR
) {
1065 fl
.l_start
+= offset
;
1069 error
= mac_file_check_lock(proc_ucred(p
), fp
->f_fglob
,
1072 (void)vnode_put(vp
);
1079 case F_OFD_SETLKWTIMEOUT
:
1081 switch (fl
.l_type
) {
1083 if ((fflag
& FREAD
) == 0) {
1087 error
= VNOP_ADVLOCK(vp
, (caddr_t
)fp
->f_fglob
,
1088 F_SETLK
, &fl
, flg
, &context
, timeout
);
1091 if ((fflag
& FWRITE
) == 0) {
1095 error
= VNOP_ADVLOCK(vp
, (caddr_t
)fp
->f_fglob
,
1096 F_SETLK
, &fl
, flg
, &context
, timeout
);
1099 error
= VNOP_ADVLOCK(vp
, (caddr_t
)fp
->f_fglob
,
1100 F_UNLCK
, &fl
, F_OFD_LOCK
, &context
,
1108 (F_RDLCK
== fl
.l_type
|| F_WRLCK
== fl
.l_type
)) {
1109 struct fileglob
*fg
= fp
->f_fglob
;
1112 * arrange F_UNLCK on last close (once
1113 * set, FG_HAS_OFDLOCK is immutable)
1115 if ((fg
->fg_lflags
& FG_HAS_OFDLOCK
) == 0) {
1116 lck_mtx_lock_spin(&fg
->fg_lock
);
1117 fg
->fg_lflags
|= FG_HAS_OFDLOCK
;
1118 lck_mtx_unlock(&fg
->fg_lock
);
1124 switch (fl
.l_type
) {
1126 if ((fflag
& FREAD
) == 0) {
1130 // XXX UInt32 unsafe for LP64 kernel
1131 OSBitOrAtomic(P_LADVLOCK
, &p
->p_ladvflag
);
1132 error
= VNOP_ADVLOCK(vp
, (caddr_t
)p
,
1133 F_SETLK
, &fl
, flg
, &context
, timeout
);
1136 if ((fflag
& FWRITE
) == 0) {
1140 // XXX UInt32 unsafe for LP64 kernel
1141 OSBitOrAtomic(P_LADVLOCK
, &p
->p_ladvflag
);
1142 error
= VNOP_ADVLOCK(vp
, (caddr_t
)p
,
1143 F_SETLK
, &fl
, flg
, &context
, timeout
);
1146 error
= VNOP_ADVLOCK(vp
, (caddr_t
)p
,
1147 F_UNLCK
, &fl
, F_POSIX
, &context
, timeout
);
1155 (void) vnode_put(vp
);
1161 case F_OFD_GETLKPID
:
1162 if (fp
->f_type
!= DTYPE_VNODE
) {
1166 vp
= (struct vnode
*)fp
->f_data
;
1168 offset
= fp
->f_offset
;
1171 /* Copy in the lock structure */
1172 error
= copyin(argp
, (caddr_t
)&fl
, sizeof(fl
));
1177 /* Check starting byte and ending byte for EOVERFLOW in SEEK_CUR */
1178 /* and ending byte for EOVERFLOW in SEEK_SET */
1179 error
= check_file_seek_range(&fl
, offset
);
1184 if ((fl
.l_whence
== SEEK_SET
) && (fl
.l_start
< 0)) {
1189 switch (fl
.l_type
) {
1199 switch (fl
.l_whence
) {
1209 if ((error
= vnode_getwithref(vp
)) == 0) {
1210 if (fl
.l_whence
== SEEK_CUR
) {
1211 fl
.l_start
+= offset
;
1215 error
= mac_file_check_lock(proc_ucred(p
), fp
->f_fglob
,
1221 error
= VNOP_ADVLOCK(vp
, (caddr_t
)fp
->f_fglob
,
1222 F_GETLK
, &fl
, F_OFD_LOCK
, &context
, NULL
);
1224 case F_OFD_GETLKPID
:
1225 error
= VNOP_ADVLOCK(vp
, (caddr_t
)fp
->f_fglob
,
1226 F_GETLKPID
, &fl
, F_OFD_LOCK
, &context
, NULL
);
1229 error
= VNOP_ADVLOCK(vp
, (caddr_t
)p
,
1230 uap
->cmd
, &fl
, F_POSIX
, &context
, NULL
);
1234 (void)vnode_put(vp
);
1237 error
= copyout((caddr_t
)&fl
, argp
, sizeof(fl
));
1242 case F_PREALLOCATE
: {
1243 fstore_t alloc_struct
; /* structure for allocate command */
1244 u_int32_t alloc_flags
= 0;
1246 if (fp
->f_type
!= DTYPE_VNODE
) {
1251 vp
= (struct vnode
*)fp
->f_data
;
1254 /* make sure that we have write permission */
1255 if ((fp
->f_flag
& FWRITE
) == 0) {
1260 error
= copyin(argp
, (caddr_t
)&alloc_struct
, sizeof(alloc_struct
));
1265 /* now set the space allocated to 0 */
1266 alloc_struct
.fst_bytesalloc
= 0;
1269 * Do some simple parameter checking
1272 /* set up the flags */
1274 alloc_flags
|= PREALLOCATE
;
1276 if (alloc_struct
.fst_flags
& F_ALLOCATECONTIG
) {
1277 alloc_flags
|= ALLOCATECONTIG
;
1280 if (alloc_struct
.fst_flags
& F_ALLOCATEALL
) {
1281 alloc_flags
|= ALLOCATEALL
;
1285 * Do any position mode specific stuff. The only
1286 * position mode supported now is PEOFPOSMODE
1289 switch (alloc_struct
.fst_posmode
) {
1291 if (alloc_struct
.fst_offset
!= 0) {
1296 alloc_flags
|= ALLOCATEFROMPEOF
;
1300 if (alloc_struct
.fst_offset
<= 0) {
1305 alloc_flags
|= ALLOCATEFROMVOL
;
1313 if ((error
= vnode_getwithref(vp
)) == 0) {
1315 * call allocate to get the space
1317 error
= VNOP_ALLOCATE(vp
, alloc_struct
.fst_length
, alloc_flags
,
1318 &alloc_struct
.fst_bytesalloc
, alloc_struct
.fst_offset
,
1320 (void)vnode_put(vp
);
1322 error2
= copyout((caddr_t
)&alloc_struct
, argp
, sizeof(alloc_struct
));
1333 if (fp
->f_type
!= DTYPE_VNODE
) {
1338 vp
= (struct vnode
*)fp
->f_data
;
1341 /* need write permissions */
1342 if ((fp
->f_flag
& FWRITE
) == 0) {
1347 if ((error
= copyin(argp
, (caddr_t
)&args
, sizeof(args
)))) {
1351 if ((error
= vnode_getwithref(vp
))) {
1356 if ((error
= mac_vnode_check_write(&context
, fp
->f_fglob
->fg_cred
, vp
))) {
1357 (void)vnode_put(vp
);
1362 error
= VNOP_IOCTL(vp
, F_PUNCHHOLE
, (caddr_t
)&args
, 0, &context
);
1363 (void)vnode_put(vp
);
1367 case F_TRIM_ACTIVE_FILE
: {
1368 ftrimactivefile_t args
;
1370 if (priv_check_cred(kauth_cred_get(), PRIV_TRIM_ACTIVE_FILE
, 0)) {
1375 if (fp
->f_type
!= DTYPE_VNODE
) {
1380 vp
= (struct vnode
*)fp
->f_data
;
1383 /* need write permissions */
1384 if ((fp
->f_flag
& FWRITE
) == 0) {
1389 if ((error
= copyin(argp
, (caddr_t
)&args
, sizeof(args
)))) {
1393 if ((error
= vnode_getwithref(vp
))) {
1397 error
= VNOP_IOCTL(vp
, F_TRIM_ACTIVE_FILE
, (caddr_t
)&args
, 0, &context
);
1398 (void)vnode_put(vp
);
1402 case F_SPECULATIVE_READ
: {
1405 if (fp
->f_type
!= DTYPE_VNODE
) {
1410 vp
= (struct vnode
*)fp
->f_data
;
1413 if ((error
= copyin(argp
, (caddr_t
)&args
, sizeof(args
)))) {
1417 /* Discard invalid offsets or lengths */
1418 if ((args
.fsr_offset
< 0) || (args
.fsr_length
< 0)) {
1424 * Round the file offset down to a page-size boundary (or to 0).
1425 * The filesystem will need to round the length up to the end of the page boundary
1426 * or to the EOF of the file.
1428 uint64_t foff
= (((uint64_t)args
.fsr_offset
) & ~((uint64_t)PAGE_MASK
));
1429 uint64_t foff_delta
= args
.fsr_offset
- foff
;
1430 args
.fsr_offset
= (off_t
) foff
;
1433 * Now add in the delta to the supplied length. Since we may have adjusted the
1434 * offset, increase it by the amount that we adjusted.
1436 args
.fsr_length
+= foff_delta
;
1438 if ((error
= vnode_getwithref(vp
))) {
1441 error
= VNOP_IOCTL(vp
, F_SPECULATIVE_READ
, (caddr_t
)&args
, 0, &context
);
1442 (void)vnode_put(vp
);
1447 if (fp
->f_type
!= DTYPE_VNODE
) {
1451 vp
= (struct vnode
*)fp
->f_data
;
1454 error
= copyin(argp
, (caddr_t
)&offset
, sizeof(off_t
));
1458 AUDIT_ARG(value64
, offset
);
1460 error
= vnode_getwithref(vp
);
1466 error
= mac_vnode_check_truncate(&context
,
1467 fp
->f_fglob
->fg_cred
, vp
);
1469 (void)vnode_put(vp
);
1474 * Make sure that we are root. Growing a file
1475 * without zero filling the data is a security hole
1476 * root would have access anyway so we'll allow it
1478 if (!kauth_cred_issuser(kauth_cred_get())) {
1484 error
= vnode_setsize(vp
, offset
, IO_NOZEROFILL
,
1489 mac_vnode_notify_truncate(&context
, fp
->f_fglob
->fg_cred
, vp
);
1494 (void)vnode_put(vp
);
1498 if (fp
->f_type
!= DTYPE_VNODE
) {
1503 fp
->f_fglob
->fg_flag
&= ~FNORDAHEAD
;
1505 fp
->f_fglob
->fg_flag
|= FNORDAHEAD
;
1511 if (fp
->f_type
!= DTYPE_VNODE
) {
1516 fp
->f_fglob
->fg_flag
|= FNOCACHE
;
1518 fp
->f_fglob
->fg_flag
&= ~FNOCACHE
;
1524 if (fp
->f_type
!= DTYPE_VNODE
) {
1529 fp
->f_fglob
->fg_flag
|= FNODIRECT
;
1531 fp
->f_fglob
->fg_flag
&= ~FNODIRECT
;
1536 case F_SINGLE_WRITER
:
1537 if (fp
->f_type
!= DTYPE_VNODE
) {
1542 fp
->f_fglob
->fg_flag
|= FSINGLE_WRITER
;
1544 fp
->f_fglob
->fg_flag
&= ~FSINGLE_WRITER
;
1549 case F_GLOBAL_NOCACHE
:
1550 if (fp
->f_type
!= DTYPE_VNODE
) {
1554 vp
= (struct vnode
*)fp
->f_data
;
1557 if ((error
= vnode_getwithref(vp
)) == 0) {
1558 *retval
= vnode_isnocache(vp
);
1561 vnode_setnocache(vp
);
1563 vnode_clearnocache(vp
);
1566 (void)vnode_put(vp
);
1570 case F_CHECK_OPENEVT
:
1571 if (fp
->f_type
!= DTYPE_VNODE
) {
1575 vp
= (struct vnode
*)fp
->f_data
;
1578 if ((error
= vnode_getwithref(vp
)) == 0) {
1579 *retval
= vnode_is_openevt(vp
);
1582 vnode_set_openevt(vp
);
1584 vnode_clear_openevt(vp
);
1587 (void)vnode_put(vp
);
1592 struct radvisory ra_struct
;
1594 if (fp
->f_type
!= DTYPE_VNODE
) {
1598 vp
= (struct vnode
*)fp
->f_data
;
1601 if ((error
= copyin(argp
, (caddr_t
)&ra_struct
, sizeof(ra_struct
)))) {
1604 if ((error
= vnode_getwithref(vp
)) == 0) {
1605 error
= VNOP_IOCTL(vp
, F_RDADVISE
, (caddr_t
)&ra_struct
, 0, &context
);
1607 (void)vnode_put(vp
);
1614 if (fp
->f_type
!= DTYPE_VNODE
) {
1618 vp
= (struct vnode
*)fp
->f_data
;
1621 if ((error
= vnode_getwithref(vp
)) == 0) {
1622 error
= VNOP_FSYNC(vp
, MNT_NOWAIT
, &context
);
1624 (void)vnode_put(vp
);
1629 case F_LOG2PHYS_EXT
: {
1630 struct log2phys l2p_struct
= {}; /* structure for allocate command */
1633 off_t file_offset
= 0;
1637 if (uap
->cmd
== F_LOG2PHYS_EXT
) {
1638 error
= copyin(argp
, (caddr_t
)&l2p_struct
, sizeof(l2p_struct
));
1642 file_offset
= l2p_struct
.l2p_devoffset
;
1644 file_offset
= fp
->f_offset
;
1646 if (fp
->f_type
!= DTYPE_VNODE
) {
1650 vp
= (struct vnode
*)fp
->f_data
;
1652 if ((error
= vnode_getwithref(vp
))) {
1655 error
= VNOP_OFFTOBLK(vp
, file_offset
, &lbn
);
1657 (void)vnode_put(vp
);
1660 error
= VNOP_BLKTOOFF(vp
, lbn
, &offset
);
1662 (void)vnode_put(vp
);
1665 devBlockSize
= vfs_devblocksize(vnode_mount(vp
));
1666 if (uap
->cmd
== F_LOG2PHYS_EXT
) {
1667 if (l2p_struct
.l2p_contigbytes
< 0) {
1673 a_size
= MIN((uint64_t)l2p_struct
.l2p_contigbytes
, SIZE_MAX
);
1675 a_size
= devBlockSize
;
1678 error
= VNOP_BLOCKMAP(vp
, offset
, a_size
, &bn
, &run
, NULL
, 0, &context
);
1680 (void)vnode_put(vp
);
1683 l2p_struct
.l2p_flags
= 0; /* for now */
1684 if (uap
->cmd
== F_LOG2PHYS_EXT
) {
1685 l2p_struct
.l2p_contigbytes
= run
- (file_offset
- offset
);
1687 l2p_struct
.l2p_contigbytes
= 0; /* for now */
1691 * The block number being -1 suggests that the file offset is not backed
1692 * by any real blocks on-disk. As a result, just let it be passed back up wholesale.
1695 /* Don't multiply it by the block size */
1696 l2p_struct
.l2p_devoffset
= bn
;
1698 l2p_struct
.l2p_devoffset
= bn
* devBlockSize
;
1699 l2p_struct
.l2p_devoffset
+= file_offset
- offset
;
1701 error
= copyout((caddr_t
)&l2p_struct
, argp
, sizeof(l2p_struct
));
1706 case F_GETPATH_NOFIRMLINK
: {
1710 if (fp
->f_type
!= DTYPE_VNODE
) {
1714 vp
= (struct vnode
*)fp
->f_data
;
1717 pathlen
= MAXPATHLEN
;
1718 MALLOC(pathbufp
, char *, pathlen
, M_TEMP
, M_WAITOK
);
1719 if (pathbufp
== NULL
) {
1723 if ((error
= vnode_getwithref(vp
)) == 0) {
1724 if (uap
->cmd
== F_GETPATH_NOFIRMLINK
) {
1725 error
= vn_getpath_ext(vp
, NULL
, pathbufp
, &pathlen
, VN_GETPATH_NO_FIRMLINK
);
1727 error
= vn_getpath(vp
, pathbufp
, &pathlen
);
1729 (void)vnode_put(vp
);
1732 error
= copyout((caddr_t
)pathbufp
, argp
, pathlen
);
1735 FREE(pathbufp
, M_TEMP
);
1739 case F_PATHPKG_CHECK
: {
1743 if (fp
->f_type
!= DTYPE_VNODE
) {
1747 vp
= (struct vnode
*)fp
->f_data
;
1750 pathlen
= MAXPATHLEN
;
1751 pathbufp
= kalloc(MAXPATHLEN
);
1753 if ((error
= copyinstr(argp
, pathbufp
, MAXPATHLEN
, &pathlen
)) == 0) {
1754 if ((error
= vnode_getwithref(vp
)) == 0) {
1755 AUDIT_ARG(text
, pathbufp
);
1756 error
= vn_path_package_check(vp
, pathbufp
, pathlen
, retval
);
1758 (void)vnode_put(vp
);
1761 kfree(pathbufp
, MAXPATHLEN
);
1765 case F_CHKCLEAN
: // used by regression tests to see if all dirty pages got cleaned by fsync()
1766 case F_FULLFSYNC
: // fsync + flush the journal + DKIOCSYNCHRONIZE
1767 case F_BARRIERFSYNC
: // fsync + barrier
1768 case F_FREEZE_FS
: // freeze all other fs operations for the fs of this fd
1769 case F_THAW_FS
: { // thaw all frozen fs operations for the fs of this fd
1770 if (fp
->f_type
!= DTYPE_VNODE
) {
1774 vp
= (struct vnode
*)fp
->f_data
;
1777 if ((error
= vnode_getwithref(vp
)) == 0) {
1778 error
= VNOP_IOCTL(vp
, uap
->cmd
, (caddr_t
)NULL
, 0, &context
);
1780 (void)vnode_put(vp
);
1786 * SPI (private) for opening a file starting from a dir fd
1789 struct user_fopenfrom fopen
;
1790 struct vnode_attr va
;
1791 struct nameidata nd
;
1794 /* Check if this isn't a valid file descriptor */
1795 if ((fp
->f_type
!= DTYPE_VNODE
) ||
1796 (fp
->f_flag
& FREAD
) == 0) {
1800 vp
= (struct vnode
*)fp
->f_data
;
1803 if (vnode_getwithref(vp
)) {
1808 /* Only valid for directories */
1809 if (vp
->v_type
!= VDIR
) {
1815 /* Get flags, mode and pathname arguments. */
1816 if (IS_64BIT_PROCESS(p
)) {
1817 error
= copyin(argp
, &fopen
, sizeof(fopen
));
1819 struct user32_fopenfrom fopen32
;
1821 error
= copyin(argp
, &fopen32
, sizeof(fopen32
));
1822 fopen
.o_flags
= fopen32
.o_flags
;
1823 fopen
.o_mode
= fopen32
.o_mode
;
1824 fopen
.o_pathname
= CAST_USER_ADDR_T(fopen32
.o_pathname
);
1830 AUDIT_ARG(fflags
, fopen
.o_flags
);
1831 AUDIT_ARG(mode
, fopen
.o_mode
);
1833 /* Mask off all but regular access permissions */
1834 cmode
= ((fopen
.o_mode
& ~fdp
->fd_cmask
) & ALLPERMS
) & ~S_ISTXT
;
1835 VATTR_SET(&va
, va_mode
, cmode
& ACCESSPERMS
);
1837 /* Start the lookup relative to the file descriptor's vnode. */
1838 NDINIT(&nd
, LOOKUP
, OP_OPEN
, USEDVP
| FOLLOW
| AUDITVNPATH1
, UIO_USERSPACE
,
1839 fopen
.o_pathname
, &context
);
1842 error
= open1(&context
, &nd
, fopen
.o_flags
, &va
,
1843 fileproc_alloc_init
, NULL
, retval
);
1849 * SPI (private) for unlinking a file starting from a dir fd
1851 case F_UNLINKFROM
: {
1852 user_addr_t pathname
;
1854 /* Check if this isn't a valid file descriptor */
1855 if ((fp
->f_type
!= DTYPE_VNODE
) ||
1856 (fp
->f_flag
& FREAD
) == 0) {
1860 vp
= (struct vnode
*)fp
->f_data
;
1863 if (vnode_getwithref(vp
)) {
1868 /* Only valid for directories */
1869 if (vp
->v_type
!= VDIR
) {
1875 /* Get flags, mode and pathname arguments. */
1876 if (IS_64BIT_PROCESS(p
)) {
1877 pathname
= (user_addr_t
)argp
;
1879 pathname
= CAST_USER_ADDR_T(argp
);
1882 /* Start the lookup relative to the file descriptor's vnode. */
1883 error
= unlink1(&context
, vp
, pathname
, UIO_USERSPACE
, 0);
1891 case F_ADDFILESIGS_FOR_DYLD_SIM
:
1892 case F_ADDFILESIGS_RETURN
:
1894 struct cs_blob
*blob
= NULL
;
1895 struct user_fsignatures fs
;
1897 vm_offset_t kernel_blob_addr
;
1898 vm_size_t kernel_blob_size
;
1899 int blob_add_flags
= 0;
1901 if (fp
->f_type
!= DTYPE_VNODE
) {
1905 vp
= (struct vnode
*)fp
->f_data
;
1908 if (uap
->cmd
== F_ADDFILESIGS_FOR_DYLD_SIM
) {
1909 blob_add_flags
|= MAC_VNODE_CHECK_DYLD_SIM
;
1910 if ((p
->p_csflags
& CS_KILL
) == 0) {
1912 p
->p_csflags
|= CS_KILL
;
1917 error
= vnode_getwithref(vp
);
1922 if (IS_64BIT_PROCESS(p
)) {
1923 error
= copyin(argp
, &fs
, sizeof(fs
));
1925 struct user32_fsignatures fs32
;
1927 error
= copyin(argp
, &fs32
, sizeof(fs32
));
1928 fs
.fs_file_start
= fs32
.fs_file_start
;
1929 fs
.fs_blob_start
= CAST_USER_ADDR_T(fs32
.fs_blob_start
);
1930 fs
.fs_blob_size
= fs32
.fs_blob_size
;
1939 * First check if we have something loaded a this offset
1941 blob
= ubc_cs_blob_get(vp
, CPU_TYPE_ANY
, fs
.fs_file_start
);
1943 /* If this is for dyld_sim revalidate the blob */
1944 if (uap
->cmd
== F_ADDFILESIGS_FOR_DYLD_SIM
) {
1945 error
= ubc_cs_blob_revalidate(vp
, blob
, NULL
, blob_add_flags
);
1948 if (error
!= EAGAIN
) {
1958 * An arbitrary limit, to prevent someone from mapping in a 20GB blob. This should cover
1959 * our use cases for the immediate future, but note that at the time of this commit, some
1960 * platforms are nearing 2MB blob sizes (with a prior soft limit of 2.5MB).
1962 * We should consider how we can manage this more effectively; the above means that some
1963 * platforms are using megabytes of memory for signing data; it merely hasn't crossed the
1964 * threshold considered ridiculous at the time of this change.
1966 #define CS_MAX_BLOB_SIZE (40ULL * 1024ULL * 1024ULL)
1967 if (fs
.fs_blob_size
> CS_MAX_BLOB_SIZE
) {
1973 kernel_blob_size
= CAST_DOWN(vm_size_t
, fs
.fs_blob_size
);
1974 kr
= ubc_cs_blob_allocate(&kernel_blob_addr
, &kernel_blob_size
);
1975 if (kr
!= KERN_SUCCESS
) {
1981 if (uap
->cmd
== F_ADDSIGS
) {
1982 error
= copyin(fs
.fs_blob_start
,
1983 (void *) kernel_blob_addr
,
1985 } else { /* F_ADDFILESIGS || F_ADDFILESIGS_RETURN || F_ADDFILESIGS_FOR_DYLD_SIM */
1988 error
= vn_rdwr(UIO_READ
,
1990 (caddr_t
) kernel_blob_addr
,
1992 fs
.fs_file_start
+ fs
.fs_blob_start
,
1998 if ((error
== 0) && resid
) {
1999 /* kernel_blob_size rounded to a page size, but signature may be at end of file */
2000 memset((void *)(kernel_blob_addr
+ (kernel_blob_size
- resid
)), 0x0, resid
);
2005 ubc_cs_blob_deallocate(kernel_blob_addr
,
2012 error
= ubc_cs_blob_add(vp
,
2013 CPU_TYPE_ANY
, /* not for a specific architecture */
2021 /* ubc_blob_add() has consumed "kernel_blob_addr" if it is zeroed */
2023 if (kernel_blob_addr
) {
2024 ubc_cs_blob_deallocate(kernel_blob_addr
,
2030 #if CHECK_CS_VALIDATION_BITMAP
2031 ubc_cs_validation_bitmap_allocate( vp
);
2036 if (uap
->cmd
== F_ADDFILESIGS_RETURN
|| uap
->cmd
== F_ADDFILESIGS_FOR_DYLD_SIM
) {
2038 * The first element of the structure is a
2039 * off_t that happen to have the same size for
2040 * all archs. Lets overwrite that.
2042 off_t end_offset
= 0;
2044 end_offset
= blob
->csb_end_offset
;
2046 error
= copyout(&end_offset
, argp
, sizeof(end_offset
));
2049 (void) vnode_put(vp
);
2058 struct fileglob
*fg
;
2061 if (fp
->f_type
!= DTYPE_VNODE
) {
2068 if (IS_64BIT_PROCESS(p
)) {
2069 error
= copyin(argp
, &lv
, sizeof(lv
));
2071 struct user32_fchecklv lv32
= {};
2073 error
= copyin(argp
, &lv32
, sizeof(lv32
));
2074 lv
.lv_file_start
= lv32
.lv_file_start
;
2075 lv
.lv_error_message
= (void *)(uintptr_t)lv32
.lv_error_message
;
2076 lv
.lv_error_message_size
= lv32
.lv_error_message_size
;
2083 error
= mac_file_check_library_validation(p
, fg
, lv
.lv_file_start
,
2084 (user_long_t
)lv
.lv_error_message
, lv
.lv_error_message_size
);
2090 case F_GETPROTECTIONCLASS
: {
2091 if (fp
->f_type
!= DTYPE_VNODE
) {
2095 vp
= (struct vnode
*)fp
->f_data
;
2099 if (vnode_getwithref(vp
)) {
2104 struct vnode_attr va
;
2107 VATTR_WANTED(&va
, va_dataprotect_class
);
2108 error
= VNOP_GETATTR(vp
, &va
, &context
);
2110 if (VATTR_IS_SUPPORTED(&va
, va_dataprotect_class
)) {
2111 *retval
= va
.va_dataprotect_class
;
2121 case F_SETPROTECTIONCLASS
: {
2122 /* tmp must be a valid PROTECTION_CLASS_* */
2123 tmp
= CAST_DOWN_EXPLICIT(uint32_t, uap
->arg
);
2125 if (fp
->f_type
!= DTYPE_VNODE
) {
2129 vp
= (struct vnode
*)fp
->f_data
;
2133 if (vnode_getwithref(vp
)) {
2138 /* Only go forward if you have write access */
2139 vfs_context_t ctx
= vfs_context_current();
2140 if (vnode_authorize(vp
, NULLVP
, (KAUTH_VNODE_ACCESS
| KAUTH_VNODE_WRITE_DATA
), ctx
) != 0) {
2146 struct vnode_attr va
;
2149 VATTR_SET(&va
, va_dataprotect_class
, tmp
);
2151 error
= VNOP_SETATTR(vp
, &va
, ctx
);
2157 case F_TRANSCODEKEY
: {
2158 if (fp
->f_type
!= DTYPE_VNODE
) {
2163 vp
= (struct vnode
*)fp
->f_data
;
2166 if (vnode_getwithref(vp
)) {
2172 .len
= CP_MAX_WRAPPEDKEYSIZE
,
2175 MALLOC(k
.key
, char *, k
.len
, M_TEMP
, M_WAITOK
| M_ZERO
);
2177 error
= VNOP_IOCTL(vp
, F_TRANSCODEKEY
, (caddr_t
)&k
, 1, &context
);
2182 error
= copyout(k
.key
, argp
, k
.len
);
2186 FREE(k
.key
, M_TEMP
);
2191 case F_GETPROTECTIONLEVEL
: {
2192 if (fp
->f_type
!= DTYPE_VNODE
) {
2197 vp
= (struct vnode
*) fp
->f_data
;
2200 if (vnode_getwithref(vp
)) {
2205 error
= VNOP_IOCTL(vp
, F_GETPROTECTIONLEVEL
, (caddr_t
)retval
, 0, &context
);
2211 case F_GETDEFAULTPROTLEVEL
: {
2212 if (fp
->f_type
!= DTYPE_VNODE
) {
2217 vp
= (struct vnode
*) fp
->f_data
;
2220 if (vnode_getwithref(vp
)) {
2226 * if cp_get_major_vers fails, error will be set to proper errno
2227 * and cp_version will still be 0.
2230 error
= VNOP_IOCTL(vp
, F_GETDEFAULTPROTLEVEL
, (caddr_t
)retval
, 0, &context
);
2236 #endif /* CONFIG_PROTECT */
2238 case F_MOVEDATAEXTENTS
: {
2239 struct fileproc
*fp2
= NULL
;
2240 struct vnode
*src_vp
= NULLVP
;
2241 struct vnode
*dst_vp
= NULLVP
;
2242 /* We need to grab the 2nd FD out of the argments before moving on. */
2243 int fd2
= CAST_DOWN_EXPLICIT(int32_t, uap
->arg
);
2245 error
= priv_check_cred(kauth_cred_get(), PRIV_VFS_MOVE_DATA_EXTENTS
, 0);
2250 if (fp
->f_type
!= DTYPE_VNODE
) {
2256 * For now, special case HFS+ and APFS only, since this
2259 src_vp
= (struct vnode
*)fp
->f_data
;
2260 if (src_vp
->v_tag
!= VT_HFS
&& src_vp
->v_tag
!= VT_APFS
) {
2266 * Get the references before we start acquiring iocounts on the vnodes,
2267 * while we still hold the proc fd lock
2269 if ((error
= fp_lookup(p
, fd2
, &fp2
, 1))) {
2273 if (fp2
->f_type
!= DTYPE_VNODE
) {
2274 fp_drop(p
, fd2
, fp2
, 1);
2278 dst_vp
= (struct vnode
*)fp2
->f_data
;
2279 if (dst_vp
->v_tag
!= VT_HFS
&& dst_vp
->v_tag
!= VT_APFS
) {
2280 fp_drop(p
, fd2
, fp2
, 1);
2286 /* Re-do MAC checks against the new FD, pass in a fake argument */
2287 error
= mac_file_check_fcntl(proc_ucred(p
), fp2
->f_fglob
, uap
->cmd
, 0);
2289 fp_drop(p
, fd2
, fp2
, 1);
2293 /* Audit the 2nd FD */
2298 if (vnode_getwithref(src_vp
)) {
2299 fp_drop(p
, fd2
, fp2
, 0);
2303 if (vnode_getwithref(dst_vp
)) {
2305 fp_drop(p
, fd2
, fp2
, 0);
2311 * Basic asserts; validate they are not the same and that
2312 * both live on the same filesystem.
2314 if (dst_vp
== src_vp
) {
2317 fp_drop(p
, fd2
, fp2
, 0);
2322 if (dst_vp
->v_mount
!= src_vp
->v_mount
) {
2325 fp_drop(p
, fd2
, fp2
, 0);
2330 /* Now we have a legit pair of FDs. Go to work */
2332 /* Now check for write access to the target files */
2333 if (vnode_authorize(src_vp
, NULLVP
,
2334 (KAUTH_VNODE_ACCESS
| KAUTH_VNODE_WRITE_DATA
), &context
) != 0) {
2337 fp_drop(p
, fd2
, fp2
, 0);
2342 if (vnode_authorize(dst_vp
, NULLVP
,
2343 (KAUTH_VNODE_ACCESS
| KAUTH_VNODE_WRITE_DATA
), &context
) != 0) {
2346 fp_drop(p
, fd2
, fp2
, 0);
2351 /* Verify that both vps point to files and not directories */
2352 if (!vnode_isreg(src_vp
) || !vnode_isreg(dst_vp
)) {
2356 fp_drop(p
, fd2
, fp2
, 0);
2361 * The exchangedata syscall handler passes in 0 for the flags to VNOP_EXCHANGE.
2362 * We'll pass in our special bit indicating that the new behavior is expected
2365 error
= VNOP_EXCHANGE(src_vp
, dst_vp
, FSOPT_EXCHANGE_DATA_ONLY
, &context
);
2369 fp_drop(p
, fd2
, fp2
, 0);
2374 * SPI for making a file compressed.
2376 case F_MAKECOMPRESSED
: {
2377 uint32_t gcounter
= CAST_DOWN_EXPLICIT(uint32_t, uap
->arg
);
2379 if (fp
->f_type
!= DTYPE_VNODE
) {
2384 vp
= (struct vnode
*) fp
->f_data
;
2388 if (vnode_getwithref(vp
)) {
2394 if ((vnode_isreg(vp
) == 0) && (vnode_islnk(vp
) == 0)) {
2400 /* invoke ioctl to pass off to FS */
2401 /* Only go forward if you have write access */
2402 vfs_context_t ctx
= vfs_context_current();
2403 if (vnode_authorize(vp
, NULLVP
, (KAUTH_VNODE_ACCESS
| KAUTH_VNODE_WRITE_DATA
), ctx
) != 0) {
2409 error
= VNOP_IOCTL(vp
, uap
->cmd
, (caddr_t
)&gcounter
, 0, &context
);
2416 * SPI (private) for indicating to a filesystem that subsequent writes to
2417 * the open FD will written to the Fastflow.
2419 case F_SET_GREEDY_MODE
:
2420 /* intentionally drop through to the same handler as F_SETSTATIC.
2421 * both fcntls should pass the argument and their selector into VNOP_IOCTL.
2425 * SPI (private) for indicating to a filesystem that subsequent writes to
2426 * the open FD will represent static content.
2428 case F_SETSTATICCONTENT
: {
2429 caddr_t ioctl_arg
= NULL
;
2432 ioctl_arg
= (caddr_t
) 1;
2435 if (fp
->f_type
!= DTYPE_VNODE
) {
2439 vp
= (struct vnode
*)fp
->f_data
;
2442 error
= vnode_getwithref(vp
);
2448 /* Only go forward if you have write access */
2449 vfs_context_t ctx
= vfs_context_current();
2450 if (vnode_authorize(vp
, NULLVP
, (KAUTH_VNODE_ACCESS
| KAUTH_VNODE_WRITE_DATA
), ctx
) != 0) {
2456 error
= VNOP_IOCTL(vp
, uap
->cmd
, ioctl_arg
, 0, &context
);
2457 (void)vnode_put(vp
);
2463 * SPI (private) for indicating to the lower level storage driver that the
2464 * subsequent writes should be of a particular IO type (burst, greedy, static),
2465 * or other flavors that may be necessary.
2472 /* extract 32 bits of flags from userland */
2473 param_ptr
= (caddr_t
) uap
->arg
;
2474 param
= (uint32_t) param_ptr
;
2476 /* If no argument is specified, error out */
2482 * Validate the different types of flags that can be specified:
2483 * all of them are mutually exclusive for now.
2486 case F_IOTYPE_ISOCHRONOUS
:
2495 if (fp
->f_type
!= DTYPE_VNODE
) {
2499 vp
= (struct vnode
*)fp
->f_data
;
2502 error
= vnode_getwithref(vp
);
2508 /* Only go forward if you have write access */
2509 vfs_context_t ctx
= vfs_context_current();
2510 if (vnode_authorize(vp
, NULLVP
, (KAUTH_VNODE_ACCESS
| KAUTH_VNODE_WRITE_DATA
), ctx
) != 0) {
2516 error
= VNOP_IOCTL(vp
, uap
->cmd
, param_ptr
, 0, &context
);
2517 (void)vnode_put(vp
);
2523 * Set the vnode pointed to by 'fd'
2524 * and tag it as the (potentially future) backing store
2525 * for another filesystem
2527 case F_SETBACKINGSTORE
: {
2528 if (fp
->f_type
!= DTYPE_VNODE
) {
2533 vp
= (struct vnode
*)fp
->f_data
;
2535 if (vp
->v_tag
!= VT_HFS
) {
2541 if (vnode_getwithref(vp
)) {
2546 /* only proceed if you have write access */
2547 vfs_context_t ctx
= vfs_context_current();
2548 if (vnode_authorize(vp
, NULLVP
, (KAUTH_VNODE_ACCESS
| KAUTH_VNODE_WRITE_DATA
), ctx
) != 0) {
2555 /* If arg != 0, set, otherwise unset */
2557 error
= VNOP_IOCTL(vp
, uap
->cmd
, (caddr_t
)1, 0, &context
);
2559 error
= VNOP_IOCTL(vp
, uap
->cmd
, (caddr_t
)NULL
, 0, &context
);
2567 * like F_GETPATH, but special semantics for
2568 * the mobile time machine handler.
2570 case F_GETPATH_MTMINFO
: {
2574 if (fp
->f_type
!= DTYPE_VNODE
) {
2578 vp
= (struct vnode
*)fp
->f_data
;
2581 pathlen
= MAXPATHLEN
;
2582 MALLOC(pathbufp
, char *, pathlen
, M_TEMP
, M_WAITOK
);
2583 if (pathbufp
== NULL
) {
2587 if ((error
= vnode_getwithref(vp
)) == 0) {
2588 int backingstore
= 0;
2590 /* Check for error from vn_getpath before moving on */
2591 if ((error
= vn_getpath(vp
, pathbufp
, &pathlen
)) == 0) {
2592 if (vp
->v_tag
== VT_HFS
) {
2593 error
= VNOP_IOCTL(vp
, uap
->cmd
, (caddr_t
) &backingstore
, 0, &context
);
2595 (void)vnode_put(vp
);
2598 error
= copyout((caddr_t
)pathbufp
, argp
, pathlen
);
2602 * If the copyout was successful, now check to ensure
2603 * that this vnode is not a BACKINGSTORE vnode. mtmd
2604 * wants the path regardless.
2611 (void)vnode_put(vp
);
2614 FREE(pathbufp
, M_TEMP
);
2618 #if DEBUG || DEVELOPMENT
2620 if (fp
->f_type
!= DTYPE_VNODE
) {
2624 vp
= (struct vnode
*)fp
->f_data
;
2633 * This is an fcntl() that we d not recognize at this level;
2634 * if this is a vnode, we send it down into the VNOP_IOCTL
2635 * for this vnode; this can include special devices, and will
2636 * effectively overload fcntl() to send ioctl()'s.
2638 if ((uap
->cmd
& IOC_VOID
) && (uap
->cmd
& IOC_INOUT
)) {
2643 /* Catch any now-invalid fcntl() selectors */
2645 case (int)APFSIOC_REVERT_TO_SNAPSHOT
:
2646 case (int)FSIOC_FIOSEEKHOLE
:
2647 case (int)FSIOC_FIOSEEKDATA
:
2648 case (int)FSIOC_CAS_BSDFLAGS
:
2649 case HFS_GET_BOOT_INFO
:
2650 case HFS_SET_BOOT_INFO
:
2652 case F_MARKDEPENDENCY
:
2660 if (fp
->f_type
!= DTYPE_VNODE
) {
2664 vp
= (struct vnode
*)fp
->f_data
;
2667 if ((error
= vnode_getwithref(vp
)) == 0) {
2668 #define STK_PARAMS 128
2669 char stkbuf
[STK_PARAMS
] = {0};
2673 * For this to work properly, we have to copy in the
2674 * ioctl() cmd argument if there is one; we must also
2675 * check that a command parameter, if present, does
2676 * not exceed the maximum command length dictated by
2677 * the number of bits we have available in the command
2678 * to represent a structure length. Finally, we have
2679 * to copy the results back out, if it is that type of
2682 size
= IOCPARM_LEN(uap
->cmd
);
2683 if (size
> IOCPARM_MAX
) {
2684 (void)vnode_put(vp
);
2690 if (size
> sizeof(stkbuf
)) {
2691 if ((memp
= (caddr_t
)kalloc(size
)) == 0) {
2692 (void)vnode_put(vp
);
2701 if (uap
->cmd
& IOC_IN
) {
2704 error
= copyin(argp
, data
, size
);
2706 (void)vnode_put(vp
);
2713 /* Bzero the section beyond that which was needed */
2714 if (size
<= sizeof(stkbuf
)) {
2715 bzero((((uint8_t*)data
) + size
), (sizeof(stkbuf
) - size
));
2720 *(user_addr_t
*)data
= argp
;
2722 *(uint32_t *)data
= (uint32_t)argp
;
2725 } else if ((uap
->cmd
& IOC_OUT
) && size
) {
2727 * Zero the buffer so the user always
2728 * gets back something deterministic.
2731 } else if (uap
->cmd
& IOC_VOID
) {
2733 *(user_addr_t
*)data
= argp
;
2735 *(uint32_t *)data
= (uint32_t)argp
;
2739 error
= VNOP_IOCTL(vp
, uap
->cmd
, CAST_DOWN(caddr_t
, data
), 0, &context
);
2741 (void)vnode_put(vp
);
2743 /* Copy any output data to user */
2744 if (error
== 0 && (uap
->cmd
& IOC_OUT
) && size
) {
2745 error
= copyout(data
, argp
, size
);
2755 AUDIT_ARG(vnpath_withref
, vp
, ARG_VNODE1
);
2756 fp_drop(p
, fd
, fp
, 0);
2759 fp_drop(p
, fd
, fp
, 1);
2768 * Description: Common code for dup, dup2, and fcntl(F_DUPFD).
2770 * Parameters: p Process performing the dup
2772 * new The fd to dup it to
2773 * fd_flags Flags to augment the new fd
2774 * retval Pointer to the call return area
2776 * Returns: 0 Success
2781 * *retval (modified) The new descriptor
2783 * Locks: Assumes proc_fdlock for process pointing to fdp is held by
2786 * Notes: This function may drop and reacquire this lock; it is unsafe
2787 * for a caller to assume that other state protected by the lock
2788 * has not been subsequently changed out from under it.
2792 struct filedesc
*fdp
, int old
, int new, int fd_flags
, int32_t *retval
)
2794 struct fileproc
*nfp
;
2795 struct fileproc
*ofp
;
2801 proc_fdlock_assert(p
, LCK_MTX_ASSERT_OWNED
);
2803 if ((ofp
= fdp
->fd_ofiles
[old
]) == NULL
||
2804 (fdp
->fd_ofileflags
[old
] & UF_RESERVED
)) {
2811 error
= mac_file_check_dup(proc_ucred(p
), ofp
->f_fglob
, new);
2821 nfp
= fileproc_alloc_init(NULL
);
2831 nfp
->f_fglob
= ofp
->f_fglob
;
2834 if (fdp
->fd_ofiles
[new] != 0) {
2835 panic("finishdup: overwriting fd_ofiles with new %d", new);
2837 if ((fdp
->fd_ofileflags
[new] & UF_RESERVED
) == 0) {
2838 panic("finishdup: unreserved fileflags with new %d", new);
2842 if (new > fdp
->fd_lastfile
) {
2843 fdp
->fd_lastfile
= new;
2845 *fdflags(p
, new) |= fd_flags
;
2846 procfdtbl_releasefd(p
, new, nfp
);
2855 * Description: The implementation of the close(2) system call
2857 * Parameters: p Process in whose per process file table
2858 * the close is to occur
2859 * uap->fd fd to be closed
2862 * Returns: 0 Success
2863 * fp_lookup:EBADF Bad file descriptor
2864 * fp_guard_exception:??? Guarded file descriptor
2865 * close_internal:EBADF
2866 * close_internal:??? Anything returnable by a per-fileops
2870 close(proc_t p
, struct close_args
*uap
, int32_t *retval
)
2872 __pthread_testcancel(1);
2873 return close_nocancel(p
, (struct close_nocancel_args
*)uap
, retval
);
2878 close_nocancel(proc_t p
, struct close_nocancel_args
*uap
, __unused
int32_t *retval
)
2880 struct fileproc
*fp
;
2884 AUDIT_SYSCLOSE(p
, fd
);
2888 if ((error
= fp_lookup(p
, fd
, &fp
, 1))) {
2893 if (FP_ISGUARDED(fp
, GUARD_CLOSE
)) {
2894 error
= fp_guard_exception(p
, fd
, fp
, kGUARD_EXC_CLOSE
);
2895 (void) fp_drop(p
, fd
, fp
, 1);
2900 error
= close_internal_locked(p
, fd
, fp
, 0);
2909 * close_internal_locked
2911 * Close a file descriptor.
2913 * Parameters: p Process in whose per process file table
2914 * the close is to occur
2915 * fd fd to be closed
2916 * fp fileproc associated with the fd
2918 * Returns: 0 Success
2919 * EBADF fd already in close wait state
2920 * closef_locked:??? Anything returnable by a per-fileops
2923 * Locks: Assumes proc_fdlock for process is held by the caller and returns
2926 * Notes: This function may drop and reacquire this lock; it is unsafe
2927 * for a caller to assume that other state protected by the lock
2928 * has not been subsequently changed out from under it.
2931 close_internal_locked(proc_t p
, int fd
, struct fileproc
*fp
, int flags
)
2933 struct filedesc
*fdp
= p
->p_fd
;
2935 int resvfd
= flags
& FD_DUP2RESV
;
2939 proc_fdlock_assert(p
, LCK_MTX_ASSERT_OWNED
);
2942 /* Keep people from using the filedesc while we are closing it */
2943 procfdtbl_markclosefd(p
, fd
);
2946 if ((fp
->f_flags
& FP_CLOSING
) == FP_CLOSING
) {
2947 panic("close_internal_locked: being called on already closing fd");
2952 if ((fdp
->fd_ofileflags
[fd
] & UF_RESERVED
) == 0) {
2953 panic("close_internal: unreserved fileflags with fd %d", fd
);
2957 fp
->f_flags
|= FP_CLOSING
;
2959 if ((fp
->f_flags
& FP_AIOISSUED
) || kauth_authorize_fileop_has_listeners()) {
2962 if ((fp
->f_type
== DTYPE_VNODE
) && kauth_authorize_fileop_has_listeners()) {
2964 * call out to allow 3rd party notification of close.
2965 * Ignore result of kauth_authorize_fileop call.
2967 if (vnode_getwithref((vnode_t
)fp
->f_data
) == 0) {
2968 u_int fileop_flags
= 0;
2969 if ((fp
->f_flags
& FP_WRITTEN
) != 0) {
2970 fileop_flags
|= KAUTH_FILEOP_CLOSE_MODIFIED
;
2972 kauth_authorize_fileop(fp
->f_fglob
->fg_cred
, KAUTH_FILEOP_CLOSE
,
2973 (uintptr_t)fp
->f_data
, (uintptr_t)fileop_flags
);
2974 vnode_put((vnode_t
)fp
->f_data
);
2977 if (fp
->f_flags
& FP_AIOISSUED
) {
2979 * cancel all async IO requests that can be cancelled.
2981 _aio_close( p
, fd
);
2987 if (fd
< fdp
->fd_knlistsize
) {
2988 knote_fdclose(p
, fd
);
2991 /* release the ref returned from fp_lookup before calling drain */
2992 (void) os_ref_release_locked(&fp
->f_iocount
);
2993 fileproc_drain(p
, fp
);
2995 if (fp
->f_flags
& FP_WAITEVENT
) {
2996 (void)waitevent_close(p
, fp
);
3002 procfdtbl_reservefd(p
, fd
);
3005 if (ENTR_SHOULDTRACE
&& fp
->f_type
== DTYPE_SOCKET
) {
3006 KERNEL_ENERGYTRACE(kEnTrActKernSocket
, DBG_FUNC_END
,
3007 fd
, 0, (int64_t)VM_KERNEL_ADDRPERM(fp
->f_data
));
3010 error
= closef_locked(fp
, fp
->f_fglob
, p
);
3011 if ((fp
->f_flags
& FP_WAITCLOSE
) == FP_WAITCLOSE
) {
3012 wakeup(&fp
->f_flags
);
3014 fp
->f_flags
&= ~(FP_WAITCLOSE
| FP_CLOSING
);
3024 if ((fdp
->fd_ofileflags
[fd
] & UF_RESERVED
) == 0) {
3025 panic("close with reserved fd returns with freed fd:%d: proc: %p", fd
, p
);
3037 * Description: Return status information about a file descriptor.
3039 * Parameters: p The process doing the fstat
3041 * ub The user stat buffer
3042 * xsecurity The user extended security
3043 * buffer, or 0 if none
3044 * xsecurity_size The size of xsecurity, or 0
3046 * isstat64 Flag to indicate 64 bit version
3047 * for inode size, etc.
3049 * Returns: 0 Success
3052 * fp_lookup:EBADF Bad file descriptor
3053 * vnode_getwithref:???
3055 * vnode_getwithref:???
3062 * Notes: Internal implementation for all other fstat() related
3065 * XXX switch on node type is bogus; need a stat in struct
3066 * XXX fileops instead.
3069 fstat1(proc_t p
, int fd
, user_addr_t ub
, user_addr_t xsecurity
, user_addr_t xsecurity_size
, int isstat64
)
3071 struct fileproc
*fp
;
3077 struct user64_stat user64_sb
;
3078 struct user32_stat user32_sb
;
3079 struct user64_stat64 user64_sb64
;
3080 struct user32_stat64 user32_sb64
;
3085 kauth_filesec_t fsec
;
3086 user_size_t xsecurity_bufsize
;
3087 vfs_context_t ctx
= vfs_context_current();
3093 if ((error
= fp_lookup(p
, fd
, &fp
, 0)) != 0) {
3098 fsec
= KAUTH_FILESEC_NONE
;
3100 sbptr
= (void *)&source
;
3104 if ((error
= vnode_getwithref((vnode_t
)data
)) == 0) {
3106 * If the caller has the file open, and is not
3107 * requesting extended security information, we are
3108 * going to let them get the basic stat information.
3110 if (xsecurity
== USER_ADDR_NULL
) {
3111 error
= vn_stat_noauth((vnode_t
)data
, sbptr
, NULL
, isstat64
, 0, ctx
,
3112 fp
->f_fglob
->fg_cred
);
3114 error
= vn_stat((vnode_t
)data
, sbptr
, &fsec
, isstat64
, 0, ctx
);
3117 AUDIT_ARG(vnpath
, (struct vnode
*)data
, ARG_VNODE1
);
3118 (void)vnode_put((vnode_t
)data
);
3124 error
= soo_stat((struct socket
*)data
, sbptr
, isstat64
);
3126 #endif /* SOCKETS */
3129 error
= pipe_stat((void *)data
, sbptr
, isstat64
);
3133 error
= pshm_stat((void *)data
, sbptr
, isstat64
);
3137 error
= kqueue_stat((void *)data
, sbptr
, isstat64
, p
);
3147 if (isstat64
!= 0) {
3148 source
.sb64
.st_lspare
= 0;
3149 source
.sb64
.st_qspare
[0] = 0LL;
3150 source
.sb64
.st_qspare
[1] = 0LL;
3152 if (IS_64BIT_PROCESS(current_proc())) {
3153 munge_user64_stat64(&source
.sb64
, &dest
.user64_sb64
);
3154 my_size
= sizeof(dest
.user64_sb64
);
3155 sbp
= (caddr_t
)&dest
.user64_sb64
;
3157 munge_user32_stat64(&source
.sb64
, &dest
.user32_sb64
);
3158 my_size
= sizeof(dest
.user32_sb64
);
3159 sbp
= (caddr_t
)&dest
.user32_sb64
;
3162 source
.sb
.st_lspare
= 0;
3163 source
.sb
.st_qspare
[0] = 0LL;
3164 source
.sb
.st_qspare
[1] = 0LL;
3165 if (IS_64BIT_PROCESS(current_proc())) {
3166 munge_user64_stat(&source
.sb
, &dest
.user64_sb
);
3167 my_size
= sizeof(dest
.user64_sb
);
3168 sbp
= (caddr_t
)&dest
.user64_sb
;
3170 munge_user32_stat(&source
.sb
, &dest
.user32_sb
);
3171 my_size
= sizeof(dest
.user32_sb
);
3172 sbp
= (caddr_t
)&dest
.user32_sb
;
3176 error
= copyout(sbp
, ub
, my_size
);
3179 /* caller wants extended security information? */
3180 if (xsecurity
!= USER_ADDR_NULL
) {
3181 /* did we get any? */
3182 if (fsec
== KAUTH_FILESEC_NONE
) {
3183 if (susize(xsecurity_size
, 0) != 0) {
3188 /* find the user buffer size */
3189 xsecurity_bufsize
= fusize(xsecurity_size
);
3191 /* copy out the actual data size */
3192 if (susize(xsecurity_size
, KAUTH_FILESEC_COPYSIZE(fsec
)) != 0) {
3197 /* if the caller supplied enough room, copy out to it */
3198 if (xsecurity_bufsize
>= KAUTH_FILESEC_COPYSIZE(fsec
)) {
3199 error
= copyout(fsec
, xsecurity
, KAUTH_FILESEC_COPYSIZE(fsec
));
3204 fp_drop(p
, fd
, fp
, 0);
3206 kauth_filesec_free(fsec
);
3215 * Description: Extended version of fstat supporting returning extended
3216 * security information
3218 * Parameters: p The process doing the fstat
3219 * uap->fd The fd to stat
3220 * uap->ub The user stat buffer
3221 * uap->xsecurity The user extended security
3222 * buffer, or 0 if none
3223 * uap->xsecurity_size The size of xsecurity, or 0
3225 * Returns: 0 Success
3226 * !0 Errno (see fstat1)
3229 fstat_extended(proc_t p
, struct fstat_extended_args
*uap
, __unused
int32_t *retval
)
3231 return fstat1(p
, uap
->fd
, uap
->ub
, uap
->xsecurity
, uap
->xsecurity_size
, 0);
3238 * Description: Get file status for the file associated with fd
3240 * Parameters: p The process doing the fstat
3241 * uap->fd The fd to stat
3242 * uap->ub The user stat buffer
3244 * Returns: 0 Success
3245 * !0 Errno (see fstat1)
3248 fstat(proc_t p
, struct fstat_args
*uap
, __unused
int32_t *retval
)
3250 return fstat1(p
, uap
->fd
, uap
->ub
, 0, 0, 0);
3257 * Description: Extended version of fstat64 supporting returning extended
3258 * security information
3260 * Parameters: p The process doing the fstat
3261 * uap->fd The fd to stat
3262 * uap->ub The user stat buffer
3263 * uap->xsecurity The user extended security
3264 * buffer, or 0 if none
3265 * uap->xsecurity_size The size of xsecurity, or 0
3267 * Returns: 0 Success
3268 * !0 Errno (see fstat1)
3271 fstat64_extended(proc_t p
, struct fstat64_extended_args
*uap
, __unused
int32_t *retval
)
3273 return fstat1(p
, uap
->fd
, uap
->ub
, uap
->xsecurity
, uap
->xsecurity_size
, 1);
3280 * Description: Get 64 bit version of the file status for the file associated
3283 * Parameters: p The process doing the fstat
3284 * uap->fd The fd to stat
3285 * uap->ub The user stat buffer
3287 * Returns: 0 Success
3288 * !0 Errno (see fstat1)
3291 fstat64(proc_t p
, struct fstat64_args
*uap
, __unused
int32_t *retval
)
3293 return fstat1(p
, uap
->fd
, uap
->ub
, 0, 0, 1);
3300 * Description: Return pathconf information about a file descriptor.
3302 * Parameters: p Process making the request
3303 * uap->fd fd to get information about
3304 * uap->name Name of information desired
3305 * retval Pointer to the call return area
3307 * Returns: 0 Success
3309 * fp_lookup:EBADF Bad file descriptor
3310 * vnode_getwithref:???
3314 * *retval (modified) Returned information (numeric)
3317 fpathconf(proc_t p
, struct fpathconf_args
*uap
, int32_t *retval
)
3320 struct fileproc
*fp
;
3327 AUDIT_ARG(fd
, uap
->fd
);
3328 if ((error
= fp_lookup(p
, fd
, &fp
, 0))) {
3336 if (uap
->name
!= _PC_PIPE_BUF
) {
3345 if (uap
->name
!= _PC_PIPE_BUF
) {
3354 vp
= (struct vnode
*)data
;
3356 if ((error
= vnode_getwithref(vp
)) == 0) {
3357 AUDIT_ARG(vnpath
, vp
, ARG_VNODE1
);
3359 error
= vn_pathconf(vp
, uap
->name
, retval
, vfs_context_current());
3361 (void)vnode_put(vp
);
3371 fp_drop(p
, fd
, fp
, 0);
3376 * Statistics counter for the number of times a process calling fdalloc()
3377 * has resulted in an expansion of the per process open file table.
3379 * XXX This would likely be of more use if it were per process
3387 * Description: Allocate a file descriptor for the process.
3389 * Parameters: p Process to allocate the fd in
3390 * want The fd we would prefer to get
3391 * result Pointer to fd we got
3393 * Returns: 0 Success
3398 * *result (modified) The fd which was allocated
3401 fdalloc(proc_t p
, int want
, int *result
)
3403 struct filedesc
*fdp
= p
->p_fd
;
3405 int lim
, last
, numfiles
, oldnfiles
;
3406 struct fileproc
**newofiles
, **ofiles
;
3407 char *newofileflags
;
3410 * Search for a free descriptor starting at the higher
3411 * of want or fd_freefile. If that fails, consider
3412 * expanding the ofile array.
3415 proc_fdlock_assert(p
, LCK_MTX_ASSERT_OWNED
);
3418 lim
= min((int)p
->p_rlimit
[RLIMIT_NOFILE
].rlim_cur
, maxfiles
);
3420 last
= min(fdp
->fd_nfiles
, lim
);
3421 if ((i
= want
) < fdp
->fd_freefile
) {
3422 i
= fdp
->fd_freefile
;
3424 for (; i
< last
; i
++) {
3425 if (fdp
->fd_ofiles
[i
] == NULL
&& !(fdp
->fd_ofileflags
[i
] & UF_RESERVED
)) {
3426 procfdtbl_reservefd(p
, i
);
3427 if (i
> fdp
->fd_lastfile
) {
3428 fdp
->fd_lastfile
= i
;
3430 if (want
<= fdp
->fd_freefile
) {
3431 fdp
->fd_freefile
= i
;
3439 * No space in current array. Expand?
3441 if (fdp
->fd_nfiles
>= lim
) {
3444 if (fdp
->fd_nfiles
< NDEXTENT
) {
3445 numfiles
= NDEXTENT
;
3447 numfiles
= 2 * fdp
->fd_nfiles
;
3450 if (numfiles
> lim
) {
3454 MALLOC_ZONE(newofiles
, struct fileproc
**,
3455 numfiles
* OFILESIZE
, M_OFILETABL
, M_WAITOK
);
3457 if (newofiles
== NULL
) {
3460 if (fdp
->fd_nfiles
>= numfiles
) {
3461 FREE_ZONE(newofiles
, numfiles
* OFILESIZE
, M_OFILETABL
);
3464 newofileflags
= (char *) &newofiles
[numfiles
];
3466 * Copy the existing ofile and ofileflags arrays
3467 * and zero the new portion of each array.
3469 oldnfiles
= fdp
->fd_nfiles
;
3470 (void) memcpy(newofiles
, fdp
->fd_ofiles
,
3471 oldnfiles
* sizeof(*fdp
->fd_ofiles
));
3472 (void) memset(&newofiles
[oldnfiles
], 0,
3473 (numfiles
- oldnfiles
) * sizeof(*fdp
->fd_ofiles
));
3475 (void) memcpy(newofileflags
, fdp
->fd_ofileflags
,
3476 oldnfiles
* sizeof(*fdp
->fd_ofileflags
));
3477 (void) memset(&newofileflags
[oldnfiles
], 0,
3478 (numfiles
- oldnfiles
) *
3479 sizeof(*fdp
->fd_ofileflags
));
3480 ofiles
= fdp
->fd_ofiles
;
3481 fdp
->fd_ofiles
= newofiles
;
3482 fdp
->fd_ofileflags
= newofileflags
;
3483 fdp
->fd_nfiles
= numfiles
;
3484 FREE_ZONE(ofiles
, oldnfiles
* OFILESIZE
, M_OFILETABL
);
3493 * Description: Check to see whether n user file descriptors are available
3496 * Parameters: p Process to check in
3497 * n The number of fd's desired
3502 * Locks: Assumes proc_fdlock for process is held by the caller
3504 * Notes: The answer only remains valid so long as the proc_fdlock is
3505 * held by the caller.
3508 fdavail(proc_t p
, int n
)
3510 struct filedesc
*fdp
= p
->p_fd
;
3511 struct fileproc
**fpp
;
3515 lim
= min((int)p
->p_rlimit
[RLIMIT_NOFILE
].rlim_cur
, maxfiles
);
3516 if ((i
= lim
- fdp
->fd_nfiles
) > 0 && (n
-= i
) <= 0) {
3519 fpp
= &fdp
->fd_ofiles
[fdp
->fd_freefile
];
3520 flags
= &fdp
->fd_ofileflags
[fdp
->fd_freefile
];
3521 for (i
= fdp
->fd_nfiles
- fdp
->fd_freefile
; --i
>= 0; fpp
++, flags
++) {
3522 if (*fpp
== NULL
&& !(*flags
& UF_RESERVED
) && --n
<= 0) {
3533 * Description: Legacy KPI wrapper function for _fdrelse
3535 * Parameters: p Process in which fd lives
3540 * Locks: Assumes proc_fdlock for process is held by the caller
3543 fdrelse(proc_t p
, int fd
)
3552 * Description: Get the fileproc pointer for the given fd from the per process
3553 * open file table without taking an explicit reference on it.
3555 * Parameters: p Process containing fd
3556 * fd fd to obtain fileproc for
3557 * resultfp Pointer to pointer return area
3559 * Returns: 0 Success
3563 * *resultfp (modified) Pointer to fileproc pointer
3565 * Locks: Assumes proc_fdlock for process is held by the caller
3567 * Notes: Because there is no reference explicitly taken, the returned
3568 * fileproc pointer is only valid so long as the proc_fdlock
3569 * remains held by the caller.
3572 fdgetf_noref(proc_t p
, int fd
, struct fileproc
**resultfp
)
3574 struct filedesc
*fdp
= p
->p_fd
;
3575 struct fileproc
*fp
;
3577 if (fd
< 0 || fd
>= fdp
->fd_nfiles
||
3578 (fp
= fdp
->fd_ofiles
[fd
]) == NULL
||
3579 (fdp
->fd_ofileflags
[fd
] & UF_RESERVED
)) {
3592 * Description: Get fileproc and vnode pointer for a given fd from the per
3593 * process open file table of the specified process, and if
3594 * successful, increment the f_iocount
3596 * Parameters: p Process in which fd lives
3597 * fd fd to get information for
3598 * resultfp Pointer to result fileproc
3599 * pointer area, or 0 if none
3600 * resultvp Pointer to result vnode pointer
3601 * area, or 0 if none
3603 * Returns: 0 Success
3604 * EBADF Bad file descriptor
3605 * ENOTSUP fd does not refer to a vnode
3608 * *resultfp (modified) Fileproc pointer
3609 * *resultvp (modified) vnode pointer
3611 * Notes: The resultfp and resultvp fields are optional, and may be
3612 * independently specified as NULL to skip returning information
3614 * Locks: Internally takes and releases proc_fdlock
3617 fp_getfvp(proc_t p
, int fd
, struct fileproc
**resultfp
, struct vnode
**resultvp
)
3619 struct filedesc
*fdp
= p
->p_fd
;
3620 struct fileproc
*fp
;
3622 proc_fdlock_spin(p
);
3623 if (fd
< 0 || fd
>= fdp
->fd_nfiles
||
3624 (fp
= fdp
->fd_ofiles
[fd
]) == NULL
||
3625 (fdp
->fd_ofileflags
[fd
] & UF_RESERVED
)) {
3629 if (fp
->f_type
!= DTYPE_VNODE
) {
3633 os_ref_retain_locked(&fp
->f_iocount
);
3639 *resultvp
= (struct vnode
*)fp
->f_data
;
3650 * Description: Get fileproc, vnode pointer, and vid for a given fd from the
3651 * per process open file table of the specified process, and if
3652 * successful, increment the f_iocount
3654 * Parameters: p Process in which fd lives
3655 * fd fd to get information for
3656 * resultfp Pointer to result fileproc
3657 * pointer area, or 0 if none
3658 * resultvp Pointer to result vnode pointer
3659 * area, or 0 if none
3660 * vidp Pointer to resuld vid area
3662 * Returns: 0 Success
3663 * EBADF Bad file descriptor
3664 * ENOTSUP fd does not refer to a vnode
3667 * *resultfp (modified) Fileproc pointer
3668 * *resultvp (modified) vnode pointer
3671 * Notes: The resultfp and resultvp fields are optional, and may be
3672 * independently specified as NULL to skip returning information
3674 * Locks: Internally takes and releases proc_fdlock
3677 fp_getfvpandvid(proc_t p
, int fd
, struct fileproc
**resultfp
,
3678 struct vnode
**resultvp
, uint32_t *vidp
)
3680 struct filedesc
*fdp
= p
->p_fd
;
3681 struct fileproc
*fp
;
3683 proc_fdlock_spin(p
);
3684 if (fd
< 0 || fd
>= fdp
->fd_nfiles
||
3685 (fp
= fdp
->fd_ofiles
[fd
]) == NULL
||
3686 (fdp
->fd_ofileflags
[fd
] & UF_RESERVED
)) {
3690 if (fp
->f_type
!= DTYPE_VNODE
) {
3694 os_ref_retain_locked(&fp
->f_iocount
);
3700 *resultvp
= (struct vnode
*)fp
->f_data
;
3703 *vidp
= (uint32_t)vnode_vid((struct vnode
*)fp
->f_data
);
3714 * Description: Get fileproc and socket pointer for a given fd from the
3715 * per process open file table of the specified process, and if
3716 * successful, increment the f_iocount
3718 * Parameters: p Process in which fd lives
3719 * fd fd to get information for
3720 * resultfp Pointer to result fileproc
3721 * pointer area, or 0 if none
3722 * results Pointer to result socket
3723 * pointer area, or 0 if none
3725 * Returns: EBADF The file descriptor is invalid
3726 * EOPNOTSUPP The file descriptor is not a socket
3730 * *resultfp (modified) Fileproc pointer
3731 * *results (modified) socket pointer
3733 * Notes: EOPNOTSUPP should probably be ENOTSOCK; this function is only
3734 * ever called from accept1().
3737 fp_getfsock(proc_t p
, int fd
, struct fileproc
**resultfp
,
3738 struct socket
**results
)
3740 struct filedesc
*fdp
= p
->p_fd
;
3741 struct fileproc
*fp
;
3743 proc_fdlock_spin(p
);
3744 if (fd
< 0 || fd
>= fdp
->fd_nfiles
||
3745 (fp
= fdp
->fd_ofiles
[fd
]) == NULL
||
3746 (fdp
->fd_ofileflags
[fd
] & UF_RESERVED
)) {
3750 if (fp
->f_type
!= DTYPE_SOCKET
) {
3754 os_ref_retain_locked(&fp
->f_iocount
);
3760 *results
= (struct socket
*)fp
->f_data
;
3771 * Description: Get fileproc and kqueue pointer for a given fd from the
3772 * per process open file table of the specified process, and if
3773 * successful, increment the f_iocount
3775 * Parameters: p Process in which fd lives
3776 * fd fd to get information for
3777 * resultfp Pointer to result fileproc
3778 * pointer area, or 0 if none
3779 * resultkq Pointer to result kqueue
3780 * pointer area, or 0 if none
3782 * Returns: EBADF The file descriptor is invalid
3783 * EBADF The file descriptor is not a socket
3787 * *resultfp (modified) Fileproc pointer
3788 * *resultkq (modified) kqueue pointer
3790 * Notes: The second EBADF should probably be something else to make
3791 * the error condition distinct.
3794 fp_getfkq(proc_t p
, int fd
, struct fileproc
**resultfp
,
3795 struct kqueue
**resultkq
)
3797 struct filedesc
*fdp
= p
->p_fd
;
3798 struct fileproc
*fp
;
3800 proc_fdlock_spin(p
);
3801 if (fd
< 0 || fd
>= fdp
->fd_nfiles
||
3802 (fp
= fdp
->fd_ofiles
[fd
]) == NULL
||
3803 (fdp
->fd_ofileflags
[fd
] & UF_RESERVED
)) {
3807 if (fp
->f_type
!= DTYPE_KQUEUE
) {
3811 os_ref_retain_locked(&fp
->f_iocount
);
3817 *resultkq
= (struct kqueue
*)fp
->f_data
;
3828 * Description: Get fileproc and POSIX shared memory pointer for a given fd
3829 * from the per process open file table of the specified process
3830 * and if successful, increment the f_iocount
3832 * Parameters: p Process in which fd lives
3833 * fd fd to get information for
3834 * resultfp Pointer to result fileproc
3835 * pointer area, or 0 if none
3836 * resultpshm Pointer to result POSIX
3837 * shared memory pointer
3838 * pointer area, or 0 if none
3840 * Returns: EBADF The file descriptor is invalid
3841 * EBADF The file descriptor is not a POSIX
3842 * shared memory area
3846 * *resultfp (modified) Fileproc pointer
3847 * *resultpshm (modified) POSIX shared memory pointer
3849 * Notes: The second EBADF should probably be something else to make
3850 * the error condition distinct.
3853 fp_getfpshm(proc_t p
, int fd
, struct fileproc
**resultfp
,
3854 struct pshmnode
**resultpshm
)
3856 struct filedesc
*fdp
= p
->p_fd
;
3857 struct fileproc
*fp
;
3859 proc_fdlock_spin(p
);
3860 if (fd
< 0 || fd
>= fdp
->fd_nfiles
||
3861 (fp
= fdp
->fd_ofiles
[fd
]) == NULL
||
3862 (fdp
->fd_ofileflags
[fd
] & UF_RESERVED
)) {
3866 if (fp
->f_type
!= DTYPE_PSXSHM
) {
3870 os_ref_retain_locked(&fp
->f_iocount
);
3876 *resultpshm
= (struct pshmnode
*)fp
->f_data
;
3887 * Description: Get fileproc and POSIX semaphore pointer for a given fd from
3888 * the per process open file table of the specified process
3889 * and if successful, increment the f_iocount
3891 * Parameters: p Process in which fd lives
3892 * fd fd to get information for
3893 * resultfp Pointer to result fileproc
3894 * pointer area, or 0 if none
3895 * resultpsem Pointer to result POSIX
3896 * semaphore pointer area, or
3899 * Returns: EBADF The file descriptor is invalid
3900 * EBADF The file descriptor is not a POSIX
3905 * *resultfp (modified) Fileproc pointer
3906 * *resultpsem (modified) POSIX semaphore pointer
3908 * Notes: The second EBADF should probably be something else to make
3909 * the error condition distinct.
3911 * In order to support unnamed POSIX semaphores, the named
3912 * POSIX semaphores will have to move out of the per-process
3913 * open filetable, and into a global table that is shared with
3914 * unnamed POSIX semaphores, since unnamed POSIX semaphores
3915 * are typically used by declaring instances in shared memory,
3916 * and there's no other way to do this without changing the
3917 * underlying type, which would introduce binary compatibility
3921 fp_getfpsem(proc_t p
, int fd
, struct fileproc
**resultfp
,
3922 struct psemnode
**resultpsem
)
3924 struct filedesc
*fdp
= p
->p_fd
;
3925 struct fileproc
*fp
;
3927 proc_fdlock_spin(p
);
3928 if (fd
< 0 || fd
>= fdp
->fd_nfiles
||
3929 (fp
= fdp
->fd_ofiles
[fd
]) == NULL
||
3930 (fdp
->fd_ofileflags
[fd
] & UF_RESERVED
)) {
3934 if (fp
->f_type
!= DTYPE_PSXSEM
) {
3938 os_ref_retain_locked(&fp
->f_iocount
);
3944 *resultpsem
= (struct psemnode
*)fp
->f_data
;
3955 * Description: Get fileproc and pipe pointer for a given fd from the
3956 * per process open file table of the specified process
3957 * and if successful, increment the f_iocount
3959 * Parameters: p Process in which fd lives
3960 * fd fd to get information for
3961 * resultfp Pointer to result fileproc
3962 * pointer area, or 0 if none
3963 * resultpipe Pointer to result pipe
3964 * pointer area, or 0 if none
3966 * Returns: EBADF The file descriptor is invalid
3967 * EBADF The file descriptor is not a socket
3971 * *resultfp (modified) Fileproc pointer
3972 * *resultpipe (modified) pipe pointer
3974 * Notes: The second EBADF should probably be something else to make
3975 * the error condition distinct.
3978 fp_getfpipe(proc_t p
, int fd
, struct fileproc
**resultfp
,
3979 struct pipe
**resultpipe
)
3981 struct filedesc
*fdp
= p
->p_fd
;
3982 struct fileproc
*fp
;
3984 proc_fdlock_spin(p
);
3985 if (fd
< 0 || fd
>= fdp
->fd_nfiles
||
3986 (fp
= fdp
->fd_ofiles
[fd
]) == NULL
||
3987 (fdp
->fd_ofileflags
[fd
] & UF_RESERVED
)) {
3991 if (fp
->f_type
!= DTYPE_PIPE
) {
3995 os_ref_retain_locked(&fp
->f_iocount
);
4001 *resultpipe
= (struct pipe
*)fp
->f_data
;
4012 * Description: Get fileproc pointer for a given fd from the per process
4013 * open file table of the specified process and if successful,
4014 * increment the f_iocount
4016 * Parameters: p Process in which fd lives
4017 * fd fd to get information for
4018 * resultfp Pointer to result fileproc
4019 * pointer area, or 0 if none
4020 * locked !0 if the caller holds the
4021 * proc_fdlock, 0 otherwise
4023 * Returns: 0 Success
4024 * EBADF Bad file descriptor
4027 * *resultfp (modified) Fileproc pointer
4029 * Locks: If the argument 'locked' is non-zero, then the caller is
4030 * expected to have taken and held the proc_fdlock; if it is
4031 * zero, than this routine internally takes and drops this lock.
4034 fp_lookup(proc_t p
, int fd
, struct fileproc
**resultfp
, int locked
)
4036 struct filedesc
*fdp
= p
->p_fd
;
4037 struct fileproc
*fp
;
4040 proc_fdlock_spin(p
);
4042 if (fd
< 0 || fdp
== NULL
|| fd
>= fdp
->fd_nfiles
||
4043 (fp
= fdp
->fd_ofiles
[fd
]) == NULL
||
4044 (fdp
->fd_ofileflags
[fd
] & UF_RESERVED
)) {
4050 os_ref_retain_locked(&fp
->f_iocount
);
4066 * Description: Swap the fileproc pointer for a given fd with a new
4067 * fileproc pointer in the per-process open file table of
4068 * the specified process. The fdlock must be held at entry.
4069 * Iff the swap is successful, the old fileproc pointer is freed.
4071 * Parameters: p Process containing the fd
4072 * fd The fd of interest
4073 * nfp Pointer to the newfp
4075 * Returns: 0 Success
4076 * EBADF Bad file descriptor
4078 * EKEEPLOOKING Other references were active, try again.
4081 fp_tryswap(proc_t p
, int fd
, struct fileproc
*nfp
)
4083 struct fileproc
*fp
;
4086 proc_fdlock_assert(p
, LCK_MTX_ASSERT_OWNED
);
4088 if (0 != (error
= fp_lookup(p
, fd
, &fp
, 1))) {
4092 * At this point, our caller (change_guardedfd_np) has
4093 * one f_iocount reference, and we just took another
4094 * one to begin the replacement.
4095 * fp and nfp have a +1 reference from allocation.
4096 * Thus if no-one else is looking, f_iocount should be 3.
4098 if (os_ref_get_count(&fp
->f_iocount
) < 3 ||
4099 1 != os_ref_get_count(&nfp
->f_iocount
)) {
4100 panic("%s: f_iocount", __func__
);
4101 } else if (3 == os_ref_get_count(&fp
->f_iocount
)) {
4102 /* Copy the contents of *fp, preserving the "type" of *nfp */
4104 nfp
->f_flags
= (nfp
->f_flags
& FP_TYPEMASK
) |
4105 (fp
->f_flags
& ~FP_TYPEMASK
);
4106 os_ref_retain_locked(&nfp
->f_iocount
);
4107 os_ref_retain_locked(&nfp
->f_iocount
);
4108 nfp
->f_fglob
= fp
->f_fglob
;
4109 nfp
->f_wset
= fp
->f_wset
;
4111 p
->p_fd
->fd_ofiles
[fd
] = nfp
;
4112 fp_drop(p
, fd
, nfp
, 1);
4114 os_ref_release_live(&fp
->f_iocount
);
4115 os_ref_release_live(&fp
->f_iocount
);
4119 * Wait for all other active references to evaporate.
4121 p
->p_fpdrainwait
= 1;
4122 error
= msleep(&p
->p_fpdrainwait
, &p
->p_fdmlock
,
4123 PRIBIO
| PCATCH
, "tryswap fpdrain", NULL
);
4126 * Return an "internal" errno to trigger a full
4127 * reevaluation of the change-guard attempt.
4129 error
= EKEEPLOOKING
;
4131 (void) fp_drop(p
, fd
, fp
, 1);
4140 * Description: Set the FP_WRITTEN flag on the fileproc and drop the I/O
4141 * reference previously taken by calling fp_lookup et. al.
4143 * Parameters: p Process in which the fd lives
4144 * fd fd associated with the fileproc
4145 * fp fileproc on which to set the
4146 * flag and drop the reference
4148 * Returns: 0 Success
4149 * fp_drop:EBADF Bad file descriptor
4151 * Locks: This function internally takes and drops the proc_fdlock for
4152 * the supplied process
4154 * Notes: The fileproc must correspond to the fd in the supplied proc
4157 fp_drop_written(proc_t p
, int fd
, struct fileproc
*fp
)
4161 proc_fdlock_spin(p
);
4163 fp
->f_flags
|= FP_WRITTEN
;
4165 error
= fp_drop(p
, fd
, fp
, 1);
4176 * Description: Set the FP_WAITEVENT flag on the fileproc and drop the I/O
4177 * reference previously taken by calling fp_lookup et. al.
4179 * Parameters: p Process in which the fd lives
4180 * fd fd associated with the fileproc
4181 * fp fileproc on which to set the
4182 * flag and drop the reference
4184 * Returns: 0 Success
4185 * fp_drop:EBADF Bad file descriptor
4187 * Locks: This function internally takes and drops the proc_fdlock for
4188 * the supplied process
4190 * Notes: The fileproc must correspond to the fd in the supplied proc
4193 fp_drop_event(proc_t p
, int fd
, struct fileproc
*fp
)
4197 proc_fdlock_spin(p
);
4199 fp
->f_flags
|= FP_WAITEVENT
;
4201 error
= fp_drop(p
, fd
, fp
, 1);
4212 * Description: Drop the I/O reference previously taken by calling fp_lookup
4215 * Parameters: p Process in which the fd lives
4216 * fd fd associated with the fileproc
4217 * fp fileproc on which to set the
4218 * flag and drop the reference
4219 * locked flag to internally take and
4220 * drop proc_fdlock if it is not
4221 * already held by the caller
4223 * Returns: 0 Success
4224 * EBADF Bad file descriptor
4226 * Locks: This function internally takes and drops the proc_fdlock for
4227 * the supplied process if 'locked' is non-zero, and assumes that
4228 * the caller already holds this lock if 'locked' is non-zero.
4230 * Notes: The fileproc must correspond to the fd in the supplied proc
4233 fp_drop(proc_t p
, int fd
, struct fileproc
*fp
, int locked
)
4235 struct filedesc
*fdp
= p
->p_fd
;
4239 proc_fdlock_spin(p
);
4241 if ((fp
== FILEPROC_NULL
) && (fd
< 0 || fd
>= fdp
->fd_nfiles
||
4242 (fp
= fdp
->fd_ofiles
[fd
]) == NULL
||
4243 ((fdp
->fd_ofileflags
[fd
] & UF_RESERVED
) &&
4244 !(fdp
->fd_ofileflags
[fd
] & UF_CLOSING
)))) {
4251 if (1 == os_ref_release_locked(&fp
->f_iocount
)) {
4252 if (fp
->f_flags
& FP_SELCONFLICT
) {
4253 fp
->f_flags
&= ~FP_SELCONFLICT
;
4256 if (p
->p_fpdrainwait
) {
4257 p
->p_fpdrainwait
= 0;
4265 wakeup(&p
->p_fpdrainwait
);
4275 * Description: Given an fd, look it up in the current process's per process
4276 * open file table, and return its internal vnode pointer.
4278 * Parameters: fd fd to obtain vnode from
4279 * vpp pointer to vnode return area
4281 * Returns: 0 Success
4282 * EINVAL The fd does not refer to a
4283 * vnode fileproc entry
4284 * fp_lookup:EBADF Bad file descriptor
4287 * *vpp (modified) Returned vnode pointer
4289 * Locks: This function internally takes and drops the proc_fdlock for
4290 * the current process
4292 * Notes: If successful, this function increments the f_iocount on the
4293 * fd's corresponding fileproc.
4295 * The fileproc referenced is not returned; because of this, care
4296 * must be taken to not drop the last reference (e.g. by closing
4297 * the file). This is inherently unsafe, since the reference may
4298 * not be recoverable from the vnode, if there is a subsequent
4299 * close that destroys the associate fileproc. The caller should
4300 * therefore retain their own reference on the fileproc so that
4301 * the f_iocount can be dropped subsequently. Failure to do this
4302 * can result in the returned pointer immediately becoming invalid
4303 * following the call.
4305 * Use of this function is discouraged.
4308 file_vnode(int fd
, struct vnode
**vpp
)
4310 proc_t p
= current_proc();
4311 struct fileproc
*fp
;
4314 proc_fdlock_spin(p
);
4315 if ((error
= fp_lookup(p
, fd
, &fp
, 1))) {
4319 if (fp
->f_type
!= DTYPE_VNODE
) {
4320 fp_drop(p
, fd
, fp
, 1);
4325 *vpp
= (struct vnode
*)fp
->f_data
;
4334 * file_vnode_withvid
4336 * Description: Given an fd, look it up in the current process's per process
4337 * open file table, and return its internal vnode pointer.
4339 * Parameters: fd fd to obtain vnode from
4340 * vpp pointer to vnode return area
4341 * vidp pointer to vid of the returned vnode
4343 * Returns: 0 Success
4344 * EINVAL The fd does not refer to a
4345 * vnode fileproc entry
4346 * fp_lookup:EBADF Bad file descriptor
4349 * *vpp (modified) Returned vnode pointer
4351 * Locks: This function internally takes and drops the proc_fdlock for
4352 * the current process
4354 * Notes: If successful, this function increments the f_iocount on the
4355 * fd's corresponding fileproc.
4357 * The fileproc referenced is not returned; because of this, care
4358 * must be taken to not drop the last reference (e.g. by closing
4359 * the file). This is inherently unsafe, since the reference may
4360 * not be recoverable from the vnode, if there is a subsequent
4361 * close that destroys the associate fileproc. The caller should
4362 * therefore retain their own reference on the fileproc so that
4363 * the f_iocount can be dropped subsequently. Failure to do this
4364 * can result in the returned pointer immediately becoming invalid
4365 * following the call.
4367 * Use of this function is discouraged.
4370 file_vnode_withvid(int fd
, struct vnode
**vpp
, uint32_t * vidp
)
4372 proc_t p
= current_proc();
4373 struct fileproc
*fp
;
4377 proc_fdlock_spin(p
);
4378 if ((error
= fp_lookup(p
, fd
, &fp
, 1))) {
4382 if (fp
->f_type
!= DTYPE_VNODE
) {
4383 fp_drop(p
, fd
, fp
, 1);
4387 vp
= (struct vnode
*)fp
->f_data
;
4392 if ((vidp
!= NULL
) && (vp
!= NULLVP
)) {
4393 *vidp
= (uint32_t)vp
->v_id
;
4405 * Description: Given an fd, look it up in the current process's per process
4406 * open file table, and return its internal socket pointer.
4408 * Parameters: fd fd to obtain vnode from
4409 * sp pointer to socket return area
4411 * Returns: 0 Success
4412 * ENOTSOCK Not a socket
4413 * fp_lookup:EBADF Bad file descriptor
4416 * *sp (modified) Returned socket pointer
4418 * Locks: This function internally takes and drops the proc_fdlock for
4419 * the current process
4421 * Notes: If successful, this function increments the f_iocount on the
4422 * fd's corresponding fileproc.
4424 * The fileproc referenced is not returned; because of this, care
4425 * must be taken to not drop the last reference (e.g. by closing
4426 * the file). This is inherently unsafe, since the reference may
4427 * not be recoverable from the socket, if there is a subsequent
4428 * close that destroys the associate fileproc. The caller should
4429 * therefore retain their own reference on the fileproc so that
4430 * the f_iocount can be dropped subsequently. Failure to do this
4431 * can result in the returned pointer immediately becoming invalid
4432 * following the call.
4434 * Use of this function is discouraged.
4437 file_socket(int fd
, struct socket
**sp
)
4439 proc_t p
= current_proc();
4440 struct fileproc
*fp
;
4443 proc_fdlock_spin(p
);
4444 if ((error
= fp_lookup(p
, fd
, &fp
, 1))) {
4448 if (fp
->f_type
!= DTYPE_SOCKET
) {
4449 fp_drop(p
, fd
, fp
, 1);
4453 *sp
= (struct socket
*)fp
->f_data
;
4463 * Description: Given an fd, look it up in the current process's per process
4464 * open file table, and return its fileproc's flags field.
4466 * Parameters: fd fd whose flags are to be
4468 * flags pointer to flags data area
4470 * Returns: 0 Success
4471 * ENOTSOCK Not a socket
4472 * fp_lookup:EBADF Bad file descriptor
4475 * *flags (modified) Returned flags field
4477 * Locks: This function internally takes and drops the proc_fdlock for
4478 * the current process
4480 * Notes: This function will internally increment and decrement the
4481 * f_iocount of the fileproc as part of its operation.
4484 file_flags(int fd
, int *flags
)
4486 proc_t p
= current_proc();
4487 struct fileproc
*fp
;
4490 proc_fdlock_spin(p
);
4491 if ((error
= fp_lookup(p
, fd
, &fp
, 1))) {
4495 *flags
= (int)fp
->f_flag
;
4496 fp_drop(p
, fd
, fp
, 1);
4506 * Description: Drop an iocount reference on an fd, and wake up any waiters
4507 * for draining (i.e. blocked in fileproc_drain() called during
4508 * the last attempt to close a file).
4510 * Parameters: fd fd on which an ioreference is
4513 * Returns: 0 Success
4514 * EBADF Bad file descriptor
4516 * Description: Given an fd, look it up in the current process's per process
4517 * open file table, and drop it's fileproc's f_iocount by one
4519 * Notes: This is intended as a corresponding operation to the functions
4520 * file_vnode() and file_socket() operations.
4522 * Technically, the close reference is supposed to be protected
4523 * by a fileproc_drain(), however, a drain will only block if
4524 * the fd refers to a character device, and that device has had
4525 * preparefileread() called on it. If it refers to something
4526 * other than a character device, then the drain will occur and
4527 * block each close attempt, rather than merely the last close.
4529 * Since it's possible for an fd that refers to a character
4530 * device to have an intermediate close followed by an open to
4531 * cause a different file to correspond to that descriptor,
4532 * unless there was a cautionary reference taken on the fileproc,
4533 * this is an inherently unsafe function. This happens in the
4534 * case where multiple fd's in a process refer to the same
4535 * character device (e.g. stdin/out/err pointing to a tty, etc.).
4537 * Use of this function is discouraged.
4542 struct fileproc
*fp
;
4543 proc_t p
= current_proc();
4546 proc_fdlock_spin(p
);
4547 if (fd
< 0 || fd
>= p
->p_fd
->fd_nfiles
||
4548 (fp
= p
->p_fd
->fd_ofiles
[fd
]) == NULL
||
4549 ((p
->p_fd
->fd_ofileflags
[fd
] & UF_RESERVED
) &&
4550 !(p
->p_fd
->fd_ofileflags
[fd
] & UF_CLOSING
))) {
4555 if (1 == os_ref_release_locked(&fp
->f_iocount
)) {
4556 if (fp
->f_flags
& FP_SELCONFLICT
) {
4557 fp
->f_flags
&= ~FP_SELCONFLICT
;
4560 if (p
->p_fpdrainwait
) {
4561 p
->p_fpdrainwait
= 0;
4568 wakeup(&p
->p_fpdrainwait
);
4574 static int falloc_withalloc_locked(proc_t
, struct fileproc
**, int *,
4575 vfs_context_t
, struct fileproc
* (*)(void *), void *, int);
4580 * Description: Allocate an entry in the per process open file table and
4581 * return the corresponding fileproc and fd.
4583 * Parameters: p The process in whose open file
4584 * table the fd is to be allocated
4585 * resultfp Pointer to fileproc pointer
4587 * resultfd Pointer to fd return area
4590 * Returns: 0 Success
4591 * falloc:ENFILE Too many open files in system
4592 * falloc:EMFILE Too many open files in process
4593 * falloc:ENOMEM M_FILEPROC or M_FILEGLOB zone
4597 * *resultfd (modified) Returned fileproc pointer
4598 * *resultfd (modified) Returned fd
4600 * Locks: This function takes and drops the proc_fdlock; if this lock
4601 * is already held, use falloc_locked() instead.
4603 * Notes: This function takes separate process and context arguments
4604 * solely to support kern_exec.c; otherwise, it would take
4605 * neither, and expect falloc_locked() to use the
4606 * vfs_context_current() routine internally.
4609 falloc(proc_t p
, struct fileproc
**resultfp
, int *resultfd
, vfs_context_t ctx
)
4611 return falloc_withalloc(p
, resultfp
, resultfd
, ctx
,
4612 fileproc_alloc_init
, NULL
);
4616 * Like falloc, but including the fileproc allocator and create-args
4619 falloc_withalloc(proc_t p
, struct fileproc
**resultfp
, int *resultfd
,
4620 vfs_context_t ctx
, fp_allocfn_t fp_zalloc
, void *arg
)
4625 error
= falloc_withalloc_locked(p
,
4626 resultfp
, resultfd
, ctx
, fp_zalloc
, arg
, 1);
4633 * "uninitialized" ops -- ensure fg->fg_ops->fo_type always exists
4635 static const struct fileops uninitops
;
4640 * Create a new open file structure and allocate
4641 * a file descriptor for the process that refers to it.
4643 * Returns: 0 Success
4645 * Description: Allocate an entry in the per process open file table and
4646 * return the corresponding fileproc and fd.
4648 * Parameters: p The process in whose open file
4649 * table the fd is to be allocated
4650 * resultfp Pointer to fileproc pointer
4652 * resultfd Pointer to fd return area
4654 * locked Flag to indicate whether the
4655 * caller holds proc_fdlock
4657 * Returns: 0 Success
4658 * ENFILE Too many open files in system
4659 * fdalloc:EMFILE Too many open files in process
4660 * ENOMEM M_FILEPROC or M_FILEGLOB zone
4665 * *resultfd (modified) Returned fileproc pointer
4666 * *resultfd (modified) Returned fd
4668 * Locks: If the parameter 'locked' is zero, this function takes and
4669 * drops the proc_fdlock; if non-zero, the caller must hold the
4672 * Notes: If you intend to use a non-zero 'locked' parameter, use the
4673 * utility function falloc() instead.
4675 * This function takes separate process and context arguments
4676 * solely to support kern_exec.c; otherwise, it would take
4677 * neither, and use the vfs_context_current() routine internally.
4680 falloc_locked(proc_t p
, struct fileproc
**resultfp
, int *resultfd
,
4681 vfs_context_t ctx
, int locked
)
4683 return falloc_withalloc_locked(p
, resultfp
, resultfd
, ctx
,
4684 fileproc_alloc_init
, NULL
, locked
);
4688 falloc_withalloc_locked(proc_t p
, struct fileproc
**resultfp
, int *resultfd
,
4689 vfs_context_t ctx
, fp_allocfn_t fp_zalloc
, void *crarg
,
4692 struct fileproc
*fp
;
4693 struct fileglob
*fg
;
4696 if (nfiles
>= maxfiles
) {
4705 if ((error
= fdalloc(p
, 0, &nfd
))) {
4713 error
= mac_file_check_create(proc_ucred(p
));
4723 * Allocate a new file descriptor.
4724 * If the process has file descriptor zero open, add to the list
4725 * of open files at that point, otherwise put it at the front of
4726 * the list of open files.
4730 fp
= (*fp_zalloc
)(crarg
);
4737 MALLOC_ZONE(fg
, struct fileglob
*, sizeof(struct fileglob
), M_FILEGLOB
, M_WAITOK
);
4745 bzero(fg
, sizeof(struct fileglob
));
4746 lck_mtx_init(&fg
->fg_lock
, file_lck_grp
, file_lck_attr
);
4748 os_ref_retain_locked(&fp
->f_iocount
);
4750 fg
->fg_ops
= &uninitops
;
4753 mac_file_label_init(fg
);
4756 kauth_cred_ref(ctx
->vc_ucred
);
4760 fp
->f_cred
= ctx
->vc_ucred
;
4763 mac_file_label_associate(fp
->f_cred
, fg
);
4766 OSAddAtomic(1, &nfiles
);
4768 p
->p_fd
->fd_ofiles
[nfd
] = fp
;
4788 * Description: Free a file structure; drop the global open file count, and
4789 * drop the credential reference, if the fileglob has one, and
4790 * destroy the instance mutex before freeing
4792 * Parameters: fg Pointer to fileglob to be
4798 fg_free(struct fileglob
*fg
)
4800 OSAddAtomic(-1, &nfiles
);
4802 if (fg
->fg_vn_data
) {
4803 fg_vn_data_free(fg
->fg_vn_data
);
4804 fg
->fg_vn_data
= NULL
;
4807 if (IS_VALID_CRED(fg
->fg_cred
)) {
4808 kauth_cred_unref(&fg
->fg_cred
);
4810 lck_mtx_destroy(&fg
->fg_lock
, file_lck_grp
);
4813 mac_file_label_destroy(fg
);
4815 FREE_ZONE(fg
, sizeof *fg
, M_FILEGLOB
);
4822 * Description: Return vnode associated with the file structure, if
4823 * any. The lifetime of the returned vnode is bound to
4824 * the lifetime of the file structure.
4826 * Parameters: fg Pointer to fileglob to
4832 fg_get_vnode(struct fileglob
*fg
)
4834 if (FILEGLOB_DTYPE(fg
) == DTYPE_VNODE
) {
4835 return (vnode_t
)fg
->fg_data
;
4844 * Description: Perform close-on-exec processing for all files in a process
4845 * that are either marked as close-on-exec, or which were in the
4846 * process of being opened at the time of the execve
4848 * Also handles the case (via posix_spawn()) where -all-
4849 * files except those marked with "inherit" as treated as
4852 * Parameters: p Pointer to process calling
4857 * Locks: This function internally takes and drops proc_fdlock()
4858 * But assumes tables don't grow/change while unlocked.
4862 fdexec(proc_t p
, short flags
, int self_exec
)
4864 struct filedesc
*fdp
= p
->p_fd
;
4866 boolean_t cloexec_default
= (flags
& POSIX_SPAWN_CLOEXEC_DEFAULT
) != 0;
4867 thread_t self
= current_thread();
4868 struct uthread
*ut
= get_bsdthread_info(self
);
4869 struct kqworkq
*dealloc_kqwq
= NULL
;
4872 * If the current thread is bound as a workq/workloop
4873 * servicing thread, we need to unbind it first.
4875 if (ut
->uu_kqr_bound
&& self_exec
) {
4876 kqueue_threadreq_unbind(p
, ut
->uu_kqr_bound
);
4882 * Deallocate the knotes for this process
4883 * and mark the tables non-existent so
4884 * subsequent kqueue closes go faster.
4887 assert(fdp
->fd_knlistsize
== 0);
4888 assert(fdp
->fd_knhashmask
== 0);
4890 for (i
= fdp
->fd_lastfile
; i
>= 0; i
--) {
4891 struct fileproc
*fp
= fdp
->fd_ofiles
[i
];
4892 char *flagp
= &fdp
->fd_ofileflags
[i
];
4894 if (fp
&& cloexec_default
) {
4896 * Reverse the usual semantics of file descriptor
4897 * inheritance - all of them should be closed
4898 * except files marked explicitly as "inherit" and
4899 * not marked close-on-exec.
4901 if ((*flagp
& (UF_EXCLOSE
| UF_INHERIT
)) != UF_INHERIT
) {
4902 *flagp
|= UF_EXCLOSE
;
4904 *flagp
&= ~UF_INHERIT
;
4908 ((*flagp
& (UF_RESERVED
| UF_EXCLOSE
)) == UF_EXCLOSE
)
4910 || (fp
&& mac_file_check_inherit(proc_ucred(p
), fp
->f_fglob
))
4913 procfdtbl_clearfd(p
, i
);
4914 if (i
== fdp
->fd_lastfile
&& i
> 0) {
4917 if (i
< fdp
->fd_freefile
) {
4918 fdp
->fd_freefile
= i
;
4922 * Wait for any third party viewers (e.g., lsof)
4923 * to release their references to this fileproc.
4925 while (os_ref_get_count(&fp
->f_iocount
) > 1) {
4926 p
->p_fpdrainwait
= 1;
4927 msleep(&p
->p_fpdrainwait
, &p
->p_fdmlock
, PRIBIO
,
4930 if (fp
->f_flags
& FP_WAITEVENT
) {
4931 (void)waitevent_close(p
, fp
);
4933 closef_locked(fp
, fp
->f_fglob
, p
);
4939 /* release the per-process workq kq */
4940 if (fdp
->fd_wqkqueue
) {
4941 dealloc_kqwq
= fdp
->fd_wqkqueue
;
4942 fdp
->fd_wqkqueue
= NULL
;
4947 /* Anything to free? */
4949 kqworkq_dealloc(dealloc_kqwq
);
4957 * Description: Copy a filedesc structure. This is normally used as part of
4958 * forkproc() when forking a new process, to copy the per process
4959 * open file table over to the new process.
4961 * Parameters: p Process whose open file table
4962 * is to be copied (parent)
4963 * uth_cdir Per thread current working
4964 * cirectory, or NULL
4966 * Returns: NULL Copy failed
4967 * !NULL Pointer to new struct filedesc
4969 * Locks: This function internally takes and drops proc_fdlock()
4971 * Notes: Files are copied directly, ignoring the new resource limits
4972 * for the process that's being copied into. Since the descriptor
4973 * references are just additional references, this does not count
4974 * against the number of open files on the system.
4976 * The struct filedesc includes the current working directory,
4977 * and the current root directory, if the process is chroot'ed.
4979 * If the exec was called by a thread using a per thread current
4980 * working directory, we inherit the working directory from the
4981 * thread making the call, rather than from the process.
4983 * In the case of a failure to obtain a reference, for most cases,
4984 * the file entry will be silently dropped. There's an exception
4985 * for the case of a chroot dir, since a failure to to obtain a
4986 * reference there would constitute an "escape" from the chroot
4987 * environment, which must not be allowed. In that case, we will
4988 * deny the execve() operation, rather than allowing the escape.
4991 fdcopy(proc_t p
, vnode_t uth_cdir
)
4993 struct filedesc
*newfdp
, *fdp
= p
->p_fd
;
4995 struct fileproc
*ofp
, *fp
;
4998 MALLOC_ZONE(newfdp
, struct filedesc
*,
4999 sizeof(*newfdp
), M_FILEDESC
, M_WAITOK
);
5000 if (newfdp
== NULL
) {
5007 * the FD_CHROOT flag will be inherited via this copy
5009 (void) memcpy(newfdp
, fdp
, sizeof(*newfdp
));
5012 * If we are running with per-thread current working directories,
5013 * inherit the new current working directory from the current thread
5014 * instead, before we take our references.
5016 if (uth_cdir
!= NULLVP
) {
5017 newfdp
->fd_cdir
= uth_cdir
;
5021 * For both fd_cdir and fd_rdir make sure we get
5022 * a valid reference... if we can't, than set
5023 * set the pointer(s) to NULL in the child... this
5024 * will keep us from using a non-referenced vp
5025 * and allows us to do the vnode_rele only on
5026 * a properly referenced vp
5028 if ((v_dir
= newfdp
->fd_cdir
)) {
5029 if (vnode_getwithref(v_dir
) == 0) {
5030 if ((vnode_ref(v_dir
))) {
5031 newfdp
->fd_cdir
= NULL
;
5035 newfdp
->fd_cdir
= NULL
;
5038 if (newfdp
->fd_cdir
== NULL
&& fdp
->fd_cdir
) {
5040 * we couldn't get a new reference on
5041 * the current working directory being
5042 * inherited... we might as well drop
5043 * our reference from the parent also
5044 * since the vnode has gone DEAD making
5045 * it useless... by dropping it we'll
5046 * be that much closer to recycling it
5048 vnode_rele(fdp
->fd_cdir
);
5049 fdp
->fd_cdir
= NULL
;
5052 if ((v_dir
= newfdp
->fd_rdir
)) {
5053 if (vnode_getwithref(v_dir
) == 0) {
5054 if ((vnode_ref(v_dir
))) {
5055 newfdp
->fd_rdir
= NULL
;
5059 newfdp
->fd_rdir
= NULL
;
5062 /* Coming from a chroot environment and unable to get a reference... */
5063 if (newfdp
->fd_rdir
== NULL
&& fdp
->fd_rdir
) {
5065 * We couldn't get a new reference on
5066 * the chroot directory being
5067 * inherited... this is fatal, since
5068 * otherwise it would constitute an
5069 * escape from a chroot environment by
5072 if (newfdp
->fd_cdir
) {
5073 vnode_rele(newfdp
->fd_cdir
);
5075 FREE_ZONE(newfdp
, sizeof *newfdp
, M_FILEDESC
);
5080 * If the number of open files fits in the internal arrays
5081 * of the open file structure, use them, otherwise allocate
5082 * additional memory for the number of descriptors currently
5085 if (newfdp
->fd_lastfile
< NDFILE
) {
5089 * Compute the smallest multiple of NDEXTENT needed
5090 * for the file descriptors currently in use,
5091 * allowing the table to shrink.
5093 i
= newfdp
->fd_nfiles
;
5094 while (i
> 1 + 2 * NDEXTENT
&& i
> 1 + newfdp
->fd_lastfile
* 2) {
5100 MALLOC_ZONE(newfdp
->fd_ofiles
, struct fileproc
**,
5101 i
* OFILESIZE
, M_OFILETABL
, M_WAITOK
);
5102 if (newfdp
->fd_ofiles
== NULL
) {
5103 if (newfdp
->fd_cdir
) {
5104 vnode_rele(newfdp
->fd_cdir
);
5106 if (newfdp
->fd_rdir
) {
5107 vnode_rele(newfdp
->fd_rdir
);
5110 FREE_ZONE(newfdp
, sizeof(*newfdp
), M_FILEDESC
);
5113 (void) memset(newfdp
->fd_ofiles
, 0, i
* OFILESIZE
);
5116 newfdp
->fd_ofileflags
= (char *) &newfdp
->fd_ofiles
[i
];
5117 newfdp
->fd_nfiles
= i
;
5119 if (fdp
->fd_nfiles
> 0) {
5120 struct fileproc
**fpp
;
5123 (void) memcpy(newfdp
->fd_ofiles
, fdp
->fd_ofiles
,
5124 (newfdp
->fd_lastfile
+ 1) * sizeof(*fdp
->fd_ofiles
));
5125 (void) memcpy(newfdp
->fd_ofileflags
, fdp
->fd_ofileflags
,
5126 (newfdp
->fd_lastfile
+ 1) * sizeof(*fdp
->fd_ofileflags
));
5128 fpp
= &newfdp
->fd_ofiles
[newfdp
->fd_lastfile
];
5129 flags
= &newfdp
->fd_ofileflags
[newfdp
->fd_lastfile
];
5130 for (i
= newfdp
->fd_lastfile
; i
>= 0; i
--, fpp
--, flags
--) {
5131 if ((ofp
= *fpp
) != NULL
&&
5132 0 == (ofp
->f_fglob
->fg_lflags
& FG_CONFINED
) &&
5133 0 == (*flags
& (UF_FORKCLOSE
| UF_RESERVED
))) {
5135 if (FILEPROC_TYPE(ofp
) != FTYPE_SIMPLE
) {
5136 panic("complex fileproc");
5139 fp
= fileproc_alloc_init(NULL
);
5142 * XXX no room to copy, unable to
5143 * XXX safely unwind state at present
5148 (ofp
->f_flags
& ~FP_TYPEMASK
);
5149 fp
->f_fglob
= ofp
->f_fglob
;
5158 if (i
== newfdp
->fd_lastfile
&& i
> 0) {
5159 newfdp
->fd_lastfile
--;
5161 if (i
< newfdp
->fd_freefile
) {
5162 newfdp
->fd_freefile
= i
;
5171 * Initialize knote and kqueue tracking structs
5173 newfdp
->fd_knlist
= NULL
;
5174 newfdp
->fd_knlistsize
= 0;
5175 newfdp
->fd_knhash
= NULL
;
5176 newfdp
->fd_knhashmask
= 0;
5177 newfdp
->fd_kqhash
= NULL
;
5178 newfdp
->fd_kqhashmask
= 0;
5179 newfdp
->fd_wqkqueue
= NULL
;
5180 lck_mtx_init(&newfdp
->fd_kqhashlock
, proc_kqhashlock_grp
, proc_lck_attr
);
5181 lck_mtx_init(&newfdp
->fd_knhashlock
, proc_knhashlock_grp
, proc_lck_attr
);
5190 * Description: Release a filedesc (per process open file table) structure;
5191 * this is done on process exit(), or from forkproc_free() if
5192 * the fork fails for some reason subsequent to a successful
5195 * Parameters: p Pointer to process going away
5199 * Locks: This function internally takes and drops proc_fdlock()
5204 struct filedesc
*fdp
;
5205 struct fileproc
*fp
;
5206 struct kqworkq
*dealloc_kqwq
= NULL
;
5211 if (p
== kernproc
|| NULL
== (fdp
= p
->p_fd
)) {
5216 extern struct filedesc filedesc0
;
5218 if (&filedesc0
== fdp
) {
5223 * deallocate all the knotes up front and claim empty
5224 * tables to make any subsequent kqueue closes faster.
5227 assert(fdp
->fd_knlistsize
== 0);
5228 assert(fdp
->fd_knhashmask
== 0);
5231 * dealloc all workloops that have outstanding retains
5232 * when created with scheduling parameters.
5234 kqworkloops_dealloc(p
);
5236 /* close file descriptors */
5237 if (fdp
->fd_nfiles
> 0 && fdp
->fd_ofiles
) {
5238 for (i
= fdp
->fd_lastfile
; i
>= 0; i
--) {
5239 if ((fp
= fdp
->fd_ofiles
[i
]) != NULL
) {
5240 if (fdp
->fd_ofileflags
[i
] & UF_RESERVED
) {
5241 panic("fdfree: found fp with UF_RESERVED");
5244 fileproc_drain(p
, fp
);
5245 procfdtbl_reservefd(p
, i
);
5247 if (fp
->f_flags
& FP_WAITEVENT
) {
5248 (void)waitevent_close(p
, fp
);
5250 (void) closef_locked(fp
, fp
->f_fglob
, p
);
5254 FREE_ZONE(fdp
->fd_ofiles
, fdp
->fd_nfiles
* OFILESIZE
, M_OFILETABL
);
5255 fdp
->fd_ofiles
= NULL
;
5259 if (fdp
->fd_wqkqueue
) {
5260 dealloc_kqwq
= fdp
->fd_wqkqueue
;
5261 fdp
->fd_wqkqueue
= NULL
;
5267 kqworkq_dealloc(dealloc_kqwq
);
5270 vnode_rele(fdp
->fd_cdir
);
5273 vnode_rele(fdp
->fd_rdir
);
5276 proc_fdlock_spin(p
);
5280 if (fdp
->fd_kqhash
) {
5281 for (uint32_t j
= 0; j
<= fdp
->fd_kqhashmask
; j
++) {
5282 assert(LIST_EMPTY(&fdp
->fd_kqhash
[j
]));
5284 FREE(fdp
->fd_kqhash
, M_KQUEUE
);
5287 lck_mtx_destroy(&fdp
->fd_kqhashlock
, proc_kqhashlock_grp
);
5288 lck_mtx_destroy(&fdp
->fd_knhashlock
, proc_knhashlock_grp
);
5290 FREE_ZONE(fdp
, sizeof(*fdp
), M_FILEDESC
);
5296 * Description: Internal form of closef; called with proc_fdlock held
5298 * Parameters: fp Pointer to fileproc for fd
5299 * fg Pointer to fileglob for fd
5300 * p Pointer to proc structure
5302 * Returns: 0 Success
5303 * closef_finish:??? Anything returnable by a per-fileops
5306 * Note: Decrements reference count on file structure; if this was the
5307 * last reference, then closef_finish() is called
5309 * p and fp are allowed to be NULL when closing a file that was
5310 * being passed in a message (but only if we are called when this
5311 * is NOT the last reference).
5314 closef_locked(struct fileproc
*fp
, struct fileglob
*fg
, proc_t p
)
5318 struct vfs_context context
;
5325 /* Set up context with cred stashed in fg */
5326 if (p
== current_proc()) {
5327 context
.vc_thread
= current_thread();
5329 context
.vc_thread
= NULL
;
5331 context
.vc_ucred
= fg
->fg_cred
;
5334 * POSIX record locking dictates that any close releases ALL
5335 * locks owned by this process. This is handled by setting
5336 * a flag in the unlock to free ONLY locks obeying POSIX
5337 * semantics, and not to free BSD-style file locks.
5338 * If the descriptor was in a message, POSIX-style locks
5339 * aren't passed with the descriptor.
5341 if (p
&& (p
->p_ladvflag
& P_LADVLOCK
) &&
5342 DTYPE_VNODE
== FILEGLOB_DTYPE(fg
)) {
5345 lf
.l_whence
= SEEK_SET
;
5348 lf
.l_type
= F_UNLCK
;
5349 vp
= (struct vnode
*)fg
->fg_data
;
5351 if ((error
= vnode_getwithref(vp
)) == 0) {
5352 (void) VNOP_ADVLOCK(vp
, (caddr_t
)p
, F_UNLCK
, &lf
, F_POSIX
, &context
, NULL
);
5353 (void)vnode_put(vp
);
5357 lck_mtx_lock_spin(&fg
->fg_lock
);
5360 if (fg
->fg_count
> 0) {
5361 lck_mtx_unlock(&fg
->fg_lock
);
5365 if (fg
->fg_count
!= 0) {
5366 panic("fg %p: being freed with bad fg_count (%d)", fg
, fg
->fg_count
);
5370 if (fp
&& (fp
->f_flags
& FP_WRITTEN
)) {
5371 fg
->fg_flag
|= FWASWRITTEN
;
5374 fg
->fg_lflags
|= FG_TERM
;
5375 lck_mtx_unlock(&fg
->fg_lock
);
5381 /* Since we ensure that fg->fg_ops is always initialized,
5382 * it is safe to invoke fo_close on the fg */
5383 error
= fo_close(fg
, &context
);
5398 * Description: Drain out pending I/O operations
5400 * Parameters: p Process closing this file
5401 * fp fileproc struct for the open
5402 * instance on the file
5406 * Locks: Assumes the caller holds the proc_fdlock
5408 * Notes: For character devices, this occurs on the last close of the
5409 * device; for all other file descriptors, this occurs on each
5410 * close to prevent fd's from being closed out from under
5411 * operations currently in progress and blocked
5413 * See Also: file_vnode(), file_socket(), file_drop(), and the cautions
5414 * regarding their use and interaction with this function.
5417 fileproc_drain(proc_t p
, struct fileproc
* fp
)
5419 struct vfs_context context
;
5421 context
.vc_thread
= proc_thread(p
); /* XXX */
5422 context
.vc_ucred
= fp
->f_fglob
->fg_cred
;
5424 /* Set the vflag for drain */
5425 fileproc_modify_vflags(fp
, FPV_DRAIN
, FALSE
);
5427 while (os_ref_get_count(&fp
->f_iocount
) > 1) {
5428 lck_mtx_convert_spin(&p
->p_fdmlock
);
5430 fo_drain(fp
, &context
);
5431 if ((fp
->f_flags
& FP_INSELECT
) == FP_INSELECT
) {
5432 if (waitq_wakeup64_all((struct waitq
*)fp
->f_wset
, NO_EVENT64
,
5433 THREAD_INTERRUPTED
, WAITQ_ALL_PRIORITIES
) == KERN_INVALID_ARGUMENT
) {
5434 panic("bad wait queue for waitq_wakeup64_all %p (fp:%p)", fp
->f_wset
, fp
);
5437 if ((fp
->f_flags
& FP_SELCONFLICT
) == FP_SELCONFLICT
) {
5438 if (waitq_wakeup64_all(&select_conflict_queue
, NO_EVENT64
,
5439 THREAD_INTERRUPTED
, WAITQ_ALL_PRIORITIES
) == KERN_INVALID_ARGUMENT
) {
5440 panic("bad select_conflict_queue");
5443 p
->p_fpdrainwait
= 1;
5445 msleep(&p
->p_fpdrainwait
, &p
->p_fdmlock
, PRIBIO
, "fpdrain", NULL
);
5448 if ((fp
->f_flags
& FP_INSELECT
) != 0) {
5449 panic("FP_INSELECT set on drained fp");
5452 if ((fp
->f_flags
& FP_SELCONFLICT
) == FP_SELCONFLICT
) {
5453 fp
->f_flags
&= ~FP_SELCONFLICT
;
5461 * Description: Release the fd and free the fileproc associated with the fd
5462 * in the per process open file table of the specified process;
5463 * these values must correspond.
5465 * Parameters: p Process containing fd
5466 * fd fd to be released
5467 * fp fileproc to be freed
5470 fp_free(proc_t p
, int fd
, struct fileproc
* fp
)
5472 proc_fdlock_spin(p
);
5476 fg_free(fp
->f_fglob
);
5477 os_ref_release_live(&fp
->f_iocount
);
5485 * Description: Apply an advisory lock on a file descriptor.
5487 * Parameters: p Process making request
5488 * uap->fd fd on which the lock is to be
5490 * uap->how (Un)Lock bits, including type
5491 * retval Pointer to the call return area
5493 * Returns: 0 Success
5494 * fp_getfvp:EBADF Bad file descriptor
5495 * fp_getfvp:ENOTSUP fd does not refer to a vnode
5496 * vnode_getwithref:???
5500 * *retval (modified) Size of dtable
5502 * Notes: Just attempt to get a record lock of the requested type on
5503 * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
5506 flock(proc_t p
, struct flock_args
*uap
, __unused
int32_t *retval
)
5510 struct fileproc
*fp
;
5513 vfs_context_t ctx
= vfs_context_current();
5516 AUDIT_ARG(fd
, uap
->fd
);
5517 if ((error
= fp_getfvp(p
, fd
, &fp
, &vp
))) {
5520 if ((error
= vnode_getwithref(vp
))) {
5523 AUDIT_ARG(vnpath
, vp
, ARG_VNODE1
);
5525 lf
.l_whence
= SEEK_SET
;
5528 if (how
& LOCK_UN
) {
5529 lf
.l_type
= F_UNLCK
;
5530 fp
->f_flag
&= ~FHASLOCK
;
5531 error
= VNOP_ADVLOCK(vp
, (caddr_t
)fp
->f_fglob
, F_UNLCK
, &lf
, F_FLOCK
, ctx
, NULL
);
5534 if (how
& LOCK_EX
) {
5535 lf
.l_type
= F_WRLCK
;
5536 } else if (how
& LOCK_SH
) {
5537 lf
.l_type
= F_RDLCK
;
5543 error
= mac_file_check_lock(proc_ucred(p
), fp
->f_fglob
, F_SETLK
, &lf
);
5548 error
= VNOP_ADVLOCK(vp
, (caddr_t
)fp
->f_fglob
, F_SETLK
, &lf
,
5549 (how
& LOCK_NB
? F_FLOCK
: F_FLOCK
| F_WAIT
),
5552 fp
->f_flag
|= FHASLOCK
;
5555 (void)vnode_put(vp
);
5557 fp_drop(p
, fd
, fp
, 0);
5564 * Description: Obtain a Mach send right for a given file descriptor.
5566 * Parameters: p Process calling fileport
5567 * uap->fd The fd to reference
5568 * uap->portnamep User address at which to place port name.
5570 * Returns: 0 Success.
5571 * EBADF Bad file descriptor.
5572 * EINVAL File descriptor had type that cannot be sent, misc. other errors.
5573 * EFAULT Address at which to store port name is not valid.
5574 * EAGAIN Resource shortage.
5577 * On success, name of send right is stored at user-specified address.
5580 fileport_makeport(proc_t p
, struct fileport_makeport_args
*uap
,
5581 __unused
int *retval
)
5585 user_addr_t user_portaddr
= uap
->portnamep
;
5586 struct fileproc
*fp
= FILEPROC_NULL
;
5587 struct fileglob
*fg
= NULL
;
5588 ipc_port_t fileport
;
5589 mach_port_name_t name
= MACH_PORT_NULL
;
5592 err
= fp_lookup(p
, fd
, &fp
, 1);
5597 if (!file_issendable(p
, fp
)) {
5602 if (FP_ISGUARDED(fp
, GUARD_FILEPORT
)) {
5603 err
= fp_guard_exception(p
, fd
, fp
, kGUARD_EXC_FILEPORT
);
5607 /* Dropped when port is deallocated */
5613 /* Allocate and initialize a port */
5614 fileport
= fileport_alloc(fg
);
5615 if (fileport
== IPC_PORT_NULL
) {
5621 /* Add an entry. Deallocates port on failure. */
5622 name
= ipc_port_copyout_send(fileport
, get_task_ipcspace(p
->task
));
5623 if (!MACH_PORT_VALID(name
)) {
5628 err
= copyout(&name
, user_portaddr
, sizeof(mach_port_name_t
));
5633 /* Tag the fileglob for debugging purposes */
5634 lck_mtx_lock_spin(&fg
->fg_lock
);
5635 fg
->fg_lflags
|= FG_PORTMADE
;
5636 lck_mtx_unlock(&fg
->fg_lock
);
5638 fp_drop(p
, fd
, fp
, 0);
5645 if (MACH_PORT_VALID(name
)) {
5646 /* Don't care if another thread races us to deallocate the entry */
5647 (void) mach_port_deallocate(get_task_ipcspace(p
->task
), name
);
5650 if (fp
!= FILEPROC_NULL
) {
5651 fp_drop(p
, fd
, fp
, 0);
5658 fileport_releasefg(struct fileglob
*fg
)
5660 (void)closef_locked(NULL
, fg
, PROC_NULL
);
5666 * fileport_makefd_internal
5668 * Description: Obtain the file descriptor for a given Mach send right.
5670 * Returns: 0 Success
5671 * EINVAL Invalid Mach port name, or port is not for a file.
5673 * fdalloc:ENOMEM Unable to allocate fileproc or extend file table.
5676 * *retval (modified) The new descriptor
5679 fileport_makefd_internal(proc_t p
, ipc_port_t port
, int uf_flags
, int *retval
)
5681 struct fileglob
*fg
;
5682 struct fileproc
*fp
= FILEPROC_NULL
;
5686 fg
= fileport_port_to_fileglob(port
);
5692 fp
= fileproc_alloc_init(NULL
);
5693 if (fp
== FILEPROC_NULL
) {
5702 err
= fdalloc(p
, 0, &fd
);
5709 *fdflags(p
, fd
) |= uf_flags
;
5712 procfdtbl_releasefd(p
, fd
, fp
);
5718 if ((fp
!= NULL
) && (0 != err
)) {
5728 * Description: Obtain the file descriptor for a given Mach send right.
5730 * Parameters: p Process calling fileport
5731 * uap->port Name of send right to file port.
5733 * Returns: 0 Success
5734 * EINVAL Invalid Mach port name, or port is not for a file.
5736 * fdalloc:ENOMEM Unable to allocate fileproc or extend file table.
5739 * *retval (modified) The new descriptor
5742 fileport_makefd(proc_t p
, struct fileport_makefd_args
*uap
, int32_t *retval
)
5744 ipc_port_t port
= IPC_PORT_NULL
;
5745 mach_port_name_t send
= uap
->port
;
5749 res
= ipc_object_copyin(get_task_ipcspace(p
->task
),
5750 send
, MACH_MSG_TYPE_COPY_SEND
, &port
, 0, NULL
, IPC_KMSG_FLAGS_ALLOW_IMMOVABLE_SEND
);
5752 if (res
== KERN_SUCCESS
) {
5753 err
= fileport_makefd_internal(p
, port
, UF_EXCLOSE
, retval
);
5758 if (IPC_PORT_NULL
!= port
) {
5759 ipc_port_release_send(port
);
5769 * Description: Duplicate the specified descriptor to a free descriptor;
5770 * this is the second half of fdopen(), above.
5772 * Parameters: fdp filedesc pointer to fill in
5774 * dfd fd to dup from
5775 * mode mode to set on new fd
5776 * error command code
5778 * Returns: 0 Success
5779 * EBADF Source fd is bad
5780 * EACCES Requested mode not allowed
5781 * !0 'error', if not ENODEV or
5784 * Notes: XXX This is not thread safe; see fdopen() above
5787 dupfdopen(struct filedesc
*fdp
, int indx
, int dfd
, int flags
, int error
)
5789 struct fileproc
*wfp
;
5790 struct fileproc
*fp
;
5794 proc_t p
= current_proc();
5797 * If the to-be-dup'd fd number is greater than the allowed number
5798 * of file descriptors, or the fd to be dup'd has already been
5799 * closed, reject. Note, check for new == old is necessary as
5800 * falloc could allocate an already closed to-be-dup'd descriptor
5801 * as the new descriptor.
5805 fp
= fdp
->fd_ofiles
[indx
];
5806 if (dfd
< 0 || dfd
>= fdp
->fd_nfiles
||
5807 (wfp
= fdp
->fd_ofiles
[dfd
]) == NULL
|| wfp
== fp
||
5808 (fdp
->fd_ofileflags
[dfd
] & UF_RESERVED
)) {
5813 myerror
= mac_file_check_dup(proc_ucred(p
), wfp
->f_fglob
, dfd
);
5820 * There are two cases of interest here.
5822 * For ENODEV simply dup (dfd) to file descriptor
5823 * (indx) and return.
5825 * For ENXIO steal away the file structure from (dfd) and
5826 * store it in (indx). (dfd) is effectively closed by
5829 * Any other error code is just returned.
5833 if (FP_ISGUARDED(wfp
, GUARD_DUP
)) {
5839 * Check that the mode the file is being opened for is a
5840 * subset of the mode of the existing descriptor.
5842 if (((flags
& (FREAD
| FWRITE
)) | wfp
->f_flag
) != wfp
->f_flag
) {
5846 if (indx
> fdp
->fd_lastfile
) {
5847 fdp
->fd_lastfile
= indx
;
5852 fg_free(fp
->f_fglob
);
5854 fp
->f_fglob
= wfp
->f_fglob
;
5856 fdp
->fd_ofileflags
[indx
] = fdp
->fd_ofileflags
[dfd
] |
5857 (flags
& O_CLOEXEC
) ? UF_EXCLOSE
: 0;
5873 * Description: Add a reference to a fileglob by fileproc
5875 * Parameters: fp fileproc containing fileglob
5880 * Notes: XXX Should use OSAddAtomic?
5883 fg_ref(struct fileproc
* fp
)
5885 struct fileglob
*fg
;
5889 lck_mtx_lock_spin(&fg
->fg_lock
);
5892 if ((fp
->f_flags
& ~((unsigned int)FP_VALID_FLAGS
)) != 0) {
5893 panic("fg_ref: invalid bits on fp %p", fp
);
5896 if (fg
->fg_count
== 0) {
5897 panic("fg_ref: adding fgcount to zeroed fg: fp %p fg %p",
5902 lck_mtx_unlock(&fg
->fg_lock
);
5909 * Description: Remove a reference to a fileglob by fileproc
5911 * Parameters: fp fileproc containing fileglob
5916 * Notes: XXX Should use OSAddAtomic?
5919 fg_drop(struct fileproc
* fp
)
5921 struct fileglob
*fg
;
5924 lck_mtx_lock_spin(&fg
->fg_lock
);
5926 lck_mtx_unlock(&fg
->fg_lock
);
5931 * fg_insertuipc_mark
5933 * Description: Mark fileglob for insertion onto message queue if needed
5934 * Also takes fileglob reference
5936 * Parameters: fg Fileglob pointer to insert
5938 * Returns: true, if the fileglob needs to be inserted onto msg queue
5940 * Locks: Takes and drops fg_lock, potentially many times
5943 fg_insertuipc_mark(struct fileglob
* fg
)
5945 boolean_t insert
= FALSE
;
5947 lck_mtx_lock_spin(&fg
->fg_lock
);
5948 while (fg
->fg_lflags
& FG_RMMSGQ
) {
5949 lck_mtx_convert_spin(&fg
->fg_lock
);
5951 fg
->fg_lflags
|= FG_WRMMSGQ
;
5952 msleep(&fg
->fg_lflags
, &fg
->fg_lock
, 0, "fg_insertuipc", NULL
);
5957 if (fg
->fg_msgcount
== 1) {
5958 fg
->fg_lflags
|= FG_INSMSGQ
;
5961 lck_mtx_unlock(&fg
->fg_lock
);
5968 * Description: Insert marked fileglob onto message queue
5970 * Parameters: fg Fileglob pointer to insert
5974 * Locks: Takes and drops fg_lock & uipc_lock
5975 * DO NOT call this function with proc_fdlock held as unp_gc()
5976 * can potentially try to acquire proc_fdlock, which can result
5977 * in a deadlock if this function is in unp_gc_wait().
5980 fg_insertuipc(struct fileglob
* fg
)
5982 if (fg
->fg_lflags
& FG_INSMSGQ
) {
5983 lck_mtx_lock_spin(uipc_lock
);
5985 LIST_INSERT_HEAD(&fmsghead
, fg
, f_msglist
);
5986 lck_mtx_unlock(uipc_lock
);
5987 lck_mtx_lock(&fg
->fg_lock
);
5988 fg
->fg_lflags
&= ~FG_INSMSGQ
;
5989 if (fg
->fg_lflags
& FG_WINSMSGQ
) {
5990 fg
->fg_lflags
&= ~FG_WINSMSGQ
;
5991 wakeup(&fg
->fg_lflags
);
5993 lck_mtx_unlock(&fg
->fg_lock
);
5998 * fg_removeuipc_mark
6000 * Description: Mark the fileglob for removal from message queue if needed
6001 * Also releases fileglob message queue reference
6003 * Parameters: fg Fileglob pointer to remove
6005 * Returns: true, if the fileglob needs to be removed from msg queue
6007 * Locks: Takes and drops fg_lock, potentially many times
6010 fg_removeuipc_mark(struct fileglob
* fg
)
6012 boolean_t remove
= FALSE
;
6014 lck_mtx_lock_spin(&fg
->fg_lock
);
6015 while (fg
->fg_lflags
& FG_INSMSGQ
) {
6016 lck_mtx_convert_spin(&fg
->fg_lock
);
6018 fg
->fg_lflags
|= FG_WINSMSGQ
;
6019 msleep(&fg
->fg_lflags
, &fg
->fg_lock
, 0, "fg_removeuipc", NULL
);
6022 if (fg
->fg_msgcount
== 0) {
6023 fg
->fg_lflags
|= FG_RMMSGQ
;
6026 lck_mtx_unlock(&fg
->fg_lock
);
6033 * Description: Remove marked fileglob from message queue
6035 * Parameters: fg Fileglob pointer to remove
6039 * Locks: Takes and drops fg_lock & uipc_lock
6040 * DO NOT call this function with proc_fdlock held as unp_gc()
6041 * can potentially try to acquire proc_fdlock, which can result
6042 * in a deadlock if this function is in unp_gc_wait().
6045 fg_removeuipc(struct fileglob
* fg
)
6047 if (fg
->fg_lflags
& FG_RMMSGQ
) {
6048 lck_mtx_lock_spin(uipc_lock
);
6050 LIST_REMOVE(fg
, f_msglist
);
6051 lck_mtx_unlock(uipc_lock
);
6052 lck_mtx_lock(&fg
->fg_lock
);
6053 fg
->fg_lflags
&= ~FG_RMMSGQ
;
6054 if (fg
->fg_lflags
& FG_WRMMSGQ
) {
6055 fg
->fg_lflags
&= ~FG_WRMMSGQ
;
6056 wakeup(&fg
->fg_lflags
);
6058 lck_mtx_unlock(&fg
->fg_lock
);
6061 #endif /* SOCKETS */
6066 * Description: Generic fileops read indirected through the fileops pointer
6067 * in the fileproc structure
6069 * Parameters: fp fileproc structure pointer
6070 * uio user I/O structure pointer
6072 * ctx VFS context for operation
6074 * Returns: 0 Success
6075 * !0 Errno from read
6078 fo_read(struct fileproc
*fp
, struct uio
*uio
, int flags
, vfs_context_t ctx
)
6080 return (*fp
->f_ops
->fo_read
)(fp
, uio
, flags
, ctx
);
6084 fo_no_read(struct fileproc
*fp
, struct uio
*uio
, int flags
, vfs_context_t ctx
)
6086 #pragma unused(fp, uio, flags, ctx)
6094 * Description: Generic fileops write indirected through the fileops pointer
6095 * in the fileproc structure
6097 * Parameters: fp fileproc structure pointer
6098 * uio user I/O structure pointer
6100 * ctx VFS context for operation
6102 * Returns: 0 Success
6103 * !0 Errno from write
6106 fo_write(struct fileproc
*fp
, struct uio
*uio
, int flags
, vfs_context_t ctx
)
6108 return (*fp
->f_ops
->fo_write
)(fp
, uio
, flags
, ctx
);
6112 fo_no_write(struct fileproc
*fp
, struct uio
*uio
, int flags
, vfs_context_t ctx
)
6114 #pragma unused(fp, uio, flags, ctx)
6122 * Description: Generic fileops ioctl indirected through the fileops pointer
6123 * in the fileproc structure
6125 * Parameters: fp fileproc structure pointer
6127 * data pointer to internalized copy
6128 * of user space ioctl command
6129 * parameter data in kernel space
6130 * ctx VFS context for operation
6132 * Returns: 0 Success
6133 * !0 Errno from ioctl
6135 * Locks: The caller is assumed to have held the proc_fdlock; this
6136 * function releases and reacquires this lock. If the caller
6137 * accesses data protected by this lock prior to calling this
6138 * function, it will need to revalidate/reacquire any cached
6139 * protected data obtained prior to the call.
6142 fo_ioctl(struct fileproc
*fp
, u_long com
, caddr_t data
, vfs_context_t ctx
)
6146 proc_fdunlock(vfs_context_proc(ctx
));
6147 error
= (*fp
->f_ops
->fo_ioctl
)(fp
, com
, data
, ctx
);
6148 proc_fdlock(vfs_context_proc(ctx
));
6153 fo_no_ioctl(struct fileproc
*fp
, u_long com
, caddr_t data
, vfs_context_t ctx
)
6155 #pragma unused(fp, com, data, ctx)
6163 * Description: Generic fileops select indirected through the fileops pointer
6164 * in the fileproc structure
6166 * Parameters: fp fileproc structure pointer
6167 * which select which
6168 * wql pointer to wait queue list
6169 * ctx VFS context for operation
6171 * Returns: 0 Success
6172 * !0 Errno from select
6175 fo_select(struct fileproc
*fp
, int which
, void *wql
, vfs_context_t ctx
)
6177 return (*fp
->f_ops
->fo_select
)(fp
, which
, wql
, ctx
);
6181 fo_no_select(struct fileproc
*fp
, int which
, void *wql
, vfs_context_t ctx
)
6183 #pragma unused(fp, which, wql, ctx)
6191 * Description: Generic fileops close indirected through the fileops pointer
6192 * in the fileproc structure
6194 * Parameters: fp fileproc structure pointer for
6196 * ctx VFS context for operation
6198 * Returns: 0 Success
6199 * !0 Errno from close
6202 fo_close(struct fileglob
*fg
, vfs_context_t ctx
)
6204 return (*fg
->fg_ops
->fo_close
)(fg
, ctx
);
6211 * Description: Generic fileops kqueue filter indirected through the fileops
6212 * pointer in the fileproc structure
6214 * Parameters: fp fileproc structure pointer
6215 * ctx VFS context for operation
6217 * Returns: 0 Success
6218 * !0 errno from drain
6221 fo_drain(struct fileproc
*fp
, vfs_context_t ctx
)
6223 return (*fp
->f_ops
->fo_drain
)(fp
, ctx
);
6227 fo_no_drain(struct fileproc
*fp
, vfs_context_t ctx
)
6229 #pragma unused(fp, ctx)
6237 * Description: Generic fileops kqueue filter indirected through the fileops
6238 * pointer in the fileproc structure
6240 * Parameters: fp fileproc structure pointer
6241 * kn pointer to knote to filter on
6243 * Returns: (kn->kn_flags & EV_ERROR) error in kn->kn_data
6244 * 0 Filter is not active
6245 * !0 Filter is active
6248 fo_kqfilter(struct fileproc
*fp
, struct knote
*kn
, struct kevent_qos_s
*kev
)
6250 return (*fp
->f_ops
->fo_kqfilter
)(fp
, kn
, kev
);
6254 fo_no_kqfilter(struct fileproc
*fp
, struct knote
*kn
, struct kevent_qos_s
*kev
)
6256 #pragma unused(fp, kev)
6257 knote_set_error(kn
, ENOTSUP
);
6263 * The ability to send a file descriptor to another
6264 * process is opt-in by file type.
6267 file_issendable(proc_t p
, struct fileproc
*fp
)
6269 proc_fdlock_assert(p
, LCK_MTX_ASSERT_OWNED
);
6271 switch (fp
->f_type
) {
6276 case DTYPE_NETPOLICY
:
6277 return 0 == (fp
->f_fglob
->fg_lflags
& FG_CONFINED
);
6279 /* DTYPE_KQUEUE, DTYPE_FSEVENTS, DTYPE_PSXSEM */
6284 os_refgrp_decl(, f_iocount_refgrp
, "f_iocount", NULL
);
6287 fileproc_alloc_init(__unused
void *arg
)
6289 struct fileproc
*fp
;
6291 MALLOC_ZONE(fp
, struct fileproc
*, sizeof(*fp
), M_FILEPROC
, M_WAITOK
);
6293 bzero(fp
, sizeof(*fp
));
6294 os_ref_init(&fp
->f_iocount
, &f_iocount_refgrp
);
6302 fileproc_free(struct fileproc
*fp
)
6304 os_ref_count_t __unused refc
= os_ref_release(&fp
->f_iocount
);
6305 #if DEVELOPMENT || DEBUG
6307 panic("%s: pid %d refc: %u != 0",
6308 __func__
, proc_pid(current_proc()), refc
);
6311 switch (FILEPROC_TYPE(fp
)) {
6313 FREE_ZONE(fp
, sizeof(*fp
), M_FILEPROC
);
6316 guarded_fileproc_free(fp
);
6319 panic("%s: corrupt fp %p flags %x", __func__
, fp
, fp
->f_flags
);
6324 fileproc_modify_vflags(struct fileproc
*fp
, fileproc_vflags_t vflags
, boolean_t clearflags
)
6327 os_atomic_andnot(&fp
->f_vflags
, vflags
, relaxed
);
6329 os_atomic_or(&fp
->f_vflags
, vflags
, relaxed
);
6334 fileproc_get_vflags(struct fileproc
*fp
)
6336 return os_atomic_load(&fp
->f_vflags
, relaxed
);