cmSystemTools.cxx 76 KB

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