traditional.c 31.8 KB
Newer Older
1
/* CPP Library - traditional lexical analysis and macro expansion.
2 3
   Copyright (C) 2002, 2004, 2005, 2007, 2008, 2009
   Free Software Foundation, Inc.
4 5 6 7
   Contributed by Neil Booth, May 2002

This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
8
Free Software Foundation; either version 3, or (at your option) any
9 10 11 12 13 14 15 16
later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
17 18
along with this program; see the file COPYING3.  If not see
<http://www.gnu.org/licenses/>.  */
19 20 21 22

#include "config.h"
#include "system.h"
#include "cpplib.h"
23
#include "internal.h"
24

25
/* The replacement text of a function-like macro is stored as a
26
   contiguous sequence of aligned blocks, each representing the text
27
   between subsequent parameters.
28

29 30 31 32
   Each block comprises the text between its surrounding parameters,
   the length of that text, and the one-based index of the following
   parameter.  The final block in the replacement text is easily
   recognizable as it has an argument index of zero.  */
33 34 35 36 37 38 39 40 41

struct block
{
  unsigned int text_len;
  unsigned short arg_index;
  uchar text[1];
};

#define BLOCK_HEADER_LEN offsetof (struct block, text)
42
#define BLOCK_LEN(TEXT_LEN) CPP_ALIGN (BLOCK_HEADER_LEN + (TEXT_LEN))
43

44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
/* Structure holding information about a function-like macro
   invocation.  */
struct fun_macro
{
  /* Memory buffer holding the trad_arg array.  */
  _cpp_buff *buff;

  /* An array of size the number of macro parameters + 1, containing
     the offsets of the start of each macro argument in the output
     buffer.  The argument continues until the character before the
     start of the next one.  */
  size_t *args;

  /* The hashnode of the macro.  */
  cpp_hashnode *node;

  /* The offset of the macro name in the output buffer.  */
  size_t offset;

63
  /* The line the macro name appeared on.  */
64
  source_location line;
65

66 67 68 69
  /* Zero-based index of argument being currently lexed.  */
  unsigned int argc;
};

Neil Booth committed
70 71
/* Lexing state.  It is mostly used to prevent macro expansion.  */
enum ls {ls_none = 0,		/* Normal state.  */
72 73
	 ls_fun_open,		/* When looking for '('.  */
	 ls_fun_close,		/* When looking for ')'.  */
Neil Booth committed
74 75 76 77 78 79
	 ls_defined,		/* After defined.  */
	 ls_defined_close,	/* Looking for ')' of defined().  */
	 ls_hash,		/* After # in preprocessor conditional.  */
	 ls_predicate,		/* After the predicate, maybe paren?  */
	 ls_answer};		/* In answer to predicate.  */

80
/* Lexing TODO: Maybe handle space in escaped newlines.  Stop lex.c
81
   from recognizing comments and directives during its lexing pass.  */
82

83 84 85 86 87 88 89 90 91 92 93 94 95
static const uchar *skip_whitespace (cpp_reader *, const uchar *, int);
static cpp_hashnode *lex_identifier (cpp_reader *, const uchar *);
static const uchar *copy_comment (cpp_reader *, const uchar *, int);
static void check_output_buffer (cpp_reader *, size_t);
static void push_replacement_text (cpp_reader *, cpp_hashnode *);
static bool scan_parameters (cpp_reader *, cpp_macro *);
static bool recursive_macro (cpp_reader *, cpp_hashnode *);
static void save_replacement_text (cpp_reader *, cpp_macro *, unsigned int);
static void maybe_start_funlike (cpp_reader *, cpp_hashnode *, const uchar *,
				 struct fun_macro *);
static void save_argument (struct fun_macro *, size_t);
static void replace_args_and_push (cpp_reader *, struct fun_macro *);
static size_t canonicalize_text (uchar *, const uchar *, size_t, uchar *);
96 97 98 99

/* Ensures we have N bytes' space in the output buffer, and
   reallocates it if not.  */
static void
100
check_output_buffer (cpp_reader *pfile, size_t n)
101
{
102
  /* We might need two bytes to terminate an unterminated comment, and
103
     one more to terminate the line with a NUL.  */
104 105
  n += 2 + 1;

106
  if (n > (size_t) (pfile->out.limit - pfile->out.cur))
107
    {
108
      size_t size = pfile->out.cur - pfile->out.base;
109 110
      size_t new_size = (size + n) * 3 / 2;

111
      pfile->out.base = XRESIZEVEC (unsigned char, pfile->out.base, new_size);
112 113
      pfile->out.limit = pfile->out.base + new_size;
      pfile->out.cur = pfile->out.base + size;
114 115 116
    }
}

117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
/* Skip a C-style block comment in a macro as a result of -CC.
   Buffer->cur points to the initial asterisk of the comment.  */
static void
skip_macro_block_comment (cpp_reader *pfile)
{
  const uchar *cur = pfile->buffer->cur;

  cur++;
  if (*cur == '/')
    cur++;

  /* People like decorating comments with '*', so check for '/'
     instead for efficiency.  */
  while(! (*cur++ == '/' && cur[-2] == '*') )
    ;

  pfile->buffer->cur = cur;
}

