source: mainline/uspace/lib/posix/stdio/scanf.c@ ec18957a

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since ec18957a was ec18957a, checked in by Jiří Zárevúcky <zarevucky.jiri@…>, 14 years ago

Added errno.h (see commentary inside).

  • Property mode set to 100644
File size: 32.5 KB
RevLine 
[08053f7]1/*
2 * Copyright (c) 2011 Petr Koupy
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 libposix
30 * @{
31 */
32/** @file Implementation of the scanf backend.
33 */
34
35#define LIBPOSIX_INTERNAL
36
37/* Must be first. */
38#include "../stdbool.h"
39
40#include "../assert.h"
[ec18957a]41#include "../errno.h"
[08053f7]42
43#include "../stdio.h"
44#include "../stdlib.h"
45#include "../stddef.h"
46#include "../string.h"
47#include "../ctype.h"
48#include "../sys/types.h"
49
50#include "../internal/common.h"
51#include "../libc/malloc.h"
52
53/** Unified data type for possible data sources for scanf. */
54typedef union __data_source {
55 FILE *stream; /**< Input file stream. */
56 const char *string; /**< Input string. */
57} _data_source;
58
59/** Internal state of the input provider. */
60enum {
61 /** Partly constructed but not yet functional. */
62 _PROV_CONSTRUCTED,
63 /** Ready to serve any request. */
64 _PROV_READY,
65 /** Cursor is temporarily lent to the external entity. No action is
66 * possible until the cursor is returned. */
67 _PROV_CURSOR_LENT,
68};
69
70/** Universal abstraction over data input for scanf. */
71typedef struct __input_provider {
72 /** Source of data elements. */
73 _data_source source;
74 /** How many elements was already processed. */
75 int consumed;
76 /** How many elements was already fetched from the source. */
77 int fetched;
78 /** Elements are fetched from the source in batches (e.g. by getline())
79 * to allow using strtol/strtod family even on streams. */
80 char *window;
81 /** Size of the current window. */
82 size_t window_size;
83 /** Points to the next element to be processed inside the current window. */
84 const char *cursor;
85 /** Internal state of the provider. */
86 int state;
87
88 /** Take control over data source. Finish initialization of the internal
89 * structures (e.g. allocation of window). */
90 void (*capture)(struct __input_provider *);
91 /** Get a single element from the source and update the internal structures
92 * accordingly (e.g. greedy update of the window). Return -1 if the
93 * element cannot be obtained. */
94 int (*pop)(struct __input_provider *);
95 /** Undo the most recent not-undone pop operation. Might be necesarry to
96 * flush current window and seek data source backwards. Return 0 if the
97 * pop history is exhausted, non-zero on success. */
98 int (*undo)(struct __input_provider *);
99 /** Lend the cursor to the caller. */
100 const char * (*borrow_cursor)(struct __input_provider *);
101 /** Take control over possibly incremented cursor and update the internal
102 * structures if necessary. */
103 void (*return_cursor)(struct __input_provider *, const char *);
104 /** Release the control over the source. That is, synchronize any
105 * fetched but non-consumed elements (e.g. by seeking) and destruct
106 * internal structures (e.g. window deallocation). */
107 void (*release)(struct __input_provider *);
108} _input_provider;
109
110/** @see __input_provider */
111static void _capture_stream(_input_provider *self)
112{
113 assert(self->source.stream);
114 assert(self->state == _PROV_CONSTRUCTED);
115 /* Caller could already pre-allocated the window. */
116 assert((self->window == NULL && self->window_size == 0) ||
117 (self->window && self->window_size > 0));
118
119 /* Initialize internal structures. */
120 self->consumed = 0;
121 ssize_t fetched = posix_getline(
122 &self->window, &self->window_size, self->source.stream);
123 if (fetched != -1) {
124 self->fetched = fetched;
125 self->cursor = self->window;
126 } else {
127 /* EOF encountered. */
128 self->fetched = 0;
129 self->cursor = NULL;
130 }
131 self->state = _PROV_READY;
132}
133
134/** @see __input_provider */
135static void _capture_string(_input_provider *self)
136{
137 assert(self->source.string);
138 assert(self->state == _PROV_CONSTRUCTED);
139
140 /* Initialize internal structures. */
141 self->consumed = 0;
142 self->fetched = posix_strlen(self->source.string);
143 self->window = (char *) self->source.string;
144 self->window_size = self->fetched + 1;
145 self->cursor = self->window;
146 self->state = _PROV_READY;
147}
148
149/** @see __input_provider */
150static int _pop_stream(_input_provider *self)
151{
152 assert(self->state == _PROV_READY);
153
154 if (self->cursor) {
155 int c = *self->cursor;
156 ++self->consumed;
157 ++self->cursor;
158 /* Do we need to fetch a new line from the source? */
159 if (*self->cursor == '\0') {
160 ssize_t fetched = posix_getline(&self->window,
161 &self->window_size, self->source.stream);
162 if (fetched != -1) {
163 self->fetched += fetched;
164 self->cursor = self->window;
165 } else {
166 /* EOF encountered. */
167 self->cursor = NULL;
168 }
169 }
170 return c;
171 } else {
172 /* Already at EOF. */
173 return -1;
174 }
175}
176
177/** @see __input_provider */
178static int _pop_string(_input_provider *self)
179{
180 assert(self->state == _PROV_READY);
181
182 if (*self->cursor != '\0') {
183 int c = *self->cursor;
184 ++self->consumed;
185 ++self->cursor;
186 return c;
187 } else {
188 /* String depleted. */
189 return -1;
190 }
191}
192
193/** @see __input_provider */
194static int _undo_stream(_input_provider *self)
195{
196 assert(self->state == _PROV_READY);
197
198 if (self->consumed == 0) {
199 /* Undo history exhausted. */
200 return 0;
201 }
202
203 if (!self->cursor || self->window == self->cursor) {
204 /* Complex case. Either at EOF (cursor == NULL) or there is no more
205 * place to retreat to inside the window. Seek the source backwards
206 * and flush the window. Regarding the scanf, this could happend only
207 * when matching unbounded string (%s) or unbounded scanset (%[) not
208 * containing newline, and at the same time newline is the character
209 * that breaks the matching process. */
210 int rc = posix_fseek(
211 self->source.stream, -1, SEEK_CUR);
212 if (rc == -1) {
213 /* Seek failed. */
214 return 0;
215 }
216 ssize_t fetched = posix_getline(&self->window,
217 &self->window_size, self->source.stream);
218 if (fetched != -1) {
219 assert(fetched == 1);
220 self->fetched = self->consumed + 1;
221 self->cursor = self->window;
222 } else {
223 /* Stream is broken. */
224 return 0;
225 }
226 } else {
227 /* Simple case. Still inside window. */
228 --self->cursor;
229 }
230 --self->consumed;
231 return 1; /* Success. */
232}
233
234/** @see __input_provider */
235static int _undo_string(_input_provider *self)
236{
237 assert(self->state == _PROV_READY);
238
239 if (self->consumed > 0) {
240 --self->consumed;
241 --self->cursor;
242 } else {
243 /* Undo history exhausted. */
244 return 0;
245 }
246 return 1; /* Success. */
247}
248
249/** @see __input_provider */
250static const char *_borrow_cursor_universal(_input_provider *self)
251{
252 assert(self->state == _PROV_READY);
253
254 self->state = _PROV_CURSOR_LENT;
255 return self->cursor;
256}
257
258/** @see __input_provider */
259static void _return_cursor_stream(_input_provider *self, const char *cursor)
260{
261 assert(self->state == _PROV_CURSOR_LENT);
262
263 /* Check how much of the window did external entity consumed. */
264 self->consumed += cursor - self->cursor;
265 self->cursor = cursor;
266 if (*self->cursor == '\0') {
267 /* Window was completely consumed, fetch new data. */
268 ssize_t fetched = posix_getline(&self->window,
269 &self->window_size, self->source.stream);
270 if (fetched != -1) {
271 self->fetched += fetched;
272 self->cursor = self->window;
273 } else {
274 /* EOF encountered. */
275 self->cursor = NULL;
276 }
277 }
278 self->state = _PROV_READY;
279}
280
281/** @see __input_provider */
282static void _return_cursor_string(_input_provider *self, const char *cursor)
283{
284 assert(self->state == _PROV_CURSOR_LENT);
285
286 /* Check how much of the window did external entity consumed. */
287 self->consumed += cursor - self->cursor;
288 self->cursor = cursor;
289 self->state = _PROV_READY;
290}
291
292/** @see __input_provider */
293static void _release_stream(_input_provider *self)
294{
295 assert(self->state == _PROV_READY);
296 assert(self->consumed >= self->fetched);
297
298 /* Try to correct the difference between the stream position and what was
299 * actually consumed. If it is not possible, continue anyway. */
300 posix_fseek(self->source.stream, self->consumed - self->fetched, SEEK_CUR);
301
302 /* Destruct internal structures. */
303 self->fetched = 0;
304 self->cursor = NULL;
305 free(self->window);
306 self->window = NULL;
307 self->window_size = 0;
308 self->state = _PROV_CONSTRUCTED;
309}
310
311/** @see __input_provider */
312static void _release_string(_input_provider *self)
313{
314 assert(self->state == _PROV_READY);
315
316 /* Destruct internal structures. */
317 self->fetched = 0;
318 self->cursor = NULL;
319 self->window = NULL;
320 self->window_size = 0;
321 self->state = _PROV_CONSTRUCTED;
322}
323
324/** Length modifier values. */
325enum {
326 LMOD_NONE,
327 LMOD_hh,
328 LMOD_h,
329 LMOD_l,
330 LMOD_ll,
331 LMOD_j,
332 LMOD_z,
333 LMOD_t,
334 LMOD_L,
335 LMOD_p, /* Reserved for %p conversion. */
336};
337
338/**
339 * Decides whether provided characters specify length modifier. If so, the
340 * recognized modifier is stored through provider pointer.
341 *
342 * @param c Candidate on the length modifier.
343 * @param _c Next character (might be NUL).
344 * @param modifier Pointer to the modifier value.
345 * @return Whether the modifier was recognized or not.
346 */
347static inline int is_length_mod(int c, int _c, int *modifier)
348{
349 assert(modifier);
350
351 /* Check whether the modifier was not already recognized. */
352 if (*modifier != LMOD_NONE) {
353 /* Format string is invalid. Notify the caller. */
354 *modifier = LMOD_NONE;
355 return 1;
356 }
357
358 switch (c) {
359 case 'h':
360 *modifier = _c == 'h' ? LMOD_hh : LMOD_h;
361 return 1;
362 case 'l':
363 *modifier = _c == 'l' ? LMOD_ll : LMOD_l;
364 return 1;
365 case 'j':
366 *modifier = LMOD_j;
367 return 1;
368 case 'z':
369 *modifier = LMOD_z;
370 return 1;
371 case 't':
372 *modifier = LMOD_t;
373 return 1;
374 case 'L':
375 *modifier = LMOD_L;
376 return 1;
377 default:
378 return 0;
379 }
380}
381
382/**
383 * Decides whether provided character specifies integer conversion. If so, the
384 * semantics of the conversion is stored through provided pointers..
385 *
386 * @param c Candidate on the integer conversion.
387 * @param is_unsigned Pointer to store whether the conversion is signed or not.
388 * @param base Pointer to store the base of the integer conversion.
389 * @return Whether the conversion was recognized or not.
390 */
391static inline int is_int_conv(int c, bool *is_unsigned, int *base)
392{
393 assert(is_unsigned && base);
394
395 switch (c) {
396 case 'd':
397 *is_unsigned = false;
398 *base = 10;
399 return 1;
400 case 'i':
401 *is_unsigned = false;
402 *base = 0;
403 return 1;
404 case 'o':
405 *is_unsigned = true;
406 *base = 8;
407 return 1;
408 case 'u':
409 *is_unsigned = true;
410 *base = 10;
411 return 1;
412 case 'p': /* According to POSIX, %p modifier is implementation defined but
413 * must correspond to its printf counterpart. */
414 case 'x':
415 case 'X':
416 *is_unsigned = true;
417 *base = 16;
418 return 1;
419 return 1;
420 default:
421 return 0;
422 }
423}
424
425/**
426 * Decides whether provided character specifies conversion of the floating
427 * point number.
428 *
429 * @param c Candidate on the floating point conversion.
430 * @return Whether the conversion was recognized or not.
431 */
432static inline int is_float_conv(int c)
433{
434 switch (c) {
435 case 'a':
436 case 'A':
437 case 'e':
438 case 'E':
439 case 'f':
440 case 'F':
441 case 'g':
442 case 'G':
443 return 1;
444 default:
445 return 0;
446 }
447}
448
449/**
450 * Decides whether provided character specifies conversion of the character
451 * sequence.
452 *
453 * @param c Candidate on the character sequence conversion.
454 * @param modifier Pointer to store length modifier for wide chars.
455 * @return Whether the conversion was recognized or not.
456 */
457static inline int is_seq_conv(int c, int *modifier)
458{
459 assert(modifier);
460
461 switch (c) {
462 case 'S':
463 *modifier = LMOD_l;
464 /* fallthrough */
465 case 's':
466 return 1;
467 case 'C':
468 *modifier = LMOD_l;
469 /* fallthrough */
470 case 'c':
471 return 1;
472 case '[':
473 return 1;
474 default:
475 return 0;
476 }
477}
478
479/**
480 * Backend for the whole family of scanf functions. Uses input provider
481 * to abstract over differences between strings and streams. Should be
482 * POSIX compliant (apart from the not supported stuff).
483 *
484 * NOT SUPPORTED: locale (see strtold), wide chars, numbered output arguments
485 *
486 * @param in Input provider.
487 * @param fmt Format description.
488 * @param arg Output arguments.
489 * @return The number of converted output items or EOF on failure.
490 */
491static inline int _internal_scanf(
492 _input_provider *in, const char *restrict fmt, va_list arg)
493{
494 int c = -1;
495 int converted_cnt = 0;
496 bool converting = false;
497 bool matching_failure = false;
498
499 bool assign_supress = false;
500 bool assign_alloc = false;
501 long width = -1;
502 int length_mod = LMOD_NONE;
503 bool int_conv_unsigned = false;
504 int int_conv_base = 0;
505
506 /* Buffers allocated by scanf for optional 'm' specifier must be remembered
507 * to deallocaate them in case of an error. Because each of those buffers
508 * corresponds to one of the argument from va_list, there is an upper bound
509 * on the number of those arguments. In case of C99, this uppper bound is
510 * 127 arguments. */
511 char *buffers[127];
512 for (int i = 0; i < 127; ++i) {
513 buffers[i] = NULL;
514 }
515 int next_unused_buffer_idx = 0;
516
517 in->capture(in);
518
519 /* Interpret format string. Control shall prematurely jump from the cycle
520 * on input failure, matching failure or illegal format string. In order
521 * to keep error reporting simple enough and to keep input consistent,
522 * error condition shall be always manifested as jump from the cycle,
523 * not function return. Format string pointer shall be updated specifically
524 * for each sub-case (i.e. there shall be no loop-wide increment).*/
525 while (*fmt) {
526
527 if (converting) {
528
529 /* Processing inside conversion specifier. Either collect optional
530 * parameters or execute the conversion. When the conversion
531 * is successfully completed, increment conversion count and switch
532 * back to normal mode. */
533 if (*fmt == '*') {
534 /* Assignment-supression (optional). */
535 if (assign_supress) {
536 /* Already set. Illegal format string. */
537 break;
538 }
539 assign_supress = true;
540 ++fmt;
541 } else if (*fmt == 'm') {
542 /* Assignment-allocation (optional). */
543 if (assign_alloc) {
544 /* Already set. Illegal format string. */
545 break;
546 }
547 assign_alloc = true;
548 ++fmt;
549 } else if (*fmt == '$') {
550 /* Reference to numbered output argument. */
551 // TODO
552 not_implemented();
553 } else if (isdigit(*fmt)) {
554 /* Maximum field length (optional). */
555 if (width != -1) {
556 /* Already set. Illegal format string. */
557 break;
558 }
559 char *fmt_new = NULL;
560 width = posix_strtol(fmt - 1, &fmt_new, 10);
561 if (width != 0) {
562 fmt = fmt_new;
563 } else {
564 /* Since POSIX requires width to be non-zero, it is
565 * sufficient to interpret zero width as error without
566 * referring to errno. */
567 break;
568 }
569 } else if (is_length_mod(*fmt, *(fmt + 1), &length_mod)) {
570 /* Length modifier (optional). */
571 if (length_mod == LMOD_NONE) {
572 /* Already set. Illegal format string. The actual detection
573 * is carried out in the is_length_mod(). */
574 break;
575 }
576 if (length_mod == LMOD_hh || length_mod == LMOD_ll) {
577 /* Modifier was two characters long. */
578 ++fmt;
579 }
580 ++fmt;
581 } else if (is_int_conv(*fmt, &int_conv_unsigned, &int_conv_base)) {
582 /* Integer conversion. */
583
584 /* Check sanity of optional parts of conversion specifier. */
585 if (assign_alloc || length_mod == LMOD_L) {
586 /* Illegal format string. */
587 break;
588 }
589
590 /* Conversion of the integer with %p specifier needs special
591 * handling, because it is not allowed to have arbitrary
592 * length modifier. */
593 if (*fmt == 'p') {
594 if (length_mod == LMOD_NONE) {
595 length_mod = LMOD_p;
596 } else {
597 /* Already set. Illegal format string. */
598 break;
599 }
600 }
601
602 /* First consume any white spaces, so we can borrow cursor
603 * from the input provider. This way, the cursor will either
604 * point to the non-white space while the input will be
605 * prefetched up to the newline (which is suitable for strtol),
606 * or the input will be at EOF. */
607 do {
608 c = in->pop(in);
609 } while (isspace(c));
610
611 /* After skipping the white spaces, can we actually continue? */
612 if (c == -1) {
613 /* Input failure. */
614 break;
615 } else {
616 /* Everything is OK, just undo the last pop, so the cursor
617 * can be borrowed. */
618 in->undo(in);
619 }
620
621 const char *cur_borrowed = NULL;
622 const char *cur_limited = NULL;
623 char *cur_updated = NULL;
624
625 /* Borrow the cursor. Until it is returned to the provider
626 * we cannot jump from the cycle, because it would leave
627 * the input inconsistent. */
628 cur_borrowed = in->borrow_cursor(in);
629
630 /* If the width is limited, the cursor horizont must be
631 * decreased accordingly. Otherwise the strtol could read more
632 * than allowed by width. */
633 if (width != -1) {
634 cur_limited = posix_strndup(cur_borrowed, width);
635 } else {
636 cur_limited = cur_borrowed;
637 }
638 cur_updated = (char *) cur_limited;
639
640 long long sres = 0;
641 unsigned long long ures = 0;
642 errno = 0; /* Reset errno to recognize error later. */
643 /* Try to convert the integer. */
644 if (int_conv_unsigned) {
645 ures = posix_strtoull(cur_limited, &cur_updated, int_conv_base);
646 } else {
647 sres = posix_strtoll(cur_limited, &cur_updated, int_conv_base);
648 }
649
650 /* Update the cursor so it can be returned to the provider. */
651 cur_borrowed += cur_updated - cur_limited;
652 if (width != -1) {
653 /* Deallocate duplicated part of the cursor view. */
654 free(cur_limited);
655 }
656 cur_limited = NULL;
657 cur_updated = NULL;
658 /* Return the cursor to the provider. Input consistency is again
659 * the job of the provider, so we can report errors from
660 * now on. */
661 in->return_cursor(in, cur_borrowed);
662 cur_borrowed = NULL;
663
664 /* Check whether the conversion was successful. */
665 if (errno != EOK) {
666 matching_failure = true;
667 break;
668 }
669
670 /* If nto supressed, assign the converted integer into
671 * the next output argument. */
672 if (!assign_supress) {
673 if (int_conv_unsigned) {
674 switch (length_mod) {
675 case LMOD_hh: ; /* Label cannot be part of declaration. */
676 unsigned char *phh = va_arg(arg, unsigned char *);
677 *phh = (unsigned char) ures;
678 break;
679 case LMOD_h: ;
680 unsigned short *ph = va_arg(arg, unsigned short *);
681 *ph = (unsigned short) ures;
682 break;
683 case LMOD_NONE: ;
684 unsigned *pdef = va_arg(arg, unsigned *);
685 *pdef = (unsigned) ures;
686 break;
687 case LMOD_l: ;
688 unsigned long *pl = va_arg(arg, unsigned long *);
689 *pl = (unsigned long) ures;
690 break;
691 case LMOD_ll: ;
692 unsigned long long *pll = va_arg(arg, unsigned long long *);
693 *pll = (unsigned long long) ures;
694 break;
695 case LMOD_j: ;
696 posix_uintmax_t *pj = va_arg(arg, posix_uintmax_t *);
697 *pj = (posix_uintmax_t) ures;
698 break;
699 case LMOD_z: ;
700 size_t *pz = va_arg(arg, size_t *);
701 *pz = (size_t) ures;
702 break;
703 case LMOD_t: ;
704 // FIXME: What is unsigned counterpart of the ptrdiff_t?
705 size_t *pt = va_arg(arg, size_t *);
706 *pt = (size_t) ures;
707 break;
708 case LMOD_p: ;
709 void **pp = va_arg(arg, void **);
710 *pp = (void *) (uintptr_t) ures;
711 break;
712 default:
713 assert(false);
714 }
715 } else {
716 switch (length_mod) {
717 case LMOD_hh: ; /* Label cannot be part of declaration. */
718 signed char *phh = va_arg(arg, signed char *);
719 *phh = (signed char) sres;
720 break;
721 case LMOD_h: ;
722 short *ph = va_arg(arg, short *);
723 *ph = (short) sres;
724 break;
725 case LMOD_NONE: ;
726 int *pdef = va_arg(arg, int *);
727 *pdef = (int) sres;
728 break;
729 case LMOD_l: ;
730 long *pl = va_arg(arg, long *);
731 *pl = (long) sres;
732 break;
733 case LMOD_ll: ;
734 long long *pll = va_arg(arg, long long *);
735 *pll = (long long) sres;
736 break;
737 case LMOD_j: ;
738 posix_intmax_t *pj = va_arg(arg, posix_intmax_t *);
739 *pj = (posix_intmax_t) sres;
740 break;
741 case LMOD_z: ;
742 ssize_t *pz = va_arg(arg, ssize_t *);
743 *pz = (ssize_t) sres;
744 break;
745 case LMOD_t: ;
746 posix_ptrdiff_t *pt = va_arg(arg, posix_ptrdiff_t *);
747 *pt = (posix_ptrdiff_t) sres;
748 break;
749 default:
750 assert(false);
751 }
752 }
753 ++converted_cnt;
754 }
755
756 converting = false;
757 ++fmt;
758 } else if (is_float_conv(*fmt)) {
759 /* Floating point number conversion. */
760
761 /* Check sanity of optional parts of conversion specifier. */
762 if (assign_alloc) {
763 /* Illegal format string. */
764 break;
765 }
766 if (length_mod != LMOD_NONE &&
767 length_mod != LMOD_l &&
768 length_mod != LMOD_L) {
769 /* Illegal format string. */
770 break;
771 }
772
773 /* First consume any white spaces, so we can borrow cursor
774 * from the input provider. This way, the cursor will either
775 * point to the non-white space while the input will be
776 * prefetched up to the newline (which is suitable for strtof),
777 * or the input will be at EOF. */
778 do {
779 c = in->pop(in);
780 } while (isspace(c));
781
782 /* After skipping the white spaces, can we actually continue? */
783 if (c == -1) {
784 /* Input failure. */
785 break;
786 } else {
787 /* Everything is OK, just undo the last pop, so the cursor
788 * can be borrowed. */
789 in->undo(in);
790 }
791
792 const char *cur_borrowed = NULL;
793 const char *cur_limited = NULL;
794 char *cur_updated = NULL;
795
796 /* Borrow the cursor. Until it is returned to the provider
797 * we cannot jump from the cycle, because it would leave
798 * the input inconsistent. */
799 cur_borrowed = in->borrow_cursor(in);
800
801 /* If the width is limited, the cursor horizont must be
802 * decreased accordingly. Otherwise the strtof could read more
803 * than allowed by width. */
804 if (width != -1) {
805 cur_limited = posix_strndup(cur_borrowed, width);
806 } else {
807 cur_limited = cur_borrowed;
808 }
809 cur_updated = (char *) cur_limited;
810
811 float fres = 0.0;
812 double dres = 0.0;
813 long double ldres = 0.0;
814 errno = 0; /* Reset errno to recognize error later. */
815 /* Try to convert the floating point nubmer. */
816 switch (length_mod) {
817 case LMOD_NONE:
818 fres = posix_strtof(cur_limited, &cur_updated);
819 break;
820 case LMOD_l:
821 dres = posix_strtod(cur_limited, &cur_updated);
822 break;
823 case LMOD_L:
824 ldres = posix_strtold(cur_limited, &cur_updated);
825 break;
826 default:
827 assert(false);
828 }
829
830 /* Update the cursor so it can be returned to the provider. */
831 cur_borrowed += cur_updated - cur_limited;
832 if (width != -1) {
833 /* Deallocate duplicated part of the cursor view. */
834 free(cur_limited);
835 }
836 cur_limited = NULL;
837 cur_updated = NULL;
838 /* Return the cursor to the provider. Input consistency is again
839 * the job of the provider, so we can report errors from
840 * now on. */
841 in->return_cursor(in, cur_borrowed);
842 cur_borrowed = NULL;
843
844 /* Check whether the conversion was successful. */
845 if (errno != EOK) {
846 matching_failure = true;
847 break;
848 }
849
850 /* If nto supressed, assign the converted floating point number
851 * into the next output argument. */
852 if (!assign_supress) {
853 switch (length_mod) {
854 case LMOD_NONE: ; /* Label cannot be part of declaration. */
855 float *pf = va_arg(arg, float *);
856 *pf = fres;
857 break;
858 case LMOD_l: ;
859 double *pd = va_arg(arg, double *);
860 *pd = dres;
861 break;
862 case LMOD_L: ;
863 long double *pld = va_arg(arg, long double *);
864 *pld = ldres;
865 break;
866 default:
867 assert(false);
868 }
869 ++converted_cnt;
870 }
871
872 converting = false;
873 ++fmt;
874 } else if (is_seq_conv(*fmt, &length_mod)) {
875 /* Character sequence conversion. */
876
877 /* Check sanity of optional parts of conversion specifier. */
878 if (length_mod != LMOD_NONE &&
879 length_mod != LMOD_l) {
880 /* Illegal format string. */
881 break;
882 }
883
884 if (length_mod == LMOD_l) {
885 /* Wide chars not supported. */
886 // TODO
887 not_implemented();
888 }
889
890 int term_size = 1; /* Size of the terminator (0 or 1)). */
891 if (*fmt == 'c') {
892 term_size = 0;
893 width = width == -1 ? 1 : width;
894 }
895
896 if (*fmt == 's') {
897 /* Skip white spaces. */
898 do {
899 c = in->pop(in);
900 } while (isspace(c));
901 } else {
902 /* Fetch a single character. */
903 c = in->pop(in);
904 }
905
906 /* Check whether there is still input to read. */
907 if (c == -1) {
908 /* Input failure. */
909 break;
910 }
911
912 /* Prepare scanset. */
913 char terminate_on[256];
914 for (int i = 0; i < 256; ++i) {
915 terminate_on[i] = 0;
916 }
917 if (*fmt == 'c') {
918 ++fmt;
919 } else if (*fmt == 's') {
920 terminate_on[' '] = 1;
921 terminate_on['\n'] = 1;
922 terminate_on['\t'] = 1;
923 terminate_on['\f'] = 1;
924 terminate_on['\r'] = 1;
925 terminate_on['\v'] = 1;
926 ++fmt;
927 } else {
928 assert(*fmt == '[');
929 bool not = false;
930 bool dash = false;
931 ++fmt;
932 /* Check for negation. */
933 if (*fmt == '^') {
934 not = true;
935 ++fmt;
936 }
937 /* Check for escape sequences. */
938 if (*fmt == '-' || *fmt == ']') {
939 terminate_on[(int) *fmt] = 1;
940 ++fmt;
941 }
942 /* Check for ordinary characters and ranges. */
943 while (*fmt != '\0' && *fmt != ']') {
944 if (dash) {
945 for (char chr = *(fmt - 2); chr <= *fmt; ++chr) {
946 terminate_on[(int) chr] = 1;
947 }
948 dash = false;
949 } else if (*fmt == '-') {
950 dash = true;
951 } else {
952 terminate_on[(int) *fmt] = 1;
953 }
954 ++fmt;
955 }
956 /* Check for escape sequence. */
957 if (dash == true) {
958 terminate_on['-'] = 1;
959 }
960 /* Check whether the specifier was correctly terminated.*/
961 if (*fmt == '\0') {
962 /* Illegal format string. */
963 break;
964 } else {
965 ++fmt;
966 }
967 /* Inverse the scanset if necessary. */
968 if (not == false) {
969 for (int i = 0; i < 256; ++i) {
970 terminate_on[i] = terminate_on[i] ? 0 : 1;
971 }
972 }
973 }
974
975 char * buf = NULL;
976 size_t buf_size = 0;
977 char * cur = NULL;
978 size_t alloc_step = 80; /* Buffer size gain during reallocation. */
979 int my_buffer_idx = 0;
980
981 /* Retrieve the buffer into which popped characters
982 * will be stored. */
983 if (!assign_supress) {
984 if (assign_alloc) {
985 /* We must allocate our own buffer. */
986 buf_size =
987 width == -1 ? alloc_step : (size_t) width + term_size;
988 buf = malloc(buf_size);
989 if (!buf) {
990 /* No memory. */
991 break;
992 }
993 my_buffer_idx = next_unused_buffer_idx;
994 ++next_unused_buffer_idx;
995 buffers[my_buffer_idx] = buf;
996 cur = buf;
997 } else {
998 /* Caller provided its buffer. */
999 buf = va_arg(arg, char *);
1000 cur = buf;
1001 buf_size =
1002 width == -1 ? SIZE_MAX : (size_t) width + term_size;
1003 }
1004 }
1005
1006 /* Match the string. The next character is already popped. */
1007 while ((width == -1 || width > 0) && c != -1 && !terminate_on[c]) {
1008
1009 /* Check whether the buffer is still sufficiently large. */
1010 if (!assign_supress) {
1011 /* Always reserve space for the null terminator. */
1012 if (cur == buf + buf_size - term_size) {
1013 /* Buffer size must be increased. */
1014 buf = realloc(buf, buf_size + alloc_step);
1015 if (buf) {
1016 buffers[my_buffer_idx] = buf;
1017 cur = buf + buf_size - term_size;
1018 buf_size += alloc_step;
1019 } else {
1020 /* Break just from this tight loop. Errno will
1021 * be checked after it. */
1022 break;
1023 }
1024 }
1025 /* Store the input character. */
1026 *cur = c;
1027 }
1028
1029 width = width == -1 ? -1 : width - 1;
1030 ++cur;
1031 c = in->pop(in);
1032 }
1033 if (errno == ENOMEM) {
1034 /* No memory. */
1035 break;
1036 }
1037 if (c != -1) {
1038 /* There is still more input, so undo the last pop. */
1039 in->undo(in);
1040 }
1041
1042 /* Check for failures. */
1043 if (cur == buf) {
1044 /* Matching failure. Input failure was already checked
1045 * earlier. */
1046 matching_failure = true;
1047 if (!assign_supress && assign_alloc) {
1048 /* Roll back. */
1049 free(buf);
1050 buffers[my_buffer_idx] = NULL;
1051 --next_unused_buffer_idx;
1052 }
1053 break;
1054 }
1055
1056 /* Store the terminator. */
1057 if (!assign_supress && term_size > 0) {
1058 /* Space for the terminator was reserved. */
1059 *cur = '\0';
1060 }
1061
1062 /* Store the result if not already stored. */
1063 if (!assign_supress) {
1064 if (assign_alloc) {
1065 char **pbuf = va_arg(arg, char **);
1066 *pbuf = buf;
1067 }
1068 ++converted_cnt;
1069 }
1070
1071 converting = false;
1072 /* Format string pointer already incremented. */
1073 } else if (*fmt == 'n') {
1074 /* Report the number of consumed bytes so far. */
1075
1076 /* Sanity check. */
1077 bool sane =
1078 width == -1 &&
1079 length_mod == LMOD_NONE &&
1080 assign_alloc == false &&
1081 assign_supress == false;
1082
1083 if (sane) {
1084 int *pi = va_arg(arg, int *);
1085 *pi = in->consumed;
1086 } else {
1087 /* Illegal format string. */
1088 break;
1089 }
1090
1091 /* This shall not be counted as conversion. */
1092 converting = false;
1093 ++fmt;
1094 } else {
1095 /* Illegal format string. */
1096 break;
1097 }
1098
1099 } else {
1100
1101 /* Processing outside conversion specifier. Either skip white
1102 * spaces or match characters one by one. If conversion specifier
1103 * is detected, switch to coversion mode. */
1104 if (isspace(*fmt)) {
1105 /* Skip white spaces in the format string. */
1106 while (isspace(*fmt)) {
1107 ++fmt;
1108 }
1109 /* Skip white spaces in the input. */
1110 do {
1111 c = in->pop(in);
1112 } while (isspace(c));
1113 if (c != -1) {
1114 /* Input is not at EOF, so undo the last pop operation. */
1115 in->undo(in);
1116 }
1117 } else if (*fmt == '%' && *(fmt + 1) != '%') {
1118 /* Conversion specifier detected. Switch modes. */
1119 converting = true;
1120 /* Reset the conversion context. */
1121 assign_supress = false;
1122 assign_alloc = false;
1123 width = -1;
1124 length_mod = LMOD_NONE;
1125 int_conv_unsigned = false;
1126 int_conv_base = 0;
1127 ++fmt;
1128 } else {
1129 /* One by one matching. */
1130 if (*fmt == '%') {
1131 /* Escape sequence detected. */
1132 ++fmt;
1133 assert(*fmt == '%');
1134 }
1135 c = in->pop(in);
1136 if (c == -1) {
1137 /* Input failure. */
1138 break;
1139 } else if (c != *fmt) {
1140 /* Matching failure. */
1141 in->undo(in);
1142 matching_failure = true;
1143 break;
1144 } else {
1145 ++fmt;
1146 }
1147 }
1148
1149 }
1150
1151 }
1152
1153 in->release(in);
1154
1155 /* This somewhat complicated return value decision is required by POSIX. */
1156 int rc;
1157 if (matching_failure) {
1158 rc = converted_cnt;
1159 } else {
1160 if (errno == EOK) {
1161 rc = converted_cnt > 0 ? converted_cnt : EOF;
1162 } else {
1163 rc = EOF;
1164 }
1165 }
1166 if (rc == EOF) {
1167 /* Caller will not know how many arguments were successfully converted,
1168 * so the deallocation of buffers is our responsibility. */
1169 for (int i = 0; i < next_unused_buffer_idx; ++i) {
1170 free(buffers[i]);
1171 buffers[i] = NULL;
1172 }
1173 next_unused_buffer_idx = 0;
1174 }
1175 return rc;
1176}
1177
1178/**
1179 * Convert formatted input from the stream.
1180 *
1181 * @param stream Input stream.
1182 * @param format Format description.
1183 * @param arg Output items.
1184 * @return The number of converted output items or EOF on failure.
1185 */
1186int posix_vfscanf(
1187 FILE *restrict stream, const char *restrict format, va_list arg)
1188{
1189 _input_provider provider = {
1190 { 0 }, 0, 0, NULL, 0, NULL, _PROV_CONSTRUCTED,
1191 _capture_stream, _pop_stream, _undo_stream,
1192 _borrow_cursor_universal, _return_cursor_stream, _release_stream
1193 };
1194 provider.source.stream = stream;
1195 return _internal_scanf(&provider, format, arg);
1196}
1197
1198/**
1199 * Convert formatted input from the string.
1200 *
1201 * @param s Input string.
1202 * @param format Format description.
1203 * @param arg Output items.
1204 * @return The number of converted output items or EOF on failure.
1205 */
1206int posix_vsscanf(
1207 const char *restrict s, const char *restrict format, va_list arg)
1208{
1209 _input_provider provider = {
1210 { 0 }, 0, 0, NULL, 0, NULL, _PROV_CONSTRUCTED,
1211 _capture_string, _pop_string, _undo_string,
1212 _borrow_cursor_universal, _return_cursor_string, _release_string
1213 };
1214 provider.source.string = s;
1215 return _internal_scanf(&provider, format, arg);
1216}
1217
1218/** @}
1219 */
Note: See TracBrowser for help on using the repository browser.