blob: 2139621cc25a5e52168d56e732fb1a77b4ce9a1d [file] [log] [blame]
Dmitriy Ivanov623b0d02014-05-14 23:11:05 -07001/* $OpenBSD: findfp.c,v 1.15 2013/12/17 16:33:27 deraadt Exp $ */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002/*-
3 * Copyright (c) 1990, 1993
4 * The Regents of the University of California. All rights reserved.
5 *
6 * This code is derived from software contributed to Berkeley by
7 * Chris Torek.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080034#include <stdio.h>
Elliott Hughes021335e2016-01-19 16:28:15 -080035
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080036#include <errno.h>
Elliott Hughes021335e2016-01-19 16:28:15 -080037#include <fcntl.h>
Elliott Hughes2704bd12016-01-20 17:14:53 -080038#include <limits.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080039#include <stdlib.h>
40#include <string.h>
Elliott Hughes021335e2016-01-19 16:28:15 -080041#include <sys/param.h>
Elliott Hughes023c3072016-01-22 15:04:51 -080042#include <sys/stat.h>
Elliott Hughes021335e2016-01-19 16:28:15 -080043#include <unistd.h>
44
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080045#include "local.h"
46#include "glue.h"
Elliott Hughes023c3072016-01-22 15:04:51 -080047#include "private/ErrnoRestorer.h"
Elliott Hughes6a03abc2014-11-03 12:32:17 -080048#include "private/thread_private.h"
49
50#define ALIGNBYTES (sizeof(uintptr_t) - 1)
51#define ALIGN(p) (((uintptr_t)(p) + ALIGNBYTES) &~ ALIGNBYTES)
Calin Juravlec20de902014-03-20 15:21:32 +000052
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080053#define NDYNAMIC 10 /* add ten more whenever necessary */
54
Elliott Hughes023c3072016-01-22 15:04:51 -080055#define std(flags, file) \
56 {0,0,0,flags,file,{0,0},0,__sF+file,__sclose,__sread,nullptr,__swrite, \
57 {(unsigned char *)(__sFext+file), 0},nullptr,0,{0},{0},{0,0},0,0}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080058
Kenny Rootf5823402011-02-12 07:13:44 -080059_THREAD_PRIVATE_MUTEX(__sfp_mutex);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080060
Elliott Hughes29ee6392015-12-07 11:07:15 -080061// TODO: when we no longer have to support both clang and GCC, we can simplify all this.
62#define SBUF_INIT {0,0}
63#if defined(__LP64__)
64#define MBSTATE_T_INIT {{0},{0}}
65#else
66#define MBSTATE_T_INIT {{0}}
67#endif
68#define WCHAR_IO_DATA_INIT {MBSTATE_T_INIT,MBSTATE_T_INIT,{0},0,0}
69
Elliott Hughesbb46afd2015-12-04 18:03:12 -080070static struct __sfileext __sFext[3] = {
Elliott Hughes023c3072016-01-22 15:04:51 -080071 { SBUF_INIT, WCHAR_IO_DATA_INIT, PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP, false, __sseek64 },
72 { SBUF_INIT, WCHAR_IO_DATA_INIT, PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP, false, __sseek64 },
73 { SBUF_INIT, WCHAR_IO_DATA_INIT, PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP, false, __sseek64 },
Elliott Hughesbb46afd2015-12-04 18:03:12 -080074};
Elliott Hughesf0141df2015-10-12 12:44:23 -070075
76// __sF is exported for backwards compatibility. Until M, we didn't have symbols
77// for stdin/stdout/stderr; they were macros accessing __sF.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080078FILE __sF[3] = {
Elliott Hughesbb46afd2015-12-04 18:03:12 -080079 std(__SRD, STDIN_FILENO),
80 std(__SWR, STDOUT_FILENO),
81 std(__SWR|__SNBF, STDERR_FILENO),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080082};
Elliott Hughesf0141df2015-10-12 12:44:23 -070083
Elliott Hughes168667c2014-11-14 14:42:59 -080084FILE* stdin = &__sF[0];
85FILE* stdout = &__sF[1];
86FILE* stderr = &__sF[2];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080087
Elliott Hughesbb46afd2015-12-04 18:03:12 -080088struct glue __sglue = { NULL, 3, __sF };
89static struct glue* lastglue = &__sglue;
90
Elliott Hughes2704bd12016-01-20 17:14:53 -080091class ScopedFileLock {
92 public:
93 ScopedFileLock(FILE* fp) : fp_(fp) {
94 FLOCKFILE(fp_);
95 }
96 ~ScopedFileLock() {
97 FUNLOCKFILE(fp_);
98 }
99
100 private:
101 FILE* fp_;
102};
103
Elliott Hughes021335e2016-01-19 16:28:15 -0800104static glue* moreglue(int n) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800105 static FILE empty;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800106
Elliott Hughes2704bd12016-01-20 17:14:53 -0800107 char* data = new char[sizeof(glue) + ALIGNBYTES + n * sizeof(FILE) + n * sizeof(__sfileext)];
108 if (data == nullptr) return nullptr;
Elliott Hughes021335e2016-01-19 16:28:15 -0800109
Elliott Hughes2704bd12016-01-20 17:14:53 -0800110 glue* g = reinterpret_cast<glue*>(data);
111 FILE* p = reinterpret_cast<FILE*>(ALIGN(data + sizeof(*g)));
112 __sfileext* pext = reinterpret_cast<__sfileext*>(ALIGN(data + sizeof(*g)) + n * sizeof(FILE));
113 g->next = NULL;
114 g->niobs = n;
115 g->iobs = p;
116 while (--n >= 0) {
117 *p = empty;
118 _FILEEXT_SETUP(p, pext);
119 p++;
120 pext++;
121 }
122 return g;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800123}
124
125/*
126 * Find a free FILE for fopen et al.
127 */
Elliott Hughes021335e2016-01-19 16:28:15 -0800128FILE* __sfp(void) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800129 FILE *fp;
130 int n;
131 struct glue *g;
132
Kenny Rootf5823402011-02-12 07:13:44 -0800133 _THREAD_PRIVATE_MUTEX_LOCK(__sfp_mutex);
134 for (g = &__sglue; g != NULL; g = g->next) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800135 for (fp = g->iobs, n = g->niobs; --n >= 0; fp++)
136 if (fp->_flags == 0)
137 goto found;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800138 }
Kenny Rootf5823402011-02-12 07:13:44 -0800139
140 /* release lock while mallocing */
141 _THREAD_PRIVATE_MUTEX_UNLOCK(__sfp_mutex);
142 if ((g = moreglue(NDYNAMIC)) == NULL)
143 return (NULL);
144 _THREAD_PRIVATE_MUTEX_LOCK(__sfp_mutex);
145 lastglue->next = g;
146 lastglue = g;
147 fp = g->iobs;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800148found:
149 fp->_flags = 1; /* reserve this slot; caller sets real flags */
Kenny Rootf5823402011-02-12 07:13:44 -0800150 _THREAD_PRIVATE_MUTEX_UNLOCK(__sfp_mutex);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800151 fp->_p = NULL; /* no current pointer */
152 fp->_w = 0; /* nothing to read or write */
153 fp->_r = 0;
154 fp->_bf._base = NULL; /* no buffer */
155 fp->_bf._size = 0;
156 fp->_lbfsize = 0; /* not line buffered */
157 fp->_file = -1; /* no file */
Elliott Hughes023c3072016-01-22 15:04:51 -0800158
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800159 fp->_lb._base = NULL; /* no line buffer */
160 fp->_lb._size = 0;
161 _FILEEXT_INIT(fp);
Elliott Hughes023c3072016-01-22 15:04:51 -0800162
163 // Caller sets cookie, _read/_write etc.
164 // We explicitly clear _seek and _seek64 to prevent subtle bugs.
165 fp->_seek = nullptr;
166 _EXT(fp)->_seek64 = nullptr;
167
168 return fp;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800169}
170
Elliott Hughes021335e2016-01-19 16:28:15 -0800171extern "C" __LIBC_HIDDEN__ void __libc_stdio_cleanup(void) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800172 // Equivalent to fflush(nullptr), but without all the locking since we're shutting down anyway.
173 _fwalk(__sflush);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800174}
Elliott Hughes923f1652016-01-19 15:46:05 -0800175
Elliott Hughes023c3072016-01-22 15:04:51 -0800176static FILE* __fopen(int fd, int flags) {
177#if !defined(__LP64__)
178 if (fd > SHRT_MAX) {
179 errno = EMFILE;
180 return nullptr;
181 }
182#endif
183
184 FILE* fp = __sfp();
185 if (fp != nullptr) {
186 fp->_file = fd;
187 fp->_flags = flags;
188 fp->_cookie = fp;
189 fp->_read = __sread;
190 fp->_write = __swrite;
191 fp->_close = __sclose;
192 _EXT(fp)->_seek64 = __sseek64;
193 }
194 return fp;
195}
196
197FILE* fopen(const char* file, const char* mode) {
198 int oflags;
199 int flags = __sflags(mode, &oflags);
200 if (flags == 0) return nullptr;
201
202 int fd = open(file, oflags, DEFFILEMODE);
203 if (fd == -1) {
204 return nullptr;
205 }
206
207 FILE* fp = __fopen(fd, flags);
208 if (fp == nullptr) {
209 ErrnoRestorer errno_restorer;
210 close(fd);
211 return nullptr;
212 }
213
214 // When opening in append mode, even though we use O_APPEND,
215 // we need to seek to the end so that ftell() gets the right
216 // answer. If the user then alters the seek pointer, or
217 // the file extends, this will fail, but there is not much
218 // we can do about this. (We could set __SAPP and check in
219 // fseek and ftell.)
220 // TODO: check in __sseek instead.
221 if (oflags & O_APPEND) __sseek64(fp, 0, SEEK_END);
222
223 return fp;
224}
225
226FILE* fdopen(int fd, const char* mode) {
227 int oflags;
228 int flags = __sflags(mode, &oflags);
229 if (flags == 0) return nullptr;
230
231 // Make sure the mode the user wants is a subset of the actual mode.
232 int fdflags = fcntl(fd, F_GETFL, 0);
233 if (fdflags < 0) return nullptr;
234 int tmp = fdflags & O_ACCMODE;
235 if (tmp != O_RDWR && (tmp != (oflags & O_ACCMODE))) {
236 errno = EINVAL;
237 return nullptr;
238 }
239
240 // If opened for appending, but underlying descriptor does not have
241 // O_APPEND bit set, assert __SAPP so that __swrite() will lseek to
242 // end before each write.
243 // TODO: use fcntl(2) to set O_APPEND instead.
244 if ((oflags & O_APPEND) && !(fdflags & O_APPEND)) flags |= __SAPP;
245
246 // If close-on-exec was requested, then turn it on if not already.
247 if ((oflags & O_CLOEXEC) && !((tmp = fcntl(fd, F_GETFD)) & FD_CLOEXEC)) {
248 fcntl(fd, F_SETFD, tmp | FD_CLOEXEC);
249 }
250
251 return __fopen(fd, flags);
252}
253
254// Re-direct an existing, open (probably) file to some other file.
255// ANSI is written such that the original file gets closed if at
256// all possible, no matter what.
257// TODO: rewrite this mess completely.
258FILE* freopen(const char* file, const char* mode, FILE* fp) {
259 int oflags;
260 int flags = __sflags(mode, &oflags);
261 if (flags == 0) {
262 fclose(fp);
263 return nullptr;
264 }
265
266 ScopedFileLock sfl(fp);
267
268 // There are actually programs that depend on being able to "freopen"
269 // descriptors that weren't originally open. Keep this from breaking.
270 // Remember whether the stream was open to begin with, and which file
271 // descriptor (if any) was associated with it. If it was attached to
272 // a descriptor, defer closing it; freopen("/dev/stdin", "r", stdin)
273 // should work. This is unnecessary if it was not a Unix file.
274 int isopen, wantfd;
275 if (fp->_flags == 0) {
276 fp->_flags = __SEOF; // Hold on to it.
277 isopen = 0;
278 wantfd = -1;
279 } else {
280 // Flush the stream; ANSI doesn't require this.
281 if (fp->_flags & __SWR) __sflush(fp);
282
283 // If close is NULL, closing is a no-op, hence pointless.
284 isopen = fp->_close != NULL;
285 if ((wantfd = fp->_file) < 0 && isopen) {
286 (*fp->_close)(fp->_cookie);
287 isopen = 0;
288 }
289 }
290
291 // Get a new descriptor to refer to the new file.
292 int fd = open(file, oflags, DEFFILEMODE);
293 if (fd < 0 && isopen) {
294 // If out of fd's close the old one and try again.
295 if (errno == ENFILE || errno == EMFILE) {
296 (*fp->_close)(fp->_cookie);
297 isopen = 0;
298 fd = open(file, oflags, DEFFILEMODE);
299 }
300 }
301
302 int sverrno = errno;
303
304 // Finish closing fp. Even if the open succeeded above, we cannot
305 // keep fp->_base: it may be the wrong size. This loses the effect
306 // of any setbuffer calls, but stdio has always done this before.
307 if (isopen && fd != wantfd) (*fp->_close)(fp->_cookie);
308 if (fp->_flags & __SMBF) free(fp->_bf._base);
309 fp->_w = 0;
310 fp->_r = 0;
311 fp->_p = NULL;
312 fp->_bf._base = NULL;
313 fp->_bf._size = 0;
314 fp->_lbfsize = 0;
315 if (HASUB(fp)) FREEUB(fp);
316 _UB(fp)._size = 0;
317 WCIO_FREE(fp);
318 if (HASLB(fp)) FREELB(fp);
319 fp->_lb._size = 0;
320
321 if (fd < 0) { // Did not get it after all.
322 fp->_flags = 0; // Release.
323 errno = sverrno; // Restore errno in case _close clobbered it.
324 return nullptr;
325 }
326
327 // If reopening something that was open before on a real file, try
328 // to maintain the descriptor. Various C library routines (perror)
329 // assume stderr is always fd STDERR_FILENO, even if being freopen'd.
330 if (wantfd >= 0 && fd != wantfd) {
331 if (dup3(fd, wantfd, oflags & O_CLOEXEC) >= 0) {
332 close(fd);
333 fd = wantfd;
334 }
335 }
336
337 // _file is only a short.
338 if (fd > SHRT_MAX) {
339 fp->_flags = 0; // Release.
340 errno = EMFILE;
341 return nullptr;
342 }
343
344 fp->_flags = flags;
345 fp->_file = fd;
346 fp->_cookie = fp;
347 fp->_read = __sread;
348 fp->_write = __swrite;
349 fp->_close = __sclose;
350 _EXT(fp)->_seek64 = __sseek64;
351
352 // When opening in append mode, even though we use O_APPEND,
353 // we need to seek to the end so that ftell() gets the right
354 // answer. If the user then alters the seek pointer, or
355 // the file extends, this will fail, but there is not much
356 // we can do about this. (We could set __SAPP and check in
357 // fseek and ftell.)
358 if (oflags & O_APPEND) __sseek64(fp, 0, SEEK_END);
359 return fp;
360}
361
Elliott Hughes923f1652016-01-19 15:46:05 -0800362int fclose(FILE* fp) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800363 if (fp->_flags == 0) {
364 // Already freed!
365 errno = EBADF;
366 return EOF;
367 }
Elliott Hughes923f1652016-01-19 15:46:05 -0800368
Elliott Hughes2704bd12016-01-20 17:14:53 -0800369 ScopedFileLock sfl(fp);
370 WCIO_FREE(fp);
371 int r = fp->_flags & __SWR ? __sflush(fp) : 0;
372 if (fp->_close != NULL && (*fp->_close)(fp->_cookie) < 0) {
373 r = EOF;
374 }
375 if (fp->_flags & __SMBF) free(fp->_bf._base);
376 if (HASUB(fp)) FREEUB(fp);
377 if (HASLB(fp)) FREELB(fp);
Elliott Hughes923f1652016-01-19 15:46:05 -0800378
Elliott Hughes2704bd12016-01-20 17:14:53 -0800379 // Poison this FILE so accesses after fclose will be obvious.
380 fp->_file = -1;
381 fp->_r = fp->_w = 0;
Elliott Hughes923f1652016-01-19 15:46:05 -0800382
Elliott Hughes2704bd12016-01-20 17:14:53 -0800383 // Release this FILE for reuse.
384 fp->_flags = 0;
385 return r;
Elliott Hughes923f1652016-01-19 15:46:05 -0800386}
387
388int fileno(FILE* fp) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800389 ScopedFileLock sfl(fp);
390 return fileno_unlocked(fp);
Elliott Hughes923f1652016-01-19 15:46:05 -0800391}
Elliott Hughes021335e2016-01-19 16:28:15 -0800392
Elliott Hughes021335e2016-01-19 16:28:15 -0800393int __sread(void* cookie, char* buf, int n) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800394 FILE* fp = reinterpret_cast<FILE*>(cookie);
395 return TEMP_FAILURE_RETRY(read(fp->_file, buf, n));
Elliott Hughes021335e2016-01-19 16:28:15 -0800396}
397
398int __swrite(void* cookie, const char* buf, int n) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800399 FILE* fp = reinterpret_cast<FILE*>(cookie);
400 if (fp->_flags & __SAPP) {
401 // The FILE* is in append mode, but the underlying fd doesn't have O_APPEND set.
402 // We need to seek manually.
Elliott Hughes023c3072016-01-22 15:04:51 -0800403 // TODO: use fcntl(2) to set O_APPEND in fdopen(3) instead?
Elliott Hughes2704bd12016-01-20 17:14:53 -0800404 TEMP_FAILURE_RETRY(lseek64(fp->_file, 0, SEEK_END));
405 }
406 return TEMP_FAILURE_RETRY(write(fp->_file, buf, n));
Elliott Hughes021335e2016-01-19 16:28:15 -0800407}
408
Elliott Hughes021335e2016-01-19 16:28:15 -0800409fpos_t __sseek(void* cookie, fpos_t offset, int whence) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800410 FILE* fp = reinterpret_cast<FILE*>(cookie);
411 return TEMP_FAILURE_RETRY(lseek(fp->_file, offset, whence));
Elliott Hughes021335e2016-01-19 16:28:15 -0800412}
413
Elliott Hughes023c3072016-01-22 15:04:51 -0800414off64_t __sseek64(void* cookie, off64_t offset, int whence) {
415 FILE* fp = reinterpret_cast<FILE*>(cookie);
416 return TEMP_FAILURE_RETRY(lseek64(fp->_file, offset, whence));
417}
418
Elliott Hughes021335e2016-01-19 16:28:15 -0800419int __sclose(void* cookie) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800420 FILE* fp = reinterpret_cast<FILE*>(cookie);
421 return close(fp->_file);
422}
423
Elliott Hughes023c3072016-01-22 15:04:51 -0800424static off64_t __seek_unlocked(FILE* fp, off64_t offset, int whence) {
425 // Use `_seek64` if set, but fall back to `_seek`.
426 if (_EXT(fp)->_seek64 != nullptr) {
427 return (*_EXT(fp)->_seek64)(fp->_cookie, offset, whence);
428 } else if (fp->_seek != nullptr) {
429 return (*fp->_seek)(fp->_cookie, offset, whence);
430 } else {
431 errno = ESPIPE;
432 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800433 }
Elliott Hughes2704bd12016-01-20 17:14:53 -0800434}
435
Elliott Hughes9677fab2016-01-25 15:50:59 -0800436static off64_t __ftello64_unlocked(FILE* fp) {
Elliott Hughes023c3072016-01-22 15:04:51 -0800437 // Find offset of underlying I/O object, then adjust for buffered bytes.
Elliott Hughes2704bd12016-01-20 17:14:53 -0800438 __sflush(fp); // May adjust seek offset on append stream.
Elliott Hughes9677fab2016-01-25 15:50:59 -0800439 off64_t result = __seek_unlocked(fp, 0, SEEK_CUR);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800440 if (result == -1) {
441 return -1;
442 }
443
444 if (fp->_flags & __SRD) {
445 // Reading. Any unread characters (including
446 // those from ungetc) cause the position to be
447 // smaller than that in the underlying object.
448 result -= fp->_r;
449 if (HASUB(fp)) result -= fp->_ur;
450 } else if (fp->_flags & __SWR && fp->_p != NULL) {
451 // Writing. Any buffered characters cause the
452 // position to be greater than that in the
453 // underlying object.
454 result += fp->_p - fp->_bf._base;
455 }
456 return result;
457}
458
Elliott Hughes9677fab2016-01-25 15:50:59 -0800459int __fseeko64(FILE* fp, off64_t offset, int whence, int off_t_bits) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800460 ScopedFileLock sfl(fp);
461
Elliott Hughes023c3072016-01-22 15:04:51 -0800462 // Change any SEEK_CUR to SEEK_SET, and check `whence` argument.
Elliott Hughes2704bd12016-01-20 17:14:53 -0800463 // After this, whence is either SEEK_SET or SEEK_END.
464 if (whence == SEEK_CUR) {
Elliott Hughes9677fab2016-01-25 15:50:59 -0800465 fpos64_t current_offset = __ftello64_unlocked(fp);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800466 if (current_offset == -1) {
Elliott Hughes9677fab2016-01-25 15:50:59 -0800467 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800468 }
469 offset += current_offset;
470 whence = SEEK_SET;
471 } else if (whence != SEEK_SET && whence != SEEK_END) {
472 errno = EINVAL;
Elliott Hughes9677fab2016-01-25 15:50:59 -0800473 return -1;
474 }
475
476 // If our caller has a 32-bit interface, refuse to go past a 32-bit file offset.
477 if (off_t_bits == 32 && offset > LONG_MAX) {
478 errno = EOVERFLOW;
479 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800480 }
481
482 if (fp->_bf._base == NULL) __smakebuf(fp);
483
484 // Flush unwritten data and attempt the seek.
Elliott Hughes023c3072016-01-22 15:04:51 -0800485 if (__sflush(fp) || __seek_unlocked(fp, offset, whence) == -1) {
Elliott Hughes9677fab2016-01-25 15:50:59 -0800486 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800487 }
488
489 // Success: clear EOF indicator and discard ungetc() data.
490 if (HASUB(fp)) FREEUB(fp);
491 fp->_p = fp->_bf._base;
492 fp->_r = 0;
493 /* fp->_w = 0; */ /* unnecessary (I think...) */
494 fp->_flags &= ~__SEOF;
495 return 0;
496}
497
Elliott Hughes9677fab2016-01-25 15:50:59 -0800498int fseeko(FILE* fp, off_t offset, int whence) {
499 static_assert(sizeof(off_t) == sizeof(long), "sizeof(off_t) != sizeof(long)");
500 return __fseeko64(fp, offset, whence, 8*sizeof(off_t));
501}
502__strong_alias(fseek, fseeko);
503
504int fseeko64(FILE* fp, off64_t offset, int whence) {
505 return __fseeko64(fp, offset, whence, 8*sizeof(off_t));
Elliott Hughes2704bd12016-01-20 17:14:53 -0800506}
507
Elliott Hughes9677fab2016-01-25 15:50:59 -0800508int fsetpos(FILE* fp, const fpos_t* pos) {
509 return fseeko(fp, *pos, SEEK_SET);
510}
511
512int fsetpos64(FILE* fp, const fpos64_t* pos) {
513 return fseeko64(fp, *pos, SEEK_SET);
514}
515
Elliott Hughes2704bd12016-01-20 17:14:53 -0800516off_t ftello(FILE* fp) {
Elliott Hughes9677fab2016-01-25 15:50:59 -0800517 static_assert(sizeof(off_t) == sizeof(long), "sizeof(off_t) != sizeof(long)");
518 off64_t result = ftello64(fp);
519 if (result > LONG_MAX) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800520 errno = EOVERFLOW;
521 return -1;
522 }
Elliott Hughes9677fab2016-01-25 15:50:59 -0800523 return result;
524}
525__strong_alias(ftell, ftello);
526
527off64_t ftello64(FILE* fp) {
528 ScopedFileLock sfl(fp);
529 return __ftello64_unlocked(fp);
Elliott Hughes021335e2016-01-19 16:28:15 -0800530}
Elliott Hughes023c3072016-01-22 15:04:51 -0800531
Elliott Hughes023c3072016-01-22 15:04:51 -0800532int fgetpos(FILE* fp, fpos_t* pos) {
533 *pos = ftello(fp);
534 return (*pos == -1);
535}
536
Elliott Hughes9677fab2016-01-25 15:50:59 -0800537int fgetpos64(FILE* fp, fpos64_t* pos) {
538 *pos = ftello64(fp);
539 return (*pos == -1);
Elliott Hughes023c3072016-01-22 15:04:51 -0800540}
Elliott Hughes03e65eb2016-01-26 14:13:04 -0800541
542static FILE* __funopen(const void* cookie,
543 int (*read_fn)(void*, char*, int),
544 int (*write_fn)(void*, const char*, int),
545 int (*close_fn)(void*)) {
546 if (read_fn == nullptr && write_fn == nullptr) {
547 errno = EINVAL;
548 return nullptr;
549 }
550
551 FILE* fp = __sfp();
552 if (fp == nullptr) return nullptr;
553
554 if (read_fn != nullptr && write_fn != nullptr) {
555 fp->_flags = __SRW;
556 } else if (read_fn != nullptr) {
557 fp->_flags = __SRD;
558 } else if (write_fn != nullptr) {
559 fp->_flags = __SWR;
560 }
561
562 fp->_file = -1;
563 fp->_cookie = const_cast<void*>(cookie); // The funopen(3) API is incoherent.
564 fp->_read = read_fn;
565 fp->_write = write_fn;
566 fp->_close = close_fn;
567
568 return fp;
569}
570
571FILE* funopen(const void* cookie,
572 int (*read_fn)(void*, char*, int),
573 int (*write_fn)(void*, const char*, int),
574 fpos_t (*seek_fn)(void*, fpos_t, int),
575 int (*close_fn)(void*)) {
576 FILE* fp = __funopen(cookie, read_fn, write_fn, close_fn);
577 if (fp != nullptr) {
578 fp->_seek = seek_fn;
579 }
580 return fp;
581}
582
583FILE* funopen64(const void* cookie,
584 int (*read_fn)(void*, char*, int),
585 int (*write_fn)(void*, const char*, int),
586 fpos64_t (*seek_fn)(void*, fpos64_t, int),
587 int (*close_fn)(void*)) {
588 FILE* fp = __funopen(cookie, read_fn, write_fn, close_fn);
589 if (fp != nullptr) {
590 _EXT(fp)->_seek64 = seek_fn;
591 }
592 return fp;
593}