OSDN Git Service

* system.h: Include filenames.h.
[pf3gnuchains/gcc-fork.git] / gcc / protoize.c
1 /* Protoize program - Original version by Ron Guilmette (rfg@segfault.us.com).
2    Copyright (C) 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3    1999, 2000, 2001, 2002, 2003 Free Software Foundation, Inc.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
11
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING.  If not, write to the Free
19 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20 02111-1307, USA.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "intl.h"
27 #include "cppdefault.h"
28
29 #include <setjmp.h>
30 #include <signal.h>
31 #if ! defined( SIGCHLD ) && defined( SIGCLD )
32 #  define SIGCHLD SIGCLD
33 #endif
34 #ifdef HAVE_UNISTD_H
35 #include <unistd.h>
36 #endif
37 #undef abort
38 #include "version.h"
39
40 /* Include getopt.h for the sake of getopt_long.  */
41 #include "getopt.h"
42
43 /* Macro to see if the path elements match.  */
44 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
45 #define IS_SAME_PATH_CHAR(a,b) (TOUPPER (a) == TOUPPER (b))
46 #else
47 #define IS_SAME_PATH_CHAR(a,b) ((a) == (b))
48 #endif
49
50 /* Macro to see if the paths match.  */
51 #define IS_SAME_PATH(a,b) (FILENAME_CMP (a, b) == 0)
52
53 /* Suffix for aux-info files.  */
54 #ifdef __MSDOS__
55 #define AUX_INFO_SUFFIX "X"
56 #else
57 #define AUX_INFO_SUFFIX ".X"
58 #endif
59
60 /* Suffix for saved files.  */
61 #ifdef __MSDOS__
62 #define SAVE_SUFFIX "sav"
63 #else
64 #define SAVE_SUFFIX ".save"
65 #endif
66
67 /* Suffix for renamed C++ files.  */
68 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
69 #define CPLUS_FILE_SUFFIX "cc"
70 #else
71 #define CPLUS_FILE_SUFFIX "C"
72 #endif
73
74 static void usage PARAMS ((void)) ATTRIBUTE_NORETURN;
75 static void aux_info_corrupted PARAMS ((void)) ATTRIBUTE_NORETURN;
76 static void declare_source_confusing PARAMS ((const char *)) ATTRIBUTE_NORETURN;
77 static const char *shortpath PARAMS ((const char *, const char *));
78 extern void fancy_abort PARAMS ((void)) ATTRIBUTE_NORETURN;
79 static void notice PARAMS ((const char *, ...)) ATTRIBUTE_PRINTF_1;
80 static char *savestring PARAMS ((const char *, unsigned int));
81 static char *dupnstr PARAMS ((const char *, size_t));
82 static const char *substr PARAMS ((const char *, const char * const));
83 static int safe_read PARAMS ((int, void *, int));
84 static void safe_write PARAMS ((int, void *, int, const char *));
85 static void save_pointers PARAMS ((void));
86 static void restore_pointers PARAMS ((void));
87 static int is_id_char PARAMS ((int));
88 static int in_system_include_dir PARAMS ((const char *));
89 static int directory_specified_p PARAMS ((const char *));
90 static int file_excluded_p PARAMS ((const char *));
91 static char *unexpand_if_needed PARAMS ((const char *));
92 static char *abspath PARAMS ((const char *, const char *));
93 static void check_aux_info PARAMS ((int));
94 static const char *find_corresponding_lparen PARAMS ((const char *));
95 static int referenced_file_is_newer PARAMS ((const char *, time_t));
96 static void save_def_or_dec PARAMS ((const char *, int));
97 static void munge_compile_params PARAMS ((const char *));
98 static int gen_aux_info_file PARAMS ((const char *));
99 static void process_aux_info_file PARAMS ((const char *, int, int));
100 static int identify_lineno PARAMS ((const char *));
101 static void check_source PARAMS ((int, const char *));
102 static const char *seek_to_line PARAMS ((int));
103 static const char *forward_to_next_token_char PARAMS ((const char *));
104 static void output_bytes PARAMS ((const char *, size_t));
105 static void output_string PARAMS ((const char *));
106 static void output_up_to PARAMS ((const char *));
107 static int other_variable_style_function PARAMS ((const char *));
108 static const char *find_rightmost_formals_list PARAMS ((const char *));
109 static void do_cleaning PARAMS ((char *, const char *));
110 static const char *careful_find_l_paren PARAMS ((const char *));
111 static void do_processing PARAMS ((void));
112
113 /* Look for these where the `const' qualifier is intentionally cast aside.  */
114 #define NONCONST
115
116 /* Define a default place to find the SYSCALLS.X file.  */
117
118 #ifndef UNPROTOIZE
119
120 #ifndef STANDARD_EXEC_PREFIX
121 #define STANDARD_EXEC_PREFIX "/usr/local/lib/gcc-lib/"
122 #endif /* !defined STANDARD_EXEC_PREFIX */
123
124 static const char * const standard_exec_prefix = STANDARD_EXEC_PREFIX;
125 static const char * const target_machine = DEFAULT_TARGET_MACHINE;
126 static const char * const target_version = DEFAULT_TARGET_VERSION;
127
128 #endif /* !defined (UNPROTOIZE) */
129
130 /* Suffix of aux_info files.  */
131
132 static const char * const aux_info_suffix = AUX_INFO_SUFFIX;
133
134 /* String to attach to filenames for saved versions of original files.  */
135
136 static const char * const save_suffix = SAVE_SUFFIX;
137
138 #ifndef UNPROTOIZE
139
140 /* String to attach to C filenames renamed to C++.  */
141
142 static const char * const cplus_suffix = CPLUS_FILE_SUFFIX;
143
144 /* File name of the file which contains descriptions of standard system
145    routines.  Note that we never actually do anything with this file per se,
146    but we do read in its corresponding aux_info file.  */
147
148 static const char syscalls_filename[] = "SYSCALLS.c";
149
150 /* Default place to find the above file.  */
151
152 static const char * default_syscalls_dir;
153
154 /* Variable to hold the complete absolutized filename of the SYSCALLS.c.X
155    file.  */
156
157 static char * syscalls_absolute_filename;
158
159 #endif /* !defined (UNPROTOIZE) */
160
161 /* Type of the structure that holds information about macro unexpansions.  */
162
163 struct unexpansion_struct {
164   const char *const expanded;
165   const char *const contracted;
166 };
167 typedef struct unexpansion_struct unexpansion;
168
169 /* A table of conversions that may need to be made for some (stupid) older
170    operating systems where these types are preprocessor macros rather than
171    typedefs (as they really ought to be).
172
173    WARNING: The contracted forms must be as small (or smaller) as the
174    expanded forms, or else havoc will ensue.  */
175
176 static const unexpansion unexpansions[] = {
177   { "struct _iobuf", "FILE" },
178   { 0, 0 }
179 };
180
181 /* The number of "primary" slots in the hash tables for filenames and for
182    function names.  This can be as big or as small as you like, except that
183    it must be a power of two.  */
184
185 #define HASH_TABLE_SIZE         (1 << 9)
186
187 /* Bit mask to use when computing hash values.  */
188
189 static const int hash_mask = (HASH_TABLE_SIZE - 1);
190
191
192 /* Datatype for lists of directories or filenames.  */
193 struct string_list
194 {
195   const char *name;
196   struct string_list *next;
197 };
198
199 static struct string_list *string_list_cons PARAMS ((const char *,
200                                                      struct string_list *));
201
202 /* List of directories in which files should be converted.  */
203
204 struct string_list *directory_list;
205
206 /* List of file names which should not be converted.
207    A file is excluded if the end of its name, following a /,
208    matches one of the names in this list.  */
209
210 struct string_list *exclude_list;
211
212 /* The name of the other style of variable-number-of-parameters functions
213    (i.e. the style that we want to leave unconverted because we don't yet
214    know how to convert them to this style.  This string is used in warning
215    messages.  */
216
217 /* Also define here the string that we can search for in the parameter lists
218    taken from the .X files which will unambiguously indicate that we have
219    found a varargs style function.  */
220
221 #ifdef UNPROTOIZE
222 static const char * const other_var_style = "stdarg";
223 #else /* !defined (UNPROTOIZE) */
224 static const char * const other_var_style = "varargs";
225 static const char *varargs_style_indicator = "va_alist";
226 #endif /* !defined (UNPROTOIZE) */
227
228 /* The following two types are used to create hash tables.  In this program,
229    there are two hash tables which are used to store and quickly lookup two
230    different classes of strings.  The first type of strings stored in the
231    first hash table are absolute filenames of files which protoize needs to
232    know about.  The second type of strings (stored in the second hash table)
233    are function names.  It is this second class of strings which really
234    inspired the use of the hash tables, because there may be a lot of them.  */
235
236 typedef struct hash_table_entry_struct hash_table_entry;
237
238 /* Do some typedefs so that we don't have to write "struct" so often.  */
239
240 typedef struct def_dec_info_struct def_dec_info;
241 typedef struct file_info_struct file_info;
242 typedef struct f_list_chain_item_struct f_list_chain_item;
243
244 #ifndef UNPROTOIZE
245 static int is_syscalls_file PARAMS ((const file_info *));
246 static void rename_c_file PARAMS ((const hash_table_entry *));
247 static const def_dec_info *find_extern_def PARAMS ((const def_dec_info *,
248                                                     const def_dec_info *));
249 static const def_dec_info *find_static_definition PARAMS ((const def_dec_info *));
250 static void connect_defs_and_decs PARAMS ((const hash_table_entry *));
251 static void add_local_decl PARAMS ((const def_dec_info *, const char *));
252 static void add_global_decls PARAMS ((const file_info *, const char *));
253 #endif /* ! UNPROTOIZE */
254 static int needs_to_be_converted PARAMS ((const file_info *));
255 static void visit_each_hash_node PARAMS ((const hash_table_entry *,
256                                           void (*)(const hash_table_entry *)));
257 static hash_table_entry *add_symbol PARAMS ((hash_table_entry *, const char *));
258 static hash_table_entry *lookup PARAMS ((hash_table_entry *, const char *));
259 static void free_def_dec PARAMS ((def_dec_info *));
260 static file_info *find_file PARAMS ((const char *, int));
261 static void reverse_def_dec_list PARAMS ((const hash_table_entry *));
262 static void edit_fn_declaration PARAMS ((const def_dec_info *, const char *));
263 static int edit_formals_lists PARAMS ((const char *, unsigned int,
264                                        const def_dec_info *));
265 static void edit_fn_definition PARAMS ((const def_dec_info *, const char *));
266 static void scan_for_missed_items PARAMS ((const file_info *));
267 static void edit_file PARAMS ((const hash_table_entry *));
268
269 /* In the struct below, note that the "_info" field has two different uses
270    depending on the type of hash table we are in (i.e. either the filenames
271    hash table or the function names hash table).  In the filenames hash table
272    the info fields of the entries point to the file_info struct which is
273    associated with each filename (1 per filename).  In the function names
274    hash table, the info field points to the head of a singly linked list of
275    def_dec_info entries which are all defs or decs of the function whose
276    name is pointed to by the "symbol" field.  Keeping all of the defs/decs
277    for a given function name on a special list specifically for that function
278    name makes it quick and easy to find out all of the important information
279    about a given (named) function.  */
280
281 struct hash_table_entry_struct {
282   hash_table_entry *            hash_next;      /* -> to secondary entries */
283   const char *                  symbol;         /* -> to the hashed string */
284   union {
285     const def_dec_info *        _ddip;
286     file_info *                 _fip;
287   } _info;
288 };
289 #define ddip _info._ddip
290 #define fip _info._fip
291
292 /* Define a type specifically for our two hash tables.  */
293
294 typedef hash_table_entry hash_table[HASH_TABLE_SIZE];
295
296 /* The following struct holds all of the important information about any
297    single filename (e.g. file) which we need to know about.  */
298
299 struct file_info_struct {
300   const hash_table_entry *      hash_entry; /* -> to associated hash entry */
301   const def_dec_info *          defs_decs;  /* -> to chain of defs/decs */
302   time_t                        mtime;      /* Time of last modification.  */
303 };
304
305 /* Due to the possibility that functions may return pointers to functions,
306    (which may themselves have their own parameter lists) and due to the
307    fact that returned pointers-to-functions may be of type "pointer-to-
308    function-returning-pointer-to-function" (ad nauseum) we have to keep
309    an entire chain of ANSI style formal parameter lists for each function.
310
311    Normally, for any given function, there will only be one formals list
312    on the chain, but you never know.
313
314    Note that the head of each chain of formals lists is pointed to by the
315    `f_list_chain' field of the corresponding def_dec_info record.
316
317    For any given chain, the item at the head of the chain is the *leftmost*
318    parameter list seen in the actual C language function declaration.  If
319    there are other members of the chain, then these are linked in left-to-right
320    order from the head of the chain.  */
321
322 struct f_list_chain_item_struct {
323   const f_list_chain_item *     chain_next;     /* -> to next item on chain */
324   const char *                  formals_list;   /* -> to formals list string */
325 };
326
327 /* The following struct holds all of the important information about any
328    single function definition or declaration which we need to know about.
329    Note that for unprotoize we don't need to know very much because we
330    never even create records for stuff that we don't intend to convert
331    (like for instance defs and decs which are already in old K&R format
332    and "implicit" function declarations).  */
333
334 struct def_dec_info_struct {
335   const def_dec_info *  next_in_file;   /* -> to rest of chain for file */
336   file_info *           file;           /* -> file_info for containing file */
337   int                   line;           /* source line number of def/dec */
338   const char *          ansi_decl;      /* -> left end of ansi decl */
339   hash_table_entry *    hash_entry;     /* -> hash entry for function name */
340   unsigned int          is_func_def;    /* = 0 means this is a declaration */
341   const def_dec_info *  next_for_func;  /* -> to rest of chain for func name */
342   unsigned int          f_list_count;   /* count of formals lists we expect */
343   char                  prototyped;     /* = 0 means already prototyped */
344 #ifndef UNPROTOIZE
345   const f_list_chain_item * f_list_chain;       /* -> chain of formals lists */
346   const def_dec_info *  definition;     /* -> def/dec containing related def */
347   char                  is_static;      /* = 0 means visibility is "extern"  */
348   char                  is_implicit;    /* != 0 for implicit func decl's */
349   char                  written;        /* != 0 means written for implicit */
350 #else /* !defined (UNPROTOIZE) */
351   const char *          formal_names;   /* -> to list of names of formals */
352   const char *          formal_decls;   /* -> to string of formal declarations */
353 #endif /* !defined (UNPROTOIZE) */
354 };
355
356 /* Pointer to the tail component of the filename by which this program was
357    invoked.  Used everywhere in error and warning messages.  */
358
359 static const char *pname;
360
361 /* Error counter.  Will be nonzero if we should give up at the next convenient
362    stopping point.  */
363
364 static int errors = 0;
365
366 /* Option flags.  */
367 /* ??? These comments should say what the flag mean as well as the options
368    that set them.  */
369
370 /* File name to use for running gcc.  Allows GCC 2 to be named
371    something other than gcc.  */
372 static const char *compiler_file_name = "gcc";
373
374 static int version_flag = 0;            /* Print our version number.  */
375 static int quiet_flag = 0;              /* Don't print messages normally.  */
376 static int nochange_flag = 0;           /* Don't convert, just say what files
377                                            we would have converted.  */
378 static int nosave_flag = 0;             /* Don't save the old version.  */
379 static int keep_flag = 0;               /* Don't delete the .X files.  */
380 static const char ** compile_params = 0;        /* Option string for gcc.  */
381 #ifdef UNPROTOIZE
382 static const char *indent_string = "     ";     /* Indentation for newly
383                                                    inserted parm decls.  */
384 #else /* !defined (UNPROTOIZE) */
385 static int local_flag = 0;              /* Insert new local decls (when?).  */
386 static int global_flag = 0;             /* set by -g option */
387 static int cplusplus_flag = 0;          /* Rename converted files to *.C.  */
388 static const char *nondefault_syscalls_dir = 0; /* Dir to look for
389                                                    SYSCALLS.c.X in.  */
390 #endif /* !defined (UNPROTOIZE) */
391
392 /* An index into the compile_params array where we should insert the source
393    file name when we are ready to exec the C compiler.  A zero value indicates
394    that we have not yet called munge_compile_params.  */
395
396 static int input_file_name_index = 0;
397
398 /* An index into the compile_params array where we should insert the filename
399    for the aux info file, when we run the C compiler.  */
400 static int aux_info_file_name_index = 0;
401
402 /* Count of command line arguments which were "filename" arguments.  */
403
404 static int n_base_source_files = 0;
405
406 /* Points to a malloc'ed list of pointers to all of the filenames of base
407    source files which were specified on the command line.  */
408
409 static const char **base_source_filenames;
410
411 /* Line number of the line within the current aux_info file that we
412    are currently processing.  Used for error messages in case the prototypes
413    info file is corrupted somehow.  */
414
415 static int current_aux_info_lineno;
416
417 /* Pointer to the name of the source file currently being converted.  */
418
419 static const char *convert_filename;
420
421 /* Pointer to relative root string (taken from aux_info file) which indicates
422    where directory the user was in when he did the compilation step that
423    produced the containing aux_info file.  */
424
425 static const char *invocation_filename;
426
427 /* Pointer to the base of the input buffer that holds the original text for the
428    source file currently being converted.  */
429
430 static const char *orig_text_base;
431
432 /* Pointer to the byte just beyond the end of the input buffer that holds the
433    original text for the source file currently being converted.  */
434
435 static const char *orig_text_limit;
436
437 /* Pointer to the base of the input buffer that holds the cleaned text for the
438    source file currently being converted.  */
439
440 static const char *clean_text_base;
441
442 /* Pointer to the byte just beyond the end of the input buffer that holds the
443    cleaned text for the source file currently being converted.  */
444
445 static const char *clean_text_limit;
446
447 /* Pointer to the last byte in the cleaned text buffer that we have already
448    (virtually) copied to the output buffer (or decided to ignore).  */
449
450 static const char * clean_read_ptr;
451
452 /* Pointer to the base of the output buffer that holds the replacement text
453    for the source file currently being converted.  */
454
455 static char *repl_text_base;
456
457 /* Pointer to the byte just beyond the end of the output buffer that holds the
458    replacement text for the source file currently being converted.  */
459
460 static char *repl_text_limit;
461
462 /* Pointer to the last byte which has been stored into the output buffer.
463    The next byte to be stored should be stored just past where this points
464    to.  */
465
466 static char * repl_write_ptr;
467
468 /* Pointer into the cleaned text buffer for the source file we are currently
469    converting.  This points to the first character of the line that we last
470    did a "seek_to_line" to (see below).  */
471
472 static const char *last_known_line_start;
473
474 /* Number of the line (in the cleaned text buffer) that we last did a
475    "seek_to_line" to.  Will be one if we just read a new source file
476    into the cleaned text buffer.  */
477
478 static int last_known_line_number;
479
480 /* The filenames hash table.  */
481
482 static hash_table filename_primary;
483
484 /* The function names hash table.  */
485
486 static hash_table function_name_primary;
487
488 /* The place to keep the recovery address which is used only in cases where
489    we get hopelessly confused by something in the cleaned original text.  */
490
491 static jmp_buf source_confusion_recovery;
492
493 /* A pointer to the current directory filename (used by abspath).  */
494
495 static char *cwd_buffer;
496
497 /* A place to save the read pointer until we are sure that an individual
498    attempt at editing will succeed.  */
499
500 static const char * saved_clean_read_ptr;
501
502 /* A place to save the write pointer until we are sure that an individual
503    attempt at editing will succeed.  */
504
505 static char * saved_repl_write_ptr;
506 \f
507 /* Translate and output an error message.  */
508 static void
509 notice (const char *msgid, ...)
510 {
511   va_list ap;
512   
513   va_start (ap, msgid);
514   vfprintf (stderr, _(msgid), ap);
515   va_end (ap);
516 }
517
518 \f
519 /* Make a copy of a string INPUT with size SIZE.  */
520
521 static char *
522 savestring (input, size)
523      const char *input;
524      unsigned int size;
525 {
526   char *output = (char *) xmalloc (size + 1);
527   strcpy (output, input);
528   return output;
529 }
530
531 /* More 'friendly' abort that prints the line and file.
532    config.h can #define abort fancy_abort if you like that sort of thing.  */
533
534 void
535 fancy_abort ()
536 {
537   notice ("%s: internal abort\n", pname);
538   exit (FATAL_EXIT_CODE);
539 }
540 \f
541 /* Make a duplicate of the first N bytes of a given string in a newly
542    allocated area.  */
543
544 static char *
545 dupnstr (s, n)
546      const char *s;
547      size_t n;
548 {
549   char *ret_val = (char *) xmalloc (n + 1);
550
551   strncpy (ret_val, s, n);
552   ret_val[n] = '\0';
553   return ret_val;
554 }
555
556 /* Return a pointer to the first occurrence of s2 within s1 or NULL if s2
557    does not occur within s1.  Assume neither s1 nor s2 are null pointers.  */
558
559 static const char *
560 substr (s1, s2)
561      const char *s1;
562      const char *const s2;
563 {
564   for (; *s1 ; s1++)
565     {
566       const char *p1;
567       const char *p2;
568       int c;
569
570       for (p1 = s1, p2 = s2; (c = *p2); p1++, p2++)
571         if (*p1 != c)
572           goto outer;
573       return s1;
574 outer:
575       ;
576     }
577   return 0;
578 }
579 \f
580 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
581    retrying if necessary.  Return the actual number of bytes read.  */
582
583 static int
584 safe_read (desc, ptr, len)
585      int desc;
586      void *ptr;
587      int len;
588 {
589   int left = len;
590   while (left > 0) {
591     int nchars = read (desc, ptr, left);
592     if (nchars < 0)
593       {
594 #ifdef EINTR
595         if (errno == EINTR)
596           continue;
597 #endif
598         return nchars;
599       }
600     if (nchars == 0)
601       break;
602     /* Arithmetic on void pointers is a gcc extension.  */
603     ptr = (char *) ptr + nchars;
604     left -= nchars;
605   }
606   return len - left;
607 }
608
609 /* Write LEN bytes at PTR to descriptor DESC,
610    retrying if necessary, and treating any real error as fatal.  */
611
612 static void
613 safe_write (desc, ptr, len, out_fname)
614      int desc;
615      void *ptr;
616      int len;
617      const char *out_fname;
618 {
619   while (len > 0) {
620     int written = write (desc, ptr, len);
621     if (written < 0)
622       {
623         int errno_val = errno;
624 #ifdef EINTR
625         if (errno_val == EINTR)
626           continue;
627 #endif
628         notice ("%s: error writing file `%s': %s\n",
629                 pname, shortpath (NULL, out_fname), xstrerror (errno_val));
630         return;
631       }
632     /* Arithmetic on void pointers is a gcc extension.  */
633     ptr = (char *) ptr + written;
634     len -= written;
635   }
636 }
637 \f
638 /* Get setup to recover in case the edit we are about to do goes awry.  */
639
640 static void
641 save_pointers ()
642 {
643   saved_clean_read_ptr = clean_read_ptr;
644   saved_repl_write_ptr = repl_write_ptr;
645 }
646
647 /* Call this routine to recover our previous state whenever something looks
648    too confusing in the source code we are trying to edit.  */
649
650 static void
651 restore_pointers ()
652 {
653   clean_read_ptr = saved_clean_read_ptr;
654   repl_write_ptr = saved_repl_write_ptr;
655 }
656
657 /* Return true if the given character is a valid identifier character.  */
658
659 static int
660 is_id_char (ch)
661      int ch;
662 {
663   return (ISIDNUM (ch) || (ch == '$'));
664 }
665
666 /* Give a message indicating the proper way to invoke this program and then
667    exit with nonzero status.  */
668
669 static void
670 usage ()
671 {
672 #ifdef UNPROTOIZE
673   notice ("%s: usage '%s [ -VqfnkN ] [ -i <istring> ] [ filename ... ]'\n",
674           pname, pname);
675 #else /* !defined (UNPROTOIZE) */
676   notice ("%s: usage '%s [ -VqfnkNlgC ] [ -B <dirname> ] [ filename ... ]'\n",
677           pname, pname);
678 #endif /* !defined (UNPROTOIZE) */
679   exit (FATAL_EXIT_CODE);
680 }
681
682 /* Return true if the given filename (assumed to be an absolute filename)
683    designates a file residing anywhere beneath any one of the "system"
684    include directories.  */
685
686 static int
687 in_system_include_dir (path)
688      const char *path;
689 {
690   const struct default_include *p;
691
692   if (! IS_ABSOLUTE_PATH (path))
693     abort ();           /* Must be an absolutized filename.  */
694
695   for (p = cpp_include_defaults; p->fname; p++)
696     if (!strncmp (path, p->fname, strlen (p->fname))
697         && IS_DIR_SEPARATOR (path[strlen (p->fname)]))
698       return 1;
699   return 0;
700 }
701 \f
702 #if 0
703 /* Return true if the given filename designates a file that the user has
704    read access to and for which the user has write access to the containing
705    directory.  */
706
707 static int
708 file_could_be_converted (const char *path)
709 {
710   char *const dir_name = (char *) alloca (strlen (path) + 1);
711
712   if (access (path, R_OK))
713     return 0;
714
715   {
716     char *dir_last_slash;
717
718     strcpy (dir_name, path);
719     dir_last_slash = strrchr (dir_name, DIR_SEPARATOR);
720 #ifdef DIR_SEPARATOR_2
721     {
722       char *slash;
723
724       slash = strrchr (dir_last_slash ? dir_last_slash : dir_name,
725                        DIR_SEPARATOR_2);
726       if (slash)
727         dir_last_slash = slash;
728     }
729 #endif
730     if (dir_last_slash)
731       *dir_last_slash = '\0';
732     else
733       abort ();  /* Should have been an absolutized filename.  */
734   }
735
736   if (access (path, W_OK))
737     return 0;
738
739   return 1;
740 }
741
742 /* Return true if the given filename designates a file that we are allowed
743    to modify.  Files which we should not attempt to modify are (a) "system"
744    include files, and (b) files which the user doesn't have write access to,
745    and (c) files which reside in directories which the user doesn't have
746    write access to.  Unless requested to be quiet, give warnings about
747    files that we will not try to convert for one reason or another.  An
748    exception is made for "system" include files, which we never try to
749    convert and for which we don't issue the usual warnings.  */
750
751 static int
752 file_normally_convertible (const char *path)
753 {
754   char *const dir_name = alloca (strlen (path) + 1);
755
756   if (in_system_include_dir (path))
757     return 0;
758
759   {
760     char *dir_last_slash;
761
762     strcpy (dir_name, path);
763     dir_last_slash = strrchr (dir_name, DIR_SEPARATOR);
764 #ifdef DIR_SEPARATOR_2
765     {
766       char *slash;
767
768       slash = strrchr (dir_last_slash ? dir_last_slash : dir_name,
769                        DIR_SEPARATOR_2);
770       if (slash)
771         dir_last_slash = slash;
772     }
773 #endif
774     if (dir_last_slash)
775       *dir_last_slash = '\0';
776     else
777       abort ();  /* Should have been an absolutized filename.  */
778   }
779
780   if (access (path, R_OK))
781     {
782       if (!quiet_flag)
783         notice ("%s: warning: no read access for file `%s'\n",
784                 pname, shortpath (NULL, path));
785       return 0;
786     }
787
788   if (access (path, W_OK))
789     {
790       if (!quiet_flag)
791         notice ("%s: warning: no write access for file `%s'\n",
792                 pname, shortpath (NULL, path));
793       return 0;
794     }
795
796   if (access (dir_name, W_OK))
797     {
798       if (!quiet_flag)
799         notice ("%s: warning: no write access for dir containing `%s'\n",
800                 pname, shortpath (NULL, path));
801       return 0;
802     }
803
804   return 1;
805 }
806 #endif /* 0 */
807 \f
808 #ifndef UNPROTOIZE
809
810 /* Return true if the given file_info struct refers to the special SYSCALLS.c.X
811    file.  Return false otherwise.  */
812
813 static int
814 is_syscalls_file (fi_p)
815      const file_info *fi_p;
816 {
817   char const *f = fi_p->hash_entry->symbol;
818   size_t fl = strlen (f), sysl = sizeof (syscalls_filename) - 1;
819   return sysl <= fl  &&  strcmp (f + fl - sysl, syscalls_filename) == 0;
820 }
821
822 #endif /* !defined (UNPROTOIZE) */
823
824 /* Check to see if this file will need to have anything done to it on this
825    run.  If there is nothing in the given file which both needs conversion
826    and for which we have the necessary stuff to do the conversion, return
827    false.  Otherwise, return true.
828
829    Note that (for protoize) it is only valid to call this function *after*
830    the connections between declarations and definitions have all been made
831    by connect_defs_and_decs.  */
832
833 static int
834 needs_to_be_converted (file_p)
835      const file_info *file_p;
836 {
837   const def_dec_info *ddp;
838
839 #ifndef UNPROTOIZE
840
841   if (is_syscalls_file (file_p))
842     return 0;
843
844 #endif /* !defined (UNPROTOIZE) */
845
846   for (ddp = file_p->defs_decs; ddp; ddp = ddp->next_in_file)
847
848     if (
849
850 #ifndef UNPROTOIZE
851
852       /* ... and if we a protoizing and this function is in old style ...  */
853       !ddp->prototyped
854       /* ... and if this a definition or is a decl with an associated def ...  */
855       && (ddp->is_func_def || (!ddp->is_func_def && ddp->definition))
856
857 #else /* defined (UNPROTOIZE) */
858
859       /* ... and if we are unprotoizing and this function is in new style ...  */
860       ddp->prototyped
861
862 #endif /* defined (UNPROTOIZE) */
863       )
864           /* ... then the containing file needs converting.  */
865           return -1;
866   return 0;
867 }
868
869 /* Return 1 if the file name NAME is in a directory
870    that should be converted.  */
871
872 static int
873 directory_specified_p (name)
874      const char *name;
875 {
876   struct string_list *p;
877
878   for (p = directory_list; p; p = p->next)
879     if (!strncmp (name, p->name, strlen (p->name))
880         && IS_DIR_SEPARATOR (name[strlen (p->name)]))
881       {
882         const char *q = name + strlen (p->name) + 1;
883
884         /* If there are more slashes, it's in a subdir, so
885            this match doesn't count.  */
886         while (*q++)
887           if (IS_DIR_SEPARATOR (*(q-1)))
888             goto lose;
889         return 1;
890
891       lose: ;
892       }
893
894   return 0;
895 }
896
897 /* Return 1 if the file named NAME should be excluded from conversion.  */
898
899 static int
900 file_excluded_p (name)
901      const char *name;
902 {
903   struct string_list *p;
904   int len = strlen (name);
905
906   for (p = exclude_list; p; p = p->next)
907     if (!strcmp (name + len - strlen (p->name), p->name)
908         && IS_DIR_SEPARATOR (name[len - strlen (p->name) - 1]))
909       return 1;
910
911   return 0;
912 }
913
914 /* Construct a new element of a string_list.
915    STRING is the new element value, and REST holds the remaining elements.  */
916
917 static struct string_list *
918 string_list_cons (string, rest)
919      const char *string;
920      struct string_list *rest;
921 {
922   struct string_list *temp
923     = (struct string_list *) xmalloc (sizeof (struct string_list));
924
925   temp->next = rest;
926   temp->name = string;
927   return temp;
928 }
929 \f
930 /* ??? The GNU convention for mentioning function args in its comments
931    is to capitalize them.  So change "hash_tab_p" to HASH_TAB_P below.
932    Likewise for all the other functions.  */
933
934 /* Given a hash table, apply some function to each node in the table. The
935    table to traverse is given as the "hash_tab_p" argument, and the
936    function to be applied to each node in the table is given as "func"
937    argument.  */
938
939 static void
940 visit_each_hash_node (hash_tab_p, func)
941      const hash_table_entry *hash_tab_p;
942      void (*func) PARAMS ((const hash_table_entry *));
943 {
944   const hash_table_entry *primary;
945
946   for (primary = hash_tab_p; primary < &hash_tab_p[HASH_TABLE_SIZE]; primary++)
947     if (primary->symbol)
948       {
949         hash_table_entry *second;
950
951         (*func)(primary);
952         for (second = primary->hash_next; second; second = second->hash_next)
953           (*func) (second);
954       }
955 }
956
957 /* Initialize all of the fields of a new hash table entry, pointed
958    to by the "p" parameter.  Note that the space to hold the entry
959    is assumed to have already been allocated before this routine is
960    called.  */
961
962 static hash_table_entry *
963 add_symbol (p, s)
964      hash_table_entry *p;
965      const char *s;
966 {
967   p->hash_next = NULL;
968   p->symbol = xstrdup (s);
969   p->ddip = NULL;
970   p->fip = NULL;
971   return p;
972 }
973
974 /* Look for a particular function name or filename in the particular
975    hash table indicated by "hash_tab_p".  If the name is not in the
976    given hash table, add it.  Either way, return a pointer to the
977    hash table entry for the given name.  */
978
979 static hash_table_entry *
980 lookup (hash_tab_p, search_symbol)
981      hash_table_entry *hash_tab_p;
982      const char *search_symbol;
983 {
984   int hash_value = 0;
985   const char *search_symbol_char_p = search_symbol;
986   hash_table_entry *p;
987
988   while (*search_symbol_char_p)
989     hash_value += *search_symbol_char_p++;
990   hash_value &= hash_mask;
991   p = &hash_tab_p[hash_value];
992   if (! p->symbol)
993       return add_symbol (p, search_symbol);
994   if (!strcmp (p->symbol, search_symbol))
995     return p;
996   while (p->hash_next)
997     {
998       p = p->hash_next;
999       if (!strcmp (p->symbol, search_symbol))
1000         return p;
1001     }
1002   p->hash_next = (hash_table_entry *) xmalloc (sizeof (hash_table_entry));
1003   p = p->hash_next;
1004   return add_symbol (p, search_symbol);
1005 }
1006 \f
1007 /* Throw a def/dec record on the junk heap.
1008
1009    Also, since we are not using this record anymore, free up all of the
1010    stuff it pointed to.  */
1011
1012 static void
1013 free_def_dec (p)
1014      def_dec_info *p;
1015 {
1016   free ((NONCONST void *) p->ansi_decl);
1017
1018 #ifndef UNPROTOIZE
1019   {
1020     const f_list_chain_item * curr;
1021     const f_list_chain_item * next;
1022
1023     for (curr = p->f_list_chain; curr; curr = next)
1024       {
1025         next = curr->chain_next;
1026         free ((NONCONST void *) curr);
1027       }
1028   }
1029 #endif /* !defined (UNPROTOIZE) */
1030
1031   free (p);
1032 }
1033
1034 /* Unexpand as many macro symbol as we can find.
1035
1036    If the given line must be unexpanded, make a copy of it in the heap and
1037    return a pointer to the unexpanded copy.  Otherwise return NULL.  */
1038
1039 static char *
1040 unexpand_if_needed (aux_info_line)
1041      const char *aux_info_line;
1042 {
1043   static char *line_buf = 0;
1044   static int line_buf_size = 0;
1045   const unexpansion *unexp_p;
1046   int got_unexpanded = 0;
1047   const char *s;
1048   char *copy_p = line_buf;
1049
1050   if (line_buf == 0)
1051     {
1052       line_buf_size = 1024;
1053       line_buf = (char *) xmalloc (line_buf_size);
1054     }
1055
1056   copy_p = line_buf;
1057
1058   /* Make a copy of the input string in line_buf, expanding as necessary.  */
1059
1060   for (s = aux_info_line; *s != '\n'; )
1061     {
1062       for (unexp_p = unexpansions; unexp_p->expanded; unexp_p++)
1063         {
1064           const char *in_p = unexp_p->expanded;
1065           size_t len = strlen (in_p);
1066
1067           if (*s == *in_p && !strncmp (s, in_p, len) && !is_id_char (s[len]))
1068             {
1069               int size = strlen (unexp_p->contracted);
1070               got_unexpanded = 1;
1071               if (copy_p + size - line_buf >= line_buf_size)
1072                 {
1073                   int offset = copy_p - line_buf;
1074                   line_buf_size *= 2;
1075                   line_buf_size += size;
1076                   line_buf = (char *) xrealloc (line_buf, line_buf_size);
1077                   copy_p = line_buf + offset;
1078                 }
1079               strcpy (copy_p, unexp_p->contracted);
1080               copy_p += size;
1081
1082               /* Assume that there will not be another replacement required
1083                  within the text just replaced.  */
1084
1085               s += len;
1086               goto continue_outer;
1087             }
1088         }
1089       if (copy_p - line_buf == line_buf_size)
1090         {
1091           int offset = copy_p - line_buf;
1092           line_buf_size *= 2;
1093           line_buf = (char *) xrealloc (line_buf, line_buf_size);
1094           copy_p = line_buf + offset;
1095         }
1096       *copy_p++ = *s++;
1097 continue_outer: ;
1098     }
1099   if (copy_p + 2 - line_buf >= line_buf_size)
1100     {
1101       int offset = copy_p - line_buf;
1102       line_buf_size *= 2;
1103       line_buf = (char *) xrealloc (line_buf, line_buf_size);
1104       copy_p = line_buf + offset;
1105     }
1106   *copy_p++ = '\n';
1107   *copy_p = '\0';
1108
1109   return (got_unexpanded ? savestring (line_buf, copy_p - line_buf) : 0);
1110 }
1111 \f
1112 /* Return the absolutized filename for the given relative
1113    filename.  Note that if that filename is already absolute, it may
1114    still be returned in a modified form because this routine also
1115    eliminates redundant slashes and single dots and eliminates double
1116    dots to get a shortest possible filename from the given input
1117    filename.  The absolutization of relative filenames is made by
1118    assuming that the given filename is to be taken as relative to
1119    the first argument (cwd) or to the current directory if cwd is
1120    NULL.  */
1121
1122 static char *
1123 abspath (cwd, rel_filename)
1124      const char *cwd;
1125      const char *rel_filename;
1126 {
1127   /* Setup the current working directory as needed.  */
1128   const char *const cwd2 = (cwd) ? cwd : cwd_buffer;
1129   char *const abs_buffer
1130     = (char *) alloca (strlen (cwd2) + strlen (rel_filename) + 2);
1131   char *endp = abs_buffer;
1132   char *outp, *inp;
1133
1134   /* Copy the  filename (possibly preceded by the current working
1135      directory name) into the absolutization buffer.  */
1136
1137   {
1138     const char *src_p;
1139
1140     if (! IS_ABSOLUTE_PATH (rel_filename))
1141       {
1142         src_p = cwd2;
1143         while ((*endp++ = *src_p++))
1144           continue;
1145         *(endp-1) = DIR_SEPARATOR;              /* overwrite null */
1146       }
1147 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
1148     else if (IS_DIR_SEPARATOR (rel_filename[0]))
1149       {
1150         /* A path starting with a directory separator is considered absolute
1151            for dos based filesystems, but it's really not -- it's just the
1152            convention used throughout GCC and it works. However, in this
1153            case, we still need to prepend the drive spec from cwd_buffer.  */
1154         *endp++ = cwd2[0];
1155         *endp++ = cwd2[1];
1156       }
1157 #endif
1158     src_p = rel_filename;
1159     while ((*endp++ = *src_p++))
1160       continue;
1161   }
1162
1163   /* Now make a copy of abs_buffer into abs_buffer, shortening the
1164      filename (by taking out slashes and dots) as we go.  */
1165
1166   outp = inp = abs_buffer;
1167   *outp++ = *inp++;             /* copy first slash */
1168 #if defined (apollo) || defined (_WIN32) || defined (__INTERIX)
1169   if (IS_DIR_SEPARATOR (inp[0]))
1170     *outp++ = *inp++;           /* copy second slash */
1171 #endif
1172   for (;;)
1173     {
1174       if (!inp[0])
1175         break;
1176       else if (IS_DIR_SEPARATOR (inp[0]) && IS_DIR_SEPARATOR (outp[-1]))
1177         {
1178           inp++;
1179           continue;
1180         }
1181       else if (inp[0] == '.' && IS_DIR_SEPARATOR (outp[-1]))
1182         {
1183           if (!inp[1])
1184             break;
1185           else if (IS_DIR_SEPARATOR (inp[1]))
1186             {
1187               inp += 2;
1188               continue;
1189             }
1190           else if ((inp[1] == '.') && (inp[2] == 0
1191                                        || IS_DIR_SEPARATOR (inp[2])))
1192             {
1193               inp += (IS_DIR_SEPARATOR (inp[2])) ? 3 : 2;
1194               outp -= 2;
1195               while (outp >= abs_buffer && ! IS_DIR_SEPARATOR (*outp))
1196                 outp--;
1197               if (outp < abs_buffer)
1198                 {
1199                   /* Catch cases like /.. where we try to backup to a
1200                      point above the absolute root of the logical file
1201                      system.  */
1202
1203                   notice ("%s: invalid file name: %s\n",
1204                           pname, rel_filename);
1205                   exit (FATAL_EXIT_CODE);
1206                 }
1207               *++outp = '\0';
1208               continue;
1209             }
1210         }
1211       *outp++ = *inp++;
1212     }
1213
1214   /* On exit, make sure that there is a trailing null, and make sure that
1215      the last character of the returned string is *not* a slash.  */
1216
1217   *outp = '\0';
1218   if (IS_DIR_SEPARATOR (outp[-1]))
1219     *--outp  = '\0';
1220
1221   /* Make a copy (in the heap) of the stuff left in the absolutization
1222      buffer and return a pointer to the copy.  */
1223
1224   return savestring (abs_buffer, outp - abs_buffer);
1225 }
1226 \f
1227 /* Given a filename (and possibly a directory name from which the filename
1228    is relative) return a string which is the shortest possible
1229    equivalent for the corresponding full (absolutized) filename.  The
1230    shortest possible equivalent may be constructed by converting the
1231    absolutized filename to be a relative filename (i.e. relative to
1232    the actual current working directory).  However if a relative filename
1233    is longer, then the full absolute filename is returned.
1234
1235    KNOWN BUG:
1236
1237    Note that "simple-minded" conversion of any given type of filename (either
1238    relative or absolute) may not result in a valid equivalent filename if any
1239    subpart of the original filename is actually a symbolic link.  */
1240
1241 static const char *
1242 shortpath (cwd, filename)
1243      const char *cwd;
1244      const char *filename;
1245 {
1246   char *rel_buffer;
1247   char *rel_buf_p;
1248   char *cwd_p = cwd_buffer;
1249   char *path_p;
1250   int unmatched_slash_count = 0;
1251   size_t filename_len = strlen (filename);
1252
1253   path_p = abspath (cwd, filename);
1254   rel_buf_p = rel_buffer = (char *) xmalloc (filename_len);
1255
1256   while (*cwd_p && IS_SAME_PATH_CHAR (*cwd_p, *path_p))
1257     {
1258       cwd_p++;
1259       path_p++;
1260     }
1261   if (!*cwd_p && (!*path_p || IS_DIR_SEPARATOR (*path_p)))
1262     {
1263       /* whole pwd matched */
1264       if (!*path_p)             /* input *is* the current path! */
1265         return ".";
1266       else
1267         return ++path_p;
1268     }
1269   else
1270     {
1271       if (*path_p)
1272         {
1273           --cwd_p;
1274           --path_p;
1275           while (! IS_DIR_SEPARATOR (*cwd_p))     /* backup to last slash */
1276             {
1277               --cwd_p;
1278               --path_p;
1279             }
1280           cwd_p++;
1281           path_p++;
1282           unmatched_slash_count++;
1283         }
1284
1285       /* Find out how many directory levels in cwd were *not* matched.  */
1286       while (*cwd_p++)
1287         if (IS_DIR_SEPARATOR (*(cwd_p-1)))
1288           unmatched_slash_count++;
1289
1290       /* Now we know how long the "short name" will be.
1291          Reject it if longer than the input.  */
1292       if (unmatched_slash_count * 3 + strlen (path_p) >= filename_len)
1293         return filename;
1294
1295       /* For each of them, put a `../' at the beginning of the short name.  */
1296       while (unmatched_slash_count--)
1297         {
1298           /* Give up if the result gets to be longer
1299              than the absolute path name.  */
1300           if (rel_buffer + filename_len <= rel_buf_p + 3)
1301             return filename;
1302           *rel_buf_p++ = '.';
1303           *rel_buf_p++ = '.';
1304           *rel_buf_p++ = DIR_SEPARATOR;
1305         }
1306
1307       /* Then tack on the unmatched part of the desired file's name.  */
1308       do
1309         {
1310           if (rel_buffer + filename_len <= rel_buf_p)
1311             return filename;
1312         }
1313       while ((*rel_buf_p++ = *path_p++));
1314
1315       --rel_buf_p;
1316       if (IS_DIR_SEPARATOR (*(rel_buf_p-1)))
1317         *--rel_buf_p = '\0';
1318       return rel_buffer;
1319     }
1320 }
1321 \f
1322 /* Lookup the given filename in the hash table for filenames.  If it is a
1323    new one, then the hash table info pointer will be null.  In this case,
1324    we create a new file_info record to go with the filename, and we initialize
1325    that record with some reasonable values.  */
1326
1327 /* FILENAME was const, but that causes a warning on AIX when calling stat.
1328    That is probably a bug in AIX, but might as well avoid the warning.  */
1329
1330 static file_info *
1331 find_file (filename, do_not_stat)
1332      const char *filename;
1333      int do_not_stat;
1334 {
1335   hash_table_entry *hash_entry_p;
1336
1337   hash_entry_p = lookup (filename_primary, filename);
1338   if (hash_entry_p->fip)
1339     return hash_entry_p->fip;
1340   else
1341     {
1342       struct stat stat_buf;
1343       file_info *file_p = (file_info *) xmalloc (sizeof (file_info));
1344
1345       /* If we cannot get status on any given source file, give a warning
1346          and then just set its time of last modification to infinity.  */
1347
1348       if (do_not_stat)
1349         stat_buf.st_mtime = (time_t) 0;
1350       else
1351         {
1352           if (stat (filename, &stat_buf) == -1)
1353             {
1354               int errno_val = errno;
1355               notice ("%s: %s: can't get status: %s\n",
1356                       pname, shortpath (NULL, filename),
1357                       xstrerror (errno_val));
1358               stat_buf.st_mtime = (time_t) -1;
1359             }
1360         }
1361
1362       hash_entry_p->fip = file_p;
1363       file_p->hash_entry = hash_entry_p;
1364       file_p->defs_decs = NULL;
1365       file_p->mtime = stat_buf.st_mtime;
1366       return file_p;
1367     }
1368 }
1369
1370 /* Generate a fatal error because some part of the aux_info file is
1371    messed up.  */
1372
1373 static void
1374 aux_info_corrupted ()
1375 {
1376   notice ("\n%s: fatal error: aux info file corrupted at line %d\n",
1377           pname, current_aux_info_lineno);
1378   exit (FATAL_EXIT_CODE);
1379 }
1380
1381 /* ??? This comment is vague.  Say what the condition is for.  */
1382 /* Check to see that a condition is true.  This is kind of like an assert.  */
1383
1384 static void
1385 check_aux_info (cond)
1386      int cond;
1387 {
1388   if (! cond)
1389     aux_info_corrupted ();
1390 }
1391
1392 /* Given a pointer to the closing right parenthesis for a particular formals
1393    list (in an aux_info file) find the corresponding left parenthesis and
1394    return a pointer to it.  */
1395
1396 static const char *
1397 find_corresponding_lparen (p)
1398      const char *p;
1399 {
1400   const char *q;
1401   int paren_depth;
1402
1403   for (paren_depth = 1, q = p-1; paren_depth; q--)
1404     {
1405       switch (*q)
1406         {
1407         case ')':
1408           paren_depth++;
1409           break;
1410         case '(':
1411           paren_depth--;
1412           break;
1413         }
1414     }
1415   return ++q;
1416 }
1417 \f
1418 /* Given a line from  an aux info file, and a time at which the aux info
1419    file it came from was created, check to see if the item described in
1420    the line comes from a file which has been modified since the aux info
1421    file was created.  If so, return nonzero, else return zero.  */
1422
1423 static int
1424 referenced_file_is_newer (l, aux_info_mtime)
1425      const char *l;
1426      time_t aux_info_mtime;
1427 {
1428   const char *p;
1429   file_info *fi_p;
1430   char *filename;
1431
1432   check_aux_info (l[0] == '/');
1433   check_aux_info (l[1] == '*');
1434   check_aux_info (l[2] == ' ');
1435
1436   {
1437     const char *filename_start = p = l + 3;
1438
1439     while (*p != ':'
1440 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
1441            || (*p == ':' && *p && *(p+1) && IS_DIR_SEPARATOR (*(p+1)))
1442 #endif
1443            )
1444       p++;
1445     filename = (char *) alloca ((size_t) (p - filename_start) + 1);
1446     strncpy (filename, filename_start, (size_t) (p - filename_start));
1447     filename[p-filename_start] = '\0';
1448   }
1449
1450   /* Call find_file to find the file_info record associated with the file
1451      which contained this particular def or dec item.  Note that this call
1452      may cause a new file_info record to be created if this is the first time
1453      that we have ever known about this particular file.  */
1454
1455   fi_p = find_file (abspath (invocation_filename, filename), 0);
1456
1457   return (fi_p->mtime > aux_info_mtime);
1458 }
1459 \f
1460 /* Given a line of info from the aux_info file, create a new
1461    def_dec_info record to remember all of the important information about
1462    a function definition or declaration.
1463
1464    Link this record onto the list of such records for the particular file in
1465    which it occurred in proper (descending) line number order (for now).
1466
1467    If there is an identical record already on the list for the file, throw
1468    this one away.  Doing so takes care of the (useless and troublesome)
1469    duplicates which are bound to crop up due to multiple inclusions of any
1470    given individual header file.
1471
1472    Finally, link the new def_dec record onto the list of such records
1473    pertaining to this particular function name.  */
1474
1475 static void
1476 save_def_or_dec (l, is_syscalls)
1477      const char *l;
1478      int is_syscalls;
1479 {
1480   const char *p;
1481   const char *semicolon_p;
1482   def_dec_info *def_dec_p = (def_dec_info *) xmalloc (sizeof (def_dec_info));
1483
1484 #ifndef UNPROTOIZE
1485   def_dec_p->written = 0;
1486 #endif /* !defined (UNPROTOIZE) */
1487
1488   /* Start processing the line by picking off 5 pieces of information from
1489      the left hand end of the line.  These are filename, line number,
1490      new/old/implicit flag (new = ANSI prototype format), definition or
1491      declaration flag, and extern/static flag).  */
1492
1493   check_aux_info (l[0] == '/');
1494   check_aux_info (l[1] == '*');
1495   check_aux_info (l[2] == ' ');
1496
1497   {
1498     const char *filename_start = p = l + 3;
1499     char *filename;
1500
1501     while (*p != ':'
1502 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
1503            || (*p == ':' && *p && *(p+1) && IS_DIR_SEPARATOR (*(p+1)))
1504 #endif
1505            )
1506       p++;
1507     filename = (char *) alloca ((size_t) (p - filename_start) + 1);
1508     strncpy (filename, filename_start, (size_t) (p - filename_start));
1509     filename[p-filename_start] = '\0';
1510
1511     /* Call find_file to find the file_info record associated with the file
1512        which contained this particular def or dec item.  Note that this call
1513        may cause a new file_info record to be created if this is the first time
1514        that we have ever known about this particular file.
1515
1516        Note that we started out by forcing all of the base source file names
1517        (i.e. the names of the aux_info files with the .X stripped off) into the
1518        filenames hash table, and we simultaneously setup file_info records for
1519        all of these base file names (even if they may be useless later).
1520        The file_info records for all of these "base" file names (properly)
1521        act as file_info records for the "original" (i.e. un-included) files
1522        which were submitted to gcc for compilation (when the -aux-info
1523        option was used).  */
1524
1525     def_dec_p->file = find_file (abspath (invocation_filename, filename), is_syscalls);
1526   }
1527
1528   {
1529     const char *line_number_start = ++p;
1530     char line_number[10];
1531
1532     while (*p != ':'
1533 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
1534            || (*p == ':' && *p && *(p+1) && IS_DIR_SEPARATOR (*(p+1)))
1535 #endif
1536            )
1537       p++;
1538     strncpy (line_number, line_number_start, (size_t) (p - line_number_start));
1539     line_number[p-line_number_start] = '\0';
1540     def_dec_p->line = atoi (line_number);
1541   }
1542
1543   /* Check that this record describes a new-style, old-style, or implicit
1544      definition or declaration.  */
1545
1546   p++;  /* Skip over the `:'.  */
1547   check_aux_info ((*p == 'N') || (*p == 'O') || (*p == 'I'));
1548
1549   /* Is this a new style (ANSI prototyped) definition or declaration? */
1550
1551   def_dec_p->prototyped = (*p == 'N');
1552
1553 #ifndef UNPROTOIZE
1554
1555   /* Is this an implicit declaration? */
1556
1557   def_dec_p->is_implicit = (*p == 'I');
1558
1559 #endif /* !defined (UNPROTOIZE) */
1560
1561   p++;
1562
1563   check_aux_info ((*p == 'C') || (*p == 'F'));
1564
1565   /* Is this item a function definition (F) or a declaration (C).  Note that
1566      we treat item taken from the syscalls file as though they were function
1567      definitions regardless of what the stuff in the file says.  */
1568
1569   def_dec_p->is_func_def = ((*p++ == 'F') || is_syscalls);
1570
1571 #ifndef UNPROTOIZE
1572   def_dec_p->definition = 0;    /* Fill this in later if protoizing.  */
1573 #endif /* !defined (UNPROTOIZE) */
1574
1575   check_aux_info (*p++ == ' ');
1576   check_aux_info (*p++ == '*');
1577   check_aux_info (*p++ == '/');
1578   check_aux_info (*p++ == ' ');
1579
1580 #ifdef UNPROTOIZE
1581   check_aux_info ((!strncmp (p, "static", 6)) || (!strncmp (p, "extern", 6)));
1582 #else /* !defined (UNPROTOIZE) */
1583   if (!strncmp (p, "static", 6))
1584     def_dec_p->is_static = -1;
1585   else if (!strncmp (p, "extern", 6))
1586     def_dec_p->is_static = 0;
1587   else
1588     check_aux_info (0); /* Didn't find either `extern' or `static'.  */
1589 #endif /* !defined (UNPROTOIZE) */
1590
1591   {
1592     const char *ansi_start = p;
1593
1594     p += 6;     /* Pass over the "static" or "extern".  */
1595
1596     /* We are now past the initial stuff.  Search forward from here to find
1597        the terminating semicolon that should immediately follow the entire
1598        ANSI format function declaration.  */
1599
1600     while (*++p != ';')
1601       continue;
1602
1603     semicolon_p = p;
1604
1605     /* Make a copy of the ansi declaration part of the line from the aux_info
1606        file.  */
1607
1608     def_dec_p->ansi_decl
1609       = dupnstr (ansi_start, (size_t) ((semicolon_p+1) - ansi_start));
1610
1611     /* Backup and point at the final right paren of the final argument list.  */
1612
1613     p--;
1614
1615 #ifndef UNPROTOIZE
1616     def_dec_p->f_list_chain = NULL;
1617 #endif /* !defined (UNPROTOIZE) */
1618
1619     while (p != ansi_start && (p[-1] == ' ' || p[-1] == '\t')) p--;
1620     if (*p != ')')
1621       {
1622         free_def_dec (def_dec_p);
1623         return;
1624       }
1625   }
1626
1627   /* Now isolate a whole set of formal argument lists, one-by-one.  Normally,
1628      there will only be one list to isolate, but there could be more.  */
1629
1630   def_dec_p->f_list_count = 0;
1631
1632   for (;;)
1633     {
1634       const char *left_paren_p = find_corresponding_lparen (p);
1635 #ifndef UNPROTOIZE
1636       {
1637         f_list_chain_item *cip
1638           = (f_list_chain_item *) xmalloc (sizeof (f_list_chain_item));
1639
1640         cip->formals_list
1641           = dupnstr (left_paren_p + 1, (size_t) (p - (left_paren_p+1)));
1642
1643         /* Add the new chain item at the head of the current list.  */
1644
1645         cip->chain_next = def_dec_p->f_list_chain;
1646         def_dec_p->f_list_chain = cip;
1647       }
1648 #endif /* !defined (UNPROTOIZE) */
1649       def_dec_p->f_list_count++;
1650
1651       p = left_paren_p - 2;
1652
1653       /* p must now point either to another right paren, or to the last
1654          character of the name of the function that was declared/defined.
1655          If p points to another right paren, then this indicates that we
1656          are dealing with multiple formals lists.  In that case, there
1657          really should be another right paren preceding this right paren.  */
1658
1659       if (*p != ')')
1660         break;
1661       else
1662         check_aux_info (*--p == ')');
1663     }
1664
1665
1666   {
1667     const char *past_fn = p + 1;
1668
1669     check_aux_info (*past_fn == ' ');
1670
1671     /* Scan leftwards over the identifier that names the function.  */
1672
1673     while (is_id_char (*p))
1674       p--;
1675     p++;
1676
1677     /* p now points to the leftmost character of the function name.  */
1678
1679     {
1680       char *fn_string = (char *) alloca (past_fn - p + 1);
1681
1682       strncpy (fn_string, p, (size_t) (past_fn - p));
1683       fn_string[past_fn-p] = '\0';
1684       def_dec_p->hash_entry = lookup (function_name_primary, fn_string);
1685     }
1686   }
1687
1688   /* Look at all of the defs and decs for this function name that we have
1689      collected so far.  If there is already one which is at the same
1690      line number in the same file, then we can discard this new def_dec_info
1691      record.
1692
1693      As an extra assurance that any such pair of (nominally) identical
1694      function declarations are in fact identical, we also compare the
1695      ansi_decl parts of the lines from the aux_info files just to be on
1696      the safe side.
1697
1698      This comparison will fail if (for instance) the user was playing
1699      messy games with the preprocessor which ultimately causes one
1700      function declaration in one header file to look differently when
1701      that file is included by two (or more) other files.  */
1702
1703   {
1704     const def_dec_info *other;
1705
1706     for (other = def_dec_p->hash_entry->ddip; other; other = other->next_for_func)
1707       {
1708         if (def_dec_p->line == other->line && def_dec_p->file == other->file)
1709           {
1710             if (strcmp (def_dec_p->ansi_decl, other->ansi_decl))
1711               {
1712                 notice ("%s:%d: declaration of function `%s' takes different forms\n",
1713                         def_dec_p->file->hash_entry->symbol,
1714                         def_dec_p->line,
1715                         def_dec_p->hash_entry->symbol);
1716                 exit (FATAL_EXIT_CODE);
1717               }
1718             free_def_dec (def_dec_p);
1719             return;
1720           }
1721       }
1722   }
1723
1724 #ifdef UNPROTOIZE
1725
1726   /* If we are doing unprotoizing, we must now setup the pointers that will
1727      point to the K&R name list and to the K&R argument declarations list.
1728
1729      Note that if this is only a function declaration, then we should not
1730      expect to find any K&R style formals list following the ANSI-style
1731      formals list.  This is because GCC knows that such information is
1732      useless in the case of function declarations (function definitions
1733      are a different story however).
1734
1735      Since we are unprotoizing, we don't need any such lists anyway.
1736      All we plan to do is to delete all characters between ()'s in any
1737      case.  */
1738
1739   def_dec_p->formal_names = NULL;
1740   def_dec_p->formal_decls = NULL;
1741
1742   if (def_dec_p->is_func_def)
1743     {
1744       p = semicolon_p;
1745       check_aux_info (*++p == ' ');
1746       check_aux_info (*++p == '/');
1747       check_aux_info (*++p == '*');
1748       check_aux_info (*++p == ' ');
1749       check_aux_info (*++p == '(');
1750
1751       {
1752         const char *kr_names_start = ++p;   /* Point just inside '('.  */
1753
1754         while (*p++ != ')')
1755           continue;
1756         p--;            /* point to closing right paren */
1757
1758         /* Make a copy of the K&R parameter names list.  */
1759
1760         def_dec_p->formal_names
1761           = dupnstr (kr_names_start, (size_t) (p - kr_names_start));
1762       }
1763
1764       check_aux_info (*++p == ' ');
1765       p++;
1766
1767       /* p now points to the first character of the K&R style declarations
1768          list (if there is one) or to the star-slash combination that ends
1769          the comment in which such lists get embedded.  */
1770
1771       /* Make a copy of the K&R formal decls list and set the def_dec record
1772          to point to it.  */
1773
1774       if (*p == '*')            /* Are there no K&R declarations? */
1775         {
1776           check_aux_info (*++p == '/');
1777           def_dec_p->formal_decls = "";
1778         }
1779       else
1780         {
1781           const char *kr_decls_start = p;
1782
1783           while (p[0] != '*' || p[1] != '/')
1784             p++;
1785           p--;
1786
1787           check_aux_info (*p == ' ');
1788
1789           def_dec_p->formal_decls
1790             = dupnstr (kr_decls_start, (size_t) (p - kr_decls_start));
1791         }
1792
1793       /* Handle a special case.  If we have a function definition marked as
1794          being in "old" style, and if its formal names list is empty, then
1795          it may actually have the string "void" in its real formals list
1796          in the original source code.  Just to make sure, we will get setup
1797          to convert such things anyway.
1798
1799          This kludge only needs to be here because of an insurmountable
1800          problem with generating .X files.  */
1801
1802       if (!def_dec_p->prototyped && !*def_dec_p->formal_names)
1803         def_dec_p->prototyped = 1;
1804     }
1805
1806   /* Since we are unprotoizing, if this item is already in old (K&R) style,
1807      we can just ignore it.  If that is true, throw away the itme now.  */
1808
1809   if (!def_dec_p->prototyped)
1810     {
1811       free_def_dec (def_dec_p);
1812       return;
1813     }
1814
1815 #endif /* defined (UNPROTOIZE) */
1816
1817   /* Add this record to the head of the list of records pertaining to this
1818      particular function name.  */
1819
1820   def_dec_p->next_for_func = def_dec_p->hash_entry->ddip;
1821   def_dec_p->hash_entry->ddip = def_dec_p;
1822
1823   /* Add this new def_dec_info record to the sorted list of def_dec_info
1824      records for this file.  Note that we don't have to worry about duplicates
1825      (caused by multiple inclusions of header files) here because we have
1826      already eliminated duplicates above.  */
1827
1828   if (!def_dec_p->file->defs_decs)
1829     {
1830       def_dec_p->file->defs_decs = def_dec_p;
1831       def_dec_p->next_in_file = NULL;
1832     }
1833   else
1834     {
1835       int line = def_dec_p->line;
1836       const def_dec_info *prev = NULL;
1837       const def_dec_info *curr = def_dec_p->file->defs_decs;
1838       const def_dec_info *next = curr->next_in_file;
1839
1840       while (next && (line < curr->line))
1841         {
1842           prev = curr;
1843           curr = next;
1844           next = next->next_in_file;
1845         }
1846       if (line >= curr->line)
1847         {
1848           def_dec_p->next_in_file = curr;
1849           if (prev)
1850             ((NONCONST def_dec_info *) prev)->next_in_file = def_dec_p;
1851           else
1852             def_dec_p->file->defs_decs = def_dec_p;
1853         }
1854       else      /* assert (next == NULL); */
1855         {
1856           ((NONCONST def_dec_info *) curr)->next_in_file = def_dec_p;
1857           /* assert (next == NULL); */
1858           def_dec_p->next_in_file = next;
1859         }
1860     }
1861 }
1862 \f
1863 /* Set up the vector COMPILE_PARAMS which is the argument list for running GCC.
1864    Also set input_file_name_index and aux_info_file_name_index
1865    to the indices of the slots where the file names should go.  */
1866
1867 /* We initialize the vector by  removing -g, -O, -S, -c, and -o options,
1868    and adding '-aux-info AUXFILE -S  -o /dev/null INFILE' at the end.  */
1869
1870 static void
1871 munge_compile_params (params_list)
1872      const char *params_list;
1873 {
1874   /* Build up the contents in a temporary vector
1875      that is so big that to has to be big enough.  */
1876   const char **temp_params
1877     = (const char **) alloca ((strlen (params_list) + 8) * sizeof (char *));
1878   int param_count = 0;
1879   const char *param;
1880   struct stat st;
1881
1882   temp_params[param_count++] = compiler_file_name;
1883   for (;;)
1884     {
1885       while (ISSPACE ((const unsigned char)*params_list))
1886         params_list++;
1887       if (!*params_list)
1888         break;
1889       param = params_list;
1890       while (*params_list && !ISSPACE ((const unsigned char)*params_list))
1891         params_list++;
1892       if (param[0] != '-')
1893         temp_params[param_count++]
1894           = dupnstr (param, (size_t) (params_list - param));
1895       else
1896         {
1897           switch (param[1])
1898             {
1899             case 'g':
1900             case 'O':
1901             case 'S':
1902             case 'c':
1903               break;            /* Don't copy these.  */
1904             case 'o':
1905               while (ISSPACE ((const unsigned char)*params_list))
1906                 params_list++;
1907               while (*params_list
1908                      && !ISSPACE ((const unsigned char)*params_list))
1909                 params_list++;
1910               break;
1911             default:
1912               temp_params[param_count++]
1913                 = dupnstr (param, (size_t) (params_list - param));
1914             }
1915         }
1916       if (!*params_list)
1917         break;
1918     }
1919   temp_params[param_count++] = "-aux-info";
1920
1921   /* Leave room for the aux-info file name argument.  */
1922   aux_info_file_name_index = param_count;
1923   temp_params[param_count++] = NULL;
1924
1925   temp_params[param_count++] = "-S";
1926   temp_params[param_count++] = "-o";
1927
1928   if ((stat (HOST_BIT_BUCKET, &st) == 0)
1929       && (!S_ISDIR (st.st_mode))
1930       && (access (HOST_BIT_BUCKET, W_OK) == 0))
1931     temp_params[param_count++] = HOST_BIT_BUCKET;
1932   else
1933     /* FIXME: This is hardly likely to be right, if HOST_BIT_BUCKET is not
1934        writable.  But until this is rejigged to use make_temp_file(), this
1935        is the best we can do.  */
1936     temp_params[param_count++] = "/dev/null";
1937
1938   /* Leave room for the input file name argument.  */
1939   input_file_name_index = param_count;
1940   temp_params[param_count++] = NULL;
1941   /* Terminate the list.  */
1942   temp_params[param_count++] = NULL;
1943
1944   /* Make a copy of the compile_params in heap space.  */
1945
1946   compile_params
1947     = (const char **) xmalloc (sizeof (char *) * (param_count+1));
1948   memcpy (compile_params, temp_params, sizeof (char *) * param_count);
1949 }
1950
1951 /* Do a recompilation for the express purpose of generating a new aux_info
1952    file to go with a specific base source file.
1953
1954    The result is a boolean indicating success.  */
1955
1956 static int
1957 gen_aux_info_file (base_filename)
1958      const char *base_filename;
1959 {
1960   if (!input_file_name_index)
1961     munge_compile_params ("");
1962
1963   /* Store the full source file name in the argument vector.  */
1964   compile_params[input_file_name_index] = shortpath (NULL, base_filename);
1965   /* Add .X to source file name to get aux-info file name.  */
1966   compile_params[aux_info_file_name_index] =
1967     concat (compile_params[input_file_name_index], aux_info_suffix, NULL);
1968
1969   if (!quiet_flag)
1970     notice ("%s: compiling `%s'\n",
1971             pname, compile_params[input_file_name_index]);
1972
1973   {
1974     char *errmsg_fmt, *errmsg_arg;
1975     int wait_status, pid;
1976
1977     pid = pexecute (compile_params[0], (char * const *) compile_params,
1978                     pname, NULL, &errmsg_fmt, &errmsg_arg,
1979                     PEXECUTE_FIRST | PEXECUTE_LAST | PEXECUTE_SEARCH);
1980
1981     if (pid == -1)
1982       {
1983         int errno_val = errno;
1984         fprintf (stderr, "%s: ", pname);
1985         fprintf (stderr, errmsg_fmt, errmsg_arg);
1986         fprintf (stderr, ": %s\n", xstrerror (errno_val));
1987         return 0;
1988       }
1989
1990     pid = pwait (pid, &wait_status, 0);
1991     if (pid == -1)
1992       {
1993         notice ("%s: wait: %s\n", pname, xstrerror (errno));
1994         return 0;
1995       }
1996     if (WIFSIGNALED (wait_status))
1997       {
1998         notice ("%s: subprocess got fatal signal %d\n",
1999                 pname, WTERMSIG (wait_status));
2000         return 0;
2001       }
2002     if (WIFEXITED (wait_status))
2003       {
2004         if (WEXITSTATUS (wait_status) != 0)
2005           {
2006             notice ("%s: %s exited with status %d\n",
2007                     pname, compile_params[0], WEXITSTATUS (wait_status));
2008             return 0;
2009           }
2010         return 1;
2011       }
2012     abort ();
2013   }
2014 }
2015 \f
2016 /* Read in all of the information contained in a single aux_info file.
2017    Save all of the important stuff for later.  */
2018
2019 static void
2020 process_aux_info_file (base_source_filename, keep_it, is_syscalls)
2021      const char *base_source_filename;
2022      int keep_it;
2023      int is_syscalls;
2024 {
2025   size_t base_len = strlen (base_source_filename);
2026   char * aux_info_filename
2027     = (char *) alloca (base_len + strlen (aux_info_suffix) + 1);
2028   char *aux_info_base;
2029   char *aux_info_limit;
2030   char *aux_info_relocated_name;
2031   const char *aux_info_second_line;
2032   time_t aux_info_mtime;
2033   size_t aux_info_size;
2034   int must_create;
2035
2036   /* Construct the aux_info filename from the base source filename.  */
2037
2038   strcpy (aux_info_filename, base_source_filename);
2039   strcat (aux_info_filename, aux_info_suffix);
2040
2041   /* Check that the aux_info file exists and is readable.  If it does not
2042      exist, try to create it (once only).  */
2043
2044   /* If file doesn't exist, set must_create.
2045      Likewise if it exists and we can read it but it is obsolete.
2046      Otherwise, report an error.  */
2047   must_create = 0;
2048
2049   /* Come here with must_create set to 1 if file is out of date.  */
2050 start_over: ;
2051
2052   if (access (aux_info_filename, R_OK) == -1)
2053     {
2054       if (errno == ENOENT)
2055         {
2056           if (is_syscalls)
2057             {
2058               notice ("%s: warning: missing SYSCALLS file `%s'\n",
2059                       pname, aux_info_filename);
2060               return;
2061             }
2062           must_create = 1;
2063         }
2064       else
2065         {
2066           int errno_val = errno;
2067           notice ("%s: can't read aux info file `%s': %s\n",
2068                   pname, shortpath (NULL, aux_info_filename),
2069                   xstrerror (errno_val));
2070           errors++;
2071           return;
2072         }
2073     }
2074 #if 0 /* There is code farther down to take care of this.  */
2075   else
2076     {
2077       struct stat s1, s2;
2078       stat (aux_info_file_name, &s1);
2079       stat (base_source_file_name, &s2);
2080       if (s2.st_mtime > s1.st_mtime)
2081         must_create = 1;
2082     }
2083 #endif /* 0 */
2084
2085   /* If we need a .X file, create it, and verify we can read it.  */
2086   if (must_create)
2087     {
2088       if (!gen_aux_info_file (base_source_filename))
2089         {
2090           errors++;
2091           return;
2092         }
2093       if (access (aux_info_filename, R_OK) == -1)
2094         {
2095           int errno_val = errno;
2096           notice ("%s: can't read aux info file `%s': %s\n",
2097                   pname, shortpath (NULL, aux_info_filename),
2098                   xstrerror (errno_val));
2099           errors++;
2100           return;
2101         }
2102     }
2103
2104   {
2105     struct stat stat_buf;
2106
2107     /* Get some status information about this aux_info file.  */
2108
2109     if (stat (aux_info_filename, &stat_buf) == -1)
2110       {
2111         int errno_val = errno;
2112         notice ("%s: can't get status of aux info file `%s': %s\n",
2113                 pname, shortpath (NULL, aux_info_filename),
2114                 xstrerror (errno_val));
2115         errors++;
2116         return;
2117       }
2118
2119     /* Check on whether or not this aux_info file is zero length.  If it is,
2120        then just ignore it and return.  */
2121
2122     if ((aux_info_size = stat_buf.st_size) == 0)
2123       return;
2124
2125     /* Get the date/time of last modification for this aux_info file and
2126        remember it.  We will have to check that any source files that it
2127        contains information about are at least this old or older.  */
2128
2129     aux_info_mtime = stat_buf.st_mtime;
2130
2131     if (!is_syscalls)
2132       {
2133         /* Compare mod time with the .c file; update .X file if obsolete.
2134            The code later on can fail to check the .c file
2135            if it did not directly define any functions.  */
2136
2137         if (stat (base_source_filename, &stat_buf) == -1)
2138           {
2139             int errno_val = errno;
2140             notice ("%s: can't get status of aux info file `%s': %s\n",
2141                     pname, shortpath (NULL, base_source_filename),
2142                     xstrerror (errno_val));
2143             errors++;
2144             return;
2145           }
2146         if (stat_buf.st_mtime > aux_info_mtime)
2147           {
2148             must_create = 1;
2149             goto start_over;
2150           }
2151       }
2152   }
2153
2154   {
2155     int aux_info_file;
2156     int fd_flags;
2157
2158     /* Open the aux_info file.  */
2159
2160     fd_flags = O_RDONLY;
2161 #ifdef O_BINARY
2162     /* Use binary mode to avoid having to deal with different EOL characters.  */
2163     fd_flags |= O_BINARY;
2164 #endif
2165     if ((aux_info_file = open (aux_info_filename, fd_flags, 0444 )) == -1)
2166       {
2167         int errno_val = errno;
2168         notice ("%s: can't open aux info file `%s' for reading: %s\n",
2169                 pname, shortpath (NULL, aux_info_filename),
2170                 xstrerror (errno_val));
2171         return;
2172       }
2173
2174     /* Allocate space to hold the aux_info file in memory.  */
2175
2176     aux_info_base = xmalloc (aux_info_size + 1);
2177     aux_info_limit = aux_info_base + aux_info_size;
2178     *aux_info_limit = '\0';
2179
2180     /* Read the aux_info file into memory.  */
2181
2182     if (safe_read (aux_info_file, aux_info_base, aux_info_size) !=
2183         (int) aux_info_size)
2184       {
2185         int errno_val = errno;
2186         notice ("%s: error reading aux info file `%s': %s\n",
2187                 pname, shortpath (NULL, aux_info_filename),
2188                 xstrerror (errno_val));
2189         free (aux_info_base);
2190         close (aux_info_file);
2191         return;
2192       }
2193
2194     /* Close the aux info file.  */
2195
2196     if (close (aux_info_file))
2197       {
2198         int errno_val = errno;
2199         notice ("%s: error closing aux info file `%s': %s\n",
2200                 pname, shortpath (NULL, aux_info_filename),
2201                 xstrerror (errno_val));
2202         free (aux_info_base);
2203         close (aux_info_file);
2204         return;
2205       }
2206   }
2207
2208   /* Delete the aux_info file (unless requested not to).  If the deletion
2209      fails for some reason, don't even worry about it.  */
2210
2211   if (must_create && !keep_it)
2212     if (unlink (aux_info_filename) == -1)
2213       {
2214         int errno_val = errno;
2215         notice ("%s: can't delete aux info file `%s': %s\n",
2216                 pname, shortpath (NULL, aux_info_filename),
2217                 xstrerror (errno_val));
2218       }
2219
2220   /* Save a pointer into the first line of the aux_info file which
2221      contains the filename of the directory from which the compiler
2222      was invoked when the associated source file was compiled.
2223      This information is used later to help create complete
2224      filenames out of the (potentially) relative filenames in
2225      the aux_info file.  */
2226
2227   {
2228     char *p = aux_info_base;
2229
2230     while (*p != ':'
2231 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
2232            || (*p == ':' && *p && *(p+1) && IS_DIR_SEPARATOR (*(p+1)))
2233 #endif
2234            )
2235       p++;
2236     p++;
2237     while (*p == ' ')
2238       p++;
2239     invocation_filename = p;    /* Save a pointer to first byte of path.  */
2240     while (*p != ' ')
2241       p++;
2242     *p++ = DIR_SEPARATOR;
2243     *p++ = '\0';
2244     while (*p++ != '\n')
2245       continue;
2246     aux_info_second_line = p;
2247     aux_info_relocated_name = 0;
2248     if (! IS_ABSOLUTE_PATH (invocation_filename))
2249       {
2250         /* INVOCATION_FILENAME is relative;
2251            append it to BASE_SOURCE_FILENAME's dir.  */
2252         char *dir_end;
2253         aux_info_relocated_name = xmalloc (base_len + (p-invocation_filename));
2254         strcpy (aux_info_relocated_name, base_source_filename);
2255         dir_end = strrchr (aux_info_relocated_name, DIR_SEPARATOR);
2256 #ifdef DIR_SEPARATOR_2
2257         {
2258           char *slash;
2259
2260           slash = strrchr (dir_end ? dir_end : aux_info_relocated_name,
2261                            DIR_SEPARATOR_2);
2262           if (slash)
2263             dir_end = slash;
2264         }
2265 #endif
2266         if (dir_end)
2267           dir_end++;
2268         else
2269           dir_end = aux_info_relocated_name;
2270         strcpy (dir_end, invocation_filename);
2271         invocation_filename = aux_info_relocated_name;
2272       }
2273   }
2274
2275
2276   {
2277     const char *aux_info_p;
2278
2279     /* Do a pre-pass on the lines in the aux_info file, making sure that all
2280        of the source files referenced in there are at least as old as this
2281        aux_info file itself.  If not, go back and regenerate the aux_info
2282        file anew.  Don't do any of this for the syscalls file.  */
2283
2284     if (!is_syscalls)
2285       {
2286         current_aux_info_lineno = 2;
2287
2288         for (aux_info_p = aux_info_second_line; *aux_info_p; )
2289           {
2290             if (referenced_file_is_newer (aux_info_p, aux_info_mtime))
2291               {
2292                 free (aux_info_base);
2293                 free (aux_info_relocated_name);
2294                 if (keep_it && unlink (aux_info_filename) == -1)
2295                   {
2296                     int errno_val = errno;
2297                     notice ("%s: can't delete file `%s': %s\n",
2298                             pname, shortpath (NULL, aux_info_filename),
2299                             xstrerror (errno_val));
2300                     return;
2301                   }
2302                 must_create = 1;
2303                 goto start_over;
2304               }
2305
2306             /* Skip over the rest of this line to start of next line.  */
2307
2308             while (*aux_info_p != '\n')
2309               aux_info_p++;
2310             aux_info_p++;
2311             current_aux_info_lineno++;
2312           }
2313       }
2314
2315     /* Now do the real pass on the aux_info lines.  Save their information in
2316        the in-core data base.  */
2317
2318     current_aux_info_lineno = 2;
2319
2320     for (aux_info_p = aux_info_second_line; *aux_info_p;)
2321       {
2322         char *unexpanded_line = unexpand_if_needed (aux_info_p);
2323
2324         if (unexpanded_line)
2325           {
2326             save_def_or_dec (unexpanded_line, is_syscalls);
2327             free (unexpanded_line);
2328           }
2329         else
2330           save_def_or_dec (aux_info_p, is_syscalls);
2331
2332         /* Skip over the rest of this line and get to start of next line.  */
2333
2334         while (*aux_info_p != '\n')
2335           aux_info_p++;
2336         aux_info_p++;
2337         current_aux_info_lineno++;
2338       }
2339   }
2340
2341   free (aux_info_base);
2342   free (aux_info_relocated_name);
2343 }
2344 \f
2345 #ifndef UNPROTOIZE
2346
2347 /* Check an individual filename for a .c suffix.  If the filename has this
2348    suffix, rename the file such that its suffix is changed to .C.  This
2349    function implements the -C option.  */
2350
2351 static void
2352 rename_c_file (hp)
2353      const hash_table_entry *hp;
2354 {
2355   const char *filename = hp->symbol;
2356   int last_char_index = strlen (filename) - 1;
2357   char *const new_filename = (char *) alloca (strlen (filename)
2358                                               + strlen (cplus_suffix) + 1);
2359
2360   /* Note that we don't care here if the given file was converted or not.  It
2361      is possible that the given file was *not* converted, simply because there
2362      was nothing in it which actually required conversion.  Even in this case,
2363      we want to do the renaming.  Note that we only rename files with the .c
2364      suffix (except for the syscalls file, which is left alone).  */
2365
2366   if (filename[last_char_index] != 'c' || filename[last_char_index-1] != '.'
2367       || IS_SAME_PATH (syscalls_absolute_filename, filename))
2368     return;
2369
2370   strcpy (new_filename, filename);
2371   strcpy (&new_filename[last_char_index], cplus_suffix);
2372
2373   if (rename (filename, new_filename) == -1)
2374     {
2375       int errno_val = errno;
2376       notice ("%s: warning: can't rename file `%s' to `%s': %s\n",
2377               pname, shortpath (NULL, filename),
2378               shortpath (NULL, new_filename), xstrerror (errno_val));
2379       errors++;
2380       return;
2381     }
2382 }
2383
2384 #endif /* !defined (UNPROTOIZE) */
2385 \f
2386 /* Take the list of definitions and declarations attached to a particular
2387    file_info node and reverse the order of the list.  This should get the
2388    list into an order such that the item with the lowest associated line
2389    number is nearest the head of the list.  When these lists are originally
2390    built, they are in the opposite order.  We want to traverse them in
2391    normal line number order later (i.e. lowest to highest) so reverse the
2392    order here.  */
2393
2394 static void
2395 reverse_def_dec_list (hp)
2396      const hash_table_entry *hp;
2397 {
2398   file_info *file_p = hp->fip;
2399   def_dec_info *prev = NULL;
2400   def_dec_info *current = (def_dec_info *) file_p->defs_decs;
2401
2402   if (!current)
2403     return;                     /* no list to reverse */
2404
2405   prev = current;
2406   if (! (current = (def_dec_info *) current->next_in_file))
2407     return;                     /* can't reverse a single list element */
2408
2409   prev->next_in_file = NULL;
2410
2411   while (current)
2412     {
2413       def_dec_info *next = (def_dec_info *) current->next_in_file;
2414
2415       current->next_in_file = prev;
2416       prev = current;
2417       current = next;
2418     }
2419
2420   file_p->defs_decs = prev;
2421 }
2422
2423 #ifndef UNPROTOIZE
2424
2425 /* Find the (only?) extern definition for a particular function name, starting
2426    from the head of the linked list of entries for the given name.  If we
2427    cannot find an extern definition for the given function name, issue a
2428    warning and scrounge around for the next best thing, i.e. an extern
2429    function declaration with a prototype attached to it.  Note that we only
2430    allow such substitutions for extern declarations and never for static
2431    declarations.  That's because the only reason we allow them at all is
2432    to let un-prototyped function declarations for system-supplied library
2433    functions get their prototypes from our own extra SYSCALLS.c.X file which
2434    contains all of the correct prototypes for system functions.  */
2435
2436 static const def_dec_info *
2437 find_extern_def (head, user)
2438      const def_dec_info *head;
2439      const def_dec_info *user;
2440 {
2441   const def_dec_info *dd_p;
2442   const def_dec_info *extern_def_p = NULL;
2443   int conflict_noted = 0;
2444
2445   /* Don't act too stupid here.  Somebody may try to convert an entire system
2446      in one swell fwoop (rather than one program at a time, as should be done)
2447      and in that case, we may find that there are multiple extern definitions
2448      of a given function name in the entire set of source files that we are
2449      converting.  If however one of these definitions resides in exactly the
2450      same source file as the reference we are trying to satisfy then in that
2451      case it would be stupid for us to fail to realize that this one definition
2452      *must* be the precise one we are looking for.
2453
2454      To make sure that we don't miss an opportunity to make this "same file"
2455      leap of faith, we do a prescan of the list of records relating to the
2456      given function name, and we look (on this first scan) *only* for a
2457      definition of the function which is in the same file as the reference
2458      we are currently trying to satisfy.  */
2459
2460   for (dd_p = head; dd_p; dd_p = dd_p->next_for_func)
2461     if (dd_p->is_func_def && !dd_p->is_static && dd_p->file == user->file)
2462       return dd_p;
2463
2464   /* Now, since we have not found a definition in the same file as the
2465      reference, we scan the list again and consider all possibilities from
2466      all files.  Here we may get conflicts with the things listed in the
2467      SYSCALLS.c.X file, but if that happens it only means that the source
2468      code being converted contains its own definition of a function which
2469      could have been supplied by libc.a.  In such cases, we should avoid
2470      issuing the normal warning, and defer to the definition given in the
2471      user's own code.  */
2472
2473   for (dd_p = head; dd_p; dd_p = dd_p->next_for_func)
2474     if (dd_p->is_func_def && !dd_p->is_static)
2475       {
2476         if (!extern_def_p)      /* Previous definition? */
2477           extern_def_p = dd_p;  /* Remember the first definition found.  */
2478         else
2479           {
2480             /* Ignore definition just found if it came from SYSCALLS.c.X.  */
2481
2482             if (is_syscalls_file (dd_p->file))
2483               continue;
2484
2485             /* Quietly replace the definition previously found with the one
2486                just found if the previous one was from SYSCALLS.c.X.  */
2487
2488             if (is_syscalls_file (extern_def_p->file))
2489               {
2490                 extern_def_p = dd_p;
2491                 continue;
2492               }
2493
2494             /* If we get here, then there is a conflict between two function
2495                declarations for the same function, both of which came from the
2496                user's own code.  */
2497
2498             if (!conflict_noted)        /* first time we noticed? */
2499               {
2500                 conflict_noted = 1;
2501                 notice ("%s: conflicting extern definitions of '%s'\n",
2502                         pname, head->hash_entry->symbol);
2503                 if (!quiet_flag)
2504                   {
2505                     notice ("%s: declarations of '%s' will not be converted\n",
2506                             pname, head->hash_entry->symbol);
2507                     notice ("%s: conflict list for '%s' follows:\n",
2508                             pname, head->hash_entry->symbol);
2509                     fprintf (stderr, "%s:     %s(%d): %s\n",
2510                              pname,
2511                              shortpath (NULL, extern_def_p->file->hash_entry->symbol),
2512                              extern_def_p->line, extern_def_p->ansi_decl);
2513                   }
2514               }
2515             if (!quiet_flag)
2516               fprintf (stderr, "%s:     %s(%d): %s\n",
2517                        pname,
2518                        shortpath (NULL, dd_p->file->hash_entry->symbol),
2519                        dd_p->line, dd_p->ansi_decl);
2520           }
2521       }
2522
2523   /* We want to err on the side of caution, so if we found multiple conflicting
2524      definitions for the same function, treat this as being that same as if we
2525      had found no definitions (i.e. return NULL).  */
2526
2527   if (conflict_noted)
2528     return NULL;
2529
2530   if (!extern_def_p)
2531     {
2532       /* We have no definitions for this function so do the next best thing.
2533          Search for an extern declaration already in prototype form.  */
2534
2535       for (dd_p = head; dd_p; dd_p = dd_p->next_for_func)
2536         if (!dd_p->is_func_def && !dd_p->is_static && dd_p->prototyped)
2537           {
2538             extern_def_p = dd_p;        /* save a pointer to the definition */
2539             if (!quiet_flag)
2540               notice ("%s: warning: using formals list from %s(%d) for function `%s'\n",
2541                       pname,
2542                       shortpath (NULL, dd_p->file->hash_entry->symbol),
2543                       dd_p->line, dd_p->hash_entry->symbol);
2544             break;
2545           }
2546
2547       /* Gripe about unprototyped function declarations that we found no
2548          corresponding definition (or other source of prototype information)
2549          for.
2550
2551          Gripe even if the unprototyped declaration we are worried about
2552          exists in a file in one of the "system" include directories.  We
2553          can gripe about these because we should have at least found a
2554          corresponding (pseudo) definition in the SYSCALLS.c.X file.  If we
2555          didn't, then that means that the SYSCALLS.c.X file is missing some
2556          needed prototypes for this particular system.  That is worth telling
2557          the user about!  */
2558
2559       if (!extern_def_p)
2560         {
2561           const char *file = user->file->hash_entry->symbol;
2562
2563           if (!quiet_flag)
2564             if (in_system_include_dir (file))
2565               {
2566                 /* Why copy this string into `needed' at all?
2567                    Why not just use user->ansi_decl without copying?  */
2568                 char *needed = (char *) alloca (strlen (user->ansi_decl) + 1);
2569                 char *p;
2570
2571                 strcpy (needed, user->ansi_decl);
2572                 p = (NONCONST char *) substr (needed, user->hash_entry->symbol)
2573                     + strlen (user->hash_entry->symbol) + 2;
2574                 /* Avoid having ??? in the string.  */
2575                 *p++ = '?';
2576                 *p++ = '?';
2577                 *p++ = '?';
2578                 strcpy (p, ");");
2579
2580                 notice ("%s: %d: `%s' used but missing from SYSCALLS\n",
2581                         shortpath (NULL, file), user->line,
2582                         needed+7);      /* Don't print "extern " */
2583               }
2584 #if 0
2585             else
2586               notice ("%s: %d: warning: no extern definition for `%s'\n",
2587                       shortpath (NULL, file), user->line,
2588                       user->hash_entry->symbol);
2589 #endif
2590         }
2591     }
2592   return extern_def_p;
2593 }
2594 \f
2595 /* Find the (only?) static definition for a particular function name in a
2596    given file.  Here we get the function-name and the file info indirectly
2597    from the def_dec_info record pointer which is passed in.  */
2598
2599 static const def_dec_info *
2600 find_static_definition (user)
2601      const def_dec_info *user;
2602 {
2603   const def_dec_info *head = user->hash_entry->ddip;
2604   const def_dec_info *dd_p;
2605   int num_static_defs = 0;
2606   const def_dec_info *static_def_p = NULL;
2607
2608   for (dd_p = head; dd_p; dd_p = dd_p->next_for_func)
2609     if (dd_p->is_func_def && dd_p->is_static && (dd_p->file == user->file))
2610       {
2611         static_def_p = dd_p;    /* save a pointer to the definition */
2612         num_static_defs++;
2613       }
2614   if (num_static_defs == 0)
2615     {
2616       if (!quiet_flag)
2617         notice ("%s: warning: no static definition for `%s' in file `%s'\n",
2618                 pname, head->hash_entry->symbol,
2619                 shortpath (NULL, user->file->hash_entry->symbol));
2620     }
2621   else if (num_static_defs > 1)
2622     {
2623       notice ("%s: multiple static defs of `%s' in file `%s'\n",
2624               pname, head->hash_entry->symbol,
2625               shortpath (NULL, user->file->hash_entry->symbol));
2626       return NULL;
2627     }
2628   return static_def_p;
2629 }
2630
2631 /* Find good prototype style formal argument lists for all of the function
2632    declarations which didn't have them before now.
2633
2634    To do this we consider each function name one at a time.  For each function
2635    name, we look at the items on the linked list of def_dec_info records for
2636    that particular name.
2637
2638    Somewhere on this list we should find one (and only one) def_dec_info
2639    record which represents the actual function definition, and this record
2640    should have a nice formal argument list already associated with it.
2641
2642    Thus, all we have to do is to connect up all of the other def_dec_info
2643    records for this particular function name to the special one which has
2644    the full-blown formals list.
2645
2646    Of course it is a little more complicated than just that.  See below for
2647    more details.  */
2648
2649 static void
2650 connect_defs_and_decs (hp)
2651      const hash_table_entry *hp;
2652 {
2653   const def_dec_info *dd_p;
2654   const def_dec_info *extern_def_p = NULL;
2655   int first_extern_reference = 1;
2656
2657   /* Traverse the list of definitions and declarations for this particular
2658      function name.  For each item on the list, if it is a function
2659      definition (either old style or new style) then GCC has already been
2660      kind enough to produce a prototype for us, and it is associated with
2661      the item already, so declare the item as its own associated "definition".
2662
2663      Also, for each item which is only a function declaration, but which
2664      nonetheless has its own prototype already (obviously supplied by the user)
2665      declare the item as its own definition.
2666
2667      Note that when/if there are multiple user-supplied prototypes already
2668      present for multiple declarations of any given function, these multiple
2669      prototypes *should* all match exactly with one another and with the
2670      prototype for the actual function definition.  We don't check for this
2671      here however, since we assume that the compiler must have already done
2672      this consistency checking when it was creating the .X files.  */
2673
2674   for (dd_p = hp->ddip; dd_p; dd_p = dd_p->next_for_func)
2675     if (dd_p->prototyped)
2676       ((NONCONST def_dec_info *) dd_p)->definition = dd_p;
2677
2678   /* Traverse the list of definitions and declarations for this particular
2679      function name.  For each item on the list, if it is an extern function
2680      declaration and if it has no associated definition yet, go try to find
2681      the matching extern definition for the declaration.
2682
2683      When looking for the matching function definition, warn the user if we
2684      fail to find one.
2685
2686      If we find more that one function definition also issue a warning.
2687
2688      Do the search for the matching definition only once per unique function
2689      name (and only when absolutely needed) so that we can avoid putting out
2690      redundant warning messages, and so that we will only put out warning
2691      messages when there is actually a reference (i.e. a declaration) for
2692      which we need to find a matching definition.  */
2693
2694   for (dd_p = hp->ddip; dd_p; dd_p = dd_p->next_for_func)
2695     if (!dd_p->is_func_def && !dd_p->is_static && !dd_p->definition)
2696       {
2697         if (first_extern_reference)
2698           {
2699             extern_def_p = find_extern_def (hp->ddip, dd_p);
2700             first_extern_reference = 0;
2701           }
2702         ((NONCONST def_dec_info *) dd_p)->definition = extern_def_p;
2703       }
2704
2705   /* Traverse the list of definitions and declarations for this particular
2706      function name.  For each item on the list, if it is a static function
2707      declaration and if it has no associated definition yet, go try to find
2708      the matching static definition for the declaration within the same file.
2709
2710      When looking for the matching function definition, warn the user if we
2711      fail to find one in the same file with the declaration, and refuse to
2712      convert this kind of cross-file static function declaration.  After all,
2713      this is stupid practice and should be discouraged.
2714
2715      We don't have to worry about the possibility that there is more than one
2716      matching function definition in the given file because that would have
2717      been flagged as an error by the compiler.
2718
2719      Do the search for the matching definition only once per unique
2720      function-name/source-file pair (and only when absolutely needed) so that
2721      we can avoid putting out redundant warning messages, and so that we will
2722      only put out warning messages when there is actually a reference (i.e. a
2723      declaration) for which we actually need to find a matching definition.  */
2724
2725   for (dd_p = hp->ddip; dd_p; dd_p = dd_p->next_for_func)
2726     if (!dd_p->is_func_def && dd_p->is_static && !dd_p->definition)
2727       {
2728         const def_dec_info *dd_p2;
2729         const def_dec_info *static_def;
2730
2731         /* We have now found a single static declaration for which we need to
2732            find a matching definition.  We want to minimize the work (and the
2733            number of warnings), so we will find an appropriate (matching)
2734            static definition for this declaration, and then distribute it
2735            (as the definition for) any and all other static declarations
2736            for this function name which occur within the same file, and which
2737            do not already have definitions.
2738
2739            Note that a trick is used here to prevent subsequent attempts to
2740            call find_static_definition for a given function-name & file
2741            if the first such call returns NULL.  Essentially, we convert
2742            these NULL return values to -1, and put the -1 into the definition
2743            field for each other static declaration from the same file which
2744            does not already have an associated definition.
2745            This makes these other static declarations look like they are
2746            actually defined already when the outer loop here revisits them
2747            later on.  Thus, the outer loop will skip over them.  Later, we
2748            turn the -1's back to NULL's.  */
2749
2750         ((NONCONST def_dec_info *) dd_p)->definition =
2751           (static_def = find_static_definition (dd_p))
2752           ? static_def
2753           : (const def_dec_info *) -1;
2754
2755         for (dd_p2 = dd_p->next_for_func; dd_p2; dd_p2 = dd_p2->next_for_func)
2756           if (!dd_p2->is_func_def && dd_p2->is_static
2757               && !dd_p2->definition && (dd_p2->file == dd_p->file))
2758             ((NONCONST def_dec_info *) dd_p2)->definition = dd_p->definition;
2759       }
2760
2761   /* Convert any dummy (-1) definitions we created in the step above back to
2762      NULL's (as they should be).  */
2763
2764   for (dd_p = hp->ddip; dd_p; dd_p = dd_p->next_for_func)
2765     if (dd_p->definition == (def_dec_info *) -1)
2766       ((NONCONST def_dec_info *) dd_p)->definition = NULL;
2767 }
2768
2769 #endif /* !defined (UNPROTOIZE) */
2770
2771 /* Give a pointer into the clean text buffer, return a number which is the
2772    original source line number that the given pointer points into.  */
2773
2774 static int
2775 identify_lineno (clean_p)
2776      const char *clean_p;
2777 {
2778   int line_num = 1;
2779   const char *scan_p;
2780
2781   for (scan_p = clean_text_base; scan_p <= clean_p; scan_p++)
2782     if (*scan_p == '\n')
2783       line_num++;
2784   return line_num;
2785 }
2786
2787 /* Issue an error message and give up on doing this particular edit.  */
2788
2789 static void
2790 declare_source_confusing (clean_p)
2791      const char *clean_p;
2792 {
2793   if (!quiet_flag)
2794     {
2795       if (clean_p == 0)
2796         notice ("%s: %d: warning: source too confusing\n",
2797                 shortpath (NULL, convert_filename), last_known_line_number);
2798       else
2799         notice ("%s: %d: warning: source too confusing\n",
2800                 shortpath (NULL, convert_filename),
2801                 identify_lineno (clean_p));
2802     }
2803   longjmp (source_confusion_recovery, 1);
2804 }
2805
2806 /* Check that a condition which is expected to be true in the original source
2807    code is in fact true.  If not, issue an error message and give up on
2808    converting this particular source file.  */
2809
2810 static void
2811 check_source (cond, clean_p)
2812      int cond;
2813      const char *clean_p;
2814 {
2815   if (!cond)
2816     declare_source_confusing (clean_p);
2817 }
2818
2819 /* If we think of the in-core cleaned text buffer as a memory mapped
2820    file (with the variable last_known_line_start acting as sort of a
2821    file pointer) then we can imagine doing "seeks" on the buffer.  The
2822    following routine implements a kind of "seek" operation for the in-core
2823    (cleaned) copy of the source file.  When finished, it returns a pointer to
2824    the start of a given (numbered) line in the cleaned text buffer.
2825
2826    Note that protoize only has to "seek" in the forward direction on the
2827    in-core cleaned text file buffers, and it never needs to back up.
2828
2829    This routine is made a little bit faster by remembering the line number
2830    (and pointer value) supplied (and returned) from the previous "seek".
2831    This prevents us from always having to start all over back at the top
2832    of the in-core cleaned buffer again.  */
2833
2834 static const char *
2835 seek_to_line (n)
2836      int n;
2837 {
2838   if (n < last_known_line_number)
2839     abort ();
2840
2841   while (n > last_known_line_number)
2842     {
2843       while (*last_known_line_start != '\n')
2844         check_source (++last_known_line_start < clean_text_limit, 0);
2845       last_known_line_start++;
2846       last_known_line_number++;
2847     }
2848   return last_known_line_start;
2849 }
2850
2851 /* Given a pointer to a character in the cleaned text buffer, return a pointer
2852    to the next non-whitespace character which follows it.  */
2853
2854 static const char *
2855 forward_to_next_token_char (ptr)
2856      const char *ptr;
2857 {
2858   for (++ptr; ISSPACE ((const unsigned char)*ptr);
2859        check_source (++ptr < clean_text_limit, 0))
2860     continue;
2861   return ptr;
2862 }
2863
2864 /* Copy a chunk of text of length `len' and starting at `str' to the current
2865    output buffer.  Note that all attempts to add stuff to the current output
2866    buffer ultimately go through here.  */
2867
2868 static void
2869 output_bytes (str, len)
2870      const char *str;
2871      size_t len;
2872 {
2873   if ((repl_write_ptr + 1) + len >= repl_text_limit)
2874     {
2875       size_t new_size = (repl_text_limit - repl_text_base) << 1;
2876       char *new_buf = (char *) xrealloc (repl_text_base, new_size);
2877
2878       repl_write_ptr = new_buf + (repl_write_ptr - repl_text_base);
2879       repl_text_base = new_buf;
2880       repl_text_limit = new_buf + new_size;
2881     }
2882   memcpy (repl_write_ptr + 1, str, len);
2883   repl_write_ptr += len;
2884 }
2885
2886 /* Copy all bytes (except the trailing null) of a null terminated string to
2887    the current output buffer.  */
2888
2889 static void
2890 output_string (str)
2891      const char *str;
2892 {
2893   output_bytes (str, strlen (str));
2894 }
2895
2896 /* Copy some characters from the original text buffer to the current output
2897    buffer.
2898
2899    This routine takes a pointer argument `p' which is assumed to be a pointer
2900    into the cleaned text buffer.  The bytes which are copied are the `original'
2901    equivalents for the set of bytes between the last value of `clean_read_ptr'
2902    and the argument value `p'.
2903
2904    The set of bytes copied however, comes *not* from the cleaned text buffer,
2905    but rather from the direct counterparts of these bytes within the original
2906    text buffer.
2907
2908    Thus, when this function is called, some bytes from the original text
2909    buffer (which may include original comments and preprocessing directives)
2910    will be copied into the  output buffer.
2911
2912    Note that the request implied when this routine is called includes the
2913    byte pointed to by the argument pointer `p'.  */
2914
2915 static void
2916 output_up_to (p)
2917      const char *p;
2918 {
2919   size_t copy_length = (size_t) (p - clean_read_ptr);
2920   const char *copy_start = orig_text_base+(clean_read_ptr-clean_text_base)+1;
2921
2922   if (copy_length == 0)
2923     return;
2924
2925   output_bytes (copy_start, copy_length);
2926   clean_read_ptr = p;
2927 }
2928
2929 /* Given a pointer to a def_dec_info record which represents some form of
2930    definition of a function (perhaps a real definition, or in lieu of that
2931    perhaps just a declaration with a full prototype) return true if this
2932    function is one which we should avoid converting.  Return false
2933    otherwise.  */
2934
2935 static int
2936 other_variable_style_function (ansi_header)
2937      const char *ansi_header;
2938 {
2939 #ifdef UNPROTOIZE
2940
2941   /* See if we have a stdarg function, or a function which has stdarg style
2942      parameters or a stdarg style return type.  */
2943
2944   return substr (ansi_header, "...") != 0;
2945
2946 #else /* !defined (UNPROTOIZE) */
2947
2948   /* See if we have a varargs function, or a function which has varargs style
2949      parameters or a varargs style return type.  */
2950
2951   const char *p;
2952   int len = strlen (varargs_style_indicator);
2953
2954   for (p = ansi_header; p; )
2955     {
2956       const char *candidate;
2957
2958       if ((candidate = substr (p, varargs_style_indicator)) == 0)
2959         return 0;
2960       else
2961         if (!is_id_char (candidate[-1]) && !is_id_char (candidate[len]))
2962           return 1;
2963         else
2964           p = candidate + 1;
2965     }
2966   return 0;
2967 #endif /* !defined (UNPROTOIZE) */
2968 }
2969
2970 /* Do the editing operation specifically for a function "declaration".  Note
2971    that editing for function "definitions" are handled in a separate routine
2972    below.  */
2973
2974 static void
2975 edit_fn_declaration (def_dec_p, clean_text_p)
2976      const def_dec_info *def_dec_p;
2977      const char *volatile clean_text_p;
2978 {
2979   const char *start_formals;
2980   const char *end_formals;
2981   const char *function_to_edit = def_dec_p->hash_entry->symbol;
2982   size_t func_name_len = strlen (function_to_edit);
2983   const char *end_of_fn_name;
2984
2985 #ifndef UNPROTOIZE
2986
2987   const f_list_chain_item *this_f_list_chain_item;
2988   const def_dec_info *definition = def_dec_p->definition;
2989
2990   /* If we are protoizing, and if we found no corresponding definition for
2991      this particular function declaration, then just leave this declaration
2992      exactly as it is.  */
2993
2994   if (!definition)
2995     return;
2996
2997   /* If we are protoizing, and if the corresponding definition that we found
2998      for this particular function declaration defined an old style varargs
2999      function, then we want to issue a warning and just leave this function
3000      declaration unconverted.  */
3001
3002   if (other_variable_style_function (definition->ansi_decl))
3003     {
3004       if (!quiet_flag)
3005         notice ("%s: %d: warning: varargs function declaration not converted\n",
3006                 shortpath (NULL, def_dec_p->file->hash_entry->symbol),
3007                 def_dec_p->line);
3008       return;
3009     }
3010
3011 #endif /* !defined (UNPROTOIZE) */
3012
3013   /* Setup here to recover from confusing source code detected during this
3014      particular "edit".  */
3015
3016   save_pointers ();
3017   if (setjmp (source_confusion_recovery))
3018     {
3019       restore_pointers ();
3020       notice ("%s: declaration of function `%s' not converted\n",
3021               pname, function_to_edit);
3022       return;
3023     }
3024
3025   /* We are editing a function declaration.  The line number we did a seek to
3026      contains the comma or semicolon which follows the declaration.  Our job
3027      now is to scan backwards looking for the function name.  This name *must*
3028      be followed by open paren (ignoring whitespace, of course).  We need to
3029      replace everything between that open paren and the corresponding closing
3030      paren.  If we are protoizing, we need to insert the prototype-style
3031      formals lists.  If we are unprotoizing, we need to just delete everything
3032      between the pairs of opening and closing parens.  */
3033
3034   /* First move up to the end of the line.  */
3035
3036   while (*clean_text_p != '\n')
3037     check_source (++clean_text_p < clean_text_limit, 0);
3038   clean_text_p--;  /* Point to just before the newline character.  */
3039
3040   /* Now we can scan backwards for the function name.  */
3041
3042   do
3043     {
3044       for (;;)
3045         {
3046           /* Scan leftwards until we find some character which can be
3047              part of an identifier.  */
3048
3049           while (!is_id_char (*clean_text_p))
3050             check_source (--clean_text_p > clean_read_ptr, 0);
3051
3052           /* Scan backwards until we find a char that cannot be part of an
3053              identifier.  */
3054
3055           while (is_id_char (*clean_text_p))
3056             check_source (--clean_text_p > clean_read_ptr, 0);
3057
3058           /* Having found an "id break", see if the following id is the one
3059              that we are looking for.  If so, then exit from this loop.  */
3060
3061           if (!strncmp (clean_text_p+1, function_to_edit, func_name_len))
3062             {
3063               char ch = *(clean_text_p + 1 + func_name_len);
3064
3065               /* Must also check to see that the name in the source text
3066                  ends where it should (in order to prevent bogus matches
3067                  on similar but longer identifiers.  */
3068
3069               if (! is_id_char (ch))
3070                 break;                  /* exit from loop */
3071             }
3072         }
3073
3074       /* We have now found the first perfect match for the function name in
3075          our backward search.  This may or may not be the actual function
3076          name at the start of the actual function declaration (i.e. we could
3077          have easily been mislead).  We will try to avoid getting fooled too
3078          often by looking forward for the open paren which should follow the
3079          identifier we just found.  We ignore whitespace while hunting.  If
3080          the next non-whitespace byte we see is *not* an open left paren,
3081          then we must assume that we have been fooled and we start over
3082          again accordingly.  Note that there is no guarantee, that even if
3083          we do see the open paren, that we are in the right place.
3084          Programmers do the strangest things sometimes!  */
3085
3086       end_of_fn_name = clean_text_p + strlen (def_dec_p->hash_entry->symbol);
3087       start_formals = forward_to_next_token_char (end_of_fn_name);
3088     }
3089   while (*start_formals != '(');
3090
3091   /* start_of_formals now points to the opening left paren which immediately
3092      follows the name of the function.  */
3093
3094   /* Note that there may be several formals lists which need to be modified
3095      due to the possibility that the return type of this function is a
3096      pointer-to-function type.  If there are several formals lists, we
3097      convert them in left-to-right order here.  */
3098
3099 #ifndef UNPROTOIZE
3100   this_f_list_chain_item = definition->f_list_chain;
3101 #endif /* !defined (UNPROTOIZE) */
3102
3103   for (;;)
3104     {
3105       {
3106         int depth;
3107
3108         end_formals = start_formals + 1;
3109         depth = 1;
3110         for (; depth; check_source (++end_formals < clean_text_limit, 0))
3111           {
3112             switch (*end_formals)
3113               {
3114               case '(':
3115                 depth++;
3116                 break;
3117               case ')':
3118                 depth--;
3119                 break;
3120               }
3121           }
3122         end_formals--;
3123       }
3124
3125       /* end_formals now points to the closing right paren of the formals
3126          list whose left paren is pointed to by start_formals.  */
3127
3128       /* Now, if we are protoizing, we insert the new ANSI-style formals list
3129          attached to the associated definition of this function.  If however
3130          we are unprotoizing, then we simply delete any formals list which
3131          may be present.  */
3132
3133       output_up_to (start_formals);
3134 #ifndef UNPROTOIZE
3135       if (this_f_list_chain_item)
3136         {
3137           output_string (this_f_list_chain_item->formals_list);
3138           this_f_list_chain_item = this_f_list_chain_item->chain_next;
3139         }
3140       else
3141         {
3142           if (!quiet_flag)
3143             notice ("%s: warning: too many parameter lists in declaration of `%s'\n",
3144                     pname, def_dec_p->hash_entry->symbol);
3145           check_source (0, end_formals);  /* leave the declaration intact */
3146         }
3147 #endif /* !defined (UNPROTOIZE) */
3148       clean_read_ptr = end_formals - 1;
3149
3150       /* Now see if it looks like there may be another formals list associated
3151          with the function declaration that we are converting (following the
3152          formals list that we just converted.  */
3153
3154       {
3155         const char *another_r_paren = forward_to_next_token_char (end_formals);
3156
3157         if ((*another_r_paren != ')')
3158             || (*(start_formals = forward_to_next_token_char (another_r_paren)) != '('))
3159           {
3160 #ifndef UNPROTOIZE
3161             if (this_f_list_chain_item)
3162               {
3163                 if (!quiet_flag)
3164                   notice ("\n%s: warning: too few parameter lists in declaration of `%s'\n",
3165                           pname, def_dec_p->hash_entry->symbol);
3166                 check_source (0, start_formals); /* leave the decl intact */
3167               }
3168 #endif /* !defined (UNPROTOIZE) */
3169             break;
3170
3171           }
3172       }
3173
3174       /* There does appear to be yet another formals list, so loop around
3175          again, and convert it also.  */
3176     }
3177 }
3178
3179 /* Edit a whole group of formals lists, starting with the rightmost one
3180    from some set of formals lists.  This routine is called once (from the
3181    outside) for each function declaration which is converted.  It is
3182    recursive however, and it calls itself once for each remaining formal
3183    list that lies to the left of the one it was originally called to work
3184    on.  Thus, a whole set gets done in right-to-left order.
3185
3186    This routine returns nonzero if it thinks that it should not be trying
3187    to convert this particular function definition (because the name of the
3188    function doesn't match the one expected).  */
3189
3190 static int
3191 edit_formals_lists (end_formals, f_list_count, def_dec_p)
3192      const char *end_formals;
3193      unsigned int f_list_count;
3194      const def_dec_info *def_dec_p;
3195 {
3196   const char *start_formals;
3197   int depth;
3198
3199   start_formals = end_formals - 1;
3200   depth = 1;
3201   for (; depth; check_source (--start_formals > clean_read_ptr, 0))
3202     {
3203       switch (*start_formals)
3204         {
3205         case '(':
3206           depth--;
3207           break;
3208         case ')':
3209           depth++;
3210           break;
3211         }
3212     }
3213   start_formals++;
3214
3215   /* start_formals now points to the opening left paren of the formals list.  */
3216
3217   f_list_count--;
3218
3219   if (f_list_count)
3220     {
3221       const char *next_end;
3222
3223       /* There should be more formal lists to the left of here.  */
3224
3225       next_end = start_formals - 1;
3226       check_source (next_end > clean_read_ptr, 0);
3227       while (ISSPACE ((const unsigned char)*next_end))
3228         check_source (--next_end > clean_read_ptr, 0);
3229       check_source (*next_end == ')', next_end);
3230       check_source (--next_end > clean_read_ptr, 0);
3231       check_source (*next_end == ')', next_end);
3232       if (edit_formals_lists (next_end, f_list_count, def_dec_p))
3233         return 1;
3234     }
3235
3236   /* Check that the function name in the header we are working on is the same
3237      as the one we would expect to find.  If not, issue a warning and return
3238      nonzero.  */
3239
3240   if (f_list_count == 0)
3241     {
3242       const char *expected = def_dec_p->hash_entry->symbol;
3243       const char *func_name_start;
3244       const char *func_name_limit;
3245       size_t func_name_len;
3246
3247       for (func_name_limit = start_formals-1;
3248            ISSPACE ((const unsigned char)*func_name_limit); )
3249         check_source (--func_name_limit > clean_read_ptr, 0);
3250
3251       for (func_name_start = func_name_limit++;
3252            is_id_char (*func_name_start);
3253            func_name_start--)
3254         check_source (func_name_start > clean_read_ptr, 0);
3255       func_name_start++;
3256       func_name_len = func_name_limit - func_name_start;
3257       if (func_name_len == 0)
3258         check_source (0, func_name_start);
3259       if (func_name_len != strlen (expected)
3260           || strncmp (func_name_start, expected, func_name_len))
3261         {
3262           notice ("%s: %d: warning: found `%s' but expected `%s'\n",
3263                   shortpath (NULL, def_dec_p->file->hash_entry->symbol),
3264                   identify_lineno (func_name_start),
3265                   dupnstr (func_name_start, func_name_len),
3266                   expected);
3267           return 1;
3268         }
3269     }
3270
3271   output_up_to (start_formals);
3272
3273 #ifdef UNPROTOIZE
3274   if (f_list_count == 0)
3275     output_string (def_dec_p->formal_names);
3276 #else /* !defined (UNPROTOIZE) */
3277   {
3278     unsigned f_list_depth;
3279     const f_list_chain_item *flci_p = def_dec_p->f_list_chain;
3280
3281     /* At this point, the current value of f_list count says how many
3282        links we have to follow through the f_list_chain to get to the
3283        particular formals list that we need to output next.  */
3284
3285     for (f_list_depth = 0; f_list_depth < f_list_count; f_list_depth++)
3286       flci_p = flci_p->chain_next;
3287     output_string (flci_p->formals_list);
3288   }
3289 #endif /* !defined (UNPROTOIZE) */
3290
3291   clean_read_ptr = end_formals - 1;
3292   return 0;
3293 }
3294
3295 /* Given a pointer to a byte in the clean text buffer which points to
3296    the beginning of a line that contains a "follower" token for a
3297    function definition header, do whatever is necessary to find the
3298    right closing paren for the rightmost formals list of the function
3299    definition header.  */
3300
3301 static const char *
3302 find_rightmost_formals_list (clean_text_p)
3303      const char *clean_text_p;
3304 {
3305   const char *end_formals;
3306
3307   /* We are editing a function definition.  The line number we did a seek
3308      to contains the first token which immediately follows the entire set of
3309      formals lists which are part of this particular function definition
3310      header.
3311
3312      Our job now is to scan leftwards in the clean text looking for the
3313      right-paren which is at the end of the function header's rightmost
3314      formals list.
3315
3316      If we ignore whitespace, this right paren should be the first one we
3317      see which is (ignoring whitespace) immediately followed either by the
3318      open curly-brace beginning the function body or by an alphabetic
3319      character (in the case where the function definition is in old (K&R)
3320      style and there are some declarations of formal parameters).  */
3321
3322    /* It is possible that the right paren we are looking for is on the
3323       current line (together with its following token).  Just in case that
3324       might be true, we start out here by skipping down to the right end of
3325       the current line before starting our scan.  */
3326
3327   for (end_formals = clean_text_p; *end_formals != '\n'; end_formals++)
3328     continue;
3329   end_formals--;
3330
3331 #ifdef UNPROTOIZE
3332
3333   /* Now scan backwards while looking for the right end of the rightmost
3334      formals list associated with this function definition.  */
3335
3336   {
3337     char ch;
3338     const char *l_brace_p;
3339
3340     /* Look leftward and try to find a right-paren.  */
3341
3342     while (*end_formals != ')')
3343       {
3344         if (ISSPACE ((unsigned char)*end_formals))
3345           while (ISSPACE ((unsigned char)*end_formals))
3346             check_source (--end_formals > clean_read_ptr, 0);
3347         else
3348           check_source (--end_formals > clean_read_ptr, 0);
3349       }
3350
3351     ch = *(l_brace_p = forward_to_next_token_char (end_formals));
3352     /* Since we are unprotoizing an ANSI-style (prototyped) function
3353        definition, there had better not be anything (except whitespace)
3354        between the end of the ANSI formals list and the beginning of the
3355        function body (i.e. the '{').  */
3356
3357     check_source (ch == '{', l_brace_p);
3358   }
3359
3360 #else /* !defined (UNPROTOIZE) */
3361
3362   /* Now scan backwards while looking for the right end of the rightmost
3363      formals list associated with this function definition.  */
3364
3365   while (1)
3366     {
3367       char ch;
3368       const char *l_brace_p;
3369
3370       /* Look leftward and try to find a right-paren.  */
3371
3372       while (*end_formals != ')')
3373         {
3374           if (ISSPACE ((const unsigned char)*end_formals))
3375             while (ISSPACE ((const unsigned char)*end_formals))
3376               check_source (--end_formals > clean_read_ptr, 0);
3377           else
3378             check_source (--end_formals > clean_read_ptr, 0);
3379         }
3380
3381       ch = *(l_brace_p = forward_to_next_token_char (end_formals));
3382
3383       /* Since it is possible that we found a right paren before the starting
3384          '{' of the body which IS NOT the one at the end of the real K&R
3385          formals list (say for instance, we found one embedded inside one of
3386          the old K&R formal parameter declarations) we have to check to be
3387          sure that this is in fact the right paren that we were looking for.
3388
3389          The one we were looking for *must* be followed by either a '{' or
3390          by an alphabetic character, while others *cannot* validly be followed
3391          by such characters.  */
3392
3393       if ((ch == '{') || ISALPHA ((unsigned char) ch))
3394         break;
3395
3396       /* At this point, we have found a right paren, but we know that it is
3397          not the one we were looking for, so backup one character and keep
3398          looking.  */
3399
3400       check_source (--end_formals > clean_read_ptr, 0);
3401     }
3402
3403 #endif /* !defined (UNPROTOIZE) */
3404
3405   return end_formals;
3406 }
3407
3408 #ifndef UNPROTOIZE
3409
3410 /* Insert into the output file a totally new declaration for a function
3411    which (up until now) was being called from within the current block
3412    without having been declared at any point such that the declaration
3413    was visible (i.e. in scope) at the point of the call.
3414
3415    We need to add in explicit declarations for all such function calls
3416    in order to get the full benefit of prototype-based function call
3417    parameter type checking.  */
3418
3419 static void
3420 add_local_decl (def_dec_p, clean_text_p)
3421      const def_dec_info *def_dec_p;
3422      const char *clean_text_p;
3423 {
3424   const char *start_of_block;
3425   const char *function_to_edit = def_dec_p->hash_entry->symbol;
3426
3427   /* Don't insert new local explicit declarations unless explicitly requested
3428      to do so.  */
3429
3430   if (!local_flag)
3431     return;
3432
3433   /* Setup here to recover from confusing source code detected during this
3434      particular "edit".  */
3435
3436   save_pointers ();
3437   if (setjmp (source_confusion_recovery))
3438     {
3439       restore_pointers ();
3440       notice ("%s: local declaration for function `%s' not inserted\n",
3441               pname, function_to_edit);
3442       return;
3443     }
3444
3445   /* We have already done a seek to the start of the line which should
3446      contain *the* open curly brace which begins the block in which we need
3447      to insert an explicit function declaration (to replace the implicit one).
3448
3449      Now we scan that line, starting from the left, until we find the
3450      open curly brace we are looking for.  Note that there may actually be
3451      multiple open curly braces on the given line, but we will be happy
3452      with the leftmost one no matter what.  */
3453
3454   start_of_block = clean_text_p;
3455   while (*start_of_block != '{' && *start_of_block != '\n')
3456     check_source (++start_of_block < clean_text_limit, 0);
3457
3458   /* Note that the line from the original source could possibly
3459      contain *no* open curly braces!  This happens if the line contains
3460      a macro call which expands into a chunk of text which includes a
3461      block (and that block's associated open and close curly braces).
3462      In cases like this, we give up, issue a warning, and do nothing.  */
3463
3464   if (*start_of_block != '{')
3465     {
3466       if (!quiet_flag)
3467         notice ("\n%s: %d: warning: can't add declaration of `%s' into macro call\n",
3468           def_dec_p->file->hash_entry->symbol, def_dec_p->line,
3469           def_dec_p->hash_entry->symbol);
3470       return;
3471     }
3472
3473   /* Figure out what a nice (pretty) indentation would be for the new
3474      declaration we are adding.  In order to do this, we must scan forward
3475      from the '{' until we find the first line which starts with some
3476      non-whitespace characters (i.e. real "token" material).  */
3477
3478   {
3479     const char *ep = forward_to_next_token_char (start_of_block) - 1;
3480     const char *sp;
3481
3482     /* Now we have ep pointing at the rightmost byte of some existing indent
3483        stuff.  At least that is the hope.
3484
3485        We can now just scan backwards and find the left end of the existing
3486        indentation string, and then copy it to the output buffer.  */
3487
3488     for (sp = ep; ISSPACE ((const unsigned char)*sp) && *sp != '\n'; sp--)
3489       continue;
3490
3491     /* Now write out the open { which began this block, and any following
3492        trash up to and including the last byte of the existing indent that
3493        we just found.  */
3494
3495     output_up_to (ep);
3496
3497     /* Now we go ahead and insert the new declaration at this point.
3498
3499        If the definition of the given function is in the same file that we
3500        are currently editing, and if its full ANSI declaration normally
3501        would start with the keyword `extern', suppress the `extern'.  */
3502
3503     {
3504       const char *decl = def_dec_p->definition->ansi_decl;
3505
3506       if ((*decl == 'e') && (def_dec_p->file == def_dec_p->definition->file))
3507         decl += 7;
3508       output_string (decl);
3509     }
3510
3511     /* Finally, write out a new indent string, just like the preceding one
3512        that we found.  This will typically include a newline as the first
3513        character of the indent string.  */
3514
3515     output_bytes (sp, (size_t) (ep - sp) + 1);
3516   }
3517 }
3518
3519 /* Given a pointer to a file_info record, and a pointer to the beginning
3520    of a line (in the clean text buffer) which is assumed to contain the
3521    first "follower" token for the first function definition header in the
3522    given file, find a good place to insert some new global function
3523    declarations (which will replace scattered and imprecise implicit ones)
3524    and then insert the new explicit declaration at that point in the file.  */
3525
3526 static void
3527 add_global_decls (file_p, clean_text_p)
3528      const file_info *file_p;
3529      const char *clean_text_p;
3530 {
3531   const def_dec_info *dd_p;
3532   const char *scan_p;
3533
3534   /* Setup here to recover from confusing source code detected during this
3535      particular "edit".  */
3536
3537   save_pointers ();
3538   if (setjmp (source_confusion_recovery))
3539     {
3540       restore_pointers ();
3541       notice ("%s: global declarations for file `%s' not inserted\n",
3542               pname, shortpath (NULL, file_p->hash_entry->symbol));
3543       return;
3544     }
3545
3546   /* Start by finding a good location for adding the new explicit function
3547      declarations.  To do this, we scan backwards, ignoring whitespace
3548      and comments and other junk until we find either a semicolon, or until
3549      we hit the beginning of the file.  */
3550
3551   scan_p = find_rightmost_formals_list (clean_text_p);
3552   for (;; --scan_p)
3553     {
3554       if (scan_p < clean_text_base)
3555         break;
3556       check_source (scan_p > clean_read_ptr, 0);
3557       if (*scan_p == ';')
3558         break;
3559     }
3560
3561   /* scan_p now points either to a semicolon, or to just before the start
3562      of the whole file.  */
3563
3564   /* Now scan forward for the first non-whitespace character.  In theory,
3565      this should be the first character of the following function definition
3566      header.  We will put in the added declarations just prior to that.  */
3567
3568   scan_p++;
3569   while (ISSPACE ((const unsigned char)*scan_p))
3570     scan_p++;
3571   scan_p--;
3572
3573   output_up_to (scan_p);
3574
3575   /* Now write out full prototypes for all of the things that had been
3576      implicitly declared in this file (but only those for which we were
3577      actually able to find unique matching definitions).  Avoid duplicates
3578      by marking things that we write out as we go.  */
3579
3580   {
3581     int some_decls_added = 0;
3582
3583     for (dd_p = file_p->defs_decs; dd_p; dd_p = dd_p->next_in_file)
3584       if (dd_p->is_implicit && dd_p->definition && !dd_p->definition->written)
3585         {
3586           const char *decl = dd_p->definition->ansi_decl;
3587
3588           /* If the function for which we are inserting a declaration is
3589              actually defined later in the same file, then suppress the
3590              leading `extern' keyword (if there is one).  */
3591
3592           if (*decl == 'e' && (dd_p->file == dd_p->definition->file))
3593             decl += 7;
3594
3595           output_string ("\n");
3596           output_string (decl);
3597           some_decls_added = 1;
3598           ((NONCONST def_dec_info *) dd_p->definition)->written = 1;
3599         }
3600     if (some_decls_added)
3601       output_string ("\n\n");
3602   }
3603
3604   /* Unmark all of the definitions that we just marked.  */
3605
3606   for (dd_p = file_p->defs_decs; dd_p; dd_p = dd_p->next_in_file)
3607     if (dd_p->definition)
3608       ((NONCONST def_dec_info *) dd_p->definition)->written = 0;
3609 }
3610
3611 #endif /* !defined (UNPROTOIZE) */
3612
3613 /* Do the editing operation specifically for a function "definition".  Note
3614    that editing operations for function "declarations" are handled by a
3615    separate routine above.  */
3616
3617 static void
3618 edit_fn_definition (def_dec_p, clean_text_p)
3619      const def_dec_info *def_dec_p;
3620      const char *clean_text_p;
3621 {
3622   const char *end_formals;
3623   const char *function_to_edit = def_dec_p->hash_entry->symbol;
3624
3625   /* Setup here to recover from confusing source code detected during this
3626      particular "edit".  */
3627
3628   save_pointers ();
3629   if (setjmp (source_confusion_recovery))
3630     {
3631       restore_pointers ();
3632       notice ("%s: definition of function `%s' not converted\n",
3633               pname, function_to_edit);
3634       return;
3635     }
3636
3637   end_formals = find_rightmost_formals_list (clean_text_p);
3638
3639   /* end_of_formals now points to the closing right paren of the rightmost
3640      formals list which is actually part of the `header' of the function
3641      definition that we are converting.  */
3642
3643   /* If the header of this function definition looks like it declares a
3644      function with a variable number of arguments, and if the way it does
3645      that is different from that way we would like it (i.e. varargs vs.
3646      stdarg) then issue a warning and leave the header unconverted.  */
3647
3648   if (other_variable_style_function (def_dec_p->ansi_decl))
3649     {
3650       if (!quiet_flag)
3651         notice ("%s: %d: warning: definition of %s not converted\n",
3652                 shortpath (NULL, def_dec_p->file->hash_entry->symbol),
3653                 identify_lineno (end_formals),
3654                 other_var_style);
3655       output_up_to (end_formals);
3656       return;
3657     }
3658
3659   if (edit_formals_lists (end_formals, def_dec_p->f_list_count, def_dec_p))
3660     {
3661       restore_pointers ();
3662       notice ("%s: definition of function `%s' not converted\n",
3663               pname, function_to_edit);
3664       return;
3665     }
3666
3667   /* Have to output the last right paren because this never gets flushed by
3668      edit_formals_list.  */
3669
3670   output_up_to (end_formals);
3671
3672 #ifdef UNPROTOIZE
3673   {
3674     const char *decl_p;
3675     const char *semicolon_p;
3676     const char *limit_p;
3677     const char *scan_p;
3678     int had_newlines = 0;
3679
3680     /* Now write out the K&R style formal declarations, one per line.  */
3681
3682     decl_p = def_dec_p->formal_decls;
3683     limit_p = decl_p + strlen (decl_p);
3684     for (;decl_p < limit_p; decl_p = semicolon_p + 2)
3685       {
3686         for (semicolon_p = decl_p; *semicolon_p != ';'; semicolon_p++)
3687           continue;
3688         output_string ("\n");
3689         output_string (indent_string);
3690         output_bytes (decl_p, (size_t) ((semicolon_p + 1) - decl_p));
3691       }
3692
3693     /* If there are no newlines between the end of the formals list and the
3694        start of the body, we should insert one now.  */
3695
3696     for (scan_p = end_formals+1; *scan_p != '{'; )
3697       {
3698         if (*scan_p == '\n')
3699           {
3700             had_newlines = 1;
3701             break;
3702           }
3703         check_source (++scan_p < clean_text_limit, 0);
3704       }
3705     if (!had_newlines)
3706       output_string ("\n");
3707   }
3708 #else /* !defined (UNPROTOIZE) */
3709   /* If we are protoizing, there may be some flotsam & jetsam (like comments
3710      and preprocessing directives) after the old formals list but before
3711      the following { and we would like to preserve that stuff while effectively
3712      deleting the existing K&R formal parameter declarations.  We do so here
3713      in a rather tricky way.  Basically, we white out any stuff *except*
3714      the comments/pp-directives in the original text buffer, then, if there
3715      is anything in this area *other* than whitespace, we output it.  */
3716   {
3717     const char *end_formals_orig;
3718     const char *start_body;
3719     const char *start_body_orig;
3720     const char *scan;
3721     const char *scan_orig;
3722     int have_flotsam = 0;
3723     int have_newlines = 0;
3724
3725     for (start_body = end_formals + 1; *start_body != '{';)
3726       check_source (++start_body < clean_text_limit, 0);
3727
3728     end_formals_orig = orig_text_base + (end_formals - clean_text_base);
3729     start_body_orig = orig_text_base + (start_body - clean_text_base);
3730     scan = end_formals + 1;
3731     scan_orig = end_formals_orig + 1;
3732     for (; scan < start_body; scan++, scan_orig++)
3733       {
3734         if (*scan == *scan_orig)
3735           {
3736             have_newlines |= (*scan_orig == '\n');
3737             /* Leave identical whitespace alone.  */
3738             if (!ISSPACE ((const unsigned char)*scan_orig))
3739               *((NONCONST char *) scan_orig) = ' '; /* identical - so whiteout */
3740           }
3741         else
3742           have_flotsam = 1;
3743       }
3744     if (have_flotsam)
3745       output_bytes (end_formals_orig + 1,
3746                     (size_t) (start_body_orig - end_formals_orig) - 1);
3747     else
3748       if (have_newlines)
3749         output_string ("\n");
3750       else
3751         output_string (" ");
3752     clean_read_ptr = start_body - 1;
3753   }
3754 #endif /* !defined (UNPROTOIZE) */
3755 }
3756
3757 /* Clean up the clean text buffer.  Do this by converting comments and
3758    preprocessing directives into spaces.   Also convert line continuations
3759    into whitespace.  Also, whiteout string and character literals.  */
3760
3761 static void
3762 do_cleaning (new_clean_text_base, new_clean_text_limit)
3763      char *new_clean_text_base;
3764      const char *new_clean_text_limit;
3765 {
3766   char *scan_p;
3767   int non_whitespace_since_newline = 0;
3768
3769   for (scan_p = new_clean_text_base; scan_p < new_clean_text_limit; scan_p++)
3770     {
3771       switch (*scan_p)
3772         {
3773         case '/':                       /* Handle comments.  */
3774           if (scan_p[1] != '*')
3775             goto regular;
3776           non_whitespace_since_newline = 1;
3777           scan_p[0] = ' ';
3778           scan_p[1] = ' ';
3779           scan_p += 2;
3780           while (scan_p[1] != '/' || scan_p[0] != '*')
3781             {
3782               if (!ISSPACE ((const unsigned char)*scan_p))
3783                 *scan_p = ' ';
3784               if (++scan_p >= new_clean_text_limit)
3785                 abort ();
3786             }
3787           *scan_p++ = ' ';
3788           *scan_p = ' ';
3789           break;
3790
3791         case '#':                       /* Handle pp directives.  */
3792           if (non_whitespace_since_newline)
3793             goto regular;
3794           *scan_p = ' ';
3795           while (scan_p[1] != '\n' || scan_p[0] == '\\')
3796             {
3797               if (!ISSPACE ((const unsigned char)*scan_p))
3798                 *scan_p = ' ';
3799               if (++scan_p >= new_clean_text_limit)
3800                 abort ();
3801             }
3802           *scan_p++ = ' ';
3803           break;
3804
3805         case '\'':                      /* Handle character literals.  */
3806           non_whitespace_since_newline = 1;
3807           while (scan_p[1] != '\'' || scan_p[0] == '\\')
3808             {
3809               if (scan_p[0] == '\\'
3810                   && !ISSPACE ((const unsigned char) scan_p[1]))
3811                 scan_p[1] = ' ';
3812               if (!ISSPACE ((const unsigned char)*scan_p))
3813                 *scan_p = ' ';
3814               if (++scan_p >= new_clean_text_limit)
3815                 abort ();
3816             }
3817           *scan_p++ = ' ';
3818           break;
3819
3820         case '"':                       /* Handle string literals.  */
3821           non_whitespace_since_newline = 1;
3822           while (scan_p[1] != '"' || scan_p[0] == '\\')
3823             {
3824               if (scan_p[0] == '\\'
3825                   && !ISSPACE ((const unsigned char) scan_p[1]))
3826                 scan_p[1] = ' ';
3827               if (!ISSPACE ((const unsigned char)*scan_p))
3828                 *scan_p = ' ';
3829               if (++scan_p >= new_clean_text_limit)
3830                 abort ();
3831             }
3832           if (!ISSPACE ((const unsigned char)*scan_p))
3833             *scan_p = ' ';
3834           scan_p++;
3835           break;
3836
3837         case '\\':                      /* Handle line continuations.  */
3838           if (scan_p[1] != '\n')
3839             goto regular;
3840           *scan_p = ' ';
3841           break;
3842
3843         case '\n':
3844           non_whitespace_since_newline = 0;     /* Reset.  */
3845           break;
3846
3847         case ' ':
3848         case '\v':
3849         case '\t':
3850         case '\r':
3851         case '\f':
3852         case '\b':
3853           break;                /* Whitespace characters.  */
3854
3855         default:
3856 regular:
3857           non_whitespace_since_newline = 1;
3858           break;
3859         }
3860     }
3861 }
3862
3863 /* Given a pointer to the closing right parenthesis for a particular formals
3864    list (in the clean text buffer) find the corresponding left parenthesis
3865    and return a pointer to it.  */
3866
3867 static const char *
3868 careful_find_l_paren (p)
3869      const char *p;
3870 {
3871   const char *q;
3872   int paren_depth;
3873
3874   for (paren_depth = 1, q = p-1; paren_depth; check_source (--q >= clean_text_base, 0))
3875     {
3876       switch (*q)
3877         {
3878         case ')':
3879           paren_depth++;
3880           break;
3881         case '(':
3882           paren_depth--;
3883           break;
3884         }
3885     }
3886   return ++q;
3887 }
3888
3889 /* Scan the clean text buffer for cases of function definitions that we
3890    don't really know about because they were preprocessed out when the
3891    aux info files were created.
3892
3893    In this version of protoize/unprotoize we just give a warning for each
3894    one found.  A later version may be able to at least unprotoize such
3895    missed items.
3896
3897    Note that we may easily find all function definitions simply by
3898    looking for places where there is a left paren which is (ignoring
3899    whitespace) immediately followed by either a left-brace or by an
3900    upper or lower case letter.  Whenever we find this combination, we
3901    have also found a function definition header.
3902
3903    Finding function *declarations* using syntactic clues is much harder.
3904    I will probably try to do this in a later version though.  */
3905
3906 static void
3907 scan_for_missed_items (file_p)
3908      const file_info *file_p;
3909 {
3910   static const char *scan_p;
3911   const char *limit = clean_text_limit - 3;
3912   static const char *backup_limit;
3913
3914   backup_limit = clean_text_base - 1;
3915
3916   for (scan_p = clean_text_base; scan_p < limit; scan_p++)
3917     {
3918       if (*scan_p == ')')
3919         {
3920           static const char *last_r_paren;
3921           const char *ahead_p;
3922
3923           last_r_paren = scan_p;
3924
3925           for (ahead_p = scan_p + 1; ISSPACE ((const unsigned char)*ahead_p); )
3926             check_source (++ahead_p < limit, limit);
3927
3928           scan_p = ahead_p - 1;
3929
3930           if (ISALPHA ((const unsigned char)*ahead_p) || *ahead_p == '{')
3931             {
3932               const char *last_l_paren;
3933               const int lineno = identify_lineno (ahead_p);
3934
3935               if (setjmp (source_confusion_recovery))
3936                 continue;
3937
3938               /* We know we have a function definition header.  Now skip
3939                  leftwards over all of its associated formals lists.  */
3940
3941               do
3942                 {
3943                   last_l_paren = careful_find_l_paren (last_r_paren);
3944                   for (last_r_paren = last_l_paren-1;
3945                        ISSPACE ((const unsigned char)*last_r_paren); )
3946                     check_source (--last_r_paren >= backup_limit, backup_limit);
3947                 }
3948               while (*last_r_paren == ')');
3949
3950               if (is_id_char (*last_r_paren))
3951                 {
3952                   const char *id_limit = last_r_paren + 1;
3953                   const char *id_start;
3954                   size_t id_length;
3955                   const def_dec_info *dd_p;
3956
3957                   for (id_start = id_limit-1; is_id_char (*id_start); )
3958                     check_source (--id_start >= backup_limit, backup_limit);
3959                   id_start++;
3960                   backup_limit = id_start;
3961                   if ((id_length = (size_t) (id_limit - id_start)) == 0)
3962                     goto not_missed;
3963
3964                   {
3965                     char *func_name = (char *) alloca (id_length + 1);
3966                     static const char * const stmt_keywords[]
3967                       = { "if", "else", "do", "while", "for", "switch", "case", "return", 0 };
3968                     const char * const *stmt_keyword;
3969
3970                     strncpy (func_name, id_start, id_length);
3971                     func_name[id_length] = '\0';
3972
3973                     /* We must check here to see if we are actually looking at
3974                        a statement rather than an actual function call.  */
3975
3976                     for (stmt_keyword = stmt_keywords; *stmt_keyword; stmt_keyword++)
3977                       if (!strcmp (func_name, *stmt_keyword))
3978                         goto not_missed;
3979
3980 #if 0
3981                     notice ("%s: found definition of `%s' at %s(%d)\n",
3982                             pname,
3983                             func_name,
3984                             shortpath (NULL, file_p->hash_entry->symbol),
3985                             identify_lineno (id_start));
3986 #endif                          /* 0 */
3987                     /* We really should check for a match of the function name
3988                        here also, but why bother.  */
3989
3990                     for (dd_p = file_p->defs_decs; dd_p; dd_p = dd_p->next_in_file)
3991                       if (dd_p->is_func_def && dd_p->line == lineno)
3992                         goto not_missed;
3993
3994                     /* If we make it here, then we did not know about this
3995                        function definition.  */
3996
3997                     notice ("%s: %d: warning: `%s' excluded by preprocessing\n",
3998                             shortpath (NULL, file_p->hash_entry->symbol),
3999                             identify_lineno (id_start), func_name);
4000                     notice ("%s: function definition not converted\n",
4001                             pname);
4002                   }
4003                 not_missed: ;
4004                 }
4005             }
4006         }
4007     }
4008 }
4009
4010 /* Do all editing operations for a single source file (either a "base" file
4011    or an "include" file).  To do this we read the file into memory, keep a
4012    virgin copy there, make another cleaned in-core copy of the original file
4013    (i.e. one in which all of the comments and preprocessing directives have
4014    been replaced with whitespace), then use these two in-core copies of the
4015    file to make a new edited in-core copy of the file.  Finally, rename the
4016    original file (as a way of saving it), and then write the edited version
4017    of the file from core to a disk file of the same name as the original.
4018
4019    Note that the trick of making a copy of the original sans comments &
4020    preprocessing directives make the editing a whole lot easier.  */
4021
4022 static void
4023 edit_file (hp)
4024      const hash_table_entry *hp;
4025 {
4026   struct stat stat_buf;
4027   const file_info *file_p = hp->fip;
4028   char *new_orig_text_base;
4029   char *new_orig_text_limit;
4030   char *new_clean_text_base;
4031   char *new_clean_text_limit;
4032   size_t orig_size;
4033   size_t repl_size;
4034   int first_definition_in_file;
4035
4036   /* If we are not supposed to be converting this file, or if there is
4037      nothing in there which needs converting, just skip this file.  */
4038
4039   if (!needs_to_be_converted (file_p))
4040     return;
4041
4042   convert_filename = file_p->hash_entry->symbol;
4043
4044   /* Convert a file if it is in a directory where we want conversion
4045      and the file is not excluded.  */
4046
4047   if (!directory_specified_p (convert_filename)
4048       || file_excluded_p (convert_filename))
4049     {
4050       if (!quiet_flag
4051 #ifdef UNPROTOIZE
4052           /* Don't even mention "system" include files unless we are
4053              protoizing.  If we are protoizing, we mention these as a
4054              gentle way of prodding the user to convert his "system"
4055              include files to prototype format.  */
4056           && !in_system_include_dir (convert_filename)
4057 #endif /* defined (UNPROTOIZE) */
4058           )
4059         notice ("%s: `%s' not converted\n",
4060                 pname, shortpath (NULL, convert_filename));
4061       return;
4062     }
4063
4064   /* Let the user know what we are up to.  */
4065
4066   if (nochange_flag)
4067     notice ("%s: would convert file `%s'\n",
4068             pname, shortpath (NULL, convert_filename));
4069   else
4070     notice ("%s: converting file `%s'\n",
4071             pname, shortpath (NULL, convert_filename));
4072   fflush (stderr);
4073
4074   /* Find out the size (in bytes) of the original file.  */
4075
4076   /* The cast avoids an erroneous warning on AIX.  */
4077   if (stat (convert_filename, &stat_buf) == -1)
4078     {
4079       int errno_val = errno;
4080       notice ("%s: can't get status for file `%s': %s\n",
4081               pname, shortpath (NULL, convert_filename),
4082               xstrerror (errno_val));
4083       return;
4084     }
4085   orig_size = stat_buf.st_size;
4086
4087   /* Allocate a buffer to hold the original text.  */
4088
4089   orig_text_base = new_orig_text_base = (char *) xmalloc (orig_size + 2);
4090   orig_text_limit = new_orig_text_limit = new_orig_text_base + orig_size;
4091
4092   /* Allocate a buffer to hold the cleaned-up version of the original text.  */
4093
4094   clean_text_base = new_clean_text_base = (char *) xmalloc (orig_size + 2);
4095   clean_text_limit = new_clean_text_limit = new_clean_text_base + orig_size;
4096   clean_read_ptr = clean_text_base - 1;
4097
4098   /* Allocate a buffer that will hopefully be large enough to hold the entire
4099      converted output text.  As an initial guess for the maximum size of the
4100      output buffer, use 125% of the size of the original + some extra.  This
4101      buffer can be expanded later as needed.  */
4102
4103   repl_size = orig_size + (orig_size >> 2) + 4096;
4104   repl_text_base = (char *) xmalloc (repl_size + 2);
4105   repl_text_limit = repl_text_base + repl_size - 1;
4106   repl_write_ptr = repl_text_base - 1;
4107
4108   {
4109     int input_file;
4110     int fd_flags;
4111
4112     /* Open the file to be converted in READ ONLY mode.  */
4113
4114     fd_flags = O_RDONLY;
4115 #ifdef O_BINARY
4116     /* Use binary mode to avoid having to deal with different EOL characters.  */
4117     fd_flags |= O_BINARY;
4118 #endif
4119     if ((input_file = open (convert_filename, fd_flags, 0444)) == -1)
4120       {
4121         int errno_val = errno;
4122         notice ("%s: can't open file `%s' for reading: %s\n",
4123                 pname, shortpath (NULL, convert_filename),
4124                 xstrerror (errno_val));
4125         return;
4126       }
4127
4128     /* Read the entire original source text file into the original text buffer
4129        in one swell fwoop.  Then figure out where the end of the text is and
4130        make sure that it ends with a newline followed by a null.  */
4131
4132     if (safe_read (input_file, new_orig_text_base, orig_size) !=
4133         (int) orig_size)
4134       {
4135         int errno_val = errno;
4136         close (input_file);
4137         notice ("\n%s: error reading input file `%s': %s\n",
4138                 pname, shortpath (NULL, convert_filename),
4139                 xstrerror (errno_val));
4140         return;
4141       }
4142
4143     close (input_file);
4144   }
4145
4146   if (orig_size == 0 || orig_text_limit[-1] != '\n')
4147     {
4148       *new_orig_text_limit++ = '\n';
4149       orig_text_limit++;
4150     }
4151
4152   /* Create the cleaned up copy of the original text.  */
4153
4154   memcpy (new_clean_text_base, orig_text_base,
4155           (size_t) (orig_text_limit - orig_text_base));
4156   do_cleaning (new_clean_text_base, new_clean_text_limit);
4157
4158 #if 0
4159   {
4160     int clean_file;
4161     size_t clean_size = orig_text_limit - orig_text_base;
4162     char *const clean_filename = (char *) alloca (strlen (convert_filename) + 6 + 1);
4163
4164     /* Open (and create) the clean file.  */
4165
4166     strcpy (clean_filename, convert_filename);
4167     strcat (clean_filename, ".clean");
4168     if ((clean_file = creat (clean_filename, 0666)) == -1)
4169       {
4170         int errno_val = errno;
4171         notice ("%s: can't create/open clean file `%s': %s\n",
4172                 pname, shortpath (NULL, clean_filename),
4173                 xstrerror (errno_val));
4174         return;
4175       }
4176
4177     /* Write the clean file.  */
4178
4179     safe_write (clean_file, new_clean_text_base, clean_size, clean_filename);
4180
4181     close (clean_file);
4182   }
4183 #endif /* 0 */
4184
4185   /* Do a simplified scan of the input looking for things that were not
4186      mentioned in the aux info files because of the fact that they were
4187      in a region of the source which was preprocessed-out (via #if or
4188      via #ifdef).  */
4189
4190   scan_for_missed_items (file_p);
4191
4192   /* Setup to do line-oriented forward seeking in the clean text buffer.  */
4193
4194   last_known_line_number = 1;
4195   last_known_line_start = clean_text_base;
4196
4197   /* Now get down to business and make all of the necessary edits.  */
4198
4199   {
4200     const def_dec_info *def_dec_p;
4201
4202     first_definition_in_file = 1;
4203     def_dec_p = file_p->defs_decs;
4204     for (; def_dec_p; def_dec_p = def_dec_p->next_in_file)
4205       {
4206         const char *clean_text_p = seek_to_line (def_dec_p->line);
4207
4208         /* clean_text_p now points to the first character of the line which
4209            contains the `terminator' for the declaration or definition that
4210            we are about to process.  */
4211
4212 #ifndef UNPROTOIZE
4213
4214         if (global_flag && def_dec_p->is_func_def && first_definition_in_file)
4215           {
4216             add_global_decls (def_dec_p->file, clean_text_p);
4217             first_definition_in_file = 0;
4218           }
4219
4220         /* Don't edit this item if it is already in prototype format or if it
4221            is a function declaration and we have found no corresponding
4222            definition.  */
4223
4224         if (def_dec_p->prototyped
4225             || (!def_dec_p->is_func_def && !def_dec_p->definition))
4226           continue;
4227
4228 #endif /* !defined (UNPROTOIZE) */
4229
4230         if (def_dec_p->is_func_def)
4231           edit_fn_definition (def_dec_p, clean_text_p);
4232         else
4233 #ifndef UNPROTOIZE
4234         if (def_dec_p->is_implicit)
4235           add_local_decl (def_dec_p, clean_text_p);
4236         else
4237 #endif /* !defined (UNPROTOIZE) */
4238           edit_fn_declaration (def_dec_p, clean_text_p);
4239       }
4240   }
4241
4242   /* Finalize things.  Output the last trailing part of the original text.  */
4243
4244   output_up_to (clean_text_limit - 1);
4245
4246   /* If this is just a test run, stop now and just deallocate the buffers.  */
4247
4248   if (nochange_flag)
4249     {
4250       free (new_orig_text_base);
4251       free (new_clean_text_base);
4252       free (repl_text_base);
4253       return;
4254     }
4255
4256   /* Change the name of the original input file.  This is just a quick way of
4257      saving the original file.  */
4258
4259   if (!nosave_flag)
4260     {
4261       char *new_filename
4262         = (char *) xmalloc (strlen (convert_filename) + strlen (save_suffix) + 2);
4263
4264       strcpy (new_filename, convert_filename);
4265 #ifdef __MSDOS__
4266       /* MSDOS filenames are restricted to 8.3 format, so we save `foo.c'
4267          as `foo.<save_suffix>'.  */
4268       new_filename[(strlen (convert_filename) - 1] = '\0';
4269 #endif
4270       strcat (new_filename, save_suffix);
4271
4272       /* Don't overwrite existing file.  */
4273       if (access (new_filename, F_OK) == 0)
4274         {
4275           if (!quiet_flag)
4276             notice ("%s: warning: file `%s' already saved in `%s'\n",
4277                     pname,
4278                     shortpath (NULL, convert_filename),
4279                     shortpath (NULL, new_filename));
4280         }
4281       else if (rename (convert_filename, new_filename) == -1)
4282         {
4283           int errno_val = errno;
4284           notice ("%s: can't link file `%s' to `%s': %s\n",
4285                   pname,
4286                   shortpath (NULL, convert_filename),
4287                   shortpath (NULL, new_filename),
4288                   xstrerror (errno_val));
4289           return;
4290         }
4291     }
4292
4293   if (unlink (convert_filename) == -1)
4294     {
4295       int errno_val = errno;
4296       /* The file may have already been renamed.  */
4297       if (errno_val != ENOENT)
4298         {
4299           notice ("%s: can't delete file `%s': %s\n",
4300                   pname, shortpath (NULL, convert_filename),
4301                   xstrerror (errno_val));
4302           return;
4303         }
4304     }
4305
4306   {
4307     int output_file;
4308
4309     /* Open (and create) the output file.  */
4310
4311     if ((output_file = creat (convert_filename, 0666)) == -1)
4312       {
4313         int errno_val = errno;
4314         notice ("%s: can't create/open output file `%s': %s\n",
4315                 pname, shortpath (NULL, convert_filename),
4316                 xstrerror (errno_val));
4317         return;
4318       }
4319 #ifdef O_BINARY
4320     /* Use binary mode to avoid changing the existing EOL character.  */
4321     setmode (output_file, O_BINARY);
4322 #endif
4323
4324     /* Write the output file.  */
4325
4326     {
4327       unsigned int out_size = (repl_write_ptr + 1) - repl_text_base;
4328
4329       safe_write (output_file, repl_text_base, out_size, convert_filename);
4330     }
4331
4332     close (output_file);
4333   }
4334
4335   /* Deallocate the conversion buffers.  */
4336
4337   free (new_orig_text_base);
4338   free (new_clean_text_base);
4339   free (repl_text_base);
4340
4341   /* Change the mode of the output file to match the original file.  */
4342
4343   /* The cast avoids an erroneous warning on AIX.  */
4344   if (chmod (convert_filename, stat_buf.st_mode) == -1)
4345     {
4346       int errno_val = errno;
4347       notice ("%s: can't change mode of file `%s': %s\n",
4348               pname, shortpath (NULL, convert_filename),
4349               xstrerror (errno_val));
4350     }
4351
4352   /* Note:  We would try to change the owner and group of the output file
4353      to match those of the input file here, except that may not be a good
4354      thing to do because it might be misleading.  Also, it might not even
4355      be possible to do that (on BSD systems with quotas for instance).  */
4356 }
4357
4358 /* Do all of the individual steps needed to do the protoization (or
4359    unprotoization) of the files referenced in the aux_info files given
4360    in the command line.  */
4361
4362 static void
4363 do_processing ()
4364 {
4365   const char * const *base_pp;
4366   const char * const * const end_pps
4367     = &base_source_filenames[n_base_source_files];
4368
4369 #ifndef UNPROTOIZE
4370   int syscalls_len;
4371 #endif /* !defined (UNPROTOIZE) */
4372
4373   /* One-by-one, check (and create if necessary), open, and read all of the
4374      stuff in each aux_info file.  After reading each aux_info file, the
4375      aux_info_file just read will be automatically deleted unless the
4376      keep_flag is set.  */
4377
4378   for (base_pp = base_source_filenames; base_pp < end_pps; base_pp++)
4379     process_aux_info_file (*base_pp, keep_flag, 0);
4380
4381 #ifndef UNPROTOIZE
4382
4383   /* Also open and read the special SYSCALLS.c aux_info file which gives us
4384      the prototypes for all of the standard system-supplied functions.  */
4385
4386   if (nondefault_syscalls_dir)
4387     {
4388       syscalls_absolute_filename
4389         = (char *) xmalloc (strlen (nondefault_syscalls_dir) + 1
4390                             + sizeof (syscalls_filename));
4391       strcpy (syscalls_absolute_filename, nondefault_syscalls_dir);
4392     }
4393   else
4394     {
4395       GET_ENVIRONMENT (default_syscalls_dir, "GCC_EXEC_PREFIX");
4396       if (!default_syscalls_dir)
4397         {
4398           default_syscalls_dir = standard_exec_prefix;
4399         }
4400       syscalls_absolute_filename
4401         = (char *) xmalloc (strlen (default_syscalls_dir) + 0
4402                             + strlen (target_machine) + 1
4403                             + strlen (target_version) + 1
4404                             + sizeof (syscalls_filename));
4405       strcpy (syscalls_absolute_filename, default_syscalls_dir);
4406       strcat (syscalls_absolute_filename, target_machine);
4407       strcat (syscalls_absolute_filename, "/");
4408       strcat (syscalls_absolute_filename, target_version);
4409       strcat (syscalls_absolute_filename, "/");
4410     }
4411
4412   syscalls_len = strlen (syscalls_absolute_filename);
4413   if (! IS_DIR_SEPARATOR (*(syscalls_absolute_filename + syscalls_len - 1)))
4414     {
4415       *(syscalls_absolute_filename + syscalls_len++) = DIR_SEPARATOR;
4416       *(syscalls_absolute_filename + syscalls_len) = '\0';
4417     }
4418   strcat (syscalls_absolute_filename, syscalls_filename);
4419
4420   /* Call process_aux_info_file in such a way that it does not try to
4421      delete the SYSCALLS aux_info file.  */
4422
4423   process_aux_info_file (syscalls_absolute_filename, 1, 1);
4424
4425 #endif /* !defined (UNPROTOIZE) */
4426
4427   /* When we first read in all of the information from the aux_info files
4428      we saved in it descending line number order, because that was likely to
4429      be faster.  Now however, we want the chains of def & dec records to
4430      appear in ascending line number order as we get further away from the
4431      file_info record that they hang from.  The following line causes all of
4432      these lists to be rearranged into ascending line number order.  */
4433
4434   visit_each_hash_node (filename_primary, reverse_def_dec_list);
4435
4436 #ifndef UNPROTOIZE
4437
4438   /* Now do the "real" work.  The following line causes each declaration record
4439      to be "visited".  For each of these nodes, an attempt is made to match
4440      up the function declaration with a corresponding function definition,
4441      which should have a full prototype-format formals list with it.  Once
4442      these match-ups are made, the conversion of the function declarations
4443      to prototype format can be made.  */
4444
4445   visit_each_hash_node (function_name_primary, connect_defs_and_decs);
4446
4447 #endif /* !defined (UNPROTOIZE) */
4448
4449   /* Now convert each file that can be converted (and needs to be).  */
4450
4451   visit_each_hash_node (filename_primary, edit_file);
4452
4453 #ifndef UNPROTOIZE
4454
4455   /* If we are working in cplusplus mode, try to rename all .c files to .C
4456      files.  Don't panic if some of the renames don't work.  */
4457
4458   if (cplusplus_flag && !nochange_flag)
4459     visit_each_hash_node (filename_primary, rename_c_file);
4460
4461 #endif /* !defined (UNPROTOIZE) */
4462 }
4463 \f
4464 static const struct option longopts[] =
4465 {
4466   {"version", 0, 0, 'V'},
4467   {"file_name", 0, 0, 'p'},
4468   {"quiet", 0, 0, 'q'},
4469   {"silent", 0, 0, 'q'},
4470   {"force", 0, 0, 'f'},
4471   {"keep", 0, 0, 'k'},
4472   {"nosave", 0, 0, 'N'},
4473   {"nochange", 0, 0, 'n'},
4474   {"compiler-options", 1, 0, 'c'},
4475   {"exclude", 1, 0, 'x'},
4476   {"directory", 1, 0, 'd'},
4477 #ifdef UNPROTOIZE
4478   {"indent", 1, 0, 'i'},
4479 #else
4480   {"local", 0, 0, 'l'},
4481   {"global", 0, 0, 'g'},
4482   {"c++", 0, 0, 'C'},
4483   {"syscalls-dir", 1, 0, 'B'},
4484 #endif
4485   {0, 0, 0, 0}
4486 };
4487
4488 extern int main PARAMS ((int, char **const));
4489
4490 int
4491 main (argc, argv)
4492      int argc;
4493      char **const argv;
4494 {
4495   int longind;
4496   int c;
4497   const char *params = "";
4498
4499   pname = strrchr (argv[0], DIR_SEPARATOR);
4500 #ifdef DIR_SEPARATOR_2
4501   {
4502     char *slash;
4503
4504     slash = strrchr (pname ? pname : argv[0], DIR_SEPARATOR_2);
4505     if (slash)
4506       pname = slash;
4507   }
4508 #endif
4509   pname = pname ? pname+1 : argv[0];
4510
4511 #ifdef SIGCHLD
4512   /* We *MUST* set SIGCHLD to SIG_DFL so that the wait4() call will
4513      receive the signal.  A different setting is inheritable */
4514   signal (SIGCHLD, SIG_DFL);
4515 #endif
4516
4517   gcc_init_libintl ();
4518
4519   cwd_buffer = getpwd ();
4520   if (!cwd_buffer)
4521     {
4522       notice ("%s: cannot get working directory: %s\n",
4523               pname, xstrerror(errno));
4524       return (FATAL_EXIT_CODE);
4525     }
4526
4527   /* By default, convert the files in the current directory.  */
4528   directory_list = string_list_cons (cwd_buffer, NULL);
4529
4530   while ((c = getopt_long (argc, argv,
4531 #ifdef UNPROTOIZE
4532                            "c:d:i:knNp:qvVx:",
4533 #else
4534                            "B:c:Cd:gklnNp:qvVx:",
4535 #endif
4536                            longopts, &longind)) != EOF)
4537     {
4538       if (c == 0)               /* Long option.  */
4539         c = longopts[longind].val;
4540       switch (c)
4541         {
4542         case 'p':
4543           compiler_file_name = optarg;
4544           break;
4545         case 'd':
4546           directory_list
4547             = string_list_cons (abspath (NULL, optarg), directory_list);
4548           break;
4549         case 'x':
4550           exclude_list = string_list_cons (optarg, exclude_list);
4551           break;
4552
4553         case 'v':
4554         case 'V':
4555           version_flag = 1;
4556           break;
4557         case 'q':
4558           quiet_flag = 1;
4559           break;
4560 #if 0
4561         case 'f':
4562           force_flag = 1;
4563           break;
4564 #endif
4565         case 'n':
4566           nochange_flag = 1;
4567           keep_flag = 1;
4568           break;
4569         case 'N':
4570           nosave_flag = 1;
4571           break;
4572         case 'k':
4573           keep_flag = 1;
4574           break;
4575         case 'c':
4576           params = optarg;
4577           break;
4578 #ifdef UNPROTOIZE
4579         case 'i':
4580           indent_string = optarg;
4581           break;
4582 #else                           /* !defined (UNPROTOIZE) */
4583         case 'l':
4584           local_flag = 1;
4585           break;
4586         case 'g':
4587           global_flag = 1;
4588           break;
4589         case 'C':
4590           cplusplus_flag = 1;
4591           break;
4592         case 'B':
4593           nondefault_syscalls_dir = optarg;
4594           break;
4595 #endif                          /* !defined (UNPROTOIZE) */
4596         default:
4597           usage ();
4598         }
4599     }
4600
4601   /* Set up compile_params based on -p and -c options.  */
4602   munge_compile_params (params);
4603
4604   n_base_source_files = argc - optind;
4605
4606   /* Now actually make a list of the base source filenames.  */
4607
4608   base_source_filenames
4609     = (const char **) xmalloc ((n_base_source_files + 1) * sizeof (char *));
4610   n_base_source_files = 0;
4611   for (; optind < argc; optind++)
4612     {
4613       const char *path = abspath (NULL, argv[optind]);
4614       int len = strlen (path);
4615
4616       if (path[len-1] == 'c' && path[len-2] == '.')
4617         base_source_filenames[n_base_source_files++] = path;
4618       else
4619         {
4620           notice ("%s: input file names must have .c suffixes: %s\n",
4621                   pname, shortpath (NULL, path));
4622           errors++;
4623         }
4624     }
4625
4626 #ifndef UNPROTOIZE
4627   /* We are only interested in the very first identifier token in the
4628      definition of `va_list', so if there is more junk after that first
4629      identifier token, delete it from the `varargs_style_indicator'.  */
4630   {
4631     const char *cp;
4632
4633     for (cp = varargs_style_indicator; ISIDNUM (*cp); cp++)
4634       continue;
4635     if (*cp != 0)
4636       varargs_style_indicator = savestring (varargs_style_indicator,
4637                                             cp - varargs_style_indicator);
4638   }
4639 #endif /* !defined (UNPROTOIZE) */
4640
4641   if (errors)
4642     usage ();
4643   else
4644     {
4645       if (version_flag)
4646         fprintf (stderr, "%s: %s\n", pname, version_string);
4647       do_processing ();
4648     }
4649
4650   return (errors ? FATAL_EXIT_CODE : SUCCESS_EXIT_CODE);
4651 }