cmSystemTools.cxx 80 KB

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