136 137 138
/* CUR points to the asterisk introducing a comment in the current
   context.  IN_DEFINE is true if we are in the replacement text of a
   macro.
139 140 141 142 143 144

   The asterisk and following comment is copied to the buffer pointed
   to by pfile->out.cur, which must be of sufficient size.
   Unterminated comments are diagnosed, and correctly terminated in
   the output.  pfile->out.cur is updated depending upon IN_DEFINE,
   -C, -CC and pfile->state.in_directive.
145 146 147

   Returns a pointer to the first character after the comment in the
   input buffer.  */
148
static const uchar *
149
copy_comment (cpp_reader *pfile, const uchar *cur, int in_define)
150
{
151
  bool unterminated, copy = false;
152
  source_location src_loc = pfile->line_table->highest_line;
153
  cpp_buffer *buffer = pfile->buffer;
154

155
  buffer->cur = cur;
156 157 158 159 160
  if (pfile->context->prev)
    unterminated = false, skip_macro_block_comment (pfile);
  else
    unterminated = _cpp_skip_block_comment (pfile);
    
161
  if (unterminated)
162
    cpp_error_with_line (pfile, CPP_DL_ERROR, src_loc, 0,
163
			 "unterminated comment");
164

165 166 167 168 169 170 171 172 173 174
  /* Comments in directives become spaces so that tokens are properly
     separated when the ISO preprocessor re-lexes the line.  The
     exception is #define.  */
  if (pfile->state.in_directive)
    {
      if (in_define)
	{
	  if (CPP_OPTION (pfile, discard_comments_in_macro_exp))
	    pfile->out.cur--;
	  else
175
	    copy = true;
176 177 178 179 180 181 182
	}
      else
	pfile->out.cur[-1] = ' ';
    }
  else if (CPP_OPTION (pfile, discard_comments))
    pfile->out.cur--;
  else
183
    copy = true;
184

185 186 187 188 189 190 191 192 193 194 195 196 197
  if (copy)
    {
      size_t len = (size_t) (buffer->cur - cur);
      memcpy (pfile->out.cur, cur, len);
      pfile->out.cur += len;
      if (unterminated)
	{
	  *pfile->out.cur++ = '*';
	  *pfile->out.cur++ = '/';
	}
    }

  return buffer->cur;
198 199
}

200 201 202 203 204 205 206 207 208 209 210 211
/* CUR points to any character in the input buffer.  Skips over all
   contiguous horizontal white space and NULs, including comments if
   SKIP_COMMENTS, until reaching the first non-horizontal-whitespace
   character or the end of the current context.  Escaped newlines are
   removed.

   The whitespace is copied verbatim to the output buffer, except that
   comments are handled as described in copy_comment().
   pfile->out.cur is updated.

   Returns a pointer to the first character after the whitespace in
   the input buffer.  */
212
static const uchar *
213
skip_whitespace (cpp_reader *pfile, const uchar *cur, int skip_comments)
214
{
215
  uchar *out = pfile->out.cur;
216 217 218

  for (;;)
    {
219 220
      unsigned int c = *cur++;
      *out++ = c;
221

222
      if (is_nvspace (c))
223 224
	continue;

225
      if (c == '/' && *cur == '*' && skip_comments)
226
	{
227 228 229
	  pfile->out.cur = out;
	  cur = copy_comment (pfile, cur, false /* in_define */);
	  out = pfile->out.cur;
230 231 232
	  continue;
	}

233
      out--;
234 235 236
      break;
    }

237 238
  pfile->out.cur = out;
  return cur - 1;
239 240
}

241 242
/* Lexes and outputs an identifier starting at CUR, which is assumed
   to point to a valid first character of an identifier.  Returns
243
   the hashnode, and updates out.cur.  */
244
static cpp_hashnode *
245
lex_identifier (cpp_reader *pfile, const uchar *cur)
246 247
{
  size_t len;
248
  uchar *out = pfile->out.cur;
249
  cpp_hashnode *result;
250 251

  do
252
    *out++ = *cur++;
253
  while (is_numchar (*cur));
254

255
  CUR (pfile->context) = cur;
256
  len = out - pfile->out.cur;
257 258
  result = CPP_HASHNODE (ht_lookup (pfile->hash_table, pfile->out.cur,
				    len, HT_ALLOC));
259
  pfile->out.cur = out;
260 261 262
  return result;
}

263 264 265 266
/* Overlays the true file buffer temporarily with text of length LEN
   starting at START.  The true buffer is restored upon calling
   restore_buff().  */
void
267
_cpp_overlay_buffer (cpp_reader *pfile, const uchar *start, size_t len)
268 269 270
{
  cpp_buffer *buffer = pfile->buffer;

Neil Booth committed
271
  pfile->overlaid_buffer = buffer;
272 273 274
  pfile->saved_cur = buffer->cur;
  pfile->saved_rlimit = buffer->rlimit;
  pfile->saved_line_base = buffer->next_line;
275
  buffer->need_line = false;
276 277

  buffer->cur = start;
278
  buffer->line_base = start;
279 280 281 282
  buffer->rlimit = start + len;
}

