xref: /dragonfly/lib/libc/stdio/fseek.c (revision 1bf4b486)
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  * @(#)fseek.c	8.3 (Berkeley) 1/2/94
37  * $FreeBSD: src/lib/libc/stdio/fseek.c,v 1.9.2.1 2001/03/05 10:56:58 obrien Exp $
38  * $DragonFly: src/lib/libc/stdio/fseek.c,v 1.9 2005/07/23 23:14:44 joerg Exp $
39  */
40 
41 #include "namespace.h"
42 #include <sys/types.h>
43 #include <sys/stat.h>
44 #include <fcntl.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <errno.h>
48 #include "un-namespace.h"
49 
50 #include "local.h"
51 #include "libc_private.h"
52 #include "priv_stdio.h"
53 
54 #define	POS_ERR	(-(fpos_t)1)
55 
56 int
57 fseek(FILE *fp, long offset, int whence)
58 {
59 	return (fseeko(fp, offset, whence));
60 }
61 
62 int
63 fseeko(fp, offset, whence)
64 	FILE *fp;
65 	off_t offset;
66 	int whence;
67 {
68 	int ret;
69 
70 	/* make sure stdio is set up */
71 	if (!__sdidinit)
72 		__sinit();
73 
74 	FLOCKFILE(fp);
75 	ret = _fseeko(fp, offset, whence);
76 	FUNLOCKFILE(fp);
77 	return (ret);
78 }
79 
80 /*
81  * Seek the given file to the given offset.
82  * `Whence' must be one of the three SEEK_* macros.
83  */
84 int
85 _fseeko(FILE *fp, off_t offset, int whence)
86 {
87 	fpos_t (*seekfn) (void *, fpos_t, int);
88 	fpos_t target, curoff;
89 	size_t n;
90 	struct stat st;
91 	int havepos;
92 
93 	/*
94 	 * Have to be able to seek.
95 	 */
96 	if ((seekfn = fp->_seek) == NULL) {
97 		errno = ESPIPE;		/* historic practice */
98 		return (EOF);
99 	}
100 
101 	/*
102 	 * Change any SEEK_CUR to SEEK_SET, and check `whence' argument.
103 	 * After this, whence is either SEEK_SET or SEEK_END.
104 	 */
105 	switch (whence) {
106 
107 	case SEEK_CUR:
108 		/*
109 		 * In order to seek relative to the current stream offset,
110 		 * we have to first find the current stream offset a la
111 		 * ftell (see ftell for details).
112 		 */
113 		if (fp->pub._flags & __SOFF)
114 			curoff = fp->_offset;
115 		else {
116 			curoff = (*seekfn)(fp->_cookie, (fpos_t)0, SEEK_CUR);
117 			if (curoff == -1) {
118 				return (EOF);
119 			}
120 		}
121 		if (fp->pub._flags & __SRD) {
122 			curoff -= fp->pub._r;
123 			if (HASUB(fp))
124 				curoff -= fp->_ur;
125 		} else if (fp->pub._flags & __SWR && fp->pub._p != NULL)
126 			curoff += fp->pub._p - fp->_bf._base;
127 
128 		offset += curoff;
129 		whence = SEEK_SET;
130 		havepos = 1;
131 		break;
132 
133 	case SEEK_SET:
134 	case SEEK_END:
135 		curoff = 0;		/* XXX just to keep gcc quiet */
136 		havepos = 0;
137 		break;
138 
139 	default:
140 		errno = EINVAL;
141 		return (EOF);
142 	}
143 
144 	/*
145 	 * Can only optimise if:
146 	 *	reading (and not reading-and-writing);
147 	 *	not unbuffered; and
148 	 *	this is a `regular' Unix file (and hence seekfn==__sseek).
149 	 * We must check __NBF first, because it is possible to have __NBF
150 	 * and __SOPT both set.
151 	 */
152 	if (fp->_bf._base == NULL)
153 		__smakebuf(fp);
154 	if (fp->pub._flags & (__SWR | __SRW | __SNBF | __SNPT))
155 		goto dumb;
156 	if ((fp->pub._flags & __SOPT) == 0) {
157 		if (seekfn != __sseek ||
158 		    fp->pub._fileno < 0 || _fstat(fp->pub._fileno, &st) ||
159 		    (st.st_mode & S_IFMT) != S_IFREG) {
160 			fp->pub._flags |= __SNPT;
161 			goto dumb;
162 		}
163 		fp->_blksize = st.st_blksize;
164 		fp->pub._flags |= __SOPT;
165 	}
166 
167 	/*
168 	 * We are reading; we can try to optimise.
169 	 * Figure out where we are going and where we are now.
170 	 */
171 	if (whence == SEEK_SET)
172 		target = offset;
173 	else {
174 		if (_fstat(fp->pub._fileno, &st))
175 			goto dumb;
176 		target = st.st_size + offset;
177 	}
178 
179 	if (!havepos) {
180 		if (fp->pub._flags & __SOFF)
181 			curoff = fp->_offset;
182 		else {
183 			curoff = (*seekfn)(fp->_cookie, (fpos_t)0, SEEK_CUR);
184 			if (curoff == POS_ERR)
185 				goto dumb;
186 		}
187 		curoff -= fp->pub._r;
188 		if (HASUB(fp))
189 			curoff -= fp->_ur;
190 	}
191 
192 	/*
193 	 * Compute the number of bytes in the input buffer (pretending
194 	 * that any ungetc() input has been discarded).  Adjust current
195 	 * offset backwards by this count so that it represents the
196 	 * file offset for the first byte in the current input buffer.
197 	 */
198 	if (HASUB(fp)) {
199 		curoff += fp->pub._r;	/* kill off ungetc */
200 		n = fp->_up - fp->_bf._base;
201 		curoff -= n;
202 		n += fp->_ur;
203 	} else {
204 		n = fp->pub._p - fp->_bf._base;
205 		curoff -= n;
206 		n += fp->pub._r;
207 	}
208 
209 	/*
210 	 * If the target offset is within the current buffer,
211 	 * simply adjust the pointers, clear EOF, undo ungetc(),
212 	 * and return.  (If the buffer was modified, we have to
213 	 * skip this; see fgetln.c.)
214 	 */
215 	if ((fp->pub._flags & __SMOD) == 0 &&
216 	    target >= curoff && target < curoff + n) {
217 		int o = target - curoff;
218 
219 		fp->pub._p = fp->_bf._base + o;
220 		fp->pub._r = n - o;
221 		if (HASUB(fp))
222 			FREEUB(fp);
223 		fp->pub._flags &= ~__SEOF;
224 		return (0);
225 	}
226 
227 	/*
228 	 * The place we want to get to is not within the current buffer,
229 	 * but we can still be kind to the kernel copyout mechanism.
230 	 * By aligning the file offset to a block boundary, we can let
231 	 * the kernel use the VM hardware to map pages instead of
232 	 * copying bytes laboriously.  Using a block boundary also
233 	 * ensures that we only read one block, rather than two.
234 	 */
235 	curoff = target & ~(fp->_blksize - 1);
236 	if ((*seekfn)(fp->_cookie, curoff, SEEK_SET) == POS_ERR)
237 		goto dumb;
238 	fp->pub._r = 0;
239 	fp->pub._p = fp->_bf._base;
240 	if (HASUB(fp))
241 		FREEUB(fp);
242 	fp->pub._flags &= ~__SEOF;
243 	n = target - curoff;
244 	if (n) {
245 		if (__srefill(fp) || fp->pub._r < n)
246 			goto dumb;
247 		fp->pub._p += n;
248 		fp->pub._r -= n;
249 	}
250 	return (0);
251 
252 	/*
253 	 * We get here if we cannot optimise the seek ... just
254 	 * do it.  Allow the seek function to change fp->_bf._base.
255 	 */
256 dumb:
257 	if (__sflush(fp) ||
258 	    (*seekfn)(fp->_cookie, (fpos_t)offset, whence) == POS_ERR) {
259 		return (EOF);
260 	}
261 	/* success: clear EOF indicator and discard ungetc() data */
262 	if (HASUB(fp))
263 		FREEUB(fp);
264 	fp->pub._p = fp->_bf._base;
265 	fp->pub._r = 0;
266 	/* fp->pub._w = 0; */	/* unnecessary (I think...) */
267 	fp->pub._flags &= ~__SEOF;
268 	return (0);
269 }
270