home *** CD-ROM | disk | FTP | other *** search
/ Fresh Fish 7 / FreshFishVol7.bin / bbs / gnu / gcc-2.3.3-src.lha / GNU / src / amiga / gcc-2.3.3 / protoize.c < prev    next >
C/C++ Source or Header  |  1994-02-06  |  148KB  |  4,667 lines

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