source: mainline/uspace/lib/c/generic/io/io.c@ 8e9b2534

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

Remove VFS_IN_SEEK from VFS

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