Racy GIT
[git.git] / read-cache.c
1 /*
2  * GIT - The information manager from hell
3  *
4  * Copyright (C) Linus Torvalds, 2005
5  */
6 #include "cache.h"
7
8 struct cache_entry **active_cache = NULL;
9 static time_t index_file_timestamp;
10 unsigned int active_nr = 0, active_alloc = 0, active_cache_changed = 0;
11
12 /*
13  * This only updates the "non-critical" parts of the directory
14  * cache, ie the parts that aren't tracked by GIT, and only used
15  * to validate the cache.
16  */
17 void fill_stat_cache_info(struct cache_entry *ce, struct stat *st)
18 {
19         ce->ce_ctime.sec = htonl(st->st_ctime);
20         ce->ce_mtime.sec = htonl(st->st_mtime);
21 #ifdef USE_NSEC
22         ce->ce_ctime.nsec = htonl(st->st_ctim.tv_nsec);
23         ce->ce_mtime.nsec = htonl(st->st_mtim.tv_nsec);
24 #endif
25         ce->ce_dev = htonl(st->st_dev);
26         ce->ce_ino = htonl(st->st_ino);
27         ce->ce_uid = htonl(st->st_uid);
28         ce->ce_gid = htonl(st->st_gid);
29         ce->ce_size = htonl(st->st_size);
30 }
31
32 static int ce_compare_data(struct cache_entry *ce, struct stat *st)
33 {
34         int match = -1;
35         int fd = open(ce->name, O_RDONLY);
36
37         if (fd >= 0) {
38                 unsigned char sha1[20];
39                 if (!index_fd(sha1, fd, st, 0, NULL))
40                         match = memcmp(sha1, ce->sha1, 20);
41                 close(fd);
42         }
43         return match;
44 }
45
46 static int ce_compare_link(struct cache_entry *ce, unsigned long expected_size)
47 {
48         int match = -1;
49         char *target;
50         void *buffer;
51         unsigned long size;
52         char type[10];
53         int len;
54
55         target = xmalloc(expected_size);
56         len = readlink(ce->name, target, expected_size);
57         if (len != expected_size) {
58                 free(target);
59                 return -1;
60         }
61         buffer = read_sha1_file(ce->sha1, type, &size);
62         if (!buffer) {
63                 free(target);
64                 return -1;
65         }
66         if (size == expected_size)
67                 match = memcmp(buffer, target, size);
68         free(buffer);
69         free(target);
70         return match;
71 }
72
73 static int ce_modified_check_fs(struct cache_entry *ce, struct stat *st)
74 {
75         switch (st->st_mode & S_IFMT) {
76         case S_IFREG:
77                 if (ce_compare_data(ce, st))
78                         return DATA_CHANGED;
79                 break;
80         case S_IFLNK:
81                 if (ce_compare_link(ce, st->st_size))
82                         return DATA_CHANGED;
83                 break;
84         default:
85                 return TYPE_CHANGED;
86         }
87         return 0;
88 }
89
90 int ce_match_stat(struct cache_entry *ce, struct stat *st)
91 {
92         unsigned int changed = 0;
93
94         switch (ntohl(ce->ce_mode) & S_IFMT) {
95         case S_IFREG:
96                 changed |= !S_ISREG(st->st_mode) ? TYPE_CHANGED : 0;
97                 /* We consider only the owner x bit to be relevant for
98                  * "mode changes"
99                  */
100                 if (trust_executable_bit &&
101                     (0100 & (ntohl(ce->ce_mode) ^ st->st_mode)))
102                         changed |= MODE_CHANGED;
103                 break;
104         case S_IFLNK:
105                 changed |= !S_ISLNK(st->st_mode) ? TYPE_CHANGED : 0;
106                 break;
107         default:
108                 die("internal error: ce_mode is %o", ntohl(ce->ce_mode));
109         }
110         if (ce->ce_mtime.sec != htonl(st->st_mtime))
111                 changed |= MTIME_CHANGED;
112         if (ce->ce_ctime.sec != htonl(st->st_ctime))
113                 changed |= CTIME_CHANGED;
114
115 #ifdef USE_NSEC
116         /*
117          * nsec seems unreliable - not all filesystems support it, so
118          * as long as it is in the inode cache you get right nsec
119          * but after it gets flushed, you get zero nsec.
120          */
121         if (ce->ce_mtime.nsec != htonl(st->st_mtim.tv_nsec))
122                 changed |= MTIME_CHANGED;
123         if (ce->ce_ctime.nsec != htonl(st->st_ctim.tv_nsec))
124                 changed |= CTIME_CHANGED;
125 #endif  
126
127         if (ce->ce_uid != htonl(st->st_uid) ||
128             ce->ce_gid != htonl(st->st_gid))
129                 changed |= OWNER_CHANGED;
130         if (ce->ce_ino != htonl(st->st_ino))
131                 changed |= INODE_CHANGED;
132
133 #ifdef USE_STDEV
134         /*
135          * st_dev breaks on network filesystems where different
136          * clients will have different views of what "device"
137          * the filesystem is on
138          */
139         if (ce->ce_dev != htonl(st->st_dev))
140                 changed |= INODE_CHANGED;
141 #endif
142
143         if (ce->ce_size != htonl(st->st_size))
144                 changed |= DATA_CHANGED;
145
146         /*
147          * Within 1 second of this sequence:
148          *      echo xyzzy >file && git-update-index --add file
149          * running this command:
150          *      echo frotz >file
151          * would give a falsely clean cache entry.  The mtime and
152          * length match the cache, and other stat fields do not change.
153          *
154          * We could detect this at update-index time (the cache entry
155          * being registered/updated records the same time as "now")
156          * and delay the return from git-update-index, but that would
157          * effectively mean we can make at most one commit per second,
158          * which is not acceptable.  Instead, we check cache entries
159          * whose mtime are the same as the index file timestamp more
160          * careful than others.
161          */
162         if (!changed &&
163             index_file_timestamp &&
164             index_file_timestamp <= ntohl(ce->ce_mtime.sec))
165                 changed |= ce_modified_check_fs(ce, st);
166
167         return changed;
168 }
169
170 int ce_modified(struct cache_entry *ce, struct stat *st)
171 {
172         int changed, changed_fs;
173         changed = ce_match_stat(ce, st);
174         if (!changed)
175                 return 0;
176         /*
177          * If the mode or type has changed, there's no point in trying
178          * to refresh the entry - it's not going to match
179          */
180         if (changed & (MODE_CHANGED | TYPE_CHANGED))
181                 return changed;
182
183         /* Immediately after read-tree or update-index --cacheinfo,
184          * the length field is zero.  For other cases the ce_size
185          * should match the SHA1 recorded in the index entry.
186          */
187         if ((changed & DATA_CHANGED) && ce->ce_size != htonl(0))
188                 return changed;
189
190         changed_fs = ce_modified_check_fs(ce, st);
191         if (changed_fs)
192                 return changed | changed_fs;
193         return 0;
194 }
195
196 int base_name_compare(const char *name1, int len1, int mode1,
197                       const char *name2, int len2, int mode2)
198 {
199         unsigned char c1, c2;
200         int len = len1 < len2 ? len1 : len2;
201         int cmp;
202
203         cmp = memcmp(name1, name2, len);
204         if (cmp)
205                 return cmp;
206         c1 = name1[len];
207         c2 = name2[len];
208         if (!c1 && S_ISDIR(mode1))
209                 c1 = '/';
210         if (!c2 && S_ISDIR(mode2))
211                 c2 = '/';
212         return (c1 < c2) ? -1 : (c1 > c2) ? 1 : 0;
213 }
214
215 int cache_name_compare(const char *name1, int flags1, const char *name2, int flags2)
216 {
217         int len1 = flags1 & CE_NAMEMASK;
218         int len2 = flags2 & CE_NAMEMASK;
219         int len = len1 < len2 ? len1 : len2;
220         int cmp;
221
222         cmp = memcmp(name1, name2, len);
223         if (cmp)
224                 return cmp;
225         if (len1 < len2)
226                 return -1;
227         if (len1 > len2)
228                 return 1;
229         if (flags1 < flags2)
230                 return -1;
231         if (flags1 > flags2)
232                 return 1;
233         return 0;
234 }
235
236 int cache_name_pos(const char *name, int namelen)
237 {
238         int first, last;
239
240         first = 0;
241         last = active_nr;
242         while (last > first) {
243                 int next = (last + first) >> 1;
244                 struct cache_entry *ce = active_cache[next];
245                 int cmp = cache_name_compare(name, namelen, ce->name, ntohs(ce->ce_flags));
246                 if (!cmp)
247                         return next;
248                 if (cmp < 0) {
249                         last = next;
250                         continue;
251                 }
252                 first = next+1;
253         }
254         return -first-1;
255 }
256
257 /* Remove entry, return true if there are more entries to go.. */
258 int remove_cache_entry_at(int pos)
259 {
260         active_cache_changed = 1;
261         active_nr--;
262         if (pos >= active_nr)
263                 return 0;
264         memmove(active_cache + pos, active_cache + pos + 1, (active_nr - pos) * sizeof(struct cache_entry *));
265         return 1;
266 }
267
268 int remove_file_from_cache(const char *path)
269 {
270         int pos = cache_name_pos(path, strlen(path));
271         if (pos < 0)
272                 pos = -pos-1;
273         while (pos < active_nr && !strcmp(active_cache[pos]->name, path))
274                 remove_cache_entry_at(pos);
275         return 0;
276 }
277
278 int ce_same_name(struct cache_entry *a, struct cache_entry *b)
279 {
280         int len = ce_namelen(a);
281         return ce_namelen(b) == len && !memcmp(a->name, b->name, len);
282 }
283
284 int ce_path_match(const struct cache_entry *ce, const char **pathspec)
285 {
286         const char *match, *name;
287         int len;
288
289         if (!pathspec)
290                 return 1;
291
292         len = ce_namelen(ce);
293         name = ce->name;
294         while ((match = *pathspec++) != NULL) {
295                 int matchlen = strlen(match);
296                 if (matchlen > len)
297                         continue;
298                 if (memcmp(name, match, matchlen))
299                         continue;
300                 if (matchlen && name[matchlen-1] == '/')
301                         return 1;
302                 if (name[matchlen] == '/' || !name[matchlen])
303                         return 1;
304                 if (!matchlen)
305                         return 1;
306         }
307         return 0;
308 }
309
310 /*
311  * Do we have another file that has the beginning components being a
312  * proper superset of the name we're trying to add?
313  */
314 static int has_file_name(const struct cache_entry *ce, int pos, int ok_to_replace)
315 {
316         int retval = 0;
317         int len = ce_namelen(ce);
318         int stage = ce_stage(ce);
319         const char *name = ce->name;
320
321         while (pos < active_nr) {
322                 struct cache_entry *p = active_cache[pos++];
323
324                 if (len >= ce_namelen(p))
325                         break;
326                 if (memcmp(name, p->name, len))
327                         break;
328                 if (ce_stage(p) != stage)
329                         continue;
330                 if (p->name[len] != '/')
331                         continue;
332                 retval = -1;
333                 if (!ok_to_replace)
334                         break;
335                 remove_cache_entry_at(--pos);
336         }
337         return retval;
338 }
339
340 /*
341  * Do we have another file with a pathname that is a proper
342  * subset of the name we're trying to add?
343  */
344 static int has_dir_name(const struct cache_entry *ce, int pos, int ok_to_replace)
345 {
346         int retval = 0;
347         int stage = ce_stage(ce);
348         const char *name = ce->name;
349         const char *slash = name + ce_namelen(ce);
350
351         for (;;) {
352                 int len;
353
354                 for (;;) {
355                         if (*--slash == '/')
356                                 break;
357                         if (slash <= ce->name)
358                                 return retval;
359                 }
360                 len = slash - name;
361
362                 pos = cache_name_pos(name, ntohs(create_ce_flags(len, stage)));
363                 if (pos >= 0) {
364                         retval = -1;
365                         if (ok_to_replace)
366                                 break;
367                         remove_cache_entry_at(pos);
368                         continue;
369                 }
370
371                 /*
372                  * Trivial optimization: if we find an entry that
373                  * already matches the sub-directory, then we know
374                  * we're ok, and we can exit.
375                  */
376                 pos = -pos-1;
377                 while (pos < active_nr) {
378                         struct cache_entry *p = active_cache[pos];
379                         if ((ce_namelen(p) <= len) ||
380                             (p->name[len] != '/') ||
381                             memcmp(p->name, name, len))
382                                 break; /* not our subdirectory */
383                         if (ce_stage(p) == stage)
384                                 /* p is at the same stage as our entry, and
385                                  * is a subdirectory of what we are looking
386                                  * at, so we cannot have conflicts at our
387                                  * level or anything shorter.
388                                  */
389                                 return retval;
390                         pos++;
391                 }
392         }
393         return retval;
394 }
395
396 /* We may be in a situation where we already have path/file and path
397  * is being added, or we already have path and path/file is being
398  * added.  Either one would result in a nonsense tree that has path
399  * twice when git-write-tree tries to write it out.  Prevent it.
400  * 
401  * If ok-to-replace is specified, we remove the conflicting entries
402  * from the cache so the caller should recompute the insert position.
403  * When this happens, we return non-zero.
404  */
405 static int check_file_directory_conflict(const struct cache_entry *ce, int pos, int ok_to_replace)
406 {
407         /*
408          * We check if the path is a sub-path of a subsequent pathname
409          * first, since removing those will not change the position
410          * in the array
411          */
412         int retval = has_file_name(ce, pos, ok_to_replace);
413         /*
414          * Then check if the path might have a clashing sub-directory
415          * before it.
416          */
417         return retval + has_dir_name(ce, pos, ok_to_replace);
418 }
419
420 int add_cache_entry(struct cache_entry *ce, int option)
421 {
422         int pos;
423         int ok_to_add = option & ADD_CACHE_OK_TO_ADD;
424         int ok_to_replace = option & ADD_CACHE_OK_TO_REPLACE;
425         int skip_df_check = option & ADD_CACHE_SKIP_DFCHECK;
426         pos = cache_name_pos(ce->name, ntohs(ce->ce_flags));
427
428         /* existing match? Just replace it. */
429         if (pos >= 0) {
430                 active_cache_changed = 1;
431                 active_cache[pos] = ce;
432                 return 0;
433         }
434         pos = -pos-1;
435
436         /*
437          * Inserting a merged entry ("stage 0") into the index
438          * will always replace all non-merged entries..
439          */
440         if (pos < active_nr && ce_stage(ce) == 0) {
441                 while (ce_same_name(active_cache[pos], ce)) {
442                         ok_to_add = 1;
443                         if (!remove_cache_entry_at(pos))
444                                 break;
445                 }
446         }
447
448         if (!ok_to_add)
449                 return -1;
450
451         if (!skip_df_check &&
452             check_file_directory_conflict(ce, pos, ok_to_replace)) {
453                 if (!ok_to_replace)
454                         return -1;
455                 pos = cache_name_pos(ce->name, ntohs(ce->ce_flags));
456                 pos = -pos-1;
457         }
458
459         /* Make sure the array is big enough .. */
460         if (active_nr == active_alloc) {
461                 active_alloc = alloc_nr(active_alloc);
462                 active_cache = xrealloc(active_cache, active_alloc * sizeof(struct cache_entry *));
463         }
464
465         /* Add it in.. */
466         active_nr++;
467         if (active_nr > pos)
468                 memmove(active_cache + pos + 1, active_cache + pos, (active_nr - pos - 1) * sizeof(ce));
469         active_cache[pos] = ce;
470         active_cache_changed = 1;
471         return 0;
472 }
473
474 static int verify_hdr(struct cache_header *hdr, unsigned long size)
475 {
476         SHA_CTX c;
477         unsigned char sha1[20];
478
479         if (hdr->hdr_signature != htonl(CACHE_SIGNATURE))
480                 return error("bad signature");
481         if (hdr->hdr_version != htonl(2))
482                 return error("bad index version");
483         SHA1_Init(&c);
484         SHA1_Update(&c, hdr, size - 20);
485         SHA1_Final(sha1, &c);
486         if (memcmp(sha1, (void *)hdr + size - 20, 20))
487                 return error("bad index file sha1 signature");
488         return 0;
489 }
490
491 int read_cache(void)
492 {
493         int fd, i;
494         struct stat st;
495         unsigned long size, offset;
496         void *map;
497         struct cache_header *hdr;
498
499         errno = EBUSY;
500         if (active_cache)
501                 return active_nr;
502
503         errno = ENOENT;
504         index_file_timestamp = 0;
505         fd = open(get_index_file(), O_RDONLY);
506         if (fd < 0) {
507                 if (errno == ENOENT)
508                         return 0;
509                 die("index file open failed (%s)", strerror(errno));
510         }
511
512         size = 0; // avoid gcc warning
513         map = MAP_FAILED;
514         if (!fstat(fd, &st)) {
515                 size = st.st_size;
516                 errno = EINVAL;
517                 if (size >= sizeof(struct cache_header) + 20)
518                         map = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
519         }
520         close(fd);
521         if (map == MAP_FAILED)
522                 die("index file mmap failed (%s)", strerror(errno));
523
524         hdr = map;
525         if (verify_hdr(hdr, size) < 0)
526                 goto unmap;
527
528         active_nr = ntohl(hdr->hdr_entries);
529         active_alloc = alloc_nr(active_nr);
530         active_cache = calloc(active_alloc, sizeof(struct cache_entry *));
531
532         offset = sizeof(*hdr);
533         for (i = 0; i < active_nr; i++) {
534                 struct cache_entry *ce = map + offset;
535                 offset = offset + ce_size(ce);
536                 active_cache[i] = ce;
537         }
538         index_file_timestamp = st.st_mtime;
539         return active_nr;
540
541 unmap:
542         munmap(map, size);
543         errno = EINVAL;
544         die("index file corrupt");
545 }
546
547 #define WRITE_BUFFER_SIZE 8192
548 static unsigned char write_buffer[WRITE_BUFFER_SIZE];
549 static unsigned long write_buffer_len;
550
551 static int ce_write(SHA_CTX *context, int fd, void *data, unsigned int len)
552 {
553         while (len) {
554                 unsigned int buffered = write_buffer_len;
555                 unsigned int partial = WRITE_BUFFER_SIZE - buffered;
556                 if (partial > len)
557                         partial = len;
558                 memcpy(write_buffer + buffered, data, partial);
559                 buffered += partial;
560                 if (buffered == WRITE_BUFFER_SIZE) {
561                         SHA1_Update(context, write_buffer, WRITE_BUFFER_SIZE);
562                         if (write(fd, write_buffer, WRITE_BUFFER_SIZE) != WRITE_BUFFER_SIZE)
563                                 return -1;
564                         buffered = 0;
565                 }
566                 write_buffer_len = buffered;
567                 len -= partial;
568                 data += partial;
569         }
570         return 0;
571 }
572
573 static int ce_flush(SHA_CTX *context, int fd)
574 {
575         unsigned int left = write_buffer_len;
576
577         if (left) {
578                 write_buffer_len = 0;
579                 SHA1_Update(context, write_buffer, left);
580         }
581
582         /* Flush first if not enough space for SHA1 signature */
583         if (left + 20 > WRITE_BUFFER_SIZE) {
584                 if (write(fd, write_buffer, left) != left)
585                         return -1;
586                 left = 0;
587         }
588
589         /* Append the SHA1 signature at the end */
590         SHA1_Final(write_buffer + left, context);
591         left += 20;
592         if (write(fd, write_buffer, left) != left)
593                 return -1;
594         return 0;
595 }
596
597 int write_cache(int newfd, struct cache_entry **cache, int entries)
598 {
599         SHA_CTX c;
600         struct cache_header hdr;
601         int i, removed;
602
603         for (i = removed = 0; i < entries; i++)
604                 if (!cache[i]->ce_mode)
605                         removed++;
606
607         hdr.hdr_signature = htonl(CACHE_SIGNATURE);
608         hdr.hdr_version = htonl(2);
609         hdr.hdr_entries = htonl(entries - removed);
610
611         SHA1_Init(&c);
612         if (ce_write(&c, newfd, &hdr, sizeof(hdr)) < 0)
613                 return -1;
614
615         for (i = 0; i < entries; i++) {
616                 struct cache_entry *ce = cache[i];
617                 if (!ce->ce_mode)
618                         continue;
619                 if (ce_write(&c, newfd, ce, ce_size(ce)) < 0)
620                         return -1;
621         }
622         return ce_flush(&c, newfd);
623 }