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

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

Must update bytes_left when reading from ungetc() buffer.

  • Property mode set to 100644
File size: 15.2 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 --bytes_left;
508 }
509
510 /* If not buffered stream, read in directly. */
511 if (stream->btype == _IONBF) {
512 total_read += _fread(dest, 1, bytes_left, stream);
513 return total_read / size;
514 }
515
516 /* Make sure no data is pending write. */
517 if (stream->buf_state == _bs_write)
518 _fflushbuf(stream);
519
520 /* Perform lazy allocation of stream buffer. */
521 if (stream->buf == NULL) {
522 if (_fallocbuf(stream) != 0)
523 return 0; /* Errno set by _fallocbuf(). */
524 }
525
526 while ((!stream->error) && (!stream->eof) && (bytes_left > 0)) {
527 if (stream->buf_head == stream->buf_tail)
528 _ffillbuf(stream);
529
530 if (stream->error || stream->eof)
531 break;
532
533 data_avail = stream->buf_head - stream->buf_tail;
534
535 if (bytes_left > data_avail)
536 now = data_avail;
537 else
538 now = bytes_left;
539
540 for (i = 0; i < now; i++) {
541 dp[i] = stream->buf_tail[i];
542 }
543
544 dp += now;
545 stream->buf_tail += now;
546 bytes_left -= now;
547 total_read += now;
548 }
549
550 return (total_read / size);
551}
552
553
554/** Write to a stream.
555 *
556 * @param buf Source buffer.
557 * @param size Size of each record.
558 * @param nmemb Number of records to write.
559 * @param stream Pointer to the stream.
560 *
561 */
562size_t fwrite(const void *buf, size_t size, size_t nmemb, FILE *stream)
563{
564 uint8_t *data;
565 size_t bytes_left;
566 size_t now;
567 size_t buf_free;
568 size_t total_written;
569 size_t i;
570 uint8_t b;
571 bool need_flush;
572
573 if (size == 0 || nmemb == 0)
574 return 0;
575
576 /* If not buffered stream, write out directly. */
577 if (stream->btype == _IONBF) {
578 now = _fwrite(buf, size, nmemb, stream);
579 fflush(stream);
580 return now;
581 }
582
583 /* Make sure buffer contains no prefetched data. */
584 if (stream->buf_state == _bs_read)
585 _fflushbuf(stream);
586
587
588 /* Perform lazy allocation of stream buffer. */
589 if (stream->buf == NULL) {
590 if (_fallocbuf(stream) != 0)
591 return 0; /* Errno set by _fallocbuf(). */
592 }
593
594 data = (uint8_t *) buf;
595 bytes_left = size * nmemb;
596 total_written = 0;
597 need_flush = false;
598
599 while ((!stream->error) && (bytes_left > 0)) {
600 buf_free = stream->buf_size - (stream->buf_head - stream->buf);
601 if (bytes_left > buf_free)
602 now = buf_free;
603 else
604 now = bytes_left;
605
606 for (i = 0; i < now; i++) {
607 b = data[i];
608 stream->buf_head[i] = b;
609
610 if ((b == '\n') && (stream->btype == _IOLBF))
611 need_flush = true;
612 }
613
614 data += now;
615 stream->buf_head += now;
616 buf_free -= now;
617 bytes_left -= now;
618 total_written += now;
619 stream->buf_state = _bs_write;
620
621 if (buf_free == 0) {
622 /* Only need to drain buffer. */
623 _fflushbuf(stream);
624 need_flush = false;
625 }
626 }
627
628 if (need_flush)
629 fflush(stream);
630
631 return (total_written / size);
632}
633
634int fputc(wchar_t c, FILE *stream)
635{
636 char buf[STR_BOUNDS(1)];
637 size_t sz = 0;
638
639 if (chr_encode(c, buf, &sz, STR_BOUNDS(1)) == EOK) {
640 size_t wr = fwrite(buf, 1, sz, stream);
641
642 if (wr < sz)
643 return EOF;
644
645 return (int) c;
646 }
647
648 return EOF;
649}
650
651int putchar(wchar_t c)
652{
653 return fputc(c, stdout);
654}
655
656int fputs(const char *str, FILE *stream)
657{
658 (void) fwrite(str, str_size(str), 1, stream);
659 if (ferror(stream))
660 return EOF;
661 return 0;
662}
663
664int puts(const char *str)
665{
666 return fputs(str, stdout);
667}
668
669int fgetc(FILE *stream)
670{
671 char c;
672
673 /* This could be made faster by only flushing when needed. */
674 if (stdout)
675 fflush(stdout);
676 if (stderr)
677 fflush(stderr);
678
679 if (fread(&c, sizeof(char), 1, stream) < sizeof(char))
680 return EOF;
681
682 return (int) c;
683}
684
685char *fgets(char *str, int size, FILE *stream)
686{
687 int c;
688 int idx;
689
690 idx = 0;
691 while (idx < size - 1) {
692 c = fgetc(stream);
693 if (c == EOF)
694 break;
695
696 str[idx++] = c;
697
698 if (c == '\n')
699 break;
700 }
701
702 if (ferror(stream))
703 return NULL;
704
705 if (idx == 0)
706 return NULL;
707
708 str[idx] = '\0';
709 return str;
710}
711
712int getchar(void)
713{
714 return fgetc(stdin);
715}
716
717int ungetc(int c, FILE *stream)
718{
719 if (c == EOF)
720 return EOF;
721
722 if (stream->ungetc_chars >= UNGETC_MAX)
723 return EOF;
724
725 stream->ungetc_buf[stream->ungetc_chars++] =
726 (uint8_t)c;
727
728 stream->eof = false;
729 return (uint8_t)c;
730}
731
732int fseek(FILE *stream, off64_t offset, int whence)
733{
734 off64_t rc;
735
736 _fflushbuf(stream);
737 stream->ungetc_chars = 0;
738
739 rc = lseek(stream->fd, offset, whence);
740 if (rc == (off64_t) (-1)) {
741 /* errno has been set by lseek64. */
742 return -1;
743 }
744
745 stream->eof = false;
746 return 0;
747}
748
749off64_t ftell(FILE *stream)
750{
751 _fflushbuf(stream);
752 return lseek(stream->fd, 0, SEEK_CUR) - stream->ungetc_chars;
753}
754
755void rewind(FILE *stream)
756{
757 (void) fseek(stream, 0, SEEK_SET);
758}
759
760int fflush(FILE *stream)
761{
762 _fflushbuf(stream);
763
764 if (stream->kio) {
765 kio_update();
766 return EOK;
767 }
768
769 if ((stream->fd >= 0) && (stream->need_sync)) {
770 /**
771 * Better than syncing always, but probably still not the
772 * right thing to do.
773 */
774 stream->need_sync = false;
775 return fsync(stream->fd);
776 }
777
778 return ENOENT;
779}
780
781int feof(FILE *stream)
782{
783 return stream->eof;
784}
785
786int ferror(FILE *stream)
787{
788 return stream->error;
789}
790
791void clearerr(FILE *stream)
792{
793 stream->eof = false;
794 stream->error = false;
795}
796
797int fileno(FILE *stream)
798{
799 if (stream->kio) {
800 errno = EBADF;
801 return -1;
802 }
803
804 return stream->fd;
805}
806
807async_sess_t *fsession(FILE *stream, iface_t iface)
808{
809 if (stream->fd >= 0) {
810 if (stream->sess == NULL)
811 stream->sess = fd_session(stream->fd, iface);
812
813 return stream->sess;
814 }
815
816 return NULL;
817}
818
819int fhandle(FILE *stream, int *handle)
820{
821 if (stream->fd >= 0) {
822 *handle = stream->fd;
823 return EOK;
824 }
825
826 return ENOENT;
827}
828
829/** @}
830 */
Note: See TracBrowser for help on using the repository browser.