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