/* Restores a buffer overlaid by _cpp_overlay_buffer().  */
283
void
284
_cpp_remove_overlay (cpp_reader *pfile)
285
{
Neil Booth committed
286
  cpp_buffer *buffer = pfile->overlaid_buffer;
287

288 289 290
  buffer->cur = pfile->saved_cur;
  buffer->rlimit = pfile->saved_rlimit;
  buffer->line_base = pfile->saved_line_base;
291
  buffer->need_line = true;
292

293
  pfile->overlaid_buffer = NULL;
294 295 296 297 298
}

/* Reads a logical line into the output buffer.  Returns TRUE if there
   is more text left in the buffer.  */
bool
299
_cpp_read_logical_line_trad (cpp_reader *pfile)
300
{
301
  do
302
    {
303
      if (pfile->buffer->need_line && !_cpp_get_fresh_line (pfile))
304
	return false;
305
    }
306
  while (!_cpp_scan_out_logical_line (pfile, NULL) || pfile->state.skipping);
307

308
  return pfile->buffer != NULL;
309 310
}

311 312 313
/* Set up state for finding the opening '(' of a function-like
   macro.  */
static void
314
maybe_start_funlike (cpp_reader *pfile, cpp_hashnode *node, const uchar *start, struct fun_macro *macro)
315 316 317 318 319 320 321 322
{
  unsigned int n = node->value.macro->paramc + 1;

  if (macro->buff)
    _cpp_release_buff (pfile, macro->buff);
  macro->buff = _cpp_get_buff (pfile, n * sizeof (size_t));
  macro->args = (size_t *) BUFF_FRONT (macro->buff);
  macro->node = node;
323
  macro->offset = start - pfile->out.base;
324 325 326 327 328
  macro->argc = 0;
}

/* Save the OFFSET of the start of the next argument to MACRO.  */
static void
329
save_argument (struct fun_macro *macro, size_t offset)
330 331 332 333 334 335
{
  macro->argc++;
  if (macro->argc <= macro->node->value.macro->paramc)
    macro->args[macro->argc] = offset;
}

336 337 338
/* Copies the next logical line in the current buffer (starting at
   buffer->cur) to the output buffer.  The output is guaranteed to
   terminate with a NUL character.  buffer->cur is updated.
339 340

   If MACRO is non-NULL, then we are scanning the replacement list of
341
   MACRO, and we call save_replacement_text() every time we meet an
342
   argument.  */
