1 /* CPP Library. (Directive handling.)
2    Copyright (C) 1986-2018 Free Software Foundation, Inc.
3    Contributed by Per Bothner, 1994-95.
4    Based on CCCP program by Paul Rubin, June 1986
5    Adapted to ANSI C, Richard Stallman, Jan 1987
6 
7 This program is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the
9 Free Software Foundation; either version 3, or (at your option) any
10 later version.
11 
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16 
17 You should have received a copy of the GNU General Public License
18 along with this program; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20 
21 #include "config.h"
22 #include "system.h"
23 #include "cpplib.h"
24 #include "internal.h"
25 #include "mkdeps.h"
26 #include "obstack.h"
27 
28 /* Stack of conditionals currently in progress
29    (including both successful and failing conditionals).  */
30 struct if_stack
31 {
32   struct if_stack *next;
33   source_location line;		/* Line where condition started.  */
34   const cpp_hashnode *mi_cmacro;/* macro name for #ifndef around entire file */
35   bool skip_elses;		/* Can future #else / #elif be skipped?  */
36   bool was_skipping;		/* If were skipping on entry.  */
37   int type;			/* Most recent conditional for diagnostics.  */
38 };
39 
40 /* Contains a registered pragma or pragma namespace.  */
41 typedef void (*pragma_cb) (cpp_reader *);
42 struct pragma_entry
43 {
44   struct pragma_entry *next;
45   const cpp_hashnode *pragma;	/* Name and length.  */
46   bool is_nspace;
47   bool is_internal;
48   bool is_deferred;
49   bool allow_expansion;
50   union {
51     pragma_cb handler;
52     struct pragma_entry *space;
53     unsigned int ident;
54   } u;
55 };
56 
57 /* Values for the origin field of struct directive.  KANDR directives
58    come from traditional (K&R) C.  STDC89 directives come from the
59    1989 C standard.  EXTENSION directives are extensions.  */
60 #define KANDR		0
61 #define STDC89		1
62 #define EXTENSION	2
63 
64 /* Values for the flags field of struct directive.  COND indicates a
65    conditional; IF_COND an opening conditional.  INCL means to treat
66    "..." and <...> as q-char and h-char sequences respectively.  IN_I
67    means this directive should be handled even if -fpreprocessed is in
68    effect (these are the directives with callback hooks).
69 
70    EXPAND is set on directives that are always macro-expanded.  */
71 #define COND		(1 << 0)
72 #define IF_COND		(1 << 1)
73 #define INCL		(1 << 2)
74 #define IN_I		(1 << 3)
75 #define EXPAND		(1 << 4)
76 #define DEPRECATED	(1 << 5)
77 
78 /* Defines one #-directive, including how to handle it.  */
79 typedef void (*directive_handler) (cpp_reader *);
80 typedef struct directive directive;
81 struct directive
82 {
83   directive_handler handler;	/* Function to handle directive.  */
84   const uchar *name;		/* Name of directive.  */
85   unsigned short length;	/* Length of name.  */
86   unsigned char origin;		/* Origin of directive.  */
87   unsigned char flags;	        /* Flags describing this directive.  */
88 };
89 
90 /* Forward declarations.  */
91 
92 static void skip_rest_of_line (cpp_reader *);
93 static void check_eol (cpp_reader *, bool);
94 static void start_directive (cpp_reader *);
95 static void prepare_directive_trad (cpp_reader *);
96 static void end_directive (cpp_reader *, int);
97 static void directive_diagnostics (cpp_reader *, const directive *, int);
98 static void run_directive (cpp_reader *, int, const char *, size_t);
99 static char *glue_header_name (cpp_reader *);
100 static const char *parse_include (cpp_reader *, int *, const cpp_token ***,
101 				  source_location *);
102 static void push_conditional (cpp_reader *, int, int, const cpp_hashnode *);
103 static unsigned int read_flag (cpp_reader *, unsigned int);
104 static bool strtolinenum (const uchar *, size_t, linenum_type *, bool *);
105 static void do_diagnostic (cpp_reader *, int, int, int);
106 static cpp_hashnode *lex_macro_node (cpp_reader *, bool);
107 static int undefine_macros (cpp_reader *, cpp_hashnode *, void *);
108 static void do_include_common (cpp_reader *, enum include_type);
109 static struct pragma_entry *lookup_pragma_entry (struct pragma_entry *,
110                                                  const cpp_hashnode *);
111 static int count_registered_pragmas (struct pragma_entry *);
112 static char ** save_registered_pragmas (struct pragma_entry *, char **);
113 static char ** restore_registered_pragmas (cpp_reader *, struct pragma_entry *,
114                                            char **);
115 static void do_pragma_once (cpp_reader *);
116 static void do_pragma_poison (cpp_reader *);
117 static void do_pragma_system_header (cpp_reader *);
118 static void do_pragma_dependency (cpp_reader *);
119 static void do_pragma_warning_or_error (cpp_reader *, bool error);
120 static void do_pragma_warning (cpp_reader *);
121 static void do_pragma_error (cpp_reader *);
122 static void do_linemarker (cpp_reader *);
123 static const cpp_token *get_token_no_padding (cpp_reader *);
124 static const cpp_token *get__Pragma_string (cpp_reader *);
125 static void destringize_and_run (cpp_reader *, const cpp_string *,
126 				 source_location);
127 static int parse_answer (cpp_reader *, struct answer **, int, source_location);
128 static cpp_hashnode *parse_assertion (cpp_reader *, struct answer **, int);
129 static struct answer ** find_answer (cpp_hashnode *, const struct answer *);
130 static void handle_assertion (cpp_reader *, const char *, int);
131 static void do_pragma_push_macro (cpp_reader *);
132 static void do_pragma_pop_macro (cpp_reader *);
133 static void cpp_pop_definition (cpp_reader *, struct def_pragma_macro *);
134 
135 /* This is the table of directive handlers.  It is ordered by
136    frequency of occurrence; the numbers at the end are directive
137    counts from all the source code I have lying around (egcs and libc
138    CVS as of 1999-05-18, plus grub-0.5.91, linux-2.2.9, and
139    pcmcia-cs-3.0.9).  This is no longer important as directive lookup
140    is now O(1).  All extensions other than #warning, #include_next,
141    and #import are deprecated.  The name is where the extension
142    appears to have come from.  */
143 
144 #define DIRECTIVE_TABLE							\
145 D(define,	T_DEFINE = 0,	KANDR,     IN_I)	   /* 270554 */ \
146 D(include,	T_INCLUDE,	KANDR,     INCL | EXPAND)  /*  52262 */ \
147 D(endif,	T_ENDIF,	KANDR,     COND)	   /*  45855 */ \
148 D(ifdef,	T_IFDEF,	KANDR,     COND | IF_COND) /*  22000 */ \
149 D(if,		T_IF,		KANDR, COND | IF_COND | EXPAND) /*  18162 */ \
150 D(else,		T_ELSE,		KANDR,     COND)	   /*   9863 */ \
151 D(ifndef,	T_IFNDEF,	KANDR,     COND | IF_COND) /*   9675 */ \
152 D(undef,	T_UNDEF,	KANDR,     IN_I)	   /*   4837 */ \
153 D(line,		T_LINE,		KANDR,     EXPAND)	   /*   2465 */ \
154 D(elif,		T_ELIF,		STDC89,    COND | EXPAND)  /*    610 */ \
155 D(error,	T_ERROR,	STDC89,    0)		   /*    475 */ \
156 D(pragma,	T_PRAGMA,	STDC89,    IN_I)	   /*    195 */ \
157 D(warning,	T_WARNING,	EXTENSION, 0)		   /*     22 */ \
158 D(include_next,	T_INCLUDE_NEXT,	EXTENSION, INCL | EXPAND)  /*     19 */ \
159 D(ident,	T_IDENT,	EXTENSION, IN_I)           /*     11 */ \
160 D(import,	T_IMPORT,	EXTENSION, INCL | EXPAND)  /* 0 ObjC */	\
161 D(assert,	T_ASSERT,	EXTENSION, DEPRECATED)	   /* 0 SVR4 */	\
162 D(unassert,	T_UNASSERT,	EXTENSION, DEPRECATED)	   /* 0 SVR4 */	\
163 D(sccs,		T_SCCS,		EXTENSION, IN_I)           /* 0 SVR4? */
164 
165 /* #sccs is synonymous with #ident.  */
166 #define do_sccs do_ident
167 
168 /* Use the table to generate a series of prototypes, an enum for the
169    directive names, and an array of directive handlers.  */
170 
171 #define D(name, t, o, f) static void do_##name (cpp_reader *);
172 DIRECTIVE_TABLE
173 #undef D
174 
175 #define D(n, tag, o, f) tag,
176 enum
177 {
178   DIRECTIVE_TABLE
179   N_DIRECTIVES
180 };
181 #undef D
182 
183 #define D(name, t, origin, flags) \
184 { do_##name, (const uchar *) #name, \
185   sizeof #name - 1, origin, flags },
186 static const directive dtable[] =
187 {
188 DIRECTIVE_TABLE
189 };
190 #undef D
191 
192 /* A NULL-terminated array of directive names for use
193    when suggesting corrections for misspelled directives.  */
194 #define D(name, t, origin, flags) #name,
195 static const char * const directive_names[] = {
196 DIRECTIVE_TABLE
197   NULL
198 };
199 #undef D
200 
201 #undef DIRECTIVE_TABLE
202 
203 /* Wrapper struct directive for linemarkers.
204    The origin is more or less true - the original K+R cpp
205    did use this notation in its preprocessed output.  */
206 static const directive linemarker_dir =
207 {
208   do_linemarker, UC"#", 1, KANDR, IN_I
209 };
210 
211 #define SEEN_EOL() (pfile->cur_token[-1].type == CPP_EOF)
212 
213 /* Skip any remaining tokens in a directive.  */
214 static void
skip_rest_of_line(cpp_reader * pfile)215 skip_rest_of_line (cpp_reader *pfile)
216 {
217   /* Discard all stacked contexts.  */
218   while (pfile->context->prev)
219     _cpp_pop_context (pfile);
220 
221   /* Sweep up all tokens remaining on the line.  */
222   if (! SEEN_EOL ())
223     while (_cpp_lex_token (pfile)->type != CPP_EOF)
224       ;
225 }
226 
227 /* Helper function for check_oel.  */
228 
229 static void
check_eol_1(cpp_reader * pfile,bool expand,int reason)230 check_eol_1 (cpp_reader *pfile, bool expand, int reason)
231 {
232   if (! SEEN_EOL () && (expand
233 			? cpp_get_token (pfile)
234 			: _cpp_lex_token (pfile))->type != CPP_EOF)
235     cpp_pedwarning (pfile, reason, "extra tokens at end of #%s directive",
236 		    pfile->directive->name);
237 }
238 
239 /* Variant of check_eol used for Wendif-labels warnings.  */
240 
241 static void
check_eol_endif_labels(cpp_reader * pfile)242 check_eol_endif_labels (cpp_reader *pfile)
243 {
244   check_eol_1 (pfile, false, CPP_W_ENDIF_LABELS);
245 }
246 
247 /* Ensure there are no stray tokens at the end of a directive.  If
248    EXPAND is true, tokens macro-expanding to nothing are allowed.  */
249 
250 static void
check_eol(cpp_reader * pfile,bool expand)251 check_eol (cpp_reader *pfile, bool expand)
252 {
253   check_eol_1 (pfile, expand, CPP_W_NONE);
254 }
255 
256 /* Ensure there are no stray tokens other than comments at the end of
257    a directive, and gather the comments.  */
258 static const cpp_token **
check_eol_return_comments(cpp_reader * pfile)259 check_eol_return_comments (cpp_reader *pfile)
260 {
261   size_t c;
262   size_t capacity = 8;
263   const cpp_token **buf;
264 
265   buf = XNEWVEC (const cpp_token *, capacity);
266   c = 0;
267   if (! SEEN_EOL ())
268     {
269       while (1)
270 	{
271 	  const cpp_token *tok;
272 
273 	  tok = _cpp_lex_token (pfile);
274 	  if (tok->type == CPP_EOF)
275 	    break;
276 	  if (tok->type != CPP_COMMENT)
277 	    cpp_error (pfile, CPP_DL_PEDWARN,
278 		       "extra tokens at end of #%s directive",
279 		       pfile->directive->name);
280 	  else
281 	    {
282 	      if (c + 1 >= capacity)
283 		{
284 		  capacity *= 2;
285 		  buf = XRESIZEVEC (const cpp_token *, buf, capacity);
286 		}
287 	      buf[c] = tok;
288 	      ++c;
289 	    }
290 	}
291     }
292   buf[c] = NULL;
293   return buf;
294 }
295 
296 /* Called when entering a directive, _Pragma or command-line directive.  */
297 static void
start_directive(cpp_reader * pfile)298 start_directive (cpp_reader *pfile)
299 {
300   /* Setup in-directive state.  */
301   pfile->state.in_directive = 1;
302   pfile->state.save_comments = 0;
303   pfile->directive_result.type = CPP_PADDING;
304 
305   /* Some handlers need the position of the # for diagnostics.  */
306   pfile->directive_line = pfile->line_table->highest_line;
307 }
308 
309 /* Called when leaving a directive, _Pragma or command-line directive.  */
310 static void
end_directive(cpp_reader * pfile,int skip_line)311 end_directive (cpp_reader *pfile, int skip_line)
312 {
313   if (CPP_OPTION (pfile, traditional))
314     {
315       /* Revert change of prepare_directive_trad.  */
316       if (!pfile->state.in_deferred_pragma)
317 	pfile->state.prevent_expansion--;
318 
319       if (pfile->directive != &dtable[T_DEFINE])
320 	_cpp_remove_overlay (pfile);
321     }
322   else if (pfile->state.in_deferred_pragma)
323     ;
324   /* We don't skip for an assembler #.  */
325   else if (skip_line)
326     {
327       skip_rest_of_line (pfile);
328       if (!pfile->keep_tokens)
329 	{
330 	  pfile->cur_run = &pfile->base_run;
331 	  pfile->cur_token = pfile->base_run.base;
332 	}
333     }
334 
335   /* Restore state.  */
336   pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
337   pfile->state.in_directive = 0;
338   pfile->state.in_expression = 0;
339   pfile->state.angled_headers = 0;
340   pfile->directive = 0;
341 }
342 
343 /* Prepare to handle the directive in pfile->directive.  */
344 static void
prepare_directive_trad(cpp_reader * pfile)345 prepare_directive_trad (cpp_reader *pfile)
346 {
347   if (pfile->directive != &dtable[T_DEFINE])
348     {
349       bool no_expand = (pfile->directive
350 			&& ! (pfile->directive->flags & EXPAND));
351       bool was_skipping = pfile->state.skipping;
352 
353       pfile->state.in_expression = (pfile->directive == &dtable[T_IF]
354 				    || pfile->directive == &dtable[T_ELIF]);
355       if (pfile->state.in_expression)
356 	pfile->state.skipping = false;
357 
358       if (no_expand)
359 	pfile->state.prevent_expansion++;
360       _cpp_scan_out_logical_line (pfile, NULL, false);
361       if (no_expand)
362 	pfile->state.prevent_expansion--;
363 
364       pfile->state.skipping = was_skipping;
365       _cpp_overlay_buffer (pfile, pfile->out.base,
366 			   pfile->out.cur - pfile->out.base);
367     }
368 
369   /* Stop ISO C from expanding anything.  */
370   pfile->state.prevent_expansion++;
371 }
372 
373 /* Output diagnostics for a directive DIR.  INDENTED is nonzero if
374    the '#' was indented.  */
375 static void
directive_diagnostics(cpp_reader * pfile,const directive * dir,int indented)376 directive_diagnostics (cpp_reader *pfile, const directive *dir, int indented)
377 {
378   /* Issue -pedantic or deprecated warnings for extensions.  We let
379      -pedantic take precedence if both are applicable.  */
380   if (! pfile->state.skipping)
381     {
382       if (dir->origin == EXTENSION
383 	  && !(dir == &dtable[T_IMPORT] && CPP_OPTION (pfile, objc))
384 	  && CPP_PEDANTIC (pfile))
385 	cpp_error (pfile, CPP_DL_PEDWARN, "#%s is a GCC extension", dir->name);
386       else if (((dir->flags & DEPRECATED) != 0
387 		|| (dir == &dtable[T_IMPORT] && !CPP_OPTION (pfile, objc)))
388 	       && CPP_OPTION (pfile, cpp_warn_deprecated))
389 	cpp_warning (pfile, CPP_W_DEPRECATED,
390                      "#%s is a deprecated GCC extension", dir->name);
391     }
392 
393   /* Traditionally, a directive is ignored unless its # is in
394      column 1.  Therefore in code intended to work with K+R
395      compilers, directives added by C89 must have their #
396      indented, and directives present in traditional C must not.
397      This is true even of directives in skipped conditional
398      blocks.  #elif cannot be used at all.  */
399   if (CPP_WTRADITIONAL (pfile))
400     {
401       if (dir == &dtable[T_ELIF])
402 	cpp_warning (pfile, CPP_W_TRADITIONAL,
403 		     "suggest not using #elif in traditional C");
404       else if (indented && dir->origin == KANDR)
405 	cpp_warning (pfile, CPP_W_TRADITIONAL,
406 		     "traditional C ignores #%s with the # indented",
407 		     dir->name);
408       else if (!indented && dir->origin != KANDR)
409 	cpp_warning (pfile, CPP_W_TRADITIONAL,
410 		     "suggest hiding #%s from traditional C with an indented #",
411 		     dir->name);
412     }
413 }
414 
415 /* Check if we have a known directive.  INDENTED is nonzero if the
416    '#' of the directive was indented.  This function is in this file
417    to save unnecessarily exporting dtable etc. to lex.c.  Returns
418    nonzero if the line of tokens has been handled, zero if we should
419    continue processing the line.  */
420 int
_cpp_handle_directive(cpp_reader * pfile,int indented)421 _cpp_handle_directive (cpp_reader *pfile, int indented)
422 {
423   const directive *dir = 0;
424   const cpp_token *dname;
425   bool was_parsing_args = pfile->state.parsing_args;
426   bool was_discarding_output = pfile->state.discarding_output;
427   int skip = 1;
428 
429   if (was_discarding_output)
430     pfile->state.prevent_expansion = 0;
431 
432   if (was_parsing_args)
433     {
434       if (CPP_OPTION (pfile, cpp_pedantic))
435 	cpp_error (pfile, CPP_DL_PEDWARN,
436 	     "embedding a directive within macro arguments is not portable");
437       pfile->state.parsing_args = 0;
438       pfile->state.prevent_expansion = 0;
439     }
440   start_directive (pfile);
441   dname = _cpp_lex_token (pfile);
442 
443   if (dname->type == CPP_NAME)
444     {
445       if (dname->val.node.node->is_directive)
446 	dir = &dtable[dname->val.node.node->directive_index];
447     }
448   /* We do not recognize the # followed by a number extension in
449      assembler code.  */
450   else if (dname->type == CPP_NUMBER && CPP_OPTION (pfile, lang) != CLK_ASM)
451     {
452       dir = &linemarker_dir;
453       if (CPP_PEDANTIC (pfile) && ! CPP_OPTION (pfile, preprocessed)
454 	  && ! pfile->state.skipping)
455 	cpp_error (pfile, CPP_DL_PEDWARN,
456 		   "style of line directive is a GCC extension");
457     }
458 
459   if (dir)
460     {
461       /* If we have a directive that is not an opening conditional,
462 	 invalidate any control macro.  */
463       if (! (dir->flags & IF_COND))
464 	pfile->mi_valid = false;
465 
466       /* Kluge alert.  In order to be sure that code like this
467 
468 	 #define HASH #
469 	 HASH define foo bar
470 
471 	 does not cause '#define foo bar' to get executed when
472 	 compiled with -save-temps, we recognize directives in
473 	 -fpreprocessed mode only if the # is in column 1.  macro.c
474 	 puts a space in front of any '#' at the start of a macro.
475 
476 	 We exclude the -fdirectives-only case because macro expansion
477 	 has not been performed yet, and block comments can cause spaces
478 	 to precede the directive.  */
479       if (CPP_OPTION (pfile, preprocessed)
480 	  && !CPP_OPTION (pfile, directives_only)
481 	  && (indented || !(dir->flags & IN_I)))
482 	{
483 	  skip = 0;
484 	  dir = 0;
485 	}
486       else
487 	{
488 	  /* In failed conditional groups, all non-conditional
489 	     directives are ignored.  Before doing that, whether
490 	     skipping or not, we should lex angle-bracketed headers
491 	     correctly, and maybe output some diagnostics.  */
492 	  pfile->state.angled_headers = dir->flags & INCL;
493 	  pfile->state.directive_wants_padding = dir->flags & INCL;
494 	  if (! CPP_OPTION (pfile, preprocessed))
495 	    directive_diagnostics (pfile, dir, indented);
496 	  if (pfile->state.skipping && !(dir->flags & COND))
497 	    dir = 0;
498 	}
499     }
500   else if (dname->type == CPP_EOF)
501     ;	/* CPP_EOF is the "null directive".  */
502   else
503     {
504       /* An unknown directive.  Don't complain about it in assembly
505 	 source: we don't know where the comments are, and # may
506 	 introduce assembler pseudo-ops.  Don't complain about invalid
507 	 directives in skipped conditional groups (6.10 p4).  */
508       if (CPP_OPTION (pfile, lang) == CLK_ASM)
509 	skip = 0;
510       else if (!pfile->state.skipping)
511 	{
512 	  const char *unrecognized
513 	    = (const char *)cpp_token_as_text (pfile, dname);
514 	  const char *hint = NULL;
515 
516 	  /* Call back into gcc to get a spelling suggestion.  Ideally
517 	     we'd just use best_match from gcc/spellcheck.h (and filter
518 	     out the uncommon directives), but that requires moving it
519 	     to a support library.  */
520 	  if (pfile->cb.get_suggestion)
521 	    hint = pfile->cb.get_suggestion (pfile, unrecognized,
522 					     directive_names);
523 
524 	  if (hint)
525 	    {
526 	      rich_location richloc (pfile->line_table, dname->src_loc);
527 	      source_range misspelled_token_range
528 		= get_range_from_loc (pfile->line_table, dname->src_loc);
529 	      richloc.add_fixit_replace (misspelled_token_range, hint);
530 	      cpp_error_at (pfile, CPP_DL_ERROR, &richloc,
531 			    "invalid preprocessing directive #%s;"
532 			    " did you mean #%s?",
533 			    unrecognized, hint);
534 	    }
535 	  else
536 	    cpp_error (pfile, CPP_DL_ERROR,
537 		       "invalid preprocessing directive #%s",
538 		       unrecognized);
539 	}
540     }
541 
542   pfile->directive = dir;
543   if (CPP_OPTION (pfile, traditional))
544     prepare_directive_trad (pfile);
545 
546   if (dir)
547     pfile->directive->handler (pfile);
548   else if (skip == 0)
549     _cpp_backup_tokens (pfile, 1);
550 
551   end_directive (pfile, skip);
552   if (was_parsing_args && !pfile->state.in_deferred_pragma)
553     {
554       /* Restore state when within macro args.  */
555       pfile->state.parsing_args = 2;
556       pfile->state.prevent_expansion = 1;
557     }
558   if (was_discarding_output)
559     pfile->state.prevent_expansion = 1;
560   return skip;
561 }
562 
563 /* Directive handler wrapper used by the command line option
564    processor.  BUF is \n terminated.  */
565 static void
run_directive(cpp_reader * pfile,int dir_no,const char * buf,size_t count)566 run_directive (cpp_reader *pfile, int dir_no, const char *buf, size_t count)
567 {
568   cpp_push_buffer (pfile, (const uchar *) buf, count,
569 		   /* from_stage3 */ true);
570   start_directive (pfile);
571 
572   /* This is a short-term fix to prevent a leading '#' being
573      interpreted as a directive.  */
574   _cpp_clean_line (pfile);
575 
576   pfile->directive = &dtable[dir_no];
577   if (CPP_OPTION (pfile, traditional))
578     prepare_directive_trad (pfile);
579   pfile->directive->handler (pfile);
580   end_directive (pfile, 1);
581   _cpp_pop_buffer (pfile);
582 }
583 
584 /* Checks for validity the macro name in #define, #undef, #ifdef and
585    #ifndef directives.  IS_DEF_OR_UNDEF is true if this call is
586    processing a #define or #undefine directive, and false
587    otherwise.  */
588 static cpp_hashnode *
lex_macro_node(cpp_reader * pfile,bool is_def_or_undef)589 lex_macro_node (cpp_reader *pfile, bool is_def_or_undef)
590 {
591   const cpp_token *token = _cpp_lex_token (pfile);
592 
593   /* The token immediately after #define must be an identifier.  That
594      identifier may not be "defined", per C99 6.10.8p4.
595      In C++, it may not be any of the "named operators" either,
596      per C++98 [lex.digraph], [lex.key].
597      Finally, the identifier may not have been poisoned.  (In that case
598      the lexer has issued the error message for us.)  */
599 
600   if (token->type == CPP_NAME)
601     {
602       cpp_hashnode *node = token->val.node.node;
603 
604       if (is_def_or_undef && node == pfile->spec_nodes.n_defined)
605 	cpp_error (pfile, CPP_DL_ERROR,
606 		   "\"defined\" cannot be used as a macro name");
607       else if (is_def_or_undef
608 	    && (node == pfile->spec_nodes.n__has_include__
609 	     || node == pfile->spec_nodes.n__has_include_next__))
610 	cpp_error (pfile, CPP_DL_ERROR,
611 		   "\"__has_include__\" cannot be used as a macro name");
612       else if (! (node->flags & NODE_POISONED))
613 	return node;
614     }
615   else if (token->flags & NAMED_OP)
616     cpp_error (pfile, CPP_DL_ERROR,
617        "\"%s\" cannot be used as a macro name as it is an operator in C++",
618 	       NODE_NAME (token->val.node.node));
619   else if (token->type == CPP_EOF)
620     cpp_error (pfile, CPP_DL_ERROR, "no macro name given in #%s directive",
621 	       pfile->directive->name);
622   else
623     cpp_error (pfile, CPP_DL_ERROR, "macro names must be identifiers");
624 
625   return NULL;
626 }
627 
628 /* Process a #define directive.  Most work is done in macro.c.  */
629 static void
do_define(cpp_reader * pfile)630 do_define (cpp_reader *pfile)
631 {
632   cpp_hashnode *node = lex_macro_node (pfile, true);
633 
634   if (node)
635     {
636       /* If we have been requested to expand comments into macros,
637 	 then re-enable saving of comments.  */
638       pfile->state.save_comments =
639 	! CPP_OPTION (pfile, discard_comments_in_macro_exp);
640 
641       if (pfile->cb.before_define)
642 	pfile->cb.before_define (pfile);
643 
644       if (_cpp_create_definition (pfile, node))
645 	if (pfile->cb.define)
646 	  pfile->cb.define (pfile, pfile->directive_line, node);
647 
648       node->flags &= ~NODE_USED;
649     }
650 }
651 
652 /* Handle #undef.  Mark the identifier NT_VOID in the hash table.  */
653 static void
do_undef(cpp_reader * pfile)654 do_undef (cpp_reader *pfile)
655 {
656   cpp_hashnode *node = lex_macro_node (pfile, true);
657 
658   if (node)
659     {
660       if (pfile->cb.before_define)
661 	pfile->cb.before_define (pfile);
662 
663       if (pfile->cb.undef)
664 	pfile->cb.undef (pfile, pfile->directive_line, node);
665 
666       /* 6.10.3.5 paragraph 2: [#undef] is ignored if the specified
667 	 identifier is not currently defined as a macro name.  */
668       if (node->type == NT_MACRO)
669 	{
670 	  if (node->flags & NODE_WARN)
671 	    cpp_error (pfile, CPP_DL_WARNING,
672 		       "undefining \"%s\"", NODE_NAME (node));
673 	  else if ((node->flags & NODE_BUILTIN)
674 		   && CPP_OPTION (pfile, warn_builtin_macro_redefined))
675 	    cpp_warning_with_line (pfile, CPP_W_BUILTIN_MACRO_REDEFINED,
676 				   pfile->directive_line, 0,
677 				   "undefining \"%s\"", NODE_NAME (node));
678 
679 	  if (CPP_OPTION (pfile, warn_unused_macros))
680 	    _cpp_warn_if_unused_macro (pfile, node, NULL);
681 
682 	  _cpp_free_definition (node);
683 	}
684     }
685 
686   check_eol (pfile, false);
687 }
688 
689 /* Undefine a single macro/assertion/whatever.  */
690 
691 static int
undefine_macros(cpp_reader * pfile ATTRIBUTE_UNUSED,cpp_hashnode * h,void * data_p ATTRIBUTE_UNUSED)692 undefine_macros (cpp_reader *pfile ATTRIBUTE_UNUSED, cpp_hashnode *h,
693 		 void *data_p ATTRIBUTE_UNUSED)
694 {
695   /* Body of _cpp_free_definition inlined here for speed.
696      Macros and assertions no longer have anything to free.  */
697   h->type = NT_VOID;
698   h->flags &= ~(NODE_POISONED|NODE_BUILTIN|NODE_DISABLED|NODE_USED);
699   return 1;
700 }
701 
702 /* Undefine all macros and assertions.  */
703 
704 void
cpp_undef_all(cpp_reader * pfile)705 cpp_undef_all (cpp_reader *pfile)
706 {
707   cpp_forall_identifiers (pfile, undefine_macros, NULL);
708 }
709 
710 
711 /* Helper routine used by parse_include.  Reinterpret the current line
712    as an h-char-sequence (< ... >); we are looking at the first token
713    after the <.  Returns a malloced filename.  */
714 static char *
glue_header_name(cpp_reader * pfile)715 glue_header_name (cpp_reader *pfile)
716 {
717   const cpp_token *token;
718   char *buffer;
719   size_t len, total_len = 0, capacity = 1024;
720 
721   /* To avoid lexed tokens overwriting our glued name, we can only
722      allocate from the string pool once we've lexed everything.  */
723   buffer = XNEWVEC (char, capacity);
724   for (;;)
725     {
726       token = get_token_no_padding (pfile);
727 
728       if (token->type == CPP_GREATER)
729 	break;
730       if (token->type == CPP_EOF)
731 	{
732 	  cpp_error (pfile, CPP_DL_ERROR, "missing terminating > character");
733 	  break;
734 	}
735 
736       len = cpp_token_len (token) + 2; /* Leading space, terminating \0.  */
737       if (total_len + len > capacity)
738 	{
739 	  capacity = (capacity + len) * 2;
740 	  buffer = XRESIZEVEC (char, buffer, capacity);
741 	}
742 
743       if (token->flags & PREV_WHITE)
744 	buffer[total_len++] = ' ';
745 
746       total_len = (cpp_spell_token (pfile, token, (uchar *) &buffer[total_len],
747 				    true)
748 		   - (uchar *) buffer);
749     }
750 
751   buffer[total_len] = '\0';
752   return buffer;
753 }
754 
755 /* Returns the file name of #include, #include_next, #import and
756    #pragma dependency.  The string is malloced and the caller should
757    free it.  Returns NULL on error.  LOCATION is the source location
758    of the file name.  */
759 
760 static const char *
parse_include(cpp_reader * pfile,int * pangle_brackets,const cpp_token *** buf,source_location * location)761 parse_include (cpp_reader *pfile, int *pangle_brackets,
762 	       const cpp_token ***buf, source_location *location)
763 {
764   char *fname;
765   const cpp_token *header;
766 
767   /* Allow macro expansion.  */
768   header = get_token_no_padding (pfile);
769   *location = header->src_loc;
770   if ((header->type == CPP_STRING && header->val.str.text[0] != 'R')
771       || header->type == CPP_HEADER_NAME)
772     {
773       fname = XNEWVEC (char, header->val.str.len - 1);
774       memcpy (fname, header->val.str.text + 1, header->val.str.len - 2);
775       fname[header->val.str.len - 2] = '\0';
776       *pangle_brackets = header->type == CPP_HEADER_NAME;
777     }
778   else if (header->type == CPP_LESS)
779     {
780       fname = glue_header_name (pfile);
781       *pangle_brackets = 1;
782     }
783   else
784     {
785       const unsigned char *dir;
786 
787       if (pfile->directive == &dtable[T_PRAGMA])
788 	dir = UC"pragma dependency";
789       else
790 	dir = pfile->directive->name;
791       cpp_error (pfile, CPP_DL_ERROR, "#%s expects \"FILENAME\" or <FILENAME>",
792 		 dir);
793 
794       return NULL;
795     }
796 
797   if (pfile->directive == &dtable[T_PRAGMA])
798     {
799       /* This pragma allows extra tokens after the file name.  */
800     }
801   else if (buf == NULL || CPP_OPTION (pfile, discard_comments))
802     check_eol (pfile, true);
803   else
804     {
805       /* If we are not discarding comments, then gather them while
806 	 doing the eol check.  */
807       *buf = check_eol_return_comments (pfile);
808     }
809 
810   return fname;
811 }
812 
813 /* Handle #include, #include_next and #import.  */
814 static void
do_include_common(cpp_reader * pfile,enum include_type type)815 do_include_common (cpp_reader *pfile, enum include_type type)
816 {
817   const char *fname;
818   int angle_brackets;
819   const cpp_token **buf = NULL;
820   source_location location;
821 
822   /* Re-enable saving of comments if requested, so that the include
823      callback can dump comments which follow #include.  */
824   pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
825 
826   fname = parse_include (pfile, &angle_brackets, &buf, &location);
827   if (!fname)
828     {
829       if (buf)
830 	XDELETEVEC (buf);
831       return;
832     }
833 
834   if (!*fname)
835   {
836     cpp_error_with_line (pfile, CPP_DL_ERROR, location, 0,
837 			 "empty filename in #%s",
838 			 pfile->directive->name);
839     XDELETEVEC (fname);
840     if (buf)
841       XDELETEVEC (buf);
842     return;
843   }
844 
845   /* Prevent #include recursion.  */
846   if (pfile->line_table->depth >= CPP_STACK_MAX)
847     cpp_error (pfile, CPP_DL_ERROR, "#include nested too deeply");
848   else
849     {
850       /* Get out of macro context, if we are.  */
851       skip_rest_of_line (pfile);
852 
853       if (pfile->cb.include)
854 	pfile->cb.include (pfile, pfile->directive_line,
855 			   pfile->directive->name, fname, angle_brackets,
856 			   buf);
857 
858       _cpp_stack_include (pfile, fname, angle_brackets, type, location);
859     }
860 
861   XDELETEVEC (fname);
862   if (buf)
863     XDELETEVEC (buf);
864 }
865 
866 static void
do_include(cpp_reader * pfile)867 do_include (cpp_reader *pfile)
868 {
869   do_include_common (pfile, IT_INCLUDE);
870 }
871 
872 static void
do_import(cpp_reader * pfile)873 do_import (cpp_reader *pfile)
874 {
875   do_include_common (pfile, IT_IMPORT);
876 }
877 
878 static void
do_include_next(cpp_reader * pfile)879 do_include_next (cpp_reader *pfile)
880 {
881   enum include_type type = IT_INCLUDE_NEXT;
882 
883   /* If this is the primary source file, warn and use the normal
884      search logic.  */
885   if (cpp_in_primary_file (pfile))
886     {
887       cpp_error (pfile, CPP_DL_WARNING,
888 		 "#include_next in primary source file");
889       type = IT_INCLUDE;
890     }
891   do_include_common (pfile, type);
892 }
893 
894 /* Subroutine of do_linemarker.  Read possible flags after file name.
895    LAST is the last flag seen; 0 if this is the first flag. Return the
896    flag if it is valid, 0 at the end of the directive. Otherwise
897    complain.  */
898 static unsigned int
read_flag(cpp_reader * pfile,unsigned int last)899 read_flag (cpp_reader *pfile, unsigned int last)
900 {
901   const cpp_token *token = _cpp_lex_token (pfile);
902 
903   if (token->type == CPP_NUMBER && token->val.str.len == 1)
904     {
905       unsigned int flag = token->val.str.text[0] - '0';
906 
907       if (flag > last && flag <= 4
908 	  && (flag != 4 || last == 3)
909 	  && (flag != 2 || last == 0))
910 	return flag;
911     }
912 
913   if (token->type != CPP_EOF)
914     cpp_error (pfile, CPP_DL_ERROR, "invalid flag \"%s\" in line directive",
915 	       cpp_token_as_text (pfile, token));
916   return 0;
917 }
918 
919 /* Subroutine of do_line and do_linemarker.  Convert a number in STR,
920    of length LEN, to binary; store it in NUMP, and return false if the
921    number was well-formed, true if not. WRAPPED is set to true if the
922    number did not fit into 'unsigned long'.  */
923 static bool
strtolinenum(const uchar * str,size_t len,linenum_type * nump,bool * wrapped)924 strtolinenum (const uchar *str, size_t len, linenum_type *nump, bool *wrapped)
925 {
926   linenum_type reg = 0;
927   linenum_type reg_prev = 0;
928 
929   uchar c;
930   *wrapped = false;
931   while (len--)
932     {
933       c = *str++;
934       if (!ISDIGIT (c))
935 	return true;
936       reg *= 10;
937       reg += c - '0';
938       if (reg < reg_prev)
939 	*wrapped = true;
940       reg_prev = reg;
941     }
942   *nump = reg;
943   return false;
944 }
945 
946 /* Interpret #line command.
947    Note that the filename string (if any) is a true string constant
948    (escapes are interpreted), unlike in #line.  */
949 static void
do_line(cpp_reader * pfile)950 do_line (cpp_reader *pfile)
951 {
952   struct line_maps *line_table = pfile->line_table;
953   const line_map_ordinary *map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
954 
955   /* skip_rest_of_line() may cause line table to be realloc()ed so note down
956      sysp right now.  */
957 
958   unsigned char map_sysp = ORDINARY_MAP_IN_SYSTEM_HEADER_P (map);
959   const cpp_token *token;
960   const char *new_file = ORDINARY_MAP_FILE_NAME (map);
961   linenum_type new_lineno;
962 
963   /* C99 raised the minimum limit on #line numbers.  */
964   linenum_type cap = CPP_OPTION (pfile, c99) ? 2147483647 : 32767;
965   bool wrapped;
966 
967   /* #line commands expand macros.  */
968   token = cpp_get_token (pfile);
969   if (token->type != CPP_NUMBER
970       || strtolinenum (token->val.str.text, token->val.str.len,
971 		       &new_lineno, &wrapped))
972     {
973       if (token->type == CPP_EOF)
974 	cpp_error (pfile, CPP_DL_ERROR, "unexpected end of file after #line");
975       else
976 	cpp_error (pfile, CPP_DL_ERROR,
977 		   "\"%s\" after #line is not a positive integer",
978 		   cpp_token_as_text (pfile, token));
979       return;
980     }
981 
982   if (CPP_PEDANTIC (pfile) && (new_lineno == 0 || new_lineno > cap || wrapped))
983     cpp_error (pfile, CPP_DL_PEDWARN, "line number out of range");
984   else if (wrapped)
985     cpp_error (pfile, CPP_DL_WARNING, "line number out of range");
986 
987   token = cpp_get_token (pfile);
988   if (token->type == CPP_STRING)
989     {
990       cpp_string s = { 0, 0 };
991       if (cpp_interpret_string_notranslate (pfile, &token->val.str, 1,
992 					    &s, CPP_STRING))
993 	new_file = (const char *)s.text;
994       check_eol (pfile, true);
995     }
996   else if (token->type != CPP_EOF)
997     {
998       cpp_error (pfile, CPP_DL_ERROR, "\"%s\" is not a valid filename",
999 		 cpp_token_as_text (pfile, token));
1000       return;
1001     }
1002 
1003   skip_rest_of_line (pfile);
1004   _cpp_do_file_change (pfile, LC_RENAME_VERBATIM, new_file, new_lineno,
1005 		       map_sysp);
1006   line_table->seen_line_directive = true;
1007 }
1008 
1009 /* Interpret the # 44 "file" [flags] notation, which has slightly
1010    different syntax and semantics from #line:  Flags are allowed,
1011    and we never complain about the line number being too big.  */
1012 static void
do_linemarker(cpp_reader * pfile)1013 do_linemarker (cpp_reader *pfile)
1014 {
1015   struct line_maps *line_table = pfile->line_table;
1016   const line_map_ordinary *map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
1017   const cpp_token *token;
1018   const char *new_file = ORDINARY_MAP_FILE_NAME (map);
1019   linenum_type new_lineno;
1020   unsigned int new_sysp = ORDINARY_MAP_IN_SYSTEM_HEADER_P (map);
1021   enum lc_reason reason = LC_RENAME_VERBATIM;
1022   int flag;
1023   bool wrapped;
1024 
1025   /* Back up so we can get the number again.  Putting this in
1026      _cpp_handle_directive risks two calls to _cpp_backup_tokens in
1027      some circumstances, which can segfault.  */
1028   _cpp_backup_tokens (pfile, 1);
1029 
1030   /* #line commands expand macros.  */
1031   token = cpp_get_token (pfile);
1032   if (token->type != CPP_NUMBER
1033       || strtolinenum (token->val.str.text, token->val.str.len,
1034 		       &new_lineno, &wrapped))
1035     {
1036       /* Unlike #line, there does not seem to be a way to get an EOF
1037 	 here.  So, it should be safe to always spell the token.  */
1038       cpp_error (pfile, CPP_DL_ERROR,
1039 		 "\"%s\" after # is not a positive integer",
1040 		 cpp_token_as_text (pfile, token));
1041       return;
1042     }
1043 
1044   token = cpp_get_token (pfile);
1045   if (token->type == CPP_STRING)
1046     {
1047       cpp_string s = { 0, 0 };
1048       if (cpp_interpret_string_notranslate (pfile, &token->val.str,
1049 					    1, &s, CPP_STRING))
1050 	new_file = (const char *)s.text;
1051 
1052       new_sysp = 0;
1053       flag = read_flag (pfile, 0);
1054       if (flag == 1)
1055 	{
1056 	  reason = LC_ENTER;
1057 	  /* Fake an include for cpp_included ().  */
1058 	  _cpp_fake_include (pfile, new_file);
1059 	  flag = read_flag (pfile, flag);
1060 	}
1061       else if (flag == 2)
1062 	{
1063 	  reason = LC_LEAVE;
1064 	  flag = read_flag (pfile, flag);
1065 	}
1066       if (flag == 3)
1067 	{
1068 	  new_sysp = 1;
1069 	  flag = read_flag (pfile, flag);
1070 	  if (flag == 4)
1071 	    new_sysp = 2;
1072 	}
1073       pfile->buffer->sysp = new_sysp;
1074 
1075       check_eol (pfile, false);
1076     }
1077   else if (token->type != CPP_EOF)
1078     {
1079       cpp_error (pfile, CPP_DL_ERROR, "\"%s\" is not a valid filename",
1080 		 cpp_token_as_text (pfile, token));
1081       return;
1082     }
1083 
1084   skip_rest_of_line (pfile);
1085 
1086   if (reason == LC_LEAVE)
1087     {
1088       /* Reread map since cpp_get_token can invalidate it with a
1089 	 reallocation.  */
1090       map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
1091       const line_map_ordinary *from;
1092       if (MAIN_FILE_P (map)
1093 	  || (new_file
1094 	      && (from = INCLUDED_FROM (pfile->line_table, map)) != NULL
1095 	      && filename_cmp (ORDINARY_MAP_FILE_NAME (from), new_file) != 0))
1096 	{
1097 	  cpp_warning (pfile, CPP_W_NONE,
1098 		       "file \"%s\" linemarker ignored due to "
1099 		       "incorrect nesting", new_file);
1100 	  return;
1101 	}
1102     }
1103   /* Compensate for the increment in linemap_add that occurs in
1104      _cpp_do_file_change.  We're currently at the start of the line
1105      *following* the #line directive.  A separate source_location for this
1106      location makes no sense (until we do the LC_LEAVE), and
1107      complicates LAST_SOURCE_LINE_LOCATION.  */
1108   pfile->line_table->highest_location--;
1109 
1110   _cpp_do_file_change (pfile, reason, new_file, new_lineno, new_sysp);
1111   line_table->seen_line_directive = true;
1112 }
1113 
1114 /* Arrange the file_change callback.  pfile->line has changed to
1115    FILE_LINE of TO_FILE, for reason REASON.  SYSP is 1 for a system
1116    header, 2 for a system header that needs to be extern "C" protected,
1117    and zero otherwise.  */
1118 void
_cpp_do_file_change(cpp_reader * pfile,enum lc_reason reason,const char * to_file,linenum_type file_line,unsigned int sysp)1119 _cpp_do_file_change (cpp_reader *pfile, enum lc_reason reason,
1120 		     const char *to_file, linenum_type file_line,
1121 		     unsigned int sysp)
1122 {
1123   linemap_assert (reason != LC_ENTER_MACRO);
1124   const struct line_map *map = linemap_add (pfile->line_table, reason, sysp,
1125 					    to_file, file_line);
1126   const line_map_ordinary *ord_map = NULL;
1127   if (map != NULL)
1128     {
1129       ord_map = linemap_check_ordinary (map);
1130       linemap_line_start (pfile->line_table,
1131 			  ORDINARY_MAP_STARTING_LINE_NUMBER (ord_map),
1132 			  127);
1133     }
1134 
1135   if (pfile->cb.file_change)
1136     pfile->cb.file_change (pfile, ord_map);
1137 }
1138 
1139 /* Report a warning or error detected by the program we are
1140    processing.  Use the directive's tokens in the error message.  */
1141 static void
do_diagnostic(cpp_reader * pfile,int code,int reason,int print_dir)1142 do_diagnostic (cpp_reader *pfile, int code, int reason, int print_dir)
1143 {
1144   const unsigned char *dir_name;
1145   unsigned char *line;
1146   source_location src_loc = pfile->cur_token[-1].src_loc;
1147 
1148   if (print_dir)
1149     dir_name = pfile->directive->name;
1150   else
1151     dir_name = NULL;
1152   pfile->state.prevent_expansion++;
1153   line = cpp_output_line_to_string (pfile, dir_name);
1154   pfile->state.prevent_expansion--;
1155 
1156   if (code == CPP_DL_WARNING_SYSHDR && reason)
1157     cpp_warning_with_line_syshdr (pfile, reason, src_loc, 0, "%s", line);
1158   else if (code == CPP_DL_WARNING && reason)
1159     cpp_warning_with_line (pfile, reason, src_loc, 0, "%s", line);
1160   else
1161     cpp_error_with_line (pfile, code, src_loc, 0, "%s", line);
1162   free (line);
1163 }
1164 
1165 static void
do_error(cpp_reader * pfile)1166 do_error (cpp_reader *pfile)
1167 {
1168   do_diagnostic (pfile, CPP_DL_ERROR, 0, 1);
1169 }
1170 
1171 static void
do_warning(cpp_reader * pfile)1172 do_warning (cpp_reader *pfile)
1173 {
1174   /* We want #warning diagnostics to be emitted in system headers too.  */
1175   do_diagnostic (pfile, CPP_DL_WARNING_SYSHDR, CPP_W_WARNING_DIRECTIVE, 1);
1176 }
1177 
1178 /* Report program identification.  */
1179 static void
do_ident(cpp_reader * pfile)1180 do_ident (cpp_reader *pfile)
1181 {
1182   const cpp_token *str = cpp_get_token (pfile);
1183 
1184   if (str->type != CPP_STRING)
1185     cpp_error (pfile, CPP_DL_ERROR, "invalid #%s directive",
1186 	       pfile->directive->name);
1187   else if (pfile->cb.ident)
1188     pfile->cb.ident (pfile, pfile->directive_line, &str->val.str);
1189 
1190   check_eol (pfile, false);
1191 }
1192 
1193 /* Lookup a PRAGMA name in a singly-linked CHAIN.  Returns the
1194    matching entry, or NULL if none is found.  The returned entry could
1195    be the start of a namespace chain, or a pragma.  */
1196 static struct pragma_entry *
lookup_pragma_entry(struct pragma_entry * chain,const cpp_hashnode * pragma)1197 lookup_pragma_entry (struct pragma_entry *chain, const cpp_hashnode *pragma)
1198 {
1199   while (chain && chain->pragma != pragma)
1200     chain = chain->next;
1201 
1202   return chain;
1203 }
1204 
1205 /* Create and insert a blank pragma entry at the beginning of a
1206    singly-linked CHAIN.  */
1207 static struct pragma_entry *
new_pragma_entry(cpp_reader * pfile,struct pragma_entry ** chain)1208 new_pragma_entry (cpp_reader *pfile, struct pragma_entry **chain)
1209 {
1210   struct pragma_entry *new_entry;
1211 
1212   new_entry = (struct pragma_entry *)
1213     _cpp_aligned_alloc (pfile, sizeof (struct pragma_entry));
1214 
1215   memset (new_entry, 0, sizeof (struct pragma_entry));
1216   new_entry->next = *chain;
1217 
1218   *chain = new_entry;
1219   return new_entry;
1220 }
1221 
1222 /* Register a pragma NAME in namespace SPACE.  If SPACE is null, it
1223    goes in the global namespace.  */
1224 static struct pragma_entry *
register_pragma_1(cpp_reader * pfile,const char * space,const char * name,bool allow_name_expansion)1225 register_pragma_1 (cpp_reader *pfile, const char *space, const char *name,
1226 		   bool allow_name_expansion)
1227 {
1228   struct pragma_entry **chain = &pfile->pragmas;
1229   struct pragma_entry *entry;
1230   const cpp_hashnode *node;
1231 
1232   if (space)
1233     {
1234       node = cpp_lookup (pfile, UC space, strlen (space));
1235       entry = lookup_pragma_entry (*chain, node);
1236       if (!entry)
1237 	{
1238 	  entry = new_pragma_entry (pfile, chain);
1239 	  entry->pragma = node;
1240 	  entry->is_nspace = true;
1241 	  entry->allow_expansion = allow_name_expansion;
1242 	}
1243       else if (!entry->is_nspace)
1244 	goto clash;
1245       else if (entry->allow_expansion != allow_name_expansion)
1246 	{
1247 	  cpp_error (pfile, CPP_DL_ICE,
1248 		     "registering pragmas in namespace \"%s\" with mismatched "
1249 		     "name expansion", space);
1250 	  return NULL;
1251 	}
1252       chain = &entry->u.space;
1253     }
1254   else if (allow_name_expansion)
1255     {
1256       cpp_error (pfile, CPP_DL_ICE,
1257 		 "registering pragma \"%s\" with name expansion "
1258 		 "and no namespace", name);
1259       return NULL;
1260     }
1261 
1262   /* Check for duplicates.  */
1263   node = cpp_lookup (pfile, UC name, strlen (name));
1264   entry = lookup_pragma_entry (*chain, node);
1265   if (entry == NULL)
1266     {
1267       entry = new_pragma_entry (pfile, chain);
1268       entry->pragma = node;
1269       return entry;
1270     }
1271 
1272   if (entry->is_nspace)
1273     clash:
1274     cpp_error (pfile, CPP_DL_ICE,
1275 	       "registering \"%s\" as both a pragma and a pragma namespace",
1276 	       NODE_NAME (node));
1277   else if (space)
1278     cpp_error (pfile, CPP_DL_ICE, "#pragma %s %s is already registered",
1279 	       space, name);
1280   else
1281     cpp_error (pfile, CPP_DL_ICE, "#pragma %s is already registered", name);
1282 
1283   return NULL;
1284 }
1285 
1286 /* Register a cpplib internal pragma SPACE NAME with HANDLER.  */
1287 static void
register_pragma_internal(cpp_reader * pfile,const char * space,const char * name,pragma_cb handler)1288 register_pragma_internal (cpp_reader *pfile, const char *space,
1289 			  const char *name, pragma_cb handler)
1290 {
1291   struct pragma_entry *entry;
1292 
1293   entry = register_pragma_1 (pfile, space, name, false);
1294   entry->is_internal = true;
1295   entry->u.handler = handler;
1296 }
1297 
1298 /* Register a pragma NAME in namespace SPACE.  If SPACE is null, it
1299    goes in the global namespace.  HANDLER is the handler it will call,
1300    which must be non-NULL.  If ALLOW_EXPANSION is set, allow macro
1301    expansion while parsing pragma NAME.  This function is exported
1302    from libcpp. */
1303 void
cpp_register_pragma(cpp_reader * pfile,const char * space,const char * name,pragma_cb handler,bool allow_expansion)1304 cpp_register_pragma (cpp_reader *pfile, const char *space, const char *name,
1305 		     pragma_cb handler, bool allow_expansion)
1306 {
1307   struct pragma_entry *entry;
1308 
1309   if (!handler)
1310     {
1311       cpp_error (pfile, CPP_DL_ICE, "registering pragma with NULL handler");
1312       return;
1313     }
1314 
1315   entry = register_pragma_1 (pfile, space, name, false);
1316   if (entry)
1317     {
1318       entry->allow_expansion = allow_expansion;
1319       entry->u.handler = handler;
1320     }
1321 }
1322 
1323 /* Similarly, but create mark the pragma for deferred processing.
1324    When found, a CPP_PRAGMA token will be insertted into the stream
1325    with IDENT in the token->u.pragma slot.  */
1326 void
cpp_register_deferred_pragma(cpp_reader * pfile,const char * space,const char * name,unsigned int ident,bool allow_expansion,bool allow_name_expansion)1327 cpp_register_deferred_pragma (cpp_reader *pfile, const char *space,
1328 			      const char *name, unsigned int ident,
1329 			      bool allow_expansion, bool allow_name_expansion)
1330 {
1331   struct pragma_entry *entry;
1332 
1333   entry = register_pragma_1 (pfile, space, name, allow_name_expansion);
1334   if (entry)
1335     {
1336       entry->is_deferred = true;
1337       entry->allow_expansion = allow_expansion;
1338       entry->u.ident = ident;
1339     }
1340 }
1341 
1342 /* Register the pragmas the preprocessor itself handles.  */
1343 void
_cpp_init_internal_pragmas(cpp_reader * pfile)1344 _cpp_init_internal_pragmas (cpp_reader *pfile)
1345 {
1346   /* Pragmas in the global namespace.  */
1347   register_pragma_internal (pfile, 0, "once", do_pragma_once);
1348   register_pragma_internal (pfile, 0, "push_macro", do_pragma_push_macro);
1349   register_pragma_internal (pfile, 0, "pop_macro", do_pragma_pop_macro);
1350 
1351   /* New GCC-specific pragmas should be put in the GCC namespace.  */
1352   register_pragma_internal (pfile, "GCC", "poison", do_pragma_poison);
1353   register_pragma_internal (pfile, "GCC", "system_header",
1354 			    do_pragma_system_header);
1355   register_pragma_internal (pfile, "GCC", "dependency", do_pragma_dependency);
1356   register_pragma_internal (pfile, "GCC", "warning", do_pragma_warning);
1357   register_pragma_internal (pfile, "GCC", "error", do_pragma_error);
1358 }
1359 
1360 /* Return the number of registered pragmas in PE.  */
1361 
1362 static int
count_registered_pragmas(struct pragma_entry * pe)1363 count_registered_pragmas (struct pragma_entry *pe)
1364 {
1365   int ct = 0;
1366   for (; pe != NULL; pe = pe->next)
1367     {
1368       if (pe->is_nspace)
1369 	ct += count_registered_pragmas (pe->u.space);
1370       ct++;
1371     }
1372   return ct;
1373 }
1374 
1375 /* Save into SD the names of the registered pragmas referenced by PE,
1376    and return a pointer to the next free space in SD.  */
1377 
1378 static char **
save_registered_pragmas(struct pragma_entry * pe,char ** sd)1379 save_registered_pragmas (struct pragma_entry *pe, char **sd)
1380 {
1381   for (; pe != NULL; pe = pe->next)
1382     {
1383       if (pe->is_nspace)
1384 	sd = save_registered_pragmas (pe->u.space, sd);
1385       *sd++ = (char *) xmemdup (HT_STR (&pe->pragma->ident),
1386                                 HT_LEN (&pe->pragma->ident),
1387                                 HT_LEN (&pe->pragma->ident) + 1);
1388     }
1389   return sd;
1390 }
1391 
1392 /* Return a newly-allocated array which saves the names of the
1393    registered pragmas.  */
1394 
1395 char **
_cpp_save_pragma_names(cpp_reader * pfile)1396 _cpp_save_pragma_names (cpp_reader *pfile)
1397 {
1398   int ct = count_registered_pragmas (pfile->pragmas);
1399   char **result = XNEWVEC (char *, ct);
1400   (void) save_registered_pragmas (pfile->pragmas, result);
1401   return result;
1402 }
1403 
1404 /* Restore from SD the names of the registered pragmas referenced by PE,
1405    and return a pointer to the next unused name in SD.  */
1406 
1407 static char **
restore_registered_pragmas(cpp_reader * pfile,struct pragma_entry * pe,char ** sd)1408 restore_registered_pragmas (cpp_reader *pfile, struct pragma_entry *pe,
1409 			    char **sd)
1410 {
1411   for (; pe != NULL; pe = pe->next)
1412     {
1413       if (pe->is_nspace)
1414 	sd = restore_registered_pragmas (pfile, pe->u.space, sd);
1415       pe->pragma = cpp_lookup (pfile, UC *sd, strlen (*sd));
1416       free (*sd);
1417       sd++;
1418     }
1419   return sd;
1420 }
1421 
1422 /* Restore the names of the registered pragmas from SAVED.  */
1423 
1424 void
_cpp_restore_pragma_names(cpp_reader * pfile,char ** saved)1425 _cpp_restore_pragma_names (cpp_reader *pfile, char **saved)
1426 {
1427   (void) restore_registered_pragmas (pfile, pfile->pragmas, saved);
1428   free (saved);
1429 }
1430 
1431 /* Pragmata handling.  We handle some, and pass the rest on to the
1432    front end.  C99 defines three pragmas and says that no macro
1433    expansion is to be performed on them; whether or not macro
1434    expansion happens for other pragmas is implementation defined.
1435    This implementation allows for a mix of both, since GCC did not
1436    traditionally macro expand its (few) pragmas, whereas OpenMP
1437    specifies that macro expansion should happen.  */
1438 static void
do_pragma(cpp_reader * pfile)1439 do_pragma (cpp_reader *pfile)
1440 {
1441   const struct pragma_entry *p = NULL;
1442   const cpp_token *token, *pragma_token;
1443   source_location pragma_token_virt_loc = 0;
1444   cpp_token ns_token;
1445   unsigned int count = 1;
1446 
1447   pfile->state.prevent_expansion++;
1448 
1449   pragma_token = token = cpp_get_token_with_location (pfile,
1450 						      &pragma_token_virt_loc);
1451   ns_token = *token;
1452   if (token->type == CPP_NAME)
1453     {
1454       p = lookup_pragma_entry (pfile->pragmas, token->val.node.node);
1455       if (p && p->is_nspace)
1456 	{
1457 	  bool allow_name_expansion = p->allow_expansion;
1458 	  if (allow_name_expansion)
1459 	    pfile->state.prevent_expansion--;
1460 
1461 	  token = cpp_get_token (pfile);
1462 	  if (token->type == CPP_NAME)
1463 	    p = lookup_pragma_entry (p->u.space, token->val.node.node);
1464 	  else
1465 	    p = NULL;
1466 	  if (allow_name_expansion)
1467 	    pfile->state.prevent_expansion++;
1468 	  count = 2;
1469 	}
1470     }
1471 
1472   if (p)
1473     {
1474       if (p->is_deferred)
1475 	{
1476 	  pfile->directive_result.src_loc = pragma_token_virt_loc;
1477 	  pfile->directive_result.type = CPP_PRAGMA;
1478 	  pfile->directive_result.flags = pragma_token->flags;
1479 	  pfile->directive_result.val.pragma = p->u.ident;
1480 	  pfile->state.in_deferred_pragma = true;
1481 	  pfile->state.pragma_allow_expansion = p->allow_expansion;
1482 	  if (!p->allow_expansion)
1483 	    pfile->state.prevent_expansion++;
1484 	}
1485       else
1486 	{
1487 	  /* Since the handler below doesn't get the line number, that
1488 	     it might need for diagnostics, make sure it has the right
1489 	     numbers in place.  */
1490 	  if (pfile->cb.line_change)
1491 	    (*pfile->cb.line_change) (pfile, pragma_token, false);
1492 	  if (p->allow_expansion)
1493 	    pfile->state.prevent_expansion--;
1494 	  (*p->u.handler) (pfile);
1495 	  if (p->allow_expansion)
1496 	    pfile->state.prevent_expansion++;
1497 	}
1498     }
1499   else if (pfile->cb.def_pragma)
1500     {
1501       if (count == 1 || pfile->context->prev == NULL)
1502 	_cpp_backup_tokens (pfile, count);
1503       else
1504 	{
1505 	  /* Invalid name comes from macro expansion, _cpp_backup_tokens
1506 	     won't allow backing 2 tokens.  */
1507 	  /* ??? The token buffer is leaked.  Perhaps if def_pragma hook
1508 	     reads both tokens, we could perhaps free it, but if it doesn't,
1509 	     we don't know the exact lifespan.  */
1510 	  cpp_token *toks = XNEWVEC (cpp_token, 2);
1511 	  toks[0] = ns_token;
1512 	  toks[0].flags |= NO_EXPAND;
1513 	  toks[1] = *token;
1514 	  toks[1].flags |= NO_EXPAND;
1515 	  _cpp_push_token_context (pfile, NULL, toks, 2);
1516 	}
1517       pfile->cb.def_pragma (pfile, pfile->directive_line);
1518     }
1519 
1520   pfile->state.prevent_expansion--;
1521 }
1522 
1523 /* Handle #pragma once.  */
1524 static void
do_pragma_once(cpp_reader * pfile)1525 do_pragma_once (cpp_reader *pfile)
1526 {
1527   if (cpp_in_primary_file (pfile))
1528     cpp_error (pfile, CPP_DL_WARNING, "#pragma once in main file");
1529 
1530   check_eol (pfile, false);
1531   _cpp_mark_file_once_only (pfile, pfile->buffer->file);
1532 }
1533 
1534 /* Handle #pragma push_macro(STRING).  */
1535 static void
do_pragma_push_macro(cpp_reader * pfile)1536 do_pragma_push_macro (cpp_reader *pfile)
1537 {
1538   cpp_hashnode *node;
1539   size_t defnlen;
1540   const uchar *defn = NULL;
1541   char *macroname, *dest;
1542   const char *limit, *src;
1543   const cpp_token *txt;
1544   struct def_pragma_macro *c;
1545 
1546   txt = get__Pragma_string (pfile);
1547   if (!txt)
1548     {
1549       source_location src_loc = pfile->cur_token[-1].src_loc;
1550       cpp_error_with_line (pfile, CPP_DL_ERROR, src_loc, 0,
1551 		 "invalid #pragma push_macro directive");
1552       check_eol (pfile, false);
1553       skip_rest_of_line (pfile);
1554       return;
1555     }
1556   dest = macroname = (char *) alloca (txt->val.str.len + 2);
1557   src = (const char *) (txt->val.str.text + 1 + (txt->val.str.text[0] == 'L'));
1558   limit = (const char *) (txt->val.str.text + txt->val.str.len - 1);
1559   while (src < limit)
1560     {
1561       /* We know there is a character following the backslash.  */
1562       if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1563 	src++;
1564       *dest++ = *src++;
1565     }
1566   *dest = 0;
1567   check_eol (pfile, false);
1568   skip_rest_of_line (pfile);
1569   c = XNEW (struct def_pragma_macro);
1570   memset (c, 0, sizeof (struct def_pragma_macro));
1571   c->name = XNEWVAR (char, strlen (macroname) + 1);
1572   strcpy (c->name, macroname);
1573   c->next = pfile->pushed_macros;
1574   node = _cpp_lex_identifier (pfile, c->name);
1575   if (node->type == NT_VOID)
1576     c->is_undef = 1;
1577   else if (node->type == NT_MACRO && (node->flags & NODE_BUILTIN))
1578     c->is_builtin = 1;
1579   else
1580     {
1581       defn = cpp_macro_definition (pfile, node);
1582       defnlen = ustrlen (defn);
1583       c->definition = XNEWVEC (uchar, defnlen + 2);
1584       c->definition[defnlen] = '\n';
1585       c->definition[defnlen + 1] = 0;
1586       c->line = node->value.macro->line;
1587       c->syshdr = node->value.macro->syshdr;
1588       c->used = node->value.macro->used;
1589       memcpy (c->definition, defn, defnlen);
1590     }
1591 
1592   pfile->pushed_macros = c;
1593 }
1594 
1595 /* Handle #pragma pop_macro(STRING).  */
1596 static void
do_pragma_pop_macro(cpp_reader * pfile)1597 do_pragma_pop_macro (cpp_reader *pfile)
1598 {
1599   char *macroname, *dest;
1600   const char *limit, *src;
1601   const cpp_token *txt;
1602   struct def_pragma_macro *l = NULL, *c = pfile->pushed_macros;
1603   txt = get__Pragma_string (pfile);
1604   if (!txt)
1605     {
1606       source_location src_loc = pfile->cur_token[-1].src_loc;
1607       cpp_error_with_line (pfile, CPP_DL_ERROR, src_loc, 0,
1608 		 "invalid #pragma pop_macro directive");
1609       check_eol (pfile, false);
1610       skip_rest_of_line (pfile);
1611       return;
1612     }
1613   dest = macroname = (char *) alloca (txt->val.str.len + 2);
1614   src = (const char *) (txt->val.str.text + 1 + (txt->val.str.text[0] == 'L'));
1615   limit = (const char *) (txt->val.str.text + txt->val.str.len - 1);
1616   while (src < limit)
1617     {
1618       /* We know there is a character following the backslash.  */
1619       if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1620 	src++;
1621       *dest++ = *src++;
1622     }
1623   *dest = 0;
1624   check_eol (pfile, false);
1625   skip_rest_of_line (pfile);
1626 
1627   while (c != NULL)
1628     {
1629       if (!strcmp (c->name, macroname))
1630 	{
1631 	  if (!l)
1632 	    pfile->pushed_macros = c->next;
1633 	  else
1634 	    l->next = c->next;
1635 	  cpp_pop_definition (pfile, c);
1636 	  free (c->definition);
1637 	  free (c->name);
1638 	  free (c);
1639 	  break;
1640 	}
1641       l = c;
1642       c = c->next;
1643     }
1644 }
1645 
1646 /* Handle #pragma GCC poison, to poison one or more identifiers so
1647    that the lexer produces a hard error for each subsequent usage.  */
1648 static void
do_pragma_poison(cpp_reader * pfile)1649 do_pragma_poison (cpp_reader *pfile)
1650 {
1651   const cpp_token *tok;
1652   cpp_hashnode *hp;
1653 
1654   pfile->state.poisoned_ok = 1;
1655   for (;;)
1656     {
1657       tok = _cpp_lex_token (pfile);
1658       if (tok->type == CPP_EOF)
1659 	break;
1660       if (tok->type != CPP_NAME)
1661 	{
1662 	  cpp_error (pfile, CPP_DL_ERROR,
1663 		     "invalid #pragma GCC poison directive");
1664 	  break;
1665 	}
1666 
1667       hp = tok->val.node.node;
1668       if (hp->flags & NODE_POISONED)
1669 	continue;
1670 
1671       if (hp->type == NT_MACRO)
1672 	cpp_error (pfile, CPP_DL_WARNING, "poisoning existing macro \"%s\"",
1673 		   NODE_NAME (hp));
1674       _cpp_free_definition (hp);
1675       hp->flags |= NODE_POISONED | NODE_DIAGNOSTIC;
1676     }
1677   pfile->state.poisoned_ok = 0;
1678 }
1679 
1680 /* Mark the current header as a system header.  This will suppress
1681    some categories of warnings (notably those from -pedantic).  It is
1682    intended for use in system libraries that cannot be implemented in
1683    conforming C, but cannot be certain that their headers appear in a
1684    system include directory.  To prevent abuse, it is rejected in the
1685    primary source file.  */
1686 static void
do_pragma_system_header(cpp_reader * pfile)1687 do_pragma_system_header (cpp_reader *pfile)
1688 {
1689   if (cpp_in_primary_file (pfile))
1690     cpp_error (pfile, CPP_DL_WARNING,
1691 	       "#pragma system_header ignored outside include file");
1692   else
1693     {
1694       check_eol (pfile, false);
1695       skip_rest_of_line (pfile);
1696       cpp_make_system_header (pfile, 1, 0);
1697     }
1698 }
1699 
1700 /* Check the modified date of the current include file against a specified
1701    file. Issue a diagnostic, if the specified file is newer. We use this to
1702    determine if a fixed header should be refixed.  */
1703 static void
do_pragma_dependency(cpp_reader * pfile)1704 do_pragma_dependency (cpp_reader *pfile)
1705 {
1706   const char *fname;
1707   int angle_brackets, ordering;
1708   source_location location;
1709 
1710   fname = parse_include (pfile, &angle_brackets, NULL, &location);
1711   if (!fname)
1712     return;
1713 
1714   ordering = _cpp_compare_file_date (pfile, fname, angle_brackets);
1715   if (ordering < 0)
1716     cpp_error (pfile, CPP_DL_WARNING, "cannot find source file %s", fname);
1717   else if (ordering > 0)
1718     {
1719       cpp_error (pfile, CPP_DL_WARNING,
1720 		 "current file is older than %s", fname);
1721       if (cpp_get_token (pfile)->type != CPP_EOF)
1722 	{
1723 	  _cpp_backup_tokens (pfile, 1);
1724 	  do_diagnostic (pfile, CPP_DL_WARNING, 0, 0);
1725 	}
1726     }
1727 
1728   free ((void *) fname);
1729 }
1730 
1731 /* Issue a diagnostic with the message taken from the pragma.  If
1732    ERROR is true, the diagnostic is a warning, otherwise, it is an
1733    error.  */
1734 static void
do_pragma_warning_or_error(cpp_reader * pfile,bool error)1735 do_pragma_warning_or_error (cpp_reader *pfile, bool error)
1736 {
1737   const cpp_token *tok = _cpp_lex_token (pfile);
1738   cpp_string str;
1739   if (tok->type != CPP_STRING
1740       || !cpp_interpret_string_notranslate (pfile, &tok->val.str, 1, &str,
1741 					    CPP_STRING)
1742       || str.len == 0)
1743     {
1744       cpp_error (pfile, CPP_DL_ERROR, "invalid \"#pragma GCC %s\" directive",
1745 		 error ? "error" : "warning");
1746       return;
1747     }
1748   cpp_error (pfile, error ? CPP_DL_ERROR : CPP_DL_WARNING,
1749 	     "%s", str.text);
1750   free ((void *)str.text);
1751 }
1752 
1753 /* Issue a warning diagnostic.  */
1754 static void
do_pragma_warning(cpp_reader * pfile)1755 do_pragma_warning (cpp_reader *pfile)
1756 {
1757   do_pragma_warning_or_error (pfile, false);
1758 }
1759 
1760 /* Issue an error diagnostic.  */
1761 static void
do_pragma_error(cpp_reader * pfile)1762 do_pragma_error (cpp_reader *pfile)
1763 {
1764   do_pragma_warning_or_error (pfile, true);
1765 }
1766 
1767 /* Get a token but skip padding.  */
1768 static const cpp_token *
get_token_no_padding(cpp_reader * pfile)1769 get_token_no_padding (cpp_reader *pfile)
1770 {
1771   for (;;)
1772     {
1773       const cpp_token *result = cpp_get_token (pfile);
1774       if (result->type != CPP_PADDING)
1775 	return result;
1776     }
1777 }
1778 
1779 /* Check syntax is "(string-literal)".  Returns the string on success,
1780    or NULL on failure.  */
1781 static const cpp_token *
get__Pragma_string(cpp_reader * pfile)1782 get__Pragma_string (cpp_reader *pfile)
1783 {
1784   const cpp_token *string;
1785   const cpp_token *paren;
1786 
1787   paren = get_token_no_padding (pfile);
1788   if (paren->type == CPP_EOF)
1789     _cpp_backup_tokens (pfile, 1);
1790   if (paren->type != CPP_OPEN_PAREN)
1791     return NULL;
1792 
1793   string = get_token_no_padding (pfile);
1794   if (string->type == CPP_EOF)
1795     _cpp_backup_tokens (pfile, 1);
1796   if (string->type != CPP_STRING && string->type != CPP_WSTRING
1797       && string->type != CPP_STRING32 && string->type != CPP_STRING16
1798       && string->type != CPP_UTF8STRING)
1799     return NULL;
1800 
1801   paren = get_token_no_padding (pfile);
1802   if (paren->type == CPP_EOF)
1803     _cpp_backup_tokens (pfile, 1);
1804   if (paren->type != CPP_CLOSE_PAREN)
1805     return NULL;
1806 
1807   return string;
1808 }
1809 
1810 /* Destringize IN into a temporary buffer, by removing the first \ of
1811    \" and \\ sequences, and process the result as a #pragma directive.  */
1812 static void
destringize_and_run(cpp_reader * pfile,const cpp_string * in,source_location expansion_loc)1813 destringize_and_run (cpp_reader *pfile, const cpp_string *in,
1814 		     source_location expansion_loc)
1815 {
1816   const unsigned char *src, *limit;
1817   char *dest, *result;
1818   cpp_context *saved_context;
1819   cpp_token *saved_cur_token;
1820   tokenrun *saved_cur_run;
1821   cpp_token *toks;
1822   int count;
1823   const struct directive *save_directive;
1824 
1825   dest = result = (char *) alloca (in->len - 1);
1826   src = in->text + 1 + (in->text[0] == 'L');
1827   limit = in->text + in->len - 1;
1828   while (src < limit)
1829     {
1830       /* We know there is a character following the backslash.  */
1831       if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1832 	src++;
1833       *dest++ = *src++;
1834     }
1835   *dest = '\n';
1836 
1837   /* Ugh; an awful kludge.  We are really not set up to be lexing
1838      tokens when in the middle of a macro expansion.  Use a new
1839      context to force cpp_get_token to lex, and so skip_rest_of_line
1840      doesn't go beyond the end of the text.  Also, remember the
1841      current lexing position so we can return to it later.
1842 
1843      Something like line-at-a-time lexing should remove the need for
1844      this.  */
1845   saved_context = pfile->context;
1846   saved_cur_token = pfile->cur_token;
1847   saved_cur_run = pfile->cur_run;
1848 
1849   pfile->context = XCNEW (cpp_context);
1850 
1851   /* Inline run_directive, since we need to delay the _cpp_pop_buffer
1852      until we've read all of the tokens that we want.  */
1853   cpp_push_buffer (pfile, (const uchar *) result, dest - result,
1854 		   /* from_stage3 */ true);
1855   /* ??? Antique Disgusting Hack.  What does this do?  */
1856   if (pfile->buffer->prev)
1857     pfile->buffer->file = pfile->buffer->prev->file;
1858 
1859   start_directive (pfile);
1860   _cpp_clean_line (pfile);
1861   save_directive = pfile->directive;
1862   pfile->directive = &dtable[T_PRAGMA];
1863   do_pragma (pfile);
1864   end_directive (pfile, 1);
1865   pfile->directive = save_directive;
1866 
1867   /* We always insert at least one token, the directive result.  It'll
1868      either be a CPP_PADDING or a CPP_PRAGMA.  In the later case, we
1869      need to insert *all* of the tokens, including the CPP_PRAGMA_EOL.  */
1870 
1871   /* If we're not handling the pragma internally, read all of the tokens from
1872      the string buffer now, while the string buffer is still installed.  */
1873   /* ??? Note that the token buffer allocated here is leaked.  It's not clear
1874      to me what the true lifespan of the tokens are.  It would appear that
1875      the lifespan is the entire parse of the main input stream, in which case
1876      this may not be wrong.  */
1877   if (pfile->directive_result.type == CPP_PRAGMA)
1878     {
1879       int maxcount;
1880 
1881       count = 1;
1882       maxcount = 50;
1883       toks = XNEWVEC (cpp_token, maxcount);
1884       toks[0] = pfile->directive_result;
1885 
1886       do
1887 	{
1888 	  if (count == maxcount)
1889 	    {
1890 	      maxcount = maxcount * 3 / 2;
1891 	      toks = XRESIZEVEC (cpp_token, toks, maxcount);
1892 	    }
1893 	  toks[count] = *cpp_get_token (pfile);
1894 	  /* _Pragma is a builtin, so we're not within a macro-map, and so
1895 	     the token locations are set to bogus ordinary locations
1896 	     near to, but after that of the "_Pragma".
1897 	     Paper over this by setting them equal to the location of the
1898 	     _Pragma itself (PR preprocessor/69126).  */
1899 	  toks[count].src_loc = expansion_loc;
1900 	  /* Macros have been already expanded by cpp_get_token
1901 	     if the pragma allowed expansion.  */
1902 	  toks[count++].flags |= NO_EXPAND;
1903 	}
1904       while (toks[count-1].type != CPP_PRAGMA_EOL);
1905     }
1906   else
1907     {
1908       count = 1;
1909       toks = XNEW (cpp_token);
1910       toks[0] = pfile->directive_result;
1911 
1912       /* If we handled the entire pragma internally, make sure we get the
1913 	 line number correct for the next token.  */
1914       if (pfile->cb.line_change)
1915 	pfile->cb.line_change (pfile, pfile->cur_token, false);
1916     }
1917 
1918   /* Finish inlining run_directive.  */
1919   pfile->buffer->file = NULL;
1920   _cpp_pop_buffer (pfile);
1921 
1922   /* Reset the old macro state before ...  */
1923   XDELETE (pfile->context);
1924   pfile->context = saved_context;
1925   pfile->cur_token = saved_cur_token;
1926   pfile->cur_run = saved_cur_run;
1927 
1928   /* ... inserting the new tokens we collected.  */
1929   _cpp_push_token_context (pfile, NULL, toks, count);
1930 }
1931 
1932 /* Handle the _Pragma operator.  Return 0 on error, 1 if ok.  */
1933 int
_cpp_do__Pragma(cpp_reader * pfile,source_location expansion_loc)1934 _cpp_do__Pragma (cpp_reader *pfile, source_location expansion_loc)
1935 {
1936   const cpp_token *string = get__Pragma_string (pfile);
1937   pfile->directive_result.type = CPP_PADDING;
1938 
1939   if (string)
1940     {
1941       destringize_and_run (pfile, &string->val.str, expansion_loc);
1942       return 1;
1943     }
1944   cpp_error (pfile, CPP_DL_ERROR,
1945 	     "_Pragma takes a parenthesized string literal");
1946   return 0;
1947 }
1948 
1949 /* Handle #ifdef.  */
1950 static void
do_ifdef(cpp_reader * pfile)1951 do_ifdef (cpp_reader *pfile)
1952 {
1953   int skip = 1;
1954 
1955   if (! pfile->state.skipping)
1956     {
1957       cpp_hashnode *node = lex_macro_node (pfile, false);
1958 
1959       if (node)
1960 	{
1961 	  /* Do not treat conditional macros as being defined.  This is due to
1962 	     the powerpc and spu ports using conditional macros for 'vector',
1963 	     'bool', and 'pixel' to act as conditional keywords.  This messes
1964 	     up tests like #ifndef bool.  */
1965 	  skip = (node->type != NT_MACRO
1966 		  || ((node->flags & NODE_CONDITIONAL) != 0));
1967 	  _cpp_mark_macro_used (node);
1968 	  if (!(node->flags & NODE_USED))
1969 	    {
1970 	      node->flags |= NODE_USED;
1971 	      if (node->type == NT_MACRO)
1972 		{
1973 		  if ((node->flags & NODE_BUILTIN)
1974 		      && pfile->cb.user_builtin_macro)
1975 		    pfile->cb.user_builtin_macro (pfile, node);
1976 		  if (pfile->cb.used_define)
1977 		    pfile->cb.used_define (pfile, pfile->directive_line, node);
1978 		}
1979 	      else
1980 		{
1981 		  if (pfile->cb.used_undef)
1982 		    pfile->cb.used_undef (pfile, pfile->directive_line, node);
1983 		}
1984 	    }
1985 	  if (pfile->cb.used)
1986 	    pfile->cb.used (pfile, pfile->directive_line, node);
1987 	  check_eol (pfile, false);
1988 	}
1989     }
1990 
1991   push_conditional (pfile, skip, T_IFDEF, 0);
1992 }
1993 
1994 /* Handle #ifndef.  */
1995 static void
do_ifndef(cpp_reader * pfile)1996 do_ifndef (cpp_reader *pfile)
1997 {
1998   int skip = 1;
1999   cpp_hashnode *node = 0;
2000 
2001   if (! pfile->state.skipping)
2002     {
2003       node = lex_macro_node (pfile, false);
2004 
2005       if (node)
2006 	{
2007 	  /* Do not treat conditional macros as being defined.  This is due to
2008 	     the powerpc and spu ports using conditional macros for 'vector',
2009 	     'bool', and 'pixel' to act as conditional keywords.  This messes
2010 	     up tests like #ifndef bool.  */
2011 	  skip = (node->type == NT_MACRO
2012 		  && ((node->flags & NODE_CONDITIONAL) == 0));
2013 	  _cpp_mark_macro_used (node);
2014 	  if (!(node->flags & NODE_USED))
2015 	    {
2016 	      node->flags |= NODE_USED;
2017 	      if (node->type == NT_MACRO)
2018 		{
2019 		  if ((node->flags & NODE_BUILTIN)
2020 		      && pfile->cb.user_builtin_macro)
2021 		    pfile->cb.user_builtin_macro (pfile, node);
2022 		  if (pfile->cb.used_define)
2023 		    pfile->cb.used_define (pfile, pfile->directive_line, node);
2024 		}
2025 	      else
2026 		{
2027 		  if (pfile->cb.used_undef)
2028 		    pfile->cb.used_undef (pfile, pfile->directive_line, node);
2029 		}
2030 	    }
2031 	  if (pfile->cb.used)
2032 	    pfile->cb.used (pfile, pfile->directive_line, node);
2033 	  check_eol (pfile, false);
2034 	}
2035     }
2036 
2037   push_conditional (pfile, skip, T_IFNDEF, node);
2038 }
2039 
2040 /* _cpp_parse_expr puts a macro in a "#if !defined ()" expression in
2041    pfile->mi_ind_cmacro so we can handle multiple-include
2042    optimizations.  If macro expansion occurs in the expression, we
2043    cannot treat it as a controlling conditional, since the expansion
2044    could change in the future.  That is handled by cpp_get_token.  */
2045 static void
do_if(cpp_reader * pfile)2046 do_if (cpp_reader *pfile)
2047 {
2048   int skip = 1;
2049 
2050   if (! pfile->state.skipping)
2051     skip = _cpp_parse_expr (pfile, true) == false;
2052 
2053   push_conditional (pfile, skip, T_IF, pfile->mi_ind_cmacro);
2054 }
2055 
2056 /* Flip skipping state if appropriate and continue without changing
2057    if_stack; this is so that the error message for missing #endif's
2058    etc. will point to the original #if.  */
2059 static void
do_else(cpp_reader * pfile)2060 do_else (cpp_reader *pfile)
2061 {
2062   cpp_buffer *buffer = pfile->buffer;
2063   struct if_stack *ifs = buffer->if_stack;
2064 
2065   if (ifs == NULL)
2066     cpp_error (pfile, CPP_DL_ERROR, "#else without #if");
2067   else
2068     {
2069       if (ifs->type == T_ELSE)
2070 	{
2071 	  cpp_error (pfile, CPP_DL_ERROR, "#else after #else");
2072 	  cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2073 			       "the conditional began here");
2074 	}
2075       ifs->type = T_ELSE;
2076 
2077       /* Skip any future (erroneous) #elses or #elifs.  */
2078       pfile->state.skipping = ifs->skip_elses;
2079       ifs->skip_elses = true;
2080 
2081       /* Invalidate any controlling macro.  */
2082       ifs->mi_cmacro = 0;
2083 
2084       /* Only check EOL if was not originally skipping.  */
2085       if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
2086 	check_eol_endif_labels (pfile);
2087     }
2088 }
2089 
2090 /* Handle a #elif directive by not changing if_stack either.  See the
2091    comment above do_else.  */
2092 static void
do_elif(cpp_reader * pfile)2093 do_elif (cpp_reader *pfile)
2094 {
2095   cpp_buffer *buffer = pfile->buffer;
2096   struct if_stack *ifs = buffer->if_stack;
2097 
2098   if (ifs == NULL)
2099     cpp_error (pfile, CPP_DL_ERROR, "#elif without #if");
2100   else
2101     {
2102       if (ifs->type == T_ELSE)
2103 	{
2104 	  cpp_error (pfile, CPP_DL_ERROR, "#elif after #else");
2105 	  cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2106 			       "the conditional began here");
2107 	}
2108       ifs->type = T_ELIF;
2109 
2110       /* See DR#412: "Only the first group whose control condition
2111 	 evaluates to true (nonzero) is processed; any following groups
2112 	 are skipped and their controlling directives are processed as
2113 	 if they were in a group that is skipped."  */
2114       if (ifs->skip_elses)
2115 	pfile->state.skipping = 1;
2116       else
2117 	{
2118 	  pfile->state.skipping = ! _cpp_parse_expr (pfile, false);
2119 	  ifs->skip_elses = ! pfile->state.skipping;
2120 	}
2121 
2122       /* Invalidate any controlling macro.  */
2123       ifs->mi_cmacro = 0;
2124     }
2125 }
2126 
2127 /* #endif pops the if stack and resets pfile->state.skipping.  */
2128 static void
do_endif(cpp_reader * pfile)2129 do_endif (cpp_reader *pfile)
2130 {
2131   cpp_buffer *buffer = pfile->buffer;
2132   struct if_stack *ifs = buffer->if_stack;
2133 
2134   if (ifs == NULL)
2135     cpp_error (pfile, CPP_DL_ERROR, "#endif without #if");
2136   else
2137     {
2138       /* Only check EOL if was not originally skipping.  */
2139       if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
2140 	check_eol_endif_labels (pfile);
2141 
2142       /* If potential control macro, we go back outside again.  */
2143       if (ifs->next == 0 && ifs->mi_cmacro)
2144 	{
2145 	  pfile->mi_valid = true;
2146 	  pfile->mi_cmacro = ifs->mi_cmacro;
2147 	}
2148 
2149       buffer->if_stack = ifs->next;
2150       pfile->state.skipping = ifs->was_skipping;
2151       obstack_free (&pfile->buffer_ob, ifs);
2152     }
2153 }
2154 
2155 /* Push an if_stack entry for a preprocessor conditional, and set
2156    pfile->state.skipping to SKIP.  If TYPE indicates the conditional
2157    is #if or #ifndef, CMACRO is a potentially controlling macro, and
2158    we need to check here that we are at the top of the file.  */
2159 static void
push_conditional(cpp_reader * pfile,int skip,int type,const cpp_hashnode * cmacro)2160 push_conditional (cpp_reader *pfile, int skip, int type,
2161 		  const cpp_hashnode *cmacro)
2162 {
2163   struct if_stack *ifs;
2164   cpp_buffer *buffer = pfile->buffer;
2165 
2166   ifs = XOBNEW (&pfile->buffer_ob, struct if_stack);
2167   ifs->line = pfile->directive_line;
2168   ifs->next = buffer->if_stack;
2169   ifs->skip_elses = pfile->state.skipping || !skip;
2170   ifs->was_skipping = pfile->state.skipping;
2171   ifs->type = type;
2172   /* This condition is effectively a test for top-of-file.  */
2173   if (pfile->mi_valid && pfile->mi_cmacro == 0)
2174     ifs->mi_cmacro = cmacro;
2175   else
2176     ifs->mi_cmacro = 0;
2177 
2178   pfile->state.skipping = skip;
2179   buffer->if_stack = ifs;
2180 }
2181 
2182 /* Read the tokens of the answer into the macro pool, in a directive
2183    of type TYPE.  Only commit the memory if we intend it as permanent
2184    storage, i.e. the #assert case.  Returns 0 on success, and sets
2185    ANSWERP to point to the answer.  PRED_LOC is the location of the
2186    predicate.  */
2187 static int
parse_answer(cpp_reader * pfile,struct answer ** answerp,int type,source_location pred_loc)2188 parse_answer (cpp_reader *pfile, struct answer **answerp, int type,
2189 	      source_location pred_loc)
2190 {
2191   const cpp_token *paren;
2192   struct answer *answer;
2193   unsigned int acount;
2194 
2195   /* In a conditional, it is legal to not have an open paren.  We
2196      should save the following token in this case.  */
2197   paren = cpp_get_token (pfile);
2198 
2199   /* If not a paren, see if we're OK.  */
2200   if (paren->type != CPP_OPEN_PAREN)
2201     {
2202       /* In a conditional no answer is a test for any answer.  It
2203          could be followed by any token.  */
2204       if (type == T_IF)
2205 	{
2206 	  _cpp_backup_tokens (pfile, 1);
2207 	  return 0;
2208 	}
2209 
2210       /* #unassert with no answer is valid - it removes all answers.  */
2211       if (type == T_UNASSERT && paren->type == CPP_EOF)
2212 	return 0;
2213 
2214       cpp_error_with_line (pfile, CPP_DL_ERROR, pred_loc, 0,
2215 			   "missing '(' after predicate");
2216       return 1;
2217     }
2218 
2219   for (acount = 0;; acount++)
2220     {
2221       size_t room_needed;
2222       const cpp_token *token = cpp_get_token (pfile);
2223       cpp_token *dest;
2224 
2225       if (token->type == CPP_CLOSE_PAREN)
2226 	break;
2227 
2228       if (token->type == CPP_EOF)
2229 	{
2230 	  cpp_error (pfile, CPP_DL_ERROR, "missing ')' to complete answer");
2231 	  return 1;
2232 	}
2233 
2234       /* struct answer includes the space for one token.  */
2235       room_needed = (sizeof (struct answer) + acount * sizeof (cpp_token));
2236 
2237       if (BUFF_ROOM (pfile->a_buff) < room_needed)
2238 	_cpp_extend_buff (pfile, &pfile->a_buff, sizeof (struct answer));
2239 
2240       dest = &((struct answer *) BUFF_FRONT (pfile->a_buff))->first[acount];
2241       *dest = *token;
2242 
2243       /* Drop whitespace at start, for answer equivalence purposes.  */
2244       if (acount == 0)
2245 	dest->flags &= ~PREV_WHITE;
2246     }
2247 
2248   if (acount == 0)
2249     {
2250       cpp_error (pfile, CPP_DL_ERROR, "predicate's answer is empty");
2251       return 1;
2252     }
2253 
2254   answer = (struct answer *) BUFF_FRONT (pfile->a_buff);
2255   answer->count = acount;
2256   answer->next = NULL;
2257   *answerp = answer;
2258 
2259   return 0;
2260 }
2261 
2262 /* Parses an assertion directive of type TYPE, returning a pointer to
2263    the hash node of the predicate, or 0 on error.  If an answer was
2264    supplied, it is placed in ANSWERP, otherwise it is set to 0.  */
2265 static cpp_hashnode *
parse_assertion(cpp_reader * pfile,struct answer ** answerp,int type)2266 parse_assertion (cpp_reader *pfile, struct answer **answerp, int type)
2267 {
2268   cpp_hashnode *result = 0;
2269   const cpp_token *predicate;
2270 
2271   /* We don't expand predicates or answers.  */
2272   pfile->state.prevent_expansion++;
2273 
2274   *answerp = 0;
2275   predicate = cpp_get_token (pfile);
2276   if (predicate->type == CPP_EOF)
2277     cpp_error (pfile, CPP_DL_ERROR, "assertion without predicate");
2278   else if (predicate->type != CPP_NAME)
2279     cpp_error_with_line (pfile, CPP_DL_ERROR, predicate->src_loc, 0,
2280 			 "predicate must be an identifier");
2281   else if (parse_answer (pfile, answerp, type, predicate->src_loc) == 0)
2282     {
2283       unsigned int len = NODE_LEN (predicate->val.node.node);
2284       unsigned char *sym = (unsigned char *) alloca (len + 1);
2285 
2286       /* Prefix '#' to get it out of macro namespace.  */
2287       sym[0] = '#';
2288       memcpy (sym + 1, NODE_NAME (predicate->val.node.node), len);
2289       result = cpp_lookup (pfile, sym, len + 1);
2290     }
2291 
2292   pfile->state.prevent_expansion--;
2293   return result;
2294 }
2295 
2296 /* Returns a pointer to the pointer to CANDIDATE in the answer chain,
2297    or a pointer to NULL if the answer is not in the chain.  */
2298 static struct answer **
find_answer(cpp_hashnode * node,const struct answer * candidate)2299 find_answer (cpp_hashnode *node, const struct answer *candidate)
2300 {
2301   unsigned int i;
2302   struct answer **result;
2303 
2304   for (result = &node->value.answers; *result; result = &(*result)->next)
2305     {
2306       struct answer *answer = *result;
2307 
2308       if (answer->count == candidate->count)
2309 	{
2310 	  for (i = 0; i < answer->count; i++)
2311 	    if (! _cpp_equiv_tokens (&answer->first[i], &candidate->first[i]))
2312 	      break;
2313 
2314 	  if (i == answer->count)
2315 	    break;
2316 	}
2317     }
2318 
2319   return result;
2320 }
2321 
2322 /* Test an assertion within a preprocessor conditional.  Returns
2323    nonzero on failure, zero on success.  On success, the result of
2324    the test is written into VALUE, otherwise the value 0.  */
2325 int
_cpp_test_assertion(cpp_reader * pfile,unsigned int * value)2326 _cpp_test_assertion (cpp_reader *pfile, unsigned int *value)
2327 {
2328   struct answer *answer;
2329   cpp_hashnode *node;
2330 
2331   node = parse_assertion (pfile, &answer, T_IF);
2332 
2333   /* For recovery, an erroneous assertion expression is handled as a
2334      failing assertion.  */
2335   *value = 0;
2336 
2337   if (node)
2338     *value = (node->type == NT_ASSERTION &&
2339 	      (answer == 0 || *find_answer (node, answer) != 0));
2340   else if (pfile->cur_token[-1].type == CPP_EOF)
2341     _cpp_backup_tokens (pfile, 1);
2342 
2343   /* We don't commit the memory for the answer - it's temporary only.  */
2344   return node == 0;
2345 }
2346 
2347 /* Handle #assert.  */
2348 static void
do_assert(cpp_reader * pfile)2349 do_assert (cpp_reader *pfile)
2350 {
2351   struct answer *new_answer;
2352   cpp_hashnode *node;
2353 
2354   node = parse_assertion (pfile, &new_answer, T_ASSERT);
2355   if (node)
2356     {
2357       size_t answer_size;
2358 
2359       /* Place the new answer in the answer list.  First check there
2360          is not a duplicate.  */
2361       new_answer->next = 0;
2362       if (node->type == NT_ASSERTION)
2363 	{
2364 	  if (*find_answer (node, new_answer))
2365 	    {
2366 	      cpp_error (pfile, CPP_DL_WARNING, "\"%s\" re-asserted",
2367 			 NODE_NAME (node) + 1);
2368 	      return;
2369 	    }
2370 	  new_answer->next = node->value.answers;
2371 	}
2372 
2373       answer_size = sizeof (struct answer) + ((new_answer->count - 1)
2374 					      * sizeof (cpp_token));
2375       /* Commit or allocate storage for the object.  */
2376       if (pfile->hash_table->alloc_subobject)
2377 	{
2378 	  struct answer *temp_answer = new_answer;
2379 	  new_answer = (struct answer *) pfile->hash_table->alloc_subobject
2380             (answer_size);
2381 	  memcpy (new_answer, temp_answer, answer_size);
2382 	}
2383       else
2384 	BUFF_FRONT (pfile->a_buff) += answer_size;
2385 
2386       node->type = NT_ASSERTION;
2387       node->value.answers = new_answer;
2388       check_eol (pfile, false);
2389     }
2390 }
2391 
2392 /* Handle #unassert.  */
2393 static void
do_unassert(cpp_reader * pfile)2394 do_unassert (cpp_reader *pfile)
2395 {
2396   cpp_hashnode *node;
2397   struct answer *answer;
2398 
2399   node = parse_assertion (pfile, &answer, T_UNASSERT);
2400   /* It isn't an error to #unassert something that isn't asserted.  */
2401   if (node && node->type == NT_ASSERTION)
2402     {
2403       if (answer)
2404 	{
2405 	  struct answer **p = find_answer (node, answer), *temp;
2406 
2407 	  /* Remove the answer from the list.  */
2408 	  temp = *p;
2409 	  if (temp)
2410 	    *p = temp->next;
2411 
2412 	  /* Did we free the last answer?  */
2413 	  if (node->value.answers == 0)
2414 	    node->type = NT_VOID;
2415 
2416 	  check_eol (pfile, false);
2417 	}
2418       else
2419 	_cpp_free_definition (node);
2420     }
2421 
2422   /* We don't commit the memory for the answer - it's temporary only.  */
2423 }
2424 
2425 /* These are for -D, -U, -A.  */
2426 
2427 /* Process the string STR as if it appeared as the body of a #define.
2428    If STR is just an identifier, define it with value 1.
2429    If STR has anything after the identifier, then it should
2430    be identifier=definition.  */
2431 void
cpp_define(cpp_reader * pfile,const char * str)2432 cpp_define (cpp_reader *pfile, const char *str)
2433 {
2434   char *buf;
2435   const char *p;
2436   size_t count;
2437 
2438   /* Copy the entire option so we can modify it.
2439      Change the first "=" in the string to a space.  If there is none,
2440      tack " 1" on the end.  */
2441 
2442   count = strlen (str);
2443   buf = (char *) alloca (count + 3);
2444   memcpy (buf, str, count);
2445 
2446   p = strchr (str, '=');
2447   if (p)
2448     buf[p - str] = ' ';
2449   else
2450     {
2451       buf[count++] = ' ';
2452       buf[count++] = '1';
2453     }
2454   buf[count] = '\n';
2455 
2456   run_directive (pfile, T_DEFINE, buf, count);
2457 }
2458 
2459 
2460 /* Use to build macros to be run through cpp_define() as
2461    described above.
2462    Example: cpp_define_formatted (pfile, "MACRO=%d", value);  */
2463 
2464 void
cpp_define_formatted(cpp_reader * pfile,const char * fmt,...)2465 cpp_define_formatted (cpp_reader *pfile, const char *fmt, ...)
2466 {
2467   char *ptr;
2468 
2469   va_list ap;
2470   va_start (ap, fmt);
2471   ptr = xvasprintf (fmt, ap);
2472   va_end (ap);
2473 
2474   cpp_define (pfile, ptr);
2475   free (ptr);
2476 }
2477 
2478 
2479 /* Slight variant of the above for use by initialize_builtins.  */
2480 void
_cpp_define_builtin(cpp_reader * pfile,const char * str)2481 _cpp_define_builtin (cpp_reader *pfile, const char *str)
2482 {
2483   size_t len = strlen (str);
2484   char *buf = (char *) alloca (len + 1);
2485   memcpy (buf, str, len);
2486   buf[len] = '\n';
2487   run_directive (pfile, T_DEFINE, buf, len);
2488 }
2489 
2490 /* Process MACRO as if it appeared as the body of an #undef.  */
2491 void
cpp_undef(cpp_reader * pfile,const char * macro)2492 cpp_undef (cpp_reader *pfile, const char *macro)
2493 {
2494   size_t len = strlen (macro);
2495   char *buf = (char *) alloca (len + 1);
2496   memcpy (buf, macro, len);
2497   buf[len] = '\n';
2498   run_directive (pfile, T_UNDEF, buf, len);
2499 }
2500 
2501 /* Replace a previous definition DEF of the macro STR.  If DEF is NULL,
2502    or first element is zero, then the macro should be undefined.  */
2503 static void
cpp_pop_definition(cpp_reader * pfile,struct def_pragma_macro * c)2504 cpp_pop_definition (cpp_reader *pfile, struct def_pragma_macro *c)
2505 {
2506   cpp_hashnode *node = _cpp_lex_identifier (pfile, c->name);
2507   if (node == NULL)
2508     return;
2509   if (c->is_builtin)
2510     {
2511       _cpp_restore_special_builtin (pfile, c);
2512       return;
2513     }
2514 
2515   if (pfile->cb.before_define)
2516     pfile->cb.before_define (pfile);
2517 
2518   if (node->type == NT_MACRO)
2519     {
2520       if (pfile->cb.undef)
2521 	pfile->cb.undef (pfile, pfile->directive_line, node);
2522       if (CPP_OPTION (pfile, warn_unused_macros))
2523 	_cpp_warn_if_unused_macro (pfile, node, NULL);
2524     }
2525   if (node->type != NT_VOID)
2526     _cpp_free_definition (node);
2527 
2528   if (c->is_undef)
2529     return;
2530   {
2531     size_t namelen;
2532     const uchar *dn;
2533     cpp_hashnode *h = NULL;
2534     cpp_buffer *nbuf;
2535 
2536     namelen = ustrcspn (c->definition, "( \n");
2537     h = cpp_lookup (pfile, c->definition, namelen);
2538     dn = c->definition + namelen;
2539 
2540     h->type = NT_VOID;
2541     h->flags &= ~(NODE_POISONED|NODE_BUILTIN|NODE_DISABLED|NODE_USED);
2542     nbuf = cpp_push_buffer (pfile, dn, ustrchr (dn, '\n') - dn, true);
2543     if (nbuf != NULL)
2544       {
2545 	_cpp_clean_line (pfile);
2546 	nbuf->sysp = 1;
2547 	if (!_cpp_create_definition (pfile, h))
2548 	  abort ();
2549 	_cpp_pop_buffer (pfile);
2550       }
2551     else
2552       abort ();
2553     h->value.macro->line = c->line;
2554     h->value.macro->syshdr = c->syshdr;
2555     h->value.macro->used = c->used;
2556   }
2557 }
2558 
2559 /* Process the string STR as if it appeared as the body of a #assert.  */
2560 void
cpp_assert(cpp_reader * pfile,const char * str)2561 cpp_assert (cpp_reader *pfile, const char *str)
2562 {
2563   handle_assertion (pfile, str, T_ASSERT);
2564 }
2565 
2566 /* Process STR as if it appeared as the body of an #unassert.  */
2567 void
cpp_unassert(cpp_reader * pfile,const char * str)2568 cpp_unassert (cpp_reader *pfile, const char *str)
2569 {
2570   handle_assertion (pfile, str, T_UNASSERT);
2571 }
2572 
2573 /* Common code for cpp_assert (-A) and cpp_unassert (-A-).  */
2574 static void
handle_assertion(cpp_reader * pfile,const char * str,int type)2575 handle_assertion (cpp_reader *pfile, const char *str, int type)
2576 {
2577   size_t count = strlen (str);
2578   const char *p = strchr (str, '=');
2579 
2580   /* Copy the entire option so we can modify it.  Change the first
2581      "=" in the string to a '(', and tack a ')' on the end.  */
2582   char *buf = (char *) alloca (count + 2);
2583 
2584   memcpy (buf, str, count);
2585   if (p)
2586     {
2587       buf[p - str] = '(';
2588       buf[count++] = ')';
2589     }
2590   buf[count] = '\n';
2591   str = buf;
2592 
2593   run_directive (pfile, type, str, count);
2594 }
2595 
2596 /* The options structure.  */
2597 cpp_options *
cpp_get_options(cpp_reader * pfile)2598 cpp_get_options (cpp_reader *pfile)
2599 {
2600   return &pfile->opts;
2601 }
2602 
2603 /* The callbacks structure.  */
2604 cpp_callbacks *
cpp_get_callbacks(cpp_reader * pfile)2605 cpp_get_callbacks (cpp_reader *pfile)
2606 {
2607   return &pfile->cb;
2608 }
2609 
2610 /* Copy the given callbacks structure to our own.  */
2611 void
cpp_set_callbacks(cpp_reader * pfile,cpp_callbacks * cb)2612 cpp_set_callbacks (cpp_reader *pfile, cpp_callbacks *cb)
2613 {
2614   pfile->cb = *cb;
2615 }
2616 
2617 /* The dependencies structure.  (Creates one if it hasn't already been.)  */
2618 struct deps *
cpp_get_deps(cpp_reader * pfile)2619 cpp_get_deps (cpp_reader *pfile)
2620 {
2621   if (!pfile->deps)
2622     pfile->deps = deps_init ();
2623   return pfile->deps;
2624 }
2625 
2626 /* Push a new buffer on the buffer stack.  Returns the new buffer; it
2627    doesn't fail.  It does not generate a file change call back; that
2628    is the responsibility of the caller.  */
2629 cpp_buffer *
cpp_push_buffer(cpp_reader * pfile,const uchar * buffer,size_t len,int from_stage3)2630 cpp_push_buffer (cpp_reader *pfile, const uchar *buffer, size_t len,
2631 		 int from_stage3)
2632 {
2633   cpp_buffer *new_buffer = XOBNEW (&pfile->buffer_ob, cpp_buffer);
2634 
2635   /* Clears, amongst other things, if_stack and mi_cmacro.  */
2636   memset (new_buffer, 0, sizeof (cpp_buffer));
2637 
2638   new_buffer->next_line = new_buffer->buf = buffer;
2639   new_buffer->rlimit = buffer + len;
2640   new_buffer->from_stage3 = from_stage3;
2641   new_buffer->prev = pfile->buffer;
2642   new_buffer->need_line = true;
2643 
2644   pfile->buffer = new_buffer;
2645 
2646   return new_buffer;
2647 }
2648 
2649 /* Pops a single buffer, with a file change call-back if appropriate.
2650    Then pushes the next -include file, if any remain.  */
2651 void
_cpp_pop_buffer(cpp_reader * pfile)2652 _cpp_pop_buffer (cpp_reader *pfile)
2653 {
2654   cpp_buffer *buffer = pfile->buffer;
2655   struct _cpp_file *inc = buffer->file;
2656   struct if_stack *ifs;
2657   const unsigned char *to_free;
2658 
2659   /* Walk back up the conditional stack till we reach its level at
2660      entry to this file, issuing error messages.  */
2661   for (ifs = buffer->if_stack; ifs; ifs = ifs->next)
2662     cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2663 			 "unterminated #%s", dtable[ifs->type].name);
2664 
2665   /* In case of a missing #endif.  */
2666   pfile->state.skipping = 0;
2667 
2668   /* _cpp_do_file_change expects pfile->buffer to be the new one.  */
2669   pfile->buffer = buffer->prev;
2670 
2671   to_free = buffer->to_free;
2672   free (buffer->notes);
2673 
2674   /* Free the buffer object now; we may want to push a new buffer
2675      in _cpp_push_next_include_file.  */
2676   obstack_free (&pfile->buffer_ob, buffer);
2677 
2678   if (inc)
2679     {
2680       _cpp_pop_file_buffer (pfile, inc, to_free);
2681 
2682       _cpp_do_file_change (pfile, LC_LEAVE, 0, 0, 0);
2683     }
2684 }
2685 
2686 /* Enter all recognized directives in the hash table.  */
2687 void
_cpp_init_directives(cpp_reader * pfile)2688 _cpp_init_directives (cpp_reader *pfile)
2689 {
2690   unsigned int i;
2691   cpp_hashnode *node;
2692 
2693   for (i = 0; i < (unsigned int) N_DIRECTIVES; i++)
2694     {
2695       node = cpp_lookup (pfile, dtable[i].name, dtable[i].length);
2696       node->is_directive = 1;
2697       node->directive_index = i;
2698     }
2699 }
2700 
2701 /* Extract header file from a bracket include. Parsing starts after '<'.
2702    The string is malloced and must be freed by the caller.  */
2703 char *
_cpp_bracket_include(cpp_reader * pfile)2704 _cpp_bracket_include(cpp_reader *pfile)
2705 {
2706   return glue_header_name (pfile);
2707 }
2708 
2709