1 /* Part of CPP library.  (Macro and #define handling.)
2    Copyright (C) 1986-2020 Free Software Foundation, Inc.
3    Written by Per Bothner, 1994.
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  In other words, you are welcome to use, share and improve this program.
22  You are forbidden to forbid anyone else to use, share and improve
23  what you give them.   Help stamp out software-hoarding!  */
24 
25 #include "config.h"
26 #include "system.h"
27 #include "cpplib.h"
28 #include "internal.h"
29 
30 typedef struct macro_arg macro_arg;
31 /* This structure represents the tokens of a macro argument.  These
32    tokens can be macro themselves, in which case they can be either
33    expanded or unexpanded.  When they are expanded, this data
34    structure keeps both the expanded and unexpanded forms.  */
35 struct macro_arg
36 {
37   const cpp_token **first;	/* First token in unexpanded argument.  */
38   const cpp_token **expanded;	/* Macro-expanded argument.  */
39   const cpp_token *stringified;	/* Stringified argument.  */
40   unsigned int count;		/* # of tokens in argument.  */
41   unsigned int expanded_count;	/* # of tokens in expanded argument.  */
42   location_t *virt_locs;	/* Where virtual locations for
43 				   unexpanded tokens are stored.  */
44   location_t *expanded_virt_locs; /* Where virtual locations for
45 					  expanded tokens are
46 					  stored.  */
47 };
48 
49 /* The kind of macro tokens which the instance of
50    macro_arg_token_iter is supposed to iterate over.  */
51 enum macro_arg_token_kind {
52   MACRO_ARG_TOKEN_NORMAL,
53   /* This is a macro argument token that got transformed into a string
54      literal, e.g. #foo.  */
55   MACRO_ARG_TOKEN_STRINGIFIED,
56   /* This is a token resulting from the expansion of a macro
57      argument that was itself a macro.  */
58   MACRO_ARG_TOKEN_EXPANDED
59 };
60 
61 /* An iterator over tokens coming from a function-like macro
62    argument.  */
63 typedef struct macro_arg_token_iter macro_arg_token_iter;
64 struct macro_arg_token_iter
65 {
66   /* Whether or not -ftrack-macro-expansion is used.  */
67   bool track_macro_exp_p;
68   /* The kind of token over which we are supposed to iterate.  */
69   enum macro_arg_token_kind kind;
70   /* A pointer to the current token pointed to by the iterator.  */
71   const cpp_token **token_ptr;
72   /* A pointer to the "full" location of the current token.  If
73      -ftrack-macro-expansion is used this location tracks loci across
74      macro expansion.  */
75   const location_t *location_ptr;
76 #if CHECKING_P
77   /* The number of times the iterator went forward. This useful only
78      when checking is enabled.  */
79   size_t num_forwards;
80 #endif
81 };
82 
83 /* Saved data about an identifier being used as a macro argument
84    name.  */
85 struct macro_arg_saved_data {
86   /* The canonical (UTF-8) spelling of this identifier.  */
87   cpp_hashnode *canonical_node;
88   /* The previous value & type of this identifier.  */
89   union _cpp_hashnode_value value;
90   node_type type;
91 };
92 
93 static const char *vaopt_paste_error =
94   N_("'##' cannot appear at either end of __VA_OPT__");
95 
96 static void expand_arg (cpp_reader *, macro_arg *);
97 
98 /* A class for tracking __VA_OPT__ state while iterating over a
99    sequence of tokens.  This is used during both macro definition and
100    expansion.  */
101 class vaopt_state {
102 
103  public:
104 
105   enum update_type
106   {
107     ERROR,
108     DROP,
109     INCLUDE,
110     BEGIN,
111     END
112   };
113 
114   /* Initialize the state tracker.  ANY_ARGS is true if variable
115      arguments were provided to the macro invocation.  */
vaopt_state(cpp_reader * pfile,bool is_variadic,macro_arg * arg)116   vaopt_state (cpp_reader *pfile, bool is_variadic, macro_arg *arg)
117     : m_pfile (pfile),
118     m_arg (arg),
119     m_variadic (is_variadic),
120     m_last_was_paste (false),
121     m_state (0),
122     m_paste_location (0),
123     m_location (0),
124     m_update (ERROR)
125   {
126   }
127 
128   /* Given a token, update the state of this tracker and return a
129      boolean indicating whether the token should be be included in the
130      expansion.  */
update(const cpp_token * token)131   update_type update (const cpp_token *token)
132   {
133     /* If the macro isn't variadic, just don't bother.  */
134     if (!m_variadic)
135       return INCLUDE;
136 
137     if (token->type == CPP_NAME
138 	&& token->val.node.node == m_pfile->spec_nodes.n__VA_OPT__)
139       {
140 	if (m_state > 0)
141 	  {
142 	    cpp_error_at (m_pfile, CPP_DL_ERROR, token->src_loc,
143 			  "__VA_OPT__ may not appear in a __VA_OPT__");
144 	    return ERROR;
145 	  }
146 	++m_state;
147 	m_location = token->src_loc;
148 	return BEGIN;
149       }
150     else if (m_state == 1)
151       {
152 	if (token->type != CPP_OPEN_PAREN)
153 	  {
154 	    cpp_error_at (m_pfile, CPP_DL_ERROR, m_location,
155 			  "__VA_OPT__ must be followed by an "
156 			  "open parenthesis");
157 	    return ERROR;
158 	  }
159 	++m_state;
160 	if (m_update == ERROR)
161 	  {
162 	    if (m_arg == NULL)
163 	      m_update = INCLUDE;
164 	    else
165 	      {
166 		m_update = DROP;
167 		if (!m_arg->expanded)
168 		  expand_arg (m_pfile, m_arg);
169 		for (unsigned idx = 0; idx < m_arg->expanded_count; ++idx)
170 		  if (m_arg->expanded[idx]->type != CPP_PADDING)
171 		    {
172 		      m_update = INCLUDE;
173 		      break;
174 		    }
175 	      }
176 	  }
177 	return DROP;
178       }
179     else if (m_state >= 2)
180       {
181 	if (m_state == 2 && token->type == CPP_PASTE)
182 	  {
183 	    cpp_error_at (m_pfile, CPP_DL_ERROR, token->src_loc,
184 			  vaopt_paste_error);
185 	    return ERROR;
186 	  }
187 	/* Advance states before further considering this token, in
188 	   case we see a close paren immediately after the open
189 	   paren.  */
190 	if (m_state == 2)
191 	  ++m_state;
192 
193 	bool was_paste = m_last_was_paste;
194 	m_last_was_paste = false;
195 	if (token->type == CPP_PASTE)
196 	  {
197 	    m_last_was_paste = true;
198 	    m_paste_location = token->src_loc;
199 	  }
200 	else if (token->type == CPP_OPEN_PAREN)
201 	  ++m_state;
202 	else if (token->type == CPP_CLOSE_PAREN)
203 	  {
204 	    --m_state;
205 	    if (m_state == 2)
206 	      {
207 		/* Saw the final paren.  */
208 		m_state = 0;
209 
210 		if (was_paste)
211 		  {
212 		    cpp_error_at (m_pfile, CPP_DL_ERROR, token->src_loc,
213 				  vaopt_paste_error);
214 		    return ERROR;
215 		  }
216 
217 		return END;
218 	      }
219 	  }
220 	return m_update;
221       }
222 
223     /* Nothing to do with __VA_OPT__.  */
224     return INCLUDE;
225   }
226 
227   /* Ensure that any __VA_OPT__ was completed.  If ok, return true.
228      Otherwise, issue an error and return false.  */
completed()229   bool completed ()
230   {
231     if (m_variadic && m_state != 0)
232       cpp_error_at (m_pfile, CPP_DL_ERROR, m_location,
233 		    "unterminated __VA_OPT__");
234     return m_state == 0;
235   }
236 
237  private:
238 
239   /* The cpp_reader.  */
240   cpp_reader *m_pfile;
241 
242   /* The __VA_ARGS__ argument.  */
243   macro_arg *m_arg;
244 
245   /* True if the macro is variadic.  */
246   bool m_variadic;
247   /* If true, the previous token was ##.  This is used to detect when
248      a paste occurs at the end of the sequence.  */
249   bool m_last_was_paste;
250 
251   /* The state variable:
252      0 means not parsing
253      1 means __VA_OPT__ seen, looking for "("
254      2 means "(" seen (so the next token can't be "##")
255      >= 3 means looking for ")", the number encodes the paren depth.  */
256   int m_state;
257 
258   /* The location of the paste token.  */
259   location_t m_paste_location;
260 
261   /* Location of the __VA_OPT__ token.  */
262   location_t m_location;
263 
264   /* If __VA_ARGS__ substitutes to no preprocessing tokens,
265      INCLUDE, otherwise DROP.  ERROR when unknown yet.  */
266   update_type m_update;
267 };
268 
269 /* Macro expansion.  */
270 
271 static int enter_macro_context (cpp_reader *, cpp_hashnode *,
272 				const cpp_token *, location_t);
273 static int builtin_macro (cpp_reader *, cpp_hashnode *,
274 			  location_t, location_t);
275 static void push_ptoken_context (cpp_reader *, cpp_hashnode *, _cpp_buff *,
276 				 const cpp_token **, unsigned int);
277 static void push_extended_tokens_context (cpp_reader *, cpp_hashnode *,
278 					  _cpp_buff *, location_t *,
279 					  const cpp_token **, unsigned int);
280 static _cpp_buff *collect_args (cpp_reader *, const cpp_hashnode *,
281 				_cpp_buff **, unsigned *);
282 static cpp_context *next_context (cpp_reader *);
283 static const cpp_token *padding_token (cpp_reader *, const cpp_token *);
284 static const cpp_token *new_string_token (cpp_reader *, uchar *, unsigned int);
285 static const cpp_token *stringify_arg (cpp_reader *, macro_arg *);
286 static void paste_all_tokens (cpp_reader *, const cpp_token *);
287 static bool paste_tokens (cpp_reader *, location_t,
288 			  const cpp_token **, const cpp_token *);
289 static void alloc_expanded_arg_mem (cpp_reader *, macro_arg *, size_t);
290 static void ensure_expanded_arg_room (cpp_reader *, macro_arg *, size_t, size_t *);
291 static void delete_macro_args (_cpp_buff*, unsigned num_args);
292 static void set_arg_token (macro_arg *, const cpp_token *,
293 			   location_t, size_t,
294 			   enum macro_arg_token_kind,
295 			   bool);
296 static const location_t *get_arg_token_location (const macro_arg *,
297 						      enum macro_arg_token_kind);
298 static const cpp_token **arg_token_ptr_at (const macro_arg *,
299 					   size_t,
300 					   enum macro_arg_token_kind,
301 					   location_t **virt_location);
302 
303 static void macro_arg_token_iter_init (macro_arg_token_iter *, bool,
304 				       enum macro_arg_token_kind,
305 				       const macro_arg *,
306 				       const cpp_token **);
307 static const cpp_token *macro_arg_token_iter_get_token
308 (const macro_arg_token_iter *it);
309 static location_t macro_arg_token_iter_get_location
310 (const macro_arg_token_iter *);
311 static void macro_arg_token_iter_forward (macro_arg_token_iter *);
312 static _cpp_buff *tokens_buff_new (cpp_reader *, size_t,
313 				   location_t **);
314 static size_t tokens_buff_count (_cpp_buff *);
315 static const cpp_token **tokens_buff_last_token_ptr (_cpp_buff *);
316 static inline const cpp_token **tokens_buff_put_token_to (const cpp_token **,
317                                                           location_t *,
318                                                           const cpp_token *,
319                                                           location_t,
320                                                           location_t,
321                                                           const line_map_macro *,
322                                                           unsigned int);
323 
324 static const cpp_token **tokens_buff_add_token (_cpp_buff *,
325 						location_t *,
326 						const cpp_token *,
327 						location_t,
328 						location_t,
329 						const line_map_macro *,
330 						unsigned int);
331 static inline void tokens_buff_remove_last_token (_cpp_buff *);
332 static void replace_args (cpp_reader *, cpp_hashnode *, cpp_macro *,
333 			  macro_arg *, location_t);
334 static _cpp_buff *funlike_invocation_p (cpp_reader *, cpp_hashnode *,
335 					_cpp_buff **, unsigned *);
336 static cpp_macro *create_iso_definition (cpp_reader *);
337 
338 /* #define directive parsing and handling.  */
339 
340 static cpp_macro *lex_expansion_token (cpp_reader *, cpp_macro *);
341 static bool warn_of_redefinition (cpp_reader *, cpp_hashnode *,
342 				  const cpp_macro *);
343 static bool parse_params (cpp_reader *, unsigned *, bool *);
344 static void check_trad_stringification (cpp_reader *, const cpp_macro *,
345 					const cpp_string *);
346 static bool reached_end_of_context (cpp_context *);
347 static void consume_next_token_from_context (cpp_reader *pfile,
348 					     const cpp_token **,
349 					     location_t *);
350 static const cpp_token* cpp_get_token_1 (cpp_reader *, location_t *);
351 
352 static cpp_hashnode* macro_of_context (cpp_context *context);
353 
354 static bool in_macro_expansion_p (cpp_reader *pfile);
355 
356 /* Statistical counter tracking the number of macros that got
357    expanded.  */
358 unsigned num_expanded_macros_counter = 0;
359 /* Statistical counter tracking the total number tokens resulting
360    from macro expansion.  */
361 unsigned num_macro_tokens_counter = 0;
362 
363 /* Wrapper around cpp_get_token to skip CPP_PADDING tokens
364    and not consume CPP_EOF.  */
365 static const cpp_token *
cpp_get_token_no_padding(cpp_reader * pfile)366 cpp_get_token_no_padding (cpp_reader *pfile)
367 {
368   for (;;)
369     {
370       const cpp_token *ret = cpp_peek_token (pfile, 0);
371       if (ret->type == CPP_EOF)
372 	return ret;
373       ret = cpp_get_token (pfile);
374       if (ret->type != CPP_PADDING)
375 	return ret;
376     }
377 }
378 
379 /* Handle meeting "__has_include" builtin macro.  */
380 
381 static int
builtin_has_include(cpp_reader * pfile,cpp_hashnode * op,bool has_next)382 builtin_has_include (cpp_reader *pfile, cpp_hashnode *op, bool has_next)
383 {
384   int result = 0;
385 
386   if (!pfile->state.in_directive)
387     cpp_error (pfile, CPP_DL_ERROR,
388 	       "\"%s\" used outside of preprocessing directive",
389 	       NODE_NAME (op));
390 
391   pfile->state.angled_headers = true;
392   const cpp_token *token = cpp_get_token_no_padding (pfile);
393   bool paren = token->type == CPP_OPEN_PAREN;
394   if (paren)
395     token = cpp_get_token_no_padding (pfile);
396   else
397     cpp_error (pfile, CPP_DL_ERROR,
398 	       "missing '(' before \"%s\" operand", NODE_NAME (op));
399   pfile->state.angled_headers = false;
400 
401   bool bracket = token->type != CPP_STRING;
402   char *fname = NULL;
403   if (token->type == CPP_STRING || token->type == CPP_HEADER_NAME)
404     {
405       fname = XNEWVEC (char, token->val.str.len - 1);
406       memcpy (fname, token->val.str.text + 1, token->val.str.len - 2);
407       fname[token->val.str.len - 2] = '\0';
408     }
409   else if (token->type == CPP_LESS)
410     fname = _cpp_bracket_include (pfile);
411   else
412     cpp_error (pfile, CPP_DL_ERROR,
413 	       "operator \"%s\" requires a header-name", NODE_NAME (op));
414 
415   if (fname)
416     {
417       /* Do not do the lookup if we're skipping, that's unnecessary
418 	 IO.  */
419       if (!pfile->state.skip_eval
420 	  && _cpp_has_header (pfile, fname, bracket,
421 			      has_next ? IT_INCLUDE_NEXT : IT_INCLUDE))
422 	result = 1;
423 
424       XDELETEVEC (fname);
425     }
426 
427   if (paren
428       && cpp_get_token_no_padding (pfile)->type != CPP_CLOSE_PAREN)
429     cpp_error (pfile, CPP_DL_ERROR,
430 	       "missing ')' after \"%s\" operand", NODE_NAME (op));
431 
432   return result;
433 }
434 
435 /* Emits a warning if NODE is a macro defined in the main file that
436    has not been used.  */
437 int
_cpp_warn_if_unused_macro(cpp_reader * pfile,cpp_hashnode * node,void * v ATTRIBUTE_UNUSED)438 _cpp_warn_if_unused_macro (cpp_reader *pfile, cpp_hashnode *node,
439 			   void *v ATTRIBUTE_UNUSED)
440 {
441   if (cpp_user_macro_p (node))
442     {
443       cpp_macro *macro = node->value.macro;
444 
445       if (!macro->used
446 	  && MAIN_FILE_P (linemap_check_ordinary
447 			    (linemap_lookup (pfile->line_table,
448 					     macro->line))))
449 	cpp_warning_with_line (pfile, CPP_W_UNUSED_MACROS, macro->line, 0,
450 			       "macro \"%s\" is not used", NODE_NAME (node));
451     }
452 
453   return 1;
454 }
455 
456 /* Allocates and returns a CPP_STRING token, containing TEXT of length
457    LEN, after null-terminating it.  TEXT must be in permanent storage.  */
458 static const cpp_token *
new_string_token(cpp_reader * pfile,unsigned char * text,unsigned int len)459 new_string_token (cpp_reader *pfile, unsigned char *text, unsigned int len)
460 {
461   cpp_token *token = _cpp_temp_token (pfile);
462 
463   text[len] = '\0';
464   token->type = CPP_STRING;
465   token->val.str.len = len;
466   token->val.str.text = text;
467   token->flags = 0;
468   return token;
469 }
470 
471 static const char * const monthnames[] =
472 {
473   "Jan", "Feb", "Mar", "Apr", "May", "Jun",
474   "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
475 };
476 
477 /* Helper function for builtin_macro.  Returns the text generated by
478    a builtin macro. */
479 const uchar *
_cpp_builtin_macro_text(cpp_reader * pfile,cpp_hashnode * node,location_t loc)480 _cpp_builtin_macro_text (cpp_reader *pfile, cpp_hashnode *node,
481 			 location_t loc)
482 {
483   const uchar *result = NULL;
484   linenum_type number = 1;
485 
486   switch (node->value.builtin)
487     {
488     default:
489       cpp_error (pfile, CPP_DL_ICE, "invalid built-in macro \"%s\"",
490 		 NODE_NAME (node));
491       break;
492 
493     case BT_TIMESTAMP:
494       {
495 	if (CPP_OPTION (pfile, warn_date_time))
496 	  cpp_warning (pfile, CPP_W_DATE_TIME, "macro \"%s\" might prevent "
497 		       "reproducible builds", NODE_NAME (node));
498 
499 	cpp_buffer *pbuffer = cpp_get_buffer (pfile);
500 	if (pbuffer->timestamp == NULL)
501 	  {
502 	    /* Initialize timestamp value of the assotiated file. */
503             struct _cpp_file *file = cpp_get_file (pbuffer);
504 	    if (file)
505 	      {
506     		/* Generate __TIMESTAMP__ string, that represents
507 		   the date and time of the last modification
508 		   of the current source file. The string constant
509 		   looks like "Sun Sep 16 01:03:52 1973".  */
510 		struct tm *tb = NULL;
511 		struct stat *st = _cpp_get_file_stat (file);
512 		if (st)
513 		  tb = localtime (&st->st_mtime);
514 		if (tb)
515 		  {
516 		    char *str = asctime (tb);
517 		    size_t len = strlen (str);
518 		    unsigned char *buf = _cpp_unaligned_alloc (pfile, len + 2);
519 		    buf[0] = '"';
520 		    strcpy ((char *) buf + 1, str);
521 		    buf[len] = '"';
522 		    pbuffer->timestamp = buf;
523 		  }
524 		else
525 		  {
526 		    cpp_errno (pfile, CPP_DL_WARNING,
527 			"could not determine file timestamp");
528 		    pbuffer->timestamp = UC"\"??? ??? ?? ??:??:?? ????\"";
529 		  }
530 	      }
531 	  }
532 	result = pbuffer->timestamp;
533       }
534       break;
535     case BT_FILE:
536     case BT_BASE_FILE:
537       {
538 	unsigned int len;
539 	const char *name;
540 	uchar *buf;
541 
542 	if (node->value.builtin == BT_FILE)
543 	  name = linemap_get_expansion_filename (pfile->line_table,
544 						 pfile->line_table->highest_line);
545 	else
546 	  {
547 	    name = _cpp_get_file_name (pfile->main_file);
548 	    if (!name)
549 	      abort ();
550 	  }
551 	if (pfile->cb.remap_filename)
552 	  name = pfile->cb.remap_filename (name);
553 	len = strlen (name);
554 	buf = _cpp_unaligned_alloc (pfile, len * 2 + 3);
555 	result = buf;
556 	*buf = '"';
557 	buf = cpp_quote_string (buf + 1, (const unsigned char *) name, len);
558 	*buf++ = '"';
559 	*buf = '\0';
560       }
561       break;
562 
563     case BT_INCLUDE_LEVEL:
564       /* The line map depth counts the primary source as level 1, but
565 	 historically __INCLUDE_DEPTH__ has called the primary source
566 	 level 0.  */
567       number = pfile->line_table->depth - 1;
568       break;
569 
570     case BT_SPECLINE:
571       /* If __LINE__ is embedded in a macro, it must expand to the
572 	 line of the macro's invocation, not its definition.
573 	 Otherwise things like assert() will not work properly.
574 	 See WG14 N1911, WG21 N4220 sec 6.5, and PR 61861.  */
575       if (CPP_OPTION (pfile, traditional))
576 	loc = pfile->line_table->highest_line;
577       else
578 	loc = linemap_resolve_location (pfile->line_table, loc,
579 					LRK_MACRO_EXPANSION_POINT, NULL);
580       number = linemap_get_expansion_line (pfile->line_table, loc);
581       break;
582 
583       /* __STDC__ has the value 1 under normal circumstances.
584 	 However, if (a) we are in a system header, (b) the option
585 	 stdc_0_in_system_headers is true (set by target config), and
586 	 (c) we are not in strictly conforming mode, then it has the
587 	 value 0.  (b) and (c) are already checked in cpp_init_builtins.  */
588     case BT_STDC:
589       if (cpp_in_system_header (pfile))
590 	number = 0;
591       else
592 	number = 1;
593       break;
594 
595     case BT_DATE:
596     case BT_TIME:
597       if (CPP_OPTION (pfile, warn_date_time))
598 	cpp_warning (pfile, CPP_W_DATE_TIME, "macro \"%s\" might prevent "
599 		     "reproducible builds", NODE_NAME (node));
600       if (pfile->date == NULL)
601 	{
602 	  /* Allocate __DATE__ and __TIME__ strings from permanent
603 	     storage.  We only do this once, and don't generate them
604 	     at init time, because time() and localtime() are very
605 	     slow on some systems.  */
606 	  time_t tt;
607 	  struct tm *tb = NULL;
608 
609 	  /* Set a reproducible timestamp for __DATE__ and __TIME__ macro
610 	     if SOURCE_DATE_EPOCH is defined.  */
611 	  if (pfile->source_date_epoch == (time_t) -2
612 	      && pfile->cb.get_source_date_epoch != NULL)
613 	    pfile->source_date_epoch = pfile->cb.get_source_date_epoch (pfile);
614 
615 	  if (pfile->source_date_epoch >= (time_t) 0)
616 	    tb = gmtime (&pfile->source_date_epoch);
617 	  else
618 	    {
619 	      /* (time_t) -1 is a legitimate value for "number of seconds
620 		 since the Epoch", so we have to do a little dance to
621 		 distinguish that from a genuine error.  */
622 	      errno = 0;
623 	      tt = time (NULL);
624 	      if (tt != (time_t)-1 || errno == 0)
625 		tb = localtime (&tt);
626 	    }
627 
628 	  if (tb)
629 	    {
630 	      pfile->date = _cpp_unaligned_alloc (pfile,
631 						  sizeof ("\"Oct 11 1347\""));
632 	      sprintf ((char *) pfile->date, "\"%s %2d %4d\"",
633 		       monthnames[tb->tm_mon], tb->tm_mday,
634 		       tb->tm_year + 1900);
635 
636 	      pfile->time = _cpp_unaligned_alloc (pfile,
637 						  sizeof ("\"12:34:56\""));
638 	      sprintf ((char *) pfile->time, "\"%02d:%02d:%02d\"",
639 		       tb->tm_hour, tb->tm_min, tb->tm_sec);
640 	    }
641 	  else
642 	    {
643 	      cpp_errno (pfile, CPP_DL_WARNING,
644 			 "could not determine date and time");
645 
646 	      pfile->date = UC"\"??? ?? ????\"";
647 	      pfile->time = UC"\"??:??:??\"";
648 	    }
649 	}
650 
651       if (node->value.builtin == BT_DATE)
652 	result = pfile->date;
653       else
654 	result = pfile->time;
655       break;
656 
657     case BT_COUNTER:
658       if (CPP_OPTION (pfile, directives_only) && pfile->state.in_directive)
659 	cpp_error (pfile, CPP_DL_ERROR,
660 	    "__COUNTER__ expanded inside directive with -fdirectives-only");
661       number = pfile->counter++;
662       break;
663 
664     case BT_HAS_ATTRIBUTE:
665       number = pfile->cb.has_attribute (pfile);
666       break;
667 
668     case BT_HAS_BUILTIN:
669       number = pfile->cb.has_builtin (pfile);
670       break;
671 
672     case BT_HAS_INCLUDE:
673     case BT_HAS_INCLUDE_NEXT:
674       number = builtin_has_include (pfile, node,
675 				    node->value.builtin == BT_HAS_INCLUDE_NEXT);
676       break;
677     }
678 
679   if (result == NULL)
680     {
681       /* 21 bytes holds all NUL-terminated unsigned 64-bit numbers.  */
682       result = _cpp_unaligned_alloc (pfile, 21);
683       sprintf ((char *) result, "%u", number);
684     }
685 
686   return result;
687 }
688 
689 /* Convert builtin macros like __FILE__ to a token and push it on the
690    context stack.  Also handles _Pragma, for which a new token may not
691    be created.  Returns 1 if it generates a new token context, 0 to
692    return the token to the caller.  LOC is the location of the expansion
693    point of the macro.  */
694 static int
builtin_macro(cpp_reader * pfile,cpp_hashnode * node,location_t loc,location_t expand_loc)695 builtin_macro (cpp_reader *pfile, cpp_hashnode *node,
696 	       location_t loc, location_t expand_loc)
697 {
698   const uchar *buf;
699   size_t len;
700   char *nbuf;
701 
702   if (node->value.builtin == BT_PRAGMA)
703     {
704       /* Don't interpret _Pragma within directives.  The standard is
705          not clear on this, but to me this makes most sense.  */
706       if (pfile->state.in_directive)
707 	return 0;
708 
709       return _cpp_do__Pragma (pfile, loc);
710     }
711 
712   buf = _cpp_builtin_macro_text (pfile, node, expand_loc);
713   len = ustrlen (buf);
714   nbuf = (char *) alloca (len + 1);
715   memcpy (nbuf, buf, len);
716   nbuf[len]='\n';
717 
718   cpp_push_buffer (pfile, (uchar *) nbuf, len, /* from_stage3 */ true);
719   _cpp_clean_line (pfile);
720 
721   /* Set pfile->cur_token as required by _cpp_lex_direct.  */
722   pfile->cur_token = _cpp_temp_token (pfile);
723   cpp_token *token = _cpp_lex_direct (pfile);
724   /* We should point to the expansion point of the builtin macro.  */
725   token->src_loc = loc;
726   if (pfile->context->tokens_kind == TOKENS_KIND_EXTENDED)
727     {
728       /* We are tracking tokens resulting from macro expansion.
729 	 Create a macro line map and generate a virtual location for
730 	 the token resulting from the expansion of the built-in
731 	 macro.  */
732       location_t *virt_locs = NULL;
733       _cpp_buff *token_buf = tokens_buff_new (pfile, 1, &virt_locs);
734       const line_map_macro * map =
735 	linemap_enter_macro (pfile->line_table, node, loc, 1);
736       tokens_buff_add_token (token_buf, virt_locs, token,
737 			     pfile->line_table->builtin_location,
738 			     pfile->line_table->builtin_location,
739 			    map, /*macro_token_index=*/0);
740       push_extended_tokens_context (pfile, node, token_buf, virt_locs,
741 				    (const cpp_token **)token_buf->base,
742 				    1);
743     }
744   else
745     _cpp_push_token_context (pfile, NULL, token, 1);
746   if (pfile->buffer->cur != pfile->buffer->rlimit)
747     cpp_error (pfile, CPP_DL_ICE, "invalid built-in macro \"%s\"",
748 	       NODE_NAME (node));
749   _cpp_pop_buffer (pfile);
750 
751   return 1;
752 }
753 
754 /* Copies SRC, of length LEN, to DEST, adding backslashes before all
755    backslashes and double quotes. DEST must be of sufficient size.
756    Returns a pointer to the end of the string.  */
757 uchar *
cpp_quote_string(uchar * dest,const uchar * src,unsigned int len)758 cpp_quote_string (uchar *dest, const uchar *src, unsigned int len)
759 {
760   while (len--)
761     {
762       uchar c = *src++;
763 
764       switch (c)
765 	{
766 	case '\n':
767 	  /* Naked LF can appear in raw string literals  */
768 	  c = 'n';
769 	  /* FALLTHROUGH */
770 
771 	case '\\':
772 	case '"':
773 	  *dest++ = '\\';
774 	  /* FALLTHROUGH */
775 
776 	default:
777 	  *dest++ = c;
778 	}
779     }
780 
781   return dest;
782 }
783 
784 /* Convert a token sequence ARG to a single string token according to
785    the rules of the ISO C #-operator.  */
786 static const cpp_token *
stringify_arg(cpp_reader * pfile,macro_arg * arg)787 stringify_arg (cpp_reader *pfile, macro_arg *arg)
788 {
789   unsigned char *dest;
790   unsigned int i, escape_it, backslash_count = 0;
791   const cpp_token *source = NULL;
792   size_t len;
793 
794   if (BUFF_ROOM (pfile->u_buff) < 3)
795     _cpp_extend_buff (pfile, &pfile->u_buff, 3);
796   dest = BUFF_FRONT (pfile->u_buff);
797   *dest++ = '"';
798 
799   /* Loop, reading in the argument's tokens.  */
800   for (i = 0; i < arg->count; i++)
801     {
802       const cpp_token *token = arg->first[i];
803 
804       if (token->type == CPP_PADDING)
805 	{
806 	  if (source == NULL
807 	      || (!(source->flags & PREV_WHITE)
808 		  && token->val.source == NULL))
809 	    source = token->val.source;
810 	  continue;
811 	}
812 
813       escape_it = (token->type == CPP_STRING || token->type == CPP_CHAR
814 		   || token->type == CPP_WSTRING || token->type == CPP_WCHAR
815 		   || token->type == CPP_STRING32 || token->type == CPP_CHAR32
816 		   || token->type == CPP_STRING16 || token->type == CPP_CHAR16
817 		   || token->type == CPP_UTF8STRING || token->type == CPP_UTF8CHAR
818 		   || cpp_userdef_string_p (token->type)
819 		   || cpp_userdef_char_p (token->type));
820 
821       /* Room for each char being written in octal, initial space and
822 	 final quote and NUL.  */
823       len = cpp_token_len (token);
824       if (escape_it)
825 	len *= 4;
826       len += 3;
827 
828       if ((size_t) (BUFF_LIMIT (pfile->u_buff) - dest) < len)
829 	{
830 	  size_t len_so_far = dest - BUFF_FRONT (pfile->u_buff);
831 	  _cpp_extend_buff (pfile, &pfile->u_buff, len);
832 	  dest = BUFF_FRONT (pfile->u_buff) + len_so_far;
833 	}
834 
835       /* Leading white space?  */
836       if (dest - 1 != BUFF_FRONT (pfile->u_buff))
837 	{
838 	  if (source == NULL)
839 	    source = token;
840 	  if (source->flags & PREV_WHITE)
841 	    *dest++ = ' ';
842 	}
843       source = NULL;
844 
845       if (escape_it)
846 	{
847 	  _cpp_buff *buff = _cpp_get_buff (pfile, len);
848 	  unsigned char *buf = BUFF_FRONT (buff);
849 	  len = cpp_spell_token (pfile, token, buf, true) - buf;
850 	  dest = cpp_quote_string (dest, buf, len);
851 	  _cpp_release_buff (pfile, buff);
852 	}
853       else
854 	dest = cpp_spell_token (pfile, token, dest, true);
855 
856       if (token->type == CPP_OTHER && token->val.str.text[0] == '\\')
857 	backslash_count++;
858       else
859 	backslash_count = 0;
860     }
861 
862   /* Ignore the final \ of invalid string literals.  */
863   if (backslash_count & 1)
864     {
865       cpp_error (pfile, CPP_DL_WARNING,
866 		 "invalid string literal, ignoring final '\\'");
867       dest--;
868     }
869 
870   /* Commit the memory, including NUL, and return the token.  */
871   *dest++ = '"';
872   len = dest - BUFF_FRONT (pfile->u_buff);
873   BUFF_FRONT (pfile->u_buff) = dest + 1;
874   return new_string_token (pfile, dest - len, len);
875 }
876 
877 /* Try to paste two tokens.  On success, return nonzero.  In any
878    case, PLHS is updated to point to the pasted token, which is
879    guaranteed to not have the PASTE_LEFT flag set.  LOCATION is
880    the virtual location used for error reporting.  */
881 static bool
paste_tokens(cpp_reader * pfile,location_t location,const cpp_token ** plhs,const cpp_token * rhs)882 paste_tokens (cpp_reader *pfile, location_t location,
883 	      const cpp_token **plhs, const cpp_token *rhs)
884 {
885   unsigned char *buf, *end, *lhsend;
886   cpp_token *lhs;
887   unsigned int len;
888 
889   len = cpp_token_len (*plhs) + cpp_token_len (rhs) + 1;
890   buf = (unsigned char *) alloca (len);
891   end = lhsend = cpp_spell_token (pfile, *plhs, buf, true);
892 
893   /* Avoid comment headers, since they are still processed in stage 3.
894      It is simpler to insert a space here, rather than modifying the
895      lexer to ignore comments in some circumstances.  Simply returning
896      false doesn't work, since we want to clear the PASTE_LEFT flag.  */
897   if ((*plhs)->type == CPP_DIV && rhs->type != CPP_EQ)
898     *end++ = ' ';
899   /* In one obscure case we might see padding here.  */
900   if (rhs->type != CPP_PADDING)
901     end = cpp_spell_token (pfile, rhs, end, true);
902   *end = '\n';
903 
904   cpp_push_buffer (pfile, buf, end - buf, /* from_stage3 */ true);
905   _cpp_clean_line (pfile);
906 
907   /* Set pfile->cur_token as required by _cpp_lex_direct.  */
908   pfile->cur_token = _cpp_temp_token (pfile);
909   lhs = _cpp_lex_direct (pfile);
910   if (pfile->buffer->cur != pfile->buffer->rlimit)
911     {
912       location_t saved_loc = lhs->src_loc;
913 
914       _cpp_pop_buffer (pfile);
915       _cpp_backup_tokens (pfile, 1);
916       *lhsend = '\0';
917 
918       /* We have to remove the PASTE_LEFT flag from the old lhs, but
919 	 we want to keep the new location.  */
920       *lhs = **plhs;
921       *plhs = lhs;
922       lhs->src_loc = saved_loc;
923       lhs->flags &= ~PASTE_LEFT;
924 
925       /* Mandatory error for all apart from assembler.  */
926       if (CPP_OPTION (pfile, lang) != CLK_ASM)
927 	cpp_error_with_line (pfile, CPP_DL_ERROR, location, 0,
928 	 "pasting \"%s\" and \"%s\" does not give a valid preprocessing token",
929 		   buf, cpp_token_as_text (pfile, rhs));
930       return false;
931     }
932 
933   *plhs = lhs;
934   _cpp_pop_buffer (pfile);
935   return true;
936 }
937 
938 /* Handles an arbitrarily long sequence of ## operators, with initial
939    operand LHS.  This implementation is left-associative,
940    non-recursive, and finishes a paste before handling succeeding
941    ones.  If a paste fails, we back up to the RHS of the failing ##
942    operator before pushing the context containing the result of prior
943    successful pastes, with the effect that the RHS appears in the
944    output stream after the pasted LHS normally.  */
945 static void
paste_all_tokens(cpp_reader * pfile,const cpp_token * lhs)946 paste_all_tokens (cpp_reader *pfile, const cpp_token *lhs)
947 {
948   const cpp_token *rhs = NULL;
949   cpp_context *context = pfile->context;
950   location_t virt_loc = 0;
951 
952   /* We are expanding a macro and we must have been called on a token
953      that appears at the left hand side of a ## operator.  */
954   if (macro_of_context (pfile->context) == NULL
955       || (!(lhs->flags & PASTE_LEFT)))
956     abort ();
957 
958   if (context->tokens_kind == TOKENS_KIND_EXTENDED)
959     /* The caller must have called consume_next_token_from_context
960        right before calling us.  That has incremented the pointer to
961        the current virtual location.  So it now points to the location
962        of the token that comes right after *LHS.  We want the
963        resulting pasted token to have the location of the current
964        *LHS, though.  */
965     virt_loc = context->c.mc->cur_virt_loc[-1];
966   else
967     /* We are not tracking macro expansion.  So the best virtual
968        location we can get here is the expansion point of the macro we
969        are currently expanding.  */
970     virt_loc = pfile->invocation_location;
971 
972   do
973     {
974       /* Take the token directly from the current context.  We can do
975 	 this, because we are in the replacement list of either an
976 	 object-like macro, or a function-like macro with arguments
977 	 inserted.  In either case, the constraints to #define
978 	 guarantee we have at least one more token.  */
979       if (context->tokens_kind == TOKENS_KIND_DIRECT)
980 	rhs = FIRST (context).token++;
981       else if (context->tokens_kind == TOKENS_KIND_INDIRECT)
982 	rhs = *FIRST (context).ptoken++;
983       else if (context->tokens_kind == TOKENS_KIND_EXTENDED)
984 	{
985 	  /* So we are in presence of an extended token context, which
986 	     means that each token in this context has a virtual
987 	     location attached to it.  So let's not forget to update
988 	     the pointer to the current virtual location of the
989 	     current token when we update the pointer to the current
990 	     token */
991 
992 	  rhs = *FIRST (context).ptoken++;
993 	  /* context->c.mc must be non-null, as if we were not in a
994 	     macro context, context->tokens_kind could not be equal to
995 	     TOKENS_KIND_EXTENDED.  */
996 	  context->c.mc->cur_virt_loc++;
997 	}
998 
999       if (rhs->type == CPP_PADDING)
1000 	{
1001 	  if (rhs->flags & PASTE_LEFT)
1002 	    abort ();
1003 	}
1004       if (!paste_tokens (pfile, virt_loc, &lhs, rhs))
1005 	break;
1006     }
1007   while (rhs->flags & PASTE_LEFT);
1008 
1009   /* Put the resulting token in its own context.  */
1010   if (context->tokens_kind == TOKENS_KIND_EXTENDED)
1011     {
1012       location_t *virt_locs = NULL;
1013       _cpp_buff *token_buf = tokens_buff_new (pfile, 1, &virt_locs);
1014       tokens_buff_add_token (token_buf, virt_locs, lhs,
1015 			     virt_loc, 0, NULL, 0);
1016       push_extended_tokens_context (pfile, context->c.mc->macro_node,
1017 				    token_buf, virt_locs,
1018 				    (const cpp_token **)token_buf->base, 1);
1019     }
1020   else
1021     _cpp_push_token_context (pfile, NULL, lhs, 1);
1022 }
1023 
1024 /* Returns TRUE if the number of arguments ARGC supplied in an
1025    invocation of the MACRO referenced by NODE is valid.  An empty
1026    invocation to a macro with no parameters should pass ARGC as zero.
1027 
1028    Note that MACRO cannot necessarily be deduced from NODE, in case
1029    NODE was redefined whilst collecting arguments.  */
1030 bool
_cpp_arguments_ok(cpp_reader * pfile,cpp_macro * macro,const cpp_hashnode * node,unsigned int argc)1031 _cpp_arguments_ok (cpp_reader *pfile, cpp_macro *macro, const cpp_hashnode *node, unsigned int argc)
1032 {
1033   if (argc == macro->paramc)
1034     return true;
1035 
1036   if (argc < macro->paramc)
1037     {
1038       /* In C++2a (here the va_opt flag is used), and also as a GNU
1039 	 extension, variadic arguments are allowed to not appear in
1040 	 the invocation at all.
1041 	 e.g. #define debug(format, args...) something
1042 	 debug("string");
1043 
1044 	 This is exactly the same as if an empty variadic list had been
1045 	 supplied - debug("string", ).  */
1046 
1047       if (argc + 1 == macro->paramc && macro->variadic)
1048 	{
1049 	  if (CPP_PEDANTIC (pfile) && ! macro->syshdr
1050 	      && ! CPP_OPTION (pfile, va_opt))
1051 	    {
1052 	      if (CPP_OPTION (pfile, cplusplus))
1053 		cpp_error (pfile, CPP_DL_PEDWARN,
1054 			   "ISO C++11 requires at least one argument "
1055 			   "for the \"...\" in a variadic macro");
1056 	      else
1057 		cpp_error (pfile, CPP_DL_PEDWARN,
1058 			   "ISO C99 requires at least one argument "
1059 			   "for the \"...\" in a variadic macro");
1060 	    }
1061 	  return true;
1062 	}
1063 
1064       cpp_error (pfile, CPP_DL_ERROR,
1065 		 "macro \"%s\" requires %u arguments, but only %u given",
1066 		 NODE_NAME (node), macro->paramc, argc);
1067     }
1068   else
1069     cpp_error (pfile, CPP_DL_ERROR,
1070 	       "macro \"%s\" passed %u arguments, but takes just %u",
1071 	       NODE_NAME (node), argc, macro->paramc);
1072 
1073   if (macro->line > RESERVED_LOCATION_COUNT)
1074     cpp_error_at (pfile, CPP_DL_NOTE, macro->line, "macro \"%s\" defined here",
1075 		  NODE_NAME (node));
1076 
1077   return false;
1078 }
1079 
1080 /* Reads and returns the arguments to a function-like macro
1081    invocation.  Assumes the opening parenthesis has been processed.
1082    If there is an error, emits an appropriate diagnostic and returns
1083    NULL.  Each argument is terminated by a CPP_EOF token, for the
1084    future benefit of expand_arg().  If there are any deferred
1085    #pragma directives among macro arguments, store pointers to the
1086    CPP_PRAGMA ... CPP_PRAGMA_EOL tokens into *PRAGMA_BUFF buffer.
1087 
1088    What is returned is the buffer that contains the memory allocated
1089    to hold the macro arguments.  NODE is the name of the macro this
1090    function is dealing with.  If NUM_ARGS is non-NULL, *NUM_ARGS is
1091    set to the actual number of macro arguments allocated in the
1092    returned buffer.  */
1093 static _cpp_buff *
collect_args(cpp_reader * pfile,const cpp_hashnode * node,_cpp_buff ** pragma_buff,unsigned * num_args)1094 collect_args (cpp_reader *pfile, const cpp_hashnode *node,
1095 	      _cpp_buff **pragma_buff, unsigned *num_args)
1096 {
1097   _cpp_buff *buff, *base_buff;
1098   cpp_macro *macro;
1099   macro_arg *args, *arg;
1100   const cpp_token *token;
1101   unsigned int argc;
1102   location_t virt_loc;
1103   bool track_macro_expansion_p = CPP_OPTION (pfile, track_macro_expansion);
1104   unsigned num_args_alloced = 0;
1105 
1106   macro = node->value.macro;
1107   if (macro->paramc)
1108     argc = macro->paramc;
1109   else
1110     argc = 1;
1111 
1112 #define DEFAULT_NUM_TOKENS_PER_MACRO_ARG 50
1113 #define ARG_TOKENS_EXTENT 1000
1114 
1115   buff = _cpp_get_buff (pfile, argc * (DEFAULT_NUM_TOKENS_PER_MACRO_ARG
1116 				       * sizeof (cpp_token *)
1117 				       + sizeof (macro_arg)));
1118   base_buff = buff;
1119   args = (macro_arg *) buff->base;
1120   memset (args, 0, argc * sizeof (macro_arg));
1121   buff->cur = (unsigned char *) &args[argc];
1122   arg = args, argc = 0;
1123 
1124   /* Collect the tokens making up each argument.  We don't yet know
1125      how many arguments have been supplied, whether too many or too
1126      few.  Hence the slightly bizarre usage of "argc" and "arg".  */
1127   do
1128     {
1129       unsigned int paren_depth = 0;
1130       unsigned int ntokens = 0;
1131       unsigned virt_locs_capacity = DEFAULT_NUM_TOKENS_PER_MACRO_ARG;
1132       num_args_alloced++;
1133 
1134       argc++;
1135       arg->first = (const cpp_token **) buff->cur;
1136       if (track_macro_expansion_p)
1137 	{
1138 	  virt_locs_capacity = DEFAULT_NUM_TOKENS_PER_MACRO_ARG;
1139 	  arg->virt_locs = XNEWVEC (location_t,
1140 				    virt_locs_capacity);
1141 	}
1142 
1143       for (;;)
1144 	{
1145 	  /* Require space for 2 new tokens (including a CPP_EOF).  */
1146 	  if ((unsigned char *) &arg->first[ntokens + 2] > buff->limit)
1147 	    {
1148 	      buff = _cpp_append_extend_buff (pfile, buff,
1149 					      ARG_TOKENS_EXTENT
1150 					      * sizeof (cpp_token *));
1151 	      arg->first = (const cpp_token **) buff->cur;
1152 	    }
1153 	  if (track_macro_expansion_p
1154 	      && (ntokens + 2 > virt_locs_capacity))
1155 	    {
1156 	      virt_locs_capacity += ARG_TOKENS_EXTENT;
1157 	      arg->virt_locs = XRESIZEVEC (location_t,
1158 					   arg->virt_locs,
1159 					   virt_locs_capacity);
1160 	    }
1161 
1162 	  token = cpp_get_token_1 (pfile, &virt_loc);
1163 
1164 	  if (token->type == CPP_PADDING)
1165 	    {
1166 	      /* Drop leading padding.  */
1167 	      if (ntokens == 0)
1168 		continue;
1169 	    }
1170 	  else if (token->type == CPP_OPEN_PAREN)
1171 	    paren_depth++;
1172 	  else if (token->type == CPP_CLOSE_PAREN)
1173 	    {
1174 	      if (paren_depth-- == 0)
1175 		break;
1176 	    }
1177 	  else if (token->type == CPP_COMMA)
1178 	    {
1179 	      /* A comma does not terminate an argument within
1180 		 parentheses or as part of a variable argument.  */
1181 	      if (paren_depth == 0
1182 		  && ! (macro->variadic && argc == macro->paramc))
1183 		break;
1184 	    }
1185 	  else if (token->type == CPP_EOF
1186 		   || (token->type == CPP_HASH && token->flags & BOL))
1187 	    break;
1188 	  else if (token->type == CPP_PRAGMA)
1189 	    {
1190 	      cpp_token *newtok = _cpp_temp_token (pfile);
1191 
1192 	      /* CPP_PRAGMA token lives in directive_result, which will
1193 		 be overwritten on the next directive.  */
1194 	      *newtok = *token;
1195 	      token = newtok;
1196 	      do
1197 		{
1198 		  if (*pragma_buff == NULL
1199 		      || BUFF_ROOM (*pragma_buff) < sizeof (cpp_token *))
1200 		    {
1201 		      _cpp_buff *next;
1202 		      if (*pragma_buff == NULL)
1203 			*pragma_buff
1204 			  = _cpp_get_buff (pfile, 32 * sizeof (cpp_token *));
1205 		      else
1206 			{
1207 			  next = *pragma_buff;
1208 			  *pragma_buff
1209 			    = _cpp_get_buff (pfile,
1210 					     (BUFF_FRONT (*pragma_buff)
1211 					      - (*pragma_buff)->base) * 2);
1212 			  (*pragma_buff)->next = next;
1213 			}
1214 		    }
1215 		  *(const cpp_token **) BUFF_FRONT (*pragma_buff) = token;
1216 		  BUFF_FRONT (*pragma_buff) += sizeof (cpp_token *);
1217 		  if (token->type == CPP_PRAGMA_EOL)
1218 		    break;
1219 		  token = cpp_get_token_1 (pfile, &virt_loc);
1220 		}
1221 	      while (token->type != CPP_EOF);
1222 
1223 	      /* In deferred pragmas parsing_args and prevent_expansion
1224 		 had been changed, reset it.  */
1225 	      pfile->state.parsing_args = 2;
1226 	      pfile->state.prevent_expansion = 1;
1227 
1228 	      if (token->type == CPP_EOF)
1229 		break;
1230 	      else
1231 		continue;
1232 	    }
1233 	  set_arg_token (arg, token, virt_loc,
1234 			 ntokens, MACRO_ARG_TOKEN_NORMAL,
1235 			 CPP_OPTION (pfile, track_macro_expansion));
1236 	  ntokens++;
1237 	}
1238 
1239       /* Drop trailing padding.  */
1240       while (ntokens > 0 && arg->first[ntokens - 1]->type == CPP_PADDING)
1241 	ntokens--;
1242 
1243       arg->count = ntokens;
1244       set_arg_token (arg, &pfile->eof, pfile->eof.src_loc,
1245 		     ntokens, MACRO_ARG_TOKEN_NORMAL,
1246 		     CPP_OPTION (pfile, track_macro_expansion));
1247 
1248       /* Terminate the argument.  Excess arguments loop back and
1249 	 overwrite the final legitimate argument, before failing.  */
1250       if (argc <= macro->paramc)
1251 	{
1252 	  buff->cur = (unsigned char *) &arg->first[ntokens + 1];
1253 	  if (argc != macro->paramc)
1254 	    arg++;
1255 	}
1256     }
1257   while (token->type != CPP_CLOSE_PAREN && token->type != CPP_EOF);
1258 
1259   if (token->type == CPP_EOF)
1260     {
1261       /* We still need the CPP_EOF to end directives, and to end
1262 	 pre-expansion of a macro argument.  Step back is not
1263 	 unconditional, since we don't want to return a CPP_EOF to our
1264 	 callers at the end of an -include-d file.  */
1265       if (pfile->context->prev || pfile->state.in_directive)
1266 	_cpp_backup_tokens (pfile, 1);
1267       cpp_error (pfile, CPP_DL_ERROR,
1268 		 "unterminated argument list invoking macro \"%s\"",
1269 		 NODE_NAME (node));
1270     }
1271   else
1272     {
1273       /* A single empty argument is counted as no argument.  */
1274       if (argc == 1 && macro->paramc == 0 && args[0].count == 0)
1275 	argc = 0;
1276       if (_cpp_arguments_ok (pfile, macro, node, argc))
1277 	{
1278 	  /* GCC has special semantics for , ## b where b is a varargs
1279 	     parameter: we remove the comma if b was omitted entirely.
1280 	     If b was merely an empty argument, the comma is retained.
1281 	     If the macro takes just one (varargs) parameter, then we
1282 	     retain the comma only if we are standards conforming.
1283 
1284 	     If FIRST is NULL replace_args () swallows the comma.  */
1285 	  if (macro->variadic && (argc < macro->paramc
1286 				  || (argc == 1 && args[0].count == 0
1287 				      && !CPP_OPTION (pfile, std))))
1288 	    args[macro->paramc - 1].first = NULL;
1289 	  if (num_args)
1290 	    *num_args = num_args_alloced;
1291 	  return base_buff;
1292 	}
1293     }
1294 
1295   /* An error occurred.  */
1296   _cpp_release_buff (pfile, base_buff);
1297   return NULL;
1298 }
1299 
1300 /* Search for an opening parenthesis to the macro of NODE, in such a
1301    way that, if none is found, we don't lose the information in any
1302    intervening padding tokens.  If we find the parenthesis, collect
1303    the arguments and return the buffer containing them.  PRAGMA_BUFF
1304    argument is the same as in collect_args.  If NUM_ARGS is non-NULL,
1305    *NUM_ARGS is set to the number of arguments contained in the
1306    returned buffer.  */
1307 static _cpp_buff *
funlike_invocation_p(cpp_reader * pfile,cpp_hashnode * node,_cpp_buff ** pragma_buff,unsigned * num_args)1308 funlike_invocation_p (cpp_reader *pfile, cpp_hashnode *node,
1309 		      _cpp_buff **pragma_buff, unsigned *num_args)
1310 {
1311   const cpp_token *token, *padding = NULL;
1312 
1313   for (;;)
1314     {
1315       token = cpp_get_token (pfile);
1316       if (token->type != CPP_PADDING)
1317 	break;
1318       if (padding == NULL
1319 	  || (!(padding->flags & PREV_WHITE) && token->val.source == NULL))
1320 	padding = token;
1321     }
1322 
1323   if (token->type == CPP_OPEN_PAREN)
1324     {
1325       pfile->state.parsing_args = 2;
1326       return collect_args (pfile, node, pragma_buff, num_args);
1327     }
1328 
1329   /* CPP_EOF can be the end of macro arguments, or the end of the
1330      file.  We mustn't back up over the latter.  Ugh.  */
1331   if (token->type != CPP_EOF || token == &pfile->eof)
1332     {
1333       /* Back up.  We may have skipped padding, in which case backing
1334 	 up more than one token when expanding macros is in general
1335 	 too difficult.  We re-insert it in its own context.  */
1336       _cpp_backup_tokens (pfile, 1);
1337       if (padding)
1338 	_cpp_push_token_context (pfile, NULL, padding, 1);
1339     }
1340 
1341   return NULL;
1342 }
1343 
1344 /* Return the real number of tokens in the expansion of MACRO.  */
1345 static inline unsigned int
macro_real_token_count(const cpp_macro * macro)1346 macro_real_token_count (const cpp_macro *macro)
1347 {
1348   if (__builtin_expect (!macro->extra_tokens, true))
1349     return macro->count;
1350 
1351   for (unsigned i = macro->count; i--;)
1352     if (macro->exp.tokens[i].type != CPP_PASTE)
1353       return i + 1;
1354 
1355   return 0;
1356 }
1357 
1358 /* Push the context of a macro with hash entry NODE onto the context
1359    stack.  If we can successfully expand the macro, we push a context
1360    containing its yet-to-be-rescanned replacement list and return one.
1361    If there were additionally any unexpanded deferred #pragma
1362    directives among macro arguments, push another context containing
1363    the pragma tokens before the yet-to-be-rescanned replacement list
1364    and return two.  Otherwise, we don't push a context and return
1365    zero. LOCATION is the location of the expansion point of the
1366    macro.  */
1367 static int
enter_macro_context(cpp_reader * pfile,cpp_hashnode * node,const cpp_token * result,location_t location)1368 enter_macro_context (cpp_reader *pfile, cpp_hashnode *node,
1369 		     const cpp_token *result, location_t location)
1370 {
1371   /* The presence of a macro invalidates a file's controlling macro.  */
1372   pfile->mi_valid = false;
1373 
1374   pfile->state.angled_headers = false;
1375 
1376   /* From here to when we push the context for the macro later down
1377      this function, we need to flag the fact that we are about to
1378      expand a macro.  This is useful when -ftrack-macro-expansion is
1379      turned off.  In that case, we need to record the location of the
1380      expansion point of the top-most macro we are about to to expand,
1381      into pfile->invocation_location.  But we must not record any such
1382      location once the process of expanding the macro starts; that is,
1383      we must not do that recording between now and later down this
1384      function where set this flag to FALSE.  */
1385   pfile->about_to_expand_macro_p = true;
1386 
1387   if (cpp_user_macro_p (node))
1388     {
1389       cpp_macro *macro = node->value.macro;
1390       _cpp_buff *pragma_buff = NULL;
1391 
1392       if (macro->fun_like)
1393 	{
1394 	  _cpp_buff *buff;
1395 	  unsigned num_args = 0;
1396 
1397 	  pfile->state.prevent_expansion++;
1398 	  pfile->keep_tokens++;
1399 	  pfile->state.parsing_args = 1;
1400 	  buff = funlike_invocation_p (pfile, node, &pragma_buff,
1401 				       &num_args);
1402 	  pfile->state.parsing_args = 0;
1403 	  pfile->keep_tokens--;
1404 	  pfile->state.prevent_expansion--;
1405 
1406 	  if (buff == NULL)
1407 	    {
1408 	      if (CPP_WTRADITIONAL (pfile) && ! node->value.macro->syshdr)
1409 		cpp_warning (pfile, CPP_W_TRADITIONAL,
1410  "function-like macro \"%s\" must be used with arguments in traditional C",
1411 			     NODE_NAME (node));
1412 
1413 	      if (pragma_buff)
1414 		_cpp_release_buff (pfile, pragma_buff);
1415 
1416 	      pfile->about_to_expand_macro_p = false;
1417 	      return 0;
1418 	    }
1419 
1420 	  if (macro->paramc > 0)
1421 	    replace_args (pfile, node, macro,
1422 			  (macro_arg *) buff->base,
1423 			  location);
1424 	  /* Free the memory used by the arguments of this
1425 	     function-like macro.  This memory has been allocated by
1426 	     funlike_invocation_p and by replace_args.  */
1427 	  delete_macro_args (buff, num_args);
1428 	}
1429 
1430       /* Disable the macro within its expansion.  */
1431       node->flags |= NODE_DISABLED;
1432 
1433       /* Laziness can only affect the expansion tokens of the macro,
1434 	 not its fun-likeness or parameters.  */
1435       _cpp_maybe_notify_macro_use (pfile, node);
1436       if (pfile->cb.used)
1437 	pfile->cb.used (pfile, location, node);
1438 
1439       macro->used = 1;
1440 
1441       if (macro->paramc == 0)
1442 	{
1443 	  unsigned tokens_count = macro_real_token_count (macro);
1444 	  if (CPP_OPTION (pfile, track_macro_expansion))
1445 	    {
1446 	      unsigned int i;
1447 	      const cpp_token *src = macro->exp.tokens;
1448 	      const line_map_macro *map;
1449 	      location_t *virt_locs = NULL;
1450 	      _cpp_buff *macro_tokens
1451 		= tokens_buff_new (pfile, tokens_count, &virt_locs);
1452 
1453 	      /* Create a macro map to record the locations of the
1454 		 tokens that are involved in the expansion. LOCATION
1455 		 is the location of the macro expansion point.  */
1456 	      map = linemap_enter_macro (pfile->line_table,
1457 					 node, location, tokens_count);
1458 	      for (i = 0; i < tokens_count; ++i)
1459 		{
1460 		  tokens_buff_add_token (macro_tokens, virt_locs,
1461 					 src, src->src_loc,
1462 					 src->src_loc, map, i);
1463 		  ++src;
1464 		}
1465 	      push_extended_tokens_context (pfile, node,
1466 					    macro_tokens,
1467 					    virt_locs,
1468 					    (const cpp_token **)
1469 					    macro_tokens->base,
1470 					    tokens_count);
1471 	    }
1472 	  else
1473 	    _cpp_push_token_context (pfile, node, macro->exp.tokens,
1474 				     tokens_count);
1475 	  num_macro_tokens_counter += tokens_count;
1476 	}
1477 
1478       if (pragma_buff)
1479 	{
1480 	  if (!pfile->state.in_directive)
1481 	    _cpp_push_token_context (pfile, NULL,
1482 				     padding_token (pfile, result), 1);
1483 	  do
1484 	    {
1485 	      unsigned tokens_count;
1486 	      _cpp_buff *tail = pragma_buff->next;
1487 	      pragma_buff->next = NULL;
1488 	      tokens_count = ((const cpp_token **) BUFF_FRONT (pragma_buff)
1489 			      - (const cpp_token **) pragma_buff->base);
1490 	      push_ptoken_context (pfile, NULL, pragma_buff,
1491 				   (const cpp_token **) pragma_buff->base,
1492 				   tokens_count);
1493 	      pragma_buff = tail;
1494 	      if (!CPP_OPTION (pfile, track_macro_expansion))
1495 		num_macro_tokens_counter += tokens_count;
1496 
1497 	    }
1498 	  while (pragma_buff != NULL);
1499 	  pfile->about_to_expand_macro_p = false;
1500 	  return 2;
1501 	}
1502 
1503       pfile->about_to_expand_macro_p = false;
1504       return 1;
1505     }
1506 
1507   pfile->about_to_expand_macro_p = false;
1508   /* Handle built-in macros and the _Pragma operator.  */
1509   {
1510     location_t expand_loc;
1511 
1512     if (/* The top-level macro invocation that triggered the expansion
1513 	   we are looking at is with a function-like user macro ...  */
1514 	cpp_fun_like_macro_p (pfile->top_most_macro_node)
1515 	/* ... and we are tracking the macro expansion.  */
1516 	&& CPP_OPTION (pfile, track_macro_expansion))
1517       /* Then the location of the end of the macro invocation is the
1518 	 location of the expansion point of this macro.  */
1519       expand_loc = location;
1520     else
1521       /* Otherwise, the location of the end of the macro invocation is
1522 	 the location of the expansion point of that top-level macro
1523 	 invocation.  */
1524       expand_loc = pfile->invocation_location;
1525 
1526     return builtin_macro (pfile, node, location, expand_loc);
1527   }
1528 }
1529 
1530 /* De-allocate the memory used by BUFF which is an array of instances
1531    of macro_arg.  NUM_ARGS is the number of instances of macro_arg
1532    present in BUFF.  */
1533 static void
delete_macro_args(_cpp_buff * buff,unsigned num_args)1534 delete_macro_args (_cpp_buff *buff, unsigned num_args)
1535 {
1536   macro_arg *macro_args;
1537   unsigned i;
1538 
1539   if (buff == NULL)
1540     return;
1541 
1542   macro_args = (macro_arg *) buff->base;
1543 
1544   /* Walk instances of macro_arg to free their expanded tokens as well
1545      as their macro_arg::virt_locs members.  */
1546   for (i = 0; i < num_args; ++i)
1547     {
1548       if (macro_args[i].expanded)
1549 	{
1550 	  free (macro_args[i].expanded);
1551 	  macro_args[i].expanded = NULL;
1552 	}
1553       if (macro_args[i].virt_locs)
1554 	{
1555 	  free (macro_args[i].virt_locs);
1556 	  macro_args[i].virt_locs = NULL;
1557 	}
1558       if (macro_args[i].expanded_virt_locs)
1559 	{
1560 	  free (macro_args[i].expanded_virt_locs);
1561 	  macro_args[i].expanded_virt_locs = NULL;
1562 	}
1563     }
1564   _cpp_free_buff (buff);
1565 }
1566 
1567 /* Set the INDEXth token of the macro argument ARG. TOKEN is the token
1568    to set, LOCATION is its virtual location.  "Virtual" location means
1569    the location that encodes loci across macro expansion. Otherwise
1570    it has to be TOKEN->SRC_LOC.  KIND is the kind of tokens the
1571    argument ARG is supposed to contain.  Note that ARG must be
1572    tailored so that it has enough room to contain INDEX + 1 numbers of
1573    tokens, at least.  */
1574 static void
set_arg_token(macro_arg * arg,const cpp_token * token,location_t location,size_t index,enum macro_arg_token_kind kind,bool track_macro_exp_p)1575 set_arg_token (macro_arg *arg, const cpp_token *token,
1576 	       location_t location, size_t index,
1577 	       enum macro_arg_token_kind kind,
1578 	       bool track_macro_exp_p)
1579 {
1580   const cpp_token **token_ptr;
1581   location_t *loc = NULL;
1582 
1583   token_ptr =
1584     arg_token_ptr_at (arg, index, kind,
1585 		      track_macro_exp_p ? &loc : NULL);
1586   *token_ptr = token;
1587 
1588   if (loc != NULL)
1589     {
1590       /* We can't set the location of a stringified argument
1591 	 token and we can't set any location if we aren't tracking
1592 	 macro expansion locations.   */
1593       gcc_checking_assert (kind != MACRO_ARG_TOKEN_STRINGIFIED
1594 			   && track_macro_exp_p);
1595       *loc = location;
1596     }
1597 }
1598 
1599 /* Get the pointer to the location of the argument token of the
1600    function-like macro argument ARG.  This function must be called
1601    only when we -ftrack-macro-expansion is on.  */
1602 static const location_t *
get_arg_token_location(const macro_arg * arg,enum macro_arg_token_kind kind)1603 get_arg_token_location (const macro_arg *arg,
1604 			enum macro_arg_token_kind kind)
1605 {
1606   const location_t *loc = NULL;
1607   const cpp_token **token_ptr =
1608     arg_token_ptr_at (arg, 0, kind, (location_t **) &loc);
1609 
1610   if (token_ptr == NULL)
1611     return NULL;
1612 
1613   return loc;
1614 }
1615 
1616 /* Return the pointer to the INDEXth token of the macro argument ARG.
1617    KIND specifies the kind of token the macro argument ARG contains.
1618    If VIRT_LOCATION is non NULL, *VIRT_LOCATION is set to the address
1619    of the virtual location of the returned token if the
1620    -ftrack-macro-expansion flag is on; otherwise, it's set to the
1621    spelling location of the returned token.  */
1622 static const cpp_token **
arg_token_ptr_at(const macro_arg * arg,size_t index,enum macro_arg_token_kind kind,location_t ** virt_location)1623 arg_token_ptr_at (const macro_arg *arg, size_t index,
1624 		  enum macro_arg_token_kind kind,
1625 		  location_t **virt_location)
1626 {
1627   const cpp_token **tokens_ptr = NULL;
1628 
1629   switch (kind)
1630     {
1631     case MACRO_ARG_TOKEN_NORMAL:
1632       tokens_ptr = arg->first;
1633       break;
1634     case MACRO_ARG_TOKEN_STRINGIFIED:
1635       tokens_ptr = (const cpp_token **) &arg->stringified;
1636       break;
1637     case MACRO_ARG_TOKEN_EXPANDED:
1638 	tokens_ptr = arg->expanded;
1639       break;
1640     }
1641 
1642   if (tokens_ptr == NULL)
1643     /* This can happen for e.g, an empty token argument to a
1644        funtion-like macro.  */
1645     return tokens_ptr;
1646 
1647   if (virt_location)
1648     {
1649       if (kind == MACRO_ARG_TOKEN_NORMAL)
1650 	*virt_location = &arg->virt_locs[index];
1651       else if (kind == MACRO_ARG_TOKEN_EXPANDED)
1652 	*virt_location = &arg->expanded_virt_locs[index];
1653       else if (kind == MACRO_ARG_TOKEN_STRINGIFIED)
1654 	*virt_location =
1655 	  (location_t *) &tokens_ptr[index]->src_loc;
1656     }
1657   return &tokens_ptr[index];
1658 }
1659 
1660 /* Initialize an iterator so that it iterates over the tokens of a
1661    function-like macro argument.  KIND is the kind of tokens we want
1662    ITER to iterate over. TOKEN_PTR points the first token ITER will
1663    iterate over.  */
1664 static void
macro_arg_token_iter_init(macro_arg_token_iter * iter,bool track_macro_exp_p,enum macro_arg_token_kind kind,const macro_arg * arg,const cpp_token ** token_ptr)1665 macro_arg_token_iter_init (macro_arg_token_iter *iter,
1666 			   bool track_macro_exp_p,
1667 			   enum macro_arg_token_kind kind,
1668 			   const macro_arg *arg,
1669 			   const cpp_token **token_ptr)
1670 {
1671   iter->track_macro_exp_p = track_macro_exp_p;
1672   iter->kind = kind;
1673   iter->token_ptr = token_ptr;
1674   /* Unconditionally initialize this so that the compiler doesn't warn
1675      about iter->location_ptr being possibly uninitialized later after
1676      this code has been inlined somewhere.  */
1677   iter->location_ptr = NULL;
1678   if (track_macro_exp_p)
1679     iter->location_ptr = get_arg_token_location (arg, kind);
1680 #if CHECKING_P
1681   iter->num_forwards = 0;
1682   if (track_macro_exp_p
1683       && token_ptr != NULL
1684       && iter->location_ptr == NULL)
1685     abort ();
1686 #endif
1687 }
1688 
1689 /* Move the iterator one token forward. Note that if IT was
1690    initialized on an argument that has a stringified token, moving it
1691    forward doesn't make sense as a stringified token is essentially one
1692    string.  */
1693 static void
macro_arg_token_iter_forward(macro_arg_token_iter * it)1694 macro_arg_token_iter_forward (macro_arg_token_iter *it)
1695 {
1696   switch (it->kind)
1697     {
1698     case MACRO_ARG_TOKEN_NORMAL:
1699     case MACRO_ARG_TOKEN_EXPANDED:
1700       it->token_ptr++;
1701       if (it->track_macro_exp_p)
1702 	it->location_ptr++;
1703       break;
1704     case MACRO_ARG_TOKEN_STRINGIFIED:
1705 #if CHECKING_P
1706       if (it->num_forwards > 0)
1707 	abort ();
1708 #endif
1709       break;
1710     }
1711 
1712 #if CHECKING_P
1713   it->num_forwards++;
1714 #endif
1715 }
1716 
1717 /* Return the token pointed to by the iterator.  */
1718 static const cpp_token *
macro_arg_token_iter_get_token(const macro_arg_token_iter * it)1719 macro_arg_token_iter_get_token (const macro_arg_token_iter *it)
1720 {
1721 #if CHECKING_P
1722   if (it->kind == MACRO_ARG_TOKEN_STRINGIFIED
1723       && it->num_forwards > 0)
1724     abort ();
1725 #endif
1726   if (it->token_ptr == NULL)
1727     return NULL;
1728   return *it->token_ptr;
1729 }
1730 
1731 /* Return the location of the token pointed to by the iterator.*/
1732 static location_t
macro_arg_token_iter_get_location(const macro_arg_token_iter * it)1733 macro_arg_token_iter_get_location (const macro_arg_token_iter *it)
1734 {
1735 #if CHECKING_P
1736   if (it->kind == MACRO_ARG_TOKEN_STRINGIFIED
1737       && it->num_forwards > 0)
1738     abort ();
1739 #endif
1740   if (it->track_macro_exp_p)
1741     return *it->location_ptr;
1742   else
1743     return (*it->token_ptr)->src_loc;
1744 }
1745 
1746 /* Return the index of a token [resulting from macro expansion] inside
1747    the total list of tokens resulting from a given macro
1748    expansion. The index can be different depending on whether if we
1749    want each tokens resulting from function-like macro arguments
1750    expansion to have a different location or not.
1751 
1752    E.g, consider this function-like macro:
1753 
1754         #define M(x) x - 3
1755 
1756    Then consider us "calling" it (and thus expanding it) like:
1757 
1758        M(1+4)
1759 
1760    It will be expanded into:
1761 
1762        1+4-3
1763 
1764    Let's consider the case of the token '4'.
1765 
1766    Its index can be 2 (it's the third token of the set of tokens
1767    resulting from the expansion) or it can be 0 if we consider that
1768    all tokens resulting from the expansion of the argument "1+2" have
1769    the same index, which is 0. In this later case, the index of token
1770    '-' would then be 1 and the index of token '3' would be 2.
1771 
1772    The later case is useful to use less memory e.g, for the case of
1773    the user using the option -ftrack-macro-expansion=1.
1774 
1775    ABSOLUTE_TOKEN_INDEX is the index of the macro argument token we
1776    are interested in.  CUR_REPLACEMENT_TOKEN is the token of the macro
1777    parameter (inside the macro replacement list) that corresponds to
1778    the macro argument for which ABSOLUTE_TOKEN_INDEX is a token index
1779    of.
1780 
1781    If we refer to the example above, for the '4' argument token,
1782    ABSOLUTE_TOKEN_INDEX would be set to 2, and CUR_REPLACEMENT_TOKEN
1783    would be set to the token 'x', in the replacement list "x - 3" of
1784    macro M.
1785 
1786    This is a subroutine of replace_args.  */
1787 inline static unsigned
expanded_token_index(cpp_reader * pfile,cpp_macro * macro,const cpp_token * cur_replacement_token,unsigned absolute_token_index)1788 expanded_token_index (cpp_reader *pfile, cpp_macro *macro,
1789 		      const cpp_token *cur_replacement_token,
1790 		      unsigned absolute_token_index)
1791 {
1792   if (CPP_OPTION (pfile, track_macro_expansion) > 1)
1793     return absolute_token_index;
1794   return cur_replacement_token - macro->exp.tokens;
1795 }
1796 
1797 /* Copy whether PASTE_LEFT is set from SRC to *PASTE_FLAG.  */
1798 
1799 static void
copy_paste_flag(cpp_reader * pfile,const cpp_token ** paste_flag,const cpp_token * src)1800 copy_paste_flag (cpp_reader *pfile, const cpp_token **paste_flag,
1801 		 const cpp_token *src)
1802 {
1803   cpp_token *token = _cpp_temp_token (pfile);
1804   token->type = (*paste_flag)->type;
1805   token->val = (*paste_flag)->val;
1806   if (src->flags & PASTE_LEFT)
1807     token->flags = (*paste_flag)->flags | PASTE_LEFT;
1808   else
1809     token->flags = (*paste_flag)->flags & ~PASTE_LEFT;
1810   *paste_flag = token;
1811 }
1812 
1813 /* True IFF the last token emitted into BUFF (if any) is PTR.  */
1814 
1815 static bool
last_token_is(_cpp_buff * buff,const cpp_token ** ptr)1816 last_token_is (_cpp_buff *buff, const cpp_token **ptr)
1817 {
1818   return (ptr && tokens_buff_last_token_ptr (buff) == ptr);
1819 }
1820 
1821 /* Replace the parameters in a function-like macro of NODE with the
1822    actual ARGS, and place the result in a newly pushed token context.
1823    Expand each argument before replacing, unless it is operated upon
1824    by the # or ## operators. EXPANSION_POINT_LOC is the location of
1825    the expansion point of the macro. E.g, the location of the
1826    function-like macro invocation.  */
1827 static void
replace_args(cpp_reader * pfile,cpp_hashnode * node,cpp_macro * macro,macro_arg * args,location_t expansion_point_loc)1828 replace_args (cpp_reader *pfile, cpp_hashnode *node, cpp_macro *macro,
1829 	      macro_arg *args, location_t expansion_point_loc)
1830 {
1831   unsigned int i, total;
1832   const cpp_token *src, *limit;
1833   const cpp_token **first = NULL;
1834   macro_arg *arg;
1835   _cpp_buff *buff = NULL;
1836   location_t *virt_locs = NULL;
1837   unsigned int exp_count;
1838   const line_map_macro *map = NULL;
1839   int track_macro_exp;
1840 
1841   /* First, fully macro-expand arguments, calculating the number of
1842      tokens in the final expansion as we go.  The ordering of the if
1843      statements below is subtle; we must handle stringification before
1844      pasting.  */
1845 
1846   /* EXP_COUNT is the number of tokens in the macro replacement
1847      list.  TOTAL is the number of tokens /after/ macro parameters
1848      have been replaced by their arguments.   */
1849   exp_count = macro_real_token_count (macro);
1850   total = exp_count;
1851   limit = macro->exp.tokens + exp_count;
1852 
1853   for (src = macro->exp.tokens; src < limit; src++)
1854     if (src->type == CPP_MACRO_ARG)
1855       {
1856 	/* Leading and trailing padding tokens.  */
1857 	total += 2;
1858 	/* Account for leading and padding tokens in exp_count too.
1859 	   This is going to be important later down this function,
1860 	   when we want to handle the case of (track_macro_exp <
1861 	   2).  */
1862 	exp_count += 2;
1863 
1864 	/* We have an argument.  If it is not being stringified or
1865 	   pasted it is macro-replaced before insertion.  */
1866 	arg = &args[src->val.macro_arg.arg_no - 1];
1867 
1868 	if (src->flags & STRINGIFY_ARG)
1869 	  {
1870 	    if (!arg->stringified)
1871 	      arg->stringified = stringify_arg (pfile, arg);
1872 	  }
1873 	else if ((src->flags & PASTE_LEFT)
1874 		 || (src != macro->exp.tokens && (src[-1].flags & PASTE_LEFT)))
1875 	  total += arg->count - 1;
1876 	else
1877 	  {
1878 	    if (!arg->expanded)
1879 	      expand_arg (pfile, arg);
1880 	    total += arg->expanded_count - 1;
1881 	  }
1882       }
1883 
1884   /* When the compiler is called with the -ftrack-macro-expansion
1885      flag, we need to keep track of the location of each token that
1886      results from macro expansion.
1887 
1888      A token resulting from macro expansion is not a new token. It is
1889      simply the same token as the token coming from the macro
1890      definition.  The new things that are allocated are the buffer
1891      that holds the tokens resulting from macro expansion and a new
1892      location that records many things like the locus of the expansion
1893      point as well as the original locus inside the definition of the
1894      macro.  This location is called a virtual location.
1895 
1896      So the buffer BUFF holds a set of cpp_token*, and the buffer
1897      VIRT_LOCS holds the virtual locations of the tokens held by BUFF.
1898 
1899      Both of these two buffers are going to be hung off of the macro
1900      context, when the latter is pushed.  The memory allocated to
1901      store the tokens and their locations is going to be freed once
1902      the context of macro expansion is popped.
1903 
1904      As far as tokens are concerned, the memory overhead of
1905      -ftrack-macro-expansion is proportional to the number of
1906      macros that get expanded multiplied by sizeof (location_t).
1907      The good news is that extra memory gets freed when the macro
1908      context is freed, i.e shortly after the macro got expanded.  */
1909 
1910   /* Is the -ftrack-macro-expansion flag in effect?  */
1911   track_macro_exp = CPP_OPTION (pfile, track_macro_expansion);
1912 
1913   /* Now allocate memory space for tokens and locations resulting from
1914      the macro expansion, copy the tokens and replace the arguments.
1915      This memory must be freed when the context of the macro MACRO is
1916      popped.  */
1917   buff = tokens_buff_new (pfile, total, track_macro_exp ? &virt_locs : NULL);
1918 
1919   first = (const cpp_token **) buff->base;
1920 
1921   /* Create a macro map to record the locations of the tokens that are
1922      involved in the expansion.  Note that the expansion point is set
1923      to the location of the closing parenthesis.  Otherwise, the
1924      subsequent map created for the first token that comes after the
1925      macro map might have a wrong line number.  That would lead to
1926      tokens with wrong line numbers after the macro expansion.  This
1927      adds up to the memory overhead of the -ftrack-macro-expansion
1928      flag; for every macro that is expanded, a "macro map" is
1929      created.  */
1930   if (track_macro_exp)
1931     {
1932       int num_macro_tokens = total;
1933       if (track_macro_exp < 2)
1934 	/* Then the number of macro tokens won't take in account the
1935 	   fact that function-like macro arguments can expand to
1936 	   multiple tokens. This is to save memory at the expense of
1937 	   accuracy.
1938 
1939 	   Suppose we have #define SQUARE(A) A * A
1940 
1941 	   And then we do SQUARE(2+3)
1942 
1943 	   Then the tokens 2, +, 3, will have the same location,
1944 	   saying they come from the expansion of the argument A.  */
1945 	num_macro_tokens = exp_count;
1946       map = linemap_enter_macro (pfile->line_table, node,
1947 				 expansion_point_loc,
1948 				 num_macro_tokens);
1949     }
1950   i = 0;
1951   vaopt_state vaopt_tracker (pfile, macro->variadic, &args[macro->paramc - 1]);
1952   const cpp_token **vaopt_start = NULL;
1953   for (src = macro->exp.tokens; src < limit; src++)
1954     {
1955       unsigned int arg_tokens_count;
1956       macro_arg_token_iter from;
1957       const cpp_token **paste_flag = NULL;
1958       const cpp_token **tmp_token_ptr;
1959 
1960       /* __VA_OPT__ handling.  */
1961       vaopt_state::update_type vostate = vaopt_tracker.update (src);
1962       if (vostate != vaopt_state::INCLUDE)
1963 	{
1964 	  if (vostate == vaopt_state::BEGIN)
1965 	    {
1966 	      /* Padding on the left of __VA_OPT__ (unless RHS of ##).  */
1967 	      if (src != macro->exp.tokens && !(src[-1].flags & PASTE_LEFT))
1968 		{
1969 		  const cpp_token *t = padding_token (pfile, src);
1970 		  unsigned index = expanded_token_index (pfile, macro, src, i);
1971 		  /* Allocate a virtual location for the padding token and
1972 		     append the token and its location to BUFF and
1973 		     VIRT_LOCS.   */
1974 		  tokens_buff_add_token (buff, virt_locs, t,
1975 					 t->src_loc, t->src_loc,
1976 					 map, index);
1977 		}
1978 	      vaopt_start = tokens_buff_last_token_ptr (buff);
1979 	    }
1980 	  else if (vostate == vaopt_state::END)
1981 	    {
1982 	      const cpp_token **start = vaopt_start;
1983 	      vaopt_start = NULL;
1984 
1985 	      /* Remove any tail padding from inside the __VA_OPT__.  */
1986 	      paste_flag = tokens_buff_last_token_ptr (buff);
1987 	      while (paste_flag && paste_flag != start
1988 		     && (*paste_flag)->type == CPP_PADDING)
1989 		{
1990 		  tokens_buff_remove_last_token (buff);
1991 		  paste_flag = tokens_buff_last_token_ptr (buff);
1992 		}
1993 
1994 	      if (src->flags & PASTE_LEFT)
1995 		{
1996 		  /* With a non-empty __VA_OPT__ on the LHS of ##, the last
1997 		     token should be flagged PASTE_LEFT.  */
1998 		  if (paste_flag && (*paste_flag)->type != CPP_PADDING)
1999 		    copy_paste_flag (pfile, paste_flag, src);
2000 		}
2001 	      else
2002 		{
2003 		  /* Otherwise, avoid paste on RHS, __VA_OPT__(c)d or
2004 		     __VA_OPT__(c)__VA_OPT__(d).  */
2005 		  const cpp_token *t = &pfile->avoid_paste;
2006 		  tokens_buff_add_token (buff, virt_locs,
2007 					 t, t->src_loc, t->src_loc,
2008 					 NULL, 0);
2009 		}
2010 	    }
2011 	  continue;
2012 	}
2013 
2014       if (src->type != CPP_MACRO_ARG)
2015 	{
2016 	  /* Allocate a virtual location for token SRC, and add that
2017 	     token and its virtual location into the buffers BUFF and
2018 	     VIRT_LOCS.  */
2019 	  unsigned index = expanded_token_index (pfile, macro, src, i);
2020 	  tokens_buff_add_token (buff, virt_locs, src,
2021 				 src->src_loc, src->src_loc,
2022 				 map, index);
2023 	  i += 1;
2024 	  continue;
2025 	}
2026 
2027       paste_flag = 0;
2028       arg = &args[src->val.macro_arg.arg_no - 1];
2029       /* SRC is a macro parameter that we need to replace with its
2030 	 corresponding argument.  So at some point we'll need to
2031 	 iterate over the tokens of the macro argument and copy them
2032 	 into the "place" now holding the correspondig macro
2033 	 parameter.  We are going to use the iterator type
2034 	 macro_argo_token_iter to handle that iterating.  The 'if'
2035 	 below is to initialize the iterator depending on the type of
2036 	 tokens the macro argument has.  It also does some adjustment
2037 	 related to padding tokens and some pasting corner cases.  */
2038       if (src->flags & STRINGIFY_ARG)
2039 	{
2040 	  arg_tokens_count = 1;
2041 	  macro_arg_token_iter_init (&from,
2042 				     CPP_OPTION (pfile,
2043 						 track_macro_expansion),
2044 				     MACRO_ARG_TOKEN_STRINGIFIED,
2045 				     arg, &arg->stringified);
2046 	}
2047       else if (src->flags & PASTE_LEFT)
2048 	{
2049 	  arg_tokens_count = arg->count;
2050 	  macro_arg_token_iter_init (&from,
2051 				     CPP_OPTION (pfile,
2052 						 track_macro_expansion),
2053 				     MACRO_ARG_TOKEN_NORMAL,
2054 				     arg, arg->first);
2055 	}
2056       else if (src != macro->exp.tokens && (src[-1].flags & PASTE_LEFT))
2057 	{
2058 	  int num_toks;
2059 	  arg_tokens_count = arg->count;
2060 	  macro_arg_token_iter_init (&from,
2061 				     CPP_OPTION (pfile,
2062 						 track_macro_expansion),
2063 				     MACRO_ARG_TOKEN_NORMAL,
2064 				     arg, arg->first);
2065 
2066 	  num_toks = tokens_buff_count (buff);
2067 
2068 	  if (num_toks != 0)
2069 	    {
2070 	      /* So the current parameter token is pasted to the previous
2071 		 token in the replacement list.  Let's look at what
2072 		 we have as previous and current arguments.  */
2073 
2074 	      /* This is the previous argument's token ...  */
2075 	      tmp_token_ptr = tokens_buff_last_token_ptr (buff);
2076 
2077 	      if ((*tmp_token_ptr)->type == CPP_COMMA
2078 		  && macro->variadic
2079 		  && src->val.macro_arg.arg_no == macro->paramc)
2080 		{
2081 		  /* ... which is a comma; and the current parameter
2082 		     is the last parameter of a variadic function-like
2083 		     macro.  If the argument to the current last
2084 		     parameter is NULL, then swallow the comma,
2085 		     otherwise drop the paste flag.  */
2086 		  if (macro_arg_token_iter_get_token (&from) == NULL)
2087 		    tokens_buff_remove_last_token (buff);
2088 		  else
2089 		    paste_flag = tmp_token_ptr;
2090 		}
2091 	      /* Remove the paste flag if the RHS is a placemarker, unless the
2092 		 previous emitted token is at the beginning of __VA_OPT__;
2093 		 placemarkers within __VA_OPT__ are ignored in that case.  */
2094 	      else if (arg_tokens_count == 0
2095 		       && tmp_token_ptr != vaopt_start)
2096 		paste_flag = tmp_token_ptr;
2097 	    }
2098 	}
2099       else
2100 	{
2101 	  arg_tokens_count = arg->expanded_count;
2102 	  macro_arg_token_iter_init (&from,
2103 				     CPP_OPTION (pfile,
2104 						 track_macro_expansion),
2105 				     MACRO_ARG_TOKEN_EXPANDED,
2106 				     arg, arg->expanded);
2107 
2108 	  if (last_token_is (buff, vaopt_start))
2109 	    {
2110 	      /* We're expanding an arg at the beginning of __VA_OPT__.
2111 		 Skip padding. */
2112 	      while (arg_tokens_count)
2113 		{
2114 		  const cpp_token *t = macro_arg_token_iter_get_token (&from);
2115 		  if (t->type != CPP_PADDING)
2116 		    break;
2117 		  macro_arg_token_iter_forward (&from);
2118 		  --arg_tokens_count;
2119 		}
2120 	    }
2121 	}
2122 
2123       /* Padding on the left of an argument (unless RHS of ##).  */
2124       if ((!pfile->state.in_directive || pfile->state.directive_wants_padding)
2125 	  && src != macro->exp.tokens && !(src[-1].flags & PASTE_LEFT)
2126 	  && !last_token_is (buff, vaopt_start))
2127 	{
2128 	  const cpp_token *t = padding_token (pfile, src);
2129 	  unsigned index = expanded_token_index (pfile, macro, src, i);
2130 	  /* Allocate a virtual location for the padding token and
2131 	     append the token and its location to BUFF and
2132 	     VIRT_LOCS.   */
2133 	  tokens_buff_add_token (buff, virt_locs, t,
2134 				 t->src_loc, t->src_loc,
2135 				 map, index);
2136 	}
2137 
2138       if (arg_tokens_count)
2139 	{
2140 	  /* So now we've got the number of tokens that make up the
2141 	     argument that is going to replace the current parameter
2142 	     in the macro's replacement list.  */
2143 	  unsigned int j;
2144 	  for (j = 0; j < arg_tokens_count; ++j)
2145 	    {
2146 	      /* So if track_macro_exp is < 2, the user wants to
2147 		 save extra memory while tracking macro expansion
2148 		 locations.  So in that case here is what we do:
2149 
2150 		 Suppose we have #define SQUARE(A) A * A
2151 
2152 		 And then we do SQUARE(2+3)
2153 
2154 		 Then the tokens 2, +, 3, will have the same location,
2155 		 saying they come from the expansion of the argument
2156 		 A.
2157 
2158 	      So that means we are going to ignore the COUNT tokens
2159 	      resulting from the expansion of the current macro
2160 	      argument. In other words all the ARG_TOKENS_COUNT tokens
2161 	      resulting from the expansion of the macro argument will
2162 	      have the index I.  Normally, each of those tokens should
2163 	      have index I+J.  */
2164 	      unsigned token_index = i;
2165 	      unsigned index;
2166 	      if (track_macro_exp > 1)
2167 		token_index += j;
2168 
2169 	      index = expanded_token_index (pfile, macro, src, token_index);
2170 	      tokens_buff_add_token (buff, virt_locs,
2171 				     macro_arg_token_iter_get_token (&from),
2172 				     macro_arg_token_iter_get_location (&from),
2173 				     src->src_loc, map, index);
2174 	      macro_arg_token_iter_forward (&from);
2175 	    }
2176 
2177 	  /* With a non-empty argument on the LHS of ##, the last
2178 	     token should be flagged PASTE_LEFT.  */
2179 	  if (src->flags & PASTE_LEFT)
2180 	    paste_flag
2181 	      = (const cpp_token **) tokens_buff_last_token_ptr (buff);
2182 	}
2183       else if (CPP_PEDANTIC (pfile) && ! CPP_OPTION (pfile, c99)
2184 	       && ! macro->syshdr && ! cpp_in_system_header (pfile))
2185 	{
2186 	  if (CPP_OPTION (pfile, cplusplus))
2187 	    cpp_pedwarning (pfile, CPP_W_PEDANTIC,
2188 			    "invoking macro %s argument %d: "
2189 			    "empty macro arguments are undefined"
2190 			    " in ISO C++98",
2191 			    NODE_NAME (node), src->val.macro_arg.arg_no);
2192 	  else if (CPP_OPTION (pfile, cpp_warn_c90_c99_compat))
2193 	    cpp_pedwarning (pfile,
2194 			    CPP_OPTION (pfile, cpp_warn_c90_c99_compat) > 0
2195 			    ? CPP_W_C90_C99_COMPAT : CPP_W_PEDANTIC,
2196 			    "invoking macro %s argument %d: "
2197 			    "empty macro arguments are undefined"
2198 			    " in ISO C90",
2199 			    NODE_NAME (node), src->val.macro_arg.arg_no);
2200 	}
2201       else if (CPP_OPTION (pfile, cpp_warn_c90_c99_compat) > 0
2202 	       && ! CPP_OPTION (pfile, cplusplus)
2203 	       && ! macro->syshdr && ! cpp_in_system_header (pfile))
2204 	cpp_warning (pfile, CPP_W_C90_C99_COMPAT,
2205 		     "invoking macro %s argument %d: "
2206 		     "empty macro arguments are undefined"
2207 		     " in ISO C90",
2208 		     NODE_NAME (node), src->val.macro_arg.arg_no);
2209 
2210       /* Avoid paste on RHS (even case count == 0).  */
2211       if (!pfile->state.in_directive && !(src->flags & PASTE_LEFT)
2212 	  && !last_token_is (buff, vaopt_start))
2213 	{
2214 	  const cpp_token *t = &pfile->avoid_paste;
2215 	  tokens_buff_add_token (buff, virt_locs,
2216 				 t, t->src_loc, t->src_loc,
2217 				 NULL, 0);
2218 	}
2219 
2220       /* Add a new paste flag, or remove an unwanted one.  */
2221       if (paste_flag)
2222 	copy_paste_flag (pfile, paste_flag, src);
2223 
2224       i += arg_tokens_count;
2225     }
2226 
2227   if (track_macro_exp)
2228     push_extended_tokens_context (pfile, node, buff, virt_locs, first,
2229 				  tokens_buff_count (buff));
2230   else
2231     push_ptoken_context (pfile, node, buff, first,
2232 			 tokens_buff_count (buff));
2233 
2234   num_macro_tokens_counter += tokens_buff_count (buff);
2235 }
2236 
2237 /* Return a special padding token, with padding inherited from SOURCE.  */
2238 static const cpp_token *
padding_token(cpp_reader * pfile,const cpp_token * source)2239 padding_token (cpp_reader *pfile, const cpp_token *source)
2240 {
2241   cpp_token *result = _cpp_temp_token (pfile);
2242 
2243   result->type = CPP_PADDING;
2244 
2245   /* Data in GCed data structures cannot be made const so far, so we
2246      need a cast here.  */
2247   result->val.source = (cpp_token *) source;
2248   result->flags = 0;
2249   return result;
2250 }
2251 
2252 /* Get a new uninitialized context.  Create a new one if we cannot
2253    re-use an old one.  */
2254 static cpp_context *
next_context(cpp_reader * pfile)2255 next_context (cpp_reader *pfile)
2256 {
2257   cpp_context *result = pfile->context->next;
2258 
2259   if (result == 0)
2260     {
2261       result = XNEW (cpp_context);
2262       memset (result, 0, sizeof (cpp_context));
2263       result->prev = pfile->context;
2264       result->next = 0;
2265       pfile->context->next = result;
2266     }
2267 
2268   pfile->context = result;
2269   return result;
2270 }
2271 
2272 /* Push a list of pointers to tokens.  */
2273 static void
push_ptoken_context(cpp_reader * pfile,cpp_hashnode * macro,_cpp_buff * buff,const cpp_token ** first,unsigned int count)2274 push_ptoken_context (cpp_reader *pfile, cpp_hashnode *macro, _cpp_buff *buff,
2275 		     const cpp_token **first, unsigned int count)
2276 {
2277   cpp_context *context = next_context (pfile);
2278 
2279   context->tokens_kind = TOKENS_KIND_INDIRECT;
2280   context->c.macro = macro;
2281   context->buff = buff;
2282   FIRST (context).ptoken = first;
2283   LAST (context).ptoken = first + count;
2284 }
2285 
2286 /* Push a list of tokens.
2287 
2288    A NULL macro means that we should continue the current macro
2289    expansion, in essence.  That means that if we are currently in a
2290    macro expansion context, we'll make the new pfile->context refer to
2291    the current macro.  */
2292 void
_cpp_push_token_context(cpp_reader * pfile,cpp_hashnode * macro,const cpp_token * first,unsigned int count)2293 _cpp_push_token_context (cpp_reader *pfile, cpp_hashnode *macro,
2294 			 const cpp_token *first, unsigned int count)
2295 {
2296   cpp_context *context;
2297 
2298    if (macro == NULL)
2299      macro = macro_of_context (pfile->context);
2300 
2301    context = next_context (pfile);
2302    context->tokens_kind = TOKENS_KIND_DIRECT;
2303    context->c.macro = macro;
2304    context->buff = NULL;
2305    FIRST (context).token = first;
2306    LAST (context).token = first + count;
2307 }
2308 
2309 /* Build a context containing a list of tokens as well as their
2310    virtual locations and push it.  TOKENS_BUFF is the buffer that
2311    contains the tokens pointed to by FIRST.  If TOKENS_BUFF is
2312    non-NULL, it means that the context owns it, meaning that
2313    _cpp_pop_context will free it as well as VIRT_LOCS_BUFF that
2314    contains the virtual locations.
2315 
2316    A NULL macro means that we should continue the current macro
2317    expansion, in essence.  That means that if we are currently in a
2318    macro expansion context, we'll make the new pfile->context refer to
2319    the current macro.  */
2320 static void
push_extended_tokens_context(cpp_reader * pfile,cpp_hashnode * macro,_cpp_buff * token_buff,location_t * virt_locs,const cpp_token ** first,unsigned int count)2321 push_extended_tokens_context (cpp_reader *pfile,
2322 			      cpp_hashnode *macro,
2323 			      _cpp_buff *token_buff,
2324 			      location_t *virt_locs,
2325 			      const cpp_token **first,
2326 			      unsigned int count)
2327 {
2328   cpp_context *context;
2329   macro_context *m;
2330 
2331   if (macro == NULL)
2332     macro = macro_of_context (pfile->context);
2333 
2334   context = next_context (pfile);
2335   context->tokens_kind = TOKENS_KIND_EXTENDED;
2336   context->buff = token_buff;
2337 
2338   m = XNEW (macro_context);
2339   m->macro_node = macro;
2340   m->virt_locs = virt_locs;
2341   m->cur_virt_loc = virt_locs;
2342   context->c.mc = m;
2343   FIRST (context).ptoken = first;
2344   LAST (context).ptoken = first + count;
2345 }
2346 
2347 /* Push a traditional macro's replacement text.  */
2348 void
_cpp_push_text_context(cpp_reader * pfile,cpp_hashnode * macro,const uchar * start,size_t len)2349 _cpp_push_text_context (cpp_reader *pfile, cpp_hashnode *macro,
2350 			const uchar *start, size_t len)
2351 {
2352   cpp_context *context = next_context (pfile);
2353 
2354   context->tokens_kind = TOKENS_KIND_DIRECT;
2355   context->c.macro = macro;
2356   context->buff = NULL;
2357   CUR (context) = start;
2358   RLIMIT (context) = start + len;
2359   macro->flags |= NODE_DISABLED;
2360 }
2361 
2362 /* Creates a buffer that holds tokens a.k.a "token buffer", usually
2363    for the purpose of storing them on a cpp_context. If VIRT_LOCS is
2364    non-null (which means that -ftrack-macro-expansion is on),
2365    *VIRT_LOCS is set to a newly allocated buffer that is supposed to
2366    hold the virtual locations of the tokens resulting from macro
2367    expansion.  */
2368 static _cpp_buff*
tokens_buff_new(cpp_reader * pfile,size_t len,location_t ** virt_locs)2369 tokens_buff_new (cpp_reader *pfile, size_t len,
2370 		 location_t **virt_locs)
2371 {
2372   size_t tokens_size = len * sizeof (cpp_token *);
2373   size_t locs_size = len * sizeof (location_t);
2374 
2375   if (virt_locs != NULL)
2376     *virt_locs = XNEWVEC (location_t, locs_size);
2377   return _cpp_get_buff (pfile, tokens_size);
2378 }
2379 
2380 /* Returns the number of tokens contained in a token buffer.  The
2381    buffer holds a set of cpp_token*.  */
2382 static size_t
tokens_buff_count(_cpp_buff * buff)2383 tokens_buff_count (_cpp_buff *buff)
2384 {
2385   return (BUFF_FRONT (buff) - buff->base) / sizeof (cpp_token *);
2386 }
2387 
2388 /* Return a pointer to the last token contained in the token buffer
2389    BUFF.  */
2390 static const cpp_token **
tokens_buff_last_token_ptr(_cpp_buff * buff)2391 tokens_buff_last_token_ptr (_cpp_buff *buff)
2392 {
2393   if (BUFF_FRONT (buff) == buff->base)
2394     return NULL;
2395   return &((const cpp_token **) BUFF_FRONT (buff))[-1];
2396 }
2397 
2398 /* Remove the last token contained in the token buffer TOKENS_BUFF.
2399    If VIRT_LOCS_BUFF is non-NULL,  it should point at the buffer
2400    containing the virtual locations of the tokens in TOKENS_BUFF; in
2401    which case the function updates that buffer as well.   */
2402 static inline void
tokens_buff_remove_last_token(_cpp_buff * tokens_buff)2403 tokens_buff_remove_last_token (_cpp_buff *tokens_buff)
2404 
2405 {
2406   if (BUFF_FRONT (tokens_buff) > tokens_buff->base)
2407     BUFF_FRONT (tokens_buff) =
2408       (unsigned char *) &((cpp_token **) BUFF_FRONT (tokens_buff))[-1];
2409 }
2410 
2411 /* Insert a token into the token buffer at the position pointed to by
2412    DEST.  Note that the buffer is not enlarged so the previous token
2413    that was at *DEST is overwritten.  VIRT_LOC_DEST, if non-null,
2414    means -ftrack-macro-expansion is effect; it then points to where to
2415    insert the virtual location of TOKEN.  TOKEN is the token to
2416    insert.  VIRT_LOC is the virtual location of the token, i.e, the
2417    location possibly encoding its locus across macro expansion.  If
2418    TOKEN is an argument of a function-like macro (inside a macro
2419    replacement list), PARM_DEF_LOC is the spelling location of the
2420    macro parameter that TOKEN is replacing, in the replacement list of
2421    the macro.  If TOKEN is not an argument of a function-like macro or
2422    if it doesn't come from a macro expansion, then VIRT_LOC can just
2423    be set to the same value as PARM_DEF_LOC.  If MAP is non null, it
2424    means TOKEN comes from a macro expansion and MAP is the macro map
2425    associated to the macro.  MACRO_TOKEN_INDEX points to the index of
2426    the token in the macro map; it is not considered if MAP is NULL.
2427 
2428    Upon successful completion this function returns the a pointer to
2429    the position of the token coming right after the insertion
2430    point.  */
2431 static inline const cpp_token **
tokens_buff_put_token_to(const cpp_token ** dest,location_t * virt_loc_dest,const cpp_token * token,location_t virt_loc,location_t parm_def_loc,const line_map_macro * map,unsigned int macro_token_index)2432 tokens_buff_put_token_to (const cpp_token **dest,
2433 			  location_t *virt_loc_dest,
2434 			  const cpp_token *token,
2435 			  location_t virt_loc,
2436 			  location_t parm_def_loc,
2437 			  const line_map_macro *map,
2438 			  unsigned int macro_token_index)
2439 {
2440   location_t macro_loc = virt_loc;
2441   const cpp_token **result;
2442 
2443   if (virt_loc_dest)
2444     {
2445       /* -ftrack-macro-expansion is on.  */
2446       if (map)
2447 	macro_loc = linemap_add_macro_token (map, macro_token_index,
2448 					     virt_loc, parm_def_loc);
2449       *virt_loc_dest = macro_loc;
2450     }
2451   *dest = token;
2452   result = &dest[1];
2453 
2454   return result;
2455 }
2456 
2457 /* Adds a token at the end of the tokens contained in BUFFER.  Note
2458    that this function doesn't enlarge BUFFER when the number of tokens
2459    reaches BUFFER's size; it aborts in that situation.
2460 
2461    TOKEN is the token to append. VIRT_LOC is the virtual location of
2462    the token, i.e, the location possibly encoding its locus across
2463    macro expansion. If TOKEN is an argument of a function-like macro
2464    (inside a macro replacement list), PARM_DEF_LOC is the location of
2465    the macro parameter that TOKEN is replacing.  If TOKEN doesn't come
2466    from a macro expansion, then VIRT_LOC can just be set to the same
2467    value as PARM_DEF_LOC.  If MAP is non null, it means TOKEN comes
2468    from a macro expansion and MAP is the macro map associated to the
2469    macro.  MACRO_TOKEN_INDEX points to the index of the token in the
2470    macro map; It is not considered if MAP is NULL.  If VIRT_LOCS is
2471    non-null, it means -ftrack-macro-expansion is on; in which case
2472    this function adds the virtual location DEF_LOC to the VIRT_LOCS
2473    array, at the same index as the one of TOKEN in BUFFER.  Upon
2474    successful completion this function returns the a pointer to the
2475    position of the token coming right after the insertion point.  */
2476 static const cpp_token **
tokens_buff_add_token(_cpp_buff * buffer,location_t * virt_locs,const cpp_token * token,location_t virt_loc,location_t parm_def_loc,const line_map_macro * map,unsigned int macro_token_index)2477 tokens_buff_add_token (_cpp_buff *buffer,
2478 		       location_t *virt_locs,
2479 		       const cpp_token *token,
2480 		       location_t virt_loc,
2481 		       location_t parm_def_loc,
2482 		       const line_map_macro *map,
2483 		       unsigned int macro_token_index)
2484 {
2485   const cpp_token **result;
2486   location_t *virt_loc_dest = NULL;
2487   unsigned token_index =
2488     (BUFF_FRONT (buffer) - buffer->base) / sizeof (cpp_token *);
2489 
2490   /* Abort if we pass the end the buffer.  */
2491   if (BUFF_FRONT (buffer) > BUFF_LIMIT (buffer))
2492     abort ();
2493 
2494   if (virt_locs != NULL)
2495     virt_loc_dest = &virt_locs[token_index];
2496 
2497   result =
2498     tokens_buff_put_token_to ((const cpp_token **) BUFF_FRONT (buffer),
2499 			      virt_loc_dest, token, virt_loc, parm_def_loc,
2500 			      map, macro_token_index);
2501 
2502   BUFF_FRONT (buffer) = (unsigned char *) result;
2503   return result;
2504 }
2505 
2506 /* Allocate space for the function-like macro argument ARG to store
2507    the tokens resulting from the macro-expansion of the tokens that
2508    make up ARG itself. That space is allocated in ARG->expanded and
2509    needs to be freed using free.  */
2510 static void
alloc_expanded_arg_mem(cpp_reader * pfile,macro_arg * arg,size_t capacity)2511 alloc_expanded_arg_mem (cpp_reader *pfile, macro_arg *arg, size_t capacity)
2512 {
2513   gcc_checking_assert (arg->expanded == NULL
2514 		       && arg->expanded_virt_locs == NULL);
2515 
2516   arg->expanded = XNEWVEC (const cpp_token *, capacity);
2517   if (CPP_OPTION (pfile, track_macro_expansion))
2518     arg->expanded_virt_locs = XNEWVEC (location_t, capacity);
2519 
2520 }
2521 
2522 /* If necessary, enlarge ARG->expanded to so that it can contain SIZE
2523    tokens.  */
2524 static void
ensure_expanded_arg_room(cpp_reader * pfile,macro_arg * arg,size_t size,size_t * expanded_capacity)2525 ensure_expanded_arg_room (cpp_reader *pfile, macro_arg *arg,
2526 			  size_t size, size_t *expanded_capacity)
2527 {
2528   if (size <= *expanded_capacity)
2529     return;
2530 
2531   size *= 2;
2532 
2533   arg->expanded =
2534     XRESIZEVEC (const cpp_token *, arg->expanded, size);
2535   *expanded_capacity = size;
2536 
2537   if (CPP_OPTION (pfile, track_macro_expansion))
2538     {
2539       if (arg->expanded_virt_locs == NULL)
2540 	arg->expanded_virt_locs = XNEWVEC (location_t, size);
2541       else
2542 	arg->expanded_virt_locs = XRESIZEVEC (location_t,
2543 					      arg->expanded_virt_locs,
2544 					      size);
2545     }
2546 }
2547 
2548 /* Expand an argument ARG before replacing parameters in a
2549    function-like macro.  This works by pushing a context with the
2550    argument's tokens, and then expanding that into a temporary buffer
2551    as if it were a normal part of the token stream.  collect_args()
2552    has terminated the argument's tokens with a CPP_EOF so that we know
2553    when we have fully expanded the argument.  */
2554 static void
expand_arg(cpp_reader * pfile,macro_arg * arg)2555 expand_arg (cpp_reader *pfile, macro_arg *arg)
2556 {
2557   size_t capacity;
2558   bool saved_warn_trad;
2559   bool track_macro_exp_p = CPP_OPTION (pfile, track_macro_expansion);
2560 
2561   if (arg->count == 0
2562       || arg->expanded != NULL)
2563     return;
2564 
2565   /* Don't warn about funlike macros when pre-expanding.  */
2566   saved_warn_trad = CPP_WTRADITIONAL (pfile);
2567   CPP_WTRADITIONAL (pfile) = 0;
2568 
2569   /* Loop, reading in the tokens of the argument.  */
2570   capacity = 256;
2571   alloc_expanded_arg_mem (pfile, arg, capacity);
2572 
2573   if (track_macro_exp_p)
2574     push_extended_tokens_context (pfile, NULL, NULL,
2575 				  arg->virt_locs,
2576 				  arg->first,
2577 				  arg->count + 1);
2578   else
2579     push_ptoken_context (pfile, NULL, NULL,
2580 			 arg->first, arg->count + 1);
2581 
2582   for (;;)
2583     {
2584       const cpp_token *token;
2585       location_t location;
2586 
2587       ensure_expanded_arg_room (pfile, arg, arg->expanded_count + 1,
2588 				&capacity);
2589 
2590       token = cpp_get_token_1 (pfile, &location);
2591 
2592       if (token->type == CPP_EOF)
2593 	break;
2594 
2595       set_arg_token (arg, token, location,
2596 		     arg->expanded_count, MACRO_ARG_TOKEN_EXPANDED,
2597 		     CPP_OPTION (pfile, track_macro_expansion));
2598       arg->expanded_count++;
2599     }
2600 
2601   _cpp_pop_context (pfile);
2602 
2603   CPP_WTRADITIONAL (pfile) = saved_warn_trad;
2604 }
2605 
2606 /* Returns the macro associated to the current context if we are in
2607    the context a macro expansion, NULL otherwise.  */
2608 static cpp_hashnode*
macro_of_context(cpp_context * context)2609 macro_of_context (cpp_context *context)
2610 {
2611   if (context == NULL)
2612     return NULL;
2613 
2614   return (context->tokens_kind == TOKENS_KIND_EXTENDED)
2615     ? context->c.mc->macro_node
2616     : context->c.macro;
2617 }
2618 
2619 /* Return TRUE iff we are expanding a macro or are about to start
2620    expanding one.  If we are effectively expanding a macro, the
2621    function macro_of_context returns a pointer to the macro being
2622    expanded.  */
2623 static bool
in_macro_expansion_p(cpp_reader * pfile)2624 in_macro_expansion_p (cpp_reader *pfile)
2625 {
2626   if (pfile == NULL)
2627     return false;
2628 
2629   return (pfile->about_to_expand_macro_p
2630 	  || macro_of_context (pfile->context));
2631 }
2632 
2633 /* Pop the current context off the stack, re-enabling the macro if the
2634    context represented a macro's replacement list.  Initially the
2635    context structure was not freed so that we can re-use it later, but
2636    now we do free it to reduce peak memory consumption.  */
2637 void
_cpp_pop_context(cpp_reader * pfile)2638 _cpp_pop_context (cpp_reader *pfile)
2639 {
2640   cpp_context *context = pfile->context;
2641 
2642   /* We should not be popping the base context.  */
2643   if (context == &pfile->base_context)
2644     abort ();
2645 
2646   if (context->c.macro)
2647     {
2648       cpp_hashnode *macro;
2649       if (context->tokens_kind == TOKENS_KIND_EXTENDED)
2650 	{
2651 	  macro_context *mc = context->c.mc;
2652 	  macro = mc->macro_node;
2653 	  /* If context->buff is set, it means the life time of tokens
2654 	     is bound to the life time of this context; so we must
2655 	     free the tokens; that means we must free the virtual
2656 	     locations of these tokens too.  */
2657 	  if (context->buff && mc->virt_locs)
2658 	    {
2659 	      free (mc->virt_locs);
2660 	      mc->virt_locs = NULL;
2661 	    }
2662 	  free (mc);
2663 	  context->c.mc = NULL;
2664 	}
2665       else
2666 	macro = context->c.macro;
2667 
2668       /* Beware that MACRO can be NULL in cases like when we are
2669 	 called from expand_arg.  In those cases, a dummy context with
2670 	 tokens is pushed just for the purpose of walking them using
2671 	 cpp_get_token_1.  In that case, no 'macro' field is set into
2672 	 the dummy context.  */
2673       if (macro != NULL
2674 	  /* Several contiguous macro expansion contexts can be
2675 	     associated to the same macro; that means it's the same
2676 	     macro expansion that spans across all these (sub)
2677 	     contexts.  So we should re-enable an expansion-disabled
2678 	     macro only when we are sure we are really out of that
2679 	     macro expansion.  */
2680 	  && macro_of_context (context->prev) != macro)
2681 	macro->flags &= ~NODE_DISABLED;
2682 
2683       if (macro == pfile->top_most_macro_node && context->prev == NULL)
2684 	/* We are popping the context of the top-most macro node.  */
2685 	pfile->top_most_macro_node = NULL;
2686     }
2687 
2688   if (context->buff)
2689     {
2690       /* Decrease memory peak consumption by freeing the memory used
2691 	 by the context.  */
2692       _cpp_free_buff (context->buff);
2693     }
2694 
2695   pfile->context = context->prev;
2696   /* decrease peak memory consumption by feeing the context.  */
2697   pfile->context->next = NULL;
2698   free (context);
2699 }
2700 
2701 /* Return TRUE if we reached the end of the set of tokens stored in
2702    CONTEXT, FALSE otherwise.  */
2703 static inline bool
reached_end_of_context(cpp_context * context)2704 reached_end_of_context (cpp_context *context)
2705 {
2706   if (context->tokens_kind == TOKENS_KIND_DIRECT)
2707       return FIRST (context).token == LAST (context).token;
2708   else if (context->tokens_kind == TOKENS_KIND_INDIRECT
2709 	   || context->tokens_kind == TOKENS_KIND_EXTENDED)
2710     return FIRST (context).ptoken == LAST (context).ptoken;
2711   else
2712     abort ();
2713 }
2714 
2715 /* Consume the next token contained in the current context of PFILE,
2716    and return it in *TOKEN. It's "full location" is returned in
2717    *LOCATION. If -ftrack-macro-location is in effeect, fFull location"
2718    means the location encoding the locus of the token across macro
2719    expansion; otherwise it's just is the "normal" location of the
2720    token which (*TOKEN)->src_loc.  */
2721 static inline void
consume_next_token_from_context(cpp_reader * pfile,const cpp_token ** token,location_t * location)2722 consume_next_token_from_context (cpp_reader *pfile,
2723 				 const cpp_token ** token,
2724 				 location_t *location)
2725 {
2726   cpp_context *c = pfile->context;
2727 
2728   if ((c)->tokens_kind == TOKENS_KIND_DIRECT)
2729     {
2730       *token = FIRST (c).token;
2731       *location = (*token)->src_loc;
2732       FIRST (c).token++;
2733     }
2734   else if ((c)->tokens_kind == TOKENS_KIND_INDIRECT)
2735     {
2736       *token = *FIRST (c).ptoken;
2737       *location = (*token)->src_loc;
2738       FIRST (c).ptoken++;
2739     }
2740   else if ((c)->tokens_kind == TOKENS_KIND_EXTENDED)
2741     {
2742       macro_context *m = c->c.mc;
2743       *token = *FIRST (c).ptoken;
2744       if (m->virt_locs)
2745 	{
2746 	  *location = *m->cur_virt_loc;
2747 	  m->cur_virt_loc++;
2748 	}
2749       else
2750 	*location = (*token)->src_loc;
2751       FIRST (c).ptoken++;
2752     }
2753   else
2754     abort ();
2755 }
2756 
2757 /* In the traditional mode of the preprocessor, if we are currently in
2758    a directive, the location of a token must be the location of the
2759    start of the directive line.  This function returns the proper
2760    location if we are in the traditional mode, and just returns
2761    LOCATION otherwise.  */
2762 
2763 static inline location_t
maybe_adjust_loc_for_trad_cpp(cpp_reader * pfile,location_t location)2764 maybe_adjust_loc_for_trad_cpp (cpp_reader *pfile, location_t location)
2765 {
2766   if (CPP_OPTION (pfile, traditional))
2767     {
2768       if (pfile->state.in_directive)
2769 	return pfile->directive_line;
2770     }
2771   return location;
2772 }
2773 
2774 /* Routine to get a token as well as its location.
2775 
2776    Macro expansions and directives are transparently handled,
2777    including entering included files.  Thus tokens are post-macro
2778    expansion, and after any intervening directives.  External callers
2779    see CPP_EOF only at EOF.  Internal callers also see it when meeting
2780    a directive inside a macro call, when at the end of a directive and
2781    state.in_directive is still 1, and at the end of argument
2782    pre-expansion.
2783 
2784    LOC is an out parameter; *LOC is set to the location "as expected
2785    by the user".  Please read the comment of
2786    cpp_get_token_with_location to learn more about the meaning of this
2787    location.  */
2788 static const cpp_token*
cpp_get_token_1(cpp_reader * pfile,location_t * location)2789 cpp_get_token_1 (cpp_reader *pfile, location_t *location)
2790 {
2791   const cpp_token *result;
2792   /* This token is a virtual token that either encodes a location
2793      related to macro expansion or a spelling location.  */
2794   location_t virt_loc = 0;
2795   /* pfile->about_to_expand_macro_p can be overriden by indirect calls
2796      to functions that push macro contexts.  So let's save it so that
2797      we can restore it when we are about to leave this routine.  */
2798   bool saved_about_to_expand_macro = pfile->about_to_expand_macro_p;
2799 
2800   for (;;)
2801     {
2802       cpp_hashnode *node;
2803       cpp_context *context = pfile->context;
2804 
2805       /* Context->prev == 0 <=> base context.  */
2806       if (!context->prev)
2807 	{
2808 	  result = _cpp_lex_token (pfile);
2809 	  virt_loc = result->src_loc;
2810 	}
2811       else if (!reached_end_of_context (context))
2812 	{
2813 	  consume_next_token_from_context (pfile, &result,
2814 					   &virt_loc);
2815 	  if (result->flags & PASTE_LEFT)
2816 	    {
2817 	      paste_all_tokens (pfile, result);
2818 	      if (pfile->state.in_directive)
2819 		continue;
2820 	      result = padding_token (pfile, result);
2821 	      goto out;
2822 	    }
2823 	}
2824       else
2825 	{
2826 	  if (pfile->context->c.macro)
2827 	    ++num_expanded_macros_counter;
2828 	  _cpp_pop_context (pfile);
2829 	  if (pfile->state.in_directive)
2830 	    continue;
2831 	  result = &pfile->avoid_paste;
2832 	  goto out;
2833 	}
2834 
2835       if (pfile->state.in_directive && result->type == CPP_COMMENT)
2836 	continue;
2837 
2838       if (result->type != CPP_NAME)
2839 	break;
2840 
2841       node = result->val.node.node;
2842 
2843       if (node->type == NT_VOID || (result->flags & NO_EXPAND))
2844 	break;
2845 
2846       if (!(node->flags & NODE_DISABLED))
2847 	{
2848 	  int ret = 0;
2849 	  /* If not in a macro context, and we're going to start an
2850 	     expansion, record the location and the top level macro
2851 	     about to be expanded.  */
2852 	  if (!in_macro_expansion_p (pfile))
2853 	    {
2854 	      pfile->invocation_location = result->src_loc;
2855 	      pfile->top_most_macro_node = node;
2856 	    }
2857 	  if (pfile->state.prevent_expansion)
2858 	    break;
2859 
2860 	  /* Conditional macros require that a predicate be evaluated
2861 	     first.  */
2862 	  if ((node->flags & NODE_CONDITIONAL) != 0)
2863 	    {
2864 	      if (pfile->cb.macro_to_expand)
2865 		{
2866 		  bool whitespace_after;
2867 		  const cpp_token *peek_tok = cpp_peek_token (pfile, 0);
2868 
2869 		  whitespace_after = (peek_tok->type == CPP_PADDING
2870 				      || (peek_tok->flags & PREV_WHITE));
2871 		  node = pfile->cb.macro_to_expand (pfile, result);
2872 		  if (node)
2873 		    ret = enter_macro_context (pfile, node, result,
2874 					       virt_loc);
2875 		  else if (whitespace_after)
2876 		    {
2877 		      /* If macro_to_expand hook returned NULL and it
2878 			 ate some tokens, see if we don't need to add
2879 			 a padding token in between this and the
2880 			 next token.  */
2881 		      peek_tok = cpp_peek_token (pfile, 0);
2882 		      if (peek_tok->type != CPP_PADDING
2883 			  && (peek_tok->flags & PREV_WHITE) == 0)
2884 			_cpp_push_token_context (pfile, NULL,
2885 						 padding_token (pfile,
2886 								peek_tok), 1);
2887 		    }
2888 		}
2889 	    }
2890 	  else
2891 	    ret = enter_macro_context (pfile, node, result,
2892 				       virt_loc);
2893 	  if (ret)
2894  	    {
2895 	      if (pfile->state.in_directive || ret == 2)
2896 		continue;
2897 	      result = padding_token (pfile, result);
2898 	      goto out;
2899 	    }
2900 	}
2901       else
2902 	{
2903 	  /* Flag this token as always unexpandable.  FIXME: move this
2904 	     to collect_args()?.  */
2905 	  cpp_token *t = _cpp_temp_token (pfile);
2906 	  t->type = result->type;
2907 	  t->flags = result->flags | NO_EXPAND;
2908 	  t->val = result->val;
2909 	  result = t;
2910 	}
2911 
2912       break;
2913     }
2914 
2915  out:
2916   if (location != NULL)
2917     {
2918       if (virt_loc == 0)
2919 	virt_loc = result->src_loc;
2920       *location = virt_loc;
2921 
2922       if (!CPP_OPTION (pfile, track_macro_expansion)
2923 	  && macro_of_context (pfile->context) != NULL)
2924 	/* We are in a macro expansion context, are not tracking
2925 	   virtual location, but were asked to report the location
2926 	   of the expansion point of the macro being expanded.  */
2927 	*location = pfile->invocation_location;
2928 
2929       *location = maybe_adjust_loc_for_trad_cpp (pfile, *location);
2930     }
2931 
2932   pfile->about_to_expand_macro_p = saved_about_to_expand_macro;
2933   return result;
2934 }
2935 
2936 /* External routine to get a token.  Also used nearly everywhere
2937    internally, except for places where we know we can safely call
2938    _cpp_lex_token directly, such as lexing a directive name.
2939 
2940    Macro expansions and directives are transparently handled,
2941    including entering included files.  Thus tokens are post-macro
2942    expansion, and after any intervening directives.  External callers
2943    see CPP_EOF only at EOF.  Internal callers also see it when meeting
2944    a directive inside a macro call, when at the end of a directive and
2945    state.in_directive is still 1, and at the end of argument
2946    pre-expansion.  */
2947 const cpp_token *
cpp_get_token(cpp_reader * pfile)2948 cpp_get_token (cpp_reader *pfile)
2949 {
2950   return cpp_get_token_1 (pfile, NULL);
2951 }
2952 
2953 /* Like cpp_get_token, but also returns a virtual token location
2954    separate from the spelling location carried by the returned token.
2955 
2956    LOC is an out parameter; *LOC is set to the location "as expected
2957    by the user".  This matters when a token results from macro
2958    expansion; in that case the token's spelling location indicates the
2959    locus of the token in the definition of the macro but *LOC
2960    virtually encodes all the other meaningful locuses associated to
2961    the token.
2962 
2963    What? virtual location? Yes, virtual location.
2964 
2965    If the token results from macro expansion and if macro expansion
2966    location tracking is enabled its virtual location encodes (at the
2967    same time):
2968 
2969    - the spelling location of the token
2970 
2971    - the locus of the macro expansion point
2972 
2973    - the locus of the point where the token got instantiated as part
2974      of the macro expansion process.
2975 
2976    You have to use the linemap API to get the locus you are interested
2977    in from a given virtual location.
2978 
2979    Note however that virtual locations are not necessarily ordered for
2980    relations '<' and '>'.  One must use the function
2981    linemap_location_before_p instead of using the relational operator
2982    '<'.
2983 
2984    If macro expansion tracking is off and if the token results from
2985    macro expansion the virtual location is the expansion point of the
2986    macro that got expanded.
2987 
2988    When the token doesn't result from macro expansion, the virtual
2989    location is just the same thing as its spelling location.  */
2990 
2991 const cpp_token *
cpp_get_token_with_location(cpp_reader * pfile,location_t * loc)2992 cpp_get_token_with_location (cpp_reader *pfile, location_t *loc)
2993 {
2994   return cpp_get_token_1 (pfile, loc);
2995 }
2996 
2997 /* Returns true if we're expanding an object-like macro that was
2998    defined in a system header.  Just checks the macro at the top of
2999    the stack.  Used for diagnostic suppression.  */
3000 int
cpp_sys_macro_p(cpp_reader * pfile)3001 cpp_sys_macro_p (cpp_reader *pfile)
3002 {
3003   cpp_hashnode *node = NULL;
3004 
3005   if (pfile->context->tokens_kind == TOKENS_KIND_EXTENDED)
3006     node = pfile->context->c.mc->macro_node;
3007   else
3008     node = pfile->context->c.macro;
3009 
3010   return node && node->value.macro && node->value.macro->syshdr;
3011 }
3012 
3013 /* Read each token in, until end of the current file.  Directives are
3014    transparently processed.  */
3015 void
cpp_scan_nooutput(cpp_reader * pfile)3016 cpp_scan_nooutput (cpp_reader *pfile)
3017 {
3018   /* Request a CPP_EOF token at the end of this file, rather than
3019      transparently continuing with the including file.  */
3020   pfile->buffer->return_at_eof = true;
3021 
3022   pfile->state.discarding_output++;
3023   pfile->state.prevent_expansion++;
3024 
3025   if (CPP_OPTION (pfile, traditional))
3026     while (_cpp_read_logical_line_trad (pfile))
3027       ;
3028   else
3029     while (cpp_get_token (pfile)->type != CPP_EOF)
3030       ;
3031 
3032   pfile->state.discarding_output--;
3033   pfile->state.prevent_expansion--;
3034 }
3035 
3036 /* Step back one or more tokens obtained from the lexer.  */
3037 void
_cpp_backup_tokens_direct(cpp_reader * pfile,unsigned int count)3038 _cpp_backup_tokens_direct (cpp_reader *pfile, unsigned int count)
3039 {
3040   pfile->lookaheads += count;
3041   while (count--)
3042     {
3043       pfile->cur_token--;
3044       if (pfile->cur_token == pfile->cur_run->base
3045           /* Possible with -fpreprocessed and no leading #line.  */
3046           && pfile->cur_run->prev != NULL)
3047         {
3048           pfile->cur_run = pfile->cur_run->prev;
3049           pfile->cur_token = pfile->cur_run->limit;
3050         }
3051     }
3052 }
3053 
3054 /* Step back one (or more) tokens.  Can only step back more than 1 if
3055    they are from the lexer, and not from macro expansion.  */
3056 void
_cpp_backup_tokens(cpp_reader * pfile,unsigned int count)3057 _cpp_backup_tokens (cpp_reader *pfile, unsigned int count)
3058 {
3059   if (pfile->context->prev == NULL)
3060     _cpp_backup_tokens_direct (pfile, count);
3061   else
3062     {
3063       if (count != 1)
3064 	abort ();
3065       if (pfile->context->tokens_kind == TOKENS_KIND_DIRECT)
3066 	FIRST (pfile->context).token--;
3067       else if (pfile->context->tokens_kind == TOKENS_KIND_INDIRECT)
3068 	FIRST (pfile->context).ptoken--;
3069       else if (pfile->context->tokens_kind == TOKENS_KIND_EXTENDED)
3070 	{
3071 	  FIRST (pfile->context).ptoken--;
3072 	  if (pfile->context->c.macro)
3073 	    {
3074 	      macro_context *m = pfile->context->c.mc;
3075 	      m->cur_virt_loc--;
3076 	      gcc_checking_assert (m->cur_virt_loc >= m->virt_locs);
3077 	    }
3078 	  else
3079 	    abort ();
3080 	}
3081       else
3082 	abort ();
3083     }
3084 }
3085 
3086 /* #define directive parsing and handling.  */
3087 
3088 /* Returns true if a macro redefinition warning is required.  */
3089 static bool
warn_of_redefinition(cpp_reader * pfile,cpp_hashnode * node,const cpp_macro * macro2)3090 warn_of_redefinition (cpp_reader *pfile, cpp_hashnode *node,
3091 		      const cpp_macro *macro2)
3092 {
3093   /* Some redefinitions need to be warned about regardless.  */
3094   if (node->flags & NODE_WARN)
3095     return true;
3096 
3097   /* Suppress warnings for builtins that lack the NODE_WARN flag,
3098      unless Wbuiltin-macro-redefined.  */
3099   if (cpp_builtin_macro_p (node))
3100     return CPP_OPTION (pfile, warn_builtin_macro_redefined);
3101 
3102   /* Redefinitions of conditional (context-sensitive) macros, on
3103      the other hand, must be allowed silently.  */
3104   if (node->flags & NODE_CONDITIONAL)
3105     return false;
3106 
3107   cpp_macro *macro1 = node->value.macro;
3108   if (macro1->lazy)
3109     {
3110       /* We don't want to mark MACRO as used, but do need to finalize
3111 	 its laziness.  */
3112       pfile->cb.user_lazy_macro (pfile, macro1, macro1->lazy - 1);
3113       macro1->lazy = 0;
3114     }
3115 
3116   /* Redefinition of a macro is allowed if and only if the old and new
3117      definitions are the same.  (6.10.3 paragraph 2).  */
3118 
3119   /* Don't check count here as it can be different in valid
3120      traditional redefinitions with just whitespace differences.  */
3121   if (macro1->paramc != macro2->paramc
3122       || macro1->fun_like != macro2->fun_like
3123       || macro1->variadic != macro2->variadic)
3124     return true;
3125 
3126   /* Check parameter spellings.  */
3127   for (unsigned i = macro1->paramc; i--; )
3128     if (macro1->parm.params[i] != macro2->parm.params[i])
3129       return true;
3130 
3131   /* Check the replacement text or tokens.  */
3132   if (macro1->kind == cmk_traditional)
3133     return _cpp_expansions_different_trad (macro1, macro2);
3134 
3135   if (macro1->count != macro2->count)
3136     return true;
3137 
3138   for (unsigned i= macro1->count; i--; )
3139     if (!_cpp_equiv_tokens (&macro1->exp.tokens[i], &macro2->exp.tokens[i]))
3140       return true;
3141 
3142   return false;
3143 }
3144 
3145 /* Free the definition of hashnode H.  */
3146 void
_cpp_free_definition(cpp_hashnode * h)3147 _cpp_free_definition (cpp_hashnode *h)
3148 {
3149   /* Macros and assertions no longer have anything to free.  */
3150   h->type = NT_VOID;
3151   h->value.answers = NULL;
3152   h->flags &= ~(NODE_DISABLED | NODE_USED);
3153 }
3154 
3155 /* Save parameter NODE (spelling SPELLING) to the parameter list of
3156    macro MACRO.  Returns true on success, false on failure.   */
3157 bool
_cpp_save_parameter(cpp_reader * pfile,unsigned n,cpp_hashnode * node,cpp_hashnode * spelling)3158 _cpp_save_parameter (cpp_reader *pfile, unsigned n, cpp_hashnode *node,
3159 		     cpp_hashnode *spelling)
3160 {
3161   /* Constraint 6.10.3.6 - duplicate parameter names.  */
3162   if (node->type == NT_MACRO_ARG)
3163     {
3164       cpp_error (pfile, CPP_DL_ERROR, "duplicate macro parameter \"%s\"",
3165 		 NODE_NAME (node));
3166       return false;
3167     }
3168 
3169   unsigned len = (n + 1) * sizeof (struct macro_arg_saved_data);
3170   if (len > pfile->macro_buffer_len)
3171     {
3172       pfile->macro_buffer
3173 	= XRESIZEVEC (unsigned char, pfile->macro_buffer, len);
3174       pfile->macro_buffer_len = len;
3175     }
3176 
3177   macro_arg_saved_data *saved = (macro_arg_saved_data *)pfile->macro_buffer;
3178   saved[n].canonical_node = node;
3179   saved[n].value = node->value;
3180   saved[n].type = node->type;
3181 
3182   void *base = _cpp_reserve_room (pfile, n * sizeof (cpp_hashnode *),
3183 				  sizeof (cpp_hashnode *));
3184   ((cpp_hashnode **)base)[n] = spelling;
3185 
3186   /* Morph into a macro arg.  */
3187   node->type = NT_MACRO_ARG;
3188   /* Index is 1 based.  */
3189   node->value.arg_index = n + 1;
3190 
3191   return true;
3192 }
3193 
3194 /* Restore the parameters to their previous state.  */
3195 void
_cpp_unsave_parameters(cpp_reader * pfile,unsigned n)3196 _cpp_unsave_parameters (cpp_reader *pfile, unsigned n)
3197 {
3198   /* Clear the fast argument lookup indices.  */
3199   while (n--)
3200     {
3201       struct macro_arg_saved_data *save =
3202 	&((struct macro_arg_saved_data *) pfile->macro_buffer)[n];
3203 
3204       struct cpp_hashnode *node = save->canonical_node;
3205       node->type = save->type;
3206       node->value = save->value;
3207     }
3208 }
3209 
3210 /* Check the syntax of the parameters in a MACRO definition.  Return
3211    false on failure.  Set *N_PTR and *VARADIC_PTR as appropriate.
3212    '(' ')'
3213    '(' parm-list ',' last-parm ')'
3214    '(' last-parm ')'
3215    parm-list: name
3216             | parm-list, name
3217    last-parm: name
3218    	    | name '...'
3219             | '...'
3220 */
3221 
3222 static bool
parse_params(cpp_reader * pfile,unsigned * n_ptr,bool * varadic_ptr)3223 parse_params (cpp_reader *pfile, unsigned *n_ptr, bool *varadic_ptr)
3224 {
3225   unsigned nparms = 0;
3226   bool ok = false;
3227 
3228   for (bool prev_ident = false;;)
3229     {
3230       const cpp_token *token = _cpp_lex_token (pfile);
3231 
3232       switch (token->type)
3233 	{
3234 	case CPP_COMMENT:
3235 	  /* Allow/ignore comments in parameter lists if we are
3236 	     preserving comments in macro expansions.  */
3237 	  if (!CPP_OPTION (pfile, discard_comments_in_macro_exp))
3238 	    break;
3239 
3240 	  /* FALLTHRU  */
3241 	default:
3242 	bad:
3243 	  {
3244 	    const char *const msgs[5] =
3245 	      {
3246 	       N_("expected parameter name, found \"%s\""),
3247 	       N_("expected ',' or ')', found \"%s\""),
3248 	       N_("expected parameter name before end of line"),
3249 	       N_("expected ')' before end of line"),
3250 	       N_("expected ')' after \"...\"")
3251 	      };
3252 	    unsigned ix = prev_ident;
3253 	    const unsigned char *as_text = NULL;
3254 	    if (*varadic_ptr)
3255 	      ix = 4;
3256 	    else if (token->type == CPP_EOF)
3257 	      ix += 2;
3258 	    else
3259 	      as_text = cpp_token_as_text (pfile, token);
3260 	    cpp_error (pfile, CPP_DL_ERROR, msgs[ix], as_text);
3261 	  }
3262 	  goto out;
3263 
3264 	case CPP_NAME:
3265 	  if (prev_ident || *varadic_ptr)
3266 	    goto bad;
3267 	  prev_ident = true;
3268 
3269 	  if (!_cpp_save_parameter (pfile, nparms, token->val.node.node,
3270 				    token->val.node.spelling))
3271 	    goto out;
3272 	  nparms++;
3273 	  break;
3274 
3275 	case CPP_CLOSE_PAREN:
3276 	  if (prev_ident || !nparms || *varadic_ptr)
3277 	    {
3278 	      ok = true;
3279 	      goto out;
3280 	    }
3281 
3282 	  /* FALLTHRU */
3283 	case CPP_COMMA:
3284 	  if (!prev_ident || *varadic_ptr)
3285 	    goto bad;
3286 	  prev_ident = false;
3287 	  break;
3288 
3289 	case CPP_ELLIPSIS:
3290 	  if (*varadic_ptr)
3291 	    goto bad;
3292 	  *varadic_ptr = true;
3293 	  if (!prev_ident)
3294 	    {
3295 	      /* An ISO bare ellipsis.  */
3296 	      _cpp_save_parameter (pfile, nparms,
3297 				   pfile->spec_nodes.n__VA_ARGS__,
3298 				   pfile->spec_nodes.n__VA_ARGS__);
3299 	      nparms++;
3300 	      pfile->state.va_args_ok = 1;
3301 	      if (! CPP_OPTION (pfile, c99)
3302 		  && CPP_OPTION (pfile, cpp_pedantic)
3303 		  && CPP_OPTION (pfile, warn_variadic_macros))
3304 		cpp_pedwarning
3305 		  (pfile, CPP_W_VARIADIC_MACROS,
3306 		   CPP_OPTION (pfile, cplusplus)
3307 		   ? N_("anonymous variadic macros were introduced in C++11")
3308 		   : N_("anonymous variadic macros were introduced in C99"));
3309 	      else if (CPP_OPTION (pfile, cpp_warn_c90_c99_compat) > 0
3310 		       && ! CPP_OPTION (pfile, cplusplus))
3311 		cpp_error (pfile, CPP_DL_WARNING,
3312 			   "anonymous variadic macros were introduced in C99");
3313 	    }
3314 	  else if (CPP_OPTION (pfile, cpp_pedantic)
3315 		   && CPP_OPTION (pfile, warn_variadic_macros))
3316 	    cpp_pedwarning (pfile, CPP_W_VARIADIC_MACROS,
3317 			    CPP_OPTION (pfile, cplusplus)
3318 			    ? N_("ISO C++ does not permit named variadic macros")
3319 			    : N_("ISO C does not permit named variadic macros"));
3320 	  break;
3321 	}
3322     }
3323 
3324  out:
3325   *n_ptr = nparms;
3326 
3327   return ok;
3328 }
3329 
3330 /* Lex a token from the expansion of MACRO, but mark parameters as we
3331    find them and warn of traditional stringification.  */
3332 static cpp_macro *
lex_expansion_token(cpp_reader * pfile,cpp_macro * macro)3333 lex_expansion_token (cpp_reader *pfile, cpp_macro *macro)
3334 {
3335   macro = (cpp_macro *)_cpp_reserve_room (pfile,
3336 					  sizeof (cpp_macro) - sizeof (cpp_token)
3337 					  + macro->count * sizeof (cpp_token),
3338 					  sizeof (cpp_token));
3339   cpp_token *saved_cur_token = pfile->cur_token;
3340   pfile->cur_token = &macro->exp.tokens[macro->count];
3341   cpp_token *token = _cpp_lex_direct (pfile);
3342   pfile->cur_token = saved_cur_token;
3343 
3344   /* Is this a parameter?  */
3345   if (token->type == CPP_NAME && token->val.node.node->type == NT_MACRO_ARG)
3346     {
3347       /* Morph into a parameter reference.  */
3348       cpp_hashnode *spelling = token->val.node.spelling;
3349       token->type = CPP_MACRO_ARG;
3350       token->val.macro_arg.arg_no = token->val.node.node->value.arg_index;
3351       token->val.macro_arg.spelling = spelling;
3352     }
3353   else if (CPP_WTRADITIONAL (pfile) && macro->paramc > 0
3354 	   && (token->type == CPP_STRING || token->type == CPP_CHAR))
3355     check_trad_stringification (pfile, macro, &token->val.str);
3356 
3357   return macro;
3358 }
3359 
3360 static cpp_macro *
create_iso_definition(cpp_reader * pfile)3361 create_iso_definition (cpp_reader *pfile)
3362 {
3363   bool following_paste_op = false;
3364   const char *paste_op_error_msg =
3365     N_("'##' cannot appear at either end of a macro expansion");
3366   unsigned int num_extra_tokens = 0;
3367   unsigned nparms = 0;
3368   cpp_hashnode **params = NULL;
3369   bool varadic = false;
3370   bool ok = false;
3371   cpp_macro *macro = NULL;
3372 
3373   /* Look at the first token, to see if this is a function-like
3374      macro.   */
3375   cpp_token first;
3376   cpp_token *saved_cur_token = pfile->cur_token;
3377   pfile->cur_token = &first;
3378   cpp_token *token = _cpp_lex_direct (pfile);
3379   pfile->cur_token = saved_cur_token;
3380 
3381   if (token->flags & PREV_WHITE)
3382     /* Preceeded by space, must be part of expansion.  */;
3383   else if (token->type == CPP_OPEN_PAREN)
3384     {
3385       /* An open-paren, get a parameter list.  */
3386       if (!parse_params (pfile, &nparms, &varadic))
3387 	goto out;
3388 
3389       params = (cpp_hashnode **)_cpp_commit_buff
3390 	(pfile, sizeof (cpp_hashnode *) * nparms);
3391       token = NULL;
3392     }
3393   else if (token->type != CPP_EOF
3394 	   && !(token->type == CPP_COMMENT
3395 		&& ! CPP_OPTION (pfile, discard_comments_in_macro_exp)))
3396     {
3397       /* While ISO C99 requires whitespace before replacement text
3398 	 in a macro definition, ISO C90 with TC1 allows characters
3399 	 from the basic source character set there.  */
3400       if (CPP_OPTION (pfile, c99))
3401 	cpp_error (pfile, CPP_DL_PEDWARN,
3402 		   CPP_OPTION (pfile, cplusplus)
3403 		   ? N_("ISO C++11 requires whitespace after the macro name")
3404 		   : N_("ISO C99 requires whitespace after the macro name"));
3405       else
3406 	{
3407 	  enum cpp_diagnostic_level warntype = CPP_DL_WARNING;
3408 	  switch (token->type)
3409 	    {
3410 	    case CPP_ATSIGN:
3411 	    case CPP_AT_NAME:
3412 	    case CPP_OBJC_STRING:
3413 	      /* '@' is not in basic character set.  */
3414 	      warntype = CPP_DL_PEDWARN;
3415 	      break;
3416 	    case CPP_OTHER:
3417 	      /* Basic character set sans letters, digits and _.  */
3418 	      if (strchr ("!\"#%&'()*+,-./:;<=>?[\\]^{|}~",
3419 			  token->val.str.text[0]) == NULL)
3420 		warntype = CPP_DL_PEDWARN;
3421 	      break;
3422 	    default:
3423 	      /* All other tokens start with a character from basic
3424 		 character set.  */
3425 	      break;
3426 	    }
3427 	  cpp_error (pfile, warntype,
3428 		     "missing whitespace after the macro name");
3429 	}
3430     }
3431 
3432   macro = _cpp_new_macro (pfile, cmk_macro,
3433 			  _cpp_reserve_room (pfile, 0, sizeof (cpp_macro)));
3434 
3435   if (!token)
3436     {
3437       macro->variadic = varadic;
3438       macro->paramc = nparms;
3439       macro->parm.params = params;
3440       macro->fun_like = true;
3441     }
3442   else
3443     {
3444       /* Preserve the token we peeked, there is already a single slot for it.  */
3445       macro->exp.tokens[0] = *token;
3446       token = &macro->exp.tokens[0];
3447       macro->count = 1;
3448     }
3449 
3450   for (vaopt_state vaopt_tracker (pfile, macro->variadic, NULL);; token = NULL)
3451     {
3452       if (!token)
3453 	{
3454 	  macro = lex_expansion_token (pfile, macro);
3455 	  token = &macro->exp.tokens[macro->count++];
3456 	}
3457 
3458       /* Check the stringifying # constraint 6.10.3.2.1 of
3459 	 function-like macros when lexing the subsequent token.  */
3460       if (macro->count > 1 && token[-1].type == CPP_HASH && macro->fun_like)
3461 	{
3462 	  if (token->type == CPP_MACRO_ARG)
3463 	    {
3464 	      if (token->flags & PREV_WHITE)
3465 		token->flags |= SP_PREV_WHITE;
3466 	      if (token[-1].flags & DIGRAPH)
3467 		token->flags |= SP_DIGRAPH;
3468 	      token->flags &= ~PREV_WHITE;
3469 	      token->flags |= STRINGIFY_ARG;
3470 	      token->flags |= token[-1].flags & PREV_WHITE;
3471 	      token[-1] = token[0];
3472 	      macro->count--;
3473 	    }
3474 	  /* Let assembler get away with murder.  */
3475 	  else if (CPP_OPTION (pfile, lang) != CLK_ASM)
3476 	    {
3477 	      cpp_error (pfile, CPP_DL_ERROR,
3478 			 "'#' is not followed by a macro parameter");
3479 	      goto out;
3480 	    }
3481 	}
3482 
3483       if (token->type == CPP_EOF)
3484 	{
3485 	  /* Paste operator constraint 6.10.3.3.1:
3486 	     Token-paste ##, can appear in both object-like and
3487 	     function-like macros, but not at the end.  */
3488 	  if (following_paste_op)
3489 	    {
3490 	      cpp_error (pfile, CPP_DL_ERROR, paste_op_error_msg);
3491 	      goto out;
3492 	    }
3493 	  if (!vaopt_tracker.completed ())
3494 	    goto out;
3495 	  break;
3496 	}
3497 
3498       /* Paste operator constraint 6.10.3.3.1.  */
3499       if (token->type == CPP_PASTE)
3500 	{
3501 	  /* Token-paste ##, can appear in both object-like and
3502 	     function-like macros, but not at the beginning.  */
3503 	  if (macro->count == 1)
3504 	    {
3505 	      cpp_error (pfile, CPP_DL_ERROR, paste_op_error_msg);
3506 	      goto out;
3507 	    }
3508 
3509 	  if (following_paste_op)
3510 	    {
3511 	      /* Consecutive paste operators.  This one will be moved
3512 		 to the end.  */
3513 	      num_extra_tokens++;
3514 	      token->val.token_no = macro->count - 1;
3515 	    }
3516 	  else
3517 	    {
3518 	      /* Drop the paste operator.  */
3519 	      --macro->count;
3520 	      token[-1].flags |= PASTE_LEFT;
3521 	      if (token->flags & DIGRAPH)
3522 		token[-1].flags |= SP_DIGRAPH;
3523 	      if (token->flags & PREV_WHITE)
3524 		token[-1].flags |= SP_PREV_WHITE;
3525 	    }
3526 	  following_paste_op = true;
3527 	}
3528       else
3529 	following_paste_op = false;
3530 
3531       if (vaopt_tracker.update (token) == vaopt_state::ERROR)
3532 	goto out;
3533     }
3534 
3535   /* We're committed to winning now.  */
3536   ok = true;
3537 
3538   /* Don't count the CPP_EOF.  */
3539   macro->count--;
3540 
3541   macro = (cpp_macro *)_cpp_commit_buff
3542     (pfile, sizeof (cpp_macro) - sizeof (cpp_token)
3543      + sizeof (cpp_token) * macro->count);
3544 
3545   /* Clear whitespace on first token.  */
3546   if (macro->count)
3547     macro->exp.tokens[0].flags &= ~PREV_WHITE;
3548 
3549   if (num_extra_tokens)
3550     {
3551       /* Place second and subsequent ## or %:%: tokens in sequences of
3552 	 consecutive such tokens at the end of the list to preserve
3553 	 information about where they appear, how they are spelt and
3554 	 whether they are preceded by whitespace without otherwise
3555 	 interfering with macro expansion.   Remember, this is
3556 	 extremely rare, so efficiency is not a priority.  */
3557       cpp_token *temp = (cpp_token *)_cpp_reserve_room
3558 	(pfile, 0, num_extra_tokens * sizeof (cpp_token));
3559       unsigned extra_ix = 0, norm_ix = 0;
3560       cpp_token *exp = macro->exp.tokens;
3561       for (unsigned ix = 0; ix != macro->count; ix++)
3562 	if (exp[ix].type == CPP_PASTE)
3563 	  temp[extra_ix++] = exp[ix];
3564 	else
3565 	  exp[norm_ix++] = exp[ix];
3566       memcpy (&exp[norm_ix], temp, num_extra_tokens * sizeof (cpp_token));
3567 
3568       /* Record there are extra tokens.  */
3569       macro->extra_tokens = 1;
3570     }
3571 
3572  out:
3573   pfile->state.va_args_ok = 0;
3574   _cpp_unsave_parameters (pfile, nparms);
3575 
3576   return ok ? macro : NULL;
3577 }
3578 
3579 cpp_macro *
_cpp_new_macro(cpp_reader * pfile,cpp_macro_kind kind,void * placement)3580 _cpp_new_macro (cpp_reader *pfile, cpp_macro_kind kind, void *placement)
3581 {
3582   cpp_macro *macro = (cpp_macro *) placement;
3583 
3584   macro->line = pfile->directive_line;
3585   macro->parm.params = 0;
3586   macro->lazy = 0;
3587   macro->paramc = 0;
3588   macro->variadic = 0;
3589   macro->used = !CPP_OPTION (pfile, warn_unused_macros);
3590   macro->count = 0;
3591   macro->fun_like = 0;
3592   macro->extra_tokens = 0;
3593   /* To suppress some diagnostics.  */
3594   macro->syshdr = pfile->buffer && pfile->buffer->sysp != 0;
3595 
3596   macro->kind = kind;
3597 
3598   return macro;
3599 }
3600 
3601 /* Parse a macro and save its expansion.  Returns nonzero on success.  */
3602 bool
_cpp_create_definition(cpp_reader * pfile,cpp_hashnode * node)3603 _cpp_create_definition (cpp_reader *pfile, cpp_hashnode *node)
3604 {
3605   cpp_macro *macro;
3606 
3607   if (CPP_OPTION (pfile, traditional))
3608     macro = _cpp_create_trad_definition (pfile);
3609   else
3610     macro = create_iso_definition (pfile);
3611 
3612   if (!macro)
3613     return false;
3614 
3615   if (cpp_macro_p (node))
3616     {
3617       if (CPP_OPTION (pfile, warn_unused_macros))
3618 	_cpp_warn_if_unused_macro (pfile, node, NULL);
3619 
3620       if (warn_of_redefinition (pfile, node, macro))
3621 	{
3622           const enum cpp_warning_reason reason
3623 	    = (cpp_builtin_macro_p (node) && !(node->flags & NODE_WARN))
3624 	    ? CPP_W_BUILTIN_MACRO_REDEFINED : CPP_W_NONE;
3625 
3626 	  bool warned =
3627 	    cpp_pedwarning_with_line (pfile, reason,
3628 				      pfile->directive_line, 0,
3629 				      "\"%s\" redefined", NODE_NAME (node));
3630 
3631 	  if (warned && cpp_user_macro_p (node))
3632 	    cpp_error_with_line (pfile, CPP_DL_NOTE,
3633 				 node->value.macro->line, 0,
3634 			 "this is the location of the previous definition");
3635 	}
3636       _cpp_free_definition (node);
3637     }
3638 
3639   /* Enter definition in hash table.  */
3640   node->type = NT_USER_MACRO;
3641   node->value.macro = macro;
3642   if (! ustrncmp (NODE_NAME (node), DSC ("__STDC_"))
3643       && ustrcmp (NODE_NAME (node), (const uchar *) "__STDC_FORMAT_MACROS")
3644       /* __STDC_LIMIT_MACROS and __STDC_CONSTANT_MACROS are mentioned
3645 	 in the C standard, as something that one must use in C++.
3646 	 However DR#593 and C++11 indicate that they play no role in C++.
3647 	 We special-case them anyway.  */
3648       && ustrcmp (NODE_NAME (node), (const uchar *) "__STDC_LIMIT_MACROS")
3649       && ustrcmp (NODE_NAME (node), (const uchar *) "__STDC_CONSTANT_MACROS"))
3650     node->flags |= NODE_WARN;
3651 
3652   /* If user defines one of the conditional macros, remove the
3653      conditional flag */
3654   node->flags &= ~NODE_CONDITIONAL;
3655 
3656   return true;
3657 }
3658 
3659 extern void
cpp_define_lazily(cpp_reader * pfile,cpp_hashnode * node,unsigned num)3660 cpp_define_lazily (cpp_reader *pfile, cpp_hashnode *node, unsigned num)
3661 {
3662   cpp_macro *macro = node->value.macro;
3663 
3664   gcc_checking_assert (pfile->cb.user_lazy_macro && macro && num < UCHAR_MAX);
3665 
3666   macro->lazy = num + 1;
3667 }
3668 
3669 /* Notify the use of NODE in a macro-aware context (i.e. expanding it,
3670    or testing its existance).  Also applies any lazy definition.  */
3671 
3672 extern void
_cpp_notify_macro_use(cpp_reader * pfile,cpp_hashnode * node)3673 _cpp_notify_macro_use (cpp_reader *pfile, cpp_hashnode *node)
3674 {
3675   node->flags |= NODE_USED;
3676   switch (node->type)
3677     {
3678     case NT_USER_MACRO:
3679       {
3680 	cpp_macro *macro = node->value.macro;
3681 	if (macro->lazy)
3682 	  {
3683 	    pfile->cb.user_lazy_macro (pfile, macro, macro->lazy - 1);
3684 	    macro->lazy = 0;
3685 	  }
3686       }
3687       /* FALLTHROUGH.  */
3688 
3689     case NT_BUILTIN_MACRO:
3690       if (pfile->cb.used_define)
3691 	pfile->cb.used_define (pfile, pfile->directive_line, node);
3692       break;
3693 
3694     case NT_VOID:
3695       if (pfile->cb.used_undef)
3696 	pfile->cb.used_undef (pfile, pfile->directive_line, node);
3697       break;
3698 
3699     default:
3700       abort ();
3701     }
3702 }
3703 
3704 /* Warn if a token in STRING matches one of a function-like MACRO's
3705    parameters.  */
3706 static void
check_trad_stringification(cpp_reader * pfile,const cpp_macro * macro,const cpp_string * string)3707 check_trad_stringification (cpp_reader *pfile, const cpp_macro *macro,
3708 			    const cpp_string *string)
3709 {
3710   unsigned int i, len;
3711   const uchar *p, *q, *limit;
3712 
3713   /* Loop over the string.  */
3714   limit = string->text + string->len - 1;
3715   for (p = string->text + 1; p < limit; p = q)
3716     {
3717       /* Find the start of an identifier.  */
3718       while (p < limit && !is_idstart (*p))
3719 	p++;
3720 
3721       /* Find the end of the identifier.  */
3722       q = p;
3723       while (q < limit && is_idchar (*q))
3724 	q++;
3725 
3726       len = q - p;
3727 
3728       /* Loop over the function macro arguments to see if the
3729 	 identifier inside the string matches one of them.  */
3730       for (i = 0; i < macro->paramc; i++)
3731 	{
3732 	  const cpp_hashnode *node = macro->parm.params[i];
3733 
3734 	  if (NODE_LEN (node) == len
3735 	      && !memcmp (p, NODE_NAME (node), len))
3736 	    {
3737 	      cpp_warning (pfile, CPP_W_TRADITIONAL,
3738 	   "macro argument \"%s\" would be stringified in traditional C",
3739 			 NODE_NAME (node));
3740 	      break;
3741 	    }
3742 	}
3743     }
3744 }
3745 
3746 /* Returns the name, arguments and expansion of a macro, in a format
3747    suitable to be read back in again, and therefore also for DWARF 2
3748    debugging info.  e.g. "PASTE(X, Y) X ## Y", or "MACNAME EXPANSION".
3749    Caller is expected to generate the "#define" bit if needed.  The
3750    returned text is temporary, and automatically freed later.  */
3751 const unsigned char *
cpp_macro_definition(cpp_reader * pfile,cpp_hashnode * node)3752 cpp_macro_definition (cpp_reader *pfile, cpp_hashnode *node)
3753 {
3754   unsigned int i, len;
3755   unsigned char *buffer;
3756 
3757   gcc_checking_assert (cpp_user_macro_p (node));
3758 
3759   const cpp_macro *macro = node->value.macro;
3760 
3761   /* Calculate length.  */
3762   len = NODE_LEN (node) * 10 + 2;		/* ' ' and NUL.  */
3763   if (macro->fun_like)
3764     {
3765       len += 4;		/* "()" plus possible final ".." of named
3766 			   varargs (we have + 1 below).  */
3767       for (i = 0; i < macro->paramc; i++)
3768 	len += NODE_LEN (macro->parm.params[i]) + 1; /* "," */
3769     }
3770 
3771   /* This should match below where we fill in the buffer.  */
3772   if (CPP_OPTION (pfile, traditional))
3773     len += _cpp_replacement_text_len (macro);
3774   else
3775     {
3776       unsigned int count = macro_real_token_count (macro);
3777       for (i = 0; i < count; i++)
3778 	{
3779 	  const cpp_token *token = &macro->exp.tokens[i];
3780 
3781 	  if (token->type == CPP_MACRO_ARG)
3782 	    len += NODE_LEN (token->val.macro_arg.spelling);
3783 	  else
3784 	    len += cpp_token_len (token);
3785 
3786 	  if (token->flags & STRINGIFY_ARG)
3787 	    len++;			/* "#" */
3788 	  if (token->flags & PASTE_LEFT)
3789 	    len += 3;		/* " ##" */
3790 	  if (token->flags & PREV_WHITE)
3791 	    len++;              /* " " */
3792 	}
3793     }
3794 
3795   if (len > pfile->macro_buffer_len)
3796     {
3797       pfile->macro_buffer = XRESIZEVEC (unsigned char,
3798                                         pfile->macro_buffer, len);
3799       pfile->macro_buffer_len = len;
3800     }
3801 
3802   /* Fill in the buffer.  Start with the macro name.  */
3803   buffer = pfile->macro_buffer;
3804   buffer = _cpp_spell_ident_ucns (buffer, node);
3805 
3806   /* Parameter names.  */
3807   if (macro->fun_like)
3808     {
3809       *buffer++ = '(';
3810       for (i = 0; i < macro->paramc; i++)
3811 	{
3812 	  cpp_hashnode *param = macro->parm.params[i];
3813 
3814 	  if (param != pfile->spec_nodes.n__VA_ARGS__)
3815 	    {
3816 	      memcpy (buffer, NODE_NAME (param), NODE_LEN (param));
3817 	      buffer += NODE_LEN (param);
3818 	    }
3819 
3820 	  if (i + 1 < macro->paramc)
3821 	    /* Don't emit a space after the comma here; we're trying
3822 	       to emit a Dwarf-friendly definition, and the Dwarf spec
3823 	       forbids spaces in the argument list.  */
3824 	    *buffer++ = ',';
3825 	  else if (macro->variadic)
3826 	    *buffer++ = '.', *buffer++ = '.', *buffer++ = '.';
3827 	}
3828       *buffer++ = ')';
3829     }
3830 
3831   /* The Dwarf spec requires a space after the macro name, even if the
3832      definition is the empty string.  */
3833   *buffer++ = ' ';
3834 
3835   if (CPP_OPTION (pfile, traditional))
3836     buffer = _cpp_copy_replacement_text (macro, buffer);
3837   else if (macro->count)
3838   /* Expansion tokens.  */
3839     {
3840       unsigned int count = macro_real_token_count (macro);
3841       for (i = 0; i < count; i++)
3842 	{
3843 	  const cpp_token *token = &macro->exp.tokens[i];
3844 
3845 	  if (token->flags & PREV_WHITE)
3846 	    *buffer++ = ' ';
3847 	  if (token->flags & STRINGIFY_ARG)
3848 	    *buffer++ = '#';
3849 
3850 	  if (token->type == CPP_MACRO_ARG)
3851 	    {
3852 	      memcpy (buffer,
3853 		      NODE_NAME (token->val.macro_arg.spelling),
3854 		      NODE_LEN (token->val.macro_arg.spelling));
3855 	      buffer += NODE_LEN (token->val.macro_arg.spelling);
3856 	    }
3857 	  else
3858 	    buffer = cpp_spell_token (pfile, token, buffer, true);
3859 
3860 	  if (token->flags & PASTE_LEFT)
3861 	    {
3862 	      *buffer++ = ' ';
3863 	      *buffer++ = '#';
3864 	      *buffer++ = '#';
3865 	      /* Next has PREV_WHITE; see _cpp_create_definition.  */
3866 	    }
3867 	}
3868     }
3869 
3870   *buffer = '\0';
3871   return pfile->macro_buffer;
3872 }
3873