343
bool
344
_cpp_scan_out_logical_line (cpp_reader *pfile, cpp_macro *macro)
345
{
346
  bool result = true;
347 348
  cpp_context *context;
  const uchar *cur;
349
  uchar *out;
350
  struct fun_macro fmacro;
351
  unsigned int c, paren_depth = 0, quote;
Neil Booth committed
352
  enum ls lex_state = ls_none;
353
  bool header_ok;
354
  const uchar *start_of_input_line;
355

356
  fmacro.buff = NULL;
357 358 359 360 361
  fmacro.args = NULL;
  fmacro.node = NULL;
  fmacro.offset = 0;
  fmacro.line = 0;
  fmacro.argc = 0;
362

363
  quote = 0;
364
  header_ok = pfile->state.angled_headers;
365 366
  CUR (pfile->context) = pfile->buffer->cur;
  RLIMIT (pfile->context) = pfile->buffer->rlimit;
367
  pfile->out.cur = pfile->out.base;
368
  pfile->out.first_line = pfile->line_table->highest_line;
369
  /* start_of_input_line is needed to make sure that directives really,
370
     really start at the first character of the line.  */
371
  start_of_input_line = pfile->buffer->cur;
372 373 374
 new_context:
  context = pfile->context;
  cur = CUR (context);
375
  check_output_buffer (pfile, RLIMIT (context) - cur);
376
  out = pfile->out.cur;
377 378 379

  for (;;)
    {
380 381 382 383 384 385
      if (!context->prev
	  && cur >= pfile->buffer->notes[pfile->buffer->cur_note].pos)
	{
	  pfile->buffer->cur = cur;
	  _cpp_process_line_notes (pfile, false);
	}
386 387 388
      c = *cur++;
      *out++ = c;

Neil Booth committed
389 390
      /* Whitespace should "continue" out of the switch,
	 non-whitespace should "break" out of it.  */
391 392
      switch (c)
	{
Neil Booth committed
393 394 395 396
	case ' ':
	case '\t':
	case '\f':
	case '\v':
397
	case '\0':
398
	  continue;
399

400
	case '\n':
401 402 403
	  /* If this is a macro's expansion, pop it.  */
	  if (context->prev)
	    {
404
	      pfile->out.cur = out - 1;
405 406 407 408
	      _cpp_pop_context (pfile);
	      goto new_context;
	    }

409 410 411 412
	  /* Omit the newline from the output buffer.  */
	  pfile->out.cur = out - 1;
	  pfile->buffer->cur = cur;
	  pfile->buffer->need_line = true;
413
	  CPP_INCREMENT_LINE (pfile, 0);
414

415
	  if ((lex_state == ls_fun_open || lex_state == ls_fun_close)
416 417
	      && !pfile->state.in_directive
	      && _cpp_get_fresh_line (pfile))
418
	    {
Neil Booth committed
419 420
	      /* Newlines in arguments become a space, but we don't
		 clear any in-progress quote.  */
421 422
	      if (lex_state == ls_fun_close)
		out[-1] = ' ';
423
	      cur = pfile->buffer->cur;
424 425 426
	      continue;
	    }
	  goto done;
427

Neil Booth committed
428
	case '<':
429
	  if (header_ok)
Neil Booth committed
430 431 432
	    quote = '>';
	  break;
	case '>':
433
	  if (c == quote)
434
	    quote = 0;
Neil Booth committed
435 436
	  break;

437 438 439 440 441 442 443 444 445
	case '"':
	case '\'':
	  if (c == quote)
	    quote = 0;
	  else if (!quote)
	    quote = c;
	  break;

	case '\\':
446 447 448
	  /* Skip escaped quotes here, it's easier than above.  */
	  if (*cur == '\\' || *cur == '"' || *cur == '\'')
	    *out++ = *cur++;
449 450 451 452 453
	  break;

	case '/':
	  /* Traditional CPP does not recognize comments within
	     literals.  */
454
	  if (!quote && *cur == '*')
455
	    {
456 457 458 459
	      pfile->out.cur = out;
	      cur = copy_comment (pfile, cur, macro != 0);
	      out = pfile->out.cur;
	      continue;
460 461 462 463 464 465 466 467 468 469 470 471 472 473
	    }
	  break;

	case '_':
	case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
	case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
	case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
	case 's': case 't': case 'u': case 'v': case 'w': case 'x':
	case 'y': case 'z':
	case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
	case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
	case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
	case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
	case 'Y': case 'Z':
Neil Booth committed
474
	  if (!pfile->state.skipping && (quote == 0 || macro))
475 476
	    {
	      cpp_hashnode *node;
Neil Booth committed
477
	      uchar *out_start = out - 1;
478

Neil Booth committed
479
	      pfile->out.cur = out_start;
480
	      node = lex_identifier (pfile, cur - 1);
Neil Booth committed
481 482
	      out = pfile->out.cur;
	      cur = CUR (context);
483

484
	      if (node->type == NT_MACRO
Neil Booth committed
485
		  /* Should we expand for ls_answer?  */
486
		  && (lex_state == ls_none || lex_state == ls_fun_open)
487
		  && !pfile->state.prevent_expansion)
488
		{
489 490 491 492
		  /* Macros invalidate MI optimization.  */
		  pfile->mi_valid = false;
		  if (! (node->flags & NODE_BUILTIN)
		      && node->value.macro->fun_like)
Neil Booth committed
493 494
		    {
		      maybe_start_funlike (pfile, node, out_start, &fmacro);
495
		      lex_state = ls_fun_open;
496
		      fmacro.line = pfile->line_table->highest_line;
Neil Booth committed
497 498
		      continue;
		    }
499
		  else if (!recursive_macro (pfile, node))
500 501 502
		    {
		      /* Remove the object-like macro's name from the
			 output, and push its replacement text.  */
Neil Booth committed
503
		      pfile->out.cur = out_start;
504
		      push_replacement_text (pfile, node);
505
		      lex_state = ls_none;
506 507
		      goto new_context;
		    }
508
		}
509
	      else if (macro && (node->flags & NODE_MACRO_ARG) != 0)
510
		{
511 512
		  /* Found a parameter in the replacement text of a
		     #define.  Remove its name from the output.  */
513
		  pfile->out.cur = out_start;
514
		  save_replacement_text (pfile, macro, node->value.arg_index);
515
		  out = pfile->out.base;
516
		}
Neil Booth committed
517 518 519 520 521 522 523 524 525 526 527
	      else if (lex_state == ls_hash)
		{
		  lex_state = ls_predicate;
		  continue;
		}
	      else if (pfile->state.in_expression
		       && node == pfile->spec_nodes.n_defined)
		{
		  lex_state = ls_defined;
		  continue;
		}
528
	    }
529 530
	  break;

531 532 533 534
	case '(':
	  if (quote == 0)
	    {
	      paren_depth++;
535
	      if (lex_state == ls_fun_open)
536
		{
537 538 539 540 541 542 543 544 545
		  if (recursive_macro (pfile, fmacro.node))
		    lex_state = ls_none;
		  else
		    {
		      lex_state = ls_fun_close;
		      paren_depth = 1;
		      out = pfile->out.base + fmacro.offset;
		      fmacro.args[0] = fmacro.offset;
		    }
546
		}
Neil Booth committed
547 548 549 550
	      else if (lex_state == ls_predicate)
		lex_state = ls_answer;
	      else if (lex_state == ls_defined)
		lex_state = ls_defined_close;
551 552 553 554
	    }
	  break;

	case ',':
555
	  if (quote == 0 && lex_state == ls_fun_close && paren_depth == 1)
556
	    save_argument (&fmacro, out - pfile->out.base);
557 558 559 560 561 562
	  break;

	case ')':
	  if (quote == 0)
	    {
	      paren_depth--;
563
	      if (lex_state == ls_fun_close && paren_depth == 0)
564 565 566
		{
		  cpp_macro *m = fmacro.node->value.macro;

567
		  m->used = 1;
568
		  lex_state = ls_none;
569
		  save_argument (&fmacro, out - pfile->out.base);
570

571 572 573
		  /* A single zero-length argument is no argument.  */
		  if (fmacro.argc == 1
		      && m->paramc == 0
Neil Booth committed
574
		      && out == pfile->out.base + fmacro.offset + 1)
575
		    fmacro.argc = 0;
576 577 578 579 580

		  if (_cpp_arguments_ok (pfile, m, fmacro.node, fmacro.argc))
		    {
		      /* Remove the macro's invocation from the
			 output, and push its replacement text.  */
581
		      pfile->out.cur = (pfile->out.base
582 583 584 585 586 587
					     + fmacro.offset);
		      CUR (context) = cur;
		      replace_args_and_push (pfile, &fmacro);
		      goto new_context;
		    }
		}
Neil Booth committed
588 589
	      else if (lex_state == ls_answer || lex_state == ls_defined_close)
		lex_state = ls_none;
590 591 592
	    }
	  break;

593
	case '#':
594
	  if (cur - 1 == start_of_input_line
595 596 597
	      /* A '#' from a macro doesn't start a directive.  */
	      && !pfile->context->prev
	      && !pfile->state.in_directive)
598
	    {
599 600 601 602 603 604 605 606 607 608
	      /* A directive.  With the way _cpp_handle_directive
		 currently works, we only want to call it if either we
		 know the directive is OK, or we want it to fail and
		 be removed from the output.  If we want it to be
		 passed through (the assembler case) then we must not
		 call _cpp_handle_directive.  */
	      pfile->out.cur = out;
	      cur = skip_whitespace (pfile, cur, true /* skip_comments */);
	      out = pfile->out.cur;

609
	      if (*cur == '\n')
610 611 612
		{
		  /* Null directive.  Ignore it and don't invalidate
		     the MI optimization.  */
613
		  pfile->buffer->need_line = true;
614
		  CPP_INCREMENT_LINE (pfile, 0);
615 616
		  result = false;
		  goto done;
617
		}
618 619 620 621
	      else
		{
		  bool do_it = false;

622 623
		  if (is_numstart (*cur)
		      && CPP_OPTION (pfile, lang) != CLK_ASM)
624 625 626 627
		    do_it = true;
		  else if (is_idstart (*cur))
		    /* Check whether we know this directive, but don't
		       advance.  */
628
		    do_it = lex_identifier (pfile, cur)->is_directive;
629 630 631 632 633 634 635

		  if (do_it || CPP_OPTION (pfile, lang) != CLK_ASM)
		    {
		      /* This is a kludge.  We want to have the ISO
			 preprocessor lex the next token.  */
		      pfile->buffer->cur = cur;
		      _cpp_handle_directive (pfile, false /* indented */);
636 637
		      result = false;
		      goto done;
638 639
		    }
		}
640
	    }
641

Neil Booth committed
642 643 644 645 646
	  if (pfile->state.in_expression)
	    {
	      lex_state = ls_hash;
	      continue;
	    }
647 648
	  break;

649 650 651
	default:
	  break;
	}
Neil Booth committed
652

653 654 655
      /* Non-whitespace disables MI optimization and stops treating
	 '<' as a quote in #include.  */
      header_ok = false;
656 657 658
      if (!pfile->state.in_directive)
	pfile->mi_valid = false;

Neil Booth committed
659 660 661 662 663
      if (lex_state == ls_none)
	continue;

      /* Some of these transitions of state are syntax errors.  The
	 ISO preprocessor will issue errors later.  */
664 665 666
      if (lex_state == ls_fun_open)
	/* Missing '('.  */
	lex_state = ls_none;
Neil Booth committed
667 668 669 670 671 672
      else if (lex_state == ls_hash
	       || lex_state == ls_predicate
	       || lex_state == ls_defined)
	lex_state = ls_none;

      /* ls_answer and ls_defined_close keep going until ')'.  */
673
    }
674 675 676 677

 done:
  if (fmacro.buff)
    _cpp_release_buff (pfile, fmacro.buff);
Neil Booth committed
678

679
  if (lex_state == ls_fun_close)
680
    cpp_error_with_line (pfile, CPP_DL_ERROR, fmacro.line, 0,
681 682
			 "unterminated argument list invoking macro \"%s\"",
			 NODE_NAME (fmacro.node));
683
  return result;
684
}
685 686

