OSDN Git Service

e1fd36b78739010f1134f0c8d61ac91b5de527e8
[pf3gnuchains/gcc-fork.git] / gcc / fixinc / fixfixes.c
1
2 /*
3
4    Test to see if a particular fix should be applied to a header file.
5
6    Copyright (C) 1997, 1998, 1999, 2000 Free Software Foundation, Inc.
7
8 = = = = = = = = = = = = = = = = = = = = = = = = =
9
10 NOTE TO DEVELOPERS
11
12 The routines you write here must work closely with fixincl.c.
13
14 Here are the rules:
15
16 1.  Every test procedure name must be suffixed with "_fix".
17     These routines will be referenced from inclhack.def, sans the suffix.
18
19 2.  Use the "FIX_PROC_HEAD()" macro _with_ the "_fix" suffix
20     (I cannot use the ## magic from ANSI C) for defining your entry point.
21
22 3.  Put your test name into the FIXUP_TABLE.
23
24 4.  Do not read anything from stdin.  It is closed.
25
26 5.  Write to stderr only in the event of a reportable error
27     In such an event, call "exit (EXIT_FAILURE)".
28
29 6.  You have access to the fixDescList entry for the fix in question.
30     This may be useful, for example, if there are interesting strings
31     or pre-compiled regular expressions stored there.
32
33     It is also possible to access fix descriptions by using the
34     index of a known fix, "my_fix_name" for example:
35
36         tFixDesc*  p_desc  = fixDescList + MY_FIX_NAME_FIXIDX;
37         tTestDesc* p_tlist = p_desc->p_test_desc;
38
39         regexec (p_tlist->p_test_regex, ...)
40
41 = = = = = = = = = = = = = = = = = = = = = = = = =
42
43 This file is part of GNU CC.
44
45 GNU CC is free software; you can redistribute it and/or modify
46 it under the terms of the GNU General Public License as published by
47 the Free Software Foundation; either version 2, or (at your option)
48 any later version.
49
50 GNU CC is distributed in the hope that it will be useful,
51 but WITHOUT ANY WARRANTY; without even the implied warranty of
52 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
53 GNU General Public License for more details.
54
55 You should have received a copy of the GNU General Public License
56 along with GNU CC; see the file COPYING.  If not, write to
57 the Free Software Foundation, 59 Temple Place - Suite 330,
58 Boston, MA 02111-1307, USA.  */
59
60 #include "fixlib.h"
61 #define    GTYPE_SE_CT 1
62
63 #ifdef __MSDOS__
64 #include "fixincl.x"
65 #endif
66
67 tSCC zNeedsArg[] = "fixincl error:  `%s' needs %s argument (c_fix_arg[%d])\n";
68
69 typedef void t_fix_proc PARAMS ((const char *, const char *, tFixDesc *));
70 typedef struct {
71     const char*  fix_name;
72     t_fix_proc*  fix_proc;
73 } fix_entry_t;
74
75 #define FIXUP_TABLE \
76   _FT_( "char_macro_def",   char_macro_def_fix ) \
77   _FT_( "char_macro_use",   char_macro_use_fix ) \
78   _FT_( "format",           format_fix )         \
79   _FT_( "machine_name",     machine_name_fix )   \
80   _FT_( "wrap",             wrap_fix )           \
81   _FT_( "gnu_type",         gnu_type_fix )
82
83
84 #define FIX_PROC_HEAD( fix )                    \
85 static t_fix_proc fix; /* avoid warning */      \
86 static void fix ( filname, text, p_fixd )       \
87     const char* filname;                        \
88     const char* text;                           \
89     tFixDesc* p_fixd;
90
91 #ifdef NEED_PRINT_QUOTE
92 /*
93  *  Skip over a quoted string.  Single quote strings may
94  *  contain multiple characters if the first character is
95  *  a backslash.  Especially a backslash followed by octal digits.
96  *  We are not doing a correctness syntax check here.
97  */
98 static char*
99 print_quote( q, text )
100   char  q;
101   char* text;
102 {
103   fputc( q, stdout );
104
105   for (;;)
106     {
107       char ch = *(text++);
108       fputc( ch, stdout );
109
110       switch (ch)
111         {
112         case '\\':
113           if (*text == NUL)
114             goto quote_done;
115
116           fputc( *(text++), stdout );
117           break;
118
119         case '"':
120         case '\'':
121           if (ch != q)
122             break;
123           /*FALLTHROUGH*/
124
125         case '\n':
126         case NUL:
127           goto quote_done;
128         }
129     } quote_done:;
130
131   return text;
132 }
133 #endif /* NEED_PRINT_QUOTE */
134
135
136 /*
137  *  Emit the GNU standard type wrapped up in such a way that
138  *  this thing can be encountered countless times during a compile
139  *  and not cause even a warning.
140  */
141 static const char*
142 emit_gnu_type ( text, rm )
143   const char* text;
144   regmatch_t* rm;
145 {
146   char z_TYPE[ 64 ];
147   char z_type[ 64 ];
148
149   fwrite (text, rm[0].rm_so, 1, stdout);
150
151   {
152     const char* ps = text   + rm[1].rm_so;
153     const char* pe = text   + rm[1].rm_eo;
154     char* pd = z_type;
155     char* pD = z_TYPE;
156
157     while (ps < pe)
158       *(pD++) = toupper( *(pd++) = *(ps++) );
159
160     *pD = *pd = NUL;
161   }
162
163   /*
164    *  Now print out the reformed typedef,
165    *  with a C++ guard for WCHAR
166    */
167   {
168     tSCC z_fmt[] = "\
169 #if !defined(_GCC_%s_T)%s\n\
170 #define _GCC_%s_T\n\
171 typedef __%s_TYPE__ %s_t;\n\
172 #endif\n";
173
174     const char* pz_guard = (strcmp (z_type, "wchar") == 0)
175                            ? " && ! defined(__cplusplus)" : "";
176
177     printf (z_fmt, z_TYPE, pz_guard, z_TYPE, z_TYPE, z_type);
178   }
179
180   return text += rm[0].rm_eo;
181 }
182
183
184 /*
185  *  Copy the `format' string to std out, replacing `%n' expressions
186  *  with the matched text from a regular expression evaluation.
187  *  Doubled '%' characters will be replaced with a single copy.
188  *  '%' characters in other contexts and all other characters are
189  *  copied out verbatim.
190  */
191 static void
192 format_write (format, text, av)
193      tCC* format;
194      tCC* text;
195      regmatch_t av[];
196 {
197   int c;
198
199   while ((c = (unsigned)*(format++)) != NUL) {
200
201     if (c != '%')
202       {
203         putchar(c);
204         continue;
205       }
206
207     c = (unsigned)*(format++);
208
209     /*
210      *  IF the character following a '%' is not a digit,
211      *  THEN we will always emit a '%' and we may or may
212      *  not emit the following character.  We will end on
213      *  a NUL and we will emit only one of a pair of '%'.
214      */
215     if (! isdigit( c ))
216       {
217         putchar( '%' );
218         switch (c) {
219         case NUL:
220           return;
221         case '%':
222           break;
223         default:
224           putchar(c);
225         }
226       }
227
228     /*
229      *  Emit the matched subexpression numbered 'c'.
230      *  IF, of course, there was such a match...
231      */
232     else {
233       regmatch_t*  pRM = av + (c - (unsigned)'0');
234       size_t len;
235
236       if (pRM->rm_so < 0)
237         continue;
238
239       len = pRM->rm_eo - pRM->rm_so;
240       if (len > 0)
241         fwrite(text + pRM->rm_so, len, 1, stdout);
242     }
243   }
244 }
245
246
247 /*
248  *  Search for multiple copies of a regular expression.  Each block
249  *  of matched text is replaced with the format string, as described
250  *  above in `format_write'.
251  */
252 FIX_PROC_HEAD( format_fix )
253 {
254   tCC*  pz_pat = p_fixd->patch_args[2];
255   tCC*  pz_fmt = p_fixd->patch_args[1];
256   regex_t re;
257   regmatch_t rm[10];
258
259   /*
260    *  We must have a format
261    */
262   if (pz_fmt == (tCC*)NULL)
263     {
264       fprintf( stderr, zNeedsArg, p_fixd->fix_name, "replacement format", 0 );
265       exit (EXIT_BROKEN);
266     }
267
268   /*
269    *  IF we don't have a search text, then go find the first
270    *  regular expression among the tests.
271    */
272   if (pz_pat == (tCC*)NULL)
273     {
274       tTestDesc* pTD = p_fixd->p_test_desc;
275       int        ct  = p_fixd->test_ct;
276       for (;;)
277         {
278           if (ct-- <= 0)
279             {
280               fprintf( stderr, zNeedsArg, p_fixd->fix_name, "search text", 1 );
281               exit (EXIT_BROKEN);
282             }
283
284           if (pTD->type == TT_EGREP)
285             {
286               pz_pat = pTD->pz_test_text;
287               break;
288             }
289
290           pTD++;
291         }
292     }
293
294   /*
295    *  Replace every copy of the text we find
296    */
297   compile_re (pz_pat, &re, 1, "format search-text", "format_fix" );
298   while (regexec (&re, text, 10, rm, 0) == 0)
299     {
300       fwrite( text, rm[0].rm_so, 1, stdout );
301       format_write( pz_fmt, text, rm );
302       text += rm[0].rm_eo;
303     }
304
305   /*
306    *  Dump out the rest of the file
307    */
308   fputs (text, stdout);
309 }
310
311
312 /* Scan the input file for all occurrences of text like this:
313
314    #define TIOCCONS _IO(T, 12)
315
316    and change them to read like this:
317
318    #define TIOCCONS _IO('T', 12)
319
320    which is the required syntax per the C standard.  (The definition of
321    _IO also has to be tweaked - see below.)  'IO' is actually whatever you
322    provide as the `c_fix_arg' argument.  */
323
324 FIX_PROC_HEAD( char_macro_use_fix )
325 {
326   /* This regexp looks for a traditional-syntax #define (# in column 1)
327      of an object-like macro.  */
328   static const char pat[] =
329     "^#[ \t]*define[ \t]+[_A-Za-z][_A-Za-z0-9]*[ \t]+";
330   static regex_t re;
331
332   const char* str = p_fixd->patch_args[1];
333   regmatch_t rm[1];
334   const char *p, *limit;
335   size_t len;
336
337   if (str == NULL)
338     {
339       fprintf (stderr, zNeedsArg, p_fixd->fix_name, "ioctl type", 0);
340       exit (EXIT_BROKEN);
341     }
342
343   len = strlen (str);
344   compile_re (pat, &re, 1, "macro pattern", "char_macro_use_fix");
345
346   for (p = text;
347        regexec (&re, p, 1, rm, 0) == 0;
348        p = limit + 1)
349     {
350       /* p + rm[0].rm_eo is the first character of the macro replacement.
351          Find the end of the macro replacement, and the STR we were
352          sent to look for within the replacement.  */
353       p += rm[0].rm_eo;
354       limit = p - 1;
355       do
356         {
357           limit = strchr (limit + 1, '\n');
358           if (!limit)
359             goto done;
360         }
361       while (limit[-1] == '\\');
362
363       do
364         {
365           if (*p == str[0] && !strncmp (p+1, str+1, len-1))
366             goto found;
367         }
368       while (++p < limit - len);
369       /* Hit end of line.  */
370       continue;
371
372     found:
373       /* Found STR on this line.  If the macro needs fixing,
374          the next few chars will be whitespace or uppercase,
375          then an open paren, then a single letter.  */
376       while ((isspace (*p) || isupper (*p)) && p < limit) p++;
377       if (*p++ != '(')
378         continue;
379       if (!isalpha (*p))
380         continue;
381       if (isalnum (p[1]) || p[1] == '_')
382         continue;
383
384       /* Splat all preceding text into the output buffer,
385          quote the character at p, then proceed.  */
386       fwrite (text, 1, p - text, stdout);
387       putchar ('\'');
388       putchar (*p);
389       putchar ('\'');
390       text = p + 1;
391     }
392  done:
393   fputs (text, stdout);
394 }
395
396
397 /* Scan the input file for all occurrences of text like this:
398
399    #define xxxIOxx(x, y) (....'x'<<16....)
400
401    and change them to read like this:
402
403    #define xxxIOxx(x, y) (....x<<16....)
404
405    which is the required syntax per the C standard.  (The uses of _IO
406    also has to be tweaked - see above.)  'IO' is actually whatever
407    you provide as the `c_fix_arg' argument.  */
408 FIX_PROC_HEAD( char_macro_def_fix )
409 {
410   /* This regexp looks for any traditional-syntax #define (# in column 1).  */
411   static const char pat[] =
412     "^#[ \t]*define[ \t]+";
413   static regex_t re;
414
415   const char* str = p_fixd->patch_args[1];
416   regmatch_t rm[1];
417   const char *p, *limit;
418   char arg;
419   size_t len;
420
421   if (str == NULL)
422     {
423       fprintf (stderr, zNeedsArg, p_fixd->fix_name, "ioctl type", 0);
424       exit (EXIT_BROKEN);
425     }
426
427   len = strlen (str);
428   compile_re (pat, &re, 1, "macro pattern", "fix_char_macro_defines");
429
430   for (p = text;
431        regexec (&re, p, 1, rm, 0) == 0;
432        p = limit + 1)
433     {
434       /* p + rm[0].rm_eo is the first character of the macro name.
435          Find the end of the macro replacement, and the STR we were
436          sent to look for within the name.  */
437       p += rm[0].rm_eo;
438       limit = p - 1;
439       do
440         {
441           limit = strchr (limit + 1, '\n');
442           if (!limit)
443             goto done;
444         }
445       while (limit[-1] == '\\');
446
447       do
448         {
449           if (*p == str[0] && !strncmp (p+1, str+1, len-1))
450             goto found;
451           p++;
452         }
453       while (isalpha (*p) || isalnum (*p) || *p == '_');
454       /* Hit end of macro name without finding the string.  */
455       continue;
456
457     found:
458       /* Found STR in this macro name.  If the macro needs fixing,
459          there may be a few uppercase letters, then there will be an
460          open paren with _no_ intervening whitespace, and then a
461          single letter.  */
462       while (isupper (*p) && p < limit) p++;
463       if (*p++ != '(')
464         continue;
465       if (!isalpha (*p))
466         continue;
467       if (isalnum (p[1]) || p[1] == '_')
468         continue;
469
470       /* The character at P is the one to look for in the following
471          text.  */
472       arg = *p;
473       p += 2;
474
475       while (p < limit)
476         {
477           if (p[-1] == '\'' && p[0] == arg && p[1] == '\'')
478             {
479               /* Remove the quotes from this use of ARG.  */
480               p--;
481               fwrite (text, 1, p - text, stdout);
482               putchar (arg);
483               p += 3;
484               text = p;
485             }
486           else
487             p++;
488         }
489     }
490  done:
491   fputs (text, stdout);
492 }
493
494 /* Fix for machine name #ifdefs that are not in the namespace reserved
495    by the C standard.  They won't be defined if compiling with -ansi,
496    and the headers will break.  We go to some trouble to only change
497    #ifdefs where the macro is defined by GCC in non-ansi mode; this
498    minimizes the number of headers touched.  */
499
500 #define SCRATCHSZ 64   /* hopefully long enough */
501
502 FIX_PROC_HEAD( machine_name_fix )
503 {
504 #ifndef MN_NAME_PAT
505   fputs( "The target machine has no needed machine name fixes\n", stderr );
506 #else
507   regmatch_t match[2];
508   const char *line, *base, *limit, *p, *q;
509   regex_t *label_re, *name_re;
510   char scratch[SCRATCHSZ];
511   size_t len;
512
513   mn_get_regexps (&label_re, &name_re, "machine_name_fix");
514
515   scratch[0] = '_';
516   scratch[1] = '_';
517
518   for (base = text;
519        regexec (label_re, base, 2, match, 0) == 0;
520        base = limit)
521     {
522       base += match[0].rm_eo;
523       /* We're looking at an #if or #ifdef.  Scan forward for the
524          next non-escaped newline.  */
525       line = limit = base;
526       do
527         {
528           limit++;
529           limit = strchr (limit, '\n');
530           if (!limit)
531             goto done;
532         }
533       while (limit[-1] == '\\');
534
535       /* If the 'name_pat' matches in between base and limit, we have
536          a bogon.  It is not worth the hassle of excluding comments
537          because comments on #if/#ifdef lines are rare, and strings on
538          such lines are illegal.
539
540          REG_NOTBOL means 'base' is not at the beginning of a line, which
541          shouldn't matter since the name_re has no ^ anchor, but let's
542          be accurate anyway.  */
543
544       for (;;)
545         {
546         again:
547           if (base == limit)
548             break;
549
550           if (regexec (name_re, base, 1, match, REG_NOTBOL))
551             goto done;  /* No remaining match in this file */
552
553           /* Match; is it on the line?  */
554           if (match[0].rm_eo > limit - base)
555             break;
556
557           p = base + match[0].rm_so;
558           base += match[0].rm_eo;
559
560           /* One more test: if on the same line we have the same string
561              with the appropriate underscores, then leave it alone.
562              We want exactly two leading and trailing underscores.  */
563           if (*p == '_')
564             {
565               len = base - p - ((*base == '_') ? 2 : 1);
566               q = p + 1;
567             }
568           else
569             {
570               len = base - p - ((*base == '_') ? 1 : 0);
571               q = p;
572             }
573           if (len + 4 > SCRATCHSZ)
574             abort ();
575           memcpy (&scratch[2], q, len);
576           len += 2;
577           scratch[len++] = '_';
578           scratch[len++] = '_';
579
580           for (q = line; q <= limit - len; q++)
581             if (*q == '_' && !strncmp (q, scratch, len))
582               goto again;
583           
584           fwrite (text, 1, p - text, stdout);
585           fwrite (scratch, 1, len, stdout);
586
587           text = base;
588         }
589     }
590  done:
591 #endif
592   fputs (text, stdout);
593 }
594
595
596 FIX_PROC_HEAD( wrap_fix )
597 {
598   char   z_fixname[ 64 ];
599   tCC*   pz_src  = p_fixd->fix_name;
600   tCC*   pz_name = z_fixname;
601   char*  pz_dst  = z_fixname;
602   size_t len     = 0;
603
604   for (;;) {
605     char ch = *(pz_src++);
606
607     if (islower(ch))
608       *(pz_dst++) = toupper( ch );
609
610     else if (isalnum( ch ))
611       *(pz_dst++) = ch;
612
613     else if (ch == NUL) {
614       *(pz_dst++) = ch;
615       break;
616     }
617     else
618       *(pz_dst++) = '_';
619
620     if (++len >= sizeof( z_fixname )) {
621       void* p = xmalloc( len + strlen( pz_src ) + 1 );
622       memcpy( p, (void*)z_fixname, len );
623       pz_name = (tCC*)p;
624       pz_dst  = (char*)pz_name + len;
625     }
626   }
627
628   printf( "#ifndef FIXINC_%s_CHECK\n", pz_name );
629   printf( "#define FIXINC_%s_CHECK 1\n\n", pz_name );
630
631   if (p_fixd->patch_args[1] == (tCC*)NULL)
632     fputs( text, stdout );
633
634   else {
635     fputs( p_fixd->patch_args[1], stdout );
636     fputs( text, stdout );
637     if (p_fixd->patch_args[2] != (tCC*)NULL)
638       fputs( p_fixd->patch_args[2], stdout );
639   }
640
641   printf( "\n#endif  /* FIXINC_%s_CHECK */\n", pz_name );
642   if (pz_name != z_fixname)
643     free( (void*)pz_name );
644 }
645
646
647 /*
648  *  Search for multiple copies of a regular expression.  Each block
649  *  of matched text is replaced with the format string, as described
650  *  above in `format_write'.
651  */
652 FIX_PROC_HEAD( gnu_type_fix )
653 {
654   const char* pz_pat;
655   regex_t    re;
656   regmatch_t rm[GTYPE_SE_CT+1];
657
658   {
659     tTestDesc* pTD = p_fixd->p_test_desc;
660     int        ct  = p_fixd->test_ct;
661     for (;;)
662       {
663         if (ct-- <= 0)
664           {
665             fprintf (stderr, zNeedsArg, p_fixd->fix_name, "search text", 1);
666             exit (EXIT_BROKEN);
667           }
668
669         if (pTD->type == TT_EGREP)
670           {
671             pz_pat = pTD->pz_test_text;
672             break;
673           }
674
675         pTD++;
676       }
677   }
678
679   compile_re (pz_pat, &re, 1, "gnu type typedef", "gnu_type_fix");
680
681   while (regexec (&re, text, GTYPE_SE_CT+1, rm, 0) == 0)
682     {
683       text = emit_gnu_type (text, rm);
684     }
685
686   /*
687    *  Dump out the rest of the file
688    */
689   fputs (text, stdout);
690 }
691
692
693 /* = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
694
695      test for fix selector
696
697      THIS IS THE ONLY EXPORTED ROUTINE
698
699 */
700 void
701 apply_fix( p_fixd, filname )
702   tFixDesc* p_fixd;
703   tCC* filname;
704 {
705 #define _FT_(n,p) { n, p },
706   static fix_entry_t fix_table[] = { FIXUP_TABLE { NULL, NULL }};
707 #undef _FT_
708 #define FIX_TABLE_CT (ARRAY_SIZE (fix_table)-1)
709
710   tCC* fixname = p_fixd->patch_args[0];
711   char* buf;
712   int ct = FIX_TABLE_CT;
713   fix_entry_t* pfe = fix_table;
714
715   for (;;)
716     {
717       if (strcmp (pfe->fix_name, fixname) == 0)
718         break;
719       if (--ct <= 0)
720         {
721           fprintf (stderr, "fixincl error:  the `%s' fix is unknown\n",
722                    fixname );
723           exit (EXIT_BROKEN);
724         }
725       pfe++;
726     }
727
728   buf = load_file_data (stdin);
729   (*pfe->fix_proc)( filname, buf, p_fixd );
730 }
731
732 #ifdef __MSDOS__
733 tSCC z_usage[] =
734 "USAGE: applyfix <fix-name> <file-to-fix> <file-source> <file-destination>\n";
735 tSCC z_reopen[] =
736 "FS error %d (%s) reopening %s as std%s\n";
737
738 int
739 main( argc, argv )
740   int     argc;
741   char**  argv;
742 {
743   tFixDesc* pFix;
744   char* pz_tmptmp;
745   char* pz_tmp_base;
746   char* pz_tmp_dot;
747
748   if (argc != 5)
749     {
750     usage_failure:
751       fputs( z_usage, stderr );
752       return EXIT_FAILURE;
753     }
754
755   {
756     char* pz = argv[1];
757     long  idx;
758
759     if (! isdigit( *pz ))
760       goto usage_failure;
761
762     idx = strtol( pz, &pz, 10 );
763     if ((*pz != NUL) || ((unsigned)idx >= FIX_COUNT))
764       goto usage_failure;
765     pFix = fixDescList + idx;
766   }
767
768   if (freopen( argv[3], "r", stdin ) != stdin)
769     {
770       fprintf( stderr, z_reopen, errno, strerror( errno ), argv[3], "in" );
771       return EXIT_FAILURE;
772     }
773
774   pz_tmptmp = (char*)xmalloc( strlen( argv[4] ) + 5 );
775   strcpy( pz_tmptmp, argv[4] );
776
777   /* Don't lose because "12345678" and "12345678X" map to the same
778      file under DOS restricted 8+3 file namespace.  Note that DOS
779      doesn't allow more than one dot in the trunk of a file name.  */
780   pz_tmp_base = basename( pz_tmptmp );
781   pz_tmp_dot = strchr( pz_tmp_base, '.' );
782   if (pathconf( pz_tmptmp, _PC_NAME_MAX ) <= 12 /* is this DOS or Windows9X? */
783       && pz_tmp_dot != (char*)NULL)
784     strcpy( pz_tmp_dot+1, "X" ); /* nuke the original extension */
785   else
786     strcat( pz_tmptmp, ".X" );
787   if (freopen( pz_tmptmp, "w", stdout ) != stdout)
788     {
789       fprintf( stderr, z_reopen, errno, strerror( errno ), pz_tmptmp, "out" );
790       return EXIT_FAILURE;
791     }
792
793   apply_fix( pFix, argv[1] );
794   close( STDOUT_FILENO );
795   close( STDIN_FILENO );
796   unlink( argv[4] );
797   if (rename( pz_tmptmp, argv[4] ) != 0)
798     {
799       fprintf( stderr, "error %d (%s) renaming %s to %s\n", errno,
800                strerror( errno ), pz_tmptmp, argv[4] );
801       return EXIT_FAILURE;
802     }
803
804   return EXIT_SUCCESS;
805 }
806 #endif