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