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