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