/* Push a context holding the replacement text of the macro NODE on
687 688
   the context stack.  NODE is either object-like, or a function-like
   macro with no arguments.  */
689
static void
690
push_replacement_text (cpp_reader *pfile, cpp_hashnode *node)
691
{
692 693
  size_t len;
  const uchar *text;
694
  uchar *buf;
695 696 697 698 699

  if (node->flags & NODE_BUILTIN)
    {
      text = _cpp_builtin_macro_text (pfile, node);
      len = ustrlen (text);
700 701 702 703
      buf = _cpp_unaligned_alloc (pfile, len + 1);
      memcpy (buf, text, len);
      buf[len]='\n';
      text = buf;
704 705 706 707
    }
  else
    {
      cpp_macro *macro = node->value.macro;
708
      macro->used = 1;
709
      text = macro->exp.text;
Geoffrey Keating committed
710
      macro->traditional = 1;
711 712
      len = macro->count;
    }
713

714
  _cpp_push_text_context (pfile, node, text, len);
715 716
}

717 718
/* Returns TRUE if traditional macro recursion is detected.  */
static bool
719
recursive_macro (cpp_reader *pfile, cpp_hashnode *node)
720
{
721
  bool recursing = !!(node->flags & NODE_DISABLED);
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749

  /* Object-like macros that are already expanding are necessarily
     recursive.

     However, it is possible to have traditional function-like macros
     that are not infinitely recursive but recurse to any given depth.
     Further, it is easy to construct examples that get ever longer
     until the point they stop recursing.  So there is no easy way to
     detect true recursion; instead we assume any expansion more than
     20 deep since the first invocation of this macro must be
     recursing.  */
  if (recursing && node->value.macro->fun_like)
    {
      size_t depth = 0;
      cpp_context *context = pfile->context;

      do
	{
	  depth++;
	  if (context->macro == node && depth > 20)
	    break;
	  context = context->prev;
	}
      while (context);
      recursing = context != NULL;
    }

  if (recursing)
750
    cpp_error (pfile, CPP_DL_ERROR,
751 752 753 754 755 756
	       "detected recursion whilst expanding macro \"%s\"",
	       NODE_NAME (node));

  return recursing;
}

