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