refs / files-backend.con commit refs: retry acquiring reference locks for 100ms (4ff0f01)
   1#include "../cache.h"
   2#include "../config.h"
   3#include "../refs.h"
   4#include "refs-internal.h"
   5#include "ref-cache.h"
   6#include "../iterator.h"
   7#include "../dir-iterator.h"
   8#include "../lockfile.h"
   9#include "../object.h"
  10#include "../dir.h"
  11
  12struct ref_lock {
  13        char *ref_name;
  14        struct lock_file *lk;
  15        struct object_id old_oid;
  16};
  17
  18/*
  19 * Return true if refname, which has the specified oid and flags, can
  20 * be resolved to an object in the database. If the referred-to object
  21 * does not exist, emit a warning and return false.
  22 */
  23static int ref_resolves_to_object(const char *refname,
  24                                  const struct object_id *oid,
  25                                  unsigned int flags)
  26{
  27        if (flags & REF_ISBROKEN)
  28                return 0;
  29        if (!has_sha1_file(oid->hash)) {
  30                error("%s does not point to a valid object!", refname);
  31                return 0;
  32        }
  33        return 1;
  34}
  35
  36struct packed_ref_cache {
  37        struct ref_cache *cache;
  38
  39        /*
  40         * Count of references to the data structure in this instance,
  41         * including the pointer from files_ref_store::packed if any.
  42         * The data will not be freed as long as the reference count
  43         * is nonzero.
  44         */
  45        unsigned int referrers;
  46
  47        /* The metadata from when this packed-refs cache was read */
  48        struct stat_validity validity;
  49};
  50
  51/*
  52 * Future: need to be in "struct repository"
  53 * when doing a full libification.
  54 */
  55struct files_ref_store {
  56        struct ref_store base;
  57        unsigned int store_flags;
  58
  59        char *gitdir;
  60        char *gitcommondir;
  61        char *packed_refs_path;
  62
  63        struct ref_cache *loose;
  64        struct packed_ref_cache *packed;
  65
  66        /*
  67         * Lock used for the "packed-refs" file. Note that this (and
  68         * thus the enclosing `files_ref_store`) must not be freed.
  69         */
  70        struct lock_file packed_refs_lock;
  71};
  72
  73/*
  74 * Increment the reference count of *packed_refs.
  75 */
  76static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
  77{
  78        packed_refs->referrers++;
  79}
  80
  81/*
  82 * Decrease the reference count of *packed_refs.  If it goes to zero,
  83 * free *packed_refs and return true; otherwise return false.
  84 */
  85static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
  86{
  87        if (!--packed_refs->referrers) {
  88                free_ref_cache(packed_refs->cache);
  89                stat_validity_clear(&packed_refs->validity);
  90                free(packed_refs);
  91                return 1;
  92        } else {
  93                return 0;
  94        }
  95}
  96
  97static void clear_packed_ref_cache(struct files_ref_store *refs)
  98{
  99        if (refs->packed) {
 100                struct packed_ref_cache *packed_refs = refs->packed;
 101
 102                if (is_lock_file_locked(&refs->packed_refs_lock))
 103                        die("BUG: packed-ref cache cleared while locked");
 104                refs->packed = NULL;
 105                release_packed_ref_cache(packed_refs);
 106        }
 107}
 108
 109static void clear_loose_ref_cache(struct files_ref_store *refs)
 110{
 111        if (refs->loose) {
 112                free_ref_cache(refs->loose);
 113                refs->loose = NULL;
 114        }
 115}
 116
 117/*
 118 * Create a new submodule ref cache and add it to the internal
 119 * set of caches.
 120 */
 121static struct ref_store *files_ref_store_create(const char *gitdir,
 122                                                unsigned int flags)
 123{
 124        struct files_ref_store *refs = xcalloc(1, sizeof(*refs));
 125        struct ref_store *ref_store = (struct ref_store *)refs;
 126        struct strbuf sb = STRBUF_INIT;
 127
 128        base_ref_store_init(ref_store, &refs_be_files);
 129        refs->store_flags = flags;
 130
 131        refs->gitdir = xstrdup(gitdir);
 132        get_common_dir_noenv(&sb, gitdir);
 133        refs->gitcommondir = strbuf_detach(&sb, NULL);
 134        strbuf_addf(&sb, "%s/packed-refs", refs->gitcommondir);
 135        refs->packed_refs_path = strbuf_detach(&sb, NULL);
 136
 137        return ref_store;
 138}
 139
 140/*
 141 * Die if refs is not the main ref store. caller is used in any
 142 * necessary error messages.
 143 */
 144static void files_assert_main_repository(struct files_ref_store *refs,
 145                                         const char *caller)
 146{
 147        if (refs->store_flags & REF_STORE_MAIN)
 148                return;
 149
 150        die("BUG: operation %s only allowed for main ref store", caller);
 151}
 152
 153/*
 154 * Downcast ref_store to files_ref_store. Die if ref_store is not a
 155 * files_ref_store. required_flags is compared with ref_store's
 156 * store_flags to ensure the ref_store has all required capabilities.
 157 * "caller" is used in any necessary error messages.
 158 */
 159static struct files_ref_store *files_downcast(struct ref_store *ref_store,
 160                                              unsigned int required_flags,
 161                                              const char *caller)
 162{
 163        struct files_ref_store *refs;
 164
 165        if (ref_store->be != &refs_be_files)
 166                die("BUG: ref_store is type \"%s\" not \"files\" in %s",
 167                    ref_store->be->name, caller);
 168
 169        refs = (struct files_ref_store *)ref_store;
 170
 171        if ((refs->store_flags & required_flags) != required_flags)
 172                die("BUG: operation %s requires abilities 0x%x, but only have 0x%x",
 173                    caller, required_flags, refs->store_flags);
 174
 175        return refs;
 176}
 177
 178/* The length of a peeled reference line in packed-refs, including EOL: */
 179#define PEELED_LINE_LENGTH 42
 180
 181/*
 182 * The packed-refs header line that we write out.  Perhaps other
 183 * traits will be added later.  The trailing space is required.
 184 */
 185static const char PACKED_REFS_HEADER[] =
 186        "# pack-refs with: peeled fully-peeled \n";
 187
 188/*
 189 * Parse one line from a packed-refs file.  Write the SHA1 to sha1.
 190 * Return a pointer to the refname within the line (null-terminated),
 191 * or NULL if there was a problem.
 192 */
 193static const char *parse_ref_line(struct strbuf *line, struct object_id *oid)
 194{
 195        const char *ref;
 196
 197        if (parse_oid_hex(line->buf, oid, &ref) < 0)
 198                return NULL;
 199        if (!isspace(*ref++))
 200                return NULL;
 201
 202        if (isspace(*ref))
 203                return NULL;
 204
 205        if (line->buf[line->len - 1] != '\n')
 206                return NULL;
 207        line->buf[--line->len] = 0;
 208
 209        return ref;
 210}
 211
 212/*
 213 * Read from `packed_refs_file` into a newly-allocated
 214 * `packed_ref_cache` and return it. The return value will already
 215 * have its reference count incremented.
 216 *
 217 * A comment line of the form "# pack-refs with: " may contain zero or
 218 * more traits. We interpret the traits as follows:
 219 *
 220 *   No traits:
 221 *
 222 *      Probably no references are peeled. But if the file contains a
 223 *      peeled value for a reference, we will use it.
 224 *
 225 *   peeled:
 226 *
 227 *      References under "refs/tags/", if they *can* be peeled, *are*
 228 *      peeled in this file. References outside of "refs/tags/" are
 229 *      probably not peeled even if they could have been, but if we find
 230 *      a peeled value for such a reference we will use it.
 231 *
 232 *   fully-peeled:
 233 *
 234 *      All references in the file that can be peeled are peeled.
 235 *      Inversely (and this is more important), any references in the
 236 *      file for which no peeled value is recorded is not peelable. This
 237 *      trait should typically be written alongside "peeled" for
 238 *      compatibility with older clients, but we do not require it
 239 *      (i.e., "peeled" is a no-op if "fully-peeled" is set).
 240 */
 241static struct packed_ref_cache *read_packed_refs(const char *packed_refs_file)
 242{
 243        FILE *f;
 244        struct packed_ref_cache *packed_refs = xcalloc(1, sizeof(*packed_refs));
 245        struct ref_entry *last = NULL;
 246        struct strbuf line = STRBUF_INIT;
 247        enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
 248        struct ref_dir *dir;
 249
 250        acquire_packed_ref_cache(packed_refs);
 251        packed_refs->cache = create_ref_cache(NULL, NULL);
 252        packed_refs->cache->root->flag &= ~REF_INCOMPLETE;
 253
 254        f = fopen(packed_refs_file, "r");
 255        if (!f) {
 256                if (errno == ENOENT) {
 257                        /*
 258                         * This is OK; it just means that no
 259                         * "packed-refs" file has been written yet,
 260                         * which is equivalent to it being empty.
 261                         */
 262                        return packed_refs;
 263                } else {
 264                        die_errno("couldn't read %s", packed_refs_file);
 265                }
 266        }
 267
 268        stat_validity_update(&packed_refs->validity, fileno(f));
 269
 270        dir = get_ref_dir(packed_refs->cache->root);
 271        while (strbuf_getwholeline(&line, f, '\n') != EOF) {
 272                struct object_id oid;
 273                const char *refname;
 274                const char *traits;
 275
 276                if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
 277                        if (strstr(traits, " fully-peeled "))
 278                                peeled = PEELED_FULLY;
 279                        else if (strstr(traits, " peeled "))
 280                                peeled = PEELED_TAGS;
 281                        /* perhaps other traits later as well */
 282                        continue;
 283                }
 284
 285                refname = parse_ref_line(&line, &oid);
 286                if (refname) {
 287                        int flag = REF_ISPACKED;
 288
 289                        if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
 290                                if (!refname_is_safe(refname))
 291                                        die("packed refname is dangerous: %s", refname);
 292                                oidclr(&oid);
 293                                flag |= REF_BAD_NAME | REF_ISBROKEN;
 294                        }
 295                        last = create_ref_entry(refname, &oid, flag);
 296                        if (peeled == PEELED_FULLY ||
 297                            (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
 298                                last->flag |= REF_KNOWS_PEELED;
 299                        add_ref_entry(dir, last);
 300                        continue;
 301                }
 302                if (last &&
 303                    line.buf[0] == '^' &&
 304                    line.len == PEELED_LINE_LENGTH &&
 305                    line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
 306                    !get_oid_hex(line.buf + 1, &oid)) {
 307                        oidcpy(&last->u.value.peeled, &oid);
 308                        /*
 309                         * Regardless of what the file header said,
 310                         * we definitely know the value of *this*
 311                         * reference:
 312                         */
 313                        last->flag |= REF_KNOWS_PEELED;
 314                }
 315        }
 316
 317        fclose(f);
 318        strbuf_release(&line);
 319
 320        return packed_refs;
 321}
 322
 323static const char *files_packed_refs_path(struct files_ref_store *refs)
 324{
 325        return refs->packed_refs_path;
 326}
 327
 328static void files_reflog_path(struct files_ref_store *refs,
 329                              struct strbuf *sb,
 330                              const char *refname)
 331{
 332        if (!refname) {
 333                /*
 334                 * FIXME: of course this is wrong in multi worktree
 335                 * setting. To be fixed real soon.
 336                 */
 337                strbuf_addf(sb, "%s/logs", refs->gitcommondir);
 338                return;
 339        }
 340
 341        switch (ref_type(refname)) {
 342        case REF_TYPE_PER_WORKTREE:
 343        case REF_TYPE_PSEUDOREF:
 344                strbuf_addf(sb, "%s/logs/%s", refs->gitdir, refname);
 345                break;
 346        case REF_TYPE_NORMAL:
 347                strbuf_addf(sb, "%s/logs/%s", refs->gitcommondir, refname);
 348                break;
 349        default:
 350                die("BUG: unknown ref type %d of ref %s",
 351                    ref_type(refname), refname);
 352        }
 353}
 354
 355static void files_ref_path(struct files_ref_store *refs,
 356                           struct strbuf *sb,
 357                           const char *refname)
 358{
 359        switch (ref_type(refname)) {
 360        case REF_TYPE_PER_WORKTREE:
 361        case REF_TYPE_PSEUDOREF:
 362                strbuf_addf(sb, "%s/%s", refs->gitdir, refname);
 363                break;
 364        case REF_TYPE_NORMAL:
 365                strbuf_addf(sb, "%s/%s", refs->gitcommondir, refname);
 366                break;
 367        default:
 368                die("BUG: unknown ref type %d of ref %s",
 369                    ref_type(refname), refname);
 370        }
 371}
 372
 373/*
 374 * Check that the packed refs cache (if any) still reflects the
 375 * contents of the file. If not, clear the cache.
 376 */
 377static void validate_packed_ref_cache(struct files_ref_store *refs)
 378{
 379        if (refs->packed &&
 380            !stat_validity_check(&refs->packed->validity,
 381                                 files_packed_refs_path(refs)))
 382                clear_packed_ref_cache(refs);
 383}
 384
 385/*
 386 * Get the packed_ref_cache for the specified files_ref_store,
 387 * creating and populating it if it hasn't been read before or if the
 388 * file has been changed (according to its `validity` field) since it
 389 * was last read. On the other hand, if we hold the lock, then assume
 390 * that the file hasn't been changed out from under us, so skip the
 391 * extra `stat()` call in `stat_validity_check()`.
 392 */
 393static struct packed_ref_cache *get_packed_ref_cache(struct files_ref_store *refs)
 394{
 395        const char *packed_refs_file = files_packed_refs_path(refs);
 396
 397        if (!is_lock_file_locked(&refs->packed_refs_lock))
 398                validate_packed_ref_cache(refs);
 399
 400        if (!refs->packed)
 401                refs->packed = read_packed_refs(packed_refs_file);
 402
 403        return refs->packed;
 404}
 405
 406static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
 407{
 408        return get_ref_dir(packed_ref_cache->cache->root);
 409}
 410
 411static struct ref_dir *get_packed_refs(struct files_ref_store *refs)
 412{
 413        return get_packed_ref_dir(get_packed_ref_cache(refs));
 414}
 415
 416/*
 417 * Add a reference to the in-memory packed reference cache.  This may
 418 * only be called while the packed-refs file is locked (see
 419 * lock_packed_refs()).  To actually write the packed-refs file, call
 420 * commit_packed_refs().
 421 */
 422static void add_packed_ref(struct files_ref_store *refs,
 423                           const char *refname, const struct object_id *oid)
 424{
 425        struct packed_ref_cache *packed_ref_cache = get_packed_ref_cache(refs);
 426
 427        if (!is_lock_file_locked(&refs->packed_refs_lock))
 428                die("BUG: packed refs not locked");
 429
 430        if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
 431                die("Reference has invalid format: '%s'", refname);
 432
 433        add_ref_entry(get_packed_ref_dir(packed_ref_cache),
 434                      create_ref_entry(refname, oid, REF_ISPACKED));
 435}
 436
 437/*
 438 * Read the loose references from the namespace dirname into dir
 439 * (without recursing).  dirname must end with '/'.  dir must be the
 440 * directory entry corresponding to dirname.
 441 */
 442static void loose_fill_ref_dir(struct ref_store *ref_store,
 443                               struct ref_dir *dir, const char *dirname)
 444{
 445        struct files_ref_store *refs =
 446                files_downcast(ref_store, REF_STORE_READ, "fill_ref_dir");
 447        DIR *d;
 448        struct dirent *de;
 449        int dirnamelen = strlen(dirname);
 450        struct strbuf refname;
 451        struct strbuf path = STRBUF_INIT;
 452        size_t path_baselen;
 453
 454        files_ref_path(refs, &path, dirname);
 455        path_baselen = path.len;
 456
 457        d = opendir(path.buf);
 458        if (!d) {
 459                strbuf_release(&path);
 460                return;
 461        }
 462
 463        strbuf_init(&refname, dirnamelen + 257);
 464        strbuf_add(&refname, dirname, dirnamelen);
 465
 466        while ((de = readdir(d)) != NULL) {
 467                struct object_id oid;
 468                struct stat st;
 469                int flag;
 470
 471                if (de->d_name[0] == '.')
 472                        continue;
 473                if (ends_with(de->d_name, ".lock"))
 474                        continue;
 475                strbuf_addstr(&refname, de->d_name);
 476                strbuf_addstr(&path, de->d_name);
 477                if (stat(path.buf, &st) < 0) {
 478                        ; /* silently ignore */
 479                } else if (S_ISDIR(st.st_mode)) {
 480                        strbuf_addch(&refname, '/');
 481                        add_entry_to_dir(dir,
 482                                         create_dir_entry(dir->cache, refname.buf,
 483                                                          refname.len, 1));
 484                } else {
 485                        if (!refs_resolve_ref_unsafe(&refs->base,
 486                                                     refname.buf,
 487                                                     RESOLVE_REF_READING,
 488                                                     oid.hash, &flag)) {
 489                                oidclr(&oid);
 490                                flag |= REF_ISBROKEN;
 491                        } else if (is_null_oid(&oid)) {
 492                                /*
 493                                 * It is so astronomically unlikely
 494                                 * that NULL_SHA1 is the SHA-1 of an
 495                                 * actual object that we consider its
 496                                 * appearance in a loose reference
 497                                 * file to be repo corruption
 498                                 * (probably due to a software bug).
 499                                 */
 500                                flag |= REF_ISBROKEN;
 501                        }
 502
 503                        if (check_refname_format(refname.buf,
 504                                                 REFNAME_ALLOW_ONELEVEL)) {
 505                                if (!refname_is_safe(refname.buf))
 506                                        die("loose refname is dangerous: %s", refname.buf);
 507                                oidclr(&oid);
 508                                flag |= REF_BAD_NAME | REF_ISBROKEN;
 509                        }
 510                        add_entry_to_dir(dir,
 511                                         create_ref_entry(refname.buf, &oid, flag));
 512                }
 513                strbuf_setlen(&refname, dirnamelen);
 514                strbuf_setlen(&path, path_baselen);
 515        }
 516        strbuf_release(&refname);
 517        strbuf_release(&path);
 518        closedir(d);
 519
 520        /*
 521         * Manually add refs/bisect, which, being per-worktree, might
 522         * not appear in the directory listing for refs/ in the main
 523         * repo.
 524         */
 525        if (!strcmp(dirname, "refs/")) {
 526                int pos = search_ref_dir(dir, "refs/bisect/", 12);
 527
 528                if (pos < 0) {
 529                        struct ref_entry *child_entry = create_dir_entry(
 530                                        dir->cache, "refs/bisect/", 12, 1);
 531                        add_entry_to_dir(dir, child_entry);
 532                }
 533        }
 534}
 535
 536static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs)
 537{
 538        if (!refs->loose) {
 539                /*
 540                 * Mark the top-level directory complete because we
 541                 * are about to read the only subdirectory that can
 542                 * hold references:
 543                 */
 544                refs->loose = create_ref_cache(&refs->base, loose_fill_ref_dir);
 545
 546                /* We're going to fill the top level ourselves: */
 547                refs->loose->root->flag &= ~REF_INCOMPLETE;
 548
 549                /*
 550                 * Add an incomplete entry for "refs/" (to be filled
 551                 * lazily):
 552                 */
 553                add_entry_to_dir(get_ref_dir(refs->loose->root),
 554                                 create_dir_entry(refs->loose, "refs/", 5, 1));
 555        }
 556        return refs->loose;
 557}
 558
 559/*
 560 * Return the ref_entry for the given refname from the packed
 561 * references.  If it does not exist, return NULL.
 562 */
 563static struct ref_entry *get_packed_ref(struct files_ref_store *refs,
 564                                        const char *refname)
 565{
 566        return find_ref_entry(get_packed_refs(refs), refname);
 567}
 568
 569/*
 570 * A loose ref file doesn't exist; check for a packed ref.
 571 */
 572static int resolve_packed_ref(struct files_ref_store *refs,
 573                              const char *refname,
 574                              unsigned char *sha1, unsigned int *flags)
 575{
 576        struct ref_entry *entry;
 577
 578        /*
 579         * The loose reference file does not exist; check for a packed
 580         * reference.
 581         */
 582        entry = get_packed_ref(refs, refname);
 583        if (entry) {
 584                hashcpy(sha1, entry->u.value.oid.hash);
 585                *flags |= REF_ISPACKED;
 586                return 0;
 587        }
 588        /* refname is not a packed reference. */
 589        return -1;
 590}
 591
 592static int files_read_raw_ref(struct ref_store *ref_store,
 593                              const char *refname, unsigned char *sha1,
 594                              struct strbuf *referent, unsigned int *type)
 595{
 596        struct files_ref_store *refs =
 597                files_downcast(ref_store, REF_STORE_READ, "read_raw_ref");
 598        struct strbuf sb_contents = STRBUF_INIT;
 599        struct strbuf sb_path = STRBUF_INIT;
 600        const char *path;
 601        const char *buf;
 602        struct stat st;
 603        int fd;
 604        int ret = -1;
 605        int save_errno;
 606        int remaining_retries = 3;
 607
 608        *type = 0;
 609        strbuf_reset(&sb_path);
 610
 611        files_ref_path(refs, &sb_path, refname);
 612
 613        path = sb_path.buf;
 614
 615stat_ref:
 616        /*
 617         * We might have to loop back here to avoid a race
 618         * condition: first we lstat() the file, then we try
 619         * to read it as a link or as a file.  But if somebody
 620         * changes the type of the file (file <-> directory
 621         * <-> symlink) between the lstat() and reading, then
 622         * we don't want to report that as an error but rather
 623         * try again starting with the lstat().
 624         *
 625         * We'll keep a count of the retries, though, just to avoid
 626         * any confusing situation sending us into an infinite loop.
 627         */
 628
 629        if (remaining_retries-- <= 0)
 630                goto out;
 631
 632        if (lstat(path, &st) < 0) {
 633                if (errno != ENOENT)
 634                        goto out;
 635                if (resolve_packed_ref(refs, refname, sha1, type)) {
 636                        errno = ENOENT;
 637                        goto out;
 638                }
 639                ret = 0;
 640                goto out;
 641        }
 642
 643        /* Follow "normalized" - ie "refs/.." symlinks by hand */
 644        if (S_ISLNK(st.st_mode)) {
 645                strbuf_reset(&sb_contents);
 646                if (strbuf_readlink(&sb_contents, path, 0) < 0) {
 647                        if (errno == ENOENT || errno == EINVAL)
 648                                /* inconsistent with lstat; retry */
 649                                goto stat_ref;
 650                        else
 651                                goto out;
 652                }
 653                if (starts_with(sb_contents.buf, "refs/") &&
 654                    !check_refname_format(sb_contents.buf, 0)) {
 655                        strbuf_swap(&sb_contents, referent);
 656                        *type |= REF_ISSYMREF;
 657                        ret = 0;
 658                        goto out;
 659                }
 660                /*
 661                 * It doesn't look like a refname; fall through to just
 662                 * treating it like a non-symlink, and reading whatever it
 663                 * points to.
 664                 */
 665        }
 666
 667        /* Is it a directory? */
 668        if (S_ISDIR(st.st_mode)) {
 669                /*
 670                 * Even though there is a directory where the loose
 671                 * ref is supposed to be, there could still be a
 672                 * packed ref:
 673                 */
 674                if (resolve_packed_ref(refs, refname, sha1, type)) {
 675                        errno = EISDIR;
 676                        goto out;
 677                }
 678                ret = 0;
 679                goto out;
 680        }
 681
 682        /*
 683         * Anything else, just open it and try to use it as
 684         * a ref
 685         */
 686        fd = open(path, O_RDONLY);
 687        if (fd < 0) {
 688                if (errno == ENOENT && !S_ISLNK(st.st_mode))
 689                        /* inconsistent with lstat; retry */
 690                        goto stat_ref;
 691                else
 692                        goto out;
 693        }
 694        strbuf_reset(&sb_contents);
 695        if (strbuf_read(&sb_contents, fd, 256) < 0) {
 696                int save_errno = errno;
 697                close(fd);
 698                errno = save_errno;
 699                goto out;
 700        }
 701        close(fd);
 702        strbuf_rtrim(&sb_contents);
 703        buf = sb_contents.buf;
 704        if (starts_with(buf, "ref:")) {
 705                buf += 4;
 706                while (isspace(*buf))
 707                        buf++;
 708
 709                strbuf_reset(referent);
 710                strbuf_addstr(referent, buf);
 711                *type |= REF_ISSYMREF;
 712                ret = 0;
 713                goto out;
 714        }
 715
 716        /*
 717         * Please note that FETCH_HEAD has additional
 718         * data after the sha.
 719         */
 720        if (get_sha1_hex(buf, sha1) ||
 721            (buf[40] != '\0' && !isspace(buf[40]))) {
 722                *type |= REF_ISBROKEN;
 723                errno = EINVAL;
 724                goto out;
 725        }
 726
 727        ret = 0;
 728
 729out:
 730        save_errno = errno;
 731        strbuf_release(&sb_path);
 732        strbuf_release(&sb_contents);
 733        errno = save_errno;
 734        return ret;
 735}
 736
 737static void unlock_ref(struct ref_lock *lock)
 738{
 739        /* Do not free lock->lk -- atexit() still looks at them */
 740        if (lock->lk)
 741                rollback_lock_file(lock->lk);
 742        free(lock->ref_name);
 743        free(lock);
 744}
 745
 746/*
 747 * Lock refname, without following symrefs, and set *lock_p to point
 748 * at a newly-allocated lock object. Fill in lock->old_oid, referent,
 749 * and type similarly to read_raw_ref().
 750 *
 751 * The caller must verify that refname is a "safe" reference name (in
 752 * the sense of refname_is_safe()) before calling this function.
 753 *
 754 * If the reference doesn't already exist, verify that refname doesn't
 755 * have a D/F conflict with any existing references. extras and skip
 756 * are passed to refs_verify_refname_available() for this check.
 757 *
 758 * If mustexist is not set and the reference is not found or is
 759 * broken, lock the reference anyway but clear sha1.
 760 *
 761 * Return 0 on success. On failure, write an error message to err and
 762 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.
 763 *
 764 * Implementation note: This function is basically
 765 *
 766 *     lock reference
 767 *     read_raw_ref()
 768 *
 769 * but it includes a lot more code to
 770 * - Deal with possible races with other processes
 771 * - Avoid calling refs_verify_refname_available() when it can be
 772 *   avoided, namely if we were successfully able to read the ref
 773 * - Generate informative error messages in the case of failure
 774 */
 775static int lock_raw_ref(struct files_ref_store *refs,
 776                        const char *refname, int mustexist,
 777                        const struct string_list *extras,
 778                        const struct string_list *skip,
 779                        struct ref_lock **lock_p,
 780                        struct strbuf *referent,
 781                        unsigned int *type,
 782                        struct strbuf *err)
 783{
 784        struct ref_lock *lock;
 785        struct strbuf ref_file = STRBUF_INIT;
 786        int attempts_remaining = 3;
 787        int ret = TRANSACTION_GENERIC_ERROR;
 788
 789        assert(err);
 790        files_assert_main_repository(refs, "lock_raw_ref");
 791
 792        *type = 0;
 793
 794        /* First lock the file so it can't change out from under us. */
 795
 796        *lock_p = lock = xcalloc(1, sizeof(*lock));
 797
 798        lock->ref_name = xstrdup(refname);
 799        files_ref_path(refs, &ref_file, refname);
 800
 801retry:
 802        switch (safe_create_leading_directories(ref_file.buf)) {
 803        case SCLD_OK:
 804                break; /* success */
 805        case SCLD_EXISTS:
 806                /*
 807                 * Suppose refname is "refs/foo/bar". We just failed
 808                 * to create the containing directory, "refs/foo",
 809                 * because there was a non-directory in the way. This
 810                 * indicates a D/F conflict, probably because of
 811                 * another reference such as "refs/foo". There is no
 812                 * reason to expect this error to be transitory.
 813                 */
 814                if (refs_verify_refname_available(&refs->base, refname,
 815                                                  extras, skip, err)) {
 816                        if (mustexist) {
 817                                /*
 818                                 * To the user the relevant error is
 819                                 * that the "mustexist" reference is
 820                                 * missing:
 821                                 */
 822                                strbuf_reset(err);
 823                                strbuf_addf(err, "unable to resolve reference '%s'",
 824                                            refname);
 825                        } else {
 826                                /*
 827                                 * The error message set by
 828                                 * refs_verify_refname_available() is
 829                                 * OK.
 830                                 */
 831                                ret = TRANSACTION_NAME_CONFLICT;
 832                        }
 833                } else {
 834                        /*
 835                         * The file that is in the way isn't a loose
 836                         * reference. Report it as a low-level
 837                         * failure.
 838                         */
 839                        strbuf_addf(err, "unable to create lock file %s.lock; "
 840                                    "non-directory in the way",
 841                                    ref_file.buf);
 842                }
 843                goto error_return;
 844        case SCLD_VANISHED:
 845                /* Maybe another process was tidying up. Try again. */
 846                if (--attempts_remaining > 0)
 847                        goto retry;
 848                /* fall through */
 849        default:
 850                strbuf_addf(err, "unable to create directory for %s",
 851                            ref_file.buf);
 852                goto error_return;
 853        }
 854
 855        if (!lock->lk)
 856                lock->lk = xcalloc(1, sizeof(struct lock_file));
 857
 858        if (hold_lock_file_for_update_timeout(
 859                            lock->lk, ref_file.buf, LOCK_NO_DEREF,
 860                            get_files_ref_lock_timeout_ms()) < 0) {
 861                if (errno == ENOENT && --attempts_remaining > 0) {
 862                        /*
 863                         * Maybe somebody just deleted one of the
 864                         * directories leading to ref_file.  Try
 865                         * again:
 866                         */
 867                        goto retry;
 868                } else {
 869                        unable_to_lock_message(ref_file.buf, errno, err);
 870                        goto error_return;
 871                }
 872        }
 873
 874        /*
 875         * Now we hold the lock and can read the reference without
 876         * fear that its value will change.
 877         */
 878
 879        if (files_read_raw_ref(&refs->base, refname,
 880                               lock->old_oid.hash, referent, type)) {
 881                if (errno == ENOENT) {
 882                        if (mustexist) {
 883                                /* Garden variety missing reference. */
 884                                strbuf_addf(err, "unable to resolve reference '%s'",
 885                                            refname);
 886                                goto error_return;
 887                        } else {
 888                                /*
 889                                 * Reference is missing, but that's OK. We
 890                                 * know that there is not a conflict with
 891                                 * another loose reference because
 892                                 * (supposing that we are trying to lock
 893                                 * reference "refs/foo/bar"):
 894                                 *
 895                                 * - We were successfully able to create
 896                                 *   the lockfile refs/foo/bar.lock, so we
 897                                 *   know there cannot be a loose reference
 898                                 *   named "refs/foo".
 899                                 *
 900                                 * - We got ENOENT and not EISDIR, so we
 901                                 *   know that there cannot be a loose
 902                                 *   reference named "refs/foo/bar/baz".
 903                                 */
 904                        }
 905                } else if (errno == EISDIR) {
 906                        /*
 907                         * There is a directory in the way. It might have
 908                         * contained references that have been deleted. If
 909                         * we don't require that the reference already
 910                         * exists, try to remove the directory so that it
 911                         * doesn't cause trouble when we want to rename the
 912                         * lockfile into place later.
 913                         */
 914                        if (mustexist) {
 915                                /* Garden variety missing reference. */
 916                                strbuf_addf(err, "unable to resolve reference '%s'",
 917                                            refname);
 918                                goto error_return;
 919                        } else if (remove_dir_recursively(&ref_file,
 920                                                          REMOVE_DIR_EMPTY_ONLY)) {
 921                                if (refs_verify_refname_available(
 922                                                    &refs->base, refname,
 923                                                    extras, skip, err)) {
 924                                        /*
 925                                         * The error message set by
 926                                         * verify_refname_available() is OK.
 927                                         */
 928                                        ret = TRANSACTION_NAME_CONFLICT;
 929                                        goto error_return;
 930                                } else {
 931                                        /*
 932                                         * We can't delete the directory,
 933                                         * but we also don't know of any
 934                                         * references that it should
 935                                         * contain.
 936                                         */
 937                                        strbuf_addf(err, "there is a non-empty directory '%s' "
 938                                                    "blocking reference '%s'",
 939                                                    ref_file.buf, refname);
 940                                        goto error_return;
 941                                }
 942                        }
 943                } else if (errno == EINVAL && (*type & REF_ISBROKEN)) {
 944                        strbuf_addf(err, "unable to resolve reference '%s': "
 945                                    "reference broken", refname);
 946                        goto error_return;
 947                } else {
 948                        strbuf_addf(err, "unable to resolve reference '%s': %s",
 949                                    refname, strerror(errno));
 950                        goto error_return;
 951                }
 952
 953                /*
 954                 * If the ref did not exist and we are creating it,
 955                 * make sure there is no existing ref that conflicts
 956                 * with refname:
 957                 */
 958                if (refs_verify_refname_available(
 959                                    &refs->base, refname,
 960                                    extras, skip, err))
 961                        goto error_return;
 962        }
 963
 964        ret = 0;
 965        goto out;
 966
 967error_return:
 968        unlock_ref(lock);
 969        *lock_p = NULL;
 970
 971out:
 972        strbuf_release(&ref_file);
 973        return ret;
 974}
 975
 976static int files_peel_ref(struct ref_store *ref_store,
 977                          const char *refname, unsigned char *sha1)
 978{
 979        struct files_ref_store *refs =
 980                files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB,
 981                               "peel_ref");
 982        int flag;
 983        unsigned char base[20];
 984
 985        if (current_ref_iter && current_ref_iter->refname == refname) {
 986                struct object_id peeled;
 987
 988                if (ref_iterator_peel(current_ref_iter, &peeled))
 989                        return -1;
 990                hashcpy(sha1, peeled.hash);
 991                return 0;
 992        }
 993
 994        if (refs_read_ref_full(ref_store, refname,
 995                               RESOLVE_REF_READING, base, &flag))
 996                return -1;
 997
 998        /*
 999         * If the reference is packed, read its ref_entry from the
1000         * cache in the hope that we already know its peeled value.
1001         * We only try this optimization on packed references because
1002         * (a) forcing the filling of the loose reference cache could
1003         * be expensive and (b) loose references anyway usually do not
1004         * have REF_KNOWS_PEELED.
1005         */
1006        if (flag & REF_ISPACKED) {
1007                struct ref_entry *r = get_packed_ref(refs, refname);
1008                if (r) {
1009                        if (peel_entry(r, 0))
1010                                return -1;
1011                        hashcpy(sha1, r->u.value.peeled.hash);
1012                        return 0;
1013                }
1014        }
1015
1016        return peel_object(base, sha1);
1017}
1018
1019struct files_ref_iterator {
1020        struct ref_iterator base;
1021
1022        struct packed_ref_cache *packed_ref_cache;
1023        struct ref_iterator *iter0;
1024        unsigned int flags;
1025};
1026
1027static int files_ref_iterator_advance(struct ref_iterator *ref_iterator)
1028{
1029        struct files_ref_iterator *iter =
1030                (struct files_ref_iterator *)ref_iterator;
1031        int ok;
1032
1033        while ((ok = ref_iterator_advance(iter->iter0)) == ITER_OK) {
1034                if (iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&
1035                    ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)
1036                        continue;
1037
1038                if (!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
1039                    !ref_resolves_to_object(iter->iter0->refname,
1040                                            iter->iter0->oid,
1041                                            iter->iter0->flags))
1042                        continue;
1043
1044                iter->base.refname = iter->iter0->refname;
1045                iter->base.oid = iter->iter0->oid;
1046                iter->base.flags = iter->iter0->flags;
1047                return ITER_OK;
1048        }
1049
1050        iter->iter0 = NULL;
1051        if (ref_iterator_abort(ref_iterator) != ITER_DONE)
1052                ok = ITER_ERROR;
1053
1054        return ok;
1055}
1056
1057static int files_ref_iterator_peel(struct ref_iterator *ref_iterator,
1058                                   struct object_id *peeled)
1059{
1060        struct files_ref_iterator *iter =
1061                (struct files_ref_iterator *)ref_iterator;
1062
1063        return ref_iterator_peel(iter->iter0, peeled);
1064}
1065
1066static int files_ref_iterator_abort(struct ref_iterator *ref_iterator)
1067{
1068        struct files_ref_iterator *iter =
1069                (struct files_ref_iterator *)ref_iterator;
1070        int ok = ITER_DONE;
1071
1072        if (iter->iter0)
1073                ok = ref_iterator_abort(iter->iter0);
1074
1075        release_packed_ref_cache(iter->packed_ref_cache);
1076        base_ref_iterator_free(ref_iterator);
1077        return ok;
1078}
1079
1080static struct ref_iterator_vtable files_ref_iterator_vtable = {
1081        files_ref_iterator_advance,
1082        files_ref_iterator_peel,
1083        files_ref_iterator_abort
1084};
1085
1086static struct ref_iterator *files_ref_iterator_begin(
1087                struct ref_store *ref_store,
1088                const char *prefix, unsigned int flags)
1089{
1090        struct files_ref_store *refs;
1091        struct ref_iterator *loose_iter, *packed_iter;
1092        struct files_ref_iterator *iter;
1093        struct ref_iterator *ref_iterator;
1094        unsigned int required_flags = REF_STORE_READ;
1095
1096        if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN))
1097                required_flags |= REF_STORE_ODB;
1098
1099        refs = files_downcast(ref_store, required_flags, "ref_iterator_begin");
1100
1101        iter = xcalloc(1, sizeof(*iter));
1102        ref_iterator = &iter->base;
1103        base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);
1104
1105        /*
1106         * We must make sure that all loose refs are read before
1107         * accessing the packed-refs file; this avoids a race
1108         * condition if loose refs are migrated to the packed-refs
1109         * file by a simultaneous process, but our in-memory view is
1110         * from before the migration. We ensure this as follows:
1111         * First, we call start the loose refs iteration with its
1112         * `prime_ref` argument set to true. This causes the loose
1113         * references in the subtree to be pre-read into the cache.
1114         * (If they've already been read, that's OK; we only need to
1115         * guarantee that they're read before the packed refs, not
1116         * *how much* before.) After that, we call
1117         * get_packed_ref_cache(), which internally checks whether the
1118         * packed-ref cache is up to date with what is on disk, and
1119         * re-reads it if not.
1120         */
1121
1122        loose_iter = cache_ref_iterator_begin(get_loose_ref_cache(refs),
1123                                              prefix, 1);
1124
1125        iter->packed_ref_cache = get_packed_ref_cache(refs);
1126        acquire_packed_ref_cache(iter->packed_ref_cache);
1127        packed_iter = cache_ref_iterator_begin(iter->packed_ref_cache->cache,
1128                                               prefix, 0);
1129
1130        iter->iter0 = overlay_ref_iterator_begin(loose_iter, packed_iter);
1131        iter->flags = flags;
1132
1133        return ref_iterator;
1134}
1135
1136/*
1137 * Verify that the reference locked by lock has the value old_sha1.
1138 * Fail if the reference doesn't exist and mustexist is set. Return 0
1139 * on success. On error, write an error message to err, set errno, and
1140 * return a negative value.
1141 */
1142static int verify_lock(struct ref_store *ref_store, struct ref_lock *lock,
1143                       const unsigned char *old_sha1, int mustexist,
1144                       struct strbuf *err)
1145{
1146        assert(err);
1147
1148        if (refs_read_ref_full(ref_store, lock->ref_name,
1149                               mustexist ? RESOLVE_REF_READING : 0,
1150                               lock->old_oid.hash, NULL)) {
1151                if (old_sha1) {
1152                        int save_errno = errno;
1153                        strbuf_addf(err, "can't verify ref '%s'", lock->ref_name);
1154                        errno = save_errno;
1155                        return -1;
1156                } else {
1157                        oidclr(&lock->old_oid);
1158                        return 0;
1159                }
1160        }
1161        if (old_sha1 && hashcmp(lock->old_oid.hash, old_sha1)) {
1162                strbuf_addf(err, "ref '%s' is at %s but expected %s",
1163                            lock->ref_name,
1164                            oid_to_hex(&lock->old_oid),
1165                            sha1_to_hex(old_sha1));
1166                errno = EBUSY;
1167                return -1;
1168        }
1169        return 0;
1170}
1171
1172static int remove_empty_directories(struct strbuf *path)
1173{
1174        /*
1175         * we want to create a file but there is a directory there;
1176         * if that is an empty directory (or a directory that contains
1177         * only empty directories), remove them.
1178         */
1179        return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
1180}
1181
1182static int create_reflock(const char *path, void *cb)
1183{
1184        struct lock_file *lk = cb;
1185
1186        return hold_lock_file_for_update_timeout(
1187                        lk, path, LOCK_NO_DEREF,
1188                        get_files_ref_lock_timeout_ms()) < 0 ? -1 : 0;
1189}
1190
1191/*
1192 * Locks a ref returning the lock on success and NULL on failure.
1193 * On failure errno is set to something meaningful.
1194 */
1195static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,
1196                                            const char *refname,
1197                                            const unsigned char *old_sha1,
1198                                            const struct string_list *extras,
1199                                            const struct string_list *skip,
1200                                            unsigned int flags, int *type,
1201                                            struct strbuf *err)
1202{
1203        struct strbuf ref_file = STRBUF_INIT;
1204        struct ref_lock *lock;
1205        int last_errno = 0;
1206        int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1207        int resolve_flags = RESOLVE_REF_NO_RECURSE;
1208        int resolved;
1209
1210        files_assert_main_repository(refs, "lock_ref_sha1_basic");
1211        assert(err);
1212
1213        lock = xcalloc(1, sizeof(struct ref_lock));
1214
1215        if (mustexist)
1216                resolve_flags |= RESOLVE_REF_READING;
1217        if (flags & REF_DELETING)
1218                resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
1219
1220        files_ref_path(refs, &ref_file, refname);
1221        resolved = !!refs_resolve_ref_unsafe(&refs->base,
1222                                             refname, resolve_flags,
1223                                             lock->old_oid.hash, type);
1224        if (!resolved && errno == EISDIR) {
1225                /*
1226                 * we are trying to lock foo but we used to
1227                 * have foo/bar which now does not exist;
1228                 * it is normal for the empty directory 'foo'
1229                 * to remain.
1230                 */
1231                if (remove_empty_directories(&ref_file)) {
1232                        last_errno = errno;
1233                        if (!refs_verify_refname_available(
1234                                            &refs->base,
1235                                            refname, extras, skip, err))
1236                                strbuf_addf(err, "there are still refs under '%s'",
1237                                            refname);
1238                        goto error_return;
1239                }
1240                resolved = !!refs_resolve_ref_unsafe(&refs->base,
1241                                                     refname, resolve_flags,
1242                                                     lock->old_oid.hash, type);
1243        }
1244        if (!resolved) {
1245                last_errno = errno;
1246                if (last_errno != ENOTDIR ||
1247                    !refs_verify_refname_available(&refs->base, refname,
1248                                                   extras, skip, err))
1249                        strbuf_addf(err, "unable to resolve reference '%s': %s",
1250                                    refname, strerror(last_errno));
1251
1252                goto error_return;
1253        }
1254
1255        /*
1256         * If the ref did not exist and we are creating it, make sure
1257         * there is no existing packed ref whose name begins with our
1258         * refname, nor a packed ref whose name is a proper prefix of
1259         * our refname.
1260         */
1261        if (is_null_oid(&lock->old_oid) &&
1262            refs_verify_refname_available(&refs->base, refname,
1263                                          extras, skip, err)) {
1264                last_errno = ENOTDIR;
1265                goto error_return;
1266        }
1267
1268        lock->lk = xcalloc(1, sizeof(struct lock_file));
1269
1270        lock->ref_name = xstrdup(refname);
1271
1272        if (raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {
1273                last_errno = errno;
1274                unable_to_lock_message(ref_file.buf, errno, err);
1275                goto error_return;
1276        }
1277
1278        if (verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {
1279                last_errno = errno;
1280                goto error_return;
1281        }
1282        goto out;
1283
1284 error_return:
1285        unlock_ref(lock);
1286        lock = NULL;
1287
1288 out:
1289        strbuf_release(&ref_file);
1290        errno = last_errno;
1291        return lock;
1292}
1293
1294/*
1295 * Write an entry to the packed-refs file for the specified refname.
1296 * If peeled is non-NULL, write it as the entry's peeled value.
1297 */
1298static void write_packed_entry(FILE *fh, const char *refname,
1299                               const unsigned char *sha1,
1300                               const unsigned char *peeled)
1301{
1302        fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
1303        if (peeled)
1304                fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
1305}
1306
1307/*
1308 * Lock the packed-refs file for writing. Flags is passed to
1309 * hold_lock_file_for_update(). Return 0 on success. On errors, set
1310 * errno appropriately and return a nonzero value.
1311 */
1312static int lock_packed_refs(struct files_ref_store *refs, int flags)
1313{
1314        static int timeout_configured = 0;
1315        static int timeout_value = 1000;
1316        struct packed_ref_cache *packed_ref_cache;
1317
1318        files_assert_main_repository(refs, "lock_packed_refs");
1319
1320        if (!timeout_configured) {
1321                git_config_get_int("core.packedrefstimeout", &timeout_value);
1322                timeout_configured = 1;
1323        }
1324
1325        if (hold_lock_file_for_update_timeout(
1326                            &refs->packed_refs_lock, files_packed_refs_path(refs),
1327                            flags, timeout_value) < 0)
1328                return -1;
1329
1330        /*
1331         * Now that we hold the `packed-refs` lock, make sure that our
1332         * cache matches the current version of the file. Normally
1333         * `get_packed_ref_cache()` does that for us, but that
1334         * function assumes that when the file is locked, any existing
1335         * cache is still valid. We've just locked the file, but it
1336         * might have changed the moment *before* we locked it.
1337         */
1338        validate_packed_ref_cache(refs);
1339
1340        packed_ref_cache = get_packed_ref_cache(refs);
1341        /* Increment the reference count to prevent it from being freed: */
1342        acquire_packed_ref_cache(packed_ref_cache);
1343        return 0;
1344}
1345
1346/*
1347 * Write the current version of the packed refs cache from memory to
1348 * disk. The packed-refs file must already be locked for writing (see
1349 * lock_packed_refs()). Return zero on success. On errors, set errno
1350 * and return a nonzero value
1351 */
1352static int commit_packed_refs(struct files_ref_store *refs)
1353{
1354        struct packed_ref_cache *packed_ref_cache =
1355                get_packed_ref_cache(refs);
1356        int ok, error = 0;
1357        int save_errno = 0;
1358        FILE *out;
1359        struct ref_iterator *iter;
1360
1361        files_assert_main_repository(refs, "commit_packed_refs");
1362
1363        if (!is_lock_file_locked(&refs->packed_refs_lock))
1364                die("BUG: packed-refs not locked");
1365
1366        out = fdopen_lock_file(&refs->packed_refs_lock, "w");
1367        if (!out)
1368                die_errno("unable to fdopen packed-refs descriptor");
1369
1370        fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
1371
1372        iter = cache_ref_iterator_begin(packed_ref_cache->cache, NULL, 0);
1373        while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1374                struct object_id peeled;
1375                int peel_error = ref_iterator_peel(iter, &peeled);
1376
1377                write_packed_entry(out, iter->refname, iter->oid->hash,
1378                                   peel_error ? NULL : peeled.hash);
1379        }
1380
1381        if (ok != ITER_DONE)
1382                die("error while iterating over references");
1383
1384        if (commit_lock_file(&refs->packed_refs_lock)) {
1385                save_errno = errno;
1386                error = -1;
1387        }
1388        release_packed_ref_cache(packed_ref_cache);
1389        errno = save_errno;
1390        return error;
1391}
1392
1393/*
1394 * Rollback the lockfile for the packed-refs file, and discard the
1395 * in-memory packed reference cache.  (The packed-refs file will be
1396 * read anew if it is needed again after this function is called.)
1397 */
1398static void rollback_packed_refs(struct files_ref_store *refs)
1399{
1400        struct packed_ref_cache *packed_ref_cache =
1401                get_packed_ref_cache(refs);
1402
1403        files_assert_main_repository(refs, "rollback_packed_refs");
1404
1405        if (!is_lock_file_locked(&refs->packed_refs_lock))
1406                die("BUG: packed-refs not locked");
1407        rollback_lock_file(&refs->packed_refs_lock);
1408        release_packed_ref_cache(packed_ref_cache);
1409        clear_packed_ref_cache(refs);
1410}
1411
1412struct ref_to_prune {
1413        struct ref_to_prune *next;
1414        unsigned char sha1[20];
1415        char name[FLEX_ARRAY];
1416};
1417
1418enum {
1419        REMOVE_EMPTY_PARENTS_REF = 0x01,
1420        REMOVE_EMPTY_PARENTS_REFLOG = 0x02
1421};
1422
1423/*
1424 * Remove empty parent directories associated with the specified
1425 * reference and/or its reflog, but spare [logs/]refs/ and immediate
1426 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or
1427 * REMOVE_EMPTY_PARENTS_REFLOG.
1428 */
1429static void try_remove_empty_parents(struct files_ref_store *refs,
1430                                     const char *refname,
1431                                     unsigned int flags)
1432{
1433        struct strbuf buf = STRBUF_INIT;
1434        struct strbuf sb = STRBUF_INIT;
1435        char *p, *q;
1436        int i;
1437
1438        strbuf_addstr(&buf, refname);
1439        p = buf.buf;
1440        for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
1441                while (*p && *p != '/')
1442                        p++;
1443                /* tolerate duplicate slashes; see check_refname_format() */
1444                while (*p == '/')
1445                        p++;
1446        }
1447        q = buf.buf + buf.len;
1448        while (flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {
1449                while (q > p && *q != '/')
1450                        q--;
1451                while (q > p && *(q-1) == '/')
1452                        q--;
1453                if (q == p)
1454                        break;
1455                strbuf_setlen(&buf, q - buf.buf);
1456
1457                strbuf_reset(&sb);
1458                files_ref_path(refs, &sb, buf.buf);
1459                if ((flags & REMOVE_EMPTY_PARENTS_REF) && rmdir(sb.buf))
1460                        flags &= ~REMOVE_EMPTY_PARENTS_REF;
1461
1462                strbuf_reset(&sb);
1463                files_reflog_path(refs, &sb, buf.buf);
1464                if ((flags & REMOVE_EMPTY_PARENTS_REFLOG) && rmdir(sb.buf))
1465                        flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;
1466        }
1467        strbuf_release(&buf);
1468        strbuf_release(&sb);
1469}
1470
1471/* make sure nobody touched the ref, and unlink */
1472static void prune_ref(struct files_ref_store *refs, struct ref_to_prune *r)
1473{
1474        struct ref_transaction *transaction;
1475        struct strbuf err = STRBUF_INIT;
1476
1477        if (check_refname_format(r->name, 0))
1478                return;
1479
1480        transaction = ref_store_transaction_begin(&refs->base, &err);
1481        if (!transaction ||
1482            ref_transaction_delete(transaction, r->name, r->sha1,
1483                                   REF_ISPRUNING | REF_NODEREF, NULL, &err) ||
1484            ref_transaction_commit(transaction, &err)) {
1485                ref_transaction_free(transaction);
1486                error("%s", err.buf);
1487                strbuf_release(&err);
1488                return;
1489        }
1490        ref_transaction_free(transaction);
1491        strbuf_release(&err);
1492}
1493
1494static void prune_refs(struct files_ref_store *refs, struct ref_to_prune *r)
1495{
1496        while (r) {
1497                prune_ref(refs, r);
1498                r = r->next;
1499        }
1500}
1501
1502/*
1503 * Return true if the specified reference should be packed.
1504 */
1505static int should_pack_ref(const char *refname,
1506                           const struct object_id *oid, unsigned int ref_flags,
1507                           unsigned int pack_flags)
1508{
1509        /* Do not pack per-worktree refs: */
1510        if (ref_type(refname) != REF_TYPE_NORMAL)
1511                return 0;
1512
1513        /* Do not pack non-tags unless PACK_REFS_ALL is set: */
1514        if (!(pack_flags & PACK_REFS_ALL) && !starts_with(refname, "refs/tags/"))
1515                return 0;
1516
1517        /* Do not pack symbolic refs: */
1518        if (ref_flags & REF_ISSYMREF)
1519                return 0;
1520
1521        /* Do not pack broken refs: */
1522        if (!ref_resolves_to_object(refname, oid, ref_flags))
1523                return 0;
1524
1525        return 1;
1526}
1527
1528static int files_pack_refs(struct ref_store *ref_store, unsigned int flags)
1529{
1530        struct files_ref_store *refs =
1531                files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,
1532                               "pack_refs");
1533        struct ref_iterator *iter;
1534        struct ref_dir *packed_refs;
1535        int ok;
1536        struct ref_to_prune *refs_to_prune = NULL;
1537
1538        lock_packed_refs(refs, LOCK_DIE_ON_ERROR);
1539        packed_refs = get_packed_refs(refs);
1540
1541        iter = cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL, 0);
1542        while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1543                /*
1544                 * If the loose reference can be packed, add an entry
1545                 * in the packed ref cache. If the reference should be
1546                 * pruned, also add it to refs_to_prune.
1547                 */
1548                struct ref_entry *packed_entry;
1549
1550                if (!should_pack_ref(iter->refname, iter->oid, iter->flags,
1551                                     flags))
1552                        continue;
1553
1554                /*
1555                 * Create an entry in the packed-refs cache equivalent
1556                 * to the one from the loose ref cache, except that
1557                 * we don't copy the peeled status, because we want it
1558                 * to be re-peeled.
1559                 */
1560                packed_entry = find_ref_entry(packed_refs, iter->refname);
1561                if (packed_entry) {
1562                        /* Overwrite existing packed entry with info from loose entry */
1563                        packed_entry->flag = REF_ISPACKED;
1564                        oidcpy(&packed_entry->u.value.oid, iter->oid);
1565                } else {
1566                        packed_entry = create_ref_entry(iter->refname, iter->oid,
1567                                                        REF_ISPACKED);
1568                        add_ref_entry(packed_refs, packed_entry);
1569                }
1570                oidclr(&packed_entry->u.value.peeled);
1571
1572                /* Schedule the loose reference for pruning if requested. */
1573                if ((flags & PACK_REFS_PRUNE)) {
1574                        struct ref_to_prune *n;
1575                        FLEX_ALLOC_STR(n, name, iter->refname);
1576                        hashcpy(n->sha1, iter->oid->hash);
1577                        n->next = refs_to_prune;
1578                        refs_to_prune = n;
1579                }
1580        }
1581        if (ok != ITER_DONE)
1582                die("error while iterating over references");
1583
1584        if (commit_packed_refs(refs))
1585                die_errno("unable to overwrite old ref-pack file");
1586
1587        prune_refs(refs, refs_to_prune);
1588        return 0;
1589}
1590
1591/*
1592 * Rewrite the packed-refs file, omitting any refs listed in
1593 * 'refnames'. On error, leave packed-refs unchanged, write an error
1594 * message to 'err', and return a nonzero value.
1595 *
1596 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
1597 */
1598static int repack_without_refs(struct files_ref_store *refs,
1599                               struct string_list *refnames, struct strbuf *err)
1600{
1601        struct ref_dir *packed;
1602        struct string_list_item *refname;
1603        int ret, needs_repacking = 0, removed = 0;
1604
1605        files_assert_main_repository(refs, "repack_without_refs");
1606        assert(err);
1607
1608        /* Look for a packed ref */
1609        for_each_string_list_item(refname, refnames) {
1610                if (get_packed_ref(refs, refname->string)) {
1611                        needs_repacking = 1;
1612                        break;
1613                }
1614        }
1615
1616        /* Avoid locking if we have nothing to do */
1617        if (!needs_repacking)
1618                return 0; /* no refname exists in packed refs */
1619
1620        if (lock_packed_refs(refs, 0)) {
1621                unable_to_lock_message(files_packed_refs_path(refs), errno, err);
1622                return -1;
1623        }
1624        packed = get_packed_refs(refs);
1625
1626        /* Remove refnames from the cache */
1627        for_each_string_list_item(refname, refnames)
1628                if (remove_entry_from_dir(packed, refname->string) != -1)
1629                        removed = 1;
1630        if (!removed) {
1631                /*
1632                 * All packed entries disappeared while we were
1633                 * acquiring the lock.
1634                 */
1635                rollback_packed_refs(refs);
1636                return 0;
1637        }
1638
1639        /* Write what remains */
1640        ret = commit_packed_refs(refs);
1641        if (ret)
1642                strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
1643                            strerror(errno));
1644        return ret;
1645}
1646
1647static int files_delete_refs(struct ref_store *ref_store, const char *msg,
1648                             struct string_list *refnames, unsigned int flags)
1649{
1650        struct files_ref_store *refs =
1651                files_downcast(ref_store, REF_STORE_WRITE, "delete_refs");
1652        struct strbuf err = STRBUF_INIT;
1653        int i, result = 0;
1654
1655        if (!refnames->nr)
1656                return 0;
1657
1658        result = repack_without_refs(refs, refnames, &err);
1659        if (result) {
1660                /*
1661                 * If we failed to rewrite the packed-refs file, then
1662                 * it is unsafe to try to remove loose refs, because
1663                 * doing so might expose an obsolete packed value for
1664                 * a reference that might even point at an object that
1665                 * has been garbage collected.
1666                 */
1667                if (refnames->nr == 1)
1668                        error(_("could not delete reference %s: %s"),
1669                              refnames->items[0].string, err.buf);
1670                else
1671                        error(_("could not delete references: %s"), err.buf);
1672
1673                goto out;
1674        }
1675
1676        for (i = 0; i < refnames->nr; i++) {
1677                const char *refname = refnames->items[i].string;
1678
1679                if (refs_delete_ref(&refs->base, msg, refname, NULL, flags))
1680                        result |= error(_("could not remove reference %s"), refname);
1681        }
1682
1683out:
1684        strbuf_release(&err);
1685        return result;
1686}
1687
1688/*
1689 * People using contrib's git-new-workdir have .git/logs/refs ->
1690 * /some/other/path/.git/logs/refs, and that may live on another device.
1691 *
1692 * IOW, to avoid cross device rename errors, the temporary renamed log must
1693 * live into logs/refs.
1694 */
1695#define TMP_RENAMED_LOG  "refs/.tmp-renamed-log"
1696
1697struct rename_cb {
1698        const char *tmp_renamed_log;
1699        int true_errno;
1700};
1701
1702static int rename_tmp_log_callback(const char *path, void *cb_data)
1703{
1704        struct rename_cb *cb = cb_data;
1705
1706        if (rename(cb->tmp_renamed_log, path)) {
1707                /*
1708                 * rename(a, b) when b is an existing directory ought
1709                 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.
1710                 * Sheesh. Record the true errno for error reporting,
1711                 * but report EISDIR to raceproof_create_file() so
1712                 * that it knows to retry.
1713                 */
1714                cb->true_errno = errno;
1715                if (errno == ENOTDIR)
1716                        errno = EISDIR;
1717                return -1;
1718        } else {
1719                return 0;
1720        }
1721}
1722
1723static int rename_tmp_log(struct files_ref_store *refs, const char *newrefname)
1724{
1725        struct strbuf path = STRBUF_INIT;
1726        struct strbuf tmp = STRBUF_INIT;
1727        struct rename_cb cb;
1728        int ret;
1729
1730        files_reflog_path(refs, &path, newrefname);
1731        files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);
1732        cb.tmp_renamed_log = tmp.buf;
1733        ret = raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);
1734        if (ret) {
1735                if (errno == EISDIR)
1736                        error("directory not empty: %s", path.buf);
1737                else
1738                        error("unable to move logfile %s to %s: %s",
1739                              tmp.buf, path.buf,
1740                              strerror(cb.true_errno));
1741        }
1742
1743        strbuf_release(&path);
1744        strbuf_release(&tmp);
1745        return ret;
1746}
1747
1748static int write_ref_to_lockfile(struct ref_lock *lock,
1749                                 const struct object_id *oid, struct strbuf *err);
1750static int commit_ref_update(struct files_ref_store *refs,
1751                             struct ref_lock *lock,
1752                             const struct object_id *oid, const char *logmsg,
1753                             struct strbuf *err);
1754
1755static int files_rename_ref(struct ref_store *ref_store,
1756                            const char *oldrefname, const char *newrefname,
1757                            const char *logmsg)
1758{
1759        struct files_ref_store *refs =
1760                files_downcast(ref_store, REF_STORE_WRITE, "rename_ref");
1761        struct object_id oid, orig_oid;
1762        int flag = 0, logmoved = 0;
1763        struct ref_lock *lock;
1764        struct stat loginfo;
1765        struct strbuf sb_oldref = STRBUF_INIT;
1766        struct strbuf sb_newref = STRBUF_INIT;
1767        struct strbuf tmp_renamed_log = STRBUF_INIT;
1768        int log, ret;
1769        struct strbuf err = STRBUF_INIT;
1770
1771        files_reflog_path(refs, &sb_oldref, oldrefname);
1772        files_reflog_path(refs, &sb_newref, newrefname);
1773        files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);
1774
1775        log = !lstat(sb_oldref.buf, &loginfo);
1776        if (log && S_ISLNK(loginfo.st_mode)) {
1777                ret = error("reflog for %s is a symlink", oldrefname);
1778                goto out;
1779        }
1780
1781        if (!refs_resolve_ref_unsafe(&refs->base, oldrefname,
1782                                     RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1783                                orig_oid.hash, &flag)) {
1784                ret = error("refname %s not found", oldrefname);
1785                goto out;
1786        }
1787
1788        if (flag & REF_ISSYMREF) {
1789                ret = error("refname %s is a symbolic ref, renaming it is not supported",
1790                            oldrefname);
1791                goto out;
1792        }
1793        if (!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {
1794                ret = 1;
1795                goto out;
1796        }
1797
1798        if (log && rename(sb_oldref.buf, tmp_renamed_log.buf)) {
1799                ret = error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
1800                            oldrefname, strerror(errno));
1801                goto out;
1802        }
1803
1804        if (refs_delete_ref(&refs->base, logmsg, oldrefname,
1805                            orig_oid.hash, REF_NODEREF)) {
1806                error("unable to delete old %s", oldrefname);
1807                goto rollback;
1808        }
1809
1810        /*
1811         * Since we are doing a shallow lookup, oid is not the
1812         * correct value to pass to delete_ref as old_oid. But that
1813         * doesn't matter, because an old_oid check wouldn't add to
1814         * the safety anyway; we want to delete the reference whatever
1815         * its current value.
1816         */
1817        if (!refs_read_ref_full(&refs->base, newrefname,
1818                                RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1819                                oid.hash, NULL) &&
1820            refs_delete_ref(&refs->base, NULL, newrefname,
1821                            NULL, REF_NODEREF)) {
1822                if (errno == EISDIR) {
1823                        struct strbuf path = STRBUF_INIT;
1824                        int result;
1825
1826                        files_ref_path(refs, &path, newrefname);
1827                        result = remove_empty_directories(&path);
1828                        strbuf_release(&path);
1829
1830                        if (result) {
1831                                error("Directory not empty: %s", newrefname);
1832                                goto rollback;
1833                        }
1834                } else {
1835                        error("unable to delete existing %s", newrefname);
1836                        goto rollback;
1837                }
1838        }
1839
1840        if (log && rename_tmp_log(refs, newrefname))
1841                goto rollback;
1842
1843        logmoved = log;
1844
1845        lock = lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,
1846                                   REF_NODEREF, NULL, &err);
1847        if (!lock) {
1848                error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
1849                strbuf_release(&err);
1850                goto rollback;
1851        }
1852        oidcpy(&lock->old_oid, &orig_oid);
1853
1854        if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1855            commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {
1856                error("unable to write current sha1 into %s: %s", newrefname, err.buf);
1857                strbuf_release(&err);
1858                goto rollback;
1859        }
1860
1861        ret = 0;
1862        goto out;
1863
1864 rollback:
1865        lock = lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,
1866                                   REF_NODEREF, NULL, &err);
1867        if (!lock) {
1868                error("unable to lock %s for rollback: %s", oldrefname, err.buf);
1869                strbuf_release(&err);
1870                goto rollbacklog;
1871        }
1872
1873        flag = log_all_ref_updates;
1874        log_all_ref_updates = LOG_REFS_NONE;
1875        if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1876            commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {
1877                error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
1878                strbuf_release(&err);
1879        }
1880        log_all_ref_updates = flag;
1881
1882 rollbacklog:
1883        if (logmoved && rename(sb_newref.buf, sb_oldref.buf))
1884                error("unable to restore logfile %s from %s: %s",
1885                        oldrefname, newrefname, strerror(errno));
1886        if (!logmoved && log &&
1887            rename(tmp_renamed_log.buf, sb_oldref.buf))
1888                error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG": %s",
1889                        oldrefname, strerror(errno));
1890        ret = 1;
1891 out:
1892        strbuf_release(&sb_newref);
1893        strbuf_release(&sb_oldref);
1894        strbuf_release(&tmp_renamed_log);
1895
1896        return ret;
1897}
1898
1899static int close_ref(struct ref_lock *lock)
1900{
1901        if (close_lock_file(lock->lk))
1902                return -1;
1903        return 0;
1904}
1905
1906static int commit_ref(struct ref_lock *lock)
1907{
1908        char *path = get_locked_file_path(lock->lk);
1909        struct stat st;
1910
1911        if (!lstat(path, &st) && S_ISDIR(st.st_mode)) {
1912                /*
1913                 * There is a directory at the path we want to rename
1914                 * the lockfile to. Hopefully it is empty; try to
1915                 * delete it.
1916                 */
1917                size_t len = strlen(path);
1918                struct strbuf sb_path = STRBUF_INIT;
1919
1920                strbuf_attach(&sb_path, path, len, len);
1921
1922                /*
1923                 * If this fails, commit_lock_file() will also fail
1924                 * and will report the problem.
1925                 */
1926                remove_empty_directories(&sb_path);
1927                strbuf_release(&sb_path);
1928        } else {
1929                free(path);
1930        }
1931
1932        if (commit_lock_file(lock->lk))
1933                return -1;
1934        return 0;
1935}
1936
1937static int open_or_create_logfile(const char *path, void *cb)
1938{
1939        int *fd = cb;
1940
1941        *fd = open(path, O_APPEND | O_WRONLY | O_CREAT, 0666);
1942        return (*fd < 0) ? -1 : 0;
1943}
1944
1945/*
1946 * Create a reflog for a ref. If force_create = 0, only create the
1947 * reflog for certain refs (those for which should_autocreate_reflog
1948 * returns non-zero). Otherwise, create it regardless of the reference
1949 * name. If the logfile already existed or was created, return 0 and
1950 * set *logfd to the file descriptor opened for appending to the file.
1951 * If no logfile exists and we decided not to create one, return 0 and
1952 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and
1953 * return -1.
1954 */
1955static int log_ref_setup(struct files_ref_store *refs,
1956                         const char *refname, int force_create,
1957                         int *logfd, struct strbuf *err)
1958{
1959        struct strbuf logfile_sb = STRBUF_INIT;
1960        char *logfile;
1961
1962        files_reflog_path(refs, &logfile_sb, refname);
1963        logfile = strbuf_detach(&logfile_sb, NULL);
1964
1965        if (force_create || should_autocreate_reflog(refname)) {
1966                if (raceproof_create_file(logfile, open_or_create_logfile, logfd)) {
1967                        if (errno == ENOENT)
1968                                strbuf_addf(err, "unable to create directory for '%s': "
1969                                            "%s", logfile, strerror(errno));
1970                        else if (errno == EISDIR)
1971                                strbuf_addf(err, "there are still logs under '%s'",
1972                                            logfile);
1973                        else
1974                                strbuf_addf(err, "unable to append to '%s': %s",
1975                                            logfile, strerror(errno));
1976
1977                        goto error;
1978                }
1979        } else {
1980                *logfd = open(logfile, O_APPEND | O_WRONLY, 0666);
1981                if (*logfd < 0) {
1982                        if (errno == ENOENT || errno == EISDIR) {
1983                                /*
1984                                 * The logfile doesn't already exist,
1985                                 * but that is not an error; it only
1986                                 * means that we won't write log
1987                                 * entries to it.
1988                                 */
1989                                ;
1990                        } else {
1991                                strbuf_addf(err, "unable to append to '%s': %s",
1992                                            logfile, strerror(errno));
1993                                goto error;
1994                        }
1995                }
1996        }
1997
1998        if (*logfd >= 0)
1999                adjust_shared_perm(logfile);
2000
2001        free(logfile);
2002        return 0;
2003
2004error:
2005        free(logfile);
2006        return -1;
2007}
2008
2009static int files_create_reflog(struct ref_store *ref_store,
2010                               const char *refname, int force_create,
2011                               struct strbuf *err)
2012{
2013        struct files_ref_store *refs =
2014                files_downcast(ref_store, REF_STORE_WRITE, "create_reflog");
2015        int fd;
2016
2017        if (log_ref_setup(refs, refname, force_create, &fd, err))
2018                return -1;
2019
2020        if (fd >= 0)
2021                close(fd);
2022
2023        return 0;
2024}
2025
2026static int log_ref_write_fd(int fd, const struct object_id *old_oid,
2027                            const struct object_id *new_oid,
2028                            const char *committer, const char *msg)
2029{
2030        int msglen, written;
2031        unsigned maxlen, len;
2032        char *logrec;
2033
2034        msglen = msg ? strlen(msg) : 0;
2035        maxlen = strlen(committer) + msglen + 100;
2036        logrec = xmalloc(maxlen);
2037        len = xsnprintf(logrec, maxlen, "%s %s %s\n",
2038                        oid_to_hex(old_oid),
2039                        oid_to_hex(new_oid),
2040                        committer);
2041        if (msglen)
2042                len += copy_reflog_msg(logrec + len - 1, msg) - 1;
2043
2044        written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
2045        free(logrec);
2046        if (written != len)
2047                return -1;
2048
2049        return 0;
2050}
2051
2052static int files_log_ref_write(struct files_ref_store *refs,
2053                               const char *refname, const struct object_id *old_oid,
2054                               const struct object_id *new_oid, const char *msg,
2055                               int flags, struct strbuf *err)
2056{
2057        int logfd, result;
2058
2059        if (log_all_ref_updates == LOG_REFS_UNSET)
2060                log_all_ref_updates = is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;
2061
2062        result = log_ref_setup(refs, refname,
2063                               flags & REF_FORCE_CREATE_REFLOG,
2064                               &logfd, err);
2065
2066        if (result)
2067                return result;
2068
2069        if (logfd < 0)
2070                return 0;
2071        result = log_ref_write_fd(logfd, old_oid, new_oid,
2072                                  git_committer_info(0), msg);
2073        if (result) {
2074                struct strbuf sb = STRBUF_INIT;
2075                int save_errno = errno;
2076
2077                files_reflog_path(refs, &sb, refname);
2078                strbuf_addf(err, "unable to append to '%s': %s",
2079                            sb.buf, strerror(save_errno));
2080                strbuf_release(&sb);
2081                close(logfd);
2082                return -1;
2083        }
2084        if (close(logfd)) {
2085                struct strbuf sb = STRBUF_INIT;
2086                int save_errno = errno;
2087
2088                files_reflog_path(refs, &sb, refname);
2089                strbuf_addf(err, "unable to append to '%s': %s",
2090                            sb.buf, strerror(save_errno));
2091                strbuf_release(&sb);
2092                return -1;
2093        }
2094        return 0;
2095}
2096
2097/*
2098 * Write sha1 into the open lockfile, then close the lockfile. On
2099 * errors, rollback the lockfile, fill in *err and
2100 * return -1.
2101 */
2102static int write_ref_to_lockfile(struct ref_lock *lock,
2103                                 const struct object_id *oid, struct strbuf *err)
2104{
2105        static char term = '\n';
2106        struct object *o;
2107        int fd;
2108
2109        o = parse_object(oid);
2110        if (!o) {
2111                strbuf_addf(err,
2112                            "trying to write ref '%s' with nonexistent object %s",
2113                            lock->ref_name, oid_to_hex(oid));
2114                unlock_ref(lock);
2115                return -1;
2116        }
2117        if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2118                strbuf_addf(err,
2119                            "trying to write non-commit object %s to branch '%s'",
2120                            oid_to_hex(oid), lock->ref_name);
2121                unlock_ref(lock);
2122                return -1;
2123        }
2124        fd = get_lock_file_fd(lock->lk);
2125        if (write_in_full(fd, oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
2126            write_in_full(fd, &term, 1) != 1 ||
2127            close_ref(lock) < 0) {
2128                strbuf_addf(err,
2129                            "couldn't write '%s'", get_lock_file_path(lock->lk));
2130                unlock_ref(lock);
2131                return -1;
2132        }
2133        return 0;
2134}
2135
2136/*
2137 * Commit a change to a loose reference that has already been written
2138 * to the loose reference lockfile. Also update the reflogs if
2139 * necessary, using the specified lockmsg (which can be NULL).
2140 */
2141static int commit_ref_update(struct files_ref_store *refs,
2142                             struct ref_lock *lock,
2143                             const struct object_id *oid, const char *logmsg,
2144                             struct strbuf *err)
2145{
2146        files_assert_main_repository(refs, "commit_ref_update");
2147
2148        clear_loose_ref_cache(refs);
2149        if (files_log_ref_write(refs, lock->ref_name,
2150                                &lock->old_oid, oid,
2151                                logmsg, 0, err)) {
2152                char *old_msg = strbuf_detach(err, NULL);
2153                strbuf_addf(err, "cannot update the ref '%s': %s",
2154                            lock->ref_name, old_msg);
2155                free(old_msg);
2156                unlock_ref(lock);
2157                return -1;
2158        }
2159
2160        if (strcmp(lock->ref_name, "HEAD") != 0) {
2161                /*
2162                 * Special hack: If a branch is updated directly and HEAD
2163                 * points to it (may happen on the remote side of a push
2164                 * for example) then logically the HEAD reflog should be
2165                 * updated too.
2166                 * A generic solution implies reverse symref information,
2167                 * but finding all symrefs pointing to the given branch
2168                 * would be rather costly for this rare event (the direct
2169                 * update of a branch) to be worth it.  So let's cheat and
2170                 * check with HEAD only which should cover 99% of all usage
2171                 * scenarios (even 100% of the default ones).
2172                 */
2173                struct object_id head_oid;
2174                int head_flag;
2175                const char *head_ref;
2176
2177                head_ref = refs_resolve_ref_unsafe(&refs->base, "HEAD",
2178                                                   RESOLVE_REF_READING,
2179                                                   head_oid.hash, &head_flag);
2180                if (head_ref && (head_flag & REF_ISSYMREF) &&
2181                    !strcmp(head_ref, lock->ref_name)) {
2182                        struct strbuf log_err = STRBUF_INIT;
2183                        if (files_log_ref_write(refs, "HEAD",
2184                                                &lock->old_oid, oid,
2185                                                logmsg, 0, &log_err)) {
2186                                error("%s", log_err.buf);
2187                                strbuf_release(&log_err);
2188                        }
2189                }
2190        }
2191
2192        if (commit_ref(lock)) {
2193                strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
2194                unlock_ref(lock);
2195                return -1;
2196        }
2197
2198        unlock_ref(lock);
2199        return 0;
2200}
2201
2202static int create_ref_symlink(struct ref_lock *lock, const char *target)
2203{
2204        int ret = -1;
2205#ifndef NO_SYMLINK_HEAD
2206        char *ref_path = get_locked_file_path(lock->lk);
2207        unlink(ref_path);
2208        ret = symlink(target, ref_path);
2209        free(ref_path);
2210
2211        if (ret)
2212                fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2213#endif
2214        return ret;
2215}
2216
2217static void update_symref_reflog(struct files_ref_store *refs,
2218                                 struct ref_lock *lock, const char *refname,
2219                                 const char *target, const char *logmsg)
2220{
2221        struct strbuf err = STRBUF_INIT;
2222        struct object_id new_oid;
2223        if (logmsg &&
2224            !refs_read_ref_full(&refs->base, target,
2225                                RESOLVE_REF_READING, new_oid.hash, NULL) &&
2226            files_log_ref_write(refs, refname, &lock->old_oid,
2227                                &new_oid, logmsg, 0, &err)) {
2228                error("%s", err.buf);
2229                strbuf_release(&err);
2230        }
2231}
2232
2233static int create_symref_locked(struct files_ref_store *refs,
2234                                struct ref_lock *lock, const char *refname,
2235                                const char *target, const char *logmsg)
2236{
2237        if (prefer_symlink_refs && !create_ref_symlink(lock, target)) {
2238                update_symref_reflog(refs, lock, refname, target, logmsg);
2239                return 0;
2240        }
2241
2242        if (!fdopen_lock_file(lock->lk, "w"))
2243                return error("unable to fdopen %s: %s",
2244                             lock->lk->tempfile.filename.buf, strerror(errno));
2245
2246        update_symref_reflog(refs, lock, refname, target, logmsg);
2247
2248        /* no error check; commit_ref will check ferror */
2249        fprintf(lock->lk->tempfile.fp, "ref: %s\n", target);
2250        if (commit_ref(lock) < 0)
2251                return error("unable to write symref for %s: %s", refname,
2252                             strerror(errno));
2253        return 0;
2254}
2255
2256static int files_create_symref(struct ref_store *ref_store,
2257                               const char *refname, const char *target,
2258                               const char *logmsg)
2259{
2260        struct files_ref_store *refs =
2261                files_downcast(ref_store, REF_STORE_WRITE, "create_symref");
2262        struct strbuf err = STRBUF_INIT;
2263        struct ref_lock *lock;
2264        int ret;
2265
2266        lock = lock_ref_sha1_basic(refs, refname, NULL,
2267                                   NULL, NULL, REF_NODEREF, NULL,
2268                                   &err);
2269        if (!lock) {
2270                error("%s", err.buf);
2271                strbuf_release(&err);
2272                return -1;
2273        }
2274
2275        ret = create_symref_locked(refs, lock, refname, target, logmsg);
2276        unlock_ref(lock);
2277        return ret;
2278}
2279
2280static int files_reflog_exists(struct ref_store *ref_store,
2281                               const char *refname)
2282{
2283        struct files_ref_store *refs =
2284                files_downcast(ref_store, REF_STORE_READ, "reflog_exists");
2285        struct strbuf sb = STRBUF_INIT;
2286        struct stat st;
2287        int ret;
2288
2289        files_reflog_path(refs, &sb, refname);
2290        ret = !lstat(sb.buf, &st) && S_ISREG(st.st_mode);
2291        strbuf_release(&sb);
2292        return ret;
2293}
2294
2295static int files_delete_reflog(struct ref_store *ref_store,
2296                               const char *refname)
2297{
2298        struct files_ref_store *refs =
2299                files_downcast(ref_store, REF_STORE_WRITE, "delete_reflog");
2300        struct strbuf sb = STRBUF_INIT;
2301        int ret;
2302
2303        files_reflog_path(refs, &sb, refname);
2304        ret = remove_path(sb.buf);
2305        strbuf_release(&sb);
2306        return ret;
2307}
2308
2309static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
2310{
2311        struct object_id ooid, noid;
2312        char *email_end, *message;
2313        timestamp_t timestamp;
2314        int tz;
2315        const char *p = sb->buf;
2316
2317        /* old SP new SP name <email> SP time TAB msg LF */
2318        if (!sb->len || sb->buf[sb->len - 1] != '\n' ||
2319            parse_oid_hex(p, &ooid, &p) || *p++ != ' ' ||
2320            parse_oid_hex(p, &noid, &p) || *p++ != ' ' ||
2321            !(email_end = strchr(p, '>')) ||
2322            email_end[1] != ' ' ||
2323            !(timestamp = parse_timestamp(email_end + 2, &message, 10)) ||
2324            !message || message[0] != ' ' ||
2325            (message[1] != '+' && message[1] != '-') ||
2326            !isdigit(message[2]) || !isdigit(message[3]) ||
2327            !isdigit(message[4]) || !isdigit(message[5]))
2328                return 0; /* corrupt? */
2329        email_end[1] = '\0';
2330        tz = strtol(message + 1, NULL, 10);
2331        if (message[6] != '\t')
2332                message += 6;
2333        else
2334                message += 7;
2335        return fn(&ooid, &noid, p, timestamp, tz, message, cb_data);
2336}
2337
2338static char *find_beginning_of_line(char *bob, char *scan)
2339{
2340        while (bob < scan && *(--scan) != '\n')
2341                ; /* keep scanning backwards */
2342        /*
2343         * Return either beginning of the buffer, or LF at the end of
2344         * the previous line.
2345         */
2346        return scan;
2347}
2348
2349static int files_for_each_reflog_ent_reverse(struct ref_store *ref_store,
2350                                             const char *refname,
2351                                             each_reflog_ent_fn fn,
2352                                             void *cb_data)
2353{
2354        struct files_ref_store *refs =
2355                files_downcast(ref_store, REF_STORE_READ,
2356                               "for_each_reflog_ent_reverse");
2357        struct strbuf sb = STRBUF_INIT;
2358        FILE *logfp;
2359        long pos;
2360        int ret = 0, at_tail = 1;
2361
2362        files_reflog_path(refs, &sb, refname);
2363        logfp = fopen(sb.buf, "r");
2364        strbuf_release(&sb);
2365        if (!logfp)
2366                return -1;
2367
2368        /* Jump to the end */
2369        if (fseek(logfp, 0, SEEK_END) < 0)
2370                ret = error("cannot seek back reflog for %s: %s",
2371                            refname, strerror(errno));
2372        pos = ftell(logfp);
2373        while (!ret && 0 < pos) {
2374                int cnt;
2375                size_t nread;
2376                char buf[BUFSIZ];
2377                char *endp, *scanp;
2378
2379                /* Fill next block from the end */
2380                cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
2381                if (fseek(logfp, pos - cnt, SEEK_SET)) {
2382                        ret = error("cannot seek back reflog for %s: %s",
2383                                    refname, strerror(errno));
2384                        break;
2385                }
2386                nread = fread(buf, cnt, 1, logfp);
2387                if (nread != 1) {
2388                        ret = error("cannot read %d bytes from reflog for %s: %s",
2389                                    cnt, refname, strerror(errno));
2390                        break;
2391                }
2392                pos -= cnt;
2393
2394                scanp = endp = buf + cnt;
2395                if (at_tail && scanp[-1] == '\n')
2396                        /* Looking at the final LF at the end of the file */
2397                        scanp--;
2398                at_tail = 0;
2399
2400                while (buf < scanp) {
2401                        /*
2402                         * terminating LF of the previous line, or the beginning
2403                         * of the buffer.
2404                         */
2405                        char *bp;
2406
2407                        bp = find_beginning_of_line(buf, scanp);
2408
2409                        if (*bp == '\n') {
2410                                /*
2411                                 * The newline is the end of the previous line,
2412                                 * so we know we have complete line starting
2413                                 * at (bp + 1). Prefix it onto any prior data
2414                                 * we collected for the line and process it.
2415                                 */
2416                                strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
2417                                scanp = bp;
2418                                endp = bp + 1;
2419                                ret = show_one_reflog_ent(&sb, fn, cb_data);
2420                                strbuf_reset(&sb);
2421                                if (ret)
2422                                        break;
2423                        } else if (!pos) {
2424                                /*
2425                                 * We are at the start of the buffer, and the
2426                                 * start of the file; there is no previous
2427                                 * line, and we have everything for this one.
2428                                 * Process it, and we can end the loop.
2429                                 */
2430                                strbuf_splice(&sb, 0, 0, buf, endp - buf);
2431                                ret = show_one_reflog_ent(&sb, fn, cb_data);
2432                                strbuf_reset(&sb);
2433                                break;
2434                        }
2435
2436                        if (bp == buf) {
2437                                /*
2438                                 * We are at the start of the buffer, and there
2439                                 * is more file to read backwards. Which means
2440                                 * we are in the middle of a line. Note that we
2441                                 * may get here even if *bp was a newline; that
2442                                 * just means we are at the exact end of the
2443                                 * previous line, rather than some spot in the
2444                                 * middle.
2445                                 *
2446                                 * Save away what we have to be combined with
2447                                 * the data from the next read.
2448                                 */
2449                                strbuf_splice(&sb, 0, 0, buf, endp - buf);
2450                                break;
2451                        }
2452                }
2453
2454        }
2455        if (!ret && sb.len)
2456                die("BUG: reverse reflog parser had leftover data");
2457
2458        fclose(logfp);
2459        strbuf_release(&sb);
2460        return ret;
2461}
2462
2463static int files_for_each_reflog_ent(struct ref_store *ref_store,
2464                                     const char *refname,
2465                                     each_reflog_ent_fn fn, void *cb_data)
2466{
2467        struct files_ref_store *refs =
2468                files_downcast(ref_store, REF_STORE_READ,
2469                               "for_each_reflog_ent");
2470        FILE *logfp;
2471        struct strbuf sb = STRBUF_INIT;
2472        int ret = 0;
2473
2474        files_reflog_path(refs, &sb, refname);
2475        logfp = fopen(sb.buf, "r");
2476        strbuf_release(&sb);
2477        if (!logfp)
2478                return -1;
2479
2480        while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
2481                ret = show_one_reflog_ent(&sb, fn, cb_data);
2482        fclose(logfp);
2483        strbuf_release(&sb);
2484        return ret;
2485}
2486
2487struct files_reflog_iterator {
2488        struct ref_iterator base;
2489
2490        struct ref_store *ref_store;
2491        struct dir_iterator *dir_iterator;
2492        struct object_id oid;
2493};
2494
2495static int files_reflog_iterator_advance(struct ref_iterator *ref_iterator)
2496{
2497        struct files_reflog_iterator *iter =
2498                (struct files_reflog_iterator *)ref_iterator;
2499        struct dir_iterator *diter = iter->dir_iterator;
2500        int ok;
2501
2502        while ((ok = dir_iterator_advance(diter)) == ITER_OK) {
2503                int flags;
2504
2505                if (!S_ISREG(diter->st.st_mode))
2506                        continue;
2507                if (diter->basename[0] == '.')
2508                        continue;
2509                if (ends_with(diter->basename, ".lock"))
2510                        continue;
2511
2512                if (refs_read_ref_full(iter->ref_store,
2513                                       diter->relative_path, 0,
2514                                       iter->oid.hash, &flags)) {
2515                        error("bad ref for %s", diter->path.buf);
2516                        continue;
2517                }
2518
2519                iter->base.refname = diter->relative_path;
2520                iter->base.oid = &iter->oid;
2521                iter->base.flags = flags;
2522                return ITER_OK;
2523        }
2524
2525        iter->dir_iterator = NULL;
2526        if (ref_iterator_abort(ref_iterator) == ITER_ERROR)
2527                ok = ITER_ERROR;
2528        return ok;
2529}
2530
2531static int files_reflog_iterator_peel(struct ref_iterator *ref_iterator,
2532                                   struct object_id *peeled)
2533{
2534        die("BUG: ref_iterator_peel() called for reflog_iterator");
2535}
2536
2537static int files_reflog_iterator_abort(struct ref_iterator *ref_iterator)
2538{
2539        struct files_reflog_iterator *iter =
2540                (struct files_reflog_iterator *)ref_iterator;
2541        int ok = ITER_DONE;
2542
2543        if (iter->dir_iterator)
2544                ok = dir_iterator_abort(iter->dir_iterator);
2545
2546        base_ref_iterator_free(ref_iterator);
2547        return ok;
2548}
2549
2550static struct ref_iterator_vtable files_reflog_iterator_vtable = {
2551        files_reflog_iterator_advance,
2552        files_reflog_iterator_peel,
2553        files_reflog_iterator_abort
2554};
2555
2556static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)
2557{
2558        struct files_ref_store *refs =
2559                files_downcast(ref_store, REF_STORE_READ,
2560                               "reflog_iterator_begin");
2561        struct files_reflog_iterator *iter = xcalloc(1, sizeof(*iter));
2562        struct ref_iterator *ref_iterator = &iter->base;
2563        struct strbuf sb = STRBUF_INIT;
2564
2565        base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);
2566        files_reflog_path(refs, &sb, NULL);
2567        iter->dir_iterator = dir_iterator_begin(sb.buf);
2568        iter->ref_store = ref_store;
2569        strbuf_release(&sb);
2570        return ref_iterator;
2571}
2572
2573/*
2574 * If update is a direct update of head_ref (the reference pointed to
2575 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
2576 */
2577static int split_head_update(struct ref_update *update,
2578                             struct ref_transaction *transaction,
2579                             const char *head_ref,
2580                             struct string_list *affected_refnames,
2581                             struct strbuf *err)
2582{
2583        struct string_list_item *item;
2584        struct ref_update *new_update;
2585
2586        if ((update->flags & REF_LOG_ONLY) ||
2587            (update->flags & REF_ISPRUNING) ||
2588            (update->flags & REF_UPDATE_VIA_HEAD))
2589                return 0;
2590
2591        if (strcmp(update->refname, head_ref))
2592                return 0;
2593
2594        /*
2595         * First make sure that HEAD is not already in the
2596         * transaction. This insertion is O(N) in the transaction
2597         * size, but it happens at most once per transaction.
2598         */
2599        item = string_list_insert(affected_refnames, "HEAD");
2600        if (item->util) {
2601                /* An entry already existed */
2602                strbuf_addf(err,
2603                            "multiple updates for 'HEAD' (including one "
2604                            "via its referent '%s') are not allowed",
2605                            update->refname);
2606                return TRANSACTION_NAME_CONFLICT;
2607        }
2608
2609        new_update = ref_transaction_add_update(
2610                        transaction, "HEAD",
2611                        update->flags | REF_LOG_ONLY | REF_NODEREF,
2612                        update->new_oid.hash, update->old_oid.hash,
2613                        update->msg);
2614
2615        item->util = new_update;
2616
2617        return 0;
2618}
2619
2620/*
2621 * update is for a symref that points at referent and doesn't have
2622 * REF_NODEREF set. Split it into two updates:
2623 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set
2624 * - A new, separate update for the referent reference
2625 * Note that the new update will itself be subject to splitting when
2626 * the iteration gets to it.
2627 */
2628static int split_symref_update(struct files_ref_store *refs,
2629                               struct ref_update *update,
2630                               const char *referent,
2631                               struct ref_transaction *transaction,
2632                               struct string_list *affected_refnames,
2633                               struct strbuf *err)
2634{
2635        struct string_list_item *item;
2636        struct ref_update *new_update;
2637        unsigned int new_flags;
2638
2639        /*
2640         * First make sure that referent is not already in the
2641         * transaction. This insertion is O(N) in the transaction
2642         * size, but it happens at most once per symref in a
2643         * transaction.
2644         */
2645        item = string_list_insert(affected_refnames, referent);
2646        if (item->util) {
2647                /* An entry already existed */
2648                strbuf_addf(err,
2649                            "multiple updates for '%s' (including one "
2650                            "via symref '%s') are not allowed",
2651                            referent, update->refname);
2652                return TRANSACTION_NAME_CONFLICT;
2653        }
2654
2655        new_flags = update->flags;
2656        if (!strcmp(update->refname, "HEAD")) {
2657                /*
2658                 * Record that the new update came via HEAD, so that
2659                 * when we process it, split_head_update() doesn't try
2660                 * to add another reflog update for HEAD. Note that
2661                 * this bit will be propagated if the new_update
2662                 * itself needs to be split.
2663                 */
2664                new_flags |= REF_UPDATE_VIA_HEAD;
2665        }
2666
2667        new_update = ref_transaction_add_update(
2668                        transaction, referent, new_flags,
2669                        update->new_oid.hash, update->old_oid.hash,
2670                        update->msg);
2671
2672        new_update->parent_update = update;
2673
2674        /*
2675         * Change the symbolic ref update to log only. Also, it
2676         * doesn't need to check its old SHA-1 value, as that will be
2677         * done when new_update is processed.
2678         */
2679        update->flags |= REF_LOG_ONLY | REF_NODEREF;
2680        update->flags &= ~REF_HAVE_OLD;
2681
2682        item->util = new_update;
2683
2684        return 0;
2685}
2686
2687/*
2688 * Return the refname under which update was originally requested.
2689 */
2690static const char *original_update_refname(struct ref_update *update)
2691{
2692        while (update->parent_update)
2693                update = update->parent_update;
2694
2695        return update->refname;
2696}
2697
2698/*
2699 * Check whether the REF_HAVE_OLD and old_oid values stored in update
2700 * are consistent with oid, which is the reference's current value. If
2701 * everything is OK, return 0; otherwise, write an error message to
2702 * err and return -1.
2703 */
2704static int check_old_oid(struct ref_update *update, struct object_id *oid,
2705                         struct strbuf *err)
2706{
2707        if (!(update->flags & REF_HAVE_OLD) ||
2708                   !oidcmp(oid, &update->old_oid))
2709                return 0;
2710
2711        if (is_null_oid(&update->old_oid))
2712                strbuf_addf(err, "cannot lock ref '%s': "
2713                            "reference already exists",
2714                            original_update_refname(update));
2715        else if (is_null_oid(oid))
2716                strbuf_addf(err, "cannot lock ref '%s': "
2717                            "reference is missing but expected %s",
2718                            original_update_refname(update),
2719                            oid_to_hex(&update->old_oid));
2720        else
2721                strbuf_addf(err, "cannot lock ref '%s': "
2722                            "is at %s but expected %s",
2723                            original_update_refname(update),
2724                            oid_to_hex(oid),
2725                            oid_to_hex(&update->old_oid));
2726
2727        return -1;
2728}
2729
2730/*
2731 * Prepare for carrying out update:
2732 * - Lock the reference referred to by update.
2733 * - Read the reference under lock.
2734 * - Check that its old SHA-1 value (if specified) is correct, and in
2735 *   any case record it in update->lock->old_oid for later use when
2736 *   writing the reflog.
2737 * - If it is a symref update without REF_NODEREF, split it up into a
2738 *   REF_LOG_ONLY update of the symref and add a separate update for
2739 *   the referent to transaction.
2740 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
2741 *   update of HEAD.
2742 */
2743static int lock_ref_for_update(struct files_ref_store *refs,
2744                               struct ref_update *update,
2745                               struct ref_transaction *transaction,
2746                               const char *head_ref,
2747                               struct string_list *affected_refnames,
2748                               struct strbuf *err)
2749{
2750        struct strbuf referent = STRBUF_INIT;
2751        int mustexist = (update->flags & REF_HAVE_OLD) &&
2752                !is_null_oid(&update->old_oid);
2753        int ret;
2754        struct ref_lock *lock;
2755
2756        files_assert_main_repository(refs, "lock_ref_for_update");
2757
2758        if ((update->flags & REF_HAVE_NEW) && is_null_oid(&update->new_oid))
2759                update->flags |= REF_DELETING;
2760
2761        if (head_ref) {
2762                ret = split_head_update(update, transaction, head_ref,
2763                                        affected_refnames, err);
2764                if (ret)
2765                        return ret;
2766        }
2767
2768        ret = lock_raw_ref(refs, update->refname, mustexist,
2769                           affected_refnames, NULL,
2770                           &lock, &referent,
2771                           &update->type, err);
2772        if (ret) {
2773                char *reason;
2774
2775                reason = strbuf_detach(err, NULL);
2776                strbuf_addf(err, "cannot lock ref '%s': %s",
2777                            original_update_refname(update), reason);
2778                free(reason);
2779                return ret;
2780        }
2781
2782        update->backend_data = lock;
2783
2784        if (update->type & REF_ISSYMREF) {
2785                if (update->flags & REF_NODEREF) {
2786                        /*
2787                         * We won't be reading the referent as part of
2788                         * the transaction, so we have to read it here
2789                         * to record and possibly check old_sha1:
2790                         */
2791                        if (refs_read_ref_full(&refs->base,
2792                                               referent.buf, 0,
2793                                               lock->old_oid.hash, NULL)) {
2794                                if (update->flags & REF_HAVE_OLD) {
2795                                        strbuf_addf(err, "cannot lock ref '%s': "
2796                                                    "error reading reference",
2797                                                    original_update_refname(update));
2798                                        return -1;
2799                                }
2800                        } else if (check_old_oid(update, &lock->old_oid, err)) {
2801                                return TRANSACTION_GENERIC_ERROR;
2802                        }
2803                } else {
2804                        /*
2805                         * Create a new update for the reference this
2806                         * symref is pointing at. Also, we will record
2807                         * and verify old_sha1 for this update as part
2808                         * of processing the split-off update, so we
2809                         * don't have to do it here.
2810                         */
2811                        ret = split_symref_update(refs, update,
2812                                                  referent.buf, transaction,
2813                                                  affected_refnames, err);
2814                        if (ret)
2815                                return ret;
2816                }
2817        } else {
2818                struct ref_update *parent_update;
2819
2820                if (check_old_oid(update, &lock->old_oid, err))
2821                        return TRANSACTION_GENERIC_ERROR;
2822
2823                /*
2824                 * If this update is happening indirectly because of a
2825                 * symref update, record the old SHA-1 in the parent
2826                 * update:
2827                 */
2828                for (parent_update = update->parent_update;
2829                     parent_update;
2830                     parent_update = parent_update->parent_update) {
2831                        struct ref_lock *parent_lock = parent_update->backend_data;
2832                        oidcpy(&parent_lock->old_oid, &lock->old_oid);
2833                }
2834        }
2835
2836        if ((update->flags & REF_HAVE_NEW) &&
2837            !(update->flags & REF_DELETING) &&
2838            !(update->flags & REF_LOG_ONLY)) {
2839                if (!(update->type & REF_ISSYMREF) &&
2840                    !oidcmp(&lock->old_oid, &update->new_oid)) {
2841                        /*
2842                         * The reference already has the desired
2843                         * value, so we don't need to write it.
2844                         */
2845                } else if (write_ref_to_lockfile(lock, &update->new_oid,
2846                                                 err)) {
2847                        char *write_err = strbuf_detach(err, NULL);
2848
2849                        /*
2850                         * The lock was freed upon failure of
2851                         * write_ref_to_lockfile():
2852                         */
2853                        update->backend_data = NULL;
2854                        strbuf_addf(err,
2855                                    "cannot update ref '%s': %s",
2856                                    update->refname, write_err);
2857                        free(write_err);
2858                        return TRANSACTION_GENERIC_ERROR;
2859                } else {
2860                        update->flags |= REF_NEEDS_COMMIT;
2861                }
2862        }
2863        if (!(update->flags & REF_NEEDS_COMMIT)) {
2864                /*
2865                 * We didn't call write_ref_to_lockfile(), so
2866                 * the lockfile is still open. Close it to
2867                 * free up the file descriptor:
2868                 */
2869                if (close_ref(lock)) {
2870                        strbuf_addf(err, "couldn't close '%s.lock'",
2871                                    update->refname);
2872                        return TRANSACTION_GENERIC_ERROR;
2873                }
2874        }
2875        return 0;
2876}
2877
2878/*
2879 * Unlock any references in `transaction` that are still locked, and
2880 * mark the transaction closed.
2881 */
2882static void files_transaction_cleanup(struct ref_transaction *transaction)
2883{
2884        size_t i;
2885
2886        for (i = 0; i < transaction->nr; i++) {
2887                struct ref_update *update = transaction->updates[i];
2888                struct ref_lock *lock = update->backend_data;
2889
2890                if (lock) {
2891                        unlock_ref(lock);
2892                        update->backend_data = NULL;
2893                }
2894        }
2895
2896        transaction->state = REF_TRANSACTION_CLOSED;
2897}
2898
2899static int files_transaction_prepare(struct ref_store *ref_store,
2900                                     struct ref_transaction *transaction,
2901                                     struct strbuf *err)
2902{
2903        struct files_ref_store *refs =
2904                files_downcast(ref_store, REF_STORE_WRITE,
2905                               "ref_transaction_prepare");
2906        size_t i;
2907        int ret = 0;
2908        struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
2909        char *head_ref = NULL;
2910        int head_type;
2911        struct object_id head_oid;
2912
2913        assert(err);
2914
2915        if (!transaction->nr)
2916                goto cleanup;
2917
2918        /*
2919         * Fail if a refname appears more than once in the
2920         * transaction. (If we end up splitting up any updates using
2921         * split_symref_update() or split_head_update(), those
2922         * functions will check that the new updates don't have the
2923         * same refname as any existing ones.)
2924         */
2925        for (i = 0; i < transaction->nr; i++) {
2926                struct ref_update *update = transaction->updates[i];
2927                struct string_list_item *item =
2928                        string_list_append(&affected_refnames, update->refname);
2929
2930                /*
2931                 * We store a pointer to update in item->util, but at
2932                 * the moment we never use the value of this field
2933                 * except to check whether it is non-NULL.
2934                 */
2935                item->util = update;
2936        }
2937        string_list_sort(&affected_refnames);
2938        if (ref_update_reject_duplicates(&affected_refnames, err)) {
2939                ret = TRANSACTION_GENERIC_ERROR;
2940                goto cleanup;
2941        }
2942
2943        /*
2944         * Special hack: If a branch is updated directly and HEAD
2945         * points to it (may happen on the remote side of a push
2946         * for example) then logically the HEAD reflog should be
2947         * updated too.
2948         *
2949         * A generic solution would require reverse symref lookups,
2950         * but finding all symrefs pointing to a given branch would be
2951         * rather costly for this rare event (the direct update of a
2952         * branch) to be worth it. So let's cheat and check with HEAD
2953         * only, which should cover 99% of all usage scenarios (even
2954         * 100% of the default ones).
2955         *
2956         * So if HEAD is a symbolic reference, then record the name of
2957         * the reference that it points to. If we see an update of
2958         * head_ref within the transaction, then split_head_update()
2959         * arranges for the reflog of HEAD to be updated, too.
2960         */
2961        head_ref = refs_resolve_refdup(ref_store, "HEAD",
2962                                       RESOLVE_REF_NO_RECURSE,
2963                                       head_oid.hash, &head_type);
2964
2965        if (head_ref && !(head_type & REF_ISSYMREF)) {
2966                FREE_AND_NULL(head_ref);
2967        }
2968
2969        /*
2970         * Acquire all locks, verify old values if provided, check
2971         * that new values are valid, and write new values to the
2972         * lockfiles, ready to be activated. Only keep one lockfile
2973         * open at a time to avoid running out of file descriptors.
2974         * Note that lock_ref_for_update() might append more updates
2975         * to the transaction.
2976         */
2977        for (i = 0; i < transaction->nr; i++) {
2978                struct ref_update *update = transaction->updates[i];
2979
2980                ret = lock_ref_for_update(refs, update, transaction,
2981                                          head_ref, &affected_refnames, err);
2982                if (ret)
2983                        break;
2984        }
2985
2986cleanup:
2987        free(head_ref);
2988        string_list_clear(&affected_refnames, 0);
2989
2990        if (ret)
2991                files_transaction_cleanup(transaction);
2992        else
2993                transaction->state = REF_TRANSACTION_PREPARED;
2994
2995        return ret;
2996}
2997
2998static int files_transaction_finish(struct ref_store *ref_store,
2999                                    struct ref_transaction *transaction,
3000                                    struct strbuf *err)
3001{
3002        struct files_ref_store *refs =
3003                files_downcast(ref_store, 0, "ref_transaction_finish");
3004        size_t i;
3005        int ret = 0;
3006        struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
3007        struct string_list_item *ref_to_delete;
3008        struct strbuf sb = STRBUF_INIT;
3009
3010        assert(err);
3011
3012        if (!transaction->nr) {
3013                transaction->state = REF_TRANSACTION_CLOSED;
3014                return 0;
3015        }
3016
3017        /* Perform updates first so live commits remain referenced */
3018        for (i = 0; i < transaction->nr; i++) {
3019                struct ref_update *update = transaction->updates[i];
3020                struct ref_lock *lock = update->backend_data;
3021
3022                if (update->flags & REF_NEEDS_COMMIT ||
3023                    update->flags & REF_LOG_ONLY) {
3024                        if (files_log_ref_write(refs,
3025                                                lock->ref_name,
3026                                                &lock->old_oid,
3027                                                &update->new_oid,
3028                                                update->msg, update->flags,
3029                                                err)) {
3030                                char *old_msg = strbuf_detach(err, NULL);
3031
3032                                strbuf_addf(err, "cannot update the ref '%s': %s",
3033                                            lock->ref_name, old_msg);
3034                                free(old_msg);
3035                                unlock_ref(lock);
3036                                update->backend_data = NULL;
3037                                ret = TRANSACTION_GENERIC_ERROR;
3038                                goto cleanup;
3039                        }
3040                }
3041                if (update->flags & REF_NEEDS_COMMIT) {
3042                        clear_loose_ref_cache(refs);
3043                        if (commit_ref(lock)) {
3044                                strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
3045                                unlock_ref(lock);
3046                                update->backend_data = NULL;
3047                                ret = TRANSACTION_GENERIC_ERROR;
3048                                goto cleanup;
3049                        }
3050                }
3051        }
3052        /* Perform deletes now that updates are safely completed */
3053        for (i = 0; i < transaction->nr; i++) {
3054                struct ref_update *update = transaction->updates[i];
3055                struct ref_lock *lock = update->backend_data;
3056
3057                if (update->flags & REF_DELETING &&
3058                    !(update->flags & REF_LOG_ONLY)) {
3059                        if (!(update->type & REF_ISPACKED) ||
3060                            update->type & REF_ISSYMREF) {
3061                                /* It is a loose reference. */
3062                                strbuf_reset(&sb);
3063                                files_ref_path(refs, &sb, lock->ref_name);
3064                                if (unlink_or_msg(sb.buf, err)) {
3065                                        ret = TRANSACTION_GENERIC_ERROR;
3066                                        goto cleanup;
3067                                }
3068                                update->flags |= REF_DELETED_LOOSE;
3069                        }
3070
3071                        if (!(update->flags & REF_ISPRUNING))
3072                                string_list_append(&refs_to_delete,
3073                                                   lock->ref_name);
3074                }
3075        }
3076
3077        if (repack_without_refs(refs, &refs_to_delete, err)) {
3078                ret = TRANSACTION_GENERIC_ERROR;
3079                goto cleanup;
3080        }
3081
3082        /* Delete the reflogs of any references that were deleted: */
3083        for_each_string_list_item(ref_to_delete, &refs_to_delete) {
3084                strbuf_reset(&sb);
3085                files_reflog_path(refs, &sb, ref_to_delete->string);
3086                if (!unlink_or_warn(sb.buf))
3087                        try_remove_empty_parents(refs, ref_to_delete->string,
3088                                                 REMOVE_EMPTY_PARENTS_REFLOG);
3089        }
3090
3091        clear_loose_ref_cache(refs);
3092
3093cleanup:
3094        files_transaction_cleanup(transaction);
3095
3096        for (i = 0; i < transaction->nr; i++) {
3097                struct ref_update *update = transaction->updates[i];
3098
3099                if (update->flags & REF_DELETED_LOOSE) {
3100                        /*
3101                         * The loose reference was deleted. Delete any
3102                         * empty parent directories. (Note that this
3103                         * can only work because we have already
3104                         * removed the lockfile.)
3105                         */
3106                        try_remove_empty_parents(refs, update->refname,
3107                                                 REMOVE_EMPTY_PARENTS_REF);
3108                }
3109        }
3110
3111        strbuf_release(&sb);
3112        string_list_clear(&refs_to_delete, 0);
3113        return ret;
3114}
3115
3116static int files_transaction_abort(struct ref_store *ref_store,
3117                                   struct ref_transaction *transaction,
3118                                   struct strbuf *err)
3119{
3120        files_transaction_cleanup(transaction);
3121        return 0;
3122}
3123
3124static int ref_present(const char *refname,
3125                       const struct object_id *oid, int flags, void *cb_data)
3126{
3127        struct string_list *affected_refnames = cb_data;
3128
3129        return string_list_has_string(affected_refnames, refname);
3130}
3131
3132static int files_initial_transaction_commit(struct ref_store *ref_store,
3133                                            struct ref_transaction *transaction,
3134                                            struct strbuf *err)
3135{
3136        struct files_ref_store *refs =
3137                files_downcast(ref_store, REF_STORE_WRITE,
3138                               "initial_ref_transaction_commit");
3139        size_t i;
3140        int ret = 0;
3141        struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3142
3143        assert(err);
3144
3145        if (transaction->state != REF_TRANSACTION_OPEN)
3146                die("BUG: commit called for transaction that is not open");
3147
3148        /* Fail if a refname appears more than once in the transaction: */
3149        for (i = 0; i < transaction->nr; i++)
3150                string_list_append(&affected_refnames,
3151                                   transaction->updates[i]->refname);
3152        string_list_sort(&affected_refnames);
3153        if (ref_update_reject_duplicates(&affected_refnames, err)) {
3154                ret = TRANSACTION_GENERIC_ERROR;
3155                goto cleanup;
3156        }
3157
3158        /*
3159         * It's really undefined to call this function in an active
3160         * repository or when there are existing references: we are
3161         * only locking and changing packed-refs, so (1) any
3162         * simultaneous processes might try to change a reference at
3163         * the same time we do, and (2) any existing loose versions of
3164         * the references that we are setting would have precedence
3165         * over our values. But some remote helpers create the remote
3166         * "HEAD" and "master" branches before calling this function,
3167         * so here we really only check that none of the references
3168         * that we are creating already exists.
3169         */
3170        if (refs_for_each_rawref(&refs->base, ref_present,
3171                                 &affected_refnames))
3172                die("BUG: initial ref transaction called with existing refs");
3173
3174        for (i = 0; i < transaction->nr; i++) {
3175                struct ref_update *update = transaction->updates[i];
3176
3177                if ((update->flags & REF_HAVE_OLD) &&
3178                    !is_null_oid(&update->old_oid))
3179                        die("BUG: initial ref transaction with old_sha1 set");
3180                if (refs_verify_refname_available(&refs->base, update->refname,
3181                                                  &affected_refnames, NULL,
3182                                                  err)) {
3183                        ret = TRANSACTION_NAME_CONFLICT;
3184                        goto cleanup;
3185                }
3186        }
3187
3188        if (lock_packed_refs(refs, 0)) {
3189                strbuf_addf(err, "unable to lock packed-refs file: %s",
3190                            strerror(errno));
3191                ret = TRANSACTION_GENERIC_ERROR;
3192                goto cleanup;
3193        }
3194
3195        for (i = 0; i < transaction->nr; i++) {
3196                struct ref_update *update = transaction->updates[i];
3197
3198                if ((update->flags & REF_HAVE_NEW) &&
3199                    !is_null_oid(&update->new_oid))
3200                        add_packed_ref(refs, update->refname,
3201                                       &update->new_oid);
3202        }
3203
3204        if (commit_packed_refs(refs)) {
3205                strbuf_addf(err, "unable to commit packed-refs file: %s",
3206                            strerror(errno));
3207                ret = TRANSACTION_GENERIC_ERROR;
3208                goto cleanup;
3209        }
3210
3211cleanup:
3212        transaction->state = REF_TRANSACTION_CLOSED;
3213        string_list_clear(&affected_refnames, 0);
3214        return ret;
3215}
3216
3217struct expire_reflog_cb {
3218        unsigned int flags;
3219        reflog_expiry_should_prune_fn *should_prune_fn;
3220        void *policy_cb;
3221        FILE *newlog;
3222        struct object_id last_kept_oid;
3223};
3224
3225static int expire_reflog_ent(struct object_id *ooid, struct object_id *noid,
3226                             const char *email, timestamp_t timestamp, int tz,
3227                             const char *message, void *cb_data)
3228{
3229        struct expire_reflog_cb *cb = cb_data;
3230        struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
3231
3232        if (cb->flags & EXPIRE_REFLOGS_REWRITE)
3233                ooid = &cb->last_kept_oid;
3234
3235        if ((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,
3236                                   message, policy_cb)) {
3237                if (!cb->newlog)
3238                        printf("would prune %s", message);
3239                else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3240                        printf("prune %s", message);
3241        } else {
3242                if (cb->newlog) {
3243                        fprintf(cb->newlog, "%s %s %s %"PRItime" %+05d\t%s",
3244                                oid_to_hex(ooid), oid_to_hex(noid),
3245                                email, timestamp, tz, message);
3246                        oidcpy(&cb->last_kept_oid, noid);
3247                }
3248                if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3249                        printf("keep %s", message);
3250        }
3251        return 0;
3252}
3253
3254static int files_reflog_expire(struct ref_store *ref_store,
3255                               const char *refname, const unsigned char *sha1,
3256                               unsigned int flags,
3257                               reflog_expiry_prepare_fn prepare_fn,
3258                               reflog_expiry_should_prune_fn should_prune_fn,
3259                               reflog_expiry_cleanup_fn cleanup_fn,
3260                               void *policy_cb_data)
3261{
3262        struct files_ref_store *refs =
3263                files_downcast(ref_store, REF_STORE_WRITE, "reflog_expire");
3264        static struct lock_file reflog_lock;
3265        struct expire_reflog_cb cb;
3266        struct ref_lock *lock;
3267        struct strbuf log_file_sb = STRBUF_INIT;
3268        char *log_file;
3269        int status = 0;
3270        int type;
3271        struct strbuf err = STRBUF_INIT;
3272        struct object_id oid;
3273
3274        memset(&cb, 0, sizeof(cb));
3275        cb.flags = flags;
3276        cb.policy_cb = policy_cb_data;
3277        cb.should_prune_fn = should_prune_fn;
3278
3279        /*
3280         * The reflog file is locked by holding the lock on the
3281         * reference itself, plus we might need to update the
3282         * reference if --updateref was specified:
3283         */
3284        lock = lock_ref_sha1_basic(refs, refname, sha1,
3285                                   NULL, NULL, REF_NODEREF,
3286                                   &type, &err);
3287        if (!lock) {
3288                error("cannot lock ref '%s': %s", refname, err.buf);
3289                strbuf_release(&err);
3290                return -1;
3291        }
3292        if (!refs_reflog_exists(ref_store, refname)) {
3293                unlock_ref(lock);
3294                return 0;
3295        }
3296
3297        files_reflog_path(refs, &log_file_sb, refname);
3298        log_file = strbuf_detach(&log_file_sb, NULL);
3299        if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3300                /*
3301                 * Even though holding $GIT_DIR/logs/$reflog.lock has
3302                 * no locking implications, we use the lock_file
3303                 * machinery here anyway because it does a lot of the
3304                 * work we need, including cleaning up if the program
3305                 * exits unexpectedly.
3306                 */
3307                if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
3308                        struct strbuf err = STRBUF_INIT;
3309                        unable_to_lock_message(log_file, errno, &err);
3310                        error("%s", err.buf);
3311                        strbuf_release(&err);
3312                        goto failure;
3313                }
3314                cb.newlog = fdopen_lock_file(&reflog_lock, "w");
3315                if (!cb.newlog) {
3316                        error("cannot fdopen %s (%s)",
3317                              get_lock_file_path(&reflog_lock), strerror(errno));
3318                        goto failure;
3319                }
3320        }
3321
3322        hashcpy(oid.hash, sha1);
3323
3324        (*prepare_fn)(refname, &oid, cb.policy_cb);
3325        refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);
3326        (*cleanup_fn)(cb.policy_cb);
3327
3328        if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3329                /*
3330                 * It doesn't make sense to adjust a reference pointed
3331                 * to by a symbolic ref based on expiring entries in
3332                 * the symbolic reference's reflog. Nor can we update
3333                 * a reference if there are no remaining reflog
3334                 * entries.
3335                 */
3336                int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
3337                        !(type & REF_ISSYMREF) &&
3338                        !is_null_oid(&cb.last_kept_oid);
3339
3340                if (close_lock_file(&reflog_lock)) {
3341                        status |= error("couldn't write %s: %s", log_file,
3342                                        strerror(errno));
3343                } else if (update &&
3344                           (write_in_full(get_lock_file_fd(lock->lk),
3345                                oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
3346                            write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||
3347                            close_ref(lock) < 0)) {
3348                        status |= error("couldn't write %s",
3349                                        get_lock_file_path(lock->lk));
3350                        rollback_lock_file(&reflog_lock);
3351                } else if (commit_lock_file(&reflog_lock)) {
3352                        status |= error("unable to write reflog '%s' (%s)",
3353                                        log_file, strerror(errno));
3354                } else if (update && commit_ref(lock)) {
3355                        status |= error("couldn't set %s", lock->ref_name);
3356                }
3357        }
3358        free(log_file);
3359        unlock_ref(lock);
3360        return status;
3361
3362 failure:
3363        rollback_lock_file(&reflog_lock);
3364        free(log_file);
3365        unlock_ref(lock);
3366        return -1;
3367}
3368
3369static int files_init_db(struct ref_store *ref_store, struct strbuf *err)
3370{
3371        struct files_ref_store *refs =
3372                files_downcast(ref_store, REF_STORE_WRITE, "init_db");
3373        struct strbuf sb = STRBUF_INIT;
3374
3375        /*
3376         * Create .git/refs/{heads,tags}
3377         */
3378        files_ref_path(refs, &sb, "refs/heads");
3379        safe_create_dir(sb.buf, 1);
3380
3381        strbuf_reset(&sb);
3382        files_ref_path(refs, &sb, "refs/tags");
3383        safe_create_dir(sb.buf, 1);
3384
3385        strbuf_release(&sb);
3386        return 0;
3387}
3388
3389struct ref_storage_be refs_be_files = {
3390        NULL,
3391        "files",
3392        files_ref_store_create,
3393        files_init_db,
3394        files_transaction_prepare,
3395        files_transaction_finish,
3396        files_transaction_abort,
3397        files_initial_transaction_commit,
3398
3399        files_pack_refs,
3400        files_peel_ref,
3401        files_create_symref,
3402        files_delete_refs,
3403        files_rename_ref,
3404
3405        files_ref_iterator_begin,
3406        files_read_raw_ref,
3407
3408        files_reflog_iterator_begin,
3409        files_for_each_reflog_ent,
3410        files_for_each_reflog_ent_reverse,
3411        files_reflog_exists,
3412        files_create_reflog,
3413        files_delete_reflog,
3414        files_reflog_expire
3415};