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