xref: /freebsd/lib/libc/stdio/fseek.c (revision 7aa383846770374466b1dcb2cefd71bde9acf463)
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  * 4. 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(fp, offset, whence)
55 	FILE *fp;
56 	long offset;
57 	int whence;
58 {
59 	int ret;
60 	int serrno = errno;
61 
62 	/* make sure stdio is set up */
63 	if (!__sdidinit)
64 		__sinit();
65 
66 	FLOCKFILE(fp);
67 	ret = _fseeko(fp, (off_t)offset, whence, 1);
68 	FUNLOCKFILE(fp);
69 	if (ret == 0)
70 		errno = serrno;
71 	return (ret);
72 }
73 
74 int
75 fseeko(fp, offset, whence)
76 	FILE *fp;
77 	off_t offset;
78 	int whence;
79 {
80 	int ret;
81 	int serrno = errno;
82 
83 	/* make sure stdio is set up */
84 	if (!__sdidinit)
85 		__sinit();
86 
87 	FLOCKFILE(fp);
88 	ret = _fseeko(fp, offset, whence, 0);
89 	FUNLOCKFILE(fp);
90 	if (ret == 0)
91 		errno = serrno;
92 	return (ret);
93 }
94 
95 /*
96  * Seek the given file to the given offset.
97  * `Whence' must be one of the three SEEK_* macros.
98  */
99 int
100 _fseeko(fp, offset, whence, ltest)
101 	FILE *fp;
102 	off_t offset;
103 	int whence;
104 	int ltest;
105 {
106 	fpos_t (*seekfn)(void *, fpos_t, int);
107 	fpos_t target, curoff, ret;
108 	size_t n;
109 	struct stat st;
110 	int havepos;
111 
112 	/*
113 	 * Have to be able to seek.
114 	 */
115 	if ((seekfn = fp->_seek) == NULL) {
116 		errno = ESPIPE;		/* historic practice */
117 		return (-1);
118 	}
119 
120 	/*
121 	 * Change any SEEK_CUR to SEEK_SET, and check `whence' argument.
122 	 * After this, whence is either SEEK_SET or SEEK_END.
123 	 */
124 	switch (whence) {
125 
126 	case SEEK_CUR:
127 		/*
128 		 * In order to seek relative to the current stream offset,
129 		 * we have to first find the current stream offset via
130 		 * ftell (see ftell for details).
131 		 */
132 		if (_ftello(fp, &curoff))
133 			return (-1);
134 		if (curoff < 0) {
135 			/* Unspecified position because of ungetc() at 0 */
136 			errno = ESPIPE;
137 			return (-1);
138 		}
139 		if (offset > 0 && curoff > OFF_MAX - offset) {
140 			errno = EOVERFLOW;
141 			return (-1);
142 		}
143 		offset += curoff;
144 		if (offset < 0) {
145 			errno = EINVAL;
146 			return (-1);
147 		}
148 		if (ltest && offset > LONG_MAX) {
149 			errno = EOVERFLOW;
150 			return (-1);
151 		}
152 		whence = SEEK_SET;
153 		havepos = 1;
154 		break;
155 
156 	case SEEK_SET:
157 		if (offset < 0) {
158 			errno = EINVAL;
159 			return (-1);
160 		}
161 	case SEEK_END:
162 		curoff = 0;		/* XXX just to keep gcc quiet */
163 		havepos = 0;
164 		break;
165 
166 	default:
167 		errno = EINVAL;
168 		return (-1);
169 	}
170 
171 	/*
172 	 * Can only optimise if:
173 	 *	reading (and not reading-and-writing);
174 	 *	not unbuffered; and
175 	 *	this is a `regular' Unix file (and hence seekfn==__sseek).
176 	 * We must check __NBF first, because it is possible to have __NBF
177 	 * and __SOPT both set.
178 	 */
179 	if (fp->_bf._base == NULL)
180 		__smakebuf(fp);
181 	if (fp->_flags & (__SWR | __SRW | __SNBF | __SNPT))
182 		goto dumb;
183 	if ((fp->_flags & __SOPT) == 0) {
184 		if (seekfn != __sseek ||
185 		    fp->_file < 0 || _fstat(fp->_file, &st) ||
186 		    (st.st_mode & S_IFMT) != S_IFREG) {
187 			fp->_flags |= __SNPT;
188 			goto dumb;
189 		}
190 		fp->_blksize = st.st_blksize;
191 		fp->_flags |= __SOPT;
192 	}
193 
194 	/*
195 	 * We are reading; we can try to optimise.
196 	 * Figure out where we are going and where we are now.
197 	 */
198 	if (whence == SEEK_SET)
199 		target = offset;
200 	else {
201 		if (_fstat(fp->_file, &st))
202 			goto dumb;
203 		if (offset > 0 && st.st_size > OFF_MAX - offset) {
204 			errno = EOVERFLOW;
205 			return (-1);
206 		}
207 		target = st.st_size + offset;
208 		if ((off_t)target < 0) {
209 			errno = EINVAL;
210 			return (-1);
211 		}
212 		if (ltest && (off_t)target > LONG_MAX) {
213 			errno = EOVERFLOW;
214 			return (-1);
215 		}
216 	}
217 
218 	if (!havepos && _ftello(fp, &curoff))
219 		goto dumb;
220 
221 	/*
222 	 * (If the buffer was modified, we have to
223 	 * skip this; see fgetln.c.)
224 	 */
225 	if (fp->_flags & __SMOD)
226 		goto abspos;
227 
228 	/*
229 	 * Compute the number of bytes in the input buffer (pretending
230 	 * that any ungetc() input has been discarded).  Adjust current
231 	 * offset backwards by this count so that it represents the
232 	 * file offset for the first byte in the current input buffer.
233 	 */
234 	if (HASUB(fp)) {
235 		curoff += fp->_r;	/* kill off ungetc */
236 		n = fp->_up - fp->_bf._base;
237 		curoff -= n;
238 		n += fp->_ur;
239 	} else {
240 		n = fp->_p - fp->_bf._base;
241 		curoff -= n;
242 		n += fp->_r;
243 	}
244 
245 	/*
246 	 * If the target offset is within the current buffer,
247 	 * simply adjust the pointers, clear EOF, undo ungetc(),
248 	 * and return.
249 	 */
250 	if (target >= curoff && target < curoff + n) {
251 		size_t o = target - curoff;
252 
253 		fp->_p = fp->_bf._base + o;
254 		fp->_r = n - o;
255 		if (HASUB(fp))
256 			FREEUB(fp);
257 		fp->_flags &= ~__SEOF;
258 		memset(&fp->_mbstate, 0, sizeof(mbstate_t));
259 		return (0);
260 	}
261 
262 abspos:
263 	/*
264 	 * The place we want to get to is not within the current buffer,
265 	 * but we can still be kind to the kernel copyout mechanism.
266 	 * By aligning the file offset to a block boundary, we can let
267 	 * the kernel use the VM hardware to map pages instead of
268 	 * copying bytes laboriously.  Using a block boundary also
269 	 * ensures that we only read one block, rather than two.
270 	 */
271 	curoff = target & ~(fp->_blksize - 1);
272 	if (_sseek(fp, curoff, SEEK_SET) == POS_ERR)
273 		goto dumb;
274 	fp->_r = 0;
275 	fp->_p = fp->_bf._base;
276 	if (HASUB(fp))
277 		FREEUB(fp);
278 	n = target - curoff;
279 	if (n) {
280 		if (__srefill(fp) || fp->_r < n)
281 			goto dumb;
282 		fp->_p += n;
283 		fp->_r -= n;
284 	}
285 	fp->_flags &= ~__SEOF;
286 	memset(&fp->_mbstate, 0, sizeof(mbstate_t));
287 	return (0);
288 
289 	/*
290 	 * We get here if we cannot optimise the seek ... just
291 	 * do it.  Allow the seek function to change fp->_bf._base.
292 	 */
293 dumb:
294 	if (__sflush(fp) ||
295 	    (ret = _sseek(fp, (fpos_t)offset, whence)) == POS_ERR)
296 		return (-1);
297 	if (ltest && ret > LONG_MAX) {
298 		fp->_flags |= __SERR;
299 		errno = EOVERFLOW;
300 		return (-1);
301 	}
302 	/* success: clear EOF indicator and discard ungetc() data */
303 	if (HASUB(fp))
304 		FREEUB(fp);
305 	fp->_p = fp->_bf._base;
306 	fp->_r = 0;
307 	/* fp->_w = 0; */	/* unnecessary (I think...) */
308 	fp->_flags &= ~__SEOF;
309 	memset(&fp->_mbstate, 0, sizeof(mbstate_t));
310 	return (0);
311 }
312