cmSystemTools.cxx 86 KB

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