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