1 /*
2  * Copyright (c) 1990 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms are permitted
6  * provided that the above copyright notice and this paragraph are
7  * duplicated in all such forms and that any documentation,
8  * and/or other materials related to such
9  * distribution and use acknowledge that the software was developed
10  * by the University of California, Berkeley.  The name of the
11  * University may not be used to endorse or promote products derived
12  * from this software without specific prior written permission.
13  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
14  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
15  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
16  */
17 
18 /*
19 FUNCTION
20 <<fseek>>, <<fseeko>>---set file position
21 
22 INDEX
23 	fseek
24 INDEX
25 	fseeko
26 INDEX
27 	_fseek_r
28 INDEX
29 	_fseeko_r
30 
31 SYNOPSIS
32 	#include <stdio.h>
33 	int fseek(FILE *<[fp]>, long <[offset]>, int <[whence]>)
34 	int fseeko(FILE *<[fp]>, off_t <[offset]>, int <[whence]>)
35 	int fseek( FILE *<[fp]>,
36 	             long <[offset]>, int <[whence]>)
37 	int fseeko( FILE *<[fp]>,
38 	             off_t <[offset]>, int <[whence]>)
39 
40 DESCRIPTION
41 Objects of type <<FILE>> can have a ``position'' that records how much
42 of the file your program has already read.  Many of the <<stdio>> functions
43 depend on this position, and many change it as a side effect.
44 
45 You can use <<fseek>>/<<fseeko>> to set the position for the file identified by
46 <[fp]>.  The value of <[offset]> determines the new position, in one
47 of three ways selected by the value of <[whence]> (defined as macros
48 in `<<stdio.h>>'):
49 
50 <<SEEK_SET>>---<[offset]> is the absolute file position (an offset
51 from the beginning of the file) desired.  <[offset]> must be positive.
52 
53 <<SEEK_CUR>>---<[offset]> is relative to the current file position.
54 <[offset]> can meaningfully be either positive or negative.
55 
56 <<SEEK_END>>---<[offset]> is relative to the current end of file.
57 <[offset]> can meaningfully be either positive (to increase the size
58 of the file) or negative.
59 
60 See <<ftell>>/<<ftello>> to determine the current file position.
61 
62 RETURNS
63 <<fseek>>/<<fseeko>> return <<0>> when successful.  On failure, the
64 result is <<EOF>>.  The reason for failure is indicated in <<errno>>:
65 either <<ESPIPE>> (the stream identified by <[fp]> doesn't support
66 repositioning) or <<EINVAL>> (invalid file position).
67 
68 PORTABILITY
69 ANSI C requires <<fseek>>.
70 
71 <<fseeko>> is defined by the Single Unix specification.
72 
73 Supporting OS subroutines required: <<close>>, <<fstat>>, <<isatty>>,
74 <<lseek>>, <<read>>, <<sbrk>>, <<write>>.
75 */
76 
77 #define _DEFAULT_SOURCE
78 #include <stdio.h>
79 #include <string.h>
80 #include <time.h>
81 #include <fcntl.h>
82 #include <stdlib.h>
83 #include <errno.h>
84 #include <sys/stat.h>
85 #include "local.h"
86 
87 #define	POS_ERR	(-(_fpos_t)1)
88 
89 /*
90  * Seek the given file to the given offset.
91  * `Whence' must be one of the three SEEK_* macros.
92  */
93 
94 int
fseeko(register FILE * fp,_off_t offset,int whence)95 fseeko (
96        register FILE *fp,
97        _off_t offset,
98        int whence)
99 {
100   _fpos_t (*seekfn) (void *, _fpos_t, int);
101 #ifdef _FSEEK_OPTIMIZATION
102   _fpos_t target;
103   size_t n;
104 #ifdef __USE_INTERNAL_STAT64
105   struct stat64 st;
106 #else
107   struct stat st;
108 #endif
109 #endif
110   _fpos_t curoff = 0;
111   int havepos;
112 
113   /* Make sure stdio is set up.  */
114 
115   CHECK_INIT (ptr, fp);
116 
117   _newlib_flockfile_start (fp);
118 
119   /* If we've been doing some writing, and we're in append mode
120      then we don't really know where the filepos is.  */
121 
122   if (fp->_flags & __SAPP && fp->_flags & __SWR)
123     {
124       /* So flush the buffer and seek to the end.  */
125       fflush ( fp);
126     }
127 
128   /* Have to be able to seek.  */
129 
130   if ((seekfn = fp->_seek) == NULL)
131     {
132       _REENT_ERRNO(ptr) = ESPIPE;	/* ??? */
133       _newlib_flockfile_exit (fp);
134       return EOF;
135     }
136 
137   /*
138    * Change any SEEK_CUR to SEEK_SET, and check `whence' argument.
139    * After this, whence is either SEEK_SET or SEEK_END.
140    */
141 
142   switch (whence)
143     {
144     case SEEK_CUR:
145       /*
146        * In order to seek relative to the current stream offset,
147        * we have to first find the current stream offset a la
148        * ftell (see ftell for details).
149        */
150       fflush ( fp);   /* may adjust seek offset on append stream */
151       if (fp->_flags & __SOFF)
152 	curoff = fp->_offset;
153       else
154 	{
155 	  curoff = seekfn (fp->_cookie, (_fpos_t) 0, SEEK_CUR);
156 	  if (curoff == -1L)
157 	    {
158 	      _newlib_flockfile_exit (fp);
159 	      return EOF;
160 	    }
161 	}
162       if (fp->_flags & __SRD)
163 	{
164 	  curoff -= fp->_r;
165 	  if (HASUB (fp))
166 	    curoff -= fp->_ur;
167 	}
168       else if (fp->_flags & __SWR && fp->_p != NULL)
169 	curoff += fp->_p - fp->_bf._base;
170 
171       offset += curoff;
172       whence = SEEK_SET;
173       havepos = 1;
174       break;
175 
176     case SEEK_SET:
177     case SEEK_END:
178       havepos = 0;
179       break;
180 
181     default:
182       _REENT_ERRNO(ptr) = EINVAL;
183       _newlib_flockfile_exit (fp);
184       return (EOF);
185     }
186 
187   (void) havepos;
188 
189   /*
190    * Can only optimise if:
191    *	reading (and not reading-and-writing);
192    *	not unbuffered; and
193    *	this is a `regular' Unix file (and hence seekfn==__sseek).
194    * We must check __NBF first, because it is possible to have __NBF
195    * and __SOPT both set.
196    */
197 
198   if (fp->_bf._base == NULL)
199     _smakebuf ( fp);
200 
201 #ifdef _FSEEK_OPTIMIZATION
202   if (fp->_flags & (__SWR | __SRW | __SNBF | __SNPT))
203     goto dumb;
204   if ((fp->_flags & __SOPT) == 0)
205     {
206       if (seekfn != __sseek
207 	  || fp->_file < 0
208 #ifdef __USE_INTERNAL_STAT64
209 	  || _fstat64_r (ptr, fp->_file, &st)
210 #else
211 	  || fstat ( fp->_file, &st)
212 #endif
213 	  || (st.st_mode & S_IFMT) != S_IFREG)
214 	{
215 	  fp->_flags |= __SNPT;
216 	  goto dumb;
217 	}
218 #ifdef	HAVE_BLKSIZE
219       fp->_blksize = st.st_blksize;
220 #else
221       fp->_blksize = 1024;
222 #endif
223       fp->_flags |= __SOPT;
224     }
225 
226   /*
227    * We are reading; we can try to optimise.
228    * Figure out where we are going and where we are now.
229    */
230 
231   if (whence == SEEK_SET)
232     target = offset;
233   else
234     {
235 #ifdef __USE_INTERNAL_STAT64
236       if (_fstat64_r (ptr, fp->_file, &st))
237 #else
238       if (fstat ( fp->_file, &st))
239 #endif
240 	goto dumb;
241       target = st.st_size + offset;
242     }
243 
244   if (!havepos)
245     {
246       if (fp->_flags & __SOFF)
247 	curoff = fp->_offset;
248       else
249 	{
250 	  curoff = seekfn (fp->_cookie, 0L, SEEK_CUR);
251 	  if (curoff == POS_ERR)
252 	    goto dumb;
253 	}
254       curoff -= fp->_r;
255       if (HASUB (fp))
256 	curoff -= fp->_ur;
257     }
258 
259   /*
260    * Compute the number of bytes in the input buffer (pretending
261    * that any ungetc() input has been discarded).  Adjust current
262    * offset backwards by this count so that it represents the
263    * file offset for the first byte in the current input buffer.
264    */
265 
266   if (HASUB (fp))
267     {
268       curoff += fp->_r;       /* kill off ungetc */
269       n = fp->_up - fp->_bf._base;
270       curoff -= n;
271       n += fp->_ur;
272     }
273   else
274     {
275       n = fp->_p - fp->_bf._base;
276       curoff -= n;
277       n += fp->_r;
278     }
279 
280   /*
281    * If the target offset is within the current buffer,
282    * simply adjust the pointers, clear EOF, undo ungetc(),
283    * and return.
284    */
285 
286   if (target >= curoff && (size_t) target < (size_t) curoff + n)
287     {
288       register int o = target - curoff;
289 
290       fp->_p = fp->_bf._base + o;
291       fp->_r = n - o;
292       if (HASUB (fp))
293 	FREEUB (ptr, fp);
294       fp->_flags &= ~__SEOF;
295       memset (&fp->_mbstate, 0, sizeof (_mbstate_t));
296       _newlib_flockfile_exit (fp);
297       return 0;
298     }
299 
300   /*
301    * The place we want to get to is not within the current buffer,
302    * but we can still be kind to the kernel copyout mechanism.
303    * By aligning the file offset to a block boundary, we can let
304    * the kernel use the VM hardware to map pages instead of
305    * copying bytes laboriously.  Using a block boundary also
306    * ensures that we only read one block, rather than two.
307    */
308 
309   curoff = target & ~(fp->_blksize - 1);
310   if (seekfn (fp->_cookie, curoff, SEEK_SET) == POS_ERR)
311     goto dumb;
312   fp->_r = 0;
313   fp->_p = fp->_bf._base;
314   if (HASUB (fp))
315     FREEUB (ptr, fp);
316   fp->_flags &= ~__SEOF;
317   n = target - curoff;
318   if (n)
319     {
320       if (_srefill ( fp) || fp->_r < (int) n)
321 	goto dumb;
322       fp->_p += n;
323       fp->_r -= n;
324     }
325   memset (&fp->_mbstate, 0, sizeof (_mbstate_t));
326   _newlib_flockfile_exit (fp);
327   return 0;
328 
329   /*
330    * We get here if we cannot optimise the seek ... just
331    * do it.  Allow the seek function to change fp->_bf._base.
332    */
333 dumb:
334 #endif
335 
336   if (fflush ( fp)
337       || seekfn (fp->_cookie, offset, whence) == POS_ERR)
338     {
339       _newlib_flockfile_exit (fp);
340       return EOF;
341     }
342   /* success: clear EOF indicator and discard ungetc() data */
343   if (HASUB (fp))
344     FREEUB (ptr, fp);
345   fp->_p = fp->_bf._base;
346   fp->_r = 0;
347   /* fp->_w = 0; *//* unnecessary (I think...) */
348   fp->_flags &= ~__SEOF;
349   /* Reset no-optimization flag after successful seek.  The
350      no-optimization flag may be set in the case of a read
351      stream that is flushed which by POSIX/SUSv3 standards,
352      means that a corresponding seek must not optimize.  The
353      optimization is then allowed if no subsequent flush
354      is performed.  */
355   fp->_flags &= ~__SNPT;
356   memset (&fp->_mbstate, 0, sizeof (_mbstate_t));
357   _newlib_flockfile_end (fp);
358   return 0;
359 }
360