init.c revision 1.122 1 /* $NetBSD: init.c,v 1.122 2021/03/25 19:11:18 rillig Exp $ */
2
3 /*
4 * Copyright (c) 1994, 1995 Jochen Pohl
5 * All Rights Reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. All advertising materials mentioning features or use of this software
16 * must display the following acknowledgement:
17 * This product includes software developed by Jochen Pohl for
18 * The NetBSD Project.
19 * 4. The name of the author may not be used to endorse or promote products
20 * derived from this software without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
23 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
24 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
25 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
26 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
27 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
31 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 */
33
34 #if HAVE_NBTOOL_CONFIG_H
35 #include "nbtool_config.h"
36 #endif
37
38 #include <sys/cdefs.h>
39 #if defined(__RCSID) && !defined(lint)
40 __RCSID("$NetBSD: init.c,v 1.122 2021/03/25 19:11:18 rillig Exp $");
41 #endif
42
43 #include <stdlib.h>
44 #include <string.h>
45
46 #include "lint1.h"
47
48
49 /*
50 * Initialization
51 *
52 * Handles initializations of global or local objects, like in:
53 *
54 * int number = 12345;
55 * int number_with_braces = { 12345 };
56 *
57 * int array_of_unknown_size[] = { 111, 222, 333 };
58 * int array_flat[2][2] = { 11, 12, 21, 22 };
59 * int array_nested[2][2] = { { 11, 12 }, { 21, 22 } };
60 *
61 * struct { int x, y; } point = { 3, 4 };
62 * struct { int x, y; } point = { .y = 4, .x = 3 };
63 *
64 * Any scalar expression in the initializer may be surrounded by arbitrarily
65 * many extra pairs of braces, like in the example 'number_with_braces' (C99
66 * 6.7.8p11).
67 *
68 * For multi-dimensional arrays, the inner braces may be omitted like in
69 * array_flat or spelled out like in array_nested.
70 *
71 * For the initializer, the grammar parser calls these functions:
72 *
73 * begin_initialization
74 * init_lbrace for each '{'
75 * designator_push_name for each '.member' before '='
76 * designator_push_subscript for each '[123]' before '='
77 * init_using_expr for each expression
78 * init_rbrace for each '}'
79 * end_initialization
80 *
81 * The state of the current initialization is stored in initstk, a stack of
82 * initstack_element, one element per type aggregate level.
83 * XXX: Or is that "one element per brace level"? C99 mandates in 6.7.8p17
84 * that "each brace-enclosed initializer list has an associated current
85 * object".
86 *
87 * Most of the time, the topmost level of initstk contains a scalar type, and
88 * its remaining count toggles between 1 and 0.
89 *
90 * See also:
91 * C99 6.7.8 "Initialization"
92 * d_c99_init.c for more examples
93 */
94
95
96 /*
97 * Type of stack which is used for initialization of aggregate types.
98 *
99 * XXX: Since C99, the initializers can be listed in arbitrary order by using
100 * designators to specify the sub-object to be initialized. The member names
101 * of non-leaf structs may thus appear repeatedly, as demonstrated in
102 * d_init_pop_member.c.
103 *
104 * See C99 6.7.8, which spans 6 pages full of tricky details and carefully
105 * selected examples.
106 */
107 typedef struct initstack_element {
108
109 /*
110 * The type to be initialized at this level.
111 *
112 * On the outermost element, this is always NULL since the outermost
113 * initializer-expression may be enclosed in an optional pair of
114 * braces, as of the current implementation.
115 *
116 * FIXME: This approach is wrong. It's not that the outermost
117 * initializer may be enclosed in additional braces, it's every scalar
118 * that may be enclosed in additional braces, as of C99 6.7.8p11.
119 *
120 * Everywhere else it is nonnull.
121 */
122 type_t *i_type;
123
124 /*
125 * The type that will be initialized at the next initialization level,
126 * usually enclosed by another pair of braces.
127 *
128 * For an array, it is the element type, but without 'const'.
129 *
130 * For a struct or union type, it is one of the member types, but
131 * without 'const'.
132 *
133 * The outermost stack element has no i_type but nevertheless has
134 * i_subt. For example, in 'int var = { 12345 }', initially there is
135 * an initstack_element with i_subt 'int'. When the '{' is processed,
136 * an element with i_type 'int' is pushed to the stack. When the
137 * corresponding '}' is processed, the inner element is popped again.
138 *
139 * During initialization, only the top 2 elements of the stack are
140 * looked at.
141 *
142 * XXX: Having i_subt here is the wrong approach, it should not be
143 * necessary at all; see i_type.
144 */
145 type_t *i_subt;
146
147 /*
148 * Whether this level of the initializer requires a '}' to be
149 * completed.
150 *
151 * Multidimensional arrays do not need a closing brace to complete
152 * an inner array; for example, { 1, 2, 3, 4 } is a valid initializer
153 * for 'int arr[2][2]'.
154 *
155 * TODO: Do structs containing structs need a closing brace?
156 * TODO: Do arrays of structs need a closing brace after each struct?
157 *
158 * XXX: Double-check whether this is the correct approach at all; see
159 * i_type.
160 */
161 bool i_brace: 1;
162
163 /* Whether i_type is an array of unknown size. */
164 bool i_array_of_unknown_size: 1;
165
166 /*
167 * XXX: This feels wrong. Whether or not there has been a named
168 * initializer (called 'designation' since C99) should not matter at
169 * all. Even after an initializer with designation, counting of the
170 * remaining elements continues, see C99 6.7.8p17.
171 */
172 bool i_seen_named_member: 1;
173
174 /*
175 * For structs, the next member to be initialized by an initializer
176 * without an optional designator.
177 *
178 * FIXME: The name is wrong. C99 defines the "current object" as
179 * being the subobject being initialized, while this is rather the
180 * next member. This only makes sense for structs anyway and should
181 * be amended by i_next_subscript for arrays. See C99 6.7.8p17 and
182 * footnote 128 for unions.
183 */
184 sym_t *i_current_object;
185
186 /*
187 * The number of remaining elements to be used by expressions without
188 * designator.
189 *
190 * This says nothing about which members have been initialized or not
191 * since starting with C99, members may be initialized in arbitrary
192 * order by using designators.
193 *
194 * For an array of unknown size, this is always 0 and thus irrelevant.
195 *
196 * XXX: for scalars?
197 * XXX: for structs?
198 * XXX: for unions?
199 * XXX: for arrays?
200 *
201 * XXX: Having the count of remaining objects should not be necessary.
202 * It is probably clearer to use i_next_member and i_next_subscript
203 * (as suggested in i_current_object) for this purpose.
204 */
205 int i_remaining;
206
207 /*
208 * The initialization state of the enclosing data structure
209 * (struct, union, array).
210 *
211 * XXX: Or for a scalar, for the top-level element, or for expressions
212 * in redundant braces such as '{{{{ 0 }}}}' (not yet implemented as
213 * of 2021-03-25).
214 */
215 struct initstack_element *i_enclosing;
216
217 } initstack_element;
218
219 /*
220 * The names for a nested C99 initialization designator, in a circular list.
221 *
222 * Example:
223 * struct stat st = {
224 * .st_size = 123,
225 * .st_mtim.tv_sec = 45,
226 * .st_mtim.tv_nsec
227 * };
228 *
229 * During initialization, this list first contains ["st_size"], then
230 * ["st_mtim", "tv_sec"], then ["st_mtim", "tv_nsec"].
231 */
232 typedef struct namlist {
233 const char *n_name;
234 struct namlist *n_prev;
235 struct namlist *n_next;
236 } namlist_t;
237
238 struct initialization {
239 /*
240 * is set as soon as a fatal error occurred in the initialization.
241 * The effect is that the rest of the initialization is ignored
242 * (parsed by yacc, expression trees built, but no initialization
243 * takes place).
244 */
245 bool initerr;
246
247 /* Pointer to the symbol which is to be initialized. */
248 sym_t *initsym;
249
250 /* Points to the top element of the initialization stack. */
251 initstack_element *initstk;
252
253 /* Points to a c9x named member. */
254 namlist_t *namedmem;
255
256 struct initialization *next;
257 };
258
259 static struct initialization *init;
260
261
262 /* XXX: unnecessary prototype since it is not recursive */
263 static bool init_array_using_string(tnode_t *);
264
265
266 /* TODO: replace the following functions with current_init */
267
268 bool *
269 current_initerr(void)
270 {
271 lint_assert(init != NULL);
272 return &init->initerr;
273 }
274
275 sym_t **
276 current_initsym(void)
277 {
278 lint_assert(init != NULL);
279 return &init->initsym;
280 }
281
282 static namlist_t **
283 current_namedmem(void)
284 {
285 lint_assert(init != NULL);
286 return &init->namedmem;
287 }
288
289 static initstack_element **
290 current_initstk(void)
291 {
292 lint_assert(init != NULL);
293 return &init->initstk;
294 }
295
296 static void
297 free_initialization(struct initialization *in)
298 {
299 initstack_element *el, *next;
300
301 for (el = in->initstk; el != NULL; el = next) {
302 next = el->i_enclosing;
303 free(el);
304 }
305
306 free(in);
307 }
308
309 #define initerr (*current_initerr())
310 #define initsym (*current_initsym())
311 #define initstk (*current_initstk())
312
313 #ifndef DEBUG
314
315 #define debug_printf(fmt, ...) do { } while (false)
316 #define debug_indent() do { } while (false)
317 #define debug_enter(a) do { } while (false)
318 #define debug_step(fmt, ...) do { } while (false)
319 #define debug_leave(a) do { } while (false)
320 #define debug_named_member() do { } while (false)
321 #define debug_initstack_element(elem) do { } while (false)
322 #define debug_initstack() do { } while (false)
323
324 #else
325
326 static int debug_ind = 0;
327
328 static void __printflike(1, 2)
329 debug_printf(const char *fmt, ...)
330 {
331 va_list va;
332
333 va_start(va, fmt);
334 vfprintf(stdout, fmt, va);
335 va_end(va);
336 }
337
338 static void
339 debug_indent(void)
340 {
341 debug_printf("%*s", 2 * debug_ind, "");
342 }
343
344 static void
345 debug_enter(const char *func)
346 {
347 printf("%*s+ %s\n", 2 * debug_ind++, "", func);
348 }
349
350 static void __printflike(1, 2)
351 debug_step(const char *fmt, ...)
352 {
353 va_list va;
354
355 printf("%*s", 2 * debug_ind, "");
356 va_start(va, fmt);
357 vfprintf(stdout, fmt, va);
358 va_end(va);
359 printf("\n");
360 }
361
362 static void
363 debug_leave(const char *func)
364 {
365 printf("%*s- %s\n", 2 * --debug_ind, "", func);
366 }
367
368 static void
369 debug_named_member(void)
370 {
371 namlist_t *head = *current_namedmem(), *name;
372
373 if (head == NULL)
374 return;
375 debug_indent();
376 debug_printf("named member: ");
377 name = head;
378 do {
379 debug_printf(".%s", name->n_name);
380 name = name->n_next;
381 } while (name != head);
382 debug_printf("\n");
383 }
384
385 /*
386 * TODO: try whether a single-line output is more readable
387 *
388 * TODO: only log the top of the stack after each modifying operation
389 *
390 * TODO: wrap all write accesses to initstack_element in setter functions
391 */
392 static void
393 debug_initstack_element(const initstack_element *elem)
394 {
395 if (elem->i_type != NULL)
396 debug_printf("type '%s'", type_name(elem->i_type));
397 if (elem->i_type != NULL && elem->i_subt != NULL)
398 debug_printf(", ");
399 if (elem->i_subt != NULL)
400 debug_printf("subtype '%s'", type_name(elem->i_subt));
401
402 if (elem->i_brace)
403 debug_printf(", needs closing brace");
404 if (elem->i_array_of_unknown_size)
405 debug_printf(", array of unknown size");
406 if (elem->i_seen_named_member)
407 debug_printf(", seen named member");
408
409 const type_t *eff_type = elem->i_type != NULL
410 ? elem->i_type : elem->i_subt;
411 if (eff_type->t_tspec == STRUCT && elem->i_current_object != NULL)
412 debug_printf(", current object '%s'",
413 elem->i_current_object->s_name);
414
415 debug_printf(", remaining %d\n", elem->i_remaining);
416 }
417
418 /*
419 * TODO: only call debug_initstack after each push/pop.
420 */
421 static void
422 debug_initstack(void)
423 {
424 if (initstk == NULL) {
425 debug_step("initstk is empty");
426 return;
427 }
428
429 size_t i = 0;
430 for (const initstack_element *elem = initstk;
431 elem != NULL; elem = elem->i_enclosing) {
432 debug_indent();
433 debug_printf("initstk[%zu]: ", i);
434 debug_initstack_element(elem);
435 i++;
436 }
437 }
438
439 #define debug_enter() debug_enter(__func__)
440 #define debug_leave() debug_leave(__func__)
441
442 #endif
443
444
445 void
446 begin_initialization(sym_t *sym)
447 {
448 struct initialization *curr_init;
449
450 debug_step("begin initialization of '%s'", type_name(sym->s_type));
451 curr_init = xcalloc(1, sizeof *curr_init);
452 curr_init->next = init;
453 init = curr_init;
454 initsym = sym;
455 }
456
457 void
458 end_initialization(void)
459 {
460 struct initialization *curr_init;
461
462 curr_init = init;
463 init = init->next;
464 free_initialization(curr_init);
465 debug_step("end initialization");
466 }
467
468 void
469 designator_push_name(sbuf_t *sb)
470 {
471 namlist_t *designation = *current_namedmem();
472 namlist_t *nam = xcalloc(1, sizeof (namlist_t));
473 nam->n_name = sb->sb_name;
474
475 if (designation == NULL) {
476 /*
477 * XXX: Why is this a circular list?
478 * XXX: Why is this a doubly-linked list?
479 * A simple queue should suffice.
480 */
481 nam->n_prev = nam->n_next = nam;
482 *current_namedmem() = nam;
483 } else {
484 designation->n_prev->n_next = nam;
485 nam->n_prev = designation->n_prev;
486 nam->n_next = designation;
487 designation->n_prev = nam;
488 }
489
490 debug_named_member();
491 }
492
493 /*
494 * A sub-object of an array is initialized using a designator. This does not
495 * have to be an array element directly, it can also be used to initialize
496 * only a sub-object of the array element.
497 *
498 * C99 example: struct { int member[4]; } var = { [2] = 12345 };
499 *
500 * GNU example: struct { int member[4]; } var = { [1 ... 3] = 12345 };
501 *
502 * TODO: test the following initialization with an outer and an inner type:
503 *
504 * .deeply[0].nested = {
505 * .deeply[1].nested = {
506 * 12345,
507 * },
508 * }
509 */
510 void
511 designator_push_subscript(range_t range)
512 {
513 debug_enter();
514 debug_step("subscript range is %zu ... %zu", range.lo, range.hi);
515 debug_initstack();
516 debug_leave();
517 }
518
519 /* TODO: add support for array subscripts, not only named members */
520 static void
521 designator_shift_name(void)
522 {
523 namlist_t *designation = *current_namedmem();
524
525 if (designation->n_next == designation) {
526 free(designation);
527 *current_namedmem() = NULL;
528 } else {
529 namlist_t *nam = designation;
530 *current_namedmem() = designation->n_next;
531 nam->n_prev->n_next = nam->n_next;
532 nam->n_next->n_prev = nam->n_prev;
533 free(nam);
534 }
535
536 debug_named_member();
537 }
538
539 /*
540 * Initialize the initialization stack by putting an entry for the object
541 * which is to be initialized on it.
542 *
543 * TODO: merge into begin_initialization
544 */
545 void
546 initstack_init(void)
547 {
548 initstack_element *istk;
549
550 if (initerr)
551 return;
552
553 /* TODO: merge into init_using_expr */
554 while (*current_namedmem() != NULL)
555 designator_shift_name();
556
557 debug_enter();
558
559 /*
560 * If the type which is to be initialized is an incomplete array,
561 * it must be duplicated.
562 */
563 if (initsym->s_type->t_tspec == ARRAY && is_incomplete(initsym->s_type))
564 initsym->s_type = duptyp(initsym->s_type);
565 /* TODO: does 'duptyp' create a memory leak? */
566
567 istk = initstk = xcalloc(1, sizeof (initstack_element));
568 istk->i_subt = initsym->s_type;
569 istk->i_remaining = 1;
570
571 debug_initstack();
572 debug_leave();
573 }
574
575 /* TODO: document me */
576 static void
577 initstack_pop_item_named_member(void)
578 {
579 initstack_element *istk = initstk;
580 sym_t *m;
581
582 /*
583 * TODO: fix wording of the debug message; this doesn't seem to be
584 * related to initializing the named member.
585 */
586 debug_step("initializing named member '%s'",
587 (*current_namedmem())->n_name);
588
589 if (istk->i_type->t_tspec != STRUCT &&
590 istk->i_type->t_tspec != UNION) {
591 /* syntax error '%s' */
592 error(249, "named member must only be used with struct/union");
593 initerr = true;
594 return;
595 }
596
597 for (m = istk->i_type->t_str->sou_first_member;
598 m != NULL; m = m->s_next) {
599
600 if (m->s_bitfield && m->s_name == unnamed)
601 continue;
602
603 if (strcmp(m->s_name, (*current_namedmem())->n_name) == 0) {
604 debug_step("found matching member");
605 istk->i_subt = m->s_type;
606 /* XXX: why ++? */
607 istk->i_remaining++;
608 /* XXX: why is i_seen_named_member not set? */
609 designator_shift_name();
610 return;
611 }
612 }
613
614 /* undefined struct/union member: %s */
615 error(101, (*current_namedmem())->n_name);
616
617 designator_shift_name();
618 istk->i_seen_named_member = true;
619 }
620
621 /* TODO: think of a better name than 'pop' */
622 static void
623 initstack_pop_item_unnamed(void)
624 {
625 initstack_element *istk = initstk;
626 sym_t *m;
627
628 /*
629 * If the removed element was a structure member, we must go
630 * to the next structure member.
631 */
632 if (istk->i_remaining > 0 && istk->i_type->t_tspec == STRUCT &&
633 !istk->i_seen_named_member) {
634 do {
635 m = istk->i_current_object =
636 istk->i_current_object->s_next;
637 /* XXX: can this assertion be made to fail? */
638 lint_assert(m != NULL);
639 debug_step("pop %s", m->s_name);
640 } while (m->s_bitfield && m->s_name == unnamed);
641 /* XXX: duplicate code for skipping unnamed bit-fields */
642 istk->i_subt = m->s_type;
643 }
644 }
645
646 /* TODO: think of a better name than 'pop' */
647 static void
648 initstack_pop_item(void)
649 {
650 initstack_element *istk;
651
652 debug_enter();
653
654 istk = initstk;
655 debug_indent();
656 debug_printf("popping: ");
657 debug_initstack_element(istk);
658
659 initstk = istk->i_enclosing;
660 free(istk);
661 istk = initstk;
662 lint_assert(istk != NULL);
663
664 istk->i_remaining--;
665 lint_assert(istk->i_remaining >= 0);
666 debug_step("%d elements remaining", istk->i_remaining);
667
668 if (*current_namedmem() != NULL)
669 initstack_pop_item_named_member();
670 else
671 initstack_pop_item_unnamed();
672
673 debug_initstack();
674 debug_leave();
675 }
676
677 /*
678 * Take all entries, including the first which requires a closing brace,
679 * from the stack.
680 */
681 static void
682 initstack_pop_brace(void)
683 {
684 bool brace;
685
686 debug_enter();
687 debug_initstack();
688 do {
689 brace = initstk->i_brace;
690 /* TODO: improve wording of the debug message */
691 debug_step("loop brace=%d", brace);
692 initstack_pop_item();
693 } while (!brace);
694 debug_initstack();
695 debug_leave();
696 }
697
698 /*
699 * Take all entries which cannot be used for further initializers from the
700 * stack, but do this only if they do not require a closing brace.
701 */
702 /* TODO: think of a better name than 'pop' */
703 static void
704 initstack_pop_nobrace(void)
705 {
706
707 debug_enter();
708 while (!initstk->i_brace && initstk->i_remaining == 0 &&
709 !initstk->i_array_of_unknown_size)
710 initstack_pop_item();
711 debug_leave();
712 }
713
714 /* Extend an array of unknown size by one element */
715 static void
716 extend_if_array_of_unknown_size(void)
717 {
718 initstack_element *istk = initstk;
719
720 if (istk->i_remaining != 0)
721 return;
722
723 /*
724 * The only place where an incomplete array may appear is at the
725 * outermost aggregate level of the object to be initialized.
726 */
727 lint_assert(istk->i_enclosing->i_enclosing == NULL);
728 lint_assert(istk->i_type->t_tspec == ARRAY);
729
730 debug_step("extending array of unknown size '%s'",
731 type_name(istk->i_type));
732 istk->i_remaining = 1;
733 istk->i_type->t_dim++;
734 setcomplete(istk->i_type, true);
735
736 debug_step("extended type is '%s'", type_name(istk->i_type));
737 }
738
739 /* TODO: document me */
740 /* TODO: think of a better name than 'push' */
741 static void
742 initstack_push_array(void)
743 {
744 initstack_element *const istk = initstk;
745
746 if (istk->i_enclosing->i_seen_named_member) {
747 istk->i_brace = true;
748 debug_step("ARRAY brace=%d, namedmem=%d",
749 istk->i_brace, istk->i_enclosing->i_seen_named_member);
750 }
751
752 if (is_incomplete(istk->i_type) &&
753 istk->i_enclosing->i_enclosing != NULL) {
754 /* initialization of an incomplete type */
755 error(175);
756 initerr = true;
757 return;
758 }
759
760 istk->i_subt = istk->i_type->t_subt;
761 istk->i_array_of_unknown_size = is_incomplete(istk->i_type);
762 istk->i_remaining = istk->i_type->t_dim;
763 debug_named_member();
764 debug_step("type '%s' remaining %d",
765 type_name(istk->i_type), istk->i_remaining);
766 }
767
768 /* TODO: document me */
769 /* TODO: think of a better name than 'push' */
770 static bool
771 initstack_push_struct_or_union(void)
772 {
773 /*
774 * TODO: remove unnecessary 'const' for variables in functions that
775 * fit on a single screen. Keep it for larger functions.
776 */
777 initstack_element *const istk = initstk;
778 int cnt;
779 sym_t *m;
780
781 if (is_incomplete(istk->i_type)) {
782 /* initialization of an incomplete type */
783 error(175);
784 initerr = true;
785 return false;
786 }
787
788 cnt = 0;
789 debug_named_member();
790 debug_step("lookup for '%s'%s",
791 type_name(istk->i_type),
792 istk->i_seen_named_member ? ", seen named member" : "");
793
794 for (m = istk->i_type->t_str->sou_first_member;
795 m != NULL; m = m->s_next) {
796 if (m->s_bitfield && m->s_name == unnamed)
797 continue;
798 /*
799 * TODO: split into separate functions:
800 *
801 * look_up_array_next
802 * look_up_array_designator
803 * look_up_struct_next
804 * look_up_struct_designator
805 */
806 if (*current_namedmem() != NULL) {
807 /* XXX: this log entry looks unnecessarily verbose */
808 debug_step("have member '%s', want member '%s'",
809 m->s_name, (*current_namedmem())->n_name);
810 if (strcmp(m->s_name, (*current_namedmem())->n_name) ==
811 0) {
812 cnt++;
813 break;
814 } else
815 continue;
816 }
817 if (++cnt == 1) {
818 istk->i_current_object = m;
819 istk->i_subt = m->s_type;
820 }
821 }
822
823 if (*current_namedmem() != NULL) {
824 if (m == NULL) {
825 debug_step("pop struct");
826 return true;
827 }
828 istk->i_current_object = m;
829 istk->i_subt = m->s_type;
830 istk->i_seen_named_member = true;
831 debug_step("named member '%s'", (*current_namedmem())->n_name);
832 designator_shift_name();
833 cnt = istk->i_type->t_tspec == STRUCT ? 2 : 1;
834 }
835 istk->i_brace = true;
836 debug_step("unnamed element with type '%s'%s",
837 type_name(istk->i_type != NULL ? istk->i_type : istk->i_subt),
838 istk->i_brace ? ", needs closing brace" : "");
839 if (cnt == 0) {
840 /* cannot init. struct/union with no named member */
841 error(179);
842 initerr = true;
843 return false;
844 }
845 istk->i_remaining = istk->i_type->t_tspec == STRUCT ? cnt : 1;
846 return false;
847 }
848
849 /* TODO: document me */
850 /* TODO: think of a better name than 'push' */
851 static void
852 initstack_push(void)
853 {
854 initstack_element *istk, *inxt;
855
856 debug_enter();
857
858 extend_if_array_of_unknown_size();
859
860 istk = initstk;
861 lint_assert(istk->i_remaining > 0);
862 lint_assert(istk->i_type == NULL || !is_scalar(istk->i_type->t_tspec));
863
864 initstk = xcalloc(1, sizeof (initstack_element));
865 initstk->i_enclosing = istk;
866 initstk->i_type = istk->i_subt;
867 lint_assert(initstk->i_type->t_tspec != FUNC);
868
869 again:
870 istk = initstk;
871
872 debug_step("expecting type '%s'", type_name(istk->i_type));
873 lint_assert(istk->i_type != NULL);
874 switch (istk->i_type->t_tspec) {
875 case ARRAY:
876 if (*current_namedmem() != NULL) {
877 debug_step("pop array namedmem=%s brace=%d",
878 (*current_namedmem())->n_name, istk->i_brace);
879 goto pop;
880 }
881
882 initstack_push_array();
883 break;
884
885 case UNION:
886 if (tflag)
887 /* initialization of union is illegal in trad. C */
888 warning(238);
889 /* FALLTHROUGH */
890 case STRUCT:
891 if (initstack_push_struct_or_union())
892 goto pop;
893 break;
894 default:
895 if (*current_namedmem() != NULL) {
896 debug_step("pop scalar");
897 pop:
898 /* TODO: extract this into end_initializer_level */
899 inxt = initstk->i_enclosing;
900 free(istk);
901 initstk = inxt;
902 goto again;
903 }
904 /* The initialization stack now expects a single scalar. */
905 istk->i_remaining = 1;
906 break;
907 }
908
909 debug_initstack();
910 debug_leave();
911 }
912
913 static void
914 check_too_many_initializers(void)
915 {
916
917 const initstack_element *istk = initstk;
918 if (istk->i_remaining > 0)
919 return;
920 /*
921 * FIXME: even with named members, there can be too many initializers
922 */
923 if (istk->i_array_of_unknown_size || istk->i_seen_named_member)
924 return;
925
926 tspec_t t = istk->i_type->t_tspec;
927 if (t == ARRAY) {
928 /* too many array initializers, expected %d */
929 error(173, istk->i_type->t_dim);
930 } else if (t == STRUCT || t == UNION) {
931 /* too many struct/union initializers */
932 error(172);
933 } else {
934 /* too many initializers */
935 error(174);
936 }
937 initerr = true;
938 }
939
940 /*
941 * Process a '{' in an initializer by starting the initialization of the
942 * nested data structure, with i_type being the i_subt of the outer
943 * initialization level.
944 */
945 static void
946 initstack_next_brace(void)
947 {
948
949 debug_enter();
950 debug_initstack();
951
952 if (initstk->i_type != NULL && is_scalar(initstk->i_type->t_tspec)) {
953 /* invalid initializer type %s */
954 error(176, type_name(initstk->i_type));
955 initerr = true;
956 }
957 if (!initerr)
958 check_too_many_initializers();
959 if (!initerr)
960 initstack_push();
961 if (!initerr) {
962 initstk->i_brace = true;
963 debug_named_member();
964 debug_step("expecting type '%s'",
965 type_name(initstk->i_type != NULL ? initstk->i_type
966 : initstk->i_subt));
967 }
968
969 debug_initstack();
970 debug_leave();
971 }
972
973 /* TODO: document me, or think of a better name */
974 static void
975 initstack_next_nobrace(tnode_t *tn)
976 {
977 debug_enter();
978
979 if (initstk->i_type == NULL && !is_scalar(initstk->i_subt->t_tspec)) {
980 /* {}-enclosed initializer required */
981 error(181);
982 /* XXX: maybe set initerr here */
983 }
984
985 if (!initerr)
986 check_too_many_initializers();
987
988 while (!initerr) {
989 initstack_element *istk = initstk;
990
991 if (tn->tn_type->t_tspec == STRUCT &&
992 istk->i_type == tn->tn_type &&
993 istk->i_enclosing != NULL &&
994 istk->i_enclosing->i_enclosing != NULL) {
995 istk->i_brace = false;
996 istk->i_remaining = 1; /* the struct itself */
997 break;
998 }
999
1000 if ((istk->i_type != NULL && is_scalar(istk->i_type->t_tspec)))
1001 break;
1002 initstack_push();
1003 }
1004
1005 debug_initstack();
1006 debug_leave();
1007 }
1008
1009 /* TODO: document me */
1010 void
1011 init_lbrace(void)
1012 {
1013 if (initerr)
1014 return;
1015
1016 debug_enter();
1017 debug_initstack();
1018
1019 if ((initsym->s_scl == AUTO || initsym->s_scl == REG) &&
1020 initstk->i_enclosing == NULL) {
1021 if (tflag && !is_scalar(initstk->i_subt->t_tspec))
1022 /* no automatic aggregate initialization in trad. C */
1023 warning(188);
1024 }
1025
1026 /*
1027 * Remove all entries which cannot be used for further initializers
1028 * and do not expect a closing brace.
1029 */
1030 initstack_pop_nobrace();
1031
1032 initstack_next_brace();
1033
1034 debug_initstack();
1035 debug_leave();
1036 }
1037
1038 /*
1039 * Process a '}' in an initializer by finishing the current level of the
1040 * initialization stack.
1041 */
1042 void
1043 init_rbrace(void)
1044 {
1045 if (initerr)
1046 return;
1047
1048 debug_enter();
1049 initstack_pop_brace();
1050 debug_leave();
1051 }
1052
1053 /* In traditional C, bit-fields can be initialized only by integer constants. */
1054 static void
1055 check_bit_field_init(const tnode_t *ln, tspec_t lt, tspec_t rt)
1056 {
1057 if (tflag &&
1058 is_integer(lt) &&
1059 ln->tn_type->t_bitfield &&
1060 !is_integer(rt)) {
1061 /* bit-field initialization is illegal in traditional C */
1062 warning(186);
1063 }
1064 }
1065
1066 static void
1067 check_non_constant_initializer(const tnode_t *tn, scl_t sclass)
1068 {
1069 /* TODO: rename CON to CONSTANT to avoid ambiguity with CONVERT */
1070 if (tn == NULL || tn->tn_op == CON)
1071 return;
1072
1073 sym_t *sym;
1074 ptrdiff_t offs;
1075 if (constant_addr(tn, &sym, &offs))
1076 return;
1077
1078 if (sclass == AUTO || sclass == REG) {
1079 /* non-constant initializer */
1080 c99ism(177);
1081 } else {
1082 /* non-constant initializer */
1083 error(177);
1084 }
1085 }
1086
1087 /*
1088 * Initialize a non-array object with automatic storage duration and only a
1089 * single initializer expression without braces by delegating to ASSIGN.
1090 */
1091 static bool
1092 init_using_assign(tnode_t *rn)
1093 {
1094 tnode_t *ln, *tn;
1095
1096 if (initsym->s_type->t_tspec == ARRAY)
1097 return false;
1098 if (initstk->i_enclosing != NULL)
1099 return false;
1100
1101 debug_step("handing over to ASSIGN");
1102
1103 ln = new_name_node(initsym, 0);
1104 ln->tn_type = tduptyp(ln->tn_type);
1105 ln->tn_type->t_const = false;
1106
1107 tn = build(ASSIGN, ln, rn);
1108 expr(tn, false, false, false, false);
1109
1110 /* XXX: why not clean up the initstack here already? */
1111 return true;
1112 }
1113
1114 static void
1115 check_init_expr(tnode_t *tn, scl_t sclass)
1116 {
1117 tnode_t *ln;
1118 tspec_t lt, rt;
1119 struct mbl *tmem;
1120
1121 /* Create a temporary node for the left side. */
1122 ln = tgetblk(sizeof (tnode_t));
1123 ln->tn_op = NAME;
1124 ln->tn_type = tduptyp(initstk->i_type);
1125 ln->tn_type->t_const = false;
1126 ln->tn_lvalue = true;
1127 ln->tn_sym = initsym; /* better than nothing */
1128
1129 tn = cconv(tn);
1130
1131 lt = ln->tn_type->t_tspec;
1132 rt = tn->tn_type->t_tspec;
1133
1134 debug_step("typeok '%s', '%s'",
1135 type_name(ln->tn_type), type_name(tn->tn_type));
1136 if (!typeok(INIT, 0, ln, tn))
1137 return;
1138
1139 /*
1140 * Preserve the tree memory. This is necessary because otherwise
1141 * expr() would free it.
1142 */
1143 tmem = tsave();
1144 expr(tn, true, false, true, false);
1145 trestor(tmem);
1146
1147 check_bit_field_init(ln, lt, rt);
1148
1149 /*
1150 * XXX: Is it correct to do this conversion _after_ the typeok above?
1151 */
1152 if (lt != rt || (initstk->i_type->t_bitfield && tn->tn_op == CON))
1153 tn = convert(INIT, 0, initstk->i_type, tn);
1154
1155 check_non_constant_initializer(tn, sclass);
1156 }
1157
1158 void
1159 init_using_expr(tnode_t *tn)
1160 {
1161 scl_t sclass;
1162
1163 debug_enter();
1164 debug_initstack();
1165 debug_named_member();
1166 debug_step("expr:");
1167 debug_node(tn, debug_ind + 1);
1168
1169 if (initerr || tn == NULL)
1170 goto done;
1171
1172 sclass = initsym->s_scl;
1173 if ((sclass == AUTO || sclass == REG) && init_using_assign(tn))
1174 goto done;
1175
1176 initstack_pop_nobrace();
1177
1178 if (init_array_using_string(tn)) {
1179 debug_step("after initializing the string:");
1180 /* XXX: why not clean up the initstack here already? */
1181 goto done_initstack;
1182 }
1183
1184 initstack_next_nobrace(tn);
1185 if (initerr || tn == NULL)
1186 goto done_initstack;
1187
1188 initstk->i_remaining--;
1189 debug_step("%d elements remaining", initstk->i_remaining);
1190
1191 check_init_expr(tn, sclass);
1192
1193 done_initstack:
1194 debug_initstack();
1195 done:
1196 debug_leave();
1197 }
1198
1199
1200 /* Initialize a character array or wchar_t array with a string literal. */
1201 static bool
1202 init_array_using_string(tnode_t *tn)
1203 {
1204 tspec_t t;
1205 initstack_element *istk;
1206 int len;
1207 strg_t *strg;
1208
1209 if (tn->tn_op != STRING)
1210 return false;
1211
1212 debug_enter();
1213 debug_initstack();
1214
1215 istk = initstk;
1216 strg = tn->tn_string;
1217
1218 /*
1219 * Check if we have an array type which can be initialized by
1220 * the string.
1221 */
1222 if (istk->i_subt != NULL && istk->i_subt->t_tspec == ARRAY) {
1223 debug_step("subt array");
1224 t = istk->i_subt->t_subt->t_tspec;
1225 if (!((strg->st_tspec == CHAR &&
1226 (t == CHAR || t == UCHAR || t == SCHAR)) ||
1227 (strg->st_tspec == WCHAR && t == WCHAR))) {
1228 debug_leave();
1229 return false;
1230 }
1231 /* XXX: duplicate code, see below */
1232
1233 /* Put the array at top of stack */
1234 initstack_push();
1235 istk = initstk;
1236
1237
1238 /* TODO: what if both i_type and i_subt are ARRAY? */
1239
1240 } else if (istk->i_type != NULL && istk->i_type->t_tspec == ARRAY) {
1241 debug_step("type array");
1242 t = istk->i_type->t_subt->t_tspec;
1243 if (!((strg->st_tspec == CHAR &&
1244 (t == CHAR || t == UCHAR || t == SCHAR)) ||
1245 (strg->st_tspec == WCHAR && t == WCHAR))) {
1246 debug_leave();
1247 return false;
1248 }
1249 /* XXX: duplicate code, see above */
1250
1251 /*
1252 * TODO: is this really not needed in the branch above this
1253 * one?
1254 */
1255 /*
1256 * If the array is already partly initialized, we are
1257 * wrong here.
1258 */
1259 if (istk->i_remaining != istk->i_type->t_dim) {
1260 debug_leave();
1261 return false;
1262 }
1263 } else {
1264 debug_leave();
1265 return false;
1266 }
1267
1268 /* Get length without trailing NUL character. */
1269 len = strg->st_len;
1270
1271 if (istk->i_array_of_unknown_size) {
1272 istk->i_array_of_unknown_size = false;
1273 istk->i_type->t_dim = len + 1;
1274 setcomplete(istk->i_type, true);
1275 } else {
1276 /*
1277 * TODO: check for buffer overflow in the object to be
1278 * initialized
1279 */
1280 /* XXX: double-check for off-by-one error */
1281 if (istk->i_type->t_dim < len) {
1282 /* non-null byte ignored in string initializer */
1283 warning(187);
1284 }
1285
1286 /*
1287 * TODO: C99 6.7.8p14 allows a string literal to be enclosed
1288 * in optional redundant braces, just like scalars. Add tests
1289 * for this.
1290 */
1291 }
1292
1293 /* In every case the array is initialized completely. */
1294 istk->i_remaining = 0;
1295
1296 debug_initstack();
1297 debug_leave();
1298 return true;
1299 }
1300