source: mainline/uspace/lib/posix/stdio.c@ 49160c4

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 49160c4 was 49160c4, checked in by Petr Koupy <petr.koupy@…>, 14 years ago

Resolved conflicts caused by mainline merge.

  • Property mode set to 100644
File size: 19.7 KB
Line 
1/*
2 * Copyright (c) 2011 Jiri Zarevucky
3 * Copyright (c) 2011 Petr Koupy
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * - Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * - Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * - The name of the author may not be used to endorse or promote products
16 * derived from this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30/** @addtogroup libposix
31 * @{
32 */
33/** @file Standard buffered input/output.
34 */
35
36#define LIBPOSIX_INTERNAL
37
38/* Has to be first. */
39#include "stdbool.h"
40
41#include "internal/common.h"
42#include "stdio.h"
43
44#include "assert.h"
45#include "errno.h"
46#include "stdlib.h"
47#include "string.h"
48#include "sys/types.h"
49#include "unistd.h"
50
51#include "libc/io/printf_core.h"
52#include "libc/str.h"
53#include "libc/malloc.h"
54#include "libc/adt/list.h"
55#include "libc/sys/stat.h"
56
57
58/* not the best of solutions, but freopen and ungetc will eventually
59 * need to be implemented in libc anyway
60 */
61#include "../c/generic/private/stdio.h"
62
63/** Clears the stream's error and end-of-file indicators.
64 *
65 * @param stream Stream whose indicators shall be cleared.
66 */
67void posix_clearerr(FILE *stream)
68{
69 stream->error = 0;
70 stream->eof = 0;
71}
72
73/**
74 * Generate a pathname for the controlling terminal.
75 *
76 * @param s Allocated buffer to which the pathname shall be put.
77 * @return Either s or static location filled with the requested pathname.
78 */
79char *posix_ctermid(char *s)
80{
81 /* Currently always returns an error value (empty string). */
82 // TODO: return a real terminal path
83
84 static char dummy_path[L_ctermid] = {'\0'};
85
86 if (s == NULL) {
87 return dummy_path;
88 }
89
90 s[0] = '\0';
91 return s;
92}
93
94/**
95 * Put a string on the stream.
96 *
97 * @param s String to be written.
98 * @param stream Output stream.
99 * @return Non-negative on success, EOF on failure.
100 */
101int posix_fputs(const char *restrict s, FILE *restrict stream)
102{
103 int rc = fputs(s, stream);
104 if (rc == 0) {
105 return EOF;
106 } else {
107 return 0;
108 }
109}
110
111/**
112 * Push byte back into input stream.
113 *
114 * @param c Byte to be pushed back.
115 * @param stream Stream to where the byte shall be pushed.
116 * @return Provided byte on success or EOF if not possible.
117 */
118int posix_ungetc(int c, FILE *stream)
119{
120 uint8_t b = (uint8_t) c;
121
122 bool can_unget =
123 /* Provided character is legal. */
124 c != EOF &&
125 /* Stream is consistent. */
126 !stream->error &&
127 /* Stream is buffered. */
128 stream->btype != _IONBF &&
129 /* Last operation on the stream was a read operation. */
130 stream->buf_state == _bs_read &&
131 /* Stream buffer is already allocated (i.e. there was already carried
132 * out either write or read operation on the stream). This is probably
133 * redundant check but let's be safe. */
134 stream->buf != NULL &&
135 /* There is still space in the stream to retreat. POSIX demands the
136 * possibility to unget at least 1 character. It should be always
137 * possible, assuming the last operation on the stream read at least 1
138 * character, because the buffer is refilled in the lazily manner. */
139 stream->buf_tail > stream->buf;
140
141 if (can_unget) {
142 --stream->buf_tail;
143 stream->buf_tail[0] = b;
144 stream->eof = false;
145 return (int) b;
146 } else {
147 return EOF;
148 }
149}
150
151/**
152 * Read a stream until the delimiter (or EOF) is encountered.
153 *
154 * @param lineptr Pointer to the output buffer in which there will be stored
155 * nul-terminated string together with the delimiter (if encountered).
156 * Will be resized if necessary.
157 * @param n Pointer to the size of the output buffer. Will be increased if
158 * necessary.
159 * @param delimiter Delimiter on which to finish reading the stream.
160 * @param stream Input stream.
161 * @return Number of fetched characters (including delimiter if encountered)
162 * or -1 on error (set in errno).
163 */
164ssize_t posix_getdelim(char **restrict lineptr, size_t *restrict n,
165 int delimiter, FILE *restrict stream)
166{
167 /* Check arguments for sanity. */
168 if (!lineptr || !n) {
169 errno = EINVAL;
170 return -1;
171 }
172
173 size_t alloc_step = 80; /* Buffer size gain during reallocation. */
174 char *pos = *lineptr; /* Next free byte of the output buffer. */
175 size_t cnt = 0; /* Number of fetched characters. */
176 int c = fgetc(stream); /* Current input character. Might be EOF. */
177
178 do {
179 /* Mask EOF as NUL to terminate string. */
180 if (c == EOF) {
181 c = '\0';
182 }
183
184 /* Ensure there is still space left in the buffer. */
185 if (pos == *lineptr + *n) {
186 *lineptr = realloc(*lineptr, *n + alloc_step);
187 if (*lineptr) {
188 pos = *lineptr + *n;
189 *n += alloc_step;
190 } else {
191 errno = ENOMEM;
192 return -1;
193 }
194 }
195
196 /* Store the fetched character. */
197 *pos = c;
198
199 /* Fetch the next character according to the current character. */
200 if (c != '\0') {
201 ++pos;
202 ++cnt;
203 if (c == delimiter) {
204 /* Delimiter was just stored. Provide EOF as the next
205 * character - it will be masked as NUL and output string
206 * will be properly terminated. */
207 c = EOF;
208 } else {
209 /* Neither delimiter nor EOF were encountered. Just fetch
210 * the next character from the stream. */
211 c = fgetc(stream);
212 }
213 }
214 } while (c != '\0');
215
216 if (errno == EOK && cnt > 0) {
217 return cnt;
218 } else {
219 /* Either some error occured or the stream was already at EOF. */
220 return -1;
221 }
222}
223
224/**
225 * Read a stream until the newline (or EOF) is encountered.
226 *
227 * @param lineptr Pointer to the output buffer in which there will be stored
228 * nul-terminated string together with the delimiter (if encountered).
229 * Will be resized if necessary.
230 * @param n Pointer to the size of the output buffer. Will be increased if
231 * necessary.
232 * @param stream Input stream.
233 * @return Number of fetched characters (including newline if encountered)
234 * or -1 on error (set in errno).
235 */
236ssize_t posix_getline(char **restrict lineptr, size_t *restrict n,
237 FILE *restrict stream)
238{
239 return posix_getdelim(lineptr, n, '\n', stream);
240}
241
242/**
243 * Reopen a file stream.
244 *
245 * @param filename Pathname of a file to be reopened or NULL for changing
246 * the mode of the stream.
247 * @param mode Mode to be used for reopening the file or changing current
248 * mode of the stream.
249 * @param stream Current stream associated with the opened file.
250 * @return On success, either a stream of the reopened file or the provided
251 * stream with a changed mode. NULL otherwise.
252 */
253FILE *posix_freopen(const char *restrict filename,
254 const char *restrict mode, FILE *restrict stream)
255{
256 assert(mode != NULL);
257 assert(stream != NULL);
258
259 /* Retrieve the node. */
260 struct stat st;
261 int rc;
262
263 if (filename == NULL) {
264 rc = fstat(stream->fd, &st);
265 } else {
266 rc = stat(filename, &st);
267 if (-rc == ENOENT) {
268 /* file does not exist, create new file */
269 FILE* tmp = fopen(filename, mode);
270 if (tmp != NULL) {
271 fclose(tmp);
272 /* try again */
273 rc = stat(filename, &st);
274 }
275 }
276 }
277
278 if (rc != EOK) {
279 fclose(stream);
280 errno = -rc;
281 return NULL;
282 }
283
284 fdi_node_t node = {
285 .fs_handle = st.fs_handle,
286 .service_id = st.service_id,
287 .index = st.index
288 };
289
290 /* Open a new stream. */
291 FILE* new = fopen_node(&node, mode);
292 if (new == NULL) {
293 fclose(stream);
294 /* fopen_node() sets errno. */
295 return NULL;
296 }
297
298 /* Close the original stream without freeing it (ignoring errors). */
299 if (stream->buf != NULL) {
300 fflush(stream);
301 }
302 if (stream->sess != NULL) {
303 async_hangup(stream->sess);
304 }
305 if (stream->fd >= 0) {
306 close(stream->fd);
307 }
308 list_remove(&stream->link);
309
310 /* Move the new stream to the original location. */
311 memcpy(stream, new, sizeof (FILE));
312 free(new);
313
314 /* Update references in the file list. */
315 stream->link.next->prev = &stream->link;
316 stream->link.prev->next = &stream->link;
317
318 return stream;
319}
320
321/**
322 *
323 * @param buf
324 * @param size
325 * @param mode
326 * @return
327 */
328FILE *posix_fmemopen(void *restrict buf, size_t size,
329 const char *restrict mode)
330{
331 // TODO
332 not_implemented();
333}
334
335/**
336 *
337 * @param bufp
338 * @param sizep
339 * @return
340 */
341FILE *posix_open_memstream(char **bufp, size_t *sizep)
342{
343 // TODO
344 not_implemented();
345}
346
347/**
348 * Write error messages to standard error.
349 *
350 * @param s Error message.
351 */
352void posix_perror(const char *s)
353{
354 if (s == NULL || s[0] == '\0') {
355 fprintf(stderr, "%s\n", posix_strerror(errno));
356 } else {
357 fprintf(stderr, "%s: %s\n", s, posix_strerror(errno));
358 }
359}
360
361struct _posix_fpos {
362 off64_t offset;
363};
364
365/** Restores stream a to position previously saved with fgetpos().
366 *
367 * @param stream Stream to restore
368 * @param pos Position to restore
369 * @return Zero on success, non-zero (with errno set) on failure
370 */
371int posix_fsetpos(FILE *stream, const posix_fpos_t *pos)
372{
373 return fseek(stream, pos->offset, SEEK_SET);
374}
375
376/** Saves the stream's position for later use by fsetpos().
377 *
378 * @param stream Stream to save
379 * @param pos Place to store the position
380 * @return Zero on success, non-zero (with errno set) on failure
381 */
382int posix_fgetpos(FILE *restrict stream, posix_fpos_t *restrict pos)
383{
384 off64_t ret = ftell(stream);
385 if (ret != -1) {
386 pos->offset = ret;
387 return 0;
388 } else {
389 return -1;
390 }
391}
392
393/**
394 * Reposition a file-position indicator in a stream.
395 *
396 * @param stream Stream to seek in.
397 * @param offset Direction and amount of bytes to seek.
398 * @param whence From where to seek.
399 * @return Zero on success, -1 otherwise.
400 */
401int posix_fseek(FILE *stream, long offset, int whence)
402{
403 return fseek(stream, (off64_t) offset, whence);
404}
405
406/**
407 * Reposition a file-position indicator in a stream.
408 *
409 * @param stream Stream to seek in.
410 * @param offset Direction and amount of bytes to seek.
411 * @param whence From where to seek.
412 * @return Zero on success, -1 otherwise.
413 */
414int posix_fseeko(FILE *stream, posix_off_t offset, int whence)
415{
416 return fseek(stream, (off64_t) offset, whence);
417}
418
419/**
420 * Discover current file offset in a stream.
421 *
422 * @param stream Stream for which the offset shall be retrieved.
423 * @return Current offset or -1 if not possible.
424 */
425long posix_ftell(FILE *stream)
426{
427 return (long) ftell(stream);
428}
429
430/**
431 * Discover current file offset in a stream.
432 *
433 * @param stream Stream for which the offset shall be retrieved.
434 * @return Current offset or -1 if not possible.
435 */
436posix_off_t posix_ftello(FILE *stream)
437{
438 return (posix_off_t) ftell(stream);
439}
440
441/**
442 * Discard prefetched data or write unwritten data.
443 *
444 * @param stream Stream that shall be flushed.
445 * @return Zero on success, EOF on failure.
446 */
447int posix_fflush(FILE *stream)
448{
449 int rc = fflush(stream);
450 if (rc < 0) {
451 errno = -rc;
452 return EOF;
453 } else {
454 return 0;
455 }
456}
457
458/**
459 * Print formatted output to the opened file.
460 *
461 * @param fildes File descriptor of the opened file.
462 * @param format Format description.
463 * @return Either the number of printed characters or negative value on error.
464 */
465int posix_dprintf(int fildes, const char *restrict format, ...)
466{
467 va_list list;
468 va_start(list, format);
469 int result = posix_vdprintf(fildes, format, list);
470 va_end(list);
471 return result;
472}
473
474/**
475 * Write ordinary string to the opened file.
476 *
477 * @param str String to be written.
478 * @param size Size of the string (in bytes)..
479 * @param fd File descriptor of the opened file.
480 * @return The number of written characters.
481 */
482static int _dprintf_str_write(const char *str, size_t size, void *fd)
483{
484 ssize_t wr = write(*(int *) fd, str, size);
485 return str_nlength(str, wr);
486}
487
488/**
489 * Write wide string to the opened file.
490 *
491 * @param str String to be written.
492 * @param size Size of the string (in bytes).
493 * @param fd File descriptor of the opened file.
494 * @return The number of written characters.
495 */
496static int _dprintf_wstr_write(const wchar_t *str, size_t size, void *fd)
497{
498 size_t offset = 0;
499 size_t chars = 0;
500 size_t sz;
501 char buf[4];
502
503 while (offset < size) {
504 sz = 0;
505 if (chr_encode(str[chars], buf, &sz, sizeof(buf)) != EOK) {
506 break;
507 }
508
509 if (write(*(int *) fd, buf, sz) != (ssize_t) sz) {
510 break;
511 }
512
513 chars++;
514 offset += sizeof(wchar_t);
515 }
516
517 return chars;
518}
519
520/**
521 * Print formatted output to the opened file.
522 *
523 * @param fildes File descriptor of the opened file.
524 * @param format Format description.
525 * @param ap Print arguments.
526 * @return Either the number of printed characters or negative value on error.
527 */
528int posix_vdprintf(int fildes, const char *restrict format, va_list ap)
529{
530 printf_spec_t spec = {
531 .str_write = _dprintf_str_write,
532 .wstr_write = _dprintf_wstr_write,
533 .data = &fildes
534 };
535
536 return printf_core(format, &spec, ap);
537}
538
539/**
540 * Print formatted output to the string.
541 *
542 * @param s Output string.
543 * @param format Format description.
544 * @return Either the number of printed characters (excluding null byte) or
545 * negative value on error.
546 */
547int posix_sprintf(char *s, const char *restrict format, ...)
548{
549 va_list list;
550 va_start(list, format);
551 int result = posix_vsprintf(s, format, list);
552 va_end(list);
553 return result;
554}
555
556/**
557 * Print formatted output to the string.
558 *
559 * @param s Output string.
560 * @param format Format description.
561 * @param ap Print arguments.
562 * @return Either the number of printed characters (excluding null byte) or
563 * negative value on error.
564 */
565int posix_vsprintf(char *s, const char *restrict format, va_list ap)
566{
567 return vsnprintf(s, STR_NO_LIMIT, format, ap);
568}
569
570/**
571 * Convert formatted input from the stream.
572 *
573 * @param stream Input stream.
574 * @param format Format description.
575 * @return The number of converted output items or EOF on failure.
576 */
577int posix_fscanf(FILE *restrict stream, const char *restrict format, ...)
578{
579 va_list list;
580 va_start(list, format);
581 int result = posix_vfscanf(stream, format, list);
582 va_end(list);
583 return result;
584}
585
586/**
587 * Convert formatted input from the standard input.
588 *
589 * @param format Format description.
590 * @return The number of converted output items or EOF on failure.
591 */
592int posix_scanf(const char *restrict format, ...)
593{
594 va_list list;
595 va_start(list, format);
596 int result = posix_vscanf(format, list);
597 va_end(list);
598 return result;
599}
600
601/**
602 * Convert formatted input from the standard input.
603 *
604 * @param format Format description.
605 * @param arg Output items.
606 * @return The number of converted output items or EOF on failure.
607 */
608int posix_vscanf(const char *restrict format, va_list arg)
609{
610 return posix_vfscanf(stdin, format, arg);
611}
612
613/**
614 * Convert formatted input from the string.
615 *
616 * @param s Input string.
617 * @param format Format description.
618 * @return The number of converted output items or EOF on failure.
619 */
620int posix_sscanf(const char *restrict s, const char *restrict format, ...)
621{
622 va_list list;
623 va_start(list, format);
624 int result = posix_vsscanf(s, format, list);
625 va_end(list);
626 return result;
627}
628
629/**
630 * Acquire file stream for the thread.
631 *
632 * @param file File stream to lock.
633 */
634void posix_flockfile(FILE *file)
635{
636 /* dummy */
637}
638
639/**
640 * Acquire file stream for the thread (non-blocking).
641 *
642 * @param file File stream to lock.
643 * @return Zero for success and non-zero if the lock cannot be acquired.
644 */
645int posix_ftrylockfile(FILE *file)
646{
647 /* dummy */
648 return 0;
649}
650
651/**
652 * Relinquish the ownership of the locked file stream.
653 *
654 * @param file File stream to unlock.
655 */
656void posix_funlockfile(FILE *file)
657{
658 /* dummy */
659}
660
661/**
662 * Get a byte from a stream (thread-unsafe).
663 *
664 * @param stream Input file stream.
665 * @return Either read byte or EOF.
666 */
667int posix_getc_unlocked(FILE *stream)
668{
669 return getc(stream);
670}
671
672/**
673 * Get a byte from the standard input stream (thread-unsafe).
674 *
675 * @return Either read byte or EOF.
676 */
677int posix_getchar_unlocked(void)
678{
679 return getchar();
680}
681
682/**
683 * Put a byte on a stream (thread-unsafe).
684 *
685 * @param c Byte to output.
686 * @param stream Output file stream.
687 * @return Either written byte or EOF.
688 */
689int posix_putc_unlocked(int c, FILE *stream)
690{
691 return putc(c, stream);
692}
693
694/**
695 * Put a byte on the standard output stream (thread-unsafe).
696 *
697 * @param c Byte to output.
698 * @return Either written byte or EOF.
699 */
700int posix_putchar_unlocked(int c)
701{
702 return putchar(c);
703}
704
705/**
706 * Remove a file or directory.
707 *
708 * @param path Pathname of the file that shall be removed.
709 * @return Zero on success, -1 (with errno set) otherwise.
710 */
711int posix_remove(const char *path)
712{
713 struct stat st;
714 int rc = stat(path, &st);
715
716 if (rc != EOK) {
717 errno = -rc;
718 return -1;
719 }
720
721 if (st.is_directory) {
722 rc = rmdir(path);
723 } else {
724 rc = unlink(path);
725 }
726
727 if (rc != EOK) {
728 errno = -rc;
729 return -1;
730 }
731 return 0;
732}
733
734/**
735 * Rename a file or directory.
736 *
737 * @param old Old pathname.
738 * @param new New pathname.
739 * @return Zero on success, -1 (with errno set) otherwise.
740 */
741int posix_rename(const char *old, const char *new)
742{
743 return errnify(rename, old, new);
744}
745
746/**
747 * Get a unique temporary file name (obsolete).
748 *
749 * @param s Buffer for the file name. Must be at least L_tmpnam bytes long.
750 * @return The value of s on success, NULL on failure.
751 */
752char *posix_tmpnam(char *s)
753{
754 assert(L_tmpnam >= posix_strlen("/tmp/tnXXXXXX"));
755
756 static char buffer[L_tmpnam + 1];
757 if (s == NULL) {
758 s = buffer;
759 }
760
761 posix_strcpy(s, "/tmp/tnXXXXXX");
762 posix_mktemp(s);
763
764 if (*s == '\0') {
765 /* Errno set by mktemp(). */
766 return NULL;
767 }
768
769 return s;
770}
771
772/**
773 * Get an unique temporary file name with additional constraints (obsolete).
774 *
775 * @param dir Path to directory, where the file should be created.
776 * @param pfx Optional prefix up to 5 characters long.
777 * @return Newly allocated unique path for temporary file. NULL on failure.
778 */
779char *posix_tempnam(const char *dir, const char *pfx)
780{
781 /* Sequence number of the filename. */
782 static int seq = 0;
783
784 size_t dir_len = posix_strlen(dir);
785 if (dir[dir_len - 1] == '/') {
786 dir_len--;
787 }
788
789 size_t pfx_len = posix_strlen(pfx);
790 if (pfx_len > 5) {
791 pfx_len = 5;
792 }
793
794 char *result = malloc(dir_len + /* slash*/ 1 +
795 pfx_len + /* three-digit seq */ 3 + /* .tmp */ 4 + /* nul */ 1);
796
797 if (result == NULL) {
798 errno = ENOMEM;
799 return NULL;
800 }
801
802 char *res_ptr = result;
803 posix_strncpy(res_ptr, dir, dir_len);
804 res_ptr += dir_len;
805 posix_strncpy(res_ptr, pfx, pfx_len);
806 res_ptr += pfx_len;
807
808 for (; seq < 1000; ++seq) {
809 snprintf(res_ptr, 8, "%03d.tmp", seq);
810
811 int orig_errno = errno;
812 errno = 0;
813 /* Check if the file exists. */
814 if (posix_access(result, F_OK) == -1) {
815 if (errno == ENOENT) {
816 errno = orig_errno;
817 break;
818 } else {
819 /* errno set by access() */
820 return NULL;
821 }
822 }
823 }
824
825 if (seq == 1000) {
826 free(result);
827 errno = EINVAL;
828 return NULL;
829 }
830
831 return result;
832}
833
834/**
835 * Create and open an unique temporary file.
836 * The file is automatically removed when the stream is closed.
837 *
838 * @param dir Path to directory, where the file should be created.
839 * @param pfx Optional prefix up to 5 characters long.
840 * @return Newly allocated unique path for temporary file. NULL on failure.
841 */
842FILE *posix_tmpfile(void)
843{
844 char filename[] = "/tmp/tfXXXXXX";
845 int fd = posix_mkstemp(filename);
846 if (fd == -1) {
847 /* errno set by mkstemp(). */
848 return NULL;
849 }
850
851 /* Unlink the created file, so that it's removed on close(). */
852 posix_unlink(filename);
853 return fdopen(fd, "w+");
854}
855
856/** @}
857 */
Note: See TracBrowser for help on using the repository browser.