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

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

A few more cstyle fixes.

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