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