1#include "builtin.h"
2#include "cache.h"
3#include "commit.h"
4#include "tree.h"
5#include "blob.h"
6#include "tag.h"
7#include "refs.h"
8#include "pack.h"
9#include "cache-tree.h"
10#include "tree-walk.h"
11#include "parse-options.h"
12
13#define REACHABLE 0x0001
14#define SEEN 0x0002
15
16static int show_root;
17static int show_tags;
18static int show_unreachable;
19static int include_reflogs = 1;
20static int check_full;
21static int check_strict;
22static int keep_cache_objects;
23static unsigned char head_sha1[20];
24static int errors_found;
25static int write_lost_and_found;
26static int verbose;
27#define ERROR_OBJECT 01
28#define ERROR_REACHABLE 02
29
30#ifdef NO_D_INO_IN_DIRENT
31#define SORT_DIRENT 0
32#define DIRENT_SORT_HINT(de) 0
33#else
34#define SORT_DIRENT 1
35#define DIRENT_SORT_HINT(de) ((de)->d_ino)
36#endif
37
38static void objreport(struct object *obj, const char *severity,
39 const char *err, va_list params)
40{
41 fprintf(stderr, "%s in %s %s: ",
42 severity, typename(obj->type), sha1_to_hex(obj->sha1));
43 vfprintf(stderr, err, params);
44 fputs("\n", stderr);
45}
46
47static int objerror(struct object *obj, const char *err, ...)
48{
49 va_list params;
50 va_start(params, err);
51 errors_found |= ERROR_OBJECT;
52 objreport(obj, "error", err, params);
53 va_end(params);
54 return -1;
55}
56
57static int objwarning(struct object *obj, const char *err, ...)
58{
59 va_list params;
60 va_start(params, err);
61 objreport(obj, "warning", err, params);
62 va_end(params);
63 return -1;
64}
65
66/*
67 * Check a single reachable object
68 */
69static void check_reachable_object(struct object *obj)
70{
71 const struct object_refs *refs;
72
73 /*
74 * We obviously want the object to be parsed,
75 * except if it was in a pack-file and we didn't
76 * do a full fsck
77 */
78 if (!obj->parsed) {
79 if (has_sha1_pack(obj->sha1, NULL))
80 return; /* it is in pack - forget about it */
81 printf("missing %s %s\n", typename(obj->type), sha1_to_hex(obj->sha1));
82 errors_found |= ERROR_REACHABLE;
83 return;
84 }
85
86 /*
87 * Check that everything that we try to reference is also good.
88 */
89 refs = lookup_object_refs(obj);
90 if (refs) {
91 unsigned j;
92 for (j = 0; j < refs->count; j++) {
93 struct object *ref = refs->ref[j];
94 if (ref->parsed ||
95 (has_sha1_file(ref->sha1)))
96 continue;
97 printf("broken link from %7s %s\n",
98 typename(obj->type), sha1_to_hex(obj->sha1));
99 printf(" to %7s %s\n",
100 typename(ref->type), sha1_to_hex(ref->sha1));
101 errors_found |= ERROR_REACHABLE;
102 }
103 }
104}
105
106/*
107 * Check a single unreachable object
108 */
109static void check_unreachable_object(struct object *obj)
110{
111 /*
112 * Missing unreachable object? Ignore it. It's not like
113 * we miss it (since it can't be reached), nor do we want
114 * to complain about it being unreachable (since it does
115 * not exist).
116 */
117 if (!obj->parsed)
118 return;
119
120 /*
121 * Unreachable object that exists? Show it if asked to,
122 * since this is something that is prunable.
123 */
124 if (show_unreachable) {
125 printf("unreachable %s %s\n", typename(obj->type), sha1_to_hex(obj->sha1));
126 return;
127 }
128
129 /*
130 * "!used" means that nothing at all points to it, including
131 * other unreachable objects. In other words, it's the "tip"
132 * of some set of unreachable objects, usually a commit that
133 * got dropped.
134 *
135 * Such starting points are more interesting than some random
136 * set of unreachable objects, so we show them even if the user
137 * hasn't asked for _all_ unreachable objects. If you have
138 * deleted a branch by mistake, this is a prime candidate to
139 * start looking at, for example.
140 */
141 if (!obj->used) {
142 printf("dangling %s %s\n", typename(obj->type),
143 sha1_to_hex(obj->sha1));
144 if (write_lost_and_found) {
145 char *filename = git_path("lost-found/%s/%s",
146 obj->type == OBJ_COMMIT ? "commit" : "other",
147 sha1_to_hex(obj->sha1));
148 FILE *f;
149
150 if (safe_create_leading_directories(filename)) {
151 error("Could not create lost-found");
152 return;
153 }
154 if (!(f = fopen(filename, "w")))
155 die("Could not open %s", filename);
156 if (obj->type == OBJ_BLOB) {
157 enum object_type type;
158 unsigned long size;
159 char *buf = read_sha1_file(obj->sha1,
160 &type, &size);
161 if (buf) {
162 fwrite(buf, size, 1, f);
163 free(buf);
164 }
165 } else
166 fprintf(f, "%s\n", sha1_to_hex(obj->sha1));
167 fclose(f);
168 }
169 return;
170 }
171
172 /*
173 * Otherwise? It's there, it's unreachable, and some other unreachable
174 * object points to it. Ignore it - it's not interesting, and we showed
175 * all the interesting cases above.
176 */
177}
178
179static void check_object(struct object *obj)
180{
181 if (verbose)
182 fprintf(stderr, "Checking %s\n", sha1_to_hex(obj->sha1));
183
184 if (obj->flags & REACHABLE)
185 check_reachable_object(obj);
186 else
187 check_unreachable_object(obj);
188}
189
190static void check_connectivity(void)
191{
192 int i, max;
193
194 /* Look up all the requirements, warn about missing objects.. */
195 max = get_max_object_index();
196 if (verbose)
197 fprintf(stderr, "Checking connectivity (%d objects)\n", max);
198
199 for (i = 0; i < max; i++) {
200 struct object *obj = get_indexed_object(i);
201
202 if (obj)
203 check_object(obj);
204 }
205}
206
207/*
208 * The entries in a tree are ordered in the _path_ order,
209 * which means that a directory entry is ordered by adding
210 * a slash to the end of it.
211 *
212 * So a directory called "a" is ordered _after_ a file
213 * called "a.c", because "a/" sorts after "a.c".
214 */
215#define TREE_UNORDERED (-1)
216#define TREE_HAS_DUPS (-2)
217
218static int verify_ordered(unsigned mode1, const char *name1, unsigned mode2, const char *name2)
219{
220 int len1 = strlen(name1);
221 int len2 = strlen(name2);
222 int len = len1 < len2 ? len1 : len2;
223 unsigned char c1, c2;
224 int cmp;
225
226 cmp = memcmp(name1, name2, len);
227 if (cmp < 0)
228 return 0;
229 if (cmp > 0)
230 return TREE_UNORDERED;
231
232 /*
233 * Ok, the first <len> characters are the same.
234 * Now we need to order the next one, but turn
235 * a '\0' into a '/' for a directory entry.
236 */
237 c1 = name1[len];
238 c2 = name2[len];
239 if (!c1 && !c2)
240 /*
241 * git-write-tree used to write out a nonsense tree that has
242 * entries with the same name, one blob and one tree. Make
243 * sure we do not have duplicate entries.
244 */
245 return TREE_HAS_DUPS;
246 if (!c1 && S_ISDIR(mode1))
247 c1 = '/';
248 if (!c2 && S_ISDIR(mode2))
249 c2 = '/';
250 return c1 < c2 ? 0 : TREE_UNORDERED;
251}
252
253static int fsck_tree(struct tree *item)
254{
255 int retval;
256 int has_full_path = 0;
257 int has_empty_name = 0;
258 int has_zero_pad = 0;
259 int has_bad_modes = 0;
260 int has_dup_entries = 0;
261 int not_properly_sorted = 0;
262 struct tree_desc desc;
263 unsigned o_mode;
264 const char *o_name;
265 const unsigned char *o_sha1;
266
267 if (verbose)
268 fprintf(stderr, "Checking tree %s\n",
269 sha1_to_hex(item->object.sha1));
270
271 init_tree_desc(&desc, item->buffer, item->size);
272
273 o_mode = 0;
274 o_name = NULL;
275 o_sha1 = NULL;
276 while (desc.size) {
277 unsigned mode;
278 const char *name;
279 const unsigned char *sha1;
280
281 sha1 = tree_entry_extract(&desc, &name, &mode);
282
283 if (strchr(name, '/'))
284 has_full_path = 1;
285 if (!*name)
286 has_empty_name = 1;
287 has_zero_pad |= *(char *)desc.buffer == '0';
288 update_tree_entry(&desc);
289
290 switch (mode) {
291 /*
292 * Standard modes..
293 */
294 case S_IFREG | 0755:
295 case S_IFREG | 0644:
296 case S_IFLNK:
297 case S_IFDIR:
298 case S_IFGITLINK:
299 break;
300 /*
301 * This is nonstandard, but we had a few of these
302 * early on when we honored the full set of mode
303 * bits..
304 */
305 case S_IFREG | 0664:
306 if (!check_strict)
307 break;
308 default:
309 has_bad_modes = 1;
310 }
311
312 if (o_name) {
313 switch (verify_ordered(o_mode, o_name, mode, name)) {
314 case TREE_UNORDERED:
315 not_properly_sorted = 1;
316 break;
317 case TREE_HAS_DUPS:
318 has_dup_entries = 1;
319 break;
320 default:
321 break;
322 }
323 }
324
325 o_mode = mode;
326 o_name = name;
327 o_sha1 = sha1;
328 }
329 free(item->buffer);
330 item->buffer = NULL;
331
332 retval = 0;
333 if (has_full_path) {
334 objwarning(&item->object, "contains full pathnames");
335 }
336 if (has_empty_name) {
337 objwarning(&item->object, "contains empty pathname");
338 }
339 if (has_zero_pad) {
340 objwarning(&item->object, "contains zero-padded file modes");
341 }
342 if (has_bad_modes) {
343 objwarning(&item->object, "contains bad file modes");
344 }
345 if (has_dup_entries) {
346 retval = objerror(&item->object, "contains duplicate file entries");
347 }
348 if (not_properly_sorted) {
349 retval = objerror(&item->object, "not properly sorted");
350 }
351 return retval;
352}
353
354static int fsck_commit(struct commit *commit)
355{
356 char *buffer = commit->buffer;
357 unsigned char tree_sha1[20], sha1[20];
358
359 if (verbose)
360 fprintf(stderr, "Checking commit %s\n",
361 sha1_to_hex(commit->object.sha1));
362
363 if (memcmp(buffer, "tree ", 5))
364 return objerror(&commit->object, "invalid format - expected 'tree' line");
365 if (get_sha1_hex(buffer+5, tree_sha1) || buffer[45] != '\n')
366 return objerror(&commit->object, "invalid 'tree' line format - bad sha1");
367 buffer += 46;
368 while (!memcmp(buffer, "parent ", 7)) {
369 if (get_sha1_hex(buffer+7, sha1) || buffer[47] != '\n')
370 return objerror(&commit->object, "invalid 'parent' line format - bad sha1");
371 buffer += 48;
372 }
373 if (memcmp(buffer, "author ", 7))
374 return objerror(&commit->object, "invalid format - expected 'author' line");
375 free(commit->buffer);
376 commit->buffer = NULL;
377 if (!commit->tree)
378 return objerror(&commit->object, "could not load commit's tree %s", tree_sha1);
379 if (!commit->parents && show_root)
380 printf("root %s\n", sha1_to_hex(commit->object.sha1));
381 if (!commit->date)
382 printf("bad commit date in %s\n",
383 sha1_to_hex(commit->object.sha1));
384 return 0;
385}
386
387static int fsck_tag(struct tag *tag)
388{
389 struct object *tagged = tag->tagged;
390
391 if (verbose)
392 fprintf(stderr, "Checking tag %s\n",
393 sha1_to_hex(tag->object.sha1));
394
395 if (!tagged) {
396 return objerror(&tag->object, "could not load tagged object");
397 }
398 if (!show_tags)
399 return 0;
400
401 printf("tagged %s %s", typename(tagged->type), sha1_to_hex(tagged->sha1));
402 printf(" (%s) in %s\n", tag->tag, sha1_to_hex(tag->object.sha1));
403 return 0;
404}
405
406static int fsck_sha1(const unsigned char *sha1)
407{
408 struct object *obj = parse_object(sha1);
409 if (!obj) {
410 errors_found |= ERROR_OBJECT;
411 return error("%s: object corrupt or missing",
412 sha1_to_hex(sha1));
413 }
414 if (obj->flags & SEEN)
415 return 0;
416 obj->flags |= SEEN;
417 if (obj->type == OBJ_BLOB)
418 return 0;
419 if (obj->type == OBJ_TREE)
420 return fsck_tree((struct tree *) obj);
421 if (obj->type == OBJ_COMMIT)
422 return fsck_commit((struct commit *) obj);
423 if (obj->type == OBJ_TAG)
424 return fsck_tag((struct tag *) obj);
425
426 /* By now, parse_object() would've returned NULL instead. */
427 return objerror(obj, "unknown type '%d' (internal fsck error)",
428 obj->type);
429}
430
431/*
432 * This is the sorting chunk size: make it reasonably
433 * big so that we can sort well..
434 */
435#define MAX_SHA1_ENTRIES (1024)
436
437struct sha1_entry {
438 unsigned long ino;
439 unsigned char sha1[20];
440};
441
442static struct {
443 unsigned long nr;
444 struct sha1_entry *entry[MAX_SHA1_ENTRIES];
445} sha1_list;
446
447static int ino_compare(const void *_a, const void *_b)
448{
449 const struct sha1_entry *a = _a, *b = _b;
450 unsigned long ino1 = a->ino, ino2 = b->ino;
451 return ino1 < ino2 ? -1 : ino1 > ino2 ? 1 : 0;
452}
453
454static void fsck_sha1_list(void)
455{
456 int i, nr = sha1_list.nr;
457
458 if (SORT_DIRENT)
459 qsort(sha1_list.entry, nr,
460 sizeof(struct sha1_entry *), ino_compare);
461 for (i = 0; i < nr; i++) {
462 struct sha1_entry *entry = sha1_list.entry[i];
463 unsigned char *sha1 = entry->sha1;
464
465 sha1_list.entry[i] = NULL;
466 fsck_sha1(sha1);
467 free(entry);
468 }
469 sha1_list.nr = 0;
470}
471
472static void add_sha1_list(unsigned char *sha1, unsigned long ino)
473{
474 struct sha1_entry *entry = xmalloc(sizeof(*entry));
475 int nr;
476
477 entry->ino = ino;
478 hashcpy(entry->sha1, sha1);
479 nr = sha1_list.nr;
480 if (nr == MAX_SHA1_ENTRIES) {
481 fsck_sha1_list();
482 nr = 0;
483 }
484 sha1_list.entry[nr] = entry;
485 sha1_list.nr = ++nr;
486}
487
488static void fsck_dir(int i, char *path)
489{
490 DIR *dir = opendir(path);
491 struct dirent *de;
492
493 if (!dir)
494 return;
495
496 if (verbose)
497 fprintf(stderr, "Checking directory %s\n", path);
498
499 while ((de = readdir(dir)) != NULL) {
500 char name[100];
501 unsigned char sha1[20];
502 int len = strlen(de->d_name);
503
504 switch (len) {
505 case 2:
506 if (de->d_name[1] != '.')
507 break;
508 case 1:
509 if (de->d_name[0] != '.')
510 break;
511 continue;
512 case 38:
513 sprintf(name, "%02x", i);
514 memcpy(name+2, de->d_name, len+1);
515 if (get_sha1_hex(name, sha1) < 0)
516 break;
517 add_sha1_list(sha1, DIRENT_SORT_HINT(de));
518 continue;
519 }
520 fprintf(stderr, "bad sha1 file: %s/%s\n", path, de->d_name);
521 }
522 closedir(dir);
523}
524
525static int default_refs;
526
527static int fsck_handle_reflog_ent(unsigned char *osha1, unsigned char *nsha1,
528 const char *email, unsigned long timestamp, int tz,
529 const char *message, void *cb_data)
530{
531 struct object *obj;
532
533 if (verbose)
534 fprintf(stderr, "Checking reflog %s->%s\n",
535 sha1_to_hex(osha1), sha1_to_hex(nsha1));
536
537 if (!is_null_sha1(osha1)) {
538 obj = lookup_object(osha1);
539 if (obj) {
540 obj->used = 1;
541 mark_reachable(obj, REACHABLE);
542 }
543 }
544 obj = lookup_object(nsha1);
545 if (obj) {
546 obj->used = 1;
547 mark_reachable(obj, REACHABLE);
548 }
549 return 0;
550}
551
552static int fsck_handle_reflog(const char *logname, const unsigned char *sha1, int flag, void *cb_data)
553{
554 for_each_reflog_ent(logname, fsck_handle_reflog_ent, NULL);
555 return 0;
556}
557
558static int fsck_handle_ref(const char *refname, const unsigned char *sha1, int flag, void *cb_data)
559{
560 struct object *obj;
561
562 obj = lookup_object(sha1);
563 if (!obj) {
564 if (has_sha1_file(sha1)) {
565 default_refs++;
566 return 0; /* it is in a pack */
567 }
568 error("%s: invalid sha1 pointer %s", refname, sha1_to_hex(sha1));
569 /* We'll continue with the rest despite the error.. */
570 return 0;
571 }
572 default_refs++;
573 obj->used = 1;
574 mark_reachable(obj, REACHABLE);
575
576 return 0;
577}
578
579static void get_default_heads(void)
580{
581 for_each_ref(fsck_handle_ref, NULL);
582 if (include_reflogs)
583 for_each_reflog(fsck_handle_reflog, NULL);
584
585 /*
586 * Not having any default heads isn't really fatal, but
587 * it does mean that "--unreachable" no longer makes any
588 * sense (since in this case everything will obviously
589 * be unreachable by definition.
590 *
591 * Showing dangling objects is valid, though (as those
592 * dangling objects are likely lost heads).
593 *
594 * So we just print a warning about it, and clear the
595 * "show_unreachable" flag.
596 */
597 if (!default_refs) {
598 fprintf(stderr, "notice: No default references\n");
599 show_unreachable = 0;
600 }
601}
602
603static void fsck_object_dir(const char *path)
604{
605 int i;
606
607 if (verbose)
608 fprintf(stderr, "Checking object directory\n");
609
610 for (i = 0; i < 256; i++) {
611 static char dir[4096];
612 sprintf(dir, "%s/%02x", path, i);
613 fsck_dir(i, dir);
614 }
615 fsck_sha1_list();
616}
617
618static int fsck_head_link(void)
619{
620 unsigned char sha1[20];
621 int flag;
622 int null_is_error = 0;
623 const char *head_points_at = resolve_ref("HEAD", sha1, 0, &flag);
624
625 if (verbose)
626 fprintf(stderr, "Checking HEAD link\n");
627
628 if (!head_points_at)
629 return error("Invalid HEAD");
630 if (!strcmp(head_points_at, "HEAD"))
631 /* detached HEAD */
632 null_is_error = 1;
633 else if (prefixcmp(head_points_at, "refs/heads/"))
634 return error("HEAD points to something strange (%s)",
635 head_points_at);
636 if (is_null_sha1(sha1)) {
637 if (null_is_error)
638 return error("HEAD: detached HEAD points at nothing");
639 fprintf(stderr, "notice: HEAD points to an unborn branch (%s)\n",
640 head_points_at + 11);
641 }
642 return 0;
643}
644
645static int fsck_cache_tree(struct cache_tree *it)
646{
647 int i;
648 int err = 0;
649
650 if (verbose)
651 fprintf(stderr, "Checking cache tree\n");
652
653 if (0 <= it->entry_count) {
654 struct object *obj = parse_object(it->sha1);
655 if (!obj) {
656 error("%s: invalid sha1 pointer in cache-tree",
657 sha1_to_hex(it->sha1));
658 return 1;
659 }
660 mark_reachable(obj, REACHABLE);
661 obj->used = 1;
662 if (obj->type != OBJ_TREE)
663 err |= objerror(obj, "non-tree in cache-tree");
664 }
665 for (i = 0; i < it->subtree_nr; i++)
666 err |= fsck_cache_tree(it->down[i]->cache_tree);
667 return err;
668}
669
670static char const * const fsck_usage[] = {
671 "git-fsck [options] [<object>...]",
672 NULL
673};
674
675static struct option fsck_opts[] = {
676 OPT__VERBOSE(&verbose),
677 OPT_BOOLEAN(0, "unreachable", &show_unreachable, "show unreachable objects"),
678 OPT_BOOLEAN(0, "tags", &show_tags, "report tags"),
679 OPT_BOOLEAN(0, "root", &show_root, "report root nodes"),
680 OPT_BOOLEAN(0, "cache", &keep_cache_objects, "make index objects head nodes"),
681 OPT_BOOLEAN(0, "reflogs", &include_reflogs, "make reflogs head nodes (default)"),
682 OPT_BOOLEAN(0, "full", &check_full, "also consider alternate objects"),
683 OPT_BOOLEAN(0, "strict", &check_strict, "enable more strict checking"),
684 OPT_BOOLEAN(0, "lost-found", &write_lost_and_found,
685 "write dangling objects in .git/lost-found"),
686 OPT_END(),
687};
688
689int cmd_fsck(int argc, const char **argv, const char *prefix)
690{
691 int i, heads;
692
693 track_object_refs = 1;
694 errors_found = 0;
695
696 argc = parse_options(argc, argv, fsck_opts, fsck_usage, 0);
697 if (write_lost_and_found) {
698 check_full = 1;
699 include_reflogs = 0;
700 }
701
702 fsck_head_link();
703 fsck_object_dir(get_object_directory());
704 if (check_full) {
705 struct alternate_object_database *alt;
706 struct packed_git *p;
707 prepare_alt_odb();
708 for (alt = alt_odb_list; alt; alt = alt->next) {
709 char namebuf[PATH_MAX];
710 int namelen = alt->name - alt->base;
711 memcpy(namebuf, alt->base, namelen);
712 namebuf[namelen - 1] = 0;
713 fsck_object_dir(namebuf);
714 }
715 prepare_packed_git();
716 for (p = packed_git; p; p = p->next)
717 /* verify gives error messages itself */
718 verify_pack(p, 0);
719
720 for (p = packed_git; p; p = p->next) {
721 uint32_t j, num;
722 if (open_pack_index(p))
723 continue;
724 num = p->num_objects;
725 for (j = 0; j < num; j++)
726 fsck_sha1(nth_packed_object_sha1(p, j));
727 }
728 }
729
730 heads = 0;
731 for (i = 1; i < argc; i++) {
732 const char *arg = argv[i];
733 if (!get_sha1(arg, head_sha1)) {
734 struct object *obj = lookup_object(head_sha1);
735
736 /* Error is printed by lookup_object(). */
737 if (!obj)
738 continue;
739
740 obj->used = 1;
741 mark_reachable(obj, REACHABLE);
742 heads++;
743 continue;
744 }
745 error("invalid parameter: expected sha1, got '%s'", arg);
746 }
747
748 /*
749 * If we've not been given any explicit head information, do the
750 * default ones from .git/refs. We also consider the index file
751 * in this case (ie this implies --cache).
752 */
753 if (!heads) {
754 get_default_heads();
755 keep_cache_objects = 1;
756 }
757
758 if (keep_cache_objects) {
759 read_cache();
760 for (i = 0; i < active_nr; i++) {
761 unsigned int mode;
762 struct blob *blob;
763 struct object *obj;
764
765 mode = ntohl(active_cache[i]->ce_mode);
766 if (S_ISGITLINK(mode))
767 continue;
768 blob = lookup_blob(active_cache[i]->sha1);
769 if (!blob)
770 continue;
771 obj = &blob->object;
772 obj->used = 1;
773 mark_reachable(obj, REACHABLE);
774 }
775 if (active_cache_tree)
776 fsck_cache_tree(active_cache_tree);
777 }
778
779 check_connectivity();
780 return errors_found;
781}