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

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since e948fde was 7699c21, checked in by Vojtech Horky <vojtechhorky@…>, 12 years ago

Add setbuf() function (C89)

  • Property mode set to 100644
File size: 14.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/klog.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 .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)
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_klog;
116 list_append(&stdout->link, &files);
117 }
118
119 if (filc > 2) {
120 stderr = fdopen(2, "w");
121 } else {
122 stderr = &stderr_klog;
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->klog = 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->klog = 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
301int fclose(FILE *stream)
302{
303 int rc = 0;
304
305 fflush(stream);
306
307 if (stream->sess != NULL)
308 async_hangup(stream->sess);
309
310 if (stream->fd >= 0)
311 rc = close(stream->fd);
312
313 list_remove(&stream->link);
314
315 if ((stream != &stdin_null)
316 && (stream != &stdout_klog)
317 && (stream != &stderr_klog))
318 free(stream);
319
320 stream = NULL;
321
322 if (rc != 0) {
323 /* errno was set by close() */
324 return EOF;
325 }
326
327 return 0;
328}
329
330/** Read from a stream (unbuffered).
331 *
332 * @param buf Destination buffer.
333 * @param size Size of each record.
334 * @param nmemb Number of records to read.
335 * @param stream Pointer to the stream.
336 */
337static size_t _fread(void *buf, size_t size, size_t nmemb, FILE *stream)
338{
339 size_t left, done;
340
341 if (size == 0 || nmemb == 0)
342 return 0;
343
344 left = size * nmemb;
345 done = 0;
346
347 while ((left > 0) && (!stream->error) && (!stream->eof)) {
348 ssize_t rd = read(stream->fd, buf + done, left);
349
350 if (rd < 0)
351 stream->error = true;
352 else if (rd == 0)
353 stream->eof = true;
354 else {
355 left -= rd;
356 done += rd;
357 }
358 }
359
360 return (done / size);
361}
362
363/** Write to a stream (unbuffered).
364 *
365 * @param buf Source buffer.
366 * @param size Size of each record.
367 * @param nmemb Number of records to write.
368 * @param stream Pointer to the stream.
369 */
370static size_t _fwrite(const void *buf, size_t size, size_t nmemb, FILE *stream)
371{
372 size_t left;
373 size_t done;
374
375 if (size == 0 || nmemb == 0)
376 return 0;
377
378 left = size * nmemb;
379 done = 0;
380
381 while ((left > 0) && (!stream->error)) {
382 ssize_t wr;
383
384 if (stream->klog)
385 wr = klog_write(buf + done, left);
386 else
387 wr = write(stream->fd, buf + done, left);
388
389 if (wr <= 0)
390 stream->error = true;
391 else {
392 left -= wr;
393 done += wr;
394 }
395 }
396
397 if (done > 0)
398 stream->need_sync = true;
399
400 return (done / size);
401}
402
403/** Read some data in stream buffer. */
404static void _ffillbuf(FILE *stream)
405{
406 ssize_t rc;
407
408 stream->buf_head = stream->buf_tail = stream->buf;
409
410 rc = read(stream->fd, stream->buf, stream->buf_size);
411 if (rc < 0) {
412 stream->error = true;
413 return;
414 }
415
416 if (rc == 0) {
417 stream->eof = true;
418 return;
419 }
420
421 stream->buf_head += rc;
422 stream->buf_state = _bs_read;
423}
424
425/** Write out stream buffer, do not sync stream. */
426static void _fflushbuf(FILE *stream)
427{
428 size_t bytes_used;
429
430 if ((!stream->buf) || (stream->btype == _IONBF) || (stream->error))
431 return;
432
433 bytes_used = stream->buf_head - stream->buf_tail;
434
435 /* If buffer has prefetched read data, we need to seek back. */
436 if (bytes_used > 0 && stream->buf_state == _bs_read)
437 lseek(stream->fd, - (ssize_t) bytes_used, SEEK_CUR);
438
439 /* If buffer has unwritten data, we need to write them out. */
440 if (bytes_used > 0 && stream->buf_state == _bs_write)
441 (void) _fwrite(stream->buf_tail, 1, bytes_used, stream);
442
443 stream->buf_head = stream->buf;
444 stream->buf_tail = stream->buf;
445 stream->buf_state = _bs_empty;
446}
447
448/** Read from a stream.
449 *
450 * @param dest Destination buffer.
451 * @param size Size of each record.
452 * @param nmemb Number of records to read.
453 * @param stream Pointer to the stream.
454 *
455 */
456size_t fread(void *dest, size_t size, size_t nmemb, FILE *stream)
457{
458 uint8_t *dp;
459 size_t bytes_left;
460 size_t now;
461 size_t data_avail;
462 size_t total_read;
463 size_t i;
464
465 if (size == 0 || nmemb == 0)
466 return 0;
467
468 /* If not buffered stream, read in directly. */
469 if (stream->btype == _IONBF) {
470 now = _fread(dest, size, nmemb, stream);
471 return now;
472 }
473
474 /* Make sure no data is pending write. */
475 if (stream->buf_state == _bs_write)
476 _fflushbuf(stream);
477
478 /* Perform lazy allocation of stream buffer. */
479 if (stream->buf == NULL) {
480 if (_fallocbuf(stream) != 0)
481 return 0; /* Errno set by _fallocbuf(). */
482 }
483
484 bytes_left = size * nmemb;
485 total_read = 0;
486 dp = (uint8_t *) dest;
487
488 while ((!stream->error) && (!stream->eof) && (bytes_left > 0)) {
489 if (stream->buf_head == stream->buf_tail)
490 _ffillbuf(stream);
491
492 if (stream->error || stream->eof)
493 break;
494
495 data_avail = stream->buf_head - stream->buf_tail;
496
497 if (bytes_left > data_avail)
498 now = data_avail;
499 else
500 now = bytes_left;
501
502 for (i = 0; i < now; i++) {
503 dp[i] = stream->buf_tail[i];
504 }
505
506 dp += now;
507 stream->buf_tail += now;
508 bytes_left -= now;
509 total_read += now;
510 }
511
512 return (total_read / size);
513}
514
515
516/** Write to a stream.
517 *
518 * @param buf Source buffer.
519 * @param size Size of each record.
520 * @param nmemb Number of records to write.
521 * @param stream Pointer to the stream.
522 *
523 */
524size_t fwrite(const void *buf, size_t size, size_t nmemb, FILE *stream)
525{
526 uint8_t *data;
527 size_t bytes_left;
528 size_t now;
529 size_t buf_free;
530 size_t total_written;
531 size_t i;
532 uint8_t b;
533 bool need_flush;
534
535 if (size == 0 || nmemb == 0)
536 return 0;
537
538 /* If not buffered stream, write out directly. */
539 if (stream->btype == _IONBF) {
540 now = _fwrite(buf, size, nmemb, stream);
541 fflush(stream);
542 return now;
543 }
544
545 /* Make sure buffer contains no prefetched data. */
546 if (stream->buf_state == _bs_read)
547 _fflushbuf(stream);
548
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 data = (uint8_t *) buf;
557 bytes_left = size * nmemb;
558 total_written = 0;
559 need_flush = false;
560
561 while ((!stream->error) && (bytes_left > 0)) {
562 buf_free = stream->buf_size - (stream->buf_head - stream->buf);
563 if (bytes_left > buf_free)
564 now = buf_free;
565 else
566 now = bytes_left;
567
568 for (i = 0; i < now; i++) {
569 b = data[i];
570 stream->buf_head[i] = b;
571
572 if ((b == '\n') && (stream->btype == _IOLBF))
573 need_flush = true;
574 }
575
576 data += now;
577 stream->buf_head += now;
578 buf_free -= now;
579 bytes_left -= now;
580 total_written += now;
581 stream->buf_state = _bs_write;
582
583 if (buf_free == 0) {
584 /* Only need to drain buffer. */
585 _fflushbuf(stream);
586 need_flush = false;
587 }
588 }
589
590 if (need_flush)
591 fflush(stream);
592
593 return (total_written / size);
594}
595
596int fputc(wchar_t c, FILE *stream)
597{
598 char buf[STR_BOUNDS(1)];
599 size_t sz = 0;
600
601 if (chr_encode(c, buf, &sz, STR_BOUNDS(1)) == EOK) {
602 size_t wr = fwrite(buf, 1, sz, stream);
603
604 if (wr < sz)
605 return EOF;
606
607 return (int) c;
608 }
609
610 return EOF;
611}
612
613int putchar(wchar_t c)
614{
615 return fputc(c, stdout);
616}
617
618int fputs(const char *str, FILE *stream)
619{
620 return fwrite(str, str_size(str), 1, stream);
621}
622
623int puts(const char *str)
624{
625 return fputs(str, stdout);
626}
627
628int fgetc(FILE *stream)
629{
630 char c;
631
632 /* This could be made faster by only flushing when needed. */
633 if (stdout)
634 fflush(stdout);
635 if (stderr)
636 fflush(stderr);
637
638 if (fread(&c, sizeof(char), 1, stream) < sizeof(char))
639 return EOF;
640
641 return (int) c;
642}
643
644char *fgets(char *str, int size, FILE *stream)
645{
646 int c;
647 int idx;
648
649 idx = 0;
650 while (idx < size - 1) {
651 c = fgetc(stream);
652 if (c == EOF)
653 break;
654
655 str[idx++] = c;
656
657 if (c == '\n')
658 break;
659 }
660
661 if (ferror(stream))
662 return NULL;
663
664 if (idx == 0)
665 return NULL;
666
667 str[idx] = '\0';
668 return str;
669}
670
671int getchar(void)
672{
673 return fgetc(stdin);
674}
675
676int fseek(FILE *stream, off64_t offset, int whence)
677{
678 off64_t rc;
679
680 _fflushbuf(stream);
681
682 rc = lseek(stream->fd, offset, whence);
683 if (rc == (off64_t) (-1)) {
684 /* errno has been set by lseek64. */
685 return -1;
686 }
687
688 stream->eof = false;
689 return 0;
690}
691
692off64_t ftell(FILE *stream)
693{
694 _fflushbuf(stream);
695 return lseek(stream->fd, 0, SEEK_CUR);
696}
697
698void rewind(FILE *stream)
699{
700 (void) fseek(stream, 0, SEEK_SET);
701}
702
703int fflush(FILE *stream)
704{
705 _fflushbuf(stream);
706
707 if (stream->klog) {
708 klog_update();
709 return EOK;
710 }
711
712 if ((stream->fd >= 0) && (stream->need_sync)) {
713 /**
714 * Better than syncing always, but probably still not the
715 * right thing to do.
716 */
717 stream->need_sync = false;
718 return fsync(stream->fd);
719 }
720
721 return ENOENT;
722}
723
724int feof(FILE *stream)
725{
726 return stream->eof;
727}
728
729int ferror(FILE *stream)
730{
731 return stream->error;
732}
733
734void clearerr(FILE *stream)
735{
736 stream->eof = false;
737 stream->error = false;
738}
739
740int fileno(FILE *stream)
741{
742 if (stream->klog) {
743 errno = EBADF;
744 return -1;
745 }
746
747 return stream->fd;
748}
749
750async_sess_t *fsession(exch_mgmt_t mgmt, FILE *stream)
751{
752 if (stream->fd >= 0) {
753 if (stream->sess == NULL)
754 stream->sess = fd_session(mgmt, stream->fd);
755
756 return stream->sess;
757 }
758
759 return NULL;
760}
761
762int fhandle(FILE *stream, int *handle)
763{
764 if (stream->fd >= 0) {
765 *handle = stream->fd;
766 return EOK;
767 }
768
769 return ENOENT;
770}
771
772/** @}
773 */
Note: See TracBrowser for help on using the repository browser.