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