Fix git-for-each-refs broken for tags
[git] / fsck-objects.c
1 #include <sys/types.h>
2 #include <dirent.h>
3
4 #include "cache.h"
5 #include "commit.h"
6 #include "tree.h"
7 #include "blob.h"
8 #include "tag.h"
9 #include "refs.h"
10 #include "pack.h"
11 #include "cache-tree.h"
12 #include "tree-walk.h"
13
14 #define REACHABLE 0x0001
15 #define SEEN      0x0002
16
17 static int show_root;
18 static int show_tags;
19 static int show_unreachable;
20 static int check_full;
21 static int check_strict;
22 static int keep_cache_objects;
23 static unsigned char head_sha1[20];
24
25 #ifdef NO_D_INO_IN_DIRENT
26 #define SORT_DIRENT 0
27 #define DIRENT_SORT_HINT(de) 0
28 #else
29 #define SORT_DIRENT 1
30 #define DIRENT_SORT_HINT(de) ((de)->d_ino)
31 #endif
32
33 static void objreport(struct object *obj, const char *severity,
34                       const char *err, va_list params)
35 {
36         fprintf(stderr, "%s in %s %s: ",
37                 severity, typename(obj->type), sha1_to_hex(obj->sha1));
38         vfprintf(stderr, err, params);
39         fputs("\n", stderr);
40 }
41
42 static int objerror(struct object *obj, const char *err, ...)
43 {
44         va_list params;
45         va_start(params, err);
46         objreport(obj, "error", err, params);
47         va_end(params);
48         return -1;
49 }
50
51 static int objwarning(struct object *obj, const char *err, ...)
52 {
53         va_list params;
54         va_start(params, err);
55         objreport(obj, "warning", err, params);
56         va_end(params);
57         return -1;
58 }
59
60
61 static void check_connectivity(void)
62 {
63         int i, max;
64
65         /* Look up all the requirements, warn about missing objects.. */
66         max = get_max_object_index();
67         for (i = 0; i < max; i++) {
68                 const struct object_refs *refs;
69                 struct object *obj = get_indexed_object(i);
70
71                 if (!obj)
72                         continue;
73
74                 if (!obj->parsed) {
75                         if (has_sha1_file(obj->sha1))
76                                 ; /* it is in pack */
77                         else
78                                 printf("missing %s %s\n",
79                                        typename(obj->type), sha1_to_hex(obj->sha1));
80                         continue;
81                 }
82
83                 refs = lookup_object_refs(obj);
84                 if (refs) {
85                         unsigned j;
86                         for (j = 0; j < refs->count; j++) {
87                                 struct object *ref = refs->ref[j];
88                                 if (ref->parsed ||
89                                     (has_sha1_file(ref->sha1)))
90                                         continue;
91                                 printf("broken link from %7s %s\n",
92                                        typename(obj->type), sha1_to_hex(obj->sha1));
93                                 printf("              to %7s %s\n",
94                                        typename(ref->type), sha1_to_hex(ref->sha1));
95                         }
96                 }
97
98                 if (show_unreachable && !(obj->flags & REACHABLE)) {
99                         printf("unreachable %s %s\n",
100                                typename(obj->type), sha1_to_hex(obj->sha1));
101                         continue;
102                 }
103
104                 if (!obj->used) {
105                         printf("dangling %s %s\n", typename(obj->type),
106                                sha1_to_hex(obj->sha1));
107                 }
108         }
109 }
110
111 /*
112  * The entries in a tree are ordered in the _path_ order,
113  * which means that a directory entry is ordered by adding
114  * a slash to the end of it.
115  *
116  * So a directory called "a" is ordered _after_ a file
117  * called "a.c", because "a/" sorts after "a.c".
118  */
119 #define TREE_UNORDERED (-1)
120 #define TREE_HAS_DUPS  (-2)
121
122 static int verify_ordered(unsigned mode1, const char *name1, unsigned mode2, const char *name2)
123 {
124         int len1 = strlen(name1);
125         int len2 = strlen(name2);
126         int len = len1 < len2 ? len1 : len2;
127         unsigned char c1, c2;
128         int cmp;
129
130         cmp = memcmp(name1, name2, len);
131         if (cmp < 0)
132                 return 0;
133         if (cmp > 0)
134                 return TREE_UNORDERED;
135
136         /*
137          * Ok, the first <len> characters are the same.
138          * Now we need to order the next one, but turn
139          * a '\0' into a '/' for a directory entry.
140          */
141         c1 = name1[len];
142         c2 = name2[len];
143         if (!c1 && !c2)
144                 /*
145                  * git-write-tree used to write out a nonsense tree that has
146                  * entries with the same name, one blob and one tree.  Make
147                  * sure we do not have duplicate entries.
148                  */
149                 return TREE_HAS_DUPS;
150         if (!c1 && S_ISDIR(mode1))
151                 c1 = '/';
152         if (!c2 && S_ISDIR(mode2))
153                 c2 = '/';
154         return c1 < c2 ? 0 : TREE_UNORDERED;
155 }
156
157 static int fsck_tree(struct tree *item)
158 {
159         int retval;
160         int has_full_path = 0;
161         int has_zero_pad = 0;
162         int has_bad_modes = 0;
163         int has_dup_entries = 0;
164         int not_properly_sorted = 0;
165         struct tree_desc desc;
166         unsigned o_mode;
167         const char *o_name;
168         const unsigned char *o_sha1;
169
170         desc.buf = item->buffer;
171         desc.size = item->size;
172
173         o_mode = 0;
174         o_name = NULL;
175         o_sha1 = NULL;
176         while (desc.size) {
177                 unsigned mode;
178                 const char *name;
179                 const unsigned char *sha1;
180
181                 sha1 = tree_entry_extract(&desc, &name, &mode);
182
183                 if (strchr(name, '/'))
184                         has_full_path = 1;
185                 has_zero_pad |= *(char *)desc.buf == '0';
186                 update_tree_entry(&desc);
187
188                 switch (mode) {
189                 /*
190                  * Standard modes..
191                  */
192                 case S_IFREG | 0755:
193                 case S_IFREG | 0644:
194                 case S_IFLNK:
195                 case S_IFDIR:
196                         break;
197                 /*
198                  * This is nonstandard, but we had a few of these
199                  * early on when we honored the full set of mode
200                  * bits..
201                  */
202                 case S_IFREG | 0664:
203                         if (!check_strict)
204                                 break;
205                 default:
206                         has_bad_modes = 1;
207                 }
208
209                 if (o_name) {
210                         switch (verify_ordered(o_mode, o_name, mode, name)) {
211                         case TREE_UNORDERED:
212                                 not_properly_sorted = 1;
213                                 break;
214                         case TREE_HAS_DUPS:
215                                 has_dup_entries = 1;
216                                 break;
217                         default:
218                                 break;
219                         }
220                 }
221
222                 o_mode = mode;
223                 o_name = name;
224                 o_sha1 = sha1;
225         }
226         free(item->buffer);
227         item->buffer = NULL;
228
229         retval = 0;
230         if (has_full_path) {
231                 objwarning(&item->object, "contains full pathnames");
232         }
233         if (has_zero_pad) {
234                 objwarning(&item->object, "contains zero-padded file modes");
235         }
236         if (has_bad_modes) {
237                 objwarning(&item->object, "contains bad file modes");
238         }
239         if (has_dup_entries) {
240                 retval = objerror(&item->object, "contains duplicate file entries");
241         }
242         if (not_properly_sorted) {
243                 retval = objerror(&item->object, "not properly sorted");
244         }
245         return retval;
246 }
247
248 static int fsck_commit(struct commit *commit)
249 {
250         char *buffer = commit->buffer;
251         unsigned char tree_sha1[20], sha1[20];
252
253         if (memcmp(buffer, "tree ", 5))
254                 return objerror(&commit->object, "invalid format - expected 'tree' line");
255         if (get_sha1_hex(buffer+5, tree_sha1) || buffer[45] != '\n')
256                 return objerror(&commit->object, "invalid 'tree' line format - bad sha1");
257         buffer += 46;
258         while (!memcmp(buffer, "parent ", 7)) {
259                 if (get_sha1_hex(buffer+7, sha1) || buffer[47] != '\n')
260                         return objerror(&commit->object, "invalid 'parent' line format - bad sha1");
261                 buffer += 48;
262         }
263         if (memcmp(buffer, "author ", 7))
264                 return objerror(&commit->object, "invalid format - expected 'author' line");
265         free(commit->buffer);
266         commit->buffer = NULL;
267         if (!commit->tree)
268                 return objerror(&commit->object, "could not load commit's tree %s", tree_sha1);
269         if (!commit->parents && show_root)
270                 printf("root %s\n", sha1_to_hex(commit->object.sha1));
271         if (!commit->date)
272                 printf("bad commit date in %s\n", 
273                        sha1_to_hex(commit->object.sha1));
274         return 0;
275 }
276
277 static int fsck_tag(struct tag *tag)
278 {
279         struct object *tagged = tag->tagged;
280
281         if (!tagged) {
282                 return objerror(&tag->object, "could not load tagged object");
283         }
284         if (!show_tags)
285                 return 0;
286
287         printf("tagged %s %s", typename(tagged->type), sha1_to_hex(tagged->sha1));
288         printf(" (%s) in %s\n", tag->tag, sha1_to_hex(tag->object.sha1));
289         return 0;
290 }
291
292 static int fsck_sha1(unsigned char *sha1)
293 {
294         struct object *obj = parse_object(sha1);
295         if (!obj)
296                 return error("%s: object not found", sha1_to_hex(sha1));
297         if (obj->flags & SEEN)
298                 return 0;
299         obj->flags |= SEEN;
300         if (obj->type == OBJ_BLOB)
301                 return 0;
302         if (obj->type == OBJ_TREE)
303                 return fsck_tree((struct tree *) obj);
304         if (obj->type == OBJ_COMMIT)
305                 return fsck_commit((struct commit *) obj);
306         if (obj->type == OBJ_TAG)
307                 return fsck_tag((struct tag *) obj);
308         /* By now, parse_object() would've returned NULL instead. */
309         return objerror(obj, "unknown type '%d' (internal fsck error)", obj->type);
310 }
311
312 /*
313  * This is the sorting chunk size: make it reasonably
314  * big so that we can sort well..
315  */
316 #define MAX_SHA1_ENTRIES (1024)
317
318 struct sha1_entry {
319         unsigned long ino;
320         unsigned char sha1[20];
321 };
322
323 static struct {
324         unsigned long nr;
325         struct sha1_entry *entry[MAX_SHA1_ENTRIES];
326 } sha1_list;
327
328 static int ino_compare(const void *_a, const void *_b)
329 {
330         const struct sha1_entry *a = _a, *b = _b;
331         unsigned long ino1 = a->ino, ino2 = b->ino;
332         return ino1 < ino2 ? -1 : ino1 > ino2 ? 1 : 0;
333 }
334
335 static void fsck_sha1_list(void)
336 {
337         int i, nr = sha1_list.nr;
338
339         if (SORT_DIRENT)
340                 qsort(sha1_list.entry, nr,
341                       sizeof(struct sha1_entry *), ino_compare);
342         for (i = 0; i < nr; i++) {
343                 struct sha1_entry *entry = sha1_list.entry[i];
344                 unsigned char *sha1 = entry->sha1;
345
346                 sha1_list.entry[i] = NULL;
347                 fsck_sha1(sha1);
348                 free(entry);
349         }
350         sha1_list.nr = 0;
351 }
352
353 static void add_sha1_list(unsigned char *sha1, unsigned long ino)
354 {
355         struct sha1_entry *entry = xmalloc(sizeof(*entry));
356         int nr;
357
358         entry->ino = ino;
359         hashcpy(entry->sha1, sha1);
360         nr = sha1_list.nr;
361         if (nr == MAX_SHA1_ENTRIES) {
362                 fsck_sha1_list();
363                 nr = 0;
364         }
365         sha1_list.entry[nr] = entry;
366         sha1_list.nr = ++nr;
367 }
368
369 static void fsck_dir(int i, char *path)
370 {
371         DIR *dir = opendir(path);
372         struct dirent *de;
373
374         if (!dir)
375                 return;
376
377         while ((de = readdir(dir)) != NULL) {
378                 char name[100];
379                 unsigned char sha1[20];
380                 int len = strlen(de->d_name);
381
382                 switch (len) {
383                 case 2:
384                         if (de->d_name[1] != '.')
385                                 break;
386                 case 1:
387                         if (de->d_name[0] != '.')
388                                 break;
389                         continue;
390                 case 38:
391                         sprintf(name, "%02x", i);
392                         memcpy(name+2, de->d_name, len+1);
393                         if (get_sha1_hex(name, sha1) < 0)
394                                 break;
395                         add_sha1_list(sha1, DIRENT_SORT_HINT(de));
396                         continue;
397                 }
398                 fprintf(stderr, "bad sha1 file: %s/%s\n", path, de->d_name);
399         }
400         closedir(dir);
401 }
402
403 static int default_refs;
404
405 static int fsck_handle_ref(const char *refname, const unsigned char *sha1, int flag, void *cb_data)
406 {
407         struct object *obj;
408
409         obj = lookup_object(sha1);
410         if (!obj) {
411                 if (has_sha1_file(sha1)) {
412                         default_refs++;
413                         return 0; /* it is in a pack */
414                 }
415                 error("%s: invalid sha1 pointer %s", refname, sha1_to_hex(sha1));
416                 /* We'll continue with the rest despite the error.. */
417                 return 0;
418         }
419         default_refs++;
420         obj->used = 1;
421         mark_reachable(obj, REACHABLE);
422         return 0;
423 }
424
425 static void get_default_heads(void)
426 {
427         for_each_ref(fsck_handle_ref, NULL);
428
429         /*
430          * Not having any default heads isn't really fatal, but
431          * it does mean that "--unreachable" no longer makes any
432          * sense (since in this case everything will obviously
433          * be unreachable by definition.
434          *
435          * Showing dangling objects is valid, though (as those
436          * dangling objects are likely lost heads).
437          *
438          * So we just print a warning about it, and clear the
439          * "show_unreachable" flag.
440          */
441         if (!default_refs) {
442                 error("No default references");
443                 show_unreachable = 0;
444         }
445 }
446
447 static void fsck_object_dir(const char *path)
448 {
449         int i;
450         for (i = 0; i < 256; i++) {
451                 static char dir[4096];
452                 sprintf(dir, "%s/%02x", path, i);
453                 fsck_dir(i, dir);
454         }
455         fsck_sha1_list();
456 }
457
458 static int fsck_head_link(void)
459 {
460         unsigned char sha1[20];
461         int flag;
462         const char *head_points_at = resolve_ref("HEAD", sha1, 1, &flag);
463
464         if (!head_points_at || !(flag & REF_ISSYMREF))
465                 return error("HEAD is not a symbolic ref");
466         if (strncmp(head_points_at, "refs/heads/", 11))
467                 return error("HEAD points to something strange (%s)",
468                              head_points_at);
469         if (is_null_sha1(sha1))
470                 return error("HEAD: not a valid git pointer");
471         return 0;
472 }
473
474 static int fsck_cache_tree(struct cache_tree *it)
475 {
476         int i;
477         int err = 0;
478
479         if (0 <= it->entry_count) {
480                 struct object *obj = parse_object(it->sha1);
481                 if (!obj) {
482                         error("%s: invalid sha1 pointer in cache-tree",
483                               sha1_to_hex(it->sha1));
484                         return 1;
485                 }
486                 mark_reachable(obj, REACHABLE);
487                 obj->used = 1;
488                 if (obj->type != OBJ_TREE)
489                         err |= objerror(obj, "non-tree in cache-tree");
490         }
491         for (i = 0; i < it->subtree_nr; i++)
492                 err |= fsck_cache_tree(it->down[i]->cache_tree);
493         return err;
494 }
495
496 int main(int argc, char **argv)
497 {
498         int i, heads;
499
500         track_object_refs = 1;
501         setup_git_directory();
502
503         for (i = 1; i < argc; i++) {
504                 const char *arg = argv[i];
505
506                 if (!strcmp(arg, "--unreachable")) {
507                         show_unreachable = 1;
508                         continue;
509                 }
510                 if (!strcmp(arg, "--tags")) {
511                         show_tags = 1;
512                         continue;
513                 }
514                 if (!strcmp(arg, "--root")) {
515                         show_root = 1;
516                         continue;
517                 }
518                 if (!strcmp(arg, "--cache")) {
519                         keep_cache_objects = 1;
520                         continue;
521                 }
522                 if (!strcmp(arg, "--full")) {
523                         check_full = 1;
524                         continue;
525                 }
526                 if (!strcmp(arg, "--strict")) {
527                         check_strict = 1;
528                         continue;
529                 }
530                 if (*arg == '-')
531                         usage("git-fsck-objects [--tags] [--root] [[--unreachable] [--cache] [--full] [--strict] <head-sha1>*]");
532         }
533
534         fsck_head_link();
535         fsck_object_dir(get_object_directory());
536         if (check_full) {
537                 struct alternate_object_database *alt;
538                 struct packed_git *p;
539                 prepare_alt_odb();
540                 for (alt = alt_odb_list; alt; alt = alt->next) {
541                         char namebuf[PATH_MAX];
542                         int namelen = alt->name - alt->base;
543                         memcpy(namebuf, alt->base, namelen);
544                         namebuf[namelen - 1] = 0;
545                         fsck_object_dir(namebuf);
546                 }
547                 prepare_packed_git();
548                 for (p = packed_git; p; p = p->next)
549                         /* verify gives error messages itself */
550                         verify_pack(p, 0);
551
552                 for (p = packed_git; p; p = p->next) {
553                         int num = num_packed_objects(p);
554                         for (i = 0; i < num; i++) {
555                                 unsigned char sha1[20];
556                                 nth_packed_object_sha1(p, i, sha1);
557                                 fsck_sha1(sha1);
558                         }
559                 }
560         }
561
562         heads = 0;
563         for (i = 1; i < argc; i++) {
564                 const char *arg = argv[i]; 
565
566                 if (*arg == '-')
567                         continue;
568
569                 if (!get_sha1(arg, head_sha1)) {
570                         struct object *obj = lookup_object(head_sha1);
571
572                         /* Error is printed by lookup_object(). */
573                         if (!obj)
574                                 continue;
575
576                         obj->used = 1;
577                         mark_reachable(obj, REACHABLE);
578                         heads++;
579                         continue;
580                 }
581                 error("invalid parameter: expected sha1, got '%s'", arg);
582         }
583
584         /*
585          * If we've not been given any explicit head information, do the
586          * default ones from .git/refs. We also consider the index file
587          * in this case (ie this implies --cache).
588          */
589         if (!heads) {
590                 get_default_heads();
591                 keep_cache_objects = 1;
592         }
593
594         if (keep_cache_objects) {
595                 int i;
596                 read_cache();
597                 for (i = 0; i < active_nr; i++) {
598                         struct blob *blob = lookup_blob(active_cache[i]->sha1);
599                         struct object *obj;
600                         if (!blob)
601                                 continue;
602                         obj = &blob->object;
603                         obj->used = 1;
604                         mark_reachable(obj, REACHABLE);
605                 }
606                 if (active_cache_tree)
607                         fsck_cache_tree(active_cache_tree);
608         }
609
610         check_connectivity();
611         return 0;
612 }