*: remove 'const' qualifier for struct index_state
[git] / attr.c
1 /*
2  * Handle git attributes.  See gitattributes(5) for a description of
3  * the file syntax, and attr.h for a description of the API.
4  *
5  * One basic design decision here is that we are not going to support
6  * an insanely large number of attributes.
7  */
8
9 #include "cache.h"
10 #include "config.h"
11 #include "exec-cmd.h"
12 #include "attr.h"
13 #include "dir.h"
14 #include "utf8.h"
15 #include "quote.h"
16 #include "thread-utils.h"
17
18 const char git_attr__true[] = "(builtin)true";
19 const char git_attr__false[] = "\0(builtin)false";
20 static const char git_attr__unknown[] = "(builtin)unknown";
21 #define ATTR__TRUE git_attr__true
22 #define ATTR__FALSE git_attr__false
23 #define ATTR__UNSET NULL
24 #define ATTR__UNKNOWN git_attr__unknown
25
26 #ifndef DEBUG_ATTR
27 #define DEBUG_ATTR 0
28 #endif
29
30 struct git_attr {
31         int attr_nr; /* unique attribute number */
32         char name[FLEX_ARRAY]; /* attribute name */
33 };
34
35 const char *git_attr_name(const struct git_attr *attr)
36 {
37         return attr->name;
38 }
39
40 struct attr_hashmap {
41         struct hashmap map;
42         pthread_mutex_t mutex;
43 };
44
45 static inline void hashmap_lock(struct attr_hashmap *map)
46 {
47         pthread_mutex_lock(&map->mutex);
48 }
49
50 static inline void hashmap_unlock(struct attr_hashmap *map)
51 {
52         pthread_mutex_unlock(&map->mutex);
53 }
54
55 /* The container for objects stored in "struct attr_hashmap" */
56 struct attr_hash_entry {
57         struct hashmap_entry ent;
58         const char *key; /* the key; memory should be owned by value */
59         size_t keylen; /* length of the key */
60         void *value; /* the stored value */
61 };
62
63 /* attr_hashmap comparison function */
64 static int attr_hash_entry_cmp(const void *unused_cmp_data,
65                                const struct hashmap_entry *eptr,
66                                const struct hashmap_entry *entry_or_key,
67                                const void *unused_keydata)
68 {
69         const struct attr_hash_entry *a, *b;
70
71         a = container_of(eptr, const struct attr_hash_entry, ent);
72         b = container_of(entry_or_key, const struct attr_hash_entry, ent);
73         return (a->keylen != b->keylen) || strncmp(a->key, b->key, a->keylen);
74 }
75
76 /*
77  * The global dictionary of all interned attributes.  This
78  * is a singleton object which is shared between threads.
79  * Access to this dictionary must be surrounded with a mutex.
80  */
81 static struct attr_hashmap g_attr_hashmap = {
82         HASHMAP_INIT(attr_hash_entry_cmp, NULL)
83 };
84
85 /*
86  * Retrieve the 'value' stored in a hashmap given the provided 'key'.
87  * If there is no matching entry, return NULL.
88  */
89 static void *attr_hashmap_get(struct attr_hashmap *map,
90                               const char *key, size_t keylen)
91 {
92         struct attr_hash_entry k;
93         struct attr_hash_entry *e;
94
95         hashmap_entry_init(&k.ent, memhash(key, keylen));
96         k.key = key;
97         k.keylen = keylen;
98         e = hashmap_get_entry(&map->map, &k, ent, NULL);
99
100         return e ? e->value : NULL;
101 }
102
103 /* Add 'value' to a hashmap based on the provided 'key'. */
104 static void attr_hashmap_add(struct attr_hashmap *map,
105                              const char *key, size_t keylen,
106                              void *value)
107 {
108         struct attr_hash_entry *e;
109
110         e = xmalloc(sizeof(struct attr_hash_entry));
111         hashmap_entry_init(&e->ent, memhash(key, keylen));
112         e->key = key;
113         e->keylen = keylen;
114         e->value = value;
115
116         hashmap_add(&map->map, &e->ent);
117 }
118
119 struct all_attrs_item {
120         const struct git_attr *attr;
121         const char *value;
122         /*
123          * If 'macro' is non-NULL, indicates that 'attr' is a macro based on
124          * the current attribute stack and contains a pointer to the match_attr
125          * definition of the macro
126          */
127         const struct match_attr *macro;
128 };
129
130 /*
131  * Reallocate and reinitialize the array of all attributes (which is used in
132  * the attribute collection process) in 'check' based on the global dictionary
133  * of attributes.
134  */
135 static void all_attrs_init(struct attr_hashmap *map, struct attr_check *check)
136 {
137         int i;
138         unsigned int size;
139
140         hashmap_lock(map);
141
142         size = hashmap_get_size(&map->map);
143         if (size < check->all_attrs_nr)
144                 BUG("interned attributes shouldn't be deleted");
145
146         /*
147          * If the number of attributes in the global dictionary has increased
148          * (or this attr_check instance doesn't have an initialized all_attrs
149          * field), reallocate the provided attr_check instance's all_attrs
150          * field and fill each entry with its corresponding git_attr.
151          */
152         if (size != check->all_attrs_nr) {
153                 struct attr_hash_entry *e;
154                 struct hashmap_iter iter;
155
156                 REALLOC_ARRAY(check->all_attrs, size);
157                 check->all_attrs_nr = size;
158
159                 hashmap_for_each_entry(&map->map, &iter, e,
160                                         ent /* member name */) {
161                         const struct git_attr *a = e->value;
162                         check->all_attrs[a->attr_nr].attr = a;
163                 }
164         }
165
166         hashmap_unlock(map);
167
168         /*
169          * Re-initialize every entry in check->all_attrs.
170          * This re-initialization can live outside of the locked region since
171          * the attribute dictionary is no longer being accessed.
172          */
173         for (i = 0; i < check->all_attrs_nr; i++) {
174                 check->all_attrs[i].value = ATTR__UNKNOWN;
175                 check->all_attrs[i].macro = NULL;
176         }
177 }
178
179 static int attr_name_valid(const char *name, size_t namelen)
180 {
181         /*
182          * Attribute name cannot begin with '-' and must consist of
183          * characters from [-A-Za-z0-9_.].
184          */
185         if (namelen <= 0 || *name == '-')
186                 return 0;
187         while (namelen--) {
188                 char ch = *name++;
189                 if (! (ch == '-' || ch == '.' || ch == '_' ||
190                        ('0' <= ch && ch <= '9') ||
191                        ('a' <= ch && ch <= 'z') ||
192                        ('A' <= ch && ch <= 'Z')) )
193                         return 0;
194         }
195         return 1;
196 }
197
198 static void report_invalid_attr(const char *name, size_t len,
199                                 const char *src, int lineno)
200 {
201         struct strbuf err = STRBUF_INIT;
202         strbuf_addf(&err, _("%.*s is not a valid attribute name"),
203                     (int) len, name);
204         fprintf(stderr, "%s: %s:%d\n", err.buf, src, lineno);
205         strbuf_release(&err);
206 }
207
208 /*
209  * Given a 'name', lookup and return the corresponding attribute in the global
210  * dictionary.  If no entry is found, create a new attribute and store it in
211  * the dictionary.
212  */
213 static const struct git_attr *git_attr_internal(const char *name, int namelen)
214 {
215         struct git_attr *a;
216
217         if (!attr_name_valid(name, namelen))
218                 return NULL;
219
220         hashmap_lock(&g_attr_hashmap);
221
222         a = attr_hashmap_get(&g_attr_hashmap, name, namelen);
223
224         if (!a) {
225                 FLEX_ALLOC_MEM(a, name, name, namelen);
226                 a->attr_nr = hashmap_get_size(&g_attr_hashmap.map);
227
228                 attr_hashmap_add(&g_attr_hashmap, a->name, namelen, a);
229                 assert(a->attr_nr ==
230                        (hashmap_get_size(&g_attr_hashmap.map) - 1));
231         }
232
233         hashmap_unlock(&g_attr_hashmap);
234
235         return a;
236 }
237
238 const struct git_attr *git_attr(const char *name)
239 {
240         return git_attr_internal(name, strlen(name));
241 }
242
243 /* What does a matched pattern decide? */
244 struct attr_state {
245         const struct git_attr *attr;
246         const char *setto;
247 };
248
249 struct pattern {
250         const char *pattern;
251         int patternlen;
252         int nowildcardlen;
253         unsigned flags;         /* PATTERN_FLAG_* */
254 };
255
256 /*
257  * One rule, as from a .gitattributes file.
258  *
259  * If is_macro is true, then u.attr is a pointer to the git_attr being
260  * defined.
261  *
262  * If is_macro is false, then u.pat is the filename pattern to which the
263  * rule applies.
264  *
265  * In either case, num_attr is the number of attributes affected by
266  * this rule, and state is an array listing them.  The attributes are
267  * listed as they appear in the file (macros unexpanded).
268  */
269 struct match_attr {
270         union {
271                 struct pattern pat;
272                 const struct git_attr *attr;
273         } u;
274         char is_macro;
275         unsigned num_attr;
276         struct attr_state state[FLEX_ARRAY];
277 };
278
279 static const char blank[] = " \t\r\n";
280
281 /*
282  * Parse a whitespace-delimited attribute state (i.e., "attr",
283  * "-attr", "!attr", or "attr=value") from the string starting at src.
284  * If e is not NULL, write the results to *e.  Return a pointer to the
285  * remainder of the string (with leading whitespace removed), or NULL
286  * if there was an error.
287  */
288 static const char *parse_attr(const char *src, int lineno, const char *cp,
289                               struct attr_state *e)
290 {
291         const char *ep, *equals;
292         int len;
293
294         ep = cp + strcspn(cp, blank);
295         equals = strchr(cp, '=');
296         if (equals && ep < equals)
297                 equals = NULL;
298         if (equals)
299                 len = equals - cp;
300         else
301                 len = ep - cp;
302         if (!e) {
303                 if (*cp == '-' || *cp == '!') {
304                         cp++;
305                         len--;
306                 }
307                 if (!attr_name_valid(cp, len)) {
308                         report_invalid_attr(cp, len, src, lineno);
309                         return NULL;
310                 }
311         } else {
312                 /*
313                  * As this function is always called twice, once with
314                  * e == NULL in the first pass and then e != NULL in
315                  * the second pass, no need for attr_name_valid()
316                  * check here.
317                  */
318                 if (*cp == '-' || *cp == '!') {
319                         e->setto = (*cp == '-') ? ATTR__FALSE : ATTR__UNSET;
320                         cp++;
321                         len--;
322                 }
323                 else if (!equals)
324                         e->setto = ATTR__TRUE;
325                 else {
326                         e->setto = xmemdupz(equals + 1, ep - equals - 1);
327                 }
328                 e->attr = git_attr_internal(cp, len);
329         }
330         return ep + strspn(ep, blank);
331 }
332
333 static struct match_attr *parse_attr_line(const char *line, const char *src,
334                                           int lineno, int macro_ok)
335 {
336         int namelen;
337         int num_attr, i;
338         const char *cp, *name, *states;
339         struct match_attr *res = NULL;
340         int is_macro;
341         struct strbuf pattern = STRBUF_INIT;
342
343         cp = line + strspn(line, blank);
344         if (!*cp || *cp == '#')
345                 return NULL;
346         name = cp;
347
348         if (*cp == '"' && !unquote_c_style(&pattern, name, &states)) {
349                 name = pattern.buf;
350                 namelen = pattern.len;
351         } else {
352                 namelen = strcspn(name, blank);
353                 states = name + namelen;
354         }
355
356         if (strlen(ATTRIBUTE_MACRO_PREFIX) < namelen &&
357             starts_with(name, ATTRIBUTE_MACRO_PREFIX)) {
358                 if (!macro_ok) {
359                         fprintf_ln(stderr, _("%s not allowed: %s:%d"),
360                                    name, src, lineno);
361                         goto fail_return;
362                 }
363                 is_macro = 1;
364                 name += strlen(ATTRIBUTE_MACRO_PREFIX);
365                 name += strspn(name, blank);
366                 namelen = strcspn(name, blank);
367                 if (!attr_name_valid(name, namelen)) {
368                         report_invalid_attr(name, namelen, src, lineno);
369                         goto fail_return;
370                 }
371         }
372         else
373                 is_macro = 0;
374
375         states += strspn(states, blank);
376
377         /* First pass to count the attr_states */
378         for (cp = states, num_attr = 0; *cp; num_attr++) {
379                 cp = parse_attr(src, lineno, cp, NULL);
380                 if (!cp)
381                         goto fail_return;
382         }
383
384         res = xcalloc(1,
385                       sizeof(*res) +
386                       sizeof(struct attr_state) * num_attr +
387                       (is_macro ? 0 : namelen + 1));
388         if (is_macro) {
389                 res->u.attr = git_attr_internal(name, namelen);
390         } else {
391                 char *p = (char *)&(res->state[num_attr]);
392                 memcpy(p, name, namelen);
393                 res->u.pat.pattern = p;
394                 parse_path_pattern(&res->u.pat.pattern,
395                                       &res->u.pat.patternlen,
396                                       &res->u.pat.flags,
397                                       &res->u.pat.nowildcardlen);
398                 if (res->u.pat.flags & PATTERN_FLAG_NEGATIVE) {
399                         warning(_("Negative patterns are ignored in git attributes\n"
400                                   "Use '\\!' for literal leading exclamation."));
401                         goto fail_return;
402                 }
403         }
404         res->is_macro = is_macro;
405         res->num_attr = num_attr;
406
407         /* Second pass to fill the attr_states */
408         for (cp = states, i = 0; *cp; i++) {
409                 cp = parse_attr(src, lineno, cp, &(res->state[i]));
410         }
411
412         strbuf_release(&pattern);
413         return res;
414
415 fail_return:
416         strbuf_release(&pattern);
417         free(res);
418         return NULL;
419 }
420
421 /*
422  * Like info/exclude and .gitignore, the attribute information can
423  * come from many places.
424  *
425  * (1) .gitattributes file of the same directory;
426  * (2) .gitattributes file of the parent directory if (1) does not have
427  *      any match; this goes recursively upwards, just like .gitignore.
428  * (3) $GIT_DIR/info/attributes, which overrides both of the above.
429  *
430  * In the same file, later entries override the earlier match, so in the
431  * global list, we would have entries from info/attributes the earliest
432  * (reading the file from top to bottom), .gitattributes of the root
433  * directory (again, reading the file from top to bottom) down to the
434  * current directory, and then scan the list backwards to find the first match.
435  * This is exactly the same as what is_excluded() does in dir.c to deal with
436  * .gitignore file and info/excludes file as a fallback.
437  */
438
439 struct attr_stack {
440         struct attr_stack *prev;
441         char *origin;
442         size_t originlen;
443         unsigned num_matches;
444         unsigned alloc;
445         struct match_attr **attrs;
446 };
447
448 static void attr_stack_free(struct attr_stack *e)
449 {
450         int i;
451         free(e->origin);
452         for (i = 0; i < e->num_matches; i++) {
453                 struct match_attr *a = e->attrs[i];
454                 int j;
455                 for (j = 0; j < a->num_attr; j++) {
456                         const char *setto = a->state[j].setto;
457                         if (setto == ATTR__TRUE ||
458                             setto == ATTR__FALSE ||
459                             setto == ATTR__UNSET ||
460                             setto == ATTR__UNKNOWN)
461                                 ;
462                         else
463                                 free((char *) setto);
464                 }
465                 free(a);
466         }
467         free(e->attrs);
468         free(e);
469 }
470
471 static void drop_attr_stack(struct attr_stack **stack)
472 {
473         while (*stack) {
474                 struct attr_stack *elem = *stack;
475                 *stack = elem->prev;
476                 attr_stack_free(elem);
477         }
478 }
479
480 /* List of all attr_check structs; access should be surrounded by mutex */
481 static struct check_vector {
482         size_t nr;
483         size_t alloc;
484         struct attr_check **checks;
485         pthread_mutex_t mutex;
486 } check_vector;
487
488 static inline void vector_lock(void)
489 {
490         pthread_mutex_lock(&check_vector.mutex);
491 }
492
493 static inline void vector_unlock(void)
494 {
495         pthread_mutex_unlock(&check_vector.mutex);
496 }
497
498 static void check_vector_add(struct attr_check *c)
499 {
500         vector_lock();
501
502         ALLOC_GROW(check_vector.checks,
503                    check_vector.nr + 1,
504                    check_vector.alloc);
505         check_vector.checks[check_vector.nr++] = c;
506
507         vector_unlock();
508 }
509
510 static void check_vector_remove(struct attr_check *check)
511 {
512         int i;
513
514         vector_lock();
515
516         /* Find entry */
517         for (i = 0; i < check_vector.nr; i++)
518                 if (check_vector.checks[i] == check)
519                         break;
520
521         if (i >= check_vector.nr)
522                 BUG("no entry found");
523
524         /* shift entries over */
525         for (; i < check_vector.nr - 1; i++)
526                 check_vector.checks[i] = check_vector.checks[i + 1];
527
528         check_vector.nr--;
529
530         vector_unlock();
531 }
532
533 /* Iterate through all attr_check instances and drop their stacks */
534 static void drop_all_attr_stacks(void)
535 {
536         int i;
537
538         vector_lock();
539
540         for (i = 0; i < check_vector.nr; i++) {
541                 drop_attr_stack(&check_vector.checks[i]->stack);
542         }
543
544         vector_unlock();
545 }
546
547 struct attr_check *attr_check_alloc(void)
548 {
549         struct attr_check *c = xcalloc(1, sizeof(struct attr_check));
550
551         /* save pointer to the check struct */
552         check_vector_add(c);
553
554         return c;
555 }
556
557 struct attr_check *attr_check_initl(const char *one, ...)
558 {
559         struct attr_check *check;
560         int cnt;
561         va_list params;
562         const char *param;
563
564         va_start(params, one);
565         for (cnt = 1; (param = va_arg(params, const char *)) != NULL; cnt++)
566                 ;
567         va_end(params);
568
569         check = attr_check_alloc();
570         check->nr = cnt;
571         check->alloc = cnt;
572         check->items = xcalloc(cnt, sizeof(struct attr_check_item));
573
574         check->items[0].attr = git_attr(one);
575         va_start(params, one);
576         for (cnt = 1; cnt < check->nr; cnt++) {
577                 const struct git_attr *attr;
578                 param = va_arg(params, const char *);
579                 if (!param)
580                         BUG("counted %d != ended at %d",
581                             check->nr, cnt);
582                 attr = git_attr(param);
583                 if (!attr)
584                         BUG("%s: not a valid attribute name", param);
585                 check->items[cnt].attr = attr;
586         }
587         va_end(params);
588         return check;
589 }
590
591 struct attr_check *attr_check_dup(const struct attr_check *check)
592 {
593         struct attr_check *ret;
594
595         if (!check)
596                 return NULL;
597
598         ret = attr_check_alloc();
599
600         ret->nr = check->nr;
601         ret->alloc = check->alloc;
602         ALLOC_ARRAY(ret->items, ret->nr);
603         COPY_ARRAY(ret->items, check->items, ret->nr);
604
605         return ret;
606 }
607
608 struct attr_check_item *attr_check_append(struct attr_check *check,
609                                           const struct git_attr *attr)
610 {
611         struct attr_check_item *item;
612
613         ALLOC_GROW(check->items, check->nr + 1, check->alloc);
614         item = &check->items[check->nr++];
615         item->attr = attr;
616         return item;
617 }
618
619 void attr_check_reset(struct attr_check *check)
620 {
621         check->nr = 0;
622 }
623
624 void attr_check_clear(struct attr_check *check)
625 {
626         FREE_AND_NULL(check->items);
627         check->alloc = 0;
628         check->nr = 0;
629
630         FREE_AND_NULL(check->all_attrs);
631         check->all_attrs_nr = 0;
632
633         drop_attr_stack(&check->stack);
634 }
635
636 void attr_check_free(struct attr_check *check)
637 {
638         if (check) {
639                 /* Remove check from the check vector */
640                 check_vector_remove(check);
641
642                 attr_check_clear(check);
643                 free(check);
644         }
645 }
646
647 static const char *builtin_attr[] = {
648         "[attr]binary -diff -merge -text",
649         NULL,
650 };
651
652 static void handle_attr_line(struct attr_stack *res,
653                              const char *line,
654                              const char *src,
655                              int lineno,
656                              int macro_ok)
657 {
658         struct match_attr *a;
659
660         a = parse_attr_line(line, src, lineno, macro_ok);
661         if (!a)
662                 return;
663         ALLOC_GROW(res->attrs, res->num_matches + 1, res->alloc);
664         res->attrs[res->num_matches++] = a;
665 }
666
667 static struct attr_stack *read_attr_from_array(const char **list)
668 {
669         struct attr_stack *res;
670         const char *line;
671         int lineno = 0;
672
673         res = xcalloc(1, sizeof(*res));
674         while ((line = *(list++)) != NULL)
675                 handle_attr_line(res, line, "[builtin]", ++lineno, 1);
676         return res;
677 }
678
679 /*
680  * Callers into the attribute system assume there is a single, system-wide
681  * global state where attributes are read from and when the state is flipped by
682  * calling git_attr_set_direction(), the stack frames that have been
683  * constructed need to be discarded so so that subsequent calls into the
684  * attribute system will lazily read from the right place.  Since changing
685  * direction causes a global paradigm shift, it should not ever be called while
686  * another thread could potentially be calling into the attribute system.
687  */
688 static enum git_attr_direction direction;
689
690 void git_attr_set_direction(enum git_attr_direction new_direction)
691 {
692         if (is_bare_repository() && new_direction != GIT_ATTR_INDEX)
693                 BUG("non-INDEX attr direction in a bare repo");
694
695         if (new_direction != direction)
696                 drop_all_attr_stacks();
697
698         direction = new_direction;
699 }
700
701 static struct attr_stack *read_attr_from_file(const char *path, int macro_ok)
702 {
703         FILE *fp = fopen_or_warn(path, "r");
704         struct attr_stack *res;
705         char buf[2048];
706         int lineno = 0;
707
708         if (!fp)
709                 return NULL;
710         res = xcalloc(1, sizeof(*res));
711         while (fgets(buf, sizeof(buf), fp)) {
712                 char *bufp = buf;
713                 if (!lineno)
714                         skip_utf8_bom(&bufp, strlen(bufp));
715                 handle_attr_line(res, bufp, path, ++lineno, macro_ok);
716         }
717         fclose(fp);
718         return res;
719 }
720
721 static struct attr_stack *read_attr_from_index(struct index_state *istate,
722                                                const char *path,
723                                                int macro_ok)
724 {
725         struct attr_stack *res;
726         char *buf, *sp;
727         int lineno = 0;
728
729         if (!istate)
730                 return NULL;
731
732         buf = read_blob_data_from_index(istate, path, NULL);
733         if (!buf)
734                 return NULL;
735
736         res = xcalloc(1, sizeof(*res));
737         for (sp = buf; *sp; ) {
738                 char *ep;
739                 int more;
740
741                 ep = strchrnul(sp, '\n');
742                 more = (*ep == '\n');
743                 *ep = '\0';
744                 handle_attr_line(res, sp, path, ++lineno, macro_ok);
745                 sp = ep + more;
746         }
747         free(buf);
748         return res;
749 }
750
751 static struct attr_stack *read_attr(struct index_state *istate,
752                                     const char *path, int macro_ok)
753 {
754         struct attr_stack *res = NULL;
755
756         if (direction == GIT_ATTR_INDEX) {
757                 res = read_attr_from_index(istate, path, macro_ok);
758         } else if (!is_bare_repository()) {
759                 if (direction == GIT_ATTR_CHECKOUT) {
760                         res = read_attr_from_index(istate, path, macro_ok);
761                         if (!res)
762                                 res = read_attr_from_file(path, macro_ok);
763                 } else if (direction == GIT_ATTR_CHECKIN) {
764                         res = read_attr_from_file(path, macro_ok);
765                         if (!res)
766                                 /*
767                                  * There is no checked out .gitattributes file
768                                  * there, but we might have it in the index.
769                                  * We allow operation in a sparsely checked out
770                                  * work tree, so read from it.
771                                  */
772                                 res = read_attr_from_index(istate, path, macro_ok);
773                 }
774         }
775
776         if (!res)
777                 res = xcalloc(1, sizeof(*res));
778         return res;
779 }
780
781 #if DEBUG_ATTR
782 static void debug_info(const char *what, struct attr_stack *elem)
783 {
784         fprintf(stderr, "%s: %s\n", what, elem->origin ? elem->origin : "()");
785 }
786 static void debug_set(const char *what, const char *match, struct git_attr *attr, const void *v)
787 {
788         const char *value = v;
789
790         if (ATTR_TRUE(value))
791                 value = "set";
792         else if (ATTR_FALSE(value))
793                 value = "unset";
794         else if (ATTR_UNSET(value))
795                 value = "unspecified";
796
797         fprintf(stderr, "%s: %s => %s (%s)\n",
798                 what, attr->name, (char *) value, match);
799 }
800 #define debug_push(a) debug_info("push", (a))
801 #define debug_pop(a) debug_info("pop", (a))
802 #else
803 #define debug_push(a) do { ; } while (0)
804 #define debug_pop(a) do { ; } while (0)
805 #define debug_set(a,b,c,d) do { ; } while (0)
806 #endif /* DEBUG_ATTR */
807
808 static const char *git_etc_gitattributes(void)
809 {
810         static const char *system_wide;
811         if (!system_wide)
812                 system_wide = system_path(ETC_GITATTRIBUTES);
813         return system_wide;
814 }
815
816 static const char *get_home_gitattributes(void)
817 {
818         if (!git_attributes_file)
819                 git_attributes_file = xdg_config_home("attributes");
820
821         return git_attributes_file;
822 }
823
824 static int git_attr_system(void)
825 {
826         return !git_env_bool("GIT_ATTR_NOSYSTEM", 0);
827 }
828
829 static GIT_PATH_FUNC(git_path_info_attributes, INFOATTRIBUTES_FILE)
830
831 static void push_stack(struct attr_stack **attr_stack_p,
832                        struct attr_stack *elem, char *origin, size_t originlen)
833 {
834         if (elem) {
835                 elem->origin = origin;
836                 if (origin)
837                         elem->originlen = originlen;
838                 elem->prev = *attr_stack_p;
839                 *attr_stack_p = elem;
840         }
841 }
842
843 static void bootstrap_attr_stack(struct index_state *istate,
844                                  struct attr_stack **stack)
845 {
846         struct attr_stack *e;
847
848         if (*stack)
849                 return;
850
851         /* builtin frame */
852         e = read_attr_from_array(builtin_attr);
853         push_stack(stack, e, NULL, 0);
854
855         /* system-wide frame */
856         if (git_attr_system()) {
857                 e = read_attr_from_file(git_etc_gitattributes(), 1);
858                 push_stack(stack, e, NULL, 0);
859         }
860
861         /* home directory */
862         if (get_home_gitattributes()) {
863                 e = read_attr_from_file(get_home_gitattributes(), 1);
864                 push_stack(stack, e, NULL, 0);
865         }
866
867         /* root directory */
868         e = read_attr(istate, GITATTRIBUTES_FILE, 1);
869         push_stack(stack, e, xstrdup(""), 0);
870
871         /* info frame */
872         if (startup_info->have_repository)
873                 e = read_attr_from_file(git_path_info_attributes(), 1);
874         else
875                 e = NULL;
876         if (!e)
877                 e = xcalloc(1, sizeof(struct attr_stack));
878         push_stack(stack, e, NULL, 0);
879 }
880
881 static void prepare_attr_stack(struct index_state *istate,
882                                const char *path, int dirlen,
883                                struct attr_stack **stack)
884 {
885         struct attr_stack *info;
886         struct strbuf pathbuf = STRBUF_INIT;
887
888         /*
889          * At the bottom of the attribute stack is the built-in
890          * set of attribute definitions, followed by the contents
891          * of $(prefix)/etc/gitattributes and a file specified by
892          * core.attributesfile.  Then, contents from
893          * .gitattributes files from directories closer to the
894          * root to the ones in deeper directories are pushed
895          * to the stack.  Finally, at the very top of the stack
896          * we always keep the contents of $GIT_DIR/info/attributes.
897          *
898          * When checking, we use entries from near the top of the
899          * stack, preferring $GIT_DIR/info/attributes, then
900          * .gitattributes in deeper directories to shallower ones,
901          * and finally use the built-in set as the default.
902          */
903         bootstrap_attr_stack(istate, stack);
904
905         /*
906          * Pop the "info" one that is always at the top of the stack.
907          */
908         info = *stack;
909         *stack = info->prev;
910
911         /*
912          * Pop the ones from directories that are not the prefix of
913          * the path we are checking. Break out of the loop when we see
914          * the root one (whose origin is an empty string "") or the builtin
915          * one (whose origin is NULL) without popping it.
916          */
917         while ((*stack)->origin) {
918                 int namelen = (*stack)->originlen;
919                 struct attr_stack *elem;
920
921                 elem = *stack;
922                 if (namelen <= dirlen &&
923                     !strncmp(elem->origin, path, namelen) &&
924                     (!namelen || path[namelen] == '/'))
925                         break;
926
927                 debug_pop(elem);
928                 *stack = elem->prev;
929                 attr_stack_free(elem);
930         }
931
932         /*
933          * bootstrap_attr_stack() should have added, and the
934          * above loop should have stopped before popping, the
935          * root element whose attr_stack->origin is set to an
936          * empty string.
937          */
938         assert((*stack)->origin);
939
940         strbuf_addstr(&pathbuf, (*stack)->origin);
941         /* Build up to the directory 'path' is in */
942         while (pathbuf.len < dirlen) {
943                 size_t len = pathbuf.len;
944                 struct attr_stack *next;
945                 char *origin;
946
947                 /* Skip path-separator */
948                 if (len < dirlen && is_dir_sep(path[len]))
949                         len++;
950                 /* Find the end of the next component */
951                 while (len < dirlen && !is_dir_sep(path[len]))
952                         len++;
953
954                 if (pathbuf.len > 0)
955                         strbuf_addch(&pathbuf, '/');
956                 strbuf_add(&pathbuf, path + pathbuf.len, (len - pathbuf.len));
957                 strbuf_addf(&pathbuf, "/%s", GITATTRIBUTES_FILE);
958
959                 next = read_attr(istate, pathbuf.buf, 0);
960
961                 /* reset the pathbuf to not include "/.gitattributes" */
962                 strbuf_setlen(&pathbuf, len);
963
964                 origin = xstrdup(pathbuf.buf);
965                 push_stack(stack, next, origin, len);
966         }
967
968         /*
969          * Finally push the "info" one at the top of the stack.
970          */
971         push_stack(stack, info, NULL, 0);
972
973         strbuf_release(&pathbuf);
974 }
975
976 static int path_matches(const char *pathname, int pathlen,
977                         int basename_offset,
978                         const struct pattern *pat,
979                         const char *base, int baselen)
980 {
981         const char *pattern = pat->pattern;
982         int prefix = pat->nowildcardlen;
983         int isdir = (pathlen && pathname[pathlen - 1] == '/');
984
985         if ((pat->flags & PATTERN_FLAG_MUSTBEDIR) && !isdir)
986                 return 0;
987
988         if (pat->flags & PATTERN_FLAG_NODIR) {
989                 return match_basename(pathname + basename_offset,
990                                       pathlen - basename_offset - isdir,
991                                       pattern, prefix,
992                                       pat->patternlen, pat->flags);
993         }
994         return match_pathname(pathname, pathlen - isdir,
995                               base, baselen,
996                               pattern, prefix, pat->patternlen, pat->flags);
997 }
998
999 static int macroexpand_one(struct all_attrs_item *all_attrs, int nr, int rem);
1000
1001 static int fill_one(const char *what, struct all_attrs_item *all_attrs,
1002                     const struct match_attr *a, int rem)
1003 {
1004         int i;
1005
1006         for (i = a->num_attr - 1; rem > 0 && i >= 0; i--) {
1007                 const struct git_attr *attr = a->state[i].attr;
1008                 const char **n = &(all_attrs[attr->attr_nr].value);
1009                 const char *v = a->state[i].setto;
1010
1011                 if (*n == ATTR__UNKNOWN) {
1012                         debug_set(what,
1013                                   a->is_macro ? a->u.attr->name : a->u.pat.pattern,
1014                                   attr, v);
1015                         *n = v;
1016                         rem--;
1017                         rem = macroexpand_one(all_attrs, attr->attr_nr, rem);
1018                 }
1019         }
1020         return rem;
1021 }
1022
1023 static int fill(const char *path, int pathlen, int basename_offset,
1024                 const struct attr_stack *stack,
1025                 struct all_attrs_item *all_attrs, int rem)
1026 {
1027         for (; rem > 0 && stack; stack = stack->prev) {
1028                 int i;
1029                 const char *base = stack->origin ? stack->origin : "";
1030
1031                 for (i = stack->num_matches - 1; 0 < rem && 0 <= i; i--) {
1032                         const struct match_attr *a = stack->attrs[i];
1033                         if (a->is_macro)
1034                                 continue;
1035                         if (path_matches(path, pathlen, basename_offset,
1036                                          &a->u.pat, base, stack->originlen))
1037                                 rem = fill_one("fill", all_attrs, a, rem);
1038                 }
1039         }
1040
1041         return rem;
1042 }
1043
1044 static int macroexpand_one(struct all_attrs_item *all_attrs, int nr, int rem)
1045 {
1046         const struct all_attrs_item *item = &all_attrs[nr];
1047
1048         if (item->macro && item->value == ATTR__TRUE)
1049                 return fill_one("expand", all_attrs, item->macro, rem);
1050         else
1051                 return rem;
1052 }
1053
1054 /*
1055  * Marks the attributes which are macros based on the attribute stack.
1056  * This prevents having to search through the attribute stack each time
1057  * a macro needs to be expanded during the fill stage.
1058  */
1059 static void determine_macros(struct all_attrs_item *all_attrs,
1060                              const struct attr_stack *stack)
1061 {
1062         for (; stack; stack = stack->prev) {
1063                 int i;
1064                 for (i = stack->num_matches - 1; i >= 0; i--) {
1065                         const struct match_attr *ma = stack->attrs[i];
1066                         if (ma->is_macro) {
1067                                 int n = ma->u.attr->attr_nr;
1068                                 if (!all_attrs[n].macro) {
1069                                         all_attrs[n].macro = ma;
1070                                 }
1071                         }
1072                 }
1073         }
1074 }
1075
1076 /*
1077  * Collect attributes for path into the array pointed to by check->all_attrs.
1078  * If check->check_nr is non-zero, only attributes in check[] are collected.
1079  * Otherwise all attributes are collected.
1080  */
1081 static void collect_some_attrs(struct index_state *istate,
1082                                const char *path,
1083                                struct attr_check *check)
1084 {
1085         int pathlen, rem, dirlen;
1086         const char *cp, *last_slash = NULL;
1087         int basename_offset;
1088
1089         for (cp = path; *cp; cp++) {
1090                 if (*cp == '/' && cp[1])
1091                         last_slash = cp;
1092         }
1093         pathlen = cp - path;
1094         if (last_slash) {
1095                 basename_offset = last_slash + 1 - path;
1096                 dirlen = last_slash - path;
1097         } else {
1098                 basename_offset = 0;
1099                 dirlen = 0;
1100         }
1101
1102         prepare_attr_stack(istate, path, dirlen, &check->stack);
1103         all_attrs_init(&g_attr_hashmap, check);
1104         determine_macros(check->all_attrs, check->stack);
1105
1106         rem = check->all_attrs_nr;
1107         fill(path, pathlen, basename_offset, check->stack, check->all_attrs, rem);
1108 }
1109
1110 void git_check_attr(struct index_state *istate,
1111                     const char *path,
1112                     struct attr_check *check)
1113 {
1114         int i;
1115
1116         collect_some_attrs(istate, path, check);
1117
1118         for (i = 0; i < check->nr; i++) {
1119                 size_t n = check->items[i].attr->attr_nr;
1120                 const char *value = check->all_attrs[n].value;
1121                 if (value == ATTR__UNKNOWN)
1122                         value = ATTR__UNSET;
1123                 check->items[i].value = value;
1124         }
1125 }
1126
1127 void git_all_attrs(struct index_state *istate,
1128                    const char *path, struct attr_check *check)
1129 {
1130         int i;
1131
1132         attr_check_reset(check);
1133         collect_some_attrs(istate, path, check);
1134
1135         for (i = 0; i < check->all_attrs_nr; i++) {
1136                 const char *name = check->all_attrs[i].attr->name;
1137                 const char *value = check->all_attrs[i].value;
1138                 struct attr_check_item *item;
1139                 if (value == ATTR__UNSET || value == ATTR__UNKNOWN)
1140                         continue;
1141                 item = attr_check_append(check, git_attr(name));
1142                 item->value = value;
1143         }
1144 }
1145
1146 void attr_start(void)
1147 {
1148         pthread_mutex_init(&g_attr_hashmap.mutex, NULL);
1149         pthread_mutex_init(&check_vector.mutex, NULL);
1150 }