OSDN Git Service

* fix-header.c (main): Fix loop over required_functions_list
[pf3gnuchains/gcc-fork.git] / gcc / fix-header.c
1 /* fix-header.c - Make C header file suitable for C++.
2    Copyright (C) 1993, 1994, 1995 Free Software Foundation, Inc.
3
4 This program is free software; you can redistribute it and/or modify it
5 under the terms of the GNU General Public License as published by the
6 Free Software Foundation; either version 2, or (at your option) any
7 later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
17
18 /* This program massages a system include file (such as stdio.h),
19    into a form more conformant with ANSI/POSIX, and more suitable for C++:
20
21    * extern "C" { ... } braces are added (inside #ifndef __cplusplus),
22    if they seem to be needed.  These prevent C++ compilers from name
23    mangling the functions inside the braces.
24
25    * If an old-style incomplete function declaration is seen (without
26    an argument list), and it is a "standard" function listed in
27    the file sys-protos.h (and with a non-empty argument list), then
28    the declaration is converted to a complete prototype by replacing
29    the empty parameter list with the argument lust from sys-protos.h.
30
31    * The program can be given a list of (names of) required standard
32    functions (such as fclose for stdio.h).  If a reqquired function
33    is not seen in the input, then a prototype for it will be
34    written to the output.
35
36    * If all of the non-comment code of the original file is protected
37    against multiple inclusion:
38         #ifndef FOO
39         #define FOO
40         <body of include file>
41         #endif
42    then extra matter added to the include file is placed inside the <body>.
43
44    * If the input file is OK (nothing needs to be done);
45    the output file is not written (nor removed if it exists).
46
47    There are also some special actions that are done for certain
48    well-known standard include files:
49
50    * If argv[1] is "sys/stat.h", the Posix.1 macros
51    S_ISBLK, S_ISCHR, S_ISDIR, S_ISFIFO, S_ISLNK, S_ISREG are added if
52    they were missing, and the corresponding "traditional" S_IFxxx
53    macros were defined.
54
55    * If argv[1] is "errno.h", errno is declared if it was missing.
56
57    * TODO:  The input file should be read complete into memory, because:
58    a) it needs to be scanned twice anyway, and
59    b) it would be nice to allow update in place.
60
61    Usage:
62         fix-header FOO.H INFILE.H OUTFILE.H [OPTIONS]
63    where:
64    * FOO.H is the relative file name of the include file,
65    as it would be #include'd by a C file.  (E.g. stdio.h)
66    * INFILE.H is a full pathname for the input file (e.g. /usr/include/stdio.h)
67    * OUTFILE.H is the full pathname for where to write the output file,
68    if anything needs to be done.  (e.g. ./include/stdio.h)
69    * OPTIONS are such as you would pass to cpp.
70
71    Written by Per Bothner <bothner@cygnus.com>, July 1993. */
72
73 #include <stdio.h>
74 #include <ctype.h>
75 #include <sys/types.h>
76 #include <sys/stat.h>
77 #ifndef O_RDONLY
78 #define O_RDONLY 0
79 #endif
80 #include "hconfig.h"
81 #include "obstack.h"
82 #include "scan.h"
83 #include "cpplib.h"
84
85 #if !__STDC__
86 #define const /* nothing */
87 #endif
88
89 sstring buf;
90
91 int verbose = 0;
92 int partial_count = 0;
93 int warnings = 0;
94
95 /* We no longer need to add extern "C", because cpp implicitly
96    forces the standard include files to be treated as C.  */
97 /*#define ADD_MISSING_EXTERN_C 1 */
98
99 #if ADD_MISSING_EXTERN_C
100 int missing_extern_C_count = 0;
101 #endif
102 int missing_errno = 0;
103
104 #include "xsys-protos.h"
105
106 #ifdef FIXPROTO_IGNORE_LIST
107 /* This is a currently unused feature. */
108
109 /* List of files and directories to ignore.
110    A directory name (ending in '/') means ignore anything in that
111    directory.  (It might be more efficient to do directory pruning
112    earlier in fixproto, but this is simpler and easier to customize.) */
113
114 static char *files_to_ignore[] = {
115   "X11/",
116   FIXPROTO_IGNORE_LIST
117   0
118 };
119 #endif
120
121 char *inf_buffer;
122 char *inf_limit;
123 char *inf_ptr;
124
125 /* Certain standard files get extra treatment */
126
127 enum special_file
128 {
129   no_special,
130   errno_h,
131   stdio_h,
132   sys_stat_h
133 };
134
135 /* A NAMELIST is a sequence of names, separated by '\0', and terminated
136    by an empty name (i.e. by "\0\0"). */
137
138 typedef const char* namelist;
139
140 struct std_include_entry {
141   const char *name;
142   namelist required;
143   namelist extra;
144   int special;
145 };
146
147 /* End of namelist NAMES. */
148
149 namelist
150 namelist_end (names)
151      namelist names;
152 {
153   register namelist ptr;
154   for (ptr = names; ; ptr++)
155     {
156       if (*ptr == '\0')
157         {
158           ptr++;
159           if (*ptr == '\0')
160             return ptr;
161         }
162     }
163 }
164
165 const char NONE[] = "";
166
167 struct std_include_entry *include_entry;
168
169 struct std_include_entry std_include_table [] = {
170   { "ctype.h",
171       "isalnum\0isalpha\0iscntrl\0isdigit\0isgraph\0islower\0\
172 isprint\0ispunct\0isspace\0isupper\0isxdigit\0tolower\0toupper\0", NONE },
173
174   { "dirent.h", "closedir\0opendir\0readdir\0rewinddir\0", NONE},
175
176   { "errno.h", NONE, "errno\0" },
177
178   { "curses.h", "box\0delwin\0endwin\0getcurx\0getcury\0initscr\0\
179 mvcur\0mvwprintw\0mvwscanw\0newwin\0overlay\0overwrite\0\
180 scroll\0subwin\0touchwin\0waddstr\0wclear\0wclrtobot\0wclrtoeol\0\
181 waddch\0wdelch\0wdeleteln\0werase\0wgetch\0wgetstr\0winsch\0winsertln\0\
182 wmove\0wprintw\0wrefresh\0wscanw\0wstandend\0wstandout\0", NONE },
183
184   { "fcntl.h", "creat\0fcntl\0open\0", NONE },
185
186   /* Maybe also "getgrent fgetgrent setgrent endgrent" */
187   { "grp.h", "getgrgid\0getgrnam\0", NONE },
188
189 /*{ "limit.h", ... provided by gcc }, */
190
191   { "locale.h", "localeconv\0setlocale\0", NONE },
192
193   { "math.h", "acos\0asin\0atan\0atan2\0ceil\0cos\0cosh\0exp\0\
194 fabs\0floor\0fmod\0frexp\0ldexp\0log10\0log\0modf\0pow\0sin\0sinh\0sqrt\0\
195 tan\0tanh\0", "HUGE_VAL\0" },
196
197   { "pwd.h", "getpwnam\0getpwuid\0", NONE },
198
199   /* Left out siglongjmp sigsetjmp - these depend on sigjmp_buf. */
200   { "setjmp.h", "longjmp\0setjmp\0", NONE },
201
202   /* Left out signal() - its prototype is too complex for us!
203      Also left out "sigaction sigaddset sigdelset sigemptyset
204      sigfillset sigismember sigpending sigprocmask sigsuspend"
205      because these need sigset_t or struct sigaction.
206      Most systems that provide them will also declare them. */
207   { "signal.h", "kill\0raise\0", NONE },
208
209   { "stdio.h", "clearerr\0fclose\0feof\0ferror\0fflush\0fgetc\0fgetpos\0\
210 fgets\0fopen\0fprintf\0fputc\0fputs\0fread\0freopen\0fscanf\0fseek\0\
211 fsetpos\0ftell\0fwrite\0getc\0getchar\0gets\0pclose\0perror\0popen\0\
212 printf\0putc\0putchar\0puts\0remove\0rename\0rewind\0scanf\0setbuf\0\
213 setvbuf\0sprintf\0sscanf\0vprintf\0vsprintf\0vfprintf\0tmpfile\0\
214 tmpnam\0ungetc\0", NONE },
215 /* Should perhaps also handle NULL, EOF, ... ? */
216
217   /* "div ldiv", - ignored because these depend on div_t, ldiv_t
218      ignore these: "mblen mbstowcs mbstowc wcstombs wctomb"
219      Left out getgroups, because SunOS4 has incompatible BSD and SVR4 versions.
220      Should perhaps also add NULL */
221   { "stdlib.h", "abort\0abs\0atexit\0atof\0atoi\0atol\0bsearch\0calloc\0\
222 exit\0free\0getenv\0labs\0malloc\0putenv\0qsort\0rand\0realloc\0\
223 srand\0strtod\0strtol\0strtoul\0system\0", NONE },
224
225   { "string.h", "memchr\0memcmp\0memcpy\0memmove\0memset\0\
226 strcat\0strchr\0strcmp\0strcoll\0strcpy\0strcspn\0strerror\0\
227 strlen\0strncat\0strncmp\0strncpy\0strpbrk\0strrchr\0strspn\0strstr\0\
228 strtok\0strxfrm\0", NONE },
229 /* Should perhaps also add NULL and size_t */
230
231   { "sys/stat.h", "chmod\0fstat\0mkdir\0mkfifo\0stat\0lstat\0umask\0",
232       "S_ISDIR\0S_ISBLK\0S_ISCHR\0S_ISFIFO\0S_ISREG\0S_ISLNK\0S_IFDIR\0\
233 S_IFBLK\0S_IFCHR\0S_IFIFO\0S_IFREG\0S_IFLNK\0" },
234
235   { "sys/times.h", "times\0", NONE },
236   /* "sys/types.h" add types (not in old g++-include) */
237
238   { "sys/utsname.h", "uname\0", NONE },
239
240   { "sys/wait.h", "wait\0waitpid\0",
241       "WEXITSTATUS\0WIFEXITED\0WIFSIGNALED\0WIFSTOPPED\0WSTOPSIG\0\
242 WTERMSIG\0WNOHANG\0WNOTRACED\0" },
243
244   { "tar.h", NONE, NONE },
245
246   { "termios.h", "cfgetispeed\0cfgetospeed\0cfsetispeed\0cfsetospeed\0tcdrain\0tcflow\0tcflush\0tcgetattr\0tcsendbreak\0tcsetattr\0", NONE },
247
248   { "time.h", "asctime\0clock\0ctime\0difftime\0gmtime\0localtime\0mktime\0strftime\0time\0tzset\0", NONE },
249
250   { "unistd.h", "_exit\0access\0alarm\0chdir\0chown\0close\0ctermid\0cuserid\0\
251 dup\0dup2\0execl\0execle\0execlp\0execv\0execve\0execvp\0fork\0fpathconf\0\
252 getcwd\0getegid\0geteuid\0getgid\0getlogin\0getopt\0getpgrp\0getpid\0\
253 getppid\0getuid\0isatty\0link\0lseek\0pathconf\0pause\0pipe\0read\0rmdir\0\
254 setgid\0setpgid\0setsid\0setuid\0sleep\0sysconf\0tcgetpgrp\0tcsetpgrp\0\
255 ttyname\0unlink\0write\0", NONE },
256
257   { 0, NONE, NONE }
258 };
259
260 enum special_file special_file_handling = no_special;
261
262 /* The following are only used when handling sys/stat.h */
263 /* They are set if the corresponding macro has been seen. */
264 int seen_S_IFBLK = 0, seen_S_ISBLK  = 0;
265 int seen_S_IFCHR = 0, seen_S_ISCHR  = 0;
266 int seen_S_IFDIR = 0, seen_S_ISDIR  = 0;
267 int seen_S_IFIFO = 0, seen_S_ISFIFO = 0;
268 int seen_S_IFLNK = 0, seen_S_ISLNK  = 0;
269 int seen_S_IFREG = 0, seen_S_ISREG  = 0;
270 \f
271 /* Wrapper around free, to avoid prototype clashes. */
272
273 void
274 xfree (ptr)
275      char *ptr;
276 {
277   free (ptr);
278 }
279
280 /* Avoid error if config defines abort as fancy_abort.
281    It's not worth "really" implementing this because ordinary
282    compiler users never run fix-header.  */
283
284 void
285 fancy_abort ()
286 {
287   abort ();
288 }
289 \f
290 #define obstack_chunk_alloc xmalloc
291 #define obstack_chunk_free xfree
292 struct obstack scan_file_obstack;
293
294 /* NOTE:  If you edit this, also edit gen-protos.c !! */
295 struct fn_decl *
296 lookup_std_proto (name, name_length)
297      const char *name;
298      int name_length;
299 {
300   int i = hashf (name, name_length, HASH_SIZE);
301   int i0 = i;
302   for (;;)
303     {
304       struct fn_decl *fn;
305       if (hash_tab[i] == 0)
306         return NULL;
307       fn = &std_protos[hash_tab[i]];
308       if (strlen (fn->fname) == name_length
309           && strncmp (fn->fname, name, name_length) == 0)
310         return fn;
311       i = (i+1) % HASH_SIZE;
312       if (i == i0)
313         abort ();
314     }
315 }
316
317 char *inc_filename;
318 int inc_filename_length;
319 char *progname = "fix-header";
320 FILE *outf;
321 sstring line;
322
323 int lbrac_line, rbrac_line;
324
325 namelist required_functions_list;
326 int required_unseen_count = 0;
327
328 void 
329 write_lbrac ()
330 {
331   
332 #if ADD_MISSING_EXTERN_C
333   if (missing_extern_C_count + required_unseen_count > 0)
334     fprintf (outf, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n");
335 #endif
336
337   if (partial_count)
338     {
339       fprintf (outf, "#ifndef _PARAMS\n");
340       fprintf (outf, "#if defined(__STDC__) || defined(__cplusplus)\n");
341       fprintf (outf, "#define _PARAMS(ARGS) ARGS\n");
342       fprintf (outf, "#else\n");
343       fprintf (outf, "#define _PARAMS(ARGS) ()\n");
344       fprintf (outf, "#endif\n#endif /* _PARAMS */\n");
345     }
346 }
347
348 struct partial_proto
349 {
350   struct partial_proto *next;
351   char *fname;  /* name of function */
352   char *rtype;  /* return type */
353   struct fn_decl *fn;
354   int line_seen;
355 };
356
357 struct partial_proto *partial_proto_list = NULL;
358
359 struct partial_proto required_dummy_proto, seen_dummy_proto;
360 #define REQUIRED(FN) ((FN)->partial == &required_dummy_proto)
361 #define SET_REQUIRED(FN) ((FN)->partial = &required_dummy_proto)
362 #define SET_SEEN(FN) ((FN)->partial = &seen_dummy_proto)
363 #define SEEN(FN) ((FN)->partial == &seen_dummy_proto)
364
365 void
366 recognized_macro (fname)
367      char *fname;
368 {
369   /* The original include file defines fname as a macro. */
370   struct fn_decl *fn = lookup_std_proto (fname, strlen (fname));
371
372   /* Since fname is a macro, don't require a prototype for it. */
373   if (fn)
374     {
375       if (REQUIRED (fn))
376         required_unseen_count--;
377       SET_SEEN (fn);
378     }
379
380   switch (special_file_handling)
381     {
382     case errno_h:
383       if (strcmp (fname, "errno") == 0) missing_errno = 0;
384       break;
385     case sys_stat_h:
386       if (fname[0] == 'S' && fname[1] == '_')
387         {
388           if (strcmp (fname, "S_IFBLK") == 0) seen_S_IFBLK++;
389           else if (strcmp (fname, "S_ISBLK") == 0) seen_S_ISBLK++;
390           else if (strcmp (fname, "S_IFCHR") == 0) seen_S_IFCHR++;
391           else if (strcmp (fname, "S_ISCHR") == 0) seen_S_ISCHR++;
392           else if (strcmp (fname, "S_IFDIR") == 0) seen_S_IFDIR++;
393           else if (strcmp (fname, "S_ISDIR") == 0) seen_S_ISDIR++;
394           else if (strcmp (fname, "S_IFIFO") == 0) seen_S_IFIFO++;
395           else if (strcmp (fname, "S_ISFIFO") == 0) seen_S_ISFIFO++;
396           else if (strcmp (fname, "S_IFLNK") == 0) seen_S_IFLNK++;
397           else if (strcmp (fname, "S_ISLNK") == 0) seen_S_ISLNK++;
398           else if (strcmp (fname, "S_IFREG") == 0) seen_S_IFREG++;
399           else if (strcmp (fname, "S_ISREG") == 0) seen_S_ISREG++;
400         }
401     }
402 }
403
404 void
405 recognized_extern (name, name_length, type, type_length)
406      char *name;
407      char *type;
408      int name_length, type_length;
409 {
410   switch (special_file_handling)
411     {
412     case errno_h:
413       if (strncmp (name, "errno", name_length) == 0) missing_errno = 0;
414       break;
415     }
416 }
417
418 /* Called by scan_decls if it saw a function definition for a function
419    named FNAME, with return type RTYPE, and argument list ARGS,
420    in source file FILE_SEEN on line LINE_SEEN.
421    KIND is 'I' for an inline function;
422    'F' if a normal function declaration preceded by 'extern "C"'
423    (or nested inside 'extern "C"' braces); or
424    'f' for other function declarations. */
425
426 void
427 recognized_function (fname, fname_length,
428                      kind, rtype, rtype_length,
429                      have_arg_list, file_seen, line_seen)
430      char *fname;
431      int fname_length;
432      int kind; /* One of 'f' 'F' or 'I' */
433      char *rtype;
434      int rtype_length;
435      int have_arg_list;
436      char *file_seen;
437      int line_seen;
438 {
439   struct partial_proto *partial;
440   int i;
441   struct fn_decl *fn;
442 #if ADD_MISSING_EXTERN_C
443   if (kind == 'f')
444     missing_extern_C_count++;
445 #endif
446
447   fn = lookup_std_proto (fname, fname_length);
448
449   /* Remove the function from the list of required function. */
450   if (fn)
451     {
452       if (REQUIRED (fn))
453         required_unseen_count--;
454       SET_SEEN (fn);
455     }
456
457   /* If we have a full prototype, we're done. */
458   if (have_arg_list)
459     return;
460       
461   if (kind == 'I')  /* don't edit inline function */
462     return;
463
464   /* If the partial prototype was included from some other file,
465      we don't need to patch it up (in this run). */
466   i = strlen (file_seen);
467   if (i < inc_filename_length
468       || strcmp (inc_filename, file_seen + (i - inc_filename_length)) != 0)
469     return;
470
471   if (fn == NULL)
472     return;
473   if (fn->params[0] == '\0' || strcmp (fn->params, "void") == 0)
474     return;
475
476   /* We only have a partial function declaration,
477      so remember that we have to add a complete prototype. */
478   partial_count++;
479   partial = (struct partial_proto*)
480     obstack_alloc (&scan_file_obstack, sizeof (struct partial_proto));
481   partial->fname = obstack_alloc (&scan_file_obstack, fname_length + 1);
482   bcopy (fname, partial->fname, fname_length);
483   partial->fname[fname_length] = 0;
484   partial->rtype = obstack_alloc (&scan_file_obstack, rtype_length + 1);
485   sprintf (partial->rtype, "%.*s", rtype_length, rtype);
486   partial->line_seen = line_seen;
487   partial->fn = fn;
488   fn->partial = partial;
489   partial->next = partial_proto_list;
490   partial_proto_list = partial;
491   if (verbose)
492     {
493       fprintf (stderr, "(%s: %s non-prototype function declaration.)\n",
494                inc_filename, partial->fname);
495     }
496 }
497
498 /* For any name in NAMES that is defined as a macro,
499    call recognized_macro on it. */
500
501 void
502 check_macro_names (pfile, names)
503      struct parse_file *pfile;
504      namelist names;
505 {
506   while (*names)
507     {
508       if (cpp_lookup (pfile, names, -1, -1))
509         recognized_macro (names);
510       names += strlen (names) + 1;
511     }
512 }
513
514 void
515 read_scan_file (in_fname, argc, argv)
516      char *in_fname;
517      int argc;
518      char **argv;
519 {
520   cpp_reader scan_in;
521   cpp_options scan_options;
522   struct fn_decl *fn;
523   int i;
524
525   obstack_init (&scan_file_obstack); 
526
527   init_parse_file (&scan_in);
528   scan_in.data = &scan_options;
529   init_parse_options (&scan_options);
530   i = cpp_handle_options (&scan_in, argc, argv);
531   if (i < argc)
532     fatal ("Invalid option `%s'", argv[i]);
533   push_parse_file (&scan_in, in_fname);
534   CPP_OPTIONS (&scan_in)->no_line_commands = 1;
535
536   scan_decls (&scan_in, argc, argv);
537   check_macro_names (&scan_in, include_entry->required);
538   check_macro_names (&scan_in, include_entry->extra);
539
540   if (verbose && (scan_in.errors + warnings) > 0)
541     fprintf (stderr, "(%s: %d errors and %d warnings from cpp)\n",
542              inc_filename, scan_in.errors, warnings);
543   if (scan_in.errors)
544     exit (0);
545
546   /* Traditionally, getc and putc are defined in terms of _filbuf and _flsbuf.
547      If so, those functions are also required. */
548   if (special_file_handling == stdio_h
549       && (fn = lookup_std_proto ("_filbuf", 7)) != NULL)
550     {
551       static char getchar_call[] = "getchar();";
552       cpp_buffer *buf =
553         cpp_push_buffer (&scan_in, getchar_call, sizeof(getchar_call) - 1);
554       int old_written = CPP_WRITTEN (&scan_in);
555       int seen_filbuf = 0;
556
557       /* Scan the macro expansion of "getchar();". */
558       for (;;)
559         {
560           enum cpp_token token = cpp_get_token (&scan_in);
561           int length = CPP_WRITTEN (&scan_in) - old_written;
562           CPP_SET_WRITTEN (&scan_in, old_written);
563           if (token == CPP_EOF) /* Should not happen ... */
564             break;
565           if (token == CPP_POP && CPP_BUFFER (&scan_in) == buf)
566             {
567               cpp_pop_buffer (&scan_in);
568               break;
569             }
570           if (token == CPP_NAME && length == 7
571               && strcmp ("_filbuf", scan_in.token_buffer + old_written) == 0)
572             seen_filbuf++;
573         }
574       if (seen_filbuf)
575         {
576           int need_filbuf = !SEEN (fn) && !REQUIRED (fn);
577           struct fn_decl *flsbuf_fn = lookup_std_proto ("_flsbuf", 7);
578           int need_flsbuf
579             = flsbuf_fn && !SEEN (flsbuf_fn) && !REQUIRED (flsbuf_fn);
580
581           /* Append "_filbuf" and/or "_flsbuf" to end of
582              required_functions_list. */
583           if (need_filbuf + need_flsbuf)
584             {
585               int old_len = namelist_end (required_functions_list)
586                 - required_functions_list;
587               char *new_list = (char*) xmalloc (old_len + 20);
588               bcopy (required_functions_list, new_list, old_len);
589               if (need_filbuf)
590                 {
591                   strcpy (new_list + old_len, "_filbuf");
592                   old_len += 8;
593                   SET_REQUIRED (fn);
594                 }
595               if (need_flsbuf)
596                 {
597                   strcpy (new_list + old_len, "_flsbuf");
598                   old_len += 8;
599                   SET_REQUIRED (flsbuf_fn);
600                 }
601               new_list[old_len] = '\0';
602               required_functions_list = (namelist)new_list;
603               required_unseen_count += need_filbuf + need_flsbuf;
604             }
605         }
606     }
607
608   if (required_unseen_count + partial_count + missing_errno
609 #if ADD_MISSING_EXTERN_C
610       + missing_extern_C_count
611 #endif      
612       == 0)
613     {
614       if (verbose)
615         fprintf (stderr, "%s: OK, nothing needs to be done.\n", inc_filename);
616       exit (0);
617     }
618   if (!verbose)
619     fprintf (stderr, "%s: fixing %s\n", progname, inc_filename);
620   else
621     {
622       if (required_unseen_count)
623         fprintf (stderr, "%s: %d missing function declarations.\n",
624                  inc_filename, required_unseen_count);
625       if (partial_count)
626         fprintf (stderr, "%s: %d non-prototype function declarations.\n",
627                  inc_filename, partial_count);
628 #if ADD_MISSING_EXTERN_C
629       if (missing_extern_C_count)
630         fprintf (stderr,
631                  "%s: %d declarations not protected by extern \"C\".\n",
632                  inc_filename, missing_extern_C_count);
633 #endif
634     }
635 }
636
637 void
638 write_rbrac ()
639 {
640   struct fn_decl *fn;
641   const char *cptr;
642
643   if (required_unseen_count)
644     {
645       fprintf (outf,
646         "#if defined(__cplusplus) || defined(__USE_FIXED_PROTOTYPES__)\n");
647 #ifdef NO_IMPLICIT_EXTERN_C
648       fprintf (outf, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n");
649 #endif
650     }
651
652   /* Now we print out prototypes for those functions that we haven't seen. */
653   for (cptr = required_functions_list; *cptr!= '\0'; )
654     {
655       int macro_protect = 0;
656       int name_len = strlen (cptr);
657
658       fn = lookup_std_proto (cptr, name_len);
659       cptr+= name_len + 1;
660       if (fn == NULL || !REQUIRED (fn))
661         continue;
662
663       /* In the case of memmove, protect in case the application
664          defines it as a macro before including the header.  */
665       if (!strcmp (fn->fname, "memmove")
666           || !strcmp (fn->fname, "vprintf")
667           || !strcmp (fn->fname, "vfprintf")
668           || !strcmp (fn->fname, "vsprintf")
669           || !strcmp (fn->fname, "rewinddir"))
670         macro_protect = 1;
671
672       if (macro_protect)
673         fprintf (outf, "#ifndef %s\n", fn->fname);
674       fprintf (outf, "extern %s %s (%s);\n",
675                fn->rtype, fn->fname, fn->params);
676       if (macro_protect)
677         fprintf (outf, "#endif\n");
678     }
679   if (required_unseen_count)
680     {
681 #ifdef NO_IMPLICIT_EXTERN_C
682       fprintf (outf, "#ifdef __cplusplus\n}\n#endif\n");
683 #endif
684       fprintf (outf,
685         "#endif /* defined(__cplusplus) || defined(__USE_FIXED_PROTOTYPES__*/\n");
686     }
687
688   switch (special_file_handling)
689     {
690     case errno_h:
691       if (missing_errno)
692         fprintf (outf, "extern int errno;\n");
693       break;
694     case sys_stat_h:
695       if (!seen_S_ISBLK && seen_S_IFBLK)
696         fprintf (outf,
697                  "#define S_ISBLK(mode) (((mode) & S_IFMT) == S_IFBLK)\n");
698       if (!seen_S_ISCHR && seen_S_IFCHR)
699         fprintf (outf,
700                  "#define S_ISCHR(mode) (((mode) & S_IFMT) == S_IFCHR)\n");
701       if (!seen_S_ISDIR && seen_S_IFDIR)
702         fprintf (outf,
703                  "#define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)\n");
704       if (!seen_S_ISFIFO && seen_S_IFIFO)
705         fprintf (outf,
706                  "#define S_ISFIFO(mode) (((mode) & S_IFMT) == S_IFIFO)\n");
707       if (!seen_S_ISLNK && seen_S_IFLNK)
708         fprintf (outf,
709                  "#define S_ISLNK(mode) (((mode) & S_IFMT) == S_IFLNK)\n");
710       if (!seen_S_ISREG && seen_S_IFREG)
711         fprintf (outf,
712                  "#define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)\n");
713       break;
714     }
715
716
717 #if ADD_MISSING_EXTERN_C
718   if (missing_extern_C_count + required_unseen_count > 0)
719     fprintf (outf, "#ifdef __cplusplus\n}\n#endif\n");
720 #endif
721 }
722
723 char *
724 xstrdup (str)
725      char *str;
726 {
727   char *copy = (char *) xmalloc (strlen (str) + 1);
728   strcpy (copy, str);
729   return copy;
730 }
731
732 /* Returns 1 iff the file is properly protected from multiple inclusion:
733    #ifndef PROTECT_NAME
734    #define PROTECT_NAME
735    #endif
736
737  */
738
739 #define INF_GET() (inf_ptr < inf_limit ? *(unsigned char*)inf_ptr++ : EOF)
740 #define INF_UNGET(c) ((c)!=EOF && inf_ptr--)
741
742 int
743 inf_skip_spaces (c)
744      int c;
745 {
746   for (;;)
747     {
748       if (c == ' ' || c == '\t')
749         c = INF_GET ();
750       else if (c == '/')
751         {
752           c = INF_GET ();
753           if (c != '*')
754             {
755               INF_UNGET (c);
756               return '/';
757             }
758           c = INF_GET ();
759           for (;;)
760             {
761               if (c == EOF)
762                 return EOF;
763               else if (c != '*')
764                 {
765                   if (c == '\n')
766                     source_lineno++, lineno++;
767                   c = INF_GET ();
768                 }
769               else if ((c = INF_GET ()) == '/')
770                 return INF_GET ();
771             }
772         }
773       else
774         break;
775     }
776   return c;
777 }
778
779 /* Read into STR from inf_buffer upto DELIM. */
780
781 int
782 inf_read_upto (str, delim)
783      sstring *str;
784      int delim;
785 {
786   int ch;
787   for (;;)
788     {
789       ch = INF_GET ();
790       if (ch == EOF || ch == delim)
791         break;
792       SSTRING_PUT (str, ch);
793     }
794   MAKE_SSTRING_SPACE (str, 1);
795   *str->ptr = 0;
796   return ch;
797 }
798
799 int
800 inf_scan_ident (s, c)
801      register sstring *s;
802      int c;
803 {
804   s->ptr = s->base;
805   if (isalpha (c) || c == '_')
806     {
807       for (;;)
808         {
809           SSTRING_PUT (s, c);
810           c = INF_GET ();
811           if (c == EOF || !(isalnum (c) || c == '_'))
812             break;
813         }
814     }
815   MAKE_SSTRING_SPACE (s, 1);
816   *s->ptr = 0;
817   return c;
818 }
819
820 /* Returns 1 if the file is correctly protected against multiple
821    inclusion, setting *ifndef_line to the line number of the initial #ifndef
822    and setting *endif_line to the final #endif.
823    Otherwise return 0. */
824
825 int
826 check_protection (ifndef_line, endif_line)
827      int *ifndef_line, *endif_line;
828 {
829   int c;
830   int if_nesting = 1; /* Level of nesting of #if's */
831   char *protect_name = NULL; /* Identifier following initial #ifndef */
832   int define_seen = 0;
833
834   /* Skip initial white space (including comments). */
835   for (;; lineno++)
836     {
837       c = inf_skip_spaces (' ');
838       if (c == EOF)
839         return 0;
840       if (c != '\n')
841         break;
842     }
843   if (c != '#')
844     return 0;
845   c = inf_scan_ident (&buf, inf_skip_spaces (' '));
846   if (SSTRING_LENGTH (&buf) == 0 || strcmp (buf.base, "ifndef") != 0)
847     return 0;
848
849   /* So far so good: We've seen an initial #ifndef. */
850   *ifndef_line = lineno;
851   c = inf_scan_ident (&buf, inf_skip_spaces (c));
852   if (SSTRING_LENGTH (&buf) == 0 || c == EOF)
853     return 0;
854   protect_name = xstrdup (buf.base);
855
856   INF_UNGET (c);
857   c = inf_read_upto (&buf, '\n');
858   if (c == EOF)
859     return 0;
860   lineno++;
861
862   for (;;)
863     {
864       c = inf_skip_spaces (' ');
865       if (c == EOF)
866         return 0;
867       if (c == '\n')
868         {
869           lineno++;
870           continue;
871         }
872       if (c != '#')
873         goto skip_to_eol;
874       c = inf_scan_ident (&buf, inf_skip_spaces (' '));
875       if (SSTRING_LENGTH (&buf) == 0)
876         ;
877       else if (!strcmp (buf.base, "ifndef")
878           || !strcmp (buf.base, "ifdef") || !strcmp (buf.base, "if"))
879         {
880           if_nesting++;
881         }
882       else if (!strcmp (buf.base, "endif"))
883         {
884           if_nesting--;
885           if (if_nesting == 0)
886             break;
887         }
888       else if (!strcmp (buf.base, "else"))
889         {
890           if (if_nesting == 1)
891             return 0;
892         }
893       else if (!strcmp (buf.base, "define"))
894         {
895           if (if_nesting != 1)
896             goto skip_to_eol;
897           c = inf_skip_spaces (c);
898           c = inf_scan_ident (&buf, c);
899           if (buf.base[0] > 0 && strcmp (buf.base, protect_name) == 0)
900             define_seen = 1;
901         }
902     skip_to_eol:
903       for (;;)
904         {
905           if (c == '\n' || c == EOF)
906             break;
907           c = INF_GET ();
908         }
909       if (c == EOF)
910         return 0;
911       lineno++;
912     }
913
914   if (!define_seen)
915      return 0;
916   *endif_line = lineno;
917   /* Skip final white space (including comments). */
918   for (;;)
919     {
920       c = inf_skip_spaces (' ');
921       if (c == EOF)
922         break;
923       if (c != '\n')
924         return 0;
925     }
926
927   return 1;
928 }
929
930 int
931 main (argc, argv)
932      int argc;
933      char **argv;
934 {
935   int inf_fd;
936   struct stat sbuf;
937   int c;
938   int i, done;
939   const char *cptr, **pptr;
940   int ifndef_line;
941   int endif_line;
942   long to_read;
943   long int inf_size;
944
945   if (argv[0] && argv[0][0])
946     {
947       register char *p;
948
949       progname = 0;
950       for (p = argv[0]; *p; p++)
951         if (*p == '/')
952           progname = p;
953       progname = progname ? progname+1 : argv[0];
954     }
955
956   if (argc < 4)
957     {
958       fprintf (stderr, "%s: Usage: foo.h infile.h outfile.h options\n",
959                progname);
960       exit (-1);
961     }
962
963   inc_filename = argv[1];
964   inc_filename_length = strlen (inc_filename);
965
966 #ifdef FIXPROTO_IGNORE_LIST
967   for (i = 0; files_to_ignore[i] != NULL; i++)
968     {
969       char *ignore_name = files_to_ignore[i];
970       int ignore_len = strlen (ignore_name);
971       if (strncmp (inc_filename, ignore_name, ignore_len) == 0)
972         {
973           if (ignore_name[ignore_len-1] == '/'
974               || inc_filename[ignore_len] == '\0')
975             {
976               if (verbose)
977                 fprintf (stderr, "%s: ignoring %s\n", progname, inc_filename);
978               exit (0);
979             }
980         }
981           
982     }
983 #endif
984
985   if (strcmp (inc_filename, "sys/stat.h") == 0)
986     special_file_handling = sys_stat_h;
987   else if (strcmp (inc_filename, "errno.h") == 0)
988     special_file_handling = errno_h, missing_errno = 1;
989   else if (strcmp (inc_filename, "stdio.h") == 0)
990     special_file_handling = stdio_h;
991   include_entry = std_include_table;
992   while (include_entry->name != NULL
993          && strcmp (inc_filename, include_entry->name) != 0)
994     include_entry++;
995
996   required_functions_list = include_entry->required;
997
998   /* Count and mark the prototypes required for this include file. */ 
999   for (cptr = required_functions_list; *cptr!= '\0'; )
1000     {
1001       int name_len = strlen (cptr);
1002       struct fn_decl *fn = lookup_std_proto (cptr, name_len);
1003       required_unseen_count++;
1004       if (fn == NULL)
1005         fprintf (stderr, "Internal error:  No prototype for %s\n", cptr);
1006       else
1007         SET_REQUIRED (fn);
1008       cptr += name_len + 1;
1009     }
1010
1011   read_scan_file (argv[2], argc - 4, argv + 4);
1012
1013   inf_fd = open (argv[2], O_RDONLY, 0666);
1014   if (inf_fd < 0)
1015     {
1016       fprintf (stderr, "%s: Cannot open '%s' for reading -",
1017                progname, argv[2]);
1018       perror (NULL);
1019       exit (-1);
1020     }
1021   if (fstat (inf_fd, &sbuf) < 0)
1022     {
1023       fprintf (stderr, "%s: Cannot get size of '%s' -", progname, argv[2]);
1024       perror (NULL);
1025       exit (-1);
1026     }
1027   inf_size = sbuf.st_size;
1028   inf_buffer = (char*) xmalloc (inf_size + 2);
1029   inf_buffer[inf_size] = '\n';
1030   inf_buffer[inf_size + 1] = '\0';
1031   inf_limit = inf_buffer + inf_size;
1032   inf_ptr = inf_buffer;
1033
1034   to_read = inf_size;
1035   while (to_read > 0)
1036     {
1037       long i = read (inf_fd, inf_buffer + inf_size - to_read, to_read);
1038       if (i < 0)
1039         {
1040           fprintf (stderr, "%s: Failed to read '%s' -", progname, argv[2]);
1041           perror (NULL);
1042           exit (-1);
1043         }
1044       if (i == 0)
1045         {
1046           inf_size -= to_read;
1047           break;
1048         }
1049       to_read -= i;
1050     }
1051
1052   close (inf_fd);
1053
1054   /* If file doesn't end with '\n', add one. */
1055   if (inf_limit > inf_buffer && inf_limit[-1] != '\n')
1056     inf_limit++;
1057
1058   unlink (argv[3]);
1059   outf = fopen (argv[3], "w");
1060   if (outf == NULL)
1061     {
1062       fprintf (stderr, "%s: Cannot open '%s' for writing -",
1063                progname, argv[3]);
1064       perror (NULL);
1065       exit (-1);
1066     }
1067
1068   lineno = 1;
1069
1070   if (check_protection (&ifndef_line, &endif_line))
1071     {
1072       lbrac_line = ifndef_line+1;
1073       rbrac_line = endif_line;
1074     }
1075   else
1076     {
1077       lbrac_line = 1;
1078       rbrac_line = -1;
1079     }
1080
1081   /* Reset input file. */
1082   inf_ptr = inf_buffer;
1083   lineno = 1;
1084
1085   for (;;)
1086     {
1087       if (lineno == lbrac_line)
1088         write_lbrac ();
1089       if (lineno == rbrac_line)
1090         write_rbrac ();
1091       for (;;)
1092         {
1093           struct fn_decl *fn;
1094           c = INF_GET ();
1095           if (c == EOF)
1096             break;
1097           if (isalpha (c) || c == '_')
1098             {
1099               c = inf_scan_ident (&buf, c);
1100               INF_UNGET (c);
1101               fputs (buf.base, outf);
1102               fn = lookup_std_proto (buf.base, strlen (buf.base));
1103               /* We only want to edit the declaration matching the one
1104                  seen by scan-decls, as there can be multiple
1105                  declarations, selected by #ifdef __STDC__ or whatever. */
1106               if (fn && fn->partial && fn->partial->line_seen == lineno)
1107                 {
1108                   c = inf_skip_spaces (' ');
1109                   if (c == EOF)
1110                     break;
1111                   if (c == '(')
1112                     {
1113                       c = inf_skip_spaces (' ');
1114                       if (c == ')')
1115                         {
1116                           fprintf (outf, " _PARAMS((%s))", fn->params);
1117                         }
1118                       else
1119                         {
1120                           putc ('(', outf);
1121                           INF_UNGET (c);
1122                         }
1123                     }
1124                   else
1125                     fprintf (outf, " %c", c);
1126                 }
1127             }
1128           else
1129             {
1130               putc (c, outf);
1131               if (c == '\n')
1132                 break;
1133             }
1134         }
1135       if (c == EOF)
1136         break;
1137       lineno++;
1138     }
1139   if (rbrac_line < 0)
1140     write_rbrac ();
1141
1142   fclose (outf);
1143
1144   return 0;
1145 }
1146 \f
1147 /* Stub error functions.  These replace cpperror.c,
1148    because we want to suppress error messages. */
1149
1150 void
1151 cpp_file_line_for_message (pfile, filename, line, column)
1152      cpp_reader *pfile;
1153      char *filename;
1154      int line, column;
1155 {
1156   if (!verbose)
1157     return;
1158   if (column > 0)
1159     fprintf (stderr, "%s:%d:%d: ", filename, line, column);
1160   else
1161     fprintf (stderr, "%s:%d: ", filename, line);
1162 }
1163
1164 void
1165 cpp_print_containing_files (pfile)
1166      cpp_reader *pfile;
1167 {
1168 }
1169
1170 /* IS_ERROR is 1 for error, 0 for warning */
1171 void cpp_message (pfile, is_error, msg, arg1, arg2, arg3)
1172      int is_error;
1173      cpp_reader *pfile;
1174      char *msg;
1175      char *arg1, *arg2, *arg3;
1176 {
1177   if (is_error)
1178     pfile->errors++;
1179   if (!verbose)
1180     return;
1181   if (!is_error)
1182     fprintf (stderr, "warning: ");
1183   fprintf (stderr, msg, arg1, arg2, arg3);
1184   fprintf (stderr, "\n");
1185 }
1186
1187 void
1188 fatal (str, arg)
1189      char *str, *arg;
1190 {
1191   fprintf (stderr, "%s: %s: ", progname, inc_filename);
1192   fprintf (stderr, str, arg);
1193   fprintf (stderr, "\n");
1194   exit (FAILURE_EXIT_CODE);
1195 }
1196
1197 void
1198 cpp_pfatal_with_name (pfile, name)
1199      cpp_reader *pfile;
1200      char *name;
1201 {
1202   cpp_perror_with_name (pfile, name);
1203   exit (FAILURE_EXIT_CODE);
1204 }