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