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

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

Rename fsync() to vfs_sync()

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