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