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
RevLine 
[b861b58]1/*
[df4ed85]2 * Copyright (c) 2005 Martin Decky
[b861b58]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.
[b2951e2]27 */
28
[fadd381]29/** @addtogroup libc
[b2951e2]30 * @{
31 */
32/** @file
[2595dab]33 */
[b861b58]34
[cc6f688]35#include <stdio.h>
[2595dab]36#include <unistd.h>
37#include <fcntl.h>
[ef8bcc6]38#include <assert.h>
[19f857a]39#include <str.h>
[56fa418]40#include <errno.h>
[3e6a98c5]41#include <stdbool.h>
[2595dab]42#include <malloc.h>
[64d2b10]43#include <async.h>
[2595dab]44#include <io/klog.h>
45#include <vfs/vfs.h>
[79ae36dd]46#include <vfs/vfs_sess.h>
[15f3c3f]47#include <ipc/loc.h>
[d9c8c81]48#include <adt/list.h>
[47b7006]49#include "../private/io.h"
[79ae36dd]50#include "../private/stdio.h"
[b861b58]51
[facebd56]52static void _ffillbuf(FILE *stream);
[ef8bcc6]53static void _fflushbuf(FILE *stream);
54
[a68f737]55static FILE stdin_null = {
[2595dab]56 .fd = -1,
57 .error = true,
58 .eof = true,
59 .klog = false,
[79ae36dd]60 .sess = NULL,
[ef8bcc6]61 .btype = _IONBF,
62 .buf = NULL,
63 .buf_size = 0,
[facebd56]64 .buf_head = NULL,
65 .buf_tail = NULL,
66 .buf_state = _bs_empty
[2595dab]67};
[350514c]68
[a68f737]69static FILE stdout_klog = {
[2595dab]70 .fd = -1,
71 .error = false,
72 .eof = false,
73 .klog = true,
[79ae36dd]74 .sess = NULL,
[ef8bcc6]75 .btype = _IOLBF,
76 .buf = NULL,
77 .buf_size = BUFSIZ,
[facebd56]78 .buf_head = NULL,
79 .buf_tail = NULL,
80 .buf_state = _bs_empty
[2595dab]81};
82
[a68f737]83static FILE stderr_klog = {
84 .fd = -1,
85 .error = false,
86 .eof = false,
87 .klog = true,
[79ae36dd]88 .sess = NULL,
[ef8bcc6]89 .btype = _IONBF,
90 .buf = NULL,
91 .buf_size = 0,
[facebd56]92 .buf_head = NULL,
93 .buf_tail = NULL,
94 .buf_state = _bs_empty
[a68f737]95};
96
97FILE *stdin = NULL;
98FILE *stdout = NULL;
99FILE *stderr = NULL;
100
101static LIST_INITIALIZE(files);
102
[7171760]103void __stdio_init(int filc)
[a68f737]104{
105 if (filc > 0) {
[76d6169]106 stdin = fdopen(0, "r");
[a68f737]107 } else {
108 stdin = &stdin_null;
109 list_append(&stdin->link, &files);
110 }
111
112 if (filc > 1) {
[76d6169]113 stdout = fdopen(1, "w");
[a68f737]114 } else {
115 stdout = &stdout_klog;
116 list_append(&stdout->link, &files);
117 }
118
119 if (filc > 2) {
[76d6169]120 stderr = fdopen(2, "w");
[a68f737]121 } else {
122 stderr = &stderr_klog;
123 list_append(&stderr->link, &files);
124 }
125}
126
[db24058]127void __stdio_done(void)
[a68f737]128{
[b72efe8]129 while (!list_empty(&files)) {
130 FILE *file = list_get_instance(list_first(&files), FILE, link);
[a68f737]131 fclose(file);
132 }
133}
[2595dab]134
135static bool parse_mode(const char *mode, int *flags)
[b861b58]136{
[2595dab]137 /* Parse mode except first character. */
138 const char *mp = mode;
139 if (*mp++ == 0) {
140 errno = EINVAL;
141 return false;
142 }
[cc6f688]143
[2595dab]144 if ((*mp == 'b') || (*mp == 't'))
145 mp++;
[c9857c6]146
[2595dab]147 bool plus;
148 if (*mp == '+') {
149 mp++;
150 plus = true;
151 } else
152 plus = false;
[566f4cfb]153
[2595dab]154 if (*mp != 0) {
155 errno = EINVAL;
156 return false;
[350514c]157 }
158
[2595dab]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);
[82582e4]174 break;
[2595dab]175 default:
176 errno = EINVAL;
177 return false;
178 }
179
180 return true;
[cc6f688]181}
[b861b58]182
[ef8bcc6]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;
[facebd56]190 stream->buf_tail = stream->buf;
191 stream->buf_state = _bs_empty;
[ef8bcc6]192}
193
[7699c21]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
[bfd247f]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
[ef8bcc6]225/** Allocate stream buffer. */
226static int _fallocbuf(FILE *stream)
227{
228 assert(stream->buf == NULL);
[bfd247f]229
[ef8bcc6]230 stream->buf = malloc(stream->buf_size);
231 if (stream->buf == NULL) {
232 errno = ENOMEM;
233 return -1;
234 }
[bfd247f]235
[ef8bcc6]236 stream->buf_head = stream->buf;
[facebd56]237 stream->buf_tail = stream->buf;
[ef8bcc6]238 return 0;
239}
240
[2595dab]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 *
[4e2cf8b]246 */
[2595dab]247FILE *fopen(const char *path, const char *mode)
[4e2cf8b]248{
[2595dab]249 int flags;
250 if (!parse_mode(mode, &flags))
251 return NULL;
[4e2cf8b]252
[2595dab]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;
[79ae36dd]270 stream->sess = NULL;
[facebd56]271 stream->need_sync = false;
[bfd247f]272 _setvbuf(stream);
[2595dab]273
[a68f737]274 list_append(&stream->link, &files);
275
[2595dab]276 return stream;
277}
278
[080ad7f]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;
[79ae36dd]292 stream->sess = NULL;
[facebd56]293 stream->need_sync = false;
[bfd247f]294 _setvbuf(stream);
[080ad7f]295
296 list_append(&stream->link, &files);
297
298 return stream;
299}
300
[2595dab]301int fclose(FILE *stream)
302{
303 int rc = 0;
304
305 fflush(stream);
306
[79ae36dd]307 if (stream->sess != NULL)
308 async_hangup(stream->sess);
[2595dab]309
310 if (stream->fd >= 0)
311 rc = close(stream->fd);
312
[a68f737]313 list_remove(&stream->link);
314
315 if ((stream != &stdin_null)
316 && (stream != &stdout_klog)
317 && (stream != &stderr_klog))
[2595dab]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;
[4e2cf8b]328}
329
[facebd56]330/** Read from a stream (unbuffered).
[2595dab]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.
[4e2cf8b]336 */
[facebd56]337static size_t _fread(void *buf, size_t size, size_t nmemb, FILE *stream)
[4e2cf8b]338{
[002252a]339 size_t left, done;
340
341 if (size == 0 || nmemb == 0)
342 return 0;
343
344 left = size * nmemb;
345 done = 0;
[bfd247f]346
[2595dab]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 }
[4e2cf8b]359
[2595dab]360 return (done / size);
361}
[55cff86]362
[facebd56]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 */
[ef8bcc6]370static size_t _fwrite(const void *buf, size_t size, size_t nmemb, FILE *stream)
[2595dab]371{
[002252a]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
[2595dab]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 }
[facebd56]396
397 if (done > 0)
398 stream->need_sync = true;
[2595dab]399
400 return (done / size);
[4e2cf8b]401}
402
[facebd56]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. */
[ef8bcc6]426static void _fflushbuf(FILE *stream)
427{
428 size_t bytes_used;
[facebd56]429
[bfd247f]430 if ((!stream->buf) || (stream->btype == _IONBF) || (stream->error))
[ef8bcc6]431 return;
[facebd56]432
433 bytes_used = stream->buf_head - stream->buf_tail;
434
435 /* If buffer has prefetched read data, we need to seek back. */
[2f72c67a]436 if (bytes_used > 0 && stream->buf_state == _bs_read)
[facebd56]437 lseek(stream->fd, - (ssize_t) bytes_used, SEEK_CUR);
438
439 /* If buffer has unwritten data, we need to write them out. */
[2f72c67a]440 if (bytes_used > 0 && stream->buf_state == _bs_write)
[facebd56]441 (void) _fwrite(stream->buf_tail, 1, bytes_used, stream);
442
[ef8bcc6]443 stream->buf_head = stream->buf;
[facebd56]444 stream->buf_tail = stream->buf;
445 stream->buf_state = _bs_empty;
[ef8bcc6]446}
447
[facebd56]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
[ef8bcc6]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;
[002252a]534
535 if (size == 0 || nmemb == 0)
536 return 0;
537
[ef8bcc6]538 /* If not buffered stream, write out directly. */
[bfd247f]539 if (stream->btype == _IONBF) {
540 now = _fwrite(buf, size, nmemb, stream);
541 fflush(stream);
542 return now;
543 }
[facebd56]544
545 /* Make sure buffer contains no prefetched data. */
546 if (stream->buf_state == _bs_read)
547 _fflushbuf(stream);
548
549
[ef8bcc6]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 }
[bfd247f]555
[ef8bcc6]556 data = (uint8_t *) buf;
557 bytes_left = size * nmemb;
558 total_written = 0;
559 need_flush = false;
[bfd247f]560
561 while ((!stream->error) && (bytes_left > 0)) {
[ef8bcc6]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;
[bfd247f]567
[ef8bcc6]568 for (i = 0; i < now; i++) {
569 b = data[i];
570 stream->buf_head[i] = b;
[bfd247f]571
572 if ((b == '\n') && (stream->btype == _IOLBF))
[ef8bcc6]573 need_flush = true;
574 }
[bfd247f]575
[0803134]576 data += now;
[ef8bcc6]577 stream->buf_head += now;
578 buf_free -= now;
579 bytes_left -= now;
580 total_written += now;
[0803134]581 stream->buf_state = _bs_write;
[bfd247f]582
[ef8bcc6]583 if (buf_free == 0) {
584 /* Only need to drain buffer. */
585 _fflushbuf(stream);
586 need_flush = false;
587 }
588 }
[facebd56]589
[ef8bcc6]590 if (need_flush)
591 fflush(stream);
[bfd247f]592
[ef8bcc6]593 return (total_written / size);
594}
595
[2595dab]596int fputc(wchar_t c, FILE *stream)
[c9857c6]597{
[56fa418]598 char buf[STR_BOUNDS(1)];
[2595dab]599 size_t sz = 0;
600
601 if (chr_encode(c, buf, &sz, STR_BOUNDS(1)) == EOK) {
[2a5af223]602 size_t wr = fwrite(buf, 1, sz, stream);
[2595dab]603
604 if (wr < sz)
605 return EOF;
606
607 return (int) c;
608 }
609
610 return EOF;
611}
[56fa418]612
[2595dab]613int putchar(wchar_t c)
614{
615 return fputc(c, stdout);
616}
[56fa418]617
[2595dab]618int fputs(const char *str, FILE *stream)
619{
620 return fwrite(str, str_size(str), 1, stream);
621}
[56fa418]622
[2595dab]623int puts(const char *str)
624{
625 return fputs(str, stdout);
[c9857c6]626}
[b27a97bb]627
[2595dab]628int fgetc(FILE *stream)
[b27a97bb]629{
[2595dab]630 char c;
[bfd247f]631
[bac82eeb]632 /* This could be made faster by only flushing when needed. */
[b8e57e8c]633 if (stdout)
634 fflush(stdout);
635 if (stderr)
636 fflush(stderr);
[bfd247f]637
[2595dab]638 if (fread(&c, sizeof(char), 1, stream) < sizeof(char))
639 return EOF;
[b27a97bb]640
[2595dab]641 return (int) c;
642}
643
[c62d2e1]644char *fgets(char *str, int size, FILE *stream)
645{
[a634485]646 int c;
[c62d2e1]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
[2595dab]671int getchar(void)
672{
673 return fgetc(stdin);
[b27a97bb]674}
675
[ed903174]676int fseek(FILE *stream, off64_t offset, int whence)
[d2cc7e1]677{
[facebd56]678 off64_t rc;
679
680 _fflushbuf(stream);
681
682 rc = lseek(stream->fd, offset, whence);
[ed903174]683 if (rc == (off64_t) (-1)) {
684 /* errno has been set by lseek64. */
[2595dab]685 return -1;
686 }
[facebd56]687
[2595dab]688 stream->eof = false;
[566f4cfb]689 return 0;
[d2cc7e1]690}
691
[ed903174]692off64_t ftell(FILE *stream)
[08232ee]693{
[8ad496d]694 _fflushbuf(stream);
[ed903174]695 return lseek(stream->fd, 0, SEEK_CUR);
[08232ee]696}
697
[080ad7f]698void rewind(FILE *stream)
699{
700 (void) fseek(stream, 0, SEEK_SET);
701}
702
[2595dab]703int fflush(FILE *stream)
704{
[ef8bcc6]705 _fflushbuf(stream);
[bfd247f]706
[2595dab]707 if (stream->klog) {
708 klog_update();
709 return EOK;
710 }
711
[79ae36dd]712 if ((stream->fd >= 0) && (stream->need_sync)) {
[facebd56]713 /**
714 * Better than syncing always, but probably still not the
715 * right thing to do.
716 */
717 stream->need_sync = false;
[2595dab]718 return fsync(stream->fd);
[facebd56]719 }
[2595dab]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
[c77a64f]734void clearerr(FILE *stream)
735{
736 stream->eof = false;
737 stream->error = false;
738}
739
[3629481]740int fileno(FILE *stream)
741{
742 if (stream->klog) {
743 errno = EBADF;
744 return -1;
745 }
746
747 return stream->fd;
748}
749
[79ae36dd]750async_sess_t *fsession(exch_mgmt_t mgmt, FILE *stream)
[2595dab]751{
752 if (stream->fd >= 0) {
[79ae36dd]753 if (stream->sess == NULL)
754 stream->sess = fd_session(mgmt, stream->fd);
[2595dab]755
[79ae36dd]756 return stream->sess;
[2595dab]757 }
758
[79ae36dd]759 return NULL;
[2595dab]760}
761
[7171760]762int fhandle(FILE *stream, int *handle)
[2595dab]763{
[7171760]764 if (stream->fd >= 0) {
765 *handle = stream->fd;
766 return EOK;
767 }
[a68f737]768
769 return ENOENT;
[2595dab]770}
771
[fadd381]772/** @}
[b2951e2]773 */
Note: See TracBrowser for help on using the repository browser.