cmSystemTools.cxx 88 KB

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