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 /* partial and simplified libbb routine */
74 static void bb_error_d(const char *s, ...) __attribute__ ((noreturn, format (printf, 1, 2)));
75 static char * bb_asprint(const char *format, ...) __attribute__ ((format (printf, 1, 2)));
76 static char *bb_simplify_path(const char *path);
78 /* stolen from libbb as is */
79 typedef struct llist_s {
84 static const char msg_enomem[] = "memory exhausted";
86 /* inline realization for fast works */
87 static inline void *xmalloc(size_t size)
89 void *p = malloc(size);
92 bb_error_d(msg_enomem);
96 static inline char *bb_xstrdup(const char *s)
101 bb_error_d(msg_enomem);
106 static int dontgenerate_dep; /* flag -d usaged */
107 static int noiwarning; /* flag -w usaged */
108 static llist_t *configs; /* list of -c usaged and them stat() after parsed */
109 static llist_t *Iop; /* list of -I include usaged */
111 static char *pwd; /* current work directory */
112 static size_t replace; /* replace current work directory with build dir */
114 static const char *kp; /* KEY path, argument of -k used */
115 static size_t kp_len;
116 static struct stat st_kp; /* stat(kp) */
118 typedef struct BB_KEYS {
124 const char *src_have_this_key;
125 struct BB_KEYS *next;
128 static bb_key_t *key_top; /* list of found KEYs */
129 static bb_key_t *Ifound; /* list of parsed includes */
132 static void parse_conf_opt(const char *opt, const char *val, size_t key_sz);
133 static void parse_inc(const char *include, const char *fname);
135 static inline bb_key_t *check_key(bb_key_t *k, const char *nk, size_t key_sz)
139 for(cur = k; cur; cur = cur->next) {
140 if(key_sz == cur->key_sz && memcmp(cur->keyname, nk, key_sz) == 0) {
141 cur->checked = cur->stored_path;
148 static inline const char *lookup_key(const char *nk, size_t key_sz)
152 for(cur = key_top; cur; cur = cur->next) {
153 if(key_sz == cur->key_sz && memcmp(cur->keyname, nk, key_sz) == 0) {
160 /* for lexical analyser */
161 static int pagesizem1; /* padding mask = getpagesize() - 1 */
163 /* for speed tricks */
164 static char first_chars[1+UCHAR_MAX]; /* + L_EOF */
165 static char isalnums[1+UCHAR_MAX]; /* + L_EOF */
167 /* trick for fast find "define", "include", "undef",
168 "if((n)def)" "else", "endif" */
169 static const char * const preproc[] = {
170 /* 0 1 2 3 4 5 6 7 8 9 */
171 "", "efine", "lif", "lse", "ndif", "f", "fdef", "fndef", "nclude", "ndef" };
172 static const unsigned char first_chars_deiu[UCHAR_MAX] = {
173 [(int)'d'] = (unsigned char)(1|0x10), /* define */
174 [(int)'e'] = (unsigned char)(2|0x40), /* elif, else, endif */
175 [(int)'i'] = (unsigned char)(5|0x80), /* if ifdef ifndef include */
176 [(int)'u'] = (unsigned char)(9|0x90), /* undef */
179 #define CONFIG_MODE 0
180 #define IF0_MODE 1 /* #if 0 */
181 #define IF1_MODE 2 /* #if 1 */
182 #define ELSE0_MODE 4 /* #else found after #if 0 */
183 #define ELSE1_MODE 8 /* #else found after #if 1 */
184 #define ELIF1_MODE 16 /* #elif found after #if 1 */
185 #define FALSE_MODES (IF0_MODE|ELSE1_MODE|ELIF1_MODE)
187 #define yy_error_d(s) bb_error_d("%s:%d hmm, %s", fname, line, s)
190 #define S 0 /* start state */
191 #define STR '"' /* string */
192 #define CHR '\'' /* char */
193 #define REM '/' /* block comment */
194 #define BS '\\' /* back slash */
195 #define POUND '#' /* # */
196 #define D '1' /* #define preprocessor's directive */
197 #define EI '2' /* #elif preprocessor's directive */
198 #define E '3' /* #else preprocessor's directive */
199 #define EF '4' /* #endif preprocessor's directive */
200 #define F '5' /* #if preprocessor's directive */
201 #define IFD '6' /* #ifdef preprocessor's directive */
202 #define IFND '7' /* #ifndef preprocessor's directive */
203 #define I '8' /* #include preprocessor's directive */
204 #define U '9' /* #undef preprocessor's directive */
205 #define DK 'K' /* #define KEY... (config mode) */
206 #define ANY '*' /* any unparsed chars */
209 #define ID(c) ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_')
211 #define ISALNUM(c) (ID(c) || (c >= '0' && c <= '9'))
213 #define L_EOF (1+UCHAR_MAX)
215 #define getc0() do { c = (optr >= oend) ? L_EOF : *optr++; } while(0)
217 #define getc1() do { getc0(); if(c == BS) { getc0(); \
218 if(c == '\n') { line++; continue; } \
219 else { optr--; c = BS; } \
222 static char id_s[4096];
223 #define put_id(ic) do { if(id_len == sizeof(id_s)) goto too_long; \
224 id[id_len++] = ic; } while(0)
226 static char ifcpp_stack[1024];
227 static int ptr_ifcpp_stack;
228 #define push_mode() do { \
229 if(ptr_ifcpp_stack == (int)sizeof(ifcpp_stack)) \
230 yy_error_d("#if* stack overflow"); \
231 ifcpp_stack[ptr_ifcpp_stack++] = (char)mode; \
234 #define pop_mode() do { \
235 if(ptr_ifcpp_stack == 0) \
236 yy_error_d("unexpected #endif"); \
237 mode = ifcpp_stack[--ptr_ifcpp_stack]; \
241 typedef long long arith_t;
243 static arith_t arith (const char *expr, int *perrcode);
245 /* The code uses a simple two-stack algorithm. See
246 * http://www.onthenet.com.au/~grahamis/int2008/week02/lect02.html
247 * for a detailed explanation of the infix-to-postfix algorithm on which
248 * this is based (this code differs in that it applies operators immediately
249 * to the stack instead of adding them to a queue to end up with an
252 #define arith_isspace(arithval) \
253 (arithval == ' ' || arithval == '\v' || arithval == '\t' || arithval == '\f')
256 typedef unsigned char operator;
258 /* An operator's token id is a bit of a bitfield. The lower 5 bits are the
259 * precedence, and 3 high bits are an ID unique across operators of that
260 * precedence. The ID portion is so that multiple operators can have the
261 * same precedence, ensuring that the leftmost one is evaluated first.
262 * Consider * and /. */
264 #define tok_decl(prec,id) (((id)<<5)|(prec))
265 #define PREC(op) ((op) & 0x1F)
267 #define TOK_LPAREN tok_decl(0,0)
269 #define TOK_COMMA tok_decl(1,0)
271 /* conditional is right associativity too */
272 #define TOK_CONDITIONAL tok_decl(2,0)
273 #define TOK_CONDITIONAL_SEP tok_decl(2,1)
275 #define TOK_OR tok_decl(3,0)
277 #define TOK_AND tok_decl(4,0)
279 #define TOK_BOR tok_decl(5,0)
281 #define TOK_BXOR tok_decl(6,0)
283 #define TOK_BAND tok_decl(7,0)
285 #define TOK_EQ tok_decl(8,0)
286 #define TOK_NE tok_decl(8,1)
288 #define TOK_LT tok_decl(9,0)
289 #define TOK_GT tok_decl(9,1)
290 #define TOK_GE tok_decl(9,2)
291 #define TOK_LE tok_decl(9,3)
293 #define TOK_LSHIFT tok_decl(10,0)
294 #define TOK_RSHIFT tok_decl(10,1)
296 #define TOK_ADD tok_decl(11,0)
297 #define TOK_SUB tok_decl(11,1)
299 #define TOK_MUL tok_decl(12,0)
300 #define TOK_DIV tok_decl(12,1)
301 #define TOK_REM tok_decl(12,2)
303 /* For now unary operators. */
305 #define TOK_BNOT tok_decl(UNARYPREC,0)
306 #define TOK_NOT tok_decl(UNARYPREC,1)
308 #define TOK_UMINUS tok_decl(UNARYPREC+1,0)
309 #define TOK_UPLUS tok_decl(UNARYPREC+1,1)
311 #define SPEC_PREC (UNARYPREC+2)
313 #define TOK_NUM tok_decl(SPEC_PREC, 0)
314 #define TOK_RPAREN tok_decl(SPEC_PREC, 1)
316 #define NUMPTR (*numstackptr)
318 typedef struct ARITCH_VAR_NUM {
320 arith_t contidional_second_val;
321 char contidional_second_val_initialized;
325 typedef struct CHK_VAR_RECURSIVE_LOOPED {
328 struct CHK_VAR_RECURSIVE_LOOPED *next;
329 } chk_var_recursive_looped_t;
331 static chk_var_recursive_looped_t *prev_chk_var_recursive;
334 static int arith_lookup_val(const char *var, size_t key_sz, arith_t *pval)
336 const char * p = lookup_key(var, key_sz);
341 /* recursive try as expression */
342 chk_var_recursive_looped_t *cur;
343 chk_var_recursive_looped_t cur_save;
345 for(cur = prev_chk_var_recursive; cur; cur = cur->next) {
346 if(cur->var_sz == key_sz && memcmp(cur->var, var, key_sz) == 0) {
347 /* expression recursion loop detected */
351 /* save current lookuped var name */
352 cur = prev_chk_var_recursive;
354 cur_save.var_sz = key_sz;
356 prev_chk_var_recursive = &cur_save;
358 *pval = arith (p, &errcode);
359 /* restore previous ptr after recursiving */
360 prev_chk_var_recursive = cur;
363 /* disallow undefined var */
364 fprintf(stderr, "%.*s ", (int)key_sz, var);
369 /* "applying" a token means performing it on the top elements on the integer
370 * stack. For a unary operator it will only change the top element, but a
371 * binary operator will pop two arguments and push a result */
373 arith_apply(operator op, v_n_t *numstack, v_n_t **numstackptr)
376 arith_t numptr_val, rez;
378 if (NUMPTR == numstack) goto err; /* There is no operator that can work
380 numptr_m1 = NUMPTR - 1;
382 rez = numptr_m1->val;
383 if (op == TOK_UMINUS)
385 else if (op == TOK_NOT)
387 else if (op == TOK_BNOT)
389 else if (op != TOK_UPLUS) {
390 /* Binary operators */
392 /* check and binary operators need two arguments */
393 if (numptr_m1 == numstack) goto err;
395 /* ... and they pop one */
398 if (op == TOK_CONDITIONAL) {
399 if(! numptr_m1->contidional_second_val_initialized) {
400 /* protect $((expr1 ? expr2)) without ": expr" */
403 rez = numptr_m1->contidional_second_val;
404 } else if(numptr_m1->contidional_second_val_initialized) {
405 /* protect $((expr1 : expr2)) without "expr ? " */
408 numptr_m1 = NUMPTR - 1;
409 if (op == TOK_CONDITIONAL) {
410 numptr_m1->contidional_second_val = rez;
412 rez = numptr_m1->val;
415 else if (op == TOK_OR)
416 rez = numptr_val || rez;
417 else if (op == TOK_BAND)
419 else if (op == TOK_BXOR)
421 else if (op == TOK_AND)
422 rez = rez && numptr_val;
423 else if (op == TOK_EQ)
424 rez = (rez == numptr_val);
425 else if (op == TOK_NE)
426 rez = (rez != numptr_val);
427 else if (op == TOK_GE)
428 rez = (rez >= numptr_val);
429 else if (op == TOK_RSHIFT)
431 else if (op == TOK_LSHIFT)
433 else if (op == TOK_GT)
434 rez = (rez > numptr_val);
435 else if (op == TOK_LT)
436 rez = (rez < numptr_val);
437 else if (op == TOK_LE)
438 rez = (rez <= numptr_val);
439 else if (op == TOK_MUL)
441 else if (op == TOK_ADD)
443 else if (op == TOK_SUB)
445 else if (op == TOK_COMMA)
447 else if (op == TOK_CONDITIONAL_SEP) {
448 if (numptr_m1 == numstack) {
449 /* protect $((expr : expr)) without "expr ? " */
452 numptr_m1->contidional_second_val_initialized = op;
453 numptr_m1->contidional_second_val = numptr_val;
455 else if (op == TOK_CONDITIONAL) {
457 numptr_val : numptr_m1->contidional_second_val;
459 else if(numptr_val==0) /* zero divisor check */
461 else if (op == TOK_DIV)
463 else if (op == TOK_REM)
466 numptr_m1->val = rez;
471 /* longest must first */
472 static const char op_tokens[] = {
473 '<','<', 0, TOK_LSHIFT,
474 '>','>', 0, TOK_RSHIFT,
494 '?', 0, TOK_CONDITIONAL,
495 ':', 0, TOK_CONDITIONAL_SEP,
501 #define endexpression &op_tokens[sizeof(op_tokens)-7]
504 * Return of a legal variable name (a letter or underscore followed by zero or
505 * more letters, underscores, and digits).
509 endofname(const char *name)
524 static arith_t arith (const char *expr, int *perrcode)
526 char arithval; /* Current character under analysis */
527 operator lasttok, op;
530 const char *p = endexpression;
533 size_t datasizes = strlen(expr) + 2;
535 /* Stack of integers */
536 /* The proof that there can be no more than strlen(startbuf)/2+1 integers
537 * in any given correct or incorrect expression is left as an exercise to
539 v_n_t *numstack = alloca(((datasizes)/2)*sizeof(v_n_t)),
540 *numstackptr = numstack;
541 /* Stack of operator tokens */
542 operator *stack = alloca((datasizes) * sizeof(operator)),
545 *stackptr++ = lasttok = TOK_LPAREN; /* start off with a left paren */
546 *perrcode = errcode = 0;
549 if ((arithval = *expr) == 0) {
550 if (p == endexpression) {
551 /* Null expression. */
553 return (*perrcode = -1);
556 /* This is only reached after all tokens have been extracted from the
557 * input stream. If there are still tokens on the operator stack, they
558 * are to be applied in order. At the end, there should be a final
559 * result on the integer stack */
561 if (expr != endexpression + 1) {
562 /* If we haven't done so already, */
563 /* append a closing right paren */
564 expr = endexpression;
565 /* and let the loop process it. */
568 /* At this point, we're done with the expression. */
569 if (numstackptr != numstack+1) {
570 /* ... but if there isn't, it's bad */
575 return numstack->val;
577 /* Continue processing the expression. */
578 if (arith_isspace(arithval)) {
579 /* Skip whitespace */
582 if((p = endofname(expr)) != expr) {
583 size_t var_name_size = (p-expr);
585 if(var_name_size == 7 &&
586 strncmp(expr, "defined", var_name_size) == 0) {
590 while(arith_isspace(*p)) p++;
593 while(arith_isspace(*p)) p++;
597 if((p = endofname(expr)) == expr)
599 var_name_size = (p-expr);
600 while(arith_isspace(*p)) p++;
601 if(brace_form && *p++ != ')')
603 v = lookup_key(expr, var_name_size);
604 numstackptr->val = (v != NULL) ? 1 : 0;
606 errcode = arith_lookup_val(expr, var_name_size,
607 &(numstackptr->val));
608 if(errcode) goto ret;
612 numstackptr->contidional_second_val_initialized = 0;
616 } else if (arithval >= '0' && arithval <= '9') {
617 numstackptr->val = strtoll(expr, (char **) &expr, 0);
618 while(*expr == 'l' || *expr == 'L' || *expr == 'u' ||
623 for(p = op_tokens; ; p++) {
627 /* strange operator not found */
630 for(o = expr; *p && *o == *p; p++)
637 /* skip tail uncompared token */
640 /* skip zero delim */
645 /* Plus and minus are binary (not unary) _only_ if the last
646 * token was as number, or a right paren (which pretends to be
647 * a number, since it evaluates to one). Think about it.
649 if (lasttok != TOK_NUM) {
652 else if(op == TOK_SUB)
655 /* We don't want a unary operator to cause recursive descent on the
656 * stack, because there can be many in a row and it could cause an
657 * operator to be evaluated before its argument is pushed onto the
659 /* But for binary operators, "apply" everything on the operator
660 * stack until we find an operator with a lesser priority than the
661 * one we have just extracted. */
662 /* Left paren is given the lowest priority so it will never be
663 * "applied" in this way.
664 * if associativity is right and priority eq, applied also skip
667 if ((prec > 0 && prec < UNARYPREC) || prec == SPEC_PREC) {
668 /* not left paren or unary */
669 if (lasttok != TOK_NUM) {
670 /* binary op must be preceded by a num */
673 while (stackptr != stack) {
674 if (op == TOK_RPAREN) {
675 /* The algorithm employed here is simple: while we don't
676 * hit an open paren nor the bottom of the stack, pop
677 * tokens and apply them */
678 if (stackptr[-1] == TOK_LPAREN) {
680 /* Any operator directly after a */
682 /* close paren should consider itself binary */
686 operator prev_prec = PREC(stackptr[-1]);
688 if (prev_prec < prec)
690 /* check right assoc */
691 if(prev_prec == prec && prec == PREC(TOK_CONDITIONAL))
694 errcode = arith_apply(*--stackptr, numstack, &numstackptr);
695 if(errcode) goto ret;
697 if (op == TOK_RPAREN) {
702 /* Push this operator to the stack and remember it. */
703 *stackptr++ = lasttok = op;
711 /* stupid C lexical analyser for configs.h */
712 static void c_lex_config(const char *fname, long fsize)
718 size_t id_len = 0; /* stupid initialization */
719 unsigned char *optr, *oend;
720 int mode = CONFIG_MODE;
727 fprintf(stderr, "Warning: %s is empty\n", fname);
730 fd = open(fname, O_RDONLY);
735 mapsize = (fsize+pagesizem1) & ~pagesizem1;
736 map = mmap(NULL, mapsize, PROT_READ, MAP_PRIVATE, fd, 0);
737 if ((long) map == -1)
738 bb_error_d("%s: mmap: %m", fname);
740 optr = (unsigned char *)map;
749 /* [ \t]+ eat first space */
750 while(c == ' ' || c == '\t')
754 while(first_chars[c] == ANY) {
762 munmap(map, mapsize);
764 if(mode != CONFIG_MODE)
765 yy_error_d("expected #endif");
773 do getc0(); while(c != '\n' && c != L_EOF);
774 } else if(c == '*') {
775 /* <S>[/][*] goto parse block comments */
778 } else if(c == POUND) {
782 } else if(c == STR || c == CHR) {
790 /* <STR>\" or <CHR>\' */
794 /* <STR,CHR>\\ but is not <STR,CHR>\\\n */
797 if(c == '\n' || c == L_EOF)
798 yy_error_d("unterminated");
802 /* <S>[A-Z_a-z0-9] */
804 /* trick for fast drop id
805 if key with this first char undefined */
806 if(first_chars[c] == 0 || (mode & FALSE_MODES) != 0) {
807 /* skip <S>[A-Z_a-z0-9]+ */
808 do getc1(); while(isalnums[c]);
812 /* <S>[A-Z_a-z0-9]+ */
815 } while(isalnums[c]);
816 check_key(key_top, id, id_len);
821 /* begin preprocessor states */
823 yy_error_d("unexpected EOF");
828 yy_error_d("detected // in preprocessor line");
830 /* <#.*>[/][*] goto parse block comments */
834 yy_error_d("strange preprocessor line");
838 int diu = (int)first_chars_deiu[c]; /* preproc ptr */
842 int p_num_str, p_num_max;
851 p_num_str = diu & 0xf;
852 p_num_max = diu >> 4;
853 for(diu = p_num_str; diu <= p_num_max; diu++)
854 if(!strcmp(id, preproc[diu])) {
861 while(isalnums[c]) getc1();
863 } else if(state == EF) {
867 } else if(state == I) {
868 if(c == STR && (mode & FALSE_MODES) == 0) {
875 yy_error_d("unexpected EOF");
879 /* store "include.h" */
880 parse_inc(id, fname);
883 /* else another (may be wrong) #include ... */
885 } else if(state == F) {
889 while(c != '\n' && c != L_EOF) {
894 t = arith(id, &errcode);
897 yy_error_d("divide by zero");
898 else if (errcode == -4)
899 yy_error_d("undefined");
900 else if (errcode == -5)
901 yy_error_d("expression recursion loop detected");
903 yy_error_d("syntax error");
906 mode = t != 0 ? IF1_MODE : IF0_MODE;
908 } else if(state == IFD || state == IFND) {
909 /* save KEY from #if(n)def KEY ... */
918 yy_error_d("expected identifier");
919 v = lookup_key(id, id_len);
921 if(state == IFD && v == NULL)
923 else if(state == IFND && v != NULL)
926 } else if(state == EI) {
928 if(mode == CONFIG_MODE || mode == ELSE0_MODE || mode == ELSE1_MODE)
929 yy_error_d("unexpected #elif");
930 if(mode == IF0_MODE) {
937 } else if(state == E) {
938 if(mode == CONFIG_MODE || mode == ELSE0_MODE || mode == ELSE1_MODE)
939 yy_error_d("unexpected #else");
942 else if(mode == IF1_MODE)
945 } else if(state == D || state == U) {
946 /* save KEY from #"define"|"undef" ... */
952 yy_error_d("expected identifier");
954 if((mode & FALSE_MODES) == 0)
955 parse_conf_opt(id, NULL, id_len);
962 /* state==<DK> #define KEY[ ] */
963 size_t opt_len = id_len;
964 char *val = id + opt_len;
968 if(c == L_EOF || c == '\n')
975 /* trim tail spaces */
976 while(--sp >= val && (*sp == ' ' || *sp == '\t'
977 || *sp == '\f' || *sp == '\v'))
979 if((mode & FALSE_MODES) == 0)
980 parse_conf_opt(id, val, opt_len);
993 yy_error_d("unexpected newline");
995 } else if(c == L_EOF)
996 yy_error_d("unexpected EOF");
1008 yy_error_d("phrase too long");
1011 /* trick for fast find "define", "include", "undef" */
1012 static const char first_chars_diu[UCHAR_MAX] = {
1013 [(int)'d'] = (char)5, /* strlen("define") - 1; */
1014 [(int)'i'] = (char)6, /* strlen("include") - 1; */
1015 [(int)'u'] = (char)4, /* strlen("undef") - 1; */
1021 #define D '5' /* #define preprocessor's directive */
1022 #define I '6' /* #include preprocessor's directive */
1023 #define U '4' /* #undef preprocessor's directive */
1025 /* stupid C lexical analyser for sources */
1026 static void c_lex_src(const char *fname, long fsize)
1032 size_t id_len = 0; /* stupid initialization */
1033 unsigned char *optr, *oend;
1040 fprintf(stderr, "Warning: %s is empty\n", fname);
1043 fd = open(fname, O_RDONLY);
1048 mapsize = (fsize+pagesizem1) & ~pagesizem1;
1049 map = mmap(NULL, mapsize, PROT_READ, MAP_PRIVATE, fd, 0);
1050 if ((long) map == -1)
1051 bb_error_d("%s: mmap: %m", fname);
1053 optr = (unsigned char *)map;
1054 oend = optr + fsize;
1062 /* [ \t]+ eat first space */
1063 while(c == ' ' || c == '\t')
1067 while(first_chars[c] == ANY) {
1075 munmap(map, mapsize);
1084 do getc0(); while(c != '\n' && c != L_EOF);
1085 } else if(c == '*') {
1086 /* <S>[/][*] goto parse block comments */
1089 } else if(c == POUND) {
1093 } else if(c == STR || c == CHR) {
1101 /* <STR>\" or <CHR>\' */
1105 /* <STR,CHR>\\ but is not <STR,CHR>\\\n */
1108 if(c == '\n' || c == L_EOF)
1109 yy_error_d("unterminated");
1113 /* <S>[A-Z_a-z0-9] */
1115 /* trick for fast drop id
1116 if key with this first char undefined */
1117 if(first_chars[c] == 0) {
1118 /* skip <S>[A-Z_a-z0-9]+ */
1119 do getc1(); while(isalnums[c]);
1123 /* <S>[A-Z_a-z0-9]+ */
1126 } while(isalnums[c]);
1127 check_key(key_top, id, id_len);
1132 /* begin preprocessor states */
1134 yy_error_d("unexpected EOF");
1139 yy_error_d("detected // in preprocessor line");
1141 /* <#.*>[/][*] goto parse block comments */
1145 yy_error_d("strange preprocessor line");
1147 if(state == POUND) {
1149 static const char * const p_preproc[] = {
1151 "", "", "", "", "ndef", "efine", "nclude"
1153 size_t diu = first_chars_diu[c]; /* strlen and p_preproc ptr */
1159 while(isalnums[c]) {
1163 /* str begins with c, read == strlen key and compared */
1164 if(diu == id_len && !memcmp(id, p_preproc[diu], diu)) {
1166 id_len = 0; /* common for save */
1169 while(isalnums[c]) getc1();
1171 } else if(state == I) {
1179 yy_error_d("unexpected EOF");
1183 /* store "include.h" */
1184 parse_inc(id, fname);
1187 /* else another (may be wrong) #include ... */
1189 } else /* if(state == D || state == U) */ {
1190 /* ignore depend with #define or #undef KEY */
1191 while(isalnums[c]) getc1();
1204 yy_error_d("unexpected newline");
1206 } else if(c == L_EOF)
1207 yy_error_d("unexpected EOF");
1219 yy_error_d("phrase too long");
1223 /* bb_simplify_path special variant for absolute pathname */
1224 static size_t bb_qa_simplify_path(char *path)
1232 if (*s == '/') { /* skip duplicate (or initial) slash */
1234 } else if (*s == '.') {
1235 if (s[1] == '/' || s[1] == 0) { /* remove extra '.' */
1237 } else if ((s[1] == '.') && (s[2] == '/' || s[2] == 0)) {
1240 while (*--p != '/'); /* omit previous dir */
1249 if ((p == path) || (*p != '/')) { /* not a trailing slash */
1250 ++p; /* so keep last character */
1257 static void parse_inc(const char *include, const char *fname)
1266 if(*include == '/') {
1268 ap = bb_xstrdup(include);
1274 p = strrchr(fname, '/'); /* fname has absolute pathname */
1276 /* find from current directory of source file */
1277 ap = bb_asprint("%.*s/%s", w, fname, include);
1281 key_sz = bb_qa_simplify_path(ap);
1282 cur = check_key(Ifound, ap, key_sz);
1284 cur->checked = cur->value;
1288 if(stat(ap, &st) == 0) {
1292 for(cfl = configs; cfl; cfl = cfl->link) {
1293 struct stat *config = (struct stat *)cfl->data;
1295 if (st.st_dev == config->st_dev && st.st_ino == config->st_ino) {
1296 /* skip depend with bb_configs.h */
1302 } else if(lo == NULL) {
1307 /* find from "-I include" specified directories */
1309 /* lo->data has absolute pathname */
1310 ap = bb_asprint("%s/%s", lo->data, include);
1314 cur = xmalloc(sizeof(bb_key_t));
1316 cur->key_sz = key_sz;
1317 cur->stored_path = ap;
1318 cur->value = cur->checked = p_i;
1319 if(p_i == NULL && noiwarning)
1320 fprintf(stderr, "%s: Warning: #include \"%s\" not found\n", fname, include);
1325 static size_t max_rec_sz;
1327 static void parse_conf_opt(const char *opt, const char *val, size_t key_sz)
1334 cur = check_key(key_top, opt, key_sz);
1336 /* already present */
1337 cur->checked = NULL; /* store only */
1338 if(cur->value == NULL && val == NULL)
1340 if(cur->value != NULL && val != NULL && !strcmp(cur->value, val))
1343 fprintf(stderr, "Warning: redefined %s\n", k);
1348 val_sz = strlen(val) + 1;
1349 recordsz = key_sz + val_sz + 1;
1350 if(max_rec_sz < recordsz)
1351 max_rec_sz = recordsz;
1352 cur = xmalloc(sizeof(bb_key_t) + recordsz);
1353 k = cur->keyname = memcpy(cur + 1, opt, key_sz);
1354 cur->keyname[key_sz] = '\0';
1355 cur->key_sz = key_sz;
1356 cur->checked = NULL;
1357 cur->src_have_this_key = NULL;
1358 cur->next = key_top;
1366 cur->value = p = cur->keyname + key_sz + 1;
1367 memcpy(p, val, val_sz);
1372 /* trick, save first char KEY for do fast identify id */
1373 first_chars[(int)*k] = *k;
1375 cur->stored_path = k = bb_asprint("%s/%s.h", kp, k);
1376 /* key conversion [A-Z_] -> [a-z/] */
1377 for(p = k + kp_len + 1; *p; p++) {
1378 if(*p >= 'A' && *p <= 'Z')
1379 *p = *p - 'A' + 'a';
1380 else if(*p == '_' && p[1] > '9') /* do not change A_1 to A/1 */
1385 static void store_keys(void)
1392 size_t recordsz = max_rec_sz * 2 + 10 * 2 + 16;
1393 /* buffer for double "#define KEY VAL\n" */
1394 char *record_buf = xmalloc(recordsz);
1396 for(cur = key_top; cur; cur = cur->next) {
1397 if(cur->src_have_this_key) {
1398 /* do generate record */
1400 if(cur->value == NULL) {
1401 recordsz = sprintf(record_buf, "#undef %s\n", k);
1403 const char *val = cur->value;
1405 recordsz = sprintf(record_buf, "#define %s\n", k);
1408 recordsz = sprintf(record_buf, "#define %s %s\n", k, val);
1410 recordsz = sprintf(record_buf, "#define %s%s\n", k, val);
1413 /* size_t -> ssize_t :( */
1414 rw_ret = (ssize_t)recordsz;
1415 /* check kp/key.h, compare after previous use */
1417 k = cur->stored_path;
1420 for(p = k + kp_len + 1; *p; p++) {
1421 /* Auto-create directories. */
1424 if (access(k, F_OK) != 0 && mkdir(k, 0755) != 0)
1425 bb_error_d("mkdir(%s): %m", k);
1431 if(st.st_size == (off_t)recordsz) {
1434 size_t padded = recordsz;
1436 /* 16-byte padding for read(2) and memcmp(3) */
1437 padded = (padded+15) & ~15;
1438 r_cmp = record_buf + padded;
1439 fd = open(k, O_RDONLY);
1440 if(fd < 0 || read(fd, r_cmp, recordsz) < rw_ret)
1441 bb_error_d("%s: %m", k);
1443 cmp_ok = memcmp(record_buf, r_cmp, recordsz) == 0;
1447 int fd = open(k, O_WRONLY|O_CREAT|O_TRUNC, 0644);
1448 if(fd < 0 || write(fd, record_buf, recordsz) < rw_ret)
1449 bb_error_d("%s: %m", k);
1456 static int show_dep(int first, bb_key_t *k, const char *name, const char *f)
1460 for(cur = k; cur; cur = cur->next) {
1465 printf("\n%s:", name);
1467 printf("\n%s/%s:", pwd, name);
1472 printf(" %s", cur->checked);
1474 cur->src_have_this_key = cur->checked;
1475 cur->checked = NULL;
1482 parse_chd(const char *fe, const char *p, size_t dirlen)
1487 static char dir_and_entry[4096];
1488 size_t fe_sz = strlen(fe) + 1;
1490 df_sz = dirlen + fe_sz + 1; /* dir/file\0 */
1491 if(df_sz > sizeof(dir_and_entry))
1492 bb_error_d("%s: file name too long", fe);
1494 /* sprintf(fp, "%s/%s", p, fe); */
1495 memcpy(fp, p, dirlen);
1497 memcpy(fp + dirlen + 1, fe, fe_sz);
1500 fprintf(stderr, "Warning: stat(%s): %m\n", fp);
1503 if(S_ISREG(st.st_mode)) {
1505 char *e = fp + df_sz - 3;
1507 if(*e++ != '.' || (*e != 'c' && *e != 'h')) {
1508 /* direntry is regular file, but is not *.[ch] */
1511 for(cfl = configs; cfl; cfl = cfl->link) {
1512 struct stat *config = (struct stat *)cfl->data;
1514 if (st.st_dev == config->st_dev && st.st_ino == config->st_ino) {
1515 /* skip already parsed bb_configs.h */
1519 /* direntry is *.[ch] regular file and is not configs */
1520 c_lex_src(fp, st.st_size);
1521 if(!dontgenerate_dep) {
1526 /* /src_dir/path/file.o to path/file.o */
1533 first = show_dep(1, Ifound, fp, e);
1534 first = show_dep(first, key_top, fp, e);
1538 show_dep(-1, key_top, NULL, NULL);
1541 } else if(S_ISDIR(st.st_mode)) {
1542 if (st.st_dev == st_kp.st_dev && st.st_ino == st_kp.st_ino)
1543 return NULL; /* drop scan kp/ directory */
1544 /* direntry is directory. buff is returned */
1545 return bb_xstrdup(fp);
1547 /* hmm, direntry is device! */
1551 /* from libbb but inlined for speed considerations */
1552 static inline llist_t *llist_add_to(llist_t *old_head, char *new_item)
1556 new_head = xmalloc(sizeof(llist_t));
1557 new_head->data = new_item;
1558 new_head->link = old_head;
1563 static void scan_dir_find_ch_files(const char *p)
1572 dirs = llist_add_to(NULL, bb_simplify_path(p));
1573 replace = strlen(dirs->data);
1574 /* emulate recursion */
1578 dir = opendir(dirs->data);
1580 fprintf(stderr, "Warning: opendir(%s): %m\n", dirs->data);
1581 dirlen = strlen(dirs->data);
1582 while ((de = readdir(dir)) != NULL) {
1585 if (de->d_name[0] == '.')
1587 found_dir = parse_chd(de->d_name, dirs->data, dirlen);
1589 d_add = llist_add_to(d_add, found_dir);
1601 static void show_usage(void) __attribute__ ((noreturn));
1602 static void show_usage(void)
1604 bb_error_d("%s\n%s\n", bb_mkdep_terse_options, bb_mkdep_full_options);
1607 int main(int argc, char **argv)
1614 /* for bb_simplify_path, this program has no chdir() */
1615 /* libbb-like my xgetcwd() */
1616 unsigned path_max = 512;
1618 s = xmalloc (path_max);
1619 while (getcwd (s, path_max) == NULL) {
1621 bb_error_d("getcwd: %m");
1623 s = xmalloc(path_max *= 2);
1628 while ((i = getopt(argc, argv, "I:c:dk:w")) > 0) {
1631 s = bb_simplify_path(optarg);
1632 Iop = llist_add_to(Iop, s);
1635 s = bb_simplify_path(optarg);
1636 configs = llist_add_to(configs, s);
1639 dontgenerate_dep = 1;
1643 bb_error_d("Hmm, why multiple -k?");
1644 kp = bb_simplify_path(optarg);
1655 kp = bb_simplify_path(INCLUDE_CONFIG_PATH);
1656 /* globals initialize */
1657 kp_len = strlen(kp);
1658 if(stat(kp, &st_kp))
1659 bb_error_d("stat(%s): %m", kp);
1660 if(!S_ISDIR(st_kp.st_mode))
1661 bb_error_d("%s is not directory", kp);
1664 Iop = llist_add_to(Iop, bb_simplify_path(LOCAL_INCLUDE_PATH));
1665 if(configs == NULL) {
1666 s = bb_simplify_path(INCLUDE_CONFIG_KEYS_PATH);
1667 configs = llist_add_to(configs, s);
1670 pagesizem1 = getpagesize() - 1;
1671 for(i = 0; i < UCHAR_MAX; i++) {
1674 /* set unparsed chars to speed up the parser */
1675 else if(i != CHR && i != STR && i != POUND && i != REM)
1676 first_chars[i] = ANY;
1678 first_chars[i] = '-'; /* L_EOF */
1681 for(fl = configs; fl; fl = fl->link) {
1684 if(stat(fl->data, &st))
1685 bb_error_d("stat(%s): %m", fl->data);
1686 c_lex_config(fl->data, st.st_size);
1688 /* trick for fast comparing found files with configs */
1689 fl->data = xmalloc(sizeof(struct stat));
1690 memcpy(fl->data, &st, sizeof(struct stat));
1697 scan_dir_find_ch_files(*argv++);
1699 scan_dir_find_ch_files(".");
1705 /* partial and simplified libbb routine */
1706 static void bb_error_d(const char *s, ...)
1711 vfprintf(stderr, s, p);
1717 static char *bb_asprint(const char *format, ...)
1723 va_start(p, format);
1724 r = vasprintf(&out, format, p);
1728 bb_error_d("bb_asprint: %m");
1732 /* partial libbb routine as is */
1734 static char *bb_simplify_path(const char *path)
1736 char *s, *start, *p;
1739 start = bb_xstrdup(path);
1741 /* is not libbb, but this program has no chdir() */
1742 start = bb_asprint("%s/%s", pwd, path);
1748 if (*s == '/') { /* skip duplicate (or initial) slash */
1750 } else if (*s == '.') {
1751 if (s[1] == '/' || s[1] == 0) { /* remove extra '.' */
1753 } else if ((s[1] == '.') && (s[2] == '/' || s[2] == 0)) {
1756 while (*--p != '/'); /* omit previous dir */
1765 if ((p == start) || (*p != '/')) { /* not a trailing slash */
1766 ++p; /* so keep last character */