xref: /netbsd/lib/libc/stdio/fseeko.c (revision bf9ec67e)
1 /*	$NetBSD: fseeko.c,v 1.2 2000/07/26 08:52:57 kleink Exp $	*/
2 
3 /*-
4  * Copyright (c) 1990, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Chris Torek.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  */
38 
39 #include <sys/cdefs.h>
40 #if defined(LIBC_SCCS) && !defined(lint)
41 __RCSID("$NetBSD: fseeko.c,v 1.2 2000/07/26 08:52:57 kleink Exp $");
42 #endif /* LIBC_SCCS and not lint */
43 
44 #include "namespace.h"
45 #include <sys/types.h>
46 #include <sys/stat.h>
47 
48 #include <assert.h>
49 #include <errno.h>
50 #include <fcntl.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include "local.h"
54 #include "reentrant.h"
55 
56 #ifdef __weak_alias
57 __weak_alias(fseeko, _fseeko)
58 #endif
59 
60 #define	POS_ERR	(-(fpos_t)1)
61 
62 /*
63  * Seek the given file to the given offset.
64  * `Whence' must be one of the three SEEK_* macros.
65  */
66 int
67 fseeko(fp, offset, whence)
68 	FILE *fp;
69 	off_t offset;
70 	int whence;
71 {
72 	fpos_t (*seekfn) __P((void *, fpos_t, int));
73 	fpos_t target, curoff;
74 	size_t n;
75 	struct stat st;
76 	int havepos;
77 
78 	_DIAGASSERT(fp != NULL);
79 
80 #ifdef __GNUC__
81 	/* This outrageous construct just to shut up a GCC warning. */
82 	(void) &curoff;
83 #endif
84 
85 	/* make sure stdio is set up */
86 	if (!__sdidinit)
87 		__sinit();
88 
89 	FLOCKFILE(fp);
90 
91 	/*
92 	 * Have to be able to seek.
93 	 */
94 	if ((seekfn = fp->_seek) == NULL) {
95 		errno = ESPIPE;			/* historic practice */
96 		FUNLOCKFILE(fp);
97 		return (-1);
98 	}
99 
100 	/*
101 	 * Change any SEEK_CUR to SEEK_SET, and check `whence' argument.
102 	 * After this, whence is either SEEK_SET or SEEK_END.
103 	 */
104 	switch (whence) {
105 
106 	case SEEK_CUR:
107 		/*
108 		 * In order to seek relative to the current stream offset,
109 		 * we have to first find the current stream offset a la
110 		 * ftell (see ftell for details).
111 		 */
112 		__sflush(fp);	/* may adjust seek offset on append stream */
113 		if (fp->_flags & __SOFF)
114 			curoff = fp->_offset;
115 		else {
116 			curoff = (*seekfn)(fp->_cookie, (fpos_t)0, SEEK_CUR);
117 			if (curoff == POS_ERR) {
118 				FUNLOCKFILE(fp);
119 				return (-1);
120 			}
121 		}
122 		if (fp->_flags & __SRD) {
123 			curoff -= fp->_r;
124 			if (HASUB(fp))
125 				curoff -= fp->_ur;
126 		} else if (fp->_flags & __SWR && fp->_p != NULL)
127 			curoff += fp->_p - fp->_bf._base;
128 
129 		offset += curoff;
130 		whence = SEEK_SET;
131 		havepos = 1;
132 		break;
133 
134 	case SEEK_SET:
135 	case SEEK_END:
136 		curoff = 0;		/* XXX just to keep gcc quiet */
137 		havepos = 0;
138 		break;
139 
140 	default:
141 		errno = EINVAL;
142 		FUNLOCKFILE(fp);
143 		return (-1);
144 	}
145 
146 	/*
147 	 * Can only optimise if:
148 	 *	reading (and not reading-and-writing);
149 	 *	not unbuffered; and
150 	 *	this is a `regular' Unix file (and hence seekfn==__sseek).
151 	 * We must check __NBF first, because it is possible to have __NBF
152 	 * and __SOPT both set.
153 	 */
154 	if (fp->_bf._base == NULL)
155 		__smakebuf(fp);
156 	if (fp->_flags & (__SWR | __SRW | __SNBF | __SNPT))
157 		goto dumb;
158 	if ((fp->_flags & __SOPT) == 0) {
159 		if (seekfn != __sseek ||
160 		    fp->_file < 0 || fstat(fp->_file, &st) ||
161 		    !S_ISREG(st.st_mode)) {
162 			fp->_flags |= __SNPT;
163 			goto dumb;
164 		}
165 		fp->_blksize = st.st_blksize;
166 		fp->_flags |= __SOPT;
167 	}
168 
169 	/*
170 	 * We are reading; we can try to optimise.
171 	 * Figure out where we are going and where we are now.
172 	 */
173 	if (whence == SEEK_SET)
174 		target = offset;
175 	else {
176 		if (fstat(fp->_file, &st))
177 			goto dumb;
178 		target = st.st_size + offset;
179 	}
180 
181 	if (!havepos) {
182 		if (fp->_flags & __SOFF)
183 			curoff = fp->_offset;
184 		else {
185 			curoff = (*seekfn)(fp->_cookie, (fpos_t)0, SEEK_CUR);
186 			if (curoff == POS_ERR)
187 				goto dumb;
188 		}
189 		curoff -= fp->_r;
190 		if (HASUB(fp))
191 			curoff -= fp->_ur;
192 	}
193 
194 	/*
195 	 * Compute the number of bytes in the input buffer (pretending
196 	 * that any ungetc() input has been discarded).  Adjust current
197 	 * offset backwards by this count so that it represents the
198 	 * file offset for the first byte in the current input buffer.
199 	 */
200 	if (HASUB(fp)) {
201 		curoff += fp->_r;	/* kill off ungetc */
202 		n = fp->_up - fp->_bf._base;
203 		curoff -= n;
204 		n += fp->_ur;
205 	} else {
206 		n = fp->_p - fp->_bf._base;
207 		curoff -= n;
208 		n += fp->_r;
209 	}
210 
211 	/*
212 	 * If the target offset is within the current buffer,
213 	 * simply adjust the pointers, clear EOF, undo ungetc(),
214 	 * and return.  (If the buffer was modified, we have to
215 	 * skip this; see fgetln.c.)
216 	 */
217 	if ((fp->_flags & __SMOD) == 0 &&
218 	    target >= curoff && target < curoff + n) {
219 		int o = (int)(target - curoff);
220 
221 		fp->_p = fp->_bf._base + o;
222 		fp->_r = n - o;
223 		if (HASUB(fp))
224 			FREEUB(fp);
225 		fp->_flags &= ~__SEOF;
226 		FUNLOCKFILE(fp);
227 		return (0);
228 	}
229 
230 	/*
231 	 * The place we want to get to is not within the current buffer,
232 	 * but we can still be kind to the kernel copyout mechanism.
233 	 * By aligning the file offset to a block boundary, we can let
234 	 * the kernel use the VM hardware to map pages instead of
235 	 * copying bytes laboriously.  Using a block boundary also
236 	 * ensures that we only read one block, rather than two.
237 	 */
238 	curoff = target & ~(fp->_blksize - 1);
239 	if ((*seekfn)(fp->_cookie, curoff, SEEK_SET) == POS_ERR)
240 		goto dumb;
241 	fp->_r = 0;
242  	fp->_p = fp->_bf._base;
243 	if (HASUB(fp))
244 		FREEUB(fp);
245 	fp->_flags &= ~__SEOF;
246 	n = (int)(target - curoff);
247 	if (n) {
248 		if (__srefill(fp) || fp->_r < n)
249 			goto dumb;
250 		fp->_p += n;
251 		fp->_r -= n;
252 	}
253 	FUNLOCKFILE(fp);
254 	return (0);
255 
256 	/*
257 	 * We get here if we cannot optimise the seek ... just
258 	 * do it.  Allow the seek function to change fp->_bf._base.
259 	 */
260 dumb:
261 	if (__sflush(fp) ||
262 	    (*seekfn)(fp->_cookie, (fpos_t)offset, whence) == POS_ERR) {
263 		FUNLOCKFILE(fp);
264 		return (-1);
265 	}
266 	/* success: clear EOF indicator and discard ungetc() data */
267 	if (HASUB(fp))
268 		FREEUB(fp);
269 	fp->_p = fp->_bf._base;
270 	fp->_r = 0;
271 	/* fp->_w = 0; */	/* unnecessary (I think...) */
272 	fp->_flags &= ~__SEOF;
273 	FUNLOCKFILE(fp);
274 	return (0);
275 }
276