source: mainline/uspace/lib/c/generic/io/io.c@ e86a617a

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since e86a617a was e86a617a, checked in by Jiri Svoboda <jiri@…>, 9 years ago

Fix fread() returning bogus data due to uninitialized ungetc_chars field of FILE structure.

  • Property mode set to 100644
File size: 16.7 KB
Line 
1/*
2 * Copyright (c) 2005 Martin Decky
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * - Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * - The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29/** @addtogroup libc
30 * @{
31 */
32/** @file
33 */
34
35#include <stdio.h>
36#include <unistd.h>
37#include <fcntl.h>
38#include <assert.h>
39#include <str.h>
40#include <errno.h>
41#include <stdbool.h>
42#include <malloc.h>
43#include <async.h>
44#include <io/kio.h>
45#include <vfs/vfs.h>
46#include <vfs/vfs_sess.h>
47#include <ipc/loc.h>
48#include <adt/list.h>
49#include "../private/io.h"
50#include "../private/stdio.h"
51
52static void _ffillbuf(FILE *stream);
53static void _fflushbuf(FILE *stream);
54
55static FILE stdin_null = {
56 .fd = -1,
57 .error = true,
58 .eof = true,
59 .kio = false,
60 .sess = NULL,
61 .btype = _IONBF,
62 .buf = NULL,
63 .buf_size = 0,
64 .buf_head = NULL,
65 .buf_tail = NULL,
66 .buf_state = _bs_empty
67};
68
69static FILE stdout_kio = {
70 .fd = -1,
71 .error = false,
72 .eof = false,
73 .kio = true,
74 .sess = NULL,
75 .btype = _IOLBF,
76 .buf = NULL,
77 .buf_size = BUFSIZ,
78 .buf_head = NULL,
79 .buf_tail = NULL,
80 .buf_state = _bs_empty
81};
82
83static FILE stderr_kio = {
84 .fd = -1,
85 .error = false,
86 .eof = false,
87 .kio = true,
88 .sess = NULL,
89 .btype = _IONBF,
90 .buf = NULL,
91 .buf_size = 0,
92 .buf_head = NULL,
93 .buf_tail = NULL,
94 .buf_state = _bs_empty
95};
96
97FILE *stdin = NULL;
98FILE *stdout = NULL;
99FILE *stderr = NULL;
100
101static LIST_INITIALIZE(files);
102
103void __stdio_init(int filc)
104{
105 if (filc > 0) {
106 stdin = fdopen(0, "r");
107 } else {
108 stdin = &stdin_null;
109 list_append(&stdin->link, &files);
110 }
111
112 if (filc > 1) {
113 stdout = fdopen(1, "w");
114 } else {
115 stdout = &stdout_kio;
116 list_append(&stdout->link, &files);
117 }
118
119 if (filc > 2) {
120 stderr = fdopen(2, "w");
121 } else {
122 stderr = &stderr_kio;
123 list_append(&stderr->link, &files);
124 }
125}
126
127void __stdio_done(void)
128{
129 while (!list_empty(&files)) {
130 FILE *file = list_get_instance(list_first(&files), FILE, link);
131 fclose(file);
132 }
133}
134
135static bool parse_mode(const char *mode, int *flags)
136{
137 /* Parse mode except first character. */
138 const char *mp = mode;
139 if (*mp++ == 0) {
140 errno = EINVAL;
141 return false;
142 }
143
144 if ((*mp == 'b') || (*mp == 't'))
145 mp++;
146
147 bool plus;
148 if (*mp == '+') {
149 mp++;
150 plus = true;
151 } else
152 plus = false;
153
154 if (*mp != 0) {
155 errno = EINVAL;
156 return false;
157 }
158
159 /* Parse first character of mode and determine flags for open(). */
160 switch (mode[0]) {
161 case 'r':
162 *flags = plus ? O_RDWR : O_RDONLY;
163 break;
164 case 'w':
165 *flags = (O_TRUNC | O_CREAT) | (plus ? O_RDWR : O_WRONLY);
166 break;
167 case 'a':
168 /* TODO: a+ must read from beginning, append to the end. */
169 if (plus) {
170 errno = ENOTSUP;
171 return false;
172 }
173 *flags = (O_APPEND | O_CREAT) | (plus ? O_RDWR : O_WRONLY);
174 break;
175 default:
176 errno = EINVAL;
177 return false;
178 }
179
180 return true;
181}
182
183/** Set stream buffer. */
184void setvbuf(FILE *stream, void *buf, int mode, size_t size)
185{
186 stream->btype = mode;
187 stream->buf = buf;
188 stream->buf_size = size;
189 stream->buf_head = stream->buf;
190 stream->buf_tail = stream->buf;
191 stream->buf_state = _bs_empty;
192}
193
194/** Set stream buffer.
195 *
196 * When @p buf is NULL, the stream is set as unbuffered, otherwise
197 * full buffering is enabled.
198 */
199void setbuf(FILE *stream, void *buf)
200{
201 if (buf == NULL) {
202 setvbuf(stream, NULL, _IONBF, BUFSIZ);
203 } else {
204 setvbuf(stream, buf, _IOFBF, BUFSIZ);
205 }
206}
207
208static void _setvbuf(FILE *stream)
209{
210 /* FIXME: Use more complex rules for setting buffering options. */
211
212 switch (stream->fd) {
213 case 1:
214 setvbuf(stream, NULL, _IOLBF, BUFSIZ);
215 break;
216 case 0:
217 case 2:
218 setvbuf(stream, NULL, _IONBF, 0);
219 break;
220 default:
221 setvbuf(stream, NULL, _IOFBF, BUFSIZ);
222 }
223}
224
225/** Allocate stream buffer. */
226static int _fallocbuf(FILE *stream)
227{
228 assert(stream->buf == NULL);
229
230 stream->buf = malloc(stream->buf_size);
231 if (stream->buf == NULL) {
232 errno = ENOMEM;
233 return EOF;
234 }
235
236 stream->buf_head = stream->buf;
237 stream->buf_tail = stream->buf;
238 return 0;
239}
240
241/** Open a stream.
242 *
243 * @param path Path of the file to open.
244 * @param mode Mode string, (r|w|a)[b|t][+].
245 *
246 */
247FILE *fopen(const char *path, const char *mode)
248{
249 int flags;
250 if (!parse_mode(mode, &flags))
251 return NULL;
252
253 /* Open file. */
254 FILE *stream = malloc(sizeof(FILE));
255 if (stream == NULL) {
256 errno = ENOMEM;
257 return NULL;
258 }
259
260 stream->fd = open(path, flags, 0666);
261 if (stream->fd < 0) {
262 /* errno was set by open() */
263 free(stream);
264 return NULL;
265 }
266
267 stream->error = false;
268 stream->eof = false;
269 stream->kio = false;
270 stream->sess = NULL;
271 stream->need_sync = false;
272 _setvbuf(stream);
273 stream->ungetc_chars = 0;
274
275 list_append(&stream->link, &files);
276
277 return stream;
278}
279
280FILE *fdopen(int fd, const char *mode)
281{
282 /* Open file. */
283 FILE *stream = malloc(sizeof(FILE));
284 if (stream == NULL) {
285 errno = ENOMEM;
286 return NULL;
287 }
288
289 stream->fd = fd;
290 stream->error = false;
291 stream->eof = false;
292 stream->kio = false;
293 stream->sess = NULL;
294 stream->need_sync = false;
295 _setvbuf(stream);
296 stream->ungetc_chars = 0;
297
298 list_append(&stream->link, &files);
299
300 return stream;
301}
302
303
304static int _fclose_nofree(FILE *stream)
305{
306 int rc = 0;
307
308 fflush(stream);
309
310 if (stream->sess != NULL)
311 async_hangup(stream->sess);
312
313 if (stream->fd >= 0)
314 rc = close(stream->fd);
315
316 list_remove(&stream->link);
317
318 if (rc != 0) {
319 /* errno was set by close() */
320 return EOF;
321 }
322
323 return 0;
324}
325
326int fclose(FILE *stream)
327{
328 int rc = _fclose_nofree(stream);
329
330 if ((stream != &stdin_null)
331 && (stream != &stdout_kio)
332 && (stream != &stderr_kio))
333 free(stream);
334
335 return rc;
336}
337
338FILE *freopen(const char *path, const char *mode, FILE *stream)
339{
340 FILE *nstr;
341
342 if (path == NULL) {
343 /* Changing mode is not supported */
344 return NULL;
345 }
346
347 (void) _fclose_nofree(stream);
348 nstr = fopen(path, mode);
349 if (nstr == NULL) {
350 free(stream);
351 return NULL;
352 }
353
354 list_remove(&nstr->link);
355 *stream = *nstr;
356 list_append(&stream->link, &files);
357
358 free(nstr);
359
360 return stream;
361}
362
363/** Read from a stream (unbuffered).
364 *
365 * @param buf Destination buffer.
366 * @param size Size of each record.
367 * @param nmemb Number of records to read.
368 * @param stream Pointer to the stream.
369 *
370 * @return Number of elements successfully read. On error this is less than
371 * nmemb, stream error indicator is set and errno is set.
372 */
373static size_t _fread(void *buf, size_t size, size_t nmemb, FILE *stream)
374{
375 size_t left, done;
376
377 if (size == 0 || nmemb == 0)
378 return 0;
379
380 left = size * nmemb;
381 done = 0;
382
383 while ((left > 0) && (!stream->error) && (!stream->eof)) {
384 ssize_t rd = read(stream->fd, buf + done, left);
385
386 if (rd < 0) {
387 /* errno was set by read() */
388 stream->error = true;
389 } else if (rd == 0) {
390 stream->eof = true;
391 } else {
392 left -= rd;
393 done += rd;
394 }
395 }
396
397 return (done / size);
398}
399
400/** Write to a stream (unbuffered).
401 *
402 * @param buf Source buffer.
403 * @param size Size of each record.
404 * @param nmemb Number of records to write.
405 * @param stream Pointer to the stream.
406 *
407 * @return Number of elements successfully written. On error this is less than
408 * nmemb, stream error indicator is set and errno is set.
409 */
410static size_t _fwrite(const void *buf, size_t size, size_t nmemb, FILE *stream)
411{
412 size_t left;
413 size_t done;
414 int rc;
415
416 if (size == 0 || nmemb == 0)
417 return 0;
418
419 left = size * nmemb;
420 done = 0;
421
422 while ((left > 0) && (!stream->error)) {
423 ssize_t wr;
424 size_t uwr;
425
426 if (stream->kio) {
427 uwr = 0;
428 rc = kio_write(buf + done, left, &uwr);
429 if (rc != EOK)
430 errno = rc;
431 } else {
432 wr = write(stream->fd, buf + done, left);
433 if (wr >= 0) {
434 uwr = (size_t)wr;
435 rc = EOK;
436 } else {
437 /* errno was set by write */
438 uwr = 0;
439 rc = errno;
440 }
441 }
442
443 if (rc != EOK) {
444 /* errno was set above */
445 stream->error = true;
446 } else {
447 left -= uwr;
448 done += uwr;
449 }
450 }
451
452 if (done > 0)
453 stream->need_sync = true;
454
455 return (done / size);
456}
457
458/** Read some data in stream buffer.
459 *
460 * On error, stream error indicator is set and errno is set.
461 */
462static void _ffillbuf(FILE *stream)
463{
464 ssize_t rc;
465
466 stream->buf_head = stream->buf_tail = stream->buf;
467
468 rc = read(stream->fd, stream->buf, stream->buf_size);
469 if (rc < 0) {
470 /* errno was set by read() */
471 stream->error = true;
472 return;
473 }
474
475 if (rc == 0) {
476 stream->eof = true;
477 return;
478 }
479
480 stream->buf_head += rc;
481 stream->buf_state = _bs_read;
482}
483
484/** Write out stream buffer, do not sync stream. */
485static void _fflushbuf(FILE *stream)
486{
487 size_t bytes_used;
488
489 if ((!stream->buf) || (stream->btype == _IONBF) || (stream->error))
490 return;
491
492 bytes_used = stream->buf_head - stream->buf_tail;
493
494 /* If buffer has prefetched read data, we need to seek back. */
495 if (bytes_used > 0 && stream->buf_state == _bs_read) {
496 off64_t rc;
497 rc = lseek(stream->fd, - (ssize_t) bytes_used, SEEK_CUR);
498 if (rc == (off64_t)-1) {
499 /* errno was set by lseek */
500 stream->error = 1;
501 return;
502 }
503 }
504
505 /* If buffer has unwritten data, we need to write them out. */
506 if (bytes_used > 0 && stream->buf_state == _bs_write) {
507 (void) _fwrite(stream->buf_tail, 1, bytes_used, stream);
508 /* On error stream error indicator and errno are set by _fwrite */
509 if (stream->error)
510 return;
511 }
512
513 stream->buf_head = stream->buf;
514 stream->buf_tail = stream->buf;
515 stream->buf_state = _bs_empty;
516}
517
518/** Read from a stream.
519 *
520 * @param dest Destination buffer.
521 * @param size Size of each record.
522 * @param nmemb Number of records to read.
523 * @param stream Pointer to the stream.
524 *
525 */
526size_t fread(void *dest, size_t size, size_t nmemb, FILE *stream)
527{
528 uint8_t *dp;
529 size_t bytes_left;
530 size_t now;
531 size_t data_avail;
532 size_t total_read;
533 size_t i;
534
535 if (size == 0 || nmemb == 0)
536 return 0;
537
538 bytes_left = size * nmemb;
539 total_read = 0;
540 dp = (uint8_t *) dest;
541
542 /* Bytes from ungetc() buffer */
543 while (stream->ungetc_chars > 0 && bytes_left > 0) {
544 *dp++ = stream->ungetc_buf[--stream->ungetc_chars];
545 ++total_read;
546 --bytes_left;
547 }
548
549 /* If not buffered stream, read in directly. */
550 if (stream->btype == _IONBF) {
551 total_read += _fread(dest, 1, bytes_left, stream);
552 return total_read / size;
553 }
554
555 /* Make sure no data is pending write. */
556 if (stream->buf_state == _bs_write)
557 _fflushbuf(stream);
558
559 /* Perform lazy allocation of stream buffer. */
560 if (stream->buf == NULL) {
561 if (_fallocbuf(stream) != 0)
562 return 0; /* Errno set by _fallocbuf(). */
563 }
564
565 while ((!stream->error) && (!stream->eof) && (bytes_left > 0)) {
566 if (stream->buf_head == stream->buf_tail)
567 _ffillbuf(stream);
568
569 if (stream->error || stream->eof) {
570 /* On error errno was set by _ffillbuf() */
571 break;
572 }
573
574 data_avail = stream->buf_head - stream->buf_tail;
575
576 if (bytes_left > data_avail)
577 now = data_avail;
578 else
579 now = bytes_left;
580
581 for (i = 0; i < now; i++) {
582 dp[i] = stream->buf_tail[i];
583 }
584
585 dp += now;
586 stream->buf_tail += now;
587 bytes_left -= now;
588 total_read += now;
589 }
590
591 return (total_read / size);
592}
593
594
595/** Write to a stream.
596 *
597 * @param buf Source buffer.
598 * @param size Size of each record.
599 * @param nmemb Number of records to write.
600 * @param stream Pointer to the stream.
601 *
602 */
603size_t fwrite(const void *buf, size_t size, size_t nmemb, FILE *stream)
604{
605 uint8_t *data;
606 size_t bytes_left;
607 size_t now;
608 size_t buf_free;
609 size_t total_written;
610 size_t i;
611 uint8_t b;
612 bool need_flush;
613
614 if (size == 0 || nmemb == 0)
615 return 0;
616
617 /* If not buffered stream, write out directly. */
618 if (stream->btype == _IONBF) {
619 now = _fwrite(buf, size, nmemb, stream);
620 fflush(stream);
621 return now;
622 }
623
624 /* Make sure buffer contains no prefetched data. */
625 if (stream->buf_state == _bs_read)
626 _fflushbuf(stream);
627
628 /* Perform lazy allocation of stream buffer. */
629 if (stream->buf == NULL) {
630 if (_fallocbuf(stream) != 0)
631 return 0; /* Errno set by _fallocbuf(). */
632 }
633
634 data = (uint8_t *) buf;
635 bytes_left = size * nmemb;
636 total_written = 0;
637 need_flush = false;
638
639 while ((!stream->error) && (bytes_left > 0)) {
640 buf_free = stream->buf_size - (stream->buf_head - stream->buf);
641 if (bytes_left > buf_free)
642 now = buf_free;
643 else
644 now = bytes_left;
645
646 for (i = 0; i < now; i++) {
647 b = data[i];
648 stream->buf_head[i] = b;
649
650 if ((b == '\n') && (stream->btype == _IOLBF))
651 need_flush = true;
652 }
653
654 data += now;
655 stream->buf_head += now;
656 buf_free -= now;
657 bytes_left -= now;
658 total_written += now;
659 stream->buf_state = _bs_write;
660
661 if (buf_free == 0) {
662 /* Only need to drain buffer. */
663 _fflushbuf(stream);
664 if (!stream->error)
665 need_flush = false;
666 }
667 }
668
669 if (need_flush)
670 fflush(stream);
671
672 return (total_written / size);
673}
674
675int fputc(wchar_t c, FILE *stream)
676{
677 char buf[STR_BOUNDS(1)];
678 size_t sz = 0;
679
680 if (chr_encode(c, buf, &sz, STR_BOUNDS(1)) == EOK) {
681 size_t wr = fwrite(buf, 1, sz, stream);
682
683 if (wr < sz)
684 return EOF;
685
686 return (int) c;
687 }
688
689 return EOF;
690}
691
692int putchar(wchar_t c)
693{
694 return fputc(c, stdout);
695}
696
697int fputs(const char *str, FILE *stream)
698{
699 (void) fwrite(str, str_size(str), 1, stream);
700 if (ferror(stream))
701 return EOF;
702 return 0;
703}
704
705int puts(const char *str)
706{
707 return fputs(str, stdout);
708}
709
710int fgetc(FILE *stream)
711{
712 char c;
713
714 /* This could be made faster by only flushing when needed. */
715 if (stdout)
716 fflush(stdout);
717 if (stderr)
718 fflush(stderr);
719
720 if (fread(&c, sizeof(char), 1, stream) < sizeof(char))
721 return EOF;
722
723 return (int) c;
724}
725
726char *fgets(char *str, int size, FILE *stream)
727{
728 int c;
729 int idx;
730
731 idx = 0;
732 while (idx < size - 1) {
733 c = fgetc(stream);
734 if (c == EOF)
735 break;
736
737 str[idx++] = c;
738
739 if (c == '\n')
740 break;
741 }
742
743 if (ferror(stream))
744 return NULL;
745
746 if (idx == 0)
747 return NULL;
748
749 str[idx] = '\0';
750 return str;
751}
752
753int getchar(void)
754{
755 return fgetc(stdin);
756}
757
758int ungetc(int c, FILE *stream)
759{
760 if (c == EOF)
761 return EOF;
762
763 if (stream->ungetc_chars >= UNGETC_MAX)
764 return EOF;
765
766 stream->ungetc_buf[stream->ungetc_chars++] =
767 (uint8_t)c;
768
769 stream->eof = false;
770 return (uint8_t)c;
771}
772
773int fseek(FILE *stream, off64_t offset, int whence)
774{
775 off64_t rc;
776
777 if (stream->error)
778 return EOF;
779
780 _fflushbuf(stream);
781 if (stream->error) {
782 /* errno was set by _fflushbuf() */
783 return EOF;
784 }
785
786 stream->ungetc_chars = 0;
787
788 rc = lseek(stream->fd, offset, whence);
789 if (rc == (off64_t) (-1)) {
790 /* errno has been set by lseek() */
791 return EOF;
792 }
793
794 stream->eof = false;
795 return 0;
796}
797
798off64_t ftell(FILE *stream)
799{
800 off64_t pos;
801
802 if (stream->error)
803 return EOF;
804
805 _fflushbuf(stream);
806 if (stream->error) {
807 /* errno was set by _fflushbuf() */
808 return EOF;
809 }
810
811 pos = lseek(stream->fd, 0, SEEK_CUR);
812 if (pos == (off64_t) -1) {
813 /* errno was set by lseek */
814 return (off64_t) -1;
815 }
816
817 return pos - stream->ungetc_chars;
818}
819
820void rewind(FILE *stream)
821{
822 (void) fseek(stream, 0, SEEK_SET);
823}
824
825int fflush(FILE *stream)
826{
827 if (stream->error)
828 return EOF;
829
830 _fflushbuf(stream);
831 if (stream->error) {
832 /* errno was set by _fflushbuf() */
833 return EOF;
834 }
835
836 if (stream->kio) {
837 kio_update();
838 return 0;
839 }
840
841 if ((stream->fd >= 0) && (stream->need_sync)) {
842 /**
843 * Better than syncing always, but probably still not the
844 * right thing to do.
845 */
846 stream->need_sync = false;
847 if (fsync(stream->fd) != 0) {
848 /* errno was set by fsync() */
849 return EOF;
850 }
851
852 return 0;
853 }
854
855 return 0;
856}
857
858int feof(FILE *stream)
859{
860 return stream->eof;
861}
862
863int ferror(FILE *stream)
864{
865 return stream->error;
866}
867
868void clearerr(FILE *stream)
869{
870 stream->eof = false;
871 stream->error = false;
872}
873
874int fileno(FILE *stream)
875{
876 if (stream->kio) {
877 errno = EBADF;
878 return EOF;
879 }
880
881 return stream->fd;
882}
883
884async_sess_t *vfs_fsession(FILE *stream, iface_t iface)
885{
886 if (stream->fd >= 0) {
887 if (stream->sess == NULL)
888 stream->sess = vfs_fd_session(stream->fd, iface);
889
890 return stream->sess;
891 }
892
893 return NULL;
894}
895
896int vfs_fhandle(FILE *stream, int *handle)
897{
898 if (stream->fd >= 0) {
899 *handle = stream->fd;
900 return EOK;
901 }
902
903 return ENOENT;
904}
905
906/** @}
907 */
Note: See TracBrowser for help on using the repository browser.