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

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

More cstyle-related fixes.

  • Property mode set to 100644
File size: 32.9 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': /* According to POSIX, %p modifier is implementation defined but
414 * must correspond to its printf counterpart. */
415 case 'x':
416 case 'X':
417 *is_unsigned = true;
418 *base = 16;
419 return 1;
420 return 1;
421 default:
422 return 0;
423 }
424}
425
426/**
427 * Decides whether provided character specifies conversion of the floating
428 * point number.
429 *
430 * @param c Candidate on the floating point conversion.
431 * @return Whether the conversion was recognized or not.
432 */
433static inline int is_float_conv(int c)
434{
435 switch (c) {
436 case 'a':
437 case 'A':
438 case 'e':
439 case 'E':
440 case 'f':
441 case 'F':
442 case 'g':
443 case 'G':
444 return 1;
445 default:
446 return 0;
447 }
448}
449
450/**
451 * Decides whether provided character specifies conversion of the character
452 * sequence.
453 *
454 * @param c Candidate on the character sequence conversion.
455 * @param modifier Pointer to store length modifier for wide chars.
456 * @return Whether the conversion was recognized or not.
457 */
458static inline int is_seq_conv(int c, int *modifier)
459{
460 assert(modifier);
461
462 switch (c) {
463 case 'S':
464 *modifier = LMOD_l;
465 /* Fallthrough */
466 case 's':
467 return 1;
468 case 'C':
469 *modifier = LMOD_l;
470 /* Fallthrough */
471 case 'c':
472 return 1;
473 case '[':
474 return 1;
475 default:
476 return 0;
477 }
478}
479
480/**
481 * Backend for the whole family of scanf functions. Uses input provider
482 * to abstract over differences between strings and streams. Should be
483 * POSIX compliant (apart from the not supported stuff).
484 *
485 * NOT SUPPORTED: locale (see strtold), wide chars, numbered output arguments
486 *
487 * @param in Input provider.
488 * @param fmt Format description.
489 * @param arg Output arguments.
490 * @return The number of converted output items or EOF on failure.
491 */
492static inline int _internal_scanf(
493 _input_provider *in, const char *restrict fmt, va_list arg)
494{
495 int c = -1;
496 int converted_cnt = 0;
497 bool converting = false;
498 bool matching_failure = false;
499
500 bool assign_supress = false;
501 bool assign_alloc = false;
502 long width = -1;
503 int length_mod = LMOD_NONE;
504 bool int_conv_unsigned = false;
505 int int_conv_base = 0;
506
507 /* Buffers allocated by scanf for optional 'm' specifier must be remembered
508 * to deallocaate them in case of an error. Because each of those buffers
509 * corresponds to one of the argument from va_list, there is an upper bound
510 * on the number of those arguments. In case of C99, this uppper bound is
511 * 127 arguments. */
512 char *buffers[127];
513 for (int i = 0; i < 127; ++i) {
514 buffers[i] = NULL;
515 }
516 int next_unused_buffer_idx = 0;
517
518 in->capture(in);
519
520 /* Interpret format string. Control shall prematurely jump from the cycle
521 * on input failure, matching failure or illegal format string. In order
522 * to keep error reporting simple enough and to keep input consistent,
523 * error condition shall be always manifested as jump from the cycle,
524 * not function return. Format string pointer shall be updated specifically
525 * for each sub-case (i.e. there shall be no loop-wide increment).*/
526 while (*fmt) {
527
528 if (converting) {
529
530 /* Processing inside conversion specifier. Either collect optional
531 * parameters or execute the conversion. When the conversion
532 * is successfully completed, increment conversion count and switch
533 * back to normal mode. */
534 if (*fmt == '*') {
535 /* Assignment-supression (optional). */
536 if (assign_supress) {
537 /* Already set. Illegal format string. */
538 break;
539 }
540 assign_supress = true;
541 ++fmt;
542 } else if (*fmt == 'm') {
543 /* Assignment-allocation (optional). */
544 if (assign_alloc) {
545 /* Already set. Illegal format string. */
546 break;
547 }
548 assign_alloc = true;
549 ++fmt;
550 } else if (*fmt == '$') {
551 /* Reference to numbered output argument. */
552 // TODO
553 not_implemented();
554 } else if (isdigit(*fmt)) {
555 /* Maximum field length (optional). */
556 if (width != -1) {
557 /* Already set. Illegal format string. */
558 break;
559 }
560 char *fmt_new = NULL;
561 width = strtol(fmt, &fmt_new, 10);
562 if (width != 0) {
563 fmt = fmt_new;
564 } else {
565 /* Since POSIX requires width to be non-zero, it is
566 * sufficient to interpret zero width as error without
567 * referring to errno. */
568 break;
569 }
570 } else if (is_length_mod(*fmt, *(fmt + 1), &length_mod)) {
571 /* Length modifier (optional). */
572 if (length_mod == LMOD_NONE) {
573 /* Already set. Illegal format string. The actual detection
574 * is carried out in the is_length_mod(). */
575 break;
576 }
577 if (length_mod == LMOD_hh || length_mod == LMOD_ll) {
578 /* Modifier was two characters long. */
579 ++fmt;
580 }
581 ++fmt;
582 } else if (is_int_conv(*fmt, &int_conv_unsigned, &int_conv_base)) {
583 /* Integer conversion. */
584
585 /* Check sanity of optional parts of conversion specifier. */
586 if (assign_alloc || length_mod == LMOD_L) {
587 /* Illegal format string. */
588 break;
589 }
590
591 /* Conversion of the integer with %p specifier needs special
592 * handling, because it is not allowed to have arbitrary
593 * length modifier. */
594 if (*fmt == 'p') {
595 if (length_mod == LMOD_NONE) {
596 length_mod = LMOD_p;
597 } else {
598 /* Already set. Illegal format string. */
599 break;
600 }
601 }
602
603 /* First consume any white spaces, so we can borrow cursor
604 * from the input provider. This way, the cursor will either
605 * point to the non-white space while the input will be
606 * prefetched up to the newline (which is suitable for strtol),
607 * or the input will be at EOF. */
608 do {
609 c = in->pop(in);
610 } while (isspace(c));
611
612 /* After skipping the white spaces, can we actually continue? */
613 if (c == -1) {
614 /* Input failure. */
615 break;
616 } else {
617 /* Everything is OK, just undo the last pop, so the cursor
618 * can be borrowed. */
619 in->undo(in);
620 }
621
622 const char *cur_borrowed = NULL;
623 char *cur_duplicated = NULL;
624 const char *cur_limited = NULL;
625 const char *cur_updated = NULL;
626
627 /* Borrow the cursor. Until it is returned to the provider
628 * we cannot jump from the cycle, because it would leave
629 * the input inconsistent. */
630 cur_borrowed = in->borrow_cursor(in);
631
632 /* If the width is limited, the cursor horizont must be
633 * decreased accordingly. Otherwise the strtol could read more
634 * than allowed by width. */
635 if (width != -1) {
636 cur_duplicated = strndup(cur_borrowed, width);
637 cur_limited = cur_duplicated;
638 } else {
639 cur_limited = cur_borrowed;
640 }
641 cur_updated = cur_limited;
642
643 long long sres = 0;
644 unsigned long long ures = 0;
645 errno = 0; /* Reset errno to recognize error later. */
646 /* Try to convert the integer. */
647 if (int_conv_unsigned) {
648 ures = strtoull(cur_limited, (char **) &cur_updated, int_conv_base);
649 } else {
650 sres = strtoll(cur_limited, (char **) &cur_updated, int_conv_base);
651 }
652
653 /* Update the cursor so it can be returned to the provider. */
654 cur_borrowed += cur_updated - cur_limited;
655 if (cur_duplicated != NULL) {
656 /* Deallocate duplicated part of the cursor view. */
657 free(cur_duplicated);
658 }
659 cur_limited = NULL;
660 cur_updated = NULL;
661 cur_duplicated = NULL;
662 /* Return the cursor to the provider. Input consistency is again
663 * the job of the provider, so we can report errors from
664 * now on. */
665 in->return_cursor(in, cur_borrowed);
666 cur_borrowed = NULL;
667
668 /* Check whether the conversion was successful. */
669 if (errno != EOK) {
670 matching_failure = true;
671 break;
672 }
673
674 /* If not supressed, assign the converted integer into
675 * the next output argument. */
676 if (!assign_supress) {
677 if (int_conv_unsigned) {
678 unsigned char *phh;
679 unsigned short *ph;
680 unsigned *pdef;
681 unsigned long *pl;
682 unsigned long long *pll;
683 uintmax_t *pj;
684 size_t *pz;
685 // XXX: What is unsigned counterpart of the ptrdiff_t?
686 size_t *pt;
687 void **pp;
688
689 switch (length_mod) {
690 case LMOD_hh:
691 phh = va_arg(arg, unsigned char *);
692 *phh = (unsigned char) ures;
693 break;
694 case LMOD_h:
695 ph = va_arg(arg, unsigned short *);
696 *ph = (unsigned short) ures;
697 break;
698 case LMOD_NONE:
699 pdef = va_arg(arg, unsigned *);
700 *pdef = (unsigned) ures;
701 break;
702 case LMOD_l:
703 pl = va_arg(arg, unsigned long *);
704 *pl = (unsigned long) ures;
705 break;
706 case LMOD_ll:
707 pll = va_arg(arg, unsigned long long *);
708 *pll = (unsigned long long) ures;
709 break;
710 case LMOD_j:
711 pj = va_arg(arg, uintmax_t *);
712 *pj = (uintmax_t) ures;
713 break;
714 case LMOD_z:
715 pz = va_arg(arg, size_t *);
716 *pz = (size_t) ures;
717 break;
718 case LMOD_t:
719 pt = va_arg(arg, size_t *);
720 *pt = (size_t) ures;
721 break;
722 case LMOD_p:
723 pp = va_arg(arg, void **);
724 *pp = (void *) (uintptr_t) ures;
725 break;
726 default:
727 assert(false);
728 }
729 } else {
730 signed char *phh;
731 short *ph;
732 int *pdef;
733 long *pl;
734 long long *pll;
735 intmax_t *pj;
736 ssize_t *pz;
737 ptrdiff_t *pt;
738
739 switch (length_mod) {
740 case LMOD_hh:
741 phh = va_arg(arg, signed char *);
742 *phh = (signed char) sres;
743 break;
744 case LMOD_h:
745 ph = va_arg(arg, short *);
746 *ph = (short) sres;
747 break;
748 case LMOD_NONE:
749 pdef = va_arg(arg, int *);
750 *pdef = (int) sres;
751 break;
752 case LMOD_l:
753 pl = va_arg(arg, long *);
754 *pl = (long) sres;
755 break;
756 case LMOD_ll:
757 pll = va_arg(arg, long long *);
758 *pll = (long long) sres;
759 break;
760 case LMOD_j:
761 pj = va_arg(arg, intmax_t *);
762 *pj = (intmax_t) sres;
763 break;
764 case LMOD_z:
765 pz = va_arg(arg, ssize_t *);
766 *pz = (ssize_t) sres;
767 break;
768 case LMOD_t:
769 pt = va_arg(arg, ptrdiff_t *);
770 *pt = (ptrdiff_t) sres;
771 break;
772 default:
773 assert(false);
774 }
775 }
776 ++converted_cnt;
777 }
778
779 converting = false;
780 ++fmt;
781 } else if (is_float_conv(*fmt)) {
782 /* Floating point number conversion. */
783
784 /* Check sanity of optional parts of conversion specifier. */
785 if (assign_alloc) {
786 /* Illegal format string. */
787 break;
788 }
789 if (length_mod != LMOD_NONE &&
790 length_mod != LMOD_l &&
791 length_mod != LMOD_L) {
792 /* Illegal format string. */
793 break;
794 }
795
796 /* First consume any white spaces, so we can borrow cursor
797 * from the input provider. This way, the cursor will either
798 * point to the non-white space while the input will be
799 * prefetched up to the newline (which is suitable for strtof),
800 * or the input will be at EOF. */
801 do {
802 c = in->pop(in);
803 } while (isspace(c));
804
805 /* After skipping the white spaces, can we actually continue? */
806 if (c == -1) {
807 /* Input failure. */
808 break;
809 } else {
810 /* Everything is OK, just undo the last pop, so the cursor
811 * can be borrowed. */
812 in->undo(in);
813 }
814
815 const char *cur_borrowed = NULL;
816 const char *cur_limited = NULL;
817 char *cur_duplicated = NULL;
818 const char *cur_updated = NULL;
819
820 /* Borrow the cursor. Until it is returned to the provider
821 * we cannot jump from the cycle, because it would leave
822 * the input inconsistent. */
823 cur_borrowed = in->borrow_cursor(in);
824
825 /* If the width is limited, the cursor horizont must be
826 * decreased accordingly. Otherwise the strtof could read more
827 * than allowed by width. */
828 if (width != -1) {
829 cur_duplicated = strndup(cur_borrowed, width);
830 cur_limited = cur_duplicated;
831 } else {
832 cur_limited = cur_borrowed;
833 }
834 cur_updated = cur_limited;
835
836 float fres = 0.0;
837 double dres = 0.0;
838 long double ldres = 0.0;
839 errno = 0; /* Reset errno to recognize error later. */
840 /* Try to convert the floating point nubmer. */
841 switch (length_mod) {
842 case LMOD_NONE:
843 fres = strtof(cur_limited, (char **) &cur_updated);
844 break;
845 case LMOD_l:
846 dres = strtod(cur_limited, (char **) &cur_updated);
847 break;
848 case LMOD_L:
849 ldres = strtold(cur_limited, (char **) &cur_updated);
850 break;
851 default:
852 assert(false);
853 }
854
855 /* Update the cursor so it can be returned to the provider. */
856 cur_borrowed += cur_updated - cur_limited;
857 if (cur_duplicated != NULL) {
858 /* Deallocate duplicated part of the cursor view. */
859 free(cur_duplicated);
860 }
861 cur_limited = NULL;
862 cur_updated = NULL;
863 /* Return the cursor to the provider. Input consistency is again
864 * the job of the provider, so we can report errors from
865 * now on. */
866 in->return_cursor(in, cur_borrowed);
867 cur_borrowed = NULL;
868
869 /* Check whether the conversion was successful. */
870 if (errno != EOK) {
871 matching_failure = true;
872 break;
873 }
874
875 /* If nto supressed, assign the converted floating point number
876 * into the next output argument. */
877 if (!assign_supress) {
878 float *pf;
879 double *pd;
880 long double *pld;
881 switch (length_mod) {
882 case LMOD_NONE:
883 pf = va_arg(arg, float *);
884 *pf = fres;
885 break;
886 case LMOD_l:
887 pd = va_arg(arg, double *);
888 *pd = dres;
889 break;
890 case LMOD_L:
891 pld = va_arg(arg, long double *);
892 *pld = ldres;
893 break;
894 default:
895 assert(false);
896 }
897 ++converted_cnt;
898 }
899
900 converting = false;
901 ++fmt;
902 } else if (is_seq_conv(*fmt, &length_mod)) {
903 /* Character sequence conversion. */
904
905 /* Check sanity of optional parts of conversion specifier. */
906 if (length_mod != LMOD_NONE &&
907 length_mod != LMOD_l) {
908 /* Illegal format string. */
909 break;
910 }
911
912 if (length_mod == LMOD_l) {
913 /* Wide chars not supported. */
914 // TODO
915 not_implemented();
916 }
917
918 int term_size = 1; /* Size of the terminator (0 or 1)). */
919 if (*fmt == 'c') {
920 term_size = 0;
921 width = width == -1 ? 1 : width;
922 }
923
924 if (*fmt == 's') {
925 /* Skip white spaces. */
926 do {
927 c = in->pop(in);
928 } while (isspace(c));
929 } else {
930 /* Fetch a single character. */
931 c = in->pop(in);
932 }
933
934 /* Check whether there is still input to read. */
935 if (c == -1) {
936 /* Input failure. */
937 break;
938 }
939
940 /* Prepare scanset. */
941 char terminate_on[256];
942 for (int i = 0; i < 256; ++i) {
943 terminate_on[i] = 0;
944 }
945 if (*fmt == 'c') {
946 ++fmt;
947 } else if (*fmt == 's') {
948 terminate_on[' '] = 1;
949 terminate_on['\n'] = 1;
950 terminate_on['\t'] = 1;
951 terminate_on['\f'] = 1;
952 terminate_on['\r'] = 1;
953 terminate_on['\v'] = 1;
954 ++fmt;
955 } else {
956 assert(*fmt == '[');
957 bool not = false;
958 bool dash = false;
959 ++fmt;
960 /* Check for negation. */
961 if (*fmt == '^') {
962 not = true;
963 ++fmt;
964 }
965 /* Check for escape sequences. */
966 if (*fmt == '-' || *fmt == ']') {
967 terminate_on[(int) *fmt] = 1;
968 ++fmt;
969 }
970 /* Check for ordinary characters and ranges. */
971 while (*fmt != '\0' && *fmt != ']') {
972 if (dash) {
973 for (char chr = *(fmt - 2); chr <= *fmt; ++chr) {
974 terminate_on[(int) chr] = 1;
975 }
976 dash = false;
977 } else if (*fmt == '-') {
978 dash = true;
979 } else {
980 terminate_on[(int) *fmt] = 1;
981 }
982 ++fmt;
983 }
984 /* Check for escape sequence. */
985 if (dash == true) {
986 terminate_on['-'] = 1;
987 }
988 /* Check whether the specifier was correctly terminated.*/
989 if (*fmt == '\0') {
990 /* Illegal format string. */
991 break;
992 } else {
993 ++fmt;
994 }
995 /* Inverse the scanset if necessary. */
996 if (not == false) {
997 for (int i = 0; i < 256; ++i) {
998 terminate_on[i] = terminate_on[i] ? 0 : 1;
999 }
1000 }
1001 }
1002
1003 char * buf = NULL;
1004 size_t buf_size = 0;
1005 char * cur = NULL;
1006 size_t alloc_step = 80; /* Buffer size gain during reallocation. */
1007 int my_buffer_idx = 0;
1008
1009 /* Retrieve the buffer into which popped characters
1010 * will be stored. */
1011 if (!assign_supress) {
1012 if (assign_alloc) {
1013 /* We must allocate our own buffer. */
1014 buf_size =
1015 width == -1 ? alloc_step : (size_t) width + term_size;
1016 buf = malloc(buf_size);
1017 if (!buf) {
1018 /* No memory. */
1019 break;
1020 }
1021 my_buffer_idx = next_unused_buffer_idx;
1022 ++next_unused_buffer_idx;
1023 buffers[my_buffer_idx] = buf;
1024 cur = buf;
1025 } else {
1026 /* Caller provided its buffer. */
1027 buf = va_arg(arg, char *);
1028 cur = buf;
1029 buf_size =
1030 width == -1 ? SIZE_MAX : (size_t) width + term_size;
1031 }
1032 }
1033
1034 /* Match the string. The next character is already popped. */
1035 while ((width == -1 || width > 0) && c != -1 && !terminate_on[c]) {
1036
1037 /* Check whether the buffer is still sufficiently large. */
1038 if (!assign_supress) {
1039 /* Always reserve space for the null terminator. */
1040 if (cur == buf + buf_size - term_size) {
1041 /* Buffer size must be increased. */
1042 buf = realloc(buf, buf_size + alloc_step);
1043 if (buf) {
1044 buffers[my_buffer_idx] = buf;
1045 cur = buf + buf_size - term_size;
1046 buf_size += alloc_step;
1047 } else {
1048 /* Break just from this tight loop. Errno will
1049 * be checked after it. */
1050 break;
1051 }
1052 }
1053 /* Store the input character. */
1054 *cur = c;
1055 }
1056
1057 width = width == -1 ? -1 : width - 1;
1058 ++cur;
1059 c = in->pop(in);
1060 }
1061 if (errno == ENOMEM) {
1062 /* No memory. */
1063 break;
1064 }
1065 if (c != -1) {
1066 /* There is still more input, so undo the last pop. */
1067 in->undo(in);
1068 }
1069
1070 /* Check for failures. */
1071 if (cur == buf) {
1072 /* Matching failure. Input failure was already checked
1073 * earlier. */
1074 matching_failure = true;
1075 if (!assign_supress && assign_alloc) {
1076 /* Roll back. */
1077 free(buf);
1078 buffers[my_buffer_idx] = NULL;
1079 --next_unused_buffer_idx;
1080 }
1081 break;
1082 }
1083
1084 /* Store the terminator. */
1085 if (!assign_supress && term_size > 0) {
1086 /* Space for the terminator was reserved. */
1087 *cur = '\0';
1088 }
1089
1090 /* Store the result if not already stored. */
1091 if (!assign_supress) {
1092 if (assign_alloc) {
1093 char **pbuf = va_arg(arg, char **);
1094 *pbuf = buf;
1095 }
1096 ++converted_cnt;
1097 }
1098
1099 converting = false;
1100 /* Format string pointer already incremented. */
1101 } else if (*fmt == 'n') {
1102 /* Report the number of consumed bytes so far. */
1103
1104 /* Sanity check. */
1105 bool sane =
1106 width == -1 &&
1107 length_mod == LMOD_NONE &&
1108 assign_alloc == false &&
1109 assign_supress == false;
1110
1111 if (sane) {
1112 int *pi = va_arg(arg, int *);
1113 *pi = in->consumed;
1114 } else {
1115 /* Illegal format string. */
1116 break;
1117 }
1118
1119 /* This shall not be counted as conversion. */
1120 converting = false;
1121 ++fmt;
1122 } else {
1123 /* Illegal format string. */
1124 break;
1125 }
1126
1127 } else {
1128
1129 /* Processing outside conversion specifier. Either skip white
1130 * spaces or match characters one by one. If conversion specifier
1131 * is detected, switch to coversion mode. */
1132 if (isspace(*fmt)) {
1133 /* Skip white spaces in the format string. */
1134 while (isspace(*fmt)) {
1135 ++fmt;
1136 }
1137 /* Skip white spaces in the input. */
1138 do {
1139 c = in->pop(in);
1140 } while (isspace(c));
1141 if (c != -1) {
1142 /* Input is not at EOF, so undo the last pop operation. */
1143 in->undo(in);
1144 }
1145 } else if (*fmt == '%' && *(fmt + 1) != '%') {
1146 /* Conversion specifier detected. Switch modes. */
1147 converting = true;
1148 /* Reset the conversion context. */
1149 assign_supress = false;
1150 assign_alloc = false;
1151 width = -1;
1152 length_mod = LMOD_NONE;
1153 int_conv_unsigned = false;
1154 int_conv_base = 0;
1155 ++fmt;
1156 } else {
1157 /* One by one matching. */
1158 if (*fmt == '%') {
1159 /* Escape sequence detected. */
1160 ++fmt;
1161 assert(*fmt == '%');
1162 }
1163 c = in->pop(in);
1164 if (c == -1) {
1165 /* Input failure. */
1166 break;
1167 } else if (c != *fmt) {
1168 /* Matching failure. */
1169 in->undo(in);
1170 matching_failure = true;
1171 break;
1172 } else {
1173 ++fmt;
1174 }
1175 }
1176
1177 }
1178
1179 }
1180
1181 in->release(in);
1182
1183 /* This somewhat complicated return value decision is required by POSIX. */
1184 int rc;
1185 if (matching_failure) {
1186 rc = converted_cnt;
1187 } else {
1188 if (errno == EOK) {
1189 rc = converted_cnt > 0 ? converted_cnt : EOF;
1190 } else {
1191 rc = EOF;
1192 }
1193 }
1194 if (rc == EOF) {
1195 /* Caller will not know how many arguments were successfully converted,
1196 * so the deallocation of buffers is our responsibility. */
1197 for (int i = 0; i < next_unused_buffer_idx; ++i) {
1198 free(buffers[i]);
1199 buffers[i] = NULL;
1200 }
1201 next_unused_buffer_idx = 0;
1202 }
1203 return rc;
1204}
1205
1206/**
1207 * Convert formatted input from the stream.
1208 *
1209 * @param stream Input stream.
1210 * @param format Format description.
1211 * @param arg Output items.
1212 * @return The number of converted output items or EOF on failure.
1213 */
1214int vfscanf(
1215 FILE *restrict stream, const char *restrict format, va_list arg)
1216{
1217 _input_provider provider = {
1218 { 0 }, 0, 0, NULL, 0, NULL, _PROV_CONSTRUCTED,
1219 _capture_stream, _pop_stream, _undo_stream,
1220 _borrow_cursor_universal, _return_cursor_stream, _release_stream
1221 };
1222 provider.source.stream = stream;
1223 return _internal_scanf(&provider, format, arg);
1224}
1225
1226/**
1227 * Convert formatted input from the string.
1228 *
1229 * @param s Input string.
1230 * @param format Format description.
1231 * @param arg Output items.
1232 * @return The number of converted output items or EOF on failure.
1233 */
1234int vsscanf(
1235 const char *restrict s, const char *restrict format, va_list arg)
1236{
1237 _input_provider provider = {
1238 { 0 }, 0, 0, NULL, 0, NULL, _PROV_CONSTRUCTED,
1239 _capture_string, _pop_string, _undo_string,
1240 _borrow_cursor_universal, _return_cursor_string, _release_string
1241 };
1242 provider.source.string = s;
1243 return _internal_scanf(&provider, format, arg);
1244}
1245
1246/** @}
1247 */
Note: See TracBrowser for help on using the repository browser.