THIS IS A TEST INSTANCE ONLY! REPOSITORIES CAN BE DELETED AT ANY TIME!

Git Source Code Mirror - This is a publish-only repository and all pull requests are ignored. Please follow Documentation/SubmittingPatches procedure for any of your improvements.
git
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2981 lines
79KB

  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 "config.h"
  9. #include "diff.h"
  10. #include "diffcore.h"
  11. #include "tempfile.h"
  12. #include "lockfile.h"
  13. #include "cache-tree.h"
  14. #include "refs.h"
  15. #include "dir.h"
  16. #include "object-store.h"
  17. #include "tree.h"
  18. #include "commit.h"
  19. #include "blob.h"
  20. #include "resolve-undo.h"
  21. #include "strbuf.h"
  22. #include "varint.h"
  23. #include "split-index.h"
  24. #include "utf8.h"
  25. #include "fsmonitor.h"
  26. /* Mask for the name length in ce_flags in the on-disk index */
  27. #define CE_NAMEMASK (0x0fff)
  28. /* Index extensions.
  29. *
  30. * The first letter should be 'A'..'Z' for extensions that are not
  31. * necessary for a correct operation (i.e. optimization data).
  32. * When new extensions are added that _needs_ to be understood in
  33. * order to correctly interpret the index file, pick character that
  34. * is outside the range, to cause the reader to abort.
  35. */
  36. #define CACHE_EXT(s) ( (s[0]<<24)|(s[1]<<16)|(s[2]<<8)|(s[3]) )
  37. #define CACHE_EXT_TREE 0x54524545 /* "TREE" */
  38. #define CACHE_EXT_RESOLVE_UNDO 0x52455543 /* "REUC" */
  39. #define CACHE_EXT_LINK 0x6c696e6b /* "link" */
  40. #define CACHE_EXT_UNTRACKED 0x554E5452 /* "UNTR" */
  41. #define CACHE_EXT_FSMONITOR 0x46534D4E /* "FSMN" */
  42. /* changes that can be kept in $GIT_DIR/index (basically all extensions) */
  43. #define EXTMASK (RESOLVE_UNDO_CHANGED | CACHE_TREE_CHANGED | \
  44. CE_ENTRY_ADDED | CE_ENTRY_REMOVED | CE_ENTRY_CHANGED | \
  45. SPLIT_INDEX_ORDERED | UNTRACKED_CHANGED | FSMONITOR_CHANGED)
  46. /*
  47. * This is an estimate of the pathname length in the index. We use
  48. * this for V4 index files to guess the un-deltafied size of the index
  49. * in memory because of pathname deltafication. This is not required
  50. * for V2/V3 index formats because their pathnames are not compressed.
  51. * If the initial amount of memory set aside is not sufficient, the
  52. * mem pool will allocate extra memory.
  53. */
  54. #define CACHE_ENTRY_PATH_LENGTH 80
  55. static inline struct cache_entry *mem_pool__ce_alloc(struct mem_pool *mem_pool, size_t len)
  56. {
  57. struct cache_entry *ce;
  58. ce = mem_pool_alloc(mem_pool, cache_entry_size(len));
  59. ce->mem_pool_allocated = 1;
  60. return ce;
  61. }
  62. static inline struct cache_entry *mem_pool__ce_calloc(struct mem_pool *mem_pool, size_t len)
  63. {
  64. struct cache_entry * ce;
  65. ce = mem_pool_calloc(mem_pool, 1, cache_entry_size(len));
  66. ce->mem_pool_allocated = 1;
  67. return ce;
  68. }
  69. static struct mem_pool *find_mem_pool(struct index_state *istate)
  70. {
  71. struct mem_pool **pool_ptr;
  72. if (istate->split_index && istate->split_index->base)
  73. pool_ptr = &istate->split_index->base->ce_mem_pool;
  74. else
  75. pool_ptr = &istate->ce_mem_pool;
  76. if (!*pool_ptr)
  77. mem_pool_init(pool_ptr, 0);
  78. return *pool_ptr;
  79. }
  80. struct index_state the_index;
  81. static const char *alternate_index_output;
  82. static void set_index_entry(struct index_state *istate, int nr, struct cache_entry *ce)
  83. {
  84. istate->cache[nr] = ce;
  85. add_name_hash(istate, ce);
  86. }
  87. static void replace_index_entry(struct index_state *istate, int nr, struct cache_entry *ce)
  88. {
  89. struct cache_entry *old = istate->cache[nr];
  90. replace_index_entry_in_base(istate, old, ce);
  91. remove_name_hash(istate, old);
  92. discard_cache_entry(old);
  93. ce->ce_flags &= ~CE_HASHED;
  94. set_index_entry(istate, nr, ce);
  95. ce->ce_flags |= CE_UPDATE_IN_BASE;
  96. mark_fsmonitor_invalid(istate, ce);
  97. istate->cache_changed |= CE_ENTRY_CHANGED;
  98. }
  99. void rename_index_entry_at(struct index_state *istate, int nr, const char *new_name)
  100. {
  101. struct cache_entry *old_entry = istate->cache[nr], *new_entry;
  102. int namelen = strlen(new_name);
  103. new_entry = make_empty_cache_entry(istate, namelen);
  104. copy_cache_entry(new_entry, old_entry);
  105. new_entry->ce_flags &= ~CE_HASHED;
  106. new_entry->ce_namelen = namelen;
  107. new_entry->index = 0;
  108. memcpy(new_entry->name, new_name, namelen + 1);
  109. cache_tree_invalidate_path(istate, old_entry->name);
  110. untracked_cache_remove_from_index(istate, old_entry->name);
  111. remove_index_entry_at(istate, nr);
  112. add_index_entry(istate, new_entry, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
  113. }
  114. void fill_stat_data(struct stat_data *sd, struct stat *st)
  115. {
  116. sd->sd_ctime.sec = (unsigned int)st->st_ctime;
  117. sd->sd_mtime.sec = (unsigned int)st->st_mtime;
  118. sd->sd_ctime.nsec = ST_CTIME_NSEC(*st);
  119. sd->sd_mtime.nsec = ST_MTIME_NSEC(*st);
  120. sd->sd_dev = st->st_dev;
  121. sd->sd_ino = st->st_ino;
  122. sd->sd_uid = st->st_uid;
  123. sd->sd_gid = st->st_gid;
  124. sd->sd_size = st->st_size;
  125. }
  126. int match_stat_data(const struct stat_data *sd, struct stat *st)
  127. {
  128. int changed = 0;
  129. if (sd->sd_mtime.sec != (unsigned int)st->st_mtime)
  130. changed |= MTIME_CHANGED;
  131. if (trust_ctime && check_stat &&
  132. sd->sd_ctime.sec != (unsigned int)st->st_ctime)
  133. changed |= CTIME_CHANGED;
  134. #ifdef USE_NSEC
  135. if (check_stat && sd->sd_mtime.nsec != ST_MTIME_NSEC(*st))
  136. changed |= MTIME_CHANGED;
  137. if (trust_ctime && check_stat &&
  138. sd->sd_ctime.nsec != ST_CTIME_NSEC(*st))
  139. changed |= CTIME_CHANGED;
  140. #endif
  141. if (check_stat) {
  142. if (sd->sd_uid != (unsigned int) st->st_uid ||
  143. sd->sd_gid != (unsigned int) st->st_gid)
  144. changed |= OWNER_CHANGED;
  145. if (sd->sd_ino != (unsigned int) st->st_ino)
  146. changed |= INODE_CHANGED;
  147. }
  148. #ifdef USE_STDEV
  149. /*
  150. * st_dev breaks on network filesystems where different
  151. * clients will have different views of what "device"
  152. * the filesystem is on
  153. */
  154. if (check_stat && sd->sd_dev != (unsigned int) st->st_dev)
  155. changed |= INODE_CHANGED;
  156. #endif
  157. if (sd->sd_size != (unsigned int) st->st_size)
  158. changed |= DATA_CHANGED;
  159. return changed;
  160. }
  161. /*
  162. * This only updates the "non-critical" parts of the directory
  163. * cache, ie the parts that aren't tracked by GIT, and only used
  164. * to validate the cache.
  165. */
  166. void fill_stat_cache_info(struct cache_entry *ce, struct stat *st)
  167. {
  168. fill_stat_data(&ce->ce_stat_data, st);
  169. if (assume_unchanged)
  170. ce->ce_flags |= CE_VALID;
  171. if (S_ISREG(st->st_mode)) {
  172. ce_mark_uptodate(ce);
  173. mark_fsmonitor_valid(ce);
  174. }
  175. }
  176. static int ce_compare_data(const struct cache_entry *ce, struct stat *st)
  177. {
  178. int match = -1;
  179. int fd = git_open_cloexec(ce->name, O_RDONLY);
  180. if (fd >= 0) {
  181. struct object_id oid;
  182. if (!index_fd(&oid, fd, st, OBJ_BLOB, ce->name, 0))
  183. match = oidcmp(&oid, &ce->oid);
  184. /* index_fd() closed the file descriptor already */
  185. }
  186. return match;
  187. }
  188. static int ce_compare_link(const struct cache_entry *ce, size_t expected_size)
  189. {
  190. int match = -1;
  191. void *buffer;
  192. unsigned long size;
  193. enum object_type type;
  194. struct strbuf sb = STRBUF_INIT;
  195. if (strbuf_readlink(&sb, ce->name, expected_size))
  196. return -1;
  197. buffer = read_object_file(&ce->oid, &type, &size);
  198. if (buffer) {
  199. if (size == sb.len)
  200. match = memcmp(buffer, sb.buf, size);
  201. free(buffer);
  202. }
  203. strbuf_release(&sb);
  204. return match;
  205. }
  206. static int ce_compare_gitlink(const struct cache_entry *ce)
  207. {
  208. struct object_id oid;
  209. /*
  210. * We don't actually require that the .git directory
  211. * under GITLINK directory be a valid git directory. It
  212. * might even be missing (in case nobody populated that
  213. * sub-project).
  214. *
  215. * If so, we consider it always to match.
  216. */
  217. if (resolve_gitlink_ref(ce->name, "HEAD", &oid) < 0)
  218. return 0;
  219. return oidcmp(&oid, &ce->oid);
  220. }
  221. static int ce_modified_check_fs(const struct cache_entry *ce, struct stat *st)
  222. {
  223. switch (st->st_mode & S_IFMT) {
  224. case S_IFREG:
  225. if (ce_compare_data(ce, st))
  226. return DATA_CHANGED;
  227. break;
  228. case S_IFLNK:
  229. if (ce_compare_link(ce, xsize_t(st->st_size)))
  230. return DATA_CHANGED;
  231. break;
  232. case S_IFDIR:
  233. if (S_ISGITLINK(ce->ce_mode))
  234. return ce_compare_gitlink(ce) ? DATA_CHANGED : 0;
  235. /* else fallthrough */
  236. default:
  237. return TYPE_CHANGED;
  238. }
  239. return 0;
  240. }
  241. static int ce_match_stat_basic(const struct cache_entry *ce, struct stat *st)
  242. {
  243. unsigned int changed = 0;
  244. if (ce->ce_flags & CE_REMOVE)
  245. return MODE_CHANGED | DATA_CHANGED | TYPE_CHANGED;
  246. switch (ce->ce_mode & S_IFMT) {
  247. case S_IFREG:
  248. changed |= !S_ISREG(st->st_mode) ? TYPE_CHANGED : 0;
  249. /* We consider only the owner x bit to be relevant for
  250. * "mode changes"
  251. */
  252. if (trust_executable_bit &&
  253. (0100 & (ce->ce_mode ^ st->st_mode)))
  254. changed |= MODE_CHANGED;
  255. break;
  256. case S_IFLNK:
  257. if (!S_ISLNK(st->st_mode) &&
  258. (has_symlinks || !S_ISREG(st->st_mode)))
  259. changed |= TYPE_CHANGED;
  260. break;
  261. case S_IFGITLINK:
  262. /* We ignore most of the st_xxx fields for gitlinks */
  263. if (!S_ISDIR(st->st_mode))
  264. changed |= TYPE_CHANGED;
  265. else if (ce_compare_gitlink(ce))
  266. changed |= DATA_CHANGED;
  267. return changed;
  268. default:
  269. die("internal error: ce_mode is %o", ce->ce_mode);
  270. }
  271. changed |= match_stat_data(&ce->ce_stat_data, st);
  272. /* Racily smudged entry? */
  273. if (!ce->ce_stat_data.sd_size) {
  274. if (!is_empty_blob_sha1(ce->oid.hash))
  275. changed |= DATA_CHANGED;
  276. }
  277. return changed;
  278. }
  279. static int is_racy_stat(const struct index_state *istate,
  280. const struct stat_data *sd)
  281. {
  282. return (istate->timestamp.sec &&
  283. #ifdef USE_NSEC
  284. /* nanosecond timestamped files can also be racy! */
  285. (istate->timestamp.sec < sd->sd_mtime.sec ||
  286. (istate->timestamp.sec == sd->sd_mtime.sec &&
  287. istate->timestamp.nsec <= sd->sd_mtime.nsec))
  288. #else
  289. istate->timestamp.sec <= sd->sd_mtime.sec
  290. #endif
  291. );
  292. }
  293. static int is_racy_timestamp(const struct index_state *istate,
  294. const struct cache_entry *ce)
  295. {
  296. return (!S_ISGITLINK(ce->ce_mode) &&
  297. is_racy_stat(istate, &ce->ce_stat_data));
  298. }
  299. int match_stat_data_racy(const struct index_state *istate,
  300. const struct stat_data *sd, struct stat *st)
  301. {
  302. if (is_racy_stat(istate, sd))
  303. return MTIME_CHANGED;
  304. return match_stat_data(sd, st);
  305. }
  306. int ie_match_stat(struct index_state *istate,
  307. const struct cache_entry *ce, struct stat *st,
  308. unsigned int options)
  309. {
  310. unsigned int changed;
  311. int ignore_valid = options & CE_MATCH_IGNORE_VALID;
  312. int ignore_skip_worktree = options & CE_MATCH_IGNORE_SKIP_WORKTREE;
  313. int assume_racy_is_modified = options & CE_MATCH_RACY_IS_DIRTY;
  314. int ignore_fsmonitor = options & CE_MATCH_IGNORE_FSMONITOR;
  315. if (!ignore_fsmonitor)
  316. refresh_fsmonitor(istate);
  317. /*
  318. * If it's marked as always valid in the index, it's
  319. * valid whatever the checked-out copy says.
  320. *
  321. * skip-worktree has the same effect with higher precedence
  322. */
  323. if (!ignore_skip_worktree && ce_skip_worktree(ce))
  324. return 0;
  325. if (!ignore_valid && (ce->ce_flags & CE_VALID))
  326. return 0;
  327. if (!ignore_fsmonitor && (ce->ce_flags & CE_FSMONITOR_VALID))
  328. return 0;
  329. /*
  330. * Intent-to-add entries have not been added, so the index entry
  331. * by definition never matches what is in the work tree until it
  332. * actually gets added.
  333. */
  334. if (ce_intent_to_add(ce))
  335. return DATA_CHANGED | TYPE_CHANGED | MODE_CHANGED;
  336. changed = ce_match_stat_basic(ce, st);
  337. /*
  338. * Within 1 second of this sequence:
  339. * echo xyzzy >file && git-update-index --add file
  340. * running this command:
  341. * echo frotz >file
  342. * would give a falsely clean cache entry. The mtime and
  343. * length match the cache, and other stat fields do not change.
  344. *
  345. * We could detect this at update-index time (the cache entry
  346. * being registered/updated records the same time as "now")
  347. * and delay the return from git-update-index, but that would
  348. * effectively mean we can make at most one commit per second,
  349. * which is not acceptable. Instead, we check cache entries
  350. * whose mtime are the same as the index file timestamp more
  351. * carefully than others.
  352. */
  353. if (!changed && is_racy_timestamp(istate, ce)) {
  354. if (assume_racy_is_modified)
  355. changed |= DATA_CHANGED;
  356. else
  357. changed |= ce_modified_check_fs(ce, st);
  358. }
  359. return changed;
  360. }
  361. int ie_modified(struct index_state *istate,
  362. const struct cache_entry *ce,
  363. struct stat *st, unsigned int options)
  364. {
  365. int changed, changed_fs;
  366. changed = ie_match_stat(istate, ce, st, options);
  367. if (!changed)
  368. return 0;
  369. /*
  370. * If the mode or type has changed, there's no point in trying
  371. * to refresh the entry - it's not going to match
  372. */
  373. if (changed & (MODE_CHANGED | TYPE_CHANGED))
  374. return changed;
  375. /*
  376. * Immediately after read-tree or update-index --cacheinfo,
  377. * the length field is zero, as we have never even read the
  378. * lstat(2) information once, and we cannot trust DATA_CHANGED
  379. * returned by ie_match_stat() which in turn was returned by
  380. * ce_match_stat_basic() to signal that the filesize of the
  381. * blob changed. We have to actually go to the filesystem to
  382. * see if the contents match, and if so, should answer "unchanged".
  383. *
  384. * The logic does not apply to gitlinks, as ce_match_stat_basic()
  385. * already has checked the actual HEAD from the filesystem in the
  386. * subproject. If ie_match_stat() already said it is different,
  387. * then we know it is.
  388. */
  389. if ((changed & DATA_CHANGED) &&
  390. (S_ISGITLINK(ce->ce_mode) || ce->ce_stat_data.sd_size != 0))
  391. return changed;
  392. changed_fs = ce_modified_check_fs(ce, st);
  393. if (changed_fs)
  394. return changed | changed_fs;
  395. return 0;
  396. }
  397. int base_name_compare(const char *name1, int len1, int mode1,
  398. const char *name2, int len2, int mode2)
  399. {
  400. unsigned char c1, c2;
  401. int len = len1 < len2 ? len1 : len2;
  402. int cmp;
  403. cmp = memcmp(name1, name2, len);
  404. if (cmp)
  405. return cmp;
  406. c1 = name1[len];
  407. c2 = name2[len];
  408. if (!c1 && S_ISDIR(mode1))
  409. c1 = '/';
  410. if (!c2 && S_ISDIR(mode2))
  411. c2 = '/';
  412. return (c1 < c2) ? -1 : (c1 > c2) ? 1 : 0;
  413. }
  414. /*
  415. * df_name_compare() is identical to base_name_compare(), except it
  416. * compares conflicting directory/file entries as equal. Note that
  417. * while a directory name compares as equal to a regular file, they
  418. * then individually compare _differently_ to a filename that has
  419. * a dot after the basename (because '\0' < '.' < '/').
  420. *
  421. * This is used by routines that want to traverse the git namespace
  422. * but then handle conflicting entries together when possible.
  423. */
  424. int df_name_compare(const char *name1, int len1, int mode1,
  425. const char *name2, int len2, int mode2)
  426. {
  427. int len = len1 < len2 ? len1 : len2, cmp;
  428. unsigned char c1, c2;
  429. cmp = memcmp(name1, name2, len);
  430. if (cmp)
  431. return cmp;
  432. /* Directories and files compare equal (same length, same name) */
  433. if (len1 == len2)
  434. return 0;
  435. c1 = name1[len];
  436. if (!c1 && S_ISDIR(mode1))
  437. c1 = '/';
  438. c2 = name2[len];
  439. if (!c2 && S_ISDIR(mode2))
  440. c2 = '/';
  441. if (c1 == '/' && !c2)
  442. return 0;
  443. if (c2 == '/' && !c1)
  444. return 0;
  445. return c1 - c2;
  446. }
  447. int name_compare(const char *name1, size_t len1, const char *name2, size_t len2)
  448. {
  449. size_t min_len = (len1 < len2) ? len1 : len2;
  450. int cmp = memcmp(name1, name2, min_len);
  451. if (cmp)
  452. return cmp;
  453. if (len1 < len2)
  454. return -1;
  455. if (len1 > len2)
  456. return 1;
  457. return 0;
  458. }
  459. int cache_name_stage_compare(const char *name1, int len1, int stage1, const char *name2, int len2, int stage2)
  460. {
  461. int cmp;
  462. cmp = name_compare(name1, len1, name2, len2);
  463. if (cmp)
  464. return cmp;
  465. if (stage1 < stage2)
  466. return -1;
  467. if (stage1 > stage2)
  468. return 1;
  469. return 0;
  470. }
  471. static int index_name_stage_pos(const struct index_state *istate, const char *name, int namelen, int stage)
  472. {
  473. int first, last;
  474. first = 0;
  475. last = istate->cache_nr;
  476. while (last > first) {
  477. int next = (last + first) >> 1;
  478. struct cache_entry *ce = istate->cache[next];
  479. int cmp = cache_name_stage_compare(name, namelen, stage, ce->name, ce_namelen(ce), ce_stage(ce));
  480. if (!cmp)
  481. return next;
  482. if (cmp < 0) {
  483. last = next;
  484. continue;
  485. }
  486. first = next+1;
  487. }
  488. return -first-1;
  489. }
  490. int index_name_pos(const struct index_state *istate, const char *name, int namelen)
  491. {
  492. return index_name_stage_pos(istate, name, namelen, 0);
  493. }
  494. int remove_index_entry_at(struct index_state *istate, int pos)
  495. {
  496. struct cache_entry *ce = istate->cache[pos];
  497. record_resolve_undo(istate, ce);
  498. remove_name_hash(istate, ce);
  499. save_or_free_index_entry(istate, ce);
  500. istate->cache_changed |= CE_ENTRY_REMOVED;
  501. istate->cache_nr--;
  502. if (pos >= istate->cache_nr)
  503. return 0;
  504. MOVE_ARRAY(istate->cache + pos, istate->cache + pos + 1,
  505. istate->cache_nr - pos);
  506. return 1;
  507. }
  508. /*
  509. * Remove all cache entries marked for removal, that is where
  510. * CE_REMOVE is set in ce_flags. This is much more effective than
  511. * calling remove_index_entry_at() for each entry to be removed.
  512. */
  513. void remove_marked_cache_entries(struct index_state *istate)
  514. {
  515. struct cache_entry **ce_array = istate->cache;
  516. unsigned int i, j;
  517. for (i = j = 0; i < istate->cache_nr; i++) {
  518. if (ce_array[i]->ce_flags & CE_REMOVE) {
  519. remove_name_hash(istate, ce_array[i]);
  520. save_or_free_index_entry(istate, ce_array[i]);
  521. }
  522. else
  523. ce_array[j++] = ce_array[i];
  524. }
  525. if (j == istate->cache_nr)
  526. return;
  527. istate->cache_changed |= CE_ENTRY_REMOVED;
  528. istate->cache_nr = j;
  529. }
  530. int remove_file_from_index(struct index_state *istate, const char *path)
  531. {
  532. int pos = index_name_pos(istate, path, strlen(path));
  533. if (pos < 0)
  534. pos = -pos-1;
  535. cache_tree_invalidate_path(istate, path);
  536. untracked_cache_remove_from_index(istate, path);
  537. while (pos < istate->cache_nr && !strcmp(istate->cache[pos]->name, path))
  538. remove_index_entry_at(istate, pos);
  539. return 0;
  540. }
  541. static int compare_name(struct cache_entry *ce, const char *path, int namelen)
  542. {
  543. return namelen != ce_namelen(ce) || memcmp(path, ce->name, namelen);
  544. }
  545. static int index_name_pos_also_unmerged(struct index_state *istate,
  546. const char *path, int namelen)
  547. {
  548. int pos = index_name_pos(istate, path, namelen);
  549. struct cache_entry *ce;
  550. if (pos >= 0)
  551. return pos;
  552. /* maybe unmerged? */
  553. pos = -1 - pos;
  554. if (pos >= istate->cache_nr ||
  555. compare_name((ce = istate->cache[pos]), path, namelen))
  556. return -1;
  557. /* order of preference: stage 2, 1, 3 */
  558. if (ce_stage(ce) == 1 && pos + 1 < istate->cache_nr &&
  559. ce_stage((ce = istate->cache[pos + 1])) == 2 &&
  560. !compare_name(ce, path, namelen))
  561. pos++;
  562. return pos;
  563. }
  564. static int different_name(struct cache_entry *ce, struct cache_entry *alias)
  565. {
  566. int len = ce_namelen(ce);
  567. return ce_namelen(alias) != len || memcmp(ce->name, alias->name, len);
  568. }
  569. /*
  570. * If we add a filename that aliases in the cache, we will use the
  571. * name that we already have - but we don't want to update the same
  572. * alias twice, because that implies that there were actually two
  573. * different files with aliasing names!
  574. *
  575. * So we use the CE_ADDED flag to verify that the alias was an old
  576. * one before we accept it as
  577. */
  578. static struct cache_entry *create_alias_ce(struct index_state *istate,
  579. struct cache_entry *ce,
  580. struct cache_entry *alias)
  581. {
  582. int len;
  583. struct cache_entry *new_entry;
  584. if (alias->ce_flags & CE_ADDED)
  585. die("Will not add file alias '%s' ('%s' already exists in index)", ce->name, alias->name);
  586. /* Ok, create the new entry using the name of the existing alias */
  587. len = ce_namelen(alias);
  588. new_entry = make_empty_cache_entry(istate, len);
  589. memcpy(new_entry->name, alias->name, len);
  590. copy_cache_entry(new_entry, ce);
  591. save_or_free_index_entry(istate, ce);
  592. return new_entry;
  593. }
  594. void set_object_name_for_intent_to_add_entry(struct cache_entry *ce)
  595. {
  596. struct object_id oid;
  597. if (write_object_file("", 0, blob_type, &oid))
  598. die("cannot create an empty blob in the object database");
  599. oidcpy(&ce->oid, &oid);
  600. }
  601. int add_to_index(struct index_state *istate, const char *path, struct stat *st, int flags)
  602. {
  603. int namelen, was_same;
  604. mode_t st_mode = st->st_mode;
  605. struct cache_entry *ce, *alias = NULL;
  606. unsigned ce_option = CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE|CE_MATCH_RACY_IS_DIRTY;
  607. int verbose = flags & (ADD_CACHE_VERBOSE | ADD_CACHE_PRETEND);
  608. int pretend = flags & ADD_CACHE_PRETEND;
  609. int intent_only = flags & ADD_CACHE_INTENT;
  610. int add_option = (ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE|
  611. (intent_only ? ADD_CACHE_NEW_ONLY : 0));
  612. int newflags = HASH_WRITE_OBJECT;
  613. if (flags & HASH_RENORMALIZE)
  614. newflags |= HASH_RENORMALIZE;
  615. if (!S_ISREG(st_mode) && !S_ISLNK(st_mode) && !S_ISDIR(st_mode))
  616. return error("%s: can only add regular files, symbolic links or git-directories", path);
  617. namelen = strlen(path);
  618. if (S_ISDIR(st_mode)) {
  619. while (namelen && path[namelen-1] == '/')
  620. namelen--;
  621. }
  622. ce = make_empty_cache_entry(istate, namelen);
  623. memcpy(ce->name, path, namelen);
  624. ce->ce_namelen = namelen;
  625. if (!intent_only)
  626. fill_stat_cache_info(ce, st);
  627. else
  628. ce->ce_flags |= CE_INTENT_TO_ADD;
  629. if (trust_executable_bit && has_symlinks) {
  630. ce->ce_mode = create_ce_mode(st_mode);
  631. } else {
  632. /* If there is an existing entry, pick the mode bits and type
  633. * from it, otherwise assume unexecutable regular file.
  634. */
  635. struct cache_entry *ent;
  636. int pos = index_name_pos_also_unmerged(istate, path, namelen);
  637. ent = (0 <= pos) ? istate->cache[pos] : NULL;
  638. ce->ce_mode = ce_mode_from_stat(ent, st_mode);
  639. }
  640. /* When core.ignorecase=true, determine if a directory of the same name but differing
  641. * case already exists within the Git repository. If it does, ensure the directory
  642. * case of the file being added to the repository matches (is folded into) the existing
  643. * entry's directory case.
  644. */
  645. if (ignore_case) {
  646. adjust_dirname_case(istate, ce->name);
  647. }
  648. if (!(flags & HASH_RENORMALIZE)) {
  649. alias = index_file_exists(istate, ce->name,
  650. ce_namelen(ce), ignore_case);
  651. if (alias &&
  652. !ce_stage(alias) &&
  653. !ie_match_stat(istate, alias, st, ce_option)) {
  654. /* Nothing changed, really */
  655. if (!S_ISGITLINK(alias->ce_mode))
  656. ce_mark_uptodate(alias);
  657. alias->ce_flags |= CE_ADDED;
  658. discard_cache_entry(ce);
  659. return 0;
  660. }
  661. }
  662. if (!intent_only) {
  663. if (index_path(&ce->oid, path, st, newflags)) {
  664. discard_cache_entry(ce);
  665. return error("unable to index file %s", path);
  666. }
  667. } else
  668. set_object_name_for_intent_to_add_entry(ce);
  669. if (ignore_case && alias && different_name(ce, alias))
  670. ce = create_alias_ce(istate, ce, alias);
  671. ce->ce_flags |= CE_ADDED;
  672. /* It was suspected to be racily clean, but it turns out to be Ok */
  673. was_same = (alias &&
  674. !ce_stage(alias) &&
  675. oideq(&alias->oid, &ce->oid) &&
  676. ce->ce_mode == alias->ce_mode);
  677. if (pretend)
  678. discard_cache_entry(ce);
  679. else if (add_index_entry(istate, ce, add_option)) {
  680. discard_cache_entry(ce);
  681. return error("unable to add %s to index", path);
  682. }
  683. if (verbose && !was_same)
  684. printf("add '%s'\n", path);
  685. return 0;
  686. }
  687. int add_file_to_index(struct index_state *istate, const char *path, int flags)
  688. {
  689. struct stat st;
  690. if (lstat(path, &st))
  691. die_errno("unable to stat '%s'", path);
  692. return add_to_index(istate, path, &st, flags);
  693. }
  694. struct cache_entry *make_empty_cache_entry(struct index_state *istate, size_t len)
  695. {
  696. return mem_pool__ce_calloc(find_mem_pool(istate), len);
  697. }
  698. struct cache_entry *make_empty_transient_cache_entry(size_t len)
  699. {
  700. return xcalloc(1, cache_entry_size(len));
  701. }
  702. struct cache_entry *make_cache_entry(struct index_state *istate,
  703. unsigned int mode,
  704. const struct object_id *oid,
  705. const char *path,
  706. int stage,
  707. unsigned int refresh_options)
  708. {
  709. struct cache_entry *ce, *ret;
  710. int len;
  711. if (!verify_path(path, mode)) {
  712. error("Invalid path '%s'", path);
  713. return NULL;
  714. }
  715. len = strlen(path);
  716. ce = make_empty_cache_entry(istate, len);
  717. oidcpy(&ce->oid, oid);
  718. memcpy(ce->name, path, len);
  719. ce->ce_flags = create_ce_flags(stage);
  720. ce->ce_namelen = len;
  721. ce->ce_mode = create_ce_mode(mode);
  722. ret = refresh_cache_entry(&the_index, ce, refresh_options);
  723. if (ret != ce)
  724. discard_cache_entry(ce);
  725. return ret;
  726. }
  727. struct cache_entry *make_transient_cache_entry(unsigned int mode, const struct object_id *oid,
  728. const char *path, int stage)
  729. {
  730. struct cache_entry *ce;
  731. int len;
  732. if (!verify_path(path, mode)) {
  733. error("Invalid path '%s'", path);
  734. return NULL;
  735. }
  736. len = strlen(path);
  737. ce = make_empty_transient_cache_entry(len);
  738. oidcpy(&ce->oid, oid);
  739. memcpy(ce->name, path, len);
  740. ce->ce_flags = create_ce_flags(stage);
  741. ce->ce_namelen = len;
  742. ce->ce_mode = create_ce_mode(mode);
  743. return ce;
  744. }
  745. /*
  746. * Chmod an index entry with either +x or -x.
  747. *
  748. * Returns -1 if the chmod for the particular cache entry failed (if it's
  749. * not a regular file), -2 if an invalid flip argument is passed in, 0
  750. * otherwise.
  751. */
  752. int chmod_index_entry(struct index_state *istate, struct cache_entry *ce,
  753. char flip)
  754. {
  755. if (!S_ISREG(ce->ce_mode))
  756. return -1;
  757. switch (flip) {
  758. case '+':
  759. ce->ce_mode |= 0111;
  760. break;
  761. case '-':
  762. ce->ce_mode &= ~0111;
  763. break;
  764. default:
  765. return -2;
  766. }
  767. cache_tree_invalidate_path(istate, ce->name);
  768. ce->ce_flags |= CE_UPDATE_IN_BASE;
  769. mark_fsmonitor_invalid(istate, ce);
  770. istate->cache_changed |= CE_ENTRY_CHANGED;
  771. return 0;
  772. }
  773. int ce_same_name(const struct cache_entry *a, const struct cache_entry *b)
  774. {
  775. int len = ce_namelen(a);
  776. return ce_namelen(b) == len && !memcmp(a->name, b->name, len);
  777. }
  778. /*
  779. * We fundamentally don't like some paths: we don't want
  780. * dot or dot-dot anywhere, and for obvious reasons don't
  781. * want to recurse into ".git" either.
  782. *
  783. * Also, we don't want double slashes or slashes at the
  784. * end that can make pathnames ambiguous.
  785. */
  786. static int verify_dotfile(const char *rest, unsigned mode)
  787. {
  788. /*
  789. * The first character was '.', but that
  790. * has already been discarded, we now test
  791. * the rest.
  792. */
  793. /* "." is not allowed */
  794. if (*rest == '\0' || is_dir_sep(*rest))
  795. return 0;
  796. switch (*rest) {
  797. /*
  798. * ".git" followed by NUL or slash is bad. Note that we match
  799. * case-insensitively here, even if ignore_case is not set.
  800. * This outlaws ".GIT" everywhere out of an abundance of caution,
  801. * since there's really no good reason to allow it.
  802. *
  803. * Once we've seen ".git", we can also find ".gitmodules", etc (also
  804. * case-insensitively).
  805. */
  806. case 'g':
  807. case 'G':
  808. if (rest[1] != 'i' && rest[1] != 'I')
  809. break;
  810. if (rest[2] != 't' && rest[2] != 'T')
  811. break;
  812. if (rest[3] == '\0' || is_dir_sep(rest[3]))
  813. return 0;
  814. if (S_ISLNK(mode)) {
  815. rest += 3;
  816. if (skip_iprefix(rest, "modules", &rest) &&
  817. (*rest == '\0' || is_dir_sep(*rest)))
  818. return 0;
  819. }
  820. break;
  821. case '.':
  822. if (rest[1] == '\0' || is_dir_sep(rest[1]))
  823. return 0;
  824. }
  825. return 1;
  826. }
  827. int verify_path(const char *path, unsigned mode)
  828. {
  829. char c;
  830. if (has_dos_drive_prefix(path))
  831. return 0;
  832. goto inside;
  833. for (;;) {
  834. if (!c)
  835. return 1;
  836. if (is_dir_sep(c)) {
  837. inside:
  838. if (protect_hfs) {
  839. if (is_hfs_dotgit(path))
  840. return 0;
  841. if (S_ISLNK(mode)) {
  842. if (is_hfs_dotgitmodules(path))
  843. return 0;
  844. }
  845. }
  846. if (protect_ntfs) {
  847. if (is_ntfs_dotgit(path))
  848. return 0;
  849. if (S_ISLNK(mode)) {
  850. if (is_ntfs_dotgitmodules(path))
  851. return 0;
  852. }
  853. }
  854. c = *path++;
  855. if ((c == '.' && !verify_dotfile(path, mode)) ||
  856. is_dir_sep(c) || c == '\0')
  857. return 0;
  858. }
  859. c = *path++;
  860. }
  861. }
  862. /*
  863. * Do we have another file that has the beginning components being a
  864. * proper superset of the name we're trying to add?
  865. */
  866. static int has_file_name(struct index_state *istate,
  867. const struct cache_entry *ce, int pos, int ok_to_replace)
  868. {
  869. int retval = 0;
  870. int len = ce_namelen(ce);
  871. int stage = ce_stage(ce);
  872. const char *name = ce->name;
  873. while (pos < istate->cache_nr) {
  874. struct cache_entry *p = istate->cache[pos++];
  875. if (len >= ce_namelen(p))
  876. break;
  877. if (memcmp(name, p->name, len))
  878. break;
  879. if (ce_stage(p) != stage)
  880. continue;
  881. if (p->name[len] != '/')
  882. continue;
  883. if (p->ce_flags & CE_REMOVE)
  884. continue;
  885. retval = -1;
  886. if (!ok_to_replace)
  887. break;
  888. remove_index_entry_at(istate, --pos);
  889. }
  890. return retval;
  891. }
  892. /*
  893. * Like strcmp(), but also return the offset of the first change.
  894. * If strings are equal, return the length.
  895. */
  896. int strcmp_offset(const char *s1, const char *s2, size_t *first_change)
  897. {
  898. size_t k;
  899. if (!first_change)
  900. return strcmp(s1, s2);
  901. for (k = 0; s1[k] == s2[k]; k++)
  902. if (s1[k] == '\0')
  903. break;
  904. *first_change = k;
  905. return (unsigned char)s1[k] - (unsigned char)s2[k];
  906. }
  907. /*
  908. * Do we have another file with a pathname that is a proper
  909. * subset of the name we're trying to add?
  910. *
  911. * That is, is there another file in the index with a path
  912. * that matches a sub-directory in the given entry?
  913. */
  914. static int has_dir_name(struct index_state *istate,
  915. const struct cache_entry *ce, int pos, int ok_to_replace)
  916. {
  917. int retval = 0;
  918. int stage = ce_stage(ce);
  919. const char *name = ce->name;
  920. const char *slash = name + ce_namelen(ce);
  921. size_t len_eq_last;
  922. int cmp_last = 0;
  923. /*
  924. * We are frequently called during an iteration on a sorted
  925. * list of pathnames and while building a new index. Therefore,
  926. * there is a high probability that this entry will eventually
  927. * be appended to the index, rather than inserted in the middle.
  928. * If we can confirm that, we can avoid binary searches on the
  929. * components of the pathname.
  930. *
  931. * Compare the entry's full path with the last path in the index.
  932. */
  933. if (istate->cache_nr > 0) {
  934. cmp_last = strcmp_offset(name,
  935. istate->cache[istate->cache_nr - 1]->name,
  936. &len_eq_last);
  937. if (cmp_last > 0) {
  938. if (len_eq_last == 0) {
  939. /*
  940. * The entry sorts AFTER the last one in the
  941. * index and their paths have no common prefix,
  942. * so there cannot be a F/D conflict.
  943. */
  944. return retval;
  945. } else {
  946. /*
  947. * The entry sorts AFTER the last one in the
  948. * index, but has a common prefix. Fall through
  949. * to the loop below to disect the entry's path
  950. * and see where the difference is.
  951. */
  952. }
  953. } else if (cmp_last == 0) {
  954. /*
  955. * The entry exactly matches the last one in the
  956. * index, but because of multiple stage and CE_REMOVE
  957. * items, we fall through and let the regular search
  958. * code handle it.
  959. */
  960. }
  961. }
  962. for (;;) {
  963. size_t len;
  964. for (;;) {
  965. if (*--slash == '/')
  966. break;
  967. if (slash <= ce->name)
  968. return retval;
  969. }
  970. len = slash - name;
  971. if (cmp_last > 0) {
  972. /*
  973. * (len + 1) is a directory boundary (including
  974. * the trailing slash). And since the loop is
  975. * decrementing "slash", the first iteration is
  976. * the longest directory prefix; subsequent
  977. * iterations consider parent directories.
  978. */
  979. if (len + 1 <= len_eq_last) {
  980. /*
  981. * The directory prefix (including the trailing
  982. * slash) also appears as a prefix in the last
  983. * entry, so the remainder cannot collide (because
  984. * strcmp said the whole path was greater).
  985. *
  986. * EQ: last: xxx/A
  987. * this: xxx/B
  988. *
  989. * LT: last: xxx/file_A
  990. * this: xxx/file_B
  991. */
  992. return retval;
  993. }
  994. if (len > len_eq_last) {
  995. /*
  996. * This part of the directory prefix (excluding
  997. * the trailing slash) is longer than the known
  998. * equal portions, so this sub-directory cannot
  999. * collide with a file.
  1000. *
  1001. * GT: last: xxxA
  1002. * this: xxxB/file
  1003. */
  1004. return retval;
  1005. }
  1006. if (istate->cache_nr > 0 &&
  1007. ce_namelen(istate->cache[istate->cache_nr - 1]) > len) {
  1008. /*
  1009. * The directory prefix lines up with part of
  1010. * a longer file or directory name, but sorts
  1011. * after it, so this sub-directory cannot
  1012. * collide with a file.
  1013. *
  1014. * last: xxx/yy-file (because '-' sorts before '/')
  1015. * this: xxx/yy/abc
  1016. */
  1017. return retval;
  1018. }
  1019. /*
  1020. * This is a possible collision. Fall through and
  1021. * let the regular search code handle it.
  1022. *
  1023. * last: xxx
  1024. * this: xxx/file
  1025. */
  1026. }
  1027. pos = index_name_stage_pos(istate, name, len, stage);
  1028. if (pos >= 0) {
  1029. /*
  1030. * Found one, but not so fast. This could
  1031. * be a marker that says "I was here, but
  1032. * I am being removed". Such an entry is
  1033. * not a part of the resulting tree, and
  1034. * it is Ok to have a directory at the same
  1035. * path.
  1036. */
  1037. if (!(istate->cache[pos]->ce_flags & CE_REMOVE)) {
  1038. retval = -1;
  1039. if (!ok_to_replace)
  1040. break;
  1041. remove_index_entry_at(istate, pos);
  1042. continue;
  1043. }
  1044. }
  1045. else
  1046. pos = -pos-1;
  1047. /*
  1048. * Trivial optimization: if we find an entry that
  1049. * already matches the sub-directory, then we know
  1050. * we're ok, and we can exit.
  1051. */
  1052. while (pos < istate->cache_nr) {
  1053. struct cache_entry *p = istate->cache[pos];
  1054. if ((ce_namelen(p) <= len) ||
  1055. (p->name[len] != '/') ||
  1056. memcmp(p->name, name, len))
  1057. break; /* not our subdirectory */
  1058. if (ce_stage(p) == stage && !(p->ce_flags & CE_REMOVE))
  1059. /*
  1060. * p is at the same stage as our entry, and
  1061. * is a subdirectory of what we are looking
  1062. * at, so we cannot have conflicts at our
  1063. * level or anything shorter.
  1064. */
  1065. return retval;
  1066. pos++;
  1067. }
  1068. }
  1069. return retval;
  1070. }
  1071. /* We may be in a situation where we already have path/file and path
  1072. * is being added, or we already have path and path/file is being
  1073. * added. Either one would result in a nonsense tree that has path
  1074. * twice when git-write-tree tries to write it out. Prevent it.
  1075. *
  1076. * If ok-to-replace is specified, we remove the conflicting entries
  1077. * from the cache so the caller should recompute the insert position.
  1078. * When this happens, we return non-zero.
  1079. */
  1080. static int check_file_directory_conflict(struct index_state *istate,
  1081. const struct cache_entry *ce,
  1082. int pos, int ok_to_replace)
  1083. {
  1084. int retval;
  1085. /*
  1086. * When ce is an "I am going away" entry, we allow it to be added
  1087. */
  1088. if (ce->ce_flags & CE_REMOVE)
  1089. return 0;
  1090. /*
  1091. * We check if the path is a sub-path of a subsequent pathname
  1092. * first, since removing those will not change the position
  1093. * in the array.
  1094. */
  1095. retval = has_file_name(istate, ce, pos, ok_to_replace);
  1096. /*
  1097. * Then check if the path might have a clashing sub-directory
  1098. * before it.
  1099. */
  1100. return retval + has_dir_name(istate, ce, pos, ok_to_replace);
  1101. }
  1102. static int add_index_entry_with_check(struct index_state *istate, struct cache_entry *ce, int option)
  1103. {
  1104. int pos;
  1105. int ok_to_add = option & ADD_CACHE_OK_TO_ADD;
  1106. int ok_to_replace = option & ADD_CACHE_OK_TO_REPLACE;
  1107. int skip_df_check = option & ADD_CACHE_SKIP_DFCHECK;
  1108. int new_only = option & ADD_CACHE_NEW_ONLY;
  1109. if (!(option & ADD_CACHE_KEEP_CACHE_TREE))
  1110. cache_tree_invalidate_path(istate, ce->name);
  1111. /*
  1112. * If this entry's path sorts after the last entry in the index,
  1113. * we can avoid searching for it.
  1114. */
  1115. if (istate->cache_nr > 0 &&
  1116. strcmp(ce->name, istate->cache[istate->cache_nr - 1]->name) > 0)
  1117. pos = -istate->cache_nr - 1;
  1118. else
  1119. pos = index_name_stage_pos(istate, ce->name, ce_namelen(ce), ce_stage(ce));
  1120. /* existing match? Just replace it. */
  1121. if (pos >= 0) {
  1122. if (!new_only)
  1123. replace_index_entry(istate, pos, ce);
  1124. return 0;
  1125. }
  1126. pos = -pos-1;
  1127. if (!(option & ADD_CACHE_KEEP_CACHE_TREE))
  1128. untracked_cache_add_to_index(istate, ce->name);
  1129. /*
  1130. * Inserting a merged entry ("stage 0") into the index
  1131. * will always replace all non-merged entries..
  1132. */
  1133. if (pos < istate->cache_nr && ce_stage(ce) == 0) {
  1134. while (ce_same_name(istate->cache[pos], ce)) {
  1135. ok_to_add = 1;
  1136. if (!remove_index_entry_at(istate, pos))
  1137. break;
  1138. }
  1139. }
  1140. if (!ok_to_add)
  1141. return -1;
  1142. if (!verify_path(ce->name, ce->ce_mode))
  1143. return error("Invalid path '%s'", ce->name);
  1144. if (!skip_df_check &&
  1145. check_file_directory_conflict(istate, ce, pos, ok_to_replace)) {
  1146. if (!ok_to_replace)
  1147. return error("'%s' appears as both a file and as a directory",
  1148. ce->name);
  1149. pos = index_name_stage_pos(istate, ce->name, ce_namelen(ce), ce_stage(ce));
  1150. pos = -pos-1;
  1151. }
  1152. return pos + 1;
  1153. }
  1154. int add_index_entry(struct index_state *istate, struct cache_entry *ce, int option)
  1155. {
  1156. int pos;
  1157. if (option & ADD_CACHE_JUST_APPEND)
  1158. pos = istate->cache_nr;
  1159. else {
  1160. int ret;
  1161. ret = add_index_entry_with_check(istate, ce, option);
  1162. if (ret <= 0)
  1163. return ret;
  1164. pos = ret - 1;
  1165. }
  1166. /* Make sure the array is big enough .. */
  1167. ALLOC_GROW(istate->cache, istate->cache_nr + 1, istate->cache_alloc);
  1168. /* Add it in.. */
  1169. istate->cache_nr++;
  1170. if (istate->cache_nr > pos + 1)
  1171. MOVE_ARRAY(istate->cache + pos + 1, istate->cache + pos,
  1172. istate->cache_nr - pos - 1);
  1173. set_index_entry(istate, pos, ce);
  1174. istate->cache_changed |= CE_ENTRY_ADDED;
  1175. return 0;
  1176. }
  1177. /*
  1178. * "refresh" does not calculate a new sha1 file or bring the
  1179. * cache up-to-date for mode/content changes. But what it
  1180. * _does_ do is to "re-match" the stat information of a file
  1181. * with the cache, so that you can refresh the cache for a
  1182. * file that hasn't been changed but where the stat entry is
  1183. * out of date.
  1184. *
  1185. * For example, you'd want to do this after doing a "git-read-tree",
  1186. * to link up the stat cache details with the proper files.
  1187. */
  1188. static struct cache_entry *refresh_cache_ent(struct index_state *istate,
  1189. struct cache_entry *ce,
  1190. unsigned int options, int *err,
  1191. int *changed_ret)
  1192. {
  1193. struct stat st;
  1194. struct cache_entry *updated;
  1195. int changed;
  1196. int refresh = options & CE_MATCH_REFRESH;
  1197. int ignore_valid = options & CE_MATCH_IGNORE_VALID;
  1198. int ignore_skip_worktree = options & CE_MATCH_IGNORE_SKIP_WORKTREE;
  1199. int ignore_missing = options & CE_MATCH_IGNORE_MISSING;
  1200. int ignore_fsmonitor = options & CE_MATCH_IGNORE_FSMONITOR;
  1201. if (!refresh || ce_uptodate(ce))
  1202. return ce;
  1203. if (!ignore_fsmonitor)
  1204. refresh_fsmonitor(istate);
  1205. /*
  1206. * CE_VALID or CE_SKIP_WORKTREE means the user promised us
  1207. * that the change to the work tree does not matter and told
  1208. * us not to worry.
  1209. */
  1210. if (!ignore_skip_worktree && ce_skip_worktree(ce)) {
  1211. ce_mark_uptodate(ce);
  1212. return ce;
  1213. }
  1214. if (!ignore_valid && (ce->ce_flags & CE_VALID)) {
  1215. ce_mark_uptodate(ce);
  1216. return ce;
  1217. }
  1218. if (!ignore_fsmonitor && (ce->ce_flags & CE_FSMONITOR_VALID)) {
  1219. ce_mark_uptodate(ce);
  1220. return ce;
  1221. }
  1222. if (has_symlink_leading_path(ce->name, ce_namelen(ce))) {
  1223. if (ignore_missing)
  1224. return ce;
  1225. if (err)
  1226. *err = ENOENT;
  1227. return NULL;
  1228. }
  1229. if (lstat(ce->name, &st) < 0) {
  1230. if (ignore_missing && errno == ENOENT)
  1231. return ce;
  1232. if (err)
  1233. *err = errno;
  1234. return NULL;
  1235. }
  1236. changed = ie_match_stat(istate, ce, &st, options);
  1237. if (changed_ret)
  1238. *changed_ret = changed;
  1239. if (!changed) {
  1240. /*
  1241. * The path is unchanged. If we were told to ignore
  1242. * valid bit, then we did the actual stat check and
  1243. * found that the entry is unmodified. If the entry
  1244. * is not marked VALID, this is the place to mark it
  1245. * valid again, under "assume unchanged" mode.
  1246. */
  1247. if (ignore_valid && assume_unchanged &&
  1248. !(ce->ce_flags & CE_VALID))
  1249. ; /* mark this one VALID again */
  1250. else {
  1251. /*
  1252. * We do not mark the index itself "modified"
  1253. * because CE_UPTODATE flag is in-core only;
  1254. * we are not going to write this change out.
  1255. */
  1256. if (!S_ISGITLINK(ce->ce_mode)) {
  1257. ce_mark_uptodate(ce);
  1258. mark_fsmonitor_valid(ce);
  1259. }
  1260. return ce;
  1261. }
  1262. }
  1263. if (ie_modified(istate, ce, &st, options)) {
  1264. if (err)
  1265. *err = EINVAL;
  1266. return NULL;
  1267. }
  1268. updated = make_empty_cache_entry(istate, ce_namelen(ce));
  1269. copy_cache_entry(updated, ce);
  1270. memcpy(updated->name, ce->name, ce->ce_namelen + 1);
  1271. fill_stat_cache_info(updated, &st);
  1272. /*
  1273. * If ignore_valid is not set, we should leave CE_VALID bit
  1274. * alone. Otherwise, paths marked with --no-assume-unchanged
  1275. * (i.e. things to be edited) will reacquire CE_VALID bit
  1276. * automatically, which is not really what we want.
  1277. */
  1278. if (!ignore_valid && assume_unchanged &&
  1279. !(ce->ce_flags & CE_VALID))
  1280. updated->ce_flags &= ~CE_VALID;
  1281. /* istate->cache_changed is updated in the caller */
  1282. return updated;
  1283. }
  1284. static void show_file(const char * fmt, const char * name, int in_porcelain,
  1285. int * first, const char *header_msg)
  1286. {
  1287. if (in_porcelain && *first && header_msg) {
  1288. printf("%s\n", header_msg);
  1289. *first = 0;
  1290. }
  1291. printf(fmt, name);
  1292. }
  1293. int refresh_index(struct index_state *istate, unsigned int flags,
  1294. const struct pathspec *pathspec,
  1295. char *seen, const char *header_msg)
  1296. {
  1297. int i;
  1298. int has_errors = 0;
  1299. int really = (flags & REFRESH_REALLY) != 0;
  1300. int allow_unmerged = (flags & REFRESH_UNMERGED) != 0;
  1301. int quiet = (flags & REFRESH_QUIET) != 0;
  1302. int not_new = (flags & REFRESH_IGNORE_MISSING) != 0;
  1303. int ignore_submodules = (flags & REFRESH_IGNORE_SUBMODULES) != 0;
  1304. int first = 1;
  1305. int in_porcelain = (flags & REFRESH_IN_PORCELAIN);
  1306. unsigned int options = (CE_MATCH_REFRESH |
  1307. (really ? CE_MATCH_IGNORE_VALID : 0) |
  1308. (not_new ? CE_MATCH_IGNORE_MISSING : 0));
  1309. const char *modified_fmt;
  1310. const char *deleted_fmt;
  1311. const char *typechange_fmt;
  1312. const char *added_fmt;
  1313. const char *unmerged_fmt;
  1314. uint64_t start = getnanotime();
  1315. modified_fmt = (in_porcelain ? "M\t%s\n" : "%s: needs update\n");
  1316. deleted_fmt = (in_porcelain ? "D\t%s\n" : "%s: needs update\n");
  1317. typechange_fmt = (in_porcelain ? "T\t%s\n" : "%s needs update\n");
  1318. added_fmt = (in_porcelain ? "A\t%s\n" : "%s needs update\n");
  1319. unmerged_fmt = (in_porcelain ? "U\t%s\n" : "%s: needs merge\n");
  1320. for (i = 0; i < istate->cache_nr; i++) {
  1321. struct cache_entry *ce, *new_entry;
  1322. int cache_errno = 0;
  1323. int changed = 0;
  1324. int filtered = 0;
  1325. ce = istate->cache[i];
  1326. if (ignore_submodules && S_ISGITLINK(ce->ce_mode))
  1327. continue;
  1328. if (pathspec && !ce_path_match(&the_index, ce, pathspec, seen))
  1329. filtered = 1;
  1330. if (ce_stage(ce)) {
  1331. while ((i < istate->cache_nr) &&
  1332. ! strcmp(istate->cache[i]->name, ce->name))
  1333. i++;
  1334. i--;
  1335. if (allow_unmerged)
  1336. continue;
  1337. if (!filtered)
  1338. show_file(unmerged_fmt, ce->name, in_porcelain,
  1339. &first, header_msg);
  1340. has_errors = 1;
  1341. continue;
  1342. }
  1343. if (filtered)
  1344. continue;
  1345. new_entry = refresh_cache_ent(istate, ce, options, &cache_errno, &changed);
  1346. if (new_entry == ce)
  1347. continue;
  1348. if (!new_entry) {
  1349. const char *fmt;
  1350. if (really && cache_errno == EINVAL) {
  1351. /* If we are doing --really-refresh that
  1352. * means the index is not valid anymore.
  1353. */
  1354. ce->ce_flags &= ~CE_VALID;
  1355. ce->ce_flags |= CE_UPDATE_IN_BASE;
  1356. mark_fsmonitor_invalid(istate, ce);
  1357. istate->cache_changed |= CE_ENTRY_CHANGED;
  1358. }
  1359. if (quiet)
  1360. continue;
  1361. if (cache_errno == ENOENT)
  1362. fmt = deleted_fmt;
  1363. else if (ce_intent_to_add(ce))
  1364. fmt = added_fmt; /* must be before other checks */
  1365. else if (changed & TYPE_CHANGED)
  1366. fmt = typechange_fmt;
  1367. else
  1368. fmt = modified_fmt;
  1369. show_file(fmt,
  1370. ce->name, in_porcelain, &first, header_msg);
  1371. has_errors = 1;
  1372. continue;
  1373. }
  1374. replace_index_entry(istate, i, new_entry);
  1375. }
  1376. trace_performance_since(start, "refresh index");
  1377. return has_errors;
  1378. }
  1379. struct cache_entry *refresh_cache_entry(struct index_state *istate,
  1380. struct cache_entry *ce,
  1381. unsigned int options)
  1382. {
  1383. return refresh_cache_ent(istate, ce, options, NULL, NULL);
  1384. }
  1385. /*****************************************************************
  1386. * Index File I/O
  1387. *****************************************************************/
  1388. #define INDEX_FORMAT_DEFAULT 3
  1389. static unsigned int get_index_format_default(void)
  1390. {
  1391. char *envversion = getenv("GIT_INDEX_VERSION");
  1392. char *endp;
  1393. int value;
  1394. unsigned int version = INDEX_FORMAT_DEFAULT;
  1395. if (!envversion) {
  1396. if (!git_config_get_int("index.version", &value))
  1397. version = value;
  1398. if (version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < version) {
  1399. warning(_("index.version set, but the value is invalid.\n"
  1400. "Using version %i"), INDEX_FORMAT_DEFAULT);
  1401. return INDEX_FORMAT_DEFAULT;
  1402. }
  1403. return version;
  1404. }
  1405. version = strtoul(envversion, &endp, 10);
  1406. if (*endp ||
  1407. version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < version) {
  1408. warning(_("GIT_INDEX_VERSION set, but the value is invalid.\n"
  1409. "Using version %i"), INDEX_FORMAT_DEFAULT);
  1410. version = INDEX_FORMAT_DEFAULT;
  1411. }
  1412. return version;
  1413. }
  1414. /*
  1415. * dev/ino/uid/gid/size are also just tracked to the low 32 bits
  1416. * Again - this is just a (very strong in practice) heuristic that
  1417. * the inode hasn't changed.
  1418. *
  1419. * We save the fields in big-endian order to allow using the
  1420. * index file over NFS transparently.
  1421. */
  1422. struct ondisk_cache_entry {
  1423. struct cache_time ctime;
  1424. struct cache_time mtime;
  1425. uint32_t dev;
  1426. uint32_t ino;
  1427. uint32_t mode;
  1428. uint32_t uid;
  1429. uint32_t gid;
  1430. uint32_t size;
  1431. unsigned char sha1[20];
  1432. uint16_t flags;
  1433. char name[FLEX_ARRAY]; /* more */
  1434. };
  1435. /*
  1436. * This struct is used when CE_EXTENDED bit is 1
  1437. * The struct must match ondisk_cache_entry exactly from
  1438. * ctime till flags
  1439. */
  1440. struct ondisk_cache_entry_extended {
  1441. struct cache_time ctime;
  1442. struct cache_time mtime;
  1443. uint32_t dev;
  1444. uint32_t ino;
  1445. uint32_t mode;
  1446. uint32_t uid;
  1447. uint32_t gid;
  1448. uint32_t size;
  1449. unsigned char sha1[20];
  1450. uint16_t flags;
  1451. uint16_t flags2;
  1452. char name[FLEX_ARRAY]; /* more */
  1453. };
  1454. /* These are only used for v3 or lower */
  1455. #define align_padding_size(size, len) ((size + (len) + 8) & ~7) - (size + len)
  1456. #define align_flex_name(STRUCT,len) ((offsetof(struct STRUCT,name) + (len) + 8) & ~7)
  1457. #define ondisk_cache_entry_size(len) align_flex_name(ondisk_cache_entry,len)
  1458. #define ondisk_cache_entry_extended_size(len) align_flex_name(ondisk_cache_entry_extended,len)
  1459. #define ondisk_ce_size(ce) (((ce)->ce_flags & CE_EXTENDED) ? \
  1460. ondisk_cache_entry_extended_size(ce_namelen(ce)) : \
  1461. ondisk_cache_entry_size(ce_namelen(ce)))
  1462. /* Allow fsck to force verification of the index checksum. */
  1463. int verify_index_checksum;
  1464. /* Allow fsck to force verification of the cache entry order. */
  1465. int verify_ce_order;
  1466. static int verify_hdr(struct cache_header *hdr, unsigned long size)
  1467. {
  1468. git_hash_ctx c;
  1469. unsigned char hash[GIT_MAX_RAWSZ];
  1470. int hdr_version;
  1471. if (hdr->hdr_signature != htonl(CACHE_SIGNATURE))
  1472. return error("bad signature");
  1473. hdr_version = ntohl(hdr->hdr_version);
  1474. if (hdr_version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < hdr_version)
  1475. return error("bad index version %d", hdr_version);
  1476. if (!verify_index_checksum)
  1477. return 0;
  1478. the_hash_algo->init_fn(&c);
  1479. the_hash_algo->update_fn(&c, hdr, size - the_hash_algo->rawsz);
  1480. the_hash_algo->final_fn(hash, &c);
  1481. if (!hasheq(hash, (unsigned char *)hdr + size - the_hash_algo->rawsz))
  1482. return error("bad index file sha1 signature");
  1483. return 0;
  1484. }
  1485. static int read_index_extension(struct index_state *istate,
  1486. const char *ext, void *data, unsigned long sz)
  1487. {
  1488. switch (CACHE_EXT(ext)) {
  1489. case CACHE_EXT_TREE:
  1490. istate->cache_tree = cache_tree_read(data, sz);
  1491. break;
  1492. case CACHE_EXT_RESOLVE_UNDO:
  1493. istate->resolve_undo = resolve_undo_read(data, sz);
  1494. break;
  1495. case CACHE_EXT_LINK:
  1496. if (read_link_extension(istate, data, sz))
  1497. return -1;
  1498. break;
  1499. case CACHE_EXT_UNTRACKED:
  1500. istate->untracked = read_untracked_extension(data, sz);
  1501. break;
  1502. case CACHE_EXT_FSMONITOR:
  1503. read_fsmonitor_extension(istate, data, sz);
  1504. break;
  1505. default:
  1506. if (*ext < 'A' || 'Z' < *ext)
  1507. return error("index uses %.4s extension, which we do not understand",
  1508. ext);
  1509. fprintf(stderr, "ignoring %.4s extension\n", ext);
  1510. break;
  1511. }
  1512. return 0;
  1513. }
  1514. int hold_locked_index(struct lock_file *lk, int lock_flags)
  1515. {
  1516. return hold_lock_file_for_update(lk, get_index_file(), lock_flags);
  1517. }
  1518. int read_index(struct index_state *istate)
  1519. {
  1520. return read_index_from(istate, get_index_file(), get_git_dir());
  1521. }
  1522. static struct cache_entry *cache_entry_from_ondisk(struct mem_pool *mem_pool,
  1523. struct ondisk_cache_entry *ondisk,
  1524. unsigned int flags,
  1525. const char *name,
  1526. size_t len)
  1527. {
  1528. struct cache_entry *ce = mem_pool__ce_alloc(mem_pool, len);
  1529. ce->ce_stat_data.sd_ctime.sec = get_be32(&ondisk->ctime.sec);
  1530. ce->ce_stat_data.sd_mtime.sec = get_be32(&ondisk->mtime.sec);
  1531. ce->ce_stat_data.sd_ctime.nsec = get_be32(&ondisk->ctime.nsec);
  1532. ce->ce_stat_data.sd_mtime.nsec = get_be32(&ondisk->mtime.nsec);
  1533. ce->ce_stat_data.sd_dev = get_be32(&ondisk->dev);
  1534. ce->ce_stat_data.sd_ino = get_be32(&ondisk->ino);
  1535. ce->ce_mode = get_be32(&ondisk->mode);
  1536. ce->ce_stat_data.sd_uid = get_be32(&ondisk->uid);
  1537. ce->ce_stat_data.sd_gid = get_be32(&ondisk->gid);
  1538. ce->ce_stat_data.sd_size = get_be32(&ondisk->size);
  1539. ce->ce_flags = flags & ~CE_NAMEMASK;
  1540. ce->ce_namelen = len;
  1541. ce->index = 0;
  1542. hashcpy(ce->oid.hash, ondisk->sha1);
  1543. memcpy(ce->name, name, len);
  1544. ce->name[len] = '\0';
  1545. return ce;
  1546. }
  1547. /*
  1548. * Adjacent cache entries tend to share the leading paths, so it makes
  1549. * sense to only store the differences in later entries. In the v4
  1550. * on-disk format of the index, each on-disk cache entry stores the
  1551. * number of bytes to be stripped from the end of the previous name,
  1552. * and the bytes to append to the result, to come up with its name.
  1553. */
  1554. static unsigned long expand_name_field(struct strbuf *name, const char *cp_)
  1555. {
  1556. const unsigned char *ep, *cp = (const unsigned char *)cp_;
  1557. size_t len = decode_varint(&cp);
  1558. if (name->len < len)
  1559. die("malformed name field in the index");
  1560. strbuf_remove(name, name->len - len, len);
  1561. for (ep = cp; *ep; ep++)
  1562. ; /* find the end */
  1563. strbuf_add(name, cp, ep - cp);
  1564. return (const char *)ep + 1 - cp_;
  1565. }
  1566. static struct cache_entry *create_from_disk(struct mem_pool *mem_pool,
  1567. struct ondisk_cache_entry *ondisk,
  1568. unsigned long *ent_size,
  1569. struct strbuf *previous_name)
  1570. {
  1571. struct cache_entry *ce;
  1572. size_t len;
  1573. const char *name;
  1574. unsigned int flags;
  1575. /* On-disk flags are just 16 bits */
  1576. flags = get_be16(&ondisk->flags);
  1577. len = flags & CE_NAMEMASK;
  1578. if (flags & CE_EXTENDED) {
  1579. struct ondisk_cache_entry_extended *ondisk2;
  1580. int extended_flags;
  1581. ondisk2 = (struct ondisk_cache_entry_extended *)ondisk;
  1582. extended_flags = get_be16(&ondisk2->flags2) << 16;
  1583. /* We do not yet understand any bit out of CE_EXTENDED_FLAGS */
  1584. if (extended_flags & ~CE_EXTENDED_FLAGS)
  1585. die("Unknown index entry format %08x", extended_flags);
  1586. flags |= extended_flags;
  1587. name = ondisk2->name;
  1588. }
  1589. else
  1590. name = ondisk->name;
  1591. if (!previous_name) {
  1592. /* v3 and earlier */
  1593. if (len == CE_NAMEMASK)
  1594. len = strlen(name);
  1595. ce = cache_entry_from_ondisk(mem_pool, ondisk, flags, name, len);
  1596. *ent_size = ondisk_ce_size(ce);
  1597. } else {
  1598. unsigned long consumed;
  1599. consumed = expand_name_field(previous_name, name);
  1600. ce = cache_entry_from_ondisk(mem_pool, ondisk, flags,
  1601. previous_name->buf,
  1602. previous_name->len);
  1603. *ent_size = (name - ((char *)ondisk)) + consumed;
  1604. }
  1605. return ce;
  1606. }
  1607. static void check_ce_order(struct index_state *istate)
  1608. {
  1609. unsigned int i;
  1610. if (!verify_ce_order)
  1611. return;
  1612. for (i = 1; i < istate->cache_nr; i++) {
  1613. struct cache_entry *ce = istate->cache[i - 1];
  1614. struct cache_entry *next_ce = istate->cache[i];
  1615. int name_compare = strcmp(ce->name, next_ce->name);
  1616. if (0 < name_compare)
  1617. die("unordered stage entries in index");
  1618. if (!name_compare) {
  1619. if (!ce_stage(ce))
  1620. die("multiple stage entries for merged file '%s'",
  1621. ce->name);
  1622. if (ce_stage(ce) > ce_stage(next_ce))
  1623. die("unordered stage entries for '%s'",
  1624. ce->name);
  1625. }
  1626. }
  1627. }
  1628. static void tweak_untracked_cache(struct index_state *istate)
  1629. {
  1630. switch (git_config_get_untracked_cache()) {
  1631. case -1: /* keep: do nothing */
  1632. break;
  1633. case 0: /* false */
  1634. remove_untracked_cache(istate);
  1635. break;
  1636. case 1: /* true */
  1637. add_untracked_cache(istate);
  1638. break;
  1639. default: /* unknown value: do nothing */
  1640. break;
  1641. }
  1642. }
  1643. static void tweak_split_index(struct index_state *istate)
  1644. {
  1645. switch (git_config_get_split_index()) {
  1646. case -1: /* unset: do nothing */
  1647. break;
  1648. case 0: /* false */
  1649. remove_split_index(istate);
  1650. break;
  1651. case 1: /* true */
  1652. add_split_index(istate);
  1653. break;
  1654. default: /* unknown value: do nothing */
  1655. break;
  1656. }
  1657. }
  1658. static void post_read_index_from(struct index_state *istate)
  1659. {
  1660. check_ce_order(istate);
  1661. tweak_untracked_cache(istate);
  1662. tweak_split_index(istate);
  1663. tweak_fsmonitor(istate);
  1664. }
  1665. static size_t estimate_cache_size_from_compressed(unsigned int entries)
  1666. {
  1667. return entries * (sizeof(struct cache_entry) + CACHE_ENTRY_PATH_LENGTH);
  1668. }
  1669. static size_t estimate_cache_size(size_t ondisk_size, unsigned int entries)
  1670. {
  1671. long per_entry = sizeof(struct cache_entry) - sizeof(struct ondisk_cache_entry);
  1672. /*
  1673. * Account for potential alignment differences.
  1674. */
  1675. per_entry += align_padding_size(sizeof(struct cache_entry), -sizeof(struct ondisk_cache_entry));
  1676. return ondisk_size + entries * per_entry;
  1677. }
  1678. /* remember to discard_cache() before reading a different cache! */
  1679. int do_read_index(struct index_state *istate, const char *path, int must_exist)
  1680. {
  1681. int fd, i;
  1682. struct stat st;
  1683. unsigned long src_offset;
  1684. struct cache_header *hdr;
  1685. void *mmap;
  1686. size_t mmap_size;
  1687. struct strbuf previous_name_buf = STRBUF_INIT, *previous_name;
  1688. if (istate->initialized)
  1689. return istate->cache_nr;
  1690. istate->timestamp.sec = 0;
  1691. istate->timestamp.nsec = 0;
  1692. fd = open(path, O_RDONLY);
  1693. if (fd < 0) {
  1694. if (!must_exist && errno == ENOENT)
  1695. return 0;
  1696. die_errno("%s: index file open failed", path);
  1697. }
  1698. if (fstat(fd, &st))
  1699. die_errno("cannot stat the open index");
  1700. mmap_size = xsize_t(st.st_size);
  1701. if (mmap_size < sizeof(struct cache_header) + the_hash_algo->rawsz)
  1702. die("index file smaller than expected");
  1703. mmap = xmmap(NULL, mmap_size, PROT_READ, MAP_PRIVATE, fd, 0);
  1704. if (mmap == MAP_FAILED)
  1705. die_errno("unable to map index file");
  1706. close(fd);
  1707. hdr = mmap;
  1708. if (verify_hdr(hdr, mmap_size) < 0)
  1709. goto unmap;
  1710. hashcpy(istate->oid.hash, (const unsigned char *)hdr + mmap_size - the_hash_algo->rawsz);
  1711. istate->version = ntohl(hdr->hdr_version);
  1712. istate->cache_nr = ntohl(hdr->hdr_entries);
  1713. istate->cache_alloc = alloc_nr(istate->cache_nr);
  1714. istate->cache = xcalloc(istate->cache_alloc, sizeof(*istate->cache));
  1715. istate->initialized = 1;
  1716. if (istate->version == 4) {
  1717. previous_name = &previous_name_buf;
  1718. mem_pool_init(&istate->ce_mem_pool,
  1719. estimate_cache_size_from_compressed(istate->cache_nr));
  1720. } else {
  1721. previous_name = NULL;
  1722. mem_pool_init(&istate->ce_mem_pool,
  1723. estimate_cache_size(mmap_size, istate->cache_nr));
  1724. }
  1725. src_offset = sizeof(*hdr);
  1726. for (i = 0; i < istate->cache_nr; i++) {
  1727. struct ondisk_cache_entry *disk_ce;
  1728. struct cache_entry *ce;
  1729. unsigned long consumed;
  1730. disk_ce = (struct ondisk_cache_entry *)((char *)mmap + src_offset);
  1731. ce = create_from_disk(istate->ce_mem_pool, disk_ce, &consumed, previous_name);
  1732. set_index_entry(istate, i, ce);
  1733. src_offset += consumed;
  1734. }
  1735. strbuf_release(&previous_name_buf);
  1736. istate->timestamp.sec = st.st_mtime;
  1737. istate->timestamp.nsec = ST_MTIME_NSEC(st);
  1738. while (src_offset <= mmap_size - the_hash_algo->rawsz - 8) {
  1739. /* After an array of active_nr index entries,
  1740. * there can be arbitrary number of extended
  1741. * sections, each of which is prefixed with
  1742. * extension name (4-byte) and section length
  1743. * in 4-byte network byte order.
  1744. */
  1745. uint32_t extsize;
  1746. memcpy(&extsize, (char *)mmap + src_offset + 4, 4);
  1747. extsize = ntohl(extsize);
  1748. if (read_index_extension(istate,
  1749. (const char *) mmap + src_offset,
  1750. (char *) mmap + src_offset + 8,
  1751. extsize) < 0)
  1752. goto unmap;
  1753. src_offset += 8;
  1754. src_offset += extsize;
  1755. }
  1756. munmap(mmap, mmap_size);
  1757. return istate->cache_nr;
  1758. unmap:
  1759. munmap(mmap, mmap_size);
  1760. die("index file corrupt");
  1761. }
  1762. /*
  1763. * Signal that the shared index is used by updating its mtime.
  1764. *
  1765. * This way, shared index can be removed if they have not been used
  1766. * for some time.
  1767. */
  1768. static void freshen_shared_index(const char *shared_index, int warn)
  1769. {
  1770. if (!check_and_freshen_file(shared_index, 1) && warn)
  1771. warning("could not freshen shared index '%s'", shared_index);
  1772. }
  1773. int read_index_from(struct index_state *istate, const char *path,
  1774. const char *gitdir)
  1775. {
  1776. uint64_t start = getnanotime();
  1777. struct split_index *split_index;
  1778. int ret;
  1779. char *base_oid_hex;
  1780. char *base_path;
  1781. /* istate->initialized covers both .git/index and .git/sharedindex.xxx */
  1782. if (istate->initialized)
  1783. return istate->cache_nr;
  1784. ret = do_read_index(istate, path, 0);
  1785. trace_performance_since(start, "read cache %s", path);
  1786. split_index = istate->split_index;
  1787. if (!split_index || is_null_oid(&split_index->base_oid)) {
  1788. post_read_index_from(istate);
  1789. return ret;
  1790. }
  1791. if (split_index->base)
  1792. discard_index(split_index->base);
  1793. else
  1794. split_index->base = xcalloc(1, sizeof(*split_index->base));
  1795. base_oid_hex = oid_to_hex(&split_index->base_oid);
  1796. base_path = xstrfmt("%s/sharedindex.%s", gitdir, base_oid_hex);
  1797. ret = do_read_index(split_index->base, base_path, 1);
  1798. if (!oideq(&split_index->base_oid, &split_index->base->oid))
  1799. die("broken index, expect %s in %s, got %s",
  1800. base_oid_hex, base_path,
  1801. oid_to_hex(&split_index->base->oid));
  1802. freshen_shared_index(base_path, 0);
  1803. merge_base_index(istate);
  1804. post_read_index_from(istate);
  1805. trace_performance_since(start, "read cache %s", base_path);
  1806. free(base_path);
  1807. return ret;
  1808. }
  1809. int is_index_unborn(struct index_state *istate)
  1810. {
  1811. return (!istate->cache_nr && !istate->timestamp.sec);
  1812. }
  1813. int discard_index(struct index_state *istate)
  1814. {
  1815. /*
  1816. * Cache entries in istate->cache[] should have been allocated
  1817. * from the memory pool associated with this index, or from an
  1818. * associated split_index. There is no need to free individual
  1819. * cache entries. validate_cache_entries can detect when this
  1820. * assertion does not hold.
  1821. */
  1822. validate_cache_entries(istate);
  1823. resolve_undo_clear_index(istate);
  1824. istate->cache_nr = 0;
  1825. istate->cache_changed = 0;
  1826. istate->timestamp.sec = 0;
  1827. istate->timestamp.nsec = 0;
  1828. free_name_hash(istate);
  1829. cache_tree_free(&(istate->cache_tree));
  1830. istate->initialized = 0;
  1831. FREE_AND_NULL(istate->cache);
  1832. istate->cache_alloc = 0;
  1833. discard_split_index(istate);
  1834. free_untracked_cache(istate->untracked);
  1835. istate->untracked = NULL;
  1836. if (istate->ce_mem_pool) {
  1837. mem_pool_discard(istate->ce_mem_pool, should_validate_cache_entries());
  1838. istate->ce_mem_pool = NULL;
  1839. }
  1840. return 0;
  1841. }
  1842. /*
  1843. * Validate the cache entries of this index.
  1844. * All cache entries associated with this index
  1845. * should have been allocated by the memory pool
  1846. * associated with this index, or by a referenced
  1847. * split index.
  1848. */
  1849. void validate_cache_entries(const struct index_state *istate)
  1850. {
  1851. int i;
  1852. if (!should_validate_cache_entries() ||!istate || !istate->initialized)
  1853. return;
  1854. for (i = 0; i < istate->cache_nr; i++) {
  1855. if (!istate) {
  1856. die("internal error: cache entry is not allocated from expected memory pool");
  1857. } else if (!istate->ce_mem_pool ||
  1858. !mem_pool_contains(istate->ce_mem_pool, istate->cache[i])) {
  1859. if (!istate->split_index ||
  1860. !istate->split_index->base ||
  1861. !istate->split_index->base->ce_mem_pool ||
  1862. !mem_pool_contains(istate->split_index->base->ce_mem_pool, istate->cache[i])) {
  1863. die("internal error: cache entry is not allocated from expected memory pool");
  1864. }
  1865. }
  1866. }
  1867. if (istate->split_index)
  1868. validate_cache_entries(istate->split_index->base);
  1869. }
  1870. int unmerged_index(const struct index_state *istate)
  1871. {
  1872. int i;
  1873. for (i = 0; i < istate->cache_nr; i++) {
  1874. if (ce_stage(istate->cache[i]))
  1875. return 1;
  1876. }
  1877. return 0;
  1878. }
  1879. int index_has_changes(const struct index_state *istate,
  1880. struct tree *tree,
  1881. struct strbuf *sb)
  1882. {
  1883. struct object_id cmp;
  1884. int i;
  1885. if (istate != &the_index) {
  1886. BUG("index_has_changes cannot yet accept istate != &the_index; do_diff_cache needs updating first.");
  1887. }
  1888. if (tree)
  1889. cmp = tree->object.oid;
  1890. if (tree || !get_oid_tree("HEAD", &cmp)) {
  1891. struct diff_options opt;
  1892. diff_setup(&opt);
  1893. opt.flags.exit_with_status = 1;
  1894. if (!sb)
  1895. opt.flags.quick = 1;
  1896. do_diff_cache(&cmp, &opt);
  1897. diffcore_std(&opt);
  1898. for (i = 0; sb && i < diff_queued_diff.nr; i++) {
  1899. if (i)
  1900. strbuf_addch(sb, ' ');
  1901. strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);
  1902. }
  1903. diff_flush(&opt);
  1904. return opt.flags.has_changes != 0;
  1905. } else {
  1906. for (i = 0; sb && i < istate->cache_nr; i++) {
  1907. if (i)
  1908. strbuf_addch(sb, ' ');
  1909. strbuf_addstr(sb, istate->cache[i]->name);
  1910. }
  1911. return !!istate->cache_nr;
  1912. }
  1913. }
  1914. #define WRITE_BUFFER_SIZE 8192
  1915. static unsigned char write_buffer[WRITE_BUFFER_SIZE];
  1916. static unsigned long write_buffer_len;
  1917. static int ce_write_flush(git_hash_ctx *context, int fd)
  1918. {
  1919. unsigned int buffered = write_buffer_len;
  1920. if (buffered) {
  1921. the_hash_algo->update_fn(context, write_buffer, buffered);
  1922. if (write_in_full(fd, write_buffer, buffered) < 0)
  1923. return -1;
  1924. write_buffer_len = 0;
  1925. }
  1926. return 0;
  1927. }
  1928. static int ce_write(git_hash_ctx *context, int fd, void *data, unsigned int len)
  1929. {
  1930. while (len) {
  1931. unsigned int buffered = write_buffer_len;
  1932. unsigned int partial = WRITE_BUFFER_SIZE - buffered;
  1933. if (partial > len)
  1934. partial = len;
  1935. memcpy(write_buffer + buffered, data, partial);
  1936. buffered += partial;
  1937. if (buffered == WRITE_BUFFER_SIZE) {
  1938. write_buffer_len = buffered;
  1939. if (ce_write_flush(context, fd))
  1940. return -1;
  1941. buffered = 0;
  1942. }
  1943. write_buffer_len = buffered;
  1944. len -= partial;
  1945. data = (char *) data + partial;
  1946. }
  1947. return 0;
  1948. }
  1949. static int write_index_ext_header(git_hash_ctx *context, int fd,
  1950. unsigned int ext, unsigned int sz)
  1951. {
  1952. ext = htonl(ext);
  1953. sz = htonl(sz);
  1954. return ((ce_write(context, fd, &ext, 4) < 0) ||
  1955. (ce_write(context, fd, &sz, 4) < 0)) ? -1 : 0;
  1956. }
  1957. static int ce_flush(git_hash_ctx *context, int fd, unsigned char *hash)
  1958. {
  1959. unsigned int left = write_buffer_len;
  1960. if (left) {
  1961. write_buffer_len = 0;
  1962. the_hash_algo->update_fn(context, write_buffer, left);
  1963. }
  1964. /* Flush first if not enough space for hash signature */
  1965. if (left + the_hash_algo->rawsz > WRITE_BUFFER_SIZE) {
  1966. if (write_in_full(fd, write_buffer, left) < 0)
  1967. return -1;
  1968. left = 0;
  1969. }
  1970. /* Append the hash signature at the end */
  1971. the_hash_algo->final_fn(write_buffer + left, context);
  1972. hashcpy(hash, write_buffer + left);
  1973. left += the_hash_algo->rawsz;
  1974. return (write_in_full(fd, write_buffer, left) < 0) ? -1 : 0;
  1975. }
  1976. static void ce_smudge_racily_clean_entry(struct cache_entry *ce)
  1977. {
  1978. /*
  1979. * The only thing we care about in this function is to smudge the
  1980. * falsely clean entry due to touch-update-touch race, so we leave
  1981. * everything else as they are. We are called for entries whose
  1982. * ce_stat_data.sd_mtime match the index file mtime.
  1983. *
  1984. * Note that this actually does not do much for gitlinks, for
  1985. * which ce_match_stat_basic() always goes to the actual
  1986. * contents. The caller checks with is_racy_timestamp() which
  1987. * always says "no" for gitlinks, so we are not called for them ;-)
  1988. */
  1989. struct stat st;
  1990. if (lstat(ce->name, &st) < 0)
  1991. return;
  1992. if (ce_match_stat_basic(ce, &st))
  1993. return;
  1994. if (ce_modified_check_fs(ce, &st)) {
  1995. /* This is "racily clean"; smudge it. Note that this
  1996. * is a tricky code. At first glance, it may appear
  1997. * that it can break with this sequence:
  1998. *
  1999. * $ echo xyzzy >frotz
  2000. * $ git-update-index --add frotz
  2001. * $ : >frotz
  2002. * $ sleep 3
  2003. * $ echo filfre >nitfol
  2004. * $ git-update-index --add nitfol
  2005. *
  2006. * but it does not. When the second update-index runs,
  2007. * it notices that the entry "frotz" has the same timestamp
  2008. * as index, and if we were to smudge it by resetting its
  2009. * size to zero here, then the object name recorded
  2010. * in index is the 6-byte file but the cached stat information
  2011. * becomes zero --- which would then match what we would
  2012. * obtain from the filesystem next time we stat("frotz").
  2013. *
  2014. * However, the second update-index, before calling
  2015. * this function, notices that the cached size is 6
  2016. * bytes and what is on the filesystem is an empty
  2017. * file, and never calls us, so the cached size information
  2018. * for "frotz" stays 6 which does not match the filesystem.
  2019. */
  2020. ce->ce_stat_data.sd_size = 0;
  2021. }
  2022. }
  2023. /* Copy miscellaneous fields but not the name */
  2024. static void copy_cache_entry_to_ondisk(struct ondisk_cache_entry *ondisk,
  2025. struct cache_entry *ce)
  2026. {
  2027. short flags;
  2028. ondisk->ctime.sec = htonl(ce->ce_stat_data.sd_ctime.sec);
  2029. ondisk->mtime.sec = htonl(ce->ce_stat_data.sd_mtime.sec);
  2030. ondisk->ctime.nsec = htonl(ce->ce_stat_data.sd_ctime.nsec);
  2031. ondisk->mtime.nsec = htonl(ce->ce_stat_data.sd_mtime.nsec);
  2032. ondisk->dev = htonl(ce->ce_stat_data.sd_dev);
  2033. ondisk->ino = htonl(ce->ce_stat_data.sd_ino);
  2034. ondisk->mode = htonl(ce->ce_mode);
  2035. ondisk->uid = htonl(ce->ce_stat_data.sd_uid);
  2036. ondisk->gid = htonl(ce->ce_stat_data.sd_gid);
  2037. ondisk->size = htonl(ce->ce_stat_data.sd_size);
  2038. hashcpy(ondisk->sha1, ce->oid.hash);
  2039. flags = ce->ce_flags & ~CE_NAMEMASK;
  2040. flags |= (ce_namelen(ce) >= CE_NAMEMASK ? CE_NAMEMASK : ce_namelen(ce));
  2041. ondisk->flags = htons(flags);
  2042. if (ce->ce_flags & CE_EXTENDED) {
  2043. struct ondisk_cache_entry_extended *ondisk2;
  2044. ondisk2 = (struct ondisk_cache_entry_extended *)ondisk;
  2045. ondisk2->flags2 = htons((ce->ce_flags & CE_EXTENDED_FLAGS) >> 16);
  2046. }
  2047. }
  2048. static int ce_write_entry(git_hash_ctx *c, int fd, struct cache_entry *ce,
  2049. struct strbuf *previous_name, struct ondisk_cache_entry *ondisk)
  2050. {
  2051. int size;
  2052. int result;
  2053. unsigned int saved_namelen;
  2054. int stripped_name = 0;
  2055. static unsigned char padding[8] = { 0x00 };
  2056. if (ce->ce_flags & CE_STRIP_NAME) {
  2057. saved_namelen = ce_namelen(ce);
  2058. ce->ce_namelen = 0;
  2059. stripped_name = 1;
  2060. }
  2061. if (ce->ce_flags & CE_EXTENDED)
  2062. size = offsetof(struct ondisk_cache_entry_extended, name);
  2063. else
  2064. size = offsetof(struct ondisk_cache_entry, name);
  2065. if (!previous_name) {
  2066. int len = ce_namelen(ce);
  2067. copy_cache_entry_to_ondisk(ondisk, ce);
  2068. result = ce_write(c, fd, ondisk, size);
  2069. if (!result)
  2070. result = ce_write(c, fd, ce->name, len);
  2071. if (!result)
  2072. result = ce_write(c, fd, padding, align_padding_size(size, len));
  2073. } else {
  2074. int common, to_remove, prefix_size;
  2075. unsigned char to_remove_vi[16];
  2076. for (common = 0;
  2077. (ce->name[common] &&
  2078. common < previous_name->len &&
  2079. ce->name[common] == previous_name->buf[common]);
  2080. common++)
  2081. ; /* still matching */
  2082. to_remove = previous_name->len - common;
  2083. prefix_size = encode_varint(to_remove, to_remove_vi);
  2084. copy_cache_entry_to_ondisk(ondisk, ce);
  2085. result = ce_write(c, fd, ondisk, size);
  2086. if (!result)
  2087. result = ce_write(c, fd, to_remove_vi, prefix_size);
  2088. if (!result)
  2089. result = ce_write(c, fd, ce->name + common, ce_namelen(ce) - common);
  2090. if (!result)
  2091. result = ce_write(c, fd, padding, 1);
  2092. strbuf_splice(previous_name, common, to_remove,
  2093. ce->name + common, ce_namelen(ce) - common);
  2094. }
  2095. if (stripped_name) {
  2096. ce->ce_namelen = saved_namelen;
  2097. ce->ce_flags &= ~CE_STRIP_NAME;
  2098. }
  2099. return result;
  2100. }
  2101. /*
  2102. * This function verifies if index_state has the correct sha1 of the
  2103. * index file. Don't die if we have any other failure, just return 0.
  2104. */
  2105. static int verify_index_from(const struct index_state *istate, const char *path)
  2106. {
  2107. int fd;
  2108. ssize_t n;
  2109. struct stat st;
  2110. unsigned char hash[GIT_MAX_RAWSZ];
  2111. if (!istate->initialized)
  2112. return 0;
  2113. fd = open(path, O_RDONLY);
  2114. if (fd < 0)
  2115. return 0;
  2116. if (fstat(fd, &st))
  2117. goto out;
  2118. if (st.st_size < sizeof(struct cache_header) + the_hash_algo->rawsz)
  2119. goto out;
  2120. n = pread_in_full(fd, hash, the_hash_algo->rawsz, st.st_size - the_hash_algo->rawsz);
  2121. if (n != the_hash_algo->rawsz)
  2122. goto out;
  2123. if (!hasheq(istate->oid.hash, hash))
  2124. goto out;
  2125. close(fd);
  2126. return 1;
  2127. out:
  2128. close(fd);
  2129. return 0;
  2130. }
  2131. static int verify_index(const struct index_state *istate)
  2132. {
  2133. return verify_index_from(istate, get_index_file());
  2134. }
  2135. static int has_racy_timestamp(struct index_state *istate)
  2136. {
  2137. int entries = istate->cache_nr;
  2138. int i;
  2139. for (i = 0; i < entries; i++) {
  2140. struct cache_entry *ce = istate->cache[i];
  2141. if (is_racy_timestamp(istate, ce))
  2142. return 1;
  2143. }
  2144. return 0;
  2145. }
  2146. void update_index_if_able(struct index_state *istate, struct lock_file *lockfile)
  2147. {
  2148. if ((istate->cache_changed || has_racy_timestamp(istate)) &&
  2149. verify_index(istate))
  2150. write_locked_index(istate, lockfile, COMMIT_LOCK);
  2151. else
  2152. rollback_lock_file(lockfile);
  2153. }
  2154. /*
  2155. * On success, `tempfile` is closed. If it is the temporary file
  2156. * of a `struct lock_file`, we will therefore effectively perform
  2157. * a 'close_lock_file_gently()`. Since that is an implementation
  2158. * detail of lockfiles, callers of `do_write_index()` should not
  2159. * rely on it.
  2160. */
  2161. static int do_write_index(struct index_state *istate, struct tempfile *tempfile,
  2162. int strip_extensions)
  2163. {
  2164. uint64_t start = getnanotime();
  2165. int newfd = tempfile->fd;
  2166. git_hash_ctx c;
  2167. struct cache_header hdr;
  2168. int i, err = 0, removed, extended, hdr_version;
  2169. struct cache_entry **cache = istate->cache;
  2170. int entries = istate->cache_nr;
  2171. struct stat st;
  2172. struct ondisk_cache_entry_extended ondisk;
  2173. struct strbuf previous_name_buf = STRBUF_INIT, *previous_name;
  2174. int drop_cache_tree = istate->drop_cache_tree;
  2175. for (i = removed = extended = 0; i < entries; i++) {
  2176. if (cache[i]->ce_flags & CE_REMOVE)
  2177. removed++;
  2178. /* reduce extended entries if possible */
  2179. cache[i]->ce_flags &= ~CE_EXTENDED;
  2180. if (cache[i]->ce_flags & CE_EXTENDED_FLAGS) {
  2181. extended++;
  2182. cache[i]->ce_flags |= CE_EXTENDED;
  2183. }
  2184. }
  2185. if (!istate->version) {
  2186. istate->version = get_index_format_default();
  2187. if (git_env_bool("GIT_TEST_SPLIT_INDEX", 0))
  2188. init_split_index(istate);
  2189. }
  2190. /* demote version 3 to version 2 when the latter suffices */
  2191. if (istate->version == 3 || istate->version == 2)
  2192. istate->version = extended ? 3 : 2;
  2193. hdr_version = istate->version;
  2194. hdr.hdr_signature = htonl(CACHE_SIGNATURE);
  2195. hdr.hdr_version = htonl(hdr_version);
  2196. hdr.hdr_entries = htonl(entries - removed);
  2197. the_hash_algo->init_fn(&c);
  2198. if (ce_write(&c, newfd, &hdr, sizeof(hdr)) < 0)
  2199. return -1;
  2200. previous_name = (hdr_version == 4) ? &previous_name_buf : NULL;
  2201. for (i = 0; i < entries; i++) {
  2202. struct cache_entry *ce = cache[i];
  2203. if (ce->ce_flags & CE_REMOVE)
  2204. continue;
  2205. if (!ce_uptodate(ce) && is_racy_timestamp(istate, ce))
  2206. ce_smudge_racily_clean_entry(ce);
  2207. if (is_null_oid(&ce->oid)) {
  2208. static const char msg[] = "cache entry has null sha1: %s";
  2209. static int allow = -1;
  2210. if (allow < 0)
  2211. allow = git_env_bool("GIT_ALLOW_NULL_SHA1", 0);
  2212. if (allow)
  2213. warning(msg, ce->name);
  2214. else
  2215. err = error(msg, ce->name);
  2216. drop_cache_tree = 1;
  2217. }
  2218. if (ce_write_entry(&c, newfd, ce, previous_name, (struct ondisk_cache_entry *)&ondisk) < 0)
  2219. err = -1;
  2220. if (err)
  2221. break;
  2222. }
  2223. strbuf_release(&previous_name_buf);
  2224. if (err)
  2225. return err;
  2226. /* Write extension data here */
  2227. if (!strip_extensions && istate->split_index) {
  2228. struct strbuf sb = STRBUF_INIT;
  2229. err = write_link_extension(&sb, istate) < 0 ||
  2230. write_index_ext_header(&c, newfd, CACHE_EXT_LINK,
  2231. sb.len) < 0 ||
  2232. ce_write(&c, newfd, sb.buf, sb.len) < 0;
  2233. strbuf_release(&sb);
  2234. if (err)
  2235. return -1;
  2236. }
  2237. if (!strip_extensions && !drop_cache_tree && istate->cache_tree) {
  2238. struct strbuf sb = STRBUF_INIT;
  2239. cache_tree_write(&sb, istate->cache_tree);
  2240. err = write_index_ext_header(&c, newfd, CACHE_EXT_TREE, sb.len) < 0
  2241. || ce_write(&c, newfd, sb.buf, sb.len) < 0;
  2242. strbuf_release(&sb);
  2243. if (err)
  2244. return -1;
  2245. }
  2246. if (!strip_extensions && istate->resolve_undo) {
  2247. struct strbuf sb = STRBUF_INIT;
  2248. resolve_undo_write(&sb, istate->resolve_undo);
  2249. err = write_index_ext_header(&c, newfd, CACHE_EXT_RESOLVE_UNDO,
  2250. sb.len) < 0
  2251. || ce_write(&c, newfd, sb.buf, sb.len) < 0;
  2252. strbuf_release(&sb);
  2253. if (err)
  2254. return -1;
  2255. }
  2256. if (!strip_extensions && istate->untracked) {
  2257. struct strbuf sb = STRBUF_INIT;
  2258. write_untracked_extension(&sb, istate->untracked);
  2259. err = write_index_ext_header(&c, newfd, CACHE_EXT_UNTRACKED,
  2260. sb.len) < 0 ||
  2261. ce_write(&c, newfd, sb.buf, sb.len) < 0;
  2262. strbuf_release(&sb);
  2263. if (err)
  2264. return -1;
  2265. }
  2266. if (!strip_extensions && istate->fsmonitor_last_update) {
  2267. struct strbuf sb = STRBUF_INIT;
  2268. write_fsmonitor_extension(&sb, istate);
  2269. err = write_index_ext_header(&c, newfd, CACHE_EXT_FSMONITOR, sb.len) < 0
  2270. || ce_write(&c, newfd, sb.buf, sb.len) < 0;
  2271. strbuf_release(&sb);
  2272. if (err)
  2273. return -1;
  2274. }
  2275. if (ce_flush(&c, newfd, istate->oid.hash))
  2276. return -1;
  2277. if (close_tempfile_gently(tempfile)) {
  2278. error(_("could not close '%s'"), tempfile->filename.buf);
  2279. return -1;
  2280. }
  2281. if (stat(tempfile->filename.buf, &st))
  2282. return -1;
  2283. istate->timestamp.sec = (unsigned int)st.st_mtime;
  2284. istate->timestamp.nsec = ST_MTIME_NSEC(st);
  2285. trace_performance_since(start, "write index, changed mask = %x", istate->cache_changed);
  2286. return 0;
  2287. }
  2288. void set_alternate_index_output(const char *name)
  2289. {
  2290. alternate_index_output = name;
  2291. }
  2292. static int commit_locked_index(struct lock_file *lk)
  2293. {
  2294. if (alternate_index_output)
  2295. return commit_lock_file_to(lk, alternate_index_output);
  2296. else
  2297. return commit_lock_file(lk);
  2298. }
  2299. static int do_write_locked_index(struct index_state *istate, struct lock_file *lock,
  2300. unsigned flags)
  2301. {
  2302. int ret = do_write_index(istate, lock->tempfile, 0);
  2303. if (ret)
  2304. return ret;
  2305. if (flags & COMMIT_LOCK)
  2306. return commit_locked_index(lock);
  2307. return close_lock_file_gently(lock);
  2308. }
  2309. static int write_split_index(struct index_state *istate,
  2310. struct lock_file *lock,
  2311. unsigned flags)
  2312. {
  2313. int ret;
  2314. prepare_to_write_split_index(istate);
  2315. ret = do_write_locked_index(istate, lock, flags);
  2316. finish_writing_split_index(istate);
  2317. return ret;
  2318. }
  2319. static const char *shared_index_expire = "2.weeks.ago";
  2320. static unsigned long get_shared_index_expire_date(void)
  2321. {
  2322. static unsigned long shared_index_expire_date;
  2323. static int shared_index_expire_date_prepared;
  2324. if (!shared_index_expire_date_prepared) {
  2325. git_config_get_expiry("splitindex.sharedindexexpire",
  2326. &shared_index_expire);
  2327. shared_index_expire_date = approxidate(shared_index_expire);
  2328. shared_index_expire_date_prepared = 1;
  2329. }
  2330. return shared_index_expire_date;
  2331. }
  2332. static int should_delete_shared_index(const char *shared_index_path)
  2333. {
  2334. struct stat st;
  2335. unsigned long expiration;
  2336. /* Check timestamp */
  2337. expiration = get_shared_index_expire_date();
  2338. if (!expiration)
  2339. return 0;
  2340. if (stat(shared_index_path, &st))
  2341. return error_errno(_("could not stat '%s'"), shared_index_path);
  2342. if (st.st_mtime > expiration)
  2343. return 0;
  2344. return 1;
  2345. }
  2346. static int clean_shared_index_files(const char *current_hex)
  2347. {
  2348. struct dirent *de;
  2349. DIR *dir = opendir(get_git_dir());
  2350. if (!dir)
  2351. return error_errno(_("unable to open git dir: %s"), get_git_dir());
  2352. while ((de = readdir(dir)) != NULL) {
  2353. const char *sha1_hex;
  2354. const char *shared_index_path;
  2355. if (!skip_prefix(de->d_name, "sharedindex.", &sha1_hex))
  2356. continue;
  2357. if (!strcmp(sha1_hex, current_hex))
  2358. continue;
  2359. shared_index_path = git_path("%s", de->d_name);
  2360. if (should_delete_shared_index(shared_index_path) > 0 &&
  2361. unlink(shared_index_path))
  2362. warning_errno(_("unable to unlink: %s"), shared_index_path);
  2363. }
  2364. closedir(dir);
  2365. return 0;
  2366. }
  2367. static int write_shared_index(struct index_state *istate,
  2368. struct tempfile **temp)
  2369. {
  2370. struct split_index *si = istate->split_index;
  2371. int ret;
  2372. move_cache_to_base_index(istate);
  2373. ret = do_write_index(si->base, *temp, 1);
  2374. if (ret)
  2375. return ret;
  2376. ret = adjust_shared_perm(get_tempfile_path(*temp));
  2377. if (ret) {
  2378. error("cannot fix permission bits on %s", get_tempfile_path(*temp));
  2379. return ret;
  2380. }
  2381. ret = rename_tempfile(temp,
  2382. git_path("sharedindex.%s", oid_to_hex(&si->base->oid)));
  2383. if (!ret) {
  2384. oidcpy(&si->base_oid, &si->base->oid);
  2385. clean_shared_index_files(oid_to_hex(&si->base->oid));
  2386. }
  2387. return ret;
  2388. }
  2389. static const int default_max_percent_split_change = 20;
  2390. static int too_many_not_shared_entries(struct index_state *istate)
  2391. {
  2392. int i, not_shared = 0;
  2393. int max_split = git_config_get_max_percent_split_change();
  2394. switch (max_split) {
  2395. case -1:
  2396. /* not or badly configured: use the default value */
  2397. max_split = default_max_percent_split_change;
  2398. break;
  2399. case 0:
  2400. return 1; /* 0% means always write a new shared index */
  2401. case 100:
  2402. return 0; /* 100% means never write a new shared index */
  2403. default:
  2404. break; /* just use the configured value */
  2405. }
  2406. /* Count not shared entries */
  2407. for (i = 0; i < istate->cache_nr; i++) {
  2408. struct cache_entry *ce = istate->cache[i];
  2409. if (!ce->index)
  2410. not_shared++;
  2411. }
  2412. return (int64_t)istate->cache_nr * max_split < (int64_t)not_shared * 100;
  2413. }
  2414. int write_locked_index(struct index_state *istate, struct lock_file *lock,
  2415. unsigned flags)
  2416. {
  2417. int new_shared_index, ret;
  2418. struct split_index *si = istate->split_index;
  2419. if ((flags & SKIP_IF_UNCHANGED) && !istate->cache_changed) {
  2420. if (flags & COMMIT_LOCK)
  2421. rollback_lock_file(lock);
  2422. return 0;
  2423. }
  2424. if (istate->fsmonitor_last_update)
  2425. fill_fsmonitor_bitmap(istate);
  2426. if (!si || alternate_index_output ||
  2427. (istate->cache_changed & ~EXTMASK)) {
  2428. if (si)
  2429. oidclr(&si->base_oid);
  2430. ret = do_write_locked_index(istate, lock, flags);
  2431. goto out;
  2432. }
  2433. if (git_env_bool("GIT_TEST_SPLIT_INDEX", 0)) {
  2434. int v = si->base_oid.hash[0];
  2435. if ((v & 15) < 6)
  2436. istate->cache_changed |= SPLIT_INDEX_ORDERED;
  2437. }
  2438. if (too_many_not_shared_entries(istate))
  2439. istate->cache_changed |= SPLIT_INDEX_ORDERED;
  2440. new_shared_index = istate->cache_changed & SPLIT_INDEX_ORDERED;
  2441. if (new_shared_index) {
  2442. struct tempfile *temp;
  2443. int saved_errno;
  2444. temp = mks_tempfile(git_path("sharedindex_XXXXXX"));
  2445. if (!temp) {
  2446. oidclr(&si->base_oid);
  2447. ret = do_write_locked_index(istate, lock, flags);
  2448. goto out;
  2449. }
  2450. ret = write_shared_index(istate, &temp);
  2451. saved_errno = errno;
  2452. if (is_tempfile_active(temp))
  2453. delete_tempfile(&temp);
  2454. errno = saved_errno;
  2455. if (ret)
  2456. goto out;
  2457. }
  2458. ret = write_split_index(istate, lock, flags);
  2459. /* Freshen the shared index only if the split-index was written */
  2460. if (!ret && !new_shared_index) {
  2461. const char *shared_index = git_path("sharedindex.%s",
  2462. oid_to_hex(&si->base_oid));
  2463. freshen_shared_index(shared_index, 1);
  2464. }
  2465. out:
  2466. if (flags & COMMIT_LOCK)
  2467. rollback_lock_file(lock);
  2468. return ret;
  2469. }
  2470. /*
  2471. * Read the index file that is potentially unmerged into given
  2472. * index_state, dropping any unmerged entries to stage #0 (potentially
  2473. * resulting in a path appearing as both a file and a directory in the
  2474. * index; the caller is responsible to clear out the extra entries
  2475. * before writing the index to a tree). Returns true if the index is
  2476. * unmerged. Callers who want to refuse to work from an unmerged
  2477. * state can call this and check its return value, instead of calling
  2478. * read_cache().
  2479. */
  2480. int read_index_unmerged(struct index_state *istate)
  2481. {
  2482. int i;
  2483. int unmerged = 0;
  2484. read_index(istate);
  2485. for (i = 0; i < istate->cache_nr; i++) {
  2486. struct cache_entry *ce = istate->cache[i];
  2487. struct cache_entry *new_ce;
  2488. int len;
  2489. if (!ce_stage(ce))
  2490. continue;
  2491. unmerged = 1;
  2492. len = ce_namelen(ce);
  2493. new_ce = make_empty_cache_entry(istate, len);
  2494. memcpy(new_ce->name, ce->name, len);
  2495. new_ce->ce_flags = create_ce_flags(0) | CE_CONFLICTED;
  2496. new_ce->ce_namelen = len;
  2497. new_ce->ce_mode = ce->ce_mode;
  2498. if (add_index_entry(istate, new_ce, ADD_CACHE_SKIP_DFCHECK))
  2499. return error("%s: cannot drop to stage #0",
  2500. new_ce->name);
  2501. }
  2502. return unmerged;
  2503. }
  2504. /*
  2505. * Returns 1 if the path is an "other" path with respect to
  2506. * the index; that is, the path is not mentioned in the index at all,
  2507. * either as a file, a directory with some files in the index,
  2508. * or as an unmerged entry.
  2509. *
  2510. * We helpfully remove a trailing "/" from directories so that
  2511. * the output of read_directory can be used as-is.
  2512. */
  2513. int index_name_is_other(const struct index_state *istate, const char *name,
  2514. int namelen)
  2515. {
  2516. int pos;
  2517. if (namelen && name[namelen - 1] == '/')
  2518. namelen--;
  2519. pos = index_name_pos(istate, name, namelen);
  2520. if (0 <= pos)
  2521. return 0; /* exact match */
  2522. pos = -pos - 1;
  2523. if (pos < istate->cache_nr) {
  2524. struct cache_entry *ce = istate->cache[pos];
  2525. if (ce_namelen(ce) == namelen &&
  2526. !memcmp(ce->name, name, namelen))
  2527. return 0; /* Yup, this one exists unmerged */
  2528. }
  2529. return 1;
  2530. }
  2531. void *read_blob_data_from_index(const struct index_state *istate,
  2532. const char *path, unsigned long *size)
  2533. {
  2534. int pos, len;
  2535. unsigned long sz;
  2536. enum object_type type;
  2537. void *data;
  2538. len = strlen(path);
  2539. pos = index_name_pos(istate, path, len);
  2540. if (pos < 0) {
  2541. /*
  2542. * We might be in the middle of a merge, in which
  2543. * case we would read stage #2 (ours).
  2544. */
  2545. int i;
  2546. for (i = -pos - 1;
  2547. (pos < 0 && i < istate->cache_nr &&
  2548. !strcmp(istate->cache[i]->name, path));
  2549. i++)
  2550. if (ce_stage(istate->cache[i]) == 2)
  2551. pos = i;
  2552. }
  2553. if (pos < 0)
  2554. return NULL;
  2555. data = read_object_file(&istate->cache[pos]->oid, &type, &sz);
  2556. if (!data || type != OBJ_BLOB) {
  2557. free(data);
  2558. return NULL;
  2559. }
  2560. if (size)
  2561. *size = sz;
  2562. return data;
  2563. }
  2564. void stat_validity_clear(struct stat_validity *sv)
  2565. {
  2566. FREE_AND_NULL(sv->sd);
  2567. }
  2568. int stat_validity_check(struct stat_validity *sv, const char *path)
  2569. {
  2570. struct stat st;
  2571. if (stat(path, &st) < 0)
  2572. return sv->sd == NULL;
  2573. if (!sv->sd)
  2574. return 0;
  2575. return S_ISREG(st.st_mode) && !match_stat_data(sv->sd, &st);
  2576. }
  2577. void stat_validity_update(struct stat_validity *sv, int fd)
  2578. {
  2579. struct stat st;
  2580. if (fstat(fd, &st) < 0 || !S_ISREG(st.st_mode))
  2581. stat_validity_clear(sv);
  2582. else {
  2583. if (!sv->sd)
  2584. sv->sd = xcalloc(1, sizeof(struct stat_data));
  2585. fill_stat_data(sv->sd, &st);
  2586. }
  2587. }
  2588. void move_index_extensions(struct index_state *dst, struct index_state *src)
  2589. {
  2590. dst->untracked = src->untracked;
  2591. src->untracked = NULL;
  2592. }
  2593. struct cache_entry *dup_cache_entry(const struct cache_entry *ce,
  2594. struct index_state *istate)
  2595. {
  2596. unsigned int size = ce_size(ce);
  2597. int mem_pool_allocated;
  2598. struct cache_entry *new_entry = make_empty_cache_entry(istate, ce_namelen(ce));
  2599. mem_pool_allocated = new_entry->mem_pool_allocated;
  2600. memcpy(new_entry, ce, size);
  2601. new_entry->mem_pool_allocated = mem_pool_allocated;
  2602. return new_entry;
  2603. }
  2604. void discard_cache_entry(struct cache_entry *ce)
  2605. {
  2606. if (ce && should_validate_cache_entries())
  2607. memset(ce, 0xCD, cache_entry_size(ce->ce_namelen));
  2608. if (ce && ce->mem_pool_allocated)
  2609. return;
  2610. free(ce);
  2611. }
  2612. int should_validate_cache_entries(void)
  2613. {
  2614. static int validate_index_cache_entries = -1;
  2615. if (validate_index_cache_entries < 0) {
  2616. if (getenv("GIT_TEST_VALIDATE_INDEX_CACHE_ENTRIES"))
  2617. validate_index_cache_entries = 1;
  2618. else
  2619. validate_index_cache_entries = 0;
  2620. }
  2621. return validate_index_cache_entries;
  2622. }