1 /* C Compatible Compiler Preprocessor (CCCP)
2 Copyright (C) 1986, 1987, 1989, 2000, 2001 Free Software Foundation, Inc.
3 Written by Paul Rubin, June 1986
4 Adapted to ANSI C, Richard Stallman, Jan 1987
5 Dusted off, polished, and adapted for use as traditional
6 preprocessor only, Zack Weinberg, Jul 2000
8 This program is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by the
10 Free Software Foundation; either version 2, or (at your option) any
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
25 #include "cppdefault.h"
28 typedef unsigned char U_CHAR;
30 /* Name under which this program was invoked. */
32 static const char *progname;
34 /* Current maximum length of directory names in the search path
35 for include files. (Altered as we get more of them.) */
37 size_t max_include_len;
39 /* Nonzero means copy comments into the output file. */
41 int put_out_comments = 0;
43 /* Nonzero means print the names of included files rather than
44 the preprocessed output. 1 means just the #include "...",
45 2 means #include <...> as well. */
49 /* File name which deps are being written to. This is 0 if deps are
50 being written to stdout. */
52 const char *deps_file = 0;
54 /* Nonzero if missing .h files in -M output are assumed to be
55 generated files and not errors. */
57 int print_deps_missing_files = 0;
59 /* Nonzero means don't output line number information. */
63 /* Nonzero means inhibit output of the preprocessed text
64 and instead output the definitions of all user-defined macros
65 in a form suitable for use as input to cccp. */
69 /* Nonzero means don't print warning messages. -w. */
71 int inhibit_warnings = 0;
73 /* Nonzero means warn if slash-star appears in a comment. */
77 /* Nonzero causes output not to be done,
78 but directives such as #define that have side effects
83 /* Value of __USER_LABEL_PREFIX__. Target-dependent, also controlled
84 by -f(no-)leading-underscore. */
85 static const char *user_label_prefix;
87 /* I/O buffer structure.
88 The `fname' field is nonzero for source files and #include files
89 and for the dummy text used for -D and -U.
90 It is zero for rescanning results of macro expansion
91 and for expanding macro arguments. */
92 #define INPUT_STACK_MAX 200
99 /* Macro that this level is the expansion of.
100 Included so that we can reenable the macro
101 at the end of this level. */
102 struct hashnode *macro;
103 /* Value of if_stack at start of this file.
104 Used to prohibit unmatched #endif (etc) in an include file. */
105 struct if_stack *if_stack;
106 /* Object to be freed at end of input at this level. */
108 } instack[INPUT_STACK_MAX];
110 typedef struct file_buf FILE_BUF;
112 /* Current nesting level of input sources.
113 `instack[indepth]' is the level currently being read. */
115 #define CHECK_DEPTH(code) \
116 if (indepth >= (INPUT_STACK_MAX - 1)) \
118 error_with_line (line_for_error (instack[indepth].lineno), \
119 "macro or #include recursion too deep"); \
123 /* Current depth in #include directives that use <...>. */
124 int system_include_depth = 0;
126 /* The output buffer. Its LENGTH field is the amount of room allocated
127 for the buffer, not the number of chars actually present. To get
128 that, subtract outbuf.buf from outbuf.bufp. */
130 #define OUTBUF_SIZE 10 /* initial size of output buffer */
133 /* Grow output buffer OBUF points at
134 so it can hold at least NEEDED more chars. */
136 #define check_expand(OBUF, NEEDED) do { \
137 if ((OBUF)->length - ((OBUF)->bufp - (OBUF)->buf) <= (NEEDED)) \
138 grow_outbuf ((OBUF), (NEEDED)); \
141 struct file_name_list
143 struct file_name_list *next;
147 struct file_name_list *include = 0; /* First dir to search */
148 /* First dir to search for <file> */
149 struct file_name_list *first_bracket_include = 0;
150 struct file_name_list *last_include = 0; /* Last in chain */
152 /* List of included files that contained #once. */
153 struct file_name_list *dont_repeat_files = 0;
155 /* List of other included files. */
156 struct file_name_list *all_include_files = 0;
158 /* Structure allocated for every #define. For a simple replacement
161 nargs = -1, the `pattern' list is null, and the expansion is just
162 the replacement text. Nargs = 0 means a functionlike macro with no args,
164 #define getchar() getc (stdin) .
165 When there are args, the expansion is the replacement text with the
166 args squashed out, and the reflist is a list describing how to
167 build the output from the input: e.g., "3 chars, then the 1st arg,
168 then 9 chars, then the 3rd arg, then 0 chars, then the 2nd arg".
169 The chars here come from the expansion. Whatever is left of the
170 expansion after the last arg-occurrence is copied after that arg.
171 Note that the reflist can be arbitrarily long---
172 its length depends on the number of times the arguments appear in
173 the replacement text, not how many args there are. Example:
174 #define f(x) x+x+x+x+x+x+x would have replacement text "++++++" and
176 { (0, 1), (1, 1), (1, 1), ..., (1, 1), NULL }
177 where (x, y) means (nchars, argno). */
179 typedef struct definition DEFINITION;
182 int length; /* length of expansion string */
185 struct reflist *next;
186 char stringify; /* nonzero if this arg was preceded by a
188 char raw_before; /* Nonzero if a ## operator before arg. */
189 char raw_after; /* Nonzero if a ## operator after arg. */
190 int nchars; /* Number of literal chars to copy before
191 this arg occurrence. */
192 int argno; /* Number of arg to substitute (origin-0) */
194 /* Names of macro args, concatenated in reverse order
195 with comma-space between them.
196 The only use of this is that we warn on redefinition
197 if this differs between the old and new definitions. */
198 const U_CHAR *argnames;
201 /* Chained list of answers to an assertion. */
205 const unsigned char *answer;
209 /* different kinds of things that can appear in the value field
210 of a hash node. Actually, this may be useless now. */
214 struct answer *answers;
217 /* The structure of a node in the hash table. The hash table
218 has entries for all tokens defined by #define commands (type T_MACRO),
219 plus some special tokens like __LINE__ (these each have their own
220 type, and the appropriate code is run when that type of node is seen.
221 It does not contain control words like "#define", which are recognized
222 by a separate piece of code. */
224 /* different flavors of hash nodes --- also used in keyword table */
226 T_DEFINE = 1, /* `#define' */
227 T_INCLUDE, /* `#include' */
228 T_IFDEF, /* `#ifdef' */
229 T_IFNDEF, /* `#ifndef' */
231 T_ELSE, /* `#else' */
232 T_ELIF, /* `#elif' */
233 T_UNDEF, /* `#undef' */
234 T_LINE, /* `#line' */
235 T_ENDIF, /* `#endif' */
236 T_ERROR, /* `#error' */
237 T_WARNING, /* `#warning' */
238 T_ASSERT, /* `#assert' */
239 T_UNASSERT, /* `#unassert' */
240 T_SPECLINE, /* special symbol `__LINE__' */
241 T_DATE, /* `__DATE__' */
242 T_FILE, /* `__FILE__' */
243 T_BASE_FILE, /* `__BASE_FILE__' */
244 T_INCLUDE_LEVEL, /* `__INCLUDE_LEVEL__' */
245 T_VERSION, /* `__VERSION__' */
246 T_TIME, /* `__TIME__' */
247 T_CONST, /* Constant value, used by `__STDC__' */
248 T_MACRO, /* macro defined by `#define' */
249 T_SPEC_DEFINED, /* special `defined' macro for use in #if statements */
250 T_UNUSED /* Used for something not defined. */
254 struct hashnode *next; /* double links for easy deletion */
255 struct hashnode *prev;
256 struct hashnode **bucket_hdr; /* also, a back pointer to this node's hash
257 chain is kept, in case the node is the head
258 of the chain and gets deleted. */
259 enum node_type type; /* type of special token */
260 int length; /* length of token, for quick comparison */
261 U_CHAR *name; /* the actual name */
262 union hashval value; /* pointer to expansion, or whatever */
265 typedef struct hashnode HASHNODE;
267 static HASHNODE *parse_assertion PARAMS ((const unsigned char *,
268 const unsigned char *,
269 struct answer **, int));
270 static struct answer **find_answer PARAMS ((HASHNODE *,
271 const struct answer *));
272 static int parse_answer PARAMS ((const unsigned char *, const unsigned char *,
273 struct answer **, int));
274 static unsigned char *canonicalize_text PARAMS ((const unsigned char *,
275 const unsigned char *,
276 const unsigned char **));
278 /* Some definitions for the hash table. The hash function MUST be
279 computed as shown in hashf () below. That is because the rescan
280 loop computes the hash value `on the fly' for most tokens,
281 in order to avoid the overhead of a lot of procedure calls to
282 the hashf () function. Hashf () only exists for the sake of
283 politeness, for use when speed isn't so important. */
285 #define HASHSIZE 1403
286 HASHNODE *hashtab[HASHSIZE];
287 #define HASHSTEP(old, c) ((old << 2) + c)
288 #define MAKE_POS(v) (v & 0x7fffffff) /* make number positive */
290 /* `struct directive' defines one #-directive, including how to handle it. */
293 int length; /* Length of name */
294 void (*func) PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
295 /* Function to handle directive */
296 const char *name; /* Name of directive */
297 enum node_type type; /* Code which describes which directive. */
300 /* Last arg to output_line_command. */
301 enum file_change_code {same_file, enter_file, leave_file};
303 /* This structure represents one parsed argument in a macro call.
304 `raw' points to the argument text as written (`raw_length' is its length).
305 `expanded' points to the argument's macro-expansion
306 (its length is `expand_length').
307 `stringified_length' is the length the argument would have
309 `free1' and `free2', if nonzero, point to blocks to be freed
310 when the macro argument data is no longer needed. */
313 U_CHAR *raw, *expanded;
314 int raw_length, expand_length;
315 int stringified_length;
316 U_CHAR *free1, *free2;
321 /* The arglist structure is built by do_define to tell
322 collect_definition where the argument names begin. That
323 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
324 would contain pointers to the strings x, y, and z.
325 Collect_definition would then build a DEFINITION node,
326 with reflist nodes pointing to the places x, y, and z had
327 appeared. So the arglist is just convenience data passed
328 between these two routines. It is not kept around after
329 the current #define has been processed and entered into the
333 struct arglist *next;
339 /* Function prototypes. */
341 static void do_define PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
342 static void do_error PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
343 static void do_warning PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
344 static void do_line PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
345 static void do_include PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
346 static void do_undef PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
347 static void do_if PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
348 static void do_ifdef PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
349 static void do_ifndef PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
350 static void do_else PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
351 static void do_elif PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
352 static void do_endif PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
353 static void do_assert PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
354 static void do_unassert PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
355 static void do_xifdef PARAMS ((U_CHAR *, U_CHAR *, enum node_type));
357 static struct hashnode *install PARAMS ((const U_CHAR *, int, enum node_type, int));
358 static int hashf PARAMS ((const U_CHAR *, int, int));
359 static int compare_defs PARAMS ((DEFINITION *, DEFINITION *));
360 static int comp_def_part PARAMS ((int, const U_CHAR *, int,
361 const U_CHAR *, int, int));
362 static void delete_macro PARAMS ((HASHNODE *));
364 /* First arg to v_message. */
365 enum msgtype { WARNING = 0, ERROR, FATAL };
366 static void v_message PARAMS ((enum msgtype mtype, int line,
367 const char *msgid, va_list ap))
368 ATTRIBUTE_PRINTF (3, 0);
370 static int line_for_error PARAMS ((int));
372 /* We know perfectly well which file this is, so we don't need to
375 #if (GCC_VERSION >= 2007)
376 #define abort() fancy_abort(__LINE__, __FUNCTION__)
378 #define abort() fancy_abort(__LINE__, 0);
381 static void macroexpand PARAMS ((HASHNODE *, FILE_BUF *));
382 static void special_symbol PARAMS ((HASHNODE *, FILE_BUF *));
383 static void dump_all_macros PARAMS ((void));
384 static void dump_defn_1 PARAMS ((const U_CHAR *, int, int));
385 static void dump_arg_n PARAMS ((DEFINITION *, int));
386 static void conditional_skip PARAMS ((FILE_BUF *, int, enum node_type));
387 static void skip_if_group PARAMS ((FILE_BUF *, int));
388 static void output_line_command PARAMS ((FILE_BUF *, FILE_BUF *,
389 int, enum file_change_code));
391 static int eval_if_expression PARAMS ((const U_CHAR *, int));
393 static void initialize_builtins PARAMS ((void));
394 static void run_directive PARAMS ((const char *, size_t,
396 static void make_definition PARAMS ((const char *));
397 static void make_undef PARAMS ((const char *));
398 static void make_assertion PARAMS ((const char *));
400 static void grow_outbuf PARAMS ((FILE_BUF *, int));
401 static int handle_directive PARAMS ((FILE_BUF *, FILE_BUF *));
402 static void finclude PARAMS ((int, const char *, FILE_BUF *));
403 static void deps_output PARAMS ((const char *, int));
404 static void rescan PARAMS ((FILE_BUF *, int));
405 static void newline_fix PARAMS ((U_CHAR *));
406 static void name_newline_fix PARAMS ((U_CHAR *));
407 static U_CHAR *macarg1 PARAMS ((U_CHAR *, const U_CHAR *, int *,
409 static const char *macarg PARAMS ((struct argdata *));
410 static int discard_comments PARAMS ((U_CHAR *, int, int));
411 static int file_size_and_mode PARAMS ((int, int *, long *));
413 static U_CHAR *skip_to_end_of_comment PARAMS ((FILE_BUF *, int *));
414 static U_CHAR *skip_quoted_string PARAMS ((const U_CHAR *, const U_CHAR *,
415 int, int *, int *, int *));
417 int main PARAMS ((int, char **));
419 /* Convenience. Write U"string" to get an unsigned string constant. */
420 #define U (const unsigned char *)
422 /* Here is the actual list of #-directives, most-often-used first. */
424 struct directive directive_table[] = {
425 { 6, do_define, "define", T_DEFINE },
426 { 7, do_include, "include", T_INCLUDE },
427 { 5, do_endif, "endif", T_ENDIF },
428 { 5, do_ifdef, "ifdef", T_IFDEF },
429 { 2, do_if, "if", T_IF, },
430 { 4, do_else, "else", T_ELSE },
431 { 6, do_ifndef, "ifndef", T_IFNDEF },
432 { 5, do_undef, "undef", T_UNDEF },
433 { 4, do_line, "line", T_LINE },
434 { 4, do_elif, "elif", T_ELIF },
435 { 5, do_error, "error", T_ERROR },
436 { 7, do_warning, "warning", T_WARNING },
437 { 6, do_assert, "assert", T_ASSERT },
438 { 8, do_unassert,"unassert",T_UNASSERT},
439 { -1, 0, "", T_UNUSED},
442 #define SKIP_WHITE_SPACE(p) do { while (is_nvspace(*p)) p++; } while (0)
443 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space(*p)) p++; } while (0)
445 int errors = 0; /* Error counter for exit code */
447 static FILE_BUF expand_to_temp_buffer PARAMS ((const U_CHAR *, const U_CHAR *, int));
448 static DEFINITION *collect_expansion PARAMS ((U_CHAR *, U_CHAR *, int,
451 /* Stack of conditionals currently in progress
452 (including both successful and failing conditionals). */
455 struct if_stack *next; /* for chaining to the next stack frame */
456 const char *fname; /* copied from input when frame is made */
457 int lineno; /* similarly */
458 int if_succeeded; /* true if a leg of this if-group
459 has been passed through rescan */
460 enum node_type type; /* type of last directive seen in this group */
462 typedef struct if_stack IF_STACK_FRAME;
463 IF_STACK_FRAME *if_stack = NULL;
465 /* Buffer of -M output. */
469 /* Number of bytes allocated in above. */
470 int deps_allocated_size;
472 /* Number of bytes used. */
475 /* Number of bytes since the last newline. */
478 /* Nonzero means -I- has been seen,
479 so don't look for #include "foo" the source-file directory. */
482 /* Pending directives. */
483 enum pending_dir_t {PD_NONE = 0, PD_DEFINE, PD_UNDEF, PD_ASSERTION, PD_FILE};
485 typedef struct pending_dir pending_dir;
489 enum pending_dir_t type;
499 const char *in_fname, *out_fname;
502 pending_dir *pend = (pending_dir *) xcalloc (argc, sizeof (pending_dir));
503 int no_standard_includes = 0;
505 /* Non-0 means don't output the preprocessed program. */
506 int inhibit_output = 0;
508 /* Stream on which to print the dependency information. */
509 FILE *deps_stream = 0;
510 /* Target-name to write with the dependency information. */
511 char *deps_target = 0;
514 /* Get rid of any avoidable limit on stack size. */
518 /* Set the stack limit huge so that alloca (particularly stringtab
519 * in dbxread.c) does not fail. */
520 getrlimit (RLIMIT_STACK, &rlim);
521 rlim.rlim_cur = rlim.rlim_max;
522 setrlimit (RLIMIT_STACK, &rlim);
524 #endif /* RLIMIT_STACK defined */
531 no_line_commands = 0;
535 max_include_len = cpp_GCC_INCLUDE_DIR_len + 7; /* ??? */
537 /* Process switches and find input file name. */
539 for (i = 1; i < argc; i++) {
540 if (argv[i][0] != '-') {
541 if (out_fname != NULL)
542 fatal ("Usage: %s [switches] input output", argv[0]);
543 else if (in_fname != NULL)
554 break; /* Ignore for compatibility with ISO/extended cpp. */
557 if (!strcmp (argv[i], "-lang-c++")
558 || !strcmp (argv[i], "-lang-objc++"))
559 fatal ("-traditional is not supported in C++");
560 else if (!strcmp (argv[i], "-lang-c89"))
561 fatal ("-traditional and -ansi are mutually exclusive");
562 else if (!strcmp (argv[i], "-lang-objc"))
563 pend[i].type = PD_DEFINE, pend[i].arg = "__OBJC__";
564 else if (!strcmp (argv[i], "-lang-asm"))
565 pend[i].type = PD_DEFINE, pend[i].arg = "__ASSEMBLER__";
566 else if (!strcmp (argv[i], "-lang-fortran"))
567 pend[i].type = PD_DEFINE, pend[i].arg = "_LANGUAGE_FORTRAN";
568 /* All other possibilities ignored. */
572 if (!strcmp (argv[i], "-include"))
575 fatal ("Filename missing after -i option");
577 pend[i].type = PD_FILE, pend[i].arg = argv[i + 1], i++;
579 else if (!strcmp (argv[i], "-iprefix"))
580 i++; /* Ignore for compatibility */
581 else if (!strcmp (argv[i], "-isystem")
582 || !strcmp (argv[i], "-iwithprefix")
583 || !strcmp (argv[i], "-iwithprefixbefore")
584 || !strcmp (argv[i], "-idirafter"))
585 goto add_include; /* best we can do */
590 if (out_fname != NULL)
591 fatal ("Output filename specified twice");
593 fatal ("Filename missing after -o option");
594 out_fname = argv[++i];
595 if (!strcmp (out_fname, "-"))
600 inhibit_warnings = 1;
604 if (!strcmp (argv[i], "-Wcomments"))
606 else if (!strcmp (argv[i], "-Wcomment"))
608 else if (!strcmp (argv[i], "-Wall")) {
614 if (!strcmp (argv[i], "-fleading-underscore"))
615 user_label_prefix = "_";
616 else if (!strcmp (argv[i], "-fno-leading-underscore"))
617 user_label_prefix = "";
624 if (!strncmp (argv[i], "-MD", 3)) {
627 } else if (!strncmp (argv[i], "-MMD", 4)) {
630 } else if (!strcmp (argv[i], "-M")) {
633 } else if (!strcmp (argv[i], "-MM")) {
636 } else if (!strcmp (argv[i], "-MG"))
637 print_deps_missing_files = 1;
641 else if (i + 1 == argc)
642 fatal ("Filename missing after %s option", argv[i]);
644 deps_file = argv[++i];
655 fprintf (stderr, "GNU traditional CPP version %s\n", version_string);
666 else if (i + 1 == argc)
667 fatal ("Macro name missing after -%c option", c);
672 pend[i].type = PD_DEFINE;
674 pend[i].type = PD_UNDEF;
676 pend[i].type = PD_ASSERTION;
682 put_out_comments = 1;
686 if (!strcmp (argv[i], "-pedantic"))
687 fatal ("-pedantic and -traditional are mutually exclusive");
691 if (!strcmp (argv[i], "-trigraphs"))
692 fatal ("-trigraphs and -traditional are mutually exclusive");
696 no_line_commands = 1;
699 case 'I': /* Add directory to path for includes. */
702 struct file_name_list *dirtmp;
704 if (! ignore_srcdir && !strcmp (argv[i] + 2, "-"))
707 dirtmp = (struct file_name_list *)
708 xmalloc (sizeof (struct file_name_list));
709 dirtmp->next = 0; /* New one goes on the end */
713 last_include->next = dirtmp;
714 last_include = dirtmp; /* Tail follows the last one */
715 if (argv[i][1] == 'I' && argv[i][2] != 0)
716 dirtmp->fname = argv[i] + 2;
717 else if (i + 1 == argc)
718 fatal ("Directory name missing after -I option");
720 dirtmp->fname = argv[++i];
721 if (strlen (dirtmp->fname) > max_include_len)
722 max_include_len = strlen (dirtmp->fname);
723 if (ignore_srcdir && first_bracket_include == 0)
724 first_bracket_include = dirtmp;
730 /* -nostdinc causes no default include directories.
731 You must specify all include-file directories with -I. */
732 no_standard_includes = 1;
735 case '\0': /* JF handle '-' as file name meaning stdin or stdout */
736 if (in_fname == NULL) {
739 } else if (out_fname == NULL) {
742 } /* else fall through into error */
745 fatal ("Invalid option `%s'", argv[i]);
750 if (print_deps_missing_files && (!print_deps || !inhibit_output))
751 fatal ("-MG must be specified with one of -M or -MM");
753 if (user_label_prefix == 0)
754 user_label_prefix = USER_LABEL_PREFIX;
756 /* Install __LINE__, etc. Must follow option processing. */
757 initialize_builtins ();
759 /* Do defines specified with -D and undefines specified with -U. */
760 for (i = 1; i < argc; i++)
761 if (pend[i].type == PD_DEFINE)
762 make_definition (pend[i].arg);
763 else if (pend[i].type == PD_UNDEF)
764 make_undef (pend[i].arg);
765 else if (pend[i].type == PD_ASSERTION)
766 make_assertion (pend[i].arg);
768 /* Unless -fnostdinc,
769 tack on the standard include file dirs to the specified list */
770 if (!no_standard_includes) {
771 const struct default_include *di;
772 struct file_name_list *old_last_include = last_include;
773 struct file_name_list *dirtmp;
774 for (di = cpp_include_defaults; di->fname; di++) {
777 dirtmp = (struct file_name_list *)
778 xmalloc (sizeof (struct file_name_list));
779 dirtmp->next = 0; /* New one goes on the end */
783 last_include->next = dirtmp;
784 last_include = dirtmp; /* Tail follows the last one */
785 dirtmp->fname = di->fname;
786 if (strlen (dirtmp->fname) > max_include_len)
787 max_include_len = strlen (dirtmp->fname);
790 if (ignore_srcdir && first_bracket_include == 0)
791 first_bracket_include = old_last_include->next;
794 /* Initialize output buffer */
796 outbuf.buf = (U_CHAR *) xmalloc (OUTBUF_SIZE);
797 outbuf.bufp = outbuf.buf;
798 outbuf.length = OUTBUF_SIZE;
800 /* Scan the -i files before the main input.
801 Much like #including them, but with no_output set
802 so that only their macro definitions matter. */
806 for (i = 1; i < argc; i++)
807 if (pend[i].type == PD_FILE)
809 int fd = open (pend[i].arg, O_RDONLY, 0666);
812 perror_with_name (pend[i].arg);
813 return FATAL_EXIT_CODE;
815 finclude (fd, pend[i].arg, &outbuf);
820 /* Pending directives no longer needed. */
823 /* Create an input stack level for the main input file
824 and copy the entire contents of the file into it. */
826 fp = &instack[++indepth];
828 /* JF check for stdin */
829 if (in_fname == NULL || *in_fname == 0) {
832 } else if ((f = open (in_fname, O_RDONLY, 0666)) < 0)
835 /* Either of two environment variables can specify output of deps.
836 Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
837 where OUTPUT_FILE is the file to write deps info to
838 and DEPS_TARGET is the target to mention in the deps. */
841 && (getenv ("SUNPRO_DEPENDENCIES") != 0
842 || getenv ("DEPENDENCIES_OUTPUT") != 0))
844 char *spec = getenv ("DEPENDENCIES_OUTPUT");
849 spec = getenv ("SUNPRO_DEPENDENCIES");
855 /* Find the space before the DEPS_TARGET, if there is one. */
856 s = strchr (spec, ' ');
862 out_file = (char *) xmalloc (s - spec + 1);
863 memcpy (out_file, spec, s - spec);
864 out_file[s - spec] = 0;
865 deps_file = out_file;
874 /* For -M, print the expected object file name
875 as the target of this Make-rule. */
879 deps_stream = fopen (deps_file, "a");
880 if (deps_stream == 0)
881 pfatal_with_name (deps_file);
883 /* If the -M option was used, output the deps to standard output. */
884 deps_stream = stdout;
886 deps_allocated_size = 200;
887 deps_buffer = (char *) xmalloc (deps_allocated_size);
893 deps_output (deps_target, 0);
894 deps_output (":", 0);
895 } else if (*in_fname == 0)
896 deps_output ("-: ", 0);
899 const char *p = in_fname;
901 /* Discard all directory prefixes from P. */
907 /* Output P, but remove known suffixes. */
909 if (p[len - 2] == '.'
910 && (p[len - 1] == 'c' || p[len - 1] == 'C' || p[len - 1] == 'S'))
911 deps_output (p, len - 2);
912 else if (p[len - 3] == '.'
914 && p[len - 1] == 'c')
915 deps_output (p, len - 3);
918 /* Supply our own suffix. */
919 deps_output (".o : ", 0);
920 deps_output (in_fname, 0);
921 deps_output (" ", 0);
925 if (file_size_and_mode (f, &st_mode, &st_size))
927 fp->fname = in_fname;
929 /* JF all this is mine about reading pipes and ttys */
930 if (!S_ISREG (st_mode)) {
931 /* Read input from a file that is not a normal disk file.
932 We cannot preallocate a buffer with the correct size,
933 so we must read in the file a piece at the time and make it bigger. */
941 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
944 cnt = read (f, bufp, bsize - size);
945 if (cnt < 0) goto sys_error; /* error! */
946 if (cnt == 0) break; /* End of file */
949 if (bsize == size) { /* Buffer is full! */
951 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
952 bufp = fp->buf + size; /* May have moved */
957 /* Read a file whose size we can determine in advance.
958 For the sake of VMS, st_size is just an upper bound. */
961 fp->buf = (U_CHAR *) xmalloc (st_size + 2);
963 while (st_size > 0) {
964 i = read (f, fp->buf + fp->length, st_size);
974 fp->if_stack = if_stack;
976 /* Make sure data ends with a newline. And put a null after it. */
978 if (fp->length > 0 && fp->buf[fp->length-1] != '\n')
979 fp->buf[fp->length++] = '\n';
980 fp->buf[fp->length] = '\0';
982 /* Now that we know the input file is valid, open the output. */
984 if (!out_fname || !strcmp (out_fname, ""))
985 out_fname = "stdout";
986 else if (! freopen (out_fname, "w", stdout))
987 pfatal_with_name (out_fname);
989 output_line_command (fp, &outbuf, 0, same_file);
991 /* Scan the input, processing macros and directives. */
995 /* Now we have processed the entire input
996 Write whichever kind of output has been requested. */
1001 else if (! inhibit_output && deps_stream != stdout) {
1002 if (write (fileno (stdout), outbuf.buf, outbuf.bufp - outbuf.buf) < 0)
1003 fatal ("I/O error on output");
1007 fputs (deps_buffer, deps_stream);
1008 putc ('\n', deps_stream);
1009 if (deps_stream != stdout) {
1010 fclose (deps_stream);
1011 if (ferror (deps_stream))
1012 fatal ("I/O error on output");
1016 if (ferror (stdout))
1017 fatal ("I/O error on output");
1020 exit (FATAL_EXIT_CODE);
1021 exit (SUCCESS_EXIT_CODE);
1024 pfatal_with_name (in_fname);
1027 /* Move all backslash-newline pairs out of embarrassing places.
1028 Exchange all such pairs following BP
1029 with any potentially-embarrasing characters that follow them.
1030 Potentially-embarrassing characters are / and *
1031 (because a backslash-newline inside a comment delimiter
1032 would cause it not to be recognized). */
1037 register U_CHAR *p = bp;
1038 register int count = 0;
1040 /* First count the backslash-newline pairs here. */
1042 while (*p++ == '\\' && *p++ == '\n')
1047 /* Exit if what follows the backslash-newlines is not embarrassing. */
1049 if (count == 0 || (*p != '/' && *p != '*'))
1052 /* Copy all potentially embarrassing characters
1053 that follow the backslash-newline pairs
1054 down to where the pairs originally started. */
1056 while (*p == '*' || *p == '/')
1059 /* Now write the same number of pairs after the embarrassing chars. */
1060 while (count-- > 0) {
1066 /* Like newline_fix but for use within a directive-name.
1067 Move any backslash-newlines up past any following symbol constituents. */
1069 name_newline_fix (bp)
1072 register U_CHAR *p = bp;
1073 register int count = 0;
1075 /* First count the backslash-newline pairs here. */
1077 while (*p++ == '\\' && *p++ == '\n')
1082 /* What follows the backslash-newlines is not embarrassing. */
1084 if (count == 0 || !is_idchar (*p))
1087 /* Copy all potentially embarrassing characters
1088 that follow the backslash-newline pairs
1089 down to where the pairs originally started. */
1091 while (is_idchar (*p))
1094 /* Now write the same number of pairs after the embarrassing chars. */
1095 while (count-- > 0) {
1102 * The main loop of the program.
1104 * Read characters from the input stack, transferring them to the
1107 * Macros are expanded and push levels on the input stack.
1108 * At the end of such a level it is popped off and we keep reading.
1109 * At the end of any other kind of level, we return.
1110 * #-directives are handled, except within macros.
1112 * If OUTPUT_MARKS is nonzero, keep Newline markers found in the input
1113 * and insert them when appropriate. This is set while scanning macro
1114 * arguments before substitution. It is zero when scanning for final output.
1115 * There are three types of Newline markers:
1116 * * Newline - follows a macro name that was not expanded
1117 * because it appeared inside an expansion of the same macro.
1118 * This marker prevents future expansion of that identifier.
1119 * When the input is rescanned into the final output, these are deleted.
1120 * These are also deleted by ## concatenation.
1121 * * Newline Space (or Newline and any other whitespace character)
1122 * stands for a place that tokens must be separated or whitespace
1123 * is otherwise desirable, but where the ANSI standard specifies there
1124 * is no whitespace. This marker turns into a Space (or whichever other
1125 * whitespace char appears in the marker) in the final output,
1126 * but it turns into nothing in an argument that is stringified with #.
1127 * Such stringified arguments are the only place where the ANSI standard
1128 * specifies with precision that whitespace may not appear.
1130 * During this function, IP->bufp is kept cached in IBP for speed of access.
1131 * Likewise, OP->bufp is kept in OBP. Before calling a subroutine
1132 * IBP, IP and OBP must be copied back to memory. IP and IBP are
1133 * copied back with the RECACHE macro. OBP must be copied back from OP->bufp
1134 * explicitly, and before RECACHE, since RECACHE uses OBP.
1138 rescan (op, output_marks)
1142 /* Character being scanned in main loop. */
1145 /* Length of pending accumulated identifier. */
1146 register int ident_length = 0;
1148 /* Hash code of pending accumulated identifier. */
1149 register int hash = 0;
1151 /* Current input level (&instack[indepth]). */
1154 /* Pointer for scanning input. */
1155 register U_CHAR *ibp;
1157 /* Pointer to end of input. End of scan is controlled by LIMIT. */
1158 register U_CHAR *limit;
1160 /* Pointer for storing output. */
1161 register U_CHAR *obp;
1163 /* REDO_CHAR is nonzero if we are processing an identifier
1164 after backing up over the terminating character.
1165 Sometimes we process an identifier without backing up over
1166 the terminating character, if the terminating character
1167 is not special. Backing up is done so that the terminating character
1168 will be dispatched on again once the identifier is dealt with. */
1171 /* 1 if within an identifier inside of which a concatenation
1172 marker (Newline -) has been seen. */
1173 int concatenated = 0;
1175 /* While scanning a comment or a string constant,
1176 this records the line it started on, for error messages. */
1179 /* Record position of last `real' newline. */
1180 U_CHAR *beg_of_line;
1182 /* Pop the innermost input stack level, assuming it is a macro expansion. */
1185 do { ip->macro->type = T_MACRO; \
1186 if (ip->free_ptr) free (ip->free_ptr); \
1187 --indepth; } while (0)
1189 /* Reload `rescan's local variables that describe the current
1190 level of the input stack. */
1193 do { ip = &instack[indepth]; \
1195 limit = ip->buf + ip->length; \
1197 check_expand (op, limit - ibp); \
1199 obp = op->bufp; } while (0)
1201 if (no_output && instack[indepth].fname != 0)
1202 skip_if_group (&instack[indepth], 1);
1208 /* Our caller must always put a null after the end of
1209 the input at each input stack level. */
1222 /* Always merge lines ending with backslash-newline,
1223 even in middle of identifier. */
1226 --obp; /* remove backslash from obuf */
1229 /* Otherwise, backslash suppresses specialness of following char,
1230 so copy it here to prevent the switch from seeing it.
1231 But first get any pending identifier processed. */
1232 if (ident_length > 0)
1238 /* If this is expanding a macro definition, don't recognize
1239 preprocessor directives. */
1245 /* # keyword: a # must be the first char on the line */
1246 if (beg_of_line == 0)
1248 if (beg_of_line + 1 != ibp)
1251 /* This # can start a directive. */
1253 --obp; /* Don't copy the '#' */
1257 if (! handle_directive (ip, op)) {
1261 /* Not a known directive: treat it as ordinary text.
1262 IP, OP, IBP, etc. have not been changed. */
1263 if (no_output && instack[indepth].fname) {
1264 /* If not generating expanded output,
1265 what we do with ordinary text is skip it.
1266 Discard everything until next # directive. */
1267 skip_if_group (&instack[indepth], 1);
1272 ++obp; /* Copy the '#' after all */
1278 /* A # directive has been successfully processed. */
1279 /* If not generating expanded output, ignore everything until
1280 next # directive. */
1281 if (no_output && instack[indepth].fname)
1282 skip_if_group (&instack[indepth], 1);
1288 case '\"': /* skip quoted string */
1290 /* A single quoted string is treated like a double -- some
1291 programs (e.g., troff) are perverse this way */
1296 start_line = ip->lineno;
1298 /* Skip ahead to a matching quote. */
1302 if (ip->macro != 0) {
1303 /* try harder: this string crosses a macro expansion boundary */
1315 /* Traditionally, end of line ends a string constant with no error.
1316 So exit the loop and record the new line. */
1324 /* Backslash newline is replaced by nothing at all,
1325 but keep the line counts correct. */
1330 /* ANSI stupidly requires that in \\ the second \
1331 is *not* prevented from combining with a newline. */
1332 while (*ibp == '\\' && ibp[1] == '\n') {
1351 if (*ibp == '\\' && ibp[1] == '\n')
1353 /* Don't look for comments inside a macro definition. */
1356 /* A comment constitutes white space, so it can terminate an identifier.
1357 Process the identifier, if any. */
1364 /* We have a comment. Skip it, optionally copying it to output. */
1366 start_line = ip->lineno;
1368 ++ibp; /* Skip the star. */
1370 /* In K+R C, a comment is equivalent to nothing. Note that we
1371 already output the slash; we might not want it. */
1372 if (! put_out_comments)
1378 U_CHAR *before_bp = ibp;
1380 while (ibp < limit) {
1383 if (warn_comments && ibp < limit && *ibp == '*')
1384 warning("`/*' within comment");
1387 if (*ibp == '\\' && ibp[1] == '\n')
1389 if (ibp >= limit || *ibp == '/')
1394 /* Copy the newline into the output buffer, in order to
1395 avoid the pain of a #line every time a multiline comment
1397 if (!put_out_comments)
1405 error_with_line (line_for_error (start_line),
1406 "unterminated comment");
1409 if (put_out_comments) {
1410 memcpy (obp, before_bp, ibp - before_bp);
1411 obp += ibp - before_bp;
1417 case '0': case '1': case '2': case '3': case '4':
1418 case '5': case '6': case '7': case '8': case '9':
1419 /* If digit is not part of identifier, it starts a number,
1420 which means that following letters are not an identifier.
1421 "0x5" does not refer to an identifier "x5".
1422 So copy all alphanumerics that follow without accumulating
1423 as an identifier. Periods also, for sake of "3.e7". */
1425 if (ident_length == 0) {
1426 while (ibp < limit) {
1427 while (ibp < limit && ibp[0] == '\\' && ibp[1] == '\n') {
1432 if (!ISALNUM (c) && c != '.' && c != '_') {
1437 /* A sign can be part of a preprocessing number
1438 if it follows an e. */
1439 if (c == 'e' || c == 'E') {
1440 while (ibp < limit && ibp[0] == '\\' && ibp[1] == '\n') {
1444 if (ibp < limit && (*ibp == '+' || *ibp == '-')) {
1446 /* Traditional C does not let the token go past the sign. */
1456 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1457 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
1458 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
1459 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
1461 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1462 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
1463 case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
1464 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
1467 /* Compute step of hash function, to avoid a proc call on every token */
1468 hash = HASHSTEP (hash, c);
1472 /* If reprocessing a macro expansion, newline is a special marker. */
1473 if (ip->macro != 0) {
1474 /* Newline White is a "funny space" to separate tokens that are
1475 supposed to be separate but without space between.
1476 Here White means any horizontal whitespace character.
1477 Newline - marks a recursive macro use that is not
1478 supposed to be expandable. */
1481 /* Newline - inhibits expansion of preceding token.
1482 If expanding a macro arg, we keep the newline -.
1483 In final output, it is deleted. */
1484 if (! concatenated) {
1489 if (!output_marks) {
1492 /* If expanding a macro arg, keep the newline -. */
1495 } else if (is_space (*ibp)) {
1496 /* Newline Space does not prevent expansion of preceding token
1497 so expand the preceding token and then come back. */
1498 if (ident_length > 0)
1501 /* If generating final output, newline space makes a space. */
1502 if (!output_marks) {
1504 /* And Newline Newline makes a newline, so count it. */
1505 if (obp[-1] == '\n')
1508 /* If expanding a macro arg, keep the newline space.
1509 If the arg gets stringified, newline space makes nothing. */
1512 } else abort (); /* Newline followed by something random? */
1516 /* If there is a pending identifier, handle it and come back here. */
1517 if (ident_length > 0)
1522 /* Update the line counts and output a #line if necessary. */
1525 if (ip->lineno != op->lineno) {
1527 output_line_command (ip, op, 1, same_file);
1528 check_expand (op, ip->length - (ip->bufp - ip->buf));
1533 /* Come here either after (1) a null character that is part of the input
1534 or (2) at the end of the input, because there is a null there. */
1537 /* Our input really contains a null character. */
1540 /* At end of a macro-expansion level, pop it and read next level. */
1541 if (ip->macro != 0) {
1544 /* If we have an identifier that ends here, process it now, so
1545 we get the right error for recursion. */
1546 if (ident_length && ! is_idchar (*instack[indepth - 1].bufp)) {
1555 /* If we don't have a pending identifier,
1556 return at end of input. */
1557 if (ident_length == 0) {
1565 /* If we do have a pending identifier, just consider this null
1566 a special character and arrange to dispatch on it again.
1567 The second time, IDENT_LENGTH will be zero so we will return. */
1573 /* Handle the case of a character such as /, ', " or null
1574 seen following an identifier. Back over it so that
1575 after the identifier is processed the special char
1576 will be dispatched on again. */
1586 if (ident_length > 0) {
1587 register HASHNODE *hp;
1589 /* We have just seen an identifier end. If it's a macro, expand it.
1591 IDENT_LENGTH is the length of the identifier
1592 and HASH is its hash code.
1594 The identifier has already been copied to the output,
1595 so if it is a macro we must remove it.
1597 If REDO_CHAR is 0, the char that terminated the identifier
1598 has been skipped in the output and the input.
1599 OBP-IDENT_LENGTH-1 points to the identifier.
1600 If the identifier is a macro, we must back over the terminator.
1602 If REDO_CHAR is 1, the terminating char has already been
1603 backed over. OBP-IDENT_LENGTH points to the identifier. */
1605 for (hp = hashtab[MAKE_POS (hash) % HASHSIZE]; hp != NULL;
1608 if (hp->length == ident_length) {
1609 U_CHAR *obufp_before_macroname;
1610 int op_lineno_before_macroname;
1611 register int i = ident_length;
1612 register U_CHAR *p = hp->name;
1613 register U_CHAR *q = obp - i;
1618 do { /* All this to avoid a strncmp () */
1623 /* We found a use of a macro name.
1624 see if the context shows it is a macro call. */
1626 /* Back up over terminating character if not already done. */
1632 obufp_before_macroname = obp - ident_length;
1633 op_lineno_before_macroname = op->lineno;
1635 /* If macro wants an arglist, verify that a '(' follows.
1636 first skip all whitespace, copying it to the output
1637 after the macro name. Then, if there is no '(',
1638 decide this is not a macro call and leave things that way. */
1639 if (hp->type == T_MACRO && hp->value.defn->nargs >= 0)
1642 /* Scan forward over whitespace, copying it to the output. */
1643 if (ibp == limit && ip->macro != 0) {
1647 /* A comment: copy it unchanged or discard it. */
1648 else if (*ibp == '/' && ibp+1 != limit && ibp[1] == '*') {
1649 if (put_out_comments) {
1654 while (ibp + 1 != limit
1655 && !(ibp[0] == '*' && ibp[1] == '/')) {
1656 /* We need not worry about newline-marks,
1657 since they are never found in comments. */
1659 /* Newline in a file. Count it. */
1663 if (put_out_comments)
1669 if (put_out_comments) {
1674 else if (is_space (*ibp)) {
1676 if (ibp[-1] == '\n') {
1677 if (ip->macro == 0) {
1678 /* Newline in a file. Count it. */
1681 } else if (!output_marks) {
1682 /* A newline mark, and we don't want marks
1683 in the output. If it is newline-hyphen,
1684 discard it entirely. Otherwise, it is
1685 newline-whitechar, so keep the whitechar. */
1695 /* A newline mark; copy both chars to the output. */
1706 /* This is now known to be a macro call.
1707 Discard the macro name from the output,
1708 along with any following whitespace just copied. */
1709 obp = obufp_before_macroname;
1710 op->lineno = op_lineno_before_macroname;
1712 /* Expand the macro, reading arguments as needed,
1713 and push the expansion on the input stack. */
1716 macroexpand (hp, op);
1718 /* Reexamine input stack, since macroexpand has pushed
1719 a new level on it. */
1726 } /* End hash-table-search loop */
1727 ident_length = hash = 0; /* Stop collecting identifier */
1730 } /* End if (ident_length > 0) */
1732 } /* End per-char loop */
1734 /* Come here to return -- but first give an error message
1735 if there was an unterminated successful conditional. */
1737 if (if_stack != ip->if_stack) {
1739 switch (if_stack->type) {
1758 error_with_line (line_for_error (if_stack->lineno),
1759 "unterminated #%s conditional", str);
1761 if_stack = ip->if_stack;
1765 * Rescan a string into a temporary buffer and return the result
1766 * as a FILE_BUF. Note this function returns a struct, not a pointer.
1768 * OUTPUT_MARKS nonzero means keep Newline markers found in the input
1769 * and insert such markers when appropriate. See `rescan' for details.
1770 * OUTPUT_MARKS is 1 for macroexpanding a macro argument separately
1771 * before substitution; it is 0 for other uses.
1774 expand_to_temp_buffer (buf, limit, output_marks)
1775 const U_CHAR *buf, *limit;
1778 register FILE_BUF *ip;
1780 int length = limit - buf;
1782 int odepth = indepth;
1787 /* Set up the input on the input stack. */
1789 buf1 = (U_CHAR *) alloca (length + 1);
1791 register const U_CHAR *p1 = buf;
1792 register U_CHAR *p2 = buf1;
1799 /* Set up to receive the output. */
1801 obuf.length = length * 2 + 100; /* Usually enough. Why be stingy? */
1802 obuf.bufp = obuf.buf = (U_CHAR *) xmalloc (obuf.length);
1807 CHECK_DEPTH ({return obuf;});
1811 ip = &instack[indepth];
1815 ip->length = length;
1816 ip->buf = ip->bufp = buf1;
1817 ip->if_stack = if_stack;
1819 ip->lineno = obuf.lineno = 1;
1821 /* Scan the input, create the output. */
1823 rescan (&obuf, output_marks);
1825 /* Pop input stack to original state. */
1828 if (indepth != odepth)
1831 /* Record the output. */
1832 obuf.length = obuf.bufp - obuf.buf;
1838 * Process a # directive. Expects IP->bufp to point to the '#', as in
1839 * `#define foo bar'. Passes to the command handler
1840 * (do_define, do_include, etc.): the addresses of the 1st and
1841 * last chars of the command (starting immediately after the #
1842 * keyword), plus op and the keyword table pointer. If the command
1843 * contains comments it is copied into a temporary buffer sans comments
1844 * and the temporary buffer is passed to the command handler instead.
1845 * Likewise for backslash-newlines.
1847 * Returns nonzero if this was a known # directive.
1848 * Otherwise, returns zero, without advancing the input pointer.
1852 handle_directive (ip, op)
1855 register U_CHAR *bp, *cp;
1856 register struct directive *kt;
1857 register int ident_length;
1860 /* Nonzero means we must copy the entire command
1861 to get rid of comments or backslash-newlines. */
1862 int copy_command = 0;
1864 U_CHAR *ident, *after_ident;
1867 /* Skip whitespace and \-newline. */
1869 if (is_nvspace (*bp))
1871 else if (*bp == '/' && (newline_fix (bp + 1), bp[1]) == '*') {
1873 skip_to_end_of_comment (ip, &ip->lineno);
1875 } else if (*bp == '\\' && bp[1] == '\n') {
1876 bp += 2; ip->lineno++;
1880 /* Now find end of directive name.
1881 If we encounter a backslash-newline, exchange it with any following
1882 symbol-constituents so that we end up with a contiguous name. */
1886 if (is_idchar (*cp))
1889 if (*cp == '\\' && cp[1] == '\n')
1890 name_newline_fix (cp);
1891 if (is_idchar (*cp))
1896 ident_length = cp - bp;
1900 /* A line of just `#' becomes blank. */
1902 if (ident_length == 0 && *after_ident == '\n') {
1903 ip->bufp = after_ident;
1908 * Decode the keyword and call the appropriate expansion
1909 * routine, after moving the input pointer up to the next line.
1911 for (kt = directive_table; kt->length > 0; kt++) {
1912 if (kt->length == ident_length
1913 && !strncmp (kt->name, (const char *)ident, ident_length)) {
1914 register U_CHAR *buf;
1915 register U_CHAR *limit = ip->buf + ip->length;
1916 int unterminated = 0;
1918 /* Nonzero means do not delete comments within the directive.
1919 #define needs this to detect traditional token paste. */
1920 int keep_comments = kt->type == T_DEFINE;
1922 /* Find the end of this command (first newline not backslashed
1923 and not in a string or comment).
1924 Set COPY_COMMAND if the command must be copied
1925 (it contains a backslash-newline or a comment). */
1927 buf = bp = after_ident;
1928 while (bp < limit) {
1929 register U_CHAR c = *bp++;
1943 bp = skip_quoted_string (bp - 1, limit, ip->lineno, &ip->lineno, ©_command, &unterminated);
1945 /* Traditional preprocessing permits unterminated strings. */
1951 /* <...> is special for #include. */
1953 if (kt->type != T_INCLUDE)
1955 while (*bp && *bp != '>') bp++;
1959 if (*bp == '\\' && bp[1] == '\n')
1962 U_CHAR *obp = bp - 1;
1964 skip_to_end_of_comment (ip, &ip->lineno);
1966 /* No need to copy the command because of a comment at the end;
1967 just don't include the comment in the directive. */
1968 if (bp == limit || *bp == '\n') {
1972 /* Don't remove the comments if this is #define. */
1973 if (! keep_comments)
1979 --bp; /* Point to the newline */
1987 resume_p = ip->bufp;
1988 /* BP is the end of the directive.
1989 RESUME_P is the next interesting data after the directive.
1990 A comment may come between. */
1993 register U_CHAR *xp = buf;
1994 /* Need to copy entire command into temp buffer before dispatching */
1996 cp = (U_CHAR *) alloca (bp - buf + 5); /* room for cmd plus
2000 /* Copy to the new buffer, deleting comments
2001 and backslash-newlines (and whitespace surrounding the latter). */
2004 register U_CHAR c = *xp++;
2011 /* <...> is special for #include. */
2013 if (kt->type != T_INCLUDE)
2015 while (xp < bp && c != '>') {
2017 if (c == '\\' && xp < bp && *xp == '\n')
2028 if (cp != buf && is_space (cp[-1])) {
2029 while (cp != buf && is_space(cp[-1])) cp--;
2031 SKIP_WHITE_SPACE (xp);
2032 } else if (is_space (*xp)) {
2034 SKIP_WHITE_SPACE (xp);
2044 register const U_CHAR *bp1
2045 = skip_quoted_string (xp - 1, limit, ip->lineno, 0, 0, 0);
2054 skip_to_end_of_comment (ip, 0);
2056 while (xp != ip->bufp)
2058 /* Delete the slash. */
2066 /* Null-terminate the copy. */
2073 ip->bufp = resume_p;
2075 /* Call the appropriate command handler. buf now points to
2076 either the appropriate place in the input buffer, or to
2077 the temp buffer if it was necessary to make one. cp
2078 points to the first char after the contents of the (possibly
2079 copied) command, in either case. */
2080 (*kt->func) (buf, cp, op);
2081 check_expand (op, ip->length - (ip->bufp - ip->buf));
2090 static const char *const
2091 monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
2092 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
2095 * expand things like __FILE__. Place the expansion into the output
2096 * buffer *without* rescanning.
2099 special_symbol (hp, op)
2107 FILE_BUF *ip = NULL;
2108 static struct tm *timebuf = NULL;
2110 int paren = 0; /* For special `defined' keyword */
2112 for (i = indepth; i >= 0; i--)
2113 if (instack[i].fname != NULL) {
2118 fatal ("not in any file?!");
2125 if (hp->type == T_FILE)
2128 string = instack[0].fname;
2132 char *tmp = (char *) alloca (3 + strlen (string));
2133 sprintf (tmp, "\"%s\"", string);
2142 case T_INCLUDE_LEVEL:
2144 char *tmp = (char *) alloca (8); /* Eigth bytes ought to be more than enough */
2146 for (i = indepth; i >= 0; i--)
2147 if (instack[i].fname != NULL)
2150 sprintf (tmp, "%d", true_indepth - 1);
2157 char *tmp = (char *) alloca (3 + strlen (version_string));
2158 sprintf (tmp, "\"%s\"", version_string);
2164 buf = hp->value.cpval;
2169 char *tmp = (char *) alloca (10);
2170 sprintf (tmp, "%d", ip->lineno);
2178 char *tmp = (char *) alloca (20);
2180 if (timebuf == NULL) {
2182 timebuf = localtime (&t);
2184 if (hp->type == T_DATE)
2185 sprintf (tmp, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
2186 timebuf->tm_mday, timebuf->tm_year + 1900);
2188 sprintf (tmp, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
2194 case T_SPEC_DEFINED:
2195 buf = " 0 "; /* Assume symbol is not defined */
2196 ip = &instack[indepth];
2197 SKIP_WHITE_SPACE (ip->bufp);
2198 if (*ip->bufp == '(') {
2200 ip->bufp++; /* Skip over the paren */
2201 SKIP_WHITE_SPACE (ip->bufp);
2204 if (!is_idstart (*ip->bufp))
2207 HASHNODE *hp = lookup (ip->bufp, -1, -1);
2209 if (hp && hp->type != T_UNUSED && hp->type != T_SPEC_DEFINED)
2212 while (is_idchar (*ip->bufp))
2214 SKIP_WHITE_SPACE (ip->bufp);
2216 if (*ip->bufp != ')')
2224 error ("`defined' must be followed by ident or (ident)");
2228 error ("cccp error: invalid special hash type"); /* time for gdb */
2232 check_expand (op, len);
2233 memcpy (op->bufp, buf, len);
2238 /* Routines to handle #directives */
2241 * Process include file by reading it in and calling rescan.
2242 * Expects to see "fname" or <fname> on the input.
2245 do_include (buf, limit, op)
2246 U_CHAR *buf, *limit;
2249 char *fname; /* Dynamically allocated fname buffer */
2250 U_CHAR *fbeg, *fend; /* Beginning and end of fname */
2252 struct file_name_list *stackp = include; /* Chain of dirs to search */
2253 struct file_name_list dsp[1]; /* First in chain, if #include "..." */
2256 int f; /* file number */
2258 int retried = 0; /* Have already tried macro
2259 expanding the include line*/
2260 FILE_BUF trybuf; /* It got expanded into here */
2261 int system_header_p = 0; /* 0 for "...", 1 for <...> */
2263 f= -1; /* JF we iz paranoid! */
2268 SKIP_WHITE_SPACE (fbeg);
2269 /* Discard trailing whitespace so we can easily see
2270 if we have parsed all the significant chars we were given. */
2271 while (limit != fbeg && is_nvspace (limit[-1])) limit--;
2276 while (fend != limit && *fend != '\"')
2278 if (*fend == '\"' && fend + 1 == limit) {
2281 /* We have "filename". Figure out directory this source
2282 file is coming from and put it on the front of the list. */
2284 /* If -I- was specified, don't search current dir, only spec'd ones. */
2285 if (ignore_srcdir) break;
2287 for (fp = &instack[indepth]; fp >= instack; fp--)
2290 const char *ep, *nam;
2292 if ((nam = fp->fname) != NULL) {
2293 /* Found a named file. Figure out dir of the file,
2294 and put it in front of the search list. */
2295 dsp[0].next = stackp;
2297 ep = strrchr (nam, '/');
2301 f = (char *) alloca (n + 1);
2302 strncpy (f, nam, n);
2305 if (n > max_include_len) max_include_len = n;
2307 dsp[0].fname = 0; /* Current directory */
2318 while (fend != limit && *fend != '>') fend++;
2319 if (*fend == '>' && fend + 1 == limit) {
2320 system_header_p = 1;
2321 /* If -I-, start with the first -I dir after the -I-. */
2322 if (first_bracket_include)
2323 stackp = first_bracket_include;
2331 error ("#include expects \"fname\" or <fname>");
2334 trybuf = expand_to_temp_buffer (buf, limit, 0);
2335 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
2336 memcpy (buf, trybuf.buf, trybuf.bufp - trybuf.buf);
2337 limit = buf + (trybuf.bufp - trybuf.buf);
2345 fname = (char *) alloca (max_include_len + flen + 2);
2346 /* + 2 above for slash and terminating null. */
2348 /* If specified file name is absolute, just open it. */
2351 strncpy (fname, (const char *)fbeg, flen);
2353 f = open (fname, O_RDONLY, 0666);
2355 /* Search directory path, trying to open the file.
2356 Copy each filename tried into FNAME. */
2358 for (; stackp; stackp = stackp->next) {
2359 if (stackp->fname) {
2360 strcpy (fname, stackp->fname);
2361 strcat (fname, "/");
2362 fname[strlen (fname) + flen] = 0;
2366 strncat (fname, (const char *)fbeg, flen);
2367 if ((f = open (fname, O_RDONLY, 0666)) >= 0)
2373 strncpy (fname, (const char *)fbeg, flen);
2375 if (print_deps_missing_files
2376 && print_deps > (system_header_p || (system_include_depth > 0))) {
2378 /* If requested as a system header, assume it belongs in
2379 the first system header directory. */
2380 if (first_bracket_include)
2381 stackp = first_bracket_include;
2385 if (!system_header_p || *fbeg == '/' || !stackp->fname)
2386 deps_output ((const char *)fbeg, flen);
2389 int len = strlen(stackp->fname);
2391 p = (char *) alloca (len + flen + 2);
2392 memcpy (p, stackp->fname, len);
2394 memcpy (p + len, fbeg, flen);
2396 deps_output (p, len);
2398 deps_output (" ", 0);
2400 } else if (print_deps
2401 && print_deps <= (system_header_p
2402 || (system_include_depth > 0)))
2403 warning ("No include path in which to find %.*s", flen, fbeg);
2405 error_from_errno (fname);
2409 /* Check to see if this include file is a once-only include file.
2412 struct file_name_list* ptr;
2414 for (ptr = dont_repeat_files; ptr; ptr = ptr->next) {
2415 if (!strcmp (ptr->fname, fname)) {
2417 return; /* This file was once'd. */
2421 for (ptr = all_include_files; ptr; ptr = ptr->next) {
2422 if (!strcmp (ptr->fname, fname))
2423 break; /* This file was included before. */
2427 /* This is the first time for this file. */
2428 /* Add it to list of files included. */
2430 ptr = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
2431 ptr->next = all_include_files;
2432 all_include_files = ptr;
2433 ptr->fname = xstrdup (fname);
2435 /* For -M, add this file to the dependencies. */
2436 if (print_deps > (system_header_p || (system_include_depth > 0))) {
2437 deps_output (fname, strlen (fname));
2438 deps_output (" ", 0);
2442 if (system_header_p)
2443 system_include_depth++;
2445 /* Actually process the file. */
2446 finclude (f, fname, op);
2448 if (system_header_p)
2449 system_include_depth--;
2455 /* Process the contents of include file FNAME, already open on descriptor F,
2456 with output to OP. */
2459 finclude (f, fname, op)
2467 FILE_BUF *fp; /* For input stack frame */
2469 CHECK_DEPTH (return;);
2471 if (file_size_and_mode (f, &st_mode, &st_size))
2474 fp = &instack[indepth + 1];
2475 memset (fp, 0, sizeof (FILE_BUF));
2479 fp->if_stack = if_stack;
2481 if (S_ISREG (st_mode)) {
2482 fp->buf = (U_CHAR *) xmalloc (st_size + 2);
2485 /* Read the file contents, knowing that st_size is an upper bound
2486 on the number of bytes we can read. */
2487 while (st_size > 0) {
2488 i = read (f, fp->buf + fp->length, st_size);
2498 /* Cannot count its file size before reading. */
2505 basep = (U_CHAR *) xmalloc (bsize + 2);
2509 i = read (f, bufp, bsize - st_size);
2511 goto nope; /* error! */
2513 break; /* End of file */
2516 if (bsize == st_size) { /* Buffer is full! */
2518 basep = (U_CHAR *) xrealloc (basep, bsize + 2);
2519 bufp = basep + st_size; /* May have moved */
2524 fp->length = st_size;
2528 /* Make sure data ends with a newline. And put a null after it. */
2530 if (fp->length > 0 && fp->buf[fp->length-1] != '\n')
2531 fp->buf[fp->length++] = '\n';
2532 fp->buf[fp->length] = '\0';
2535 output_line_command (fp, op, 0, enter_file);
2538 instack[indepth].lineno++;
2539 instack[indepth].bufp++; /* Skip the new line. */
2540 output_line_command (&instack[indepth], op, 0, leave_file);
2545 perror_with_name (fname);
2550 /* Process a #define command.
2551 BUF points to the contents of the #define command, as a continguous string.
2552 LIMIT points to the first character past the end of the definition.
2553 KEYWORD is the keyword-table entry for #define. */
2556 do_define (buf, limit, op)
2557 U_CHAR *buf, *limit;
2558 FILE_BUF *op ATTRIBUTE_UNUSED;
2560 U_CHAR *bp; /* temp ptr into input buffer */
2561 U_CHAR *symname; /* remember where symbol name starts */
2562 int sym_length; /* and how long it is */
2565 int arglengths = 0; /* Accumulate lengths of arg names
2566 plus number of args. */
2571 while (is_nvspace (*bp))
2574 symname = bp; /* remember where it starts */
2575 while (is_idchar (*bp) && bp < limit) {
2578 sym_length = bp - symname;
2579 if (sym_length == 0)
2581 error ("invalid macro name");
2584 else if (!is_idstart (*symname)) {
2585 U_CHAR *msg; /* what pain... */
2586 msg = (U_CHAR *) alloca (sym_length + 1);
2587 memcpy (msg, symname, sym_length);
2588 msg[sym_length] = 0;
2589 error ("invalid macro name `%s'", msg);
2592 if (! strncmp ((const char *)symname, "defined", 7) && sym_length == 7)
2594 error ("\"defined\" cannot be used as a macro name");
2599 /* lossage will occur if identifiers or control keywords are broken
2600 across lines using backslash. This is not the right place to take
2604 struct arglist *arg_ptrs = NULL;
2607 bp++; /* skip '(' */
2608 SKIP_WHITE_SPACE (bp);
2610 /* Loop over macro argument names. */
2611 while (*bp != ')') {
2612 struct arglist *temp;
2614 temp = (struct arglist *) alloca (sizeof (struct arglist));
2616 temp->next = arg_ptrs;
2617 temp->argno = argno++;
2620 if (!is_idstart (*bp))
2621 warning ("parameter name starts with a digit in #define");
2623 /* Find the end of the arg name. */
2624 while (is_idchar (*bp)) {
2627 temp->length = bp - temp->name;
2628 arglengths += temp->length + 2;
2629 SKIP_WHITE_SPACE (bp);
2630 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
2631 error ("badly punctuated parameter list in #define");
2636 SKIP_WHITE_SPACE (bp);
2639 error ("unterminated parameter list in #define");
2644 ++bp; /* skip paren */
2645 while (is_nvspace (*bp)) /* and leading whitespace */
2647 /* now everything from bp before limit is the definition. */
2648 defn = collect_expansion (bp, limit, argno, arg_ptrs);
2650 /* Now set defn->argnames to the result of concatenating
2651 the argument names in reverse order
2652 with comma-space between them. */
2654 struct arglist *temp;
2656 U_CHAR *tmp = (U_CHAR *) xmalloc (arglengths + 1);
2658 for (temp = arg_ptrs; temp; temp = temp->next) {
2659 memcpy (&tmp[i], temp->name, temp->length);
2661 if (temp->next != 0) {
2667 defn->argnames = tmp;
2671 /* simple expansion or empty definition; skip leading whitespace */
2672 while (is_nvspace (*bp))
2674 /* now everything from bp before limit is the definition. */
2675 defn = collect_expansion (bp, limit, -1, 0);
2676 defn->argnames = (const U_CHAR *) "";
2679 hashcode = hashf (symname, sym_length, HASHSIZE);
2683 if ((hp = lookup (symname, sym_length, hashcode)) == NULL)
2684 hp = install (symname, sym_length, T_MACRO, hashcode);
2686 if (hp->type != T_MACRO || compare_defs (defn, hp->value.defn))
2687 warning ("\"%.*s\" redefined", sym_length, symname);
2689 /* Replace the old definition. */
2693 hp->value.defn = defn;
2698 * return zero if two DEFINITIONs are isomorphic
2701 compare_defs (d1, d2)
2702 DEFINITION *d1, *d2;
2704 register struct reflist *a1, *a2;
2705 register U_CHAR *p1 = d1->expansion;
2706 register U_CHAR *p2 = d2->expansion;
2709 if (d1->nargs != d2->nargs)
2711 if (strcmp ((const char *)d1->argnames, (const char *)d2->argnames))
2713 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
2714 a1 = a1->next, a2 = a2->next) {
2715 if (!((a1->nchars == a2->nchars
2716 && ! strncmp ((const char *)p1, (const char *)p2, a1->nchars))
2717 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
2718 || a1->argno != a2->argno
2719 || a1->stringify != a2->stringify
2720 || a1->raw_before != a2->raw_before
2721 || a1->raw_after != a2->raw_after)
2729 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
2730 p2, d2->length - (p2 - d2->expansion), 1))
2735 /* Return 1 if two parts of two macro definitions are effectively different.
2736 One of the parts starts at BEG1 and has LEN1 chars;
2737 the other has LEN2 chars at BEG2.
2738 Any sequence of whitespace matches any other sequence of whitespace.
2739 FIRST means these parts are the first of a macro definition;
2740 so ignore leading whitespace entirely.
2741 LAST means these parts are the last of a macro definition;
2742 so ignore trailing whitespace entirely. */
2744 comp_def_part (first, beg1, len1, beg2, len2, last)
2746 const U_CHAR *beg1, *beg2;
2750 register const U_CHAR *end1 = beg1 + len1;
2751 register const U_CHAR *end2 = beg2 + len2;
2753 while (beg1 != end1 && is_space (*beg1)) beg1++;
2754 while (beg2 != end2 && is_space (*beg2)) beg2++;
2757 while (beg1 != end1 && is_space (end1[-1])) end1--;
2758 while (beg2 != end2 && is_space (end2[-1])) end2--;
2760 while (beg1 != end1 && beg2 != end2) {
2761 if (is_space (*beg1) && is_space (*beg2)) {
2762 while (beg1 != end1 && is_space (*beg1)) beg1++;
2763 while (beg2 != end2 && is_space (*beg2)) beg2++;
2764 } else if (*beg1 == *beg2) {
2768 return (beg1 != end1) || (beg2 != end2);
2771 /* Read a replacement list for a macro with parameters.
2772 Build the DEFINITION structure.
2773 Reads characters of text starting at BUF until LIMIT.
2774 ARGLIST specifies the formal parameters to look for
2775 in the text of the definition; NARGS is the number of args
2776 in that list, or -1 for a macro name that wants no argument list.
2777 MACRONAME is the macro name itself (so we can avoid recursive expansion)
2778 and NAMELEN is its length in characters.
2780 Note that comments and backslash-newlines have already been deleted
2781 from the argument. */
2783 /* Leading and trailing Space, Tab, etc. are converted to markers
2784 Newline Space, Newline Tab, etc.
2785 Newline Space makes a space in the final output
2786 but is discarded if stringified. (Newline Tab is similar but
2787 makes a Tab instead.)
2789 If there is no trailing whitespace, a Newline Space is added at the end
2790 to prevent concatenation that would be contrary to the standard. */
2793 collect_expansion (buf, end, nargs, arglist)
2796 struct arglist *arglist;
2799 register U_CHAR *p, *limit, *lastp, *exp_p;
2800 struct reflist *endpat = NULL;
2801 /* Pointer to first nonspace after last ## seen. */
2803 /* Pointer to first nonspace after last single-# seen. */
2804 U_CHAR *stringify = 0;
2806 int expected_delimiter = '\0';
2808 /* Scan thru the replacement list, ignoring comments and quoted
2809 strings, picking up on the macro calls. It does a linear search
2810 thru the arg list on every potential symbol. Profiling might say
2811 that something smarter should happen. */
2816 /* Find the beginning of the trailing whitespace. */
2817 /* Find end of leading whitespace. */
2820 while (p < limit && is_space (limit[-1])) limit--;
2821 while (p < limit && is_space (*p)) p++;
2823 /* Allocate space for the text in the macro definition.
2824 Leading and trailing whitespace chars need 2 bytes each.
2825 Each other input char may or may not need 1 byte,
2826 so this is an upper bound.
2827 The extra 2 are for invented trailing newline-marker and final null. */
2828 maxsize = (sizeof (DEFINITION)
2829 + 2 * (end - limit) + 2 * (p - buf)
2831 defn = (DEFINITION *) xcalloc (1, maxsize);
2833 defn->nargs = nargs;
2834 exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
2839 /* Convert leading whitespace to Newline-markers. */
2840 while (p < limit && is_space (*p)) {
2845 /* Process the main body of the definition. */
2847 int skipped_arg = 0;
2848 register U_CHAR c = *p++;
2852 /* In -traditional mode, recognize arguments inside strings and
2853 and character constants, and ignore special properties of #.
2854 Arguments inside strings are considered "stringified", but no
2855 extra quote marks are supplied. */
2859 if (expected_delimiter != '\0') {
2860 if (c == expected_delimiter)
2861 expected_delimiter = '\0';
2863 expected_delimiter = c;
2867 /* Backslash quotes delimiters and itself, but not macro args. */
2868 if (expected_delimiter != 0 && p < limit
2869 && (*p == expected_delimiter || *p == '\\')) {
2876 if (expected_delimiter != '\0') /* No comments inside strings. */
2879 /* If we find a comment that wasn't removed by handle_directive,
2880 this must be -traditional. So replace the comment with
2884 while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
2890 if (is_idchar (c) && nargs > 0) {
2891 U_CHAR *id_beg = p - 1;
2895 while (p != limit && is_idchar (*p)) p++;
2896 id_len = p - id_beg;
2898 if (is_idstart (c)) {
2899 register struct arglist *arg;
2901 for (arg = arglist; arg != NULL; arg = arg->next) {
2902 struct reflist *tpat;
2904 if (arg->name[0] == c
2905 && arg->length == id_len
2906 && strncmp ((const char *)arg->name,
2907 (const char *)id_beg, id_len) == 0) {
2908 /* make a pat node for this arg and append it to the end of
2910 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
2912 tpat->raw_before = concat == id_beg;
2913 tpat->raw_after = 0;
2914 tpat->stringify = expected_delimiter != '\0';
2917 defn->pattern = tpat;
2919 endpat->next = tpat;
2922 tpat->argno = arg->argno;
2923 tpat->nchars = exp_p - lastp;
2925 register U_CHAR *p1 = p;
2926 SKIP_WHITE_SPACE (p1);
2927 if (p1 + 2 <= limit && p1[0] == '#' && p1[1] == '#')
2928 tpat->raw_after = 1;
2930 lastp = exp_p; /* place to start copying from next time */
2937 /* If this was not a macro arg, copy it into the expansion. */
2938 if (! skipped_arg) {
2939 register U_CHAR *lim1 = p;
2943 if (stringify == id_beg)
2944 error ("# operator should be followed by a macro argument name");
2950 /* Convert trailing whitespace to Newline-markers. */
2951 while (limit < end && is_space (*limit)) {
2953 *exp_p++ = *limit++;
2958 defn->length = exp_p - defn->expansion;
2960 /* Crash now if we overrun the allocated size. */
2961 if (defn->length + 1 > maxsize)
2968 * interpret #line command. Remembers previously seen fnames
2969 * in its very own hash table.
2971 #define FNAME_HASHSIZE 37
2973 do_line (buf, limit, op)
2974 U_CHAR *buf, *limit;
2977 register U_CHAR *bp;
2978 FILE_BUF *ip = &instack[indepth];
2981 enum file_change_code file_change = same_file;
2983 /* Expand any macros. */
2984 tem = expand_to_temp_buffer (buf, limit, 0);
2986 /* Point to macroexpanded line, which is null-terminated now. */
2988 SKIP_WHITE_SPACE (bp);
2990 if (!ISDIGIT (*bp)) {
2991 error ("invalid format #line command");
2995 /* The Newline at the end of this line remains to be processed.
2996 To put the next line at the specified line number,
2997 we must store a line number now that is one less. */
2998 new_lineno = atoi ((const char *)bp);
3000 /* skip over the line number. */
3001 while (ISDIGIT (*bp))
3004 SKIP_WHITE_SPACE (bp);
3007 static HASHNODE *fname_table[FNAME_HASHSIZE];
3008 HASHNODE *hp, **hash_bucket;
3014 while (*bp && *bp != '\"')
3017 error ("invalid format #line command");
3021 fname_length = bp - fname;
3024 SKIP_WHITE_SPACE (bp);
3027 file_change = enter_file;
3028 else if (*bp == '2')
3029 file_change = leave_file;
3031 error ("invalid format #line command");
3036 SKIP_WHITE_SPACE (bp);
3038 error ("invalid format #line command");
3044 &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
3045 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
3046 if (hp->length == fname_length &&
3047 strncmp (hp->value.cpval, (const char *)fname, fname_length) == 0) {
3048 ip->fname = hp->value.cpval;
3053 /* Didn't find it; cons up a new one. */
3054 hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
3055 hp->next = *hash_bucket;
3058 hp->length = fname_length;
3059 ip->fname = hp->value.cpval = q = ((char *) hp) + sizeof (HASHNODE);
3060 memcpy (q, fname, fname_length);
3063 error ("invalid format #line command");
3067 ip->lineno = new_lineno;
3068 output_line_command (ip, op, 0, file_change);
3069 ip->bufp++; /* Skip the new line. */
3070 check_expand (op, ip->length - (ip->bufp - ip->buf));
3074 * remove all definitions of symbol from symbol table.
3075 * according to un*x /lib/cpp, it is not an error to undef
3076 * something that has no definitions, so it isn't one here either.
3079 do_undef (buf, limit, op)
3081 U_CHAR *limit ATTRIBUTE_UNUSED;
3082 FILE_BUF *op ATTRIBUTE_UNUSED;
3086 SKIP_WHITE_SPACE (buf);
3088 if (! strncmp ((const char *)buf, "defined", 7) && ! is_idchar (buf[7]))
3089 warning ("undefining `defined'");
3091 while ((hp = lookup (buf, -1, -1)) != NULL) {
3092 if (hp->type != T_MACRO)
3093 warning ("undefining `%s'", hp->name);
3098 /* Read the tokens of the answer into the macro pool. Only commit the
3099 memory if we intend it as permanent storage, i.e. the #assert case.
3100 Returns 0 on success. */
3103 parse_answer (buf, limit, answerp, type)
3104 const unsigned char *buf, *limit;
3105 struct answer **answerp;
3108 const unsigned char *start;
3110 /* Skip leading whitespace. */
3111 if (buf < limit && *buf == ' ')
3114 /* Parentheses are optional here. */
3115 if (buf == limit && type == T_UNASSERT)
3118 if (buf == limit || *buf++ != '(')
3123 error ("missing '(' after predicate");
3127 /* Drop whitespace at start. */
3128 while (buf < limit && *buf == ' ')
3132 while (buf < limit && *buf != ')')
3137 error ("missing ')' to complete answer");
3143 error ("predicate's answer is empty");
3147 if ((type == T_ASSERT || type == T_UNASSERT) && buf + 1 != limit)
3149 error ("extra text at end of directive");
3153 /* Lose trailing whitespace. */
3157 *answerp = (struct answer *) xmalloc (sizeof (struct answer));
3158 (*answerp)->answer = start;
3159 (*answerp)->len = buf - start;
3164 /* Parses an assertion, returning a pointer to the hash node of the
3165 predicate, or 0 on error. If an answer was supplied, it is placed
3166 in ANSWERP, otherwise it is set to 0. */
3168 parse_assertion (buf, limit, answerp, type)
3169 const unsigned char *buf, *limit;
3170 struct answer **answerp;
3173 HASHNODE *result = 0;
3174 const unsigned char *climit;
3175 unsigned char *bp, *symname = canonicalize_text (buf, limit, &climit);
3179 if (bp < climit && is_idstart (*bp))
3183 while (bp < climit && is_idchar (*bp));
3190 if (symname == climit)
3191 error ("assertion without predicate");
3193 error ("predicate must be an identifier");
3195 /* Unfortunately, because of the way we handle #if, we don't avoid
3196 macro expansion in answers. This is not easy to fix. */
3197 else if (parse_answer (bp, climit, answerp, type) == 0)
3199 unsigned char *sym = alloca (len + 1);
3202 /* Prefix '#' to get it out of macro namespace. */
3204 memcpy (sym + 1, symname, len);
3206 hashcode = hashf (sym, len + 1, HASHSIZE);
3207 result = lookup (sym, len + 1, hashcode);
3209 result = install (sym, len + 1, T_UNUSED, hashcode);
3215 /* Test an assertion within a preprocessor conditional. Returns zero
3216 on error or failure, one on success. */
3218 test_assertion (pbuf)
3219 unsigned char **pbuf; /* NUL-terminated. */
3221 unsigned char *buf = *pbuf;
3222 unsigned char *limit = buf + strlen ((char *) buf);
3223 struct answer *answer;
3227 node = parse_assertion (buf, limit, &answer, T_IF);
3230 result = (node->type == T_ASSERT &&
3231 (answer == 0 || *find_answer (node, answer) != 0));
3233 /* Yuk. We update pbuf to point after the assertion test.
3234 First, move past the identifier. */
3235 if (is_space (*buf))
3237 while (is_idchar (*buf))
3239 /* If we have an answer, we need to move past the parentheses. */
3241 while (*buf++ != ')')
3249 /* Handle a #error directive. */
3251 do_error (buf, limit, op)
3254 FILE_BUF *op ATTRIBUTE_UNUSED;
3256 error ("#error%.*s", (int) (limit - buf), buf);
3259 /* Handle a #warning directive. */
3261 do_warning (buf, limit, op)
3264 FILE_BUF *op ATTRIBUTE_UNUSED;
3266 warning ("#warning%.*s", (int) (limit - buf), buf);
3269 /* Handle a #assert directive. */
3271 do_assert (buf, limit, op)
3274 FILE_BUF *op ATTRIBUTE_UNUSED;
3276 struct answer *new_answer;
3279 node = parse_assertion (buf, limit, &new_answer, T_ASSERT);
3282 /* Place the new answer in the answer list. First check there
3283 is not a duplicate. */
3284 new_answer->next = 0;
3285 if (node->type == T_ASSERT)
3287 if (*find_answer (node, new_answer))
3290 warning ("\"%s\" re-asserted", node->name + 1);
3293 new_answer->next = node->value.answers;
3295 node->type = T_ASSERT;
3296 node->value.answers = new_answer;
3300 /* Function body to be provided later. */
3302 do_unassert (buf, limit, op)
3305 FILE_BUF *op ATTRIBUTE_UNUSED;
3308 struct answer *answer;
3310 node = parse_assertion (buf, limit, &answer, T_UNASSERT);
3311 /* It isn't an error to #unassert something that isn't asserted. */
3314 if (node->type == T_ASSERT)
3318 struct answer **p = find_answer (node, answer), *temp;
3320 /* Remove the answer from the list. */
3325 /* Did we free the last answer? */
3326 if (node->value.answers == 0)
3327 delete_macro (node);
3330 delete_macro (node);
3337 /* Returns a pointer to the pointer to the answer in the answer chain,
3338 or a pointer to NULL if the answer is not in the chain. */
3339 static struct answer **
3340 find_answer (node, candidate)
3342 const struct answer *candidate;
3344 struct answer **result;
3346 for (result = &node->value.answers; *result; result = &(*result)->next)
3348 struct answer *answer = *result;
3350 if (answer->len == candidate->len
3351 && !memcmp (answer->answer, candidate->answer, answer->len))
3358 /* Return a malloced buffer with leading and trailing whitespace
3359 removed, and all instances of internal whitespace reduced to a
3361 static unsigned char *
3362 canonicalize_text (buf, limit, climit)
3363 const unsigned char *buf, *limit, **climit;
3365 unsigned int len = limit - buf;
3366 unsigned char *result = (unsigned char *) xmalloc (len), *dest;
3368 for (dest = result; buf < limit;)
3370 if (! is_space (*buf))
3374 while (++buf < limit && is_space (*buf))
3376 if (dest != result && buf != limit)
3386 * handle #if command by
3387 * 1) inserting special `defined' keyword into the hash table
3388 * that gets turned into 0 or 1 by special_symbol (thus,
3389 * if the luser has a symbol called `defined' already, it won't
3390 * work inside the #if command)
3391 * 2) rescan the input into a temporary output buffer
3392 * 3) pass the output buffer to the yacc parser and collect a value
3393 * 4) clean up the mess left from steps 1 and 2.
3394 * 5) call conditional_skip to skip til the next #endif (etc.),
3395 * or not, depending on the value from step 3.
3398 do_if (buf, limit, op)
3399 U_CHAR *buf, *limit;
3400 FILE_BUF *op ATTRIBUTE_UNUSED;
3403 FILE_BUF *ip = &instack[indepth];
3405 value = eval_if_expression (buf, limit - buf);
3406 conditional_skip (ip, value == 0, T_IF);
3410 * handle a #elif directive by not changing if_stack either.
3411 * see the comment above do_else.
3414 do_elif (buf, limit, op)
3415 U_CHAR *buf, *limit;
3419 FILE_BUF *ip = &instack[indepth];
3421 if (if_stack == instack[indepth].if_stack) {
3422 error ("#elif not within a conditional");
3425 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
3426 error ("#elif after #else");
3427 fprintf (stderr, " (matches line %d", if_stack->lineno);
3428 if (if_stack->fname != NULL && ip->fname != NULL &&
3429 strcmp (if_stack->fname, ip->fname) != 0)
3430 fprintf (stderr, ", file %s", if_stack->fname);
3431 fprintf (stderr, ")\n");
3433 if_stack->type = T_ELIF;
3436 if (if_stack->if_succeeded)
3437 skip_if_group (ip, 0);
3439 value = eval_if_expression (buf, limit - buf);
3441 skip_if_group (ip, 0);
3443 ++if_stack->if_succeeded; /* continue processing input */
3444 output_line_command (ip, op, 1, same_file);
3450 * evaluate a #if expression in BUF, of length LENGTH,
3451 * then parse the result as a C expression and return the value as an int.
3454 eval_if_expression (buf, length)
3459 HASHNODE *save_defined;
3462 save_defined = install (U"defined", -1, T_SPEC_DEFINED, -1);
3463 temp_obuf = expand_to_temp_buffer (buf, buf + length, 0);
3464 delete_macro (save_defined); /* clean up special symbol */
3466 value = parse_c_expression ((const char *)temp_obuf.buf);
3468 free (temp_obuf.buf);
3474 * routine to handle ifdef/ifndef. Try to look up the symbol,
3475 * then do or don't skip to the #endif/#else/#elif depending
3476 * on what directive is actually being processed.
3479 do_xifdef (buf, limit, type)
3480 U_CHAR *buf, *limit;
3481 enum node_type type;
3484 FILE_BUF *ip = &instack[indepth];
3487 /* Discard leading and trailing whitespace. */
3488 SKIP_WHITE_SPACE (buf);
3489 while (limit != buf && is_nvspace (limit[-1])) limit--;
3491 /* Find the end of the identifier at the beginning. */
3492 for (end = buf; is_idchar (*end); end++);
3495 skip = (type == T_IFDEF);
3497 skip = (lookup (buf, end-buf, -1) == NULL) ^ (type == T_IFNDEF);
3499 conditional_skip (ip, skip, T_IF);
3503 do_ifdef (buf, limit, op)
3504 U_CHAR *buf, *limit;
3505 FILE_BUF *op ATTRIBUTE_UNUSED;
3507 do_xifdef (buf, limit, T_IFDEF);
3511 do_ifndef (buf, limit, op)
3512 U_CHAR *buf, *limit;
3513 FILE_BUF *op ATTRIBUTE_UNUSED;
3515 do_xifdef (buf, limit, T_IFNDEF);
3519 * push TYPE on stack; then, if SKIP is nonzero, skip ahead.
3522 conditional_skip (ip, skip, type)
3525 enum node_type type;
3527 IF_STACK_FRAME *temp;
3529 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
3530 temp->fname = ip->fname;
3531 temp->lineno = ip->lineno;
3532 temp->next = if_stack;
3535 if_stack->type = type;
3538 skip_if_group (ip, 0);
3541 ++if_stack->if_succeeded;
3542 output_line_command (ip, &outbuf, 1, same_file);
3547 * skip to #endif, #else, or #elif. adjust line numbers, etc.
3548 * leaves input ptr at the sharp sign found.
3549 * If ANY is nonzero, return at next directive of any sort.
3552 skip_if_group (ip, any)
3556 register U_CHAR *bp = ip->bufp, *cp;
3557 register U_CHAR *endb = ip->buf + ip->length;
3558 struct directive *kt;
3559 IF_STACK_FRAME *save_if_stack = if_stack; /* don't pop past here */
3560 U_CHAR *beg_of_line = bp;
3564 case '/': /* possible comment */
3565 if (*bp == '\\' && bp[1] == '\n')
3569 bp = skip_to_end_of_comment (ip, &ip->lineno);
3574 bp = skip_quoted_string (bp - 1, endb, ip->lineno, &ip->lineno, 0, 0);
3577 /* Char after backslash loses its special meaning. */
3580 ++ip->lineno; /* But do update the line-count. */
3591 /* # keyword: a # must be first nonblank char on the line */
3592 if (beg_of_line == 0)
3594 /* Scan from start of line, skipping whitespace, comments
3595 and backslash-newlines, and see if we reach this #.
3596 If not, this # is not special. */
3599 if (is_nvspace (*bp))
3601 else if (*bp == '\\' && bp[1] == '\n')
3603 else if (*bp == '/' && bp[1] == '*') {
3605 while (!(*bp == '*' && bp[1] == '/')) {
3614 if (bp != ip->bufp) {
3615 bp = ip->bufp + 1; /* Reset bp to after the #. */
3619 bp = ip->bufp + 1; /* Point after '#'. */
3621 /* Skip whitespace and \-newline. */
3623 if (is_nvspace (*bp))
3625 else if (*bp == '\\' && bp[1] == '\n')
3627 else if (*bp == '/' && bp[1] == '*') {
3629 while (!(*bp == '*' && bp[1] == '/'))
3638 /* Now find end of directive name.
3639 If we encounter a backslash-newline, exchange it with any following
3640 symbol-constituents so that we end up with a contiguous name. */
3643 if (is_idchar (*bp))
3646 if (*bp == '\\' && bp[1] == '\n')
3647 name_newline_fix (bp);
3648 if (is_idchar (*bp))
3654 for (kt = directive_table; kt->length >= 0; kt++) {
3655 IF_STACK_FRAME *temp;
3656 if (strncmp ((const char *)cp, kt->name, kt->length) == 0
3657 && !is_idchar (cp[kt->length])) {
3659 /* If we are asked to return on next directive,
3668 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
3669 temp->next = if_stack;
3671 temp->lineno = ip->lineno;
3672 temp->fname = ip->fname;
3673 temp->type = kt->type;
3678 if (if_stack == instack[indepth].if_stack) {
3679 error ("#%s not within a conditional", kt->name);
3682 else if (if_stack == save_if_stack)
3683 return; /* found what we came for */
3685 if (kt->type != T_ENDIF) {
3686 if (if_stack->type == T_ELSE)
3687 error ("#else or #elif after #else");
3688 if_stack->type = kt->type;
3693 if_stack = if_stack->next;
3698 /* Anything else is ignored. */
3707 /* after this returns, rescan will exit because ip->bufp
3708 now points to the end of the buffer.
3709 rescan is responsible for the error message also. */
3713 * handle a #else directive. Do this by just continuing processing
3714 * without changing if_stack ; this is so that the error message
3715 * for missing #endif's etc. will point to the original #if. It
3716 * is possible that something different would be better.
3719 do_else (buf, limit, op)
3720 U_CHAR *buf ATTRIBUTE_UNUSED;
3721 U_CHAR *limit ATTRIBUTE_UNUSED;
3724 FILE_BUF *ip = &instack[indepth];
3726 if (if_stack == instack[indepth].if_stack) {
3727 error ("#else not within a conditional");
3730 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
3731 error ("#else after #else");
3732 fprintf (stderr, " (matches line %d", if_stack->lineno);
3733 if (strcmp (if_stack->fname, ip->fname) != 0)
3734 fprintf (stderr, ", file %s", if_stack->fname);
3735 fprintf (stderr, ")\n");
3737 if_stack->type = T_ELSE;
3740 if (if_stack->if_succeeded)
3741 skip_if_group (ip, 0);
3743 ++if_stack->if_succeeded; /* continue processing input */
3744 output_line_command (ip, op, 1, same_file);
3749 * unstack after #endif command
3752 do_endif (buf, limit, op)
3753 U_CHAR *buf ATTRIBUTE_UNUSED;
3754 U_CHAR *limit ATTRIBUTE_UNUSED;
3757 if (if_stack == instack[indepth].if_stack)
3758 error ("unbalanced #endif");
3760 IF_STACK_FRAME *temp = if_stack;
3761 if_stack = if_stack->next;
3763 output_line_command (&instack[indepth], op, 1, same_file);
3768 * Skip a comment, assuming the input ptr immediately follows the
3769 * initial slash-star. Bump line counter as necessary.
3770 * (The canonical line counter is &ip->lineno).
3771 * Don't use this routine (or the next one) if bumping the line
3772 * counter is not sufficient to deal with newlines in the string.
3775 skip_to_end_of_comment (ip, line_counter)
3776 register FILE_BUF *ip;
3777 int *line_counter; /* place to remember newlines, or NULL */
3779 register U_CHAR *limit = ip->buf + ip->length;
3780 register U_CHAR *bp = ip->bufp;
3781 FILE_BUF *op = &outbuf; /* JF */
3782 int output = put_out_comments && !line_counter;
3784 /* JF this line_counter stuff is a crock to make sure the
3785 comment is only put out once, no matter how many times
3786 the comment is skipped. It almost works */
3791 while (bp < limit) {
3796 if (warn_comments && bp < limit && *bp == '*')
3797 warning("`/*' within comment");
3800 if (line_counter != NULL)
3806 if (*bp == '\\' && bp[1] == '\n')
3822 * Skip over a quoted string. BP points to the opening quote.
3823 * Returns a pointer after the closing quote. Don't go past LIMIT.
3824 * START_LINE is the line number of the starting point (but it need
3825 * not be valid if the starting point is inside a macro expansion).
3827 * The input stack state is not changed.
3829 * If COUNT_NEWLINES is nonzero, it points to an int to increment
3830 * for each newline passed.
3832 * If BACKSLASH_NEWLINES_P is nonzero, store 1 thru it
3833 * if we pass a backslash-newline.
3835 * If EOFP is nonzero, set *EOFP to 1 if the string is unterminated.
3838 skip_quoted_string (bp, limit, start_line, count_newlines, backslash_newlines_p, eofp)
3839 register const U_CHAR *bp;
3840 register const U_CHAR *limit;
3842 int *count_newlines;
3843 int *backslash_newlines_p;
3846 register U_CHAR c, match;
3851 error_with_line (line_for_error (start_line),
3852 "unterminated string or character constant");
3859 while (*bp == '\\' && bp[1] == '\n') {
3860 if (backslash_newlines_p)
3861 *backslash_newlines_p = 1;
3866 if (*bp == '\n' && count_newlines) {
3867 if (backslash_newlines_p)
3868 *backslash_newlines_p = 1;
3872 } else if (c == '\n') {
3873 /* Unterminated strings and character constants are 'legal'. */
3874 bp--; /* Don't consume the newline. */
3878 } else if (c == match)
3881 return (U_CHAR *) bp;
3885 * write out a #line command, for instance, after an #include file.
3886 * If CONDITIONAL is nonzero, we can omit the #line if it would
3887 * appear to be a no-op, and we can output a few newlines instead
3888 * if we want to increase the line number by a small amount.
3889 * FILE_CHANGE says whether we are entering a file, leaving, or neither.
3893 output_line_command (ip, op, conditional, file_change)
3896 enum file_change_code file_change;
3899 char line_cmd_buf[500];
3901 if (no_line_commands
3902 || ip->fname == NULL
3904 op->lineno = ip->lineno;
3909 if (ip->lineno == op->lineno)
3912 /* If the inherited line number is a little too small,
3913 output some newlines instead of a #line command. */
3914 if (ip->lineno > op->lineno && ip->lineno < op->lineno + 8) {
3915 check_expand (op, 10);
3916 while (ip->lineno > op->lineno) {
3924 sprintf (line_cmd_buf, "# %d \"%s\"", ip->lineno, ip->fname);
3925 if (file_change != same_file)
3926 strcat (line_cmd_buf, file_change == enter_file ? " 1" : " 2");
3927 if (system_include_depth > 0)
3928 strcat (line_cmd_buf, " 3");
3929 len = strlen (line_cmd_buf);
3930 line_cmd_buf[len++] = '\n';
3931 check_expand (op, len + 1);
3932 if (op->bufp > op->buf && op->bufp[-1] != '\n')
3934 memcpy (op->bufp, line_cmd_buf, len);
3936 op->lineno = ip->lineno;
3940 /* Expand a macro call.
3941 HP points to the symbol that is the macro being called.
3942 Put the result of expansion onto the input stack
3943 so that subsequent input by our caller will use it.
3945 If macro wants arguments, caller has already verified that
3946 an argument list follows; arguments come from the input stack. */
3949 macroexpand (hp, op)
3954 DEFINITION *defn = hp->value.defn;
3955 register U_CHAR *xbuf;
3957 int start_line = instack[indepth].lineno;
3959 CHECK_DEPTH (return;);
3961 /* it might not actually be a macro. */
3962 if (hp->type != T_MACRO) {
3963 special_symbol (hp, op);
3967 nargs = defn->nargs;
3971 struct argdata *args;
3972 const char *parse_error = 0;
3974 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
3976 for (i = 0; i < nargs; i++) {
3977 args[i].raw = args[i].expanded = (U_CHAR *) "";
3978 args[i].raw_length = args[i].expand_length
3979 = args[i].stringified_length = 0;
3980 args[i].free1 = args[i].free2 = 0;
3983 /* Parse all the macro args that are supplied. I counts them.
3984 The first NARGS args are stored in ARGS.
3985 The rest are discarded. */
3988 /* Discard the open-parenthesis or comma before the next arg. */
3989 ++instack[indepth].bufp;
3991 = macarg ((i < nargs || (nargs == 0 && i == 0)) ? &args[i] : 0);
3994 error_with_line (line_for_error (start_line), parse_error);
3998 } while (*instack[indepth].bufp != ')');
4000 /* If we got one arg but it was just whitespace, call that 0 args. */
4002 register const U_CHAR *bp = args[0].raw;
4003 register const U_CHAR *lim = bp + args[0].raw_length;
4004 while (bp != lim && is_space (*bp)) bp++;
4009 if (nargs == 0 && i > 0)
4010 error ("arguments given to macro `%s'", hp->name);
4011 else if (i < nargs) {
4012 /* traditional C allows foo() if foo wants one argument. */
4013 if (nargs == 1 && i == 0)
4016 error ("no args to macro `%s'", hp->name);
4018 error ("only 1 arg to macro `%s'", hp->name);
4020 error ("only %d args to macro `%s'", i, hp->name);
4021 } else if (i > nargs)
4022 error ("too many (%d) args to macro `%s'", i, hp->name);
4024 /* Swallow the closeparen. */
4025 ++instack[indepth].bufp;
4027 /* If macro wants zero args, we parsed the arglist for checking only.
4028 Read directly from the macro definition. */
4030 xbuf = defn->expansion;
4031 xbuf_len = defn->length;
4033 register U_CHAR *exp = defn->expansion;
4034 register int offset; /* offset in expansion,
4035 copied a piece at a time */
4036 register int totlen; /* total amount of exp buffer filled so far */
4038 register struct reflist *ap;
4040 /* Macro really takes args. Compute the expansion of this call. */
4042 /* Compute length in characters of the macro's expansion. */
4043 xbuf_len = defn->length;
4044 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
4046 xbuf_len += args[ap->argno].stringified_length;
4048 xbuf_len += args[ap->argno].raw_length;
4051 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
4053 /* Generate in XBUF the complete expansion
4054 with arguments substituted in.
4055 TOTLEN is the total size generated so far.
4056 OFFSET is the index in the definition
4057 of where we are copying from. */
4058 offset = totlen = 0;
4059 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
4060 register struct argdata *arg = &args[ap->argno];
4062 for (i = 0; i < ap->nchars; i++)
4063 xbuf[totlen++] = exp[offset++];
4065 if (ap->stringify != 0) {
4066 int arglen = arg->raw_length;
4072 && (c = arg->raw[i], is_space (c)))
4075 && (c = arg->raw[arglen - 1], is_space (c)))
4077 for (; i < arglen; i++) {
4080 /* Special markers Newline Space
4081 generate nothing for a stringified argument. */
4082 if (c == '\n' && arg->raw[i+1] != '\n') {
4087 /* Internal sequences of whitespace are replaced by one space
4088 except within an string or char token. */
4090 && (c == '\n' ? arg->raw[i+1] == '\n' : is_space (c))) {
4092 /* Note that Newline Space does occur within whitespace
4093 sequences; consider it part of the sequence. */
4094 if (c == '\n' && is_space (arg->raw[i+1]))
4096 else if (c != '\n' && is_space (c))
4113 } else if (c == '\"' || c == '\'')
4117 /* Escape these chars */
4118 if (c == '\"' || (in_string && c == '\\'))
4119 xbuf[totlen++] = '\\';
4123 sprintf ((char *) &xbuf[totlen], "\\%03o", (unsigned int) c);
4128 const U_CHAR *p1 = arg->raw;
4129 const U_CHAR *l1 = p1 + arg->raw_length;
4131 if (ap->raw_before) {
4132 while (p1 != l1 && is_space (*p1)) p1++;
4133 while (p1 != l1 && is_idchar (*p1))
4134 xbuf[totlen++] = *p1++;
4135 /* Delete any no-reexpansion marker that follows
4136 an identifier at the beginning of the argument
4137 if the argument is concatenated with what precedes it. */
4138 if (p1[0] == '\n' && p1[1] == '-')
4141 if (ap->raw_after) {
4142 /* Arg is concatenated after: delete trailing whitespace,
4143 whitespace markers, and no-reexpansion markers. */
4145 if (is_space (l1[-1])) l1--;
4146 else if (l1[-1] == '-') {
4147 const U_CHAR *p2 = l1 - 1;
4148 /* If a `-' is preceded by an odd number of newlines then it
4149 and the last newline are a no-reexpansion marker. */
4150 while (p2 != p1 && p2[-1] == '\n') p2--;
4151 if ((l1 - 1 - p2) & 1) {
4159 memmove (xbuf + totlen, p1, l1 - p1);
4163 if (totlen > xbuf_len)
4167 /* if there is anything left of the definition
4168 after handling the arg list, copy that in too. */
4170 for (i = offset; i < defn->length; i++)
4171 xbuf[totlen++] = exp[i];
4176 for (i = 0; i < nargs; i++) {
4177 if (args[i].free1 != 0)
4178 free (args[i].free1);
4179 if (args[i].free2 != 0)
4180 free (args[i].free2);
4184 xbuf = defn->expansion;
4185 xbuf_len = defn->length;
4188 /* Now put the expansion on the input stack
4189 so our caller will commence reading from it. */
4191 register FILE_BUF *ip2;
4193 ip2 = &instack[++indepth];
4198 ip2->length = xbuf_len;
4200 ip2->free_ptr = (nargs > 0) ? xbuf : 0;
4202 ip2->if_stack = if_stack;
4207 * Parse a macro argument and store the info on it into *ARGPTR.
4208 * Return nonzero to indicate a syntax error.
4213 register struct argdata *argptr;
4215 FILE_BUF *ip = &instack[indepth];
4220 /* Try to parse as much of the argument as exists at this
4221 input stack level. */
4222 U_CHAR *bp = macarg1 (ip->bufp, ip->buf + ip->length,
4223 &paren, &newlines, &comments);
4225 /* If we find the end of the argument at this level,
4226 set up *ARGPTR to point at it in the input stack. */
4227 if (!(ip->fname != 0 && (newlines != 0 || comments != 0))
4228 && bp != ip->buf + ip->length) {
4230 argptr->raw = ip->bufp;
4231 argptr->raw_length = bp - ip->bufp;
4235 /* This input stack level ends before the macro argument does.
4236 We must pop levels and keep parsing.
4237 Therefore, we must allocate a temporary buffer and copy
4238 the macro argument into it. */
4239 int bufsize = bp - ip->bufp;
4240 int extra = newlines;
4241 U_CHAR *buffer = (U_CHAR *) xmalloc (bufsize + extra + 1);
4242 int final_start = 0;
4244 memcpy (buffer, ip->bufp, bufsize);
4246 ip->lineno += newlines;
4248 while (bp == ip->buf + ip->length) {
4249 if (instack[indepth].macro == 0) {
4251 return "unterminated macro call";
4253 ip->macro->type = T_MACRO;
4255 free (ip->free_ptr);
4256 ip = &instack[--indepth];
4259 bp = macarg1 (ip->bufp, ip->buf + ip->length, &paren,
4260 &newlines, &comments);
4261 final_start = bufsize;
4262 bufsize += bp - ip->bufp;
4264 buffer = (U_CHAR *) xrealloc (buffer, bufsize + extra + 1);
4265 memcpy (buffer + bufsize - (bp - ip->bufp), ip->bufp, bp - ip->bufp);
4267 ip->lineno += newlines;
4270 /* Now, if arg is actually wanted, record its raw form,
4271 discarding comments and duplicating newlines in whatever
4272 part of it did not come from a macro expansion.
4273 EXTRA space has been preallocated for duplicating the newlines.
4274 FINAL_START is the index of the start of that part. */
4276 argptr->raw = buffer;
4277 argptr->raw_length = bufsize;
4278 argptr->free1 = buffer;
4279 argptr->newlines = newlines;
4280 argptr->comments = comments;
4281 if ((newlines || comments) && ip->fname != 0)
4284 discard_comments (argptr->raw + final_start,
4285 argptr->raw_length - final_start,
4287 argptr->raw[argptr->raw_length] = 0;
4288 if (argptr->raw_length > bufsize + extra)
4293 /* If we are not discarding this argument,
4294 macroexpand it and compute its length as stringified.
4295 All this info goes into *ARGPTR. */
4299 register const U_CHAR *buf, *lim;
4300 register int totlen;
4302 obuf = expand_to_temp_buffer (argptr->raw,
4303 argptr->raw + argptr->raw_length,
4306 argptr->expanded = obuf.buf;
4307 argptr->expand_length = obuf.length;
4308 argptr->free2 = obuf.buf;
4311 lim = buf + argptr->raw_length;
4314 while (buf != lim) {
4315 register U_CHAR c = *buf++;
4317 /* Internal sequences of whitespace are replaced by one space
4318 in most cases, but not always. So count all the whitespace
4319 in case we need to keep it all. */
4320 if (c == '\"' || c == '\\') /* escape these chars */
4322 else if (!ISPRINT (c))
4325 argptr->stringified_length = totlen;
4330 /* Scan text from START (inclusive) up to LIMIT (exclusive),
4331 counting parens in *DEPTHPTR,
4332 and return if reach LIMIT
4333 or before a `)' that would make *DEPTHPTR negative
4334 or before a comma when *DEPTHPTR is zero.
4335 Single and double quotes are matched and termination
4336 is inhibited within them. Comments also inhibit it.
4337 Value returned is pointer to stopping place.
4339 Increment *NEWLINES each time a newline is passed.
4340 Set *COMMENTS to 1 if a comment is seen. */
4343 macarg1 (start, limit, depthptr, newlines, comments)
4345 register const U_CHAR *limit;
4346 int *depthptr, *newlines, *comments;
4348 register U_CHAR *bp = start;
4350 while (bp < limit) {
4356 if (--(*depthptr) < 0)
4360 /* Traditionally, backslash makes following char not special. */
4364 /* But count source lines anyway. */
4373 if (bp[1] == '\\' && bp[2] == '\n')
4374 newline_fix (bp + 1);
4375 if (bp[1] != '*' || bp + 1 >= limit)
4379 while (bp + 1 < limit) {
4381 && bp[1] == '\\' && bp[2] == '\n')
4382 newline_fix (bp + 1);
4383 if (bp[0] == '*' && bp[1] == '/')
4385 if (*bp == '\n') ++*newlines;
4394 for (quotec = *bp++; bp + 1 < limit && *bp != quotec; bp++) {
4399 while (*bp == '\\' && bp[1] == '\n') {
4402 } else if (*bp == '\n') {
4411 if ((*depthptr) == 0)
4421 /* Discard comments and duplicate newlines
4422 in the string of length LENGTH at START,
4423 except inside of string constants.
4424 The string is copied into itself with its beginning staying fixed.
4426 NEWLINES is the number of newlines that must be duplicated.
4427 We assume that that much extra space is available past the end
4431 discard_comments (start, length, newlines)
4436 register U_CHAR *ibp;
4437 register U_CHAR *obp;
4438 register const U_CHAR *limit;
4441 /* If we have newlines to duplicate, copy everything
4442 that many characters up. Then, in the second part,
4443 we will have room to insert the newlines
4445 NEWLINES may actually be too large, because it counts
4446 newlines in string constants, and we don't duplicate those.
4447 But that does no harm. */
4449 ibp = start + length;
4450 obp = ibp + newlines;
4452 while (limit != ibp)
4456 ibp = start + newlines;
4457 limit = start + length + newlines;
4460 while (ibp < limit) {
4461 *obp++ = c = *ibp++;
4464 /* Duplicate the newline. */
4476 if (*ibp == '\\' && ibp[1] == '\n')
4478 /* Delete any comment. */
4479 if (ibp[0] != '*' || ibp + 1 >= limit)
4483 while (ibp + 1 < limit) {
4485 && ibp[1] == '\\' && ibp[2] == '\n')
4486 newline_fix (ibp + 1);
4487 if (ibp[0] == '*' && ibp[1] == '/')
4496 /* Notice and skip strings, so that we don't
4497 think that comments start inside them,
4498 and so we don't duplicate newlines in them. */
4501 while (ibp < limit) {
4502 *obp++ = c = *ibp++;
4505 if (c == '\n' && quotec == '\'')
4507 if (c == '\\' && ibp < limit) {
4508 while (*ibp == '\\' && ibp[1] == '\n')
4522 /* Core error handling routine. */
4524 v_message (mtype, line, msgid, ap)
4530 const char *fname = 0;
4533 if (mtype == WARNING && inhibit_warnings)
4536 for (i = indepth; i >= 0; i--)
4537 if (instack[i].fname != NULL) {
4539 line = instack[i].lineno;
4540 fname = instack[i].fname;
4545 fprintf (stderr, "%s:%d: ", fname, line);
4547 fprintf (stderr, "%s: ", progname);
4549 if (mtype == WARNING)
4550 fputs ("warning: ", stderr);
4552 vfprintf (stderr, msgid, ap);
4553 putc ('\n', stderr);
4560 * error - print error message and increment count of errors.
4563 error VPARAMS ((const char *msgid, ...))
4565 #ifndef ANSI_PROTOTYPES
4570 VA_START(ap, msgid);
4572 #ifndef ANSI_PROTOTYPES
4573 msgid = va_arg (ap, const char *);
4576 v_message (ERROR, 0, msgid, ap);
4580 error_with_line VPARAMS ((int line, const char *msgid, ...))
4582 #ifndef ANSI_PROTOTYPES
4588 VA_START(ap, msgid);
4590 #ifndef ANSI_PROTOTYPES
4591 line = va_arg (ap, int);
4592 msgid = va_arg (ap, const char *);
4595 v_message (ERROR, line, msgid, ap);
4598 /* Error including a message from `errno'. */
4600 error_from_errno (name)
4603 error ("%s: %s", name, strerror (errno));
4606 /* Print error message but don't count it. */
4608 warning VPARAMS ((const char *msgid, ...))
4610 #ifndef ANSI_PROTOTYPES
4615 VA_START(ap, msgid);
4617 #ifndef ANSI_PROTOTYPES
4618 msgid = va_arg (ap, const char *);
4621 v_message (WARNING, 0, msgid, ap);
4625 fatal VPARAMS ((const char *msgid, ...))
4627 #ifndef ANSI_PROTOTYPES
4632 VA_START(ap, msgid);
4634 #ifndef ANSI_PROTOTYPES
4635 msgid = va_arg (ap, const char *);
4638 v_message (FATAL, 0, msgid, ap);
4639 exit (FATAL_EXIT_CODE);
4642 /* More 'friendly' abort that prints the location at which we died. */
4644 fancy_abort (line, func)
4648 fatal ("Internal error in %s, at tradcpp.c:%d\n\
4649 Please submit a full bug report.\n\
4650 See %s for instructions.", func, line, GCCBUGURL);
4654 perror_with_name (name)
4657 fprintf (stderr, "%s: %s: %s\n", progname, name, strerror (errno));
4662 pfatal_with_name (name)
4665 perror_with_name (name);
4666 exit (FATAL_EXIT_CODE);
4669 /* Return the line at which an error occurred.
4670 The error is not necessarily associated with the current spot
4671 in the input stack, so LINE says where. LINE will have been
4672 copied from ip->lineno for the current input level.
4673 If the current level is for a file, we return LINE.
4674 But if the current level is not for a file, LINE is meaningless.
4675 In that case, we return the lineno of the innermost file. */
4677 line_for_error (line)
4683 for (i = indepth; i >= 0; ) {
4684 if (instack[i].fname != 0)
4689 line1 = instack[i].lineno;
4695 * If OBUF doesn't have NEEDED bytes after OPTR, make it bigger.
4697 * As things stand, nothing is ever placed in the output buffer to be
4698 * removed again except when it's KNOWN to be part of an identifier,
4699 * so flushing and moving down everything left, instead of expanding,
4704 grow_outbuf (obuf, needed)
4705 register FILE_BUF *obuf;
4706 register int needed;
4711 if (obuf->length - (obuf->bufp - obuf->buf) > needed)
4714 /* Make it at least twice as big as it is now. */
4716 /* Make it have at least 150% of the free space we will need. */
4717 minsize = (3 * needed) / 2 + (obuf->bufp - obuf->buf);
4718 if (minsize > obuf->length)
4719 obuf->length = minsize;
4721 p = (U_CHAR *) xrealloc (obuf->buf, obuf->length);
4722 obuf->bufp = p + (obuf->bufp - obuf->buf);
4726 /* Symbol table for macro names and special symbols */
4729 * install a name in the main hash table, even if it is already there.
4730 * name stops with first non alphanumeric, except leading '#'.
4731 * caller must check against redefinition if that is desired.
4732 * delete_macro () removes things installed by install () in fifo order.
4733 * this is important because of the `defined' special symbol used
4734 * in #if, and also if pushdef/popdef directives are ever implemented.
4736 * If LEN is >= 0, it is the length of the name.
4737 * Otherwise, compute the length by scanning the entire name.
4739 * If HASH is >= 0, it is the precomputed hash code.
4740 * Otherwise, compute the hash code.
4742 * caller must set the value, if any is desired.
4745 install (name, len, type, hash)
4748 enum node_type type;
4750 /* watch out here if sizeof (U_CHAR *) != sizeof (int) */
4752 register HASHNODE *hp;
4753 register int bucket;
4754 register const U_CHAR *p;
4759 while (is_idchar (*p))
4765 hash = hashf (name, len, HASHSIZE);
4767 hp = (HASHNODE *) xmalloc (sizeof (HASHNODE) + len + 1);
4769 hp->bucket_hdr = &hashtab[bucket];
4770 hp->next = hashtab[bucket];
4771 hashtab[bucket] = hp;
4773 if (hp->next != NULL)
4774 hp->next->prev = hp;
4777 hp->name = q = ((U_CHAR *) hp) + sizeof (HASHNODE);
4778 memcpy (q, name, len);
4784 * find the most recent hash node for name name (ending with first
4785 * non-identifier char) installed by install
4787 * If LEN is >= 0, it is the length of the name.
4788 * Otherwise, compute the length by scanning the entire name.
4790 * If HASH is >= 0, it is the precomputed hash code.
4791 * Otherwise, compute the hash code.
4794 lookup (name, len, hash)
4799 register const U_CHAR *bp;
4800 register HASHNODE *bucket;
4803 for (bp = name; is_idchar (*bp); bp++) ;
4808 hash = hashf (name, len, HASHSIZE);
4810 bucket = hashtab[hash];
4812 if (bucket->length == len
4813 && strncmp ((const char *)bucket->name, (const char *)name, len) == 0)
4815 bucket = bucket->next;
4821 * Delete a hash node. Some weirdness to free junk from macros.
4822 * More such weirdness will have to be added if you define more hash
4823 * types that need it.
4826 /* Note that the DEFINITION of a macro is removed from the hash table
4827 but its storage is not freed. This would be a storage leak
4828 except that it is not reasonable to keep undefining and redefining
4829 large numbers of macros many times.
4830 In any case, this is necessary, because a macro can be #undef'd
4831 in the middle of reading the arguments to a call to it.
4832 If #undef freed the DEFINITION, that would crash. */
4838 if (hp->prev != NULL)
4839 hp->prev->next = hp->next;
4840 if (hp->next != NULL)
4841 hp->next->prev = hp->prev;
4843 /* make sure that the bucket chain header that
4844 the deleted guy was on points to the right thing afterwards. */
4845 if (hp == *hp->bucket_hdr)
4846 *hp->bucket_hdr = hp->next;
4852 * return hash function on name. must be compatible with the one
4853 * computed a step at a time, elsewhere
4856 hashf (name, len, hashsize)
4857 register const U_CHAR *name;
4864 r = HASHSTEP (r, *name++);
4866 return MAKE_POS (r) % hashsize;
4869 /* Dump all macro definitions as #defines to stdout. */
4876 for (bucket = 0; bucket < HASHSIZE; bucket++) {
4877 register HASHNODE *hp;
4879 for (hp = hashtab[bucket]; hp; hp= hp->next) {
4880 if (hp->type == T_MACRO) {
4881 register DEFINITION *defn = hp->value.defn;
4887 /* Print the definition of the macro HP. */
4889 printf ("#define %s", hp->name);
4890 if (defn->nargs >= 0) {
4894 for (i = 0; i < defn->nargs; i++) {
4895 dump_arg_n (defn, i);
4896 if (i + 1 < defn->nargs)
4906 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
4907 dump_defn_1 (defn->expansion, offset, ap->nchars);
4908 if (ap->nchars != 0)
4910 offset += ap->nchars;
4913 if (ap->raw_before && !concat)
4916 dump_arg_n (defn, ap->argno);
4917 if (ap->raw_after) {
4922 dump_defn_1 (defn->expansion, offset, defn->length - offset);
4929 /* Output to stdout a substring of a macro definition.
4930 BASE is the beginning of the definition.
4931 Output characters START thru LENGTH.
4932 Discard newlines outside of strings, thus
4933 converting funny-space markers to ordinary spaces. */
4935 dump_defn_1 (base, start, length)
4940 const U_CHAR *p = base + start;
4941 const U_CHAR *limit = base + start + length;
4946 else if (*p == '\"' || *p =='\'') {
4947 const U_CHAR *p1 = skip_quoted_string (p, limit, 0, 0, 0, 0);
4948 fwrite (p, p1 - p, 1, stdout);
4955 /* Print the name of argument number ARGNUM of macro definition DEFN.
4956 Recall that DEFN->argnames contains all the arg names
4957 concatenated in reverse order with comma-space in between. */
4959 dump_arg_n (defn, argnum)
4963 register const U_CHAR *p = defn->argnames;
4964 while (argnum + 1 < defn->nargs) {
4965 p = (const U_CHAR *) strchr ((const char *)p, ' ') + 1;
4969 while (*p && *p != ',') {
4975 /* Initialize the built-in macros. */
4976 #define DSC(x) U x, sizeof x - 1
4977 #define install_spec(name, type) \
4978 install(DSC(name), type, -1);
4979 #define install_value(name, val) \
4980 hp = install(DSC(name), T_CONST, -1); hp->value.cpval = val;
4982 initialize_builtins ()
4986 install_spec ("__BASE_FILE__", T_BASE_FILE);
4987 install_spec ("__DATE__", T_DATE);
4988 install_spec ("__FILE__", T_FILE);
4989 install_spec ("__TIME__", T_TIME);
4990 install_spec ("__VERSION__", T_VERSION);
4991 install_spec ("__INCLUDE_LEVEL__", T_INCLUDE_LEVEL);
4992 install_spec ("__LINE__", T_SPECLINE);
4994 #ifndef NO_BUILTIN_SIZE_TYPE
4995 install_value ("__SIZE_TYPE__", SIZE_TYPE);
4997 #ifndef NO_BUILTIN_PTRDIFF_TYPE
4998 install_value ("__PTRDIFF_TYPE__", PTRDIFF_TYPE);
5000 #ifndef NO_BUILTIN_WCHAR_TYPE
5001 install_value ("__WCHAR_TYPE__", WCHAR_TYPE);
5003 #ifndef NO_BUILTIN_WINT_TYPE
5004 install_value ("__WINT_TYPE__", WINT_TYPE);
5006 install_value ("__REGISTER_PREFIX__", REGISTER_PREFIX);
5007 install_value ("__USER_LABEL_PREFIX__", user_label_prefix);
5011 #undef install_value
5013 /* Common handler of command line directives -U, -D and -A. */
5015 run_directive (str, len, type)
5018 enum node_type type;
5020 struct directive *kt;
5021 FILE_BUF *ip = &instack[++indepth];
5022 ip->fname = "*command line*";
5024 ip->buf = ip->bufp = (U_CHAR *) str;
5029 ip->if_stack = if_stack;
5031 for (kt = directive_table; kt->type != type; kt++)
5034 (*kt->func) ((U_CHAR *) str, (U_CHAR *) str + len, NULL);
5038 /* Handle the -D option. If STR is just an identifier, define it with
5039 * value 1. If STR has anything after the identifier, then it should
5040 * be identifier-space-definition. */
5042 make_definition (str)
5048 /* Copy the entire option so we can modify it.
5049 Change the first "=" in the string to a space. If there is none,
5050 tack " 1" on the end. */
5052 /* Length including the null. */
5053 count = strlen (str);
5054 buf = (char *) alloca (count + 2);
5055 memcpy (buf, str, count);
5057 p = strchr (str, '=');
5066 run_directive (buf, count, T_DEFINE);
5069 /* Handle the -U option. */
5074 run_directive (str, strlen (str), T_UNDEF);
5077 /* Handles the #assert (-A) and #unassert (-A-) command line options. */
5079 make_assertion (str)
5082 enum node_type type = T_ASSERT;
5092 count = strlen (str);
5093 p = strchr (str, '=');
5096 /* Copy the entire option so we can modify it. Change the first
5097 "=" in the string to a '(', and tack a ')' on the end. */
5098 char *buf = (char *) alloca (count + 1);
5100 memcpy (buf, str, count);
5106 run_directive (str, count, type);
5109 /* Add output to `deps_buffer' for the -M switch.
5110 STRING points to the text to be output.
5111 SIZE is the number of bytes, or 0 meaning output until a null.
5112 If SIZE is nonzero, we break the line first, if it is long enough. */
5114 deps_output (string, size)
5118 #ifndef MAX_OUTPUT_COLUMNS
5119 #define MAX_OUTPUT_COLUMNS 75
5121 if (size != 0 && deps_column != 0
5122 && size + deps_column > MAX_OUTPUT_COLUMNS) {
5123 deps_output ("\\\n ", 0);
5128 size = strlen (string);
5130 if (deps_size + size + 1 > deps_allocated_size) {
5131 deps_allocated_size = deps_size + size + 50;
5132 deps_allocated_size *= 2;
5133 deps_buffer = (char *) xrealloc (deps_buffer, deps_allocated_size);
5135 memcpy (&deps_buffer[deps_size], string, size);
5137 deps_column += size;
5138 deps_buffer[deps_size] = 0;
5141 /* Get the file-mode and data size of the file open on FD
5142 and store them in *MODE_POINTER and *SIZE_POINTER. */
5145 file_size_and_mode (fd, mode_pointer, size_pointer)
5152 if (fstat (fd, &sbuf) < 0) return -1;
5153 if (mode_pointer) *mode_pointer = sbuf.st_mode;
5154 if (size_pointer) *size_pointer = sbuf.st_size;