757 758 759
/* Return the length of the replacement text of a function-like or
   object-like non-builtin macro.  */
size_t
760
_cpp_replacement_text_len (const cpp_macro *macro)
761 762 763
{
  size_t len;

764
  if (macro->fun_like && (macro->paramc != 0))
765 766 767
    {
      const uchar *exp;

768
      len = 0;
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
      for (exp = macro->exp.text;;)
	{
	  struct block *b = (struct block *) exp;

	  len += b->text_len;
	  if (b->arg_index == 0)
	    break;
	  len += NODE_LEN (macro->params[b->arg_index - 1]);
	  exp += BLOCK_LEN (b->text_len);
	}
    }
  else
    len = macro->count;
  
  return len;
}

/* Copy the replacement text of MACRO to DEST, which must be of
   sufficient size.  It is not NUL-terminated.  The next character is
   returned.  */
uchar *
790
_cpp_copy_replacement_text (const cpp_macro *macro, uchar *dest)
791
{
792
  if (macro->fun_like && (macro->paramc != 0))
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
    {
      const uchar *exp;

      for (exp = macro->exp.text;;)
	{
	  struct block *b = (struct block *) exp;
	  cpp_hashnode *param;

	  memcpy (dest, b->text, b->text_len);
	  dest += b->text_len;
	  if (b->arg_index == 0)
	    break;
	  param = macro->params[b->arg_index - 1];
	  memcpy (dest, NODE_NAME (param), NODE_LEN (param));
	  dest += NODE_LEN (param);
	  exp += BLOCK_LEN (b->text_len);
	}
    }
  else
    {
      memcpy (dest, macro->exp.text, macro->count);
      dest += macro->count;
    }

  return dest;
}

820 821 822 823
/* Push a context holding the replacement text of the macro NODE on
   the context stack.  NODE is either object-like, or a function-like
   macro with no arguments.  */
