source: mainline/uspace/lib/c/generic/io/io.c@ 79ae36dd

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 79ae36dd was 79ae36dd, checked in by Martin Decky <martin@…>, 14 years ago

new async framework with integrated exchange tracking

  • strict isolation between low-level IPC and high-level async framework with integrated exchange tracking
    • each IPC connection is represented by an async_sess_t structure
    • each IPC exchange is represented by an async_exch_t structure
    • exchange management is either based on atomic messages (EXCHANGE_ATOMIC), locking (EXCHANGE_SERIALIZE) or connection cloning (EXCHANGE_CLONE)
  • async_obsolete: temporary compatibility layer to keep old async clients working (several pieces of code are currently broken, but only non-essential functionality)
  • IPC_M_PHONE_HANGUP is now method no. 0 (for elegant boolean evaluation)
  • IPC_M_DEBUG_ALL has been renamed to IPC_M_DEBUG
  • IPC_M_PING has been removed (VFS protocol now has VFS_IN_PING)
  • console routines in libc have been rewritten for better abstraction
  • additional use for libc-private header files (FILE structure opaque to the client)
  • various cstyle changes (typos, indentation, missing externs in header files, improved comments, etc.)
  • Property mode set to 100644
File size: 14.6 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 <bool.h>
42#include <malloc.h>
43#include <async.h>
44#include <io/klog.h>
45#include <vfs/vfs.h>
46#include <vfs/vfs_sess.h>
47#include <ipc/devmap.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 .klog = 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_klog = {
70 .fd = -1,
71 .error = false,
72 .eof = false,
73 .klog = 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_klog = {
84 .fd = -1,
85 .error = false,
86 .eof = false,
87 .klog = 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, fdi_node_t *filv[])
104{
105 if (filc > 0) {
106 stdin = fopen_node(filv[0], "r");
107 } else {
108 stdin = &stdin_null;
109 list_append(&stdin->link, &files);
110 }
111
112 if (filc > 1) {
113 stdout = fopen_node(filv[1], "w");
114 } else {
115 stdout = &stdout_klog;
116 list_append(&stdout->link, &files);
117 }
118
119 if (filc > 2) {
120 stderr = fopen_node(filv[2], "w");
121 } else {
122 stderr = &stderr_klog;
123 list_append(&stderr->link, &files);
124 }
125}
126
127void __stdio_done(void)
128{
129 link_t *link = files.next;
130
131 while (link != &files) {
132 FILE *file = list_get_instance(link, FILE, link);
133 fclose(file);
134 link = files.next;
135 }
136}
137
138static bool parse_mode(const char *mode, int *flags)
139{
140 /* Parse mode except first character. */
141 const char *mp = mode;
142 if (*mp++ == 0) {
143 errno = EINVAL;
144 return false;
145 }
146
147 if ((*mp == 'b') || (*mp == 't'))
148 mp++;
149
150 bool plus;
151 if (*mp == '+') {
152 mp++;
153 plus = true;
154 } else
155 plus = false;
156
157 if (*mp != 0) {
158 errno = EINVAL;
159 return false;
160 }
161
162 /* Parse first character of mode and determine flags for open(). */
163 switch (mode[0]) {
164 case 'r':
165 *flags = plus ? O_RDWR : O_RDONLY;
166 break;
167 case 'w':
168 *flags = (O_TRUNC | O_CREAT) | (plus ? O_RDWR : O_WRONLY);
169 break;
170 case 'a':
171 /* TODO: a+ must read from beginning, append to the end. */
172 if (plus) {
173 errno = ENOTSUP;
174 return false;
175 }
176 *flags = (O_APPEND | O_CREAT) | (plus ? O_RDWR : O_WRONLY);
177 break;
178 default:
179 errno = EINVAL;
180 return false;
181 }
182
183 return true;
184}
185
186/** Set stream buffer. */
187void setvbuf(FILE *stream, void *buf, int mode, size_t size)
188{
189 stream->btype = mode;
190 stream->buf = buf;
191 stream->buf_size = size;
192 stream->buf_head = stream->buf;
193 stream->buf_tail = stream->buf;
194 stream->buf_state = _bs_empty;
195}
196
197static void _setvbuf(FILE *stream)
198{
199 /* FIXME: Use more complex rules for setting buffering options. */
200
201 switch (stream->fd) {
202 case 1:
203 setvbuf(stream, NULL, _IOLBF, BUFSIZ);
204 break;
205 case 0:
206 case 2:
207 setvbuf(stream, NULL, _IONBF, 0);
208 break;
209 default:
210 setvbuf(stream, NULL, _IOFBF, BUFSIZ);
211 }
212}
213
214/** Allocate stream buffer. */
215static int _fallocbuf(FILE *stream)
216{
217 assert(stream->buf == NULL);
218
219 stream->buf = malloc(stream->buf_size);
220 if (stream->buf == NULL) {
221 errno = ENOMEM;
222 return -1;
223 }
224
225 stream->buf_head = stream->buf;
226 stream->buf_tail = stream->buf;
227 return 0;
228}
229
230/** Open a stream.
231 *
232 * @param path Path of the file to open.
233 * @param mode Mode string, (r|w|a)[b|t][+].
234 *
235 */
236FILE *fopen(const char *path, const char *mode)
237{
238 int flags;
239 if (!parse_mode(mode, &flags))
240 return NULL;
241
242 /* Open file. */
243 FILE *stream = malloc(sizeof(FILE));
244 if (stream == NULL) {
245 errno = ENOMEM;
246 return NULL;
247 }
248
249 stream->fd = open(path, flags, 0666);
250 if (stream->fd < 0) {
251 /* errno was set by open() */
252 free(stream);
253 return NULL;
254 }
255
256 stream->error = false;
257 stream->eof = false;
258 stream->klog = false;
259 stream->sess = NULL;
260 stream->need_sync = false;
261 _setvbuf(stream);
262
263 list_append(&stream->link, &files);
264
265 return stream;
266}
267
268FILE *fdopen(int fd, const char *mode)
269{
270 /* Open file. */
271 FILE *stream = malloc(sizeof(FILE));
272 if (stream == NULL) {
273 errno = ENOMEM;
274 return NULL;
275 }
276
277 stream->fd = fd;
278 stream->error = false;
279 stream->eof = false;
280 stream->klog = false;
281 stream->sess = NULL;
282 stream->need_sync = false;
283 _setvbuf(stream);
284
285 list_append(&stream->link, &files);
286
287 return stream;
288}
289
290FILE *fopen_node(fdi_node_t *node, const char *mode)
291{
292 int flags;
293 if (!parse_mode(mode, &flags))
294 return NULL;
295
296 /* Open file. */
297 FILE *stream = malloc(sizeof(FILE));
298 if (stream == NULL) {
299 errno = ENOMEM;
300 return NULL;
301 }
302
303 stream->fd = open_node(node, flags);
304 if (stream->fd < 0) {
305 /* errno was set by open_node() */
306 free(stream);
307 return NULL;
308 }
309
310 stream->error = false;
311 stream->eof = false;
312 stream->klog = false;
313 stream->sess = NULL;
314 stream->need_sync = false;
315 _setvbuf(stream);
316
317 list_append(&stream->link, &files);
318
319 return stream;
320}
321
322int fclose(FILE *stream)
323{
324 int rc = 0;
325
326 fflush(stream);
327
328 if (stream->sess != NULL)
329 async_hangup(stream->sess);
330
331 if (stream->fd >= 0)
332 rc = close(stream->fd);
333
334 list_remove(&stream->link);
335
336 if ((stream != &stdin_null)
337 && (stream != &stdout_klog)
338 && (stream != &stderr_klog))
339 free(stream);
340
341 stream = NULL;
342
343 if (rc != 0) {
344 /* errno was set by close() */
345 return EOF;
346 }
347
348 return 0;
349}
350
351/** Read from a stream (unbuffered).
352 *
353 * @param buf Destination buffer.
354 * @param size Size of each record.
355 * @param nmemb Number of records to read.
356 * @param stream Pointer to the stream.
357 */
358static size_t _fread(void *buf, size_t size, size_t nmemb, FILE *stream)
359{
360 size_t left, done;
361
362 if (size == 0 || nmemb == 0)
363 return 0;
364
365 left = size * nmemb;
366 done = 0;
367
368 while ((left > 0) && (!stream->error) && (!stream->eof)) {
369 ssize_t rd = read(stream->fd, buf + done, left);
370
371 if (rd < 0)
372 stream->error = true;
373 else if (rd == 0)
374 stream->eof = true;
375 else {
376 left -= rd;
377 done += rd;
378 }
379 }
380
381 return (done / size);
382}
383
384/** Write to a stream (unbuffered).
385 *
386 * @param buf Source buffer.
387 * @param size Size of each record.
388 * @param nmemb Number of records to write.
389 * @param stream Pointer to the stream.
390 */
391static size_t _fwrite(const void *buf, size_t size, size_t nmemb, FILE *stream)
392{
393 size_t left;
394 size_t done;
395
396 if (size == 0 || nmemb == 0)
397 return 0;
398
399 left = size * nmemb;
400 done = 0;
401
402 while ((left > 0) && (!stream->error)) {
403 ssize_t wr;
404
405 if (stream->klog)
406 wr = klog_write(buf + done, left);
407 else
408 wr = write(stream->fd, buf + done, left);
409
410 if (wr <= 0)
411 stream->error = true;
412 else {
413 left -= wr;
414 done += wr;
415 }
416 }
417
418 if (done > 0)
419 stream->need_sync = true;
420
421 return (done / size);
422}
423
424/** Read some data in stream buffer. */
425static void _ffillbuf(FILE *stream)
426{
427 ssize_t rc;
428
429 stream->buf_head = stream->buf_tail = stream->buf;
430
431 rc = read(stream->fd, stream->buf, stream->buf_size);
432 if (rc < 0) {
433 stream->error = true;
434 return;
435 }
436
437 if (rc == 0) {
438 stream->eof = true;
439 return;
440 }
441
442 stream->buf_head += rc;
443 stream->buf_state = _bs_read;
444}
445
446/** Write out stream buffer, do not sync stream. */
447static void _fflushbuf(FILE *stream)
448{
449 size_t bytes_used;
450
451 if ((!stream->buf) || (stream->btype == _IONBF) || (stream->error))
452 return;
453
454 bytes_used = stream->buf_head - stream->buf_tail;
455 if (bytes_used == 0)
456 return;
457
458 /* If buffer has prefetched read data, we need to seek back. */
459 if (stream->buf_state == _bs_read)
460 lseek(stream->fd, - (ssize_t) bytes_used, SEEK_CUR);
461
462 /* If buffer has unwritten data, we need to write them out. */
463 if (stream->buf_state == _bs_write)
464 (void) _fwrite(stream->buf_tail, 1, bytes_used, stream);
465
466 stream->buf_head = stream->buf;
467 stream->buf_tail = stream->buf;
468 stream->buf_state = _bs_empty;
469}
470
471/** Read from a stream.
472 *
473 * @param dest Destination buffer.
474 * @param size Size of each record.
475 * @param nmemb Number of records to read.
476 * @param stream Pointer to the stream.
477 *
478 */
479size_t fread(void *dest, size_t size, size_t nmemb, FILE *stream)
480{
481 uint8_t *dp;
482 size_t bytes_left;
483 size_t now;
484 size_t data_avail;
485 size_t total_read;
486 size_t i;
487
488 if (size == 0 || nmemb == 0)
489 return 0;
490
491 /* If not buffered stream, read in directly. */
492 if (stream->btype == _IONBF) {
493 now = _fread(dest, size, nmemb, stream);
494 return now;
495 }
496
497 /* Make sure no data is pending write. */
498 if (stream->buf_state == _bs_write)
499 _fflushbuf(stream);
500
501 /* Perform lazy allocation of stream buffer. */
502 if (stream->buf == NULL) {
503 if (_fallocbuf(stream) != 0)
504 return 0; /* Errno set by _fallocbuf(). */
505 }
506
507 bytes_left = size * nmemb;
508 total_read = 0;
509 dp = (uint8_t *) dest;
510
511 while ((!stream->error) && (!stream->eof) && (bytes_left > 0)) {
512 if (stream->buf_head == stream->buf_tail)
513 _ffillbuf(stream);
514
515 if (stream->error || stream->eof)
516 break;
517
518 data_avail = stream->buf_head - stream->buf_tail;
519
520 if (bytes_left > data_avail)
521 now = data_avail;
522 else
523 now = bytes_left;
524
525 for (i = 0; i < now; i++) {
526 dp[i] = stream->buf_tail[i];
527 }
528
529 dp += now;
530 stream->buf_tail += now;
531 bytes_left -= now;
532 total_read += now;
533 }
534
535 return (total_read / size);
536}
537
538
539/** Write to a stream.
540 *
541 * @param buf Source buffer.
542 * @param size Size of each record.
543 * @param nmemb Number of records to write.
544 * @param stream Pointer to the stream.
545 *
546 */
547size_t fwrite(const void *buf, size_t size, size_t nmemb, FILE *stream)
548{
549 uint8_t *data;
550 size_t bytes_left;
551 size_t now;
552 size_t buf_free;
553 size_t total_written;
554 size_t i;
555 uint8_t b;
556 bool need_flush;
557
558 if (size == 0 || nmemb == 0)
559 return 0;
560
561 /* If not buffered stream, write out directly. */
562 if (stream->btype == _IONBF) {
563 now = _fwrite(buf, size, nmemb, stream);
564 fflush(stream);
565 return now;
566 }
567
568 /* Make sure buffer contains no prefetched data. */
569 if (stream->buf_state == _bs_read)
570 _fflushbuf(stream);
571
572
573 /* Perform lazy allocation of stream buffer. */
574 if (stream->buf == NULL) {
575 if (_fallocbuf(stream) != 0)
576 return 0; /* Errno set by _fallocbuf(). */
577 }
578
579 data = (uint8_t *) buf;
580 bytes_left = size * nmemb;
581 total_written = 0;
582 need_flush = false;
583
584 while ((!stream->error) && (bytes_left > 0)) {
585 buf_free = stream->buf_size - (stream->buf_head - stream->buf);
586 if (bytes_left > buf_free)
587 now = buf_free;
588 else
589 now = bytes_left;
590
591 for (i = 0; i < now; i++) {
592 b = data[i];
593 stream->buf_head[i] = b;
594
595 if ((b == '\n') && (stream->btype == _IOLBF))
596 need_flush = true;
597 }
598
599 buf += now;
600 stream->buf_head += now;
601 buf_free -= now;
602 bytes_left -= now;
603 total_written += now;
604
605 if (buf_free == 0) {
606 /* Only need to drain buffer. */
607 _fflushbuf(stream);
608 need_flush = false;
609 }
610 }
611
612 if (total_written > 0)
613 stream->buf_state = _bs_write;
614
615 if (need_flush)
616 fflush(stream);
617
618 return (total_written / size);
619}
620
621int fputc(wchar_t c, FILE *stream)
622{
623 char buf[STR_BOUNDS(1)];
624 size_t sz = 0;
625
626 if (chr_encode(c, buf, &sz, STR_BOUNDS(1)) == EOK) {
627 size_t wr = fwrite(buf, 1, sz, stream);
628
629 if (wr < sz)
630 return EOF;
631
632 return (int) c;
633 }
634
635 return EOF;
636}
637
638int putchar(wchar_t c)
639{
640 return fputc(c, stdout);
641}
642
643int fputs(const char *str, FILE *stream)
644{
645 return fwrite(str, str_size(str), 1, stream);
646}
647
648int puts(const char *str)
649{
650 return fputs(str, stdout);
651}
652
653int fgetc(FILE *stream)
654{
655 char c;
656
657 /* This could be made faster by only flushing when needed. */
658 if (stdout)
659 fflush(stdout);
660 if (stderr)
661 fflush(stderr);
662
663 if (fread(&c, sizeof(char), 1, stream) < sizeof(char))
664 return EOF;
665
666 return (int) c;
667}
668
669char *fgets(char *str, int size, FILE *stream)
670{
671 int c;
672 int idx;
673
674 idx = 0;
675 while (idx < size - 1) {
676 c = fgetc(stream);
677 if (c == EOF)
678 break;
679
680 str[idx++] = c;
681
682 if (c == '\n')
683 break;
684 }
685
686 if (ferror(stream))
687 return NULL;
688
689 if (idx == 0)
690 return NULL;
691
692 str[idx] = '\0';
693 return str;
694}
695
696int getchar(void)
697{
698 return fgetc(stdin);
699}
700
701int fseek(FILE *stream, off64_t offset, int whence)
702{
703 off64_t rc;
704
705 _fflushbuf(stream);
706
707 rc = lseek(stream->fd, offset, whence);
708 if (rc == (off64_t) (-1)) {
709 /* errno has been set by lseek64. */
710 return -1;
711 }
712
713 stream->eof = false;
714 return 0;
715}
716
717off64_t ftell(FILE *stream)
718{
719 return lseek(stream->fd, 0, SEEK_CUR);
720}
721
722void rewind(FILE *stream)
723{
724 (void) fseek(stream, 0, SEEK_SET);
725}
726
727int fflush(FILE *stream)
728{
729 _fflushbuf(stream);
730
731 if (stream->klog) {
732 klog_update();
733 return EOK;
734 }
735
736 if ((stream->fd >= 0) && (stream->need_sync)) {
737 /**
738 * Better than syncing always, but probably still not the
739 * right thing to do.
740 */
741 stream->need_sync = false;
742 return fsync(stream->fd);
743 }
744
745 return ENOENT;
746}
747
748int feof(FILE *stream)
749{
750 return stream->eof;
751}
752
753int ferror(FILE *stream)
754{
755 return stream->error;
756}
757
758void clearerr(FILE *stream)
759{
760 stream->eof = false;
761 stream->error = false;
762}
763
764int fileno(FILE *stream)
765{
766 if (stream->klog) {
767 errno = EBADF;
768 return -1;
769 }
770
771 return stream->fd;
772}
773
774async_sess_t *fsession(exch_mgmt_t mgmt, FILE *stream)
775{
776 if (stream->fd >= 0) {
777 if (stream->sess == NULL)
778 stream->sess = fd_session(mgmt, stream->fd);
779
780 return stream->sess;
781 }
782
783 return NULL;
784}
785
786int fnode(FILE *stream, fdi_node_t *node)
787{
788 if (stream->fd >= 0)
789 return fd_node(stream->fd, node);
790
791 return ENOENT;
792}
793
794/** @}
795 */
Note: See TracBrowser for help on using the repository browser.