xref: /illumos-gate/usr/src/lib/libc/port/gen/dup.c (revision 8b6b46dcb073dba71917d6a7309f0df7bad798a2)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /* Copyright 2013, OmniTI Computer Consulting, Inc. All rights reserved. */
23 
24 /*
25  * Copyright 2010 Sun Microsystems, Inc.  All rights reserved.
26  * Use is subject to license terms.
27  * Copyright 2024 Oxide Computer Company
28  */
29 
30 /*	Copyright (c) 1988 AT&T	*/
31 /*	  All Rights Reserved	*/
32 
33 #include	"lint.h"
34 #include	<sys/types.h>
35 #include	<fcntl.h>
36 #include	<errno.h>
37 
38 #pragma weak _dup = dup
39 int
40 dup(int fildes)
41 {
42 	return (fcntl(fildes, F_DUPFD, 0));
43 }
44 
45 #pragma weak _dup2 = dup2
46 int
47 dup2(int fildes, int fildes2)
48 {
49 	return (fcntl(fildes, F_DUP2FD, fildes2));
50 }
51 
52 int
53 dup3(int fildes, int fildes2, int flags)
54 {
55 	int dflags = 0;
56 
57 	/*
58 	 * dup3() only supports O_ open flags that translate into file
59 	 * descriptor flags in the F_GETFD sense.
60 	 */
61 	if (flags & ~(O_CLOEXEC | O_CLOFORK)) {
62 		errno = EINVAL;
63 		return (-1);
64 	}
65 
66 	/*
67 	 * This call differs from dup2 such that it is an error when
68 	 * fildes == fildes2
69 	 */
70 	if (fildes == fildes2) {
71 		errno = EINVAL;
72 		return (-1);
73 	}
74 
75 	if ((flags & O_CLOEXEC) != 0)
76 		dflags |= FD_CLOEXEC;
77 	if ((flags & O_CLOFORK) != 0)
78 		dflags |= FD_CLOFORK;
79 
80 	return (fcntl(fildes, F_DUP3FD, fildes2, dflags));
81 }
82