cmSystemTools.cxx 86 KB

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