eoie: add End of Index Entry (EOIE) extension
[git/git.git] / read-cache.c
CommitLineData
8bc9a0c7
LT
1/*
2 * GIT - The information manager from hell
3 *
4 * Copyright (C) Linus Torvalds, 2005
5 */
4aab5b46 6#define NO_THE_INDEX_COMPATIBILITY_MACROS
e83c5163 7#include "cache.h"
b2141fc1 8#include "config.h"
cffbfad5
EN
9#include "diff.h"
10#include "diffcore.h"
f6ecc62d 11#include "tempfile.h"
697cc8ef 12#include "lockfile.h"
bad68ec9 13#include "cache-tree.h"
f35a6d3b 14#include "refs.h"
d616813d 15#include "dir.h"
cbd53a21 16#include "object-store.h"
041aee31
JH
17#include "tree.h"
18#include "commit.h"
39425819 19#include "blob.h"
cfc5789a 20#include "resolve-undo.h"
6c9cd161
JH
21#include "strbuf.h"
22#include "varint.h"
5fc2fc8f 23#include "split-index.h"
a42643aa 24#include "utf8.h"
883e248b 25#include "fsmonitor.h"
bad68ec9 26
b60e188c
TG
27/* Mask for the name length in ce_flags in the on-disk index */
28
29#define CE_NAMEMASK (0x0fff)
30
bad68ec9
JH
31/* Index extensions.
32 *
33 * The first letter should be 'A'..'Z' for extensions that are not
34 * necessary for a correct operation (i.e. optimization data).
35 * When new extensions are added that _needs_ to be understood in
36 * order to correctly interpret the index file, pick character that
37 * is outside the range, to cause the reader to abort.
38 */
39
40#define CACHE_EXT(s) ( (s[0]<<24)|(s[1]<<16)|(s[2]<<8)|(s[3]) )
41#define CACHE_EXT_TREE 0x54524545 /* "TREE" */
b659b49b 42#define CACHE_EXT_RESOLVE_UNDO 0x52455543 /* "REUC" */
5fc2fc8f 43#define CACHE_EXT_LINK 0x6c696e6b /* "link" */
83c094ad 44#define CACHE_EXT_UNTRACKED 0x554E5452 /* "UNTR" */
883e248b 45#define CACHE_EXT_FSMONITOR 0x46534D4E /* "FSMN" */
3b1d9e04 46#define CACHE_EXT_ENDOFINDEXENTRIES 0x454F4945 /* "EOIE" */
5fc2fc8f
NTND
47
48/* changes that can be kept in $GIT_DIR/index (basically all extensions) */
e0cf0d7d 49#define EXTMASK (RESOLVE_UNDO_CHANGED | CACHE_TREE_CHANGED | \
c18b80a0 50 CE_ENTRY_ADDED | CE_ENTRY_REMOVED | CE_ENTRY_CHANGED | \
883e248b 51 SPLIT_INDEX_ORDERED | UNTRACKED_CHANGED | FSMONITOR_CHANGED)
e83c5163 52
8e72d675
JM
53
54/*
55 * This is an estimate of the pathname length in the index. We use
56 * this for V4 index files to guess the un-deltafied size of the index
57 * in memory because of pathname deltafication. This is not required
58 * for V2/V3 index formats because their pathnames are not compressed.
59 * If the initial amount of memory set aside is not sufficient, the
60 * mem pool will allocate extra memory.
61 */
62#define CACHE_ENTRY_PATH_LENGTH 80
63
64static inline struct cache_entry *mem_pool__ce_alloc(struct mem_pool *mem_pool, size_t len)
65{
66 struct cache_entry *ce;
67 ce = mem_pool_alloc(mem_pool, cache_entry_size(len));
68 ce->mem_pool_allocated = 1;
69 return ce;
70}
71
72static inline struct cache_entry *mem_pool__ce_calloc(struct mem_pool *mem_pool, size_t len)
73{
74 struct cache_entry * ce;
75 ce = mem_pool_calloc(mem_pool, 1, cache_entry_size(len));
76 ce->mem_pool_allocated = 1;
77 return ce;
78}
79
80static struct mem_pool *find_mem_pool(struct index_state *istate)
81{
82 struct mem_pool **pool_ptr;
83
84 if (istate->split_index && istate->split_index->base)
85 pool_ptr = &istate->split_index->base->ce_mem_pool;
86 else
87 pool_ptr = &istate->ce_mem_pool;
88
89 if (!*pool_ptr)
90 mem_pool_init(pool_ptr, 0);
91
92 return *pool_ptr;
93}
94
228e94f9 95struct index_state the_index;
626f35c8 96static const char *alternate_index_output;
8fd2cb40 97
9cb76b8c
JH
98static void set_index_entry(struct index_state *istate, int nr, struct cache_entry *ce)
99{
100 istate->cache[nr] = ce;
96872bc2 101 add_name_hash(istate, ce);
9cb76b8c
JH
102}
103
cf558704
LT
104static void replace_index_entry(struct index_state *istate, int nr, struct cache_entry *ce)
105{
106 struct cache_entry *old = istate->cache[nr];
107
078a58e8 108 replace_index_entry_in_base(istate, old, ce);
2092678c 109 remove_name_hash(istate, old);
a849735b 110 discard_cache_entry(old);
0e267b7a 111 ce->ce_flags &= ~CE_HASHED;
a22c6371 112 set_index_entry(istate, nr, ce);
078a58e8 113 ce->ce_flags |= CE_UPDATE_IN_BASE;
883e248b 114 mark_fsmonitor_invalid(istate, ce);
e636a7b4 115 istate->cache_changed |= CE_ENTRY_CHANGED;
cf558704
LT
116}
117
81dc2307
PB
118void rename_index_entry_at(struct index_state *istate, int nr, const char *new_name)
119{
285c2e25 120 struct cache_entry *old_entry = istate->cache[nr], *new_entry;
81dc2307
PB
121 int namelen = strlen(new_name);
122
a849735b 123 new_entry = make_empty_cache_entry(istate, namelen);
285c2e25
BW
124 copy_cache_entry(new_entry, old_entry);
125 new_entry->ce_flags &= ~CE_HASHED;
126 new_entry->ce_namelen = namelen;
127 new_entry->index = 0;
128 memcpy(new_entry->name, new_name, namelen + 1);
81dc2307 129
285c2e25
BW
130 cache_tree_invalidate_path(istate, old_entry->name);
131 untracked_cache_remove_from_index(istate, old_entry->name);
81dc2307 132 remove_index_entry_at(istate, nr);
285c2e25 133 add_index_entry(istate, new_entry, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
81dc2307
PB
134}
135
c21d39d7
MH
136void fill_stat_data(struct stat_data *sd, struct stat *st)
137{
138 sd->sd_ctime.sec = (unsigned int)st->st_ctime;
139 sd->sd_mtime.sec = (unsigned int)st->st_mtime;
140 sd->sd_ctime.nsec = ST_CTIME_NSEC(*st);
141 sd->sd_mtime.nsec = ST_MTIME_NSEC(*st);
142 sd->sd_dev = st->st_dev;
143 sd->sd_ino = st->st_ino;
144 sd->sd_uid = st->st_uid;
145 sd->sd_gid = st->st_gid;
146 sd->sd_size = st->st_size;
147}
148
149int match_stat_data(const struct stat_data *sd, struct stat *st)
150{
151 int changed = 0;
152
153 if (sd->sd_mtime.sec != (unsigned int)st->st_mtime)
154 changed |= MTIME_CHANGED;
155 if (trust_ctime && check_stat &&
156 sd->sd_ctime.sec != (unsigned int)st->st_ctime)
157 changed |= CTIME_CHANGED;
158
159#ifdef USE_NSEC
160 if (check_stat && sd->sd_mtime.nsec != ST_MTIME_NSEC(*st))
161 changed |= MTIME_CHANGED;
162 if (trust_ctime && check_stat &&
163 sd->sd_ctime.nsec != ST_CTIME_NSEC(*st))
164 changed |= CTIME_CHANGED;
165#endif
166
167 if (check_stat) {
168 if (sd->sd_uid != (unsigned int) st->st_uid ||
169 sd->sd_gid != (unsigned int) st->st_gid)
170 changed |= OWNER_CHANGED;
171 if (sd->sd_ino != (unsigned int) st->st_ino)
172 changed |= INODE_CHANGED;
173 }
174
175#ifdef USE_STDEV
176 /*
177 * st_dev breaks on network filesystems where different
178 * clients will have different views of what "device"
179 * the filesystem is on
180 */
181 if (check_stat && sd->sd_dev != (unsigned int) st->st_dev)
182 changed |= INODE_CHANGED;
183#endif
184
185 if (sd->sd_size != (unsigned int) st->st_size)
186 changed |= DATA_CHANGED;
187
188 return changed;
189}
190
415e96c8
JH
191/*
192 * This only updates the "non-critical" parts of the directory
193 * cache, ie the parts that aren't tracked by GIT, and only used
194 * to validate the cache.
195 */
196void fill_stat_cache_info(struct cache_entry *ce, struct stat *st)
197{
c21d39d7 198 fill_stat_data(&ce->ce_stat_data, st);
5f73076c
JH
199
200 if (assume_unchanged)
7a51ed66 201 ce->ce_flags |= CE_VALID;
eadb5831 202
883e248b 203 if (S_ISREG(st->st_mode)) {
eadb5831 204 ce_mark_uptodate(ce);
883e248b
BP
205 mark_fsmonitor_valid(ce);
206 }
415e96c8
JH
207}
208
21a6b9fa 209static int ce_compare_data(const struct cache_entry *ce, struct stat *st)
29e4d363
JH
210{
211 int match = -1;
1b8ac5ea 212 int fd = git_open_cloexec(ce->name, O_RDONLY);
29e4d363
JH
213
214 if (fd >= 0) {
bebfecb9 215 struct object_id oid;
e3506559 216 if (!index_fd(&oid, fd, st, OBJ_BLOB, ce->name, 0))
6a29d7b7 217 match = !oideq(&oid, &ce->oid);
7f8508e8 218 /* index_fd() closed the file descriptor already */
29e4d363
JH
219 }
220 return match;
221}
222
21a6b9fa 223static int ce_compare_link(const struct cache_entry *ce, size_t expected_size)
29e4d363
JH
224{
225 int match = -1;
29e4d363
JH
226 void *buffer;
227 unsigned long size;
21666f1a 228 enum object_type type;
a60272b3 229 struct strbuf sb = STRBUF_INIT;
29e4d363 230
a60272b3 231 if (strbuf_readlink(&sb, ce->name, expected_size))
29e4d363 232 return -1;
a60272b3 233
b4f5aca4 234 buffer = read_object_file(&ce->oid, &type, &size);
a60272b3
LT
235 if (buffer) {
236 if (size == sb.len)
237 match = memcmp(buffer, sb.buf, size);
238 free(buffer);
29e4d363 239 }
a60272b3 240 strbuf_release(&sb);
29e4d363
JH
241 return match;
242}
243
21a6b9fa 244static int ce_compare_gitlink(const struct cache_entry *ce)
f35a6d3b 245{
1053fe82 246 struct object_id oid;
f35a6d3b
LT
247
248 /*
249 * We don't actually require that the .git directory
302b9282 250 * under GITLINK directory be a valid git directory. It
f35a6d3b
LT
251 * might even be missing (in case nobody populated that
252 * sub-project).
253 *
254 * If so, we consider it always to match.
255 */
a98e6101 256 if (resolve_gitlink_ref(ce->name, "HEAD", &oid) < 0)
f35a6d3b 257 return 0;
6a29d7b7 258 return !oideq(&oid, &ce->oid);
f35a6d3b
LT
259}
260
21a6b9fa 261static int ce_modified_check_fs(const struct cache_entry *ce, struct stat *st)
29e4d363
JH
262{
263 switch (st->st_mode & S_IFMT) {
264 case S_IFREG:
265 if (ce_compare_data(ce, st))
266 return DATA_CHANGED;
267 break;
268 case S_IFLNK:
dc49cd76 269 if (ce_compare_link(ce, xsize_t(st->st_size)))
29e4d363
JH
270 return DATA_CHANGED;
271 break;
a8ee75bc 272 case S_IFDIR:
7a51ed66 273 if (S_ISGITLINK(ce->ce_mode))
c70115b4 274 return ce_compare_gitlink(ce) ? DATA_CHANGED : 0;
1cf01a34 275 /* else fallthrough */
29e4d363
JH
276 default:
277 return TYPE_CHANGED;
278 }
279 return 0;
280}
281
21a6b9fa 282static int ce_match_stat_basic(const struct cache_entry *ce, struct stat *st)
734aab75
LT
283{
284 unsigned int changed = 0;
285
7a51ed66
LT
286 if (ce->ce_flags & CE_REMOVE)
287 return MODE_CHANGED | DATA_CHANGED | TYPE_CHANGED;
288
289 switch (ce->ce_mode & S_IFMT) {
8ae0a8c5
KS
290 case S_IFREG:
291 changed |= !S_ISREG(st->st_mode) ? TYPE_CHANGED : 0;
3e09cdfd
JH
292 /* We consider only the owner x bit to be relevant for
293 * "mode changes"
294 */
295 if (trust_executable_bit &&
7a51ed66 296 (0100 & (ce->ce_mode ^ st->st_mode)))
ffbe1add 297 changed |= MODE_CHANGED;
8ae0a8c5
KS
298 break;
299 case S_IFLNK:
78a8d641
JS
300 if (!S_ISLNK(st->st_mode) &&
301 (has_symlinks || !S_ISREG(st->st_mode)))
302 changed |= TYPE_CHANGED;
8ae0a8c5 303 break;
302b9282 304 case S_IFGITLINK:
c70115b4 305 /* We ignore most of the st_xxx fields for gitlinks */
f35a6d3b
LT
306 if (!S_ISDIR(st->st_mode))
307 changed |= TYPE_CHANGED;
308 else if (ce_compare_gitlink(ce))
309 changed |= DATA_CHANGED;
a8ee75bc 310 return changed;
8ae0a8c5 311 default:
7a51ed66 312 die("internal error: ce_mode is %o", ce->ce_mode);
8ae0a8c5 313 }
2cb45e95 314
c21d39d7 315 changed |= match_stat_data(&ce->ce_stat_data, st);
b0391890 316
f49c2c22 317 /* Racily smudged entry? */
c21d39d7 318 if (!ce->ce_stat_data.sd_size) {
99d1a986 319 if (!is_empty_blob_sha1(ce->oid.hash))
f49c2c22
LT
320 changed |= DATA_CHANGED;
321 }
322
407c8eb0
JH
323 return changed;
324}
325
2bb4cda1
NTND
326static int is_racy_stat(const struct index_state *istate,
327 const struct stat_data *sd)
6d91da6d 328{
2bb4cda1 329 return (istate->timestamp.sec &&
fba2f38a
KB
330#ifdef USE_NSEC
331 /* nanosecond timestamped files can also be racy! */
2bb4cda1
NTND
332 (istate->timestamp.sec < sd->sd_mtime.sec ||
333 (istate->timestamp.sec == sd->sd_mtime.sec &&
334 istate->timestamp.nsec <= sd->sd_mtime.nsec))
fba2f38a 335#else
2bb4cda1 336 istate->timestamp.sec <= sd->sd_mtime.sec
fba2f38a 337#endif
2bb4cda1
NTND
338 );
339}
340
341static int is_racy_timestamp(const struct index_state *istate,
342 const struct cache_entry *ce)
343{
344 return (!S_ISGITLINK(ce->ce_mode) &&
345 is_racy_stat(istate, &ce->ce_stat_data));
6d91da6d
JH
346}
347
ed4efab1
NTND
348int match_stat_data_racy(const struct index_state *istate,
349 const struct stat_data *sd, struct stat *st)
350{
351 if (is_racy_stat(istate, sd))
352 return MTIME_CHANGED;
353 return match_stat_data(sd, st);
6d91da6d
JH
354}
355
883e248b 356int ie_match_stat(struct index_state *istate,
21a6b9fa 357 const struct cache_entry *ce, struct stat *st,
4bd5b7da 358 unsigned int options)
407c8eb0 359{
5f73076c 360 unsigned int changed;
4bd5b7da 361 int ignore_valid = options & CE_MATCH_IGNORE_VALID;
56cac48c 362 int ignore_skip_worktree = options & CE_MATCH_IGNORE_SKIP_WORKTREE;
4bd5b7da 363 int assume_racy_is_modified = options & CE_MATCH_RACY_IS_DIRTY;
883e248b 364 int ignore_fsmonitor = options & CE_MATCH_IGNORE_FSMONITOR;
5f73076c 365
883e248b
BP
366 if (!ignore_fsmonitor)
367 refresh_fsmonitor(istate);
5f73076c
JH
368 /*
369 * If it's marked as always valid in the index, it's
370 * valid whatever the checked-out copy says.
56cac48c
NTND
371 *
372 * skip-worktree has the same effect with higher precedence
5f73076c 373 */
56cac48c
NTND
374 if (!ignore_skip_worktree && ce_skip_worktree(ce))
375 return 0;
7a51ed66 376 if (!ignore_valid && (ce->ce_flags & CE_VALID))
5f73076c 377 return 0;
883e248b
BP
378 if (!ignore_fsmonitor && (ce->ce_flags & CE_FSMONITOR_VALID))
379 return 0;
5f73076c 380
331fcb59
JH
381 /*
382 * Intent-to-add entries have not been added, so the index entry
383 * by definition never matches what is in the work tree until it
384 * actually gets added.
385 */
895ff3b2 386 if (ce_intent_to_add(ce))
331fcb59
JH
387 return DATA_CHANGED | TYPE_CHANGED | MODE_CHANGED;
388
5f73076c 389 changed = ce_match_stat_basic(ce, st);
407c8eb0 390
29e4d363
JH
391 /*
392 * Within 1 second of this sequence:
393 * echo xyzzy >file && git-update-index --add file
394 * running this command:
395 * echo frotz >file
396 * would give a falsely clean cache entry. The mtime and
397 * length match the cache, and other stat fields do not change.
398 *
399 * We could detect this at update-index time (the cache entry
400 * being registered/updated records the same time as "now")
401 * and delay the return from git-update-index, but that would
402 * effectively mean we can make at most one commit per second,
403 * which is not acceptable. Instead, we check cache entries
404 * whose mtime are the same as the index file timestamp more
5f73076c 405 * carefully than others.
29e4d363 406 */
6d91da6d 407 if (!changed && is_racy_timestamp(istate, ce)) {
42f77406
JH
408 if (assume_racy_is_modified)
409 changed |= DATA_CHANGED;
410 else
411 changed |= ce_modified_check_fs(ce, st);
412 }
b0391890 413
29e4d363 414 return changed;
b0391890
JH
415}
416
883e248b 417int ie_modified(struct index_state *istate,
21a6b9fa
RS
418 const struct cache_entry *ce,
419 struct stat *st, unsigned int options)
b0391890 420{
29e4d363 421 int changed, changed_fs;
4bd5b7da
JH
422
423 changed = ie_match_stat(istate, ce, st, options);
b0391890
JH
424 if (!changed)
425 return 0;
b0391890
JH
426 /*
427 * If the mode or type has changed, there's no point in trying
428 * to refresh the entry - it's not going to match
429 */
430 if (changed & (MODE_CHANGED | TYPE_CHANGED))
431 return changed;
432
c70115b4
JH
433 /*
434 * Immediately after read-tree or update-index --cacheinfo,
435 * the length field is zero, as we have never even read the
436 * lstat(2) information once, and we cannot trust DATA_CHANGED
437 * returned by ie_match_stat() which in turn was returned by
438 * ce_match_stat_basic() to signal that the filesize of the
439 * blob changed. We have to actually go to the filesystem to
440 * see if the contents match, and if so, should answer "unchanged".
441 *
442 * The logic does not apply to gitlinks, as ce_match_stat_basic()
443 * already has checked the actual HEAD from the filesystem in the
444 * subproject. If ie_match_stat() already said it is different,
445 * then we know it is.
b0391890 446 */
c70115b4 447 if ((changed & DATA_CHANGED) &&
c21d39d7 448 (S_ISGITLINK(ce->ce_mode) || ce->ce_stat_data.sd_size != 0))
b0391890
JH
449 return changed;
450
29e4d363
JH
451 changed_fs = ce_modified_check_fs(ce, st);
452 if (changed_fs)
453 return changed | changed_fs;
b0391890
JH
454 return 0;
455}
456
958ba6c9
LT
457int base_name_compare(const char *name1, int len1, int mode1,
458 const char *name2, int len2, int mode2)
459{
460 unsigned char c1, c2;
461 int len = len1 < len2 ? len1 : len2;
462 int cmp;
463
464 cmp = memcmp(name1, name2, len);
465 if (cmp)
466 return cmp;
467 c1 = name1[len];
468 c2 = name2[len];
1833a925 469 if (!c1 && S_ISDIR(mode1))
958ba6c9 470 c1 = '/';
1833a925 471 if (!c2 && S_ISDIR(mode2))
958ba6c9
LT
472 c2 = '/';
473 return (c1 < c2) ? -1 : (c1 > c2) ? 1 : 0;
474}
475
0ab9e1e8
LT
476/*
477 * df_name_compare() is identical to base_name_compare(), except it
478 * compares conflicting directory/file entries as equal. Note that
479 * while a directory name compares as equal to a regular file, they
480 * then individually compare _differently_ to a filename that has
481 * a dot after the basename (because '\0' < '.' < '/').
482 *
483 * This is used by routines that want to traverse the git namespace
484 * but then handle conflicting entries together when possible.
485 */
486int df_name_compare(const char *name1, int len1, int mode1,
487 const char *name2, int len2, int mode2)
488{
489 int len = len1 < len2 ? len1 : len2, cmp;
490 unsigned char c1, c2;
491
492 cmp = memcmp(name1, name2, len);
493 if (cmp)
494 return cmp;
495 /* Directories and files compare equal (same length, same name) */
496 if (len1 == len2)
497 return 0;
498 c1 = name1[len];
499 if (!c1 && S_ISDIR(mode1))
500 c1 = '/';
501 c2 = name2[len];
502 if (!c2 && S_ISDIR(mode2))
503 c2 = '/';
504 if (c1 == '/' && !c2)
505 return 0;
506 if (c2 == '/' && !c1)
507 return 0;
508 return c1 - c2;
509}
510
ccdd4a0f 511int name_compare(const char *name1, size_t len1, const char *name2, size_t len2)
eb38c22f 512{
ccdd4a0f
JM
513 size_t min_len = (len1 < len2) ? len1 : len2;
514 int cmp = memcmp(name1, name2, min_len);
eb38c22f
LT
515 if (cmp)
516 return cmp;
517 if (len1 < len2)
518 return -1;
519 if (len1 > len2)
520 return 1;
ccdd4a0f
JM
521 return 0;
522}
523
524int cache_name_stage_compare(const char *name1, int len1, int stage1, const char *name2, int len2, int stage2)
525{
526 int cmp;
527
528 cmp = name_compare(name1, len1, name2, len2);
529 if (cmp)
530 return cmp;
5f73076c 531
b60e188c 532 if (stage1 < stage2)
95fd5bf8 533 return -1;
b60e188c 534 if (stage1 > stage2)
95fd5bf8 535 return 1;
eb38c22f
LT
536 return 0;
537}
538
357e9c69 539static int index_name_stage_pos(const struct index_state *istate, const char *name, int namelen, int stage)
eb38c22f
LT
540{
541 int first, last;
542
543 first = 0;
4aab5b46 544 last = istate->cache_nr;
eb38c22f
LT
545 while (last > first) {
546 int next = (last + first) >> 1;
4aab5b46 547 struct cache_entry *ce = istate->cache[next];
b60e188c 548 int cmp = cache_name_stage_compare(name, namelen, stage, ce->name, ce_namelen(ce), ce_stage(ce));
eb38c22f 549 if (!cmp)
76e7f4ec 550 return next;
eb38c22f
LT
551 if (cmp < 0) {
552 last = next;
553 continue;
554 }
555 first = next+1;
556 }
76e7f4ec 557 return -first-1;
eb38c22f
LT
558}
559
b60e188c
TG
560int index_name_pos(const struct index_state *istate, const char *name, int namelen)
561{
562 return index_name_stage_pos(istate, name, namelen, 0);
563}
564
4aab5b46 565int remove_index_entry_at(struct index_state *istate, int pos)
7b937ca3 566{
cf558704
LT
567 struct cache_entry *ce = istate->cache[pos];
568
cfc5789a 569 record_resolve_undo(istate, ce);
2092678c 570 remove_name_hash(istate, ce);
045113a5 571 save_or_free_index_entry(istate, ce);
e636a7b4 572 istate->cache_changed |= CE_ENTRY_REMOVED;
4aab5b46
JH
573 istate->cache_nr--;
574 if (pos >= istate->cache_nr)
7b937ca3 575 return 0;
f331ab9d
RS
576 MOVE_ARRAY(istate->cache + pos, istate->cache + pos + 1,
577 istate->cache_nr - pos);
7b937ca3
LT
578 return 1;
579}
580
36419c8e 581/*
98e023de 582 * Remove all cache entries marked for removal, that is where
36419c8e
KB
583 * CE_REMOVE is set in ce_flags. This is much more effective than
584 * calling remove_index_entry_at() for each entry to be removed.
585 */
586void remove_marked_cache_entries(struct index_state *istate)
587{
588 struct cache_entry **ce_array = istate->cache;
589 unsigned int i, j;
590
591 for (i = j = 0; i < istate->cache_nr; i++) {
5699d17e 592 if (ce_array[i]->ce_flags & CE_REMOVE) {
2092678c 593 remove_name_hash(istate, ce_array[i]);
045113a5 594 save_or_free_index_entry(istate, ce_array[i]);
5699d17e 595 }
36419c8e
KB
596 else
597 ce_array[j++] = ce_array[i];
598 }
ad837d9e
NTND
599 if (j == istate->cache_nr)
600 return;
e636a7b4 601 istate->cache_changed |= CE_ENTRY_REMOVED;
36419c8e
KB
602 istate->cache_nr = j;
603}
604
4aab5b46 605int remove_file_from_index(struct index_state *istate, const char *path)
197ee8c9 606{
4aab5b46 607 int pos = index_name_pos(istate, path, strlen(path));
c4e3cca1
JH
608 if (pos < 0)
609 pos = -pos-1;
a5400efe 610 cache_tree_invalidate_path(istate, path);
e931371a 611 untracked_cache_remove_from_index(istate, path);
4aab5b46
JH
612 while (pos < istate->cache_nr && !strcmp(istate->cache[pos]->name, path))
613 remove_index_entry_at(istate, pos);
197ee8c9
LT
614 return 0;
615}
616
20314271
JS
617static int compare_name(struct cache_entry *ce, const char *path, int namelen)
618{
619 return namelen != ce_namelen(ce) || memcmp(path, ce->name, namelen);
620}
621
622static int index_name_pos_also_unmerged(struct index_state *istate,
623 const char *path, int namelen)
624{
625 int pos = index_name_pos(istate, path, namelen);
626 struct cache_entry *ce;
627
628 if (pos >= 0)
629 return pos;
630
631 /* maybe unmerged? */
632 pos = -1 - pos;
633 if (pos >= istate->cache_nr ||
634 compare_name((ce = istate->cache[pos]), path, namelen))
635 return -1;
636
637 /* order of preference: stage 2, 1, 3 */
638 if (ce_stage(ce) == 1 && pos + 1 < istate->cache_nr &&
639 ce_stage((ce = istate->cache[pos + 1])) == 2 &&
640 !compare_name(ce, path, namelen))
641 pos++;
642 return pos;
643}
644
1102952b
LT
645static int different_name(struct cache_entry *ce, struct cache_entry *alias)
646{
647 int len = ce_namelen(ce);
648 return ce_namelen(alias) != len || memcmp(ce->name, alias->name, len);
649}
650
651/*
652 * If we add a filename that aliases in the cache, we will use the
653 * name that we already have - but we don't want to update the same
654 * alias twice, because that implies that there were actually two
655 * different files with aliasing names!
656 *
657 * So we use the CE_ADDED flag to verify that the alias was an old
658 * one before we accept it as
659 */
045113a5
NTND
660static struct cache_entry *create_alias_ce(struct index_state *istate,
661 struct cache_entry *ce,
662 struct cache_entry *alias)
1102952b
LT
663{
664 int len;
285c2e25 665 struct cache_entry *new_entry;
1102952b
LT
666
667 if (alias->ce_flags & CE_ADDED)
668 die("Will not add file alias '%s' ('%s' already exists in index)", ce->name, alias->name);
669
670 /* Ok, create the new entry using the name of the existing alias */
671 len = ce_namelen(alias);
a849735b 672 new_entry = make_empty_cache_entry(istate, len);
285c2e25
BW
673 memcpy(new_entry->name, alias->name, len);
674 copy_cache_entry(new_entry, ce);
045113a5 675 save_or_free_index_entry(istate, ce);
285c2e25 676 return new_entry;
1102952b
LT
677}
678
b4b313f9 679void set_object_name_for_intent_to_add_entry(struct cache_entry *ce)
39425819 680{
a09c985e
PO
681 struct object_id oid;
682 if (write_object_file("", 0, blob_type, &oid))
39425819 683 die("cannot create an empty blob in the object database");
a09c985e 684 oidcpy(&ce->oid, &oid);
39425819
JH
685}
686
610d55af 687int add_to_index(struct index_state *istate, const char *path, struct stat *st, int flags)
11be42a4 688{
a849735b 689 int namelen, was_same;
d177cab0 690 mode_t st_mode = st->st_mode;
9472935d 691 struct cache_entry *ce, *alias = NULL;
56cac48c 692 unsigned ce_option = CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE|CE_MATCH_RACY_IS_DIRTY;
38ed1d89
JH
693 int verbose = flags & (ADD_CACHE_VERBOSE | ADD_CACHE_PRETEND);
694 int pretend = flags & ADD_CACHE_PRETEND;
39425819
JH
695 int intent_only = flags & ADD_CACHE_INTENT;
696 int add_option = (ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE|
697 (intent_only ? ADD_CACHE_NEW_ONLY : 0));
9472935d
TB
698 int newflags = HASH_WRITE_OBJECT;
699
700 if (flags & HASH_RENORMALIZE)
701 newflags |= HASH_RENORMALIZE;
11be42a4 702
d177cab0 703 if (!S_ISREG(st_mode) && !S_ISLNK(st_mode) && !S_ISDIR(st_mode))
960b8ad1 704 return error("%s: can only add regular files, symbolic links or git-directories", path);
11be42a4
JS
705
706 namelen = strlen(path);
d177cab0 707 if (S_ISDIR(st_mode)) {
09595258
LT
708 while (namelen && path[namelen-1] == '/')
709 namelen--;
710 }
a849735b 711 ce = make_empty_cache_entry(istate, namelen);
11be42a4 712 memcpy(ce->name, path, namelen);
b60e188c 713 ce->ce_namelen = namelen;
39425819
JH
714 if (!intent_only)
715 fill_stat_cache_info(ce, st);
388b2acd
JH
716 else
717 ce->ce_flags |= CE_INTENT_TO_ADD;
11be42a4 718
610d55af
TG
719
720 if (trust_executable_bit && has_symlinks) {
d177cab0 721 ce->ce_mode = create_ce_mode(st_mode);
610d55af 722 } else {
78a8d641
JS
723 /* If there is an existing entry, pick the mode bits and type
724 * from it, otherwise assume unexecutable regular file.
11be42a4 725 */
185c975f 726 struct cache_entry *ent;
20314271 727 int pos = index_name_pos_also_unmerged(istate, path, namelen);
185c975f 728
4aab5b46 729 ent = (0 <= pos) ? istate->cache[pos] : NULL;
d177cab0 730 ce->ce_mode = ce_mode_from_stat(ent, st_mode);
11be42a4
JS
731 }
732
dc1ae704
JJ
733 /* When core.ignorecase=true, determine if a directory of the same name but differing
734 * case already exists within the Git repository. If it does, ensure the directory
735 * case of the file being added to the repository matches (is folded into) the existing
736 * entry's directory case.
737 */
738 if (ignore_case) {
41284eb0 739 adjust_dirname_case(istate, ce->name);
dc1ae704 740 }
9472935d
TB
741 if (!(flags & HASH_RENORMALIZE)) {
742 alias = index_file_exists(istate, ce->name,
743 ce_namelen(ce), ignore_case);
744 if (alias &&
745 !ce_stage(alias) &&
746 !ie_match_stat(istate, alias, st, ce_option)) {
747 /* Nothing changed, really */
748 if (!S_ISGITLINK(alias->ce_mode))
749 ce_mark_uptodate(alias);
750 alias->ce_flags |= CE_ADDED;
dc1ae704 751
a849735b 752 discard_cache_entry(ce);
9472935d
TB
753 return 0;
754 }
0781b8a9 755 }
39425819 756 if (!intent_only) {
9472935d 757 if (index_path(&ce->oid, path, st, newflags)) {
a849735b 758 discard_cache_entry(ce);
39425819 759 return error("unable to index file %s", path);
2d9426b0 760 }
39425819 761 } else
b4b313f9 762 set_object_name_for_intent_to_add_entry(ce);
39425819 763
1102952b 764 if (ignore_case && alias && different_name(ce, alias))
045113a5 765 ce = create_alias_ce(istate, ce, alias);
1102952b 766 ce->ce_flags |= CE_ADDED;
38ed1d89 767
3bf0dd1f 768 /* It was suspected to be racily clean, but it turns out to be Ok */
38ed1d89
JH
769 was_same = (alias &&
770 !ce_stage(alias) &&
4a7e27e9 771 oideq(&alias->oid, &ce->oid) &&
38ed1d89
JH
772 ce->ce_mode == alias->ce_mode);
773
774 if (pretend)
a849735b 775 discard_cache_entry(ce);
067178ed 776 else if (add_index_entry(istate, ce, add_option)) {
a849735b 777 discard_cache_entry(ce);
067178ed
JH
778 return error("unable to add %s to index", path);
779 }
38ed1d89 780 if (verbose && !was_same)
11be42a4 781 printf("add '%s'\n", path);
11be42a4
JS
782 return 0;
783}
784
610d55af 785int add_file_to_index(struct index_state *istate, const char *path, int flags)
d177cab0
LT
786{
787 struct stat st;
788 if (lstat(path, &st))
d824cbba 789 die_errno("unable to stat '%s'", path);
610d55af 790 return add_to_index(istate, path, &st, flags);
d177cab0
LT
791}
792
a849735b
JM
793struct cache_entry *make_empty_cache_entry(struct index_state *istate, size_t len)
794{
8e72d675 795 return mem_pool__ce_calloc(find_mem_pool(istate), len);
a849735b
JM
796}
797
798struct cache_entry *make_empty_transient_cache_entry(size_t len)
799{
800 return xcalloc(1, cache_entry_size(len));
801}
802
803struct cache_entry *make_cache_entry(struct index_state *istate,
804 unsigned int mode,
825ed4d9
JM
805 const struct object_id *oid,
806 const char *path,
807 int stage,
808 unsigned int refresh_options)
6640f881 809{
bc1c2caa 810 struct cache_entry *ce, *ret;
a849735b 811 int len;
6640f881 812
10ecfa76 813 if (!verify_path(path, mode)) {
7e7abea9 814 error("Invalid path '%s'", path);
6640f881 815 return NULL;
7e7abea9 816 }
6640f881
CR
817
818 len = strlen(path);
a849735b 819 ce = make_empty_cache_entry(istate, len);
6640f881 820
825ed4d9 821 oidcpy(&ce->oid, oid);
6640f881 822 memcpy(ce->name, path, len);
b60e188c
TG
823 ce->ce_flags = create_ce_flags(stage);
824 ce->ce_namelen = len;
6640f881
CR
825 ce->ce_mode = create_ce_mode(mode);
826
768d7965 827 ret = refresh_cache_entry(&the_index, ce, refresh_options);
915e44c6 828 if (ret != ce)
a849735b 829 discard_cache_entry(ce);
915e44c6 830 return ret;
6640f881
CR
831}
832
a849735b
JM
833struct cache_entry *make_transient_cache_entry(unsigned int mode, const struct object_id *oid,
834 const char *path, int stage)
835{
836 struct cache_entry *ce;
837 int len;
838
839 if (!verify_path(path, mode)) {
840 error("Invalid path '%s'", path);
841 return NULL;
842 }
843
844 len = strlen(path);
845 ce = make_empty_transient_cache_entry(len);
846
847 oidcpy(&ce->oid, oid);
848 memcpy(ce->name, path, len);
849 ce->ce_flags = create_ce_flags(stage);
850 ce->ce_namelen = len;
851 ce->ce_mode = create_ce_mode(mode);
852
853 return ce;
854}
855
d9d70966
TG
856/*
857 * Chmod an index entry with either +x or -x.
858 *
859 * Returns -1 if the chmod for the particular cache entry failed (if it's
860 * not a regular file), -2 if an invalid flip argument is passed in, 0
861 * otherwise.
862 */
863int chmod_index_entry(struct index_state *istate, struct cache_entry *ce,
864 char flip)
865{
866 if (!S_ISREG(ce->ce_mode))
867 return -1;
868 switch (flip) {
869 case '+':
870 ce->ce_mode |= 0111;
871 break;
872 case '-':
873 ce->ce_mode &= ~0111;
874 break;
875 default:
876 return -2;
877 }
878 cache_tree_invalidate_path(istate, ce->name);
879 ce->ce_flags |= CE_UPDATE_IN_BASE;
883e248b 880 mark_fsmonitor_invalid(istate, ce);
d9d70966
TG
881 istate->cache_changed |= CE_ENTRY_CHANGED;
882
883 return 0;
884}
885
9c5e6c80 886int ce_same_name(const struct cache_entry *a, const struct cache_entry *b)
7b937ca3
LT
887{
888 int len = ce_namelen(a);
889 return ce_namelen(b) == len && !memcmp(a->name, b->name, len);
890}
891
8dcf39c4
LT
892/*
893 * We fundamentally don't like some paths: we don't want
894 * dot or dot-dot anywhere, and for obvious reasons don't
895 * want to recurse into ".git" either.
896 *
897 * Also, we don't want double slashes or slashes at the
898 * end that can make pathnames ambiguous.
899 */
10ecfa76 900static int verify_dotfile(const char *rest, unsigned mode)
8dcf39c4
LT
901{
902 /*
903 * The first character was '.', but that
904 * has already been discarded, we now test
905 * the rest.
906 */
e0f530ff 907
8dcf39c4 908 /* "." is not allowed */
e0f530ff 909 if (*rest == '\0' || is_dir_sep(*rest))
8dcf39c4
LT
910 return 0;
911
e0f530ff 912 switch (*rest) {
8dcf39c4 913 /*
641084b6
JK
914 * ".git" followed by NUL or slash is bad. Note that we match
915 * case-insensitively here, even if ignore_case is not set.
916 * This outlaws ".GIT" everywhere out of an abundance of caution,
917 * since there's really no good reason to allow it.
10ecfa76
JK
918 *
919 * Once we've seen ".git", we can also find ".gitmodules", etc (also
920 * case-insensitively).
8dcf39c4
LT
921 */
922 case 'g':
cc2fc7c2
JK
923 case 'G':
924 if (rest[1] != 'i' && rest[1] != 'I')
8dcf39c4 925 break;
cc2fc7c2 926 if (rest[2] != 't' && rest[2] != 'T')
8dcf39c4 927 break;
e19e5e66
JK
928 if (rest[3] == '\0' || is_dir_sep(rest[3]))
929 return 0;
10ecfa76
JK
930 if (S_ISLNK(mode)) {
931 rest += 3;
932 if (skip_iprefix(rest, "modules", &rest) &&
933 (*rest == '\0' || is_dir_sep(*rest)))
934 return 0;
935 }
e19e5e66 936 break;
8dcf39c4 937 case '.':
e0f530ff 938 if (rest[1] == '\0' || is_dir_sep(rest[1]))
8dcf39c4
LT
939 return 0;
940 }
941 return 1;
942}
943
10ecfa76 944int verify_path(const char *path, unsigned mode)
8dcf39c4
LT
945{
946 char c;
947
56948cb6
EFL
948 if (has_dos_drive_prefix(path))
949 return 0;
950
8dcf39c4
LT
951 goto inside;
952 for (;;) {
953 if (!c)
954 return 1;
56948cb6 955 if (is_dir_sep(c)) {
8dcf39c4 956inside:
10ecfa76
JK
957 if (protect_hfs) {
958 if (is_hfs_dotgit(path))
959 return 0;
960 if (S_ISLNK(mode)) {
961 if (is_hfs_dotgitmodules(path))
962 return 0;
963 }
964 }
965 if (protect_ntfs) {
966 if (is_ntfs_dotgit(path))
967 return 0;
968 if (S_ISLNK(mode)) {
969 if (is_ntfs_dotgitmodules(path))
970 return 0;
971 }
972 }
973
8dcf39c4 974 c = *path++;
10ecfa76 975 if ((c == '.' && !verify_dotfile(path, mode)) ||
3bdf09c7
JH
976 is_dir_sep(c) || c == '\0')
977 return 0;
8dcf39c4
LT
978 }
979 c = *path++;
980 }
981}
982
12676608
LT
983/*
984 * Do we have another file that has the beginning components being a
985 * proper superset of the name we're trying to add?
0f1e4f04 986 */
4aab5b46
JH
987static int has_file_name(struct index_state *istate,
988 const struct cache_entry *ce, int pos, int ok_to_replace)
0f1e4f04 989{
12676608
LT
990 int retval = 0;
991 int len = ce_namelen(ce);
b155725d 992 int stage = ce_stage(ce);
12676608 993 const char *name = ce->name;
0f1e4f04 994
4aab5b46
JH
995 while (pos < istate->cache_nr) {
996 struct cache_entry *p = istate->cache[pos++];
0f1e4f04 997
12676608 998 if (len >= ce_namelen(p))
0f1e4f04 999 break;
12676608
LT
1000 if (memcmp(name, p->name, len))
1001 break;
b155725d
JH
1002 if (ce_stage(p) != stage)
1003 continue;
12676608
LT
1004 if (p->name[len] != '/')
1005 continue;
7a51ed66 1006 if (p->ce_flags & CE_REMOVE)
21cd8d00 1007 continue;
12676608
LT
1008 retval = -1;
1009 if (!ok_to_replace)
1010 break;
4aab5b46 1011 remove_index_entry_at(istate, --pos);
0f1e4f04 1012 }
12676608
LT
1013 return retval;
1014}
0f1e4f04 1015
a6db3fbb
JH
1016
1017/*
1018 * Like strcmp(), but also return the offset of the first change.
1019 * If strings are equal, return the length.
1020 */
1021int strcmp_offset(const char *s1, const char *s2, size_t *first_change)
1022{
1023 size_t k;
1024
1025 if (!first_change)
1026 return strcmp(s1, s2);
1027
1028 for (k = 0; s1[k] == s2[k]; k++)
1029 if (s1[k] == '\0')
1030 break;
1031
1032 *first_change = k;
1033 return (unsigned char)s1[k] - (unsigned char)s2[k];
1034}
1035
12676608
LT
1036/*
1037 * Do we have another file with a pathname that is a proper
1038 * subset of the name we're trying to add?
06b6d81b
JH
1039 *
1040 * That is, is there another file in the index with a path
1041 * that matches a sub-directory in the given entry?
12676608 1042 */
4aab5b46
JH
1043static int has_dir_name(struct index_state *istate,
1044 const struct cache_entry *ce, int pos, int ok_to_replace)
12676608
LT
1045{
1046 int retval = 0;
b155725d 1047 int stage = ce_stage(ce);
12676608
LT
1048 const char *name = ce->name;
1049 const char *slash = name + ce_namelen(ce);
06b6d81b
JH
1050 size_t len_eq_last;
1051 int cmp_last = 0;
1052
1053 /*
1054 * We are frequently called during an iteration on a sorted
1055 * list of pathnames and while building a new index. Therefore,
1056 * there is a high probability that this entry will eventually
1057 * be appended to the index, rather than inserted in the middle.
1058 * If we can confirm that, we can avoid binary searches on the
1059 * components of the pathname.
1060 *
1061 * Compare the entry's full path with the last path in the index.
1062 */
1063 if (istate->cache_nr > 0) {
1064 cmp_last = strcmp_offset(name,
1065 istate->cache[istate->cache_nr - 1]->name,
1066 &len_eq_last);
1067 if (cmp_last > 0) {
1068 if (len_eq_last == 0) {
1069 /*
1070 * The entry sorts AFTER the last one in the
1071 * index and their paths have no common prefix,
1072 * so there cannot be a F/D conflict.
1073 */
1074 return retval;
1075 } else {
1076 /*
1077 * The entry sorts AFTER the last one in the
1078 * index, but has a common prefix. Fall through
1079 * to the loop below to disect the entry's path
1080 * and see where the difference is.
1081 */
1082 }
1083 } else if (cmp_last == 0) {
1084 /*
1085 * The entry exactly matches the last one in the
1086 * index, but because of multiple stage and CE_REMOVE
1087 * items, we fall through and let the regular search
1088 * code handle it.
1089 */
1090 }
1091 }
0f1e4f04 1092
12676608 1093 for (;;) {
b986df5c 1094 size_t len;
0f1e4f04 1095
12676608
LT
1096 for (;;) {
1097 if (*--slash == '/')
1098 break;
1099 if (slash <= ce->name)
1100 return retval;
1101 }
1102 len = slash - name;
0f1e4f04 1103
b986df5c
JH
1104 if (cmp_last > 0) {
1105 /*
1106 * (len + 1) is a directory boundary (including
1107 * the trailing slash). And since the loop is
1108 * decrementing "slash", the first iteration is
1109 * the longest directory prefix; subsequent
1110 * iterations consider parent directories.
1111 */
1112
1113 if (len + 1 <= len_eq_last) {
1114 /*
1115 * The directory prefix (including the trailing
1116 * slash) also appears as a prefix in the last
1117 * entry, so the remainder cannot collide (because
1118 * strcmp said the whole path was greater).
1119 *
1120 * EQ: last: xxx/A
1121 * this: xxx/B
1122 *
1123 * LT: last: xxx/file_A
1124 * this: xxx/file_B
1125 */
1126 return retval;
1127 }
1128
1129 if (len > len_eq_last) {
1130 /*
1131 * This part of the directory prefix (excluding
1132 * the trailing slash) is longer than the known
1133 * equal portions, so this sub-directory cannot
1134 * collide with a file.
1135 *
1136 * GT: last: xxxA
1137 * this: xxxB/file
1138 */
1139 return retval;
1140 }
1141
1142 if (istate->cache_nr > 0 &&
1143 ce_namelen(istate->cache[istate->cache_nr - 1]) > len) {
1144 /*
1145 * The directory prefix lines up with part of
1146 * a longer file or directory name, but sorts
1147 * after it, so this sub-directory cannot
1148 * collide with a file.
1149 *
1150 * last: xxx/yy-file (because '-' sorts before '/')
1151 * this: xxx/yy/abc
1152 */
1153 return retval;
1154 }
1155
1156 /*
1157 * This is a possible collision. Fall through and
1158 * let the regular search code handle it.
1159 *
1160 * last: xxx
1161 * this: xxx/file
1162 */
1163 }
1164
b60e188c 1165 pos = index_name_stage_pos(istate, name, len, stage);
12676608 1166 if (pos >= 0) {
21cd8d00
JH
1167 /*
1168 * Found one, but not so fast. This could
1169 * be a marker that says "I was here, but
1170 * I am being removed". Such an entry is
1171 * not a part of the resulting tree, and
1172 * it is Ok to have a directory at the same
1173 * path.
1174 */
077c48df 1175 if (!(istate->cache[pos]->ce_flags & CE_REMOVE)) {
21cd8d00
JH
1176 retval = -1;
1177 if (!ok_to_replace)
1178 break;
4aab5b46 1179 remove_index_entry_at(istate, pos);
21cd8d00
JH
1180 continue;
1181 }
12676608 1182 }
21cd8d00
JH
1183 else
1184 pos = -pos-1;
12676608
LT
1185
1186 /*
1187 * Trivial optimization: if we find an entry that
1188 * already matches the sub-directory, then we know
b155725d 1189 * we're ok, and we can exit.
12676608 1190 */
4aab5b46
JH
1191 while (pos < istate->cache_nr) {
1192 struct cache_entry *p = istate->cache[pos];
b155725d
JH
1193 if ((ce_namelen(p) <= len) ||
1194 (p->name[len] != '/') ||
1195 memcmp(p->name, name, len))
1196 break; /* not our subdirectory */
077c48df
JH
1197 if (ce_stage(p) == stage && !(p->ce_flags & CE_REMOVE))
1198 /*
1199 * p is at the same stage as our entry, and
b155725d
JH
1200 * is a subdirectory of what we are looking
1201 * at, so we cannot have conflicts at our
1202 * level or anything shorter.
1203 */
1204 return retval;
1205 pos++;
192268c1 1206 }
0f1e4f04 1207 }
12676608
LT
1208 return retval;
1209}
1210
1211/* We may be in a situation where we already have path/file and path
1212 * is being added, or we already have path and path/file is being
1213 * added. Either one would result in a nonsense tree that has path
1214 * twice when git-write-tree tries to write it out. Prevent it.
a6080a0a 1215 *
12676608
LT
1216 * If ok-to-replace is specified, we remove the conflicting entries
1217 * from the cache so the caller should recompute the insert position.
1218 * When this happens, we return non-zero.
1219 */
4aab5b46
JH
1220static int check_file_directory_conflict(struct index_state *istate,
1221 const struct cache_entry *ce,
1222 int pos, int ok_to_replace)
12676608 1223{
21cd8d00
JH
1224 int retval;
1225
1226 /*
1227 * When ce is an "I am going away" entry, we allow it to be added
1228 */
7a51ed66 1229 if (ce->ce_flags & CE_REMOVE)
21cd8d00
JH
1230 return 0;
1231
12676608
LT
1232 /*
1233 * We check if the path is a sub-path of a subsequent pathname
1234 * first, since removing those will not change the position
21cd8d00 1235 * in the array.
12676608 1236 */
4aab5b46 1237 retval = has_file_name(istate, ce, pos, ok_to_replace);
21cd8d00 1238
12676608
LT
1239 /*
1240 * Then check if the path might have a clashing sub-directory
1241 * before it.
1242 */
4aab5b46 1243 return retval + has_dir_name(istate, ce, pos, ok_to_replace);
0f1e4f04
JH
1244}
1245
af3785dc 1246static int add_index_entry_with_check(struct index_state *istate, struct cache_entry *ce, int option)
197ee8c9
LT
1247{
1248 int pos;
192268c1
JH
1249 int ok_to_add = option & ADD_CACHE_OK_TO_ADD;
1250 int ok_to_replace = option & ADD_CACHE_OK_TO_REPLACE;
b155725d 1251 int skip_df_check = option & ADD_CACHE_SKIP_DFCHECK;
39425819 1252 int new_only = option & ADD_CACHE_NEW_ONLY;
5f73076c 1253
ce7c614b
NTND
1254 if (!(option & ADD_CACHE_KEEP_CACHE_TREE))
1255 cache_tree_invalidate_path(istate, ce->name);
e5494631
JH
1256
1257 /*
1258 * If this entry's path sorts after the last entry in the index,
1259 * we can avoid searching for it.
1260 */
1261 if (istate->cache_nr > 0 &&
1262 strcmp(ce->name, istate->cache[istate->cache_nr - 1]->name) > 0)
1263 pos = -istate->cache_nr - 1;
1264 else
1265 pos = index_name_stage_pos(istate, ce->name, ce_namelen(ce), ce_stage(ce));
197ee8c9 1266
3e09cdfd 1267 /* existing match? Just replace it. */
76e7f4ec 1268 if (pos >= 0) {
39425819
JH
1269 if (!new_only)
1270 replace_index_entry(istate, pos, ce);
197ee8c9
LT
1271 return 0;
1272 }
76e7f4ec 1273 pos = -pos-1;
197ee8c9 1274
ffcc9ba7
NTND
1275 if (!(option & ADD_CACHE_KEEP_CACHE_TREE))
1276 untracked_cache_add_to_index(istate, ce->name);
e931371a 1277
7b937ca3
LT
1278 /*
1279 * Inserting a merged entry ("stage 0") into the index
1280 * will always replace all non-merged entries..
1281 */
4aab5b46
JH
1282 if (pos < istate->cache_nr && ce_stage(ce) == 0) {
1283 while (ce_same_name(istate->cache[pos], ce)) {
7b937ca3 1284 ok_to_add = 1;
4aab5b46 1285 if (!remove_index_entry_at(istate, pos))
7b937ca3
LT
1286 break;
1287 }
1288 }
1289
121481ab
LT
1290 if (!ok_to_add)
1291 return -1;
10ecfa76 1292 if (!verify_path(ce->name, ce->ce_mode))
7e7abea9 1293 return error("Invalid path '%s'", ce->name);
121481ab 1294
3e09cdfd 1295 if (!skip_df_check &&
4aab5b46 1296 check_file_directory_conflict(istate, ce, pos, ok_to_replace)) {
192268c1 1297 if (!ok_to_replace)
4aab5b46
JH
1298 return error("'%s' appears as both a file and as a directory",
1299 ce->name);
b60e188c 1300 pos = index_name_stage_pos(istate, ce->name, ce_namelen(ce), ce_stage(ce));
192268c1
JH
1301 pos = -pos-1;
1302 }
af3785dc
JH
1303 return pos + 1;
1304}
1305
1306int add_index_entry(struct index_state *istate, struct cache_entry *ce, int option)
1307{
1308 int pos;
1309
1310 if (option & ADD_CACHE_JUST_APPEND)
1311 pos = istate->cache_nr;
1312 else {
1313 int ret;
1314 ret = add_index_entry_with_check(istate, ce, option);
1315 if (ret <= 0)
1316 return ret;
1317 pos = ret - 1;
1318 }
0f1e4f04 1319
197ee8c9 1320 /* Make sure the array is big enough .. */
999f5660 1321 ALLOC_GROW(istate->cache, istate->cache_nr + 1, istate->cache_alloc);
197ee8c9
LT
1322
1323 /* Add it in.. */
4aab5b46 1324 istate->cache_nr++;
af3785dc 1325 if (istate->cache_nr > pos + 1)
f919ffeb
SG
1326 MOVE_ARRAY(istate->cache + pos + 1, istate->cache + pos,
1327 istate->cache_nr - pos - 1);
cf558704 1328 set_index_entry(istate, pos, ce);
e636a7b4 1329 istate->cache_changed |= CE_ENTRY_ADDED;
197ee8c9
LT
1330 return 0;
1331}
1332
405e5b2f
LT
1333/*
1334 * "refresh" does not calculate a new sha1 file or bring the
1335 * cache up-to-date for mode/content changes. But what it
1336 * _does_ do is to "re-match" the stat information of a file
1337 * with the cache, so that you can refresh the cache for a
1338 * file that hasn't been changed but where the stat entry is
1339 * out of date.
1340 *
1341 * For example, you'd want to do this after doing a "git-read-tree",
1342 * to link up the stat cache details with the proper files.
1343 */
4aab5b46 1344static struct cache_entry *refresh_cache_ent(struct index_state *istate,
4bd5b7da 1345 struct cache_entry *ce,
d05e6970
JK
1346 unsigned int options, int *err,
1347 int *changed_ret)
405e5b2f
LT
1348{
1349 struct stat st;
1350 struct cache_entry *updated;
a849735b 1351 int changed;
25762726 1352 int refresh = options & CE_MATCH_REFRESH;
4bd5b7da 1353 int ignore_valid = options & CE_MATCH_IGNORE_VALID;
56cac48c 1354 int ignore_skip_worktree = options & CE_MATCH_IGNORE_SKIP_WORKTREE;
2e2e7ec1 1355 int ignore_missing = options & CE_MATCH_IGNORE_MISSING;
883e248b 1356 int ignore_fsmonitor = options & CE_MATCH_IGNORE_FSMONITOR;
405e5b2f 1357
25762726 1358 if (!refresh || ce_uptodate(ce))
eadb5831
JH
1359 return ce;
1360
883e248b
BP
1361 if (!ignore_fsmonitor)
1362 refresh_fsmonitor(istate);
aa9349d4 1363 /*
56cac48c
NTND
1364 * CE_VALID or CE_SKIP_WORKTREE means the user promised us
1365 * that the change to the work tree does not matter and told
1366 * us not to worry.
aa9349d4 1367 */
56cac48c
NTND
1368 if (!ignore_skip_worktree && ce_skip_worktree(ce)) {
1369 ce_mark_uptodate(ce);
1370 return ce;
1371 }
aa9349d4
MSO
1372 if (!ignore_valid && (ce->ce_flags & CE_VALID)) {
1373 ce_mark_uptodate(ce);
1374 return ce;
1375 }
883e248b
BP
1376 if (!ignore_fsmonitor && (ce->ce_flags & CE_FSMONITOR_VALID)) {
1377 ce_mark_uptodate(ce);
1378 return ce;
1379 }
aa9349d4 1380
ccad42d4
RS
1381 if (has_symlink_leading_path(ce->name, ce_namelen(ce))) {
1382 if (ignore_missing)
1383 return ce;
1384 if (err)
1385 *err = ENOENT;
1386 return NULL;
1387 }
1388
8fd2cb40 1389 if (lstat(ce->name, &st) < 0) {
2e2e7ec1
BK
1390 if (ignore_missing && errno == ENOENT)
1391 return ce;
ec0cc704
JH
1392 if (err)
1393 *err = errno;
8fd2cb40
JS
1394 return NULL;
1395 }
405e5b2f 1396
4bd5b7da 1397 changed = ie_match_stat(istate, ce, &st, options);
d05e6970
JK
1398 if (changed_ret)
1399 *changed_ret = changed;
405e5b2f 1400 if (!changed) {
4bd5b7da
JH
1401 /*
1402 * The path is unchanged. If we were told to ignore
1403 * valid bit, then we did the actual stat check and
1404 * found that the entry is unmodified. If the entry
1405 * is not marked VALID, this is the place to mark it
1406 * valid again, under "assume unchanged" mode.
1407 */
1408 if (ignore_valid && assume_unchanged &&
7a51ed66 1409 !(ce->ce_flags & CE_VALID))
405e5b2f 1410 ; /* mark this one VALID again */
eadb5831
JH
1411 else {
1412 /*
1413 * We do not mark the index itself "modified"
1414 * because CE_UPTODATE flag is in-core only;
1415 * we are not going to write this change out.
1416 */
883e248b 1417 if (!S_ISGITLINK(ce->ce_mode)) {
125fd984 1418 ce_mark_uptodate(ce);
883e248b
BP
1419 mark_fsmonitor_valid(ce);
1420 }
8fd2cb40 1421 return ce;
eadb5831 1422 }
405e5b2f
LT
1423 }
1424
4bd5b7da 1425 if (ie_modified(istate, ce, &st, options)) {
ec0cc704
JH
1426 if (err)
1427 *err = EINVAL;
8fd2cb40
JS
1428 return NULL;
1429 }
405e5b2f 1430
a849735b 1431 updated = make_empty_cache_entry(istate, ce_namelen(ce));
0e267b7a
BP
1432 copy_cache_entry(updated, ce);
1433 memcpy(updated->name, ce->name, ce->ce_namelen + 1);
405e5b2f 1434 fill_stat_cache_info(updated, &st);
4bd5b7da
JH
1435 /*
1436 * If ignore_valid is not set, we should leave CE_VALID bit
1437 * alone. Otherwise, paths marked with --no-assume-unchanged
1438 * (i.e. things to be edited) will reacquire CE_VALID bit
1439 * automatically, which is not really what we want.
405e5b2f 1440 */
4bd5b7da 1441 if (!ignore_valid && assume_unchanged &&
7a51ed66
LT
1442 !(ce->ce_flags & CE_VALID))
1443 updated->ce_flags &= ~CE_VALID;
405e5b2f 1444
e636a7b4 1445 /* istate->cache_changed is updated in the caller */
405e5b2f
LT
1446 return updated;
1447}
1448
3deffc52 1449static void show_file(const char * fmt, const char * name, int in_porcelain,
046613c5 1450 int * first, const char *header_msg)
3deffc52
MM
1451{
1452 if (in_porcelain && *first && header_msg) {
1453 printf("%s\n", header_msg);
cd2b8ae9 1454 *first = 0;
3deffc52
MM
1455 }
1456 printf(fmt, name);
1457}
1458
9b2d6149
NTND
1459int refresh_index(struct index_state *istate, unsigned int flags,
1460 const struct pathspec *pathspec,
046613c5 1461 char *seen, const char *header_msg)
405e5b2f
LT
1462{
1463 int i;
1464 int has_errors = 0;
1465 int really = (flags & REFRESH_REALLY) != 0;
1466 int allow_unmerged = (flags & REFRESH_UNMERGED) != 0;
1467 int quiet = (flags & REFRESH_QUIET) != 0;
1468 int not_new = (flags & REFRESH_IGNORE_MISSING) != 0;
5fdeacb0 1469 int ignore_submodules = (flags & REFRESH_IGNORE_SUBMODULES) != 0;
3deffc52
MM
1470 int first = 1;
1471 int in_porcelain = (flags & REFRESH_IN_PORCELAIN);
25762726
BK
1472 unsigned int options = (CE_MATCH_REFRESH |
1473 (really ? CE_MATCH_IGNORE_VALID : 0) |
2e2e7ec1 1474 (not_new ? CE_MATCH_IGNORE_MISSING : 0));
4bd4e730 1475 const char *modified_fmt;
73b7eae6
JK
1476 const char *deleted_fmt;
1477 const char *typechange_fmt;
1478 const char *added_fmt;
4bd4e730 1479 const char *unmerged_fmt;
405e5b2f 1480
c46c406a 1481 trace_performance_enter();
4bd4e730 1482 modified_fmt = (in_porcelain ? "M\t%s\n" : "%s: needs update\n");
73b7eae6
JK
1483 deleted_fmt = (in_porcelain ? "D\t%s\n" : "%s: needs update\n");
1484 typechange_fmt = (in_porcelain ? "T\t%s\n" : "%s needs update\n");
1485 added_fmt = (in_porcelain ? "A\t%s\n" : "%s needs update\n");
4bd4e730 1486 unmerged_fmt = (in_porcelain ? "U\t%s\n" : "%s: needs merge\n");
4aab5b46 1487 for (i = 0; i < istate->cache_nr; i++) {
285c2e25 1488 struct cache_entry *ce, *new_entry;
ec0cc704 1489 int cache_errno = 0;
73b7eae6 1490 int changed = 0;
3d1f148c 1491 int filtered = 0;
ec0cc704 1492
4aab5b46 1493 ce = istate->cache[i];
5fdeacb0
JS
1494 if (ignore_submodules && S_ISGITLINK(ce->ce_mode))
1495 continue;
1496
6d2df284 1497 if (pathspec && !ce_path_match(&the_index, ce, pathspec, seen))
3d1f148c
JH
1498 filtered = 1;
1499
405e5b2f 1500 if (ce_stage(ce)) {
4aab5b46
JH
1501 while ((i < istate->cache_nr) &&
1502 ! strcmp(istate->cache[i]->name, ce->name))
405e5b2f
LT
1503 i++;
1504 i--;
1505 if (allow_unmerged)
1506 continue;
3d1f148c
JH
1507 if (!filtered)
1508 show_file(unmerged_fmt, ce->name, in_porcelain,
1509 &first, header_msg);
405e5b2f
LT
1510 has_errors = 1;
1511 continue;
1512 }
1513
3d1f148c 1514 if (filtered)
d616813d
AJ
1515 continue;
1516
285c2e25
BW
1517 new_entry = refresh_cache_ent(istate, ce, options, &cache_errno, &changed);
1518 if (new_entry == ce)
405e5b2f 1519 continue;
285c2e25 1520 if (!new_entry) {
73b7eae6
JK
1521 const char *fmt;
1522
8fd2cb40 1523 if (really && cache_errno == EINVAL) {
405e5b2f
LT
1524 /* If we are doing --really-refresh that
1525 * means the index is not valid anymore.
1526 */
7a51ed66 1527 ce->ce_flags &= ~CE_VALID;
078a58e8 1528 ce->ce_flags |= CE_UPDATE_IN_BASE;
883e248b 1529 mark_fsmonitor_invalid(istate, ce);
e636a7b4 1530 istate->cache_changed |= CE_ENTRY_CHANGED;
405e5b2f
LT
1531 }
1532 if (quiet)
1533 continue;
73b7eae6
JK
1534
1535 if (cache_errno == ENOENT)
1536 fmt = deleted_fmt;
895ff3b2 1537 else if (ce_intent_to_add(ce))
73b7eae6
JK
1538 fmt = added_fmt; /* must be before other checks */
1539 else if (changed & TYPE_CHANGED)
1540 fmt = typechange_fmt;
1541 else
1542 fmt = modified_fmt;
1543 show_file(fmt,
1544 ce->name, in_porcelain, &first, header_msg);
405e5b2f
LT
1545 has_errors = 1;
1546 continue;
1547 }
cf558704 1548
285c2e25 1549 replace_index_entry(istate, i, new_entry);
405e5b2f 1550 }
c46c406a 1551 trace_performance_leave("refresh index");
405e5b2f
LT
1552 return has_errors;
1553}
1554
768d7965
JM
1555struct cache_entry *refresh_cache_entry(struct index_state *istate,
1556 struct cache_entry *ce,
1557 unsigned int options)
ec0cc704 1558{
768d7965 1559 return refresh_cache_ent(istate, ce, options, NULL, NULL);
ec0cc704
JH
1560}
1561
db3b313c
JH
1562
1563/*****************************************************************
1564 * Index File I/O
1565 *****************************************************************/
1566
9d227781
JH
1567#define INDEX_FORMAT_DEFAULT 3
1568
136347d7
TG
1569static unsigned int get_index_format_default(void)
1570{
1571 char *envversion = getenv("GIT_INDEX_VERSION");
3c09d684 1572 char *endp;
b27a5720 1573 int value;
3c09d684
TG
1574 unsigned int version = INDEX_FORMAT_DEFAULT;
1575
136347d7 1576 if (!envversion) {
b27a5720
TA
1577 if (!git_config_get_int("index.version", &value))
1578 version = value;
3c09d684
TG
1579 if (version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < version) {
1580 warning(_("index.version set, but the value is invalid.\n"
136347d7 1581 "Using version %i"), INDEX_FORMAT_DEFAULT);
3c09d684 1582 return INDEX_FORMAT_DEFAULT;
136347d7
TG
1583 }
1584 return version;
1585 }
3c09d684
TG
1586
1587 version = strtoul(envversion, &endp, 10);
1588 if (*endp ||
1589 version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < version) {
1590 warning(_("GIT_INDEX_VERSION set, but the value is invalid.\n"
1591 "Using version %i"), INDEX_FORMAT_DEFAULT);
1592 version = INDEX_FORMAT_DEFAULT;
1593 }
1594 return version;
136347d7
TG
1595}
1596
db3b313c
JH
1597/*
1598 * dev/ino/uid/gid/size are also just tracked to the low 32 bits
1599 * Again - this is just a (very strong in practice) heuristic that
1600 * the inode hasn't changed.
1601 *
1602 * We save the fields in big-endian order to allow using the
1603 * index file over NFS transparently.
1604 */
1605struct ondisk_cache_entry {
1606 struct cache_time ctime;
1607 struct cache_time mtime;
7800c1eb
TG
1608 uint32_t dev;
1609 uint32_t ino;
1610 uint32_t mode;
1611 uint32_t uid;
1612 uint32_t gid;
1613 uint32_t size;
db3b313c 1614 unsigned char sha1[20];
7800c1eb 1615 uint16_t flags;
db3b313c
JH
1616 char name[FLEX_ARRAY]; /* more */
1617};
1618
1619/*
1620 * This struct is used when CE_EXTENDED bit is 1
1621 * The struct must match ondisk_cache_entry exactly from
1622 * ctime till flags
1623 */
1624struct ondisk_cache_entry_extended {
1625 struct cache_time ctime;
1626 struct cache_time mtime;
7800c1eb
TG
1627 uint32_t dev;
1628 uint32_t ino;
1629 uint32_t mode;
1630 uint32_t uid;
1631 uint32_t gid;
1632 uint32_t size;
db3b313c 1633 unsigned char sha1[20];
7800c1eb
TG
1634 uint16_t flags;
1635 uint16_t flags2;
db3b313c
JH
1636 char name[FLEX_ARRAY]; /* more */
1637};
1638
6c9cd161 1639/* These are only used for v3 or lower */
ce012deb 1640#define align_padding_size(size, len) ((size + (len) + 8) & ~7) - (size + len)
db3b313c
JH
1641#define align_flex_name(STRUCT,len) ((offsetof(struct STRUCT,name) + (len) + 8) & ~7)
1642#define ondisk_cache_entry_size(len) align_flex_name(ondisk_cache_entry,len)
1643#define ondisk_cache_entry_extended_size(len) align_flex_name(ondisk_cache_entry_extended,len)
1644#define ondisk_ce_size(ce) (((ce)->ce_flags & CE_EXTENDED) ? \
1645 ondisk_cache_entry_extended_size(ce_namelen(ce)) : \
1646 ondisk_cache_entry_size(ce_namelen(ce)))
1647
a33fc72f
JH
1648/* Allow fsck to force verification of the index checksum. */
1649int verify_index_checksum;
1650
00ec50e5
BP
1651/* Allow fsck to force verification of the cache entry order. */
1652int verify_ce_order;
1653
371ed0de 1654static int verify_hdr(const struct cache_header *hdr, unsigned long size)
e83c5163 1655{
aab61359 1656 git_hash_ctx c;
1657 unsigned char hash[GIT_MAX_RAWSZ];
0136bac9 1658 int hdr_version;
e83c5163 1659
ccc4feb5 1660 if (hdr->hdr_signature != htonl(CACHE_SIGNATURE))
e83c5163 1661 return error("bad signature");
0136bac9 1662 hdr_version = ntohl(hdr->hdr_version);
b82a7b5b 1663 if (hdr_version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < hdr_version)
0136bac9 1664 return error("bad index version %d", hdr_version);
a33fc72f
JH
1665
1666 if (!verify_index_checksum)
1667 return 0;
1668
aab61359 1669 the_hash_algo->init_fn(&c);
1670 the_hash_algo->update_fn(&c, hdr, size - the_hash_algo->rawsz);
1671 the_hash_algo->final_fn(hash, &c);
67947c34 1672 if (!hasheq(hash, (unsigned char *)hdr + size - the_hash_algo->rawsz))
ca9be054 1673 return error("bad index file sha1 signature");
e83c5163
LT
1674 return 0;
1675}
1676
4aab5b46 1677static int read_index_extension(struct index_state *istate,
371ed0de 1678 const char *ext, const char *data, unsigned long sz)
bad68ec9
JH
1679{
1680 switch (CACHE_EXT(ext)) {
1681 case CACHE_EXT_TREE:
4aab5b46 1682 istate->cache_tree = cache_tree_read(data, sz);
bad68ec9 1683 break;
cfc5789a
JH
1684 case CACHE_EXT_RESOLVE_UNDO:
1685 istate->resolve_undo = resolve_undo_read(data, sz);
1686 break;
5fc2fc8f
NTND
1687 case CACHE_EXT_LINK:
1688 if (read_link_extension(istate, data, sz))
1689 return -1;
1690 break;
f9e6c649
NTND
1691 case CACHE_EXT_UNTRACKED:
1692 istate->untracked = read_untracked_extension(data, sz);
1693 break;
883e248b
BP
1694 case CACHE_EXT_FSMONITOR:
1695 read_fsmonitor_extension(istate, data, sz);
1696 break;
3b1d9e04
BP
1697 case CACHE_EXT_ENDOFINDEXENTRIES:
1698 /* already handled in do_read_index() */
1699 break;
bad68ec9
JH
1700 default:
1701 if (*ext < 'A' || 'Z' < *ext)
1702 return error("index uses %.4s extension, which we do not understand",
1703 ext);
1704 fprintf(stderr, "ignoring %.4s extension\n", ext);
1705 break;
1706 }
1707 return 0;
1708}
1709
b3e83cc7 1710int hold_locked_index(struct lock_file *lk, int lock_flags)
216aab1e 1711{
b3e83cc7 1712 return hold_lock_file_for_update(lk, get_index_file(), lock_flags);
216aab1e
MH
1713}
1714
4aab5b46 1715int read_index(struct index_state *istate)
8fd2cb40 1716{
a125a223 1717 return read_index_from(istate, get_index_file(), get_git_dir());
8fd2cb40
JS
1718}
1719
252d079c 1720static struct cache_entry *create_from_disk(struct index_state *istate,
a849735b 1721 struct ondisk_cache_entry *ondisk,
6c9cd161 1722 unsigned long *ent_size,
252d079c 1723 const struct cache_entry *previous_ce)
7a51ed66 1724{
debed2a6 1725 struct cache_entry *ce;
7fec10b7 1726 size_t len;
06aaaa0b 1727 const char *name;
debed2a6 1728 unsigned int flags;
252d079c
NTND
1729 size_t copy_len;
1730 /*
1731 * Adjacent cache entries tend to share the leading paths, so it makes
1732 * sense to only store the differences in later entries. In the v4
1733 * on-disk format of the index, each on-disk cache entry stores the
1734 * number of bytes to be stripped from the end of the previous name,
1735 * and the bytes to append to the result, to come up with its name.
1736 */
1737 int expand_name_field = istate->version == 4;
7fec10b7 1738
7a51ed66 1739 /* On-disk flags are just 16 bits */
c3d8da57 1740 flags = get_be16(&ondisk->flags);
debed2a6 1741 len = flags & CE_NAMEMASK;
7fec10b7 1742
debed2a6 1743 if (flags & CE_EXTENDED) {
06aaaa0b
NTND
1744 struct ondisk_cache_entry_extended *ondisk2;
1745 int extended_flags;
1746 ondisk2 = (struct ondisk_cache_entry_extended *)ondisk;
c3d8da57 1747 extended_flags = get_be16(&ondisk2->flags2) << 16;
06aaaa0b
NTND
1748 /* We do not yet understand any bit out of CE_EXTENDED_FLAGS */
1749 if (extended_flags & ~CE_EXTENDED_FLAGS)
1750 die("Unknown index entry format %08x", extended_flags);
debed2a6 1751 flags |= extended_flags;
06aaaa0b
NTND
1752 name = ondisk2->name;
1753 }
1754 else
1755 name = ondisk->name;
1756
252d079c
NTND
1757 if (expand_name_field) {
1758 const unsigned char *cp = (const unsigned char *)name;
1759 size_t strip_len, previous_len;
6c9cd161 1760
252d079c
NTND
1761 previous_len = previous_ce ? previous_ce->ce_namelen : 0;
1762 strip_len = decode_varint(&cp);
1763 if (previous_len < strip_len) {
1764 if (previous_ce)
1765 die(_("malformed name field in the index, near path '%s'"),
1766 previous_ce->name);
1767 else
1768 die(_("malformed name field in the index in the first path"));
1769 }
1770 copy_len = previous_len - strip_len;
1771 name = (const char *)cp;
1772 }
1773
1774 if (len == CE_NAMEMASK) {
1775 len = strlen(name);
1776 if (expand_name_field)
1777 len += copy_len;
1778 }
1779
1780 ce = mem_pool__ce_alloc(istate->ce_mem_pool, len);
1781
1782 ce->ce_stat_data.sd_ctime.sec = get_be32(&ondisk->ctime.sec);
1783 ce->ce_stat_data.sd_mtime.sec = get_be32(&ondisk->mtime.sec);
1784 ce->ce_stat_data.sd_ctime.nsec = get_be32(&ondisk->ctime.nsec);
1785 ce->ce_stat_data.sd_mtime.nsec = get_be32(&ondisk->mtime.nsec);
1786 ce->ce_stat_data.sd_dev = get_be32(&ondisk->dev);
1787 ce->ce_stat_data.sd_ino = get_be32(&ondisk->ino);
1788 ce->ce_mode = get_be32(&ondisk->mode);
1789 ce->ce_stat_data.sd_uid = get_be32(&ondisk->uid);
1790 ce->ce_stat_data.sd_gid = get_be32(&ondisk->gid);
1791 ce->ce_stat_data.sd_size = get_be32(&ondisk->size);
1792 ce->ce_flags = flags & ~CE_NAMEMASK;
1793 ce->ce_namelen = len;
1794 ce->index = 0;
1795 hashcpy(ce->oid.hash, ondisk->sha1);
6c9cd161 1796
252d079c
NTND
1797 if (expand_name_field) {
1798 if (copy_len)
1799 memcpy(ce->name, previous_ce->name, copy_len);
1800 memcpy(ce->name + copy_len, name, len + 1 - copy_len);
1801 *ent_size = (name - ((char *)ondisk)) + len + 1 - copy_len;
1802 } else {
1803 memcpy(ce->name, name, len + 1);
1804 *ent_size = ondisk_ce_size(ce);
6c9cd161 1805 }
debed2a6 1806 return ce;
cf558704
LT
1807}
1808
03f15a79 1809static void check_ce_order(struct index_state *istate)
15999d0b 1810{
03f15a79
TG
1811 unsigned int i;
1812
00ec50e5
BP
1813 if (!verify_ce_order)
1814 return;
1815
03f15a79
TG
1816 for (i = 1; i < istate->cache_nr; i++) {
1817 struct cache_entry *ce = istate->cache[i - 1];
1818 struct cache_entry *next_ce = istate->cache[i];
1819 int name_compare = strcmp(ce->name, next_ce->name);
1820
1821 if (0 < name_compare)
1822 die("unordered stage entries in index");
1823 if (!name_compare) {
1824 if (!ce_stage(ce))
1825 die("multiple stage entries for merged file '%s'",
1826 ce->name);
1827 if (ce_stage(ce) > ce_stage(next_ce))
1828 die("unordered stage entries for '%s'",
1829 ce->name);
1830 }
15999d0b
JSP
1831 }
1832}
1833
435ec090
CC
1834static void tweak_untracked_cache(struct index_state *istate)
1835{
1836 switch (git_config_get_untracked_cache()) {
1837 case -1: /* keep: do nothing */
1838 break;
1839 case 0: /* false */
1840 remove_untracked_cache(istate);
1841 break;
1842 case 1: /* true */
1843 add_untracked_cache(istate);
1844 break;
1845 default: /* unknown value: do nothing */
1846 break;
1847 }
1848}
1849
43925312
CC
1850static void tweak_split_index(struct index_state *istate)
1851{
1852 switch (git_config_get_split_index()) {
1853 case -1: /* unset: do nothing */
1854 break;
1855 case 0: /* false */
1856 remove_split_index(istate);
1857 break;
1858 case 1: /* true */
1859 add_split_index(istate);
1860 break;
1861 default: /* unknown value: do nothing */
1862 break;
1863 }
1864}
1865
435ec090
CC
1866static void post_read_index_from(struct index_state *istate)
1867{
1868 check_ce_order(istate);
1869 tweak_untracked_cache(istate);
43925312 1870 tweak_split_index(istate);
883e248b 1871 tweak_fsmonitor(istate);
435ec090
CC
1872}
1873
8e72d675
JM
1874static size_t estimate_cache_size_from_compressed(unsigned int entries)
1875{
1876 return entries * (sizeof(struct cache_entry) + CACHE_ENTRY_PATH_LENGTH);
1877}
1878
1879static size_t estimate_cache_size(size_t ondisk_size, unsigned int entries)
1880{
1881 long per_entry = sizeof(struct cache_entry) - sizeof(struct ondisk_cache_entry);
1882
1883 /*
1884 * Account for potential alignment differences.
1885 */
1886 per_entry += align_padding_size(sizeof(struct cache_entry), -sizeof(struct ondisk_cache_entry));
1887 return ondisk_size + entries * per_entry;
1888}
1889
3b1d9e04
BP
1890static size_t read_eoie_extension(const char *mmap, size_t mmap_size);
1891static void write_eoie_extension(struct strbuf *sb, git_hash_ctx *eoie_context, size_t offset);
1892
8fd2cb40 1893/* remember to discard_cache() before reading a different cache! */
3e52f70b 1894int do_read_index(struct index_state *istate, const char *path, int must_exist)
e83c5163
LT
1895{
1896 int fd, i;
1897 struct stat st;
debed2a6 1898 unsigned long src_offset;
371ed0de
BP
1899 const struct cache_header *hdr;
1900 const char *mmap;
7a51ed66 1901 size_t mmap_size;
252d079c 1902 const struct cache_entry *previous_ce = NULL;
e83c5163 1903
913e0e99 1904 if (istate->initialized)
4aab5b46 1905 return istate->cache_nr;
5d1a5c02 1906
fba2f38a
KB
1907 istate->timestamp.sec = 0;
1908 istate->timestamp.nsec = 0;
8fd2cb40 1909 fd = open(path, O_RDONLY);
5d1a5c02 1910 if (fd < 0) {
5fc2fc8f 1911 if (!must_exist && errno == ENOENT)
5d1a5c02 1912 return 0;
5fc2fc8f 1913 die_errno("%s: index file open failed", path);
5d1a5c02 1914 }
e83c5163 1915
3511a377 1916 if (fstat(fd, &st))
d824cbba 1917 die_errno("cannot stat the open index");
3511a377 1918
7a51ed66 1919 mmap_size = xsize_t(st.st_size);
aab61359 1920 if (mmap_size < sizeof(struct cache_header) + the_hash_algo->rawsz)
3511a377
LFC
1921 die("index file smaller than expected");
1922
a1293ef7 1923 mmap = xmmap(NULL, mmap_size, PROT_READ, MAP_PRIVATE, fd, 0);
7a51ed66 1924 if (mmap == MAP_FAILED)
0721c314 1925 die_errno("unable to map index file");
57d84f8d 1926 close(fd);
e83c5163 1927
371ed0de 1928 hdr = (const struct cache_header *)mmap;
7a51ed66 1929 if (verify_hdr(hdr, mmap_size) < 0)
e83c5163
LT
1930 goto unmap;
1931
75691ea3 1932 hashcpy(istate->oid.hash, (const unsigned char *)hdr + mmap_size - the_hash_algo->rawsz);
9d227781 1933 istate->version = ntohl(hdr->hdr_version);
4aab5b46
JH
1934 istate->cache_nr = ntohl(hdr->hdr_entries);
1935 istate->cache_alloc = alloc_nr(istate->cache_nr);
c4aa3167 1936 istate->cache = xcalloc(istate->cache_alloc, sizeof(*istate->cache));
913e0e99 1937 istate->initialized = 1;
7a51ed66 1938
8e72d675 1939 if (istate->version == 4) {
8e72d675
JM
1940 mem_pool_init(&istate->ce_mem_pool,
1941 estimate_cache_size_from_compressed(istate->cache_nr));
1942 } else {
8e72d675
JM
1943 mem_pool_init(&istate->ce_mem_pool,
1944 estimate_cache_size(mmap_size, istate->cache_nr));
1945 }
6c9cd161 1946
7a51ed66 1947 src_offset = sizeof(*hdr);
4aab5b46 1948 for (i = 0; i < istate->cache_nr; i++) {
7a51ed66 1949 struct ondisk_cache_entry *disk_ce;
4aab5b46 1950 struct cache_entry *ce;
936f53d0 1951 unsigned long consumed;
4aab5b46 1952
371ed0de 1953 disk_ce = (struct ondisk_cache_entry *)(mmap + src_offset);
252d079c 1954 ce = create_from_disk(istate, disk_ce, &consumed, previous_ce);
cf558704 1955 set_index_entry(istate, i, ce);
7a51ed66 1956
936f53d0 1957 src_offset += consumed;
252d079c 1958 previous_ce = ce;
e83c5163 1959 }
fba2f38a 1960 istate->timestamp.sec = st.st_mtime;
c06ff490 1961 istate->timestamp.nsec = ST_MTIME_NSEC(st);
fba2f38a 1962
aab61359 1963 while (src_offset <= mmap_size - the_hash_algo->rawsz - 8) {
bad68ec9
JH
1964 /* After an array of active_nr index entries,
1965 * there can be arbitrary number of extended
1966 * sections, each of which is prefixed with
1967 * extension name (4-byte) and section length
1968 * in 4-byte network byte order.
1969 */
07cc8eca 1970 uint32_t extsize;
371ed0de 1971 extsize = get_be32(mmap + src_offset + 4);
4aab5b46 1972 if (read_index_extension(istate,
371ed0de
BP
1973 mmap + src_offset,
1974 mmap + src_offset + 8,
1d7f171c 1975 extsize) < 0)
bad68ec9 1976 goto unmap;
7a51ed66
LT
1977 src_offset += 8;
1978 src_offset += extsize;
bad68ec9 1979 }
371ed0de 1980 munmap((void *)mmap, mmap_size);
4aab5b46 1981 return istate->cache_nr;
e83c5163
LT
1982
1983unmap:
371ed0de 1984 munmap((void *)mmap, mmap_size);
5d1a5c02 1985 die("index file corrupt");
e83c5163
LT
1986}
1987
0d59ffb4
CC
1988/*
1989 * Signal that the shared index is used by updating its mtime.
1990 *
1991 * This way, shared index can be removed if they have not been used
1992 * for some time.
1993 */
a125a223 1994static void freshen_shared_index(const char *shared_index, int warn)
0d59ffb4 1995{
0d59ffb4
CC
1996 if (!check_and_freshen_file(shared_index, 1) && warn)
1997 warning("could not freshen shared index '%s'", shared_index);
1998}
1999
a125a223
TG
2000int read_index_from(struct index_state *istate, const char *path,
2001 const char *gitdir)
5fc2fc8f
NTND
2002{
2003 struct split_index *split_index;
2004 int ret;
2182abd9 2005 char *base_oid_hex;
a125a223 2006 char *base_path;
5fc2fc8f
NTND
2007
2008 /* istate->initialized covers both .git/index and .git/sharedindex.xxx */
2009 if (istate->initialized)
2010 return istate->cache_nr;
2011
c46c406a 2012 trace_performance_enter();
5fc2fc8f 2013 ret = do_read_index(istate, path, 0);
c46c406a 2014 trace_performance_leave("read cache %s", path);
435ec090 2015
5fc2fc8f 2016 split_index = istate->split_index;
2182abd9 2017 if (!split_index || is_null_oid(&split_index->base_oid)) {
435ec090 2018 post_read_index_from(istate);
5fc2fc8f 2019 return ret;
03f15a79 2020 }
5fc2fc8f 2021
c46c406a 2022 trace_performance_enter();
5fc2fc8f
NTND
2023 if (split_index->base)
2024 discard_index(split_index->base);
2025 else
2026 split_index->base = xcalloc(1, sizeof(*split_index->base));
de6ae5f9 2027
2182abd9 2028 base_oid_hex = oid_to_hex(&split_index->base_oid);
2029 base_path = xstrfmt("%s/sharedindex.%s", gitdir, base_oid_hex);
de6ae5f9 2030 ret = do_read_index(split_index->base, base_path, 1);
9001dc2a 2031 if (!oideq(&split_index->base_oid, &split_index->base->oid))
5fc2fc8f 2032 die("broken index, expect %s in %s, got %s",
2182abd9 2033 base_oid_hex, base_path,
75691ea3 2034 oid_to_hex(&split_index->base->oid));
de6ae5f9 2035
a125a223 2036 freshen_shared_index(base_path, 0);
5fc2fc8f 2037 merge_base_index(istate);
435ec090 2038 post_read_index_from(istate);
a125a223 2039 free(base_path);
c46c406a 2040 trace_performance_leave("read cache %s", base_path);
5fc2fc8f
NTND
2041 return ret;
2042}
2043
fa7b3c2f
JH
2044int is_index_unborn(struct index_state *istate)
2045{
debed2a6 2046 return (!istate->cache_nr && !istate->timestamp.sec);
fa7b3c2f
JH
2047}
2048
4aab5b46 2049int discard_index(struct index_state *istate)
6d297f81 2050{
8e72d675
JM
2051 /*
2052 * Cache entries in istate->cache[] should have been allocated
2053 * from the memory pool associated with this index, or from an
2054 * associated split_index. There is no need to free individual
8616a2d0
JM
2055 * cache entries. validate_cache_entries can detect when this
2056 * assertion does not hold.
8e72d675 2057 */
8616a2d0 2058 validate_cache_entries(istate);
debed2a6 2059
cfc5789a 2060 resolve_undo_clear_index(istate);
4aab5b46
JH
2061 istate->cache_nr = 0;
2062 istate->cache_changed = 0;
fba2f38a
KB
2063 istate->timestamp.sec = 0;
2064 istate->timestamp.nsec = 0;
2092678c 2065 free_name_hash(istate);
4aab5b46 2066 cache_tree_free(&(istate->cache_tree));
913e0e99 2067 istate->initialized = 0;
6a83d902 2068 FREE_AND_NULL(istate->cache);
a0fc4db0 2069 istate->cache_alloc = 0;
5fc2fc8f 2070 discard_split_index(istate);
f9e6c649
NTND
2071 free_untracked_cache(istate->untracked);
2072 istate->untracked = NULL;
8e72d675
JM
2073
2074 if (istate->ce_mem_pool) {
8616a2d0 2075 mem_pool_discard(istate->ce_mem_pool, should_validate_cache_entries());
8e72d675
JM
2076 istate->ce_mem_pool = NULL;
2077 }
2078
7a51ed66 2079 return 0;
6d297f81
JS
2080}
2081
8616a2d0
JM
2082/*
2083 * Validate the cache entries of this index.
2084 * All cache entries associated with this index
2085 * should have been allocated by the memory pool
2086 * associated with this index, or by a referenced
2087 * split index.
2088 */
2089void validate_cache_entries(const struct index_state *istate)
2090{
2091 int i;
2092
2093 if (!should_validate_cache_entries() ||!istate || !istate->initialized)
2094 return;
2095
2096 for (i = 0; i < istate->cache_nr; i++) {
2097 if (!istate) {
2098 die("internal error: cache entry is not allocated from expected memory pool");
2099 } else if (!istate->ce_mem_pool ||
2100 !mem_pool_contains(istate->ce_mem_pool, istate->cache[i])) {
2101 if (!istate->split_index ||
2102 !istate->split_index->base ||
2103 !istate->split_index->base->ce_mem_pool ||
2104 !mem_pool_contains(istate->split_index->base->ce_mem_pool, istate->cache[i])) {
2105 die("internal error: cache entry is not allocated from expected memory pool");
2106 }
2107 }
2108 }
2109
2110 if (istate->split_index)
2111 validate_cache_entries(istate->split_index->base);
2112}
2113
d1f128b0 2114int unmerged_index(const struct index_state *istate)
94a5728c
DB
2115{
2116 int i;
2117 for (i = 0; i < istate->cache_nr; i++) {
2118 if (ce_stage(istate->cache[i]))
2119 return 1;
2120 }
2121 return 0;
2122}
2123
e1f8694f
EN
2124int index_has_changes(const struct index_state *istate,
2125 struct tree *tree,
2126 struct strbuf *sb)
cffbfad5 2127{
e1f8694f 2128 struct object_id cmp;
cffbfad5
EN
2129 int i;
2130
1b9fbefb
EN
2131 if (istate != &the_index) {
2132 BUG("index_has_changes cannot yet accept istate != &the_index; do_diff_cache needs updating first.");
2133 }
e1f8694f
EN
2134 if (tree)
2135 cmp = tree->object.oid;
2136 if (tree || !get_oid_tree("HEAD", &cmp)) {
cffbfad5
EN
2137 struct diff_options opt;
2138
2139 diff_setup(&opt);
2140 opt.flags.exit_with_status = 1;
2141 if (!sb)
2142 opt.flags.quick = 1;
e1f8694f 2143 do_diff_cache(&cmp, &opt);
cffbfad5
EN
2144 diffcore_std(&opt);
2145 for (i = 0; sb && i < diff_queued_diff.nr; i++) {
2146 if (i)
2147 strbuf_addch(sb, ' ');
2148 strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);
2149 }
2150 diff_flush(&opt);
2151 return opt.flags.has_changes != 0;
2152 } else {
1b9fbefb 2153 for (i = 0; sb && i < istate->cache_nr; i++) {
cffbfad5
EN
2154 if (i)
2155 strbuf_addch(sb, ' ');
1b9fbefb 2156 strbuf_addstr(sb, istate->cache[i]->name);
cffbfad5 2157 }
1b9fbefb 2158 return !!istate->cache_nr;
cffbfad5
EN
2159 }
2160}
2161
4990aadc 2162#define WRITE_BUFFER_SIZE 8192
bf0f910d 2163static unsigned char write_buffer[WRITE_BUFFER_SIZE];
4990aadc
LT
2164static unsigned long write_buffer_len;
2165
aab61359 2166static int ce_write_flush(git_hash_ctx *context, int fd)
6015c28b
JH
2167{
2168 unsigned int buffered = write_buffer_len;
2169 if (buffered) {
aab61359 2170 the_hash_algo->update_fn(context, write_buffer, buffered);
06f46f23 2171 if (write_in_full(fd, write_buffer, buffered) < 0)
6015c28b
JH
2172 return -1;
2173 write_buffer_len = 0;
2174 }
2175 return 0;
2176}
2177
aab61359 2178static int ce_write(git_hash_ctx *context, int fd, void *data, unsigned int len)
4990aadc
LT
2179{
2180 while (len) {
2181 unsigned int buffered = write_buffer_len;
2182 unsigned int partial = WRITE_BUFFER_SIZE - buffered;
2183 if (partial > len)
2184 partial = len;
2185 memcpy(write_buffer + buffered, data, partial);
2186 buffered += partial;
2187 if (buffered == WRITE_BUFFER_SIZE) {
6015c28b
JH
2188 write_buffer_len = buffered;
2189 if (ce_write_flush(context, fd))
4990aadc
LT
2190 return -1;
2191 buffered = 0;
2192 }
2193 write_buffer_len = buffered;
2194 len -= partial;
1d7f171c 2195 data = (char *) data + partial;
a6080a0a
JH
2196 }
2197 return 0;
4990aadc
LT
2198}
2199
3b1d9e04
BP
2200static int write_index_ext_header(git_hash_ctx *context, git_hash_ctx *eoie_context,
2201 int fd, unsigned int ext, unsigned int sz)
bad68ec9
JH
2202{
2203 ext = htonl(ext);
2204 sz = htonl(sz);
3b1d9e04
BP
2205 if (eoie_context) {
2206 the_hash_algo->update_fn(eoie_context, &ext, 4);
2207 the_hash_algo->update_fn(eoie_context, &sz, 4);
2208 }
968a1d65
DR
2209 return ((ce_write(context, fd, &ext, 4) < 0) ||
2210 (ce_write(context, fd, &sz, 4) < 0)) ? -1 : 0;
bad68ec9
JH
2211}
2212
aab61359 2213static int ce_flush(git_hash_ctx *context, int fd, unsigned char *hash)
4990aadc
LT
2214{
2215 unsigned int left = write_buffer_len;
ca9be054 2216
4990aadc
LT
2217 if (left) {
2218 write_buffer_len = 0;
aab61359 2219 the_hash_algo->update_fn(context, write_buffer, left);
4990aadc 2220 }
ca9be054 2221
aab61359 2222 /* Flush first if not enough space for hash signature */
2223 if (left + the_hash_algo->rawsz > WRITE_BUFFER_SIZE) {
06f46f23 2224 if (write_in_full(fd, write_buffer, left) < 0)
2c865d9a
QH
2225 return -1;
2226 left = 0;
2227 }
2228
aab61359 2229 /* Append the hash signature at the end */
2230 the_hash_algo->final_fn(write_buffer + left, context);
2231 hashcpy(hash, write_buffer + left);
2232 left += the_hash_algo->rawsz;
06f46f23 2233 return (write_in_full(fd, write_buffer, left) < 0) ? -1 : 0;
4990aadc
LT
2234}
2235
407c8eb0
JH
2236static void ce_smudge_racily_clean_entry(struct cache_entry *ce)
2237{
2238 /*
2239 * The only thing we care about in this function is to smudge the
2240 * falsely clean entry due to touch-update-touch race, so we leave
2241 * everything else as they are. We are called for entries whose
c21d39d7 2242 * ce_stat_data.sd_mtime match the index file mtime.
c70115b4
JH
2243 *
2244 * Note that this actually does not do much for gitlinks, for
2245 * which ce_match_stat_basic() always goes to the actual
2246 * contents. The caller checks with is_racy_timestamp() which
2247 * always says "no" for gitlinks, so we are not called for them ;-)
407c8eb0
JH
2248 */
2249 struct stat st;
2250
2251 if (lstat(ce->name, &st) < 0)
2252 return;
2253 if (ce_match_stat_basic(ce, &st))
2254 return;
2255 if (ce_modified_check_fs(ce, &st)) {
4b3511b0
JH
2256 /* This is "racily clean"; smudge it. Note that this
2257 * is a tricky code. At first glance, it may appear
2258 * that it can break with this sequence:
2259 *
2260 * $ echo xyzzy >frotz
2261 * $ git-update-index --add frotz
2262 * $ : >frotz
2263 * $ sleep 3
2264 * $ echo filfre >nitfol
2265 * $ git-update-index --add nitfol
2266 *
b7e58b17 2267 * but it does not. When the second update-index runs,
4b3511b0
JH
2268 * it notices that the entry "frotz" has the same timestamp
2269 * as index, and if we were to smudge it by resetting its
2270 * size to zero here, then the object name recorded
2271 * in index is the 6-byte file but the cached stat information
2272 * becomes zero --- which would then match what we would
a6080a0a 2273 * obtain from the filesystem next time we stat("frotz").
4b3511b0
JH
2274 *
2275 * However, the second update-index, before calling
2276 * this function, notices that the cached size is 6
2277 * bytes and what is on the filesystem is an empty
2278 * file, and never calls us, so the cached size information
2279 * for "frotz" stays 6 which does not match the filesystem.
2280 */
c21d39d7 2281 ce->ce_stat_data.sd_size = 0;
407c8eb0
JH
2282 }
2283}
2284
f136f7bf 2285/* Copy miscellaneous fields but not the name */
ce012deb 2286static void copy_cache_entry_to_ondisk(struct ondisk_cache_entry *ondisk,
f136f7bf 2287 struct cache_entry *ce)
7a51ed66 2288{
b60e188c
TG
2289 short flags;
2290
c21d39d7
MH
2291 ondisk->ctime.sec = htonl(ce->ce_stat_data.sd_ctime.sec);
2292 ondisk->mtime.sec = htonl(ce->ce_stat_data.sd_mtime.sec);
2293 ondisk->ctime.nsec = htonl(ce->ce_stat_data.sd_ctime.nsec);
2294 ondisk->mtime.nsec = htonl(ce->ce_stat_data.sd_mtime.nsec);
2295 ondisk->dev = htonl(ce->ce_stat_data.sd_dev);
2296 ondisk->ino = htonl(ce->ce_stat_data.sd_ino);
7a51ed66 2297 ondisk->mode = htonl(ce->ce_mode);
c21d39d7
MH
2298 ondisk->uid = htonl(ce->ce_stat_data.sd_uid);
2299 ondisk->gid = htonl(ce->ce_stat_data.sd_gid);
2300 ondisk->size = htonl(ce->ce_stat_data.sd_size);
99d1a986 2301 hashcpy(ondisk->sha1, ce->oid.hash);
b60e188c 2302
ce51bf09 2303 flags = ce->ce_flags & ~CE_NAMEMASK;
b60e188c
TG
2304 flags |= (ce_namelen(ce) >= CE_NAMEMASK ? CE_NAMEMASK : ce_namelen(ce));
2305 ondisk->flags = htons(flags);
06aaaa0b
NTND
2306 if (ce->ce_flags & CE_EXTENDED) {
2307 struct ondisk_cache_entry_extended *ondisk2;
2308 ondisk2 = (struct ondisk_cache_entry_extended *)ondisk;
2309 ondisk2->flags2 = htons((ce->ce_flags & CE_EXTENDED_FLAGS) >> 16);
f136f7bf
JH
2310 }
2311}
2312
aab61359 2313static int ce_write_entry(git_hash_ctx *c, int fd, struct cache_entry *ce,
ce012deb 2314 struct strbuf *previous_name, struct ondisk_cache_entry *ondisk)
f136f7bf 2315{
9d227781 2316 int size;
f136f7bf 2317 int result;
00a4b035
RJ
2318 unsigned int saved_namelen;
2319 int stripped_name = 0;
ce012deb 2320 static unsigned char padding[8] = { 0x00 };
f136f7bf 2321
b3c96fb1
NTND
2322 if (ce->ce_flags & CE_STRIP_NAME) {
2323 saved_namelen = ce_namelen(ce);
2324 ce->ce_namelen = 0;
00a4b035 2325 stripped_name = 1;
b3c96fb1
NTND
2326 }
2327
ce012deb
KW
2328 if (ce->ce_flags & CE_EXTENDED)
2329 size = offsetof(struct ondisk_cache_entry_extended, name);
2330 else
2331 size = offsetof(struct ondisk_cache_entry, name);
2332
9d227781 2333 if (!previous_name) {
ce012deb
KW
2334 int len = ce_namelen(ce);
2335 copy_cache_entry_to_ondisk(ondisk, ce);
2336 result = ce_write(c, fd, ondisk, size);
2337 if (!result)
2338 result = ce_write(c, fd, ce->name, len);
2339 if (!result)
2340 result = ce_write(c, fd, padding, align_padding_size(size, len));
9d227781
JH
2341 } else {
2342 int common, to_remove, prefix_size;
2343 unsigned char to_remove_vi[16];
2344 for (common = 0;
2345 (ce->name[common] &&
2346 common < previous_name->len &&
2347 ce->name[common] == previous_name->buf[common]);
2348 common++)
2349 ; /* still matching */
2350 to_remove = previous_name->len - common;
2351 prefix_size = encode_varint(to_remove, to_remove_vi);
2352
ce012deb
KW
2353 copy_cache_entry_to_ondisk(ondisk, ce);
2354 result = ce_write(c, fd, ondisk, size);
2355 if (!result)
2356 result = ce_write(c, fd, to_remove_vi, prefix_size);
2357 if (!result)
0b90b881
TG
2358 result = ce_write(c, fd, ce->name + common, ce_namelen(ce) - common);
2359 if (!result)
2360 result = ce_write(c, fd, padding, 1);
9d227781
JH
2361
2362 strbuf_splice(previous_name, common, to_remove,
2363 ce->name + common, ce_namelen(ce) - common);
06aaaa0b 2364 }
00a4b035 2365 if (stripped_name) {
b3c96fb1
NTND
2366 ce->ce_namelen = saved_namelen;
2367 ce->ce_flags &= ~CE_STRIP_NAME;
2368 }
7a51ed66 2369
59efba64 2370 return result;
7a51ed66
LT
2371}
2372
426ddeea
YM
2373/*
2374 * This function verifies if index_state has the correct sha1 of the
2375 * index file. Don't die if we have any other failure, just return 0.
2376 */
2377static int verify_index_from(const struct index_state *istate, const char *path)
2378{
2379 int fd;
2380 ssize_t n;
2381 struct stat st;
aab61359 2382 unsigned char hash[GIT_MAX_RAWSZ];
426ddeea
YM
2383
2384 if (!istate->initialized)
2385 return 0;
2386
2387 fd = open(path, O_RDONLY);
2388 if (fd < 0)
2389 return 0;
2390
2391 if (fstat(fd, &st))
2392 goto out;
2393
aab61359 2394 if (st.st_size < sizeof(struct cache_header) + the_hash_algo->rawsz)
426ddeea
YM
2395 goto out;
2396
aab61359 2397 n = pread_in_full(fd, hash, the_hash_algo->rawsz, st.st_size - the_hash_algo->rawsz);
2398 if (n != the_hash_algo->rawsz)
426ddeea
YM
2399 goto out;
2400
67947c34 2401 if (!hasheq(istate->oid.hash, hash))
426ddeea
YM
2402 goto out;
2403
2404 close(fd);
2405 return 1;
2406
2407out:
2408 close(fd);
2409 return 0;
2410}
2411
2412static int verify_index(const struct index_state *istate)
2413{
2414 return verify_index_from(istate, get_index_file());
2415}
2416
483fbe2b
JH
2417static int has_racy_timestamp(struct index_state *istate)
2418{
2419 int entries = istate->cache_nr;
2420 int i;
2421
2422 for (i = 0; i < entries; i++) {
2423 struct cache_entry *ce = istate->cache[i];
2424 if (is_racy_timestamp(istate, ce))
2425 return 1;
2426 }
2427 return 0;
2428}
2429
ccdc4ec3
JH
2430void update_index_if_able(struct index_state *istate, struct lock_file *lockfile)
2431{
483fbe2b 2432 if ((istate->cache_changed || has_racy_timestamp(istate)) &&
df60cf57
2433 verify_index(istate))
2434 write_locked_index(istate, lockfile, COMMIT_LOCK);
b74c90fb
2435 else
2436 rollback_lock_file(lockfile);
ccdc4ec3
JH
2437}
2438
812d6b00
2439/*
2440 * On success, `tempfile` is closed. If it is the temporary file
2441 * of a `struct lock_file`, we will therefore effectively perform
2442 * a 'close_lock_file_gently()`. Since that is an implementation
2443 * detail of lockfiles, callers of `do_write_index()` should not
2444 * rely on it.
2445 */
9f41c7a6 2446static int do_write_index(struct index_state *istate, struct tempfile *tempfile,
c18b80a0 2447 int strip_extensions)
197ee8c9 2448{
ca54d9ba 2449 uint64_t start = getnanotime();
9f41c7a6 2450 int newfd = tempfile->fd;
3b1d9e04 2451 git_hash_ctx c, eoie_c;
197ee8c9 2452 struct cache_header hdr;
b50386c7 2453 int i, err = 0, removed, extended, hdr_version;
4aab5b46
JH
2454 struct cache_entry **cache = istate->cache;
2455 int entries = istate->cache_nr;
e1afca4f 2456 struct stat st;
ce012deb 2457 struct ondisk_cache_entry_extended ondisk;
9d227781 2458 struct strbuf previous_name_buf = STRBUF_INIT, *previous_name;
4bddd983 2459 int drop_cache_tree = istate->drop_cache_tree;
3b1d9e04 2460 off_t offset;
025a0709 2461
06aaaa0b 2462 for (i = removed = extended = 0; i < entries; i++) {
7a51ed66 2463 if (cache[i]->ce_flags & CE_REMOVE)
025a0709 2464 removed++;
197ee8c9 2465
06aaaa0b
NTND
2466 /* reduce extended entries if possible */
2467 cache[i]->ce_flags &= ~CE_EXTENDED;
2468 if (cache[i]->ce_flags & CE_EXTENDED_FLAGS) {
2469 extended++;
2470 cache[i]->ce_flags |= CE_EXTENDED;
2471 }
2472 }
2473
d6e3c181 2474 if (!istate->version) {
136347d7 2475 istate->version = get_index_format_default();
4c2db938 2476 if (git_env_bool("GIT_TEST_SPLIT_INDEX", 0))
d6e3c181
NTND
2477 init_split_index(istate);
2478 }
9d227781
JH
2479
2480 /* demote version 3 to version 2 when the latter suffices */
2481 if (istate->version == 3 || istate->version == 2)
2482 istate->version = extended ? 3 : 2;
2483
2484 hdr_version = istate->version;
2485
ccc4feb5 2486 hdr.hdr_signature = htonl(CACHE_SIGNATURE);
9d227781 2487 hdr.hdr_version = htonl(hdr_version);
025a0709 2488 hdr.hdr_entries = htonl(entries - removed);
197ee8c9 2489
aab61359 2490 the_hash_algo->init_fn(&c);
ca9be054 2491 if (ce_write(&c, newfd, &hdr, sizeof(hdr)) < 0)
197ee8c9
LT
2492 return -1;
2493
3b1d9e04
BP
2494 offset = lseek(newfd, 0, SEEK_CUR);
2495 if (offset < 0)
2496 return -1;
2497 offset += write_buffer_len;
9d227781 2498 previous_name = (hdr_version == 4) ? &previous_name_buf : NULL;
ce012deb 2499
197ee8c9
LT
2500 for (i = 0; i < entries; i++) {
2501 struct cache_entry *ce = cache[i];
7a51ed66 2502 if (ce->ce_flags & CE_REMOVE)
aa16021e 2503 continue;
e06c43c7 2504 if (!ce_uptodate(ce) && is_racy_timestamp(istate, ce))
407c8eb0 2505 ce_smudge_racily_clean_entry(ce);
99d1a986 2506 if (is_null_oid(&ce->oid)) {
83bd7437
JK
2507 static const char msg[] = "cache entry has null sha1: %s";
2508 static int allow = -1;
2509
2510 if (allow < 0)
2511 allow = git_env_bool("GIT_ALLOW_NULL_SHA1", 0);
2512 if (allow)
2513 warning(msg, ce->name);
2514 else
b50386c7 2515 err = error(msg, ce->name);
a96d3cc3
JK
2516
2517 drop_cache_tree = 1;
83bd7437 2518 }
ce012deb 2519 if (ce_write_entry(&c, newfd, ce, previous_name, (struct ondisk_cache_entry *)&ondisk) < 0)
b50386c7
KW
2520 err = -1;
2521
2522 if (err)
2523 break;
197ee8c9 2524 }
9d227781 2525 strbuf_release(&previous_name_buf);
1af1c2b6 2526
b50386c7
KW
2527 if (err)
2528 return err;
2529
bad68ec9 2530 /* Write extension data here */
3b1d9e04
BP
2531 offset = lseek(newfd, 0, SEEK_CUR);
2532 if (offset < 0)
2533 return -1;
2534 offset += write_buffer_len;
2535 the_hash_algo->init_fn(&eoie_c);
2536
c18b80a0 2537 if (!strip_extensions && istate->split_index) {
5fc2fc8f
NTND
2538 struct strbuf sb = STRBUF_INIT;
2539
2540 err = write_link_extension(&sb, istate) < 0 ||
3b1d9e04 2541 write_index_ext_header(&c, &eoie_c, newfd, CACHE_EXT_LINK,
5fc2fc8f
NTND
2542 sb.len) < 0 ||
2543 ce_write(&c, newfd, sb.buf, sb.len) < 0;
2544 strbuf_release(&sb);
2545 if (err)
2546 return -1;
2547 }
a96d3cc3 2548 if (!strip_extensions && !drop_cache_tree && istate->cache_tree) {
f285a2d7 2549 struct strbuf sb = STRBUF_INIT;
1dffb8fa 2550
1dffb8fa 2551 cache_tree_write(&sb, istate->cache_tree);
3b1d9e04 2552 err = write_index_ext_header(&c, &eoie_c, newfd, CACHE_EXT_TREE, sb.len) < 0
1dffb8fa
PH
2553 || ce_write(&c, newfd, sb.buf, sb.len) < 0;
2554 strbuf_release(&sb);
2555 if (err)
bad68ec9 2556 return -1;
bad68ec9 2557 }
c18b80a0 2558 if (!strip_extensions && istate->resolve_undo) {
cfc5789a
JH
2559 struct strbuf sb = STRBUF_INIT;
2560
2561 resolve_undo_write(&sb, istate->resolve_undo);
3b1d9e04 2562 err = write_index_ext_header(&c, &eoie_c, newfd, CACHE_EXT_RESOLVE_UNDO,
cfc5789a
JH
2563 sb.len) < 0
2564 || ce_write(&c, newfd, sb.buf, sb.len) < 0;
2565 strbuf_release(&sb);
2566 if (err)
2567 return -1;
2568 }
83c094ad
NTND
2569 if (!strip_extensions && istate->untracked) {
2570 struct strbuf sb = STRBUF_INIT;
2571
2572 write_untracked_extension(&sb, istate->untracked);
3b1d9e04 2573 err = write_index_ext_header(&c, &eoie_c, newfd, CACHE_EXT_UNTRACKED,
83c094ad
NTND
2574 sb.len) < 0 ||
2575 ce_write(&c, newfd, sb.buf, sb.len) < 0;
2576 strbuf_release(&sb);
2577 if (err)
2578 return -1;
2579 }
883e248b
BP
2580 if (!strip_extensions && istate->fsmonitor_last_update) {
2581 struct strbuf sb = STRBUF_INIT;
2582
2583 write_fsmonitor_extension(&sb, istate);
3b1d9e04
BP
2584 err = write_index_ext_header(&c, &eoie_c, newfd, CACHE_EXT_FSMONITOR, sb.len) < 0
2585 || ce_write(&c, newfd, sb.buf, sb.len) < 0;
2586 strbuf_release(&sb);
2587 if (err)
2588 return -1;
2589 }
2590
2591 /*
2592 * CACHE_EXT_ENDOFINDEXENTRIES must be written as the last entry before the SHA1
2593 * so that it can be found and processed before all the index entries are
2594 * read. Write it out regardless of the strip_extensions parameter as we need it
2595 * when loading the shared index.
2596 */
2597 if (offset) {
2598 struct strbuf sb = STRBUF_INIT;
2599
2600 write_eoie_extension(&sb, &eoie_c, offset);
2601 err = write_index_ext_header(&c, NULL, newfd, CACHE_EXT_ENDOFINDEXENTRIES, sb.len) < 0
883e248b
BP
2602 || ce_write(&c, newfd, sb.buf, sb.len) < 0;
2603 strbuf_release(&sb);
2604 if (err)
2605 return -1;
2606 }
e1afca4f 2607
75691ea3 2608 if (ce_flush(&c, newfd, istate->oid.hash))
9f41c7a6 2609 return -1;
49bd0fc2
JK
2610 if (close_tempfile_gently(tempfile)) {
2611 error(_("could not close '%s'"), tempfile->filename.buf);
49bd0fc2
JK
2612 return -1;
2613 }
9f41c7a6 2614 if (stat(tempfile->filename.buf, &st))
e1afca4f 2615 return -1;
5bcf109c
KB
2616 istate->timestamp.sec = (unsigned int)st.st_mtime;
2617 istate->timestamp.nsec = ST_MTIME_NSEC(st);
ca54d9ba 2618 trace_performance_since(start, "write index, changed mask = %x", istate->cache_changed);
e1afca4f 2619 return 0;
197ee8c9 2620}
e46bbcf6 2621
626f35c8
NTND
2622void set_alternate_index_output(const char *name)
2623{
2624 alternate_index_output = name;
2625}
2626
2627static int commit_locked_index(struct lock_file *lk)
2628{
751baced
MH
2629 if (alternate_index_output)
2630 return commit_lock_file_to(lk, alternate_index_output);
2631 else
626f35c8 2632 return commit_lock_file(lk);
626f35c8
NTND
2633}
2634
03b86647
NTND
2635static int do_write_locked_index(struct index_state *istate, struct lock_file *lock,
2636 unsigned flags)
2637{
076aa2cb 2638 int ret = do_write_index(istate, lock->tempfile, 0);
03b86647
NTND
2639 if (ret)
2640 return ret;
03b86647
NTND
2641 if (flags & COMMIT_LOCK)
2642 return commit_locked_index(lock);
812d6b00 2643 return close_lock_file_gently(lock);
03b86647
NTND
2644}
2645
5fc2fc8f
NTND
2646static int write_split_index(struct index_state *istate,
2647 struct lock_file *lock,
2648 unsigned flags)
2649{
2650 int ret;
2651 prepare_to_write_split_index(istate);
2652 ret = do_write_locked_index(istate, lock, flags);
2653 finish_writing_split_index(istate);
2654 return ret;
2655}
2656
b9683722
CC
2657static const char *shared_index_expire = "2.weeks.ago";
2658
2659static unsigned long get_shared_index_expire_date(void)
2660{
2661 static unsigned long shared_index_expire_date;
2662 static int shared_index_expire_date_prepared;
2663
2664 if (!shared_index_expire_date_prepared) {
2665 git_config_get_expiry("splitindex.sharedindexexpire",
2666 &shared_index_expire);
2667 shared_index_expire_date = approxidate(shared_index_expire);
2668 shared_index_expire_date_prepared = 1;
2669 }
2670
2671 return shared_index_expire_date;
2672}
2673
2674static int should_delete_shared_index(const char *shared_index_path)
2675{
2676 struct stat st;
2677 unsigned long expiration;
2678
2679 /* Check timestamp */
2680 expiration = get_shared_index_expire_date();
2681 if (!expiration)
2682 return 0;
2683 if (stat(shared_index_path, &st))
78bde923 2684 return error_errno(_("could not stat '%s'"), shared_index_path);
b9683722
CC
2685 if (st.st_mtime > expiration)
2686 return 0;
2687
2688 return 1;
2689}
2690
2691static int clean_shared_index_files(const char *current_hex)
2692{
2693 struct dirent *de;
2694 DIR *dir = opendir(get_git_dir());
2695
2696 if (!dir)
2697 return error_errno(_("unable to open git dir: %s"), get_git_dir());
2698
2699 while ((de = readdir(dir)) != NULL) {
2700 const char *sha1_hex;
2701 const char *shared_index_path;
2702 if (!skip_prefix(de->d_name, "sharedindex.", &sha1_hex))
2703 continue;
2704 if (!strcmp(sha1_hex, current_hex))
2705 continue;
2706 shared_index_path = git_path("%s", de->d_name);
2707 if (should_delete_shared_index(shared_index_path) > 0 &&
2708 unlink(shared_index_path))
2709 warning_errno(_("unable to unlink: %s"), shared_index_path);
2710 }
2711 closedir(dir);
2712
2713 return 0;
2714}
2715
a0a96756 2716static int write_shared_index(struct index_state *istate,
59f9d2dd 2717 struct tempfile **temp)
c18b80a0
NTND
2718{
2719 struct split_index *si = istate->split_index;
076aa2cb 2720 int ret;
c18b80a0 2721
c18b80a0 2722 move_cache_to_base_index(istate);
7db2d08c 2723 ret = do_write_index(si->base, *temp, 1);
59f9d2dd 2724 if (ret)
c18b80a0 2725 return ret;
7db2d08c 2726 ret = adjust_shared_perm(get_tempfile_path(*temp));
df801f3f 2727 if (ret) {
7db2d08c 2728 error("cannot fix permission bits on %s", get_tempfile_path(*temp));
df801f3f
CC
2729 return ret;
2730 }
7db2d08c 2731 ret = rename_tempfile(temp,
75691ea3 2732 git_path("sharedindex.%s", oid_to_hex(&si->base->oid)));
b9683722 2733 if (!ret) {
75691ea3 2734 oidcpy(&si->base_oid, &si->base->oid);
2735 clean_shared_index_files(oid_to_hex(&si->base->oid));
b9683722
CC
2736 }
2737
c18b80a0
NTND
2738 return ret;
2739}
2740
e6a1dd77
CC
2741static const int default_max_percent_split_change = 20;
2742
2743static int too_many_not_shared_entries(struct index_state *istate)
2744{
2745 int i, not_shared = 0;
2746 int max_split = git_config_get_max_percent_split_change();
2747
2748 switch (max_split) {
2749 case -1:
2750 /* not or badly configured: use the default value */
2751 max_split = default_max_percent_split_change;
2752 break;
2753 case 0:
2754 return 1; /* 0% means always write a new shared index */
2755 case 100:
2756 return 0; /* 100% means never write a new shared index */
2757 default:
2758 break; /* just use the configured value */
2759 }
2760
2761 /* Count not shared entries */
2762 for (i = 0; i < istate->cache_nr; i++) {
2763 struct cache_entry *ce = istate->cache[i];
2764 if (!ce->index)
2765 not_shared++;
2766 }
2767
2768 return (int64_t)istate->cache_nr * max_split < (int64_t)not_shared * 100;
2769}
2770
03b86647
NTND
2771int write_locked_index(struct index_state *istate, struct lock_file *lock,
2772 unsigned flags)
2773{
0d59ffb4 2774 int new_shared_index, ret;
5fc2fc8f
NTND
2775 struct split_index *si = istate->split_index;
2776
4592e608
NTND
2777 if (git_env_bool("GIT_TEST_CHECK_CACHE_TREE", 0))
2778 cache_tree_verify(istate);
2779
61000814
2780 if ((flags & SKIP_IF_UNCHANGED) && !istate->cache_changed) {
2781 if (flags & COMMIT_LOCK)
2782 rollback_lock_file(lock);
2783 return 0;
2784 }
2785
3bd28eb2
AV
2786 if (istate->fsmonitor_last_update)
2787 fill_fsmonitor_bitmap(istate);
2788
5165dd59
NTND
2789 if (!si || alternate_index_output ||
2790 (istate->cache_changed & ~EXTMASK)) {
5fc2fc8f 2791 if (si)
2182abd9 2792 oidclr(&si->base_oid);
df60cf57
2793 ret = do_write_locked_index(istate, lock, flags);
2794 goto out;
5fc2fc8f
NTND
2795 }
2796
4c2db938 2797 if (git_env_bool("GIT_TEST_SPLIT_INDEX", 0)) {
2182abd9 2798 int v = si->base_oid.hash[0];
d6e3c181
NTND
2799 if ((v & 15) < 6)
2800 istate->cache_changed |= SPLIT_INDEX_ORDERED;
2801 }
e6a1dd77
CC
2802 if (too_many_not_shared_entries(istate))
2803 istate->cache_changed |= SPLIT_INDEX_ORDERED;
0d59ffb4
CC
2804
2805 new_shared_index = istate->cache_changed & SPLIT_INDEX_ORDERED;
2806
2807 if (new_shared_index) {
59f9d2dd
NTND
2808 struct tempfile *temp;
2809 int saved_errno;
2810
2811 temp = mks_tempfile(git_path("sharedindex_XXXXXX"));
2812 if (!temp) {
2182abd9 2813 oidclr(&si->base_oid);
59f9d2dd 2814 ret = do_write_locked_index(istate, lock, flags);
ef5b3a6c
NTND
2815 goto out;
2816 }
2817 ret = write_shared_index(istate, &temp);
59f9d2dd
NTND
2818
2819 saved_errno = errno;
2820 if (is_tempfile_active(temp))
2821 delete_tempfile(&temp);
2822 errno = saved_errno;
2823
c18b80a0 2824 if (ret)
df60cf57 2825 goto out;
c18b80a0
NTND
2826 }
2827
0d59ffb4
CC
2828 ret = write_split_index(istate, lock, flags);
2829
2830 /* Freshen the shared index only if the split-index was written */
a125a223
TG
2831 if (!ret && !new_shared_index) {
2832 const char *shared_index = git_path("sharedindex.%s",
2182abd9 2833 oid_to_hex(&si->base_oid));
a125a223
TG
2834 freshen_shared_index(shared_index, 1);
2835 }
0d59ffb4 2836
df60cf57
2837out:
2838 if (flags & COMMIT_LOCK)
2839 rollback_lock_file(lock);
0d59ffb4 2840 return ret;
03b86647
NTND
2841}
2842
e46bbcf6
MV
2843/*
2844 * Read the index file that is potentially unmerged into given
ad376204
EN
2845 * index_state, dropping any unmerged entries to stage #0 (potentially
2846 * resulting in a path appearing as both a file and a directory in the
2847 * index; the caller is responsible to clear out the extra entries
2848 * before writing the index to a tree). Returns true if the index is
2849 * unmerged. Callers who want to refuse to work from an unmerged
2850 * state can call this and check its return value, instead of calling
2851 * read_cache().
e46bbcf6
MV
2852 */
2853int read_index_unmerged(struct index_state *istate)
2854{
2855 int i;
d1a43f2a 2856 int unmerged = 0;
e46bbcf6
MV
2857
2858 read_index(istate);
e46bbcf6
MV
2859 for (i = 0; i < istate->cache_nr; i++) {
2860 struct cache_entry *ce = istate->cache[i];
d1a43f2a 2861 struct cache_entry *new_ce;
a849735b 2862 int len;
d1a43f2a
JH
2863
2864 if (!ce_stage(ce))
e46bbcf6 2865 continue;
d1a43f2a 2866 unmerged = 1;
68c4f6a5 2867 len = ce_namelen(ce);
a849735b 2868 new_ce = make_empty_cache_entry(istate, len);
d1a43f2a 2869 memcpy(new_ce->name, ce->name, len);
b60e188c
TG
2870 new_ce->ce_flags = create_ce_flags(0) | CE_CONFLICTED;
2871 new_ce->ce_namelen = len;
d1a43f2a 2872 new_ce->ce_mode = ce->ce_mode;
ad376204 2873 if (add_index_entry(istate, new_ce, ADD_CACHE_SKIP_DFCHECK))
d1a43f2a 2874 return error("%s: cannot drop to stage #0",
5699d17e 2875 new_ce->name);
e46bbcf6 2876 }
d1a43f2a 2877 return unmerged;
e46bbcf6 2878}
041aee31 2879
98fa4738
JK
2880/*
2881 * Returns 1 if the path is an "other" path with respect to
2882 * the index; that is, the path is not mentioned in the index at all,
2883 * either as a file, a directory with some files in the index,
2884 * or as an unmerged entry.
2885 *
2886 * We helpfully remove a trailing "/" from directories so that
2887 * the output of read_directory can be used as-is.
2888 */
2889int index_name_is_other(const struct index_state *istate, const char *name,
2890 int namelen)
2891{
2892 int pos;
2893 if (namelen && name[namelen - 1] == '/')
2894 namelen--;
2895 pos = index_name_pos(istate, name, namelen);
2896 if (0 <= pos)
2897 return 0; /* exact match */
2898 pos = -pos - 1;
2899 if (pos < istate->cache_nr) {
2900 struct cache_entry *ce = istate->cache[pos];
2901 if (ce_namelen(ce) == namelen &&
2902 !memcmp(ce->name, name, namelen))
2903 return 0; /* Yup, this one exists unmerged */
2904 }
2905 return 1;
2906}
29fb37b2 2907
87542508
BW
2908void *read_blob_data_from_index(const struct index_state *istate,
2909 const char *path, unsigned long *size)
29fb37b2
LF
2910{
2911 int pos, len;
2912 unsigned long sz;
2913 enum object_type type;
2914 void *data;
2915
2916 len = strlen(path);
2917 pos = index_name_pos(istate, path, len);
2918 if (pos < 0) {
2919 /*
2920 * We might be in the middle of a merge, in which
2921 * case we would read stage #2 (ours).
2922 */
2923 int i;
2924 for (i = -pos - 1;
2925 (pos < 0 && i < istate->cache_nr &&
2926 !strcmp(istate->cache[i]->name, path));
2927 i++)
2928 if (ce_stage(istate->cache[i]) == 2)
2929 pos = i;
2930 }
2931 if (pos < 0)
2932 return NULL;
b4f5aca4 2933 data = read_object_file(&istate->cache[pos]->oid, &type, &sz);
29fb37b2
LF
2934 if (!data || type != OBJ_BLOB) {
2935 free(data);
2936 return NULL;
2937 }
ff366825
LF
2938 if (size)
2939 *size = sz;
29fb37b2
LF
2940 return data;
2941}
38612532
MH
2942
2943void stat_validity_clear(struct stat_validity *sv)
2944{
6a83d902 2945 FREE_AND_NULL(sv->sd);
38612532
MH
2946}
2947
2948int stat_validity_check(struct stat_validity *sv, const char *path)
2949{
2950 struct stat st;
2951
2952 if (stat(path, &st) < 0)
2953 return sv->sd == NULL;
2954 if (!sv->sd)
2955 return 0;
2956 return S_ISREG(st.st_mode) && !match_stat_data(sv->sd, &st);
2957}
2958
2959void stat_validity_update(struct stat_validity *sv, int fd)
2960{
2961 struct stat st;
2962
2963 if (fstat(fd, &st) < 0 || !S_ISREG(st.st_mode))
2964 stat_validity_clear(sv);
2965 else {
2966 if (!sv->sd)
2967 sv->sd = xcalloc(1, sizeof(struct stat_data));
2968 fill_stat_data(sv->sd, &st);
2969 }
2970}
edf3b905
DT
2971
2972void move_index_extensions(struct index_state *dst, struct index_state *src)
2973{
2974 dst->untracked = src->untracked;
2975 src->untracked = NULL;
836ef2b6
NTND
2976 dst->cache_tree = src->cache_tree;
2977 src->cache_tree = NULL;
edf3b905 2978}
a849735b 2979
8e72d675
JM
2980struct cache_entry *dup_cache_entry(const struct cache_entry *ce,
2981 struct index_state *istate)
2982{
2983 unsigned int size = ce_size(ce);
2984 int mem_pool_allocated;
2985 struct cache_entry *new_entry = make_empty_cache_entry(istate, ce_namelen(ce));
2986 mem_pool_allocated = new_entry->mem_pool_allocated;
2987
2988 memcpy(new_entry, ce, size);
2989 new_entry->mem_pool_allocated = mem_pool_allocated;
2990 return new_entry;
2991}
2992
a849735b
JM
2993void discard_cache_entry(struct cache_entry *ce)
2994{
8616a2d0
JM
2995 if (ce && should_validate_cache_entries())
2996 memset(ce, 0xCD, cache_entry_size(ce->ce_namelen));
2997
8e72d675
JM
2998 if (ce && ce->mem_pool_allocated)
2999 return;
3000
a849735b
JM
3001 free(ce);
3002}
8616a2d0
JM
3003
3004int should_validate_cache_entries(void)
3005{
3006 static int validate_index_cache_entries = -1;
3007
3008 if (validate_index_cache_entries < 0) {
3009 if (getenv("GIT_TEST_VALIDATE_INDEX_CACHE_ENTRIES"))
3010 validate_index_cache_entries = 1;
3011 else
3012 validate_index_cache_entries = 0;
3013 }
3014
3015 return validate_index_cache_entries;
3016}
3b1d9e04
BP
3017
3018#define EOIE_SIZE (4 + GIT_SHA1_RAWSZ) /* <4-byte offset> + <20-byte hash> */
3019#define EOIE_SIZE_WITH_HEADER (4 + 4 + EOIE_SIZE) /* <4-byte signature> + <4-byte length> + EOIE_SIZE */
3020
3021static size_t read_eoie_extension(const char *mmap, size_t mmap_size)
3022{
3023 /*
3024 * The end of index entries (EOIE) extension is guaranteed to be last
3025 * so that it can be found by scanning backwards from the EOF.
3026 *
3027 * "EOIE"
3028 * <4-byte length>
3029 * <4-byte offset>
3030 * <20-byte hash>
3031 */
3032 const char *index, *eoie;
3033 uint32_t extsize;
3034 size_t offset, src_offset;
3035 unsigned char hash[GIT_MAX_RAWSZ];
3036 git_hash_ctx c;
3037
3038 /* ensure we have an index big enough to contain an EOIE extension */
3039 if (mmap_size < sizeof(struct cache_header) + EOIE_SIZE_WITH_HEADER + the_hash_algo->rawsz)
3040 return 0;
3041
3042 /* validate the extension signature */
3043 index = eoie = mmap + mmap_size - EOIE_SIZE_WITH_HEADER - the_hash_algo->rawsz;
3044 if (CACHE_EXT(index) != CACHE_EXT_ENDOFINDEXENTRIES)
3045 return 0;
3046 index += sizeof(uint32_t);
3047
3048 /* validate the extension size */
3049 extsize = get_be32(index);
3050 if (extsize != EOIE_SIZE)
3051 return 0;
3052 index += sizeof(uint32_t);
3053
3054 /*
3055 * Validate the offset we're going to look for the first extension
3056 * signature is after the index header and before the eoie extension.
3057 */
3058 offset = get_be32(index);
3059 if (mmap + offset < mmap + sizeof(struct cache_header))
3060 return 0;
3061 if (mmap + offset >= eoie)
3062 return 0;
3063 index += sizeof(uint32_t);
3064
3065 /*
3066 * The hash is computed over extension types and their sizes (but not
3067 * their contents). E.g. if we have "TREE" extension that is N-bytes
3068 * long, "REUC" extension that is M-bytes long, followed by "EOIE",
3069 * then the hash would be:
3070 *
3071 * SHA-1("TREE" + <binary representation of N> +
3072 * "REUC" + <binary representation of M>)
3073 */
3074 src_offset = offset;
3075 the_hash_algo->init_fn(&c);
3076 while (src_offset < mmap_size - the_hash_algo->rawsz - EOIE_SIZE_WITH_HEADER) {
3077 /* After an array of active_nr index entries,
3078 * there can be arbitrary number of extended
3079 * sections, each of which is prefixed with
3080 * extension name (4-byte) and section length
3081 * in 4-byte network byte order.
3082 */
3083 uint32_t extsize;
3084 memcpy(&extsize, mmap + src_offset + 4, 4);
3085 extsize = ntohl(extsize);
3086
3087 /* verify the extension size isn't so large it will wrap around */
3088 if (src_offset + 8 + extsize < src_offset)
3089 return 0;
3090
3091 the_hash_algo->update_fn(&c, mmap + src_offset, 8);
3092
3093 src_offset += 8;
3094 src_offset += extsize;
3095 }
3096 the_hash_algo->final_fn(hash, &c);
3097 if (!hasheq(hash, (const unsigned char *)index))
3098 return 0;
3099
3100 /* Validate that the extension offsets returned us back to the eoie extension. */
3101 if (src_offset != mmap_size - the_hash_algo->rawsz - EOIE_SIZE_WITH_HEADER)
3102 return 0;
3103
3104 return offset;
3105}
3106
3107static void write_eoie_extension(struct strbuf *sb, git_hash_ctx *eoie_context, size_t offset)
3108{
3109 uint32_t buffer;
3110 unsigned char hash[GIT_MAX_RAWSZ];
3111
3112 /* offset */
3113 put_be32(&buffer, offset);
3114 strbuf_add(sb, &buffer, sizeof(uint32_t));
3115
3116 /* hash */
3117 the_hash_algo->final_fn(hash, eoie_context);
3118 strbuf_add(sb, hash, the_hash_algo->rawsz);
3119}