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