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