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