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

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since fe91f66 was fcab7ef, checked in by Jakub Jermar <jakub@…>, 8 years ago

Merge dup2() into vfs_clone()

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