Pass 9th fp argument correctly on System V/eabi; Add @plt for -fPIC/-mrelocatable
[official-gcc.git] / gcc / protoize.c
blob3b50836774abc2f9748da0ae2e1d1a2bb3a74391
1 /* Protoize program - Original version by Ron Guilmette (rfg@segfault.us.com).
2 Copyright (C) 1989, 92-96, 1997 Free Software Foundation, Inc.
4 This file is part of GNU CC.
6 GNU CC is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
11 GNU CC is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU CC; see the file COPYING. If not, write to
18 the Free Software Foundation, 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
21 /* Any reasonable C++ compiler should have all of the same features
22 as __STDC__ plus more, so make sure that __STDC__ is defined if
23 __cplusplus is defined. */
25 #if defined(__cplusplus) && !defined(__STDC__)
26 #define __STDC__ 1
27 #endif /* defined(__cplusplus) && !defined(__STDC__) */
29 #if defined(__GNUC__) || defined (__GNUG__)
30 #define VOLATILE volatile
31 #else
32 #define VOLATILE
33 #endif
35 #ifndef __STDC__
36 #define const
37 #define volatile
38 #endif
40 #include "config.h"
42 #if 0
43 /* Users are not supposed to use _POSIX_SOURCE to say the
44 system is a POSIX system. That is not what _POSIX_SOURCE means! -- rms */
45 /* If the user asked for POSIX via _POSIX_SOURCE, turn on POSIX code. */
46 #if defined(_POSIX_SOURCE) && !defined(POSIX)
47 #define POSIX
48 #endif
49 #endif /* 0 */
51 #ifdef POSIX /* We should be able to define _POSIX_SOURCE unconditionally,
52 but some systems respond in buggy ways to it,
53 including SunOS 4.1.1. Which we don't classify as POSIX. */
54 /* In case this is a POSIX system with an ANSI C compiler,
55 ask for definition of all POSIX facilities. */
56 #undef _POSIX_SOURCE
57 #define _POSIX_SOURCE
58 #endif
60 #ifdef HAVE_VARARGS_H
61 #include <varargs.h>
62 #else
63 #ifdef HAVE_SYS_VARARGS_H
64 #include <sys/varargs.h>
65 #endif
66 #endif
68 /* On some systems stdio.h includes stdarg.h;
69 we must bring in varargs.h first. */
70 #include <stdio.h>
71 #include <ctype.h>
72 #include <errno.h>
73 #include <sys/types.h>
74 #include <sys/stat.h>
75 #if ! defined (_WIN32) || defined (__CYGWIN32__)
76 #if defined(POSIX) || defined(CONCURRENT)
77 #include <dirent.h>
78 #else
79 #include <sys/dir.h>
80 #endif
81 #endif
82 #include <setjmp.h>
84 #include "gansidecl.h"
86 /* Include getopt.h for the sake of getopt_long.
87 We don't need the declaration of getopt, and it could conflict
88 with something from a system header file, so effectively nullify that. */
89 #define getopt getopt_loser
90 #include "getopt.h"
91 #undef getopt
93 #ifndef errno
94 extern int errno;
95 #endif
97 #ifndef HAVE_STRERROR
98 extern int sys_nerr;
99 extern char *sys_errlist[];
100 #else
101 extern char *strerror();
102 #endif
104 extern char *version_string;
106 /* Systems which are compatible only with POSIX 1003.1-1988 (but *not*
107 with POSIX 1003.1-1990), e.g. Ultrix 4.2, might not have
108 const qualifiers in the prototypes in the system include files.
109 Unfortunately, this can lead to GCC issuing lots of warnings for
110 calls to the following functions. To eliminate these warnings we
111 provide the following #defines. */
113 #define my_access(file,flag) access((char *)file, flag)
114 #define my_stat(file,pkt) stat((char *)file, pkt)
115 #define my_link(file1, file2) link((char *)file1, (char *)file2)
116 #define my_unlink(file) unlink((char *)file)
117 #define my_open(file, mode, flag) open((char *)file, mode, flag)
118 #define my_chmod(file, mode) chmod((char *)file, mode)
120 extern char *getpwd ();
122 extern char *choose_temp_base PROTO ((void));
124 extern int pexecute PROTO ((const char *, char * const *, const char *,
125 const char *, char **, char **, int));
126 extern int pwait PROTO ((int, int *, int));
127 /* Flag arguments to pexecute. */
128 #define PEXECUTE_FIRST 1
129 #define PEXECUTE_LAST 2
130 #define PEXECUTE_SEARCH 4
132 /* Aliases for pointers to void.
133 These were made to facilitate compilation with old brain-dead DEC C
134 compilers which didn't properly grok `void*' types. */
136 #ifdef __STDC__
137 typedef void * pointer_type;
138 typedef const void * const_pointer_type;
139 #else
140 typedef char * pointer_type;
141 typedef char * const_pointer_type;
142 #endif
144 #if defined(POSIX)
146 #include <stdlib.h>
147 #include <unistd.h>
148 #include <signal.h>
149 #include <fcntl.h>
150 #include <sys/wait.h>
152 #else /* !defined(POSIX) */
154 #define R_OK 4 /* Test for Read permission */
155 #define W_OK 2 /* Test for Write permission */
156 #define X_OK 1 /* Test for eXecute permission */
157 #define F_OK 0 /* Test for existence of File */
159 #ifndef O_RDONLY
160 #define O_RDONLY 0
161 #endif
163 #ifndef O_WRONLY
164 #define O_WRONLY 1
165 #endif
167 #ifndef WIFSIGNALED
168 #define WIFSIGNALED(S) (((S) & 0xff) != 0 && ((S) & 0xff) != 0x7f)
169 #endif
170 #ifndef WTERMSIG
171 #define WTERMSIG(S) ((S) & 0x7f)
172 #endif
173 #ifndef WIFEXITED
174 #define WIFEXITED(S) (((S) & 0xff) == 0)
175 #endif
176 #ifndef WEXITSTATUS
177 #define WEXITSTATUS(S) (((S) & 0xff00) >> 8)
178 #endif
180 /* Declaring stat or __flsbuf with a prototype
181 causes conflicts with system headers on some systems. */
183 #ifndef abort
184 typedef void voidfn ();
185 extern VOLATILE voidfn abort;
186 #endif
187 extern int creat ();
188 #if 0 /* These conflict with stdio.h on some systems. */
189 extern int fprintf (FILE *, const char *, ...);
190 extern int printf (const char *, ...);
191 extern int open (const char *, int, ...);
192 #endif /* 0 */
193 extern void exit ();
194 extern void free ();
195 extern int read ();
196 extern int write ();
197 extern int close ();
198 extern int fflush ();
199 extern int atoi ();
200 extern int puts ();
201 extern int fputs ();
202 extern int fputc ();
203 #if !defined(_WIN32)
204 extern int link ();
205 #endif
206 extern int unlink ();
207 extern int access ();
209 #if 0 /* size_t from sys/types.h may fail to match GCC.
210 If so, we would get a warning from this. */
211 extern size_t strlen ()
212 #endif
214 /* Fork is not declared because the declaration caused a conflict
215 on the HPPA. */
216 #if !(defined (USG) || defined (VMS))
217 #define fork vfork
218 #endif /* (defined (USG) || defined (VMS)) */
220 #endif /* !defined (POSIX) */
222 extern char *rindex ();
224 /* Look for these where the `const' qualifier is intentionally cast aside. */
226 #define NONCONST
228 /* Define a STRINGIFY macro that's right for ANSI or traditional C. */
230 #ifdef __STDC__
231 #define STRINGIFY(STRING) #STRING
232 #else
233 #define STRINGIFY(STRING) "STRING"
234 #endif
236 /* Define a default place to find the SYSCALLS.X file. */
238 #ifndef STD_PROTO_DIR
239 #define STD_PROTO_DIR "/usr/local/lib"
240 #endif /* !defined (STD_PROTO_DIR) */
242 /* Suffix of aux_info files. */
244 static const char * const aux_info_suffix = ".X";
246 /* String to attach to filenames for saved versions of original files. */
248 static const char * const save_suffix = ".save";
250 #ifndef UNPROTOIZE
252 /* File name of the file which contains descriptions of standard system
253 routines. Note that we never actually do anything with this file per se,
254 but we do read in its corresponding aux_info file. */
256 static const char syscalls_filename[] = "SYSCALLS.c";
258 /* Default place to find the above file. */
260 static const char * const default_syscalls_dir = STD_PROTO_DIR;
262 /* Variable to hold the complete absolutized filename of the SYSCALLS.c.X
263 file. */
265 static char * syscalls_absolute_filename;
267 #endif /* !defined (UNPROTOIZE) */
269 /* Type of the structure that holds information about macro unexpansions. */
271 struct unexpansion_struct {
272 const char *expanded;
273 const char *contracted;
275 typedef struct unexpansion_struct unexpansion;
277 /* A table of conversions that may need to be made for some (stupid) older
278 operating systems where these types are preprocessor macros rather than
279 typedefs (as they really ought to be).
281 WARNING: The contracted forms must be as small (or smaller) as the
282 expanded forms, or else havoc will ensue. */
284 static const unexpansion unexpansions[] = {
285 { "struct _iobuf", "FILE" },
286 { 0, 0 }
289 /* The number of "primary" slots in the hash tables for filenames and for
290 function names. This can be as big or as small as you like, except that
291 it must be a power of two. */
293 #define HASH_TABLE_SIZE (1 << 9)
295 /* Bit mask to use when computing hash values. */
297 static const int hash_mask = (HASH_TABLE_SIZE - 1);
299 /* Make a table of default system include directories
300 just as it is done in cccp.c. */
302 #ifndef STANDARD_INCLUDE_DIR
303 #define STANDARD_INCLUDE_DIR "/usr/include"
304 #endif
306 #ifndef LOCAL_INCLUDE_DIR
307 #define LOCAL_INCLUDE_DIR "/usr/local/include"
308 #endif
310 struct default_include { const char *fname; int x1, x2; } include_defaults[]
311 #ifdef INCLUDE_DEFAULTS
312 = INCLUDE_DEFAULTS;
313 #else
315 /* Pick up GNU C++ specific include files. */
316 { GPLUSPLUS_INCLUDE_DIR, 1, 1 },
317 #ifdef CROSS_COMPILE
318 /* This is the dir for fixincludes. Put it just before
319 the files that we fix. */
320 { GCC_INCLUDE_DIR, 0, 0 },
321 /* For cross-compilation, this dir name is generated
322 automatically in Makefile.in. */
323 { CROSS_INCLUDE_DIR, 0, 0 },
324 /* This is another place that the target system's headers might be. */
325 { TOOL_INCLUDE_DIR, 0, 0 },
326 #else /* not CROSS_COMPILE */
327 /* This should be /use/local/include and should come before
328 the fixincludes-fixed header files. */
329 { LOCAL_INCLUDE_DIR, 0, 1 },
330 /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
331 Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h. */
332 { TOOL_INCLUDE_DIR, 0, 0 },
333 /* This is the dir for fixincludes. Put it just before
334 the files that we fix. */
335 { GCC_INCLUDE_DIR, 0, 0 },
336 /* Some systems have an extra dir of include files. */
337 #ifdef SYSTEM_INCLUDE_DIR
338 { SYSTEM_INCLUDE_DIR, 0, 0 },
339 #endif
340 { STANDARD_INCLUDE_DIR, 0, 0},
341 #endif /* not CROSS_COMPILE */
342 { 0, 0, 0}
344 #endif /* no INCLUDE_DEFAULTS */
346 /* Datatype for lists of directories or filenames. */
347 struct string_list
349 char *name;
350 struct string_list *next;
353 /* List of directories in which files should be converted. */
355 struct string_list *directory_list;
357 /* List of file names which should not be converted.
358 A file is excluded if the end of its name, following a /,
359 matches one of the names in this list. */
361 struct string_list *exclude_list;
363 /* The name of the other style of variable-number-of-parameters functions
364 (i.e. the style that we want to leave unconverted because we don't yet
365 know how to convert them to this style. This string is used in warning
366 messages. */
368 /* Also define here the string that we can search for in the parameter lists
369 taken from the .X files which will unambiguously indicate that we have
370 found a varargs style function. */
372 #ifdef UNPROTOIZE
373 static const char * const other_var_style = "stdarg";
374 #else /* !defined (UNPROTOIZE) */
375 static const char * const other_var_style = "varargs";
376 /* Note that this is a string containing the expansion of va_alist.
377 But in `main' we discard all but the first token. */
378 static const char *varargs_style_indicator = STRINGIFY (va_alist);
379 #endif /* !defined (UNPROTOIZE) */
381 /* The following two types are used to create hash tables. In this program,
382 there are two hash tables which are used to store and quickly lookup two
383 different classes of strings. The first type of strings stored in the
384 first hash table are absolute filenames of files which protoize needs to
385 know about. The second type of strings (stored in the second hash table)
386 are function names. It is this second class of strings which really
387 inspired the use of the hash tables, because there may be a lot of them. */
389 typedef struct hash_table_entry_struct hash_table_entry;
391 /* Do some typedefs so that we don't have to write "struct" so often. */
393 typedef struct def_dec_info_struct def_dec_info;
394 typedef struct file_info_struct file_info;
395 typedef struct f_list_chain_item_struct f_list_chain_item;
397 /* In the struct below, note that the "_info" field has two different uses
398 depending on the type of hash table we are in (i.e. either the filenames
399 hash table or the function names hash table). In the filenames hash table
400 the info fields of the entries point to the file_info struct which is
401 associated with each filename (1 per filename). In the function names
402 hash table, the info field points to the head of a singly linked list of
403 def_dec_info entries which are all defs or decs of the function whose
404 name is pointed to by the "symbol" field. Keeping all of the defs/decs
405 for a given function name on a special list specifically for that function
406 name makes it quick and easy to find out all of the important information
407 about a given (named) function. */
409 struct hash_table_entry_struct {
410 hash_table_entry * hash_next; /* -> to secondary entries */
411 const char * symbol; /* -> to the hashed string */
412 union {
413 const def_dec_info * _ddip;
414 file_info * _fip;
415 } _info;
417 #define ddip _info._ddip
418 #define fip _info._fip
420 /* Define a type specifically for our two hash tables. */
422 typedef hash_table_entry hash_table[HASH_TABLE_SIZE];
424 /* The following struct holds all of the important information about any
425 single filename (e.g. file) which we need to know about. */
427 struct file_info_struct {
428 const hash_table_entry * hash_entry; /* -> to associated hash entry */
429 const def_dec_info * defs_decs; /* -> to chain of defs/decs */
430 time_t mtime; /* Time of last modification. */
433 /* Due to the possibility that functions may return pointers to functions,
434 (which may themselves have their own parameter lists) and due to the
435 fact that returned pointers-to-functions may be of type "pointer-to-
436 function-returning-pointer-to-function" (ad nauseum) we have to keep
437 an entire chain of ANSI style formal parameter lists for each function.
439 Normally, for any given function, there will only be one formals list
440 on the chain, but you never know.
442 Note that the head of each chain of formals lists is pointed to by the
443 `f_list_chain' field of the corresponding def_dec_info record.
445 For any given chain, the item at the head of the chain is the *leftmost*
446 parameter list seen in the actual C language function declaration. If
447 there are other members of the chain, then these are linked in left-to-right
448 order from the head of the chain. */
450 struct f_list_chain_item_struct {
451 const f_list_chain_item * chain_next; /* -> to next item on chain */
452 const char * formals_list; /* -> to formals list string */
455 /* The following struct holds all of the important information about any
456 single function definition or declaration which we need to know about.
457 Note that for unprotoize we don't need to know very much because we
458 never even create records for stuff that we don't intend to convert
459 (like for instance defs and decs which are already in old K&R format
460 and "implicit" function declarations). */
462 struct def_dec_info_struct {
463 const def_dec_info * next_in_file; /* -> to rest of chain for file */
464 file_info * file; /* -> file_info for containing file */
465 int line; /* source line number of def/dec */
466 const char * ansi_decl; /* -> left end of ansi decl */
467 hash_table_entry * hash_entry; /* -> hash entry for function name */
468 unsigned int is_func_def; /* = 0 means this is a declaration */
469 const def_dec_info * next_for_func; /* -> to rest of chain for func name */
470 unsigned int f_list_count; /* count of formals lists we expect */
471 char prototyped; /* = 0 means already prototyped */
472 #ifndef UNPROTOIZE
473 const f_list_chain_item * f_list_chain; /* -> chain of formals lists */
474 const def_dec_info * definition; /* -> def/dec containing related def */
475 char is_static; /* = 0 means visibility is "extern" */
476 char is_implicit; /* != 0 for implicit func decl's */
477 char written; /* != 0 means written for implicit */
478 #else /* !defined (UNPROTOIZE) */
479 const char * formal_names; /* -> to list of names of formals */
480 const char * formal_decls; /* -> to string of formal declarations */
481 #endif /* !defined (UNPROTOIZE) */
484 /* Pointer to the tail component of the filename by which this program was
485 invoked. Used everywhere in error and warning messages. */
487 static const char *pname;
489 /* Error counter. Will be non-zero if we should give up at the next convenient
490 stopping point. */
492 static int errors = 0;
494 /* Option flags. */
495 /* ??? These comments should say what the flag mean as well as the options
496 that set them. */
498 /* File name to use for running gcc. Allows GCC 2 to be named
499 something other than gcc. */
500 static const char *compiler_file_name = "gcc";
502 static int version_flag = 0; /* Print our version number. */
503 static int quiet_flag = 0; /* Don't print messages normally. */
504 static int nochange_flag = 0; /* Don't convert, just say what files
505 we would have converted. */
506 static int nosave_flag = 0; /* Don't save the old version. */
507 static int keep_flag = 0; /* Don't delete the .X files. */
508 static const char ** compile_params = 0; /* Option string for gcc. */
509 #ifdef UNPROTOIZE
510 static const char *indent_string = " "; /* Indentation for newly
511 inserted parm decls. */
512 #else /* !defined (UNPROTOIZE) */
513 static int local_flag = 0; /* Insert new local decls (when?). */
514 static int global_flag = 0; /* set by -g option */
515 static int cplusplus_flag = 0; /* Rename converted files to *.C. */
516 static const char *nondefault_syscalls_dir = 0; /* Dir to look for
517 SYSCALLS.c.X in. */
518 #endif /* !defined (UNPROTOIZE) */
520 /* An index into the compile_params array where we should insert the source
521 file name when we are ready to exec the C compiler. A zero value indicates
522 that we have not yet called munge_compile_params. */
524 static int input_file_name_index = 0;
526 /* An index into the compile_params array where we should insert the filename
527 for the aux info file, when we run the C compiler. */
528 static int aux_info_file_name_index = 0;
530 /* Count of command line arguments which were "filename" arguments. */
532 static int n_base_source_files = 0;
534 /* Points to a malloc'ed list of pointers to all of the filenames of base
535 source files which were specified on the command line. */
537 static const char **base_source_filenames;
539 /* Line number of the line within the current aux_info file that we
540 are currently processing. Used for error messages in case the prototypes
541 info file is corrupted somehow. */
543 static int current_aux_info_lineno;
545 /* Pointer to the name of the source file currently being converted. */
547 static const char *convert_filename;
549 /* Pointer to relative root string (taken from aux_info file) which indicates
550 where directory the user was in when he did the compilation step that
551 produced the containing aux_info file. */
553 static const char *invocation_filename;
555 /* Pointer to the base of the input buffer that holds the original text for the
556 source file currently being converted. */
558 static const char *orig_text_base;
560 /* Pointer to the byte just beyond the end of the input buffer that holds the
561 original text for the source file currently being converted. */
563 static const char *orig_text_limit;
565 /* Pointer to the base of the input buffer that holds the cleaned text for the
566 source file currently being converted. */
568 static const char *clean_text_base;
570 /* Pointer to the byte just beyond the end of the input buffer that holds the
571 cleaned text for the source file currently being converted. */
573 static const char *clean_text_limit;
575 /* Pointer to the last byte in the cleaned text buffer that we have already
576 (virtually) copied to the output buffer (or decided to ignore). */
578 static const char * clean_read_ptr;
580 /* Pointer to the base of the output buffer that holds the replacement text
581 for the source file currently being converted. */
583 static char *repl_text_base;
585 /* Pointer to the byte just beyond the end of the output buffer that holds the
586 replacement text for the source file currently being converted. */
588 static char *repl_text_limit;
590 /* Pointer to the last byte which has been stored into the output buffer.
591 The next byte to be stored should be stored just past where this points
592 to. */
594 static char * repl_write_ptr;
596 /* Pointer into the cleaned text buffer for the source file we are currently
597 converting. This points to the first character of the line that we last
598 did a "seek_to_line" to (see below). */
600 static const char *last_known_line_start;
602 /* Number of the line (in the cleaned text buffer) that we last did a
603 "seek_to_line" to. Will be one if we just read a new source file
604 into the cleaned text buffer. */
606 static int last_known_line_number;
608 /* The filenames hash table. */
610 static hash_table filename_primary;
612 /* The function names hash table. */
614 static hash_table function_name_primary;
616 /* The place to keep the recovery address which is used only in cases where
617 we get hopelessly confused by something in the cleaned original text. */
619 static jmp_buf source_confusion_recovery;
621 /* A pointer to the current directory filename (used by abspath). */
623 static char *cwd_buffer;
625 /* A place to save the read pointer until we are sure that an individual
626 attempt at editing will succeed. */
628 static const char * saved_clean_read_ptr;
630 /* A place to save the write pointer until we are sure that an individual
631 attempt at editing will succeed. */
633 static char * saved_repl_write_ptr;
635 /* Forward declaration. */
637 static const char *shortpath ();
639 char *
640 my_strerror(e)
641 int e;
644 #ifdef HAVE_STRERROR
645 return strerror(e);
647 #else
649 static char buffer[30];
650 if (!e)
651 return "";
653 if (e > 0 && e < sys_nerr)
654 return sys_errlist[e];
656 sprintf (buffer, "Unknown error %d", e);
657 return buffer;
658 #endif
661 /* Allocate some space, but check that the allocation was successful. */
662 /* alloca.c uses this, so don't make it static. */
664 pointer_type
665 xmalloc (byte_count)
666 size_t byte_count;
668 pointer_type rv;
670 rv = (pointer_type) malloc (byte_count);
671 if (rv == NULL)
673 fprintf (stderr, "\n%s: virtual memory exceeded\n", pname);
674 exit (FATAL_EXIT_CODE);
675 return 0; /* avoid warnings */
677 else
678 return rv;
681 /* Reallocate some space, but check that the reallocation was successful. */
683 pointer_type
684 xrealloc (old_space, byte_count)
685 pointer_type old_space;
686 size_t byte_count;
688 pointer_type rv;
690 rv = (pointer_type) realloc (old_space, byte_count);
691 if (rv == NULL)
693 fprintf (stderr, "\n%s: virtual memory exceeded\n", pname);
694 exit (FATAL_EXIT_CODE);
695 return 0; /* avoid warnings */
697 else
698 return rv;
701 /* Deallocate the area pointed to by an arbitrary pointer, but first, strip
702 the `const' qualifier from it and also make sure that the pointer value
703 is non-null. */
705 void
706 xfree (p)
707 const_pointer_type p;
709 if (p)
710 free ((NONCONST pointer_type) p);
713 /* Make a copy of a string INPUT with size SIZE. */
715 static char *
716 savestring (input, size)
717 const char *input;
718 unsigned int size;
720 char *output = (char *) xmalloc (size + 1);
721 strcpy (output, input);
722 return output;
725 /* Make a copy of the concatenation of INPUT1 and INPUT2. */
727 static char *
728 savestring2 (input1, size1, input2, size2)
729 const char *input1;
730 unsigned int size1;
731 const char *input2;
732 unsigned int size2;
734 char *output = (char *) xmalloc (size1 + size2 + 1);
735 strcpy (output, input1);
736 strcpy (&output[size1], input2);
737 return output;
740 /* More 'friendly' abort that prints the line and file.
741 config.h can #define abort fancy_abort if you like that sort of thing. */
743 void
744 fancy_abort ()
746 fprintf (stderr, "%s: internal abort\n", pname);
747 exit (FATAL_EXIT_CODE);
750 /* Make a duplicate of the first N bytes of a given string in a newly
751 allocated area. */
753 static char *
754 dupnstr (s, n)
755 const char *s;
756 size_t n;
758 char *ret_val = (char *) xmalloc (n + 1);
760 strncpy (ret_val, s, n);
761 ret_val[n] = '\0';
762 return ret_val;
765 /* Return a pointer to the first occurrence of s2 within s1 or NULL if s2
766 does not occur within s1. Assume neither s1 nor s2 are null pointers. */
768 static const char *
769 substr (s1, s2)
770 const char *s1;
771 const char *const s2;
773 for (; *s1 ; s1++)
775 const char *p1;
776 const char *p2;
777 int c;
779 for (p1 = s1, p2 = s2; c = *p2; p1++, p2++)
780 if (*p1 != c)
781 goto outer;
782 return s1;
783 outer:
786 return 0;
789 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
790 retrying if necessary. Return the actual number of bytes read. */
792 static int
793 safe_read (desc, ptr, len)
794 int desc;
795 char *ptr;
796 int len;
798 int left = len;
799 while (left > 0) {
800 int nchars = read (desc, ptr, left);
801 if (nchars < 0)
803 #ifdef EINTR
804 if (errno == EINTR)
805 continue;
806 #endif
807 return nchars;
809 if (nchars == 0)
810 break;
811 ptr += nchars;
812 left -= nchars;
814 return len - left;
817 /* Write LEN bytes at PTR to descriptor DESC,
818 retrying if necessary, and treating any real error as fatal. */
820 static void
821 safe_write (desc, ptr, len, out_fname)
822 int desc;
823 char *ptr;
824 int len;
825 char *out_fname;
827 while (len > 0) {
828 int written = write (desc, ptr, len);
829 if (written < 0)
831 #ifdef EINTR
832 if (errno == EINTR)
833 continue;
834 #endif
835 fprintf (stderr, "%s: error writing file `%s': %s\n",
836 pname, shortpath (NULL, out_fname), my_strerror(errno));
837 return;
839 ptr += written;
840 len -= written;
844 /* Get setup to recover in case the edit we are about to do goes awry. */
846 void
847 save_pointers ()
849 saved_clean_read_ptr = clean_read_ptr;
850 saved_repl_write_ptr = repl_write_ptr;
853 /* Call this routine to recover our previous state whenever something looks
854 too confusing in the source code we are trying to edit. */
856 void
857 restore_pointers ()
859 clean_read_ptr = saved_clean_read_ptr;
860 repl_write_ptr = saved_repl_write_ptr;
863 /* Return true if the given character is a valid identifier character. */
865 static int
866 is_id_char (ch)
867 char ch;
869 return (isalnum (ch) || (ch == '_') || (ch == '$'));
872 /* Give a message indicating the proper way to invoke this program and then
873 exit with non-zero status. */
875 static void
876 usage ()
878 #ifdef UNPROTOIZE
879 fprintf (stderr, "%s: usage '%s [ -VqfnkN ] [ -i <istring> ] [ filename ... ]'\n",
880 pname, pname);
881 #else /* !defined (UNPROTOIZE) */
882 fprintf (stderr, "%s: usage '%s [ -VqfnkNlgC ] [ -B <dirname> ] [ filename ... ]'\n",
883 pname, pname);
884 #endif /* !defined (UNPROTOIZE) */
885 exit (FATAL_EXIT_CODE);
888 /* Return true if the given filename (assumed to be an absolute filename)
889 designates a file residing anywhere beneath any one of the "system"
890 include directories. */
892 static int
893 in_system_include_dir (path)
894 const char *path;
896 struct default_include *p;
898 if (path[0] != '/')
899 abort (); /* Must be an absolutized filename. */
901 for (p = include_defaults; p->fname; p++)
902 if (!strncmp (path, p->fname, strlen (p->fname))
903 && path[strlen (p->fname)] == '/')
904 return 1;
905 return 0;
908 #if 0
909 /* Return true if the given filename designates a file that the user has
910 read access to and for which the user has write access to the containing
911 directory. */
913 static int
914 file_could_be_converted (const char *path)
916 char *const dir_name = (char *) alloca (strlen (path) + 1);
918 if (my_access (path, R_OK))
919 return 0;
922 char *dir_last_slash;
924 strcpy (dir_name, path);
925 dir_last_slash = rindex (dir_name, '/');
926 if (dir_last_slash)
927 *dir_last_slash = '\0';
928 else
929 abort (); /* Should have been an absolutized filename. */
932 if (my_access (path, W_OK))
933 return 0;
935 return 1;
938 /* Return true if the given filename designates a file that we are allowed
939 to modify. Files which we should not attempt to modify are (a) "system"
940 include files, and (b) files which the user doesn't have write access to,
941 and (c) files which reside in directories which the user doesn't have
942 write access to. Unless requested to be quiet, give warnings about
943 files that we will not try to convert for one reason or another. An
944 exception is made for "system" include files, which we never try to
945 convert and for which we don't issue the usual warnings. */
947 static int
948 file_normally_convertible (const char *path)
950 char *const dir_name = alloca (strlen (path) + 1);
952 if (in_system_include_dir (path))
953 return 0;
956 char *dir_last_slash;
958 strcpy (dir_name, path);
959 dir_last_slash = rindex (dir_name, '/');
960 if (dir_last_slash)
961 *dir_last_slash = '\0';
962 else
963 abort (); /* Should have been an absolutized filename. */
966 if (my_access (path, R_OK))
968 if (!quiet_flag)
969 fprintf (stderr, "%s: warning: no read access for file `%s'\n",
970 pname, shortpath (NULL, path));
971 return 0;
974 if (my_access (path, W_OK))
976 if (!quiet_flag)
977 fprintf (stderr, "%s: warning: no write access for file `%s'\n",
978 pname, shortpath (NULL, path));
979 return 0;
982 if (my_access (dir_name, W_OK))
984 if (!quiet_flag)
985 fprintf (stderr, "%s: warning: no write access for dir containing `%s'\n",
986 pname, shortpath (NULL, path));
987 return 0;
990 return 1;
992 #endif /* 0 */
994 #ifndef UNPROTOIZE
996 /* Return true if the given file_info struct refers to the special SYSCALLS.c.X
997 file. Return false otherwise. */
999 static int
1000 is_syscalls_file (fi_p)
1001 const file_info *fi_p;
1003 char const *f = fi_p->hash_entry->symbol;
1004 size_t fl = strlen (f), sysl = sizeof (syscalls_filename) - 1;
1005 return sysl <= fl && strcmp (f + fl - sysl, syscalls_filename) == 0;
1008 #endif /* !defined (UNPROTOIZE) */
1010 /* Check to see if this file will need to have anything done to it on this
1011 run. If there is nothing in the given file which both needs conversion
1012 and for which we have the necessary stuff to do the conversion, return
1013 false. Otherwise, return true.
1015 Note that (for protoize) it is only valid to call this function *after*
1016 the connections between declarations and definitions have all been made
1017 by connect_defs_and_decs. */
1019 static int
1020 needs_to_be_converted (file_p)
1021 const file_info *file_p;
1023 const def_dec_info *ddp;
1025 #ifndef UNPROTOIZE
1027 if (is_syscalls_file (file_p))
1028 return 0;
1030 #endif /* !defined (UNPROTOIZE) */
1032 for (ddp = file_p->defs_decs; ddp; ddp = ddp->next_in_file)
1034 if (
1036 #ifndef UNPROTOIZE
1038 /* ... and if we a protoizing and this function is in old style ... */
1039 !ddp->prototyped
1040 /* ... and if this a definition or is a decl with an associated def ... */
1041 && (ddp->is_func_def || (!ddp->is_func_def && ddp->definition))
1043 #else /* defined (UNPROTOIZE) */
1045 /* ... and if we are unprotoizing and this function is in new style ... */
1046 ddp->prototyped
1048 #endif /* defined (UNPROTOIZE) */
1050 /* ... then the containing file needs converting. */
1051 return -1;
1052 return 0;
1055 /* Return 1 if the file name NAME is in a directory
1056 that should be converted. */
1058 static int
1059 directory_specified_p (name)
1060 const char *name;
1062 struct string_list *p;
1064 for (p = directory_list; p; p = p->next)
1065 if (!strncmp (name, p->name, strlen (p->name))
1066 && name[strlen (p->name)] == '/')
1068 const char *q = name + strlen (p->name) + 1;
1070 /* If there are more slashes, it's in a subdir, so
1071 this match doesn't count. */
1072 while (*q)
1073 if (*q++ == '/')
1074 goto lose;
1075 return 1;
1077 lose: ;
1080 return 0;
1083 /* Return 1 if the file named NAME should be excluded from conversion. */
1085 static int
1086 file_excluded_p (name)
1087 const char *name;
1089 struct string_list *p;
1090 int len = strlen (name);
1092 for (p = exclude_list; p; p = p->next)
1093 if (!strcmp (name + len - strlen (p->name), p->name)
1094 && name[len - strlen (p->name) - 1] == '/')
1095 return 1;
1097 return 0;
1100 /* Construct a new element of a string_list.
1101 STRING is the new element value, and REST holds the remaining elements. */
1103 static struct string_list *
1104 string_list_cons (string, rest)
1105 char *string;
1106 struct string_list *rest;
1108 struct string_list *temp
1109 = (struct string_list *) xmalloc (sizeof (struct string_list));
1111 temp->next = rest;
1112 temp->name = string;
1113 return temp;
1116 /* ??? The GNU convention for mentioning function args in its comments
1117 is to capitalize them. So change "hash_tab_p" to HASH_TAB_P below.
1118 Likewise for all the other functions. */
1120 /* Given a hash table, apply some function to each node in the table. The
1121 table to traverse is given as the "hash_tab_p" argument, and the
1122 function to be applied to each node in the table is given as "func"
1123 argument. */
1125 static void
1126 visit_each_hash_node (hash_tab_p, func)
1127 const hash_table_entry *hash_tab_p;
1128 void (*func)();
1130 const hash_table_entry *primary;
1132 for (primary = hash_tab_p; primary < &hash_tab_p[HASH_TABLE_SIZE]; primary++)
1133 if (primary->symbol)
1135 hash_table_entry *second;
1137 (*func)(primary);
1138 for (second = primary->hash_next; second; second = second->hash_next)
1139 (*func) (second);
1143 /* Initialize all of the fields of a new hash table entry, pointed
1144 to by the "p" parameter. Note that the space to hold the entry
1145 is assumed to have already been allocated before this routine is
1146 called. */
1148 static hash_table_entry *
1149 add_symbol (p, s)
1150 hash_table_entry *p;
1151 const char *s;
1153 p->hash_next = NULL;
1154 p->symbol = savestring (s, strlen (s));
1155 p->ddip = NULL;
1156 p->fip = NULL;
1157 return p;
1160 /* Look for a particular function name or filename in the particular
1161 hash table indicated by "hash_tab_p". If the name is not in the
1162 given hash table, add it. Either way, return a pointer to the
1163 hash table entry for the given name. */
1165 static hash_table_entry *
1166 lookup (hash_tab_p, search_symbol)
1167 hash_table_entry *hash_tab_p;
1168 const char *search_symbol;
1170 int hash_value = 0;
1171 const char *search_symbol_char_p = search_symbol;
1172 hash_table_entry *p;
1174 while (*search_symbol_char_p)
1175 hash_value += *search_symbol_char_p++;
1176 hash_value &= hash_mask;
1177 p = &hash_tab_p[hash_value];
1178 if (! p->symbol)
1179 return add_symbol (p, search_symbol);
1180 if (!strcmp (p->symbol, search_symbol))
1181 return p;
1182 while (p->hash_next)
1184 p = p->hash_next;
1185 if (!strcmp (p->symbol, search_symbol))
1186 return p;
1188 p->hash_next = (hash_table_entry *) xmalloc (sizeof (hash_table_entry));
1189 p = p->hash_next;
1190 return add_symbol (p, search_symbol);
1193 /* Throw a def/dec record on the junk heap.
1195 Also, since we are not using this record anymore, free up all of the
1196 stuff it pointed to. */
1198 static void
1199 free_def_dec (p)
1200 def_dec_info *p;
1202 xfree (p->ansi_decl);
1204 #ifndef UNPROTOIZE
1206 const f_list_chain_item * curr;
1207 const f_list_chain_item * next;
1209 for (curr = p->f_list_chain; curr; curr = next)
1211 next = curr->chain_next;
1212 xfree (curr);
1215 #endif /* !defined (UNPROTOIZE) */
1217 xfree (p);
1220 /* Unexpand as many macro symbol as we can find.
1222 If the given line must be unexpanded, make a copy of it in the heap and
1223 return a pointer to the unexpanded copy. Otherwise return NULL. */
1225 static char *
1226 unexpand_if_needed (aux_info_line)
1227 const char *aux_info_line;
1229 static char *line_buf = 0;
1230 static int line_buf_size = 0;
1231 const unexpansion *unexp_p;
1232 int got_unexpanded = 0;
1233 const char *s;
1234 char *copy_p = line_buf;
1236 if (line_buf == 0)
1238 line_buf_size = 1024;
1239 line_buf = (char *) xmalloc (line_buf_size);
1242 copy_p = line_buf;
1244 /* Make a copy of the input string in line_buf, expanding as necessary. */
1246 for (s = aux_info_line; *s != '\n'; )
1248 for (unexp_p = unexpansions; unexp_p->expanded; unexp_p++)
1250 const char *in_p = unexp_p->expanded;
1251 size_t len = strlen (in_p);
1253 if (*s == *in_p && !strncmp (s, in_p, len) && !is_id_char (s[len]))
1255 int size = strlen (unexp_p->contracted);
1256 got_unexpanded = 1;
1257 if (copy_p + size - line_buf >= line_buf_size)
1259 int offset = copy_p - line_buf;
1260 line_buf_size *= 2;
1261 line_buf_size += size;
1262 line_buf = (char *) xrealloc (line_buf, line_buf_size);
1263 copy_p = line_buf + offset;
1265 strcpy (copy_p, unexp_p->contracted);
1266 copy_p += size;
1268 /* Assume the there will not be another replacement required
1269 within the text just replaced. */
1271 s += len;
1272 goto continue_outer;
1275 if (copy_p - line_buf == line_buf_size)
1277 int offset = copy_p - line_buf;
1278 line_buf_size *= 2;
1279 line_buf = (char *) xrealloc (line_buf, line_buf_size);
1280 copy_p = line_buf + offset;
1282 *copy_p++ = *s++;
1283 continue_outer: ;
1285 if (copy_p + 2 - line_buf >= line_buf_size)
1287 int offset = copy_p - line_buf;
1288 line_buf_size *= 2;
1289 line_buf = (char *) xrealloc (line_buf, line_buf_size);
1290 copy_p = line_buf + offset;
1292 *copy_p++ = '\n';
1293 *copy_p = '\0';
1295 return (got_unexpanded ? savestring (line_buf, copy_p - line_buf) : 0);
1298 /* Return the absolutized filename for the given relative
1299 filename. Note that if that filename is already absolute, it may
1300 still be returned in a modified form because this routine also
1301 eliminates redundant slashes and single dots and eliminates double
1302 dots to get a shortest possible filename from the given input
1303 filename. The absolutization of relative filenames is made by
1304 assuming that the given filename is to be taken as relative to
1305 the first argument (cwd) or to the current directory if cwd is
1306 NULL. */
1308 static char *
1309 abspath (cwd, rel_filename)
1310 const char *cwd;
1311 const char *rel_filename;
1313 /* Setup the current working directory as needed. */
1314 const char *cwd2 = (cwd) ? cwd : cwd_buffer;
1315 char *const abs_buffer
1316 = (char *) alloca (strlen (cwd2) + strlen (rel_filename) + 2);
1317 char *endp = abs_buffer;
1318 char *outp, *inp;
1320 /* Copy the filename (possibly preceded by the current working
1321 directory name) into the absolutization buffer. */
1324 const char *src_p;
1326 if (rel_filename[0] != '/')
1328 src_p = cwd2;
1329 while (*endp++ = *src_p++)
1330 continue;
1331 *(endp-1) = '/'; /* overwrite null */
1333 src_p = rel_filename;
1334 while (*endp++ = *src_p++)
1335 continue;
1338 /* Now make a copy of abs_buffer into abs_buffer, shortening the
1339 filename (by taking out slashes and dots) as we go. */
1341 outp = inp = abs_buffer;
1342 *outp++ = *inp++; /* copy first slash */
1343 #ifdef apollo
1344 if (inp[0] == '/')
1345 *outp++ = *inp++; /* copy second slash */
1346 #endif
1347 for (;;)
1349 if (!inp[0])
1350 break;
1351 else if (inp[0] == '/' && outp[-1] == '/')
1353 inp++;
1354 continue;
1356 else if (inp[0] == '.' && outp[-1] == '/')
1358 if (!inp[1])
1359 break;
1360 else if (inp[1] == '/')
1362 inp += 2;
1363 continue;
1365 else if ((inp[1] == '.') && (inp[2] == 0 || inp[2] == '/'))
1367 inp += (inp[2] == '/') ? 3 : 2;
1368 outp -= 2;
1369 while (outp >= abs_buffer && *outp != '/')
1370 outp--;
1371 if (outp < abs_buffer)
1373 /* Catch cases like /.. where we try to backup to a
1374 point above the absolute root of the logical file
1375 system. */
1377 fprintf (stderr, "%s: invalid file name: %s\n",
1378 pname, rel_filename);
1379 exit (FATAL_EXIT_CODE);
1381 *++outp = '\0';
1382 continue;
1385 *outp++ = *inp++;
1388 /* On exit, make sure that there is a trailing null, and make sure that
1389 the last character of the returned string is *not* a slash. */
1391 *outp = '\0';
1392 if (outp[-1] == '/')
1393 *--outp = '\0';
1395 /* Make a copy (in the heap) of the stuff left in the absolutization
1396 buffer and return a pointer to the copy. */
1398 return savestring (abs_buffer, outp - abs_buffer);
1401 /* Given a filename (and possibly a directory name from which the filename
1402 is relative) return a string which is the shortest possible
1403 equivalent for the corresponding full (absolutized) filename. The
1404 shortest possible equivalent may be constructed by converting the
1405 absolutized filename to be a relative filename (i.e. relative to
1406 the actual current working directory). However if a relative filename
1407 is longer, then the full absolute filename is returned.
1409 KNOWN BUG:
1411 Note that "simple-minded" conversion of any given type of filename (either
1412 relative or absolute) may not result in a valid equivalent filename if any
1413 subpart of the original filename is actually a symbolic link. */
1415 static const char *
1416 shortpath (cwd, filename)
1417 const char *cwd;
1418 const char *filename;
1420 char *rel_buffer;
1421 char *rel_buf_p;
1422 char *cwd_p = cwd_buffer;
1423 char *path_p;
1424 int unmatched_slash_count = 0;
1425 size_t filename_len = strlen (filename);
1427 path_p = abspath (cwd, filename);
1428 rel_buf_p = rel_buffer = (char *) xmalloc (filename_len);
1430 while (*cwd_p && (*cwd_p == *path_p))
1432 cwd_p++;
1433 path_p++;
1435 if (!*cwd_p && (!*path_p || *path_p == '/')) /* whole pwd matched */
1437 if (!*path_p) /* input *is* the current path! */
1438 return ".";
1439 else
1440 return ++path_p;
1442 else
1444 if (*path_p)
1446 --cwd_p;
1447 --path_p;
1448 while (*cwd_p != '/') /* backup to last slash */
1450 --cwd_p;
1451 --path_p;
1453 cwd_p++;
1454 path_p++;
1455 unmatched_slash_count++;
1458 /* Find out how many directory levels in cwd were *not* matched. */
1459 while (*cwd_p)
1460 if (*cwd_p++ == '/')
1461 unmatched_slash_count++;
1463 /* Now we know how long the "short name" will be.
1464 Reject it if longer than the input. */
1465 if (unmatched_slash_count * 3 + strlen (path_p) >= filename_len)
1466 return filename;
1468 /* For each of them, put a `../' at the beginning of the short name. */
1469 while (unmatched_slash_count--)
1471 /* Give up if the result gets to be longer
1472 than the absolute path name. */
1473 if (rel_buffer + filename_len <= rel_buf_p + 3)
1474 return filename;
1475 *rel_buf_p++ = '.';
1476 *rel_buf_p++ = '.';
1477 *rel_buf_p++ = '/';
1480 /* Then tack on the unmatched part of the desired file's name. */
1483 if (rel_buffer + filename_len <= rel_buf_p)
1484 return filename;
1486 while (*rel_buf_p++ = *path_p++);
1488 --rel_buf_p;
1489 if (*(rel_buf_p-1) == '/')
1490 *--rel_buf_p = '\0';
1491 return rel_buffer;
1495 /* Lookup the given filename in the hash table for filenames. If it is a
1496 new one, then the hash table info pointer will be null. In this case,
1497 we create a new file_info record to go with the filename, and we initialize
1498 that record with some reasonable values. */
1500 /* FILENAME was const, but that causes a warning on AIX when calling stat.
1501 That is probably a bug in AIX, but might as well avoid the warning. */
1503 static file_info *
1504 find_file (filename, do_not_stat)
1505 char *filename;
1506 int do_not_stat;
1508 hash_table_entry *hash_entry_p;
1510 hash_entry_p = lookup (filename_primary, filename);
1511 if (hash_entry_p->fip)
1512 return hash_entry_p->fip;
1513 else
1515 struct stat stat_buf;
1516 file_info *file_p = (file_info *) xmalloc (sizeof (file_info));
1518 /* If we cannot get status on any given source file, give a warning
1519 and then just set its time of last modification to infinity. */
1521 if (do_not_stat)
1522 stat_buf.st_mtime = (time_t) 0;
1523 else
1525 if (my_stat (filename, &stat_buf) == -1)
1527 fprintf (stderr, "%s: %s: can't get status: %s\n",
1528 pname, shortpath (NULL, filename), my_strerror(errno));
1529 stat_buf.st_mtime = (time_t) -1;
1533 hash_entry_p->fip = file_p;
1534 file_p->hash_entry = hash_entry_p;
1535 file_p->defs_decs = NULL;
1536 file_p->mtime = stat_buf.st_mtime;
1537 return file_p;
1541 /* Generate a fatal error because some part of the aux_info file is
1542 messed up. */
1544 static void
1545 aux_info_corrupted ()
1547 fprintf (stderr, "\n%s: fatal error: aux info file corrupted at line %d\n",
1548 pname, current_aux_info_lineno);
1549 exit (FATAL_EXIT_CODE);
1552 /* ??? This comment is vague. Say what the condition is for. */
1553 /* Check to see that a condition is true. This is kind of like an assert. */
1555 static void
1556 check_aux_info (cond)
1557 int cond;
1559 if (! cond)
1560 aux_info_corrupted ();
1563 /* Given a pointer to the closing right parenthesis for a particular formals
1564 list (in an aux_info file) find the corresponding left parenthesis and
1565 return a pointer to it. */
1567 static const char *
1568 find_corresponding_lparen (p)
1569 const char *p;
1571 const char *q;
1572 int paren_depth;
1574 for (paren_depth = 1, q = p-1; paren_depth; q--)
1576 switch (*q)
1578 case ')':
1579 paren_depth++;
1580 break;
1581 case '(':
1582 paren_depth--;
1583 break;
1586 return ++q;
1589 /* Given a line from an aux info file, and a time at which the aux info
1590 file it came from was created, check to see if the item described in
1591 the line comes from a file which has been modified since the aux info
1592 file was created. If so, return non-zero, else return zero. */
1594 static int
1595 referenced_file_is_newer (l, aux_info_mtime)
1596 const char *l;
1597 time_t aux_info_mtime;
1599 const char *p;
1600 file_info *fi_p;
1601 char *filename;
1603 check_aux_info (l[0] == '/');
1604 check_aux_info (l[1] == '*');
1605 check_aux_info (l[2] == ' ');
1608 const char *filename_start = p = l + 3;
1610 while (*p != ':')
1611 p++;
1612 filename = (char *) alloca ((size_t) (p - filename_start) + 1);
1613 strncpy (filename, filename_start, (size_t) (p - filename_start));
1614 filename[p-filename_start] = '\0';
1617 /* Call find_file to find the file_info record associated with the file
1618 which contained this particular def or dec item. Note that this call
1619 may cause a new file_info record to be created if this is the first time
1620 that we have ever known about this particular file. */
1622 fi_p = find_file (abspath (invocation_filename, filename), 0);
1624 return (fi_p->mtime > aux_info_mtime);
1627 /* Given a line of info from the aux_info file, create a new
1628 def_dec_info record to remember all of the important information about
1629 a function definition or declaration.
1631 Link this record onto the list of such records for the particular file in
1632 which it occurred in proper (descending) line number order (for now).
1634 If there is an identical record already on the list for the file, throw
1635 this one away. Doing so takes care of the (useless and troublesome)
1636 duplicates which are bound to crop up due to multiple inclusions of any
1637 given individual header file.
1639 Finally, link the new def_dec record onto the list of such records
1640 pertaining to this particular function name. */
1642 static void
1643 save_def_or_dec (l, is_syscalls)
1644 const char *l;
1645 int is_syscalls;
1647 const char *p;
1648 const char *semicolon_p;
1649 def_dec_info *def_dec_p = (def_dec_info *) xmalloc (sizeof (def_dec_info));
1651 #ifndef UNPROTOIZE
1652 def_dec_p->written = 0;
1653 #endif /* !defined (UNPROTOIZE) */
1655 /* Start processing the line by picking off 5 pieces of information from
1656 the left hand end of the line. These are filename, line number,
1657 new/old/implicit flag (new = ANSI prototype format), definition or
1658 declaration flag, and extern/static flag). */
1660 check_aux_info (l[0] == '/');
1661 check_aux_info (l[1] == '*');
1662 check_aux_info (l[2] == ' ');
1665 const char *filename_start = p = l + 3;
1666 char *filename;
1668 while (*p != ':')
1669 p++;
1670 filename = (char *) alloca ((size_t) (p - filename_start) + 1);
1671 strncpy (filename, filename_start, (size_t) (p - filename_start));
1672 filename[p-filename_start] = '\0';
1674 /* Call find_file to find the file_info record associated with the file
1675 which contained this particular def or dec item. Note that this call
1676 may cause a new file_info record to be created if this is the first time
1677 that we have ever known about this particular file.
1679 Note that we started out by forcing all of the base source file names
1680 (i.e. the names of the aux_info files with the .X stripped off) into the
1681 filenames hash table, and we simultaneously setup file_info records for
1682 all of these base file names (even if they may be useless later).
1683 The file_info records for all of these "base" file names (properly)
1684 act as file_info records for the "original" (i.e. un-included) files
1685 which were submitted to gcc for compilation (when the -aux-info
1686 option was used). */
1688 def_dec_p->file = find_file (abspath (invocation_filename, filename), is_syscalls);
1692 const char *line_number_start = ++p;
1693 char line_number[10];
1695 while (*p != ':')
1696 p++;
1697 strncpy (line_number, line_number_start, (size_t) (p - line_number_start));
1698 line_number[p-line_number_start] = '\0';
1699 def_dec_p->line = atoi (line_number);
1702 /* Check that this record describes a new-style, old-style, or implicit
1703 definition or declaration. */
1705 p++; /* Skip over the `:'. */
1706 check_aux_info ((*p == 'N') || (*p == 'O') || (*p == 'I'));
1708 /* Is this a new style (ANSI prototyped) definition or declaration? */
1710 def_dec_p->prototyped = (*p == 'N');
1712 #ifndef UNPROTOIZE
1714 /* Is this an implicit declaration? */
1716 def_dec_p->is_implicit = (*p == 'I');
1718 #endif /* !defined (UNPROTOIZE) */
1720 p++;
1722 check_aux_info ((*p == 'C') || (*p == 'F'));
1724 /* Is this item a function definition (F) or a declaration (C). Note that
1725 we treat item taken from the syscalls file as though they were function
1726 definitions regardless of what the stuff in the file says. */
1728 def_dec_p->is_func_def = ((*p++ == 'F') || is_syscalls);
1730 #ifndef UNPROTOIZE
1731 def_dec_p->definition = 0; /* Fill this in later if protoizing. */
1732 #endif /* !defined (UNPROTOIZE) */
1734 check_aux_info (*p++ == ' ');
1735 check_aux_info (*p++ == '*');
1736 check_aux_info (*p++ == '/');
1737 check_aux_info (*p++ == ' ');
1739 #ifdef UNPROTOIZE
1740 check_aux_info ((!strncmp (p, "static", 6)) || (!strncmp (p, "extern", 6)));
1741 #else /* !defined (UNPROTOIZE) */
1742 if (!strncmp (p, "static", 6))
1743 def_dec_p->is_static = -1;
1744 else if (!strncmp (p, "extern", 6))
1745 def_dec_p->is_static = 0;
1746 else
1747 check_aux_info (0); /* Didn't find either `extern' or `static'. */
1748 #endif /* !defined (UNPROTOIZE) */
1751 const char *ansi_start = p;
1753 p += 6; /* Pass over the "static" or "extern". */
1755 /* We are now past the initial stuff. Search forward from here to find
1756 the terminating semicolon that should immediately follow the entire
1757 ANSI format function declaration. */
1759 while (*++p != ';')
1760 continue;
1762 semicolon_p = p;
1764 /* Make a copy of the ansi declaration part of the line from the aux_info
1765 file. */
1767 def_dec_p->ansi_decl
1768 = dupnstr (ansi_start, (size_t) ((semicolon_p+1) - ansi_start));
1770 /* Backup and point at the final right paren of the final argument list. */
1772 p--;
1774 #ifndef UNPROTOIZE
1775 def_dec_p->f_list_chain = NULL;
1776 #endif /* !defined (UNPROTOIZE) */
1778 while (p != ansi_start && (p[-1] == ' ' || p[-1] == '\t')) p--;
1779 if (*p != ')')
1781 free_def_dec (def_dec_p);
1782 return;
1786 /* Now isolate a whole set of formal argument lists, one-by-one. Normally,
1787 there will only be one list to isolate, but there could be more. */
1789 def_dec_p->f_list_count = 0;
1791 for (;;)
1793 const char *left_paren_p = find_corresponding_lparen (p);
1794 #ifndef UNPROTOIZE
1796 f_list_chain_item *cip
1797 = (f_list_chain_item *) xmalloc (sizeof (f_list_chain_item));
1799 cip->formals_list
1800 = dupnstr (left_paren_p + 1, (size_t) (p - (left_paren_p+1)));
1802 /* Add the new chain item at the head of the current list. */
1804 cip->chain_next = def_dec_p->f_list_chain;
1805 def_dec_p->f_list_chain = cip;
1807 #endif /* !defined (UNPROTOIZE) */
1808 def_dec_p->f_list_count++;
1810 p = left_paren_p - 2;
1812 /* p must now point either to another right paren, or to the last
1813 character of the name of the function that was declared/defined.
1814 If p points to another right paren, then this indicates that we
1815 are dealing with multiple formals lists. In that case, there
1816 really should be another right paren preceding this right paren. */
1818 if (*p != ')')
1819 break;
1820 else
1821 check_aux_info (*--p == ')');
1826 const char *past_fn = p + 1;
1828 check_aux_info (*past_fn == ' ');
1830 /* Scan leftwards over the identifier that names the function. */
1832 while (is_id_char (*p))
1833 p--;
1834 p++;
1836 /* p now points to the leftmost character of the function name. */
1839 char *fn_string = (char *) alloca (past_fn - p + 1);
1841 strncpy (fn_string, p, (size_t) (past_fn - p));
1842 fn_string[past_fn-p] = '\0';
1843 def_dec_p->hash_entry = lookup (function_name_primary, fn_string);
1847 /* Look at all of the defs and decs for this function name that we have
1848 collected so far. If there is already one which is at the same
1849 line number in the same file, then we can discard this new def_dec_info
1850 record.
1852 As an extra assurance that any such pair of (nominally) identical
1853 function declarations are in fact identical, we also compare the
1854 ansi_decl parts of the lines from the aux_info files just to be on
1855 the safe side.
1857 This comparison will fail if (for instance) the user was playing
1858 messy games with the preprocessor which ultimately causes one
1859 function declaration in one header file to look differently when
1860 that file is included by two (or more) other files. */
1863 const def_dec_info *other;
1865 for (other = def_dec_p->hash_entry->ddip; other; other = other->next_for_func)
1867 if (def_dec_p->line == other->line && def_dec_p->file == other->file)
1869 if (strcmp (def_dec_p->ansi_decl, other->ansi_decl))
1871 fprintf (stderr, "%s:%d: declaration of function `%s' takes different forms\n",
1872 def_dec_p->file->hash_entry->symbol,
1873 def_dec_p->line,
1874 def_dec_p->hash_entry->symbol);
1875 exit (FATAL_EXIT_CODE);
1877 free_def_dec (def_dec_p);
1878 return;
1883 #ifdef UNPROTOIZE
1885 /* If we are doing unprotoizing, we must now setup the pointers that will
1886 point to the K&R name list and to the K&R argument declarations list.
1888 Note that if this is only a function declaration, then we should not
1889 expect to find any K&R style formals list following the ANSI-style
1890 formals list. This is because GCC knows that such information is
1891 useless in the case of function declarations (function definitions
1892 are a different story however).
1894 Since we are unprotoizing, we don't need any such lists anyway.
1895 All we plan to do is to delete all characters between ()'s in any
1896 case. */
1898 def_dec_p->formal_names = NULL;
1899 def_dec_p->formal_decls = NULL;
1901 if (def_dec_p->is_func_def)
1903 p = semicolon_p;
1904 check_aux_info (*++p == ' ');
1905 check_aux_info (*++p == '/');
1906 check_aux_info (*++p == '*');
1907 check_aux_info (*++p == ' ');
1908 check_aux_info (*++p == '(');
1911 const char *kr_names_start = ++p; /* Point just inside '('. */
1913 while (*p++ != ')')
1914 continue;
1915 p--; /* point to closing right paren */
1917 /* Make a copy of the K&R parameter names list. */
1919 def_dec_p->formal_names
1920 = dupnstr (kr_names_start, (size_t) (p - kr_names_start));
1923 check_aux_info (*++p == ' ');
1924 p++;
1926 /* p now points to the first character of the K&R style declarations
1927 list (if there is one) or to the star-slash combination that ends
1928 the comment in which such lists get embedded. */
1930 /* Make a copy of the K&R formal decls list and set the def_dec record
1931 to point to it. */
1933 if (*p == '*') /* Are there no K&R declarations? */
1935 check_aux_info (*++p == '/');
1936 def_dec_p->formal_decls = "";
1938 else
1940 const char *kr_decls_start = p;
1942 while (p[0] != '*' || p[1] != '/')
1943 p++;
1944 p--;
1946 check_aux_info (*p == ' ');
1948 def_dec_p->formal_decls
1949 = dupnstr (kr_decls_start, (size_t) (p - kr_decls_start));
1952 /* Handle a special case. If we have a function definition marked as
1953 being in "old" style, and if it's formal names list is empty, then
1954 it may actually have the string "void" in its real formals list
1955 in the original source code. Just to make sure, we will get setup
1956 to convert such things anyway.
1958 This kludge only needs to be here because of an insurmountable
1959 problem with generating .X files. */
1961 if (!def_dec_p->prototyped && !*def_dec_p->formal_names)
1962 def_dec_p->prototyped = 1;
1965 /* Since we are unprotoizing, if this item is already in old (K&R) style,
1966 we can just ignore it. If that is true, throw away the itme now. */
1968 if (!def_dec_p->prototyped)
1970 free_def_dec (def_dec_p);
1971 return;
1974 #endif /* defined (UNPROTOIZE) */
1976 /* Add this record to the head of the list of records pertaining to this
1977 particular function name. */
1979 def_dec_p->next_for_func = def_dec_p->hash_entry->ddip;
1980 def_dec_p->hash_entry->ddip = def_dec_p;
1982 /* Add this new def_dec_info record to the sorted list of def_dec_info
1983 records for this file. Note that we don't have to worry about duplicates
1984 (caused by multiple inclusions of header files) here because we have
1985 already eliminated duplicates above. */
1987 if (!def_dec_p->file->defs_decs)
1989 def_dec_p->file->defs_decs = def_dec_p;
1990 def_dec_p->next_in_file = NULL;
1992 else
1994 int line = def_dec_p->line;
1995 const def_dec_info *prev = NULL;
1996 const def_dec_info *curr = def_dec_p->file->defs_decs;
1997 const def_dec_info *next = curr->next_in_file;
1999 while (next && (line < curr->line))
2001 prev = curr;
2002 curr = next;
2003 next = next->next_in_file;
2005 if (line >= curr->line)
2007 def_dec_p->next_in_file = curr;
2008 if (prev)
2009 ((NONCONST def_dec_info *) prev)->next_in_file = def_dec_p;
2010 else
2011 def_dec_p->file->defs_decs = def_dec_p;
2013 else /* assert (next == NULL); */
2015 ((NONCONST def_dec_info *) curr)->next_in_file = def_dec_p;
2016 /* assert (next == NULL); */
2017 def_dec_p->next_in_file = next;
2022 /* Set up the vector COMPILE_PARAMS which is the argument list for running GCC.
2023 Also set input_file_name_index and aux_info_file_name_index
2024 to the indices of the slots where the file names should go. */
2026 /* We initialize the vector by removing -g, -O, -S, -c, and -o options,
2027 and adding '-aux-info AUXFILE -S -o /dev/null INFILE' at the end. */
2029 static void
2030 munge_compile_params (params_list)
2031 const char *params_list;
2033 /* Build up the contents in a temporary vector
2034 that is so big that to has to be big enough. */
2035 const char **temp_params
2036 = (const char **) alloca ((strlen (params_list) + 8) * sizeof (char *));
2037 int param_count = 0;
2038 const char *param;
2040 temp_params[param_count++] = compiler_file_name;
2041 for (;;)
2043 while (isspace (*params_list))
2044 params_list++;
2045 if (!*params_list)
2046 break;
2047 param = params_list;
2048 while (*params_list && !isspace (*params_list))
2049 params_list++;
2050 if (param[0] != '-')
2051 temp_params[param_count++]
2052 = dupnstr (param, (size_t) (params_list - param));
2053 else
2055 switch (param[1])
2057 case 'g':
2058 case 'O':
2059 case 'S':
2060 case 'c':
2061 break; /* Don't copy these. */
2062 case 'o':
2063 while (isspace (*params_list))
2064 params_list++;
2065 while (*params_list && !isspace (*params_list))
2066 params_list++;
2067 break;
2068 default:
2069 temp_params[param_count++]
2070 = dupnstr (param, (size_t) (params_list - param));
2073 if (!*params_list)
2074 break;
2076 temp_params[param_count++] = "-aux-info";
2078 /* Leave room for the aux-info file name argument. */
2079 aux_info_file_name_index = param_count;
2080 temp_params[param_count++] = NULL;
2082 temp_params[param_count++] = "-S";
2083 temp_params[param_count++] = "-o";
2084 temp_params[param_count++] = "/dev/null";
2086 /* Leave room for the input file name argument. */
2087 input_file_name_index = param_count;
2088 temp_params[param_count++] = NULL;
2089 /* Terminate the list. */
2090 temp_params[param_count++] = NULL;
2092 /* Make a copy of the compile_params in heap space. */
2094 compile_params
2095 = (const char **) xmalloc (sizeof (char *) * (param_count+1));
2096 memcpy (compile_params, temp_params, sizeof (char *) * param_count);
2099 /* Do a recompilation for the express purpose of generating a new aux_info
2100 file to go with a specific base source file.
2102 The result is a boolean indicating success. */
2104 static int
2105 gen_aux_info_file (base_filename)
2106 const char *base_filename;
2108 if (!input_file_name_index)
2109 munge_compile_params ("");
2111 /* Store the full source file name in the argument vector. */
2112 compile_params[input_file_name_index] = shortpath (NULL, base_filename);
2113 /* Add .X to source file name to get aux-info file name. */
2114 compile_params[aux_info_file_name_index]
2115 = savestring2 (compile_params[input_file_name_index],
2116 strlen (compile_params[input_file_name_index]),
2117 ".X",
2120 if (!quiet_flag)
2121 fprintf (stderr, "%s: compiling `%s'\n",
2122 pname, compile_params[input_file_name_index]);
2125 char *errmsg_fmt, *errmsg_arg;
2126 int wait_status, pid;
2127 char *temp_base = choose_temp_base ();
2129 pid = pexecute (compile_params[0], (char * const *) compile_params,
2130 pname, temp_base, &errmsg_fmt, &errmsg_arg,
2131 PEXECUTE_FIRST | PEXECUTE_LAST | PEXECUTE_SEARCH);
2133 if (pid == -1)
2135 int errno_val = errno;
2136 fprintf (stderr, "%s: ", pname);
2137 fprintf (stderr, errmsg_fmt, errmsg_arg);
2138 fprintf (stderr, ": %s\n", my_strerror (errno_val));
2139 return 0;
2142 pid = pwait (pid, &wait_status, 0);
2143 if (pid == -1)
2145 fprintf (stderr, "%s: wait: %s\n", pname, my_strerror (errno));
2146 return 0;
2148 if (WIFSIGNALED (wait_status))
2150 fprintf (stderr, "%s: subprocess got fatal signal %d\n",
2151 pname, WTERMSIG (wait_status));
2152 return 0;
2154 if (WIFEXITED (wait_status))
2156 if (WEXITSTATUS (wait_status) != 0)
2158 fprintf (stderr, "%s: %s exited with status %d\n",
2159 pname, compile_params[0], WEXITSTATUS (wait_status));
2160 return 0;
2162 return 1;
2164 abort ();
2168 /* Read in all of the information contained in a single aux_info file.
2169 Save all of the important stuff for later. */
2171 static void
2172 process_aux_info_file (base_source_filename, keep_it, is_syscalls)
2173 const char *base_source_filename;
2174 int keep_it;
2175 int is_syscalls;
2177 size_t base_len = strlen (base_source_filename);
2178 char * aux_info_filename
2179 = (char *) alloca (base_len + strlen (aux_info_suffix) + 1);
2180 char *aux_info_base;
2181 char *aux_info_limit;
2182 char *aux_info_relocated_name;
2183 const char *aux_info_second_line;
2184 time_t aux_info_mtime;
2185 size_t aux_info_size;
2186 int must_create;
2188 /* Construct the aux_info filename from the base source filename. */
2190 strcpy (aux_info_filename, base_source_filename);
2191 strcat (aux_info_filename, aux_info_suffix);
2193 /* Check that the aux_info file exists and is readable. If it does not
2194 exist, try to create it (once only). */
2196 /* If file doesn't exist, set must_create.
2197 Likewise if it exists and we can read it but it is obsolete.
2198 Otherwise, report an error. */
2199 must_create = 0;
2201 /* Come here with must_create set to 1 if file is out of date. */
2202 start_over: ;
2204 if (my_access (aux_info_filename, R_OK) == -1)
2206 if (errno == ENOENT)
2208 if (is_syscalls)
2210 fprintf (stderr, "%s: warning: missing SYSCALLS file `%s'\n",
2211 pname, aux_info_filename);
2212 return;
2214 must_create = 1;
2216 else
2218 fprintf (stderr, "%s: can't read aux info file `%s': %s\n",
2219 pname, shortpath (NULL, aux_info_filename),
2220 my_strerror(errno));
2221 errors++;
2222 return;
2225 #if 0 /* There is code farther down to take care of this. */
2226 else
2228 struct stat s1, s2;
2229 stat (aux_info_file_name, &s1);
2230 stat (base_source_file_name, &s2);
2231 if (s2.st_mtime > s1.st_mtime)
2232 must_create = 1;
2234 #endif /* 0 */
2236 /* If we need a .X file, create it, and verify we can read it. */
2237 if (must_create)
2239 if (!gen_aux_info_file (base_source_filename))
2241 errors++;
2242 return;
2244 if (my_access (aux_info_filename, R_OK) == -1)
2246 fprintf (stderr, "%s: can't read aux info file `%s': %s\n",
2247 pname, shortpath (NULL, aux_info_filename),
2248 my_strerror(errno));
2249 errors++;
2250 return;
2255 struct stat stat_buf;
2257 /* Get some status information about this aux_info file. */
2259 if (my_stat (aux_info_filename, &stat_buf) == -1)
2261 fprintf (stderr, "%s: can't get status of aux info file `%s': %s\n",
2262 pname, shortpath (NULL, aux_info_filename),
2263 my_strerror(errno));
2264 errors++;
2265 return;
2268 /* Check on whether or not this aux_info file is zero length. If it is,
2269 then just ignore it and return. */
2271 if ((aux_info_size = stat_buf.st_size) == 0)
2272 return;
2274 /* Get the date/time of last modification for this aux_info file and
2275 remember it. We will have to check that any source files that it
2276 contains information about are at least this old or older. */
2278 aux_info_mtime = stat_buf.st_mtime;
2280 if (!is_syscalls)
2282 /* Compare mod time with the .c file; update .X file if obsolete.
2283 The code later on can fail to check the .c file
2284 if it did not directly define any functions. */
2286 if (my_stat (base_source_filename, &stat_buf) == -1)
2288 fprintf (stderr, "%s: can't get status of aux info file `%s': %s\n",
2289 pname, shortpath (NULL, base_source_filename),
2290 my_strerror(errno));
2291 errors++;
2292 return;
2294 if (stat_buf.st_mtime > aux_info_mtime)
2296 must_create = 1;
2297 goto start_over;
2303 int aux_info_file;
2305 /* Open the aux_info file. */
2307 if ((aux_info_file = my_open (aux_info_filename, O_RDONLY, 0444 )) == -1)
2309 fprintf (stderr, "%s: can't open aux info file `%s' for reading: %s\n",
2310 pname, shortpath (NULL, aux_info_filename),
2311 my_strerror(errno));
2312 return;
2315 /* Allocate space to hold the aux_info file in memory. */
2317 aux_info_base = xmalloc (aux_info_size + 1);
2318 aux_info_limit = aux_info_base + aux_info_size;
2319 *aux_info_limit = '\0';
2321 /* Read the aux_info file into memory. */
2323 if (safe_read (aux_info_file, aux_info_base, aux_info_size) != aux_info_size)
2325 fprintf (stderr, "%s: error reading aux info file `%s': %s\n",
2326 pname, shortpath (NULL, aux_info_filename),
2327 my_strerror(errno));
2328 free (aux_info_base);
2329 close (aux_info_file);
2330 return;
2333 /* Close the aux info file. */
2335 if (close (aux_info_file))
2337 fprintf (stderr, "%s: error closing aux info file `%s': %s\n",
2338 pname, shortpath (NULL, aux_info_filename),
2339 my_strerror(errno));
2340 free (aux_info_base);
2341 close (aux_info_file);
2342 return;
2346 /* Delete the aux_info file (unless requested not to). If the deletion
2347 fails for some reason, don't even worry about it. */
2349 if (must_create && !keep_it)
2350 if (my_unlink (aux_info_filename) == -1)
2351 fprintf (stderr, "%s: can't delete aux info file `%s': %s\n",
2352 pname, shortpath (NULL, aux_info_filename),
2353 my_strerror(errno));
2355 /* Save a pointer into the first line of the aux_info file which
2356 contains the filename of the directory from which the compiler
2357 was invoked when the associated source file was compiled.
2358 This information is used later to help create complete
2359 filenames out of the (potentially) relative filenames in
2360 the aux_info file. */
2363 char *p = aux_info_base;
2365 while (*p != ':')
2366 p++;
2367 p++;
2368 while (*p == ' ')
2369 p++;
2370 invocation_filename = p; /* Save a pointer to first byte of path. */
2371 while (*p != ' ')
2372 p++;
2373 *p++ = '/';
2374 *p++ = '\0';
2375 while (*p++ != '\n')
2376 continue;
2377 aux_info_second_line = p;
2378 aux_info_relocated_name = 0;
2379 if (invocation_filename[0] != '/')
2381 /* INVOCATION_FILENAME is relative;
2382 append it to BASE_SOURCE_FILENAME's dir. */
2383 char *dir_end;
2384 aux_info_relocated_name = xmalloc (base_len + (p-invocation_filename));
2385 strcpy (aux_info_relocated_name, base_source_filename);
2386 dir_end = rindex (aux_info_relocated_name, '/');
2387 if (dir_end)
2388 dir_end++;
2389 else
2390 dir_end = aux_info_relocated_name;
2391 strcpy (dir_end, invocation_filename);
2392 invocation_filename = aux_info_relocated_name;
2398 const char *aux_info_p;
2400 /* Do a pre-pass on the lines in the aux_info file, making sure that all
2401 of the source files referenced in there are at least as old as this
2402 aux_info file itself. If not, go back and regenerate the aux_info
2403 file anew. Don't do any of this for the syscalls file. */
2405 if (!is_syscalls)
2407 current_aux_info_lineno = 2;
2409 for (aux_info_p = aux_info_second_line; *aux_info_p; )
2411 if (referenced_file_is_newer (aux_info_p, aux_info_mtime))
2413 free (aux_info_base);
2414 xfree (aux_info_relocated_name);
2415 if (keep_it && my_unlink (aux_info_filename) == -1)
2417 fprintf (stderr, "%s: can't delete file `%s': %s\n",
2418 pname, shortpath (NULL, aux_info_filename),
2419 my_strerror(errno));
2420 return;
2422 must_create = 1;
2423 goto start_over;
2426 /* Skip over the rest of this line to start of next line. */
2428 while (*aux_info_p != '\n')
2429 aux_info_p++;
2430 aux_info_p++;
2431 current_aux_info_lineno++;
2435 /* Now do the real pass on the aux_info lines. Save their information in
2436 the in-core data base. */
2438 current_aux_info_lineno = 2;
2440 for (aux_info_p = aux_info_second_line; *aux_info_p;)
2442 char *unexpanded_line = unexpand_if_needed (aux_info_p);
2444 if (unexpanded_line)
2446 save_def_or_dec (unexpanded_line, is_syscalls);
2447 free (unexpanded_line);
2449 else
2450 save_def_or_dec (aux_info_p, is_syscalls);
2452 /* Skip over the rest of this line and get to start of next line. */
2454 while (*aux_info_p != '\n')
2455 aux_info_p++;
2456 aux_info_p++;
2457 current_aux_info_lineno++;
2461 free (aux_info_base);
2462 xfree (aux_info_relocated_name);
2465 #ifndef UNPROTOIZE
2467 /* Check an individual filename for a .c suffix. If the filename has this
2468 suffix, rename the file such that its suffix is changed to .C. This
2469 function implements the -C option. */
2471 static void
2472 rename_c_file (hp)
2473 const hash_table_entry *hp;
2475 const char *filename = hp->symbol;
2476 int last_char_index = strlen (filename) - 1;
2477 char *const new_filename = (char *) alloca (strlen (filename) + 1);
2479 /* Note that we don't care here if the given file was converted or not. It
2480 is possible that the given file was *not* converted, simply because there
2481 was nothing in it which actually required conversion. Even in this case,
2482 we want to do the renaming. Note that we only rename files with the .c
2483 suffix. */
2485 if (filename[last_char_index] != 'c' || filename[last_char_index-1] != '.')
2486 return;
2488 strcpy (new_filename, filename);
2489 new_filename[last_char_index] = 'C';
2491 if (my_link (filename, new_filename) == -1)
2493 fprintf (stderr, "%s: warning: can't link file `%s' to `%s': %s\n",
2494 pname, shortpath (NULL, filename),
2495 shortpath (NULL, new_filename), my_strerror(errno));
2496 errors++;
2497 return;
2500 if (my_unlink (filename) == -1)
2502 fprintf (stderr, "%s: warning: can't delete file `%s': %s\n",
2503 pname, shortpath (NULL, filename), my_strerror(errno));
2504 errors++;
2505 return;
2509 #endif /* !defined (UNPROTOIZE) */
2511 /* Take the list of definitions and declarations attached to a particular
2512 file_info node and reverse the order of the list. This should get the
2513 list into an order such that the item with the lowest associated line
2514 number is nearest the head of the list. When these lists are originally
2515 built, they are in the opposite order. We want to traverse them in
2516 normal line number order later (i.e. lowest to highest) so reverse the
2517 order here. */
2519 static void
2520 reverse_def_dec_list (hp)
2521 const hash_table_entry *hp;
2523 file_info *file_p = hp->fip;
2524 def_dec_info *prev = NULL;
2525 def_dec_info *current = (def_dec_info *)file_p->defs_decs;
2527 if (!current)
2528 return; /* no list to reverse */
2530 prev = current;
2531 if (! (current = (def_dec_info *)current->next_in_file))
2532 return; /* can't reverse a single list element */
2534 prev->next_in_file = NULL;
2536 while (current)
2538 def_dec_info *next = (def_dec_info *)current->next_in_file;
2540 current->next_in_file = prev;
2541 prev = current;
2542 current = next;
2545 file_p->defs_decs = prev;
2548 #ifndef UNPROTOIZE
2550 /* Find the (only?) extern definition for a particular function name, starting
2551 from the head of the linked list of entries for the given name. If we
2552 cannot find an extern definition for the given function name, issue a
2553 warning and scrounge around for the next best thing, i.e. an extern
2554 function declaration with a prototype attached to it. Note that we only
2555 allow such substitutions for extern declarations and never for static
2556 declarations. That's because the only reason we allow them at all is
2557 to let un-prototyped function declarations for system-supplied library
2558 functions get their prototypes from our own extra SYSCALLS.c.X file which
2559 contains all of the correct prototypes for system functions. */
2561 static const def_dec_info *
2562 find_extern_def (head, user)
2563 const def_dec_info *head;
2564 const def_dec_info *user;
2566 const def_dec_info *dd_p;
2567 const def_dec_info *extern_def_p = NULL;
2568 int conflict_noted = 0;
2570 /* Don't act too stupid here. Somebody may try to convert an entire system
2571 in one swell fwoop (rather than one program at a time, as should be done)
2572 and in that case, we may find that there are multiple extern definitions
2573 of a given function name in the entire set of source files that we are
2574 converting. If however one of these definitions resides in exactly the
2575 same source file as the reference we are trying to satisfy then in that
2576 case it would be stupid for us to fail to realize that this one definition
2577 *must* be the precise one we are looking for.
2579 To make sure that we don't miss an opportunity to make this "same file"
2580 leap of faith, we do a prescan of the list of records relating to the
2581 given function name, and we look (on this first scan) *only* for a
2582 definition of the function which is in the same file as the reference
2583 we are currently trying to satisfy. */
2585 for (dd_p = head; dd_p; dd_p = dd_p->next_for_func)
2586 if (dd_p->is_func_def && !dd_p->is_static && dd_p->file == user->file)
2587 return dd_p;
2589 /* Now, since we have not found a definition in the same file as the
2590 reference, we scan the list again and consider all possibilities from
2591 all files. Here we may get conflicts with the things listed in the
2592 SYSCALLS.c.X file, but if that happens it only means that the source
2593 code being converted contains its own definition of a function which
2594 could have been supplied by libc.a. In such cases, we should avoid
2595 issuing the normal warning, and defer to the definition given in the
2596 user's own code. */
2598 for (dd_p = head; dd_p; dd_p = dd_p->next_for_func)
2599 if (dd_p->is_func_def && !dd_p->is_static)
2601 if (!extern_def_p) /* Previous definition? */
2602 extern_def_p = dd_p; /* Remember the first definition found. */
2603 else
2605 /* Ignore definition just found if it came from SYSCALLS.c.X. */
2607 if (is_syscalls_file (dd_p->file))
2608 continue;
2610 /* Quietly replace the definition previously found with the one
2611 just found if the previous one was from SYSCALLS.c.X. */
2613 if (is_syscalls_file (extern_def_p->file))
2615 extern_def_p = dd_p;
2616 continue;
2619 /* If we get here, then there is a conflict between two function
2620 declarations for the same function, both of which came from the
2621 user's own code. */
2623 if (!conflict_noted) /* first time we noticed? */
2625 conflict_noted = 1;
2626 fprintf (stderr, "%s: conflicting extern definitions of '%s'\n",
2627 pname, head->hash_entry->symbol);
2628 if (!quiet_flag)
2630 fprintf (stderr, "%s: declarations of '%s' will not be converted\n",
2631 pname, head->hash_entry->symbol);
2632 fprintf (stderr, "%s: conflict list for '%s' follows:\n",
2633 pname, head->hash_entry->symbol);
2634 fprintf (stderr, "%s: %s(%d): %s\n",
2635 pname,
2636 shortpath (NULL, extern_def_p->file->hash_entry->symbol),
2637 extern_def_p->line, extern_def_p->ansi_decl);
2640 if (!quiet_flag)
2641 fprintf (stderr, "%s: %s(%d): %s\n",
2642 pname,
2643 shortpath (NULL, dd_p->file->hash_entry->symbol),
2644 dd_p->line, dd_p->ansi_decl);
2648 /* We want to err on the side of caution, so if we found multiple conflicting
2649 definitions for the same function, treat this as being that same as if we
2650 had found no definitions (i.e. return NULL). */
2652 if (conflict_noted)
2653 return NULL;
2655 if (!extern_def_p)
2657 /* We have no definitions for this function so do the next best thing.
2658 Search for an extern declaration already in prototype form. */
2660 for (dd_p = head; dd_p; dd_p = dd_p->next_for_func)
2661 if (!dd_p->is_func_def && !dd_p->is_static && dd_p->prototyped)
2663 extern_def_p = dd_p; /* save a pointer to the definition */
2664 if (!quiet_flag)
2665 fprintf (stderr, "%s: warning: using formals list from %s(%d) for function `%s'\n",
2666 pname,
2667 shortpath (NULL, dd_p->file->hash_entry->symbol),
2668 dd_p->line, dd_p->hash_entry->symbol);
2669 break;
2672 /* Gripe about unprototyped function declarations that we found no
2673 corresponding definition (or other source of prototype information)
2674 for.
2676 Gripe even if the unprototyped declaration we are worried about
2677 exists in a file in one of the "system" include directories. We
2678 can gripe about these because we should have at least found a
2679 corresponding (pseudo) definition in the SYSCALLS.c.X file. If we
2680 didn't, then that means that the SYSCALLS.c.X file is missing some
2681 needed prototypes for this particular system. That is worth telling
2682 the user about! */
2684 if (!extern_def_p)
2686 const char *file = user->file->hash_entry->symbol;
2688 if (!quiet_flag)
2689 if (in_system_include_dir (file))
2691 /* Why copy this string into `needed' at all?
2692 Why not just use user->ansi_decl without copying? */
2693 char *needed = (char *) alloca (strlen (user->ansi_decl) + 1);
2694 char *p;
2696 strcpy (needed, user->ansi_decl);
2697 p = (NONCONST char *) substr (needed, user->hash_entry->symbol)
2698 + strlen (user->hash_entry->symbol) + 2;
2699 /* Avoid having ??? in the string. */
2700 *p++ = '?';
2701 *p++ = '?';
2702 *p++ = '?';
2703 strcpy (p, ");");
2705 fprintf (stderr, "%s: %d: `%s' used but missing from SYSCALLS\n",
2706 shortpath (NULL, file), user->line,
2707 needed+7); /* Don't print "extern " */
2709 #if 0
2710 else
2711 fprintf (stderr, "%s: %d: warning: no extern definition for `%s'\n",
2712 shortpath (NULL, file), user->line,
2713 user->hash_entry->symbol);
2714 #endif
2717 return extern_def_p;
2720 /* Find the (only?) static definition for a particular function name in a
2721 given file. Here we get the function-name and the file info indirectly
2722 from the def_dec_info record pointer which is passed in. */
2724 static const def_dec_info *
2725 find_static_definition (user)
2726 const def_dec_info *user;
2728 const def_dec_info *head = user->hash_entry->ddip;
2729 const def_dec_info *dd_p;
2730 int num_static_defs = 0;
2731 const def_dec_info *static_def_p = NULL;
2733 for (dd_p = head; dd_p; dd_p = dd_p->next_for_func)
2734 if (dd_p->is_func_def && dd_p->is_static && (dd_p->file == user->file))
2736 static_def_p = dd_p; /* save a pointer to the definition */
2737 num_static_defs++;
2739 if (num_static_defs == 0)
2741 if (!quiet_flag)
2742 fprintf (stderr, "%s: warning: no static definition for `%s' in file `%s'\n",
2743 pname, head->hash_entry->symbol,
2744 shortpath (NULL, user->file->hash_entry->symbol));
2746 else if (num_static_defs > 1)
2748 fprintf (stderr, "%s: multiple static defs of `%s' in file `%s'\n",
2749 pname, head->hash_entry->symbol,
2750 shortpath (NULL, user->file->hash_entry->symbol));
2751 return NULL;
2753 return static_def_p;
2756 /* Find good prototype style formal argument lists for all of the function
2757 declarations which didn't have them before now.
2759 To do this we consider each function name one at a time. For each function
2760 name, we look at the items on the linked list of def_dec_info records for
2761 that particular name.
2763 Somewhere on this list we should find one (and only one) def_dec_info
2764 record which represents the actual function definition, and this record
2765 should have a nice formal argument list already associated with it.
2767 Thus, all we have to do is to connect up all of the other def_dec_info
2768 records for this particular function name to the special one which has
2769 the full-blown formals list.
2771 Of course it is a little more complicated than just that. See below for
2772 more details. */
2774 static void
2775 connect_defs_and_decs (hp)
2776 const hash_table_entry *hp;
2778 const def_dec_info *dd_p;
2779 const def_dec_info *extern_def_p = NULL;
2780 int first_extern_reference = 1;
2782 /* Traverse the list of definitions and declarations for this particular
2783 function name. For each item on the list, if it is a function
2784 definition (either old style or new style) then GCC has already been
2785 kind enough to produce a prototype for us, and it is associated with
2786 the item already, so declare the item as its own associated "definition".
2788 Also, for each item which is only a function declaration, but which
2789 nonetheless has its own prototype already (obviously supplied by the user)
2790 declare the item as it's own definition.
2792 Note that when/if there are multiple user-supplied prototypes already
2793 present for multiple declarations of any given function, these multiple
2794 prototypes *should* all match exactly with one another and with the
2795 prototype for the actual function definition. We don't check for this
2796 here however, since we assume that the compiler must have already done
2797 this consistency checking when it was creating the .X files. */
2799 for (dd_p = hp->ddip; dd_p; dd_p = dd_p->next_for_func)
2800 if (dd_p->prototyped)
2801 ((NONCONST def_dec_info *) dd_p)->definition = dd_p;
2803 /* Traverse the list of definitions and declarations for this particular
2804 function name. For each item on the list, if it is an extern function
2805 declaration and if it has no associated definition yet, go try to find
2806 the matching extern definition for the declaration.
2808 When looking for the matching function definition, warn the user if we
2809 fail to find one.
2811 If we find more that one function definition also issue a warning.
2813 Do the search for the matching definition only once per unique function
2814 name (and only when absolutely needed) so that we can avoid putting out
2815 redundant warning messages, and so that we will only put out warning
2816 messages when there is actually a reference (i.e. a declaration) for
2817 which we need to find a matching definition. */
2819 for (dd_p = hp->ddip; dd_p; dd_p = dd_p->next_for_func)
2820 if (!dd_p->is_func_def && !dd_p->is_static && !dd_p->definition)
2822 if (first_extern_reference)
2824 extern_def_p = find_extern_def (hp->ddip, dd_p);
2825 first_extern_reference = 0;
2827 ((NONCONST def_dec_info *) dd_p)->definition = extern_def_p;
2830 /* Traverse the list of definitions and declarations for this particular
2831 function name. For each item on the list, if it is a static function
2832 declaration and if it has no associated definition yet, go try to find
2833 the matching static definition for the declaration within the same file.
2835 When looking for the matching function definition, warn the user if we
2836 fail to find one in the same file with the declaration, and refuse to
2837 convert this kind of cross-file static function declaration. After all,
2838 this is stupid practice and should be discouraged.
2840 We don't have to worry about the possibility that there is more than one
2841 matching function definition in the given file because that would have
2842 been flagged as an error by the compiler.
2844 Do the search for the matching definition only once per unique
2845 function-name/source-file pair (and only when absolutely needed) so that
2846 we can avoid putting out redundant warning messages, and so that we will
2847 only put out warning messages when there is actually a reference (i.e. a
2848 declaration) for which we actually need to find a matching definition. */
2850 for (dd_p = hp->ddip; dd_p; dd_p = dd_p->next_for_func)
2851 if (!dd_p->is_func_def && dd_p->is_static && !dd_p->definition)
2853 const def_dec_info *dd_p2;
2854 const def_dec_info *static_def;
2856 /* We have now found a single static declaration for which we need to
2857 find a matching definition. We want to minimize the work (and the
2858 number of warnings), so we will find an appropriate (matching)
2859 static definition for this declaration, and then distribute it
2860 (as the definition for) any and all other static declarations
2861 for this function name which occur within the same file, and which
2862 do not already have definitions.
2864 Note that a trick is used here to prevent subsequent attempts to
2865 call find_static_definition for a given function-name & file
2866 if the first such call returns NULL. Essentially, we convert
2867 these NULL return values to -1, and put the -1 into the definition
2868 field for each other static declaration from the same file which
2869 does not already have an associated definition.
2870 This makes these other static declarations look like they are
2871 actually defined already when the outer loop here revisits them
2872 later on. Thus, the outer loop will skip over them. Later, we
2873 turn the -1's back to NULL's. */
2875 ((NONCONST def_dec_info *) dd_p)->definition =
2876 (static_def = find_static_definition (dd_p))
2877 ? static_def
2878 : (const def_dec_info *) -1;
2880 for (dd_p2 = dd_p->next_for_func; dd_p2; dd_p2 = dd_p2->next_for_func)
2881 if (!dd_p2->is_func_def && dd_p2->is_static
2882 && !dd_p2->definition && (dd_p2->file == dd_p->file))
2883 ((NONCONST def_dec_info *)dd_p2)->definition = dd_p->definition;
2886 /* Convert any dummy (-1) definitions we created in the step above back to
2887 NULL's (as they should be). */
2889 for (dd_p = hp->ddip; dd_p; dd_p = dd_p->next_for_func)
2890 if (dd_p->definition == (def_dec_info *) -1)
2891 ((NONCONST def_dec_info *) dd_p)->definition = NULL;
2894 #endif /* !defined (UNPROTOIZE) */
2896 /* Give a pointer into the clean text buffer, return a number which is the
2897 original source line number that the given pointer points into. */
2899 static int
2900 identify_lineno (clean_p)
2901 const char *clean_p;
2903 int line_num = 1;
2904 const char *scan_p;
2906 for (scan_p = clean_text_base; scan_p <= clean_p; scan_p++)
2907 if (*scan_p == '\n')
2908 line_num++;
2909 return line_num;
2912 /* Issue an error message and give up on doing this particular edit. */
2914 static void
2915 declare_source_confusing (clean_p)
2916 const char *clean_p;
2918 if (!quiet_flag)
2920 if (clean_p == 0)
2921 fprintf (stderr, "%s: %d: warning: source too confusing\n",
2922 shortpath (NULL, convert_filename), last_known_line_number);
2923 else
2924 fprintf (stderr, "%s: %d: warning: source too confusing\n",
2925 shortpath (NULL, convert_filename),
2926 identify_lineno (clean_p));
2928 longjmp (source_confusion_recovery, 1);
2931 /* Check that a condition which is expected to be true in the original source
2932 code is in fact true. If not, issue an error message and give up on
2933 converting this particular source file. */
2935 static void
2936 check_source (cond, clean_p)
2937 int cond;
2938 const char *clean_p;
2940 if (!cond)
2941 declare_source_confusing (clean_p);
2944 /* If we think of the in-core cleaned text buffer as a memory mapped
2945 file (with the variable last_known_line_start acting as sort of a
2946 file pointer) then we can imagine doing "seeks" on the buffer. The
2947 following routine implements a kind of "seek" operation for the in-core
2948 (cleaned) copy of the source file. When finished, it returns a pointer to
2949 the start of a given (numbered) line in the cleaned text buffer.
2951 Note that protoize only has to "seek" in the forward direction on the
2952 in-core cleaned text file buffers, and it never needs to back up.
2954 This routine is made a little bit faster by remembering the line number
2955 (and pointer value) supplied (and returned) from the previous "seek".
2956 This prevents us from always having to start all over back at the top
2957 of the in-core cleaned buffer again. */
2959 static const char *
2960 seek_to_line (n)
2961 int n;
2963 if (n < last_known_line_number)
2964 abort ();
2966 while (n > last_known_line_number)
2968 while (*last_known_line_start != '\n')
2969 check_source (++last_known_line_start < clean_text_limit, 0);
2970 last_known_line_start++;
2971 last_known_line_number++;
2973 return last_known_line_start;
2976 /* Given a pointer to a character in the cleaned text buffer, return a pointer
2977 to the next non-whitespace character which follows it. */
2979 static const char *
2980 forward_to_next_token_char (ptr)
2981 const char *ptr;
2983 for (++ptr; isspace (*ptr); check_source (++ptr < clean_text_limit, 0))
2984 continue;
2985 return ptr;
2988 /* Copy a chunk of text of length `len' and starting at `str' to the current
2989 output buffer. Note that all attempts to add stuff to the current output
2990 buffer ultimately go through here. */
2992 static void
2993 output_bytes (str, len)
2994 const char *str;
2995 size_t len;
2997 if ((repl_write_ptr + 1) + len >= repl_text_limit)
2999 size_t new_size = (repl_text_limit - repl_text_base) << 1;
3000 char *new_buf = (char *) xrealloc (repl_text_base, new_size);
3002 repl_write_ptr = new_buf + (repl_write_ptr - repl_text_base);
3003 repl_text_base = new_buf;
3004 repl_text_limit = new_buf + new_size;
3006 memcpy (repl_write_ptr + 1, str, len);
3007 repl_write_ptr += len;
3010 /* Copy all bytes (except the trailing null) of a null terminated string to
3011 the current output buffer. */
3013 static void
3014 output_string (str)
3015 const char *str;
3017 output_bytes (str, strlen (str));
3020 /* Copy some characters from the original text buffer to the current output
3021 buffer.
3023 This routine takes a pointer argument `p' which is assumed to be a pointer
3024 into the cleaned text buffer. The bytes which are copied are the `original'
3025 equivalents for the set of bytes between the last value of `clean_read_ptr'
3026 and the argument value `p'.
3028 The set of bytes copied however, comes *not* from the cleaned text buffer,
3029 but rather from the direct counterparts of these bytes within the original
3030 text buffer.
3032 Thus, when this function is called, some bytes from the original text
3033 buffer (which may include original comments and preprocessing directives)
3034 will be copied into the output buffer.
3036 Note that the request implied when this routine is called includes the
3037 byte pointed to by the argument pointer `p'. */
3039 static void
3040 output_up_to (p)
3041 const char *p;
3043 size_t copy_length = (size_t) (p - clean_read_ptr);
3044 const char *copy_start = orig_text_base+(clean_read_ptr-clean_text_base)+1;
3046 if (copy_length == 0)
3047 return;
3049 output_bytes (copy_start, copy_length);
3050 clean_read_ptr = p;
3053 /* Given a pointer to a def_dec_info record which represents some form of
3054 definition of a function (perhaps a real definition, or in lieu of that
3055 perhaps just a declaration with a full prototype) return true if this
3056 function is one which we should avoid converting. Return false
3057 otherwise. */
3059 static int
3060 other_variable_style_function (ansi_header)
3061 const char *ansi_header;
3063 #ifdef UNPROTOIZE
3065 /* See if we have a stdarg function, or a function which has stdarg style
3066 parameters or a stdarg style return type. */
3068 return substr (ansi_header, "...") != 0;
3070 #else /* !defined (UNPROTOIZE) */
3072 /* See if we have a varargs function, or a function which has varargs style
3073 parameters or a varargs style return type. */
3075 const char *p;
3076 int len = strlen (varargs_style_indicator);
3078 for (p = ansi_header; p; )
3080 const char *candidate;
3082 if ((candidate = substr (p, varargs_style_indicator)) == 0)
3083 return 0;
3084 else
3085 if (!is_id_char (candidate[-1]) && !is_id_char (candidate[len]))
3086 return 1;
3087 else
3088 p = candidate + 1;
3090 return 0;
3091 #endif /* !defined (UNPROTOIZE) */
3094 /* Do the editing operation specifically for a function "declaration". Note
3095 that editing for function "definitions" are handled in a separate routine
3096 below. */
3098 static void
3099 edit_fn_declaration (def_dec_p, clean_text_p)
3100 const def_dec_info *def_dec_p;
3101 const char *volatile clean_text_p;
3103 const char *start_formals;
3104 const char *end_formals;
3105 const char *function_to_edit = def_dec_p->hash_entry->symbol;
3106 size_t func_name_len = strlen (function_to_edit);
3107 const char *end_of_fn_name;
3109 #ifndef UNPROTOIZE
3111 const f_list_chain_item *this_f_list_chain_item;
3112 const def_dec_info *definition = def_dec_p->definition;
3114 /* If we are protoizing, and if we found no corresponding definition for
3115 this particular function declaration, then just leave this declaration
3116 exactly as it is. */
3118 if (!definition)
3119 return;
3121 /* If we are protoizing, and if the corresponding definition that we found
3122 for this particular function declaration defined an old style varargs
3123 function, then we want to issue a warning and just leave this function
3124 declaration unconverted. */
3126 if (other_variable_style_function (definition->ansi_decl))
3128 if (!quiet_flag)
3129 fprintf (stderr, "%s: %d: warning: varargs function declaration not converted\n",
3130 shortpath (NULL, def_dec_p->file->hash_entry->symbol),
3131 def_dec_p->line);
3132 return;
3135 #endif /* !defined (UNPROTOIZE) */
3137 /* Setup here to recover from confusing source code detected during this
3138 particular "edit". */
3140 save_pointers ();
3141 if (setjmp (source_confusion_recovery))
3143 restore_pointers ();
3144 fprintf (stderr, "%s: declaration of function `%s' not converted\n",
3145 pname, function_to_edit);
3146 return;
3149 /* We are editing a function declaration. The line number we did a seek to
3150 contains the comma or semicolon which follows the declaration. Our job
3151 now is to scan backwards looking for the function name. This name *must*
3152 be followed by open paren (ignoring whitespace, of course). We need to
3153 replace everything between that open paren and the corresponding closing
3154 paren. If we are protoizing, we need to insert the prototype-style
3155 formals lists. If we are unprotoizing, we need to just delete everything
3156 between the pairs of opening and closing parens. */
3158 /* First move up to the end of the line. */
3160 while (*clean_text_p != '\n')
3161 check_source (++clean_text_p < clean_text_limit, 0);
3162 clean_text_p--; /* Point to just before the newline character. */
3164 /* Now we can scan backwards for the function name. */
3168 for (;;)
3170 /* Scan leftwards until we find some character which can be
3171 part of an identifier. */
3173 while (!is_id_char (*clean_text_p))
3174 check_source (--clean_text_p > clean_read_ptr, 0);
3176 /* Scan backwards until we find a char that cannot be part of an
3177 identifier. */
3179 while (is_id_char (*clean_text_p))
3180 check_source (--clean_text_p > clean_read_ptr, 0);
3182 /* Having found an "id break", see if the following id is the one
3183 that we are looking for. If so, then exit from this loop. */
3185 if (!strncmp (clean_text_p+1, function_to_edit, func_name_len))
3187 char ch = *(clean_text_p + 1 + func_name_len);
3189 /* Must also check to see that the name in the source text
3190 ends where it should (in order to prevent bogus matches
3191 on similar but longer identifiers. */
3193 if (! is_id_char (ch))
3194 break; /* exit from loop */
3198 /* We have now found the first perfect match for the function name in
3199 our backward search. This may or may not be the actual function
3200 name at the start of the actual function declaration (i.e. we could
3201 have easily been mislead). We will try to avoid getting fooled too
3202 often by looking forward for the open paren which should follow the
3203 identifier we just found. We ignore whitespace while hunting. If
3204 the next non-whitespace byte we see is *not* an open left paren,
3205 then we must assume that we have been fooled and we start over
3206 again accordingly. Note that there is no guarantee, that even if
3207 we do see the open paren, that we are in the right place.
3208 Programmers do the strangest things sometimes! */
3210 end_of_fn_name = clean_text_p + strlen (def_dec_p->hash_entry->symbol);
3211 start_formals = forward_to_next_token_char (end_of_fn_name);
3213 while (*start_formals != '(');
3215 /* start_of_formals now points to the opening left paren which immediately
3216 follows the name of the function. */
3218 /* Note that there may be several formals lists which need to be modified
3219 due to the possibility that the return type of this function is a
3220 pointer-to-function type. If there are several formals lists, we
3221 convert them in left-to-right order here. */
3223 #ifndef UNPROTOIZE
3224 this_f_list_chain_item = definition->f_list_chain;
3225 #endif /* !defined (UNPROTOIZE) */
3227 for (;;)
3230 int depth;
3232 end_formals = start_formals + 1;
3233 depth = 1;
3234 for (; depth; check_source (++end_formals < clean_text_limit, 0))
3236 switch (*end_formals)
3238 case '(':
3239 depth++;
3240 break;
3241 case ')':
3242 depth--;
3243 break;
3246 end_formals--;
3249 /* end_formals now points to the closing right paren of the formals
3250 list whose left paren is pointed to by start_formals. */
3252 /* Now, if we are protoizing, we insert the new ANSI-style formals list
3253 attached to the associated definition of this function. If however
3254 we are unprotoizing, then we simply delete any formals list which
3255 may be present. */
3257 output_up_to (start_formals);
3258 #ifndef UNPROTOIZE
3259 if (this_f_list_chain_item)
3261 output_string (this_f_list_chain_item->formals_list);
3262 this_f_list_chain_item = this_f_list_chain_item->chain_next;
3264 else
3266 if (!quiet_flag)
3267 fprintf (stderr, "%s: warning: too many parameter lists in declaration of `%s'\n",
3268 pname, def_dec_p->hash_entry->symbol);
3269 check_source (0, end_formals); /* leave the declaration intact */
3271 #endif /* !defined (UNPROTOIZE) */
3272 clean_read_ptr = end_formals - 1;
3274 /* Now see if it looks like there may be another formals list associated
3275 with the function declaration that we are converting (following the
3276 formals list that we just converted. */
3279 const char *another_r_paren = forward_to_next_token_char (end_formals);
3281 if ((*another_r_paren != ')')
3282 || (*(start_formals = forward_to_next_token_char (another_r_paren)) != '('))
3284 #ifndef UNPROTOIZE
3285 if (this_f_list_chain_item)
3287 if (!quiet_flag)
3288 fprintf (stderr, "\n%s: warning: too few parameter lists in declaration of `%s'\n",
3289 pname, def_dec_p->hash_entry->symbol);
3290 check_source (0, start_formals); /* leave the decl intact */
3292 #endif /* !defined (UNPROTOIZE) */
3293 break;
3298 /* There does appear to be yet another formals list, so loop around
3299 again, and convert it also. */
3303 /* Edit a whole group of formals lists, starting with the rightmost one
3304 from some set of formals lists. This routine is called once (from the
3305 outside) for each function declaration which is converted. It is
3306 recursive however, and it calls itself once for each remaining formal
3307 list that lies to the left of the one it was originally called to work
3308 on. Thus, a whole set gets done in right-to-left order.
3310 This routine returns non-zero if it thinks that it should not be trying
3311 to convert this particular function definition (because the name of the
3312 function doesn't match the one expected). */
3314 static int
3315 edit_formals_lists (end_formals, f_list_count, def_dec_p)
3316 const char *end_formals;
3317 unsigned int f_list_count;
3318 const def_dec_info *def_dec_p;
3320 const char *start_formals;
3321 int depth;
3323 start_formals = end_formals - 1;
3324 depth = 1;
3325 for (; depth; check_source (--start_formals > clean_read_ptr, 0))
3327 switch (*start_formals)
3329 case '(':
3330 depth--;
3331 break;
3332 case ')':
3333 depth++;
3334 break;
3337 start_formals++;
3339 /* start_formals now points to the opening left paren of the formals list. */
3341 f_list_count--;
3343 if (f_list_count)
3345 const char *next_end;
3347 /* There should be more formal lists to the left of here. */
3349 next_end = start_formals - 1;
3350 check_source (next_end > clean_read_ptr, 0);
3351 while (isspace (*next_end))
3352 check_source (--next_end > clean_read_ptr, 0);
3353 check_source (*next_end == ')', next_end);
3354 check_source (--next_end > clean_read_ptr, 0);
3355 check_source (*next_end == ')', next_end);
3356 if (edit_formals_lists (next_end, f_list_count, def_dec_p))
3357 return 1;
3360 /* Check that the function name in the header we are working on is the same
3361 as the one we would expect to find. If not, issue a warning and return
3362 non-zero. */
3364 if (f_list_count == 0)
3366 const char *expected = def_dec_p->hash_entry->symbol;
3367 const char *func_name_start;
3368 const char *func_name_limit;
3369 size_t func_name_len;
3371 for (func_name_limit = start_formals-1; isspace (*func_name_limit); )
3372 check_source (--func_name_limit > clean_read_ptr, 0);
3374 for (func_name_start = func_name_limit++;
3375 is_id_char (*func_name_start);
3376 func_name_start--)
3377 check_source (func_name_start > clean_read_ptr, 0);
3378 func_name_start++;
3379 func_name_len = func_name_limit - func_name_start;
3380 if (func_name_len == 0)
3381 check_source (0, func_name_start);
3382 if (func_name_len != strlen (expected)
3383 || strncmp (func_name_start, expected, func_name_len))
3385 fprintf (stderr, "%s: %d: warning: found `%s' but expected `%s'\n",
3386 shortpath (NULL, def_dec_p->file->hash_entry->symbol),
3387 identify_lineno (func_name_start),
3388 dupnstr (func_name_start, func_name_len),
3389 expected);
3390 return 1;
3394 output_up_to (start_formals);
3396 #ifdef UNPROTOIZE
3397 if (f_list_count == 0)
3398 output_string (def_dec_p->formal_names);
3399 #else /* !defined (UNPROTOIZE) */
3401 unsigned f_list_depth;
3402 const f_list_chain_item *flci_p = def_dec_p->f_list_chain;
3404 /* At this point, the current value of f_list count says how many
3405 links we have to follow through the f_list_chain to get to the
3406 particular formals list that we need to output next. */
3408 for (f_list_depth = 0; f_list_depth < f_list_count; f_list_depth++)
3409 flci_p = flci_p->chain_next;
3410 output_string (flci_p->formals_list);
3412 #endif /* !defined (UNPROTOIZE) */
3414 clean_read_ptr = end_formals - 1;
3415 return 0;
3418 /* Given a pointer to a byte in the clean text buffer which points to
3419 the beginning of a line that contains a "follower" token for a
3420 function definition header, do whatever is necessary to find the
3421 right closing paren for the rightmost formals list of the function
3422 definition header. */
3424 static const char *
3425 find_rightmost_formals_list (clean_text_p)
3426 const char *clean_text_p;
3428 const char *end_formals;
3430 /* We are editing a function definition. The line number we did a seek
3431 to contains the first token which immediately follows the entire set of
3432 formals lists which are part of this particular function definition
3433 header.
3435 Our job now is to scan leftwards in the clean text looking for the
3436 right-paren which is at the end of the function header's rightmost
3437 formals list.
3439 If we ignore whitespace, this right paren should be the first one we
3440 see which is (ignoring whitespace) immediately followed either by the
3441 open curly-brace beginning the function body or by an alphabetic
3442 character (in the case where the function definition is in old (K&R)
3443 style and there are some declarations of formal parameters). */
3445 /* It is possible that the right paren we are looking for is on the
3446 current line (together with its following token). Just in case that
3447 might be true, we start out here by skipping down to the right end of
3448 the current line before starting our scan. */
3450 for (end_formals = clean_text_p; *end_formals != '\n'; end_formals++)
3451 continue;
3452 end_formals--;
3454 #ifdef UNPROTOIZE
3456 /* Now scan backwards while looking for the right end of the rightmost
3457 formals list associated with this function definition. */
3460 char ch;
3461 const char *l_brace_p;
3463 /* Look leftward and try to find a right-paren. */
3465 while (*end_formals != ')')
3467 if (isspace (*end_formals))
3468 while (isspace (*end_formals))
3469 check_source (--end_formals > clean_read_ptr, 0);
3470 else
3471 check_source (--end_formals > clean_read_ptr, 0);
3474 ch = *(l_brace_p = forward_to_next_token_char (end_formals));
3475 /* Since we are unprotoizing an ANSI-style (prototyped) function
3476 definition, there had better not be anything (except whitespace)
3477 between the end of the ANSI formals list and the beginning of the
3478 function body (i.e. the '{'). */
3480 check_source (ch == '{', l_brace_p);
3483 #else /* !defined (UNPROTOIZE) */
3485 /* Now scan backwards while looking for the right end of the rightmost
3486 formals list associated with this function definition. */
3488 while (1)
3490 char ch;
3491 const char *l_brace_p;
3493 /* Look leftward and try to find a right-paren. */
3495 while (*end_formals != ')')
3497 if (isspace (*end_formals))
3498 while (isspace (*end_formals))
3499 check_source (--end_formals > clean_read_ptr, 0);
3500 else
3501 check_source (--end_formals > clean_read_ptr, 0);
3504 ch = *(l_brace_p = forward_to_next_token_char (end_formals));
3506 /* Since it is possible that we found a right paren before the starting
3507 '{' of the body which IS NOT the one at the end of the real K&R
3508 formals list (say for instance, we found one embedded inside one of
3509 the old K&R formal parameter declarations) we have to check to be
3510 sure that this is in fact the right paren that we were looking for.
3512 The one we were looking for *must* be followed by either a '{' or
3513 by an alphabetic character, while others *cannot* validly be followed
3514 by such characters. */
3516 if ((ch == '{') || isalpha (ch))
3517 break;
3519 /* At this point, we have found a right paren, but we know that it is
3520 not the one we were looking for, so backup one character and keep
3521 looking. */
3523 check_source (--end_formals > clean_read_ptr, 0);
3526 #endif /* !defined (UNPROTOIZE) */
3528 return end_formals;
3531 #ifndef UNPROTOIZE
3533 /* Insert into the output file a totally new declaration for a function
3534 which (up until now) was being called from within the current block
3535 without having been declared at any point such that the declaration
3536 was visible (i.e. in scope) at the point of the call.
3538 We need to add in explicit declarations for all such function calls
3539 in order to get the full benefit of prototype-based function call
3540 parameter type checking. */
3542 static void
3543 add_local_decl (def_dec_p, clean_text_p)
3544 const def_dec_info *def_dec_p;
3545 const char *clean_text_p;
3547 const char *start_of_block;
3548 const char *function_to_edit = def_dec_p->hash_entry->symbol;
3550 /* Don't insert new local explicit declarations unless explicitly requested
3551 to do so. */
3553 if (!local_flag)
3554 return;
3556 /* Setup here to recover from confusing source code detected during this
3557 particular "edit". */
3559 save_pointers ();
3560 if (setjmp (source_confusion_recovery))
3562 restore_pointers ();
3563 fprintf (stderr, "%s: local declaration for function `%s' not inserted\n",
3564 pname, function_to_edit);
3565 return;
3568 /* We have already done a seek to the start of the line which should
3569 contain *the* open curly brace which begins the block in which we need
3570 to insert an explicit function declaration (to replace the implicit one).
3572 Now we scan that line, starting from the left, until we find the
3573 open curly brace we are looking for. Note that there may actually be
3574 multiple open curly braces on the given line, but we will be happy
3575 with the leftmost one no matter what. */
3577 start_of_block = clean_text_p;
3578 while (*start_of_block != '{' && *start_of_block != '\n')
3579 check_source (++start_of_block < clean_text_limit, 0);
3581 /* Note that the line from the original source could possibly
3582 contain *no* open curly braces! This happens if the line contains
3583 a macro call which expands into a chunk of text which includes a
3584 block (and that block's associated open and close curly braces).
3585 In cases like this, we give up, issue a warning, and do nothing. */
3587 if (*start_of_block != '{')
3589 if (!quiet_flag)
3590 fprintf (stderr,
3591 "\n%s: %d: warning: can't add declaration of `%s' into macro call\n",
3592 def_dec_p->file->hash_entry->symbol, def_dec_p->line,
3593 def_dec_p->hash_entry->symbol);
3594 return;
3597 /* Figure out what a nice (pretty) indentation would be for the new
3598 declaration we are adding. In order to do this, we must scan forward
3599 from the '{' until we find the first line which starts with some
3600 non-whitespace characters (i.e. real "token" material). */
3603 const char *ep = forward_to_next_token_char (start_of_block) - 1;
3604 const char *sp;
3606 /* Now we have ep pointing at the rightmost byte of some existing indent
3607 stuff. At least that is the hope.
3609 We can now just scan backwards and find the left end of the existing
3610 indentation string, and then copy it to the output buffer. */
3612 for (sp = ep; isspace (*sp) && *sp != '\n'; sp--)
3613 continue;
3615 /* Now write out the open { which began this block, and any following
3616 trash up to and including the last byte of the existing indent that
3617 we just found. */
3619 output_up_to (ep);
3621 /* Now we go ahead and insert the new declaration at this point.
3623 If the definition of the given function is in the same file that we
3624 are currently editing, and if its full ANSI declaration normally
3625 would start with the keyword `extern', suppress the `extern'. */
3628 const char *decl = def_dec_p->definition->ansi_decl;
3630 if ((*decl == 'e') && (def_dec_p->file == def_dec_p->definition->file))
3631 decl += 7;
3632 output_string (decl);
3635 /* Finally, write out a new indent string, just like the preceding one
3636 that we found. This will typically include a newline as the first
3637 character of the indent string. */
3639 output_bytes (sp, (size_t) (ep - sp) + 1);
3643 /* Given a pointer to a file_info record, and a pointer to the beginning
3644 of a line (in the clean text buffer) which is assumed to contain the
3645 first "follower" token for the first function definition header in the
3646 given file, find a good place to insert some new global function
3647 declarations (which will replace scattered and imprecise implicit ones)
3648 and then insert the new explicit declaration at that point in the file. */
3650 static void
3651 add_global_decls (file_p, clean_text_p)
3652 const file_info *file_p;
3653 const char *clean_text_p;
3655 const def_dec_info *dd_p;
3656 const char *scan_p;
3658 /* Setup here to recover from confusing source code detected during this
3659 particular "edit". */
3661 save_pointers ();
3662 if (setjmp (source_confusion_recovery))
3664 restore_pointers ();
3665 fprintf (stderr, "%s: global declarations for file `%s' not inserted\n",
3666 pname, shortpath (NULL, file_p->hash_entry->symbol));
3667 return;
3670 /* Start by finding a good location for adding the new explicit function
3671 declarations. To do this, we scan backwards, ignoring whitespace
3672 and comments and other junk until we find either a semicolon, or until
3673 we hit the beginning of the file. */
3675 scan_p = find_rightmost_formals_list (clean_text_p);
3676 for (;; --scan_p)
3678 if (scan_p < clean_text_base)
3679 break;
3680 check_source (scan_p > clean_read_ptr, 0);
3681 if (*scan_p == ';')
3682 break;
3685 /* scan_p now points either to a semicolon, or to just before the start
3686 of the whole file. */
3688 /* Now scan forward for the first non-whitespace character. In theory,
3689 this should be the first character of the following function definition
3690 header. We will put in the added declarations just prior to that. */
3692 scan_p++;
3693 while (isspace (*scan_p))
3694 scan_p++;
3695 scan_p--;
3697 output_up_to (scan_p);
3699 /* Now write out full prototypes for all of the things that had been
3700 implicitly declared in this file (but only those for which we were
3701 actually able to find unique matching definitions). Avoid duplicates
3702 by marking things that we write out as we go. */
3705 int some_decls_added = 0;
3707 for (dd_p = file_p->defs_decs; dd_p; dd_p = dd_p->next_in_file)
3708 if (dd_p->is_implicit && dd_p->definition && !dd_p->definition->written)
3710 const char *decl = dd_p->definition->ansi_decl;
3712 /* If the function for which we are inserting a declaration is
3713 actually defined later in the same file, then suppress the
3714 leading `extern' keyword (if there is one). */
3716 if (*decl == 'e' && (dd_p->file == dd_p->definition->file))
3717 decl += 7;
3719 output_string ("\n");
3720 output_string (decl);
3721 some_decls_added = 1;
3722 ((NONCONST def_dec_info *) dd_p->definition)->written = 1;
3724 if (some_decls_added)
3725 output_string ("\n\n");
3728 /* Unmark all of the definitions that we just marked. */
3730 for (dd_p = file_p->defs_decs; dd_p; dd_p = dd_p->next_in_file)
3731 if (dd_p->definition)
3732 ((NONCONST def_dec_info *) dd_p->definition)->written = 0;
3735 #endif /* !defined (UNPROTOIZE) */
3737 /* Do the editing operation specifically for a function "definition". Note
3738 that editing operations for function "declarations" are handled by a
3739 separate routine above. */
3741 static void
3742 edit_fn_definition (def_dec_p, clean_text_p)
3743 const def_dec_info *def_dec_p;
3744 const char *clean_text_p;
3746 const char *end_formals;
3747 const char *function_to_edit = def_dec_p->hash_entry->symbol;
3749 /* Setup here to recover from confusing source code detected during this
3750 particular "edit". */
3752 save_pointers ();
3753 if (setjmp (source_confusion_recovery))
3755 restore_pointers ();
3756 fprintf (stderr, "%s: definition of function `%s' not converted\n",
3757 pname, function_to_edit);
3758 return;
3761 end_formals = find_rightmost_formals_list (clean_text_p);
3763 /* end_of_formals now points to the closing right paren of the rightmost
3764 formals list which is actually part of the `header' of the function
3765 definition that we are converting. */
3767 /* If the header of this function definition looks like it declares a
3768 function with a variable number of arguments, and if the way it does
3769 that is different from that way we would like it (i.e. varargs vs.
3770 stdarg) then issue a warning and leave the header unconverted. */
3772 if (other_variable_style_function (def_dec_p->ansi_decl))
3774 if (!quiet_flag)
3775 fprintf (stderr, "%s: %d: warning: definition of %s not converted\n",
3776 shortpath (NULL, def_dec_p->file->hash_entry->symbol),
3777 identify_lineno (end_formals),
3778 other_var_style);
3779 output_up_to (end_formals);
3780 return;
3783 if (edit_formals_lists (end_formals, def_dec_p->f_list_count, def_dec_p))
3785 restore_pointers ();
3786 fprintf (stderr, "%s: definition of function `%s' not converted\n",
3787 pname, function_to_edit);
3788 return;
3791 /* Have to output the last right paren because this never gets flushed by
3792 edit_formals_list. */
3794 output_up_to (end_formals);
3796 #ifdef UNPROTOIZE
3798 const char *decl_p;
3799 const char *semicolon_p;
3800 const char *limit_p;
3801 const char *scan_p;
3802 int had_newlines = 0;
3804 /* Now write out the K&R style formal declarations, one per line. */
3806 decl_p = def_dec_p->formal_decls;
3807 limit_p = decl_p + strlen (decl_p);
3808 for (;decl_p < limit_p; decl_p = semicolon_p + 2)
3810 for (semicolon_p = decl_p; *semicolon_p != ';'; semicolon_p++)
3811 continue;
3812 output_string ("\n");
3813 output_string (indent_string);
3814 output_bytes (decl_p, (size_t) ((semicolon_p + 1) - decl_p));
3817 /* If there are no newlines between the end of the formals list and the
3818 start of the body, we should insert one now. */
3820 for (scan_p = end_formals+1; *scan_p != '{'; )
3822 if (*scan_p == '\n')
3824 had_newlines = 1;
3825 break;
3827 check_source (++scan_p < clean_text_limit, 0);
3829 if (!had_newlines)
3830 output_string ("\n");
3832 #else /* !defined (UNPROTOIZE) */
3833 /* If we are protoizing, there may be some flotsam & jetsam (like comments
3834 and preprocessing directives) after the old formals list but before
3835 the following { and we would like to preserve that stuff while effectively
3836 deleting the existing K&R formal parameter declarations. We do so here
3837 in a rather tricky way. Basically, we white out any stuff *except*
3838 the comments/pp-directives in the original text buffer, then, if there
3839 is anything in this area *other* than whitespace, we output it. */
3841 const char *end_formals_orig;
3842 const char *start_body;
3843 const char *start_body_orig;
3844 const char *scan;
3845 const char *scan_orig;
3846 int have_flotsam = 0;
3847 int have_newlines = 0;
3849 for (start_body = end_formals + 1; *start_body != '{';)
3850 check_source (++start_body < clean_text_limit, 0);
3852 end_formals_orig = orig_text_base + (end_formals - clean_text_base);
3853 start_body_orig = orig_text_base + (start_body - clean_text_base);
3854 scan = end_formals + 1;
3855 scan_orig = end_formals_orig + 1;
3856 for (; scan < start_body; scan++, scan_orig++)
3858 if (*scan == *scan_orig)
3860 have_newlines |= (*scan_orig == '\n');
3861 /* Leave identical whitespace alone. */
3862 if (!isspace (*scan_orig))
3863 *((NONCONST char *)scan_orig) = ' '; /* identical - so whiteout */
3865 else
3866 have_flotsam = 1;
3868 if (have_flotsam)
3869 output_bytes (end_formals_orig + 1,
3870 (size_t) (start_body_orig - end_formals_orig) - 1);
3871 else
3872 if (have_newlines)
3873 output_string ("\n");
3874 else
3875 output_string (" ");
3876 clean_read_ptr = start_body - 1;
3878 #endif /* !defined (UNPROTOIZE) */
3881 /* Clean up the clean text buffer. Do this by converting comments and
3882 preprocessing directives into spaces. Also convert line continuations
3883 into whitespace. Also, whiteout string and character literals. */
3885 static void
3886 do_cleaning (new_clean_text_base, new_clean_text_limit)
3887 char *new_clean_text_base;
3888 char *new_clean_text_limit;
3890 char *scan_p;
3891 int non_whitespace_since_newline = 0;
3893 for (scan_p = new_clean_text_base; scan_p < new_clean_text_limit; scan_p++)
3895 switch (*scan_p)
3897 case '/': /* Handle comments. */
3898 if (scan_p[1] != '*')
3899 goto regular;
3900 non_whitespace_since_newline = 1;
3901 scan_p[0] = ' ';
3902 scan_p[1] = ' ';
3903 scan_p += 2;
3904 while (scan_p[1] != '/' || scan_p[0] != '*')
3906 if (!isspace (*scan_p))
3907 *scan_p = ' ';
3908 if (++scan_p >= new_clean_text_limit)
3909 abort ();
3911 *scan_p++ = ' ';
3912 *scan_p = ' ';
3913 break;
3915 case '#': /* Handle pp directives. */
3916 if (non_whitespace_since_newline)
3917 goto regular;
3918 *scan_p = ' ';
3919 while (scan_p[1] != '\n' || scan_p[0] == '\\')
3921 if (!isspace (*scan_p))
3922 *scan_p = ' ';
3923 if (++scan_p >= new_clean_text_limit)
3924 abort ();
3926 *scan_p++ = ' ';
3927 break;
3929 case '\'': /* Handle character literals. */
3930 non_whitespace_since_newline = 1;
3931 while (scan_p[1] != '\'' || scan_p[0] == '\\')
3933 if (scan_p[0] == '\\' && !isspace (scan_p[1]))
3934 scan_p[1] = ' ';
3935 if (!isspace (*scan_p))
3936 *scan_p = ' ';
3937 if (++scan_p >= new_clean_text_limit)
3938 abort ();
3940 *scan_p++ = ' ';
3941 break;
3943 case '"': /* Handle string literals. */
3944 non_whitespace_since_newline = 1;
3945 while (scan_p[1] != '"' || scan_p[0] == '\\')
3947 if (scan_p[0] == '\\' && !isspace (scan_p[1]))
3948 scan_p[1] = ' ';
3949 if (!isspace (*scan_p))
3950 *scan_p = ' ';
3951 if (++scan_p >= new_clean_text_limit)
3952 abort ();
3954 if (!isspace (*scan_p))
3955 *scan_p = ' ';
3956 scan_p++;
3957 break;
3959 case '\\': /* Handle line continuations. */
3960 if (scan_p[1] != '\n')
3961 goto regular;
3962 *scan_p = ' ';
3963 break;
3965 case '\n':
3966 non_whitespace_since_newline = 0; /* Reset. */
3967 break;
3969 case ' ':
3970 case '\v':
3971 case '\t':
3972 case '\r':
3973 case '\f':
3974 case '\b':
3975 break; /* Whitespace characters. */
3977 default:
3978 regular:
3979 non_whitespace_since_newline = 1;
3980 break;
3985 /* Given a pointer to the closing right parenthesis for a particular formals
3986 list (in the clean text buffer) find the corresponding left parenthesis
3987 and return a pointer to it. */
3989 static const char *
3990 careful_find_l_paren (p)
3991 const char *p;
3993 const char *q;
3994 int paren_depth;
3996 for (paren_depth = 1, q = p-1; paren_depth; check_source (--q >= clean_text_base, 0))
3998 switch (*q)
4000 case ')':
4001 paren_depth++;
4002 break;
4003 case '(':
4004 paren_depth--;
4005 break;
4008 return ++q;
4011 /* Scan the clean text buffer for cases of function definitions that we
4012 don't really know about because they were preprocessed out when the
4013 aux info files were created.
4015 In this version of protoize/unprotoize we just give a warning for each
4016 one found. A later version may be able to at least unprotoize such
4017 missed items.
4019 Note that we may easily find all function definitions simply by
4020 looking for places where there is a left paren which is (ignoring
4021 whitespace) immediately followed by either a left-brace or by an
4022 upper or lower case letter. Whenever we find this combination, we
4023 have also found a function definition header.
4025 Finding function *declarations* using syntactic clues is much harder.
4026 I will probably try to do this in a later version though. */
4028 static void
4029 scan_for_missed_items (file_p)
4030 const file_info *file_p;
4032 static const char *scan_p;
4033 const char *limit = clean_text_limit - 3;
4034 static const char *backup_limit;
4036 backup_limit = clean_text_base - 1;
4038 for (scan_p = clean_text_base; scan_p < limit; scan_p++)
4040 if (*scan_p == ')')
4042 static const char *last_r_paren;
4043 const char *ahead_p;
4045 last_r_paren = scan_p;
4047 for (ahead_p = scan_p + 1; isspace (*ahead_p); )
4048 check_source (++ahead_p < limit, limit);
4050 scan_p = ahead_p - 1;
4052 if (isalpha (*ahead_p) || *ahead_p == '{')
4054 const char *last_l_paren;
4055 const int lineno = identify_lineno (ahead_p);
4057 if (setjmp (source_confusion_recovery))
4058 continue;
4060 /* We know we have a function definition header. Now skip
4061 leftwards over all of its associated formals lists. */
4065 last_l_paren = careful_find_l_paren (last_r_paren);
4066 for (last_r_paren = last_l_paren-1; isspace (*last_r_paren); )
4067 check_source (--last_r_paren >= backup_limit, backup_limit);
4069 while (*last_r_paren == ')');
4071 if (is_id_char (*last_r_paren))
4073 const char *id_limit = last_r_paren + 1;
4074 const char *id_start;
4075 size_t id_length;
4076 const def_dec_info *dd_p;
4078 for (id_start = id_limit-1; is_id_char (*id_start); )
4079 check_source (--id_start >= backup_limit, backup_limit);
4080 id_start++;
4081 backup_limit = id_start;
4082 if ((id_length = (size_t) (id_limit - id_start)) == 0)
4083 goto not_missed;
4086 char *func_name = (char *) alloca (id_length + 1);
4087 static const char * const stmt_keywords[]
4088 = { "if", "else", "do", "while", "for", "switch", "case", "return", 0 };
4089 const char * const *stmt_keyword;
4091 strncpy (func_name, id_start, id_length);
4092 func_name[id_length] = '\0';
4094 /* We must check here to see if we are actually looking at
4095 a statement rather than an actual function call. */
4097 for (stmt_keyword = stmt_keywords; *stmt_keyword; stmt_keyword++)
4098 if (!strcmp (func_name, *stmt_keyword))
4099 goto not_missed;
4101 #if 0
4102 fprintf (stderr, "%s: found definition of `%s' at %s(%d)\n",
4103 pname,
4104 func_name,
4105 shortpath (NULL, file_p->hash_entry->symbol),
4106 identify_lineno (id_start));
4107 #endif /* 0 */
4108 /* We really should check for a match of the function name
4109 here also, but why bother. */
4111 for (dd_p = file_p->defs_decs; dd_p; dd_p = dd_p->next_in_file)
4112 if (dd_p->is_func_def && dd_p->line == lineno)
4113 goto not_missed;
4115 /* If we make it here, then we did not know about this
4116 function definition. */
4118 fprintf (stderr, "%s: %d: warning: `%s' excluded by preprocessing\n",
4119 shortpath (NULL, file_p->hash_entry->symbol),
4120 identify_lineno (id_start), func_name);
4121 fprintf (stderr, "%s: function definition not converted\n",
4122 pname);
4124 not_missed: ;
4131 /* Do all editing operations for a single source file (either a "base" file
4132 or an "include" file). To do this we read the file into memory, keep a
4133 virgin copy there, make another cleaned in-core copy of the original file
4134 (i.e. one in which all of the comments and preprocessing directives have
4135 been replaced with whitespace), then use these two in-core copies of the
4136 file to make a new edited in-core copy of the file. Finally, rename the
4137 original file (as a way of saving it), and then write the edited version
4138 of the file from core to a disk file of the same name as the original.
4140 Note that the trick of making a copy of the original sans comments &
4141 preprocessing directives make the editing a whole lot easier. */
4143 static void
4144 edit_file (hp)
4145 const hash_table_entry *hp;
4147 struct stat stat_buf;
4148 const file_info *file_p = hp->fip;
4149 char *new_orig_text_base;
4150 char *new_orig_text_limit;
4151 char *new_clean_text_base;
4152 char *new_clean_text_limit;
4153 size_t orig_size;
4154 size_t repl_size;
4155 int first_definition_in_file;
4157 /* If we are not supposed to be converting this file, or if there is
4158 nothing in there which needs converting, just skip this file. */
4160 if (!needs_to_be_converted (file_p))
4161 return;
4163 convert_filename = file_p->hash_entry->symbol;
4165 /* Convert a file if it is in a directory where we want conversion
4166 and the file is not excluded. */
4168 if (!directory_specified_p (convert_filename)
4169 || file_excluded_p (convert_filename))
4171 if (!quiet_flag
4172 #ifdef UNPROTOIZE
4173 /* Don't even mention "system" include files unless we are
4174 protoizing. If we are protoizing, we mention these as a
4175 gentle way of prodding the user to convert his "system"
4176 include files to prototype format. */
4177 && !in_system_include_dir (convert_filename)
4178 #endif /* defined (UNPROTOIZE) */
4180 fprintf (stderr, "%s: `%s' not converted\n",
4181 pname, shortpath (NULL, convert_filename));
4182 return;
4185 /* Let the user know what we are up to. */
4187 if (nochange_flag)
4188 fprintf (stderr, "%s: would convert file `%s'\n",
4189 pname, shortpath (NULL, convert_filename));
4190 else
4191 fprintf (stderr, "%s: converting file `%s'\n",
4192 pname, shortpath (NULL, convert_filename));
4193 fflush (stderr);
4195 /* Find out the size (in bytes) of the original file. */
4197 /* The cast avoids an erroneous warning on AIX. */
4198 if (my_stat ((char *)convert_filename, &stat_buf) == -1)
4200 fprintf (stderr, "%s: can't get status for file `%s': %s\n",
4201 pname, shortpath (NULL, convert_filename), my_strerror(errno));
4202 return;
4204 orig_size = stat_buf.st_size;
4206 /* Allocate a buffer to hold the original text. */
4208 orig_text_base = new_orig_text_base = (char *) xmalloc (orig_size + 2);
4209 orig_text_limit = new_orig_text_limit = new_orig_text_base + orig_size;
4211 /* Allocate a buffer to hold the cleaned-up version of the original text. */
4213 clean_text_base = new_clean_text_base = (char *) xmalloc (orig_size + 2);
4214 clean_text_limit = new_clean_text_limit = new_clean_text_base + orig_size;
4215 clean_read_ptr = clean_text_base - 1;
4217 /* Allocate a buffer that will hopefully be large enough to hold the entire
4218 converted output text. As an initial guess for the maximum size of the
4219 output buffer, use 125% of the size of the original + some extra. This
4220 buffer can be expanded later as needed. */
4222 repl_size = orig_size + (orig_size >> 2) + 4096;
4223 repl_text_base = (char *) xmalloc (repl_size + 2);
4224 repl_text_limit = repl_text_base + repl_size - 1;
4225 repl_write_ptr = repl_text_base - 1;
4228 int input_file;
4230 /* Open the file to be converted in READ ONLY mode. */
4232 if ((input_file = my_open (convert_filename, O_RDONLY, 0444)) == -1)
4234 fprintf (stderr, "%s: can't open file `%s' for reading: %s\n",
4235 pname, shortpath (NULL, convert_filename),
4236 my_strerror(errno));
4237 return;
4240 /* Read the entire original source text file into the original text buffer
4241 in one swell fwoop. Then figure out where the end of the text is and
4242 make sure that it ends with a newline followed by a null. */
4244 if (safe_read (input_file, new_orig_text_base, orig_size) != orig_size)
4246 close (input_file);
4247 fprintf (stderr, "\n%s: error reading input file `%s': %s\n",
4248 pname, shortpath (NULL, convert_filename),
4249 my_strerror(errno));
4250 return;
4253 close (input_file);
4256 if (orig_size == 0 || orig_text_limit[-1] != '\n')
4258 *new_orig_text_limit++ = '\n';
4259 orig_text_limit++;
4262 /* Create the cleaned up copy of the original text. */
4264 memcpy (new_clean_text_base, orig_text_base,
4265 (size_t) (orig_text_limit - orig_text_base));
4266 do_cleaning (new_clean_text_base, new_clean_text_limit);
4268 #if 0
4270 int clean_file;
4271 size_t clean_size = orig_text_limit - orig_text_base;
4272 char *const clean_filename = (char *) alloca (strlen (convert_filename) + 6 + 1);
4274 /* Open (and create) the clean file. */
4276 strcpy (clean_filename, convert_filename);
4277 strcat (clean_filename, ".clean");
4278 if ((clean_file = creat (clean_filename, 0666)) == -1)
4280 fprintf (stderr, "%s: can't create/open clean file `%s': %s\n",
4281 pname, shortpath (NULL, clean_filename),
4282 my_strerror(errno));
4283 return;
4286 /* Write the clean file. */
4288 safe_write (clean_file, new_clean_text_base, clean_size, clean_filename);
4290 close (clean_file);
4292 #endif /* 0 */
4294 /* Do a simplified scan of the input looking for things that were not
4295 mentioned in the aux info files because of the fact that they were
4296 in a region of the source which was preprocessed-out (via #if or
4297 via #ifdef). */
4299 scan_for_missed_items (file_p);
4301 /* Setup to do line-oriented forward seeking in the clean text buffer. */
4303 last_known_line_number = 1;
4304 last_known_line_start = clean_text_base;
4306 /* Now get down to business and make all of the necessary edits. */
4309 const def_dec_info *def_dec_p;
4311 first_definition_in_file = 1;
4312 def_dec_p = file_p->defs_decs;
4313 for (; def_dec_p; def_dec_p = def_dec_p->next_in_file)
4315 const char *clean_text_p = seek_to_line (def_dec_p->line);
4317 /* clean_text_p now points to the first character of the line which
4318 contains the `terminator' for the declaration or definition that
4319 we are about to process. */
4321 #ifndef UNPROTOIZE
4323 if (global_flag && def_dec_p->is_func_def && first_definition_in_file)
4325 add_global_decls (def_dec_p->file, clean_text_p);
4326 first_definition_in_file = 0;
4329 /* Don't edit this item if it is already in prototype format or if it
4330 is a function declaration and we have found no corresponding
4331 definition. */
4333 if (def_dec_p->prototyped
4334 || (!def_dec_p->is_func_def && !def_dec_p->definition))
4335 continue;
4337 #endif /* !defined (UNPROTOIZE) */
4339 if (def_dec_p->is_func_def)
4340 edit_fn_definition (def_dec_p, clean_text_p);
4341 else
4342 #ifndef UNPROTOIZE
4343 if (def_dec_p->is_implicit)
4344 add_local_decl (def_dec_p, clean_text_p);
4345 else
4346 #endif /* !defined (UNPROTOIZE) */
4347 edit_fn_declaration (def_dec_p, clean_text_p);
4351 /* Finalize things. Output the last trailing part of the original text. */
4353 output_up_to (clean_text_limit - 1);
4355 /* If this is just a test run, stop now and just deallocate the buffers. */
4357 if (nochange_flag)
4359 free (new_orig_text_base);
4360 free (new_clean_text_base);
4361 free (repl_text_base);
4362 return;
4365 /* Change the name of the original input file. This is just a quick way of
4366 saving the original file. */
4368 if (!nosave_flag)
4370 char *new_filename
4371 = (char *) xmalloc (strlen (convert_filename) + strlen (save_suffix) + 2);
4373 strcpy (new_filename, convert_filename);
4374 strcat (new_filename, save_suffix);
4375 if (my_link (convert_filename, new_filename) == -1)
4377 if (errno == EEXIST)
4379 if (!quiet_flag)
4380 fprintf (stderr, "%s: warning: file `%s' already saved in `%s'\n",
4381 pname,
4382 shortpath (NULL, convert_filename),
4383 shortpath (NULL, new_filename));
4385 else
4387 fprintf (stderr, "%s: can't link file `%s' to `%s': %s\n",
4388 pname,
4389 shortpath (NULL, convert_filename),
4390 shortpath (NULL, new_filename),
4391 my_strerror(errno));
4392 return;
4397 if (my_unlink (convert_filename) == -1)
4399 fprintf (stderr, "%s: can't delete file `%s': %s\n",
4400 pname, shortpath (NULL, convert_filename), my_strerror(errno));
4401 return;
4405 int output_file;
4407 /* Open (and create) the output file. */
4409 if ((output_file = creat (convert_filename, 0666)) == -1)
4411 fprintf (stderr, "%s: can't create/open output file `%s': %s\n",
4412 pname, shortpath (NULL, convert_filename),
4413 my_strerror(errno));
4414 return;
4417 /* Write the output file. */
4420 unsigned int out_size = (repl_write_ptr + 1) - repl_text_base;
4422 safe_write (output_file, repl_text_base, out_size, convert_filename);
4425 close (output_file);
4428 /* Deallocate the conversion buffers. */
4430 free (new_orig_text_base);
4431 free (new_clean_text_base);
4432 free (repl_text_base);
4434 /* Change the mode of the output file to match the original file. */
4436 /* The cast avoids an erroneous warning on AIX. */
4437 if (my_chmod ((char *)convert_filename, stat_buf.st_mode) == -1)
4438 fprintf (stderr, "%s: can't change mode of file `%s': %s\n",
4439 pname, shortpath (NULL, convert_filename), my_strerror(errno));
4441 /* Note: We would try to change the owner and group of the output file
4442 to match those of the input file here, except that may not be a good
4443 thing to do because it might be misleading. Also, it might not even
4444 be possible to do that (on BSD systems with quotas for instance). */
4447 /* Do all of the individual steps needed to do the protoization (or
4448 unprotoization) of the files referenced in the aux_info files given
4449 in the command line. */
4451 static void
4452 do_processing ()
4454 const char * const *base_pp;
4455 const char * const * const end_pps
4456 = &base_source_filenames[n_base_source_files];
4458 #ifndef UNPROTOIZE
4459 int syscalls_len;
4460 #endif /* !defined (UNPROTOIZE) */
4462 /* One-by-one, check (and create if necessary), open, and read all of the
4463 stuff in each aux_info file. After reading each aux_info file, the
4464 aux_info_file just read will be automatically deleted unless the
4465 keep_flag is set. */
4467 for (base_pp = base_source_filenames; base_pp < end_pps; base_pp++)
4468 process_aux_info_file (*base_pp, keep_flag, 0);
4470 #ifndef UNPROTOIZE
4472 /* Also open and read the special SYSCALLS.c aux_info file which gives us
4473 the prototypes for all of the standard system-supplied functions. */
4475 if (nondefault_syscalls_dir)
4477 syscalls_absolute_filename
4478 = (char *) xmalloc (strlen (nondefault_syscalls_dir)
4479 + sizeof (syscalls_filename) + 1);
4480 strcpy (syscalls_absolute_filename, nondefault_syscalls_dir);
4482 else
4484 syscalls_absolute_filename
4485 = (char *) xmalloc (strlen (default_syscalls_dir)
4486 + sizeof (syscalls_filename) + 1);
4487 strcpy (syscalls_absolute_filename, default_syscalls_dir);
4490 syscalls_len = strlen (syscalls_absolute_filename);
4491 if (*(syscalls_absolute_filename + syscalls_len - 1) != '/')
4493 *(syscalls_absolute_filename + syscalls_len++) = '/';
4494 *(syscalls_absolute_filename + syscalls_len) = '\0';
4496 strcat (syscalls_absolute_filename, syscalls_filename);
4498 /* Call process_aux_info_file in such a way that it does not try to
4499 delete the SYSCALLS aux_info file. */
4501 process_aux_info_file (syscalls_absolute_filename, 1, 1);
4503 #endif /* !defined (UNPROTOIZE) */
4505 /* When we first read in all of the information from the aux_info files
4506 we saved in it descending line number order, because that was likely to
4507 be faster. Now however, we want the chains of def & dec records to
4508 appear in ascending line number order as we get further away from the
4509 file_info record that they hang from. The following line causes all of
4510 these lists to be rearranged into ascending line number order. */
4512 visit_each_hash_node (filename_primary, reverse_def_dec_list);
4514 #ifndef UNPROTOIZE
4516 /* Now do the "real" work. The following line causes each declaration record
4517 to be "visited". For each of these nodes, an attempt is made to match
4518 up the function declaration with a corresponding function definition,
4519 which should have a full prototype-format formals list with it. Once
4520 these match-ups are made, the conversion of the function declarations
4521 to prototype format can be made. */
4523 visit_each_hash_node (function_name_primary, connect_defs_and_decs);
4525 #endif /* !defined (UNPROTOIZE) */
4527 /* Now convert each file that can be converted (and needs to be). */
4529 visit_each_hash_node (filename_primary, edit_file);
4531 #ifndef UNPROTOIZE
4533 /* If we are working in cplusplus mode, try to rename all .c files to .C
4534 files. Don't panic if some of the renames don't work. */
4536 if (cplusplus_flag && !nochange_flag)
4537 visit_each_hash_node (filename_primary, rename_c_file);
4539 #endif /* !defined (UNPROTOIZE) */
4542 static struct option longopts[] =
4544 {"version", 0, 0, 'V'},
4545 {"file_name", 0, 0, 'p'},
4546 {"quiet", 0, 0, 'q'},
4547 {"silent", 0, 0, 'q'},
4548 {"force", 0, 0, 'f'},
4549 {"keep", 0, 0, 'k'},
4550 {"nosave", 0, 0, 'N'},
4551 {"nochange", 0, 0, 'n'},
4552 {"compiler-options", 1, 0, 'c'},
4553 {"exclude", 1, 0, 'x'},
4554 {"directory", 1, 0, 'd'},
4555 #ifdef UNPROTOIZE
4556 {"indent", 1, 0, 'i'},
4557 #else
4558 {"local", 0, 0, 'l'},
4559 {"global", 0, 0, 'g'},
4560 {"c++", 0, 0, 'C'},
4561 {"syscalls-dir", 1, 0, 'B'},
4562 #endif
4563 {0, 0, 0, 0}
4567 main (argc, argv)
4568 int argc;
4569 char **const argv;
4571 int longind;
4572 int c;
4573 const char *params = "";
4575 pname = rindex (argv[0], '/');
4576 pname = pname ? pname+1 : argv[0];
4578 cwd_buffer = getpwd ();
4579 if (!cwd_buffer)
4581 fprintf (stderr, "%s: cannot get working directory: %s\n",
4582 pname, my_strerror(errno));
4583 exit (FATAL_EXIT_CODE);
4586 /* By default, convert the files in the current directory. */
4587 directory_list = string_list_cons (cwd_buffer, NULL);
4589 while ((c = getopt_long (argc, argv,
4590 #ifdef UNPROTOIZE
4591 "c:d:i:knNp:qvVx:",
4592 #else
4593 "B:c:Cd:gklnNp:qvVx:",
4594 #endif
4595 longopts, &longind)) != EOF)
4597 if (c == 0) /* Long option. */
4598 c = longopts[longind].val;
4599 switch (c)
4601 case 'p':
4602 compiler_file_name = optarg;
4603 break;
4604 case 'd':
4605 directory_list
4606 = string_list_cons (abspath (NULL, optarg), directory_list);
4607 break;
4608 case 'x':
4609 exclude_list = string_list_cons (optarg, exclude_list);
4610 break;
4612 case 'v':
4613 case 'V':
4614 version_flag = 1;
4615 break;
4616 case 'q':
4617 quiet_flag = 1;
4618 break;
4619 #if 0
4620 case 'f':
4621 force_flag = 1;
4622 break;
4623 #endif
4624 case 'n':
4625 nochange_flag = 1;
4626 keep_flag = 1;
4627 break;
4628 case 'N':
4629 nosave_flag = 1;
4630 break;
4631 case 'k':
4632 keep_flag = 1;
4633 break;
4634 case 'c':
4635 params = optarg;
4636 break;
4637 #ifdef UNPROTOIZE
4638 case 'i':
4639 indent_string = optarg;
4640 break;
4641 #else /* !defined (UNPROTOIZE) */
4642 case 'l':
4643 local_flag = 1;
4644 break;
4645 case 'g':
4646 global_flag = 1;
4647 break;
4648 case 'C':
4649 cplusplus_flag = 1;
4650 break;
4651 case 'B':
4652 nondefault_syscalls_dir = optarg;
4653 break;
4654 #endif /* !defined (UNPROTOIZE) */
4655 default:
4656 usage ();
4660 /* Set up compile_params based on -p and -c options. */
4661 munge_compile_params (params);
4663 n_base_source_files = argc - optind;
4665 /* Now actually make a list of the base source filenames. */
4667 base_source_filenames
4668 = (const char **) xmalloc ((n_base_source_files + 1) * sizeof (char *));
4669 n_base_source_files = 0;
4670 for (; optind < argc; optind++)
4672 const char *path = abspath (NULL, argv[optind]);
4673 int len = strlen (path);
4675 if (path[len-1] == 'c' && path[len-2] == '.')
4676 base_source_filenames[n_base_source_files++] = path;
4677 else
4679 fprintf (stderr, "%s: input file names must have .c suffixes: %s\n",
4680 pname, shortpath (NULL, path));
4681 errors++;
4685 #ifndef UNPROTOIZE
4686 /* We are only interested in the very first identifier token in the
4687 definition of `va_list', so if there is more junk after that first
4688 identifier token, delete it from the `varargs_style_indicator'. */
4690 const char *cp;
4692 for (cp = varargs_style_indicator; isalnum (*cp) || *cp == '_'; cp++)
4693 continue;
4694 if (*cp != 0)
4695 varargs_style_indicator = savestring (varargs_style_indicator,
4696 cp - varargs_style_indicator);
4698 #endif /* !defined (UNPROTOIZE) */
4700 if (errors)
4701 usage ();
4702 else
4704 if (version_flag)
4705 fprintf (stderr, "%s: %s\n", pname, version_string);
4706 do_processing ();
4709 exit (errors ? FATAL_EXIT_CODE : SUCCESS_EXIT_CODE);
4711 return 1;