1 /* Protoize program - Original version by Ron Guilmette (rfg@segfault.us.com).
2 Copyright (C) 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3 1999, 2000 Free Software Foundation, Inc.
5 This file is part of GNU CC.
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)
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.
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, 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
34 /* Include getopt.h for the sake of getopt_long. */
37 /* Macro to see if the path elements match. */
38 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
39 #define IS_SAME_PATH_CHAR(a,b) (toupper (a) == toupper (b))
41 #define IS_SAME_PATH_CHAR(a,b) ((a) == (b))
44 /* Macro to see if the paths match. */
45 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
46 #define IS_SAME_PATH(a,b) (strcasecmp (a, b) == 0)
48 #define IS_SAME_PATH(a,b) (strcmp (a, b) == 0)
51 /* Suffix for aux-info files. */
53 #define AUX_INFO_SUFFIX "X"
55 #define AUX_INFO_SUFFIX ".X"
58 /* Suffix for saved files. */
60 #define SAVE_SUFFIX "sav"
62 #define SAVE_SUFFIX ".save"
65 /* Suffix for renamed C++ files. */
66 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
67 #define CPLUS_FILE_SUFFIX "cc"
69 #define CPLUS_FILE_SUFFIX "C"
72 static void usage PARAMS ((void)) ATTRIBUTE_NORETURN;
73 static void aux_info_corrupted PARAMS ((void)) ATTRIBUTE_NORETURN;
74 static void declare_source_confusing PARAMS ((const char *)) ATTRIBUTE_NORETURN;
75 static const char *shortpath PARAMS ((const char *, const char *));
76 extern void fancy_abort PARAMS ((void)) ATTRIBUTE_NORETURN;
77 static void notice PARAMS ((const char *, ...)) ATTRIBUTE_PRINTF_1;
78 static char *savestring PARAMS ((const char *, unsigned int));
79 static char *dupnstr PARAMS ((const char *, size_t));
80 static const char *substr PARAMS ((const char *, const char * const));
81 static int safe_read PARAMS ((int, PTR, int));
82 static void safe_write PARAMS ((int, PTR, int, const char *));
83 static void save_pointers PARAMS ((void));
84 static void restore_pointers PARAMS ((void));
85 static int is_id_char PARAMS ((int));
86 static int in_system_include_dir PARAMS ((const char *));
87 static int directory_specified_p PARAMS ((const char *));
88 static int file_excluded_p PARAMS ((const char *));
89 static char *unexpand_if_needed PARAMS ((const char *));
90 static char *abspath PARAMS ((const char *, const char *));
91 static int is_abspath PARAMS ((const char *));
92 static void check_aux_info PARAMS ((int));
93 static const char *find_corresponding_lparen PARAMS ((const char *));
94 static int referenced_file_is_newer PARAMS ((const char *, time_t));
95 static void save_def_or_dec PARAMS ((const char *, int));
96 static void munge_compile_params PARAMS ((const char *));
97 static int gen_aux_info_file PARAMS ((const char *));
98 static void process_aux_info_file PARAMS ((const char *, int, int));
99 static int identify_lineno PARAMS ((const char *));
100 static void check_source PARAMS ((int, const char *));
101 static const char *seek_to_line PARAMS ((int));
102 static const char *forward_to_next_token_char PARAMS ((const char *));
103 static void output_bytes PARAMS ((const char *, size_t));
104 static void output_string PARAMS ((const char *));
105 static void output_up_to PARAMS ((const char *));
106 static int other_variable_style_function PARAMS ((const char *));
107 static const char *find_rightmost_formals_list PARAMS ((const char *));
108 static void do_cleaning PARAMS ((char *, const char *));
109 static const char *careful_find_l_paren PARAMS ((const char *));
110 static void do_processing PARAMS ((void));
112 /* Look for these where the `const' qualifier is intentionally cast aside. */
115 /* Define a default place to find the SYSCALLS.X file. */
119 #ifndef STANDARD_EXEC_PREFIX
120 #define STANDARD_EXEC_PREFIX "/usr/local/lib/gcc-lib/"
121 #endif /* !defined STANDARD_EXEC_PREFIX */
123 static const char * const standard_exec_prefix = STANDARD_EXEC_PREFIX;
124 static const char * const target_machine = DEFAULT_TARGET_MACHINE;
125 static const char * const target_version = DEFAULT_TARGET_VERSION;
127 #ifndef GET_ENV_PATH_LIST
128 #define GET_ENV_PATH_LIST(VAR,NAME) do { (VAR) = getenv (NAME); } while (0)
131 #endif /* !defined (UNPROTOIZE) */
133 /* Suffix of aux_info files. */
135 static const char * const aux_info_suffix = AUX_INFO_SUFFIX;
137 /* String to attach to filenames for saved versions of original files. */
139 static const char * const save_suffix = SAVE_SUFFIX;
141 /* String to attach to C filenames renamed to C++. */
143 static const char * const cplus_suffix = CPLUS_FILE_SUFFIX;
147 /* File name of the file which contains descriptions of standard system
148 routines. Note that we never actually do anything with this file per se,
149 but we do read in its corresponding aux_info file. */
151 static const char syscalls_filename[] = "SYSCALLS.c";
153 /* Default place to find the above file. */
155 static const char * default_syscalls_dir;
157 /* Variable to hold the complete absolutized filename of the SYSCALLS.c.X
160 static char * syscalls_absolute_filename;
162 #endif /* !defined (UNPROTOIZE) */
164 /* Type of the structure that holds information about macro unexpansions. */
166 struct unexpansion_struct {
167 const char *expanded;
168 const char *contracted;
170 typedef struct unexpansion_struct unexpansion;
172 /* A table of conversions that may need to be made for some (stupid) older
173 operating systems where these types are preprocessor macros rather than
174 typedefs (as they really ought to be).
176 WARNING: The contracted forms must be as small (or smaller) as the
177 expanded forms, or else havoc will ensue. */
179 static const unexpansion unexpansions[] = {
180 { "struct _iobuf", "FILE" },
184 /* The number of "primary" slots in the hash tables for filenames and for
185 function names. This can be as big or as small as you like, except that
186 it must be a power of two. */
188 #define HASH_TABLE_SIZE (1 << 9)
190 /* Bit mask to use when computing hash values. */
192 static const int hash_mask = (HASH_TABLE_SIZE - 1);
194 /* Make a table of default system include directories
195 just as it is done in cpp. */
197 #ifndef STANDARD_INCLUDE_DIR
198 #define STANDARD_INCLUDE_DIR "/usr/include"
201 #ifndef LOCAL_INCLUDE_DIR
202 #define LOCAL_INCLUDE_DIR "/usr/local/include"
205 struct default_include { const char *fname;
206 const char *component;
207 int x1, x2; } include_defaults[]
208 #ifdef INCLUDE_DEFAULTS
212 /* Pick up GNU C++ specific include files. */
213 { GPLUSPLUS_INCLUDE_DIR, "G++", 1, 1 },
215 /* This is the dir for fixincludes. Put it just before
216 the files that we fix. */
217 { GCC_INCLUDE_DIR, "GCC", 0, 0 },
218 /* For cross-compilation, this dir name is generated
219 automatically in Makefile.in. */
220 { CROSS_INCLUDE_DIR, 0, 0, 0 },
221 /* This is another place that the target system's headers might be. */
222 { TOOL_INCLUDE_DIR, "BINUTILS", 0, 0 },
223 #else /* not CROSS_COMPILE */
224 /* This should be /use/local/include and should come before
225 the fixincludes-fixed header files. */
226 { LOCAL_INCLUDE_DIR, 0, 0, 1 },
227 /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
228 Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h. */
229 { TOOL_INCLUDE_DIR, "BINUTILS", 0, 0 },
230 /* This is the dir for fixincludes. Put it just before
231 the files that we fix. */
232 { GCC_INCLUDE_DIR, "GCC", 0, 0 },
233 /* Some systems have an extra dir of include files. */
234 #ifdef SYSTEM_INCLUDE_DIR
235 { SYSTEM_INCLUDE_DIR, 0, 0, 0 },
237 { STANDARD_INCLUDE_DIR, 0, 0, 0},
238 #endif /* not CROSS_COMPILE */
241 #endif /* no INCLUDE_DEFAULTS */
243 /* Datatype for lists of directories or filenames. */
247 struct string_list *next;
250 static struct string_list *string_list_cons PARAMS ((const char *,
251 struct string_list *));
253 /* List of directories in which files should be converted. */
255 struct string_list *directory_list;
257 /* List of file names which should not be converted.
258 A file is excluded if the end of its name, following a /,
259 matches one of the names in this list. */
261 struct string_list *exclude_list;
263 /* The name of the other style of variable-number-of-parameters functions
264 (i.e. the style that we want to leave unconverted because we don't yet
265 know how to convert them to this style. This string is used in warning
268 /* Also define here the string that we can search for in the parameter lists
269 taken from the .X files which will unambiguously indicate that we have
270 found a varargs style function. */
273 static const char * const other_var_style = "stdarg";
274 #else /* !defined (UNPROTOIZE) */
275 static const char * const other_var_style = "varargs";
276 /* Note that this is a string containing the expansion of va_alist.
277 But in `main' we discard all but the first token. */
278 static const char *varargs_style_indicator = STRINGIFY (va_alist);
279 #endif /* !defined (UNPROTOIZE) */
281 /* The following two types are used to create hash tables. In this program,
282 there are two hash tables which are used to store and quickly lookup two
283 different classes of strings. The first type of strings stored in the
284 first hash table are absolute filenames of files which protoize needs to
285 know about. The second type of strings (stored in the second hash table)
286 are function names. It is this second class of strings which really
287 inspired the use of the hash tables, because there may be a lot of them. */
289 typedef struct hash_table_entry_struct hash_table_entry;
291 /* Do some typedefs so that we don't have to write "struct" so often. */
293 typedef struct def_dec_info_struct def_dec_info;
294 typedef struct file_info_struct file_info;
295 typedef struct f_list_chain_item_struct f_list_chain_item;
298 static int is_syscalls_file PARAMS ((const file_info *));
299 static void rename_c_file PARAMS ((const hash_table_entry *));
300 static const def_dec_info *find_extern_def PARAMS ((const def_dec_info *,
301 const def_dec_info *));
302 static const def_dec_info *find_static_definition PARAMS ((const def_dec_info *));
303 static void connect_defs_and_decs PARAMS ((const hash_table_entry *));
304 static void add_local_decl PARAMS ((const def_dec_info *, const char *));
305 static void add_global_decls PARAMS ((const file_info *, const char *));
306 #endif /* ! UNPROTOIZE */
307 static int needs_to_be_converted PARAMS ((const file_info *));
308 static void visit_each_hash_node PARAMS ((const hash_table_entry *,
309 void (*)(const hash_table_entry *)));
310 static hash_table_entry *add_symbol PARAMS ((hash_table_entry *, const char *));
311 static hash_table_entry *lookup PARAMS ((hash_table_entry *, const char *));
312 static void free_def_dec PARAMS ((def_dec_info *));
313 static file_info *find_file PARAMS ((const char *, int));
314 static void reverse_def_dec_list PARAMS ((const hash_table_entry *));
315 static void edit_fn_declaration PARAMS ((const def_dec_info *, const char *));
316 static int edit_formals_lists PARAMS ((const char *, unsigned int,
317 const def_dec_info *));
318 static void edit_fn_definition PARAMS ((const def_dec_info *, const char *));
319 static void scan_for_missed_items PARAMS ((const file_info *));
320 static void edit_file PARAMS ((const hash_table_entry *));
322 /* In the struct below, note that the "_info" field has two different uses
323 depending on the type of hash table we are in (i.e. either the filenames
324 hash table or the function names hash table). In the filenames hash table
325 the info fields of the entries point to the file_info struct which is
326 associated with each filename (1 per filename). In the function names
327 hash table, the info field points to the head of a singly linked list of
328 def_dec_info entries which are all defs or decs of the function whose
329 name is pointed to by the "symbol" field. Keeping all of the defs/decs
330 for a given function name on a special list specifically for that function
331 name makes it quick and easy to find out all of the important information
332 about a given (named) function. */
334 struct hash_table_entry_struct {
335 hash_table_entry * hash_next; /* -> to secondary entries */
336 const char * symbol; /* -> to the hashed string */
338 const def_dec_info * _ddip;
342 #define ddip _info._ddip
343 #define fip _info._fip
345 /* Define a type specifically for our two hash tables. */
347 typedef hash_table_entry hash_table[HASH_TABLE_SIZE];
349 /* The following struct holds all of the important information about any
350 single filename (e.g. file) which we need to know about. */
352 struct file_info_struct {
353 const hash_table_entry * hash_entry; /* -> to associated hash entry */
354 const def_dec_info * defs_decs; /* -> to chain of defs/decs */
355 time_t mtime; /* Time of last modification. */
358 /* Due to the possibility that functions may return pointers to functions,
359 (which may themselves have their own parameter lists) and due to the
360 fact that returned pointers-to-functions may be of type "pointer-to-
361 function-returning-pointer-to-function" (ad nauseum) we have to keep
362 an entire chain of ANSI style formal parameter lists for each function.
364 Normally, for any given function, there will only be one formals list
365 on the chain, but you never know.
367 Note that the head of each chain of formals lists is pointed to by the
368 `f_list_chain' field of the corresponding def_dec_info record.
370 For any given chain, the item at the head of the chain is the *leftmost*
371 parameter list seen in the actual C language function declaration. If
372 there are other members of the chain, then these are linked in left-to-right
373 order from the head of the chain. */
375 struct f_list_chain_item_struct {
376 const f_list_chain_item * chain_next; /* -> to next item on chain */
377 const char * formals_list; /* -> to formals list string */
380 /* The following struct holds all of the important information about any
381 single function definition or declaration which we need to know about.
382 Note that for unprotoize we don't need to know very much because we
383 never even create records for stuff that we don't intend to convert
384 (like for instance defs and decs which are already in old K&R format
385 and "implicit" function declarations). */
387 struct def_dec_info_struct {
388 const def_dec_info * next_in_file; /* -> to rest of chain for file */
389 file_info * file; /* -> file_info for containing file */
390 int line; /* source line number of def/dec */
391 const char * ansi_decl; /* -> left end of ansi decl */
392 hash_table_entry * hash_entry; /* -> hash entry for function name */
393 unsigned int is_func_def; /* = 0 means this is a declaration */
394 const def_dec_info * next_for_func; /* -> to rest of chain for func name */
395 unsigned int f_list_count; /* count of formals lists we expect */
396 char prototyped; /* = 0 means already prototyped */
398 const f_list_chain_item * f_list_chain; /* -> chain of formals lists */
399 const def_dec_info * definition; /* -> def/dec containing related def */
400 char is_static; /* = 0 means visibility is "extern" */
401 char is_implicit; /* != 0 for implicit func decl's */
402 char written; /* != 0 means written for implicit */
403 #else /* !defined (UNPROTOIZE) */
404 const char * formal_names; /* -> to list of names of formals */
405 const char * formal_decls; /* -> to string of formal declarations */
406 #endif /* !defined (UNPROTOIZE) */
409 /* Pointer to the tail component of the filename by which this program was
410 invoked. Used everywhere in error and warning messages. */
412 static const char *pname;
414 /* Error counter. Will be non-zero if we should give up at the next convenient
417 static int errors = 0;
420 /* ??? These comments should say what the flag mean as well as the options
423 /* File name to use for running gcc. Allows GCC 2 to be named
424 something other than gcc. */
425 static const char *compiler_file_name = "gcc";
427 static int version_flag = 0; /* Print our version number. */
428 static int quiet_flag = 0; /* Don't print messages normally. */
429 static int nochange_flag = 0; /* Don't convert, just say what files
430 we would have converted. */
431 static int nosave_flag = 0; /* Don't save the old version. */
432 static int keep_flag = 0; /* Don't delete the .X files. */
433 static const char ** compile_params = 0; /* Option string for gcc. */
435 static const char *indent_string = " "; /* Indentation for newly
436 inserted parm decls. */
437 #else /* !defined (UNPROTOIZE) */
438 static int local_flag = 0; /* Insert new local decls (when?). */
439 static int global_flag = 0; /* set by -g option */
440 static int cplusplus_flag = 0; /* Rename converted files to *.C. */
441 static const char *nondefault_syscalls_dir = 0; /* Dir to look for
443 #endif /* !defined (UNPROTOIZE) */
445 /* An index into the compile_params array where we should insert the source
446 file name when we are ready to exec the C compiler. A zero value indicates
447 that we have not yet called munge_compile_params. */
449 static int input_file_name_index = 0;
451 /* An index into the compile_params array where we should insert the filename
452 for the aux info file, when we run the C compiler. */
453 static int aux_info_file_name_index = 0;
455 /* Count of command line arguments which were "filename" arguments. */
457 static int n_base_source_files = 0;
459 /* Points to a malloc'ed list of pointers to all of the filenames of base
460 source files which were specified on the command line. */
462 static const char **base_source_filenames;
464 /* Line number of the line within the current aux_info file that we
465 are currently processing. Used for error messages in case the prototypes
466 info file is corrupted somehow. */
468 static int current_aux_info_lineno;
470 /* Pointer to the name of the source file currently being converted. */
472 static const char *convert_filename;
474 /* Pointer to relative root string (taken from aux_info file) which indicates
475 where directory the user was in when he did the compilation step that
476 produced the containing aux_info file. */
478 static const char *invocation_filename;
480 /* Pointer to the base of the input buffer that holds the original text for the
481 source file currently being converted. */
483 static const char *orig_text_base;
485 /* Pointer to the byte just beyond the end of the input buffer that holds the
486 original text for the source file currently being converted. */
488 static const char *orig_text_limit;
490 /* Pointer to the base of the input buffer that holds the cleaned text for the
491 source file currently being converted. */
493 static const char *clean_text_base;
495 /* Pointer to the byte just beyond the end of the input buffer that holds the
496 cleaned text for the source file currently being converted. */
498 static const char *clean_text_limit;
500 /* Pointer to the last byte in the cleaned text buffer that we have already
501 (virtually) copied to the output buffer (or decided to ignore). */
503 static const char * clean_read_ptr;
505 /* Pointer to the base of the output buffer that holds the replacement text
506 for the source file currently being converted. */
508 static char *repl_text_base;
510 /* Pointer to the byte just beyond the end of the output buffer that holds the
511 replacement text for the source file currently being converted. */
513 static char *repl_text_limit;
515 /* Pointer to the last byte which has been stored into the output buffer.
516 The next byte to be stored should be stored just past where this points
519 static char * repl_write_ptr;
521 /* Pointer into the cleaned text buffer for the source file we are currently
522 converting. This points to the first character of the line that we last
523 did a "seek_to_line" to (see below). */
525 static const char *last_known_line_start;
527 /* Number of the line (in the cleaned text buffer) that we last did a
528 "seek_to_line" to. Will be one if we just read a new source file
529 into the cleaned text buffer. */
531 static int last_known_line_number;
533 /* The filenames hash table. */
535 static hash_table filename_primary;
537 /* The function names hash table. */
539 static hash_table function_name_primary;
541 /* The place to keep the recovery address which is used only in cases where
542 we get hopelessly confused by something in the cleaned original text. */
544 static jmp_buf source_confusion_recovery;
546 /* A pointer to the current directory filename (used by abspath). */
548 static char *cwd_buffer;
550 /* A place to save the read pointer until we are sure that an individual
551 attempt at editing will succeed. */
553 static const char * saved_clean_read_ptr;
555 /* A place to save the write pointer until we are sure that an individual
556 attempt at editing will succeed. */
558 static char * saved_repl_write_ptr;
560 /* Translate and output an error message. */
562 notice VPARAMS ((const char *msgid, ...))
564 #ifndef ANSI_PROTOTYPES
569 VA_START (ap, msgid);
571 #ifndef ANSI_PROTOTYPES
572 msgid = va_arg (ap, const char *);
575 vfprintf (stderr, _(msgid), ap);
580 /* Make a copy of a string INPUT with size SIZE. */
583 savestring (input, size)
587 char *output = (char *) xmalloc (size + 1);
588 strcpy (output, input);
592 /* More 'friendly' abort that prints the line and file.
593 config.h can #define abort fancy_abort if you like that sort of thing. */
598 notice ("%s: internal abort\n", pname);
599 exit (FATAL_EXIT_CODE);
602 /* Make a duplicate of the first N bytes of a given string in a newly
610 char *ret_val = (char *) xmalloc (n + 1);
612 strncpy (ret_val, s, n);
617 /* Return a pointer to the first occurrence of s2 within s1 or NULL if s2
618 does not occur within s1. Assume neither s1 nor s2 are null pointers. */
623 const char *const s2;
631 for (p1 = s1, p2 = s2; (c = *p2); p1++, p2++)
641 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
642 retrying if necessary. Return the actual number of bytes read. */
645 safe_read (desc, ptr, len)
652 int nchars = read (desc, ptr, left);
663 /* Arithmetic on void pointers is a gcc extention. */
664 ptr = (char *) ptr + nchars;
670 /* Write LEN bytes at PTR to descriptor DESC,
671 retrying if necessary, and treating any real error as fatal. */
674 safe_write (desc, ptr, len, out_fname)
678 const char *out_fname;
681 int written = write (desc, ptr, len);
684 int errno_val = errno;
686 if (errno_val == EINTR)
689 notice ("%s: error writing file `%s': %s\n",
690 pname, shortpath (NULL, out_fname), xstrerror (errno_val));
693 /* Arithmetic on void pointers is a gcc extention. */
694 ptr = (char *) ptr + written;
699 /* Get setup to recover in case the edit we are about to do goes awry. */
704 saved_clean_read_ptr = clean_read_ptr;
705 saved_repl_write_ptr = repl_write_ptr;
708 /* Call this routine to recover our previous state whenever something looks
709 too confusing in the source code we are trying to edit. */
714 clean_read_ptr = saved_clean_read_ptr;
715 repl_write_ptr = saved_repl_write_ptr;
718 /* Return true if the given character is a valid identifier character. */
724 return (ISALNUM (ch) || (ch == '_') || (ch == '$'));
727 /* Give a message indicating the proper way to invoke this program and then
728 exit with non-zero status. */
734 notice ("%s: usage '%s [ -VqfnkN ] [ -i <istring> ] [ filename ... ]'\n",
736 #else /* !defined (UNPROTOIZE) */
737 notice ("%s: usage '%s [ -VqfnkNlgC ] [ -B <dirname> ] [ filename ... ]'\n",
739 #endif /* !defined (UNPROTOIZE) */
740 exit (FATAL_EXIT_CODE);
743 /* Return true if the given filename (assumed to be an absolute filename)
744 designates a file residing anywhere beneath any one of the "system"
745 include directories. */
748 in_system_include_dir (path)
751 struct default_include *p;
753 if (! is_abspath (path))
754 abort (); /* Must be an absolutized filename. */
756 for (p = include_defaults; p->fname; p++)
757 if (!strncmp (path, p->fname, strlen (p->fname))
758 && IS_DIR_SEPARATOR (path[strlen (p->fname)]))
764 /* Return true if the given filename designates a file that the user has
765 read access to and for which the user has write access to the containing
769 file_could_be_converted (const char *path)
771 char *const dir_name = (char *) alloca (strlen (path) + 1);
773 if (access (path, R_OK))
777 char *dir_last_slash;
779 strcpy (dir_name, path);
780 dir_last_slash = strrchr (dir_name, DIR_SEPARATOR);
781 #ifdef DIR_SEPARATOR_2
785 slash = strrchr (dir_last_slash ? dir_last_slash : dir_name,
788 dir_last_slash = slash;
792 *dir_last_slash = '\0';
794 abort (); /* Should have been an absolutized filename. */
797 if (access (path, W_OK))
803 /* Return true if the given filename designates a file that we are allowed
804 to modify. Files which we should not attempt to modify are (a) "system"
805 include files, and (b) files which the user doesn't have write access to,
806 and (c) files which reside in directories which the user doesn't have
807 write access to. Unless requested to be quiet, give warnings about
808 files that we will not try to convert for one reason or another. An
809 exception is made for "system" include files, which we never try to
810 convert and for which we don't issue the usual warnings. */
813 file_normally_convertible (const char *path)
815 char *const dir_name = alloca (strlen (path) + 1);
817 if (in_system_include_dir (path))
821 char *dir_last_slash;
823 strcpy (dir_name, path);
824 dir_last_slash = strrchr (dir_name, DIR_SEPARATOR);
825 #ifdef DIR_SEPARATOR_2
829 slash = strrchr (dir_last_slash ? dir_last_slash : dir_name,
832 dir_last_slash = slash;
836 *dir_last_slash = '\0';
838 abort (); /* Should have been an absolutized filename. */
841 if (access (path, R_OK))
844 notice ("%s: warning: no read access for file `%s'\n",
845 pname, shortpath (NULL, path));
849 if (access (path, W_OK))
852 notice ("%s: warning: no write access for file `%s'\n",
853 pname, shortpath (NULL, path));
857 if (access (dir_name, W_OK))
860 notice ("%s: warning: no write access for dir containing `%s'\n",
861 pname, shortpath (NULL, path));
871 /* Return true if the given file_info struct refers to the special SYSCALLS.c.X
872 file. Return false otherwise. */
875 is_syscalls_file (fi_p)
876 const file_info *fi_p;
878 char const *f = fi_p->hash_entry->symbol;
879 size_t fl = strlen (f), sysl = sizeof (syscalls_filename) - 1;
880 return sysl <= fl && strcmp (f + fl - sysl, syscalls_filename) == 0;
883 #endif /* !defined (UNPROTOIZE) */
885 /* Check to see if this file will need to have anything done to it on this
886 run. If there is nothing in the given file which both needs conversion
887 and for which we have the necessary stuff to do the conversion, return
888 false. Otherwise, return true.
890 Note that (for protoize) it is only valid to call this function *after*
891 the connections between declarations and definitions have all been made
892 by connect_defs_and_decs. */
895 needs_to_be_converted (file_p)
896 const file_info *file_p;
898 const def_dec_info *ddp;
902 if (is_syscalls_file (file_p))
905 #endif /* !defined (UNPROTOIZE) */
907 for (ddp = file_p->defs_decs; ddp; ddp = ddp->next_in_file)
913 /* ... and if we a protoizing and this function is in old style ... */
915 /* ... and if this a definition or is a decl with an associated def ... */
916 && (ddp->is_func_def || (!ddp->is_func_def && ddp->definition))
918 #else /* defined (UNPROTOIZE) */
920 /* ... and if we are unprotoizing and this function is in new style ... */
923 #endif /* defined (UNPROTOIZE) */
925 /* ... then the containing file needs converting. */
930 /* Return 1 if the file name NAME is in a directory
931 that should be converted. */
934 directory_specified_p (name)
937 struct string_list *p;
939 for (p = directory_list; p; p = p->next)
940 if (!strncmp (name, p->name, strlen (p->name))
941 && IS_DIR_SEPARATOR (name[strlen (p->name)]))
943 const char *q = name + strlen (p->name) + 1;
945 /* If there are more slashes, it's in a subdir, so
946 this match doesn't count. */
948 if (IS_DIR_SEPARATOR (*(q-1)))
958 /* Return 1 if the file named NAME should be excluded from conversion. */
961 file_excluded_p (name)
964 struct string_list *p;
965 int len = strlen (name);
967 for (p = exclude_list; p; p = p->next)
968 if (!strcmp (name + len - strlen (p->name), p->name)
969 && IS_DIR_SEPARATOR (name[len - strlen (p->name) - 1]))
975 /* Construct a new element of a string_list.
976 STRING is the new element value, and REST holds the remaining elements. */
978 static struct string_list *
979 string_list_cons (string, rest)
981 struct string_list *rest;
983 struct string_list *temp
984 = (struct string_list *) xmalloc (sizeof (struct string_list));
991 /* ??? The GNU convention for mentioning function args in its comments
992 is to capitalize them. So change "hash_tab_p" to HASH_TAB_P below.
993 Likewise for all the other functions. */
995 /* Given a hash table, apply some function to each node in the table. The
996 table to traverse is given as the "hash_tab_p" argument, and the
997 function to be applied to each node in the table is given as "func"
1001 visit_each_hash_node (hash_tab_p, func)
1002 const hash_table_entry *hash_tab_p;
1003 void (*func) PARAMS ((const hash_table_entry *));
1005 const hash_table_entry *primary;
1007 for (primary = hash_tab_p; primary < &hash_tab_p[HASH_TABLE_SIZE]; primary++)
1008 if (primary->symbol)
1010 hash_table_entry *second;
1013 for (second = primary->hash_next; second; second = second->hash_next)
1018 /* Initialize all of the fields of a new hash table entry, pointed
1019 to by the "p" parameter. Note that the space to hold the entry
1020 is assumed to have already been allocated before this routine is
1023 static hash_table_entry *
1025 hash_table_entry *p;
1028 p->hash_next = NULL;
1029 p->symbol = xstrdup (s);
1035 /* Look for a particular function name or filename in the particular
1036 hash table indicated by "hash_tab_p". If the name is not in the
1037 given hash table, add it. Either way, return a pointer to the
1038 hash table entry for the given name. */
1040 static hash_table_entry *
1041 lookup (hash_tab_p, search_symbol)
1042 hash_table_entry *hash_tab_p;
1043 const char *search_symbol;
1046 const char *search_symbol_char_p = search_symbol;
1047 hash_table_entry *p;
1049 while (*search_symbol_char_p)
1050 hash_value += *search_symbol_char_p++;
1051 hash_value &= hash_mask;
1052 p = &hash_tab_p[hash_value];
1054 return add_symbol (p, search_symbol);
1055 if (!strcmp (p->symbol, search_symbol))
1057 while (p->hash_next)
1060 if (!strcmp (p->symbol, search_symbol))
1063 p->hash_next = (hash_table_entry *) xmalloc (sizeof (hash_table_entry));
1065 return add_symbol (p, search_symbol);
1068 /* Throw a def/dec record on the junk heap.
1070 Also, since we are not using this record anymore, free up all of the
1071 stuff it pointed to. */
1077 free ((NONCONST PTR) p->ansi_decl);
1081 const f_list_chain_item * curr;
1082 const f_list_chain_item * next;
1084 for (curr = p->f_list_chain; curr; curr = next)
1086 next = curr->chain_next;
1087 free ((NONCONST PTR) curr);
1090 #endif /* !defined (UNPROTOIZE) */
1095 /* Unexpand as many macro symbol as we can find.
1097 If the given line must be unexpanded, make a copy of it in the heap and
1098 return a pointer to the unexpanded copy. Otherwise return NULL. */
1101 unexpand_if_needed (aux_info_line)
1102 const char *aux_info_line;
1104 static char *line_buf = 0;
1105 static int line_buf_size = 0;
1106 const unexpansion *unexp_p;
1107 int got_unexpanded = 0;
1109 char *copy_p = line_buf;
1113 line_buf_size = 1024;
1114 line_buf = (char *) xmalloc (line_buf_size);
1119 /* Make a copy of the input string in line_buf, expanding as necessary. */
1121 for (s = aux_info_line; *s != '\n'; )
1123 for (unexp_p = unexpansions; unexp_p->expanded; unexp_p++)
1125 const char *in_p = unexp_p->expanded;
1126 size_t len = strlen (in_p);
1128 if (*s == *in_p && !strncmp (s, in_p, len) && !is_id_char (s[len]))
1130 int size = strlen (unexp_p->contracted);
1132 if (copy_p + size - line_buf >= line_buf_size)
1134 int offset = copy_p - line_buf;
1136 line_buf_size += size;
1137 line_buf = (char *) xrealloc (line_buf, line_buf_size);
1138 copy_p = line_buf + offset;
1140 strcpy (copy_p, unexp_p->contracted);
1143 /* Assume the there will not be another replacement required
1144 within the text just replaced. */
1147 goto continue_outer;
1150 if (copy_p - line_buf == line_buf_size)
1152 int offset = copy_p - line_buf;
1154 line_buf = (char *) xrealloc (line_buf, line_buf_size);
1155 copy_p = line_buf + offset;
1160 if (copy_p + 2 - line_buf >= line_buf_size)
1162 int offset = copy_p - line_buf;
1164 line_buf = (char *) xrealloc (line_buf, line_buf_size);
1165 copy_p = line_buf + offset;
1170 return (got_unexpanded ? savestring (line_buf, copy_p - line_buf) : 0);
1173 /* Return 1 if pathname is absolute. */
1179 return (IS_DIR_SEPARATOR (path[0])
1180 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
1181 /* Check for disk name on MS-DOS-based systems. */
1182 || (path[0] && path[1] == ':' && IS_DIR_SEPARATOR (path[2]))
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
1198 abspath (cwd, rel_filename)
1200 const char *rel_filename;
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;
1209 /* Copy the filename (possibly preceded by the current working
1210 directory name) into the absolutization buffer. */
1215 if (! is_abspath (rel_filename))
1218 while ((*endp++ = *src_p++))
1220 *(endp-1) = DIR_SEPARATOR; /* overwrite null */
1222 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
1223 else if (IS_DIR_SEPARATOR (rel_filename[0]))
1225 /* A path starting with a directory separator is considered absolute
1226 for dos based filesystems, but it's really not -- it's just the
1227 convention used throughout GCC and it works. However, in this
1228 case, we still need to prepend the drive spec from cwd_buffer. */
1233 src_p = rel_filename;
1234 while ((*endp++ = *src_p++))
1238 /* Now make a copy of abs_buffer into abs_buffer, shortening the
1239 filename (by taking out slashes and dots) as we go. */
1241 outp = inp = abs_buffer;
1242 *outp++ = *inp++; /* copy first slash */
1243 #if defined (apollo) || defined (_WIN32) || defined (__INTERIX)
1244 if (IS_DIR_SEPARATOR (inp[0]))
1245 *outp++ = *inp++; /* copy second slash */
1251 else if (IS_DIR_SEPARATOR (inp[0]) && IS_DIR_SEPARATOR (outp[-1]))
1256 else if (inp[0] == '.' && IS_DIR_SEPARATOR (outp[-1]))
1260 else if (IS_DIR_SEPARATOR (inp[1]))
1265 else if ((inp[1] == '.') && (inp[2] == 0
1266 || IS_DIR_SEPARATOR (inp[2])))
1268 inp += (IS_DIR_SEPARATOR (inp[2])) ? 3 : 2;
1270 while (outp >= abs_buffer && ! IS_DIR_SEPARATOR (*outp))
1272 if (outp < abs_buffer)
1274 /* Catch cases like /.. where we try to backup to a
1275 point above the absolute root of the logical file
1278 notice ("%s: invalid file name: %s\n",
1279 pname, rel_filename);
1280 exit (FATAL_EXIT_CODE);
1289 /* On exit, make sure that there is a trailing null, and make sure that
1290 the last character of the returned string is *not* a slash. */
1293 if (IS_DIR_SEPARATOR (outp[-1]))
1296 /* Make a copy (in the heap) of the stuff left in the absolutization
1297 buffer and return a pointer to the copy. */
1299 return savestring (abs_buffer, outp - abs_buffer);
1302 /* Given a filename (and possibly a directory name from which the filename
1303 is relative) return a string which is the shortest possible
1304 equivalent for the corresponding full (absolutized) filename. The
1305 shortest possible equivalent may be constructed by converting the
1306 absolutized filename to be a relative filename (i.e. relative to
1307 the actual current working directory). However if a relative filename
1308 is longer, then the full absolute filename is returned.
1312 Note that "simple-minded" conversion of any given type of filename (either
1313 relative or absolute) may not result in a valid equivalent filename if any
1314 subpart of the original filename is actually a symbolic link. */
1317 shortpath (cwd, filename)
1319 const char *filename;
1323 char *cwd_p = cwd_buffer;
1325 int unmatched_slash_count = 0;
1326 size_t filename_len = strlen (filename);
1328 path_p = abspath (cwd, filename);
1329 rel_buf_p = rel_buffer = (char *) xmalloc (filename_len);
1331 while (*cwd_p && IS_SAME_PATH_CHAR (*cwd_p, *path_p))
1336 if (!*cwd_p && (!*path_p || IS_DIR_SEPARATOR (*path_p)))
1338 /* whole pwd matched */
1339 if (!*path_p) /* input *is* the current path! */
1350 while (! IS_DIR_SEPARATOR (*cwd_p)) /* backup to last slash */
1357 unmatched_slash_count++;
1360 /* Find out how many directory levels in cwd were *not* matched. */
1362 if (IS_DIR_SEPARATOR (*(cwd_p-1)))
1363 unmatched_slash_count++;
1365 /* Now we know how long the "short name" will be.
1366 Reject it if longer than the input. */
1367 if (unmatched_slash_count * 3 + strlen (path_p) >= filename_len)
1370 /* For each of them, put a `../' at the beginning of the short name. */
1371 while (unmatched_slash_count--)
1373 /* Give up if the result gets to be longer
1374 than the absolute path name. */
1375 if (rel_buffer + filename_len <= rel_buf_p + 3)
1379 *rel_buf_p++ = DIR_SEPARATOR;
1382 /* Then tack on the unmatched part of the desired file's name. */
1385 if (rel_buffer + filename_len <= rel_buf_p)
1388 while ((*rel_buf_p++ = *path_p++));
1391 if (IS_DIR_SEPARATOR (*(rel_buf_p-1)))
1392 *--rel_buf_p = '\0';
1397 /* Lookup the given filename in the hash table for filenames. If it is a
1398 new one, then the hash table info pointer will be null. In this case,
1399 we create a new file_info record to go with the filename, and we initialize
1400 that record with some reasonable values. */
1402 /* FILENAME was const, but that causes a warning on AIX when calling stat.
1403 That is probably a bug in AIX, but might as well avoid the warning. */
1406 find_file (filename, do_not_stat)
1407 const char *filename;
1410 hash_table_entry *hash_entry_p;
1412 hash_entry_p = lookup (filename_primary, filename);
1413 if (hash_entry_p->fip)
1414 return hash_entry_p->fip;
1417 struct stat stat_buf;
1418 file_info *file_p = (file_info *) xmalloc (sizeof (file_info));
1420 /* If we cannot get status on any given source file, give a warning
1421 and then just set its time of last modification to infinity. */
1424 stat_buf.st_mtime = (time_t) 0;
1427 if (stat (filename, &stat_buf) == -1)
1429 int errno_val = errno;
1430 notice ("%s: %s: can't get status: %s\n",
1431 pname, shortpath (NULL, filename),
1432 xstrerror (errno_val));
1433 stat_buf.st_mtime = (time_t) -1;
1437 hash_entry_p->fip = file_p;
1438 file_p->hash_entry = hash_entry_p;
1439 file_p->defs_decs = NULL;
1440 file_p->mtime = stat_buf.st_mtime;
1445 /* Generate a fatal error because some part of the aux_info file is
1449 aux_info_corrupted ()
1451 notice ("\n%s: fatal error: aux info file corrupted at line %d\n",
1452 pname, current_aux_info_lineno);
1453 exit (FATAL_EXIT_CODE);
1456 /* ??? This comment is vague. Say what the condition is for. */
1457 /* Check to see that a condition is true. This is kind of like an assert. */
1460 check_aux_info (cond)
1464 aux_info_corrupted ();
1467 /* Given a pointer to the closing right parenthesis for a particular formals
1468 list (in an aux_info file) find the corresponding left parenthesis and
1469 return a pointer to it. */
1472 find_corresponding_lparen (p)
1478 for (paren_depth = 1, q = p-1; paren_depth; q--)
1493 /* Given a line from an aux info file, and a time at which the aux info
1494 file it came from was created, check to see if the item described in
1495 the line comes from a file which has been modified since the aux info
1496 file was created. If so, return non-zero, else return zero. */
1499 referenced_file_is_newer (l, aux_info_mtime)
1501 time_t aux_info_mtime;
1507 check_aux_info (l[0] == '/');
1508 check_aux_info (l[1] == '*');
1509 check_aux_info (l[2] == ' ');
1512 const char *filename_start = p = l + 3;
1515 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
1516 || (*p == ':' && *p && *(p+1) && IS_DIR_SEPARATOR (*(p+1)))
1520 filename = (char *) alloca ((size_t) (p - filename_start) + 1);
1521 strncpy (filename, filename_start, (size_t) (p - filename_start));
1522 filename[p-filename_start] = '\0';
1525 /* Call find_file to find the file_info record associated with the file
1526 which contained this particular def or dec item. Note that this call
1527 may cause a new file_info record to be created if this is the first time
1528 that we have ever known about this particular file. */
1530 fi_p = find_file (abspath (invocation_filename, filename), 0);
1532 return (fi_p->mtime > aux_info_mtime);
1535 /* Given a line of info from the aux_info file, create a new
1536 def_dec_info record to remember all of the important information about
1537 a function definition or declaration.
1539 Link this record onto the list of such records for the particular file in
1540 which it occurred in proper (descending) line number order (for now).
1542 If there is an identical record already on the list for the file, throw
1543 this one away. Doing so takes care of the (useless and troublesome)
1544 duplicates which are bound to crop up due to multiple inclusions of any
1545 given individual header file.
1547 Finally, link the new def_dec record onto the list of such records
1548 pertaining to this particular function name. */
1551 save_def_or_dec (l, is_syscalls)
1556 const char *semicolon_p;
1557 def_dec_info *def_dec_p = (def_dec_info *) xmalloc (sizeof (def_dec_info));
1560 def_dec_p->written = 0;
1561 #endif /* !defined (UNPROTOIZE) */
1563 /* Start processing the line by picking off 5 pieces of information from
1564 the left hand end of the line. These are filename, line number,
1565 new/old/implicit flag (new = ANSI prototype format), definition or
1566 declaration flag, and extern/static flag). */
1568 check_aux_info (l[0] == '/');
1569 check_aux_info (l[1] == '*');
1570 check_aux_info (l[2] == ' ');
1573 const char *filename_start = p = l + 3;
1577 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
1578 || (*p == ':' && *p && *(p+1) && IS_DIR_SEPARATOR (*(p+1)))
1582 filename = (char *) alloca ((size_t) (p - filename_start) + 1);
1583 strncpy (filename, filename_start, (size_t) (p - filename_start));
1584 filename[p-filename_start] = '\0';
1586 /* Call find_file to find the file_info record associated with the file
1587 which contained this particular def or dec item. Note that this call
1588 may cause a new file_info record to be created if this is the first time
1589 that we have ever known about this particular file.
1591 Note that we started out by forcing all of the base source file names
1592 (i.e. the names of the aux_info files with the .X stripped off) into the
1593 filenames hash table, and we simultaneously setup file_info records for
1594 all of these base file names (even if they may be useless later).
1595 The file_info records for all of these "base" file names (properly)
1596 act as file_info records for the "original" (i.e. un-included) files
1597 which were submitted to gcc for compilation (when the -aux-info
1598 option was used). */
1600 def_dec_p->file = find_file (abspath (invocation_filename, filename), is_syscalls);
1604 const char *line_number_start = ++p;
1605 char line_number[10];
1608 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
1609 || (*p == ':' && *p && *(p+1) && IS_DIR_SEPARATOR (*(p+1)))
1613 strncpy (line_number, line_number_start, (size_t) (p - line_number_start));
1614 line_number[p-line_number_start] = '\0';
1615 def_dec_p->line = atoi (line_number);
1618 /* Check that this record describes a new-style, old-style, or implicit
1619 definition or declaration. */
1621 p++; /* Skip over the `:'. */
1622 check_aux_info ((*p == 'N') || (*p == 'O') || (*p == 'I'));
1624 /* Is this a new style (ANSI prototyped) definition or declaration? */
1626 def_dec_p->prototyped = (*p == 'N');
1630 /* Is this an implicit declaration? */
1632 def_dec_p->is_implicit = (*p == 'I');
1634 #endif /* !defined (UNPROTOIZE) */
1638 check_aux_info ((*p == 'C') || (*p == 'F'));
1640 /* Is this item a function definition (F) or a declaration (C). Note that
1641 we treat item taken from the syscalls file as though they were function
1642 definitions regardless of what the stuff in the file says. */
1644 def_dec_p->is_func_def = ((*p++ == 'F') || is_syscalls);
1647 def_dec_p->definition = 0; /* Fill this in later if protoizing. */
1648 #endif /* !defined (UNPROTOIZE) */
1650 check_aux_info (*p++ == ' ');
1651 check_aux_info (*p++ == '*');
1652 check_aux_info (*p++ == '/');
1653 check_aux_info (*p++ == ' ');
1656 check_aux_info ((!strncmp (p, "static", 6)) || (!strncmp (p, "extern", 6)));
1657 #else /* !defined (UNPROTOIZE) */
1658 if (!strncmp (p, "static", 6))
1659 def_dec_p->is_static = -1;
1660 else if (!strncmp (p, "extern", 6))
1661 def_dec_p->is_static = 0;
1663 check_aux_info (0); /* Didn't find either `extern' or `static'. */
1664 #endif /* !defined (UNPROTOIZE) */
1667 const char *ansi_start = p;
1669 p += 6; /* Pass over the "static" or "extern". */
1671 /* We are now past the initial stuff. Search forward from here to find
1672 the terminating semicolon that should immediately follow the entire
1673 ANSI format function declaration. */
1680 /* Make a copy of the ansi declaration part of the line from the aux_info
1683 def_dec_p->ansi_decl
1684 = dupnstr (ansi_start, (size_t) ((semicolon_p+1) - ansi_start));
1686 /* Backup and point at the final right paren of the final argument list. */
1691 def_dec_p->f_list_chain = NULL;
1692 #endif /* !defined (UNPROTOIZE) */
1694 while (p != ansi_start && (p[-1] == ' ' || p[-1] == '\t')) p--;
1697 free_def_dec (def_dec_p);
1702 /* Now isolate a whole set of formal argument lists, one-by-one. Normally,
1703 there will only be one list to isolate, but there could be more. */
1705 def_dec_p->f_list_count = 0;
1709 const char *left_paren_p = find_corresponding_lparen (p);
1712 f_list_chain_item *cip
1713 = (f_list_chain_item *) xmalloc (sizeof (f_list_chain_item));
1716 = dupnstr (left_paren_p + 1, (size_t) (p - (left_paren_p+1)));
1718 /* Add the new chain item at the head of the current list. */
1720 cip->chain_next = def_dec_p->f_list_chain;
1721 def_dec_p->f_list_chain = cip;
1723 #endif /* !defined (UNPROTOIZE) */
1724 def_dec_p->f_list_count++;
1726 p = left_paren_p - 2;
1728 /* p must now point either to another right paren, or to the last
1729 character of the name of the function that was declared/defined.
1730 If p points to another right paren, then this indicates that we
1731 are dealing with multiple formals lists. In that case, there
1732 really should be another right paren preceding this right paren. */
1737 check_aux_info (*--p == ')');
1742 const char *past_fn = p + 1;
1744 check_aux_info (*past_fn == ' ');
1746 /* Scan leftwards over the identifier that names the function. */
1748 while (is_id_char (*p))
1752 /* p now points to the leftmost character of the function name. */
1755 char *fn_string = (char *) alloca (past_fn - p + 1);
1757 strncpy (fn_string, p, (size_t) (past_fn - p));
1758 fn_string[past_fn-p] = '\0';
1759 def_dec_p->hash_entry = lookup (function_name_primary, fn_string);
1763 /* Look at all of the defs and decs for this function name that we have
1764 collected so far. If there is already one which is at the same
1765 line number in the same file, then we can discard this new def_dec_info
1768 As an extra assurance that any such pair of (nominally) identical
1769 function declarations are in fact identical, we also compare the
1770 ansi_decl parts of the lines from the aux_info files just to be on
1773 This comparison will fail if (for instance) the user was playing
1774 messy games with the preprocessor which ultimately causes one
1775 function declaration in one header file to look differently when
1776 that file is included by two (or more) other files. */
1779 const def_dec_info *other;
1781 for (other = def_dec_p->hash_entry->ddip; other; other = other->next_for_func)
1783 if (def_dec_p->line == other->line && def_dec_p->file == other->file)
1785 if (strcmp (def_dec_p->ansi_decl, other->ansi_decl))
1787 notice ("%s:%d: declaration of function `%s' takes different forms\n",
1788 def_dec_p->file->hash_entry->symbol,
1790 def_dec_p->hash_entry->symbol);
1791 exit (FATAL_EXIT_CODE);
1793 free_def_dec (def_dec_p);
1801 /* If we are doing unprotoizing, we must now setup the pointers that will
1802 point to the K&R name list and to the K&R argument declarations list.
1804 Note that if this is only a function declaration, then we should not
1805 expect to find any K&R style formals list following the ANSI-style
1806 formals list. This is because GCC knows that such information is
1807 useless in the case of function declarations (function definitions
1808 are a different story however).
1810 Since we are unprotoizing, we don't need any such lists anyway.
1811 All we plan to do is to delete all characters between ()'s in any
1814 def_dec_p->formal_names = NULL;
1815 def_dec_p->formal_decls = NULL;
1817 if (def_dec_p->is_func_def)
1820 check_aux_info (*++p == ' ');
1821 check_aux_info (*++p == '/');
1822 check_aux_info (*++p == '*');
1823 check_aux_info (*++p == ' ');
1824 check_aux_info (*++p == '(');
1827 const char *kr_names_start = ++p; /* Point just inside '('. */
1831 p--; /* point to closing right paren */
1833 /* Make a copy of the K&R parameter names list. */
1835 def_dec_p->formal_names
1836 = dupnstr (kr_names_start, (size_t) (p - kr_names_start));
1839 check_aux_info (*++p == ' ');
1842 /* p now points to the first character of the K&R style declarations
1843 list (if there is one) or to the star-slash combination that ends
1844 the comment in which such lists get embedded. */
1846 /* Make a copy of the K&R formal decls list and set the def_dec record
1849 if (*p == '*') /* Are there no K&R declarations? */
1851 check_aux_info (*++p == '/');
1852 def_dec_p->formal_decls = "";
1856 const char *kr_decls_start = p;
1858 while (p[0] != '*' || p[1] != '/')
1862 check_aux_info (*p == ' ');
1864 def_dec_p->formal_decls
1865 = dupnstr (kr_decls_start, (size_t) (p - kr_decls_start));
1868 /* Handle a special case. If we have a function definition marked as
1869 being in "old" style, and if its formal names list is empty, then
1870 it may actually have the string "void" in its real formals list
1871 in the original source code. Just to make sure, we will get setup
1872 to convert such things anyway.
1874 This kludge only needs to be here because of an insurmountable
1875 problem with generating .X files. */
1877 if (!def_dec_p->prototyped && !*def_dec_p->formal_names)
1878 def_dec_p->prototyped = 1;
1881 /* Since we are unprotoizing, if this item is already in old (K&R) style,
1882 we can just ignore it. If that is true, throw away the itme now. */
1884 if (!def_dec_p->prototyped)
1886 free_def_dec (def_dec_p);
1890 #endif /* defined (UNPROTOIZE) */
1892 /* Add this record to the head of the list of records pertaining to this
1893 particular function name. */
1895 def_dec_p->next_for_func = def_dec_p->hash_entry->ddip;
1896 def_dec_p->hash_entry->ddip = def_dec_p;
1898 /* Add this new def_dec_info record to the sorted list of def_dec_info
1899 records for this file. Note that we don't have to worry about duplicates
1900 (caused by multiple inclusions of header files) here because we have
1901 already eliminated duplicates above. */
1903 if (!def_dec_p->file->defs_decs)
1905 def_dec_p->file->defs_decs = def_dec_p;
1906 def_dec_p->next_in_file = NULL;
1910 int line = def_dec_p->line;
1911 const def_dec_info *prev = NULL;
1912 const def_dec_info *curr = def_dec_p->file->defs_decs;
1913 const def_dec_info *next = curr->next_in_file;
1915 while (next && (line < curr->line))
1919 next = next->next_in_file;
1921 if (line >= curr->line)
1923 def_dec_p->next_in_file = curr;
1925 ((NONCONST def_dec_info *) prev)->next_in_file = def_dec_p;
1927 def_dec_p->file->defs_decs = def_dec_p;
1929 else /* assert (next == NULL); */
1931 ((NONCONST def_dec_info *) curr)->next_in_file = def_dec_p;
1932 /* assert (next == NULL); */
1933 def_dec_p->next_in_file = next;
1938 /* Set up the vector COMPILE_PARAMS which is the argument list for running GCC.
1939 Also set input_file_name_index and aux_info_file_name_index
1940 to the indices of the slots where the file names should go. */
1942 /* We initialize the vector by removing -g, -O, -S, -c, and -o options,
1943 and adding '-aux-info AUXFILE -S -o /dev/null INFILE' at the end. */
1946 munge_compile_params (params_list)
1947 const char *params_list;
1949 /* Build up the contents in a temporary vector
1950 that is so big that to has to be big enough. */
1951 const char **temp_params
1952 = (const char **) alloca ((strlen (params_list) + 8) * sizeof (char *));
1953 int param_count = 0;
1957 temp_params[param_count++] = compiler_file_name;
1960 while (ISSPACE ((const unsigned char)*params_list))
1964 param = params_list;
1965 while (*params_list && !ISSPACE ((const unsigned char)*params_list))
1967 if (param[0] != '-')
1968 temp_params[param_count++]
1969 = dupnstr (param, (size_t) (params_list - param));
1978 break; /* Don't copy these. */
1980 while (ISSPACE ((const unsigned char)*params_list))
1983 && !ISSPACE ((const unsigned char)*params_list))
1987 temp_params[param_count++]
1988 = dupnstr (param, (size_t) (params_list - param));
1994 temp_params[param_count++] = "-aux-info";
1996 /* Leave room for the aux-info file name argument. */
1997 aux_info_file_name_index = param_count;
1998 temp_params[param_count++] = NULL;
2000 temp_params[param_count++] = "-S";
2001 temp_params[param_count++] = "-o";
2003 if ((stat (HOST_BIT_BUCKET, &st) == 0) && (!S_ISDIR (st.st_mode))
2004 (access (HOST_BIT_BUCKET, W_OK) == 0))
2005 temp_params[param_count++] = HOST_BIT_BUCKET;
2007 /* FIXME: This is hardly likely to be right, if HOST_BIT_BUCKET is not
2008 writable. But until this is rejigged to use make_temp_file(), this
2009 is the best we can do. */
2010 temp_params[param_count++] = "/dev/null";
2012 /* Leave room for the input file name argument. */
2013 input_file_name_index = param_count;
2014 temp_params[param_count++] = NULL;
2015 /* Terminate the list. */
2016 temp_params[param_count++] = NULL;
2018 /* Make a copy of the compile_params in heap space. */
2021 = (const char **) xmalloc (sizeof (char *) * (param_count+1));
2022 memcpy (compile_params, temp_params, sizeof (char *) * param_count);
2025 /* Do a recompilation for the express purpose of generating a new aux_info
2026 file to go with a specific base source file.
2028 The result is a boolean indicating success. */
2031 gen_aux_info_file (base_filename)
2032 const char *base_filename;
2034 if (!input_file_name_index)
2035 munge_compile_params ("");
2037 /* Store the full source file name in the argument vector. */
2038 compile_params[input_file_name_index] = shortpath (NULL, base_filename);
2039 /* Add .X to source file name to get aux-info file name. */
2040 compile_params[aux_info_file_name_index] =
2041 concat (compile_params[input_file_name_index], aux_info_suffix, NULL);
2044 notice ("%s: compiling `%s'\n",
2045 pname, compile_params[input_file_name_index]);
2048 char *errmsg_fmt, *errmsg_arg;
2049 int wait_status, pid;
2051 pid = pexecute (compile_params[0], (char * const *) compile_params,
2052 pname, NULL, &errmsg_fmt, &errmsg_arg,
2053 PEXECUTE_FIRST | PEXECUTE_LAST | PEXECUTE_SEARCH);
2057 int errno_val = errno;
2058 fprintf (stderr, "%s: ", pname);
2059 fprintf (stderr, errmsg_fmt, errmsg_arg);
2060 fprintf (stderr, ": %s\n", xstrerror (errno_val));
2064 pid = pwait (pid, &wait_status, 0);
2067 notice ("%s: wait: %s\n", pname, xstrerror (errno));
2070 if (WIFSIGNALED (wait_status))
2072 notice ("%s: subprocess got fatal signal %d\n",
2073 pname, WTERMSIG (wait_status));
2076 if (WIFEXITED (wait_status))
2078 if (WEXITSTATUS (wait_status) != 0)
2080 notice ("%s: %s exited with status %d\n",
2081 pname, compile_params[0], WEXITSTATUS (wait_status));
2090 /* Read in all of the information contained in a single aux_info file.
2091 Save all of the important stuff for later. */
2094 process_aux_info_file (base_source_filename, keep_it, is_syscalls)
2095 const char *base_source_filename;
2099 size_t base_len = strlen (base_source_filename);
2100 char * aux_info_filename
2101 = (char *) alloca (base_len + strlen (aux_info_suffix) + 1);
2102 char *aux_info_base;
2103 char *aux_info_limit;
2104 char *aux_info_relocated_name;
2105 const char *aux_info_second_line;
2106 time_t aux_info_mtime;
2107 size_t aux_info_size;
2110 /* Construct the aux_info filename from the base source filename. */
2112 strcpy (aux_info_filename, base_source_filename);
2113 strcat (aux_info_filename, aux_info_suffix);
2115 /* Check that the aux_info file exists and is readable. If it does not
2116 exist, try to create it (once only). */
2118 /* If file doesn't exist, set must_create.
2119 Likewise if it exists and we can read it but it is obsolete.
2120 Otherwise, report an error. */
2123 /* Come here with must_create set to 1 if file is out of date. */
2126 if (access (aux_info_filename, R_OK) == -1)
2128 if (errno == ENOENT)
2132 notice ("%s: warning: missing SYSCALLS file `%s'\n",
2133 pname, aux_info_filename);
2140 int errno_val = errno;
2141 notice ("%s: can't read aux info file `%s': %s\n",
2142 pname, shortpath (NULL, aux_info_filename),
2143 xstrerror (errno_val));
2148 #if 0 /* There is code farther down to take care of this. */
2152 stat (aux_info_file_name, &s1);
2153 stat (base_source_file_name, &s2);
2154 if (s2.st_mtime > s1.st_mtime)
2159 /* If we need a .X file, create it, and verify we can read it. */
2162 if (!gen_aux_info_file (base_source_filename))
2167 if (access (aux_info_filename, R_OK) == -1)
2169 int errno_val = errno;
2170 notice ("%s: can't read aux info file `%s': %s\n",
2171 pname, shortpath (NULL, aux_info_filename),
2172 xstrerror (errno_val));
2179 struct stat stat_buf;
2181 /* Get some status information about this aux_info file. */
2183 if (stat (aux_info_filename, &stat_buf) == -1)
2185 int errno_val = errno;
2186 notice ("%s: can't get status of aux info file `%s': %s\n",
2187 pname, shortpath (NULL, aux_info_filename),
2188 xstrerror (errno_val));
2193 /* Check on whether or not this aux_info file is zero length. If it is,
2194 then just ignore it and return. */
2196 if ((aux_info_size = stat_buf.st_size) == 0)
2199 /* Get the date/time of last modification for this aux_info file and
2200 remember it. We will have to check that any source files that it
2201 contains information about are at least this old or older. */
2203 aux_info_mtime = stat_buf.st_mtime;
2207 /* Compare mod time with the .c file; update .X file if obsolete.
2208 The code later on can fail to check the .c file
2209 if it did not directly define any functions. */
2211 if (stat (base_source_filename, &stat_buf) == -1)
2213 int errno_val = errno;
2214 notice ("%s: can't get status of aux info file `%s': %s\n",
2215 pname, shortpath (NULL, base_source_filename),
2216 xstrerror (errno_val));
2220 if (stat_buf.st_mtime > aux_info_mtime)
2232 /* Open the aux_info file. */
2234 fd_flags = O_RDONLY;
2236 /* Use binary mode to avoid having to deal with different EOL characters. */
2237 fd_flags |= O_BINARY;
2239 if ((aux_info_file = open (aux_info_filename, fd_flags, 0444 )) == -1)
2241 int errno_val = errno;
2242 notice ("%s: can't open aux info file `%s' for reading: %s\n",
2243 pname, shortpath (NULL, aux_info_filename),
2244 xstrerror (errno_val));
2248 /* Allocate space to hold the aux_info file in memory. */
2250 aux_info_base = xmalloc (aux_info_size + 1);
2251 aux_info_limit = aux_info_base + aux_info_size;
2252 *aux_info_limit = '\0';
2254 /* Read the aux_info file into memory. */
2256 if (safe_read (aux_info_file, aux_info_base, aux_info_size) !=
2257 (int) aux_info_size)
2259 int errno_val = errno;
2260 notice ("%s: error reading aux info file `%s': %s\n",
2261 pname, shortpath (NULL, aux_info_filename),
2262 xstrerror (errno_val));
2263 free (aux_info_base);
2264 close (aux_info_file);
2268 /* Close the aux info file. */
2270 if (close (aux_info_file))
2272 int errno_val = errno;
2273 notice ("%s: error closing aux info file `%s': %s\n",
2274 pname, shortpath (NULL, aux_info_filename),
2275 xstrerror (errno_val));
2276 free (aux_info_base);
2277 close (aux_info_file);
2282 /* Delete the aux_info file (unless requested not to). If the deletion
2283 fails for some reason, don't even worry about it. */
2285 if (must_create && !keep_it)
2286 if (unlink (aux_info_filename) == -1)
2288 int errno_val = errno;
2289 notice ("%s: can't delete aux info file `%s': %s\n",
2290 pname, shortpath (NULL, aux_info_filename),
2291 xstrerror (errno_val));
2294 /* Save a pointer into the first line of the aux_info file which
2295 contains the filename of the directory from which the compiler
2296 was invoked when the associated source file was compiled.
2297 This information is used later to help create complete
2298 filenames out of the (potentially) relative filenames in
2299 the aux_info file. */
2302 char *p = aux_info_base;
2305 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
2306 || (*p == ':' && *p && *(p+1) && IS_DIR_SEPARATOR (*(p+1)))
2313 invocation_filename = p; /* Save a pointer to first byte of path. */
2316 *p++ = DIR_SEPARATOR;
2318 while (*p++ != '\n')
2320 aux_info_second_line = p;
2321 aux_info_relocated_name = 0;
2322 if (! is_abspath (invocation_filename))
2324 /* INVOCATION_FILENAME is relative;
2325 append it to BASE_SOURCE_FILENAME's dir. */
2327 aux_info_relocated_name = xmalloc (base_len + (p-invocation_filename));
2328 strcpy (aux_info_relocated_name, base_source_filename);
2329 dir_end = strrchr (aux_info_relocated_name, DIR_SEPARATOR);
2330 #ifdef DIR_SEPARATOR_2
2334 slash = strrchr (dir_end ? dir_end : aux_info_relocated_name,
2343 dir_end = aux_info_relocated_name;
2344 strcpy (dir_end, invocation_filename);
2345 invocation_filename = aux_info_relocated_name;
2351 const char *aux_info_p;
2353 /* Do a pre-pass on the lines in the aux_info file, making sure that all
2354 of the source files referenced in there are at least as old as this
2355 aux_info file itself. If not, go back and regenerate the aux_info
2356 file anew. Don't do any of this for the syscalls file. */
2360 current_aux_info_lineno = 2;
2362 for (aux_info_p = aux_info_second_line; *aux_info_p; )
2364 if (referenced_file_is_newer (aux_info_p, aux_info_mtime))
2366 free (aux_info_base);
2367 free (aux_info_relocated_name);
2368 if (keep_it && unlink (aux_info_filename) == -1)
2370 int errno_val = errno;
2371 notice ("%s: can't delete file `%s': %s\n",
2372 pname, shortpath (NULL, aux_info_filename),
2373 xstrerror (errno_val));
2380 /* Skip over the rest of this line to start of next line. */
2382 while (*aux_info_p != '\n')
2385 current_aux_info_lineno++;
2389 /* Now do the real pass on the aux_info lines. Save their information in
2390 the in-core data base. */
2392 current_aux_info_lineno = 2;
2394 for (aux_info_p = aux_info_second_line; *aux_info_p;)
2396 char *unexpanded_line = unexpand_if_needed (aux_info_p);
2398 if (unexpanded_line)
2400 save_def_or_dec (unexpanded_line, is_syscalls);
2401 free (unexpanded_line);
2404 save_def_or_dec (aux_info_p, is_syscalls);
2406 /* Skip over the rest of this line and get to start of next line. */
2408 while (*aux_info_p != '\n')
2411 current_aux_info_lineno++;
2415 free (aux_info_base);
2416 free (aux_info_relocated_name);
2421 /* Check an individual filename for a .c suffix. If the filename has this
2422 suffix, rename the file such that its suffix is changed to .C. This
2423 function implements the -C option. */
2427 const hash_table_entry *hp;
2429 const char *filename = hp->symbol;
2430 int last_char_index = strlen (filename) - 1;
2431 char *const new_filename = (char *) alloca (strlen (filename)
2432 + strlen (cplus_suffix) + 1);
2434 /* Note that we don't care here if the given file was converted or not. It
2435 is possible that the given file was *not* converted, simply because there
2436 was nothing in it which actually required conversion. Even in this case,
2437 we want to do the renaming. Note that we only rename files with the .c
2438 suffix (except for the syscalls file, which is left alone). */
2440 if (filename[last_char_index] != 'c' || filename[last_char_index-1] != '.'
2441 || IS_SAME_PATH (syscalls_absolute_filename, filename))
2444 strcpy (new_filename, filename);
2445 strcpy (&new_filename[last_char_index], cplus_suffix);
2447 if (rename (filename, new_filename) == -1)
2449 int errno_val = errno;
2450 notice ("%s: warning: can't rename file `%s' to `%s': %s\n",
2451 pname, shortpath (NULL, filename),
2452 shortpath (NULL, new_filename), xstrerror (errno_val));
2458 #endif /* !defined (UNPROTOIZE) */
2460 /* Take the list of definitions and declarations attached to a particular
2461 file_info node and reverse the order of the list. This should get the
2462 list into an order such that the item with the lowest associated line
2463 number is nearest the head of the list. When these lists are originally
2464 built, they are in the opposite order. We want to traverse them in
2465 normal line number order later (i.e. lowest to highest) so reverse the
2469 reverse_def_dec_list (hp)
2470 const hash_table_entry *hp;
2472 file_info *file_p = hp->fip;
2473 def_dec_info *prev = NULL;
2474 def_dec_info *current = (def_dec_info *)file_p->defs_decs;
2477 return; /* no list to reverse */
2480 if (! (current = (def_dec_info *)current->next_in_file))
2481 return; /* can't reverse a single list element */
2483 prev->next_in_file = NULL;
2487 def_dec_info *next = (def_dec_info *)current->next_in_file;
2489 current->next_in_file = prev;
2494 file_p->defs_decs = prev;
2499 /* Find the (only?) extern definition for a particular function name, starting
2500 from the head of the linked list of entries for the given name. If we
2501 cannot find an extern definition for the given function name, issue a
2502 warning and scrounge around for the next best thing, i.e. an extern
2503 function declaration with a prototype attached to it. Note that we only
2504 allow such substitutions for extern declarations and never for static
2505 declarations. That's because the only reason we allow them at all is
2506 to let un-prototyped function declarations for system-supplied library
2507 functions get their prototypes from our own extra SYSCALLS.c.X file which
2508 contains all of the correct prototypes for system functions. */
2510 static const def_dec_info *
2511 find_extern_def (head, user)
2512 const def_dec_info *head;
2513 const def_dec_info *user;
2515 const def_dec_info *dd_p;
2516 const def_dec_info *extern_def_p = NULL;
2517 int conflict_noted = 0;
2519 /* Don't act too stupid here. Somebody may try to convert an entire system
2520 in one swell fwoop (rather than one program at a time, as should be done)
2521 and in that case, we may find that there are multiple extern definitions
2522 of a given function name in the entire set of source files that we are
2523 converting. If however one of these definitions resides in exactly the
2524 same source file as the reference we are trying to satisfy then in that
2525 case it would be stupid for us to fail to realize that this one definition
2526 *must* be the precise one we are looking for.
2528 To make sure that we don't miss an opportunity to make this "same file"
2529 leap of faith, we do a prescan of the list of records relating to the
2530 given function name, and we look (on this first scan) *only* for a
2531 definition of the function which is in the same file as the reference
2532 we are currently trying to satisfy. */
2534 for (dd_p = head; dd_p; dd_p = dd_p->next_for_func)
2535 if (dd_p->is_func_def && !dd_p->is_static && dd_p->file == user->file)
2538 /* Now, since we have not found a definition in the same file as the
2539 reference, we scan the list again and consider all possibilities from
2540 all files. Here we may get conflicts with the things listed in the
2541 SYSCALLS.c.X file, but if that happens it only means that the source
2542 code being converted contains its own definition of a function which
2543 could have been supplied by libc.a. In such cases, we should avoid
2544 issuing the normal warning, and defer to the definition given in the
2547 for (dd_p = head; dd_p; dd_p = dd_p->next_for_func)
2548 if (dd_p->is_func_def && !dd_p->is_static)
2550 if (!extern_def_p) /* Previous definition? */
2551 extern_def_p = dd_p; /* Remember the first definition found. */
2554 /* Ignore definition just found if it came from SYSCALLS.c.X. */
2556 if (is_syscalls_file (dd_p->file))
2559 /* Quietly replace the definition previously found with the one
2560 just found if the previous one was from SYSCALLS.c.X. */
2562 if (is_syscalls_file (extern_def_p->file))
2564 extern_def_p = dd_p;
2568 /* If we get here, then there is a conflict between two function
2569 declarations for the same function, both of which came from the
2572 if (!conflict_noted) /* first time we noticed? */
2575 notice ("%s: conflicting extern definitions of '%s'\n",
2576 pname, head->hash_entry->symbol);
2579 notice ("%s: declarations of '%s' will not be converted\n",
2580 pname, head->hash_entry->symbol);
2581 notice ("%s: conflict list for '%s' follows:\n",
2582 pname, head->hash_entry->symbol);
2583 fprintf (stderr, "%s: %s(%d): %s\n",
2585 shortpath (NULL, extern_def_p->file->hash_entry->symbol),
2586 extern_def_p->line, extern_def_p->ansi_decl);
2590 fprintf (stderr, "%s: %s(%d): %s\n",
2592 shortpath (NULL, dd_p->file->hash_entry->symbol),
2593 dd_p->line, dd_p->ansi_decl);
2597 /* We want to err on the side of caution, so if we found multiple conflicting
2598 definitions for the same function, treat this as being that same as if we
2599 had found no definitions (i.e. return NULL). */
2606 /* We have no definitions for this function so do the next best thing.
2607 Search for an extern declaration already in prototype form. */
2609 for (dd_p = head; dd_p; dd_p = dd_p->next_for_func)
2610 if (!dd_p->is_func_def && !dd_p->is_static && dd_p->prototyped)
2612 extern_def_p = dd_p; /* save a pointer to the definition */
2614 notice ("%s: warning: using formals list from %s(%d) for function `%s'\n",
2616 shortpath (NULL, dd_p->file->hash_entry->symbol),
2617 dd_p->line, dd_p->hash_entry->symbol);
2621 /* Gripe about unprototyped function declarations that we found no
2622 corresponding definition (or other source of prototype information)
2625 Gripe even if the unprototyped declaration we are worried about
2626 exists in a file in one of the "system" include directories. We
2627 can gripe about these because we should have at least found a
2628 corresponding (pseudo) definition in the SYSCALLS.c.X file. If we
2629 didn't, then that means that the SYSCALLS.c.X file is missing some
2630 needed prototypes for this particular system. That is worth telling
2635 const char *file = user->file->hash_entry->symbol;
2638 if (in_system_include_dir (file))
2640 /* Why copy this string into `needed' at all?
2641 Why not just use user->ansi_decl without copying? */
2642 char *needed = (char *) alloca (strlen (user->ansi_decl) + 1);
2645 strcpy (needed, user->ansi_decl);
2646 p = (NONCONST char *) substr (needed, user->hash_entry->symbol)
2647 + strlen (user->hash_entry->symbol) + 2;
2648 /* Avoid having ??? in the string. */
2654 notice ("%s: %d: `%s' used but missing from SYSCALLS\n",
2655 shortpath (NULL, file), user->line,
2656 needed+7); /* Don't print "extern " */
2660 notice ("%s: %d: warning: no extern definition for `%s'\n",
2661 shortpath (NULL, file), user->line,
2662 user->hash_entry->symbol);
2666 return extern_def_p;
2669 /* Find the (only?) static definition for a particular function name in a
2670 given file. Here we get the function-name and the file info indirectly
2671 from the def_dec_info record pointer which is passed in. */
2673 static const def_dec_info *
2674 find_static_definition (user)
2675 const def_dec_info *user;
2677 const def_dec_info *head = user->hash_entry->ddip;
2678 const def_dec_info *dd_p;
2679 int num_static_defs = 0;
2680 const def_dec_info *static_def_p = NULL;
2682 for (dd_p = head; dd_p; dd_p = dd_p->next_for_func)
2683 if (dd_p->is_func_def && dd_p->is_static && (dd_p->file == user->file))
2685 static_def_p = dd_p; /* save a pointer to the definition */
2688 if (num_static_defs == 0)
2691 notice ("%s: warning: no static definition for `%s' in file `%s'\n",
2692 pname, head->hash_entry->symbol,
2693 shortpath (NULL, user->file->hash_entry->symbol));
2695 else if (num_static_defs > 1)
2697 notice ("%s: multiple static defs of `%s' in file `%s'\n",
2698 pname, head->hash_entry->symbol,
2699 shortpath (NULL, user->file->hash_entry->symbol));
2702 return static_def_p;
2705 /* Find good prototype style formal argument lists for all of the function
2706 declarations which didn't have them before now.
2708 To do this we consider each function name one at a time. For each function
2709 name, we look at the items on the linked list of def_dec_info records for
2710 that particular name.
2712 Somewhere on this list we should find one (and only one) def_dec_info
2713 record which represents the actual function definition, and this record
2714 should have a nice formal argument list already associated with it.
2716 Thus, all we have to do is to connect up all of the other def_dec_info
2717 records for this particular function name to the special one which has
2718 the full-blown formals list.
2720 Of course it is a little more complicated than just that. See below for
2724 connect_defs_and_decs (hp)
2725 const hash_table_entry *hp;
2727 const def_dec_info *dd_p;
2728 const def_dec_info *extern_def_p = NULL;
2729 int first_extern_reference = 1;
2731 /* Traverse the list of definitions and declarations for this particular
2732 function name. For each item on the list, if it is a function
2733 definition (either old style or new style) then GCC has already been
2734 kind enough to produce a prototype for us, and it is associated with
2735 the item already, so declare the item as its own associated "definition".
2737 Also, for each item which is only a function declaration, but which
2738 nonetheless has its own prototype already (obviously supplied by the user)
2739 declare the item as its own definition.
2741 Note that when/if there are multiple user-supplied prototypes already
2742 present for multiple declarations of any given function, these multiple
2743 prototypes *should* all match exactly with one another and with the
2744 prototype for the actual function definition. We don't check for this
2745 here however, since we assume that the compiler must have already done
2746 this consistency checking when it was creating the .X files. */
2748 for (dd_p = hp->ddip; dd_p; dd_p = dd_p->next_for_func)
2749 if (dd_p->prototyped)
2750 ((NONCONST def_dec_info *) dd_p)->definition = dd_p;
2752 /* Traverse the list of definitions and declarations for this particular
2753 function name. For each item on the list, if it is an extern function
2754 declaration and if it has no associated definition yet, go try to find
2755 the matching extern definition for the declaration.
2757 When looking for the matching function definition, warn the user if we
2760 If we find more that one function definition also issue a warning.
2762 Do the search for the matching definition only once per unique function
2763 name (and only when absolutely needed) so that we can avoid putting out
2764 redundant warning messages, and so that we will only put out warning
2765 messages when there is actually a reference (i.e. a declaration) for
2766 which we need to find a matching definition. */
2768 for (dd_p = hp->ddip; dd_p; dd_p = dd_p->next_for_func)
2769 if (!dd_p->is_func_def && !dd_p->is_static && !dd_p->definition)
2771 if (first_extern_reference)
2773 extern_def_p = find_extern_def (hp->ddip, dd_p);
2774 first_extern_reference = 0;
2776 ((NONCONST def_dec_info *) dd_p)->definition = extern_def_p;
2779 /* Traverse the list of definitions and declarations for this particular
2780 function name. For each item on the list, if it is a static function
2781 declaration and if it has no associated definition yet, go try to find
2782 the matching static definition for the declaration within the same file.
2784 When looking for the matching function definition, warn the user if we
2785 fail to find one in the same file with the declaration, and refuse to
2786 convert this kind of cross-file static function declaration. After all,
2787 this is stupid practice and should be discouraged.
2789 We don't have to worry about the possibility that there is more than one
2790 matching function definition in the given file because that would have
2791 been flagged as an error by the compiler.
2793 Do the search for the matching definition only once per unique
2794 function-name/source-file pair (and only when absolutely needed) so that
2795 we can avoid putting out redundant warning messages, and so that we will
2796 only put out warning messages when there is actually a reference (i.e. a
2797 declaration) for which we actually need to find a matching definition. */
2799 for (dd_p = hp->ddip; dd_p; dd_p = dd_p->next_for_func)
2800 if (!dd_p->is_func_def && dd_p->is_static && !dd_p->definition)
2802 const def_dec_info *dd_p2;
2803 const def_dec_info *static_def;
2805 /* We have now found a single static declaration for which we need to
2806 find a matching definition. We want to minimize the work (and the
2807 number of warnings), so we will find an appropriate (matching)
2808 static definition for this declaration, and then distribute it
2809 (as the definition for) any and all other static declarations
2810 for this function name which occur within the same file, and which
2811 do not already have definitions.
2813 Note that a trick is used here to prevent subsequent attempts to
2814 call find_static_definition for a given function-name & file
2815 if the first such call returns NULL. Essentially, we convert
2816 these NULL return values to -1, and put the -1 into the definition
2817 field for each other static declaration from the same file which
2818 does not already have an associated definition.
2819 This makes these other static declarations look like they are
2820 actually defined already when the outer loop here revisits them
2821 later on. Thus, the outer loop will skip over them. Later, we
2822 turn the -1's back to NULL's. */
2824 ((NONCONST def_dec_info *) dd_p)->definition =
2825 (static_def = find_static_definition (dd_p))
2827 : (const def_dec_info *) -1;
2829 for (dd_p2 = dd_p->next_for_func; dd_p2; dd_p2 = dd_p2->next_for_func)
2830 if (!dd_p2->is_func_def && dd_p2->is_static
2831 && !dd_p2->definition && (dd_p2->file == dd_p->file))
2832 ((NONCONST def_dec_info *)dd_p2)->definition = dd_p->definition;
2835 /* Convert any dummy (-1) definitions we created in the step above back to
2836 NULL's (as they should be). */
2838 for (dd_p = hp->ddip; dd_p; dd_p = dd_p->next_for_func)
2839 if (dd_p->definition == (def_dec_info *) -1)
2840 ((NONCONST def_dec_info *) dd_p)->definition = NULL;
2843 #endif /* !defined (UNPROTOIZE) */
2845 /* Give a pointer into the clean text buffer, return a number which is the
2846 original source line number that the given pointer points into. */
2849 identify_lineno (clean_p)
2850 const char *clean_p;
2855 for (scan_p = clean_text_base; scan_p <= clean_p; scan_p++)
2856 if (*scan_p == '\n')
2861 /* Issue an error message and give up on doing this particular edit. */
2864 declare_source_confusing (clean_p)
2865 const char *clean_p;
2870 notice ("%s: %d: warning: source too confusing\n",
2871 shortpath (NULL, convert_filename), last_known_line_number);
2873 notice ("%s: %d: warning: source too confusing\n",
2874 shortpath (NULL, convert_filename),
2875 identify_lineno (clean_p));
2877 longjmp (source_confusion_recovery, 1);
2880 /* Check that a condition which is expected to be true in the original source
2881 code is in fact true. If not, issue an error message and give up on
2882 converting this particular source file. */
2885 check_source (cond, clean_p)
2887 const char *clean_p;
2890 declare_source_confusing (clean_p);
2893 /* If we think of the in-core cleaned text buffer as a memory mapped
2894 file (with the variable last_known_line_start acting as sort of a
2895 file pointer) then we can imagine doing "seeks" on the buffer. The
2896 following routine implements a kind of "seek" operation for the in-core
2897 (cleaned) copy of the source file. When finished, it returns a pointer to
2898 the start of a given (numbered) line in the cleaned text buffer.
2900 Note that protoize only has to "seek" in the forward direction on the
2901 in-core cleaned text file buffers, and it never needs to back up.
2903 This routine is made a little bit faster by remembering the line number
2904 (and pointer value) supplied (and returned) from the previous "seek".
2905 This prevents us from always having to start all over back at the top
2906 of the in-core cleaned buffer again. */
2912 if (n < last_known_line_number)
2915 while (n > last_known_line_number)
2917 while (*last_known_line_start != '\n')
2918 check_source (++last_known_line_start < clean_text_limit, 0);
2919 last_known_line_start++;
2920 last_known_line_number++;
2922 return last_known_line_start;
2925 /* Given a pointer to a character in the cleaned text buffer, return a pointer
2926 to the next non-whitespace character which follows it. */
2929 forward_to_next_token_char (ptr)
2932 for (++ptr; ISSPACE ((const unsigned char)*ptr);
2933 check_source (++ptr < clean_text_limit, 0))
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. */
2943 output_bytes (str, len)
2947 if ((repl_write_ptr + 1) + len >= repl_text_limit)
2949 size_t new_size = (repl_text_limit - repl_text_base) << 1;
2950 char *new_buf = (char *) xrealloc (repl_text_base, new_size);
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;
2956 memcpy (repl_write_ptr + 1, str, len);
2957 repl_write_ptr += len;
2960 /* Copy all bytes (except the trailing null) of a null terminated string to
2961 the current output buffer. */
2967 output_bytes (str, strlen (str));
2970 /* Copy some characters from the original text buffer to the current output
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'.
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
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.
2986 Note that the request implied when this routine is called includes the
2987 byte pointed to by the argument pointer `p'. */
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;
2996 if (copy_length == 0)
2999 output_bytes (copy_start, copy_length);
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
3010 other_variable_style_function (ansi_header)
3011 const char *ansi_header;
3015 /* See if we have a stdarg function, or a function which has stdarg style
3016 parameters or a stdarg style return type. */
3018 return substr (ansi_header, "...") != 0;
3020 #else /* !defined (UNPROTOIZE) */
3022 /* See if we have a varargs function, or a function which has varargs style
3023 parameters or a varargs style return type. */
3026 int len = strlen (varargs_style_indicator);
3028 for (p = ansi_header; p; )
3030 const char *candidate;
3032 if ((candidate = substr (p, varargs_style_indicator)) == 0)
3035 if (!is_id_char (candidate[-1]) && !is_id_char (candidate[len]))
3041 #endif /* !defined (UNPROTOIZE) */
3044 /* Do the editing operation specifically for a function "declaration". Note
3045 that editing for function "definitions" are handled in a separate routine
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;
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;
3061 const f_list_chain_item *this_f_list_chain_item;
3062 const def_dec_info *definition = def_dec_p->definition;
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. */
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. */
3076 if (other_variable_style_function (definition->ansi_decl))
3079 notice ("%s: %d: warning: varargs function declaration not converted\n",
3080 shortpath (NULL, def_dec_p->file->hash_entry->symbol),
3085 #endif /* !defined (UNPROTOIZE) */
3087 /* Setup here to recover from confusing source code detected during this
3088 particular "edit". */
3091 if (setjmp (source_confusion_recovery))
3093 restore_pointers ();
3094 notice ("%s: declaration of function `%s' not converted\n",
3095 pname, function_to_edit);
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. */
3108 /* First move up to the end of the line. */
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. */
3114 /* Now we can scan backwards for the function name. */
3120 /* Scan leftwards until we find some character which can be
3121 part of an identifier. */
3123 while (!is_id_char (*clean_text_p))
3124 check_source (--clean_text_p > clean_read_ptr, 0);
3126 /* Scan backwards until we find a char that cannot be part of an
3129 while (is_id_char (*clean_text_p))
3130 check_source (--clean_text_p > clean_read_ptr, 0);
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. */
3135 if (!strncmp (clean_text_p+1, function_to_edit, func_name_len))
3137 char ch = *(clean_text_p + 1 + func_name_len);
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. */
3143 if (! is_id_char (ch))
3144 break; /* exit from loop */
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! */
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);
3163 while (*start_formals != '(');
3165 /* start_of_formals now points to the opening left paren which immediately
3166 follows the name of the function. */
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. */
3174 this_f_list_chain_item = definition->f_list_chain;
3175 #endif /* !defined (UNPROTOIZE) */
3182 end_formals = start_formals + 1;
3184 for (; depth; check_source (++end_formals < clean_text_limit, 0))
3186 switch (*end_formals)
3199 /* end_formals now points to the closing right paren of the formals
3200 list whose left paren is pointed to by start_formals. */
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
3207 output_up_to (start_formals);
3209 if (this_f_list_chain_item)
3211 output_string (this_f_list_chain_item->formals_list);
3212 this_f_list_chain_item = this_f_list_chain_item->chain_next;
3217 notice ("%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 */
3221 #endif /* !defined (UNPROTOIZE) */
3222 clean_read_ptr = end_formals - 1;
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. */
3229 const char *another_r_paren = forward_to_next_token_char (end_formals);
3231 if ((*another_r_paren != ')')
3232 || (*(start_formals = forward_to_next_token_char (another_r_paren)) != '('))
3235 if (this_f_list_chain_item)
3238 notice ("\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 */
3242 #endif /* !defined (UNPROTOIZE) */
3248 /* There does appear to be yet another formals list, so loop around
3249 again, and convert it also. */
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.
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). */
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;
3270 const char *start_formals;
3273 start_formals = end_formals - 1;
3275 for (; depth; check_source (--start_formals > clean_read_ptr, 0))
3277 switch (*start_formals)
3289 /* start_formals now points to the opening left paren of the formals list. */
3295 const char *next_end;
3297 /* There should be more formal lists to the left of here. */
3299 next_end = start_formals - 1;
3300 check_source (next_end > clean_read_ptr, 0);
3301 while (ISSPACE ((const unsigned char)*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))
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
3314 if (f_list_count == 0)
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;
3321 for (func_name_limit = start_formals-1;
3322 ISSPACE ((const unsigned char)*func_name_limit); )
3323 check_source (--func_name_limit > clean_read_ptr, 0);
3325 for (func_name_start = func_name_limit++;
3326 is_id_char (*func_name_start);
3328 check_source (func_name_start > clean_read_ptr, 0);
3330 func_name_len = func_name_limit - func_name_start;
3331 if (func_name_len == 0)
3332 check_source (0, func_name_start);
3333 if (func_name_len != strlen (expected)
3334 || strncmp (func_name_start, expected, func_name_len))
3336 notice ("%s: %d: warning: found `%s' but expected `%s'\n",
3337 shortpath (NULL, def_dec_p->file->hash_entry->symbol),
3338 identify_lineno (func_name_start),
3339 dupnstr (func_name_start, func_name_len),
3345 output_up_to (start_formals);
3348 if (f_list_count == 0)
3349 output_string (def_dec_p->formal_names);
3350 #else /* !defined (UNPROTOIZE) */
3352 unsigned f_list_depth;
3353 const f_list_chain_item *flci_p = def_dec_p->f_list_chain;
3355 /* At this point, the current value of f_list count says how many
3356 links we have to follow through the f_list_chain to get to the
3357 particular formals list that we need to output next. */
3359 for (f_list_depth = 0; f_list_depth < f_list_count; f_list_depth++)
3360 flci_p = flci_p->chain_next;
3361 output_string (flci_p->formals_list);
3363 #endif /* !defined (UNPROTOIZE) */
3365 clean_read_ptr = end_formals - 1;
3369 /* Given a pointer to a byte in the clean text buffer which points to
3370 the beginning of a line that contains a "follower" token for a
3371 function definition header, do whatever is necessary to find the
3372 right closing paren for the rightmost formals list of the function
3373 definition header. */
3376 find_rightmost_formals_list (clean_text_p)
3377 const char *clean_text_p;
3379 const char *end_formals;
3381 /* We are editing a function definition. The line number we did a seek
3382 to contains the first token which immediately follows the entire set of
3383 formals lists which are part of this particular function definition
3386 Our job now is to scan leftwards in the clean text looking for the
3387 right-paren which is at the end of the function header's rightmost
3390 If we ignore whitespace, this right paren should be the first one we
3391 see which is (ignoring whitespace) immediately followed either by the
3392 open curly-brace beginning the function body or by an alphabetic
3393 character (in the case where the function definition is in old (K&R)
3394 style and there are some declarations of formal parameters). */
3396 /* It is possible that the right paren we are looking for is on the
3397 current line (together with its following token). Just in case that
3398 might be true, we start out here by skipping down to the right end of
3399 the current line before starting our scan. */
3401 for (end_formals = clean_text_p; *end_formals != '\n'; end_formals++)
3407 /* Now scan backwards while looking for the right end of the rightmost
3408 formals list associated with this function definition. */
3412 const char *l_brace_p;
3414 /* Look leftward and try to find a right-paren. */
3416 while (*end_formals != ')')
3418 if (ISSPACE ((unsigned char)*end_formals))
3419 while (ISSPACE ((unsigned char)*end_formals))
3420 check_source (--end_formals > clean_read_ptr, 0);
3422 check_source (--end_formals > clean_read_ptr, 0);
3425 ch = *(l_brace_p = forward_to_next_token_char (end_formals));
3426 /* Since we are unprotoizing an ANSI-style (prototyped) function
3427 definition, there had better not be anything (except whitespace)
3428 between the end of the ANSI formals list and the beginning of the
3429 function body (i.e. the '{'). */
3431 check_source (ch == '{', l_brace_p);
3434 #else /* !defined (UNPROTOIZE) */
3436 /* Now scan backwards while looking for the right end of the rightmost
3437 formals list associated with this function definition. */
3442 const char *l_brace_p;
3444 /* Look leftward and try to find a right-paren. */
3446 while (*end_formals != ')')
3448 if (ISSPACE ((const unsigned char)*end_formals))
3449 while (ISSPACE ((const unsigned char)*end_formals))
3450 check_source (--end_formals > clean_read_ptr, 0);
3452 check_source (--end_formals > clean_read_ptr, 0);
3455 ch = *(l_brace_p = forward_to_next_token_char (end_formals));
3457 /* Since it is possible that we found a right paren before the starting
3458 '{' of the body which IS NOT the one at the end of the real K&R
3459 formals list (say for instance, we found one embedded inside one of
3460 the old K&R formal parameter declarations) we have to check to be
3461 sure that this is in fact the right paren that we were looking for.
3463 The one we were looking for *must* be followed by either a '{' or
3464 by an alphabetic character, while others *cannot* validly be followed
3465 by such characters. */
3467 if ((ch == '{') || ISALPHA ((unsigned char)ch))
3470 /* At this point, we have found a right paren, but we know that it is
3471 not the one we were looking for, so backup one character and keep
3474 check_source (--end_formals > clean_read_ptr, 0);
3477 #endif /* !defined (UNPROTOIZE) */
3484 /* Insert into the output file a totally new declaration for a function
3485 which (up until now) was being called from within the current block
3486 without having been declared at any point such that the declaration
3487 was visible (i.e. in scope) at the point of the call.
3489 We need to add in explicit declarations for all such function calls
3490 in order to get the full benefit of prototype-based function call
3491 parameter type checking. */
3494 add_local_decl (def_dec_p, clean_text_p)
3495 const def_dec_info *def_dec_p;
3496 const char *clean_text_p;
3498 const char *start_of_block;
3499 const char *function_to_edit = def_dec_p->hash_entry->symbol;
3501 /* Don't insert new local explicit declarations unless explicitly requested
3507 /* Setup here to recover from confusing source code detected during this
3508 particular "edit". */
3511 if (setjmp (source_confusion_recovery))
3513 restore_pointers ();
3514 notice ("%s: local declaration for function `%s' not inserted\n",
3515 pname, function_to_edit);
3519 /* We have already done a seek to the start of the line which should
3520 contain *the* open curly brace which begins the block in which we need
3521 to insert an explicit function declaration (to replace the implicit one).
3523 Now we scan that line, starting from the left, until we find the
3524 open curly brace we are looking for. Note that there may actually be
3525 multiple open curly braces on the given line, but we will be happy
3526 with the leftmost one no matter what. */
3528 start_of_block = clean_text_p;
3529 while (*start_of_block != '{' && *start_of_block != '\n')
3530 check_source (++start_of_block < clean_text_limit, 0);
3532 /* Note that the line from the original source could possibly
3533 contain *no* open curly braces! This happens if the line contains
3534 a macro call which expands into a chunk of text which includes a
3535 block (and that block's associated open and close curly braces).
3536 In cases like this, we give up, issue a warning, and do nothing. */
3538 if (*start_of_block != '{')
3541 notice ("\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);
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). */
3553 const char *ep = forward_to_next_token_char (start_of_block) - 1;
3556 /* Now we have ep pointing at the rightmost byte of some existing indent
3557 stuff. At least that is the hope.
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. */
3562 for (sp = ep; ISSPACE ((const unsigned char)*sp) && *sp != '\n'; sp--)
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
3571 /* Now we go ahead and insert the new declaration at this point.
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'. */
3578 const char *decl = def_dec_p->definition->ansi_decl;
3580 if ((*decl == 'e') && (def_dec_p->file == def_dec_p->definition->file))
3582 output_string (decl);
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. */
3589 output_bytes (sp, (size_t) (ep - sp) + 1);
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. */
3601 add_global_decls (file_p, clean_text_p)
3602 const file_info *file_p;
3603 const char *clean_text_p;
3605 const def_dec_info *dd_p;
3608 /* Setup here to recover from confusing source code detected during this
3609 particular "edit". */
3612 if (setjmp (source_confusion_recovery))
3614 restore_pointers ();
3615 notice ("%s: global declarations for file `%s' not inserted\n",
3616 pname, shortpath (NULL, file_p->hash_entry->symbol));
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. */
3625 scan_p = find_rightmost_formals_list (clean_text_p);
3628 if (scan_p < clean_text_base)
3630 check_source (scan_p > clean_read_ptr, 0);
3635 /* scan_p now points either to a semicolon, or to just before the start
3636 of the whole file. */
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. */
3643 while (ISSPACE ((const unsigned char)*scan_p))
3647 output_up_to (scan_p);
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. */
3655 int some_decls_added = 0;
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)
3660 const char *decl = dd_p->definition->ansi_decl;
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). */
3666 if (*decl == 'e' && (dd_p->file == dd_p->definition->file))
3669 output_string ("\n");
3670 output_string (decl);
3671 some_decls_added = 1;
3672 ((NONCONST def_dec_info *) dd_p->definition)->written = 1;
3674 if (some_decls_added)
3675 output_string ("\n\n");
3678 /* Unmark all of the definitions that we just marked. */
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;
3685 #endif /* !defined (UNPROTOIZE) */
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. */
3692 edit_fn_definition (def_dec_p, clean_text_p)
3693 const def_dec_info *def_dec_p;
3694 const char *clean_text_p;
3696 const char *end_formals;
3697 const char *function_to_edit = def_dec_p->hash_entry->symbol;
3699 /* Setup here to recover from confusing source code detected during this
3700 particular "edit". */
3703 if (setjmp (source_confusion_recovery))
3705 restore_pointers ();
3706 notice ("%s: definition of function `%s' not converted\n",
3707 pname, function_to_edit);
3711 end_formals = find_rightmost_formals_list (clean_text_p);
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. */
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. */
3722 if (other_variable_style_function (def_dec_p->ansi_decl))
3725 notice ("%s: %d: warning: definition of %s not converted\n",
3726 shortpath (NULL, def_dec_p->file->hash_entry->symbol),
3727 identify_lineno (end_formals),
3729 output_up_to (end_formals);
3733 if (edit_formals_lists (end_formals, def_dec_p->f_list_count, def_dec_p))
3735 restore_pointers ();
3736 notice ("%s: definition of function `%s' not converted\n",
3737 pname, function_to_edit);
3741 /* Have to output the last right paren because this never gets flushed by
3742 edit_formals_list. */
3744 output_up_to (end_formals);
3749 const char *semicolon_p;
3750 const char *limit_p;
3752 int had_newlines = 0;
3754 /* Now write out the K&R style formal declarations, one per line. */
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)
3760 for (semicolon_p = decl_p; *semicolon_p != ';'; semicolon_p++)
3762 output_string ("\n");
3763 output_string (indent_string);
3764 output_bytes (decl_p, (size_t) ((semicolon_p + 1) - decl_p));
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. */
3770 for (scan_p = end_formals+1; *scan_p != '{'; )
3772 if (*scan_p == '\n')
3777 check_source (++scan_p < clean_text_limit, 0);
3780 output_string ("\n");
3782 #else /* !defined (UNPROTOIZE) */
3783 /* If we are protoizing, there may be some flotsam & jetsam (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. */
3791 const char *end_formals_orig;
3792 const char *start_body;
3793 const char *start_body_orig;
3795 const char *scan_orig;
3796 int have_flotsam = 0;
3797 int have_newlines = 0;
3799 for (start_body = end_formals + 1; *start_body != '{';)
3800 check_source (++start_body < clean_text_limit, 0);
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++)
3808 if (*scan == *scan_orig)
3810 have_newlines |= (*scan_orig == '\n');
3811 /* Leave identical whitespace alone. */
3812 if (!ISSPACE ((const unsigned char)*scan_orig))
3813 *((NONCONST char *)scan_orig) = ' '; /* identical - so whiteout */
3819 output_bytes (end_formals_orig + 1,
3820 (size_t) (start_body_orig - end_formals_orig) - 1);
3823 output_string ("\n");
3825 output_string (" ");
3826 clean_read_ptr = start_body - 1;
3828 #endif /* !defined (UNPROTOIZE) */
3831 /* Clean up the clean text buffer. Do this by converting comments and
3832 preprocessing directives into spaces. Also convert line continuations
3833 into whitespace. Also, whiteout string and character literals. */
3836 do_cleaning (new_clean_text_base, new_clean_text_limit)
3837 char *new_clean_text_base;
3838 const char *new_clean_text_limit;
3841 int non_whitespace_since_newline = 0;
3843 for (scan_p = new_clean_text_base; scan_p < new_clean_text_limit; scan_p++)
3847 case '/': /* Handle comments. */
3848 if (scan_p[1] != '*')
3850 non_whitespace_since_newline = 1;
3854 while (scan_p[1] != '/' || scan_p[0] != '*')
3856 if (!ISSPACE ((const unsigned char)*scan_p))
3858 if (++scan_p >= new_clean_text_limit)
3865 case '#': /* Handle pp directives. */
3866 if (non_whitespace_since_newline)
3869 while (scan_p[1] != '\n' || scan_p[0] == '\\')
3871 if (!ISSPACE ((const unsigned char)*scan_p))
3873 if (++scan_p >= new_clean_text_limit)
3879 case '\'': /* Handle character literals. */
3880 non_whitespace_since_newline = 1;
3881 while (scan_p[1] != '\'' || scan_p[0] == '\\')
3883 if (scan_p[0] == '\\'
3884 && !ISSPACE ((const unsigned char)scan_p[1]))
3886 if (!ISSPACE ((const unsigned char)*scan_p))
3888 if (++scan_p >= new_clean_text_limit)
3894 case '"': /* Handle string literals. */
3895 non_whitespace_since_newline = 1;
3896 while (scan_p[1] != '"' || scan_p[0] == '\\')
3898 if (scan_p[0] == '\\'
3899 && !ISSPACE ((const unsigned char)scan_p[1]))
3901 if (!ISSPACE ((const unsigned char)*scan_p))
3903 if (++scan_p >= new_clean_text_limit)
3906 if (!ISSPACE ((const unsigned char)*scan_p))
3911 case '\\': /* Handle line continuations. */
3912 if (scan_p[1] != '\n')
3918 non_whitespace_since_newline = 0; /* Reset. */
3927 break; /* Whitespace characters. */
3931 non_whitespace_since_newline = 1;
3937 /* Given a pointer to the closing right parenthesis for a particular formals
3938 list (in the clean text buffer) find the corresponding left parenthesis
3939 and return a pointer to it. */
3942 careful_find_l_paren (p)
3948 for (paren_depth = 1, q = p-1; paren_depth; check_source (--q >= clean_text_base, 0))
3963 /* Scan the clean text buffer for cases of function definitions that we
3964 don't really know about because they were preprocessed out when the
3965 aux info files were created.
3967 In this version of protoize/unprotoize we just give a warning for each
3968 one found. A later version may be able to at least unprotoize such
3971 Note that we may easily find all function definitions simply by
3972 looking for places where there is a left paren which is (ignoring
3973 whitespace) immediately followed by either a left-brace or by an
3974 upper or lower case letter. Whenever we find this combination, we
3975 have also found a function definition header.
3977 Finding function *declarations* using syntactic clues is much harder.
3978 I will probably try to do this in a later version though. */
3981 scan_for_missed_items (file_p)
3982 const file_info *file_p;
3984 static const char *scan_p;
3985 const char *limit = clean_text_limit - 3;
3986 static const char *backup_limit;
3988 backup_limit = clean_text_base - 1;
3990 for (scan_p = clean_text_base; scan_p < limit; scan_p++)
3994 static const char *last_r_paren;
3995 const char *ahead_p;
3997 last_r_paren = scan_p;
3999 for (ahead_p = scan_p + 1; ISSPACE ((const unsigned char)*ahead_p); )
4000 check_source (++ahead_p < limit, limit);
4002 scan_p = ahead_p - 1;
4004 if (ISALPHA ((const unsigned char)*ahead_p) || *ahead_p == '{')
4006 const char *last_l_paren;
4007 const int lineno = identify_lineno (ahead_p);
4009 if (setjmp (source_confusion_recovery))
4012 /* We know we have a function definition header. Now skip
4013 leftwards over all of its associated formals lists. */
4017 last_l_paren = careful_find_l_paren (last_r_paren);
4018 for (last_r_paren = last_l_paren-1;
4019 ISSPACE ((const unsigned char)*last_r_paren); )
4020 check_source (--last_r_paren >= backup_limit, backup_limit);
4022 while (*last_r_paren == ')');
4024 if (is_id_char (*last_r_paren))
4026 const char *id_limit = last_r_paren + 1;
4027 const char *id_start;
4029 const def_dec_info *dd_p;
4031 for (id_start = id_limit-1; is_id_char (*id_start); )
4032 check_source (--id_start >= backup_limit, backup_limit);
4034 backup_limit = id_start;
4035 if ((id_length = (size_t) (id_limit - id_start)) == 0)
4039 char *func_name = (char *) alloca (id_length + 1);
4040 static const char * const stmt_keywords[]
4041 = { "if", "else", "do", "while", "for", "switch", "case", "return", 0 };
4042 const char * const *stmt_keyword;
4044 strncpy (func_name, id_start, id_length);
4045 func_name[id_length] = '\0';
4047 /* We must check here to see if we are actually looking at
4048 a statement rather than an actual function call. */
4050 for (stmt_keyword = stmt_keywords; *stmt_keyword; stmt_keyword++)
4051 if (!strcmp (func_name, *stmt_keyword))
4055 notice ("%s: found definition of `%s' at %s(%d)\n",
4058 shortpath (NULL, file_p->hash_entry->symbol),
4059 identify_lineno (id_start));
4061 /* We really should check for a match of the function name
4062 here also, but why bother. */
4064 for (dd_p = file_p->defs_decs; dd_p; dd_p = dd_p->next_in_file)
4065 if (dd_p->is_func_def && dd_p->line == lineno)
4068 /* If we make it here, then we did not know about this
4069 function definition. */
4071 notice ("%s: %d: warning: `%s' excluded by preprocessing\n",
4072 shortpath (NULL, file_p->hash_entry->symbol),
4073 identify_lineno (id_start), func_name);
4074 notice ("%s: function definition not converted\n",
4084 /* Do all editing operations for a single source file (either a "base" file
4085 or an "include" file). To do this we read the file into memory, keep a
4086 virgin copy there, make another cleaned in-core copy of the original file
4087 (i.e. one in which all of the comments and preprocessing directives have
4088 been replaced with whitespace), then use these two in-core copies of the
4089 file to make a new edited in-core copy of the file. Finally, rename the
4090 original file (as a way of saving it), and then write the edited version
4091 of the file from core to a disk file of the same name as the original.
4093 Note that the trick of making a copy of the original sans comments &
4094 preprocessing directives make the editing a whole lot easier. */
4098 const hash_table_entry *hp;
4100 struct stat stat_buf;
4101 const file_info *file_p = hp->fip;
4102 char *new_orig_text_base;
4103 char *new_orig_text_limit;
4104 char *new_clean_text_base;
4105 char *new_clean_text_limit;
4108 int first_definition_in_file;
4110 /* If we are not supposed to be converting this file, or if there is
4111 nothing in there which needs converting, just skip this file. */
4113 if (!needs_to_be_converted (file_p))
4116 convert_filename = file_p->hash_entry->symbol;
4118 /* Convert a file if it is in a directory where we want conversion
4119 and the file is not excluded. */
4121 if (!directory_specified_p (convert_filename)
4122 || file_excluded_p (convert_filename))
4126 /* Don't even mention "system" include files unless we are
4127 protoizing. If we are protoizing, we mention these as a
4128 gentle way of prodding the user to convert his "system"
4129 include files to prototype format. */
4130 && !in_system_include_dir (convert_filename)
4131 #endif /* defined (UNPROTOIZE) */
4133 notice ("%s: `%s' not converted\n",
4134 pname, shortpath (NULL, convert_filename));
4138 /* Let the user know what we are up to. */
4141 notice ("%s: would convert file `%s'\n",
4142 pname, shortpath (NULL, convert_filename));
4144 notice ("%s: converting file `%s'\n",
4145 pname, shortpath (NULL, convert_filename));
4148 /* Find out the size (in bytes) of the original file. */
4150 /* The cast avoids an erroneous warning on AIX. */
4151 if (stat (convert_filename, &stat_buf) == -1)
4153 int errno_val = errno;
4154 notice ("%s: can't get status for file `%s': %s\n",
4155 pname, shortpath (NULL, convert_filename),
4156 xstrerror (errno_val));
4159 orig_size = stat_buf.st_size;
4161 /* Allocate a buffer to hold the original text. */
4163 orig_text_base = new_orig_text_base = (char *) xmalloc (orig_size + 2);
4164 orig_text_limit = new_orig_text_limit = new_orig_text_base + orig_size;
4166 /* Allocate a buffer to hold the cleaned-up version of the original text. */
4168 clean_text_base = new_clean_text_base = (char *) xmalloc (orig_size + 2);
4169 clean_text_limit = new_clean_text_limit = new_clean_text_base + orig_size;
4170 clean_read_ptr = clean_text_base - 1;
4172 /* Allocate a buffer that will hopefully be large enough to hold the entire
4173 converted output text. As an initial guess for the maximum size of the
4174 output buffer, use 125% of the size of the original + some extra. This
4175 buffer can be expanded later as needed. */
4177 repl_size = orig_size + (orig_size >> 2) + 4096;
4178 repl_text_base = (char *) xmalloc (repl_size + 2);
4179 repl_text_limit = repl_text_base + repl_size - 1;
4180 repl_write_ptr = repl_text_base - 1;
4186 /* Open the file to be converted in READ ONLY mode. */
4188 fd_flags = O_RDONLY;
4190 /* Use binary mode to avoid having to deal with different EOL characters. */
4191 fd_flags |= O_BINARY;
4193 if ((input_file = open (convert_filename, fd_flags, 0444)) == -1)
4195 int errno_val = errno;
4196 notice ("%s: can't open file `%s' for reading: %s\n",
4197 pname, shortpath (NULL, convert_filename),
4198 xstrerror (errno_val));
4202 /* Read the entire original source text file into the original text buffer
4203 in one swell fwoop. Then figure out where the end of the text is and
4204 make sure that it ends with a newline followed by a null. */
4206 if (safe_read (input_file, new_orig_text_base, orig_size) !=
4209 int errno_val = errno;
4211 notice ("\n%s: error reading input file `%s': %s\n",
4212 pname, shortpath (NULL, convert_filename),
4213 xstrerror (errno_val));
4220 if (orig_size == 0 || orig_text_limit[-1] != '\n')
4222 *new_orig_text_limit++ = '\n';
4226 /* Create the cleaned up copy of the original text. */
4228 memcpy (new_clean_text_base, orig_text_base,
4229 (size_t) (orig_text_limit - orig_text_base));
4230 do_cleaning (new_clean_text_base, new_clean_text_limit);
4235 size_t clean_size = orig_text_limit - orig_text_base;
4236 char *const clean_filename = (char *) alloca (strlen (convert_filename) + 6 + 1);
4238 /* Open (and create) the clean file. */
4240 strcpy (clean_filename, convert_filename);
4241 strcat (clean_filename, ".clean");
4242 if ((clean_file = creat (clean_filename, 0666)) == -1)
4244 int errno_val = errno;
4245 notice ("%s: can't create/open clean file `%s': %s\n",
4246 pname, shortpath (NULL, clean_filename),
4247 xstrerror (errno_val));
4251 /* Write the clean file. */
4253 safe_write (clean_file, new_clean_text_base, clean_size, clean_filename);
4259 /* Do a simplified scan of the input looking for things that were not
4260 mentioned in the aux info files because of the fact that they were
4261 in a region of the source which was preprocessed-out (via #if or
4264 scan_for_missed_items (file_p);
4266 /* Setup to do line-oriented forward seeking in the clean text buffer. */
4268 last_known_line_number = 1;
4269 last_known_line_start = clean_text_base;
4271 /* Now get down to business and make all of the necessary edits. */
4274 const def_dec_info *def_dec_p;
4276 first_definition_in_file = 1;
4277 def_dec_p = file_p->defs_decs;
4278 for (; def_dec_p; def_dec_p = def_dec_p->next_in_file)
4280 const char *clean_text_p = seek_to_line (def_dec_p->line);
4282 /* clean_text_p now points to the first character of the line which
4283 contains the `terminator' for the declaration or definition that
4284 we are about to process. */
4288 if (global_flag && def_dec_p->is_func_def && first_definition_in_file)
4290 add_global_decls (def_dec_p->file, clean_text_p);
4291 first_definition_in_file = 0;
4294 /* Don't edit this item if it is already in prototype format or if it
4295 is a function declaration and we have found no corresponding
4298 if (def_dec_p->prototyped
4299 || (!def_dec_p->is_func_def && !def_dec_p->definition))
4302 #endif /* !defined (UNPROTOIZE) */
4304 if (def_dec_p->is_func_def)
4305 edit_fn_definition (def_dec_p, clean_text_p);
4308 if (def_dec_p->is_implicit)
4309 add_local_decl (def_dec_p, clean_text_p);
4311 #endif /* !defined (UNPROTOIZE) */
4312 edit_fn_declaration (def_dec_p, clean_text_p);
4316 /* Finalize things. Output the last trailing part of the original text. */
4318 output_up_to (clean_text_limit - 1);
4320 /* If this is just a test run, stop now and just deallocate the buffers. */
4324 free (new_orig_text_base);
4325 free (new_clean_text_base);
4326 free (repl_text_base);
4330 /* Change the name of the original input file. This is just a quick way of
4331 saving the original file. */
4336 = (char *) xmalloc (strlen (convert_filename) + strlen (save_suffix) + 2);
4338 strcpy (new_filename, convert_filename);
4340 /* MSDOS filenames are restricted to 8.3 format, so we save `foo.c'
4341 as `foo.<save_suffix>'. */
4342 new_filename[(strlen (convert_filename) - 1] = '\0';
4344 strcat (new_filename, save_suffix);
4346 /* Don't overwrite existing file. */
4347 if (access (new_filename, F_OK) == 0)
4350 notice ("%s: warning: file `%s' already saved in `%s'\n",
4352 shortpath (NULL, convert_filename),
4353 shortpath (NULL, new_filename));
4355 else if (rename (convert_filename, new_filename) == -1)
4357 int errno_val = errno;
4358 notice ("%s: can't link file `%s' to `%s': %s\n",
4360 shortpath (NULL, convert_filename),
4361 shortpath (NULL, new_filename),
4362 xstrerror (errno_val));
4367 if (unlink (convert_filename) == -1)
4369 int errno_val = errno;
4370 /* The file may have already been renamed. */
4371 if (errno_val != ENOENT)
4373 notice ("%s: can't delete file `%s': %s\n",
4374 pname, shortpath (NULL, convert_filename),
4375 xstrerror (errno_val));
4383 /* Open (and create) the output file. */
4385 if ((output_file = creat (convert_filename, 0666)) == -1)
4387 int errno_val = errno;
4388 notice ("%s: can't create/open output file `%s': %s\n",
4389 pname, shortpath (NULL, convert_filename),
4390 xstrerror (errno_val));
4394 /* Use binary mode to avoid changing the existing EOL character. */
4395 setmode (output_file, O_BINARY);
4398 /* Write the output file. */
4401 unsigned int out_size = (repl_write_ptr + 1) - repl_text_base;
4403 safe_write (output_file, repl_text_base, out_size, convert_filename);
4406 close (output_file);
4409 /* Deallocate the conversion buffers. */
4411 free (new_orig_text_base);
4412 free (new_clean_text_base);
4413 free (repl_text_base);
4415 /* Change the mode of the output file to match the original file. */
4417 /* The cast avoids an erroneous warning on AIX. */
4418 if (chmod (convert_filename, stat_buf.st_mode) == -1)
4420 int errno_val = errno;
4421 notice ("%s: can't change mode of file `%s': %s\n",
4422 pname, shortpath (NULL, convert_filename),
4423 xstrerror (errno_val));
4426 /* Note: We would try to change the owner and group of the output file
4427 to match those of the input file here, except that may not be a good
4428 thing to do because it might be misleading. Also, it might not even
4429 be possible to do that (on BSD systems with quotas for instance). */
4432 /* Do all of the individual steps needed to do the protoization (or
4433 unprotoization) of the files referenced in the aux_info files given
4434 in the command line. */
4439 const char * const *base_pp;
4440 const char * const * const end_pps
4441 = &base_source_filenames[n_base_source_files];
4445 #endif /* !defined (UNPROTOIZE) */
4447 /* One-by-one, check (and create if necessary), open, and read all of the
4448 stuff in each aux_info file. After reading each aux_info file, the
4449 aux_info_file just read will be automatically deleted unless the
4450 keep_flag is set. */
4452 for (base_pp = base_source_filenames; base_pp < end_pps; base_pp++)
4453 process_aux_info_file (*base_pp, keep_flag, 0);
4457 /* Also open and read the special SYSCALLS.c aux_info file which gives us
4458 the prototypes for all of the standard system-supplied functions. */
4460 if (nondefault_syscalls_dir)
4462 syscalls_absolute_filename
4463 = (char *) xmalloc (strlen (nondefault_syscalls_dir) + 1
4464 + sizeof (syscalls_filename));
4465 strcpy (syscalls_absolute_filename, nondefault_syscalls_dir);
4469 GET_ENV_PATH_LIST (default_syscalls_dir, "GCC_EXEC_PREFIX");
4470 if (!default_syscalls_dir)
4472 default_syscalls_dir = standard_exec_prefix;
4474 syscalls_absolute_filename
4475 = (char *) xmalloc (strlen (default_syscalls_dir) + 0
4476 + strlen (target_machine) + 1
4477 + strlen (target_version) + 1
4478 + sizeof (syscalls_filename));
4479 strcpy (syscalls_absolute_filename, default_syscalls_dir);
4480 strcat (syscalls_absolute_filename, target_machine);
4481 strcat (syscalls_absolute_filename, "/");
4482 strcat (syscalls_absolute_filename, target_version);
4483 strcat (syscalls_absolute_filename, "/");
4486 syscalls_len = strlen (syscalls_absolute_filename);
4487 if (! IS_DIR_SEPARATOR (*(syscalls_absolute_filename + syscalls_len - 1)))
4489 *(syscalls_absolute_filename + syscalls_len++) = DIR_SEPARATOR;
4490 *(syscalls_absolute_filename + syscalls_len) = '\0';
4492 strcat (syscalls_absolute_filename, syscalls_filename);
4494 /* Call process_aux_info_file in such a way that it does not try to
4495 delete the SYSCALLS aux_info file. */
4497 process_aux_info_file (syscalls_absolute_filename, 1, 1);
4499 #endif /* !defined (UNPROTOIZE) */
4501 /* When we first read in all of the information from the aux_info files
4502 we saved in it descending line number order, because that was likely to
4503 be faster. Now however, we want the chains of def & dec records to
4504 appear in ascending line number order as we get further away from the
4505 file_info record that they hang from. The following line causes all of
4506 these lists to be rearranged into ascending line number order. */
4508 visit_each_hash_node (filename_primary, reverse_def_dec_list);
4512 /* Now do the "real" work. The following line causes each declaration record
4513 to be "visited". For each of these nodes, an attempt is made to match
4514 up the function declaration with a corresponding function definition,
4515 which should have a full prototype-format formals list with it. Once
4516 these match-ups are made, the conversion of the function declarations
4517 to prototype format can be made. */
4519 visit_each_hash_node (function_name_primary, connect_defs_and_decs);
4521 #endif /* !defined (UNPROTOIZE) */
4523 /* Now convert each file that can be converted (and needs to be). */
4525 visit_each_hash_node (filename_primary, edit_file);
4529 /* If we are working in cplusplus mode, try to rename all .c files to .C
4530 files. Don't panic if some of the renames don't work. */
4532 if (cplusplus_flag && !nochange_flag)
4533 visit_each_hash_node (filename_primary, rename_c_file);
4535 #endif /* !defined (UNPROTOIZE) */
4538 static struct option longopts[] =
4540 {"version", 0, 0, 'V'},
4541 {"file_name", 0, 0, 'p'},
4542 {"quiet", 0, 0, 'q'},
4543 {"silent", 0, 0, 'q'},
4544 {"force", 0, 0, 'f'},
4545 {"keep", 0, 0, 'k'},
4546 {"nosave", 0, 0, 'N'},
4547 {"nochange", 0, 0, 'n'},
4548 {"compiler-options", 1, 0, 'c'},
4549 {"exclude", 1, 0, 'x'},
4550 {"directory", 1, 0, 'd'},
4552 {"indent", 1, 0, 'i'},
4554 {"local", 0, 0, 'l'},
4555 {"global", 0, 0, 'g'},
4557 {"syscalls-dir", 1, 0, 'B'},
4562 extern int main PARAMS ((int, char **const));
4571 const char *params = "";
4573 pname = strrchr (argv[0], DIR_SEPARATOR);
4574 #ifdef DIR_SEPARATOR_2
4578 slash = strrchr (pname ? pname : argv[0], DIR_SEPARATOR_2);
4583 pname = pname ? pname+1 : argv[0];
4585 #ifdef HAVE_LC_MESSAGES
4586 setlocale (LC_MESSAGES, "");
4588 (void) bindtextdomain (PACKAGE, localedir);
4589 (void) textdomain (PACKAGE);
4591 cwd_buffer = getpwd ();
4594 notice ("%s: cannot get working directory: %s\n",
4595 pname, xstrerror(errno));
4596 return (FATAL_EXIT_CODE);
4599 /* By default, convert the files in the current directory. */
4600 directory_list = string_list_cons (cwd_buffer, NULL);
4602 while ((c = getopt_long (argc, argv,
4606 "B:c:Cd:gklnNp:qvVx:",
4608 longopts, &longind)) != EOF)
4610 if (c == 0) /* Long option. */
4611 c = longopts[longind].val;
4615 compiler_file_name = optarg;
4619 = string_list_cons (abspath (NULL, optarg), directory_list);
4622 exclude_list = string_list_cons (optarg, exclude_list);
4652 indent_string = optarg;
4654 #else /* !defined (UNPROTOIZE) */
4665 nondefault_syscalls_dir = optarg;
4667 #endif /* !defined (UNPROTOIZE) */
4673 /* Set up compile_params based on -p and -c options. */
4674 munge_compile_params (params);
4676 n_base_source_files = argc - optind;
4678 /* Now actually make a list of the base source filenames. */
4680 base_source_filenames
4681 = (const char **) xmalloc ((n_base_source_files + 1) * sizeof (char *));
4682 n_base_source_files = 0;
4683 for (; optind < argc; optind++)
4685 const char *path = abspath (NULL, argv[optind]);
4686 int len = strlen (path);
4688 if (path[len-1] == 'c' && path[len-2] == '.')
4689 base_source_filenames[n_base_source_files++] = path;
4692 notice ("%s: input file names must have .c suffixes: %s\n",
4693 pname, shortpath (NULL, path));
4699 /* We are only interested in the very first identifier token in the
4700 definition of `va_list', so if there is more junk after that first
4701 identifier token, delete it from the `varargs_style_indicator'. */
4705 for (cp = varargs_style_indicator;
4706 ISALNUM ((const unsigned char)*cp) || *cp == '_'; cp++)
4709 varargs_style_indicator = savestring (varargs_style_indicator,
4710 cp - varargs_style_indicator);
4712 #endif /* !defined (UNPROTOIZE) */
4719 fprintf (stderr, "%s: %s\n", pname, version_string);
4723 return (errors ? FATAL_EXIT_CODE : SUCCESS_EXIT_CODE);