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