several changes to toolchain packages
[hdw-linux/hdw-linux.git] / packages / base / linux / unidef.patch
1 diff -Naur linux-2.6.18.1.orig/Makefile linux-2.6.18.1/Makefile
2 --- linux-2.6.18.1.orig/Makefile        2006-10-14 03:34:03.000000000 +0000
3 +++ linux-2.6.18.1/Makefile     2006-10-14 20:05:20.000000000 +0000
4 @@ -893,11 +893,11 @@
5  export INSTALL_HDR_PATH
6  
7  PHONY += headers_install
8 -headers_install: include/linux/version.h
9 +headers_install: include/linux/version.h scripts_basic FORCE
10         @if [ ! -r include/asm-$(ARCH)/Kbuild ]; then \
11           echo '*** Error: Headers not exportable for this architecture ($(ARCH))'; \
12           exit 1 ; fi
13 -       $(Q)unifdef -Ux /dev/null
14 +       $(Q)$(MAKE) $(build)=scripts scripts/unifdef
15         $(Q)rm -rf $(INSTALL_HDR_PATH)/include
16         $(Q)$(MAKE) -rR -f $(srctree)/scripts/Makefile.headersinst obj=include
17  
18 diff -Naur linux-2.6.18.1.orig/scripts/Makefile linux-2.6.18.1/scripts/Makefile
19 --- linux-2.6.18.1.orig/scripts/Makefile        2006-10-14 03:34:03.000000000 +0000
20 +++ linux-2.6.18.1/scripts/Makefile     2006-10-14 20:04:09.000000000 +0000
21 @@ -15,6 +15,9 @@
22  
23  always         := $(hostprogs-y)
24  
25 +# The following hostprogs-y programs are only build on demand
26 +hostprogs-y += unifdef
27 +
28  subdir-$(CONFIG_MODVERSIONS) += genksyms
29  subdir-$(CONFIG_MODULES)     += mod
30  
31 diff -Naur linux-2.6.18.1.orig/scripts/Makefile.headersinst linux-2.6.18.1/scripts/Makefile.headersinst
32 --- linux-2.6.18.1.orig/scripts/Makefile.headersinst    2006-10-14 03:34:03.000000000 +0000
33 +++ linux-2.6.18.1/scripts/Makefile.headersinst 2006-10-14 20:04:09.000000000 +0000
34 @@ -7,7 +7,7 @@
35  #
36  # ==========================================================================
37  
38 -UNIFDEF := unifdef -U__KERNEL__
39 +UNIFDEF := scripts/unifdef -U__KERNEL__
40  
41  # Eliminate the contents of (and inclusions of) compiler.h
42  HDRSED  := sed         -e "s/ inline / __inline__ /g" \
43 diff -Naur linux-2.6.18.1.orig/scripts/unifdef.c linux-2.6.18.1/scripts/unifdef.c
44 --- linux-2.6.18.1.orig/scripts/unifdef.c       1970-01-01 00:00:00.000000000 +0000
45 +++ linux-2.6.18.1/scripts/unifdef.c    2006-10-14 20:04:09.000000000 +0000
46 @@ -0,0 +1,1005 @@
47 +/*
48 + * Copyright (c) 2002 - 2005 Tony Finch <dot@dotat.at>.  All rights reserved.
49 + *
50 + * This code is derived from software contributed to Berkeley by Dave Yost.
51 + * It was rewritten to support ANSI C by Tony Finch. The original version of
52 + * unifdef carried the following copyright notice. None of its code remains
53 + * in this version (though some of the names remain).
54 + *
55 + * Copyright (c) 1985, 1993
56 + *     The Regents of the University of California.  All rights reserved.
57 + *
58 + * Redistribution and use in source and binary forms, with or without
59 + * modification, are permitted provided that the following conditions
60 + * are met:
61 + * 1. Redistributions of source code must retain the above copyright
62 + *    notice, this list of conditions and the following disclaimer.
63 + * 2. Redistributions in binary form must reproduce the above copyright
64 + *    notice, this list of conditions and the following disclaimer in the
65 + *    documentation and/or other materials provided with the distribution.
66 + *
67 + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
68 + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
69 + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
70 + * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
71 + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
72 + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
73 + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
74 + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
75 + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
76 + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
77 + * SUCH DAMAGE.
78 + */
79 +
80 +#include <sys/cdefs.h>
81 +
82 +#ifndef lint
83 +#if 0
84 +static const char copyright[] =
85 +"@(#) Copyright (c) 1985, 1993\n\
86 +       The Regents of the University of California.  All rights reserved.\n";
87 +#endif
88 +#ifdef __IDSTRING
89 +__IDSTRING(Berkeley, "@(#)unifdef.c    8.1 (Berkeley) 6/6/93");
90 +__IDSTRING(NetBSD, "$NetBSD: unifdef.c,v 1.8 2000/07/03 02:51:36 matt Exp $");
91 +__IDSTRING(dotat, "$dotat: things/unifdef.c,v 1.171 2005/03/08 12:38:48 fanf2 Exp $");
92 +#endif
93 +#endif /* not lint */
94 +#ifdef __FBSDID
95 +__FBSDID("$FreeBSD: /repoman/r/ncvs/src/usr.bin/unifdef/unifdef.c,v 1.20 2005/05/21 09:55:09 ru Exp $");
96 +#endif
97 +
98 +/*
99 + * unifdef - remove ifdef'ed lines
100 + *
101 + *  Wishlist:
102 + *      provide an option which will append the name of the
103 + *        appropriate symbol after #else's and #endif's
104 + *      provide an option which will check symbols after
105 + *        #else's and #endif's to see that they match their
106 + *        corresponding #ifdef or #ifndef
107 + *
108 + *   The first two items above require better buffer handling, which would
109 + *     also make it possible to handle all "dodgy" directives correctly.
110 + */
111 +
112 +#include <ctype.h>
113 +#include <err.h>
114 +#include <stdarg.h>
115 +#include <stdbool.h>
116 +#include <stdio.h>
117 +#include <stdlib.h>
118 +#include <string.h>
119 +#include <unistd.h>
120 +
121 +size_t strlcpy(char *dst, const char *src, size_t siz);
122 +
123 +/* types of input lines: */
124 +typedef enum {
125 +       LT_TRUEI,               /* a true #if with ignore flag */
126 +       LT_FALSEI,              /* a false #if with ignore flag */
127 +       LT_IF,                  /* an unknown #if */
128 +       LT_TRUE,                /* a true #if */
129 +       LT_FALSE,               /* a false #if */
130 +       LT_ELIF,                /* an unknown #elif */
131 +       LT_ELTRUE,              /* a true #elif */
132 +       LT_ELFALSE,             /* a false #elif */
133 +       LT_ELSE,                /* #else */
134 +       LT_ENDIF,               /* #endif */
135 +       LT_DODGY,               /* flag: directive is not on one line */
136 +       LT_DODGY_LAST = LT_DODGY + LT_ENDIF,
137 +       LT_PLAIN,               /* ordinary line */
138 +       LT_EOF,                 /* end of file */
139 +       LT_COUNT
140 +} Linetype;
141 +
142 +static char const * const linetype_name[] = {
143 +       "TRUEI", "FALSEI", "IF", "TRUE", "FALSE",
144 +       "ELIF", "ELTRUE", "ELFALSE", "ELSE", "ENDIF",
145 +       "DODGY TRUEI", "DODGY FALSEI",
146 +       "DODGY IF", "DODGY TRUE", "DODGY FALSE",
147 +       "DODGY ELIF", "DODGY ELTRUE", "DODGY ELFALSE",
148 +       "DODGY ELSE", "DODGY ENDIF",
149 +       "PLAIN", "EOF"
150 +};
151 +
152 +/* state of #if processing */
153 +typedef enum {
154 +       IS_OUTSIDE,
155 +       IS_FALSE_PREFIX,        /* false #if followed by false #elifs */
156 +       IS_TRUE_PREFIX,         /* first non-false #(el)if is true */
157 +       IS_PASS_MIDDLE,         /* first non-false #(el)if is unknown */
158 +       IS_FALSE_MIDDLE,        /* a false #elif after a pass state */
159 +       IS_TRUE_MIDDLE,         /* a true #elif after a pass state */
160 +       IS_PASS_ELSE,           /* an else after a pass state */
161 +       IS_FALSE_ELSE,          /* an else after a true state */
162 +       IS_TRUE_ELSE,           /* an else after only false states */
163 +       IS_FALSE_TRAILER,       /* #elifs after a true are false */
164 +       IS_COUNT
165 +} Ifstate;
166 +
167 +static char const * const ifstate_name[] = {
168 +       "OUTSIDE", "FALSE_PREFIX", "TRUE_PREFIX",
169 +       "PASS_MIDDLE", "FALSE_MIDDLE", "TRUE_MIDDLE",
170 +       "PASS_ELSE", "FALSE_ELSE", "TRUE_ELSE",
171 +       "FALSE_TRAILER"
172 +};
173 +
174 +/* state of comment parser */
175 +typedef enum {
176 +       NO_COMMENT = false,     /* outside a comment */
177 +       C_COMMENT,              /* in a comment like this one */
178 +       CXX_COMMENT,            /* between // and end of line */
179 +       STARTING_COMMENT,       /* just after slash-backslash-newline */
180 +       FINISHING_COMMENT,      /* star-backslash-newline in a C comment */
181 +       CHAR_LITERAL,           /* inside '' */
182 +       STRING_LITERAL          /* inside "" */
183 +} Comment_state;
184 +
185 +static char const * const comment_name[] = {
186 +       "NO", "C", "CXX", "STARTING", "FINISHING", "CHAR", "STRING"
187 +};
188 +
189 +/* state of preprocessor line parser */
190 +typedef enum {
191 +       LS_START,               /* only space and comments on this line */
192 +       LS_HASH,                /* only space, comments, and a hash */
193 +       LS_DIRTY                /* this line can't be a preprocessor line */
194 +} Line_state;
195 +
196 +static char const * const linestate_name[] = {
197 +       "START", "HASH", "DIRTY"
198 +};
199 +
200 +/*
201 + * Minimum translation limits from ISO/IEC 9899:1999 5.2.4.1
202 + */
203 +#define        MAXDEPTH        64                      /* maximum #if nesting */
204 +#define        MAXLINE         4096                    /* maximum length of line */
205 +#define        MAXSYMS         4096                    /* maximum number of symbols */
206 +
207 +/*
208 + * Sometimes when editing a keyword the replacement text is longer, so
209 + * we leave some space at the end of the tline buffer to accommodate this.
210 + */
211 +#define        EDITSLOP        10
212 +
213 +/*
214 + * Globals.
215 + */
216 +
217 +static bool             complement;            /* -c: do the complement */
218 +static bool             debugging;             /* -d: debugging reports */
219 +static bool             iocccok;               /* -e: fewer IOCCC errors */
220 +static bool             killconsts;            /* -k: eval constant #ifs */
221 +static bool             lnblank;               /* -l: blank deleted lines */
222 +static bool             lnnum;                 /* -n: add #line directives */
223 +static bool             symlist;               /* -s: output symbol list */
224 +static bool             text;                  /* -t: this is a text file */
225 +
226 +static const char      *symname[MAXSYMS];      /* symbol name */
227 +static const char      *value[MAXSYMS];                /* -Dsym=value */
228 +static bool             ignore[MAXSYMS];       /* -iDsym or -iUsym */
229 +static int              nsyms;                 /* number of symbols */
230 +
231 +static FILE            *input;                 /* input file pointer */
232 +static const char      *filename;              /* input file name */
233 +static int              linenum;               /* current line number */
234 +
235 +static char             tline[MAXLINE+EDITSLOP];/* input buffer plus space */
236 +static char            *keyword;               /* used for editing #elif's */
237 +
238 +static Comment_state    incomment;             /* comment parser state */
239 +static Line_state       linestate;             /* #if line parser state */
240 +static Ifstate          ifstate[MAXDEPTH];     /* #if processor state */
241 +static bool             ignoring[MAXDEPTH];    /* ignore comments state */
242 +static int              stifline[MAXDEPTH];    /* start of current #if */
243 +static int              depth;                 /* current #if nesting */
244 +static int              delcount;              /* count of deleted lines */
245 +static bool             keepthis;              /* don't delete constant #if */
246 +
247 +static int              exitstat;              /* program exit status */
248 +
249 +static void             addsym(bool, bool, char *);
250 +static void             debug(const char *, ...);
251 +static void             done(void);
252 +static void             error(const char *);
253 +static int              findsym(const char *);
254 +static void             flushline(bool);
255 +static Linetype         getline(void);
256 +static Linetype         ifeval(const char **);
257 +static void             ignoreoff(void);
258 +static void             ignoreon(void);
259 +static void             keywordedit(const char *);
260 +static void             nest(void);
261 +static void             process(void);
262 +static const char      *skipcomment(const char *);
263 +static const char      *skipsym(const char *);
264 +static void             state(Ifstate);
265 +static int              strlcmp(const char *, const char *, size_t);
266 +static void             unnest(void);
267 +static void             usage(void);
268 +
269 +#define endsym(c) (!isalpha((unsigned char)c) && !isdigit((unsigned char)c) && c != '_')
270 +
271 +/*
272 + * The main program.
273 + */
274 +int
275 +main(int argc, char *argv[])
276 +{
277 +       int opt;
278 +
279 +       while ((opt = getopt(argc, argv, "i:D:U:I:cdeklnst")) != -1)
280 +               switch (opt) {
281 +               case 'i': /* treat stuff controlled by these symbols as text */
282 +                       /*
283 +                        * For strict backwards-compatibility the U or D
284 +                        * should be immediately after the -i but it doesn't
285 +                        * matter much if we relax that requirement.
286 +                        */
287 +                       opt = *optarg++;
288 +                       if (opt == 'D')
289 +                               addsym(true, true, optarg);
290 +                       else if (opt == 'U')
291 +                               addsym(true, false, optarg);
292 +                       else
293 +                               usage();
294 +                       break;
295 +               case 'D': /* define a symbol */
296 +                       addsym(false, true, optarg);
297 +                       break;
298 +               case 'U': /* undef a symbol */
299 +                       addsym(false, false, optarg);
300 +                       break;
301 +               case 'I':
302 +                       /* no-op for compatibility with cpp */
303 +                       break;
304 +               case 'c': /* treat -D as -U and vice versa */
305 +                       complement = true;
306 +                       break;
307 +               case 'd':
308 +                       debugging = true;
309 +                       break;
310 +               case 'e': /* fewer errors from dodgy lines */
311 +                       iocccok = true;
312 +                       break;
313 +               case 'k': /* process constant #ifs */
314 +                       killconsts = true;
315 +                       break;
316 +               case 'l': /* blank deleted lines instead of omitting them */
317 +                       lnblank = true;
318 +                       break;
319 +               case 'n': /* add #line directive after deleted lines */
320 +                       lnnum = true;
321 +                       break;
322 +               case 's': /* only output list of symbols that control #ifs */
323 +                       symlist = true;
324 +                       break;
325 +               case 't': /* don't parse C comments */
326 +                       text = true;
327 +                       break;
328 +               default:
329 +                       usage();
330 +               }
331 +       argc -= optind;
332 +       argv += optind;
333 +       if (argc > 1) {
334 +               errx(2, "can only do one file");
335 +       } else if (argc == 1 && strcmp(*argv, "-") != 0) {
336 +               filename = *argv;
337 +               input = fopen(filename, "r");
338 +               if (input == NULL)
339 +                       err(2, "can't open %s", filename);
340 +       } else {
341 +               filename = "[stdin]";
342 +               input = stdin;
343 +       }
344 +       process();
345 +       abort(); /* bug */
346 +}
347 +
348 +static void
349 +usage(void)
350 +{
351 +       fprintf(stderr, "usage: unifdef [-cdeklnst] [-Ipath]"
352 +           " [-Dsym[=val]] [-Usym] [-iDsym[=val]] [-iUsym] ... [file]\n");
353 +       exit(2);
354 +}
355 +
356 +/*
357 + * A state transition function alters the global #if processing state
358 + * in a particular way. The table below is indexed by the current
359 + * processing state and the type of the current line.
360 + *
361 + * Nesting is handled by keeping a stack of states; some transition
362 + * functions increase or decrease the depth. They also maintain the
363 + * ignore state on a stack. In some complicated cases they have to
364 + * alter the preprocessor directive, as follows.
365 + *
366 + * When we have processed a group that starts off with a known-false
367 + * #if/#elif sequence (which has therefore been deleted) followed by a
368 + * #elif that we don't understand and therefore must keep, we edit the
369 + * latter into a #if to keep the nesting correct.
370 + *
371 + * When we find a true #elif in a group, the following block will
372 + * always be kept and the rest of the sequence after the next #elif or
373 + * #else will be discarded. We edit the #elif into a #else and the
374 + * following directive to #endif since this has the desired behaviour.
375 + *
376 + * "Dodgy" directives are split across multiple lines, the most common
377 + * example being a multi-line comment hanging off the right of the
378 + * directive. We can handle them correctly only if there is no change
379 + * from printing to dropping (or vice versa) caused by that directive.
380 + * If the directive is the first of a group we have a choice between
381 + * failing with an error, or passing it through unchanged instead of
382 + * evaluating it. The latter is not the default to avoid questions from
383 + * users about unifdef unexpectedly leaving behind preprocessor directives.
384 + */
385 +typedef void state_fn(void);
386 +
387 +/* report an error */
388 +static void Eelif (void) { error("Inappropriate #elif"); }
389 +static void Eelse (void) { error("Inappropriate #else"); }
390 +static void Eendif(void) { error("Inappropriate #endif"); }
391 +static void Eeof  (void) { error("Premature EOF"); }
392 +static void Eioccc(void) { error("Obfuscated preprocessor control line"); }
393 +/* plain line handling */
394 +static void print (void) { flushline(true); }
395 +static void drop  (void) { flushline(false); }
396 +/* output lacks group's start line */
397 +static void Strue (void) { drop();  ignoreoff(); state(IS_TRUE_PREFIX); }
398 +static void Sfalse(void) { drop();  ignoreoff(); state(IS_FALSE_PREFIX); }
399 +static void Selse (void) { drop();               state(IS_TRUE_ELSE); }
400 +/* print/pass this block */
401 +static void Pelif (void) { print(); ignoreoff(); state(IS_PASS_MIDDLE); }
402 +static void Pelse (void) { print();              state(IS_PASS_ELSE); }
403 +static void Pendif(void) { print(); unnest(); }
404 +/* discard this block */
405 +static void Dfalse(void) { drop();  ignoreoff(); state(IS_FALSE_TRAILER); }
406 +static void Delif (void) { drop();  ignoreoff(); state(IS_FALSE_MIDDLE); }
407 +static void Delse (void) { drop();               state(IS_FALSE_ELSE); }
408 +static void Dendif(void) { drop();  unnest(); }
409 +/* first line of group */
410 +static void Fdrop (void) { nest();  Dfalse(); }
411 +static void Fpass (void) { nest();  Pelif(); }
412 +static void Ftrue (void) { nest();  Strue(); }
413 +static void Ffalse(void) { nest();  Sfalse(); }
414 +/* variable pedantry for obfuscated lines */
415 +static void Oiffy (void) { if (!iocccok) Eioccc(); Fpass(); ignoreon(); }
416 +static void Oif   (void) { if (!iocccok) Eioccc(); Fpass(); }
417 +static void Oelif (void) { if (!iocccok) Eioccc(); Pelif(); }
418 +/* ignore comments in this block */
419 +static void Idrop (void) { Fdrop();  ignoreon(); }
420 +static void Itrue (void) { Ftrue();  ignoreon(); }
421 +static void Ifalse(void) { Ffalse(); ignoreon(); }
422 +/* edit this line */
423 +static void Mpass (void) { strncpy(keyword, "if  ", 4); Pelif(); }
424 +static void Mtrue (void) { keywordedit("else\n");  state(IS_TRUE_MIDDLE); }
425 +static void Melif (void) { keywordedit("endif\n"); state(IS_FALSE_TRAILER); }
426 +static void Melse (void) { keywordedit("endif\n"); state(IS_FALSE_ELSE); }
427 +
428 +static state_fn * const trans_table[IS_COUNT][LT_COUNT] = {
429 +/* IS_OUTSIDE */
430 +{ Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Eendif,
431 +  Oiffy, Oiffy, Fpass, Oif,   Oif,   Eelif, Eelif, Eelif, Eelse, Eendif,
432 +  print, done },
433 +/* IS_FALSE_PREFIX */
434 +{ Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Strue, Sfalse,Selse, Dendif,
435 +  Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Eioccc,Eioccc,Eioccc,Eioccc,
436 +  drop,  Eeof },
437 +/* IS_TRUE_PREFIX */
438 +{ Itrue, Ifalse,Fpass, Ftrue, Ffalse,Dfalse,Dfalse,Dfalse,Delse, Dendif,
439 +  Oiffy, Oiffy, Fpass, Oif,   Oif,   Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
440 +  print, Eeof },
441 +/* IS_PASS_MIDDLE */
442 +{ Itrue, Ifalse,Fpass, Ftrue, Ffalse,Pelif, Mtrue, Delif, Pelse, Pendif,
443 +  Oiffy, Oiffy, Fpass, Oif,   Oif,   Pelif, Oelif, Oelif, Pelse, Pendif,
444 +  print, Eeof },
445 +/* IS_FALSE_MIDDLE */
446 +{ Idrop, Idrop, Fdrop, Fdrop, Fdrop, Pelif, Mtrue, Delif, Pelse, Pendif,
447 +  Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
448 +  drop,  Eeof },
449 +/* IS_TRUE_MIDDLE */
450 +{ Itrue, Ifalse,Fpass, Ftrue, Ffalse,Melif, Melif, Melif, Melse, Pendif,
451 +  Oiffy, Oiffy, Fpass, Oif,   Oif,   Eioccc,Eioccc,Eioccc,Eioccc,Pendif,
452 +  print, Eeof },
453 +/* IS_PASS_ELSE */
454 +{ Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Pendif,
455 +  Oiffy, Oiffy, Fpass, Oif,   Oif,   Eelif, Eelif, Eelif, Eelse, Pendif,
456 +  print, Eeof },
457 +/* IS_FALSE_ELSE */
458 +{ Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Dendif,
459 +  Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Eioccc,
460 +  drop,  Eeof },
461 +/* IS_TRUE_ELSE */
462 +{ Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Dendif,
463 +  Oiffy, Oiffy, Fpass, Oif,   Oif,   Eelif, Eelif, Eelif, Eelse, Eioccc,
464 +  print, Eeof },
465 +/* IS_FALSE_TRAILER */
466 +{ Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Dendif,
467 +  Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Eioccc,
468 +  drop,  Eeof }
469 +/*TRUEI  FALSEI IF     TRUE   FALSE  ELIF   ELTRUE ELFALSE ELSE  ENDIF
470 +  TRUEI  FALSEI IF     TRUE   FALSE  ELIF   ELTRUE ELFALSE ELSE  ENDIF (DODGY)
471 +  PLAIN  EOF */
472 +};
473 +
474 +/*
475 + * State machine utility functions
476 + */
477 +static void
478 +done(void)
479 +{
480 +       if (incomment)
481 +               error("EOF in comment");
482 +       exit(exitstat);
483 +}
484 +static void
485 +ignoreoff(void)
486 +{
487 +       if (depth == 0)
488 +               abort(); /* bug */
489 +       ignoring[depth] = ignoring[depth-1];
490 +}
491 +static void
492 +ignoreon(void)
493 +{
494 +       ignoring[depth] = true;
495 +}
496 +static void
497 +keywordedit(const char *replacement)
498 +{
499 +       size_t size = tline + sizeof(tline) - keyword;
500 +       char *dst = keyword;
501 +       const char *src = replacement;
502 +       if (size != 0) {
503 +               while ((--size != 0) && (*src != '\0'))
504 +                       *dst++ = *src++;
505 +               *dst = '\0';
506 +       }
507 +       print();
508 +}
509 +static void
510 +nest(void)
511 +{
512 +       depth += 1;
513 +       if (depth >= MAXDEPTH)
514 +               error("Too many levels of nesting");
515 +       stifline[depth] = linenum;
516 +}
517 +static void
518 +unnest(void)
519 +{
520 +       if (depth == 0)
521 +               abort(); /* bug */
522 +       depth -= 1;
523 +}
524 +static void
525 +state(Ifstate is)
526 +{
527 +       ifstate[depth] = is;
528 +}
529 +
530 +/*
531 + * Write a line to the output or not, according to command line options.
532 + */
533 +static void
534 +flushline(bool keep)
535 +{
536 +       if (symlist)
537 +               return;
538 +       if (keep ^ complement) {
539 +               if (lnnum && delcount > 0)
540 +                       printf("#line %d\n", linenum);
541 +               fputs(tline, stdout);
542 +               delcount = 0;
543 +       } else {
544 +               if (lnblank)
545 +                       putc('\n', stdout);
546 +               exitstat = 1;
547 +               delcount += 1;
548 +       }
549 +}
550 +
551 +/*
552 + * The driver for the state machine.
553 + */
554 +static void
555 +process(void)
556 +{
557 +       Linetype lineval;
558 +
559 +       for (;;) {
560 +               linenum++;
561 +               lineval = getline();
562 +               trans_table[ifstate[depth]][lineval]();
563 +               debug("process %s -> %s depth %d",
564 +                   linetype_name[lineval],
565 +                   ifstate_name[ifstate[depth]], depth);
566 +       }
567 +}
568 +
569 +/*
570 + * Parse a line and determine its type. We keep the preprocessor line
571 + * parser state between calls in the global variable linestate, with
572 + * help from skipcomment().
573 + */
574 +static Linetype
575 +getline(void)
576 +{
577 +       const char *cp;
578 +       int cursym;
579 +       int kwlen;
580 +       Linetype retval;
581 +       Comment_state wascomment;
582 +
583 +       if (fgets(tline, MAXLINE, input) == NULL)
584 +               return (LT_EOF);
585 +       retval = LT_PLAIN;
586 +       wascomment = incomment;
587 +       cp = skipcomment(tline);
588 +       if (linestate == LS_START) {
589 +               if (*cp == '#') {
590 +                       linestate = LS_HASH;
591 +                       cp = skipcomment(cp + 1);
592 +               } else if (*cp != '\0')
593 +                       linestate = LS_DIRTY;
594 +       }
595 +       if (!incomment && linestate == LS_HASH) {
596 +               keyword = tline + (cp - tline);
597 +               cp = skipsym(cp);
598 +               kwlen = cp - keyword;
599 +               /* no way can we deal with a continuation inside a keyword */
600 +               if (strncmp(cp, "\\\n", 2) == 0)
601 +                       Eioccc();
602 +               if (strlcmp("ifdef", keyword, kwlen) == 0 ||
603 +                   strlcmp("ifndef", keyword, kwlen) == 0) {
604 +                       cp = skipcomment(cp);
605 +                       if ((cursym = findsym(cp)) < 0)
606 +                               retval = LT_IF;
607 +                       else {
608 +                               retval = (keyword[2] == 'n')
609 +                                   ? LT_FALSE : LT_TRUE;
610 +                               if (value[cursym] == NULL)
611 +                                       retval = (retval == LT_TRUE)
612 +                                           ? LT_FALSE : LT_TRUE;
613 +                               if (ignore[cursym])
614 +                                       retval = (retval == LT_TRUE)
615 +                                           ? LT_TRUEI : LT_FALSEI;
616 +                       }
617 +                       cp = skipsym(cp);
618 +               } else if (strlcmp("if", keyword, kwlen) == 0)
619 +                       retval = ifeval(&cp);
620 +               else if (strlcmp("elif", keyword, kwlen) == 0)
621 +                       retval = ifeval(&cp) - LT_IF + LT_ELIF;
622 +               else if (strlcmp("else", keyword, kwlen) == 0)
623 +                       retval = LT_ELSE;
624 +               else if (strlcmp("endif", keyword, kwlen) == 0)
625 +                       retval = LT_ENDIF;
626 +               else {
627 +                       linestate = LS_DIRTY;
628 +                       retval = LT_PLAIN;
629 +               }
630 +               cp = skipcomment(cp);
631 +               if (*cp != '\0') {
632 +                       linestate = LS_DIRTY;
633 +                       if (retval == LT_TRUE || retval == LT_FALSE ||
634 +                           retval == LT_TRUEI || retval == LT_FALSEI)
635 +                               retval = LT_IF;
636 +                       if (retval == LT_ELTRUE || retval == LT_ELFALSE)
637 +                               retval = LT_ELIF;
638 +               }
639 +               if (retval != LT_PLAIN && (wascomment || incomment)) {
640 +                       retval += LT_DODGY;
641 +                       if (incomment)
642 +                               linestate = LS_DIRTY;
643 +               }
644 +               /* skipcomment should have changed the state */
645 +               if (linestate == LS_HASH)
646 +                       abort(); /* bug */
647 +       }
648 +       if (linestate == LS_DIRTY) {
649 +               while (*cp != '\0')
650 +                       cp = skipcomment(cp + 1);
651 +       }
652 +       debug("parser %s comment %s line",
653 +           comment_name[incomment], linestate_name[linestate]);
654 +       return (retval);
655 +}
656 +
657 +/*
658 + * These are the binary operators that are supported by the expression
659 + * evaluator. Note that if support for division is added then we also
660 + * need short-circuiting booleans because of divide-by-zero.
661 + */
662 +static int op_lt(int a, int b) { return (a < b); }
663 +static int op_gt(int a, int b) { return (a > b); }
664 +static int op_le(int a, int b) { return (a <= b); }
665 +static int op_ge(int a, int b) { return (a >= b); }
666 +static int op_eq(int a, int b) { return (a == b); }
667 +static int op_ne(int a, int b) { return (a != b); }
668 +static int op_or(int a, int b) { return (a || b); }
669 +static int op_and(int a, int b) { return (a && b); }
670 +
671 +/*
672 + * An evaluation function takes three arguments, as follows: (1) a pointer to
673 + * an element of the precedence table which lists the operators at the current
674 + * level of precedence; (2) a pointer to an integer which will receive the
675 + * value of the expression; and (3) a pointer to a char* that points to the
676 + * expression to be evaluated and that is updated to the end of the expression
677 + * when evaluation is complete. The function returns LT_FALSE if the value of
678 + * the expression is zero, LT_TRUE if it is non-zero, or LT_IF if the
679 + * expression could not be evaluated.
680 + */
681 +struct ops;
682 +
683 +typedef Linetype eval_fn(const struct ops *, int *, const char **);
684 +
685 +static eval_fn eval_table, eval_unary;
686 +
687 +/*
688 + * The precedence table. Expressions involving binary operators are evaluated
689 + * in a table-driven way by eval_table. When it evaluates a subexpression it
690 + * calls the inner function with its first argument pointing to the next
691 + * element of the table. Innermost expressions have special non-table-driven
692 + * handling.
693 + */
694 +static const struct ops {
695 +       eval_fn *inner;
696 +       struct op {
697 +               const char *str;
698 +               int (*fn)(int, int);
699 +       } op[5];
700 +} eval_ops[] = {
701 +       { eval_table, { { "||", op_or } } },
702 +       { eval_table, { { "&&", op_and } } },
703 +       { eval_table, { { "==", op_eq },
704 +                       { "!=", op_ne } } },
705 +       { eval_unary, { { "<=", op_le },
706 +                       { ">=", op_ge },
707 +                       { "<", op_lt },
708 +                       { ">", op_gt } } }
709 +};
710 +
711 +/*
712 + * Function for evaluating the innermost parts of expressions,
713 + * viz. !expr (expr) defined(symbol) symbol number
714 + * We reset the keepthis flag when we find a non-constant subexpression.
715 + */
716 +static Linetype
717 +eval_unary(const struct ops *ops, int *valp, const char **cpp)
718 +{
719 +       const char *cp;
720 +       char *ep;
721 +       int sym;
722 +
723 +       cp = skipcomment(*cpp);
724 +       if (*cp == '!') {
725 +               debug("eval%d !", ops - eval_ops);
726 +               cp++;
727 +               if (eval_unary(ops, valp, &cp) == LT_IF)
728 +                       return (LT_IF);
729 +               *valp = !*valp;
730 +       } else if (*cp == '(') {
731 +               cp++;
732 +               debug("eval%d (", ops - eval_ops);
733 +               if (eval_table(eval_ops, valp, &cp) == LT_IF)
734 +                       return (LT_IF);
735 +               cp = skipcomment(cp);
736 +               if (*cp++ != ')')
737 +                       return (LT_IF);
738 +       } else if (isdigit((unsigned char)*cp)) {
739 +               debug("eval%d number", ops - eval_ops);
740 +               *valp = strtol(cp, &ep, 0);
741 +               cp = skipsym(cp);
742 +       } else if (strncmp(cp, "defined", 7) == 0 && endsym(cp[7])) {
743 +               cp = skipcomment(cp+7);
744 +               debug("eval%d defined", ops - eval_ops);
745 +               if (*cp++ != '(')
746 +                       return (LT_IF);
747 +               cp = skipcomment(cp);
748 +               sym = findsym(cp);
749 +               if (sym < 0)
750 +                       return (LT_IF);
751 +               *valp = (value[sym] != NULL);
752 +               cp = skipsym(cp);
753 +               cp = skipcomment(cp);
754 +               if (*cp++ != ')')
755 +                       return (LT_IF);
756 +               keepthis = false;
757 +       } else if (!endsym(*cp)) {
758 +               debug("eval%d symbol", ops - eval_ops);
759 +               sym = findsym(cp);
760 +               if (sym < 0)
761 +                       return (LT_IF);
762 +               if (value[sym] == NULL)
763 +                       *valp = 0;
764 +               else {
765 +                       *valp = strtol(value[sym], &ep, 0);
766 +                       if (*ep != '\0' || ep == value[sym])
767 +                               return (LT_IF);
768 +               }
769 +               cp = skipsym(cp);
770 +               keepthis = false;
771 +       } else {
772 +               debug("eval%d bad expr", ops - eval_ops);
773 +               return (LT_IF);
774 +       }
775 +
776 +       *cpp = cp;
777 +       debug("eval%d = %d", ops - eval_ops, *valp);
778 +       return (*valp ? LT_TRUE : LT_FALSE);
779 +}
780 +
781 +/*
782 + * Table-driven evaluation of binary operators.
783 + */
784 +static Linetype
785 +eval_table(const struct ops *ops, int *valp, const char **cpp)
786 +{
787 +       const struct op *op;
788 +       const char *cp;
789 +       int val;
790 +
791 +       debug("eval%d", ops - eval_ops);
792 +       cp = *cpp;
793 +       if (ops->inner(ops+1, valp, &cp) == LT_IF)
794 +               return (LT_IF);
795 +       for (;;) {
796 +               cp = skipcomment(cp);
797 +               for (op = ops->op; op->str != NULL; op++)
798 +                       if (strncmp(cp, op->str, strlen(op->str)) == 0)
799 +                               break;
800 +               if (op->str == NULL)
801 +                       break;
802 +               cp += strlen(op->str);
803 +               debug("eval%d %s", ops - eval_ops, op->str);
804 +               if (ops->inner(ops+1, &val, &cp) == LT_IF)
805 +                       return (LT_IF);
806 +               *valp = op->fn(*valp, val);
807 +       }
808 +
809 +       *cpp = cp;
810 +       debug("eval%d = %d", ops - eval_ops, *valp);
811 +       return (*valp ? LT_TRUE : LT_FALSE);
812 +}
813 +
814 +/*
815 + * Evaluate the expression on a #if or #elif line. If we can work out
816 + * the result we return LT_TRUE or LT_FALSE accordingly, otherwise we
817 + * return just a generic LT_IF.
818 + */
819 +static Linetype
820 +ifeval(const char **cpp)
821 +{
822 +       int ret;
823 +       int val;
824 +
825 +       debug("eval %s", *cpp);
826 +       keepthis = killconsts ? false : true;
827 +       ret = eval_table(eval_ops, &val, cpp);
828 +       debug("eval = %d", val);
829 +       return (keepthis ? LT_IF : ret);
830 +}
831 +
832 +/*
833 + * Skip over comments, strings, and character literals and stop at the
834 + * next character position that is not whitespace. Between calls we keep
835 + * the comment state in the global variable incomment, and we also adjust
836 + * the global variable linestate when we see a newline.
837 + * XXX: doesn't cope with the buffer splitting inside a state transition.
838 + */
839 +static const char *
840 +skipcomment(const char *cp)
841 +{
842 +       if (text || ignoring[depth]) {
843 +               for (; isspace((unsigned char)*cp); cp++)
844 +                       if (*cp == '\n')
845 +                               linestate = LS_START;
846 +               return (cp);
847 +       }
848 +       while (*cp != '\0')
849 +               /* don't reset to LS_START after a line continuation */
850 +               if (strncmp(cp, "\\\n", 2) == 0)
851 +                       cp += 2;
852 +               else switch (incomment) {
853 +               case NO_COMMENT:
854 +                       if (strncmp(cp, "/\\\n", 3) == 0) {
855 +                               incomment = STARTING_COMMENT;
856 +                               cp += 3;
857 +                       } else if (strncmp(cp, "/*", 2) == 0) {
858 +                               incomment = C_COMMENT;
859 +                               cp += 2;
860 +                       } else if (strncmp(cp, "//", 2) == 0) {
861 +                               incomment = CXX_COMMENT;
862 +                               cp += 2;
863 +                       } else if (strncmp(cp, "\'", 1) == 0) {
864 +                               incomment = CHAR_LITERAL;
865 +                               linestate = LS_DIRTY;
866 +                               cp += 1;
867 +                       } else if (strncmp(cp, "\"", 1) == 0) {
868 +                               incomment = STRING_LITERAL;
869 +                               linestate = LS_DIRTY;
870 +                               cp += 1;
871 +                       } else if (strncmp(cp, "\n", 1) == 0) {
872 +                               linestate = LS_START;
873 +                               cp += 1;
874 +                       } else if (strchr(" \t", *cp) != NULL) {
875 +                               cp += 1;
876 +                       } else
877 +                               return (cp);
878 +                       continue;
879 +               case CXX_COMMENT:
880 +                       if (strncmp(cp, "\n", 1) == 0) {
881 +                               incomment = NO_COMMENT;
882 +                               linestate = LS_START;
883 +                       }
884 +                       cp += 1;
885 +                       continue;
886 +               case CHAR_LITERAL:
887 +               case STRING_LITERAL:
888 +                       if ((incomment == CHAR_LITERAL && cp[0] == '\'') ||
889 +                           (incomment == STRING_LITERAL && cp[0] == '\"')) {
890 +                               incomment = NO_COMMENT;
891 +                               cp += 1;
892 +                       } else if (cp[0] == '\\') {
893 +                               if (cp[1] == '\0')
894 +                                       cp += 1;
895 +                               else
896 +                                       cp += 2;
897 +                       } else if (strncmp(cp, "\n", 1) == 0) {
898 +                               if (incomment == CHAR_LITERAL)
899 +                                       error("unterminated char literal");
900 +                               else
901 +                                       error("unterminated string literal");
902 +                       } else
903 +                               cp += 1;
904 +                       continue;
905 +               case C_COMMENT:
906 +                       if (strncmp(cp, "*\\\n", 3) == 0) {
907 +                               incomment = FINISHING_COMMENT;
908 +                               cp += 3;
909 +                       } else if (strncmp(cp, "*/", 2) == 0) {
910 +                               incomment = NO_COMMENT;
911 +                               cp += 2;
912 +                       } else
913 +                               cp += 1;
914 +                       continue;
915 +               case STARTING_COMMENT:
916 +                       if (*cp == '*') {
917 +                               incomment = C_COMMENT;
918 +                               cp += 1;
919 +                       } else if (*cp == '/') {
920 +                               incomment = CXX_COMMENT;
921 +                               cp += 1;
922 +                       } else {
923 +                               incomment = NO_COMMENT;
924 +                               linestate = LS_DIRTY;
925 +                       }
926 +                       continue;
927 +               case FINISHING_COMMENT:
928 +                       if (*cp == '/') {
929 +                               incomment = NO_COMMENT;
930 +                               cp += 1;
931 +                       } else
932 +                               incomment = C_COMMENT;
933 +                       continue;
934 +               default:
935 +                       abort(); /* bug */
936 +               }
937 +       return (cp);
938 +}
939 +
940 +/*
941 + * Skip over an identifier.
942 + */
943 +static const char *
944 +skipsym(const char *cp)
945 +{
946 +       while (!endsym(*cp))
947 +               ++cp;
948 +       return (cp);
949 +}
950 +
951 +/*
952 + * Look for the symbol in the symbol table. If is is found, we return
953 + * the symbol table index, else we return -1.
954 + */
955 +static int
956 +findsym(const char *str)
957 +{
958 +       const char *cp;
959 +       int symind;
960 +
961 +       cp = skipsym(str);
962 +       if (cp == str)
963 +               return (-1);
964 +       if (symlist) {
965 +               printf("%.*s\n", (int)(cp-str), str);
966 +               /* we don't care about the value of the symbol */
967 +               return (0);
968 +       }
969 +       for (symind = 0; symind < nsyms; ++symind) {
970 +               if (strlcmp(symname[symind], str, cp-str) == 0) {
971 +                       debug("findsym %s %s", symname[symind],
972 +                           value[symind] ? value[symind] : "");
973 +                       return (symind);
974 +               }
975 +       }
976 +       return (-1);
977 +}
978 +
979 +/*
980 + * Add a symbol to the symbol table.
981 + */
982 +static void
983 +addsym(bool ignorethis, bool definethis, char *sym)
984 +{
985 +       int symind;
986 +       char *val;
987 +
988 +       symind = findsym(sym);
989 +       if (symind < 0) {
990 +               if (nsyms >= MAXSYMS)
991 +                       errx(2, "too many symbols");
992 +               symind = nsyms++;
993 +       }
994 +       symname[symind] = sym;
995 +       ignore[symind] = ignorethis;
996 +       val = sym + (skipsym(sym) - sym);
997 +       if (definethis) {
998 +               if (*val == '=') {
999 +                       value[symind] = val+1;
1000 +                       *val = '\0';
1001 +               } else if (*val == '\0')
1002 +                       value[symind] = "";
1003 +               else
1004 +                       usage();
1005 +       } else {
1006 +               if (*val != '\0')
1007 +                       usage();
1008 +               value[symind] = NULL;
1009 +       }
1010 +}
1011 +
1012 +/*
1013 + * Compare s with n characters of t.
1014 + * The same as strncmp() except that it checks that s[n] == '\0'.
1015 + */
1016 +static int
1017 +strlcmp(const char *s, const char *t, size_t n)
1018 +{
1019 +       while (n-- && *t != '\0')
1020 +               if (*s != *t)
1021 +                       return ((unsigned char)*s - (unsigned char)*t);
1022 +               else
1023 +                       ++s, ++t;
1024 +       return ((unsigned char)*s);
1025 +}
1026 +
1027 +/*
1028 + * Diagnostics.
1029 + */
1030 +static void
1031 +debug(const char *msg, ...)
1032 +{
1033 +       va_list ap;
1034 +
1035 +       if (debugging) {
1036 +               va_start(ap, msg);
1037 +               vwarnx(msg, ap);
1038 +               va_end(ap);
1039 +       }
1040 +}
1041 +
1042 +static void
1043 +error(const char *msg)
1044 +{
1045 +       if (depth == 0)
1046 +               warnx("%s: %d: %s", filename, linenum, msg);
1047 +       else
1048 +               warnx("%s: %d: %s (#if line %d depth %d)",
1049 +                   filename, linenum, msg, stifline[depth], depth);
1050 +       errx(2, "output may be truncated");
1051 +}