xref: /illumos-gate/usr/src/lib/libc/port/stdio/_endopen.c (revision cd61ae21816e53b94bc1673f3f1aa651fc3115e8)
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 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*	Copyright (c) 1988 AT&T	*/
28 /*	  All Rights Reserved	*/
29 
30 /* Copyright (c) 2013 OmniTI Computer Consulting, Inc. All rights reserved. */
31 
32 /*
33  *	This routine is a special case, in that it is aware of
34  *	both small and large file interfaces. It must be built
35  *	in the small compilation environment.
36  */
37 
38 #include "lint.h"
39 #include "file64.h"
40 #include <mtlib.h>
41 #include <sys/types.h>
42 #include <stdio.h>
43 #include <fcntl.h>
44 #include <unistd.h>
45 #include <limits.h>
46 #include <thread.h>
47 #include <synch.h>
48 #include "stdiom.h"
49 #include <errno.h>
50 
51 /*
52  * open UNIX file name, associate with iop
53  */
54 
55 FILE *
56 _endopen(const char *name, const char *type, FILE *iop, int largefile)
57 {
58 	int oflag, fd, fflag, eflag, plusflag, xflag;
59 	const char *echr;
60 
61 	if (iop == NULL)
62 		return (NULL);
63 
64 	if (_stdio_flags(type, &oflag, &fflag) != 0) {
65 		return (NULL);
66 	}
67 
68 	/* select small or large file open based on flag */
69 	if (largefile) {
70 		fd = open64(name, oflag, 0666);
71 	} else {
72 		fd = open(name, oflag, 0666);
73 	}
74 	if (fd < 0)
75 		return (NULL);
76 
77 	/* As long as we make sure _flag stays != 0, we don't need to lock */
78 #ifdef	_LP64
79 	iop->_file = fd;
80 	iop->_flag = (iop->_flag & ~_DEF_FLAG_MASK) | fflag;
81 #else
82 	if (fd <= _FILE_FD_MAX) {
83 		SET_FILE(iop, fd);
84 	} else if (_file_set(iop, fd, type) != 0) {
85 		/* errno set in _file_set() */
86 		int err = errno;
87 		(void) close(fd);
88 		errno = err;
89 		return (NULL);
90 	}
91 	iop->_flag = fflag;
92 #endif	/*	_LP64	*/
93 
94 	if (oflag == (O_WRONLY | O_APPEND | O_CREAT)) {	/* type == "a" */
95 		if (_xseek64(iop, (off64_t)0, SEEK_END) < (off64_t)0) {
96 			(void) _xclose(iop);
97 			return (NULL);
98 		}
99 	}
100 
101 	return (iop);
102 }
103