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