source: mainline/uspace/lib/c/generic/io/io.c@ 80bee81

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

freopen() goes home too.

  • Property mode set to 100644
File size: 15.1 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 -1;
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 */
368static size_t _fread(void *buf, size_t size, size_t nmemb, FILE *stream)
369{
370 size_t left, done;
371
372 if (size == 0 || nmemb == 0)
373 return 0;
374
375 left = size * nmemb;
376 done = 0;
377
378 while ((left > 0) && (!stream->error) && (!stream->eof)) {
379 ssize_t rd = read(stream->fd, buf + done, left);
380
381 if (rd < 0)
382 stream->error = true;
383 else if (rd == 0)
384 stream->eof = true;
385 else {
386 left -= rd;
387 done += rd;
388 }
389 }
390
391 return (done / size);
392}
393
394/** Write to a stream (unbuffered).
395 *
396 * @param buf Source buffer.
397 * @param size Size of each record.
398 * @param nmemb Number of records to write.
399 * @param stream Pointer to the stream.
400 */
401static size_t _fwrite(const void *buf, size_t size, size_t nmemb, FILE *stream)
402{
403 size_t left;
404 size_t done;
405
406 if (size == 0 || nmemb == 0)
407 return 0;
408
409 left = size * nmemb;
410 done = 0;
411
412 while ((left > 0) && (!stream->error)) {
413 ssize_t wr;
414
415 if (stream->kio)
416 wr = kio_write(buf + done, left);
417 else
418 wr = write(stream->fd, buf + done, left);
419
420 if (wr <= 0)
421 stream->error = true;
422 else {
423 left -= wr;
424 done += wr;
425 }
426 }
427
428 if (done > 0)
429 stream->need_sync = true;
430
431 return (done / size);
432}
433
434/** Read some data in stream buffer. */
435static void _ffillbuf(FILE *stream)
436{
437 ssize_t rc;
438
439 stream->buf_head = stream->buf_tail = stream->buf;
440
441 rc = read(stream->fd, stream->buf, stream->buf_size);
442 if (rc < 0) {
443 stream->error = true;
444 return;
445 }
446
447 if (rc == 0) {
448 stream->eof = true;
449 return;
450 }
451
452 stream->buf_head += rc;
453 stream->buf_state = _bs_read;
454}
455
456/** Write out stream buffer, do not sync stream. */
457static void _fflushbuf(FILE *stream)
458{
459 size_t bytes_used;
460
461 if ((!stream->buf) || (stream->btype == _IONBF) || (stream->error))
462 return;
463
464 bytes_used = stream->buf_head - stream->buf_tail;
465
466 /* If buffer has prefetched read data, we need to seek back. */
467 if (bytes_used > 0 && stream->buf_state == _bs_read)
468 lseek(stream->fd, - (ssize_t) bytes_used, SEEK_CUR);
469
470 /* If buffer has unwritten data, we need to write them out. */
471 if (bytes_used > 0 && stream->buf_state == _bs_write)
472 (void) _fwrite(stream->buf_tail, 1, bytes_used, stream);
473
474 stream->buf_head = stream->buf;
475 stream->buf_tail = stream->buf;
476 stream->buf_state = _bs_empty;
477}
478
479/** Read from a stream.
480 *
481 * @param dest Destination buffer.
482 * @param size Size of each record.
483 * @param nmemb Number of records to read.
484 * @param stream Pointer to the stream.
485 *
486 */
487size_t fread(void *dest, size_t size, size_t nmemb, FILE *stream)
488{
489 uint8_t *dp;
490 size_t bytes_left;
491 size_t now;
492 size_t data_avail;
493 size_t total_read;
494 size_t i;
495
496 if (size == 0 || nmemb == 0)
497 return 0;
498
499 bytes_left = size * nmemb;
500 total_read = 0;
501 dp = (uint8_t *) dest;
502
503 /* Bytes from ungetc() buffer */
504 while (stream->ungetc_chars > 0 && bytes_left > 0) {
505 *dp++ = stream->ungetc_buf[--stream->ungetc_chars];
506 ++total_read;
507 }
508
509 /* If not buffered stream, read in directly. */
510 if (stream->btype == _IONBF) {
511 total_read += _fread(dest, 1, bytes_left, stream);
512 return total_read / size;
513 }
514
515 /* Make sure no data is pending write. */
516 if (stream->buf_state == _bs_write)
517 _fflushbuf(stream);
518
519 /* Perform lazy allocation of stream buffer. */
520 if (stream->buf == NULL) {
521 if (_fallocbuf(stream) != 0)
522 return 0; /* Errno set by _fallocbuf(). */
523 }
524
525 while ((!stream->error) && (!stream->eof) && (bytes_left > 0)) {
526 if (stream->buf_head == stream->buf_tail)
527 _ffillbuf(stream);
528
529 if (stream->error || stream->eof)
530 break;
531
532 data_avail = stream->buf_head - stream->buf_tail;
533
534 if (bytes_left > data_avail)
535 now = data_avail;
536 else
537 now = bytes_left;
538
539 for (i = 0; i < now; i++) {
540 dp[i] = stream->buf_tail[i];
541 }
542
543 dp += now;
544 stream->buf_tail += now;
545 bytes_left -= now;
546 total_read += now;
547 }
548
549 return (total_read / size);
550}
551
552
553/** Write to a stream.
554 *
555 * @param buf Source buffer.
556 * @param size Size of each record.
557 * @param nmemb Number of records to write.
558 * @param stream Pointer to the stream.
559 *
560 */
561size_t fwrite(const void *buf, size_t size, size_t nmemb, FILE *stream)
562{
563 uint8_t *data;
564 size_t bytes_left;
565 size_t now;
566 size_t buf_free;
567 size_t total_written;
568 size_t i;
569 uint8_t b;
570 bool need_flush;
571
572 if (size == 0 || nmemb == 0)
573 return 0;
574
575 /* If not buffered stream, write out directly. */
576 if (stream->btype == _IONBF) {
577 now = _fwrite(buf, size, nmemb, stream);
578 fflush(stream);
579 return now;
580 }
581
582 /* Make sure buffer contains no prefetched data. */
583 if (stream->buf_state == _bs_read)
584 _fflushbuf(stream);
585
586
587 /* Perform lazy allocation of stream buffer. */
588 if (stream->buf == NULL) {
589 if (_fallocbuf(stream) != 0)
590 return 0; /* Errno set by _fallocbuf(). */
591 }
592
593 data = (uint8_t *) buf;
594 bytes_left = size * nmemb;
595 total_written = 0;
596 need_flush = false;
597
598 while ((!stream->error) && (bytes_left > 0)) {
599 buf_free = stream->buf_size - (stream->buf_head - stream->buf);
600 if (bytes_left > buf_free)
601 now = buf_free;
602 else
603 now = bytes_left;
604
605 for (i = 0; i < now; i++) {
606 b = data[i];
607 stream->buf_head[i] = b;
608
609 if ((b == '\n') && (stream->btype == _IOLBF))
610 need_flush = true;
611 }
612
613 data += now;
614 stream->buf_head += now;
615 buf_free -= now;
616 bytes_left -= now;
617 total_written += now;
618 stream->buf_state = _bs_write;
619
620 if (buf_free == 0) {
621 /* Only need to drain buffer. */
622 _fflushbuf(stream);
623 need_flush = false;
624 }
625 }
626
627 if (need_flush)
628 fflush(stream);
629
630 return (total_written / size);
631}
632
633int fputc(wchar_t c, FILE *stream)
634{
635 char buf[STR_BOUNDS(1)];
636 size_t sz = 0;
637
638 if (chr_encode(c, buf, &sz, STR_BOUNDS(1)) == EOK) {
639 size_t wr = fwrite(buf, 1, sz, stream);
640
641 if (wr < sz)
642 return EOF;
643
644 return (int) c;
645 }
646
647 return EOF;
648}
649
650int putchar(wchar_t c)
651{
652 return fputc(c, stdout);
653}
654
655int fputs(const char *str, FILE *stream)
656{
657 (void) fwrite(str, str_size(str), 1, stream);
658 if (ferror(stream))
659 return EOF;
660 return 0;
661}
662
663int puts(const char *str)
664{
665 return fputs(str, stdout);
666}
667
668int fgetc(FILE *stream)
669{
670 char c;
671
672 /* This could be made faster by only flushing when needed. */
673 if (stdout)
674 fflush(stdout);
675 if (stderr)
676 fflush(stderr);
677
678 if (fread(&c, sizeof(char), 1, stream) < sizeof(char))
679 return EOF;
680
681 return (int) c;
682}
683
684char *fgets(char *str, int size, FILE *stream)
685{
686 int c;
687 int idx;
688
689 idx = 0;
690 while (idx < size - 1) {
691 c = fgetc(stream);
692 if (c == EOF)
693 break;
694
695 str[idx++] = c;
696
697 if (c == '\n')
698 break;
699 }
700
701 if (ferror(stream))
702 return NULL;
703
704 if (idx == 0)
705 return NULL;
706
707 str[idx] = '\0';
708 return str;
709}
710
711int getchar(void)
712{
713 return fgetc(stdin);
714}
715
716int ungetc(int c, FILE *stream)
717{
718 if (c == EOF)
719 return EOF;
720
721 if (stream->ungetc_chars >= UNGETC_MAX)
722 return EOF;
723
724 stream->ungetc_buf[stream->ungetc_chars++] =
725 (uint8_t)c;
726
727 stream->eof = false;
728 return (uint8_t)c;
729}
730
731int fseek(FILE *stream, off64_t offset, int whence)
732{
733 off64_t rc;
734
735 _fflushbuf(stream);
736 stream->ungetc_chars = 0;
737
738 rc = lseek(stream->fd, offset, whence);
739 if (rc == (off64_t) (-1)) {
740 /* errno has been set by lseek64. */
741 return -1;
742 }
743
744 stream->eof = false;
745 return 0;
746}
747
748off64_t ftell(FILE *stream)
749{
750 _fflushbuf(stream);
751 return lseek(stream->fd, 0, SEEK_CUR) - stream->ungetc_chars;
752}
753
754void rewind(FILE *stream)
755{
756 (void) fseek(stream, 0, SEEK_SET);
757}
758
759int fflush(FILE *stream)
760{
761 _fflushbuf(stream);
762
763 if (stream->kio) {
764 kio_update();
765 return EOK;
766 }
767
768 if ((stream->fd >= 0) && (stream->need_sync)) {
769 /**
770 * Better than syncing always, but probably still not the
771 * right thing to do.
772 */
773 stream->need_sync = false;
774 return fsync(stream->fd);
775 }
776
777 return ENOENT;
778}
779
780int feof(FILE *stream)
781{
782 return stream->eof;
783}
784
785int ferror(FILE *stream)
786{
787 return stream->error;
788}
789
790void clearerr(FILE *stream)
791{
792 stream->eof = false;
793 stream->error = false;
794}
795
796int fileno(FILE *stream)
797{
798 if (stream->kio) {
799 errno = EBADF;
800 return -1;
801 }
802
803 return stream->fd;
804}
805
806async_sess_t *fsession(FILE *stream, iface_t iface)
807{
808 if (stream->fd >= 0) {
809 if (stream->sess == NULL)
810 stream->sess = fd_session(stream->fd, iface);
811
812 return stream->sess;
813 }
814
815 return NULL;
816}
817
818int fhandle(FILE *stream, int *handle)
819{
820 if (stream->fd >= 0) {
821 *handle = stream->fd;
822 return EOK;
823 }
824
825 return ENOENT;
826}
827
828/** @}
829 */
Note: See TracBrowser for help on using the repository browser.