2 * Another fast dependencies generator for Makefiles, Version 4.2
4 * Copyright (C) 2005,2006 by Vladimir Oleynik <dzo@simtreas.ru>
6 * mmaping file may be originally by Linus Torvalds.
8 * infix parser/evaluator for #if expression
9 * Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
10 * Copyright (c) 2001 Manuel Novoa III <mjn3@codepoet.org>
11 * Copyright (c) 2003 Vladimir Oleynik <dzo@simtreas.ru>
14 * Copyright (C) 2005 Manuel Novoa III <mjn3@codepoet.org>
16 * xmalloc() bb_xstrdup() bb_error_d():
17 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
20 * Copyright (C) 2003 Glenn McGrath
21 * Copyright (C) Vladimir Oleynik <dzo@simtreas.ru>
23 * (c) 2005,2006 Bernhard Fischer:
25 * - move "memory exhausted" into msg_enomem,
26 * - more verbose --help output.
29 * 1) find #define KEY VALUE or #undef KEY from include/bb_config.h
30 * 2) recursive find and scan *.[ch] files, but skips scan of include/config/
31 * 3) find #include "*.h" and KEYs using, if not as #define and #undef
32 * 4) generate dependencies to stdout
33 * pwd/file.o: include/config/key*.h found_include_*.h
34 * path/inc.h: include/config/key*.h found_included_include_*.h
35 * 5) save include/config/key*.h if changed after previous usage
36 * This program does not generate dependencies for #include <...>
37 * Config file can have #if #elif #else #ifdef #ifndef #endif lines
40 #define LOCAL_INCLUDE_PATH "include"
41 #define INCLUDE_CONFIG_PATH LOCAL_INCLUDE_PATH"/config"
42 #define INCLUDE_CONFIG_KEYS_PATH LOCAL_INCLUDE_PATH"/bb_config.h"
44 #define bb_mkdep_full_options \
46 "\n\t-I local_include_path include paths, default: \"" LOCAL_INCLUDE_PATH "\"" \
47 "\n\t-d don't generate depend" \
48 "\n\t-w show warning if include files not found" \
49 "\n\t-k include/config default: \"" INCLUDE_CONFIG_PATH "\"" \
50 "\n\t-c include/config.h configs, default: \"" INCLUDE_CONFIG_KEYS_PATH "\"" \
51 "\n\tdirs_to_scan default \".\""
53 #define bb_mkdep_terse_options "Usage: [-I local_include_paths] [-dw] " \
54 "[-k path_for_stored_keys] [dirs]"
58 #include <sys/types.h>
73 #define ATTRIBUTE __attribute__
75 #define ATTRIBUTE(a) /* nothing */
78 #if !(defined __USE_ISOC99 || (defined __GLIBC_HAVE_LONG_LONG && defined __USE_MISC))
79 #define strtoll strtol
82 /* partial and simplified libbb routine */
83 static void bb_error_d(const char *s, ...) ATTRIBUTE ((noreturn, format (printf, 1, 2)));
84 static char * bb_asprint(const char *format, ...) ATTRIBUTE ((format (printf, 1, 2)));
85 static char *bb_simplify_path(const char *path);
87 /* stolen from libbb as is */
88 typedef struct llist_s {
93 static const char msg_enomem[] = "memory exhausted";
95 /* inline realization for fast works */
96 static inline void *xmalloc(size_t size)
98 void *p = malloc(size);
101 bb_error_d(msg_enomem);
105 static inline char *bb_xstrdup(const char *s)
110 bb_error_d(msg_enomem);
115 static int dontgenerate_dep; /* flag -d usaged */
116 static int noiwarning; /* flag -w usaged */
117 static llist_t *configs; /* list of -c usaged and them stat() after parsed */
118 static llist_t *Iop; /* list of -I include usaged */
120 static char *pwd; /* current work directory */
121 static size_t replace; /* replace current work directory with build dir */
123 static const char *kp; /* KEY path, argument of -k used */
124 static size_t kp_len;
125 static struct stat st_kp; /* stat(kp) */
127 typedef struct BB_KEYS {
133 const char *src_have_this_key;
134 struct BB_KEYS *next;
137 static bb_key_t *key_top; /* list of found KEYs */
138 static bb_key_t *Ifound; /* list of parsed includes */
141 static void parse_conf_opt(const char *opt, const char *val, size_t key_sz);
142 static void parse_inc(const char *include, const char *fname);
144 static inline bb_key_t *check_key(bb_key_t *k, const char *nk, size_t key_sz)
148 for(cur = k; cur; cur = cur->next) {
149 if(key_sz == cur->key_sz && memcmp(cur->keyname, nk, key_sz) == 0) {
150 cur->checked = cur->stored_path;
157 static inline const char *lookup_key(const char *nk, size_t key_sz)
161 for(cur = key_top; cur; cur = cur->next) {
162 if(key_sz == cur->key_sz && memcmp(cur->keyname, nk, key_sz) == 0) {
169 /* for lexical analyser */
170 static int pagesizem1; /* padding mask = getpagesize() - 1 */
172 /* for speed tricks */
173 static char first_chars[1+UCHAR_MAX]; /* + L_EOF */
174 static char isalnums[1+UCHAR_MAX]; /* + L_EOF */
176 /* trick for fast find "define", "include", "undef",
177 "if((n)def)" "else", "endif" */
178 static const char * const preproc[] = {
179 /* 0 1 2 3 4 5 6 7 8 9 */
180 "", "efine", "lif", "lse", "ndif", "f", "fdef", "fndef", "nclude", "ndef" };
181 static const unsigned char first_chars_deiu[UCHAR_MAX] = {
182 [(int)'d'] = (unsigned char)(1|0x10), /* define */
183 [(int)'e'] = (unsigned char)(2|0x40), /* elif, else, endif */
184 [(int)'i'] = (unsigned char)(5|0x80), /* if ifdef ifndef include */
185 [(int)'u'] = (unsigned char)(9|0x90), /* undef */
188 #define CONFIG_MODE 0
189 #define IF0_MODE 1 /* #if 0 */
190 #define IF1_MODE 2 /* #if 1 */
191 #define ELSE0_MODE 4 /* #else found after #if 0 */
192 #define ELSE1_MODE 8 /* #else found after #if 1 */
193 #define ELIF1_MODE 16 /* #elif found after #if 1 */
194 #define FALSE_MODES (IF0_MODE|ELSE1_MODE|ELIF1_MODE)
196 #define yy_error_d(s) bb_error_d("%s:%d hmm, %s", fname, line, s)
199 #define S 0 /* start state */
200 #define STR '"' /* string */
201 #define CHR '\'' /* char */
202 #define REM '/' /* block comment */
203 #define BS '\\' /* back slash */
204 #define POUND '#' /* # */
205 #define D '1' /* #define preprocessor's directive */
206 #define EI '2' /* #elif preprocessor's directive */
207 #define E '3' /* #else preprocessor's directive */
208 #define EF '4' /* #endif preprocessor's directive */
209 #define F '5' /* #if preprocessor's directive */
210 #define IFD '6' /* #ifdef preprocessor's directive */
211 #define IFND '7' /* #ifndef preprocessor's directive */
212 #define I '8' /* #include preprocessor's directive */
213 #define U '9' /* #undef preprocessor's directive */
214 #define DK 'K' /* #define KEY... (config mode) */
215 #define ANY '*' /* any unparsed chars */
218 #define ID(c) ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_')
220 #define ISALNUM(c) (ID(c) || (c >= '0' && c <= '9'))
222 #define L_EOF (1+UCHAR_MAX)
224 #define getc0() do { c = (optr >= oend) ? L_EOF : *optr++; } while(0)
226 #define getc1() do { getc0(); if(c == BS) { getc0(); \
227 if(c == '\n') { line++; continue; } \
228 else { optr--; c = BS; } \
231 static char id_s[4096];
232 #define put_id(ic) do { if(id_len == sizeof(id_s)) goto too_long; \
233 id[id_len++] = ic; } while(0)
235 static char ifcpp_stack[1024];
236 static int ptr_ifcpp_stack;
237 #define push_mode() do { \
238 if(ptr_ifcpp_stack == (int)sizeof(ifcpp_stack)) \
239 yy_error_d("#if* stack overflow"); \
240 ifcpp_stack[ptr_ifcpp_stack++] = (char)mode; \
243 #define pop_mode() do { \
244 if(ptr_ifcpp_stack == 0) \
245 yy_error_d("unexpected #endif"); \
246 mode = ifcpp_stack[--ptr_ifcpp_stack]; \
250 typedef long long arith_t;
252 static arith_t arith (const char *expr, int *perrcode);
254 /* The code uses a simple two-stack algorithm. See
255 * http://www.onthenet.com.au/~grahamis/int2008/week02/lect02.html
256 * for a detailed explanation of the infix-to-postfix algorithm on which
257 * this is based (this code differs in that it applies operators immediately
258 * to the stack instead of adding them to a queue to end up with an
261 #define arith_isspace(arithval) \
262 (arithval == ' ' || arithval == '\v' || arithval == '\t' || arithval == '\f')
265 typedef unsigned char operator;
267 /* An operator's token id is a bit of a bitfield. The lower 5 bits are the
268 * precedence, and 3 high bits are an ID unique across operators of that
269 * precedence. The ID portion is so that multiple operators can have the
270 * same precedence, ensuring that the leftmost one is evaluated first.
271 * Consider * and /. */
273 #define tok_decl(prec,id) (((id)<<5)|(prec))
274 #define PREC(op) ((op) & 0x1F)
276 #define TOK_LPAREN tok_decl(0,0)
278 #define TOK_COMMA tok_decl(1,0)
280 /* conditional is right associativity too */
281 #define TOK_CONDITIONAL tok_decl(2,0)
282 #define TOK_CONDITIONAL_SEP tok_decl(2,1)
284 #define TOK_OR tok_decl(3,0)
286 #define TOK_AND tok_decl(4,0)
288 #define TOK_BOR tok_decl(5,0)
290 #define TOK_BXOR tok_decl(6,0)
292 #define TOK_BAND tok_decl(7,0)
294 #define TOK_EQ tok_decl(8,0)
295 #define TOK_NE tok_decl(8,1)
297 #define TOK_LT tok_decl(9,0)
298 #define TOK_GT tok_decl(9,1)
299 #define TOK_GE tok_decl(9,2)
300 #define TOK_LE tok_decl(9,3)
302 #define TOK_LSHIFT tok_decl(10,0)
303 #define TOK_RSHIFT tok_decl(10,1)
305 #define TOK_ADD tok_decl(11,0)
306 #define TOK_SUB tok_decl(11,1)
308 #define TOK_MUL tok_decl(12,0)
309 #define TOK_DIV tok_decl(12,1)
310 #define TOK_REM tok_decl(12,2)
312 /* For now unary operators. */
314 #define TOK_BNOT tok_decl(UNARYPREC,0)
315 #define TOK_NOT tok_decl(UNARYPREC,1)
317 #define TOK_UMINUS tok_decl(UNARYPREC+1,0)
318 #define TOK_UPLUS tok_decl(UNARYPREC+1,1)
320 #define SPEC_PREC (UNARYPREC+2)
322 #define TOK_NUM tok_decl(SPEC_PREC, 0)
323 #define TOK_RPAREN tok_decl(SPEC_PREC, 1)
325 #define NUMPTR (*numstackptr)
327 typedef struct ARITCH_VAR_NUM {
329 arith_t contidional_second_val;
330 char contidional_second_val_initialized;
334 typedef struct CHK_VAR_RECURSIVE_LOOPED {
337 struct CHK_VAR_RECURSIVE_LOOPED *next;
338 } chk_var_recursive_looped_t;
340 static chk_var_recursive_looped_t *prev_chk_var_recursive;
343 static int arith_lookup_val(const char *var, size_t key_sz, arith_t *pval)
345 const char * p = lookup_key(var, key_sz);
350 /* recursive try as expression */
351 chk_var_recursive_looped_t *cur;
352 chk_var_recursive_looped_t cur_save;
354 for(cur = prev_chk_var_recursive; cur; cur = cur->next) {
355 if(cur->var_sz == key_sz && memcmp(cur->var, var, key_sz) == 0) {
356 /* expression recursion loop detected */
360 /* save current lookuped var name */
361 cur = prev_chk_var_recursive;
363 cur_save.var_sz = key_sz;
365 prev_chk_var_recursive = &cur_save;
367 *pval = arith (p, &errcode);
368 /* restore previous ptr after recursiving */
369 prev_chk_var_recursive = cur;
372 /* disallow undefined var */
373 fprintf(stderr, "%.*s ", (int)key_sz, var);
378 /* "applying" a token means performing it on the top elements on the integer
379 * stack. For a unary operator it will only change the top element, but a
380 * binary operator will pop two arguments and push a result */
382 arith_apply(operator op, v_n_t *numstack, v_n_t **numstackptr)
385 arith_t numptr_val, rez;
387 if (NUMPTR == numstack) goto err; /* There is no operator that can work
389 numptr_m1 = NUMPTR - 1;
391 rez = numptr_m1->val;
392 if (op == TOK_UMINUS)
394 else if (op == TOK_NOT)
396 else if (op == TOK_BNOT)
398 else if (op != TOK_UPLUS) {
399 /* Binary operators */
401 /* check and binary operators need two arguments */
402 if (numptr_m1 == numstack) goto err;
404 /* ... and they pop one */
407 if (op == TOK_CONDITIONAL) {
408 if(! numptr_m1->contidional_second_val_initialized) {
409 /* protect $((expr1 ? expr2)) without ": expr" */
412 rez = numptr_m1->contidional_second_val;
413 } else if(numptr_m1->contidional_second_val_initialized) {
414 /* protect $((expr1 : expr2)) without "expr ? " */
417 numptr_m1 = NUMPTR - 1;
418 if (op == TOK_CONDITIONAL) {
419 numptr_m1->contidional_second_val = rez;
421 rez = numptr_m1->val;
424 else if (op == TOK_OR)
425 rez = numptr_val || rez;
426 else if (op == TOK_BAND)
428 else if (op == TOK_BXOR)
430 else if (op == TOK_AND)
431 rez = rez && numptr_val;
432 else if (op == TOK_EQ)
433 rez = (rez == numptr_val);
434 else if (op == TOK_NE)
435 rez = (rez != numptr_val);
436 else if (op == TOK_GE)
437 rez = (rez >= numptr_val);
438 else if (op == TOK_RSHIFT)
440 else if (op == TOK_LSHIFT)
442 else if (op == TOK_GT)
443 rez = (rez > numptr_val);
444 else if (op == TOK_LT)
445 rez = (rez < numptr_val);
446 else if (op == TOK_LE)
447 rez = (rez <= numptr_val);
448 else if (op == TOK_MUL)
450 else if (op == TOK_ADD)
452 else if (op == TOK_SUB)
454 else if (op == TOK_COMMA)
456 else if (op == TOK_CONDITIONAL_SEP) {
457 if (numptr_m1 == numstack) {
458 /* protect $((expr : expr)) without "expr ? " */
461 numptr_m1->contidional_second_val_initialized = op;
462 numptr_m1->contidional_second_val = numptr_val;
464 else if (op == TOK_CONDITIONAL) {
466 numptr_val : numptr_m1->contidional_second_val;
468 else if(numptr_val==0) /* zero divisor check */
470 else if (op == TOK_DIV)
472 else if (op == TOK_REM)
475 numptr_m1->val = rez;
480 /* longest must first */
481 static const char op_tokens[] = {
482 '<','<', 0, TOK_LSHIFT,
483 '>','>', 0, TOK_RSHIFT,
503 '?', 0, TOK_CONDITIONAL,
504 ':', 0, TOK_CONDITIONAL_SEP,
510 #define endexpression &op_tokens[sizeof(op_tokens)-7]
513 * Return of a legal variable name (a letter or underscore followed by zero or
514 * more letters, underscores, and digits).
518 endofname(const char *name)
533 static arith_t arith (const char *expr, int *perrcode)
535 char arithval; /* Current character under analysis */
536 operator lasttok, op;
539 const char *p = endexpression;
542 size_t datasizes = strlen(expr) + 2;
544 /* Stack of integers */
545 /* The proof that there can be no more than strlen(startbuf)/2+1 integers
546 * in any given correct or incorrect expression is left as an exercise to
548 v_n_t *numstack = alloca(((datasizes)/2)*sizeof(v_n_t)),
549 *numstackptr = numstack;
550 /* Stack of operator tokens */
551 operator *stack = alloca((datasizes) * sizeof(operator)),
554 *stackptr++ = lasttok = TOK_LPAREN; /* start off with a left paren */
555 *perrcode = errcode = 0;
558 if ((arithval = *expr) == 0) {
559 if (p == endexpression) {
560 /* Null expression. */
562 return (*perrcode = -1);
565 /* This is only reached after all tokens have been extracted from the
566 * input stream. If there are still tokens on the operator stack, they
567 * are to be applied in order. At the end, there should be a final
568 * result on the integer stack */
570 if (expr != endexpression + 1) {
571 /* If we haven't done so already, */
572 /* append a closing right paren */
573 expr = endexpression;
574 /* and let the loop process it. */
577 /* At this point, we're done with the expression. */
578 if (numstackptr != numstack+1) {
579 /* ... but if there isn't, it's bad */
584 return numstack->val;
586 /* Continue processing the expression. */
587 if (arith_isspace(arithval)) {
588 /* Skip whitespace */
591 if((p = endofname(expr)) != expr) {
592 size_t var_name_size = (p-expr);
594 if(var_name_size == 7 &&
595 strncmp(expr, "defined", var_name_size) == 0) {
599 while(arith_isspace(*p)) p++;
602 while(arith_isspace(*p)) p++;
606 if((p = endofname(expr)) == expr)
608 var_name_size = (p-expr);
609 while(arith_isspace(*p)) p++;
610 if(brace_form && *p++ != ')')
612 v = lookup_key(expr, var_name_size);
613 numstackptr->val = (v != NULL) ? 1 : 0;
615 errcode = arith_lookup_val(expr, var_name_size,
616 &(numstackptr->val));
617 if(errcode) goto ret;
621 numstackptr->contidional_second_val_initialized = 0;
625 } else if (arithval >= '0' && arithval <= '9') {
626 numstackptr->val = strtoll(expr, (char **) &expr, 0);
627 while(*expr == 'l' || *expr == 'L' || *expr == 'u' ||
632 for(p = op_tokens; ; p++) {
636 /* strange operator not found */
639 for(o = expr; *p && *o == *p; p++)
646 /* skip tail uncompared token */
649 /* skip zero delim */
654 /* Plus and minus are binary (not unary) _only_ if the last
655 * token was as number, or a right paren (which pretends to be
656 * a number, since it evaluates to one). Think about it.
658 if (lasttok != TOK_NUM) {
661 else if(op == TOK_SUB)
664 /* We don't want a unary operator to cause recursive descent on the
665 * stack, because there can be many in a row and it could cause an
666 * operator to be evaluated before its argument is pushed onto the
668 /* But for binary operators, "apply" everything on the operator
669 * stack until we find an operator with a lesser priority than the
670 * one we have just extracted. */
671 /* Left paren is given the lowest priority so it will never be
672 * "applied" in this way.
673 * if associativity is right and priority eq, applied also skip
676 if ((prec > 0 && prec < UNARYPREC) || prec == SPEC_PREC) {
677 /* not left paren or unary */
678 if (lasttok != TOK_NUM) {
679 /* binary op must be preceded by a num */
682 while (stackptr != stack) {
683 if (op == TOK_RPAREN) {
684 /* The algorithm employed here is simple: while we don't
685 * hit an open paren nor the bottom of the stack, pop
686 * tokens and apply them */
687 if (stackptr[-1] == TOK_LPAREN) {
689 /* Any operator directly after a */
691 /* close paren should consider itself binary */
695 operator prev_prec = PREC(stackptr[-1]);
697 if (prev_prec < prec)
699 /* check right assoc */
700 if(prev_prec == prec && prec == PREC(TOK_CONDITIONAL))
703 errcode = arith_apply(*--stackptr, numstack, &numstackptr);
704 if(errcode) goto ret;
706 if (op == TOK_RPAREN) {
711 /* Push this operator to the stack and remember it. */
712 *stackptr++ = lasttok = op;
720 /* stupid C lexical analyser for configs.h */
721 static void c_lex_config(const char *fname, long fsize)
727 size_t id_len = 0; /* stupid initialization */
728 unsigned char *optr, *oend;
729 int mode = CONFIG_MODE;
736 fprintf(stderr, "Warning: %s is empty\n", fname);
739 fd = open(fname, O_RDONLY);
744 mapsize = (fsize+pagesizem1) & ~pagesizem1;
745 map = mmap(NULL, mapsize, PROT_READ, MAP_PRIVATE, fd, 0);
746 if ((long) map == -1)
747 bb_error_d("%s: mmap: %m", fname);
749 optr = (unsigned char *)map;
758 /* [ \t]+ eat first space */
759 while(c == ' ' || c == '\t')
763 while(first_chars[c] == ANY) {
771 munmap(map, mapsize);
773 if(mode != CONFIG_MODE)
774 yy_error_d("expected #endif");
782 do getc0(); while(c != '\n' && c != L_EOF);
783 } else if(c == '*') {
784 /* <S>[/][*] goto parse block comments */
787 } else if(c == POUND) {
791 } else if(c == STR || c == CHR) {
799 /* <STR>\" or <CHR>\' */
803 /* <STR,CHR>\\ but is not <STR,CHR>\\\n */
806 if(c == '\n' || c == L_EOF)
807 yy_error_d("unterminated");
811 /* <S>[A-Z_a-z0-9] */
813 /* trick for fast drop id
814 if key with this first char undefined */
815 if(first_chars[c] == 0 || (mode & FALSE_MODES) != 0) {
816 /* skip <S>[A-Z_a-z0-9]+ */
817 do getc1(); while(isalnums[c]);
821 /* <S>[A-Z_a-z0-9]+ */
824 } while(isalnums[c]);
825 check_key(key_top, id, id_len);
830 /* begin preprocessor states */
832 yy_error_d("unexpected EOF");
837 yy_error_d("detected // in preprocessor line");
839 /* <#.*>[/][*] goto parse block comments */
843 yy_error_d("strange preprocessor line");
847 int diu = (int)first_chars_deiu[c]; /* preproc ptr */
851 int p_num_str, p_num_max;
860 p_num_str = diu & 0xf;
861 p_num_max = diu >> 4;
862 for(diu = p_num_str; diu <= p_num_max; diu++)
863 if(!strcmp(id, preproc[diu])) {
870 while(isalnums[c]) getc1();
872 } else if(state == EF) {
876 } else if(state == I) {
877 if(c == STR && (mode & FALSE_MODES) == 0) {
884 yy_error_d("unexpected EOF");
888 /* store "include.h" */
889 parse_inc(id, fname);
892 /* else another (may be wrong) #include ... */
894 } else if(state == F) {
898 while(c != '\n' && c != L_EOF) {
903 t = arith(id, &errcode);
906 yy_error_d("divide by zero");
907 else if (errcode == -4)
908 yy_error_d("undefined");
909 else if (errcode == -5)
910 yy_error_d("expression recursion loop detected");
912 yy_error_d("syntax error");
915 mode = t != 0 ? IF1_MODE : IF0_MODE;
917 } else if(state == IFD || state == IFND) {
918 /* save KEY from #if(n)def KEY ... */
927 yy_error_d("expected identifier");
928 v = lookup_key(id, id_len);
930 if(state == IFD && v == NULL)
932 else if(state == IFND && v != NULL)
935 } else if(state == EI) {
937 if(mode == CONFIG_MODE || mode == ELSE0_MODE || mode == ELSE1_MODE)
938 yy_error_d("unexpected #elif");
939 if(mode == IF0_MODE) {
946 } else if(state == E) {
947 if(mode == CONFIG_MODE || mode == ELSE0_MODE || mode == ELSE1_MODE)
948 yy_error_d("unexpected #else");
951 else if(mode == IF1_MODE)
954 } else if(state == D || state == U) {
955 /* save KEY from #"define"|"undef" ... */
961 yy_error_d("expected identifier");
963 if((mode & FALSE_MODES) == 0)
964 parse_conf_opt(id, NULL, id_len);
971 /* state==<DK> #define KEY[ ] */
972 size_t opt_len = id_len;
973 char *val = id + opt_len;
977 if(c == L_EOF || c == '\n')
984 /* trim tail spaces */
985 while(--sp >= val && (*sp == ' ' || *sp == '\t'
986 || *sp == '\f' || *sp == '\v'))
988 if((mode & FALSE_MODES) == 0)
989 parse_conf_opt(id, val, opt_len);
1002 yy_error_d("unexpected newline");
1004 } else if(c == L_EOF)
1005 yy_error_d("unexpected EOF");
1017 yy_error_d("phrase too long");
1020 /* trick for fast find "define", "include", "undef" */
1021 static const char first_chars_diu[UCHAR_MAX] = {
1022 [(int)'d'] = (char)5, /* strlen("define") - 1; */
1023 [(int)'i'] = (char)6, /* strlen("include") - 1; */
1024 [(int)'u'] = (char)4, /* strlen("undef") - 1; */
1030 #define D '5' /* #define preprocessor's directive */
1031 #define I '6' /* #include preprocessor's directive */
1032 #define U '4' /* #undef preprocessor's directive */
1034 /* stupid C lexical analyser for sources */
1035 static void c_lex_src(const char *fname, long fsize)
1041 size_t id_len = 0; /* stupid initialization */
1042 unsigned char *optr, *oend;
1049 fprintf(stderr, "Warning: %s is empty\n", fname);
1052 fd = open(fname, O_RDONLY);
1057 mapsize = (fsize+pagesizem1) & ~pagesizem1;
1058 map = mmap(NULL, mapsize, PROT_READ, MAP_PRIVATE, fd, 0);
1059 if ((long) map == -1)
1060 bb_error_d("%s: mmap: %m", fname);
1062 optr = (unsigned char *)map;
1063 oend = optr + fsize;
1071 /* [ \t]+ eat first space */
1072 while(c == ' ' || c == '\t')
1076 while(first_chars[c] == ANY) {
1084 munmap(map, mapsize);
1093 do getc0(); while(c != '\n' && c != L_EOF);
1094 } else if(c == '*') {
1095 /* <S>[/][*] goto parse block comments */
1098 } else if(c == POUND) {
1102 } else if(c == STR || c == CHR) {
1110 /* <STR>\" or <CHR>\' */
1114 /* <STR,CHR>\\ but is not <STR,CHR>\\\n */
1117 if(c == '\n' || c == L_EOF)
1118 yy_error_d("unterminated");
1122 /* <S>[A-Z_a-z0-9] */
1124 /* trick for fast drop id
1125 if key with this first char undefined */
1126 if(first_chars[c] == 0) {
1127 /* skip <S>[A-Z_a-z0-9]+ */
1128 do getc1(); while(isalnums[c]);
1132 /* <S>[A-Z_a-z0-9]+ */
1135 } while(isalnums[c]);
1136 check_key(key_top, id, id_len);
1141 /* begin preprocessor states */
1143 yy_error_d("unexpected EOF");
1148 yy_error_d("detected // in preprocessor line");
1150 /* <#.*>[/][*] goto parse block comments */
1154 yy_error_d("strange preprocessor line");
1156 if(state == POUND) {
1158 static const char * const p_preproc[] = {
1160 "", "", "", "", "ndef", "efine", "nclude"
1162 size_t diu = first_chars_diu[c]; /* strlen and p_preproc ptr */
1168 while(isalnums[c]) {
1172 /* str begins with c, read == strlen key and compared */
1173 if(diu == id_len && !memcmp(id, p_preproc[diu], diu)) {
1175 id_len = 0; /* common for save */
1178 while(isalnums[c]) getc1();
1180 } else if(state == I) {
1188 yy_error_d("unexpected EOF");
1192 /* store "include.h" */
1193 parse_inc(id, fname);
1196 /* else another (may be wrong) #include ... */
1198 } else /* if(state == D || state == U) */ {
1199 /* ignore depend with #define or #undef KEY */
1200 while(isalnums[c]) getc1();
1213 yy_error_d("unexpected newline");
1215 } else if(c == L_EOF)
1216 yy_error_d("unexpected EOF");
1228 yy_error_d("phrase too long");
1232 /* bb_simplify_path special variant for absolute pathname */
1233 static size_t bb_qa_simplify_path(char *path)
1241 if (*s == '/') { /* skip duplicate (or initial) slash */
1243 } else if (*s == '.') {
1244 if (s[1] == '/' || s[1] == 0) { /* remove extra '.' */
1246 } else if ((s[1] == '.') && (s[2] == '/' || s[2] == 0)) {
1249 while (*--p != '/'); /* omit previous dir */
1258 if ((p == path) || (*p != '/')) { /* not a trailing slash */
1259 ++p; /* so keep last character */
1266 static void parse_inc(const char *include, const char *fname)
1275 if(*include == '/') {
1277 ap = bb_xstrdup(include);
1283 p = strrchr(fname, '/'); /* fname has absolute pathname */
1285 /* find from current directory of source file */
1286 ap = bb_asprint("%.*s/%s", w, fname, include);
1290 key_sz = bb_qa_simplify_path(ap);
1291 cur = check_key(Ifound, ap, key_sz);
1293 cur->checked = cur->value;
1297 if(stat(ap, &st) == 0) {
1301 for(cfl = configs; cfl; cfl = cfl->link) {
1302 struct stat *config = (struct stat *)cfl->data;
1304 if (st.st_dev == config->st_dev && st.st_ino == config->st_ino) {
1305 /* skip depend with bb_configs.h */
1311 } else if(lo == NULL) {
1316 /* find from "-I include" specified directories */
1318 /* lo->data has absolute pathname */
1319 ap = bb_asprint("%s/%s", lo->data, include);
1323 cur = xmalloc(sizeof(bb_key_t));
1325 cur->key_sz = key_sz;
1326 cur->stored_path = ap;
1327 cur->value = cur->checked = p_i;
1328 if(p_i == NULL && noiwarning)
1329 fprintf(stderr, "%s: Warning: #include \"%s\" not found\n", fname, include);
1334 static size_t max_rec_sz;
1336 static void parse_conf_opt(const char *opt, const char *val, size_t key_sz)
1343 cur = check_key(key_top, opt, key_sz);
1345 /* already present */
1346 cur->checked = NULL; /* store only */
1347 if(cur->value == NULL && val == NULL)
1349 if(cur->value != NULL && val != NULL && !strcmp(cur->value, val))
1352 fprintf(stderr, "Warning: redefined %s\n", k);
1357 val_sz = strlen(val) + 1;
1358 recordsz = key_sz + val_sz + 1;
1359 if(max_rec_sz < recordsz)
1360 max_rec_sz = recordsz;
1361 cur = xmalloc(sizeof(bb_key_t) + recordsz);
1362 k = cur->keyname = memcpy(cur + 1, opt, key_sz);
1363 cur->keyname[key_sz] = '\0';
1364 cur->key_sz = key_sz;
1365 cur->checked = NULL;
1366 cur->src_have_this_key = NULL;
1367 cur->next = key_top;
1375 cur->value = p = cur->keyname + key_sz + 1;
1376 memcpy(p, val, val_sz);
1381 /* trick, save first char KEY for do fast identify id */
1382 first_chars[(int)*k] = *k;
1384 cur->stored_path = k = bb_asprint("%s/%s.h", kp, k);
1385 /* key conversion [A-Z_] -> [a-z/] */
1386 for(p = k + kp_len + 1; *p; p++) {
1387 if(*p >= 'A' && *p <= 'Z')
1388 *p = *p - 'A' + 'a';
1389 else if(*p == '_' && p[1] > '9') /* do not change A_1 to A/1 */
1394 static void store_keys(void)
1401 size_t recordsz = max_rec_sz * 2 + 10 * 2 + 16;
1402 /* buffer for double "#define KEY VAL\n" */
1403 char *record_buf = xmalloc(recordsz);
1405 for(cur = key_top; cur; cur = cur->next) {
1406 if(cur->src_have_this_key) {
1407 /* do generate record */
1409 if(cur->value == NULL) {
1410 recordsz = sprintf(record_buf, "#undef %s\n", k);
1412 const char *val = cur->value;
1414 recordsz = sprintf(record_buf, "#define %s\n", k);
1417 recordsz = sprintf(record_buf, "#define %s %s\n", k, val);
1419 recordsz = sprintf(record_buf, "#define %s%s\n", k, val);
1422 /* size_t -> ssize_t :( */
1423 rw_ret = (ssize_t)recordsz;
1424 /* check kp/key.h, compare after previous use */
1426 k = cur->stored_path;
1429 for(p = k + kp_len + 1; *p; p++) {
1430 /* Auto-create directories. */
1433 if (access(k, F_OK) != 0 && mkdir(k, 0755) != 0)
1434 bb_error_d("mkdir(%s): %m", k);
1440 if(st.st_size == (off_t)recordsz) {
1443 size_t padded = recordsz;
1445 /* 16-byte padding for read(2) and memcmp(3) */
1446 padded = (padded+15) & ~15;
1447 r_cmp = record_buf + padded;
1448 fd = open(k, O_RDONLY);
1449 if(fd < 0 || read(fd, r_cmp, recordsz) < rw_ret)
1450 bb_error_d("%s: %m", k);
1452 cmp_ok = memcmp(record_buf, r_cmp, recordsz) == 0;
1456 int fd = open(k, O_WRONLY|O_CREAT|O_TRUNC, 0644);
1457 if(fd < 0 || write(fd, record_buf, recordsz) < rw_ret)
1458 bb_error_d("%s: %m", k);
1465 static int show_dep(int first, bb_key_t *k, const char *name, const char *f)
1469 for(cur = k; cur; cur = cur->next) {
1474 printf("\n%s:", name);
1476 printf("\n%s/%s:", pwd, name);
1481 printf(" %s", cur->checked);
1483 cur->src_have_this_key = cur->checked;
1484 cur->checked = NULL;
1491 parse_chd(const char *fe, const char *p, size_t dirlen)
1496 static char dir_and_entry[4096];
1497 size_t fe_sz = strlen(fe) + 1;
1499 df_sz = dirlen + fe_sz + 1; /* dir/file\0 */
1500 if(df_sz > sizeof(dir_and_entry))
1501 bb_error_d("%s: file name too long", fe);
1503 /* sprintf(fp, "%s/%s", p, fe); */
1504 memcpy(fp, p, dirlen);
1506 memcpy(fp + dirlen + 1, fe, fe_sz);
1509 fprintf(stderr, "Warning: stat(%s): %m\n", fp);
1512 if(S_ISREG(st.st_mode)) {
1514 char *e = fp + df_sz - 3;
1516 if(*e++ != '.' || (*e != 'c' && *e != 'h')) {
1517 /* direntry is regular file, but is not *.[ch] */
1520 for(cfl = configs; cfl; cfl = cfl->link) {
1521 struct stat *config = (struct stat *)cfl->data;
1523 if (st.st_dev == config->st_dev && st.st_ino == config->st_ino) {
1524 /* skip already parsed bb_configs.h */
1528 /* direntry is *.[ch] regular file and is not configs */
1529 c_lex_src(fp, st.st_size);
1530 if(!dontgenerate_dep) {
1535 /* /src_dir/path/file.o to path/file.o */
1542 first = show_dep(1, Ifound, fp, e);
1543 first = show_dep(first, key_top, fp, e);
1547 show_dep(-1, key_top, NULL, NULL);
1550 } else if(S_ISDIR(st.st_mode)) {
1551 if (st.st_dev == st_kp.st_dev && st.st_ino == st_kp.st_ino)
1552 return NULL; /* drop scan kp/ directory */
1553 /* direntry is directory. buff is returned */
1554 return bb_xstrdup(fp);
1556 /* hmm, direntry is device! */
1560 /* from libbb but inlined for speed considerations */
1561 static inline llist_t *llist_add_to(llist_t *old_head, char *new_item)
1565 new_head = xmalloc(sizeof(llist_t));
1566 new_head->data = new_item;
1567 new_head->link = old_head;
1572 static void scan_dir_find_ch_files(const char *p)
1581 dirs = llist_add_to(NULL, bb_simplify_path(p));
1582 replace = strlen(dirs->data);
1583 /* emulate recursion */
1587 dir = opendir(dirs->data);
1589 fprintf(stderr, "Warning: opendir(%s): %m\n", dirs->data);
1590 dirlen = strlen(dirs->data);
1591 while ((de = readdir(dir)) != NULL) {
1594 if (de->d_name[0] == '.')
1596 found_dir = parse_chd(de->d_name, dirs->data, dirlen);
1598 d_add = llist_add_to(d_add, found_dir);
1610 static void show_usage(void) ATTRIBUTE ((noreturn));
1611 static void show_usage(void)
1613 bb_error_d("%s\n%s\n", bb_mkdep_terse_options, bb_mkdep_full_options);
1616 int main(int argc, char **argv)
1623 /* for bb_simplify_path, this program has no chdir() */
1624 /* libbb-like my xgetcwd() */
1625 unsigned path_max = 512;
1627 s = xmalloc (path_max);
1628 while (getcwd (s, path_max) == NULL) {
1630 bb_error_d("getcwd: %m");
1632 s = xmalloc(path_max *= 2);
1637 while ((i = getopt(argc, argv, "I:c:dk:w")) > 0) {
1640 s = bb_simplify_path(optarg);
1641 Iop = llist_add_to(Iop, s);
1644 s = bb_simplify_path(optarg);
1645 configs = llist_add_to(configs, s);
1648 dontgenerate_dep = 1;
1652 bb_error_d("Hmm, why multiple -k?");
1653 kp = bb_simplify_path(optarg);
1664 kp = bb_simplify_path(INCLUDE_CONFIG_PATH);
1665 /* globals initialize */
1666 kp_len = strlen(kp);
1667 if(stat(kp, &st_kp))
1668 bb_error_d("stat(%s): %m", kp);
1669 if(!S_ISDIR(st_kp.st_mode))
1670 bb_error_d("%s is not directory", kp);
1673 Iop = llist_add_to(Iop, bb_simplify_path(LOCAL_INCLUDE_PATH));
1674 if(configs == NULL) {
1675 s = bb_simplify_path(INCLUDE_CONFIG_KEYS_PATH);
1676 configs = llist_add_to(configs, s);
1679 pagesizem1 = getpagesize() - 1;
1680 for(i = 0; i < UCHAR_MAX; i++) {
1683 /* set unparsed chars to speed up the parser */
1684 else if(i != CHR && i != STR && i != POUND && i != REM)
1685 first_chars[i] = ANY;
1687 first_chars[i] = '-'; /* L_EOF */
1690 for(fl = configs; fl; fl = fl->link) {
1693 if(stat(fl->data, &st))
1694 bb_error_d("stat(%s): %m", fl->data);
1695 c_lex_config(fl->data, st.st_size);
1697 /* trick for fast comparing found files with configs */
1698 fl->data = xmalloc(sizeof(struct stat));
1699 memcpy(fl->data, &st, sizeof(struct stat));
1706 scan_dir_find_ch_files(*argv++);
1708 scan_dir_find_ch_files(".");
1714 /* partial and simplified libbb routine */
1715 static void bb_error_d(const char *s, ...)
1720 vfprintf(stderr, s, p);
1726 static char *bb_asprint(const char *format, ...)
1733 va_start(p, format);
1734 r = vasprintf(&out, format, p);
1737 out = xmalloc(BUFSIZ);
1738 va_start(p, format);
1739 r = vsprintf(out, format, p);
1744 bb_error_d("bb_asprint: %m");
1748 /* partial libbb routine as is */
1750 static char *bb_simplify_path(const char *path)
1752 char *s, *start, *p;
1755 start = bb_xstrdup(path);
1757 /* is not libbb, but this program has no chdir() */
1758 start = bb_asprint("%s/%s", pwd, path);
1764 if (*s == '/') { /* skip duplicate (or initial) slash */
1766 } else if (*s == '.') {
1767 if (s[1] == '/' || s[1] == 0) { /* remove extra '.' */
1769 } else if ((s[1] == '.') && (s[2] == '/' || s[2] == 0)) {
1772 while (*--p != '/'); /* omit previous dir */
1781 if ((p == start) || (*p != '/')) { /* not a trailing slash */
1782 ++p; /* so keep last character */