summaryrefslogtreecommitdiff
path: root/src/stdio
AgeCommit message (Collapse)AuthorLines
2015-03-30correctly handle write errors encountered by printf-family functionsRich Felker-2/+12
previously, write errors neither stopped further output attempts nor caused the function to return an error to the caller. this could result in silent loss of output, possibly in the middle of output in the event of a non-permanent error. the simplest solution is temporarily clearing the error flag for the target stream, then suppressing further output when the error flag is set and checking/restoring it at the end of the operation to determine the correct return value. since the wide version of the code internally calls the narrow fprintf to perform some of its underlying operations, initial clearing of the error flag is suppressed when performing a narrow vfprintf on a wide-oriented stream. this is not a problem since the behavior of narrow operations on wide-oriented streams is undefined. (cherry picked from commit d42269d7c85308abdbf8cee38b1a1097249eb38b)
2015-03-30fix behavior of printf with alt-form octal, zero precision, zero valueRich Felker-1/+1
in this case there are two conflicting rules in play: that an explicit precision of zero with the value zero produces no output, and that the '#' modifier for octal increases the precision sufficiently to yield a leading zero. ISO C (7.19.6.1 paragraph 6 in C99+TC3) includes a parenthetical remark to clarify that the precision-increasing behavior takes precedence, but the corresponding text in POSIX off of which I based the implementation is missing this remark. this issue was covered in WG14 DR#151. (cherry picked from commit b91cdbe2bc8b626aa04dc6e3e84345accf34e4b1)
2015-03-30fix multiple stdio functions' behavior on zero-length operationsRich Felker-9/+7
previously, fgets, fputs, fread, and fwrite completely omitted locking and access to the FILE object when their arguments yielded a zero length read or write operation independent of the FILE state. this optimization was invalid; it wrongly skipped marking the stream as byte-oriented (a C conformance bug) and exposed observably missing synchronization (a POSIX conformance bug) where one of these functions could wrongly complete despite another thread provably holding the lock. (cherry picked from commit 6e2bb7acf42589fb7130b039d0623e2ca42503dd)
2015-03-30suppress null termination when fgets reads EOF with no dataRich Felker-1/+1
the C standard requires that "the contents of the array remain unchanged" in this case. this patch also changes the behavior on read errors, but in that case "the array contents are indeterminate", so the application cannot inspect them anyway. (cherry picked from commit 402611c3ba3be5b3b0486835d98e22ac7ced2722)
2014-07-28work around constant folding bug 61144 in gcc 4.9.0 and 4.9.1Rich Felker-5/+5
previously we detected this bug in configure and issued advice for a workaround, but this turned out not to work. since then gcc 4.9.0 has appeared in several distributions, and now 4.9.1 has been released without a fix despite this being a wrong code generation bug which is supposed to be a release-blocker, per gcc policy. since the scope of the bug seems to affect only data objects (rather than functions) whose definitions are overridable, and there are only a very small number of these in musl, I am just changing them from const to volatile for the time being. simply removing the const would be sufficient to make gcc 4.9.1 work (the non-const case was inadvertently fixed as part of another change in gcc), and this would also be sufficient with 4.9.0 if we forced -O0 on the affected files or on the whole build. however it's cleaner to just remove all the broken compiler detection and use volatile, which will ensure that they are never constant-folded. the quality of a non-broken compiler's output should not be affected except for the fact that these objects are no longer const and thus possibly add a few bytes to data/bss. this change can be reconsidered and possibly reverted at some point in the future when the broken gcc versions are no longer relevant. (cherry picked from commit a6adb2bcd8145353943377d6119c1d7a4242bae1)
2014-07-28simplify __stdio_exit static linking logicRich Felker-11/+8
the purpose of this logic is to avoid linking __stdio_exit unless any stdio reads (which might require repositioning the file offset at exit time) or writes (which might require flushing at exit time) could have been performed. previously, exit called two wrapper functions for __stdio_exit named __flush_on_exit and __seek_on_exit. both of these functions actually performed both tasks (seek and flushing) by calling the underlying __stdio_exit. in order to avoid doing this twice, an overridable data object __towrite_used was used to cause __seek_on_exit to act as a nop when __towrite was linked. now, exit only makes one call, directly to __stdio_exit. this is satisfiable by a weak dummy definition in exit.c, but the real definition is pulled in by either __toread.c or __towrite.c through their referencing a symbol which is defined only in __stdio_exit.c. (cherry picked from commit c463e11eda8326aacee2ac1d516954a9574a2dcd)
2014-07-28fix failure of wide printf/scanf functions to set wide orientationRich Felker-0/+3
in some cases, these functions internally call a byte-based input or output function before calling getwc/putwc, so they cannot rely on the latter to set the orientation. (cherry picked from commit 984c25b74da085c6ae6b44a87bbd5f8afc9be331)
2014-07-28fix incorrect return value for fwide functionRich Felker-1/+2
when the orientation of the stream was already set, fwide was incorrectly returning its argument (the requested orientation) rather than the actual orientation of the stream. (cherry picked from commit ebd8142a6ae19db1a5440d11c01afc7529eae0cd)
2014-04-16fix printf rounding with %g for some corner case midpointsRich Felker-1/+1
the subsequent rounding code assumes the end pointer (z) accurately reflects the end of significance in the decimal expansion, but for certain large integers, spurious trailing zero slots were left behind when applying the binary exponent. issue reported by Morten Welinder; the analysis of the cause was performed by nsz, who also proposed this change. (cherry picked from commit e94d0692864ecf9522fd6a97610a47a2f718d3de)
2014-04-16fix failure of printf %g to strip trailing zeros in some casesRich Felker-1/+1
the code to strip trailing zeros was only looking in the last slot for up to 9 zeros, assuming that the rounding code had already removed fully-zero slots from the end. however, this ignored cases where the rounding code did not run at all, which occur when the value being printed is exactly representable in the requested precision. the simplest solution is to move the code that strips trailing zero slots to run unconditionally, immediately after rounding, rather than as the last step of rounding. (cherry picked from commit 89740868c9f1c84b8ee528468d12df1fa72cd392)
2014-04-16fix carry into uninitialized slots during printf floating point roundingRich Felker-1/+1
in cases where rounding caused a carry, the slot into which the carry was taking place was unconditionally treated as valid, despite the possibility that it could be a new slot prior to the beginning of the existing non-rounded number. in theory this could lead to unbounded runaway carry, but in order for that to happen, the whole uninitialized buffer would need to have been pre-filled with 32-bit integer values greater than or equal to 999999999. patch based on proposed fix by Morten Welinder, who also discovered and reported the bug. (cherry picked from commit 109048e031f39fbb370211fde44ababf6c04c8fb)
2014-03-09fix incorrect rounding in printf floating point corner casesRich Felker-2/+2
the printf floating point formatting code contains an optimization to avoid computing digits that will be thrown away by rounding at the specified (or default) precision. while it was correctly retaining all places up to the last decimal place to be printed, it was not retaining enough precision to see the next nonzero decimal place in all cases. this could cause incorrect rounding down in round-to-even (default) rounding mode, for example, when printing 0.5+DBL_EPSILON with "%.0f". in the fix, LDBL_MANT_DIG/3 is a lazy (non-sharp) upper bound on the number of zeros between any two nonzero decimal digits.
2014-03-09fix buffer overflow in printf formatting of denormals with low bit setRich Felker-1/+2
empirically the overflow was an off-by-one, and it did not seem to be overwriting meaningful data. rather than simply increasing the buffer size by one, however, I have attempted to make the size obviously correct in terms of bounds on the number of iterations for the loops that fill the buffer. this still results in no more than a negligible size increase of the buffer on the stack (6-7 32-bit slots) and is a "safer" fix unless/until somebody wants to do the proof that a smaller buffer would suffice.
2014-02-07in fdopen, avoid setting O_APPEND flag if it's already setRich Felker-1/+2
this saves a syscall in the case where the underlying open already took place with O_APPEND, which is common because fopen with append modes sets O_APPEND at the time of open before passing the file descriptor to __fdopen.
2014-02-07fix ftello result for append streams with unflushed outputRich Felker-1/+4
when there is unflushed output, ftello (and ftell) compute the logical stream position as the underlying file descriptor's offset plus an adjustment for the amount of buffered data. however, this can give the wrong result for append-mode streams where the unflushed writes should adjust the logical position to be at the end of the file, as if a seek to end-of-file takes place before the write. the solution turns out to be a simple trick: when ftello (indirectly) calls lseek to determine the current file offset, use SEEK_END instead of SEEK_CUR if the stream is append-mode and there's unwritten buffered data. the ISO C rules regarding switching between reading and writing for a stream opened in an update mode, along with the POSIX rules regarding switching "active handles", conveniently leave undefined the hypothetical usage cases where this fix might lead to observably incorrect offsets. the bug being fixed was discovered via the test case for glibc issue
2014-01-08add __isoc99_vfscanf weak alias to vfscanfSzabolcs Nagy-0/+2
this glibc abi compatibility function was missed when the scanf aliases were added.
2013-12-12include cleanups: remove unused headers and add feature test macrosSzabolcs Nagy-9/+3
2013-10-07minor vfprintf and vfwprintf changes to please static code analyzersSzabolcs Nagy-6/+11
add missing va_end and remove some unnecessary code.
2013-10-04removed unused variable in vfwprintfRich Felker-2/+1
2013-09-01fix special-case breakage in popen due to reversed argument orderRich Felker-1/+1
2013-08-31fix invalid %m format crash in wide scanf variantsRich Felker-0/+2
the wide variant was missed in the previous commit.
2013-08-31avoid crash in scanf when invalid %m format is encounteredRich Felker-0/+2
invalid format strings invoke undefined behavior, so this is not a conformance issue, but it's nicer for scanf to report the error safely instead of calling free on a potentially-uninitialized pointer or a pointer to memory belonging to the caller.
2013-08-02protect against long double type mismatches (mainly powerpc for now)Rich Felker-0/+7
check in configure to be polite (failing early if we're going to fail) and in vfprintf.c since that is the point at which a mismatching type would be extremely dangerous.
2013-07-20fix uninitialized/stale use of alloc (%m modifier) flag in scanfRich Felker-0/+4
for conversion specifiers, alloc is always set when the specifier is parsed. however, if scanf stops due to mismatching literal text, either an uninitialized (if no conversions have been performed yet) or stale (from the previous conversion) of the flag will be used, possibly causing an invalid pointer to be passed to free when the function returns.
2013-06-22fix scanf %c conversion wrongly storing a terminating null byteRich Felker-4/+8
this seems to have been a regression from the refactoring which added the 'm' modifier.
2013-06-06implement 'm' modifier for wide scanf variantsRich Felker-7/+40
2013-06-05implement the 'm' (malloc) modifier for scanfRich Felker-22/+48
this commit only covers the byte-based scanf-family functions. the wide functions still lack support for the 'm' modifier.
2013-06-05refactor wide-char scanf string handlingRich Felker-55/+32
this brings the wide version of the code into alignment with the byte-based version, in preparation for adding support for the m (malloc) modifier.
2013-06-04simplify some logic in scanf and remove redundant invalid-format checkRich Felker-18/+8
2013-06-04refactor scanf core to use common code path for all string formatsRich Felker-85/+52
the concept here is that %s and %c are essentially special-cases of %[, with some minimal additional special-casing. aside from simplifying the code and reducing the number of complex code-paths that would need changing to make optimizations later, the main purpose of this change is to simplify addition of the 'm' modifier which causes scanf to allocate storage for the string being read.
2013-04-06fix argument omission in ABI-compat weak_alias for fscanfRich Felker-1/+1
2013-04-05Add ABI compatability aliases.Isaac Dunham-0/+33
GNU used several extensions that were incompatible with C99 and POSIX, so they used alternate names for the standard functions. The result is that we need these to run standards-conformant programs that were linked with glibc.
2013-03-24rewrite popen to use posix_spawn instead of fragile vfork hacksRich Felker-41/+41
2012-12-10document self-synchronized destruction issue for stdio lockingRich Felker-0/+10
2012-11-09always add memory streams to stdio open file listRich Felker-18/+21
per interpretation for austin group issue #626, fflush(0) and exit() must block waiting for a lock if another thread has locked a memory stream with flockfile. this adds some otherwise-unnecessary synchronization cost to use of memory streams, but there was already a synchronization cost calling malloc anyway. previously the stream was only added to the open file list in single-threaded programs, so that upon subsequent call to pthread_create, locking could be turned on for the stream.
2012-11-08clean up sloppy nested inclusion from pthread_impl.hRich Felker-0/+4
this mirrors the stdio_impl.h cleanup. one header which is not strictly needed, errno.h, is left in pthread_impl.h, because since pthread functions return their error codes rather than using errno, nearly every single pthread function needs the errno constants. in a few places, rather than bringing in string.h to use memset, the memset was replaced by direct assignment. this seems to generate much better code anyway, and makes many functions which were previously non-leaf functions into leaf functions (possibly eliminating a great deal of bloat on some platforms where non-leaf functions require ugly prologue and/or epilogue).
2012-11-08clean up stdio_impl.hRich Felker-2/+83
this header evolved to facilitate the extremely lazy practice of omitting explicit includes of the necessary headers in individual stdio source files; not only was this sloppy, but it also increased build time. now, stdio_impl.h is only including the headers it needs for its own use; any further headers needed by source files are included directly where needed.
2012-11-01fix more unused variable warningsRich Felker-3/+2
some of these were coming from stdio functions locking files without unlocking them. I believe it's useful for this to throw a warning, so I added a new macro that's self-documenting that the file will never be unlocked to avoid the warning in the few places where it's wrong.
2012-10-27separate getc/putc from fgetc/fputcRich Felker-6/+25
for conformance, two functions should not have the same address. a conforming program could use the addresses of getc and fgetc in ways that assume they are distinct. normally i would just use a wrapper, but these functions are so small and performance-critical that an extra layer of function call could make the one that's a wrapper nearly twice as slow, so I'm just duplicating the code instead.
2012-10-24correct locking in stdio functions that tried to be lock-freeRich Felker-16/+36
these functions must behave as if they obtain the lock via flockfile to satisfy POSIX requirements. since another thread can provably hold the lock when they are called, they must wait to obtain the lock before they can return, even if the correct return value could be obtained without locking. in the case of fclose and freopen, failure to do so could cause correct (albeit obscure) programs to crash or otherwise misbehave; in the case of feof, ferror, and fwide, failure to obtain the lock could sometimes return incorrect results. in any case, having these functions proceed and return while another thread held the lock was wrong.
2012-10-24greatly improve freopen behaviorRich Felker-15/+27
1. don't open /dev/null just as a basis to copy flags; use shared __fmodeflags function to get the right file flags for the mode. 2. handle the case (probably invalid, but whatever) case where the original stream's file descriptor was closed; previously, the logic re-closed it. 3. accept the "e" mode flag for close-on-exec; update dup3 to fallback to using dup2 so we can simply call __dup3 instead of putting fallback logic in freopen itself.
2012-10-24remove useless failure-check from freopen (can't happen)Rich Felker-2/+2
2012-10-21fix copy/paste error in popen changes that broke signalsRich Felker-1/+1
signal mask was not being restored after fork, but instead blocked again.
2012-10-19fix usage of locks with vforkRich Felker-1/+1
__release_ptc() is only valid in the parent; if it's performed in the child, the lock will be unlocked early then double-unlocked later, corrupting the lock state.
2012-10-18avoid raising spurious division-by-zero exception in printfRich Felker-1/+1
2012-10-18overhaul system() and popen() to use vfork; fix various related bugsRich Felker-24/+44
since we target systems without overcommit, special care should be taken that system() and popen(), like posix_spawn(), do not fail in processes whose commit charges are too high to allow ordinary forking. this in turn requires special precautions to ensure that the parent process's signal handlers do not end up running in the shared-memory child, where they could corrupt the state of the parent process. popen has also been updated to use pipe2, so it does not have a fd-leak race in multi-threaded programs. since pipe2 is missing on older kernels, (non-atomic) emulation has been added. some silly bugs in the old code should be gone too.
2012-09-29add 'e' modifier (close-on-exec) to fopen and fdopenRich Felker-2/+5
this feature will be in the next version of POSIX, and can be used internally immediately. there are many internal uses of fopen where close-on-exec is needed to fix bugs.
2012-09-29fix some more O_CLOEXEC/SOCK_CLOEXEC issuesRich Felker-1/+1
2012-09-06fix invalid implicit pointer conversion in gnulib-compat functionsRich Felker-1/+1
2012-09-06use restrict everywhere it's required by c99 and/or posix 2008Rich Felker-43/+43
to deal with the fact that the public headers may be used with pre-c99 compilers, __restrict is used in place of restrict, and defined appropriately for any supported compiler. we also avoid the form [restrict] since older versions of gcc rejected it due to a bug in the original c99 standard, and instead use the form *restrict.