cmSystemTools.cxx 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmSystemTools.h"
  4. #include "cmAlgorithms.h"
  5. #if defined(CMAKE_BUILD_WITH_CMAKE)
  6. #include "cmArchiveWrite.h"
  7. #include "cmLocale.h"
  8. #include <cm_libarchive.h>
  9. #ifndef __LA_INT64_T
  10. #define __LA_INT64_T la_int64_t
  11. #endif
  12. #endif
  13. #if defined(CMAKE_BUILD_WITH_CMAKE)
  14. #include "cmCryptoHash.h"
  15. #endif
  16. #if defined(CMAKE_USE_ELF_PARSER)
  17. #include "cmELF.h"
  18. #endif
  19. #if defined(CMAKE_USE_MACH_PARSER)
  20. #include "cmMachO.h"
  21. #endif
  22. #include <algorithm>
  23. #include <assert.h>
  24. #include <cmsys/Directory.hxx>
  25. #include <cmsys/Encoding.hxx>
  26. #include <cmsys/FStream.hxx>
  27. #include <cmsys/RegularExpression.hxx>
  28. #include <cmsys/System.h>
  29. #include <cmsys/SystemTools.hxx>
  30. #include <cmsys/Terminal.h>
  31. #include <ctype.h>
  32. #include <errno.h>
  33. #include <iostream>
  34. #include <set>
  35. #include <sstream>
  36. #include <stdio.h>
  37. #include <stdlib.h>
  38. #include <string.h>
  39. #include <sys/stat.h>
  40. #include <time.h>
  41. #if defined(_WIN32)
  42. #include <windows.h>
  43. // include wincrypt.h after windows.h
  44. #include <wincrypt.h>
  45. #else
  46. #include <sys/time.h>
  47. #include <unistd.h>
  48. #include <utime.h>
  49. #endif
  50. #if defined(_WIN32) && \
  51. (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__MINGW32__))
  52. #include <io.h>
  53. #endif
  54. #if defined(__APPLE__)
  55. #include <mach-o/dyld.h>
  56. #endif
  57. #ifdef __QNX__
  58. #include <malloc.h> /* for malloc/free on QNX */
  59. #endif
  60. static bool cm_isspace(char c)
  61. {
  62. return ((c & 0x80) == 0) && isspace(c);
  63. }
  64. class cmSystemToolsFileTime
  65. {
  66. public:
  67. #if defined(_WIN32) && !defined(__CYGWIN__)
  68. FILETIME timeCreation;
  69. FILETIME timeLastAccess;
  70. FILETIME timeLastWrite;
  71. #else
  72. struct utimbuf timeBuf;
  73. #endif
  74. };
  75. #if !defined(HAVE_ENVIRON_NOT_REQUIRE_PROTOTYPE)
  76. // For GetEnvironmentVariables
  77. #if defined(_WIN32)
  78. extern __declspec(dllimport) char** environ;
  79. #else
  80. extern char** environ;
  81. #endif
  82. #endif
  83. #if defined(CMAKE_BUILD_WITH_CMAKE)
  84. static std::string cm_archive_entry_pathname(struct archive_entry* entry)
  85. {
  86. #if cmsys_STL_HAS_WSTRING
  87. return cmsys::Encoding::ToNarrow(archive_entry_pathname_w(entry));
  88. #else
  89. return archive_entry_pathname(entry);
  90. #endif
  91. }
  92. static int cm_archive_read_open_file(struct archive* a, const char* file,
  93. int block_size)
  94. {
  95. #if cmsys_STL_HAS_WSTRING
  96. std::wstring wfile = cmsys::Encoding::ToWide(file);
  97. return archive_read_open_filename_w(a, wfile.c_str(), block_size);
  98. #else
  99. return archive_read_open_filename(a, file, block_size);
  100. #endif
  101. }
  102. #endif
  103. #ifdef _WIN32
  104. class cmSystemToolsWindowsHandle
  105. {
  106. public:
  107. cmSystemToolsWindowsHandle(HANDLE h)
  108. : handle_(h)
  109. {
  110. }
  111. ~cmSystemToolsWindowsHandle()
  112. {
  113. if (this->handle_ != INVALID_HANDLE_VALUE) {
  114. CloseHandle(this->handle_);
  115. }
  116. }
  117. operator bool() const { return this->handle_ != INVALID_HANDLE_VALUE; }
  118. bool operator!() const { return this->handle_ == INVALID_HANDLE_VALUE; }
  119. operator HANDLE() const { return this->handle_; }
  120. private:
  121. HANDLE handle_;
  122. };
  123. #elif defined(__APPLE__)
  124. #include <crt_externs.h>
  125. #define environ (*_NSGetEnviron())
  126. #endif
  127. bool cmSystemTools::s_RunCommandHideConsole = false;
  128. bool cmSystemTools::s_DisableRunCommandOutput = false;
  129. bool cmSystemTools::s_ErrorOccured = false;
  130. bool cmSystemTools::s_FatalErrorOccured = false;
  131. bool cmSystemTools::s_DisableMessages = false;
  132. bool cmSystemTools::s_ForceUnixPaths = false;
  133. cmSystemTools::MessageCallback cmSystemTools::s_MessageCallback;
  134. cmSystemTools::OutputCallback cmSystemTools::s_StdoutCallback;
  135. cmSystemTools::OutputCallback cmSystemTools::s_StderrCallback;
  136. cmSystemTools::InterruptCallback cmSystemTools::s_InterruptCallback;
  137. void* cmSystemTools::s_MessageCallbackClientData;
  138. void* cmSystemTools::s_StdoutCallbackClientData;
  139. void* cmSystemTools::s_StderrCallbackClientData;
  140. void* cmSystemTools::s_InterruptCallbackClientData;
  141. // replace replace with with as many times as it shows up in source.
  142. // write the result into source.
  143. #if defined(_WIN32) && !defined(__CYGWIN__)
  144. void cmSystemTools::ExpandRegistryValues(std::string& source, KeyWOW64 view)
  145. {
  146. // Regular expression to match anything inside [...] that begins in HKEY.
  147. // Note that there is a special rule for regular expressions to match a
  148. // close square-bracket inside a list delimited by square brackets.
  149. // The "[^]]" part of this expression will match any character except
  150. // a close square-bracket. The ']' character must be the first in the
  151. // list of characters inside the [^...] block of the expression.
  152. cmsys::RegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  153. // check for black line or comment
  154. while (regEntry.find(source)) {
  155. // the arguments are the second match
  156. std::string key = regEntry.match(1);
  157. std::string val;
  158. if (ReadRegistryValue(key.c_str(), val, view)) {
  159. std::string reg = "[";
  160. reg += key + "]";
  161. cmSystemTools::ReplaceString(source, reg.c_str(), val.c_str());
  162. } else {
  163. std::string reg = "[";
  164. reg += key + "]";
  165. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  166. }
  167. }
  168. }
  169. #else
  170. void cmSystemTools::ExpandRegistryValues(std::string& source,
  171. KeyWOW64 /*unused*/)
  172. {
  173. cmsys::RegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  174. while (regEntry.find(source)) {
  175. // the arguments are the second match
  176. std::string key = regEntry.match(1);
  177. std::string val;
  178. std::string reg = "[";
  179. reg += key + "]";
  180. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  181. }
  182. }
  183. #endif
  184. std::string cmSystemTools::EscapeQuotes(const std::string& str)
  185. {
  186. std::string result;
  187. result.reserve(str.size());
  188. for (const char* ch = str.c_str(); *ch != '\0'; ++ch) {
  189. if (*ch == '"') {
  190. result += '\\';
  191. }
  192. result += *ch;
  193. }
  194. return result;
  195. }
  196. std::string cmSystemTools::HelpFileName(std::string name)
  197. {
  198. cmSystemTools::ReplaceString(name, "<", "");
  199. cmSystemTools::ReplaceString(name, ">", "");
  200. return name;
  201. }
  202. std::string cmSystemTools::TrimWhitespace(const std::string& s)
  203. {
  204. std::string::const_iterator start = s.begin();
  205. while (start != s.end() && cm_isspace(*start)) {
  206. ++start;
  207. }
  208. if (start == s.end()) {
  209. return "";
  210. }
  211. std::string::const_iterator stop = s.end() - 1;
  212. while (cm_isspace(*stop)) {
  213. --stop;
  214. }
  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. }
  299. std::cerr << m1 << std::endl << std::flush;
  300. }
  301. void cmSystemTools::ReportLastSystemError(const char* msg)
  302. {
  303. std::string m = msg;
  304. m += ": System Error: ";
  305. m += Superclass::GetLastSystemError();
  306. cmSystemTools::Error(m.c_str());
  307. }
  308. bool cmSystemTools::IsInternallyOn(const char* val)
  309. {
  310. if (!val) {
  311. return false;
  312. }
  313. std::basic_string<char> v = val;
  314. if (v.size() > 4) {
  315. return false;
  316. }
  317. for (std::basic_string<char>::iterator c = v.begin(); c != v.end(); c++) {
  318. *c = static_cast<char>(toupper(*c));
  319. }
  320. return v == "I_ON";
  321. }
  322. bool cmSystemTools::IsOn(const char* val)
  323. {
  324. if (!val) {
  325. return false;
  326. }
  327. size_t len = strlen(val);
  328. if (len > 4) {
  329. return false;
  330. }
  331. std::basic_string<char> v(val, len);
  332. static std::set<std::string> onValues;
  333. if (onValues.empty()) {
  334. onValues.insert("ON");
  335. onValues.insert("1");
  336. onValues.insert("YES");
  337. onValues.insert("TRUE");
  338. onValues.insert("Y");
  339. }
  340. for (std::basic_string<char>::iterator c = v.begin(); c != v.end(); c++) {
  341. *c = static_cast<char>(toupper(*c));
  342. }
  343. return (onValues.count(v) > 0);
  344. }
  345. bool cmSystemTools::IsNOTFOUND(const char* val)
  346. {
  347. if (strcmp(val, "NOTFOUND") == 0) {
  348. return true;
  349. }
  350. return cmHasLiteralSuffix(val, "-NOTFOUND");
  351. }
  352. bool cmSystemTools::IsOff(const char* val)
  353. {
  354. if (!val || !*val) {
  355. return true;
  356. }
  357. size_t len = strlen(val);
  358. // Try and avoid toupper() for large strings.
  359. if (len > 6) {
  360. return cmSystemTools::IsNOTFOUND(val);
  361. }
  362. static std::set<std::string> offValues;
  363. if (offValues.empty()) {
  364. offValues.insert("OFF");
  365. offValues.insert("0");
  366. offValues.insert("NO");
  367. offValues.insert("FALSE");
  368. offValues.insert("N");
  369. offValues.insert("IGNORE");
  370. }
  371. // Try and avoid toupper().
  372. std::basic_string<char> v(val, len);
  373. for (std::basic_string<char>::iterator c = v.begin(); c != v.end(); c++) {
  374. *c = static_cast<char>(toupper(*c));
  375. }
  376. return (offValues.count(v) > 0);
  377. }
  378. void cmSystemTools::ParseWindowsCommandLine(const char* command,
  379. std::vector<std::string>& args)
  380. {
  381. // See the MSDN document "Parsing C Command-Line Arguments" at
  382. // http://msdn2.microsoft.com/en-us/library/a1y7w461.aspx for rules
  383. // of parsing the windows command line.
  384. bool in_argument = false;
  385. bool in_quotes = false;
  386. int backslashes = 0;
  387. std::string arg;
  388. for (const char* c = command; *c; ++c) {
  389. if (*c == '\\') {
  390. ++backslashes;
  391. in_argument = true;
  392. } else if (*c == '"') {
  393. int backslash_pairs = backslashes >> 1;
  394. int backslash_escaped = backslashes & 1;
  395. arg.append(backslash_pairs, '\\');
  396. backslashes = 0;
  397. if (backslash_escaped) {
  398. /* An odd number of backslashes precede this quote.
  399. It is escaped. */
  400. arg.append(1, '"');
  401. } else {
  402. /* An even number of backslashes precede this quote.
  403. It is not escaped. */
  404. in_quotes = !in_quotes;
  405. }
  406. in_argument = true;
  407. } else {
  408. arg.append(backslashes, '\\');
  409. backslashes = 0;
  410. if (cm_isspace(*c)) {
  411. if (in_quotes) {
  412. arg.append(1, *c);
  413. } else if (in_argument) {
  414. args.push_back(arg);
  415. arg = "";
  416. in_argument = false;
  417. }
  418. } else {
  419. in_argument = true;
  420. arg.append(1, *c);
  421. }
  422. }
  423. }
  424. arg.append(backslashes, '\\');
  425. if (in_argument) {
  426. args.push_back(arg);
  427. }
  428. }
  429. class cmSystemToolsArgV
  430. {
  431. char** ArgV;
  432. public:
  433. cmSystemToolsArgV(char** argv)
  434. : ArgV(argv)
  435. {
  436. }
  437. ~cmSystemToolsArgV()
  438. {
  439. for (char** arg = this->ArgV; arg && *arg; ++arg) {
  440. free(*arg);
  441. }
  442. free(this->ArgV);
  443. }
  444. void Store(std::vector<std::string>& args) const
  445. {
  446. for (char** arg = this->ArgV; arg && *arg; ++arg) {
  447. args.push_back(*arg);
  448. }
  449. }
  450. };
  451. void cmSystemTools::ParseUnixCommandLine(const char* command,
  452. std::vector<std::string>& args)
  453. {
  454. // Invoke the underlying parser.
  455. cmSystemToolsArgV argv = cmsysSystem_Parse_CommandForUnix(command, 0);
  456. argv.Store(args);
  457. }
  458. std::vector<std::string> cmSystemTools::ParseArguments(const char* command)
  459. {
  460. std::vector<std::string> args;
  461. std::string arg;
  462. bool win_path = false;
  463. if ((command[0] != '/' && command[1] == ':' && command[2] == '\\') ||
  464. (command[0] == '\"' && command[1] != '/' && command[2] == ':' &&
  465. command[3] == '\\') ||
  466. (command[0] == '\'' && command[1] != '/' && command[2] == ':' &&
  467. command[3] == '\\') ||
  468. (command[0] == '\\' && command[1] == '\\')) {
  469. win_path = true;
  470. }
  471. // Split the command into an argv array.
  472. for (const char* c = command; *c;) {
  473. // Skip over whitespace.
  474. while (*c == ' ' || *c == '\t') {
  475. ++c;
  476. }
  477. arg = "";
  478. if (*c == '"') {
  479. // Parse a quoted argument.
  480. ++c;
  481. while (*c && *c != '"') {
  482. arg.append(1, *c);
  483. ++c;
  484. }
  485. if (*c) {
  486. ++c;
  487. }
  488. args.push_back(arg);
  489. } else if (*c == '\'') {
  490. // Parse a quoted argument.
  491. ++c;
  492. while (*c && *c != '\'') {
  493. arg.append(1, *c);
  494. ++c;
  495. }
  496. if (*c) {
  497. ++c;
  498. }
  499. args.push_back(arg);
  500. } else if (*c) {
  501. // Parse an unquoted argument.
  502. while (*c && *c != ' ' && *c != '\t') {
  503. if (*c == '\\' && !win_path) {
  504. ++c;
  505. if (*c) {
  506. arg.append(1, *c);
  507. ++c;
  508. }
  509. } else {
  510. arg.append(1, *c);
  511. ++c;
  512. }
  513. }
  514. args.push_back(arg);
  515. }
  516. }
  517. return args;
  518. }
  519. bool cmSystemTools::RunSingleCommand(std::vector<std::string> const& command,
  520. std::string* captureStdOut,
  521. std::string* captureStdErr, int* retVal,
  522. const char* dir, OutputOption outputflag,
  523. double timeout)
  524. {
  525. std::vector<const char*> argv;
  526. for (std::vector<std::string>::const_iterator a = command.begin();
  527. a != command.end(); ++a) {
  528. argv.push_back(a->c_str());
  529. }
  530. argv.push_back(CM_NULLPTR);
  531. cmsysProcess* cp = cmsysProcess_New();
  532. cmsysProcess_SetCommand(cp, &*argv.begin());
  533. cmsysProcess_SetWorkingDirectory(cp, dir);
  534. if (cmSystemTools::GetRunCommandHideConsole()) {
  535. cmsysProcess_SetOption(cp, cmsysProcess_Option_HideWindow, 1);
  536. }
  537. if (outputflag == OUTPUT_PASSTHROUGH) {
  538. cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDOUT, 1);
  539. cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDERR, 1);
  540. captureStdOut = CM_NULLPTR;
  541. captureStdErr = CM_NULLPTR;
  542. } else if (outputflag == OUTPUT_MERGE ||
  543. (captureStdErr && captureStdErr == captureStdOut)) {
  544. cmsysProcess_SetOption(cp, cmsysProcess_Option_MergeOutput, 1);
  545. captureStdErr = CM_NULLPTR;
  546. }
  547. assert(!captureStdErr || captureStdErr != captureStdOut);
  548. cmsysProcess_SetTimeout(cp, timeout);
  549. cmsysProcess_Execute(cp);
  550. std::vector<char> tempStdOut;
  551. std::vector<char> tempStdErr;
  552. char* data;
  553. int length;
  554. int pipe;
  555. if (outputflag != OUTPUT_PASSTHROUGH &&
  556. (captureStdOut || captureStdErr || outputflag != OUTPUT_NONE)) {
  557. while ((pipe = cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR)) >
  558. 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, CM_NULLPTR);
  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 == CM_NULLPTR) || (*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 != CM_NULLPTR && 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. }
  1558. if (pipe == cmsysProcess_Pipe_STDOUT) {
  1559. // Append to the stdout buffer.
  1560. std::vector<char>::size_type size = out.size();
  1561. out.insert(out.end(), data, data + length);
  1562. outiter = out.begin() + size;
  1563. } else if (pipe == cmsysProcess_Pipe_STDERR) {
  1564. // Append to the stderr buffer.
  1565. std::vector<char>::size_type size = err.size();
  1566. err.insert(err.end(), data, data + length);
  1567. erriter = err.begin() + size;
  1568. } else if (pipe == cmsysProcess_Pipe_None) {
  1569. // Both stdout and stderr pipes have broken. Return leftover data.
  1570. if (!out.empty()) {
  1571. line.append(&out[0], outiter - out.begin());
  1572. out.erase(out.begin(), out.end());
  1573. return cmsysProcess_Pipe_STDOUT;
  1574. }
  1575. if (!err.empty()) {
  1576. line.append(&err[0], erriter - err.begin());
  1577. err.erase(err.begin(), err.end());
  1578. return cmsysProcess_Pipe_STDERR;
  1579. }
  1580. return cmsysProcess_Pipe_None;
  1581. }
  1582. }
  1583. }
  1584. void cmSystemTools::DoNotInheritStdPipes()
  1585. {
  1586. #ifdef _WIN32
  1587. // Check to see if we are attached to a console
  1588. // if so, then do not stop the inherited pipes
  1589. // or stdout and stderr will not show up in dos
  1590. // shell windows
  1591. CONSOLE_SCREEN_BUFFER_INFO hOutInfo;
  1592. HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
  1593. if (GetConsoleScreenBufferInfo(hOut, &hOutInfo)) {
  1594. return;
  1595. }
  1596. {
  1597. HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
  1598. DuplicateHandle(GetCurrentProcess(), out, GetCurrentProcess(), &out, 0,
  1599. FALSE, DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  1600. SetStdHandle(STD_OUTPUT_HANDLE, out);
  1601. }
  1602. {
  1603. HANDLE out = GetStdHandle(STD_ERROR_HANDLE);
  1604. DuplicateHandle(GetCurrentProcess(), out, GetCurrentProcess(), &out, 0,
  1605. FALSE, DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  1606. SetStdHandle(STD_ERROR_HANDLE, out);
  1607. }
  1608. #endif
  1609. }
  1610. bool cmSystemTools::CopyFileTime(const char* fromFile, const char* toFile)
  1611. {
  1612. #if defined(_WIN32) && !defined(__CYGWIN__)
  1613. cmSystemToolsWindowsHandle hFrom = CreateFileW(
  1614. SystemTools::ConvertToWindowsExtendedPath(fromFile).c_str(), GENERIC_READ,
  1615. FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
  1616. cmSystemToolsWindowsHandle hTo = CreateFileW(
  1617. SystemTools::ConvertToWindowsExtendedPath(toFile).c_str(),
  1618. FILE_WRITE_ATTRIBUTES, 0, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
  1619. if (!hFrom || !hTo) {
  1620. return false;
  1621. }
  1622. FILETIME timeCreation;
  1623. FILETIME timeLastAccess;
  1624. FILETIME timeLastWrite;
  1625. if (!GetFileTime(hFrom, &timeCreation, &timeLastAccess, &timeLastWrite)) {
  1626. return false;
  1627. }
  1628. return SetFileTime(hTo, &timeCreation, &timeLastAccess, &timeLastWrite) != 0;
  1629. #else
  1630. struct stat fromStat;
  1631. if (stat(fromFile, &fromStat) < 0) {
  1632. return false;
  1633. }
  1634. struct utimbuf buf;
  1635. buf.actime = fromStat.st_atime;
  1636. buf.modtime = fromStat.st_mtime;
  1637. return utime(toFile, &buf) >= 0;
  1638. #endif
  1639. }
  1640. cmSystemToolsFileTime* cmSystemTools::FileTimeNew()
  1641. {
  1642. return new cmSystemToolsFileTime;
  1643. }
  1644. void cmSystemTools::FileTimeDelete(cmSystemToolsFileTime* t)
  1645. {
  1646. delete t;
  1647. }
  1648. bool cmSystemTools::FileTimeGet(const char* fname, cmSystemToolsFileTime* t)
  1649. {
  1650. #if defined(_WIN32) && !defined(__CYGWIN__)
  1651. cmSystemToolsWindowsHandle h = CreateFileW(
  1652. SystemTools::ConvertToWindowsExtendedPath(fname).c_str(), GENERIC_READ,
  1653. FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
  1654. if (!h) {
  1655. return false;
  1656. }
  1657. if (!GetFileTime(h, &t->timeCreation, &t->timeLastAccess,
  1658. &t->timeLastWrite)) {
  1659. return false;
  1660. }
  1661. #else
  1662. struct stat st;
  1663. if (stat(fname, &st) < 0) {
  1664. return false;
  1665. }
  1666. t->timeBuf.actime = st.st_atime;
  1667. t->timeBuf.modtime = st.st_mtime;
  1668. #endif
  1669. return true;
  1670. }
  1671. bool cmSystemTools::FileTimeSet(const char* fname, cmSystemToolsFileTime* t)
  1672. {
  1673. #if defined(_WIN32) && !defined(__CYGWIN__)
  1674. cmSystemToolsWindowsHandle h = CreateFileW(
  1675. SystemTools::ConvertToWindowsExtendedPath(fname).c_str(),
  1676. FILE_WRITE_ATTRIBUTES, 0, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
  1677. if (!h) {
  1678. return false;
  1679. }
  1680. return SetFileTime(h, &t->timeCreation, &t->timeLastAccess,
  1681. &t->timeLastWrite) != 0;
  1682. #else
  1683. return utime(fname, &t->timeBuf) >= 0;
  1684. #endif
  1685. }
  1686. #ifdef _WIN32
  1687. #ifndef CRYPT_SILENT
  1688. #define CRYPT_SILENT 0x40 /* Not defined by VS 6 version of header. */
  1689. #endif
  1690. static int WinCryptRandom(void* data, size_t size)
  1691. {
  1692. int result = 0;
  1693. HCRYPTPROV hProvider = 0;
  1694. if (CryptAcquireContextW(&hProvider, 0, 0, PROV_RSA_FULL,
  1695. CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {
  1696. result = CryptGenRandom(hProvider, (DWORD)size, (BYTE*)data) ? 1 : 0;
  1697. CryptReleaseContext(hProvider, 0);
  1698. }
  1699. return result;
  1700. }
  1701. #endif
  1702. unsigned int cmSystemTools::RandomSeed()
  1703. {
  1704. #if defined(_WIN32) && !defined(__CYGWIN__)
  1705. unsigned int seed = 0;
  1706. // Try using a real random source.
  1707. if (WinCryptRandom(&seed, sizeof(seed))) {
  1708. return seed;
  1709. }
  1710. // Fall back to the time and pid.
  1711. FILETIME ft;
  1712. GetSystemTimeAsFileTime(&ft);
  1713. unsigned int t1 = static_cast<unsigned int>(ft.dwHighDateTime);
  1714. unsigned int t2 = static_cast<unsigned int>(ft.dwLowDateTime);
  1715. unsigned int pid = static_cast<unsigned int>(GetCurrentProcessId());
  1716. return t1 ^ t2 ^ pid;
  1717. #else
  1718. union
  1719. {
  1720. unsigned int integer;
  1721. char bytes[sizeof(unsigned int)];
  1722. } seed;
  1723. // Try using a real random source.
  1724. cmsys::ifstream fin;
  1725. fin.rdbuf()->pubsetbuf(CM_NULLPTR, 0); // Unbuffered read.
  1726. fin.open("/dev/urandom");
  1727. if (fin.good() && fin.read(seed.bytes, sizeof(seed)) &&
  1728. fin.gcount() == sizeof(seed)) {
  1729. return seed.integer;
  1730. }
  1731. // Fall back to the time and pid.
  1732. struct timeval t;
  1733. gettimeofday(&t, CM_NULLPTR);
  1734. unsigned int pid = static_cast<unsigned int>(getpid());
  1735. unsigned int tv_sec = static_cast<unsigned int>(t.tv_sec);
  1736. unsigned int tv_usec = static_cast<unsigned int>(t.tv_usec);
  1737. // Since tv_usec never fills more than 11 bits we shift it to fill
  1738. // in the slow-changing high-order bits of tv_sec.
  1739. return tv_sec ^ (tv_usec << 21) ^ pid;
  1740. #endif
  1741. }
  1742. static std::string cmSystemToolsCMakeCommand;
  1743. static std::string cmSystemToolsCTestCommand;
  1744. static std::string cmSystemToolsCPackCommand;
  1745. static std::string cmSystemToolsCMakeCursesCommand;
  1746. static std::string cmSystemToolsCMakeGUICommand;
  1747. static std::string cmSystemToolsCMClDepsCommand;
  1748. static std::string cmSystemToolsCMakeRoot;
  1749. void cmSystemTools::FindCMakeResources(const char* argv0)
  1750. {
  1751. std::string exe_dir;
  1752. #if defined(_WIN32) && !defined(__CYGWIN__)
  1753. (void)argv0; // ignore this on windows
  1754. wchar_t modulepath[_MAX_PATH];
  1755. ::GetModuleFileNameW(NULL, modulepath, sizeof(modulepath));
  1756. exe_dir =
  1757. cmSystemTools::GetFilenamePath(cmsys::Encoding::ToNarrow(modulepath));
  1758. #elif defined(__APPLE__)
  1759. (void)argv0; // ignore this on OS X
  1760. #define CM_EXE_PATH_LOCAL_SIZE 16384
  1761. char exe_path_local[CM_EXE_PATH_LOCAL_SIZE];
  1762. #if defined(MAC_OS_X_VERSION_10_3) && !defined(MAC_OS_X_VERSION_10_4)
  1763. unsigned long exe_path_size = CM_EXE_PATH_LOCAL_SIZE;
  1764. #else
  1765. uint32_t exe_path_size = CM_EXE_PATH_LOCAL_SIZE;
  1766. #endif
  1767. #undef CM_EXE_PATH_LOCAL_SIZE
  1768. char* exe_path = exe_path_local;
  1769. if (_NSGetExecutablePath(exe_path, &exe_path_size) < 0) {
  1770. exe_path = (char*)malloc(exe_path_size);
  1771. _NSGetExecutablePath(exe_path, &exe_path_size);
  1772. }
  1773. exe_dir =
  1774. cmSystemTools::GetFilenamePath(cmSystemTools::GetRealPath(exe_path));
  1775. if (exe_path != exe_path_local) {
  1776. free(exe_path);
  1777. }
  1778. if (cmSystemTools::GetFilenameName(exe_dir) == "MacOS") {
  1779. // The executable is inside an application bundle.
  1780. // Look for ..<CMAKE_BIN_DIR> (install tree) and then fall back to
  1781. // ../../../bin (build tree).
  1782. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  1783. if (cmSystemTools::FileExists(exe_dir + CMAKE_BIN_DIR "/cmake")) {
  1784. exe_dir += CMAKE_BIN_DIR;
  1785. } else {
  1786. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  1787. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  1788. }
  1789. }
  1790. #else
  1791. std::string errorMsg;
  1792. std::string exe;
  1793. if (cmSystemTools::FindProgramPath(argv0, exe, errorMsg)) {
  1794. // remove symlinks
  1795. exe = cmSystemTools::GetRealPath(exe);
  1796. exe_dir = cmSystemTools::GetFilenamePath(exe);
  1797. } else {
  1798. // ???
  1799. }
  1800. #endif
  1801. cmSystemToolsCMakeCommand = exe_dir;
  1802. cmSystemToolsCMakeCommand += "/cmake";
  1803. cmSystemToolsCMakeCommand += cmSystemTools::GetExecutableExtension();
  1804. #ifndef CMAKE_BUILD_WITH_CMAKE
  1805. // The bootstrap cmake does not provide the other tools,
  1806. // so use the directory where they are about to be built.
  1807. exe_dir = CMAKE_BOOTSTRAP_BINARY_DIR "/bin";
  1808. #endif
  1809. cmSystemToolsCTestCommand = exe_dir;
  1810. cmSystemToolsCTestCommand += "/ctest";
  1811. cmSystemToolsCTestCommand += cmSystemTools::GetExecutableExtension();
  1812. cmSystemToolsCPackCommand = exe_dir;
  1813. cmSystemToolsCPackCommand += "/cpack";
  1814. cmSystemToolsCPackCommand += cmSystemTools::GetExecutableExtension();
  1815. cmSystemToolsCMakeGUICommand = exe_dir;
  1816. cmSystemToolsCMakeGUICommand += "/cmake-gui";
  1817. cmSystemToolsCMakeGUICommand += cmSystemTools::GetExecutableExtension();
  1818. if (!cmSystemTools::FileExists(cmSystemToolsCMakeGUICommand.c_str())) {
  1819. cmSystemToolsCMakeGUICommand = "";
  1820. }
  1821. cmSystemToolsCMakeCursesCommand = exe_dir;
  1822. cmSystemToolsCMakeCursesCommand += "/ccmake";
  1823. cmSystemToolsCMakeCursesCommand += cmSystemTools::GetExecutableExtension();
  1824. if (!cmSystemTools::FileExists(cmSystemToolsCMakeCursesCommand.c_str())) {
  1825. cmSystemToolsCMakeCursesCommand = "";
  1826. }
  1827. cmSystemToolsCMClDepsCommand = exe_dir;
  1828. cmSystemToolsCMClDepsCommand += "/cmcldeps";
  1829. cmSystemToolsCMClDepsCommand += cmSystemTools::GetExecutableExtension();
  1830. if (!cmSystemTools::FileExists(cmSystemToolsCMClDepsCommand.c_str())) {
  1831. cmSystemToolsCMClDepsCommand = "";
  1832. }
  1833. #ifdef CMAKE_BUILD_WITH_CMAKE
  1834. // Install tree has
  1835. // - "<prefix><CMAKE_BIN_DIR>/cmake"
  1836. // - "<prefix><CMAKE_DATA_DIR>"
  1837. if (cmHasSuffix(exe_dir, CMAKE_BIN_DIR)) {
  1838. std::string const prefix =
  1839. exe_dir.substr(0, exe_dir.size() - strlen(CMAKE_BIN_DIR));
  1840. cmSystemToolsCMakeRoot = prefix + CMAKE_DATA_DIR;
  1841. }
  1842. if (cmSystemToolsCMakeRoot.empty() ||
  1843. !cmSystemTools::FileExists(
  1844. (cmSystemToolsCMakeRoot + "/Modules/CMake.cmake").c_str())) {
  1845. // Build tree has "<build>/bin[/<config>]/cmake" and
  1846. // "<build>/CMakeFiles/CMakeSourceDir.txt".
  1847. std::string dir = cmSystemTools::GetFilenamePath(exe_dir);
  1848. std::string src_dir_txt = dir + "/CMakeFiles/CMakeSourceDir.txt";
  1849. cmsys::ifstream fin(src_dir_txt.c_str());
  1850. std::string src_dir;
  1851. if (fin && cmSystemTools::GetLineFromStream(fin, src_dir) &&
  1852. cmSystemTools::FileIsDirectory(src_dir)) {
  1853. cmSystemToolsCMakeRoot = src_dir;
  1854. } else {
  1855. dir = cmSystemTools::GetFilenamePath(dir);
  1856. src_dir_txt = dir + "/CMakeFiles/CMakeSourceDir.txt";
  1857. cmsys::ifstream fin2(src_dir_txt.c_str());
  1858. if (fin2 && cmSystemTools::GetLineFromStream(fin2, src_dir) &&
  1859. cmSystemTools::FileIsDirectory(src_dir)) {
  1860. cmSystemToolsCMakeRoot = src_dir;
  1861. }
  1862. }
  1863. }
  1864. #else
  1865. // Bootstrap build knows its source.
  1866. cmSystemToolsCMakeRoot = CMAKE_BOOTSTRAP_SOURCE_DIR;
  1867. #endif
  1868. }
  1869. std::string const& cmSystemTools::GetCMakeCommand()
  1870. {
  1871. return cmSystemToolsCMakeCommand;
  1872. }
  1873. std::string const& cmSystemTools::GetCTestCommand()
  1874. {
  1875. return cmSystemToolsCTestCommand;
  1876. }
  1877. std::string const& cmSystemTools::GetCPackCommand()
  1878. {
  1879. return cmSystemToolsCPackCommand;
  1880. }
  1881. std::string const& cmSystemTools::GetCMakeCursesCommand()
  1882. {
  1883. return cmSystemToolsCMakeCursesCommand;
  1884. }
  1885. std::string const& cmSystemTools::GetCMakeGUICommand()
  1886. {
  1887. return cmSystemToolsCMakeGUICommand;
  1888. }
  1889. std::string const& cmSystemTools::GetCMClDepsCommand()
  1890. {
  1891. return cmSystemToolsCMClDepsCommand;
  1892. }
  1893. std::string const& cmSystemTools::GetCMakeRoot()
  1894. {
  1895. return cmSystemToolsCMakeRoot;
  1896. }
  1897. void cmSystemTools::MakefileColorEcho(int color, const char* message,
  1898. bool newline, bool enabled)
  1899. {
  1900. // On some platforms (an MSYS prompt) cmsysTerminal may not be able
  1901. // to determine whether the stream is displayed on a tty. In this
  1902. // case it assumes no unless we tell it otherwise. Since we want
  1903. // color messages to be displayed for users we will assume yes.
  1904. // However, we can test for some situations when the answer is most
  1905. // likely no.
  1906. int assumeTTY = cmsysTerminal_Color_AssumeTTY;
  1907. if (cmSystemTools::HasEnv("DART_TEST_FROM_DART") ||
  1908. cmSystemTools::HasEnv("DASHBOARD_TEST_FROM_CTEST") ||
  1909. cmSystemTools::HasEnv("CTEST_INTERACTIVE_DEBUG_MODE")) {
  1910. // Avoid printing color escapes during dashboard builds.
  1911. assumeTTY = 0;
  1912. }
  1913. if (enabled && color != cmsysTerminal_Color_Normal) {
  1914. // Print with color. Delay the newline until later so that
  1915. // all color restore sequences appear before it.
  1916. cmsysTerminal_cfprintf(color | assumeTTY, stdout, "%s", message);
  1917. } else {
  1918. // Color is disabled. Print without color.
  1919. fprintf(stdout, "%s", message);
  1920. }
  1921. if (newline) {
  1922. fprintf(stdout, "\n");
  1923. }
  1924. }
  1925. bool cmSystemTools::GuessLibrarySOName(std::string const& fullPath,
  1926. std::string& soname)
  1927. {
  1928. // For ELF shared libraries use a real parser to get the correct
  1929. // soname.
  1930. #if defined(CMAKE_USE_ELF_PARSER)
  1931. cmELF elf(fullPath.c_str());
  1932. if (elf) {
  1933. return elf.GetSOName(soname);
  1934. }
  1935. #endif
  1936. // If the file is not a symlink we have no guess for its soname.
  1937. if (!cmSystemTools::FileIsSymlink(fullPath)) {
  1938. return false;
  1939. }
  1940. if (!cmSystemTools::ReadSymlink(fullPath, soname)) {
  1941. return false;
  1942. }
  1943. // If the symlink has a path component we have no guess for the soname.
  1944. if (!cmSystemTools::GetFilenamePath(soname).empty()) {
  1945. return false;
  1946. }
  1947. // If the symlink points at an extended version of the same name
  1948. // assume it is the soname.
  1949. std::string name = cmSystemTools::GetFilenameName(fullPath);
  1950. return soname.length() > name.length() &&
  1951. soname.compare(0, name.length(), name) == 0;
  1952. }
  1953. bool cmSystemTools::GuessLibraryInstallName(std::string const& fullPath,
  1954. std::string& soname)
  1955. {
  1956. #if defined(CMAKE_USE_MACH_PARSER)
  1957. cmMachO macho(fullPath.c_str());
  1958. if (macho) {
  1959. return macho.GetInstallName(soname);
  1960. }
  1961. #else
  1962. (void)fullPath;
  1963. (void)soname;
  1964. #endif
  1965. return false;
  1966. }
  1967. #if defined(CMAKE_USE_ELF_PARSER)
  1968. std::string::size_type cmSystemToolsFindRPath(std::string const& have,
  1969. std::string const& want)
  1970. {
  1971. std::string::size_type pos = 0;
  1972. while (pos < have.size()) {
  1973. // Look for an occurrence of the string.
  1974. std::string::size_type const beg = have.find(want, pos);
  1975. if (beg == std::string::npos) {
  1976. return std::string::npos;
  1977. }
  1978. // Make sure it is separated from preceding entries.
  1979. if (beg > 0 && have[beg - 1] != ':') {
  1980. pos = beg + 1;
  1981. continue;
  1982. }
  1983. // Make sure it is separated from following entries.
  1984. std::string::size_type const end = beg + want.size();
  1985. if (end < have.size() && have[end] != ':') {
  1986. pos = beg + 1;
  1987. continue;
  1988. }
  1989. // Return the position of the path portion.
  1990. return beg;
  1991. }
  1992. // The desired rpath was not found.
  1993. return std::string::npos;
  1994. }
  1995. #endif
  1996. #if defined(CMAKE_USE_ELF_PARSER)
  1997. struct cmSystemToolsRPathInfo
  1998. {
  1999. unsigned long Position;
  2000. unsigned long Size;
  2001. std::string Name;
  2002. std::string Value;
  2003. };
  2004. #endif
  2005. bool cmSystemTools::ChangeRPath(std::string const& file,
  2006. std::string const& oldRPath,
  2007. std::string const& newRPath, std::string* emsg,
  2008. bool* changed)
  2009. {
  2010. #if defined(CMAKE_USE_ELF_PARSER)
  2011. if (changed) {
  2012. *changed = false;
  2013. }
  2014. int rp_count = 0;
  2015. bool remove_rpath = true;
  2016. cmSystemToolsRPathInfo rp[2];
  2017. {
  2018. // Parse the ELF binary.
  2019. cmELF elf(file.c_str());
  2020. // Get the RPATH and RUNPATH entries from it.
  2021. int se_count = 0;
  2022. cmELF::StringEntry const* se[2] = { CM_NULLPTR, CM_NULLPTR };
  2023. const char* se_name[2] = { CM_NULLPTR, CM_NULLPTR };
  2024. if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
  2025. se[se_count] = se_rpath;
  2026. se_name[se_count] = "RPATH";
  2027. ++se_count;
  2028. }
  2029. if (cmELF::StringEntry const* se_runpath = elf.GetRunPath()) {
  2030. se[se_count] = se_runpath;
  2031. se_name[se_count] = "RUNPATH";
  2032. ++se_count;
  2033. }
  2034. if (se_count == 0) {
  2035. if (newRPath.empty()) {
  2036. // The new rpath is empty and there is no rpath anyway so it is
  2037. // okay.
  2038. return true;
  2039. }
  2040. if (emsg) {
  2041. *emsg = "No valid ELF RPATH or RUNPATH entry exists in the file; ";
  2042. *emsg += elf.GetErrorMessage();
  2043. }
  2044. return false;
  2045. }
  2046. for (int i = 0; i < se_count; ++i) {
  2047. // If both RPATH and RUNPATH refer to the same string literal it
  2048. // needs to be changed only once.
  2049. if (rp_count && rp[0].Position == se[i]->Position) {
  2050. continue;
  2051. }
  2052. // Make sure the current rpath contains the old rpath.
  2053. std::string::size_type pos =
  2054. cmSystemToolsFindRPath(se[i]->Value, oldRPath);
  2055. if (pos == std::string::npos) {
  2056. // If it contains the new rpath instead then it is okay.
  2057. if (cmSystemToolsFindRPath(se[i]->Value, newRPath) !=
  2058. std::string::npos) {
  2059. remove_rpath = false;
  2060. continue;
  2061. }
  2062. if (emsg) {
  2063. std::ostringstream e;
  2064. /* clang-format off */
  2065. e << "The current " << se_name[i] << " is:\n"
  2066. << " " << se[i]->Value << "\n"
  2067. << "which does not contain:\n"
  2068. << " " << oldRPath << "\n"
  2069. << "as was expected.";
  2070. /* clang-format on */
  2071. *emsg = e.str();
  2072. }
  2073. return false;
  2074. }
  2075. // Store information about the entry in the file.
  2076. rp[rp_count].Position = se[i]->Position;
  2077. rp[rp_count].Size = se[i]->Size;
  2078. rp[rp_count].Name = se_name[i];
  2079. std::string::size_type prefix_len = pos;
  2080. // If oldRPath was at the end of the file's RPath, and newRPath is empty,
  2081. // we should remove the unnecessary ':' at the end.
  2082. if (newRPath.empty() && pos > 0 && se[i]->Value[pos - 1] == ':' &&
  2083. pos + oldRPath.length() == se[i]->Value.length()) {
  2084. prefix_len--;
  2085. }
  2086. // Construct the new value which preserves the part of the path
  2087. // not being changed.
  2088. rp[rp_count].Value = se[i]->Value.substr(0, prefix_len);
  2089. rp[rp_count].Value += newRPath;
  2090. rp[rp_count].Value +=
  2091. se[i]->Value.substr(pos + oldRPath.length(), oldRPath.npos);
  2092. if (!rp[rp_count].Value.empty()) {
  2093. remove_rpath = false;
  2094. }
  2095. // Make sure there is enough room to store the new rpath and at
  2096. // least one null terminator.
  2097. if (rp[rp_count].Size < rp[rp_count].Value.length() + 1) {
  2098. if (emsg) {
  2099. *emsg = "The replacement path is too long for the ";
  2100. *emsg += se_name[i];
  2101. *emsg += " entry.";
  2102. }
  2103. return false;
  2104. }
  2105. // This entry is ready for update.
  2106. ++rp_count;
  2107. }
  2108. }
  2109. // If no runtime path needs to be changed, we are done.
  2110. if (rp_count == 0) {
  2111. return true;
  2112. }
  2113. // If the resulting rpath is empty, just remove the entire entry instead.
  2114. if (remove_rpath) {
  2115. return cmSystemTools::RemoveRPath(file, emsg, changed);
  2116. }
  2117. {
  2118. // Open the file for update.
  2119. cmsys::ofstream f(file.c_str(),
  2120. std::ios::in | std::ios::out | std::ios::binary);
  2121. if (!f) {
  2122. if (emsg) {
  2123. *emsg = "Error opening file for update.";
  2124. }
  2125. return false;
  2126. }
  2127. // Store the new RPATH and RUNPATH strings.
  2128. for (int i = 0; i < rp_count; ++i) {
  2129. // Seek to the RPATH position.
  2130. if (!f.seekp(rp[i].Position)) {
  2131. if (emsg) {
  2132. *emsg = "Error seeking to ";
  2133. *emsg += rp[i].Name;
  2134. *emsg += " position.";
  2135. }
  2136. return false;
  2137. }
  2138. // Write the new rpath. Follow it with enough null terminators to
  2139. // fill the string table entry.
  2140. f << rp[i].Value;
  2141. for (unsigned long j = rp[i].Value.length(); j < rp[i].Size; ++j) {
  2142. f << '\0';
  2143. }
  2144. // Make sure it wrote correctly.
  2145. if (!f) {
  2146. if (emsg) {
  2147. *emsg = "Error writing the new ";
  2148. *emsg += rp[i].Name;
  2149. *emsg += " string to the file.";
  2150. }
  2151. return false;
  2152. }
  2153. }
  2154. }
  2155. // Everything was updated successfully.
  2156. if (changed) {
  2157. *changed = true;
  2158. }
  2159. return true;
  2160. #else
  2161. (void)file;
  2162. (void)oldRPath;
  2163. (void)newRPath;
  2164. (void)emsg;
  2165. (void)changed;
  2166. return false;
  2167. #endif
  2168. }
  2169. bool cmSystemTools::VersionCompare(cmSystemTools::CompareOp op,
  2170. const char* lhss, const char* rhss)
  2171. {
  2172. const char* endl = lhss;
  2173. const char* endr = rhss;
  2174. unsigned long lhs, rhs;
  2175. while (((*endl >= '0') && (*endl <= '9')) ||
  2176. ((*endr >= '0') && (*endr <= '9'))) {
  2177. // Do component-wise comparison.
  2178. lhs = strtoul(endl, const_cast<char**>(&endl), 10);
  2179. rhs = strtoul(endr, const_cast<char**>(&endr), 10);
  2180. if (lhs < rhs) {
  2181. // lhs < rhs, so true if operation is LESS
  2182. return (op & cmSystemTools::OP_LESS) != 0;
  2183. }
  2184. if (lhs > rhs) {
  2185. // lhs > rhs, so true if operation is GREATER
  2186. return (op & cmSystemTools::OP_GREATER) != 0;
  2187. }
  2188. if (*endr == '.') {
  2189. endr++;
  2190. }
  2191. if (*endl == '.') {
  2192. endl++;
  2193. }
  2194. }
  2195. // lhs == rhs, so true if operation is EQUAL
  2196. return (op & cmSystemTools::OP_EQUAL) != 0;
  2197. }
  2198. bool cmSystemTools::VersionCompareEqual(std::string const& lhs,
  2199. std::string const& rhs)
  2200. {
  2201. return cmSystemTools::VersionCompare(cmSystemTools::OP_EQUAL, lhs.c_str(),
  2202. rhs.c_str());
  2203. }
  2204. bool cmSystemTools::VersionCompareGreater(std::string const& lhs,
  2205. std::string const& rhs)
  2206. {
  2207. return cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER, lhs.c_str(),
  2208. rhs.c_str());
  2209. }
  2210. bool cmSystemTools::VersionCompareGreaterEq(std::string const& lhs,
  2211. std::string const& rhs)
  2212. {
  2213. return cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
  2214. lhs.c_str(), rhs.c_str());
  2215. }
  2216. static size_t cm_strverscmp_find_first_difference_or_end(const char* lhs,
  2217. const char* rhs)
  2218. {
  2219. size_t i = 0;
  2220. /* Step forward until we find a difference or both strings end together.
  2221. The difference may lie on the null-terminator of one string. */
  2222. while (lhs[i] == rhs[i] && lhs[i] != 0) {
  2223. ++i;
  2224. }
  2225. return i;
  2226. }
  2227. static size_t cm_strverscmp_find_digits_begin(const char* s, size_t i)
  2228. {
  2229. /* Step back until we are not preceded by a digit. */
  2230. while (i > 0 && isdigit(s[i - 1])) {
  2231. --i;
  2232. }
  2233. return i;
  2234. }
  2235. static size_t cm_strverscmp_find_digits_end(const char* s, size_t i)
  2236. {
  2237. /* Step forward over digits. */
  2238. while (isdigit(s[i])) {
  2239. ++i;
  2240. }
  2241. return i;
  2242. }
  2243. static size_t cm_strverscmp_count_leading_zeros(const char* s, size_t b)
  2244. {
  2245. size_t i = b;
  2246. /* Step forward over zeros that are followed by another digit. */
  2247. while (s[i] == '0' && isdigit(s[i + 1])) {
  2248. ++i;
  2249. }
  2250. return i - b;
  2251. }
  2252. static int cm_strverscmp(const char* lhs, const char* rhs)
  2253. {
  2254. size_t const i = cm_strverscmp_find_first_difference_or_end(lhs, rhs);
  2255. if (lhs[i] != rhs[i]) {
  2256. /* The strings differ starting at 'i'. Check for a digit sequence. */
  2257. size_t const b = cm_strverscmp_find_digits_begin(lhs, i);
  2258. if (b != i || (isdigit(lhs[i]) && isdigit(rhs[i]))) {
  2259. /* A digit sequence starts at 'b', preceding or at 'i'. */
  2260. /* Look for leading zeros, implying a leading decimal point. */
  2261. size_t const lhs_zeros = cm_strverscmp_count_leading_zeros(lhs, b);
  2262. size_t const rhs_zeros = cm_strverscmp_count_leading_zeros(rhs, b);
  2263. if (lhs_zeros != rhs_zeros) {
  2264. /* The side with more leading zeros orders first. */
  2265. return rhs_zeros > lhs_zeros ? 1 : -1;
  2266. }
  2267. if (lhs_zeros == 0) {
  2268. /* No leading zeros; compare digit sequence lengths. */
  2269. size_t const lhs_end = cm_strverscmp_find_digits_end(lhs, i);
  2270. size_t const rhs_end = cm_strverscmp_find_digits_end(rhs, i);
  2271. if (lhs_end != rhs_end) {
  2272. /* The side with fewer digits orders first. */
  2273. return lhs_end > rhs_end ? 1 : -1;
  2274. }
  2275. }
  2276. }
  2277. }
  2278. /* Ordering was not decided by digit sequence lengths; compare bytes. */
  2279. return lhs[i] - rhs[i];
  2280. }
  2281. int cmSystemTools::strverscmp(std::string const& lhs, std::string const& rhs)
  2282. {
  2283. return cm_strverscmp(lhs.c_str(), rhs.c_str());
  2284. }
  2285. bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg,
  2286. bool* removed)
  2287. {
  2288. #if defined(CMAKE_USE_ELF_PARSER)
  2289. if (removed) {
  2290. *removed = false;
  2291. }
  2292. int zeroCount = 0;
  2293. unsigned long zeroPosition[2] = { 0, 0 };
  2294. unsigned long zeroSize[2] = { 0, 0 };
  2295. unsigned long bytesBegin = 0;
  2296. std::vector<char> bytes;
  2297. {
  2298. // Parse the ELF binary.
  2299. cmELF elf(file.c_str());
  2300. // Get the RPATH and RUNPATH entries from it and sort them by index
  2301. // in the dynamic section header.
  2302. int se_count = 0;
  2303. cmELF::StringEntry const* se[2] = { CM_NULLPTR, CM_NULLPTR };
  2304. if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
  2305. se[se_count++] = se_rpath;
  2306. }
  2307. if (cmELF::StringEntry const* se_runpath = elf.GetRunPath()) {
  2308. se[se_count++] = se_runpath;
  2309. }
  2310. if (se_count == 0) {
  2311. // There is no RPATH or RUNPATH anyway.
  2312. return true;
  2313. }
  2314. if (se_count == 2 && se[1]->IndexInSection < se[0]->IndexInSection) {
  2315. std::swap(se[0], se[1]);
  2316. }
  2317. // Obtain a copy of the dynamic entries
  2318. cmELF::DynamicEntryList dentries = elf.GetDynamicEntries();
  2319. if (dentries.empty()) {
  2320. // This should happen only for invalid ELF files where a DT_NULL
  2321. // appears before the end of the table.
  2322. if (emsg) {
  2323. *emsg = "DYNAMIC section contains a DT_NULL before the end.";
  2324. }
  2325. return false;
  2326. }
  2327. // Save information about the string entries to be zeroed.
  2328. zeroCount = se_count;
  2329. for (int i = 0; i < se_count; ++i) {
  2330. zeroPosition[i] = se[i]->Position;
  2331. zeroSize[i] = se[i]->Size;
  2332. }
  2333. // Get size of one DYNAMIC entry
  2334. unsigned long const sizeof_dentry =
  2335. elf.GetDynamicEntryPosition(1) - elf.GetDynamicEntryPosition(0);
  2336. // Adjust the entry list as necessary to remove the run path
  2337. unsigned long entriesErased = 0;
  2338. for (cmELF::DynamicEntryList::iterator it = dentries.begin();
  2339. it != dentries.end();) {
  2340. if (it->first == cmELF::TagRPath || it->first == cmELF::TagRunPath) {
  2341. it = dentries.erase(it);
  2342. entriesErased++;
  2343. continue;
  2344. } else {
  2345. if (cmELF::TagMipsRldMapRel != 0 &&
  2346. it->first == cmELF::TagMipsRldMapRel) {
  2347. // Background: debuggers need to know the "linker map" which contains
  2348. // the addresses each dynamic object is loaded at. Most arches use
  2349. // the DT_DEBUG tag which the dynamic linker writes to (directly) and
  2350. // contain the location of the linker map, however on MIPS the
  2351. // .dynamic section is always read-only so this is not possible. MIPS
  2352. // objects instead contain a DT_MIPS_RLD_MAP tag which contains the
  2353. // address where the dyanmic linker will write to (an indirect
  2354. // version of DT_DEBUG). Since this doesn't work when using PIE, a
  2355. // relative equivalent was created - DT_MIPS_RLD_MAP_REL. Since this
  2356. // version contains a relative offset, moving it changes the
  2357. // calculated address. This may cause the dyanmic linker to write
  2358. // into memory it should not be changing.
  2359. //
  2360. // To fix this, we adjust the value of DT_MIPS_RLD_MAP_REL here. If
  2361. // we move it up by n bytes, we add n bytes to the value of this tag.
  2362. it->second += entriesErased * sizeof_dentry;
  2363. }
  2364. it++;
  2365. }
  2366. }
  2367. // Encode new entries list
  2368. bytes = elf.EncodeDynamicEntries(dentries);
  2369. bytesBegin = elf.GetDynamicEntryPosition(0);
  2370. }
  2371. // Open the file for update.
  2372. cmsys::ofstream f(file.c_str(),
  2373. std::ios::in | std::ios::out | std::ios::binary);
  2374. if (!f) {
  2375. if (emsg) {
  2376. *emsg = "Error opening file for update.";
  2377. }
  2378. return false;
  2379. }
  2380. // Write the new DYNAMIC table header.
  2381. if (!f.seekp(bytesBegin)) {
  2382. if (emsg) {
  2383. *emsg = "Error seeking to DYNAMIC table header for RPATH.";
  2384. }
  2385. return false;
  2386. }
  2387. if (!f.write(&bytes[0], bytes.size())) {
  2388. if (emsg) {
  2389. *emsg = "Error replacing DYNAMIC table header.";
  2390. }
  2391. return false;
  2392. }
  2393. // Fill the RPATH and RUNPATH strings with zero bytes.
  2394. for (int i = 0; i < zeroCount; ++i) {
  2395. if (!f.seekp(zeroPosition[i])) {
  2396. if (emsg) {
  2397. *emsg = "Error seeking to RPATH position.";
  2398. }
  2399. return false;
  2400. }
  2401. for (unsigned long j = 0; j < zeroSize[i]; ++j) {
  2402. f << '\0';
  2403. }
  2404. if (!f) {
  2405. if (emsg) {
  2406. *emsg = "Error writing the empty rpath string to the file.";
  2407. }
  2408. return false;
  2409. }
  2410. }
  2411. // Everything was updated successfully.
  2412. if (removed) {
  2413. *removed = true;
  2414. }
  2415. return true;
  2416. #else
  2417. (void)file;
  2418. (void)emsg;
  2419. (void)removed;
  2420. return false;
  2421. #endif
  2422. }
  2423. bool cmSystemTools::CheckRPath(std::string const& file,
  2424. std::string const& newRPath)
  2425. {
  2426. #if defined(CMAKE_USE_ELF_PARSER)
  2427. // Parse the ELF binary.
  2428. cmELF elf(file.c_str());
  2429. // Get the RPATH or RUNPATH entry from it.
  2430. cmELF::StringEntry const* se = elf.GetRPath();
  2431. if (!se) {
  2432. se = elf.GetRunPath();
  2433. }
  2434. // Make sure the current rpath contains the new rpath.
  2435. if (newRPath.empty()) {
  2436. if (!se) {
  2437. return true;
  2438. }
  2439. } else {
  2440. if (se &&
  2441. cmSystemToolsFindRPath(se->Value, newRPath) != std::string::npos) {
  2442. return true;
  2443. }
  2444. }
  2445. return false;
  2446. #else
  2447. (void)file;
  2448. (void)newRPath;
  2449. return false;
  2450. #endif
  2451. }
  2452. bool cmSystemTools::RepeatedRemoveDirectory(const char* dir)
  2453. {
  2454. // Windows sometimes locks files temporarily so try a few times.
  2455. for (int i = 0; i < 10; ++i) {
  2456. if (cmSystemTools::RemoveADirectory(dir)) {
  2457. return true;
  2458. }
  2459. cmSystemTools::Delay(100);
  2460. }
  2461. return false;
  2462. }
  2463. std::vector<std::string> cmSystemTools::tokenize(const std::string& str,
  2464. const std::string& sep)
  2465. {
  2466. std::vector<std::string> tokens;
  2467. std::string::size_type tokend = 0;
  2468. do {
  2469. std::string::size_type tokstart = str.find_first_not_of(sep, tokend);
  2470. if (tokstart == std::string::npos) {
  2471. break; // no more tokens
  2472. }
  2473. tokend = str.find_first_of(sep, tokstart);
  2474. if (tokend == std::string::npos) {
  2475. tokens.push_back(str.substr(tokstart));
  2476. } else {
  2477. tokens.push_back(str.substr(tokstart, tokend - tokstart));
  2478. }
  2479. } while (tokend != std::string::npos);
  2480. if (tokens.empty()) {
  2481. tokens.push_back("");
  2482. }
  2483. return tokens;
  2484. }
  2485. bool cmSystemTools::StringToLong(const char* str, long* value)
  2486. {
  2487. errno = 0;
  2488. char* endp;
  2489. *value = strtol(str, &endp, 10);
  2490. return (*endp == '\0') && (endp != str) && (errno == 0);
  2491. }
  2492. bool cmSystemTools::StringToULong(const char* str, unsigned long* value)
  2493. {
  2494. errno = 0;
  2495. char* endp;
  2496. *value = strtoul(str, &endp, 10);
  2497. return (*endp == '\0') && (endp != str) && (errno == 0);
  2498. }