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