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