cmSystemTools.cxx 88 KB

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