static void
824
replace_args_and_push (cpp_reader *pfile, struct fun_macro *fmacro)
825 826 827 828 829 830 831 832 833 834 835
{
  cpp_macro *macro = fmacro->node->value.macro;

  if (macro->paramc == 0)
    push_replacement_text (pfile, fmacro->node);
  else
    {
      const uchar *exp;
      uchar *p;
      _cpp_buff *buff;
      size_t len = 0;
836
      int cxtquote = 0;
837

838 839 840
      /* Get an estimate of the length of the argument-replaced text.
	 This is a worst case estimate, assuming that every replacement
	 text character needs quoting.  */
841 842 843 844 845 846 847
      for (exp = macro->exp.text;;)
	{
	  struct block *b = (struct block *) exp;

	  len += b->text_len;
	  if (b->arg_index == 0)
	    break;
848 849
	  len += 2 * (fmacro->args[b->arg_index]
		      - fmacro->args[b->arg_index - 1] - 1);
850 851 852
	  exp += BLOCK_LEN (b->text_len);
	}

853
      /* Allocate room for the expansion plus \n.  */
854 855 856
      buff = _cpp_get_buff (pfile, len + 1);

      /* Copy the expansion and replace arguments.  */
857
      /* Accumulate actual length, including quoting as necessary */
858
      p = BUFF_FRONT (buff);
859
      len = 0;
860 861 862 863
      for (exp = macro->exp.text;;)
	{
	  struct block *b = (struct block *) exp;
	  size_t arglen;
864 865 866
	  int argquote;
	  uchar *base;
	  uchar *in;
867

868 869 870 871 872 873 874 875 876 877
	  len += b->text_len;
	  /* Copy the non-argument text literally, keeping
	     track of whether matching quotes have been seen. */
	  for (arglen = b->text_len, in = b->text; arglen > 0; arglen--)
	    {
	      if (*in == '"')
		cxtquote = ! cxtquote;
	      *p++ = *in++;
	    }
	  /* Done if no more arguments */
878 879 880 881
	  if (b->arg_index == 0)
	    break;
	  arglen = (fmacro->args[b->arg_index]
		    - fmacro->args[b->arg_index - 1] - 1);
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919
	  base = pfile->out.base + fmacro->args[b->arg_index - 1];
	  in = base;
#if 0
	  /* Skip leading whitespace in the text for the argument to
	     be substituted. To be compatible with gcc 2.95, we would
	     also need to trim trailing whitespace. Gcc 2.95 trims
	     leading and trailing whitespace, which may be a bug.  The
	     current gcc testsuite explicitly checks that this leading
	     and trailing whitespace in actual arguments is
	     preserved. */
	  while (arglen > 0 && is_space (*in))
	    {
	      in++;
	      arglen--;
	    }
#endif
	  for (argquote = 0; arglen > 0; arglen--)
	    {
	      if (cxtquote && *in == '"')
		{
		  if (in > base && *(in-1) != '\\')
		    argquote = ! argquote;
		  /* Always add backslash before double quote if argument
		     is expanded in a quoted context */
		  *p++ = '\\';
		  len++;
		}
	      else if (cxtquote && argquote && *in == '\\')
		{
		  /* Always add backslash before a backslash in an argument
		     that is expanded in a quoted context and also in the
		     range of a quoted context in the argument itself. */
		  *p++ = '\\';
		  len++;
		}
	      *p++ = *in++;
	      len++;
	    }
920 921 922
	  exp += BLOCK_LEN (b->text_len);
	}

923 924
      /* \n-terminate.  */
      *p = '\n';
925 926 927 928 929
      _cpp_push_text_context (pfile, fmacro->node, BUFF_FRONT (buff), len);

      /* So we free buffer allocation when macro is left.  */
      pfile->context->buff = buff;
    }
930 931
}

932
/* Read and record the parameters, if any, of a function-like macro
933
   definition.  Destroys pfile->out.cur.
934 935 936 937 938

   Returns true on success, false on failure (syntax error or a
   duplicate parameter).  On success, CUR (pfile->context) is just
   past the closing parenthesis.  */
static bool
939
scan_parameters (cpp_reader *pfile, cpp_macro *macro)
940 941 942 943 944 945
{
  const uchar *cur = CUR (pfile->context) + 1;
  bool ok;

  for (;;)
    {
946
      cur = skip_whitespace (pfile, cur, true /* skip_comments */);
947

948
      if (is_idstart (*cur))
949 950 951 952
	{
	  ok = false;
	  if (_cpp_save_parameter (pfile, macro, lex_identifier (pfile, cur)))
	    break;
953 954
	  cur = skip_whitespace (pfile, CUR (pfile->context),
				 true /* skip_comments */);
955 956 957 958 959 960 961 962 963 964 965 966 967
	  if (*cur == ',')
	    {
	      cur++;
	      continue;
	    }
	  ok = (*cur == ')');
	  break;
	}

      ok = (*cur == ')' && macro->paramc == 0);
      break;
    }

968 969 970
  if (!ok)
    cpp_error (pfile, CPP_DL_ERROR, "syntax error in macro parameter list");

971 972 973 974 975
  CUR (pfile->context) = cur + (*cur == ')');

  return ok;
}

976
/* Save the text from pfile->out.base to pfile->out.cur as
977 978 979 980
   the replacement text for the current macro, followed by argument
   ARG_INDEX, with zero indicating the end of the replacement
   text.  */
static void
981 982
save_replacement_text (cpp_reader *pfile, cpp_macro *macro,
		       unsigned int arg_index)
983
{
984
  size_t len = pfile->out.cur - pfile->out.base;
985 986 987 988 989
  uchar *exp;

  if (macro->paramc == 0)
    {
      /* Object-like and function-like macros without parameters
990
	 simply store their \n-terminated replacement text.  */
991
      exp = _cpp_unaligned_alloc (pfile, len + 1);
992
      memcpy (exp, pfile->out.base, len);
993
      exp[len] = '\n';
994
      macro->exp.text = exp;
Geoffrey Keating committed
995
      macro->traditional = 1;
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
      macro->count = len;
    }
  else
    {
      /* Store the text's length (unsigned int), the argument index
	 (unsigned short, base 1) and then the text.  */
      size_t blen = BLOCK_LEN (len);
      struct block *block;

      if (macro->count + blen > BUFF_ROOM (pfile->a_buff))
	_cpp_extend_buff (pfile, &pfile->a_buff, macro->count + blen);

      exp = BUFF_FRONT (pfile->a_buff);
      block = (struct block *) (exp + macro->count);
      macro->exp.text = exp;
Geoffrey Keating committed
1011
      macro->traditional = 1;
1012 1013 1014 1015

      /* Write out the block information.  */
      block->text_len = len;
      block->arg_index = arg_index;
1016
      memcpy (block->text, pfile->out.base, len);
1017 1018

      /* Lex the rest into the start of the output buffer.  */
1019
      pfile->out.cur = pfile->out.base;
1020

1021
      macro->count += blen;
1022 1023 1024 1025

      /* If we've finished, commit the memory.  */
      if (arg_index == 0)
	BUFF_FRONT (pfile->a_buff) += macro->count;
1026 1027 1028 1029 1030
    }
}

