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