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