source: mainline/uspace/lib/c/generic/io/io.c@ 7db5cfd

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

fputs() and the incredible adventures of its return value.

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