cmSystemTools.cxx 99 KB

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