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

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

UNIX-like I/O functions should use errno to return error code for many reasons.

  • Property mode set to 100644
File size: 16.6 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
274 list_append(&stream->link, &files);
275
276 return stream;
277}
278
279FILE *fdopen(int fd, const char *mode)
280{
281 /* Open file. */
282 FILE *stream = malloc(sizeof(FILE));
283 if (stream == NULL) {
284 errno = ENOMEM;
285 return NULL;
286 }
287
288 stream->fd = fd;
289 stream->error = false;
290 stream->eof = false;
291 stream->kio = false;
292 stream->sess = NULL;
293 stream->need_sync = false;
294 _setvbuf(stream);
295
296 list_append(&stream->link, &files);
297
298 return stream;
299}
300
301
302static int _fclose_nofree(FILE *stream)
303{
304 int rc = 0;
305
306 fflush(stream);
307
308 if (stream->sess != NULL)
309 async_hangup(stream->sess);
310
311 if (stream->fd >= 0)
312 rc = close(stream->fd);
313
314 list_remove(&stream->link);
315
316 if (rc != 0) {
317 /* errno was set by close() */
318 return EOF;
319 }
320
321 return 0;
322}
323
324int fclose(FILE *stream)
325{
326 int rc = _fclose_nofree(stream);
327
328 if ((stream != &stdin_null)
329 && (stream != &stdout_kio)
330 && (stream != &stderr_kio))
331 free(stream);
332
333 return rc;
334}
335
336FILE *freopen(const char *path, const char *mode, FILE *stream)
337{
338 FILE *nstr;
339
340 if (path == NULL) {
341 /* Changing mode is not supported */
342 return NULL;
343 }
344
345 (void) _fclose_nofree(stream);
346 nstr = fopen(path, mode);
347 if (nstr == NULL) {
348 free(stream);
349 return NULL;
350 }
351
352 list_remove(&nstr->link);
353 *stream = *nstr;
354 list_append(&stream->link, &files);
355
356 free(nstr);
357
358 return stream;
359}
360
361/** Read from a stream (unbuffered).
362 *
363 * @param buf Destination buffer.
364 * @param size Size of each record.
365 * @param nmemb Number of records to read.
366 * @param stream Pointer to the stream.
367 *
368 * @return Number of elements successfully read. On error this is less than
369 * nmemb, stream error indicator is set and errno is set.
370 */
371static size_t _fread(void *buf, size_t size, size_t nmemb, FILE *stream)
372{
373 size_t left, done;
374
375 if (size == 0 || nmemb == 0)
376 return 0;
377
378 left = size * nmemb;
379 done = 0;
380
381 while ((left > 0) && (!stream->error) && (!stream->eof)) {
382 ssize_t rd = read(stream->fd, buf + done, left);
383
384 if (rd < 0) {
385 /* errno was set by read() */
386 stream->error = true;
387 } else if (rd == 0) {
388 stream->eof = true;
389 } else {
390 left -= rd;
391 done += rd;
392 }
393 }
394
395 return (done / size);
396}
397
398/** Write to a stream (unbuffered).
399 *
400 * @param buf Source buffer.
401 * @param size Size of each record.
402 * @param nmemb Number of records to write.
403 * @param stream Pointer to the stream.
404 *
405 * @return Number of elements successfully written. On error this is less than
406 * nmemb, stream error indicator is set and errno is set.
407 */
408static size_t _fwrite(const void *buf, size_t size, size_t nmemb, FILE *stream)
409{
410 size_t left;
411 size_t done;
412 int rc;
413
414 if (size == 0 || nmemb == 0)
415 return 0;
416
417 left = size * nmemb;
418 done = 0;
419
420 while ((left > 0) && (!stream->error)) {
421 ssize_t wr;
422 size_t uwr;
423
424 if (stream->kio) {
425 uwr = 0;
426 rc = kio_write(buf + done, left, &uwr);
427 if (rc != EOK)
428 errno = rc;
429 } else {
430 wr = write(stream->fd, buf + done, left);
431 if (wr >= 0) {
432 uwr = (size_t)wr;
433 rc = EOK;
434 } else {
435 /* errno was set by write */
436 uwr = 0;
437 rc = errno;
438 }
439 }
440
441 if (rc != EOK) {
442 /* errno was set above */
443 stream->error = true;
444 } else {
445 left -= uwr;
446 done += uwr;
447 }
448 }
449
450 if (done > 0)
451 stream->need_sync = true;
452
453 return (done / size);
454}
455
456/** Read some data in stream buffer.
457 *
458 * On error, stream error indicator is set and errno is set.
459 */
460static void _ffillbuf(FILE *stream)
461{
462 ssize_t rc;
463
464 stream->buf_head = stream->buf_tail = stream->buf;
465
466 rc = read(stream->fd, stream->buf, stream->buf_size);
467 if (rc < 0) {
468 /* errno was set by read() */
469 stream->error = true;
470 return;
471 }
472
473 if (rc == 0) {
474 stream->eof = true;
475 return;
476 }
477
478 stream->buf_head += rc;
479 stream->buf_state = _bs_read;
480}
481
482/** Write out stream buffer, do not sync stream. */
483static void _fflushbuf(FILE *stream)
484{
485 size_t bytes_used;
486
487 if ((!stream->buf) || (stream->btype == _IONBF) || (stream->error))
488 return;
489
490 bytes_used = stream->buf_head - stream->buf_tail;
491
492 /* If buffer has prefetched read data, we need to seek back. */
493 if (bytes_used > 0 && stream->buf_state == _bs_read) {
494 off64_t rc;
495 rc = lseek(stream->fd, - (ssize_t) bytes_used, SEEK_CUR);
496 if (rc == (off64_t)-1) {
497 /* errno was set by lseek */
498 stream->error = 1;
499 return;
500 }
501 }
502
503 /* If buffer has unwritten data, we need to write them out. */
504 if (bytes_used > 0 && stream->buf_state == _bs_write) {
505 (void) _fwrite(stream->buf_tail, 1, bytes_used, stream);
506 /* On error stream error indicator and errno are set by _fwrite */
507 if (stream->error)
508 return;
509 }
510
511 stream->buf_head = stream->buf;
512 stream->buf_tail = stream->buf;
513 stream->buf_state = _bs_empty;
514}
515
516/** Read from a stream.
517 *
518 * @param dest Destination buffer.
519 * @param size Size of each record.
520 * @param nmemb Number of records to read.
521 * @param stream Pointer to the stream.
522 *
523 */
524size_t fread(void *dest, size_t size, size_t nmemb, FILE *stream)
525{
526 uint8_t *dp;
527 size_t bytes_left;
528 size_t now;
529 size_t data_avail;
530 size_t total_read;
531 size_t i;
532
533 if (size == 0 || nmemb == 0)
534 return 0;
535
536 bytes_left = size * nmemb;
537 total_read = 0;
538 dp = (uint8_t *) dest;
539
540 /* Bytes from ungetc() buffer */
541 while (stream->ungetc_chars > 0 && bytes_left > 0) {
542 *dp++ = stream->ungetc_buf[--stream->ungetc_chars];
543 ++total_read;
544 --bytes_left;
545 }
546
547 /* If not buffered stream, read in directly. */
548 if (stream->btype == _IONBF) {
549 total_read += _fread(dest, 1, bytes_left, stream);
550 return total_read / size;
551 }
552
553 /* Make sure no data is pending write. */
554 if (stream->buf_state == _bs_write)
555 _fflushbuf(stream);
556
557 /* Perform lazy allocation of stream buffer. */
558 if (stream->buf == NULL) {
559 if (_fallocbuf(stream) != 0)
560 return 0; /* Errno set by _fallocbuf(). */
561 }
562
563 while ((!stream->error) && (!stream->eof) && (bytes_left > 0)) {
564 if (stream->buf_head == stream->buf_tail)
565 _ffillbuf(stream);
566
567 if (stream->error || stream->eof) {
568 /* On error errno was set by _ffillbuf() */
569 break;
570 }
571
572 data_avail = stream->buf_head - stream->buf_tail;
573
574 if (bytes_left > data_avail)
575 now = data_avail;
576 else
577 now = bytes_left;
578
579 for (i = 0; i < now; i++) {
580 dp[i] = stream->buf_tail[i];
581 }
582
583 dp += now;
584 stream->buf_tail += now;
585 bytes_left -= now;
586 total_read += now;
587 }
588
589 return (total_read / size);
590}
591
592
593/** Write to a stream.
594 *
595 * @param buf Source buffer.
596 * @param size Size of each record.
597 * @param nmemb Number of records to write.
598 * @param stream Pointer to the stream.
599 *
600 */
601size_t fwrite(const void *buf, size_t size, size_t nmemb, FILE *stream)
602{
603 uint8_t *data;
604 size_t bytes_left;
605 size_t now;
606 size_t buf_free;
607 size_t total_written;
608 size_t i;
609 uint8_t b;
610 bool need_flush;
611
612 if (size == 0 || nmemb == 0)
613 return 0;
614
615 /* If not buffered stream, write out directly. */
616 if (stream->btype == _IONBF) {
617 now = _fwrite(buf, size, nmemb, stream);
618 fflush(stream);
619 return now;
620 }
621
622 /* Make sure buffer contains no prefetched data. */
623 if (stream->buf_state == _bs_read)
624 _fflushbuf(stream);
625
626 /* Perform lazy allocation of stream buffer. */
627 if (stream->buf == NULL) {
628 if (_fallocbuf(stream) != 0)
629 return 0; /* Errno set by _fallocbuf(). */
630 }
631
632 data = (uint8_t *) buf;
633 bytes_left = size * nmemb;
634 total_written = 0;
635 need_flush = false;
636
637 while ((!stream->error) && (bytes_left > 0)) {
638 buf_free = stream->buf_size - (stream->buf_head - stream->buf);
639 if (bytes_left > buf_free)
640 now = buf_free;
641 else
642 now = bytes_left;
643
644 for (i = 0; i < now; i++) {
645 b = data[i];
646 stream->buf_head[i] = b;
647
648 if ((b == '\n') && (stream->btype == _IOLBF))
649 need_flush = true;
650 }
651
652 data += now;
653 stream->buf_head += now;
654 buf_free -= now;
655 bytes_left -= now;
656 total_written += now;
657 stream->buf_state = _bs_write;
658
659 if (buf_free == 0) {
660 /* Only need to drain buffer. */
661 _fflushbuf(stream);
662 if (!stream->error)
663 need_flush = false;
664 }
665 }
666
667 if (need_flush)
668 fflush(stream);
669
670 return (total_written / size);
671}
672
673int fputc(wchar_t c, FILE *stream)
674{
675 char buf[STR_BOUNDS(1)];
676 size_t sz = 0;
677
678 if (chr_encode(c, buf, &sz, STR_BOUNDS(1)) == EOK) {
679 size_t wr = fwrite(buf, 1, sz, stream);
680
681 if (wr < sz)
682 return EOF;
683
684 return (int) c;
685 }
686
687 return EOF;
688}
689
690int putchar(wchar_t c)
691{
692 return fputc(c, stdout);
693}
694
695int fputs(const char *str, FILE *stream)
696{
697 (void) fwrite(str, str_size(str), 1, stream);
698 if (ferror(stream))
699 return EOF;
700 return 0;
701}
702
703int puts(const char *str)
704{
705 return fputs(str, stdout);
706}
707
708int fgetc(FILE *stream)
709{
710 char c;
711
712 /* This could be made faster by only flushing when needed. */
713 if (stdout)
714 fflush(stdout);
715 if (stderr)
716 fflush(stderr);
717
718 if (fread(&c, sizeof(char), 1, stream) < sizeof(char))
719 return EOF;
720
721 return (int) c;
722}
723
724char *fgets(char *str, int size, FILE *stream)
725{
726 int c;
727 int idx;
728
729 idx = 0;
730 while (idx < size - 1) {
731 c = fgetc(stream);
732 if (c == EOF)
733 break;
734
735 str[idx++] = c;
736
737 if (c == '\n')
738 break;
739 }
740
741 if (ferror(stream))
742 return NULL;
743
744 if (idx == 0)
745 return NULL;
746
747 str[idx] = '\0';
748 return str;
749}
750
751int getchar(void)
752{
753 return fgetc(stdin);
754}
755
756int ungetc(int c, FILE *stream)
757{
758 if (c == EOF)
759 return EOF;
760
761 if (stream->ungetc_chars >= UNGETC_MAX)
762 return EOF;
763
764 stream->ungetc_buf[stream->ungetc_chars++] =
765 (uint8_t)c;
766
767 stream->eof = false;
768 return (uint8_t)c;
769}
770
771int fseek(FILE *stream, off64_t offset, int whence)
772{
773 off64_t rc;
774
775 if (stream->error)
776 return EOF;
777
778 _fflushbuf(stream);
779 if (stream->error) {
780 /* errno was set by _fflushbuf() */
781 return EOF;
782 }
783
784 stream->ungetc_chars = 0;
785
786 rc = lseek(stream->fd, offset, whence);
787 if (rc == (off64_t) (-1)) {
788 /* errno has been set by lseek() */
789 return EOF;
790 }
791
792 stream->eof = false;
793 return 0;
794}
795
796off64_t ftell(FILE *stream)
797{
798 off64_t pos;
799
800 if (stream->error)
801 return EOF;
802
803 _fflushbuf(stream);
804 if (stream->error) {
805 /* errno was set by _fflushbuf() */
806 return EOF;
807 }
808
809 pos = lseek(stream->fd, 0, SEEK_CUR);
810 if (pos == (off64_t) -1) {
811 /* errno was set by lseek */
812 return (off64_t) -1;
813 }
814
815 return pos - stream->ungetc_chars;
816}
817
818void rewind(FILE *stream)
819{
820 (void) fseek(stream, 0, SEEK_SET);
821}
822
823int fflush(FILE *stream)
824{
825 if (stream->error)
826 return EOF;
827
828 _fflushbuf(stream);
829 if (stream->error) {
830 /* errno was set by _fflushbuf() */
831 return EOF;
832 }
833
834 if (stream->kio) {
835 kio_update();
836 return 0;
837 }
838
839 if ((stream->fd >= 0) && (stream->need_sync)) {
840 /**
841 * Better than syncing always, but probably still not the
842 * right thing to do.
843 */
844 stream->need_sync = false;
845 if (fsync(stream->fd) != 0) {
846 /* errno was set by fsync() */
847 return EOF;
848 }
849
850 return 0;
851 }
852
853 return 0;
854}
855
856int feof(FILE *stream)
857{
858 return stream->eof;
859}
860
861int ferror(FILE *stream)
862{
863 return stream->error;
864}
865
866void clearerr(FILE *stream)
867{
868 stream->eof = false;
869 stream->error = false;
870}
871
872int fileno(FILE *stream)
873{
874 if (stream->kio) {
875 errno = EBADF;
876 return EOF;
877 }
878
879 return stream->fd;
880}
881
882async_sess_t *vfs_fsession(FILE *stream, iface_t iface)
883{
884 if (stream->fd >= 0) {
885 if (stream->sess == NULL)
886 stream->sess = vfs_fd_session(stream->fd, iface);
887
888 return stream->sess;
889 }
890
891 return NULL;
892}
893
894int vfs_fhandle(FILE *stream, int *handle)
895{
896 if (stream->fd >= 0) {
897 *handle = stream->fd;
898 return EOK;
899 }
900
901 return ENOENT;
902}
903
904/** @}
905 */
Note: See TracBrowser for help on using the repository browser.