Documentation/technical/racy-git.txt
[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 */
e83c5163 6#include "cache.h"
bad68ec9
JH
7#include "cache-tree.h"
8
9/* Index extensions.
10 *
11 * The first letter should be 'A'..'Z' for extensions that are not
12 * necessary for a correct operation (i.e. optimization data).
13 * When new extensions are added that _needs_ to be understood in
14 * order to correctly interpret the index file, pick character that
15 * is outside the range, to cause the reader to abort.
16 */
17
18#define CACHE_EXT(s) ( (s[0]<<24)|(s[1]<<16)|(s[2]<<8)|(s[3]) )
19#define CACHE_EXT_TREE 0x54524545 /* "TREE" */
e83c5163 20
e83c5163 21struct cache_entry **active_cache = NULL;
29e4d363 22static time_t index_file_timestamp;
ee267527 23unsigned int active_nr = 0, active_alloc = 0, active_cache_changed = 0;
e83c5163 24
bad68ec9
JH
25struct cache_tree *active_cache_tree = NULL;
26
8fd2cb40
JS
27int cache_errno = 0;
28
29static void *cache_mmap = NULL;
30static size_t cache_mmap_size = 0;
31
415e96c8
JH
32/*
33 * This only updates the "non-critical" parts of the directory
34 * cache, ie the parts that aren't tracked by GIT, and only used
35 * to validate the cache.
36 */
37void fill_stat_cache_info(struct cache_entry *ce, struct stat *st)
38{
39 ce->ce_ctime.sec = htonl(st->st_ctime);
40 ce->ce_mtime.sec = htonl(st->st_mtime);
2cb45e95 41#ifdef USE_NSEC
415e96c8
JH
42 ce->ce_ctime.nsec = htonl(st->st_ctim.tv_nsec);
43 ce->ce_mtime.nsec = htonl(st->st_mtim.tv_nsec);
44#endif
45 ce->ce_dev = htonl(st->st_dev);
46 ce->ce_ino = htonl(st->st_ino);
47 ce->ce_uid = htonl(st->st_uid);
48 ce->ce_gid = htonl(st->st_gid);
49 ce->ce_size = htonl(st->st_size);
5f73076c
JH
50
51 if (assume_unchanged)
52 ce->ce_flags |= htons(CE_VALID);
415e96c8
JH
53}
54
29e4d363
JH
55static int ce_compare_data(struct cache_entry *ce, struct stat *st)
56{
57 int match = -1;
58 int fd = open(ce->name, O_RDONLY);
59
60 if (fd >= 0) {
61 unsigned char sha1[20];
62 if (!index_fd(sha1, fd, st, 0, NULL))
63 match = memcmp(sha1, ce->sha1, 20);
7f8508e8 64 /* index_fd() closed the file descriptor already */
29e4d363
JH
65 }
66 return match;
67}
68
69static int ce_compare_link(struct cache_entry *ce, unsigned long expected_size)
70{
71 int match = -1;
72 char *target;
73 void *buffer;
74 unsigned long size;
75 char type[10];
76 int len;
77
78 target = xmalloc(expected_size);
79 len = readlink(ce->name, target, expected_size);
80 if (len != expected_size) {
81 free(target);
82 return -1;
83 }
84 buffer = read_sha1_file(ce->sha1, type, &size);
85 if (!buffer) {
86 free(target);
87 return -1;
88 }
89 if (size == expected_size)
90 match = memcmp(buffer, target, size);
91 free(buffer);
92 free(target);
93 return match;
94}
95
96static int ce_modified_check_fs(struct cache_entry *ce, struct stat *st)
97{
98 switch (st->st_mode & S_IFMT) {
99 case S_IFREG:
100 if (ce_compare_data(ce, st))
101 return DATA_CHANGED;
102 break;
103 case S_IFLNK:
104 if (ce_compare_link(ce, st->st_size))
105 return DATA_CHANGED;
106 break;
107 default:
108 return TYPE_CHANGED;
109 }
110 return 0;
111}
112
407c8eb0 113static int ce_match_stat_basic(struct cache_entry *ce, struct stat *st)
734aab75
LT
114{
115 unsigned int changed = 0;
116
8ae0a8c5
KS
117 switch (ntohl(ce->ce_mode) & S_IFMT) {
118 case S_IFREG:
119 changed |= !S_ISREG(st->st_mode) ? TYPE_CHANGED : 0;
3e09cdfd
JH
120 /* We consider only the owner x bit to be relevant for
121 * "mode changes"
122 */
123 if (trust_executable_bit &&
124 (0100 & (ntohl(ce->ce_mode) ^ st->st_mode)))
ffbe1add 125 changed |= MODE_CHANGED;
8ae0a8c5
KS
126 break;
127 case S_IFLNK:
128 changed |= !S_ISLNK(st->st_mode) ? TYPE_CHANGED : 0;
129 break;
130 default:
131 die("internal error: ce_mode is %o", ntohl(ce->ce_mode));
132 }
ccc4feb5 133 if (ce->ce_mtime.sec != htonl(st->st_mtime))
734aab75 134 changed |= MTIME_CHANGED;
ccc4feb5
LT
135 if (ce->ce_ctime.sec != htonl(st->st_ctime))
136 changed |= CTIME_CHANGED;
137
2cb45e95 138#ifdef USE_NSEC
ccc4feb5
LT
139 /*
140 * nsec seems unreliable - not all filesystems support it, so
141 * as long as it is in the inode cache you get right nsec
142 * but after it gets flushed, you get zero nsec.
143 */
94dfb7f2 144 if (ce->ce_mtime.nsec != htonl(st->st_mtim.tv_nsec))
ccc4feb5 145 changed |= MTIME_CHANGED;
94dfb7f2 146 if (ce->ce_ctime.nsec != htonl(st->st_ctim.tv_nsec))
734aab75 147 changed |= CTIME_CHANGED;
ccc4feb5
LT
148#endif
149
150 if (ce->ce_uid != htonl(st->st_uid) ||
151 ce->ce_gid != htonl(st->st_gid))
734aab75 152 changed |= OWNER_CHANGED;
2cb45e95 153 if (ce->ce_ino != htonl(st->st_ino))
734aab75 154 changed |= INODE_CHANGED;
2cb45e95
LT
155
156#ifdef USE_STDEV
157 /*
158 * st_dev breaks on network filesystems where different
159 * clients will have different views of what "device"
160 * the filesystem is on
161 */
162 if (ce->ce_dev != htonl(st->st_dev))
163 changed |= INODE_CHANGED;
164#endif
165
ccc4feb5 166 if (ce->ce_size != htonl(st->st_size))
734aab75 167 changed |= DATA_CHANGED;
b0391890 168
407c8eb0
JH
169 return changed;
170}
171
5f73076c 172int ce_match_stat(struct cache_entry *ce, struct stat *st, int ignore_valid)
407c8eb0 173{
5f73076c
JH
174 unsigned int changed;
175
176 /*
177 * If it's marked as always valid in the index, it's
178 * valid whatever the checked-out copy says.
179 */
180 if (!ignore_valid && (ce->ce_flags & htons(CE_VALID)))
181 return 0;
182
183 changed = ce_match_stat_basic(ce, st);
407c8eb0 184
29e4d363
JH
185 /*
186 * Within 1 second of this sequence:
187 * echo xyzzy >file && git-update-index --add file
188 * running this command:
189 * echo frotz >file
190 * would give a falsely clean cache entry. The mtime and
191 * length match the cache, and other stat fields do not change.
192 *
193 * We could detect this at update-index time (the cache entry
194 * being registered/updated records the same time as "now")
195 * and delay the return from git-update-index, but that would
196 * effectively mean we can make at most one commit per second,
197 * which is not acceptable. Instead, we check cache entries
198 * whose mtime are the same as the index file timestamp more
5f73076c 199 * carefully than others.
29e4d363
JH
200 */
201 if (!changed &&
202 index_file_timestamp &&
203 index_file_timestamp <= ntohl(ce->ce_mtime.sec))
204 changed |= ce_modified_check_fs(ce, st);
b0391890 205
29e4d363 206 return changed;
b0391890
JH
207}
208
5f73076c 209int ce_modified(struct cache_entry *ce, struct stat *st, int really)
b0391890 210{
29e4d363 211 int changed, changed_fs;
5f73076c 212 changed = ce_match_stat(ce, st, really);
b0391890
JH
213 if (!changed)
214 return 0;
b0391890
JH
215 /*
216 * If the mode or type has changed, there's no point in trying
217 * to refresh the entry - it's not going to match
218 */
219 if (changed & (MODE_CHANGED | TYPE_CHANGED))
220 return changed;
221
222 /* Immediately after read-tree or update-index --cacheinfo,
223 * the length field is zero. For other cases the ce_size
224 * should match the SHA1 recorded in the index entry.
225 */
226 if ((changed & DATA_CHANGED) && ce->ce_size != htonl(0))
227 return changed;
228
29e4d363
JH
229 changed_fs = ce_modified_check_fs(ce, st);
230 if (changed_fs)
231 return changed | changed_fs;
b0391890
JH
232 return 0;
233}
234
958ba6c9
LT
235int base_name_compare(const char *name1, int len1, int mode1,
236 const char *name2, int len2, int mode2)
237{
238 unsigned char c1, c2;
239 int len = len1 < len2 ? len1 : len2;
240 int cmp;
241
242 cmp = memcmp(name1, name2, len);
243 if (cmp)
244 return cmp;
245 c1 = name1[len];
246 c2 = name2[len];
247 if (!c1 && S_ISDIR(mode1))
248 c1 = '/';
249 if (!c2 && S_ISDIR(mode2))
250 c2 = '/';
251 return (c1 < c2) ? -1 : (c1 > c2) ? 1 : 0;
252}
253
95fd5bf8 254int cache_name_compare(const char *name1, int flags1, const char *name2, int flags2)
eb38c22f 255{
95fd5bf8
LT
256 int len1 = flags1 & CE_NAMEMASK;
257 int len2 = flags2 & CE_NAMEMASK;
eb38c22f
LT
258 int len = len1 < len2 ? len1 : len2;
259 int cmp;
260
261 cmp = memcmp(name1, name2, len);
262 if (cmp)
263 return cmp;
264 if (len1 < len2)
265 return -1;
266 if (len1 > len2)
267 return 1;
5f73076c 268
7b80be15
JH
269 /* Compare stages */
270 flags1 &= CE_STAGEMASK;
271 flags2 &= CE_STAGEMASK;
5f73076c 272
95fd5bf8
LT
273 if (flags1 < flags2)
274 return -1;
275 if (flags1 > flags2)
276 return 1;
eb38c22f
LT
277 return 0;
278}
279
280int cache_name_pos(const char *name, int namelen)
281{
282 int first, last;
283
284 first = 0;
285 last = active_nr;
286 while (last > first) {
287 int next = (last + first) >> 1;
288 struct cache_entry *ce = active_cache[next];
972d1bb0 289 int cmp = cache_name_compare(name, namelen, ce->name, ntohs(ce->ce_flags));
eb38c22f 290 if (!cmp)
76e7f4ec 291 return next;
eb38c22f
LT
292 if (cmp < 0) {
293 last = next;
294 continue;
295 }
296 first = next+1;
297 }
76e7f4ec 298 return -first-1;
eb38c22f
LT
299}
300
7b937ca3 301/* Remove entry, return true if there are more entries to go.. */
dbbce55b 302int remove_cache_entry_at(int pos)
7b937ca3 303{
ee267527 304 active_cache_changed = 1;
7b937ca3
LT
305 active_nr--;
306 if (pos >= active_nr)
307 return 0;
308 memmove(active_cache + pos, active_cache + pos + 1, (active_nr - pos) * sizeof(struct cache_entry *));
309 return 1;
310}
311
6b5ee137 312int remove_file_from_cache(const char *path)
197ee8c9
LT
313{
314 int pos = cache_name_pos(path, strlen(path));
c4e3cca1
JH
315 if (pos < 0)
316 pos = -pos-1;
317 while (pos < active_nr && !strcmp(active_cache[pos]->name, path))
dbbce55b 318 remove_cache_entry_at(pos);
197ee8c9
LT
319 return 0;
320}
321
11be42a4
JS
322int add_file_to_index(const char *path, int verbose)
323{
324 int size, namelen;
325 struct stat st;
326 struct cache_entry *ce;
327
328 if (lstat(path, &st))
329 die("%s: unable to stat (%s)", path, strerror(errno));
330
331 if (!S_ISREG(st.st_mode) && !S_ISLNK(st.st_mode))
332 die("%s: can only add regular files or symbolic links", path);
333
334 namelen = strlen(path);
335 size = cache_entry_size(namelen);
336 ce = xcalloc(1, size);
337 memcpy(ce->name, path, namelen);
338 ce->ce_flags = htons(namelen);
339 fill_stat_cache_info(ce, &st);
340
341 ce->ce_mode = create_ce_mode(st.st_mode);
342 if (!trust_executable_bit) {
343 /* If there is an existing entry, pick the mode bits
344 * from it.
345 */
346 int pos = cache_name_pos(path, namelen);
347 if (pos >= 0)
348 ce->ce_mode = active_cache[pos]->ce_mode;
349 }
350
351 if (index_path(ce->sha1, path, &st, 1))
352 die("unable to index file %s", path);
353 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD))
354 die("unable to add %s to index",path);
355 if (verbose)
356 printf("add '%s'\n", path);
357 cache_tree_invalidate_path(active_cache_tree, path);
358 return 0;
359}
360
dbbce55b 361int ce_same_name(struct cache_entry *a, struct cache_entry *b)
7b937ca3
LT
362{
363 int len = ce_namelen(a);
364 return ce_namelen(b) == len && !memcmp(a->name, b->name, len);
365}
366
c0fd1f51
LT
367int ce_path_match(const struct cache_entry *ce, const char **pathspec)
368{
369 const char *match, *name;
370 int len;
371
372 if (!pathspec)
373 return 1;
374
375 len = ce_namelen(ce);
376 name = ce->name;
377 while ((match = *pathspec++) != NULL) {
378 int matchlen = strlen(match);
379 if (matchlen > len)
380 continue;
381 if (memcmp(name, match, matchlen))
382 continue;
383 if (matchlen && name[matchlen-1] == '/')
384 return 1;
385 if (name[matchlen] == '/' || !name[matchlen])
386 return 1;
f332726e
LT
387 if (!matchlen)
388 return 1;
c0fd1f51
LT
389 }
390 return 0;
391}
392
8dcf39c4
LT
393/*
394 * We fundamentally don't like some paths: we don't want
395 * dot or dot-dot anywhere, and for obvious reasons don't
396 * want to recurse into ".git" either.
397 *
398 * Also, we don't want double slashes or slashes at the
399 * end that can make pathnames ambiguous.
400 */
401static int verify_dotfile(const char *rest)
402{
403 /*
404 * The first character was '.', but that
405 * has already been discarded, we now test
406 * the rest.
407 */
408 switch (*rest) {
409 /* "." is not allowed */
410 case '\0': case '/':
411 return 0;
412
413 /*
414 * ".git" followed by NUL or slash is bad. This
415 * shares the path end test with the ".." case.
416 */
417 case 'g':
418 if (rest[1] != 'i')
419 break;
420 if (rest[2] != 't')
421 break;
422 rest += 2;
423 /* fallthrough */
424 case '.':
425 if (rest[1] == '\0' || rest[1] == '/')
426 return 0;
427 }
428 return 1;
429}
430
431int verify_path(const char *path)
432{
433 char c;
434
435 goto inside;
436 for (;;) {
437 if (!c)
438 return 1;
439 if (c == '/') {
440inside:
441 c = *path++;
442 switch (c) {
443 default:
444 continue;
445 case '/': case '\0':
446 break;
447 case '.':
448 if (verify_dotfile(path))
449 continue;
450 }
451 return 0;
452 }
453 c = *path++;
454 }
455}
456
12676608
LT
457/*
458 * Do we have another file that has the beginning components being a
459 * proper superset of the name we're trying to add?
0f1e4f04 460 */
12676608 461static int has_file_name(const struct cache_entry *ce, int pos, int ok_to_replace)
0f1e4f04 462{
12676608
LT
463 int retval = 0;
464 int len = ce_namelen(ce);
b155725d 465 int stage = ce_stage(ce);
12676608 466 const char *name = ce->name;
0f1e4f04 467
12676608
LT
468 while (pos < active_nr) {
469 struct cache_entry *p = active_cache[pos++];
0f1e4f04 470
12676608 471 if (len >= ce_namelen(p))
0f1e4f04 472 break;
12676608
LT
473 if (memcmp(name, p->name, len))
474 break;
b155725d
JH
475 if (ce_stage(p) != stage)
476 continue;
12676608
LT
477 if (p->name[len] != '/')
478 continue;
12676608
LT
479 retval = -1;
480 if (!ok_to_replace)
481 break;
482 remove_cache_entry_at(--pos);
0f1e4f04 483 }
12676608
LT
484 return retval;
485}
0f1e4f04 486
12676608
LT
487/*
488 * Do we have another file with a pathname that is a proper
489 * subset of the name we're trying to add?
490 */
491static int has_dir_name(const struct cache_entry *ce, int pos, int ok_to_replace)
492{
493 int retval = 0;
b155725d 494 int stage = ce_stage(ce);
12676608
LT
495 const char *name = ce->name;
496 const char *slash = name + ce_namelen(ce);
0f1e4f04 497
12676608
LT
498 for (;;) {
499 int len;
0f1e4f04 500
12676608
LT
501 for (;;) {
502 if (*--slash == '/')
503 break;
504 if (slash <= ce->name)
505 return retval;
506 }
507 len = slash - name;
0f1e4f04 508
b155725d 509 pos = cache_name_pos(name, ntohs(create_ce_flags(len, stage)));
12676608
LT
510 if (pos >= 0) {
511 retval = -1;
512 if (ok_to_replace)
513 break;
dbbce55b 514 remove_cache_entry_at(pos);
12676608
LT
515 continue;
516 }
517
518 /*
519 * Trivial optimization: if we find an entry that
520 * already matches the sub-directory, then we know
b155725d 521 * we're ok, and we can exit.
12676608
LT
522 */
523 pos = -pos-1;
b155725d 524 while (pos < active_nr) {
12676608 525 struct cache_entry *p = active_cache[pos];
b155725d
JH
526 if ((ce_namelen(p) <= len) ||
527 (p->name[len] != '/') ||
528 memcmp(p->name, name, len))
529 break; /* not our subdirectory */
530 if (ce_stage(p) == stage)
531 /* p is at the same stage as our entry, and
532 * is a subdirectory of what we are looking
533 * at, so we cannot have conflicts at our
534 * level or anything shorter.
535 */
536 return retval;
537 pos++;
192268c1 538 }
0f1e4f04 539 }
12676608
LT
540 return retval;
541}
542
543/* We may be in a situation where we already have path/file and path
544 * is being added, or we already have path and path/file is being
545 * added. Either one would result in a nonsense tree that has path
546 * twice when git-write-tree tries to write it out. Prevent it.
547 *
548 * If ok-to-replace is specified, we remove the conflicting entries
549 * from the cache so the caller should recompute the insert position.
550 * When this happens, we return non-zero.
551 */
552static int check_file_directory_conflict(const struct cache_entry *ce, int pos, int ok_to_replace)
553{
554 /*
555 * We check if the path is a sub-path of a subsequent pathname
556 * first, since removing those will not change the position
557 * in the array
558 */
559 int retval = has_file_name(ce, pos, ok_to_replace);
560 /*
561 * Then check if the path might have a clashing sub-directory
562 * before it.
563 */
564 return retval + has_dir_name(ce, pos, ok_to_replace);
0f1e4f04
JH
565}
566
192268c1 567int add_cache_entry(struct cache_entry *ce, int option)
197ee8c9
LT
568{
569 int pos;
192268c1
JH
570 int ok_to_add = option & ADD_CACHE_OK_TO_ADD;
571 int ok_to_replace = option & ADD_CACHE_OK_TO_REPLACE;
b155725d 572 int skip_df_check = option & ADD_CACHE_SKIP_DFCHECK;
5f73076c 573
972d1bb0 574 pos = cache_name_pos(ce->name, ntohs(ce->ce_flags));
197ee8c9 575
3e09cdfd 576 /* existing match? Just replace it. */
76e7f4ec 577 if (pos >= 0) {
ee267527 578 active_cache_changed = 1;
76e7f4ec 579 active_cache[pos] = ce;
197ee8c9
LT
580 return 0;
581 }
76e7f4ec 582 pos = -pos-1;
197ee8c9 583
7b937ca3
LT
584 /*
585 * Inserting a merged entry ("stage 0") into the index
586 * will always replace all non-merged entries..
587 */
588 if (pos < active_nr && ce_stage(ce) == 0) {
dbbce55b 589 while (ce_same_name(active_cache[pos], ce)) {
7b937ca3 590 ok_to_add = 1;
dbbce55b 591 if (!remove_cache_entry_at(pos))
7b937ca3
LT
592 break;
593 }
594 }
595
121481ab
LT
596 if (!ok_to_add)
597 return -1;
8dcf39c4
LT
598 if (!verify_path(ce->name))
599 return -1;
121481ab 600
3e09cdfd
JH
601 if (!skip_df_check &&
602 check_file_directory_conflict(ce, pos, ok_to_replace)) {
192268c1
JH
603 if (!ok_to_replace)
604 return -1;
972d1bb0 605 pos = cache_name_pos(ce->name, ntohs(ce->ce_flags));
192268c1
JH
606 pos = -pos-1;
607 }
0f1e4f04 608
197ee8c9
LT
609 /* Make sure the array is big enough .. */
610 if (active_nr == active_alloc) {
611 active_alloc = alloc_nr(active_alloc);
812666c8 612 active_cache = xrealloc(active_cache, active_alloc * sizeof(struct cache_entry *));
197ee8c9
LT
613 }
614
615 /* Add it in.. */
616 active_nr++;
617 if (active_nr > pos)
618 memmove(active_cache + pos + 1, active_cache + pos, (active_nr - pos - 1) * sizeof(ce));
619 active_cache[pos] = ce;
ee267527 620 active_cache_changed = 1;
197ee8c9
LT
621 return 0;
622}
623
405e5b2f
LT
624/*
625 * "refresh" does not calculate a new sha1 file or bring the
626 * cache up-to-date for mode/content changes. But what it
627 * _does_ do is to "re-match" the stat information of a file
628 * with the cache, so that you can refresh the cache for a
629 * file that hasn't been changed but where the stat entry is
630 * out of date.
631 *
632 * For example, you'd want to do this after doing a "git-read-tree",
633 * to link up the stat cache details with the proper files.
634 */
8fd2cb40 635struct cache_entry *refresh_cache_entry(struct cache_entry *ce, int really)
405e5b2f
LT
636{
637 struct stat st;
638 struct cache_entry *updated;
639 int changed, size;
640
8fd2cb40
JS
641 if (lstat(ce->name, &st) < 0) {
642 cache_errno = errno;
643 return NULL;
644 }
405e5b2f
LT
645
646 changed = ce_match_stat(ce, &st, really);
647 if (!changed) {
648 if (really && assume_unchanged &&
649 !(ce->ce_flags & htons(CE_VALID)))
650 ; /* mark this one VALID again */
651 else
8fd2cb40 652 return ce;
405e5b2f
LT
653 }
654
8fd2cb40
JS
655 if (ce_modified(ce, &st, really)) {
656 cache_errno = EINVAL;
657 return NULL;
658 }
405e5b2f
LT
659
660 size = ce_size(ce);
661 updated = xmalloc(size);
662 memcpy(updated, ce, size);
663 fill_stat_cache_info(updated, &st);
664
665 /* In this case, if really is not set, we should leave
666 * CE_VALID bit alone. Otherwise, paths marked with
667 * --no-assume-unchanged (i.e. things to be edited) will
668 * reacquire CE_VALID bit automatically, which is not
669 * really what we want.
670 */
671 if (!really && assume_unchanged && !(ce->ce_flags & htons(CE_VALID)))
672 updated->ce_flags &= ~htons(CE_VALID);
673
674 return updated;
675}
676
677int refresh_cache(unsigned int flags)
678{
679 int i;
680 int has_errors = 0;
681 int really = (flags & REFRESH_REALLY) != 0;
682 int allow_unmerged = (flags & REFRESH_UNMERGED) != 0;
683 int quiet = (flags & REFRESH_QUIET) != 0;
684 int not_new = (flags & REFRESH_IGNORE_MISSING) != 0;
685
686 for (i = 0; i < active_nr; i++) {
687 struct cache_entry *ce, *new;
688 ce = active_cache[i];
689 if (ce_stage(ce)) {
690 while ((i < active_nr) &&
691 ! strcmp(active_cache[i]->name, ce->name))
692 i++;
693 i--;
694 if (allow_unmerged)
695 continue;
696 printf("%s: needs merge\n", ce->name);
697 has_errors = 1;
698 continue;
699 }
700
8fd2cb40
JS
701 new = refresh_cache_entry(ce, really);
702 if (new == ce)
405e5b2f 703 continue;
8fd2cb40
JS
704 if (!new) {
705 if (not_new && cache_errno == ENOENT)
405e5b2f 706 continue;
8fd2cb40 707 if (really && cache_errno == EINVAL) {
405e5b2f
LT
708 /* If we are doing --really-refresh that
709 * means the index is not valid anymore.
710 */
711 ce->ce_flags &= ~htons(CE_VALID);
712 active_cache_changed = 1;
713 }
714 if (quiet)
715 continue;
716 printf("%s: needs update\n", ce->name);
717 has_errors = 1;
718 continue;
719 }
720 active_cache_changed = 1;
721 /* You can NOT just free active_cache[i] here, since it
722 * might not be necessarily malloc()ed but can also come
723 * from mmap(). */
724 active_cache[i] = new;
725 }
726 return has_errors;
727}
728
bad68ec9 729static int verify_hdr(struct cache_header *hdr, unsigned long size)
e83c5163
LT
730{
731 SHA_CTX c;
bad68ec9 732 unsigned char sha1[20];
e83c5163 733
ccc4feb5 734 if (hdr->hdr_signature != htonl(CACHE_SIGNATURE))
e83c5163 735 return error("bad signature");
ca9be054
LT
736 if (hdr->hdr_version != htonl(2))
737 return error("bad index version");
e83c5163 738 SHA1_Init(&c);
ca9be054 739 SHA1_Update(&c, hdr, size - 20);
e83c5163 740 SHA1_Final(sha1, &c);
1d7f171c 741 if (memcmp(sha1, (char *) hdr + size - 20, 20))
ca9be054 742 return error("bad index file sha1 signature");
e83c5163
LT
743 return 0;
744}
745
bad68ec9
JH
746static int read_index_extension(const char *ext, void *data, unsigned long sz)
747{
748 switch (CACHE_EXT(ext)) {
749 case CACHE_EXT_TREE:
750 active_cache_tree = cache_tree_read(data, sz);
751 break;
752 default:
753 if (*ext < 'A' || 'Z' < *ext)
754 return error("index uses %.4s extension, which we do not understand",
755 ext);
756 fprintf(stderr, "ignoring %.4s extension\n", ext);
757 break;
758 }
759 return 0;
760}
761
762int read_cache(void)
8fd2cb40
JS
763{
764 return read_cache_from(get_index_file());
765}
766
767/* remember to discard_cache() before reading a different cache! */
768int read_cache_from(const char *path)
e83c5163
LT
769{
770 int fd, i;
771 struct stat st;
8fd2cb40 772 unsigned long offset;
e83c5163
LT
773 struct cache_header *hdr;
774
775 errno = EBUSY;
8fd2cb40 776 if (cache_mmap)
5d1a5c02
LT
777 return active_nr;
778
e83c5163 779 errno = ENOENT;
29e4d363 780 index_file_timestamp = 0;
8fd2cb40 781 fd = open(path, O_RDONLY);
5d1a5c02
LT
782 if (fd < 0) {
783 if (errno == ENOENT)
784 return 0;
785 die("index file open failed (%s)", strerror(errno));
786 }
e83c5163 787
8fd2cb40 788 cache_mmap = MAP_FAILED;
e83c5163 789 if (!fstat(fd, &st)) {
8fd2cb40 790 cache_mmap_size = st.st_size;
e83c5163 791 errno = EINVAL;
8fd2cb40
JS
792 if (cache_mmap_size >= sizeof(struct cache_header) + 20)
793 cache_mmap = mmap(NULL, cache_mmap_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
e83c5163
LT
794 }
795 close(fd);
8fd2cb40 796 if (cache_mmap == MAP_FAILED)
5d1a5c02 797 die("index file mmap failed (%s)", strerror(errno));
e83c5163 798
8fd2cb40
JS
799 hdr = cache_mmap;
800 if (verify_hdr(hdr, cache_mmap_size) < 0)
e83c5163
LT
801 goto unmap;
802
ccc4feb5 803 active_nr = ntohl(hdr->hdr_entries);
e83c5163 804 active_alloc = alloc_nr(active_nr);
28cc4ab4 805 active_cache = xcalloc(active_alloc, sizeof(struct cache_entry *));
e83c5163
LT
806
807 offset = sizeof(*hdr);
ccc4feb5 808 for (i = 0; i < active_nr; i++) {
8fd2cb40 809 struct cache_entry *ce = (struct cache_entry *) ((char *) cache_mmap + offset);
e83c5163
LT
810 offset = offset + ce_size(ce);
811 active_cache[i] = ce;
812 }
29e4d363 813 index_file_timestamp = st.st_mtime;
8fd2cb40 814 while (offset <= cache_mmap_size - 20 - 8) {
bad68ec9
JH
815 /* After an array of active_nr index entries,
816 * there can be arbitrary number of extended
817 * sections, each of which is prefixed with
818 * extension name (4-byte) and section length
819 * in 4-byte network byte order.
820 */
821 unsigned long extsize;
8fd2cb40 822 memcpy(&extsize, (char *) cache_mmap + offset + 4, 4);
bad68ec9 823 extsize = ntohl(extsize);
8fd2cb40
JS
824 if (read_index_extension(((const char *) cache_mmap) + offset,
825 (char *) cache_mmap + offset + 8,
1d7f171c 826 extsize) < 0)
bad68ec9
JH
827 goto unmap;
828 offset += 8;
829 offset += extsize;
830 }
e83c5163
LT
831 return active_nr;
832
833unmap:
8fd2cb40 834 munmap(cache_mmap, cache_mmap_size);
e83c5163 835 errno = EINVAL;
5d1a5c02 836 die("index file corrupt");
e83c5163
LT
837}
838
4990aadc 839#define WRITE_BUFFER_SIZE 8192
bf0f910d 840static unsigned char write_buffer[WRITE_BUFFER_SIZE];
4990aadc
LT
841static unsigned long write_buffer_len;
842
6015c28b
JH
843static int ce_write_flush(SHA_CTX *context, int fd)
844{
845 unsigned int buffered = write_buffer_len;
846 if (buffered) {
847 SHA1_Update(context, write_buffer, buffered);
848 if (write(fd, write_buffer, buffered) != buffered)
849 return -1;
850 write_buffer_len = 0;
851 }
852 return 0;
853}
854
ca9be054 855static int ce_write(SHA_CTX *context, int fd, void *data, unsigned int len)
4990aadc
LT
856{
857 while (len) {
858 unsigned int buffered = write_buffer_len;
859 unsigned int partial = WRITE_BUFFER_SIZE - buffered;
860 if (partial > len)
861 partial = len;
862 memcpy(write_buffer + buffered, data, partial);
863 buffered += partial;
864 if (buffered == WRITE_BUFFER_SIZE) {
6015c28b
JH
865 write_buffer_len = buffered;
866 if (ce_write_flush(context, fd))
4990aadc
LT
867 return -1;
868 buffered = 0;
869 }
870 write_buffer_len = buffered;
871 len -= partial;
1d7f171c 872 data = (char *) data + partial;
4990aadc
LT
873 }
874 return 0;
875}
876
bad68ec9 877static int write_index_ext_header(SHA_CTX *context, int fd,
ac58c7b1 878 unsigned int ext, unsigned int sz)
bad68ec9
JH
879{
880 ext = htonl(ext);
881 sz = htonl(sz);
968a1d65
DR
882 return ((ce_write(context, fd, &ext, 4) < 0) ||
883 (ce_write(context, fd, &sz, 4) < 0)) ? -1 : 0;
bad68ec9
JH
884}
885
886static int ce_flush(SHA_CTX *context, int fd)
4990aadc
LT
887{
888 unsigned int left = write_buffer_len;
ca9be054 889
4990aadc
LT
890 if (left) {
891 write_buffer_len = 0;
ca9be054 892 SHA1_Update(context, write_buffer, left);
4990aadc 893 }
ca9be054 894
2c865d9a
QH
895 /* Flush first if not enough space for SHA1 signature */
896 if (left + 20 > WRITE_BUFFER_SIZE) {
897 if (write(fd, write_buffer, left) != left)
898 return -1;
899 left = 0;
900 }
901
ca9be054 902 /* Append the SHA1 signature at the end */
bad68ec9 903 SHA1_Final(write_buffer + left, context);
ca9be054 904 left += 20;
968a1d65 905 return (write(fd, write_buffer, left) != left) ? -1 : 0;
4990aadc
LT
906}
907
407c8eb0
JH
908static void ce_smudge_racily_clean_entry(struct cache_entry *ce)
909{
910 /*
911 * The only thing we care about in this function is to smudge the
912 * falsely clean entry due to touch-update-touch race, so we leave
913 * everything else as they are. We are called for entries whose
914 * ce_mtime match the index file mtime.
915 */
916 struct stat st;
917
918 if (lstat(ce->name, &st) < 0)
919 return;
920 if (ce_match_stat_basic(ce, &st))
921 return;
922 if (ce_modified_check_fs(ce, &st)) {
4b3511b0
JH
923 /* This is "racily clean"; smudge it. Note that this
924 * is a tricky code. At first glance, it may appear
925 * that it can break with this sequence:
926 *
927 * $ echo xyzzy >frotz
928 * $ git-update-index --add frotz
929 * $ : >frotz
930 * $ sleep 3
931 * $ echo filfre >nitfol
932 * $ git-update-index --add nitfol
933 *
b7e58b17 934 * but it does not. When the second update-index runs,
4b3511b0
JH
935 * it notices that the entry "frotz" has the same timestamp
936 * as index, and if we were to smudge it by resetting its
937 * size to zero here, then the object name recorded
938 * in index is the 6-byte file but the cached stat information
939 * becomes zero --- which would then match what we would
940 * obtain from the filesystem next time we stat("frotz").
941 *
942 * However, the second update-index, before calling
943 * this function, notices that the cached size is 6
944 * bytes and what is on the filesystem is an empty
945 * file, and never calls us, so the cached size information
946 * for "frotz" stays 6 which does not match the filesystem.
947 */
407c8eb0
JH
948 ce->ce_size = htonl(0);
949 }
950}
951
bad68ec9 952int write_cache(int newfd, struct cache_entry **cache, int entries)
197ee8c9
LT
953{
954 SHA_CTX c;
955 struct cache_header hdr;
b7e58b17
JH
956 int i, removed, recent;
957 struct stat st;
958 time_t now;
025a0709
JH
959
960 for (i = removed = 0; i < entries; i++)
961 if (!cache[i]->ce_mode)
962 removed++;
197ee8c9 963
ccc4feb5 964 hdr.hdr_signature = htonl(CACHE_SIGNATURE);
ca9be054 965 hdr.hdr_version = htonl(2);
025a0709 966 hdr.hdr_entries = htonl(entries - removed);
197ee8c9
LT
967
968 SHA1_Init(&c);
ca9be054 969 if (ce_write(&c, newfd, &hdr, sizeof(hdr)) < 0)
197ee8c9
LT
970 return -1;
971
972 for (i = 0; i < entries; i++) {
973 struct cache_entry *ce = cache[i];
aa16021e
LT
974 if (!ce->ce_mode)
975 continue;
6015c28b
JH
976 if (index_file_timestamp &&
977 index_file_timestamp <= ntohl(ce->ce_mtime.sec))
407c8eb0 978 ce_smudge_racily_clean_entry(ce);
ca9be054 979 if (ce_write(&c, newfd, ce, ce_size(ce)) < 0)
197ee8c9
LT
980 return -1;
981 }
1af1c2b6 982
bad68ec9
JH
983 /* Write extension data here */
984 if (active_cache_tree) {
985 unsigned long sz;
986 void *data = cache_tree_write(active_cache_tree, &sz);
987 if (data &&
988 !write_index_ext_header(&c, newfd, CACHE_EXT_TREE, sz) &&
989 !ce_write(&c, newfd, data, sz))
990 ;
991 else {
992 free(data);
993 return -1;
994 }
995 }
b7e58b17
JH
996
997 /*
998 * To prevent later ce_match_stat() from always falling into
999 * check_fs(), if we have too many entries that can trigger
1000 * racily clean check, we are better off delaying the return.
1001 * We arbitrarily say if more than 20 paths or 25% of total
1002 * paths are very new, we delay the return until the index
1003 * file gets a new timestamp.
1004 *
1005 * NOTE! NOTE! NOTE!
1006 *
1007 * This assumes that nobody is touching the working tree while
1008 * we are updating the index.
1009 */
6015c28b
JH
1010
1011 /* Make sure that the new index file has st_mtime
1012 * that is current enough -- ce_write() batches the data
1013 * so it might not have written anything yet.
1014 */
1015 ce_write_flush(&c, newfd);
1016
1017 now = fstat(newfd, &st) ? 0 : st.st_mtime;
1018 if (now) {
1019 recent = 0;
1020 for (i = 0; i < entries; i++) {
1021 struct cache_entry *ce = cache[i];
1022 time_t entry_time = (time_t) ntohl(ce->ce_mtime.sec);
1023 if (!ce->ce_mode)
1024 continue;
1025 if (now && now <= entry_time)
1026 recent++;
1027 }
1028 if (20 < recent && entries <= recent * 4) {
1029#if 0
1030 fprintf(stderr, "entries %d\n", entries);
1031 fprintf(stderr, "recent %d\n", recent);
1032 fprintf(stderr, "now %lu\n", now);
1033#endif
1034 while (!fstat(newfd, &st) && st.st_mtime <= now) {
6015c28b 1035 off_t where = lseek(newfd, 0, SEEK_CUR);
789a09b4 1036 sleep(1);
6015c28b
JH
1037 if ((where == (off_t) -1) ||
1038 (write(newfd, "", 1) != 1) ||
1039 (lseek(newfd, -1, SEEK_CUR) != where) ||
1040 ftruncate(newfd, where))
1041 break;
1042 }
b7e58b17
JH
1043 }
1044 }
bad68ec9 1045 return ce_flush(&c, newfd);
197ee8c9 1046}