1
0

cmSystemTools.cxx 117 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #if !defined(_WIN32) && !defined(__sun) && !defined(__OpenBSD__)
  4. // POSIX APIs are needed
  5. // NOLINTNEXTLINE(bugprone-reserved-identifier)
  6. # define _POSIX_C_SOURCE 200809L
  7. #endif
  8. #if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__NetBSD__) || \
  9. defined(__QNX__)
  10. // For isascii
  11. // NOLINTNEXTLINE(bugprone-reserved-identifier)
  12. # define _XOPEN_SOURCE 700
  13. #endif
  14. #if defined(__APPLE__)
  15. // Restore Darwin APIs removed by _POSIX_C_SOURCE.
  16. // NOLINTNEXTLINE(bugprone-reserved-identifier)
  17. # define _DARWIN_C_SOURCE
  18. #endif
  19. #include "cmSystemTools.h"
  20. #include <iterator>
  21. #if defined(_WIN32) || defined(__APPLE__)
  22. # include <unordered_map>
  23. #endif
  24. #include <cm/optional>
  25. #include <cmext/algorithm>
  26. #include <cmext/string_view>
  27. #include <cm3p/uv.h>
  28. #include "cmDuration.h"
  29. #include "cmELF.h"
  30. #include "cmMessageMetadata.h"
  31. #include "cmPathResolver.h"
  32. #include "cmProcessOutput.h"
  33. #include "cmRange.h"
  34. #include "cmStringAlgorithms.h"
  35. #include "cmUVHandlePtr.h"
  36. #include "cmUVProcessChain.h"
  37. #include "cmUVStream.h"
  38. #include "cmValue.h"
  39. #include "cmWorkingDirectory.h"
  40. #if !defined(CMAKE_BOOTSTRAP)
  41. # include <cm3p/archive.h>
  42. # include <cm3p/archive_entry.h>
  43. # include "cmArchiveWrite.h"
  44. # include "cmLocale.h"
  45. # ifndef __LA_INT64_T
  46. # define __LA_INT64_T la_int64_t
  47. # endif
  48. # ifndef __LA_SSIZE_T
  49. # define __LA_SSIZE_T la_ssize_t
  50. # endif
  51. #endif
  52. #if defined(CMake_USE_MACH_PARSER)
  53. # include "cmMachO.h"
  54. #endif
  55. #if defined(CMake_USE_XCOFF_PARSER)
  56. # include "cmXCOFF.h"
  57. #endif
  58. #include <algorithm>
  59. #include <cassert>
  60. #include <cctype>
  61. #include <cerrno>
  62. #include <cstdint>
  63. #include <cstdio>
  64. #include <cstdlib>
  65. #include <cstring>
  66. #include <ctime>
  67. #include <functional>
  68. #include <iostream>
  69. #include <memory>
  70. #include <sstream>
  71. #include <utility>
  72. #include <vector>
  73. #include <fcntl.h>
  74. #include "cmsys/Directory.hxx"
  75. #include "cmsys/Encoding.hxx"
  76. #include "cmsys/FStream.hxx"
  77. #include "cmsys/RegularExpression.hxx"
  78. #include "cmsys/System.h"
  79. #include "cmsys/Terminal.h"
  80. #if defined(_WIN32)
  81. # include <windows.h>
  82. # include <knownfolders.h>
  83. # include <shlobj.h>
  84. // include wincrypt.h after windows.h
  85. # include <wincrypt.h>
  86. #else
  87. # include <unistd.h>
  88. # include <sys/time.h>
  89. #endif
  90. #if defined(_WIN32) && \
  91. (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__MINGW32__))
  92. # include <io.h>
  93. #endif
  94. #if defined(__APPLE__)
  95. # include <mach-o/dyld.h>
  96. #endif
  97. #ifdef __QNX__
  98. # include <malloc.h> /* for malloc/free on QNX */
  99. #endif
  100. #if !defined(_WIN32) && !defined(__ANDROID__)
  101. # include <sys/utsname.h>
  102. #endif
  103. #if defined(_MSC_VER) && _MSC_VER >= 1800
  104. # define CM_WINDOWS_DEPRECATED_GetVersionEx
  105. #endif
  106. namespace {
  107. cmSystemTools::InterruptCallback s_InterruptCallback;
  108. cmSystemTools::MessageCallback s_MessageCallback;
  109. cmSystemTools::OutputCallback s_StderrCallback;
  110. cmSystemTools::OutputCallback s_StdoutCallback;
  111. #ifdef _WIN32
  112. std::string GetDosDriveWorkingDirectory(char letter)
  113. {
  114. // The Windows command processor tracks a per-drive working
  115. // directory for compatibility with MS-DOS by using special
  116. // environment variables named "=C:".
  117. // https://web.archive.org/web/20100522040616/
  118. // https://blogs.msdn.com/oldnewthing/archive/2010/05/06/10008132.aspx
  119. return cmSystemTools::GetEnvVar(cmStrCat('=', letter, ':'))
  120. .value_or(std::string());
  121. }
  122. cmsys::Status ReadNameOnDisk(std::string const& path, std::string& name)
  123. {
  124. std::wstring wp = cmsys::Encoding::ToWide(path);
  125. HANDLE h = CreateFileW(
  126. wp.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
  127. FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, nullptr);
  128. if (h == INVALID_HANDLE_VALUE) {
  129. return cmsys::Status::Windows_GetLastError();
  130. }
  131. WCHAR local_fni[((sizeof(FILE_NAME_INFO) - 1) / sizeof(WCHAR)) + 1024];
  132. size_t fni_size = sizeof(local_fni);
  133. auto* fni = reinterpret_cast<FILE_NAME_INFO*>(local_fni);
  134. if (!GetFileInformationByHandleEx(h, FileNameInfo, fni, fni_size)) {
  135. DWORD e = GetLastError();
  136. if (e != ERROR_MORE_DATA) {
  137. CloseHandle(h);
  138. return cmsys::Status::Windows(e);
  139. }
  140. fni_size = fni->FileNameLength;
  141. fni = static_cast<FILE_NAME_INFO*>(malloc(fni_size));
  142. if (!fni) {
  143. e = ERROR_NOT_ENOUGH_MEMORY;
  144. CloseHandle(h);
  145. return cmsys::Status::Windows(e);
  146. }
  147. if (!GetFileInformationByHandleEx(h, FileNameInfo, fni, fni_size)) {
  148. e = GetLastError();
  149. free(fni);
  150. CloseHandle(h);
  151. return cmsys::Status::Windows(e);
  152. }
  153. }
  154. std::wstring wn{ fni->FileName, fni->FileNameLength / sizeof(WCHAR) };
  155. std::string nn = cmsys::Encoding::ToNarrow(wn);
  156. std::string::size_type last_slash = nn.find_last_of("/\\");
  157. if (last_slash != std::string::npos) {
  158. name = nn.substr(last_slash + 1);
  159. }
  160. if (fni != reinterpret_cast<FILE_NAME_INFO*>(local_fni)) {
  161. free(fni);
  162. }
  163. CloseHandle(h);
  164. return cmsys::Status::Success();
  165. }
  166. #elif defined(__APPLE__)
  167. cmsys::Status ReadNameOnDiskIterateDir(std::string const& path,
  168. std::string& name)
  169. {
  170. // Read contents of the parent directory to find the
  171. // entry matching the given path.
  172. std::string const bn = cmSystemTools::GetFilenameName(path);
  173. std::string const dn = cmSystemTools::GetFilenamePath(path);
  174. DIR* d = opendir(dn.c_str());
  175. while (struct dirent* dr = readdir(d)) {
  176. if (strcasecmp(dr->d_name, bn.c_str()) == 0) {
  177. name = dr->d_name;
  178. closedir(d);
  179. return cmsys::Status::Success();
  180. }
  181. }
  182. closedir(d);
  183. return cmsys::Status::POSIX(ENOENT);
  184. }
  185. cmsys::Status ReadNameOnDiskFcntlGetPath(std::string const& path,
  186. std::string& name)
  187. {
  188. // macOS (and *BSD) offer a syscall to get an on-disk path to
  189. // a descriptor's file.
  190. int fd = open(path.c_str(), O_SYMLINK | O_RDONLY);
  191. if (fd == -1) {
  192. return cmsys::Status::POSIX(errno);
  193. }
  194. char out[MAXPATHLEN + 1];
  195. if (fcntl(fd, F_GETPATH, out) == -1) {
  196. int e = errno;
  197. close(fd);
  198. return cmsys::Status::POSIX(e);
  199. }
  200. close(fd);
  201. name = cmSystemTools::GetFilenameName(out);
  202. return cmsys::Status::Success();
  203. }
  204. cmsys::Status ReadNameOnDisk(std::string const& path, std::string& name)
  205. {
  206. struct stat stat_path;
  207. if (lstat(path.c_str(), &stat_path) != 0) {
  208. return cmsys::Status::POSIX(errno);
  209. }
  210. // macOS (and *BSD) use namei(9) to cache file paths. Use it unless
  211. // the inode has multiple hardlinks: if it is opened through multiple
  212. // paths, the results may be unpredictable.
  213. if (S_ISDIR(stat_path.st_mode) || stat_path.st_nlink < 2) {
  214. return ReadNameOnDiskFcntlGetPath(path, name);
  215. }
  216. // Fall back to reading the parent directory.
  217. return ReadNameOnDiskIterateDir(path, name);
  218. }
  219. #endif
  220. class RealSystem : public cm::PathResolver::System
  221. {
  222. public:
  223. ~RealSystem() override = default;
  224. cmsys::Status ReadSymlink(std::string const& path,
  225. std::string& link) override
  226. {
  227. return cmSystemTools::ReadSymlink(path, link);
  228. }
  229. bool PathExists(std::string const& path) override
  230. {
  231. return cmSystemTools::PathExists(path);
  232. }
  233. std::string GetWorkingDirectory() override
  234. {
  235. return cmSystemTools::GetLogicalWorkingDirectory();
  236. }
  237. #ifdef _WIN32
  238. std::string GetWorkingDirectoryOnDrive(char letter) override
  239. {
  240. return GetDosDriveWorkingDirectory(letter);
  241. }
  242. #endif
  243. #if defined(_WIN32) || defined(__APPLE__)
  244. struct NameOnDisk
  245. {
  246. cmsys::Status Status;
  247. std::string Name;
  248. };
  249. using NameOnDiskMap = std::unordered_map<std::string, NameOnDisk>;
  250. NameOnDiskMap CachedNameOnDisk;
  251. cmsys::Status ReadName(std::string const& path, std::string& name) override
  252. {
  253. // Cache results to avoid repeated filesystem access.
  254. // We assume any files created by our own process keep their case.
  255. // Index the cache by lower-case paths to make it case-insensitive.
  256. std::string path_lower = cmSystemTools::LowerCase(path);
  257. auto i = this->CachedNameOnDisk.find(path_lower);
  258. if (i == this->CachedNameOnDisk.end()) {
  259. i = this->CachedNameOnDisk.emplace(path_lower, NameOnDisk()).first;
  260. i->second.Status = ReadNameOnDisk(path, i->second.Name);
  261. }
  262. name = i->second.Name;
  263. return i->second.Status;
  264. }
  265. #endif
  266. };
  267. RealSystem RealOS;
  268. } // namespace
  269. #if !defined(HAVE_ENVIRON_NOT_REQUIRE_PROTOTYPE)
  270. // For GetEnvironmentVariables
  271. # if defined(_WIN32)
  272. extern __declspec(dllimport) char** environ;
  273. # else
  274. extern char** environ; // NOLINT(readability-redundant-declaration)
  275. # endif
  276. #endif
  277. #if !defined(CMAKE_BOOTSTRAP)
  278. static std::string cm_archive_entry_pathname(struct archive_entry* entry)
  279. {
  280. # if cmsys_STL_HAS_WSTRING
  281. return cmsys::Encoding::ToNarrow(archive_entry_pathname_w(entry));
  282. # else
  283. return archive_entry_pathname(entry);
  284. # endif
  285. }
  286. static int cm_archive_read_open_file(struct archive* a, const char* file,
  287. int block_size)
  288. {
  289. # if cmsys_STL_HAS_WSTRING
  290. std::wstring wfile = cmsys::Encoding::ToWide(file);
  291. return archive_read_open_filename_w(a, wfile.c_str(), block_size);
  292. # else
  293. return archive_read_open_filename(a, file, block_size);
  294. # endif
  295. }
  296. #endif
  297. #ifdef _WIN32
  298. #elif defined(__APPLE__)
  299. # include <crt_externs.h>
  300. # define environ (*_NSGetEnviron())
  301. #endif
  302. bool cmSystemTools::s_RunCommandHideConsole = false;
  303. bool cmSystemTools::s_DisableRunCommandOutput = false;
  304. bool cmSystemTools::s_ErrorOccurred = false;
  305. bool cmSystemTools::s_FatalErrorOccurred = false;
  306. bool cmSystemTools::s_ForceUnixPaths = false;
  307. // replace replace with with as many times as it shows up in source.
  308. // write the result into source.
  309. #if defined(_WIN32) && !defined(__CYGWIN__)
  310. void cmSystemTools::ExpandRegistryValues(std::string& source, KeyWOW64 view)
  311. {
  312. // Regular expression to match anything inside [...] that begins in HKEY.
  313. // Note that there is a special rule for regular expressions to match a
  314. // close square-bracket inside a list delimited by square brackets.
  315. // The "[^]]" part of this expression will match any character except
  316. // a close square-bracket. The ']' character must be the first in the
  317. // list of characters inside the [^...] block of the expression.
  318. cmsys::RegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  319. // check for black line or comment
  320. while (regEntry.find(source)) {
  321. // the arguments are the second match
  322. std::string key = regEntry.match(1);
  323. std::string val;
  324. if (ReadRegistryValue(key.c_str(), val, view)) {
  325. std::string reg = cmStrCat('[', key, ']');
  326. cmSystemTools::ReplaceString(source, reg.c_str(), val.c_str());
  327. } else {
  328. std::string reg = cmStrCat('[', key, ']');
  329. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  330. }
  331. }
  332. }
  333. #else
  334. void cmSystemTools::ExpandRegistryValues(std::string& source,
  335. KeyWOW64 /*unused*/)
  336. {
  337. cmsys::RegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  338. while (regEntry.find(source)) {
  339. // the arguments are the second match
  340. std::string key = regEntry.match(1);
  341. std::string reg = cmStrCat('[', key, ']');
  342. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  343. }
  344. }
  345. #endif
  346. // Return a lower case string
  347. std::string cmSystemTools::LowerCase(cm::string_view s)
  348. {
  349. std::string n;
  350. n.resize(s.size());
  351. for (size_t i = 0; i < s.size(); i++) {
  352. n[i] = static_cast<std::string::value_type>(tolower(s[i]));
  353. }
  354. return n;
  355. }
  356. // Return an upper case string
  357. std::string cmSystemTools::UpperCase(cm::string_view s)
  358. {
  359. std::string n;
  360. n.resize(s.size());
  361. for (size_t i = 0; i < s.size(); i++) {
  362. n[i] = static_cast<std::string::value_type>(toupper(s[i]));
  363. }
  364. return n;
  365. }
  366. std::string cmSystemTools::HelpFileName(cm::string_view str)
  367. {
  368. std::string name(str);
  369. cmSystemTools::ReplaceString(name, "<", "");
  370. cmSystemTools::ReplaceString(name, ">", "");
  371. return name;
  372. }
  373. void cmSystemTools::Error(const std::string& m)
  374. {
  375. std::string message = "CMake Error: " + m;
  376. cmSystemTools::s_ErrorOccurred = true;
  377. cmSystemTools::Message(message, "Error");
  378. }
  379. void cmSystemTools::SetInterruptCallback(InterruptCallback f)
  380. {
  381. s_InterruptCallback = std::move(f);
  382. }
  383. bool cmSystemTools::GetInterruptFlag()
  384. {
  385. if (s_InterruptCallback) {
  386. return s_InterruptCallback();
  387. }
  388. return false;
  389. }
  390. void cmSystemTools::SetMessageCallback(MessageCallback f)
  391. {
  392. s_MessageCallback = std::move(f);
  393. }
  394. void cmSystemTools::SetStdoutCallback(OutputCallback f)
  395. {
  396. s_StdoutCallback = std::move(f);
  397. }
  398. void cmSystemTools::SetStderrCallback(OutputCallback f)
  399. {
  400. s_StderrCallback = std::move(f);
  401. }
  402. void cmSystemTools::Stderr(const std::string& s)
  403. {
  404. if (s_StderrCallback) {
  405. s_StderrCallback(s);
  406. } else {
  407. std::cerr << s << std::flush;
  408. }
  409. }
  410. void cmSystemTools::Stdout(const std::string& s)
  411. {
  412. if (s_StdoutCallback) {
  413. s_StdoutCallback(s);
  414. } else {
  415. std::cout << s << std::flush;
  416. }
  417. }
  418. void cmSystemTools::Message(const std::string& m, const char* title)
  419. {
  420. cmMessageMetadata md;
  421. md.title = title;
  422. Message(m, md);
  423. }
  424. void cmSystemTools::Message(const std::string& m, const cmMessageMetadata& md)
  425. {
  426. if (s_MessageCallback) {
  427. s_MessageCallback(m, md);
  428. } else {
  429. std::cerr << m << std::endl;
  430. }
  431. }
  432. void cmSystemTools::ReportLastSystemError(const char* msg)
  433. {
  434. std::string m =
  435. cmStrCat(msg, ": System Error: ", Superclass::GetLastSystemError());
  436. cmSystemTools::Error(m);
  437. }
  438. void cmSystemTools::ParseWindowsCommandLine(const char* command,
  439. std::vector<std::string>& args)
  440. {
  441. // See the MSDN document "Parsing C Command-Line Arguments" at
  442. // http://msdn2.microsoft.com/en-us/library/a1y7w461.aspx for rules
  443. // of parsing the windows command line.
  444. bool in_argument = false;
  445. bool in_quotes = false;
  446. int backslashes = 0;
  447. std::string arg;
  448. for (const char* c = command; *c; ++c) {
  449. if (*c == '\\') {
  450. ++backslashes;
  451. in_argument = true;
  452. } else if (*c == '"') {
  453. int backslash_pairs = backslashes >> 1;
  454. int backslash_escaped = backslashes & 1;
  455. arg.append(backslash_pairs, '\\');
  456. backslashes = 0;
  457. if (backslash_escaped) {
  458. /* An odd number of backslashes precede this quote.
  459. It is escaped. */
  460. arg.append(1, '"');
  461. } else {
  462. /* An even number of backslashes precede this quote.
  463. It is not escaped. */
  464. in_quotes = !in_quotes;
  465. }
  466. in_argument = true;
  467. } else {
  468. arg.append(backslashes, '\\');
  469. backslashes = 0;
  470. if (cmIsSpace(*c)) {
  471. if (in_quotes) {
  472. arg.append(1, *c);
  473. } else if (in_argument) {
  474. args.push_back(arg);
  475. arg.clear();
  476. in_argument = false;
  477. }
  478. } else {
  479. in_argument = true;
  480. arg.append(1, *c);
  481. }
  482. }
  483. }
  484. arg.append(backslashes, '\\');
  485. if (in_argument) {
  486. args.push_back(arg);
  487. }
  488. }
  489. class cmSystemToolsArgV
  490. {
  491. char** ArgV;
  492. public:
  493. cmSystemToolsArgV(char** argv)
  494. : ArgV(argv)
  495. {
  496. }
  497. ~cmSystemToolsArgV()
  498. {
  499. for (char** arg = this->ArgV; arg && *arg; ++arg) {
  500. free(*arg);
  501. }
  502. free(this->ArgV);
  503. }
  504. cmSystemToolsArgV(const cmSystemToolsArgV&) = delete;
  505. cmSystemToolsArgV& operator=(const cmSystemToolsArgV&) = delete;
  506. void Store(std::vector<std::string>& args) const
  507. {
  508. for (char** arg = this->ArgV; arg && *arg; ++arg) {
  509. args.emplace_back(*arg);
  510. }
  511. }
  512. };
  513. void cmSystemTools::ParseUnixCommandLine(const char* command,
  514. std::vector<std::string>& args)
  515. {
  516. // Invoke the underlying parser.
  517. cmSystemToolsArgV argv(cmsysSystem_Parse_CommandForUnix(command, 0));
  518. argv.Store(args);
  519. }
  520. std::vector<std::string> cmSystemTools::HandleResponseFile(
  521. std::vector<std::string>::const_iterator argBeg,
  522. std::vector<std::string>::const_iterator argEnd)
  523. {
  524. std::vector<std::string> arg_full;
  525. for (std::string const& arg : cmMakeRange(argBeg, argEnd)) {
  526. if (cmHasLiteralPrefix(arg, "@")) {
  527. cmsys::ifstream responseFile(arg.substr(1).c_str(), std::ios::in);
  528. if (!responseFile) {
  529. std::string error = cmStrCat("failed to open for reading (",
  530. cmSystemTools::GetLastSystemError(),
  531. "):\n ", cm::string_view(arg).substr(1));
  532. cmSystemTools::Error(error);
  533. } else {
  534. std::string line;
  535. cmSystemTools::GetLineFromStream(responseFile, line);
  536. std::vector<std::string> args2;
  537. #ifdef _WIN32
  538. cmSystemTools::ParseWindowsCommandLine(line.c_str(), args2);
  539. #else
  540. cmSystemTools::ParseUnixCommandLine(line.c_str(), args2);
  541. #endif
  542. cm::append(arg_full, args2);
  543. }
  544. } else {
  545. arg_full.push_back(arg);
  546. }
  547. }
  548. return arg_full;
  549. }
  550. std::vector<std::string> cmSystemTools::ParseArguments(const std::string& cmd)
  551. {
  552. std::vector<std::string> args;
  553. std::string arg;
  554. bool win_path = false;
  555. const char* command = cmd.c_str();
  556. if (command[0] && command[1] &&
  557. ((command[0] != '/' && command[1] == ':' && command[2] == '\\') ||
  558. (command[0] == '\"' && command[1] != '/' && command[2] == ':' &&
  559. command[3] == '\\') ||
  560. (command[0] == '\'' && command[1] != '/' && command[2] == ':' &&
  561. command[3] == '\\') ||
  562. (command[0] == '\\' && command[1] == '\\'))) {
  563. win_path = true;
  564. }
  565. // Split the command into an argv array.
  566. for (const char* c = command; *c;) {
  567. // Skip over whitespace.
  568. while (*c == ' ' || *c == '\t') {
  569. ++c;
  570. }
  571. arg.clear();
  572. if (*c == '"') {
  573. // Parse a quoted argument.
  574. ++c;
  575. while (*c && *c != '"') {
  576. arg.append(1, *c);
  577. ++c;
  578. }
  579. if (*c) {
  580. ++c;
  581. }
  582. args.push_back(arg);
  583. } else if (*c == '\'') {
  584. // Parse a quoted argument.
  585. ++c;
  586. while (*c && *c != '\'') {
  587. arg.append(1, *c);
  588. ++c;
  589. }
  590. if (*c) {
  591. ++c;
  592. }
  593. args.push_back(arg);
  594. } else if (*c) {
  595. // Parse an unquoted argument.
  596. while (*c && *c != ' ' && *c != '\t') {
  597. if (*c == '\\' && !win_path) {
  598. ++c;
  599. if (*c) {
  600. arg.append(1, *c);
  601. ++c;
  602. }
  603. } else {
  604. arg.append(1, *c);
  605. ++c;
  606. }
  607. }
  608. args.push_back(arg);
  609. }
  610. }
  611. return args;
  612. }
  613. bool cmSystemTools::SplitProgramFromArgs(std::string const& command,
  614. std::string& program,
  615. std::string& args)
  616. {
  617. const char* c = command.c_str();
  618. // Skip leading whitespace.
  619. while (cmIsSpace(*c)) {
  620. ++c;
  621. }
  622. // Parse one command-line element up to an unquoted space.
  623. bool in_escape = false;
  624. bool in_double = false;
  625. bool in_single = false;
  626. for (; *c; ++c) {
  627. if (in_single) {
  628. if (*c == '\'') {
  629. in_single = false;
  630. } else {
  631. program += *c;
  632. }
  633. } else if (in_escape) {
  634. in_escape = false;
  635. program += *c;
  636. } else if (*c == '\\') {
  637. in_escape = true;
  638. } else if (in_double) {
  639. if (*c == '"') {
  640. in_double = false;
  641. } else {
  642. program += *c;
  643. }
  644. } else if (*c == '"') {
  645. in_double = true;
  646. } else if (*c == '\'') {
  647. in_single = true;
  648. } else if (cmIsSpace(*c)) {
  649. break;
  650. } else {
  651. program += *c;
  652. }
  653. }
  654. // The remainder of the command line holds unparsed arguments.
  655. args = c;
  656. return !in_single && !in_escape && !in_double;
  657. }
  658. std::size_t cmSystemTools::CalculateCommandLineLengthLimit()
  659. {
  660. size_t sz =
  661. #ifdef _WIN32
  662. // There's a maximum of 65536 bytes and thus 32768 WCHARs on Windows
  663. // However, cmd.exe itself can only handle 8191 WCHARs and Ninja for
  664. // example uses it to spawn processes.
  665. size_t(8191);
  666. #elif defined(__linux)
  667. // MAX_ARG_STRLEN is the maximum length of a string permissible for
  668. // the execve() syscall on Linux. It's defined as (PAGE_SIZE * 32)
  669. // in Linux's binfmts.h
  670. static_cast<size_t>(sysconf(_SC_PAGESIZE) * 32);
  671. #else
  672. size_t(0);
  673. #endif
  674. #if defined(_SC_ARG_MAX)
  675. // ARG_MAX is the maximum size of the command and environment
  676. // that can be passed to the exec functions on UNIX.
  677. // The value in climits does not need to be present and may
  678. // depend upon runtime memory constraints, hence sysconf()
  679. // should be used to query it.
  680. long szArgMax = sysconf(_SC_ARG_MAX);
  681. // A return value of -1 signifies an undetermined limit, but
  682. // it does not imply an infinite limit, and thus is ignored.
  683. if (szArgMax != -1) {
  684. // We estimate the size of the environment block to be 1000.
  685. // This isn't accurate at all, but leaves some headroom.
  686. szArgMax = szArgMax < 1000 ? 0 : szArgMax - 1000;
  687. # if defined(_WIN32) || defined(__linux)
  688. sz = std::min(sz, static_cast<size_t>(szArgMax));
  689. # else
  690. sz = static_cast<size_t>(szArgMax);
  691. # endif
  692. }
  693. #endif
  694. return sz;
  695. }
  696. bool cmSystemTools::RunSingleCommand(std::vector<std::string> const& command,
  697. std::string* captureStdOut,
  698. std::string* captureStdErr, int* retVal,
  699. const char* dir, OutputOption outputflag,
  700. cmDuration timeout, Encoding encoding)
  701. {
  702. cmUVProcessChainBuilder builder;
  703. builder.SetExternalStream(cmUVProcessChainBuilder::Stream_INPUT, stdin)
  704. .AddCommand(command);
  705. if (dir) {
  706. builder.SetWorkingDirectory(dir);
  707. }
  708. if (outputflag == OUTPUT_PASSTHROUGH) {
  709. captureStdOut = nullptr;
  710. captureStdErr = nullptr;
  711. builder.SetExternalStream(cmUVProcessChainBuilder::Stream_OUTPUT, stdout)
  712. .SetExternalStream(cmUVProcessChainBuilder::Stream_ERROR, stderr);
  713. } else if (outputflag == OUTPUT_MERGE ||
  714. (captureStdErr && captureStdErr == captureStdOut)) {
  715. builder.SetMergedBuiltinStreams();
  716. captureStdErr = nullptr;
  717. } else {
  718. builder.SetBuiltinStream(cmUVProcessChainBuilder::Stream_OUTPUT)
  719. .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR);
  720. }
  721. assert(!captureStdErr || captureStdErr != captureStdOut);
  722. auto chain = builder.Start();
  723. bool timedOut = false;
  724. cm::uv_timer_ptr timer;
  725. if (timeout.count()) {
  726. timer.init(chain.GetLoop(), &timedOut);
  727. timer.start(
  728. [](uv_timer_t* t) {
  729. auto* timedOutPtr = static_cast<bool*>(t->data);
  730. *timedOutPtr = true;
  731. },
  732. static_cast<uint64_t>(timeout.count() * 1000.0), 0);
  733. }
  734. std::vector<char> tempStdOut;
  735. std::vector<char> tempStdErr;
  736. cm::uv_pipe_ptr outStream;
  737. bool outFinished = true;
  738. cm::uv_pipe_ptr errStream;
  739. bool errFinished = true;
  740. cmProcessOutput processOutput(encoding);
  741. std::unique_ptr<cmUVStreamReadHandle> outputHandle;
  742. std::unique_ptr<cmUVStreamReadHandle> errorHandle;
  743. if (outputflag != OUTPUT_PASSTHROUGH &&
  744. (captureStdOut || captureStdErr || outputflag != OUTPUT_NONE)) {
  745. auto startRead =
  746. [&outputflag, &processOutput,
  747. &chain](cm::uv_pipe_ptr& pipe, int stream, std::string* captureStd,
  748. std::vector<char>& tempStd, int id,
  749. void (*outputFunc)(const std::string&),
  750. bool& finished) -> std::unique_ptr<cmUVStreamReadHandle> {
  751. if (stream < 0) {
  752. return nullptr;
  753. }
  754. pipe.init(chain.GetLoop(), 0);
  755. uv_pipe_open(pipe, stream);
  756. finished = false;
  757. return cmUVStreamRead(
  758. pipe,
  759. [outputflag, &processOutput, captureStd, &tempStd, id,
  760. outputFunc](std::vector<char> data) {
  761. // Translate NULL characters in the output into valid text.
  762. for (auto& c : data) {
  763. if (c == '\0') {
  764. c = ' ';
  765. }
  766. }
  767. if (outputflag != OUTPUT_NONE) {
  768. std::string strdata;
  769. processOutput.DecodeText(data.data(), data.size(), strdata, id);
  770. outputFunc(strdata);
  771. }
  772. if (captureStd) {
  773. cm::append(tempStd, data.data(), data.data() + data.size());
  774. }
  775. },
  776. [&finished, outputflag, &processOutput, id, outputFunc]() {
  777. finished = true;
  778. if (outputflag != OUTPUT_NONE) {
  779. std::string strdata;
  780. processOutput.DecodeText(std::string(), strdata, id);
  781. if (!strdata.empty()) {
  782. outputFunc(strdata);
  783. }
  784. }
  785. });
  786. };
  787. outputHandle =
  788. startRead(outStream, chain.OutputStream(), captureStdOut, tempStdOut, 1,
  789. cmSystemTools::Stdout, outFinished);
  790. if (chain.OutputStream() != chain.ErrorStream()) {
  791. errorHandle =
  792. startRead(errStream, chain.ErrorStream(), captureStdErr, tempStdErr, 2,
  793. cmSystemTools::Stderr, errFinished);
  794. }
  795. }
  796. while (!timedOut && !(chain.Finished() && outFinished && errFinished)) {
  797. uv_run(&chain.GetLoop(), UV_RUN_ONCE);
  798. }
  799. if (captureStdOut) {
  800. captureStdOut->assign(tempStdOut.begin(), tempStdOut.end());
  801. processOutput.DecodeText(*captureStdOut, *captureStdOut);
  802. }
  803. if (captureStdErr) {
  804. captureStdErr->assign(tempStdErr.begin(), tempStdErr.end());
  805. processOutput.DecodeText(*captureStdErr, *captureStdErr);
  806. }
  807. bool result = true;
  808. if (timedOut) {
  809. const char* error_str = "Process terminated due to timeout\n";
  810. if (outputflag != OUTPUT_NONE) {
  811. std::cerr << error_str << std::endl;
  812. }
  813. if (captureStdErr) {
  814. captureStdErr->append(error_str, strlen(error_str));
  815. }
  816. result = false;
  817. } else {
  818. auto const& status = chain.GetStatus(0);
  819. auto exception = status.GetException();
  820. switch (exception.first) {
  821. case cmUVProcessChain::ExceptionCode::None:
  822. if (retVal) {
  823. *retVal = static_cast<int>(status.ExitStatus);
  824. } else {
  825. if (status.ExitStatus != 0) {
  826. result = false;
  827. }
  828. }
  829. break;
  830. default: {
  831. if (outputflag != OUTPUT_NONE) {
  832. std::cerr << exception.second << std::endl;
  833. }
  834. if (captureStdErr) {
  835. captureStdErr->append(exception.second);
  836. } else if (captureStdOut) {
  837. captureStdOut->append(exception.second);
  838. }
  839. result = false;
  840. } break;
  841. }
  842. }
  843. return result;
  844. }
  845. bool cmSystemTools::RunSingleCommand(const std::string& command,
  846. std::string* captureStdOut,
  847. std::string* captureStdErr, int* retVal,
  848. const char* dir, OutputOption outputflag,
  849. cmDuration timeout)
  850. {
  851. if (s_DisableRunCommandOutput) {
  852. outputflag = OUTPUT_NONE;
  853. }
  854. std::vector<std::string> args = cmSystemTools::ParseArguments(command);
  855. if (args.empty()) {
  856. return false;
  857. }
  858. return cmSystemTools::RunSingleCommand(args, captureStdOut, captureStdErr,
  859. retVal, dir, outputflag, timeout);
  860. }
  861. std::string cmSystemTools::PrintSingleCommand(
  862. std::vector<std::string> const& command)
  863. {
  864. if (command.empty()) {
  865. return std::string();
  866. }
  867. return cmWrap('"', command, '"', " ");
  868. }
  869. bool cmSystemTools::DoesFileExistWithExtensions(
  870. const std::string& name, const std::vector<std::string>& headerExts)
  871. {
  872. std::string hname;
  873. for (std::string const& headerExt : headerExts) {
  874. hname = cmStrCat(name, '.', headerExt);
  875. if (cmSystemTools::FileExists(hname)) {
  876. return true;
  877. }
  878. }
  879. return false;
  880. }
  881. std::string cmSystemTools::FileExistsInParentDirectories(
  882. const std::string& fname, const std::string& directory,
  883. const std::string& toplevel)
  884. {
  885. std::string file = fname;
  886. cmSystemTools::ConvertToUnixSlashes(file);
  887. std::string dir = directory;
  888. cmSystemTools::ConvertToUnixSlashes(dir);
  889. std::string prevDir;
  890. while (dir != prevDir) {
  891. std::string path = cmStrCat(dir, "/", file);
  892. if (cmSystemTools::FileExists(path)) {
  893. return path;
  894. }
  895. if (dir.size() < toplevel.size()) {
  896. break;
  897. }
  898. prevDir = dir;
  899. dir = cmSystemTools::GetParentDirectory(dir);
  900. }
  901. return "";
  902. }
  903. #ifdef _WIN32
  904. namespace {
  905. /* Helper class to save and restore the specified file (or directory)
  906. attribute bits. Instantiate this class as an automatic variable on the
  907. stack. Its constructor saves a copy of the file attributes, and then its
  908. destructor restores the original attribute settings. */
  909. class SaveRestoreFileAttributes
  910. {
  911. public:
  912. SaveRestoreFileAttributes(std::wstring const& path,
  913. uint32_t file_attrs_to_set);
  914. ~SaveRestoreFileAttributes();
  915. SaveRestoreFileAttributes(SaveRestoreFileAttributes const&) = delete;
  916. SaveRestoreFileAttributes& operator=(SaveRestoreFileAttributes const&) =
  917. delete;
  918. void SetPath(std::wstring const& path) { path_ = path; }
  919. private:
  920. std::wstring path_;
  921. uint32_t original_attr_bits_;
  922. };
  923. SaveRestoreFileAttributes::SaveRestoreFileAttributes(
  924. std::wstring const& path, uint32_t file_attrs_to_set)
  925. : path_(path)
  926. , original_attr_bits_(0)
  927. {
  928. // Set the specified attributes for the source file/directory.
  929. original_attr_bits_ = GetFileAttributesW(path_.c_str());
  930. if ((INVALID_FILE_ATTRIBUTES != original_attr_bits_) &&
  931. ((file_attrs_to_set & original_attr_bits_) != file_attrs_to_set)) {
  932. SetFileAttributesW(path_.c_str(), original_attr_bits_ | file_attrs_to_set);
  933. }
  934. }
  935. // We set attribute bits. Now we need to restore their original state.
  936. SaveRestoreFileAttributes::~SaveRestoreFileAttributes()
  937. {
  938. DWORD last_error = GetLastError();
  939. // Verify or restore the original attributes.
  940. const DWORD source_attr_bits = GetFileAttributesW(path_.c_str());
  941. if (INVALID_FILE_ATTRIBUTES != source_attr_bits) {
  942. if (original_attr_bits_ != source_attr_bits) {
  943. // The file still exists, and its attributes aren't our saved values.
  944. // Time to restore them.
  945. SetFileAttributesW(path_.c_str(), original_attr_bits_);
  946. }
  947. }
  948. SetLastError(last_error);
  949. }
  950. struct WindowsFileRetryInit
  951. {
  952. cmSystemTools::WindowsFileRetry Retry;
  953. bool Explicit;
  954. };
  955. WindowsFileRetryInit InitWindowsFileRetry(wchar_t const* const values[2],
  956. unsigned int const defaults[2])
  957. {
  958. unsigned int data[2] = { 0, 0 };
  959. HKEY const keys[2] = { HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE };
  960. for (int k = 0; k < 2; ++k) {
  961. HKEY hKey;
  962. if (RegOpenKeyExW(keys[k], L"Software\\Kitware\\CMake\\Config", 0,
  963. KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS) {
  964. for (int v = 0; v < 2; ++v) {
  965. DWORD dwData, dwType, dwSize = 4;
  966. if (!data[v] &&
  967. RegQueryValueExW(hKey, values[v], 0, &dwType, (BYTE*)&dwData,
  968. &dwSize) == ERROR_SUCCESS &&
  969. dwType == REG_DWORD && dwSize == 4) {
  970. data[v] = static_cast<unsigned int>(dwData);
  971. }
  972. }
  973. RegCloseKey(hKey);
  974. }
  975. }
  976. WindowsFileRetryInit init;
  977. init.Explicit = data[0] || data[1];
  978. init.Retry.Count = data[0] ? data[0] : defaults[0];
  979. init.Retry.Delay = data[1] ? data[1] : defaults[1];
  980. return init;
  981. }
  982. WindowsFileRetryInit InitWindowsFileRetry()
  983. {
  984. static wchar_t const* const values[2] = { L"FilesystemRetryCount",
  985. L"FilesystemRetryDelay" };
  986. static unsigned int const defaults[2] = { 5, 500 };
  987. return InitWindowsFileRetry(values, defaults);
  988. }
  989. WindowsFileRetryInit InitWindowsDirectoryRetry()
  990. {
  991. static wchar_t const* const values[2] = { L"FilesystemDirectoryRetryCount",
  992. L"FilesystemDirectoryRetryDelay" };
  993. static unsigned int const defaults[2] = { 120, 500 };
  994. WindowsFileRetryInit dirInit = InitWindowsFileRetry(values, defaults);
  995. if (dirInit.Explicit) {
  996. return dirInit;
  997. }
  998. WindowsFileRetryInit fileInit = InitWindowsFileRetry();
  999. if (fileInit.Explicit) {
  1000. return fileInit;
  1001. }
  1002. return dirInit;
  1003. }
  1004. cmSystemTools::WindowsFileRetry GetWindowsRetry(std::wstring const& path)
  1005. {
  1006. // If we are performing a directory operation, then try and get the
  1007. // appropriate timing info.
  1008. DWORD const attrs = GetFileAttributesW(path.c_str());
  1009. if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
  1010. return cmSystemTools::GetWindowsDirectoryRetry();
  1011. }
  1012. return cmSystemTools::GetWindowsFileRetry();
  1013. }
  1014. } // end of anonymous namespace
  1015. cmSystemTools::WindowsFileRetry cmSystemTools::GetWindowsFileRetry()
  1016. {
  1017. static WindowsFileRetry retry = InitWindowsFileRetry().Retry;
  1018. return retry;
  1019. }
  1020. cmSystemTools::WindowsFileRetry cmSystemTools::GetWindowsDirectoryRetry()
  1021. {
  1022. static cmSystemTools::WindowsFileRetry retry =
  1023. InitWindowsDirectoryRetry().Retry;
  1024. return retry;
  1025. }
  1026. cmSystemTools::WindowsVersion cmSystemTools::GetWindowsVersion()
  1027. {
  1028. /* Windows version number data. */
  1029. OSVERSIONINFOEXW osviex;
  1030. ZeroMemory(&osviex, sizeof(osviex));
  1031. osviex.dwOSVersionInfoSize = sizeof(osviex);
  1032. # ifdef CM_WINDOWS_DEPRECATED_GetVersionEx
  1033. # pragma warning(push)
  1034. # ifdef __INTEL_COMPILER
  1035. # pragma warning(disable : 1478)
  1036. # elif defined __clang__
  1037. # pragma clang diagnostic push
  1038. # pragma clang diagnostic ignored "-Wdeprecated-declarations"
  1039. # else
  1040. # pragma warning(disable : 4996)
  1041. # endif
  1042. # endif
  1043. GetVersionExW((OSVERSIONINFOW*)&osviex);
  1044. # ifdef CM_WINDOWS_DEPRECATED_GetVersionEx
  1045. # ifdef __clang__
  1046. # pragma clang diagnostic pop
  1047. # else
  1048. # pragma warning(pop)
  1049. # endif
  1050. # endif
  1051. WindowsVersion result;
  1052. result.dwMajorVersion = osviex.dwMajorVersion;
  1053. result.dwMinorVersion = osviex.dwMinorVersion;
  1054. result.dwBuildNumber = osviex.dwBuildNumber;
  1055. return result;
  1056. }
  1057. std::string cmSystemTools::GetComspec()
  1058. {
  1059. std::string comspec;
  1060. if (!cmSystemTools::GetEnv("COMSPEC", comspec) ||
  1061. !cmSystemTools::FileIsFullPath(comspec)) {
  1062. comspec = "cmd.exe";
  1063. }
  1064. return comspec;
  1065. }
  1066. #endif
  1067. std::string cmSystemTools::GetRealPath(const std::string& path,
  1068. std::string* errorMessage)
  1069. {
  1070. #ifdef _WIN32
  1071. std::string resolved_path;
  1072. using namespace cm::PathResolver;
  1073. // IWYU pragma: no_forward_declare cm::PathResolver::Policies::RealPath
  1074. static const Resolver<Policies::RealPath> resolver(RealOS);
  1075. cmsys::Status status = resolver.Resolve(path, resolved_path);
  1076. if (!status) {
  1077. if (errorMessage) {
  1078. *errorMessage = status.GetString();
  1079. resolved_path.clear();
  1080. } else {
  1081. resolved_path = path;
  1082. }
  1083. }
  1084. return resolved_path;
  1085. #else
  1086. return cmsys::SystemTools::GetRealPath(path, errorMessage);
  1087. #endif
  1088. }
  1089. void cmSystemTools::InitializeLibUV()
  1090. {
  1091. #if defined(_WIN32)
  1092. // Perform libuv one-time initialization now, and then un-do its
  1093. // global _fmode setting so that using libuv does not change the
  1094. // default file text/binary mode. See libuv issue 840.
  1095. if (uv_loop_t* loop = uv_default_loop()) {
  1096. uv_loop_close(loop);
  1097. }
  1098. # ifdef _MSC_VER
  1099. _set_fmode(_O_TEXT);
  1100. # else
  1101. _fmode = _O_TEXT;
  1102. # endif
  1103. // Replace libuv's report handler with our own to suppress popups.
  1104. cmSystemTools::EnableMSVCDebugHook();
  1105. #endif
  1106. }
  1107. #if defined(_WIN32)
  1108. # include <random>
  1109. # include <wctype.h>
  1110. # ifdef _MSC_VER
  1111. using mode_t = cmSystemTools::SystemTools::mode_t;
  1112. # endif
  1113. #else
  1114. # include <sys/stat.h>
  1115. #endif
  1116. inline int Mkdir(const char* dir, const mode_t* mode)
  1117. {
  1118. #if defined(_WIN32)
  1119. int ret = _wmkdir(cmSystemTools::ConvertToWindowsExtendedPath(dir).c_str());
  1120. if (ret == 0 && mode)
  1121. cmSystemTools::SystemTools::SetPermissions(dir, *mode);
  1122. return ret;
  1123. #else
  1124. return mkdir(dir, mode ? *mode : 0777);
  1125. #endif
  1126. }
  1127. cmsys::Status cmSystemTools::MakeTempDirectory(std::string& path,
  1128. const mode_t* mode)
  1129. {
  1130. if (path.empty()) {
  1131. return cmsys::Status::POSIX(EINVAL);
  1132. }
  1133. return cmSystemTools::MakeTempDirectory(&path.front(), mode);
  1134. }
  1135. cmsys::Status cmSystemTools::MakeTempDirectory(char* path, const mode_t* mode)
  1136. {
  1137. if (!path) {
  1138. return cmsys::Status::POSIX(EINVAL);
  1139. }
  1140. // verify that path ends with "XXXXXX"
  1141. const auto l = std::strlen(path);
  1142. if (!cmHasLiteralSuffix(cm::string_view{ path, l }, "XXXXXX")) {
  1143. return cmsys::Status::POSIX(EINVAL);
  1144. }
  1145. // create parent directories
  1146. auto* sep = path;
  1147. while ((sep = strchr(sep, '/'))) {
  1148. // all underlying functions use C strings,
  1149. // so temporarily end the string here
  1150. *sep = '\0';
  1151. Mkdir(path, mode);
  1152. *sep = '/';
  1153. ++sep;
  1154. }
  1155. #ifdef _WIN32
  1156. const int nchars = 36;
  1157. const char chars[nchars + 1] = "abcdefghijklmnopqrstuvwxyz0123456789";
  1158. std::random_device rd;
  1159. std::mt19937 rg{ rd() };
  1160. std::uniform_int_distribution<int> dist{ 0, nchars - 1 };
  1161. for (auto tries = 100; tries; --tries) {
  1162. for (auto n = l - 6; n < l; ++n) {
  1163. path[n] = chars[dist(rg)];
  1164. }
  1165. if (Mkdir(path, mode) == 0) {
  1166. return cmsys::Status::Success();
  1167. } else if (errno != EEXIST) {
  1168. return cmsys::Status::POSIX_errno();
  1169. }
  1170. }
  1171. return cmsys::Status::POSIX(EAGAIN);
  1172. #else
  1173. if (mkdtemp(path)) {
  1174. if (mode) {
  1175. chmod(path, *mode);
  1176. }
  1177. } else {
  1178. return cmsys::Status::POSIX_errno();
  1179. }
  1180. return cmsys::Status::Success();
  1181. #endif
  1182. }
  1183. #ifdef _WIN32
  1184. namespace {
  1185. bool cmMoveFile(std::wstring const& oldname, std::wstring const& newname,
  1186. cmSystemTools::Replace replace)
  1187. {
  1188. // Not only ignore any previous error, but clear any memory of it.
  1189. SetLastError(0);
  1190. DWORD flags = 0;
  1191. if (replace == cmSystemTools::Replace::Yes) {
  1192. // Use MOVEFILE_REPLACE_EXISTING to replace an existing destination file.
  1193. flags = flags | MOVEFILE_REPLACE_EXISTING;
  1194. }
  1195. return MoveFileExW(oldname.c_str(), newname.c_str(), flags);
  1196. }
  1197. }
  1198. #endif
  1199. cmSystemTools::CopyResult cmSystemTools::CopySingleFile(
  1200. std::string const& oldname, std::string const& newname, CopyWhen when,
  1201. CopyInputRecent inputRecent, std::string* err)
  1202. {
  1203. switch (when) {
  1204. case CopyWhen::Always:
  1205. break;
  1206. case CopyWhen::OnlyIfDifferent:
  1207. if (!FilesDiffer(oldname, newname)) {
  1208. return CopyResult::Success;
  1209. }
  1210. break;
  1211. }
  1212. mode_t perm = 0;
  1213. cmsys::Status perms = SystemTools::GetPermissions(oldname, perm);
  1214. // If files are the same do not copy
  1215. if (SystemTools::SameFile(oldname, newname)) {
  1216. return CopyResult::Success;
  1217. }
  1218. cmsys::SystemTools::CopyStatus status;
  1219. status = cmsys::SystemTools::CloneFileContent(oldname, newname);
  1220. if (!status) {
  1221. // if cloning did not succeed, fall back to blockwise copy
  1222. #ifdef _WIN32
  1223. if (inputRecent == CopyInputRecent::Yes) {
  1224. // Windows sometimes locks a file immediately after creation.
  1225. // Retry a few times.
  1226. WindowsFileRetry retry = cmSystemTools::GetWindowsFileRetry();
  1227. while ((status =
  1228. cmsys::SystemTools::CopyFileContentBlockwise(oldname, newname),
  1229. status.Path == cmsys::SystemTools::CopyStatus::SourcePath &&
  1230. status.GetPOSIX() == EACCES && --retry.Count)) {
  1231. cmSystemTools::Delay(retry.Delay);
  1232. }
  1233. } else {
  1234. status = cmsys::SystemTools::CopyFileContentBlockwise(oldname, newname);
  1235. }
  1236. #else
  1237. static_cast<void>(inputRecent);
  1238. status = cmsys::SystemTools::CopyFileContentBlockwise(oldname, newname);
  1239. #endif
  1240. }
  1241. if (!status) {
  1242. if (err) {
  1243. *err = status.GetString();
  1244. switch (status.Path) {
  1245. case cmsys::SystemTools::CopyStatus::SourcePath:
  1246. *err = cmStrCat(*err, " (input)");
  1247. break;
  1248. case cmsys::SystemTools::CopyStatus::DestPath:
  1249. *err = cmStrCat(*err, " (output)");
  1250. break;
  1251. default:
  1252. break;
  1253. }
  1254. }
  1255. return CopyResult::Failure;
  1256. }
  1257. if (perms) {
  1258. perms = SystemTools::SetPermissions(newname, perm);
  1259. if (!perms) {
  1260. if (err) {
  1261. *err = cmStrCat(perms.GetString(), " (output)");
  1262. }
  1263. return CopyResult::Failure;
  1264. }
  1265. }
  1266. return CopyResult::Success;
  1267. }
  1268. bool cmSystemTools::RenameFile(const std::string& oldname,
  1269. const std::string& newname)
  1270. {
  1271. return cmSystemTools::RenameFile(oldname, newname, Replace::Yes) ==
  1272. RenameResult::Success;
  1273. }
  1274. cmSystemTools::RenameResult cmSystemTools::RenameFile(
  1275. std::string const& oldname, std::string const& newname, Replace replace,
  1276. std::string* err)
  1277. {
  1278. #ifdef _WIN32
  1279. # ifndef INVALID_FILE_ATTRIBUTES
  1280. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  1281. # endif
  1282. std::wstring const oldname_wstr =
  1283. SystemTools::ConvertToWindowsExtendedPath(oldname);
  1284. std::wstring const newname_wstr =
  1285. SystemTools::ConvertToWindowsExtendedPath(newname);
  1286. /* Windows MoveFileEx may not replace read-only or in-use files. If it
  1287. fails then remove the read-only attribute from any existing destination.
  1288. Try multiple times since we may be racing against another process
  1289. creating/opening the destination file just before our MoveFileEx. */
  1290. WindowsFileRetry retry = GetWindowsRetry(oldname_wstr);
  1291. // Use RAII to set the attribute bit blocking Microsoft Search Indexing,
  1292. // and restore the previous value upon return.
  1293. SaveRestoreFileAttributes save_restore_file_attributes(
  1294. oldname_wstr, FILE_ATTRIBUTE_NOT_CONTENT_INDEXED);
  1295. DWORD move_last_error = 0;
  1296. while (!cmMoveFile(oldname_wstr, newname_wstr, replace) && --retry.Count) {
  1297. move_last_error = GetLastError();
  1298. // There was no error ==> the operation is not yet complete.
  1299. if (move_last_error == NO_ERROR) {
  1300. break;
  1301. }
  1302. // Try again only if failure was due to access/sharing permissions.
  1303. // Most often ERROR_ACCESS_DENIED (a.k.a. I/O error) for a directory, and
  1304. // ERROR_SHARING_VIOLATION for a file, are caused by one of the following:
  1305. // 1) Anti-Virus Software
  1306. // 2) Windows Search Indexer
  1307. // 3) Windows Explorer has an associated directory already opened.
  1308. if (move_last_error != ERROR_ACCESS_DENIED &&
  1309. move_last_error != ERROR_SHARING_VIOLATION) {
  1310. if (replace == Replace::No && move_last_error == ERROR_ALREADY_EXISTS) {
  1311. return RenameResult::NoReplace;
  1312. }
  1313. if (err) {
  1314. *err = cmsys::Status::Windows(move_last_error).GetString();
  1315. }
  1316. return RenameResult::Failure;
  1317. }
  1318. DWORD const attrs = GetFileAttributesW(newname_wstr.c_str());
  1319. if ((attrs != INVALID_FILE_ATTRIBUTES) &&
  1320. (attrs & FILE_ATTRIBUTE_READONLY) &&
  1321. // FILE_ATTRIBUTE_READONLY is not honored on directories.
  1322. !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {
  1323. // Remove the read-only attribute from the destination file.
  1324. SetFileAttributesW(newname_wstr.c_str(),
  1325. attrs & ~FILE_ATTRIBUTE_READONLY);
  1326. } else {
  1327. // The file may be temporarily in use so wait a bit.
  1328. cmSystemTools::Delay(retry.Delay);
  1329. }
  1330. }
  1331. // If we were successful, then there was no error.
  1332. if (retry.Count > 0) {
  1333. move_last_error = 0;
  1334. // Restore the attributes on the new name.
  1335. save_restore_file_attributes.SetPath(newname_wstr);
  1336. }
  1337. SetLastError(move_last_error);
  1338. if (retry.Count > 0) {
  1339. return RenameResult::Success;
  1340. }
  1341. if (replace == Replace::No && GetLastError() == ERROR_ALREADY_EXISTS) {
  1342. return RenameResult::NoReplace;
  1343. }
  1344. if (err) {
  1345. *err = cmsys::Status::Windows_GetLastError().GetString();
  1346. }
  1347. return RenameResult::Failure;
  1348. #else
  1349. // On UNIX we have OS-provided calls to create 'newname' atomically.
  1350. if (replace == Replace::No) {
  1351. if (link(oldname.c_str(), newname.c_str()) == 0) {
  1352. return RenameResult::Success;
  1353. }
  1354. if (errno == EEXIST) {
  1355. return RenameResult::NoReplace;
  1356. }
  1357. if (err) {
  1358. *err = cmsys::Status::POSIX_errno().GetString();
  1359. }
  1360. return RenameResult::Failure;
  1361. }
  1362. if (rename(oldname.c_str(), newname.c_str()) == 0) {
  1363. return RenameResult::Success;
  1364. }
  1365. if (err) {
  1366. *err = cmsys::Status::POSIX_errno().GetString();
  1367. }
  1368. return RenameResult::Failure;
  1369. #endif
  1370. }
  1371. cmsys::Status cmSystemTools::MoveFileIfDifferent(
  1372. const std::string& source, const std::string& destination)
  1373. {
  1374. cmsys::Status res = {};
  1375. if (FilesDiffer(source, destination)) {
  1376. if (RenameFile(source, destination)) {
  1377. return res;
  1378. }
  1379. res = CopyFileAlways(source, destination);
  1380. }
  1381. RemoveFile(source);
  1382. return res;
  1383. }
  1384. void cmSystemTools::Glob(const std::string& directory,
  1385. const std::string& regexp,
  1386. std::vector<std::string>& files)
  1387. {
  1388. cmsys::Directory d;
  1389. cmsys::RegularExpression reg(regexp.c_str());
  1390. if (d.Load(directory)) {
  1391. size_t numf;
  1392. unsigned int i;
  1393. numf = d.GetNumberOfFiles();
  1394. for (i = 0; i < numf; i++) {
  1395. std::string fname = d.GetFile(i);
  1396. if (reg.find(fname)) {
  1397. files.push_back(std::move(fname));
  1398. }
  1399. }
  1400. }
  1401. }
  1402. void cmSystemTools::GlobDirs(const std::string& path,
  1403. std::vector<std::string>& files)
  1404. {
  1405. std::string::size_type pos = path.find("/*");
  1406. if (pos == std::string::npos) {
  1407. files.push_back(path);
  1408. return;
  1409. }
  1410. std::string startPath = path.substr(0, pos);
  1411. std::string finishPath = path.substr(pos + 2);
  1412. cmsys::Directory d;
  1413. if (d.Load(startPath)) {
  1414. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i) {
  1415. if ((std::string(d.GetFile(i)) != ".") &&
  1416. (std::string(d.GetFile(i)) != "..")) {
  1417. std::string fname = cmStrCat(startPath, '/', d.GetFile(i));
  1418. if (cmSystemTools::FileIsDirectory(fname)) {
  1419. fname += finishPath;
  1420. cmSystemTools::GlobDirs(fname, files);
  1421. }
  1422. }
  1423. }
  1424. }
  1425. }
  1426. bool cmSystemTools::SimpleGlob(const std::string& glob,
  1427. std::vector<std::string>& files,
  1428. int type /* = 0 */)
  1429. {
  1430. files.clear();
  1431. if (glob.back() != '*') {
  1432. return false;
  1433. }
  1434. std::string path = cmSystemTools::GetFilenamePath(glob);
  1435. std::string ppath = cmSystemTools::GetFilenameName(glob);
  1436. ppath = ppath.substr(0, ppath.size() - 1);
  1437. if (path.empty()) {
  1438. path = "/";
  1439. }
  1440. bool res = false;
  1441. cmsys::Directory d;
  1442. if (d.Load(path)) {
  1443. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i) {
  1444. if ((std::string(d.GetFile(i)) != ".") &&
  1445. (std::string(d.GetFile(i)) != "..")) {
  1446. std::string fname = path;
  1447. if (path.back() != '/') {
  1448. fname += "/";
  1449. }
  1450. fname += d.GetFile(i);
  1451. std::string sfname = d.GetFile(i);
  1452. if (type > 0 && cmSystemTools::FileIsDirectory(fname)) {
  1453. continue;
  1454. }
  1455. if (type < 0 && !cmSystemTools::FileIsDirectory(fname)) {
  1456. continue;
  1457. }
  1458. if (cmHasPrefix(sfname, ppath)) {
  1459. files.push_back(fname);
  1460. res = true;
  1461. }
  1462. }
  1463. }
  1464. }
  1465. return res;
  1466. }
  1467. std::string cmSystemTools::ConvertToOutputPath(std::string const& path)
  1468. {
  1469. #if defined(_WIN32) && !defined(__CYGWIN__)
  1470. if (s_ForceUnixPaths) {
  1471. return cmSystemTools::ConvertToUnixOutputPath(path);
  1472. }
  1473. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1474. #else
  1475. return cmSystemTools::ConvertToUnixOutputPath(path);
  1476. #endif
  1477. }
  1478. void cmSystemTools::ConvertToOutputSlashes(std::string& path)
  1479. {
  1480. #if defined(_WIN32) && !defined(__CYGWIN__)
  1481. if (!s_ForceUnixPaths) {
  1482. // Convert to windows slashes.
  1483. std::string::size_type pos = 0;
  1484. while ((pos = path.find('/', pos)) != std::string::npos) {
  1485. path[pos++] = '\\';
  1486. }
  1487. }
  1488. #else
  1489. static_cast<void>(path);
  1490. #endif
  1491. }
  1492. void cmSystemTools::ConvertToLongPath(std::string& path)
  1493. {
  1494. #if defined(_WIN32) && !defined(__CYGWIN__)
  1495. // Try to convert path to a long path only if the path contains character '~'
  1496. if (path.find('~') == std::string::npos) {
  1497. return;
  1498. }
  1499. std::wstring wPath = cmsys::Encoding::ToWide(path);
  1500. DWORD ret = GetLongPathNameW(wPath.c_str(), nullptr, 0);
  1501. std::vector<wchar_t> buffer(ret);
  1502. if (ret != 0) {
  1503. ret = GetLongPathNameW(wPath.c_str(), buffer.data(),
  1504. static_cast<DWORD>(buffer.size()));
  1505. }
  1506. if (ret != 0) {
  1507. path = cmsys::Encoding::ToNarrow(buffer.data());
  1508. }
  1509. #else
  1510. static_cast<void>(path);
  1511. #endif
  1512. }
  1513. std::string cmSystemTools::ConvertToRunCommandPath(const std::string& path)
  1514. {
  1515. #if defined(_WIN32) && !defined(__CYGWIN__)
  1516. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1517. #else
  1518. return cmSystemTools::ConvertToUnixOutputPath(path);
  1519. #endif
  1520. }
  1521. // compute the relative path from here to there
  1522. std::string cmSystemTools::RelativePath(std::string const& local,
  1523. std::string const& remote)
  1524. {
  1525. if (!cmSystemTools::FileIsFullPath(local)) {
  1526. cmSystemTools::Error("RelativePath must be passed a full path to local: " +
  1527. local);
  1528. }
  1529. if (!cmSystemTools::FileIsFullPath(remote)) {
  1530. cmSystemTools::Error(
  1531. "RelativePath must be passed a full path to remote: " + remote);
  1532. }
  1533. return cmsys::SystemTools::RelativePath(local, remote);
  1534. }
  1535. std::string cmSystemTools::ForceToRelativePath(std::string const& local_path,
  1536. std::string const& remote_path)
  1537. {
  1538. // The paths should never be quoted.
  1539. assert(local_path.front() != '\"');
  1540. assert(remote_path.front() != '\"');
  1541. // The local path should never have a trailing slash except if it is just the
  1542. // bare root directory
  1543. assert(local_path.empty() || local_path.back() != '/' ||
  1544. local_path.size() == 1 ||
  1545. (local_path.size() == 3 && local_path[1] == ':' &&
  1546. ((local_path[0] >= 'A' && local_path[0] <= 'Z') ||
  1547. (local_path[0] >= 'a' && local_path[0] <= 'z'))));
  1548. // If the path is already relative then just return the path.
  1549. if (!cmSystemTools::FileIsFullPath(remote_path)) {
  1550. return remote_path;
  1551. }
  1552. // Identify the longest shared path component between the remote
  1553. // path and the local path.
  1554. std::vector<std::string> local;
  1555. cmSystemTools::SplitPath(local_path, local);
  1556. std::vector<std::string> remote;
  1557. cmSystemTools::SplitPath(remote_path, remote);
  1558. unsigned int common = 0;
  1559. while (common < remote.size() && common < local.size() &&
  1560. cmSystemTools::ComparePath(remote[common], local[common])) {
  1561. ++common;
  1562. }
  1563. // If no part of the path is in common then return the full path.
  1564. if (common == 0) {
  1565. return remote_path;
  1566. }
  1567. // If the entire path is in common then just return a ".".
  1568. if (common == remote.size() && common == local.size()) {
  1569. return ".";
  1570. }
  1571. // If the entire path is in common except for a trailing slash then
  1572. // just return a "./".
  1573. if (common + 1 == remote.size() && remote[common].empty() &&
  1574. common == local.size()) {
  1575. return "./";
  1576. }
  1577. // Construct the relative path.
  1578. std::string relative;
  1579. // First add enough ../ to get up to the level of the shared portion
  1580. // of the path. Leave off the trailing slash. Note that the last
  1581. // component of local will never be empty because local should never
  1582. // have a trailing slash.
  1583. for (unsigned int i = common; i < local.size(); ++i) {
  1584. relative += "..";
  1585. if (i < local.size() - 1) {
  1586. relative += "/";
  1587. }
  1588. }
  1589. // Now add the portion of the destination path that is not included
  1590. // in the shared portion of the path. Add a slash the first time
  1591. // only if there was already something in the path. If there was a
  1592. // trailing slash in the input then the last iteration of the loop
  1593. // will add a slash followed by an empty string which will preserve
  1594. // the trailing slash in the output.
  1595. if (!relative.empty() && !remote.empty()) {
  1596. relative += "/";
  1597. }
  1598. relative += cmJoin(cmMakeRange(remote).advance(common), "/");
  1599. // Finally return the path.
  1600. return relative;
  1601. }
  1602. std::string cmSystemTools::RelativeIfUnder(std::string const& top,
  1603. std::string const& in)
  1604. {
  1605. std::string out;
  1606. if (in == top) {
  1607. out = ".";
  1608. } else if (cmSystemTools::IsSubDirectory(in, top)) {
  1609. out = in.substr(top.size() + 1);
  1610. } else {
  1611. out = in;
  1612. }
  1613. return out;
  1614. }
  1615. cm::optional<std::string> cmSystemTools::GetEnvVar(std::string const& var)
  1616. {
  1617. cm::optional<std::string> result;
  1618. {
  1619. std::string value;
  1620. if (cmSystemTools::GetEnv(var, value)) {
  1621. result = std::move(value);
  1622. }
  1623. }
  1624. return result;
  1625. }
  1626. std::vector<std::string> cmSystemTools::GetEnvPathNormalized(
  1627. std::string const& var)
  1628. {
  1629. std::vector<std::string> result;
  1630. if (cm::optional<std::string> env = cmSystemTools::GetEnvVar(var)) {
  1631. std::vector<std::string> p = cmSystemTools::SplitEnvPathNormalized(*env);
  1632. std::move(p.begin(), p.end(), std::back_inserter(result));
  1633. }
  1634. return result;
  1635. }
  1636. std::vector<std::string> cmSystemTools::SplitEnvPath(cm::string_view in)
  1637. {
  1638. #if defined(_WIN32) && !defined(__CYGWIN__)
  1639. static cm::string_view sep = ";"_s;
  1640. #else
  1641. static cm::string_view sep = ":"_s;
  1642. #endif
  1643. std::vector<std::string> paths;
  1644. cm::string_view::size_type e = 0;
  1645. for (;;) {
  1646. cm::string_view::size_type b = in.find_first_not_of(sep, e);
  1647. if (b == cm::string_view::npos) {
  1648. break;
  1649. }
  1650. e = in.find_first_of(sep, b);
  1651. if (e == cm::string_view::npos) {
  1652. paths.emplace_back(in.substr(b));
  1653. break;
  1654. }
  1655. paths.emplace_back(in.substr(b, e - b));
  1656. }
  1657. return paths;
  1658. }
  1659. std::vector<std::string> cmSystemTools::SplitEnvPathNormalized(
  1660. cm::string_view in)
  1661. {
  1662. std::vector<std::string> paths = cmSystemTools::SplitEnvPath(in);
  1663. std::transform(paths.begin(), paths.end(), paths.begin(),
  1664. cmSystemTools::ToNormalizedPathOnDisk);
  1665. return paths;
  1666. }
  1667. std::string cmSystemTools::ToNormalizedPathOnDisk(std::string p)
  1668. {
  1669. using namespace cm::PathResolver;
  1670. // IWYU pragma: no_forward_declare cm::PathResolver::Policies::LogicalPath
  1671. static const Resolver<Policies::LogicalPath> resolver(RealOS);
  1672. resolver.Resolve(std::move(p), p);
  1673. return p;
  1674. }
  1675. #ifndef CMAKE_BOOTSTRAP
  1676. bool cmSystemTools::UnsetEnv(const char* value)
  1677. {
  1678. # if !defined(HAVE_UNSETENV)
  1679. return cmSystemTools::UnPutEnv(value);
  1680. # else
  1681. unsetenv(value);
  1682. return true;
  1683. # endif
  1684. }
  1685. std::vector<std::string> cmSystemTools::GetEnvironmentVariables()
  1686. {
  1687. std::vector<std::string> env;
  1688. int cc;
  1689. # ifdef _WIN32
  1690. // if program starts with main, _wenviron is initially NULL, call to
  1691. // _wgetenv and create wide-character string environment
  1692. _wgetenv(L"");
  1693. for (cc = 0; _wenviron[cc]; ++cc) {
  1694. env.emplace_back(cmsys::Encoding::ToNarrow(_wenviron[cc]));
  1695. }
  1696. # else
  1697. for (cc = 0; environ[cc]; ++cc) {
  1698. env.emplace_back(environ[cc]);
  1699. }
  1700. # endif
  1701. return env;
  1702. }
  1703. void cmSystemTools::AppendEnv(std::vector<std::string> const& env)
  1704. {
  1705. for (std::string const& eit : env) {
  1706. cmSystemTools::PutEnv(eit);
  1707. }
  1708. }
  1709. void cmSystemTools::EnvDiff::AppendEnv(std::vector<std::string> const& env)
  1710. {
  1711. for (std::string const& eit : env) {
  1712. this->PutEnv(eit);
  1713. }
  1714. }
  1715. void cmSystemTools::EnvDiff::PutEnv(const std::string& env)
  1716. {
  1717. auto const eq_loc = env.find('=');
  1718. if (eq_loc != std::string::npos) {
  1719. std::string name = env.substr(0, eq_loc);
  1720. diff[name] = env.substr(eq_loc + 1);
  1721. } else {
  1722. this->UnPutEnv(env);
  1723. }
  1724. }
  1725. void cmSystemTools::EnvDiff::UnPutEnv(const std::string& env)
  1726. {
  1727. diff[env] = cm::nullopt;
  1728. }
  1729. bool cmSystemTools::EnvDiff::ParseOperation(const std::string& envmod)
  1730. {
  1731. char path_sep = GetSystemPathlistSeparator();
  1732. auto apply_diff = [this](const std::string& name,
  1733. std::function<void(std::string&)> const& apply) {
  1734. cm::optional<std::string> old_value = diff[name];
  1735. std::string output;
  1736. if (old_value) {
  1737. output = *old_value;
  1738. } else {
  1739. const char* curval = cmSystemTools::GetEnv(name);
  1740. if (curval) {
  1741. output = curval;
  1742. }
  1743. }
  1744. apply(output);
  1745. diff[name] = output;
  1746. };
  1747. // Split on `=`
  1748. auto const eq_loc = envmod.find_first_of('=');
  1749. if (eq_loc == std::string::npos) {
  1750. cmSystemTools::Error(cmStrCat(
  1751. "Error: Missing `=` after the variable name in: ", envmod, '\n'));
  1752. return false;
  1753. }
  1754. auto const name = envmod.substr(0, eq_loc);
  1755. // Split value on `:`
  1756. auto const op_value_start = eq_loc + 1;
  1757. auto const colon_loc = envmod.find_first_of(':', op_value_start);
  1758. if (colon_loc == std::string::npos) {
  1759. cmSystemTools::Error(
  1760. cmStrCat("Error: Missing `:` after the operation in: ", envmod, '\n'));
  1761. return false;
  1762. }
  1763. auto const op = envmod.substr(op_value_start, colon_loc - op_value_start);
  1764. auto const value_start = colon_loc + 1;
  1765. auto const value = envmod.substr(value_start);
  1766. // Determine what to do with the operation.
  1767. if (op == "reset"_s) {
  1768. auto entry = diff.find(name);
  1769. if (entry != diff.end()) {
  1770. diff.erase(entry);
  1771. }
  1772. } else if (op == "set"_s) {
  1773. diff[name] = value;
  1774. } else if (op == "unset"_s) {
  1775. diff[name] = cm::nullopt;
  1776. } else if (op == "string_append"_s) {
  1777. apply_diff(name, [&value](std::string& output) { output += value; });
  1778. } else if (op == "string_prepend"_s) {
  1779. apply_diff(name,
  1780. [&value](std::string& output) { output.insert(0, value); });
  1781. } else if (op == "path_list_append"_s) {
  1782. apply_diff(name, [&value, path_sep](std::string& output) {
  1783. if (!output.empty()) {
  1784. output += path_sep;
  1785. }
  1786. output += value;
  1787. });
  1788. } else if (op == "path_list_prepend"_s) {
  1789. apply_diff(name, [&value, path_sep](std::string& output) {
  1790. if (!output.empty()) {
  1791. output.insert(output.begin(), path_sep);
  1792. }
  1793. output.insert(0, value);
  1794. });
  1795. } else if (op == "cmake_list_append"_s) {
  1796. apply_diff(name, [&value](std::string& output) {
  1797. if (!output.empty()) {
  1798. output += ';';
  1799. }
  1800. output += value;
  1801. });
  1802. } else if (op == "cmake_list_prepend"_s) {
  1803. apply_diff(name, [&value](std::string& output) {
  1804. if (!output.empty()) {
  1805. output.insert(output.begin(), ';');
  1806. }
  1807. output.insert(0, value);
  1808. });
  1809. } else {
  1810. cmSystemTools::Error(cmStrCat(
  1811. "Error: Unrecognized environment manipulation argument: ", op, '\n'));
  1812. return false;
  1813. }
  1814. return true;
  1815. }
  1816. void cmSystemTools::EnvDiff::ApplyToCurrentEnv(std::ostringstream* measurement)
  1817. {
  1818. for (auto const& env_apply : diff) {
  1819. if (env_apply.second) {
  1820. auto const env_update =
  1821. cmStrCat(env_apply.first, '=', *env_apply.second);
  1822. cmSystemTools::PutEnv(env_update);
  1823. if (measurement) {
  1824. *measurement << env_update << std::endl;
  1825. }
  1826. } else {
  1827. cmSystemTools::UnsetEnv(env_apply.first.c_str());
  1828. if (measurement) {
  1829. // Signify that this variable is being actively unset
  1830. *measurement << '#' << env_apply.first << "=\n";
  1831. }
  1832. }
  1833. }
  1834. }
  1835. cmSystemTools::SaveRestoreEnvironment::SaveRestoreEnvironment()
  1836. {
  1837. this->Env = cmSystemTools::GetEnvironmentVariables();
  1838. }
  1839. cmSystemTools::SaveRestoreEnvironment::~SaveRestoreEnvironment()
  1840. {
  1841. // First clear everything in the current environment:
  1842. std::vector<std::string> currentEnv = GetEnvironmentVariables();
  1843. for (std::string var : currentEnv) {
  1844. std::string::size_type pos = var.find('=');
  1845. if (pos != std::string::npos) {
  1846. var = var.substr(0, pos);
  1847. }
  1848. cmSystemTools::UnsetEnv(var.c_str());
  1849. }
  1850. // Then put back each entry from the original environment:
  1851. cmSystemTools::AppendEnv(this->Env);
  1852. }
  1853. #endif
  1854. void cmSystemTools::EnableVSConsoleOutput()
  1855. {
  1856. #ifdef _WIN32
  1857. // Visual Studio tools like devenv may not
  1858. // display output to the console unless this environment variable is
  1859. // set. We need it to capture the output of these build tools.
  1860. // Note for future work that one could pass "/out \\.\pipe\NAME" to
  1861. // either of these executables where NAME is created with
  1862. // CreateNamedPipe. This would bypass the internal buffering of the
  1863. // output and allow it to be captured on the fly.
  1864. cmSystemTools::PutEnv("vsconsoleoutput=1");
  1865. # ifndef CMAKE_BOOTSTRAP
  1866. // VS sets an environment variable to tell MS tools like "cl" to report
  1867. // output through a backdoor pipe instead of stdout/stderr. Unset the
  1868. // environment variable to close this backdoor for any path of process
  1869. // invocations that passes through CMake so we can capture the output.
  1870. cmSystemTools::UnsetEnv("VS_UNICODE_OUTPUT");
  1871. # endif
  1872. #endif
  1873. }
  1874. bool cmSystemTools::IsPathToFramework(const std::string& path)
  1875. {
  1876. return (cmSystemTools::FileIsFullPath(path) &&
  1877. cmHasLiteralSuffix(path, ".framework"));
  1878. }
  1879. bool cmSystemTools::IsPathToXcFramework(const std::string& path)
  1880. {
  1881. return (cmSystemTools::FileIsFullPath(path) &&
  1882. cmHasLiteralSuffix(path, ".xcframework"));
  1883. }
  1884. bool cmSystemTools::IsPathToMacOSSharedLibrary(const std::string& path)
  1885. {
  1886. return (cmSystemTools::FileIsFullPath(path) &&
  1887. cmHasLiteralSuffix(path, ".dylib"));
  1888. }
  1889. bool cmSystemTools::CreateTar(const std::string& outFileName,
  1890. const std::vector<std::string>& files,
  1891. const std::string& workingDirectory,
  1892. cmTarCompression compressType, bool verbose,
  1893. std::string const& mtime,
  1894. std::string const& format, int compressionLevel)
  1895. {
  1896. #if !defined(CMAKE_BOOTSTRAP)
  1897. cmWorkingDirectory workdir(cmSystemTools::GetLogicalWorkingDirectory());
  1898. if (!workingDirectory.empty()) {
  1899. workdir.SetDirectory(workingDirectory);
  1900. }
  1901. const std::string cwd = cmSystemTools::GetLogicalWorkingDirectory();
  1902. cmsys::ofstream fout(outFileName.c_str(), std::ios::out | std::ios::binary);
  1903. if (!fout) {
  1904. std::string e = cmStrCat("Cannot open output file \"", outFileName,
  1905. "\": ", cmSystemTools::GetLastSystemError());
  1906. cmSystemTools::Error(e);
  1907. return false;
  1908. }
  1909. cmArchiveWrite::Compress compress = cmArchiveWrite::CompressNone;
  1910. switch (compressType) {
  1911. case TarCompressGZip:
  1912. compress = cmArchiveWrite::CompressGZip;
  1913. break;
  1914. case TarCompressBZip2:
  1915. compress = cmArchiveWrite::CompressBZip2;
  1916. break;
  1917. case TarCompressXZ:
  1918. compress = cmArchiveWrite::CompressXZ;
  1919. break;
  1920. case TarCompressZstd:
  1921. compress = cmArchiveWrite::CompressZstd;
  1922. break;
  1923. case TarCompressNone:
  1924. compress = cmArchiveWrite::CompressNone;
  1925. break;
  1926. }
  1927. cmArchiveWrite a(fout, compress, format.empty() ? "paxr" : format,
  1928. compressionLevel);
  1929. if (!a.Open()) {
  1930. cmSystemTools::Error(a.GetError());
  1931. return false;
  1932. }
  1933. a.SetMTime(mtime);
  1934. a.SetVerbose(verbose);
  1935. bool tarCreatedSuccessfully = true;
  1936. for (auto path : files) {
  1937. if (cmSystemTools::FileIsFullPath(path)) {
  1938. // Get the relative path to the file.
  1939. path = cmSystemTools::RelativePath(cwd, path);
  1940. }
  1941. if (!a.Add(path)) {
  1942. cmSystemTools::Error(a.GetError());
  1943. tarCreatedSuccessfully = false;
  1944. }
  1945. }
  1946. return tarCreatedSuccessfully;
  1947. #else
  1948. (void)outFileName;
  1949. (void)files;
  1950. (void)verbose;
  1951. return false;
  1952. #endif
  1953. }
  1954. #if !defined(CMAKE_BOOTSTRAP)
  1955. namespace {
  1956. # define BSDTAR_FILESIZE_PRINTF "%lu"
  1957. # define BSDTAR_FILESIZE_TYPE unsigned long
  1958. void list_item_verbose(FILE* out, struct archive_entry* entry)
  1959. {
  1960. char tmp[100];
  1961. size_t w;
  1962. const char* p;
  1963. const char* fmt;
  1964. time_t tim;
  1965. static time_t now;
  1966. size_t u_width = 6;
  1967. size_t gs_width = 13;
  1968. /*
  1969. * We avoid collecting the entire list in memory at once by
  1970. * listing things as we see them. However, that also means we can't
  1971. * just pre-compute the field widths. Instead, we start with guesses
  1972. * and just widen them as necessary. These numbers are completely
  1973. * arbitrary.
  1974. */
  1975. if (!now) {
  1976. time(&now);
  1977. }
  1978. fprintf(out, "%s %d ", archive_entry_strmode(entry),
  1979. archive_entry_nlink(entry));
  1980. /* Use uname if it's present, else uid. */
  1981. p = archive_entry_uname(entry);
  1982. if (!p || (*p == '\0')) {
  1983. snprintf(tmp, sizeof(tmp), "%lu ",
  1984. static_cast<unsigned long>(archive_entry_uid(entry)));
  1985. p = tmp;
  1986. }
  1987. w = strlen(p);
  1988. if (w > u_width) {
  1989. u_width = w;
  1990. }
  1991. fprintf(out, "%-*s ", static_cast<int>(u_width), p);
  1992. /* Use gname if it's present, else gid. */
  1993. p = archive_entry_gname(entry);
  1994. if (p && p[0] != '\0') {
  1995. fprintf(out, "%s", p);
  1996. w = strlen(p);
  1997. } else {
  1998. snprintf(tmp, sizeof(tmp), "%lu",
  1999. static_cast<unsigned long>(archive_entry_gid(entry)));
  2000. w = strlen(tmp);
  2001. fprintf(out, "%s", tmp);
  2002. }
  2003. /*
  2004. * Print device number or file size, right-aligned so as to make
  2005. * total width of group and devnum/filesize fields be gs_width.
  2006. * If gs_width is too small, grow it.
  2007. */
  2008. if (archive_entry_filetype(entry) == AE_IFCHR ||
  2009. archive_entry_filetype(entry) == AE_IFBLK) {
  2010. unsigned long rdevmajor = archive_entry_rdevmajor(entry);
  2011. unsigned long rdevminor = archive_entry_rdevminor(entry);
  2012. snprintf(tmp, sizeof(tmp), "%lu,%lu", rdevmajor, rdevminor);
  2013. } else {
  2014. /*
  2015. * Note the use of platform-dependent macros to format
  2016. * the filesize here. We need the format string and the
  2017. * corresponding type for the cast.
  2018. */
  2019. snprintf(tmp, sizeof(tmp), BSDTAR_FILESIZE_PRINTF,
  2020. static_cast<BSDTAR_FILESIZE_TYPE>(archive_entry_size(entry)));
  2021. }
  2022. if (w + strlen(tmp) >= gs_width) {
  2023. gs_width = w + strlen(tmp) + 1;
  2024. }
  2025. fprintf(out, "%*s", static_cast<int>(gs_width - w), tmp);
  2026. /* Format the time using 'ls -l' conventions. */
  2027. tim = archive_entry_mtime(entry);
  2028. # define HALF_YEAR ((time_t)365 * 86400 / 2)
  2029. # if defined(_WIN32) && !defined(__CYGWIN__)
  2030. /* Windows' strftime function does not support %e format. */
  2031. # define DAY_FMT "%d"
  2032. # else
  2033. # define DAY_FMT "%e" /* Day number without leading zeros */
  2034. # endif
  2035. if (tim < now - HALF_YEAR || tim > now + HALF_YEAR) {
  2036. fmt = DAY_FMT " %b %Y";
  2037. } else {
  2038. fmt = DAY_FMT " %b %H:%M";
  2039. }
  2040. strftime(tmp, sizeof(tmp), fmt, localtime(&tim));
  2041. fprintf(out, " %s ", tmp);
  2042. fprintf(out, "%s", cm_archive_entry_pathname(entry).c_str());
  2043. /* Extra information for links. */
  2044. if (archive_entry_hardlink(entry)) /* Hard link */
  2045. {
  2046. fprintf(out, " link to %s", archive_entry_hardlink(entry));
  2047. } else if (archive_entry_symlink(entry)) /* Symbolic link */
  2048. {
  2049. fprintf(out, " -> %s", archive_entry_symlink(entry));
  2050. }
  2051. fflush(out);
  2052. }
  2053. void ArchiveError(const char* m1, struct archive* a)
  2054. {
  2055. std::string message(m1);
  2056. const char* m2 = archive_error_string(a);
  2057. if (m2) {
  2058. message += m2;
  2059. }
  2060. cmSystemTools::Error(message);
  2061. }
  2062. bool la_diagnostic(struct archive* ar, __LA_SSIZE_T r)
  2063. {
  2064. // See archive.h definition of ARCHIVE_OK for return values.
  2065. if (r >= ARCHIVE_OK) {
  2066. return true;
  2067. }
  2068. if (r >= ARCHIVE_WARN) {
  2069. const char* warn = archive_error_string(ar);
  2070. if (!warn) {
  2071. warn = "unknown warning";
  2072. }
  2073. std::cerr << "cmake -E tar: warning: " << warn << '\n';
  2074. return true;
  2075. }
  2076. // Error.
  2077. const char* err = archive_error_string(ar);
  2078. if (!err) {
  2079. err = "unknown error";
  2080. }
  2081. std::cerr << "cmake -E tar: error: " << err << '\n';
  2082. return false;
  2083. }
  2084. // Return 'true' on success
  2085. bool copy_data(struct archive* ar, struct archive* aw)
  2086. {
  2087. long r;
  2088. const void* buff;
  2089. size_t size;
  2090. # if defined(ARCHIVE_VERSION_NUMBER) && ARCHIVE_VERSION_NUMBER >= 3000000
  2091. __LA_INT64_T offset;
  2092. # else
  2093. off_t offset;
  2094. # endif
  2095. for (;;) {
  2096. // See archive.h definition of ARCHIVE_OK for return values.
  2097. r = archive_read_data_block(ar, &buff, &size, &offset);
  2098. if (r == ARCHIVE_EOF) {
  2099. return true;
  2100. }
  2101. if (!la_diagnostic(ar, r)) {
  2102. return false;
  2103. }
  2104. // See archive.h definition of ARCHIVE_OK for return values.
  2105. __LA_SSIZE_T const w = archive_write_data_block(aw, buff, size, offset);
  2106. if (!la_diagnostic(ar, w)) {
  2107. return false;
  2108. }
  2109. }
  2110. # if !defined(__clang__) && !defined(__NVCOMPILER) && !defined(__HP_aCC)
  2111. return false; /* this should not happen but it quiets some compilers */
  2112. # endif
  2113. }
  2114. bool extract_tar(const std::string& outFileName,
  2115. const std::vector<std::string>& files, bool verbose,
  2116. cmSystemTools::cmTarExtractTimestamps extractTimestamps,
  2117. bool extract)
  2118. {
  2119. cmLocaleRAII localeRAII;
  2120. static_cast<void>(localeRAII);
  2121. struct archive* a = archive_read_new();
  2122. struct archive* ext = archive_write_disk_new();
  2123. archive_read_support_filter_all(a);
  2124. archive_read_support_format_all(a);
  2125. struct archive_entry* entry;
  2126. struct archive* matching = archive_match_new();
  2127. if (!matching) {
  2128. cmSystemTools::Error("Out of memory");
  2129. return false;
  2130. }
  2131. for (const auto& filename : files) {
  2132. if (archive_match_include_pattern(matching, filename.c_str()) !=
  2133. ARCHIVE_OK) {
  2134. cmSystemTools::Error("Failed to add to inclusion list: " + filename);
  2135. return false;
  2136. }
  2137. }
  2138. int r = cm_archive_read_open_file(a, outFileName.c_str(), 10240);
  2139. if (r) {
  2140. ArchiveError("Problem with archive_read_open_file(): ", a);
  2141. archive_write_free(ext);
  2142. archive_read_close(a);
  2143. return false;
  2144. }
  2145. for (;;) {
  2146. r = archive_read_next_header(a, &entry);
  2147. if (r == ARCHIVE_EOF) {
  2148. break;
  2149. }
  2150. if (r != ARCHIVE_OK) {
  2151. ArchiveError("Problem with archive_read_next_header(): ", a);
  2152. break;
  2153. }
  2154. if (archive_match_excluded(matching, entry)) {
  2155. continue;
  2156. }
  2157. if (verbose) {
  2158. if (extract) {
  2159. cmSystemTools::Stdout(
  2160. cmStrCat("x ", cm_archive_entry_pathname(entry)));
  2161. } else {
  2162. list_item_verbose(stdout, entry);
  2163. }
  2164. cmSystemTools::Stdout("\n");
  2165. } else if (!extract) {
  2166. cmSystemTools::Stdout(cmStrCat(cm_archive_entry_pathname(entry), '\n'));
  2167. }
  2168. if (extract) {
  2169. if (extractTimestamps == cmSystemTools::cmTarExtractTimestamps::Yes) {
  2170. r = archive_write_disk_set_options(ext, ARCHIVE_EXTRACT_TIME);
  2171. if (r != ARCHIVE_OK) {
  2172. ArchiveError("Problem with archive_write_disk_set_options(): ", ext);
  2173. break;
  2174. }
  2175. }
  2176. r = archive_write_header(ext, entry);
  2177. if (r == ARCHIVE_OK) {
  2178. if (!copy_data(a, ext)) {
  2179. break;
  2180. }
  2181. r = archive_write_finish_entry(ext);
  2182. if (r != ARCHIVE_OK) {
  2183. ArchiveError("Problem with archive_write_finish_entry(): ", ext);
  2184. break;
  2185. }
  2186. }
  2187. # ifdef _WIN32
  2188. else if (const char* linktext = archive_entry_symlink(entry)) {
  2189. std::cerr << "cmake -E tar: warning: skipping symbolic link \""
  2190. << cm_archive_entry_pathname(entry) << "\" -> \"" << linktext
  2191. << "\"." << std::endl;
  2192. }
  2193. # endif
  2194. else {
  2195. ArchiveError("Problem with archive_write_header(): ", ext);
  2196. cmSystemTools::Error("Current file: " +
  2197. cm_archive_entry_pathname(entry));
  2198. break;
  2199. }
  2200. }
  2201. }
  2202. bool error_occured = false;
  2203. if (matching) {
  2204. const char* p;
  2205. int ar;
  2206. while ((ar = archive_match_path_unmatched_inclusions_next(matching, &p)) ==
  2207. ARCHIVE_OK) {
  2208. cmSystemTools::Error("tar: " + std::string(p) +
  2209. ": Not found in archive");
  2210. error_occured = true;
  2211. }
  2212. if (error_occured) {
  2213. return false;
  2214. }
  2215. if (ar == ARCHIVE_FATAL) {
  2216. cmSystemTools::Error("tar: Out of memory");
  2217. return false;
  2218. }
  2219. }
  2220. archive_match_free(matching);
  2221. archive_write_free(ext);
  2222. archive_read_close(a);
  2223. archive_read_free(a);
  2224. return r == ARCHIVE_EOF || r == ARCHIVE_OK;
  2225. }
  2226. }
  2227. #endif
  2228. bool cmSystemTools::ExtractTar(const std::string& outFileName,
  2229. const std::vector<std::string>& files,
  2230. cmTarExtractTimestamps extractTimestamps,
  2231. bool verbose)
  2232. {
  2233. #if !defined(CMAKE_BOOTSTRAP)
  2234. return extract_tar(outFileName, files, verbose, extractTimestamps, true);
  2235. #else
  2236. (void)outFileName;
  2237. (void)files;
  2238. (void)extractTimestamps;
  2239. (void)verbose;
  2240. return false;
  2241. #endif
  2242. }
  2243. bool cmSystemTools::ListTar(const std::string& outFileName,
  2244. const std::vector<std::string>& files,
  2245. bool verbose)
  2246. {
  2247. #if !defined(CMAKE_BOOTSTRAP)
  2248. return extract_tar(outFileName, files, verbose, cmTarExtractTimestamps::Yes,
  2249. false);
  2250. #else
  2251. (void)outFileName;
  2252. (void)files;
  2253. (void)verbose;
  2254. return false;
  2255. #endif
  2256. }
  2257. cmSystemTools::WaitForLineResult cmSystemTools::WaitForLine(
  2258. uv_loop_t* loop, uv_stream_t* outPipe, uv_stream_t* errPipe,
  2259. std::string& line, cmDuration timeout, std::vector<char>& out,
  2260. std::vector<char>& err)
  2261. {
  2262. line.clear();
  2263. auto outiter = out.begin();
  2264. auto erriter = err.begin();
  2265. cmProcessOutput processOutput;
  2266. std::string strdata;
  2267. while (true) {
  2268. // Check for a newline in stdout.
  2269. for (; outiter != out.end(); ++outiter) {
  2270. if ((*outiter == '\r') && ((outiter + 1) == out.end())) {
  2271. break;
  2272. }
  2273. if (*outiter == '\n' || *outiter == '\0') {
  2274. std::vector<char>::size_type length = outiter - out.begin();
  2275. if (length > 1 && *(outiter - 1) == '\r') {
  2276. --length;
  2277. }
  2278. if (length > 0) {
  2279. line.append(out.data(), length);
  2280. }
  2281. out.erase(out.begin(), outiter + 1);
  2282. return WaitForLineResult::STDOUT;
  2283. }
  2284. }
  2285. // Check for a newline in stderr.
  2286. for (; erriter != err.end(); ++erriter) {
  2287. if ((*erriter == '\r') && ((erriter + 1) == err.end())) {
  2288. break;
  2289. }
  2290. if (*erriter == '\n' || *erriter == '\0') {
  2291. std::vector<char>::size_type length = erriter - err.begin();
  2292. if (length > 1 && *(erriter - 1) == '\r') {
  2293. --length;
  2294. }
  2295. if (length > 0) {
  2296. line.append(err.data(), length);
  2297. }
  2298. err.erase(err.begin(), erriter + 1);
  2299. return WaitForLineResult::STDERR;
  2300. }
  2301. }
  2302. // No newlines found. Wait for more data from the process.
  2303. struct ReadData
  2304. {
  2305. uv_stream_t* Stream;
  2306. std::vector<char> Buffer;
  2307. bool Read = false;
  2308. bool Finished = false;
  2309. };
  2310. auto startRead =
  2311. [](uv_stream_t* stream,
  2312. ReadData& data) -> std::unique_ptr<cmUVStreamReadHandle> {
  2313. data.Stream = stream;
  2314. return cmUVStreamRead(
  2315. stream,
  2316. [&data](std::vector<char> buf) {
  2317. data.Buffer = std::move(buf);
  2318. data.Read = true;
  2319. uv_read_stop(data.Stream);
  2320. },
  2321. [&data]() { data.Finished = true; });
  2322. };
  2323. ReadData outData;
  2324. auto outHandle = startRead(outPipe, outData);
  2325. ReadData errData;
  2326. auto errHandle = startRead(errPipe, errData);
  2327. cm::uv_timer_ptr timer;
  2328. bool timedOut = false;
  2329. timer.init(*loop, &timedOut);
  2330. timer.start(
  2331. [](uv_timer_t* handle) {
  2332. auto* timedOutPtr = static_cast<bool*>(handle->data);
  2333. *timedOutPtr = true;
  2334. },
  2335. static_cast<uint64_t>(timeout.count() * 1000.0), 0);
  2336. uv_run(loop, UV_RUN_ONCE);
  2337. if (timedOut) {
  2338. // Timeout has been exceeded.
  2339. return WaitForLineResult::Timeout;
  2340. }
  2341. if (outData.Read) {
  2342. processOutput.DecodeText(outData.Buffer.data(), outData.Buffer.size(),
  2343. strdata, 1);
  2344. // Append to the stdout buffer.
  2345. std::vector<char>::size_type size = out.size();
  2346. cm::append(out, strdata);
  2347. outiter = out.begin() + size;
  2348. } else if (errData.Read) {
  2349. processOutput.DecodeText(errData.Buffer.data(), errData.Buffer.size(),
  2350. strdata, 2);
  2351. // Append to the stderr buffer.
  2352. std::vector<char>::size_type size = err.size();
  2353. cm::append(err, strdata);
  2354. erriter = err.begin() + size;
  2355. } else if (outData.Finished && errData.Finished) {
  2356. // Both stdout and stderr pipes have broken. Return leftover data.
  2357. processOutput.DecodeText(std::string(), strdata, 1);
  2358. if (!strdata.empty()) {
  2359. std::vector<char>::size_type size = out.size();
  2360. cm::append(out, strdata);
  2361. outiter = out.begin() + size;
  2362. }
  2363. processOutput.DecodeText(std::string(), strdata, 2);
  2364. if (!strdata.empty()) {
  2365. std::vector<char>::size_type size = err.size();
  2366. cm::append(err, strdata);
  2367. erriter = err.begin() + size;
  2368. }
  2369. if (!out.empty()) {
  2370. line.append(out.data(), outiter - out.begin());
  2371. out.erase(out.begin(), out.end());
  2372. return WaitForLineResult::STDOUT;
  2373. }
  2374. if (!err.empty()) {
  2375. line.append(err.data(), erriter - err.begin());
  2376. err.erase(err.begin(), err.end());
  2377. return WaitForLineResult::STDERR;
  2378. }
  2379. return WaitForLineResult::None;
  2380. }
  2381. if (!outData.Finished) {
  2382. uv_read_stop(outPipe);
  2383. }
  2384. if (!errData.Finished) {
  2385. uv_read_stop(errPipe);
  2386. }
  2387. }
  2388. }
  2389. #ifdef _WIN32
  2390. static void EnsureStdPipe(int stdFd, DWORD nStdHandle, FILE* stream,
  2391. const wchar_t* mode)
  2392. {
  2393. if (fileno(stream) >= 0) {
  2394. return;
  2395. }
  2396. _close(stdFd);
  2397. _wfreopen(L"NUL", mode, stream);
  2398. int fd = fileno(stream);
  2399. if (fd < 0) {
  2400. perror("failed to open NUL for missing stdio pipe");
  2401. abort();
  2402. }
  2403. if (fd != stdFd) {
  2404. _dup2(fd, stdFd);
  2405. }
  2406. SetStdHandle(nStdHandle, reinterpret_cast<HANDLE>(_get_osfhandle(fd)));
  2407. }
  2408. void cmSystemTools::EnsureStdPipes()
  2409. {
  2410. EnsureStdPipe(0, STD_INPUT_HANDLE, stdin, L"rb");
  2411. EnsureStdPipe(1, STD_OUTPUT_HANDLE, stdout, L"wb");
  2412. EnsureStdPipe(2, STD_ERROR_HANDLE, stderr, L"wb");
  2413. }
  2414. #else
  2415. static void EnsureStdPipe(int fd)
  2416. {
  2417. if (fcntl(fd, F_GETFD) != -1 || errno != EBADF) {
  2418. return;
  2419. }
  2420. int f = open("/dev/null", fd == STDIN_FILENO ? O_RDONLY : O_WRONLY);
  2421. if (f == -1) {
  2422. perror("failed to open /dev/null for missing stdio pipe");
  2423. abort();
  2424. }
  2425. if (f != fd) {
  2426. dup2(f, fd);
  2427. close(f);
  2428. }
  2429. }
  2430. void cmSystemTools::EnsureStdPipes()
  2431. {
  2432. EnsureStdPipe(STDIN_FILENO);
  2433. EnsureStdPipe(STDOUT_FILENO);
  2434. EnsureStdPipe(STDERR_FILENO);
  2435. }
  2436. #endif
  2437. #ifdef _WIN32
  2438. # ifndef CRYPT_SILENT
  2439. # define CRYPT_SILENT 0x40 /* Not defined by VS 6 version of header. */
  2440. # endif
  2441. static int WinCryptRandom(void* data, size_t size)
  2442. {
  2443. int result = 0;
  2444. HCRYPTPROV hProvider = 0;
  2445. if (CryptAcquireContextW(&hProvider, 0, 0, PROV_RSA_FULL,
  2446. CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {
  2447. result = CryptGenRandom(hProvider, (DWORD)size, (BYTE*)data) ? 1 : 0;
  2448. CryptReleaseContext(hProvider, 0);
  2449. }
  2450. return result;
  2451. }
  2452. #endif
  2453. unsigned int cmSystemTools::RandomSeed()
  2454. {
  2455. #if defined(_WIN32) && !defined(__CYGWIN__)
  2456. unsigned int seed = 0;
  2457. // Try using a real random source.
  2458. if (WinCryptRandom(&seed, sizeof(seed))) {
  2459. return seed;
  2460. }
  2461. // Fall back to the time and pid.
  2462. FILETIME ft;
  2463. GetSystemTimeAsFileTime(&ft);
  2464. unsigned int t1 = static_cast<unsigned int>(ft.dwHighDateTime);
  2465. unsigned int t2 = static_cast<unsigned int>(ft.dwLowDateTime);
  2466. unsigned int pid = static_cast<unsigned int>(GetCurrentProcessId());
  2467. return t1 ^ t2 ^ pid;
  2468. #else
  2469. union
  2470. {
  2471. unsigned int integer;
  2472. char bytes[sizeof(unsigned int)];
  2473. } seed;
  2474. // Try using a real random source.
  2475. cmsys::ifstream fin;
  2476. fin.rdbuf()->pubsetbuf(nullptr, 0); // Unbuffered read.
  2477. fin.open("/dev/urandom");
  2478. if (fin.good() && fin.read(seed.bytes, sizeof(seed)) &&
  2479. fin.gcount() == sizeof(seed)) {
  2480. return seed.integer;
  2481. }
  2482. // Fall back to the time and pid.
  2483. struct timeval t;
  2484. gettimeofday(&t, nullptr);
  2485. unsigned int pid = static_cast<unsigned int>(getpid());
  2486. unsigned int tv_sec = static_cast<unsigned int>(t.tv_sec);
  2487. unsigned int tv_usec = static_cast<unsigned int>(t.tv_usec);
  2488. // Since tv_usec never fills more than 11 bits we shift it to fill
  2489. // in the slow-changing high-order bits of tv_sec.
  2490. return tv_sec ^ (tv_usec << 21) ^ pid;
  2491. #endif
  2492. }
  2493. namespace {
  2494. std::string InitLogicalWorkingDirectory()
  2495. {
  2496. std::string cwd = cmsys::SystemTools::GetCurrentWorkingDirectory();
  2497. std::string pwd;
  2498. if (cmSystemTools::GetEnv("PWD", pwd)) {
  2499. std::string const pwd_real = cmSystemTools::GetRealPath(pwd);
  2500. if (pwd_real == cwd) {
  2501. cwd = std::move(pwd);
  2502. }
  2503. }
  2504. return cwd;
  2505. }
  2506. std::string cmSystemToolsLogicalWorkingDirectory =
  2507. InitLogicalWorkingDirectory();
  2508. std::string cmSystemToolsCMakeCommand;
  2509. std::string cmSystemToolsCTestCommand;
  2510. std::string cmSystemToolsCPackCommand;
  2511. std::string cmSystemToolsCMakeCursesCommand;
  2512. std::string cmSystemToolsCMakeGUICommand;
  2513. std::string cmSystemToolsCMClDepsCommand;
  2514. std::string cmSystemToolsCMakeRoot;
  2515. std::string cmSystemToolsHTMLDoc;
  2516. #if defined(__APPLE__)
  2517. bool IsCMakeAppBundleExe(std::string const& exe)
  2518. {
  2519. return cmHasLiteralSuffix(cmSystemTools::LowerCase(exe), "/macos/cmake");
  2520. }
  2521. #endif
  2522. std::string FindOwnExecutable(const char* argv0)
  2523. {
  2524. #if defined(_WIN32) && !defined(__CYGWIN__)
  2525. static_cast<void>(argv0);
  2526. wchar_t modulepath[_MAX_PATH];
  2527. ::GetModuleFileNameW(nullptr, modulepath, sizeof(modulepath));
  2528. std::string exe = cmsys::Encoding::ToNarrow(modulepath);
  2529. #elif defined(__APPLE__)
  2530. static_cast<void>(argv0);
  2531. # define CM_EXE_PATH_LOCAL_SIZE 16384
  2532. char exe_path_local[CM_EXE_PATH_LOCAL_SIZE];
  2533. # if defined(MAC_OS_X_VERSION_10_3) && !defined(MAC_OS_X_VERSION_10_4)
  2534. unsigned long exe_path_size = CM_EXE_PATH_LOCAL_SIZE;
  2535. # else
  2536. uint32_t exe_path_size = CM_EXE_PATH_LOCAL_SIZE;
  2537. # endif
  2538. # undef CM_EXE_PATH_LOCAL_SIZE
  2539. char* exe_path = exe_path_local;
  2540. if (_NSGetExecutablePath(exe_path, &exe_path_size) < 0) {
  2541. exe_path = static_cast<char*>(malloc(exe_path_size));
  2542. _NSGetExecutablePath(exe_path, &exe_path_size);
  2543. }
  2544. std::string exe = exe_path;
  2545. if (exe_path != exe_path_local) {
  2546. free(exe_path);
  2547. }
  2548. if (IsCMakeAppBundleExe(exe)) {
  2549. // The executable is inside an application bundle.
  2550. // The install tree has "..<CMAKE_BIN_DIR>/cmake-gui".
  2551. // The build tree has '../../../cmake-gui".
  2552. std::string dir = cmSystemTools::GetFilenamePath(exe);
  2553. dir = cmSystemTools::GetFilenamePath(dir);
  2554. exe = cmStrCat(dir, CMAKE_BIN_DIR "/cmake-gui");
  2555. if (!cmSystemTools::PathExists(exe)) {
  2556. dir = cmSystemTools::GetFilenamePath(dir);
  2557. dir = cmSystemTools::GetFilenamePath(dir);
  2558. exe = cmStrCat(dir, "/cmake-gui");
  2559. }
  2560. }
  2561. #else
  2562. std::string errorMsg;
  2563. std::string exe;
  2564. if (!cmSystemTools::FindProgramPath(argv0, exe, errorMsg)) {
  2565. // ???
  2566. }
  2567. #endif
  2568. exe = cmSystemTools::ToNormalizedPathOnDisk(std::move(exe));
  2569. return exe;
  2570. }
  2571. #ifndef CMAKE_BOOTSTRAP
  2572. bool ResolveSymlinkToOwnExecutable(std::string& exe, std::string& exe_dir)
  2573. {
  2574. std::string linked_exe;
  2575. if (!cmSystemTools::ReadSymlink(exe, linked_exe)) {
  2576. return false;
  2577. }
  2578. # if defined(__APPLE__)
  2579. // Ignore "cmake-gui -> ../MacOS/CMake".
  2580. if (IsCMakeAppBundleExe(linked_exe)) {
  2581. return false;
  2582. }
  2583. # endif
  2584. if (cmSystemTools::FileIsFullPath(linked_exe)) {
  2585. exe = std::move(linked_exe);
  2586. } else {
  2587. exe = cmStrCat(exe_dir, '/', std::move(linked_exe));
  2588. }
  2589. exe = cmSystemTools::ToNormalizedPathOnDisk(std::move(exe));
  2590. exe_dir = cmSystemTools::GetFilenamePath(exe);
  2591. return true;
  2592. }
  2593. bool FindCMakeResourcesInInstallTree(std::string const& exe_dir)
  2594. {
  2595. // Install tree has
  2596. // - "<prefix><CMAKE_BIN_DIR>/cmake"
  2597. // - "<prefix><CMAKE_DATA_DIR>"
  2598. // - "<prefix><CMAKE_DOC_DIR>"
  2599. if (cmHasLiteralSuffix(exe_dir, CMAKE_BIN_DIR)) {
  2600. std::string const prefix =
  2601. exe_dir.substr(0, exe_dir.size() - cmStrLen(CMAKE_BIN_DIR));
  2602. // Set cmSystemToolsCMakeRoot set to the location expected in an
  2603. // install tree, even if it does not exist, so that
  2604. // cmake::AddCMakePaths can print the location in its error message.
  2605. cmSystemToolsCMakeRoot = cmStrCat(prefix, CMAKE_DATA_DIR);
  2606. if (cmSystemTools::FileExists(
  2607. cmStrCat(cmSystemToolsCMakeRoot, "/Modules/CMake.cmake"))) {
  2608. if (cmSystemTools::FileExists(
  2609. cmStrCat(prefix, CMAKE_DOC_DIR "/html/index.html"))) {
  2610. cmSystemToolsHTMLDoc = cmStrCat(prefix, CMAKE_DOC_DIR "/html");
  2611. }
  2612. return true;
  2613. }
  2614. }
  2615. return false;
  2616. }
  2617. void FindCMakeResourcesInBuildTree(std::string const& exe_dir)
  2618. {
  2619. // Build tree has "<build>/bin[/<config>]/cmake" and
  2620. // "<build>/CMakeFiles/CMakeSourceDir.txt".
  2621. std::string dir = cmSystemTools::GetFilenamePath(exe_dir);
  2622. std::string src_dir_txt = cmStrCat(dir, "/CMakeFiles/CMakeSourceDir.txt");
  2623. cmsys::ifstream fin(src_dir_txt.c_str());
  2624. std::string src_dir;
  2625. if (fin && cmSystemTools::GetLineFromStream(fin, src_dir) &&
  2626. cmSystemTools::FileIsDirectory(src_dir)) {
  2627. cmSystemToolsCMakeRoot = src_dir;
  2628. } else {
  2629. dir = cmSystemTools::GetFilenamePath(dir);
  2630. src_dir_txt = cmStrCat(dir, "/CMakeFiles/CMakeSourceDir.txt");
  2631. cmsys::ifstream fin2(src_dir_txt.c_str());
  2632. if (fin2 && cmSystemTools::GetLineFromStream(fin2, src_dir) &&
  2633. cmSystemTools::FileIsDirectory(src_dir)) {
  2634. cmSystemToolsCMakeRoot = src_dir;
  2635. }
  2636. }
  2637. if (!cmSystemToolsCMakeRoot.empty() && cmSystemToolsHTMLDoc.empty() &&
  2638. cmSystemTools::FileExists(
  2639. cmStrCat(dir, "/Utilities/Sphinx/html/index.html"))) {
  2640. cmSystemToolsHTMLDoc = cmStrCat(dir, "/Utilities/Sphinx/html");
  2641. }
  2642. }
  2643. #endif
  2644. }
  2645. void cmSystemTools::FindCMakeResources(const char* argv0)
  2646. {
  2647. std::string exe = FindOwnExecutable(argv0);
  2648. #ifdef CMAKE_BOOTSTRAP
  2649. // The bootstrap cmake knows its resource locations.
  2650. cmSystemToolsCMakeRoot = CMAKE_BOOTSTRAP_SOURCE_DIR;
  2651. cmSystemToolsCMakeCommand = exe;
  2652. // The bootstrap cmake does not provide the other tools,
  2653. // so use the directory where they are about to be built.
  2654. std::string exe_dir = CMAKE_BOOTSTRAP_BINARY_DIR "/bin";
  2655. #else
  2656. // Find resources relative to our own executable.
  2657. std::string exe_dir = cmSystemTools::GetFilenamePath(exe);
  2658. bool found = false;
  2659. do {
  2660. found = FindCMakeResourcesInInstallTree(exe_dir);
  2661. } while (!found && ResolveSymlinkToOwnExecutable(exe, exe_dir));
  2662. if (!found) {
  2663. FindCMakeResourcesInBuildTree(exe_dir);
  2664. }
  2665. cmSystemToolsCMakeCommand =
  2666. cmStrCat(exe_dir, "/cmake", cmSystemTools::GetExecutableExtension());
  2667. #endif
  2668. cmSystemToolsCTestCommand =
  2669. cmStrCat(exe_dir, "/ctest", cmSystemTools::GetExecutableExtension());
  2670. cmSystemToolsCPackCommand =
  2671. cmStrCat(exe_dir, "/cpack", cmSystemTools::GetExecutableExtension());
  2672. cmSystemToolsCMakeGUICommand =
  2673. cmStrCat(exe_dir, "/cmake-gui", cmSystemTools::GetExecutableExtension());
  2674. if (!cmSystemTools::FileExists(cmSystemToolsCMakeGUICommand)) {
  2675. cmSystemToolsCMakeGUICommand.clear();
  2676. }
  2677. cmSystemToolsCMakeCursesCommand =
  2678. cmStrCat(exe_dir, "/ccmake", cmSystemTools::GetExecutableExtension());
  2679. if (!cmSystemTools::FileExists(cmSystemToolsCMakeCursesCommand)) {
  2680. cmSystemToolsCMakeCursesCommand.clear();
  2681. }
  2682. cmSystemToolsCMClDepsCommand =
  2683. cmStrCat(exe_dir, "/cmcldeps", cmSystemTools::GetExecutableExtension());
  2684. if (!cmSystemTools::FileExists(cmSystemToolsCMClDepsCommand)) {
  2685. cmSystemToolsCMClDepsCommand.clear();
  2686. }
  2687. }
  2688. std::string const& cmSystemTools::GetCMakeCommand()
  2689. {
  2690. return cmSystemToolsCMakeCommand;
  2691. }
  2692. std::string const& cmSystemTools::GetCTestCommand()
  2693. {
  2694. return cmSystemToolsCTestCommand;
  2695. }
  2696. std::string const& cmSystemTools::GetCPackCommand()
  2697. {
  2698. return cmSystemToolsCPackCommand;
  2699. }
  2700. std::string const& cmSystemTools::GetCMakeCursesCommand()
  2701. {
  2702. return cmSystemToolsCMakeCursesCommand;
  2703. }
  2704. std::string const& cmSystemTools::GetCMakeGUICommand()
  2705. {
  2706. return cmSystemToolsCMakeGUICommand;
  2707. }
  2708. std::string const& cmSystemTools::GetCMClDepsCommand()
  2709. {
  2710. return cmSystemToolsCMClDepsCommand;
  2711. }
  2712. std::string const& cmSystemTools::GetCMakeRoot()
  2713. {
  2714. return cmSystemToolsCMakeRoot;
  2715. }
  2716. std::string const& cmSystemTools::GetHTMLDoc()
  2717. {
  2718. return cmSystemToolsHTMLDoc;
  2719. }
  2720. cm::optional<std::string> cmSystemTools::GetSystemConfigDirectory()
  2721. {
  2722. #if defined(_WIN32)
  2723. LPWSTR lpwstr;
  2724. if (FAILED(SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, NULL, &lpwstr))) {
  2725. return cm::nullopt;
  2726. }
  2727. std::wstring wstr = std::wstring(lpwstr);
  2728. CoTaskMemFree(lpwstr);
  2729. std::string config = cmsys::Encoding::ToNarrow(wstr);
  2730. cmSystemTools::ConvertToUnixSlashes(config);
  2731. return config;
  2732. #else
  2733. auto config = cmSystemTools::GetEnvVar("XDG_CONFIG_HOME");
  2734. if (!config.has_value()) {
  2735. config = cmSystemTools::GetEnvVar("HOME");
  2736. if (config.has_value()) {
  2737. # if defined(__APPLE__)
  2738. config = cmStrCat(config.value(), "/Library/Application Support");
  2739. # else
  2740. config = cmStrCat(config.value(), "/.config");
  2741. # endif
  2742. }
  2743. }
  2744. return config;
  2745. #endif
  2746. }
  2747. cm::optional<std::string> cmSystemTools::GetCMakeConfigDirectory()
  2748. {
  2749. auto config = cmSystemTools::GetEnvVar("CMAKE_CONFIG_DIR");
  2750. if (!config.has_value()) {
  2751. config = cmSystemTools::GetSystemConfigDirectory();
  2752. if (config.has_value()) {
  2753. #if defined(_WIN32) || defined(__APPLE__)
  2754. config = cmStrCat(config.value(), "/CMake");
  2755. #else
  2756. config = cmStrCat(config.value(), "/cmake");
  2757. #endif
  2758. }
  2759. }
  2760. return config;
  2761. }
  2762. std::string const& cmSystemTools::GetLogicalWorkingDirectory()
  2763. {
  2764. return cmSystemToolsLogicalWorkingDirectory;
  2765. }
  2766. cmsys::Status cmSystemTools::SetLogicalWorkingDirectory(std::string const& lwd)
  2767. {
  2768. cmsys::Status status = cmSystemTools::ChangeDirectory(lwd);
  2769. if (status) {
  2770. cmSystemToolsLogicalWorkingDirectory = lwd;
  2771. }
  2772. return status;
  2773. }
  2774. void cmSystemTools::MakefileColorEcho(int color, const char* message,
  2775. bool newline, bool enabled)
  2776. {
  2777. // On some platforms (an MSYS prompt) cmsysTerminal may not be able
  2778. // to determine whether the stream is displayed on a tty. In this
  2779. // case it assumes no unless we tell it otherwise. Since we want
  2780. // color messages to be displayed for users we will assume yes.
  2781. // However, we can test for some situations when the answer is most
  2782. // likely no.
  2783. int assumeTTY = cmsysTerminal_Color_AssumeTTY;
  2784. if (cmSystemTools::HasEnv("DART_TEST_FROM_DART") ||
  2785. cmSystemTools::HasEnv("DASHBOARD_TEST_FROM_CTEST") ||
  2786. cmSystemTools::HasEnv("CTEST_INTERACTIVE_DEBUG_MODE")) {
  2787. // Avoid printing color escapes during dashboard builds.
  2788. assumeTTY = 0;
  2789. }
  2790. if (enabled && color != cmsysTerminal_Color_Normal) {
  2791. // Print with color. Delay the newline until later so that
  2792. // all color restore sequences appear before it.
  2793. cmsysTerminal_cfprintf(color | assumeTTY, stdout, "%s", message);
  2794. } else {
  2795. // Color is disabled. Print without color.
  2796. fprintf(stdout, "%s", message);
  2797. }
  2798. if (newline) {
  2799. fprintf(stdout, "\n");
  2800. }
  2801. }
  2802. bool cmSystemTools::GuessLibrarySOName(std::string const& fullPath,
  2803. std::string& soname)
  2804. {
  2805. // For ELF shared libraries use a real parser to get the correct
  2806. // soname.
  2807. cmELF elf(fullPath.c_str());
  2808. if (elf) {
  2809. return elf.GetSOName(soname);
  2810. }
  2811. // If the file is not a symlink we have no guess for its soname.
  2812. if (!cmSystemTools::FileIsSymlink(fullPath)) {
  2813. return false;
  2814. }
  2815. if (!cmSystemTools::ReadSymlink(fullPath, soname)) {
  2816. return false;
  2817. }
  2818. // If the symlink has a path component we have no guess for the soname.
  2819. if (!cmSystemTools::GetFilenamePath(soname).empty()) {
  2820. return false;
  2821. }
  2822. // If the symlink points at an extended version of the same name
  2823. // assume it is the soname.
  2824. std::string name = cmSystemTools::GetFilenameName(fullPath);
  2825. return soname.length() > name.length() &&
  2826. soname.compare(0, name.length(), name) == 0;
  2827. }
  2828. bool cmSystemTools::GuessLibraryInstallName(std::string const& fullPath,
  2829. std::string& soname)
  2830. {
  2831. #if defined(CMake_USE_MACH_PARSER)
  2832. cmMachO macho(fullPath.c_str());
  2833. if (macho) {
  2834. return macho.GetInstallName(soname);
  2835. }
  2836. #else
  2837. (void)fullPath;
  2838. (void)soname;
  2839. #endif
  2840. return false;
  2841. }
  2842. static std::string::size_type cmSystemToolsFindRPath(
  2843. cm::string_view const& have, cm::string_view const& want)
  2844. {
  2845. std::string::size_type pos = 0;
  2846. while (pos < have.size()) {
  2847. // Look for an occurrence of the string.
  2848. std::string::size_type const beg = have.find(want, pos);
  2849. if (beg == std::string::npos) {
  2850. return std::string::npos;
  2851. }
  2852. // Make sure it is separated from preceding entries.
  2853. if (beg > 0 && have[beg - 1] != ':') {
  2854. pos = beg + 1;
  2855. continue;
  2856. }
  2857. // Make sure it is separated from following entries.
  2858. std::string::size_type const end = beg + want.size();
  2859. if (end < have.size() && have[end] != ':') {
  2860. pos = beg + 1;
  2861. continue;
  2862. }
  2863. // Return the position of the path portion.
  2864. return beg;
  2865. }
  2866. // The desired rpath was not found.
  2867. return std::string::npos;
  2868. }
  2869. namespace {
  2870. struct cmSystemToolsRPathInfo
  2871. {
  2872. unsigned long Position;
  2873. unsigned long Size;
  2874. std::string Name;
  2875. std::string Value;
  2876. };
  2877. using EmptyCallback = std::function<bool(std::string*, const cmELF&)>;
  2878. using AdjustCallback = std::function<bool(
  2879. cm::optional<std::string>&, const std::string&, const char*, std::string*)>;
  2880. cm::optional<bool> AdjustRPathELF(std::string const& file,
  2881. const EmptyCallback& emptyCallback,
  2882. const AdjustCallback& adjustCallback,
  2883. std::string* emsg, bool* changed)
  2884. {
  2885. if (changed) {
  2886. *changed = false;
  2887. }
  2888. int rp_count = 0;
  2889. bool remove_rpath = true;
  2890. cmSystemToolsRPathInfo rp[2];
  2891. {
  2892. // Parse the ELF binary.
  2893. cmELF elf(file.c_str());
  2894. if (!elf) {
  2895. return cm::nullopt; // Not a valid ELF file.
  2896. }
  2897. if (!elf.HasDynamicSection()) {
  2898. return true; // No dynamic section to update.
  2899. }
  2900. // Get the RPATH and RUNPATH entries from it.
  2901. int se_count = 0;
  2902. cmELF::StringEntry const* se[2] = { nullptr, nullptr };
  2903. const char* se_name[2] = { nullptr, nullptr };
  2904. if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
  2905. se[se_count] = se_rpath;
  2906. se_name[se_count] = "RPATH";
  2907. ++se_count;
  2908. }
  2909. if (cmELF::StringEntry const* se_runpath = elf.GetRunPath()) {
  2910. se[se_count] = se_runpath;
  2911. se_name[se_count] = "RUNPATH";
  2912. ++se_count;
  2913. }
  2914. if (se_count == 0) {
  2915. return emptyCallback(emsg, elf);
  2916. }
  2917. for (int i = 0; i < se_count; ++i) {
  2918. // If both RPATH and RUNPATH refer to the same string literal it
  2919. // needs to be changed only once.
  2920. if (rp_count && rp[0].Position == se[i]->Position) {
  2921. continue;
  2922. }
  2923. // Store information about the entry in the file.
  2924. rp[rp_count].Position = se[i]->Position;
  2925. rp[rp_count].Size = se[i]->Size;
  2926. rp[rp_count].Name = se_name[i];
  2927. // Adjust the rpath.
  2928. cm::optional<std::string> outRPath;
  2929. if (!adjustCallback(outRPath, se[i]->Value, se_name[i], emsg)) {
  2930. return false;
  2931. }
  2932. if (outRPath) {
  2933. if (!outRPath->empty()) {
  2934. remove_rpath = false;
  2935. }
  2936. // Make sure there is enough room to store the new rpath and at
  2937. // least one null terminator.
  2938. if (rp[rp_count].Size < outRPath->length() + 1) {
  2939. if (emsg) {
  2940. *emsg = cmStrCat("The replacement path is too long for the ",
  2941. se_name[i], " entry.");
  2942. }
  2943. return false;
  2944. }
  2945. // This entry is ready for update.
  2946. rp[rp_count].Value = std::move(*outRPath);
  2947. ++rp_count;
  2948. } else {
  2949. remove_rpath = false;
  2950. }
  2951. }
  2952. }
  2953. // If no runtime path needs to be changed, we are done.
  2954. if (rp_count == 0) {
  2955. return true;
  2956. }
  2957. // If the resulting rpath is empty, just remove the entire entry instead.
  2958. if (remove_rpath) {
  2959. return cmSystemTools::RemoveRPath(file, emsg, changed);
  2960. }
  2961. {
  2962. // Open the file for update.
  2963. cmsys::ofstream f(file.c_str(),
  2964. std::ios::in | std::ios::out | std::ios::binary);
  2965. if (!f) {
  2966. if (emsg) {
  2967. *emsg = "Error opening file for update.";
  2968. }
  2969. return false;
  2970. }
  2971. // Store the new RPATH and RUNPATH strings.
  2972. for (int i = 0; i < rp_count; ++i) {
  2973. // Seek to the RPATH position.
  2974. if (!f.seekp(rp[i].Position)) {
  2975. if (emsg) {
  2976. *emsg = cmStrCat("Error seeking to ", rp[i].Name, " position.");
  2977. }
  2978. return false;
  2979. }
  2980. // Write the new rpath. Follow it with enough null terminators to
  2981. // fill the string table entry.
  2982. f << rp[i].Value;
  2983. for (unsigned long j = rp[i].Value.length(); j < rp[i].Size; ++j) {
  2984. f << '\0';
  2985. }
  2986. // Make sure it wrote correctly.
  2987. if (!f) {
  2988. if (emsg) {
  2989. *emsg = cmStrCat("Error writing the new ", rp[i].Name,
  2990. " string to the file.");
  2991. }
  2992. return false;
  2993. }
  2994. }
  2995. }
  2996. // Everything was updated successfully.
  2997. if (changed) {
  2998. *changed = true;
  2999. }
  3000. return true;
  3001. }
  3002. std::function<bool(std::string*, const cmELF&)> MakeEmptyCallback(
  3003. const std::string& newRPath)
  3004. {
  3005. return [newRPath](std::string* emsg, const cmELF& elf) -> bool {
  3006. if (newRPath.empty()) {
  3007. // The new rpath is empty and there is no rpath anyway so it is
  3008. // okay.
  3009. return true;
  3010. }
  3011. if (emsg) {
  3012. *emsg =
  3013. cmStrCat("No valid ELF RPATH or RUNPATH entry exists in the file; ",
  3014. elf.GetErrorMessage());
  3015. }
  3016. return false;
  3017. };
  3018. }
  3019. }
  3020. static cm::optional<bool> ChangeRPathELF(std::string const& file,
  3021. std::string const& oldRPath,
  3022. std::string const& newRPath,
  3023. bool removeEnvironmentRPath,
  3024. std::string* emsg, bool* changed)
  3025. {
  3026. auto adjustCallback = [oldRPath, newRPath, removeEnvironmentRPath](
  3027. cm::optional<std::string>& outRPath,
  3028. const std::string& inRPath, const char* se_name,
  3029. std::string* emsg2) -> bool {
  3030. // Make sure the current rpath contains the old rpath.
  3031. std::string::size_type pos = cmSystemToolsFindRPath(inRPath, oldRPath);
  3032. if (pos == std::string::npos) {
  3033. // If it contains the new rpath instead then it is okay.
  3034. if (cmSystemToolsFindRPath(inRPath, newRPath) != std::string::npos) {
  3035. return true;
  3036. }
  3037. if (emsg2) {
  3038. std::ostringstream e;
  3039. /* clang-format off */
  3040. e << "The current " << se_name << " is:\n"
  3041. " " << inRPath << "\n"
  3042. "which does not contain:\n"
  3043. " " << oldRPath << "\n"
  3044. "as was expected.";
  3045. /* clang-format on */
  3046. *emsg2 = e.str();
  3047. }
  3048. return false;
  3049. }
  3050. std::string::size_type prefix_len = pos;
  3051. // If oldRPath was at the end of the file's RPath, and newRPath is empty,
  3052. // we should remove the unnecessary ':' at the end.
  3053. if (newRPath.empty() && pos > 0 && inRPath[pos - 1] == ':' &&
  3054. pos + oldRPath.length() == inRPath.length()) {
  3055. prefix_len--;
  3056. }
  3057. // Construct the new value which preserves the part of the path
  3058. // not being changed.
  3059. outRPath.emplace();
  3060. if (!removeEnvironmentRPath) {
  3061. *outRPath += inRPath.substr(0, prefix_len);
  3062. }
  3063. *outRPath += newRPath;
  3064. *outRPath += inRPath.substr(pos + oldRPath.length());
  3065. return true;
  3066. };
  3067. return AdjustRPathELF(file, MakeEmptyCallback(newRPath), adjustCallback,
  3068. emsg, changed);
  3069. }
  3070. static cm::optional<bool> SetRPathELF(std::string const& file,
  3071. std::string const& newRPath,
  3072. std::string* emsg, bool* changed)
  3073. {
  3074. auto adjustCallback = [newRPath](cm::optional<std::string>& outRPath,
  3075. const std::string& inRPath,
  3076. const char* /*se_name*/, std::string*
  3077. /*emsg*/) -> bool {
  3078. if (inRPath != newRPath) {
  3079. outRPath = newRPath;
  3080. }
  3081. return true;
  3082. };
  3083. return AdjustRPathELF(file, MakeEmptyCallback(newRPath), adjustCallback,
  3084. emsg, changed);
  3085. }
  3086. static cm::optional<bool> ChangeRPathXCOFF(std::string const& file,
  3087. std::string const& oldRPath,
  3088. std::string const& newRPath,
  3089. bool removeEnvironmentRPath,
  3090. std::string* emsg, bool* changed)
  3091. {
  3092. if (changed) {
  3093. *changed = false;
  3094. }
  3095. #if !defined(CMake_USE_XCOFF_PARSER)
  3096. (void)file;
  3097. (void)oldRPath;
  3098. (void)newRPath;
  3099. (void)removeEnvironmentRPath;
  3100. (void)emsg;
  3101. return cm::nullopt;
  3102. #else
  3103. bool chg = false;
  3104. cmXCOFF xcoff(file.c_str(), cmXCOFF::Mode::ReadWrite);
  3105. if (!xcoff) {
  3106. return cm::nullopt; // Not a valid XCOFF file
  3107. }
  3108. if (cm::optional<cm::string_view> maybeLibPath = xcoff.GetLibPath()) {
  3109. cm::string_view libPath = *maybeLibPath;
  3110. // Make sure the current rpath contains the old rpath.
  3111. std::string::size_type pos = cmSystemToolsFindRPath(libPath, oldRPath);
  3112. if (pos == std::string::npos) {
  3113. // If it contains the new rpath instead then it is okay.
  3114. if (cmSystemToolsFindRPath(libPath, newRPath) != std::string::npos) {
  3115. return true;
  3116. }
  3117. if (emsg) {
  3118. std::ostringstream e;
  3119. /* clang-format off */
  3120. e << "The current RPATH is:\n"
  3121. " " << libPath << "\n"
  3122. "which does not contain:\n"
  3123. " " << oldRPath << "\n"
  3124. "as was expected.";
  3125. /* clang-format on */
  3126. *emsg = e.str();
  3127. }
  3128. return false;
  3129. }
  3130. // The prefix is either empty or ends in a ':'.
  3131. cm::string_view prefix = libPath.substr(0, pos);
  3132. if (newRPath.empty() && !prefix.empty()) {
  3133. prefix.remove_suffix(1);
  3134. }
  3135. // The suffix is either empty or starts in a ':'.
  3136. cm::string_view suffix = libPath.substr(pos + oldRPath.length());
  3137. // Construct the new value which preserves the part of the path
  3138. // not being changed.
  3139. std::string newLibPath;
  3140. if (!removeEnvironmentRPath) {
  3141. newLibPath = std::string(prefix);
  3142. }
  3143. newLibPath += newRPath;
  3144. newLibPath += suffix;
  3145. chg = xcoff.SetLibPath(newLibPath);
  3146. }
  3147. if (!xcoff) {
  3148. if (emsg) {
  3149. *emsg = xcoff.GetErrorMessage();
  3150. }
  3151. return false;
  3152. }
  3153. // Everything was updated successfully.
  3154. if (changed) {
  3155. *changed = chg;
  3156. }
  3157. return true;
  3158. #endif
  3159. }
  3160. static cm::optional<bool> SetRPathXCOFF(std::string const& /*file*/,
  3161. std::string const& /*newRPath*/,
  3162. std::string* /*emsg*/,
  3163. bool* /*changed*/)
  3164. {
  3165. return cm::nullopt; // Not implemented.
  3166. }
  3167. bool cmSystemTools::ChangeRPath(std::string const& file,
  3168. std::string const& oldRPath,
  3169. std::string const& newRPath,
  3170. bool removeEnvironmentRPath, std::string* emsg,
  3171. bool* changed)
  3172. {
  3173. if (cm::optional<bool> result = ChangeRPathELF(
  3174. file, oldRPath, newRPath, removeEnvironmentRPath, emsg, changed)) {
  3175. return result.value();
  3176. }
  3177. if (cm::optional<bool> result = ChangeRPathXCOFF(
  3178. file, oldRPath, newRPath, removeEnvironmentRPath, emsg, changed)) {
  3179. return result.value();
  3180. }
  3181. // The file format is not recognized. Assume it has no RPATH.
  3182. if (newRPath.empty()) {
  3183. // The caller wanted no RPATH anyway.
  3184. return true;
  3185. }
  3186. if (emsg) {
  3187. *emsg = "The file format is not recognized.";
  3188. }
  3189. return false;
  3190. }
  3191. bool cmSystemTools::SetRPath(std::string const& file,
  3192. std::string const& newRPath, std::string* emsg,
  3193. bool* changed)
  3194. {
  3195. if (cm::optional<bool> result = SetRPathELF(file, newRPath, emsg, changed)) {
  3196. return result.value();
  3197. }
  3198. if (cm::optional<bool> result =
  3199. SetRPathXCOFF(file, newRPath, emsg, changed)) {
  3200. return result.value();
  3201. }
  3202. // The file format is not recognized. Assume it has no RPATH.
  3203. if (newRPath.empty()) {
  3204. // The caller wanted no RPATH anyway.
  3205. return true;
  3206. }
  3207. if (emsg) {
  3208. *emsg = "The file format is not recognized.";
  3209. }
  3210. return false;
  3211. }
  3212. namespace {
  3213. bool VersionCompare(cmSystemTools::CompareOp op, const char* lhss,
  3214. const char* rhss)
  3215. {
  3216. const char* endl = lhss;
  3217. const char* endr = rhss;
  3218. while (((*endl >= '0') && (*endl <= '9')) ||
  3219. ((*endr >= '0') && (*endr <= '9'))) {
  3220. // Do component-wise comparison, ignoring leading zeros
  3221. // (components are treated as integers, not as mantissas)
  3222. while (*endl == '0') {
  3223. endl++;
  3224. }
  3225. while (*endr == '0') {
  3226. endr++;
  3227. }
  3228. const char* beginl = endl;
  3229. const char* beginr = endr;
  3230. // count significant digits
  3231. while ((*endl >= '0') && (*endl <= '9')) {
  3232. endl++;
  3233. }
  3234. while ((*endr >= '0') && (*endr <= '9')) {
  3235. endr++;
  3236. }
  3237. // compare number of digits first
  3238. ptrdiff_t r = ((endl - beginl) - (endr - beginr));
  3239. if (r == 0) {
  3240. // compare the digits if number of digits is equal
  3241. r = strncmp(beginl, beginr, endl - beginl);
  3242. }
  3243. if (r < 0) {
  3244. // lhs < rhs, so true if operation is LESS
  3245. return (op & cmSystemTools::OP_LESS) != 0;
  3246. }
  3247. if (r > 0) {
  3248. // lhs > rhs, so true if operation is GREATER
  3249. return (op & cmSystemTools::OP_GREATER) != 0;
  3250. }
  3251. if (*endr == '.') {
  3252. endr++;
  3253. }
  3254. if (*endl == '.') {
  3255. endl++;
  3256. }
  3257. }
  3258. // lhs == rhs, so true if operation is EQUAL
  3259. return (op & cmSystemTools::OP_EQUAL) != 0;
  3260. }
  3261. }
  3262. bool cmSystemTools::VersionCompare(cmSystemTools::CompareOp op,
  3263. const std::string& lhs,
  3264. const std::string& rhs)
  3265. {
  3266. return ::VersionCompare(op, lhs.c_str(), rhs.c_str());
  3267. }
  3268. bool cmSystemTools::VersionCompare(cmSystemTools::CompareOp op,
  3269. const std::string& lhs, const char rhs[])
  3270. {
  3271. return ::VersionCompare(op, lhs.c_str(), rhs);
  3272. }
  3273. bool cmSystemTools::VersionCompareEqual(std::string const& lhs,
  3274. std::string const& rhs)
  3275. {
  3276. return cmSystemTools::VersionCompare(cmSystemTools::OP_EQUAL, lhs, rhs);
  3277. }
  3278. bool cmSystemTools::VersionCompareGreater(std::string const& lhs,
  3279. std::string const& rhs)
  3280. {
  3281. return cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER, lhs, rhs);
  3282. }
  3283. bool cmSystemTools::VersionCompareGreaterEq(std::string const& lhs,
  3284. std::string const& rhs)
  3285. {
  3286. return cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL, lhs,
  3287. rhs);
  3288. }
  3289. static size_t cm_strverscmp_find_first_difference_or_end(const char* lhs,
  3290. const char* rhs)
  3291. {
  3292. size_t i = 0;
  3293. /* Step forward until we find a difference or both strings end together.
  3294. The difference may lie on the null-terminator of one string. */
  3295. while (lhs[i] == rhs[i] && lhs[i] != 0) {
  3296. ++i;
  3297. }
  3298. return i;
  3299. }
  3300. static size_t cm_strverscmp_find_digits_begin(const char* s, size_t i)
  3301. {
  3302. /* Step back until we are not preceded by a digit. */
  3303. while (i > 0 && isdigit(s[i - 1])) {
  3304. --i;
  3305. }
  3306. return i;
  3307. }
  3308. static size_t cm_strverscmp_find_digits_end(const char* s, size_t i)
  3309. {
  3310. /* Step forward over digits. */
  3311. while (isdigit(s[i])) {
  3312. ++i;
  3313. }
  3314. return i;
  3315. }
  3316. static size_t cm_strverscmp_count_leading_zeros(const char* s, size_t b)
  3317. {
  3318. size_t i = b;
  3319. /* Step forward over zeros that are followed by another digit. */
  3320. while (s[i] == '0' && isdigit(s[i + 1])) {
  3321. ++i;
  3322. }
  3323. return i - b;
  3324. }
  3325. static int cm_strverscmp(const char* lhs, const char* rhs)
  3326. {
  3327. size_t const i = cm_strverscmp_find_first_difference_or_end(lhs, rhs);
  3328. if (lhs[i] != rhs[i]) {
  3329. /* The strings differ starting at 'i'. Check for a digit sequence. */
  3330. size_t const b = cm_strverscmp_find_digits_begin(lhs, i);
  3331. if (b != i || (isdigit(lhs[i]) && isdigit(rhs[i]))) {
  3332. /* A digit sequence starts at 'b', preceding or at 'i'. */
  3333. /* Look for leading zeros, implying a leading decimal point. */
  3334. size_t const lhs_zeros = cm_strverscmp_count_leading_zeros(lhs, b);
  3335. size_t const rhs_zeros = cm_strverscmp_count_leading_zeros(rhs, b);
  3336. if (lhs_zeros != rhs_zeros) {
  3337. /* The side with more leading zeros orders first. */
  3338. return rhs_zeros > lhs_zeros ? 1 : -1;
  3339. }
  3340. if (lhs_zeros == 0) {
  3341. /* No leading zeros; compare digit sequence lengths. */
  3342. size_t const lhs_end = cm_strverscmp_find_digits_end(lhs, i);
  3343. size_t const rhs_end = cm_strverscmp_find_digits_end(rhs, i);
  3344. if (lhs_end != rhs_end) {
  3345. /* The side with fewer digits orders first. */
  3346. return lhs_end > rhs_end ? 1 : -1;
  3347. }
  3348. }
  3349. }
  3350. }
  3351. /* Ordering was not decided by digit sequence lengths; compare bytes. */
  3352. return lhs[i] - rhs[i];
  3353. }
  3354. int cmSystemTools::strverscmp(std::string const& lhs, std::string const& rhs)
  3355. {
  3356. return cm_strverscmp(lhs.c_str(), rhs.c_str());
  3357. }
  3358. static cm::optional<bool> RemoveRPathELF(std::string const& file,
  3359. std::string* emsg, bool* removed)
  3360. {
  3361. if (removed) {
  3362. *removed = false;
  3363. }
  3364. int zeroCount = 0;
  3365. unsigned long zeroPosition[2] = { 0, 0 };
  3366. unsigned long zeroSize[2] = { 0, 0 };
  3367. unsigned long bytesBegin = 0;
  3368. std::vector<char> bytes;
  3369. {
  3370. // Parse the ELF binary.
  3371. cmELF elf(file.c_str());
  3372. if (!elf) {
  3373. return cm::nullopt; // Not a valid ELF file.
  3374. }
  3375. // Get the RPATH and RUNPATH entries from it and sort them by index
  3376. // in the dynamic section header.
  3377. int se_count = 0;
  3378. cmELF::StringEntry const* se[2] = { nullptr, nullptr };
  3379. if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
  3380. se[se_count++] = se_rpath;
  3381. }
  3382. if (cmELF::StringEntry const* se_runpath = elf.GetRunPath()) {
  3383. se[se_count++] = se_runpath;
  3384. }
  3385. if (se_count == 0) {
  3386. // There is no RPATH or RUNPATH anyway.
  3387. return true;
  3388. }
  3389. if (se_count == 2 && se[1]->IndexInSection < se[0]->IndexInSection) {
  3390. std::swap(se[0], se[1]);
  3391. }
  3392. // Obtain a copy of the dynamic entries
  3393. cmELF::DynamicEntryList dentries = elf.GetDynamicEntries();
  3394. if (dentries.empty()) {
  3395. // This should happen only for invalid ELF files where a DT_NULL
  3396. // appears before the end of the table.
  3397. if (emsg) {
  3398. *emsg = "DYNAMIC section contains a DT_NULL before the end.";
  3399. }
  3400. return false;
  3401. }
  3402. // Save information about the string entries to be zeroed.
  3403. zeroCount = se_count;
  3404. for (int i = 0; i < se_count; ++i) {
  3405. zeroPosition[i] = se[i]->Position;
  3406. zeroSize[i] = se[i]->Size;
  3407. }
  3408. // Get size of one DYNAMIC entry
  3409. unsigned long const sizeof_dentry =
  3410. elf.GetDynamicEntryPosition(1) - elf.GetDynamicEntryPosition(0);
  3411. // Adjust the entry list as necessary to remove the run path
  3412. unsigned long entriesErased = 0;
  3413. for (auto it = dentries.begin(); it != dentries.end();) {
  3414. if (it->first == cmELF::TagRPath || it->first == cmELF::TagRunPath) {
  3415. it = dentries.erase(it);
  3416. entriesErased++;
  3417. continue;
  3418. }
  3419. if (it->first == cmELF::TagMipsRldMapRel && elf.IsMIPS()) {
  3420. // Background: debuggers need to know the "linker map" which contains
  3421. // the addresses each dynamic object is loaded at. Most arches use
  3422. // the DT_DEBUG tag which the dynamic linker writes to (directly) and
  3423. // contain the location of the linker map, however on MIPS the
  3424. // .dynamic section is always read-only so this is not possible. MIPS
  3425. // objects instead contain a DT_MIPS_RLD_MAP tag which contains the
  3426. // address where the dynamic linker will write to (an indirect
  3427. // version of DT_DEBUG). Since this doesn't work when using PIE, a
  3428. // relative equivalent was created - DT_MIPS_RLD_MAP_REL. Since this
  3429. // version contains a relative offset, moving it changes the
  3430. // calculated address. This may cause the dynamic linker to write
  3431. // into memory it should not be changing.
  3432. //
  3433. // To fix this, we adjust the value of DT_MIPS_RLD_MAP_REL here. If
  3434. // we move it up by n bytes, we add n bytes to the value of this tag.
  3435. it->second += entriesErased * sizeof_dentry;
  3436. }
  3437. it++;
  3438. }
  3439. // Encode new entries list
  3440. bytes = elf.EncodeDynamicEntries(dentries);
  3441. bytesBegin = elf.GetDynamicEntryPosition(0);
  3442. }
  3443. // Open the file for update.
  3444. cmsys::ofstream f(file.c_str(),
  3445. std::ios::in | std::ios::out | std::ios::binary);
  3446. if (!f) {
  3447. if (emsg) {
  3448. *emsg = "Error opening file for update.";
  3449. }
  3450. return false;
  3451. }
  3452. // Write the new DYNAMIC table header.
  3453. if (!f.seekp(bytesBegin)) {
  3454. if (emsg) {
  3455. *emsg = "Error seeking to DYNAMIC table header for RPATH.";
  3456. }
  3457. return false;
  3458. }
  3459. if (!f.write(bytes.data(), bytes.size())) {
  3460. if (emsg) {
  3461. *emsg = "Error replacing DYNAMIC table header.";
  3462. }
  3463. return false;
  3464. }
  3465. // Fill the RPATH and RUNPATH strings with zero bytes.
  3466. for (int i = 0; i < zeroCount; ++i) {
  3467. if (!f.seekp(zeroPosition[i])) {
  3468. if (emsg) {
  3469. *emsg = "Error seeking to RPATH position.";
  3470. }
  3471. return false;
  3472. }
  3473. for (unsigned long j = 0; j < zeroSize[i]; ++j) {
  3474. f << '\0';
  3475. }
  3476. if (!f) {
  3477. if (emsg) {
  3478. *emsg = "Error writing the empty rpath string to the file.";
  3479. }
  3480. return false;
  3481. }
  3482. }
  3483. // Everything was updated successfully.
  3484. if (removed) {
  3485. *removed = true;
  3486. }
  3487. return true;
  3488. }
  3489. static cm::optional<bool> RemoveRPathXCOFF(std::string const& file,
  3490. std::string* emsg, bool* removed)
  3491. {
  3492. if (removed) {
  3493. *removed = false;
  3494. }
  3495. #if !defined(CMake_USE_XCOFF_PARSER)
  3496. (void)file;
  3497. (void)emsg;
  3498. return cm::nullopt; // Cannot handle XCOFF files.
  3499. #else
  3500. cmXCOFF xcoff(file.c_str(), cmXCOFF::Mode::ReadWrite);
  3501. if (!xcoff) {
  3502. return cm::nullopt; // Not a valid XCOFF file.
  3503. }
  3504. bool rm = xcoff.RemoveLibPath();
  3505. if (!xcoff) {
  3506. if (emsg) {
  3507. *emsg = xcoff.GetErrorMessage();
  3508. }
  3509. return false;
  3510. }
  3511. if (removed) {
  3512. *removed = rm;
  3513. }
  3514. return true;
  3515. #endif
  3516. }
  3517. bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg,
  3518. bool* removed)
  3519. {
  3520. if (cm::optional<bool> result = RemoveRPathELF(file, emsg, removed)) {
  3521. return result.value();
  3522. }
  3523. if (cm::optional<bool> result = RemoveRPathXCOFF(file, emsg, removed)) {
  3524. return result.value();
  3525. }
  3526. // The file format is not recognized. Assume it has no RPATH.
  3527. return true;
  3528. }
  3529. bool cmSystemTools::CheckRPath(std::string const& file,
  3530. std::string const& newRPath)
  3531. {
  3532. // Parse the ELF binary.
  3533. cmELF elf(file.c_str());
  3534. if (elf) {
  3535. // Get the RPATH or RUNPATH entry from it.
  3536. cmELF::StringEntry const* se = elf.GetRPath();
  3537. if (!se) {
  3538. se = elf.GetRunPath();
  3539. }
  3540. // Make sure the current rpath contains the new rpath.
  3541. if (newRPath.empty()) {
  3542. if (!se) {
  3543. return true;
  3544. }
  3545. } else {
  3546. if (se &&
  3547. cmSystemToolsFindRPath(se->Value, newRPath) != std::string::npos) {
  3548. return true;
  3549. }
  3550. }
  3551. return false;
  3552. }
  3553. #if defined(CMake_USE_XCOFF_PARSER)
  3554. // Parse the XCOFF binary.
  3555. cmXCOFF xcoff(file.c_str());
  3556. if (xcoff) {
  3557. if (cm::optional<cm::string_view> libPath = xcoff.GetLibPath()) {
  3558. if (cmSystemToolsFindRPath(*libPath, newRPath) != std::string::npos) {
  3559. return true;
  3560. }
  3561. }
  3562. return false;
  3563. }
  3564. #endif
  3565. // The file format is not recognized. Assume it has no RPATH.
  3566. // Therefore we succeed if the new rpath is empty anyway.
  3567. return newRPath.empty();
  3568. }
  3569. bool cmSystemTools::RepeatedRemoveDirectory(const std::string& dir)
  3570. {
  3571. #ifdef _WIN32
  3572. // Windows sometimes locks files temporarily so try a few times.
  3573. WindowsFileRetry retry = cmSystemTools::GetWindowsFileRetry();
  3574. for (unsigned int i = 0; i < retry.Count; ++i) {
  3575. if (cmSystemTools::RemoveADirectory(dir)) {
  3576. return true;
  3577. }
  3578. cmSystemTools::Delay(retry.Delay);
  3579. }
  3580. return false;
  3581. #else
  3582. return static_cast<bool>(cmSystemTools::RemoveADirectory(dir));
  3583. #endif
  3584. }
  3585. std::string cmSystemTools::EncodeURL(std::string const& in, bool escapeSlashes)
  3586. {
  3587. std::string out;
  3588. for (char c : in) {
  3589. char hexCh[4] = { 0, 0, 0, 0 };
  3590. hexCh[0] = c;
  3591. switch (c) {
  3592. case '+':
  3593. case '?':
  3594. case '\\':
  3595. case '&':
  3596. case ' ':
  3597. case '=':
  3598. case '%':
  3599. snprintf(hexCh, sizeof(hexCh), "%%%02X", static_cast<int>(c));
  3600. break;
  3601. case '/':
  3602. if (escapeSlashes) {
  3603. strcpy(hexCh, "%2F");
  3604. }
  3605. break;
  3606. default:
  3607. break;
  3608. }
  3609. out.append(hexCh);
  3610. }
  3611. return out;
  3612. }
  3613. cmsys::Status cmSystemTools::CreateSymlink(std::string const& origName,
  3614. std::string const& newName)
  3615. {
  3616. cmsys::Status status =
  3617. cmSystemTools::CreateSymlinkQuietly(origName, newName);
  3618. if (!status) {
  3619. cmSystemTools::Error(cmStrCat("failed to create symbolic link '", newName,
  3620. "': ", status.GetString()));
  3621. }
  3622. return status;
  3623. }
  3624. cmsys::Status cmSystemTools::CreateSymlinkQuietly(std::string const& origName,
  3625. std::string const& newName)
  3626. {
  3627. uv_fs_t req;
  3628. int flags = 0;
  3629. #if defined(_WIN32)
  3630. if (cmsys::SystemTools::FileIsDirectory(origName)) {
  3631. flags |= UV_FS_SYMLINK_DIR;
  3632. }
  3633. #endif
  3634. int err = uv_fs_symlink(nullptr, &req, origName.c_str(), newName.c_str(),
  3635. flags, nullptr);
  3636. cmsys::Status status;
  3637. if (err) {
  3638. #if defined(_WIN32)
  3639. status = cmsys::Status::Windows(uv_fs_get_system_error(&req));
  3640. #elif UV_VERSION_MAJOR > 1 || (UV_VERSION_MAJOR == 1 && UV_VERSION_MINOR >= 38)
  3641. status = cmsys::Status::POSIX(uv_fs_get_system_error(&req));
  3642. #else
  3643. status = cmsys::Status::POSIX(-err);
  3644. #endif
  3645. }
  3646. return status;
  3647. }
  3648. cmsys::Status cmSystemTools::CreateLink(std::string const& origName,
  3649. std::string const& newName)
  3650. {
  3651. cmsys::Status status = cmSystemTools::CreateLinkQuietly(origName, newName);
  3652. if (!status) {
  3653. cmSystemTools::Error(
  3654. cmStrCat("failed to create link '", newName, "': ", status.GetString()));
  3655. }
  3656. return status;
  3657. }
  3658. cmsys::Status cmSystemTools::CreateLinkQuietly(std::string const& origName,
  3659. std::string const& newName)
  3660. {
  3661. uv_fs_t req;
  3662. int err =
  3663. uv_fs_link(nullptr, &req, origName.c_str(), newName.c_str(), nullptr);
  3664. cmsys::Status status;
  3665. if (err) {
  3666. #if defined(_WIN32)
  3667. status = cmsys::Status::Windows(uv_fs_get_system_error(&req));
  3668. #elif UV_VERSION_MAJOR > 1 || (UV_VERSION_MAJOR == 1 && UV_VERSION_MINOR >= 38)
  3669. status = cmsys::Status::POSIX(uv_fs_get_system_error(&req));
  3670. #else
  3671. status = cmsys::Status::POSIX(-err);
  3672. #endif
  3673. }
  3674. return status;
  3675. }
  3676. cm::string_view cmSystemTools::GetSystemName()
  3677. {
  3678. #if defined(_WIN32)
  3679. return "Windows";
  3680. #elif defined(__MSYS__)
  3681. return "MSYS";
  3682. #elif defined(__CYGWIN__)
  3683. return "CYGWIN";
  3684. #elif defined(__ANDROID__)
  3685. return "Android";
  3686. #else
  3687. static struct utsname uts_name;
  3688. static bool initialized = false;
  3689. static cm::string_view systemName;
  3690. if (initialized) {
  3691. return systemName;
  3692. }
  3693. if (uname(&uts_name) >= 0) {
  3694. initialized = true;
  3695. systemName = uts_name.sysname;
  3696. if (cmIsOff(systemName)) {
  3697. systemName = "UnknownOS";
  3698. }
  3699. // fix for BSD/OS, remove the /
  3700. static const cmsys::RegularExpression bsdOsRegex("BSD.OS");
  3701. cmsys::RegularExpressionMatch match;
  3702. if (bsdOsRegex.find(uts_name.sysname, match)) {
  3703. systemName = "BSDOS";
  3704. }
  3705. // fix for GNU/kFreeBSD, remove the GNU/
  3706. if (systemName.find("kFreeBSD") != cm::string_view::npos) {
  3707. systemName = "kFreeBSD";
  3708. }
  3709. return systemName;
  3710. }
  3711. return "";
  3712. #endif
  3713. }
  3714. char cmSystemTools::GetSystemPathlistSeparator()
  3715. {
  3716. #if defined(_WIN32)
  3717. return ';';
  3718. #else
  3719. return ':';
  3720. #endif
  3721. }