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 <<setvbuf>>---specify file or stream buffering
21 
22 INDEX
23 	setvbuf
24 
25 SYNOPSIS
26 	#include <stdio.h>
27 	int setvbuf(FILE *<[fp]>, char *<[buf]>,
28 	            int <[mode]>, size_t <[size]>);
29 
30 DESCRIPTION
31 Use <<setvbuf>> to specify what kind of buffering you want for the
32 file or stream identified by <[fp]>, by using one of the following
33 values (from <<stdio.h>>) as the <[mode]> argument:
34 
35 o+
36 o _IONBF
37 Do not use a buffer: send output directly to the host system for the
38 file or stream identified by <[fp]>.
39 
40 o _IOFBF
41 Use full output buffering: output will be passed on to the host system
42 only when the buffer is full, or when an input operation intervenes.
43 
44 o _IOLBF
45 Use line buffering: pass on output to the host system at every
46 newline, as well as when the buffer is full, or when an input
47 operation intervenes.
48 o-
49 
50 Use the <[size]> argument to specify how large a buffer you wish.  You
51 can supply the buffer itself, if you wish, by passing a pointer to a
52 suitable area of memory as <[buf]>.  Otherwise, you may pass <<NULL>>
53 as the <[buf]> argument, and <<setvbuf>> will allocate the buffer.
54 
55 WARNINGS
56 You may only use <<setvbuf>> before performing any file operation other
57 than opening the file.
58 
59 If you supply a non-null <[buf]>, you must ensure that the associated
60 storage continues to be available until you close the stream
61 identified by <[fp]>.
62 
63 RETURNS
64 A <<0>> result indicates success, <<EOF>> failure (invalid <[mode]> or
65 <[size]> can cause failure).
66 
67 PORTABILITY
68 Both ANSI C and the System V Interface Definition (Issue 2) require
69 <<setvbuf>>. However, they differ on the meaning of a <<NULL>> buffer
70 pointer: the SVID issue 2 specification says that a <<NULL>> buffer
71 pointer requests unbuffered output.  For maximum portability, avoid
72 <<NULL>> buffer pointers.
73 
74 Both specifications describe the result on failure only as a
75 nonzero value.
76 
77 Supporting OS subroutines required: <<close>>, <<fstat>>, <<isatty>>,
78 <<lseek>>, <<read>>, <<sbrk>>, <<write>>.
79 */
80 
81 #define _DEFAULT_SOURCE
82 #include <stdio.h>
83 #include <stdlib.h>
84 #include "local.h"
85 
86 /*
87  * Set one of the three kinds of buffering, optionally including a buffer.
88  */
89 
90 int
setvbuf(register FILE * fp,char * buf,register int mode,register size_t size)91 setvbuf (register FILE * fp,
92        char *buf,
93        register int mode,
94        register size_t size)
95 {
96   int ret = 0;
97   size_t iosize;
98   int ttyflag;
99 
100   CHECK_INIT (reent, fp);
101 
102   /*
103    * Verify arguments.  The `int' limit on `size' is due to this
104    * particular implementation.  Note, buf and size are ignored
105    * when setting _IONBF.
106    */
107   if (mode != _IONBF)
108     if ((mode != _IOFBF && mode != _IOLBF) || (int)(_POINTER_INT) size < 0)
109       return (EOF);
110 
111 
112   /*
113    * Write current buffer, if any; drop read count, if any.
114    * Make sure putc() will not think fp is line buffered.
115    * Free old buffer if it was from malloc().  Clear line and
116    * non buffer flags, and clear malloc flag.
117    */
118   _newlib_flockfile_start (fp);
119   fflush ( fp);
120   if (HASUB(fp))
121     FREEUB(reent, fp);
122   fp->_r = fp->_lbfsize = 0;
123   if (fp->_flags & __SMBF)
124     free ((void *) fp->_bf._base);
125   fp->_flags &= ~(__SLBF | __SNBF | __SMBF | __SOPT | __SNPT | __SEOF);
126 
127   if (mode == _IONBF)
128     goto nbf;
129 
130   /*
131    * Find optimal I/O size for seek optimization.  This also returns
132    * a `tty flag' to suggest that we check isatty(fd), but we do not
133    * care since our caller told us how to buffer.
134    */
135   fp->_flags |= _swhatbuf ( fp, &iosize, &ttyflag);
136   if (size == 0)
137     {
138       buf = NULL;
139       size = iosize;
140     }
141 
142   /* Allocate buffer if needed. */
143   if (buf == NULL)
144     {
145       if ((buf = malloc (size)) == NULL)
146 	{
147 	  /*
148 	   * Unable to honor user's request.  We will return
149 	   * failure, but try again with file system size.
150 	   */
151 	  ret = EOF;
152 	  if (size != iosize)
153 	    {
154 	      size = iosize;
155 	      buf = malloc (size);
156 	    }
157 	}
158       if (buf == NULL)
159         {
160           /* No luck; switch to unbuffered I/O. */
161 nbf:
162           fp->_flags |= __SNBF;
163           fp->_w = 0;
164           fp->_bf._base = fp->_p = fp->_nbuf;
165           fp->_bf._size = 1;
166           _newlib_flockfile_exit (fp);
167           return (ret);
168         }
169       fp->_flags |= __SMBF;
170     }
171 
172   /*
173    * We're committed to buffering from here, so make sure we've
174    * registered to flush buffers on exit.
175    */
176   if (!_REENT_CLEANUP(reent))
177     __sinit();
178 
179 #ifdef _FSEEK_OPTIMIZATION
180   /*
181    * Kill any seek optimization if the buffer is not the
182    * right size.
183    *
184    * SHOULD WE ALLOW MULTIPLES HERE (i.e., ok iff (size % iosize) == 0)?
185    */
186   if (size != iosize)
187      fp->_flags |= __SNPT;
188 #endif
189 
190   /*
191    * Fix up the FILE fields, and set __cleanup for output flush on
192    * exit (since we are buffered in some way).
193    */
194   if (mode == _IOLBF)
195     fp->_flags |= __SLBF;
196   fp->_bf._base = fp->_p = (unsigned char *) buf;
197   fp->_bf._size = size;
198   /* fp->_lbfsize is still 0 */
199   if (fp->_flags & __SWR)
200     {
201       /*
202        * Begin or continue writing: see __swsetup().  Note
203        * that __SNBF is impossible (it was handled earlier).
204        */
205       if (fp->_flags & __SLBF)
206 	{
207 	  fp->_w = 0;
208 	  fp->_lbfsize = -fp->_bf._size;
209 	}
210       else
211         fp->_w = size;
212     }
213   else
214     {
215       /* begin/continue reading, or stay in intermediate state */
216       fp->_w = 0;
217     }
218 
219   _newlib_flockfile_end (fp);
220   return 0;
221 }
222