unquote_c_style: fix off-by-one.
[git/dscho.git] / builtin-fsck.c
blob2a6e94deaf6b27f27ad7655ebf6072a05b25017c
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"
13 #define REACHABLE 0x0001
14 #define SEEN      0x0002
16 static int show_root;
17 static int show_tags;
18 static int show_unreachable;
19 static int include_reflogs = 1;
20 static int check_full;
21 static int check_strict;
22 static int keep_cache_objects;
23 static unsigned char head_sha1[20];
24 static int errors_found;
25 static int write_lost_and_found;
26 static int verbose;
27 #define ERROR_OBJECT 01
28 #define ERROR_REACHABLE 02
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
38 static void objreport(struct object *obj, const char *severity,
39                       const char *err, va_list params)
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);
47 static int objerror(struct object *obj, const char *err, ...)
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;
57 static int objwarning(struct object *obj, const char *err, ...)
59         va_list params;
60         va_start(params, err);
61         objreport(obj, "warning", err, params);
62         va_end(params);
63         return -1;
67  * Check a single reachable object
68  */
69 static void check_reachable_object(struct object *obj)
71         const struct object_refs *refs;
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         }
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         }
107  * Check a single unreachable object
108  */
109 static void check_unreachable_object(struct object *obj)
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;
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         }
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;
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         }
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          */
179 static void check_object(struct object *obj)
181         if (verbose)
182                 fprintf(stderr, "Checking %s\n", sha1_to_hex(obj->sha1));
184         if (obj->flags & REACHABLE)
185                 check_reachable_object(obj);
186         else
187                 check_unreachable_object(obj);
190 static void check_connectivity(void)
192         int i, max;
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);
199         for (i = 0; i < max; i++) {
200                 struct object *obj = get_indexed_object(i);
202                 if (obj)
203                         check_object(obj);
204         }
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.
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)
218 static int verify_ordered(unsigned mode1, const char *name1, unsigned mode2, const char *name2)
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;
226         cmp = memcmp(name1, name2, len);
227         if (cmp < 0)
228                 return 0;
229         if (cmp > 0)
230                 return TREE_UNORDERED;
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;
253 static int fsck_tree(struct tree *item)
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;
267         if (verbose)
268                 fprintf(stderr, "Checking tree %s\n",
269                                 sha1_to_hex(item->object.sha1));
271         init_tree_desc(&desc, item->buffer, item->size);
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;
281                 sha1 = tree_entry_extract(&desc, &name, &mode);
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);
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                 }
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                 }
325                 o_mode = mode;
326                 o_name = name;
327                 o_sha1 = sha1;
328         }
329         free(item->buffer);
330         item->buffer = NULL;
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;
354 static int fsck_commit(struct commit *commit)
356         char *buffer = commit->buffer;
357         unsigned char tree_sha1[20], sha1[20];
359         if (verbose)
360                 fprintf(stderr, "Checking commit %s\n",
361                         sha1_to_hex(commit->object.sha1));
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;
387 static int fsck_tag(struct tag *tag)
389         struct object *tagged = tag->tagged;
391         if (verbose)
392                 fprintf(stderr, "Checking tag %s\n",
393                         sha1_to_hex(tag->object.sha1));
395         if (!tagged) {
396                 return objerror(&tag->object, "could not load tagged object");
397         }
398         if (!show_tags)
399                 return 0;
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;
406 static int fsck_sha1(const unsigned char *sha1)
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);
426         /* By now, parse_object() would've returned NULL instead. */
427         return objerror(obj, "unknown type '%d' (internal fsck error)",
428                         obj->type);
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)
437 struct sha1_entry {
438         unsigned long ino;
439         unsigned char sha1[20];
442 static struct {
443         unsigned long nr;
444         struct sha1_entry *entry[MAX_SHA1_ENTRIES];
445 } sha1_list;
447 static int ino_compare(const void *_a, const void *_b)
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;
454 static void fsck_sha1_list(void)
456         int i, nr = sha1_list.nr;
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;
465                 sha1_list.entry[i] = NULL;
466                 fsck_sha1(sha1);
467                 free(entry);
468         }
469         sha1_list.nr = 0;
472 static void add_sha1_list(unsigned char *sha1, unsigned long ino)
474         struct sha1_entry *entry = xmalloc(sizeof(*entry));
475         int nr;
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;
488 static void fsck_dir(int i, char *path)
490         DIR *dir = opendir(path);
491         struct dirent *de;
493         if (!dir)
494                 return;
496         if (verbose)
497                 fprintf(stderr, "Checking directory %s\n", path);
499         while ((de = readdir(dir)) != NULL) {
500                 char name[100];
501                 unsigned char sha1[20];
502                 int len = strlen(de->d_name);
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);
525 static int default_refs;
527 static 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)
531         struct object *obj;
533         if (verbose)
534                 fprintf(stderr, "Checking reflog %s->%s\n",
535                         sha1_to_hex(osha1), sha1_to_hex(nsha1));
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;
552 static int fsck_handle_reflog(const char *logname, const unsigned char *sha1, int flag, void *cb_data)
554         for_each_reflog_ent(logname, fsck_handle_reflog_ent, NULL);
555         return 0;
558 static int is_branch(const char *refname)
560         return !strcmp(refname, "HEAD") || !prefixcmp(refname, "refs/heads/");
563 static int fsck_handle_ref(const char *refname, const unsigned char *sha1, int flag, void *cb_data)
565         struct object *obj;
567         obj = parse_object(sha1);
568         if (!obj) {
569                 error("%s: invalid sha1 pointer %s", refname, sha1_to_hex(sha1));
570                 /* We'll continue with the rest despite the error.. */
571                 return 0;
572         }
573         if (obj->type != OBJ_COMMIT && is_branch(refname))
574                 error("%s: not a commit", refname);
575         default_refs++;
576         obj->used = 1;
577         mark_reachable(obj, REACHABLE);
579         return 0;
582 static void get_default_heads(void)
584         for_each_ref(fsck_handle_ref, NULL);
585         if (include_reflogs)
586                 for_each_reflog(fsck_handle_reflog, NULL);
588         /*
589          * Not having any default heads isn't really fatal, but
590          * it does mean that "--unreachable" no longer makes any
591          * sense (since in this case everything will obviously
592          * be unreachable by definition.
593          *
594          * Showing dangling objects is valid, though (as those
595          * dangling objects are likely lost heads).
596          *
597          * So we just print a warning about it, and clear the
598          * "show_unreachable" flag.
599          */
600         if (!default_refs) {
601                 fprintf(stderr, "notice: No default references\n");
602                 show_unreachable = 0;
603         }
606 static void fsck_object_dir(const char *path)
608         int i;
610         if (verbose)
611                 fprintf(stderr, "Checking object directory\n");
613         for (i = 0; i < 256; i++) {
614                 static char dir[4096];
615                 sprintf(dir, "%s/%02x", path, i);
616                 fsck_dir(i, dir);
617         }
618         fsck_sha1_list();
621 static int fsck_head_link(void)
623         unsigned char sha1[20];
624         int flag;
625         int null_is_error = 0;
626         const char *head_points_at = resolve_ref("HEAD", sha1, 0, &flag);
628         if (verbose)
629                 fprintf(stderr, "Checking HEAD link\n");
631         if (!head_points_at)
632                 return error("Invalid HEAD");
633         if (!strcmp(head_points_at, "HEAD"))
634                 /* detached HEAD */
635                 null_is_error = 1;
636         else if (prefixcmp(head_points_at, "refs/heads/"))
637                 return error("HEAD points to something strange (%s)",
638                              head_points_at);
639         if (is_null_sha1(sha1)) {
640                 if (null_is_error)
641                         return error("HEAD: detached HEAD points at nothing");
642                 fprintf(stderr, "notice: HEAD points to an unborn branch (%s)\n",
643                         head_points_at + 11);
644         }
645         return 0;
648 static int fsck_cache_tree(struct cache_tree *it)
650         int i;
651         int err = 0;
653         if (verbose)
654                 fprintf(stderr, "Checking cache tree\n");
656         if (0 <= it->entry_count) {
657                 struct object *obj = parse_object(it->sha1);
658                 if (!obj) {
659                         error("%s: invalid sha1 pointer in cache-tree",
660                               sha1_to_hex(it->sha1));
661                         return 1;
662                 }
663                 mark_reachable(obj, REACHABLE);
664                 obj->used = 1;
665                 if (obj->type != OBJ_TREE)
666                         err |= objerror(obj, "non-tree in cache-tree");
667         }
668         for (i = 0; i < it->subtree_nr; i++)
669                 err |= fsck_cache_tree(it->down[i]->cache_tree);
670         return err;
673 static char const * const fsck_usage[] = {
674         "git-fsck [options] [<object>...]",
675         NULL
678 static struct option fsck_opts[] = {
679         OPT__VERBOSE(&verbose),
680         OPT_BOOLEAN(0, "unreachable", &show_unreachable, "show unreachable objects"),
681         OPT_BOOLEAN(0, "tags", &show_tags, "report tags"),
682         OPT_BOOLEAN(0, "root", &show_root, "report root nodes"),
683         OPT_BOOLEAN(0, "cache", &keep_cache_objects, "make index objects head nodes"),
684         OPT_BOOLEAN(0, "reflogs", &include_reflogs, "make reflogs head nodes (default)"),
685         OPT_BOOLEAN(0, "full", &check_full, "also consider alternate objects"),
686         OPT_BOOLEAN(0, "strict", &check_strict, "enable more strict checking"),
687         OPT_BOOLEAN(0, "lost-found", &write_lost_and_found,
688                                 "write dangling objects in .git/lost-found"),
689         OPT_END(),
692 int cmd_fsck(int argc, const char **argv, const char *prefix)
694         int i, heads;
696         track_object_refs = 1;
697         errors_found = 0;
699         argc = parse_options(argc, argv, fsck_opts, fsck_usage, 0);
700         if (write_lost_and_found) {
701                 check_full = 1;
702                 include_reflogs = 0;
703         }
705         fsck_head_link();
706         fsck_object_dir(get_object_directory());
707         if (check_full) {
708                 struct alternate_object_database *alt;
709                 struct packed_git *p;
710                 prepare_alt_odb();
711                 for (alt = alt_odb_list; alt; alt = alt->next) {
712                         char namebuf[PATH_MAX];
713                         int namelen = alt->name - alt->base;
714                         memcpy(namebuf, alt->base, namelen);
715                         namebuf[namelen - 1] = 0;
716                         fsck_object_dir(namebuf);
717                 }
718                 prepare_packed_git();
719                 for (p = packed_git; p; p = p->next)
720                         /* verify gives error messages itself */
721                         verify_pack(p, 0);
723                 for (p = packed_git; p; p = p->next) {
724                         uint32_t j, num;
725                         if (open_pack_index(p))
726                                 continue;
727                         num = p->num_objects;
728                         for (j = 0; j < num; j++)
729                                 fsck_sha1(nth_packed_object_sha1(p, j));
730                 }
731         }
733         heads = 0;
734         for (i = 1; i < argc; i++) {
735                 const char *arg = argv[i];
736                 if (!get_sha1(arg, head_sha1)) {
737                         struct object *obj = lookup_object(head_sha1);
739                         /* Error is printed by lookup_object(). */
740                         if (!obj)
741                                 continue;
743                         obj->used = 1;
744                         mark_reachable(obj, REACHABLE);
745                         heads++;
746                         continue;
747                 }
748                 error("invalid parameter: expected sha1, got '%s'", arg);
749         }
751         /*
752          * If we've not been given any explicit head information, do the
753          * default ones from .git/refs. We also consider the index file
754          * in this case (ie this implies --cache).
755          */
756         if (!heads) {
757                 get_default_heads();
758                 keep_cache_objects = 1;
759         }
761         if (keep_cache_objects) {
762                 read_cache();
763                 for (i = 0; i < active_nr; i++) {
764                         unsigned int mode;
765                         struct blob *blob;
766                         struct object *obj;
768                         mode = ntohl(active_cache[i]->ce_mode);
769                         if (S_ISGITLINK(mode))
770                                 continue;
771                         blob = lookup_blob(active_cache[i]->sha1);
772                         if (!blob)
773                                 continue;
774                         obj = &blob->object;
775                         obj->used = 1;
776                         mark_reachable(obj, REACHABLE);
777                 }
778                 if (active_cache_tree)
779                         fsck_cache_tree(active_cache_tree);
780         }
782         check_connectivity();
783         return errors_found;