/* Analyze and save the replacement text of a macro.  Returns true on
   success.  */
1031
bool
1032
_cpp_create_trad_definition (cpp_reader *pfile, cpp_macro *macro)
1033
{
1034 1035
  const uchar *cur;
  uchar *limit;
1036
  cpp_context *context = pfile->context;
1037

1038 1039 1040 1041 1042 1043
  /* The context has not been set up for command line defines, and CUR
     has not been updated for the macro name for in-file defines.  */
  pfile->out.cur = pfile->out.base;
  CUR (context) = pfile->buffer->cur;
  RLIMIT (context) = pfile->buffer->rlimit;
  check_output_buffer (pfile, RLIMIT (context) - CUR (context));
1044

1045
  /* Is this a function-like macro?  */
1046
  if (* CUR (context) == '(')
1047
    {
1048 1049 1050 1051 1052
      bool ok = scan_parameters (pfile, macro);

      /* Remember the params so we can clear NODE_MACRO_ARG flags.  */
      macro->params = (cpp_hashnode **) BUFF_FRONT (pfile->a_buff);

1053
      /* Setting macro to NULL indicates an error occurred, and
1054
	 prevents unnecessary work in _cpp_scan_out_logical_line.  */
1055
      if (!ok)
1056 1057 1058 1059 1060 1061 1062 1063
	macro = NULL;
      else
	{
	  BUFF_FRONT (pfile->a_buff) = (uchar *) &macro->params[macro->paramc];
	  macro->fun_like = 1;
	}
    }

1064
  /* Skip leading whitespace in the replacement text.  */
1065 1066
  pfile->buffer->cur
    = skip_whitespace (pfile, CUR (context),
1067
		       CPP_OPTION (pfile, discard_comments_in_macro_exp));
1068

1069
  pfile->state.prevent_expansion++;
1070
  _cpp_scan_out_logical_line (pfile, macro);
1071 1072 1073 1074
  pfile->state.prevent_expansion--;

  if (!macro)
    return false;
1075 1076

  /* Skip trailing white space.  */
1077 1078
  cur = pfile->out.base;
  limit = pfile->out.cur;
1079 1080
  while (limit > cur && is_space (limit[-1]))
    limit--;
1081
  pfile->out.cur = limit;
1082
  save_replacement_text (pfile, macro, 0);
1083 1084 1085 1086

  return true;
}

1087 1088 1089 1090 1091
/* Copy SRC of length LEN to DEST, but convert all contiguous
   whitespace to a single space, provided it is not in quotes.  The
   quote currently in effect is pointed to by PQUOTE, and is updated
   by the function.  Returns the number of bytes copied.  */
static size_t
1092
canonicalize_text (uchar *dest, const uchar *src, size_t len, uchar *pquote)
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
{
  uchar *orig_dest = dest;
  uchar quote = *pquote;

  while (len)
    {
      if (is_space (*src) && !quote)
	{
	  do
	    src++, len--;
	  while (len && is_space (*src));
	  *dest++ = ' ';
	}
      else
	{
	  if (*src == '\'' || *src == '"')
	    {
	      if (!quote)
		quote = *src;
	      else if (quote == *src)
		quote = 0;
	    }
	  *dest++ = *src++, len--;
	}
    }

  *pquote = quote;
  return dest - orig_dest;
}

/* Returns true if MACRO1 and MACRO2 have expansions different other
   than in the form of their whitespace.  */
bool
1126 1127
_cpp_expansions_different_trad (const cpp_macro *macro1,
				const cpp_macro *macro2)
1128
{
1129
  uchar *p1 = XNEWVEC (uchar, macro1->count + macro2->count);
1130
  uchar *p2 = p1 + macro1->count;
1131
  uchar quote1 = 0, quote2 = 0;
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
  bool mismatch;
  size_t len1, len2;

  if (macro1->paramc > 0)
    {
      const uchar *exp1 = macro1->exp.text, *exp2 = macro2->exp.text;

      mismatch = true;
      for (;;)
	{
	  struct block *b1 = (struct block *) exp1;
	  struct block *b2 = (struct block *) exp2;

	  if (b1->arg_index != b2->arg_index)
	    break;

	  len1 = canonicalize_text (p1, b1->text, b1->text_len, &quote1);
	  len2 = canonicalize_text (p2, b2->text, b2->text_len, &quote2);
	  if (len1 != len2 || memcmp (p1, p2, len1))
	    break;
	  if (b1->arg_index == 0)
	    {
	      mismatch = false;
	      break;
	    }
	  exp1 += BLOCK_LEN (b1->text_len);
	  exp2 += BLOCK_LEN (b2->text_len);
	}
    }
  else
    {
      len1 = canonicalize_text (p1, macro1->exp.text, macro1->count, &quote1);
      len2 = canonicalize_text (p2, macro2->exp.text, macro2->count, &quote2);
      mismatch = (len1 != len2 || memcmp (p1, p2, len1));
    }

  free (p1);
  return mismatch;
}