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