read-cache.c 98 KB

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