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. #if defined(CMAKE_BUILD_WITH_CMAKE)
  7. #include "cmArchiveWrite.h"
  8. #include "cmLocale.h"
  9. #include <cm_libarchive.h>
  10. #ifndef __LA_INT64_T
  11. #define __LA_INT64_T la_int64_t
  12. #endif
  13. #endif
  14. #if defined(CMAKE_BUILD_WITH_CMAKE)
  15. #include "cmCryptoHash.h"
  16. #endif
  17. #if defined(CMAKE_USE_ELF_PARSER)
  18. #include "cmELF.h"
  19. #endif
  20. #if defined(CMAKE_USE_MACH_PARSER)
  21. #include "cmMachO.h"
  22. #endif
  23. #include <algorithm>
  24. #include <assert.h>
  25. #include <cmsys/Directory.hxx>
  26. #include <cmsys/Encoding.hxx>
  27. #include <cmsys/FStream.hxx>
  28. #include <cmsys/RegularExpression.hxx>
  29. #include <cmsys/System.h>
  30. #include <cmsys/SystemTools.hxx>
  31. #include <cmsys/Terminal.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 <sys/stat.h>
  41. #include <time.h>
  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. // Visual Studio 7 puts these characters in the output of its
  564. // build process.
  565. for (int i = 0; i < length; ++i) {
  566. if (data[i] == '\0') {
  567. data[i] = ' ';
  568. }
  569. }
  570. if (pipe == cmsysProcess_Pipe_STDOUT) {
  571. if (outputflag != OUTPUT_NONE) {
  572. processOutput.DecodeText(data, length, strdata, 1);
  573. cmSystemTools::Stdout(strdata.c_str(), strdata.size());
  574. }
  575. if (captureStdOut) {
  576. tempStdOut.insert(tempStdOut.end(), data, data + length);
  577. }
  578. } else if (pipe == cmsysProcess_Pipe_STDERR) {
  579. if (outputflag != OUTPUT_NONE) {
  580. processOutput.DecodeText(data, length, strdata, 2);
  581. cmSystemTools::Stderr(strdata.c_str(), strdata.size());
  582. }
  583. if (captureStdErr) {
  584. tempStdErr.insert(tempStdErr.end(), data, data + length);
  585. }
  586. }
  587. }
  588. if (outputflag != OUTPUT_NONE) {
  589. processOutput.DecodeText(std::string(), strdata, 1);
  590. if (!strdata.empty()) {
  591. cmSystemTools::Stdout(strdata.c_str(), strdata.size());
  592. }
  593. processOutput.DecodeText(std::string(), strdata, 2);
  594. if (!strdata.empty()) {
  595. cmSystemTools::Stderr(strdata.c_str(), strdata.size());
  596. }
  597. }
  598. }
  599. cmsysProcess_WaitForExit(cp, CM_NULLPTR);
  600. if (captureStdOut) {
  601. captureStdOut->assign(tempStdOut.begin(), tempStdOut.end());
  602. processOutput.DecodeText(*captureStdOut, *captureStdOut);
  603. }
  604. if (captureStdErr) {
  605. captureStdErr->assign(tempStdErr.begin(), tempStdErr.end());
  606. processOutput.DecodeText(*captureStdErr, *captureStdErr);
  607. }
  608. bool result = true;
  609. if (cmsysProcess_GetState(cp) == cmsysProcess_State_Exited) {
  610. if (retVal) {
  611. *retVal = cmsysProcess_GetExitValue(cp);
  612. } else {
  613. if (cmsysProcess_GetExitValue(cp) != 0) {
  614. result = false;
  615. }
  616. }
  617. } else if (cmsysProcess_GetState(cp) == cmsysProcess_State_Exception) {
  618. const char* exception_str = cmsysProcess_GetExceptionString(cp);
  619. if (outputflag != OUTPUT_NONE) {
  620. std::cerr << exception_str << std::endl;
  621. }
  622. if (captureStdErr) {
  623. captureStdErr->append(exception_str, strlen(exception_str));
  624. }
  625. result = false;
  626. } else if (cmsysProcess_GetState(cp) == cmsysProcess_State_Error) {
  627. const char* error_str = cmsysProcess_GetErrorString(cp);
  628. if (outputflag != OUTPUT_NONE) {
  629. std::cerr << error_str << std::endl;
  630. }
  631. if (captureStdErr) {
  632. captureStdErr->append(error_str, strlen(error_str));
  633. }
  634. result = false;
  635. } else if (cmsysProcess_GetState(cp) == cmsysProcess_State_Expired) {
  636. const char* error_str = "Process terminated due to timeout\n";
  637. if (outputflag != OUTPUT_NONE) {
  638. std::cerr << error_str << std::endl;
  639. }
  640. if (captureStdErr) {
  641. captureStdErr->append(error_str, strlen(error_str));
  642. }
  643. result = false;
  644. }
  645. cmsysProcess_Delete(cp);
  646. return result;
  647. }
  648. bool cmSystemTools::RunSingleCommand(const char* command,
  649. std::string* captureStdOut,
  650. std::string* captureStdErr, int* retVal,
  651. const char* dir, OutputOption outputflag,
  652. double timeout)
  653. {
  654. if (s_DisableRunCommandOutput) {
  655. outputflag = OUTPUT_NONE;
  656. }
  657. std::vector<std::string> args = cmSystemTools::ParseArguments(command);
  658. if (args.empty()) {
  659. return false;
  660. }
  661. return cmSystemTools::RunSingleCommand(args, captureStdOut, captureStdErr,
  662. retVal, dir, outputflag, timeout);
  663. }
  664. std::string cmSystemTools::PrintSingleCommand(
  665. std::vector<std::string> const& command)
  666. {
  667. if (command.empty()) {
  668. return std::string();
  669. }
  670. return cmWrap('"', command, '"', " ");
  671. }
  672. bool cmSystemTools::DoesFileExistWithExtensions(
  673. const char* name, const std::vector<std::string>& headerExts)
  674. {
  675. std::string hname;
  676. for (std::vector<std::string>::const_iterator ext = headerExts.begin();
  677. ext != headerExts.end(); ++ext) {
  678. hname = name;
  679. hname += ".";
  680. hname += *ext;
  681. if (cmSystemTools::FileExists(hname.c_str())) {
  682. return true;
  683. }
  684. }
  685. return false;
  686. }
  687. std::string cmSystemTools::FileExistsInParentDirectories(const char* fname,
  688. const char* directory,
  689. const char* toplevel)
  690. {
  691. std::string file = fname;
  692. cmSystemTools::ConvertToUnixSlashes(file);
  693. std::string dir = directory;
  694. cmSystemTools::ConvertToUnixSlashes(dir);
  695. std::string prevDir;
  696. while (dir != prevDir) {
  697. std::string path = dir + "/" + file;
  698. if (cmSystemTools::FileExists(path.c_str())) {
  699. return path;
  700. }
  701. if (dir.size() < strlen(toplevel)) {
  702. break;
  703. }
  704. prevDir = dir;
  705. dir = cmSystemTools::GetParentDirectory(dir);
  706. }
  707. return "";
  708. }
  709. bool cmSystemTools::cmCopyFile(const char* source, const char* destination)
  710. {
  711. return Superclass::CopyFileAlways(source, destination);
  712. }
  713. bool cmSystemTools::CopyFileIfDifferent(const char* source,
  714. const char* destination)
  715. {
  716. return Superclass::CopyFileIfDifferent(source, destination);
  717. }
  718. #ifdef _WIN32
  719. cmSystemTools::WindowsFileRetry cmSystemTools::GetWindowsFileRetry()
  720. {
  721. static WindowsFileRetry retry = { 0, 0 };
  722. if (!retry.Count) {
  723. unsigned int data[2] = { 0, 0 };
  724. HKEY const keys[2] = { HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE };
  725. wchar_t const* const values[2] = { L"FilesystemRetryCount",
  726. L"FilesystemRetryDelay" };
  727. for (int k = 0; k < 2; ++k) {
  728. HKEY hKey;
  729. if (RegOpenKeyExW(keys[k], L"Software\\Kitware\\CMake\\Config", 0,
  730. KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS) {
  731. for (int v = 0; v < 2; ++v) {
  732. DWORD dwData, dwType, dwSize = 4;
  733. if (!data[v] &&
  734. RegQueryValueExW(hKey, values[v], 0, &dwType, (BYTE*)&dwData,
  735. &dwSize) == ERROR_SUCCESS &&
  736. dwType == REG_DWORD && dwSize == 4) {
  737. data[v] = static_cast<unsigned int>(dwData);
  738. }
  739. }
  740. RegCloseKey(hKey);
  741. }
  742. }
  743. retry.Count = data[0] ? data[0] : 5;
  744. retry.Delay = data[1] ? data[1] : 500;
  745. }
  746. return retry;
  747. }
  748. #endif
  749. bool cmSystemTools::RenameFile(const char* oldname, const char* newname)
  750. {
  751. #ifdef _WIN32
  752. #ifndef INVALID_FILE_ATTRIBUTES
  753. #define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  754. #endif
  755. /* Windows MoveFileEx may not replace read-only or in-use files. If it
  756. fails then remove the read-only attribute from any existing destination.
  757. Try multiple times since we may be racing against another process
  758. creating/opening the destination file just before our MoveFileEx. */
  759. WindowsFileRetry retry = cmSystemTools::GetWindowsFileRetry();
  760. while (
  761. !MoveFileExW(SystemTools::ConvertToWindowsExtendedPath(oldname).c_str(),
  762. SystemTools::ConvertToWindowsExtendedPath(newname).c_str(),
  763. MOVEFILE_REPLACE_EXISTING) &&
  764. --retry.Count) {
  765. DWORD last_error = GetLastError();
  766. // Try again only if failure was due to access/sharing permissions.
  767. if (last_error != ERROR_ACCESS_DENIED &&
  768. last_error != ERROR_SHARING_VIOLATION) {
  769. return false;
  770. }
  771. DWORD attrs = GetFileAttributesW(
  772. SystemTools::ConvertToWindowsExtendedPath(newname).c_str());
  773. if ((attrs != INVALID_FILE_ATTRIBUTES) &&
  774. (attrs & FILE_ATTRIBUTE_READONLY)) {
  775. // Remove the read-only attribute from the destination file.
  776. SetFileAttributesW(
  777. SystemTools::ConvertToWindowsExtendedPath(newname).c_str(),
  778. attrs & ~FILE_ATTRIBUTE_READONLY);
  779. } else {
  780. // The file may be temporarily in use so wait a bit.
  781. cmSystemTools::Delay(retry.Delay);
  782. }
  783. }
  784. return retry.Count > 0;
  785. #else
  786. /* On UNIX we have an OS-provided call to do this atomically. */
  787. return rename(oldname, newname) == 0;
  788. #endif
  789. }
  790. bool cmSystemTools::ComputeFileMD5(const std::string& source, char* md5out)
  791. {
  792. #if defined(CMAKE_BUILD_WITH_CMAKE)
  793. cmCryptoHash md5(cmCryptoHash::AlgoMD5);
  794. std::string const str = md5.HashFile(source);
  795. strncpy(md5out, str.c_str(), 32);
  796. return !str.empty();
  797. #else
  798. (void)source;
  799. (void)md5out;
  800. cmSystemTools::Message("md5sum not supported in bootstrapping mode",
  801. "Error");
  802. return false;
  803. #endif
  804. }
  805. std::string cmSystemTools::ComputeStringMD5(const std::string& input)
  806. {
  807. #if defined(CMAKE_BUILD_WITH_CMAKE)
  808. cmCryptoHash md5(cmCryptoHash::AlgoMD5);
  809. return md5.HashString(input);
  810. #else
  811. (void)input;
  812. cmSystemTools::Message("md5sum not supported in bootstrapping mode",
  813. "Error");
  814. return "";
  815. #endif
  816. }
  817. std::string cmSystemTools::ComputeCertificateThumbprint(
  818. const std::string& source)
  819. {
  820. std::string thumbprint;
  821. #if defined(CMAKE_BUILD_WITH_CMAKE) && defined(_WIN32)
  822. BYTE* certData = NULL;
  823. CRYPT_INTEGER_BLOB cryptBlob;
  824. HCERTSTORE certStore = NULL;
  825. PCCERT_CONTEXT certContext = NULL;
  826. HANDLE certFile = CreateFileW(
  827. cmsys::Encoding::ToWide(source.c_str()).c_str(), GENERIC_READ,
  828. FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  829. if (certFile != INVALID_HANDLE_VALUE && certFile != NULL) {
  830. DWORD fileSize = GetFileSize(certFile, NULL);
  831. if (fileSize != INVALID_FILE_SIZE) {
  832. certData = new BYTE[fileSize];
  833. if (certData != NULL) {
  834. DWORD dwRead = 0;
  835. if (ReadFile(certFile, certData, fileSize, &dwRead, NULL)) {
  836. cryptBlob.cbData = fileSize;
  837. cryptBlob.pbData = certData;
  838. // Verify that this is a valid cert
  839. if (PFXIsPFXBlob(&cryptBlob)) {
  840. // Open the certificate as a store
  841. certStore = PFXImportCertStore(&cryptBlob, NULL, CRYPT_EXPORTABLE);
  842. if (certStore != NULL) {
  843. // There should only be 1 cert.
  844. certContext =
  845. CertEnumCertificatesInStore(certStore, certContext);
  846. if (certContext != NULL) {
  847. // The hash is 20 bytes
  848. BYTE hashData[20];
  849. DWORD hashLength = 20;
  850. // Buffer to print the hash. Each byte takes 2 chars +
  851. // terminating character
  852. char hashPrint[41];
  853. char* pHashPrint = hashPrint;
  854. // Get the hash property from the certificate
  855. if (CertGetCertificateContextProperty(
  856. certContext, CERT_HASH_PROP_ID, hashData, &hashLength)) {
  857. for (DWORD i = 0; i < hashLength; i++) {
  858. // Convert each byte to hexadecimal
  859. sprintf(pHashPrint, "%02X", hashData[i]);
  860. pHashPrint += 2;
  861. }
  862. *pHashPrint = '\0';
  863. thumbprint = hashPrint;
  864. }
  865. CertFreeCertificateContext(certContext);
  866. }
  867. CertCloseStore(certStore, 0);
  868. }
  869. }
  870. }
  871. delete[] certData;
  872. }
  873. }
  874. CloseHandle(certFile);
  875. }
  876. #else
  877. (void)source;
  878. cmSystemTools::Message("ComputeCertificateThumbprint is not implemented",
  879. "Error");
  880. #endif
  881. return thumbprint;
  882. }
  883. void cmSystemTools::Glob(const std::string& directory,
  884. const std::string& regexp,
  885. std::vector<std::string>& files)
  886. {
  887. cmsys::Directory d;
  888. cmsys::RegularExpression reg(regexp.c_str());
  889. if (d.Load(directory)) {
  890. size_t numf;
  891. unsigned int i;
  892. numf = d.GetNumberOfFiles();
  893. for (i = 0; i < numf; i++) {
  894. std::string fname = d.GetFile(i);
  895. if (reg.find(fname)) {
  896. files.push_back(fname);
  897. }
  898. }
  899. }
  900. }
  901. void cmSystemTools::GlobDirs(const std::string& path,
  902. std::vector<std::string>& files)
  903. {
  904. std::string::size_type pos = path.find("/*");
  905. if (pos == std::string::npos) {
  906. files.push_back(path);
  907. return;
  908. }
  909. std::string startPath = path.substr(0, pos);
  910. std::string finishPath = path.substr(pos + 2);
  911. cmsys::Directory d;
  912. if (d.Load(startPath)) {
  913. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i) {
  914. if ((std::string(d.GetFile(i)) != ".") &&
  915. (std::string(d.GetFile(i)) != "..")) {
  916. std::string fname = startPath;
  917. fname += "/";
  918. fname += d.GetFile(i);
  919. if (cmSystemTools::FileIsDirectory(fname)) {
  920. fname += finishPath;
  921. cmSystemTools::GlobDirs(fname, files);
  922. }
  923. }
  924. }
  925. }
  926. }
  927. void cmSystemTools::ExpandList(std::vector<std::string> const& arguments,
  928. std::vector<std::string>& newargs)
  929. {
  930. std::vector<std::string>::const_iterator i;
  931. for (i = arguments.begin(); i != arguments.end(); ++i) {
  932. cmSystemTools::ExpandListArgument(*i, newargs);
  933. }
  934. }
  935. void cmSystemTools::ExpandListArgument(const std::string& arg,
  936. std::vector<std::string>& newargs,
  937. bool emptyArgs)
  938. {
  939. // If argument is empty, it is an empty list.
  940. if (!emptyArgs && arg.empty()) {
  941. return;
  942. }
  943. // if there are no ; in the name then just copy the current string
  944. if (arg.find(';') == std::string::npos) {
  945. newargs.push_back(arg);
  946. return;
  947. }
  948. std::string newArg;
  949. const char* last = arg.c_str();
  950. // Break the string at non-escaped semicolons not nested in [].
  951. int squareNesting = 0;
  952. for (const char* c = last; *c; ++c) {
  953. switch (*c) {
  954. case '\\': {
  955. // We only want to allow escaping of semicolons. Other
  956. // escapes should not be processed here.
  957. const char* next = c + 1;
  958. if (*next == ';') {
  959. newArg.append(last, c - last);
  960. // Skip over the escape character
  961. last = c = next;
  962. }
  963. } break;
  964. case '[': {
  965. ++squareNesting;
  966. } break;
  967. case ']': {
  968. --squareNesting;
  969. } break;
  970. case ';': {
  971. // Break the string here if we are not nested inside square
  972. // brackets.
  973. if (squareNesting == 0) {
  974. newArg.append(last, c - last);
  975. // Skip over the semicolon
  976. last = c + 1;
  977. if (!newArg.empty() || emptyArgs) {
  978. // Add the last argument if the string is not empty.
  979. newargs.push_back(newArg);
  980. newArg = "";
  981. }
  982. }
  983. } break;
  984. default: {
  985. // Just append this character.
  986. } break;
  987. }
  988. }
  989. newArg.append(last);
  990. if (!newArg.empty() || emptyArgs) {
  991. // Add the last argument if the string is not empty.
  992. newargs.push_back(newArg);
  993. }
  994. }
  995. bool cmSystemTools::SimpleGlob(const std::string& glob,
  996. std::vector<std::string>& files,
  997. int type /* = 0 */)
  998. {
  999. files.clear();
  1000. if (glob[glob.size() - 1] != '*') {
  1001. return false;
  1002. }
  1003. std::string path = cmSystemTools::GetFilenamePath(glob);
  1004. std::string ppath = cmSystemTools::GetFilenameName(glob);
  1005. ppath = ppath.substr(0, ppath.size() - 1);
  1006. if (path.empty()) {
  1007. path = "/";
  1008. }
  1009. bool res = false;
  1010. cmsys::Directory d;
  1011. if (d.Load(path)) {
  1012. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i) {
  1013. if ((std::string(d.GetFile(i)) != ".") &&
  1014. (std::string(d.GetFile(i)) != "..")) {
  1015. std::string fname = path;
  1016. if (path[path.size() - 1] != '/') {
  1017. fname += "/";
  1018. }
  1019. fname += d.GetFile(i);
  1020. std::string sfname = d.GetFile(i);
  1021. if (type > 0 && cmSystemTools::FileIsDirectory(fname)) {
  1022. continue;
  1023. }
  1024. if (type < 0 && !cmSystemTools::FileIsDirectory(fname)) {
  1025. continue;
  1026. }
  1027. if (sfname.size() >= ppath.size() &&
  1028. sfname.substr(0, ppath.size()) == ppath) {
  1029. files.push_back(fname);
  1030. res = true;
  1031. }
  1032. }
  1033. }
  1034. }
  1035. return res;
  1036. }
  1037. cmSystemTools::FileFormat cmSystemTools::GetFileFormat(const char* cext)
  1038. {
  1039. if (!cext || *cext == 0) {
  1040. return cmSystemTools::NO_FILE_FORMAT;
  1041. }
  1042. // std::string ext = cmSystemTools::LowerCase(cext);
  1043. std::string ext = cext;
  1044. if (ext == "c" || ext == ".c" || ext == "m" || ext == ".m") {
  1045. return cmSystemTools::C_FILE_FORMAT;
  1046. }
  1047. if (ext == "C" || ext == ".C" || ext == "M" || ext == ".M" || ext == "c++" ||
  1048. ext == ".c++" || ext == "cc" || ext == ".cc" || ext == "cpp" ||
  1049. ext == ".cpp" || ext == "cxx" || ext == ".cxx" || ext == "mm" ||
  1050. ext == ".mm") {
  1051. return cmSystemTools::CXX_FILE_FORMAT;
  1052. }
  1053. if (ext == "f" || ext == ".f" || ext == "F" || ext == ".F" || ext == "f77" ||
  1054. ext == ".f77" || ext == "f90" || ext == ".f90" || ext == "for" ||
  1055. ext == ".for" || ext == "f95" || ext == ".f95") {
  1056. return cmSystemTools::FORTRAN_FILE_FORMAT;
  1057. }
  1058. if (ext == "java" || ext == ".java") {
  1059. return cmSystemTools::JAVA_FILE_FORMAT;
  1060. }
  1061. if (ext == "H" || ext == ".H" || ext == "h" || ext == ".h" || ext == "h++" ||
  1062. ext == ".h++" || ext == "hm" || ext == ".hm" || ext == "hpp" ||
  1063. ext == ".hpp" || ext == "hxx" || ext == ".hxx" || ext == "in" ||
  1064. ext == ".in" || ext == "txx" || ext == ".txx") {
  1065. return cmSystemTools::HEADER_FILE_FORMAT;
  1066. }
  1067. if (ext == "rc" || ext == ".rc") {
  1068. return cmSystemTools::RESOURCE_FILE_FORMAT;
  1069. }
  1070. if (ext == "def" || ext == ".def") {
  1071. return cmSystemTools::DEFINITION_FILE_FORMAT;
  1072. }
  1073. if (ext == "lib" || ext == ".lib" || ext == "a" || ext == ".a") {
  1074. return cmSystemTools::STATIC_LIBRARY_FILE_FORMAT;
  1075. }
  1076. if (ext == "o" || ext == ".o" || ext == "obj" || ext == ".obj") {
  1077. return cmSystemTools::OBJECT_FILE_FORMAT;
  1078. }
  1079. #ifdef __APPLE__
  1080. if (ext == "dylib" || ext == ".dylib") {
  1081. return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT;
  1082. }
  1083. if (ext == "so" || ext == ".so" || ext == "bundle" || ext == ".bundle") {
  1084. return cmSystemTools::MODULE_FILE_FORMAT;
  1085. }
  1086. #else // __APPLE__
  1087. if (ext == "so" || ext == ".so" || ext == "sl" || ext == ".sl" ||
  1088. ext == "dll" || ext == ".dll") {
  1089. return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT;
  1090. }
  1091. #endif // __APPLE__
  1092. return cmSystemTools::UNKNOWN_FILE_FORMAT;
  1093. }
  1094. bool cmSystemTools::Split(const char* s, std::vector<std::string>& l)
  1095. {
  1096. std::vector<std::string> temp;
  1097. bool res = Superclass::Split(s, temp);
  1098. l.insert(l.end(), temp.begin(), temp.end());
  1099. return res;
  1100. }
  1101. std::string cmSystemTools::ConvertToOutputPath(const char* path)
  1102. {
  1103. #if defined(_WIN32) && !defined(__CYGWIN__)
  1104. if (s_ForceUnixPaths) {
  1105. return cmSystemTools::ConvertToUnixOutputPath(path);
  1106. }
  1107. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1108. #else
  1109. return cmSystemTools::ConvertToUnixOutputPath(path);
  1110. #endif
  1111. }
  1112. void cmSystemTools::ConvertToOutputSlashes(std::string& path)
  1113. {
  1114. #if defined(_WIN32) && !defined(__CYGWIN__)
  1115. if (!s_ForceUnixPaths) {
  1116. // Convert to windows slashes.
  1117. std::string::size_type pos = 0;
  1118. while ((pos = path.find('/', pos)) != std::string::npos) {
  1119. path[pos++] = '\\';
  1120. }
  1121. }
  1122. #else
  1123. static_cast<void>(path);
  1124. #endif
  1125. }
  1126. std::string cmSystemTools::ConvertToRunCommandPath(const char* path)
  1127. {
  1128. #if defined(_WIN32) && !defined(__CYGWIN__)
  1129. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1130. #else
  1131. return cmSystemTools::ConvertToUnixOutputPath(path);
  1132. #endif
  1133. }
  1134. // compute the relative path from here to there
  1135. std::string cmSystemTools::RelativePath(const char* local, const char* remote)
  1136. {
  1137. if (!cmSystemTools::FileIsFullPath(local)) {
  1138. cmSystemTools::Error("RelativePath must be passed a full path to local: ",
  1139. local);
  1140. }
  1141. if (!cmSystemTools::FileIsFullPath(remote)) {
  1142. cmSystemTools::Error("RelativePath must be passed a full path to remote: ",
  1143. remote);
  1144. }
  1145. return cmsys::SystemTools::RelativePath(local, remote);
  1146. }
  1147. std::string cmSystemTools::CollapseCombinedPath(std::string const& dir,
  1148. std::string const& file)
  1149. {
  1150. if (dir.empty() || dir == ".") {
  1151. return file;
  1152. }
  1153. std::vector<std::string> dirComponents;
  1154. std::vector<std::string> fileComponents;
  1155. cmSystemTools::SplitPath(dir, dirComponents);
  1156. cmSystemTools::SplitPath(file, fileComponents);
  1157. if (fileComponents.empty()) {
  1158. return dir;
  1159. }
  1160. if (fileComponents[0] != "") {
  1161. // File is not a relative path.
  1162. return file;
  1163. }
  1164. std::vector<std::string>::iterator i = fileComponents.begin() + 1;
  1165. while (i != fileComponents.end() && *i == ".." && dirComponents.size() > 1) {
  1166. ++i; // Remove ".." file component.
  1167. dirComponents.pop_back(); // Remove last dir component.
  1168. }
  1169. dirComponents.insert(dirComponents.end(), i, fileComponents.end());
  1170. return cmSystemTools::JoinPath(dirComponents);
  1171. }
  1172. #ifdef CMAKE_BUILD_WITH_CMAKE
  1173. bool cmSystemTools::UnsetEnv(const char* value)
  1174. {
  1175. #if !defined(HAVE_UNSETENV)
  1176. std::string var = value;
  1177. var += "=";
  1178. return cmSystemTools::PutEnv(var.c_str());
  1179. #else
  1180. unsetenv(value);
  1181. return true;
  1182. #endif
  1183. }
  1184. std::vector<std::string> cmSystemTools::GetEnvironmentVariables()
  1185. {
  1186. std::vector<std::string> env;
  1187. int cc;
  1188. for (cc = 0; environ[cc]; ++cc) {
  1189. env.push_back(environ[cc]);
  1190. }
  1191. return env;
  1192. }
  1193. void cmSystemTools::AppendEnv(std::vector<std::string> const& env)
  1194. {
  1195. for (std::vector<std::string>::const_iterator eit = env.begin();
  1196. eit != env.end(); ++eit) {
  1197. cmSystemTools::PutEnv(*eit);
  1198. }
  1199. }
  1200. cmSystemTools::SaveRestoreEnvironment::SaveRestoreEnvironment()
  1201. {
  1202. this->Env = cmSystemTools::GetEnvironmentVariables();
  1203. }
  1204. cmSystemTools::SaveRestoreEnvironment::~SaveRestoreEnvironment()
  1205. {
  1206. // First clear everything in the current environment:
  1207. std::vector<std::string> currentEnv = GetEnvironmentVariables();
  1208. for (std::vector<std::string>::const_iterator eit = currentEnv.begin();
  1209. eit != currentEnv.end(); ++eit) {
  1210. std::string var(*eit);
  1211. std::string::size_type pos = var.find('=');
  1212. if (pos != std::string::npos) {
  1213. var = var.substr(0, pos);
  1214. }
  1215. cmSystemTools::UnsetEnv(var.c_str());
  1216. }
  1217. // Then put back each entry from the original environment:
  1218. cmSystemTools::AppendEnv(this->Env);
  1219. }
  1220. #endif
  1221. void cmSystemTools::EnableVSConsoleOutput()
  1222. {
  1223. #ifdef _WIN32
  1224. // Visual Studio 8 2005 (devenv.exe or VCExpress.exe) will not
  1225. // display output to the console unless this environment variable is
  1226. // set. We need it to capture the output of these build tools.
  1227. // Note for future work that one could pass "/out \\.\pipe\NAME" to
  1228. // either of these executables where NAME is created with
  1229. // CreateNamedPipe. This would bypass the internal buffering of the
  1230. // output and allow it to be captured on the fly.
  1231. cmSystemTools::PutEnv("vsconsoleoutput=1");
  1232. #ifdef CMAKE_BUILD_WITH_CMAKE
  1233. // VS sets an environment variable to tell MS tools like "cl" to report
  1234. // output through a backdoor pipe instead of stdout/stderr. Unset the
  1235. // environment variable to close this backdoor for any path of process
  1236. // invocations that passes through CMake so we can capture the output.
  1237. cmSystemTools::UnsetEnv("VS_UNICODE_OUTPUT");
  1238. #endif
  1239. #endif
  1240. }
  1241. bool cmSystemTools::IsPathToFramework(const char* path)
  1242. {
  1243. return (cmSystemTools::FileIsFullPath(path) &&
  1244. cmHasLiteralSuffix(path, ".framework"));
  1245. }
  1246. bool cmSystemTools::CreateTar(const char* outFileName,
  1247. const std::vector<std::string>& files,
  1248. cmTarCompression compressType, bool verbose,
  1249. std::string const& mtime,
  1250. std::string const& format)
  1251. {
  1252. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1253. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1254. cmsys::ofstream fout(outFileName, std::ios::out | std::ios::binary);
  1255. if (!fout) {
  1256. std::string e = "Cannot open output file \"";
  1257. e += outFileName;
  1258. e += "\": ";
  1259. e += cmSystemTools::GetLastSystemError();
  1260. cmSystemTools::Error(e.c_str());
  1261. return false;
  1262. }
  1263. cmArchiveWrite::Compress compress = cmArchiveWrite::CompressNone;
  1264. switch (compressType) {
  1265. case TarCompressGZip:
  1266. compress = cmArchiveWrite::CompressGZip;
  1267. break;
  1268. case TarCompressBZip2:
  1269. compress = cmArchiveWrite::CompressBZip2;
  1270. break;
  1271. case TarCompressXZ:
  1272. compress = cmArchiveWrite::CompressXZ;
  1273. break;
  1274. case TarCompressNone:
  1275. compress = cmArchiveWrite::CompressNone;
  1276. break;
  1277. }
  1278. cmArchiveWrite a(fout, compress, format.empty() ? "paxr" : format);
  1279. a.SetMTime(mtime);
  1280. a.SetVerbose(verbose);
  1281. for (std::vector<std::string>::const_iterator i = files.begin();
  1282. i != files.end(); ++i) {
  1283. std::string path = *i;
  1284. if (cmSystemTools::FileIsFullPath(path.c_str())) {
  1285. // Get the relative path to the file.
  1286. path = cmSystemTools::RelativePath(cwd.c_str(), path.c_str());
  1287. }
  1288. if (!a.Add(path)) {
  1289. break;
  1290. }
  1291. }
  1292. if (!a) {
  1293. cmSystemTools::Error(a.GetError().c_str());
  1294. return false;
  1295. }
  1296. return true;
  1297. #else
  1298. (void)outFileName;
  1299. (void)files;
  1300. (void)verbose;
  1301. return false;
  1302. #endif
  1303. }
  1304. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1305. namespace {
  1306. #define BSDTAR_FILESIZE_PRINTF "%lu"
  1307. #define BSDTAR_FILESIZE_TYPE unsigned long
  1308. void list_item_verbose(FILE* out, struct archive_entry* entry)
  1309. {
  1310. char tmp[100];
  1311. size_t w;
  1312. const char* p;
  1313. const char* fmt;
  1314. time_t tim;
  1315. static time_t now;
  1316. size_t u_width = 6;
  1317. size_t gs_width = 13;
  1318. /*
  1319. * We avoid collecting the entire list in memory at once by
  1320. * listing things as we see them. However, that also means we can't
  1321. * just pre-compute the field widths. Instead, we start with guesses
  1322. * and just widen them as necessary. These numbers are completely
  1323. * arbitrary.
  1324. */
  1325. if (!now) {
  1326. time(&now);
  1327. }
  1328. fprintf(out, "%s %d ", archive_entry_strmode(entry),
  1329. archive_entry_nlink(entry));
  1330. /* Use uname if it's present, else uid. */
  1331. p = archive_entry_uname(entry);
  1332. if ((p == CM_NULLPTR) || (*p == '\0')) {
  1333. sprintf(tmp, "%lu ", (unsigned long)archive_entry_uid(entry));
  1334. p = tmp;
  1335. }
  1336. w = strlen(p);
  1337. if (w > u_width) {
  1338. u_width = w;
  1339. }
  1340. fprintf(out, "%-*s ", (int)u_width, p);
  1341. /* Use gname if it's present, else gid. */
  1342. p = archive_entry_gname(entry);
  1343. if (p != CM_NULLPTR && p[0] != '\0') {
  1344. fprintf(out, "%s", p);
  1345. w = strlen(p);
  1346. } else {
  1347. sprintf(tmp, "%lu", (unsigned long)archive_entry_gid(entry));
  1348. w = strlen(tmp);
  1349. fprintf(out, "%s", tmp);
  1350. }
  1351. /*
  1352. * Print device number or file size, right-aligned so as to make
  1353. * total width of group and devnum/filesize fields be gs_width.
  1354. * If gs_width is too small, grow it.
  1355. */
  1356. if (archive_entry_filetype(entry) == AE_IFCHR ||
  1357. archive_entry_filetype(entry) == AE_IFBLK) {
  1358. sprintf(tmp, "%lu,%lu", (unsigned long)archive_entry_rdevmajor(entry),
  1359. (unsigned long)archive_entry_rdevminor(entry));
  1360. } else {
  1361. /*
  1362. * Note the use of platform-dependent macros to format
  1363. * the filesize here. We need the format string and the
  1364. * corresponding type for the cast.
  1365. */
  1366. sprintf(tmp, BSDTAR_FILESIZE_PRINTF,
  1367. (BSDTAR_FILESIZE_TYPE)archive_entry_size(entry));
  1368. }
  1369. if (w + strlen(tmp) >= gs_width) {
  1370. gs_width = w + strlen(tmp) + 1;
  1371. }
  1372. fprintf(out, "%*s", (int)(gs_width - w), tmp);
  1373. /* Format the time using 'ls -l' conventions. */
  1374. tim = archive_entry_mtime(entry);
  1375. #define HALF_YEAR ((time_t)365 * 86400 / 2)
  1376. #if defined(_WIN32) && !defined(__CYGWIN__)
  1377. /* Windows' strftime function does not support %e format. */
  1378. #define DAY_FMT "%d"
  1379. #else
  1380. #define DAY_FMT "%e" /* Day number without leading zeros */
  1381. #endif
  1382. if (tim < now - HALF_YEAR || tim > now + HALF_YEAR) {
  1383. fmt = DAY_FMT " %b %Y";
  1384. } else {
  1385. fmt = DAY_FMT " %b %H:%M";
  1386. }
  1387. strftime(tmp, sizeof(tmp), fmt, localtime(&tim));
  1388. fprintf(out, " %s ", tmp);
  1389. fprintf(out, "%s", cm_archive_entry_pathname(entry).c_str());
  1390. /* Extra information for links. */
  1391. if (archive_entry_hardlink(entry)) /* Hard link */
  1392. {
  1393. fprintf(out, " link to %s", archive_entry_hardlink(entry));
  1394. } else if (archive_entry_symlink(entry)) /* Symbolic link */
  1395. {
  1396. fprintf(out, " -> %s", archive_entry_symlink(entry));
  1397. }
  1398. fflush(out);
  1399. }
  1400. long copy_data(struct archive* ar, struct archive* aw)
  1401. {
  1402. long r;
  1403. const void* buff;
  1404. size_t size;
  1405. #if defined(ARCHIVE_VERSION_NUMBER) && ARCHIVE_VERSION_NUMBER >= 3000000
  1406. __LA_INT64_T offset;
  1407. #else
  1408. off_t offset;
  1409. #endif
  1410. for (;;) {
  1411. r = archive_read_data_block(ar, &buff, &size, &offset);
  1412. if (r == ARCHIVE_EOF) {
  1413. return (ARCHIVE_OK);
  1414. }
  1415. if (r != ARCHIVE_OK) {
  1416. return (r);
  1417. }
  1418. r = archive_write_data_block(aw, buff, size, offset);
  1419. if (r != ARCHIVE_OK) {
  1420. cmSystemTools::Message("archive_write_data_block()",
  1421. archive_error_string(aw));
  1422. return (r);
  1423. }
  1424. }
  1425. #if !defined(__clang__) && !defined(__HP_aCC)
  1426. return r; /* this should not happen but it quiets some compilers */
  1427. #endif
  1428. }
  1429. bool extract_tar(const char* outFileName, bool verbose, bool extract)
  1430. {
  1431. cmLocaleRAII localeRAII;
  1432. static_cast<void>(localeRAII);
  1433. struct archive* a = archive_read_new();
  1434. struct archive* ext = archive_write_disk_new();
  1435. archive_read_support_filter_all(a);
  1436. archive_read_support_format_all(a);
  1437. struct archive_entry* entry;
  1438. int r = cm_archive_read_open_file(a, outFileName, 10240);
  1439. if (r) {
  1440. cmSystemTools::Error("Problem with archive_read_open_file(): ",
  1441. archive_error_string(a));
  1442. archive_write_free(ext);
  1443. archive_read_close(a);
  1444. return false;
  1445. }
  1446. for (;;) {
  1447. r = archive_read_next_header(a, &entry);
  1448. if (r == ARCHIVE_EOF) {
  1449. break;
  1450. }
  1451. if (r != ARCHIVE_OK) {
  1452. cmSystemTools::Error("Problem with archive_read_next_header(): ",
  1453. archive_error_string(a));
  1454. break;
  1455. }
  1456. if (verbose) {
  1457. if (extract) {
  1458. cmSystemTools::Stdout("x ");
  1459. cmSystemTools::Stdout(cm_archive_entry_pathname(entry).c_str());
  1460. } else {
  1461. list_item_verbose(stdout, entry);
  1462. }
  1463. cmSystemTools::Stdout("\n");
  1464. } else if (!extract) {
  1465. cmSystemTools::Stdout(cm_archive_entry_pathname(entry).c_str());
  1466. cmSystemTools::Stdout("\n");
  1467. }
  1468. if (extract) {
  1469. r = archive_write_disk_set_options(ext, ARCHIVE_EXTRACT_TIME);
  1470. if (r != ARCHIVE_OK) {
  1471. cmSystemTools::Error("Problem with archive_write_disk_set_options(): ",
  1472. archive_error_string(ext));
  1473. break;
  1474. }
  1475. r = archive_write_header(ext, entry);
  1476. if (r == ARCHIVE_OK) {
  1477. copy_data(a, ext);
  1478. r = archive_write_finish_entry(ext);
  1479. if (r != ARCHIVE_OK) {
  1480. cmSystemTools::Error("Problem with archive_write_finish_entry(): ",
  1481. archive_error_string(ext));
  1482. break;
  1483. }
  1484. }
  1485. #ifdef _WIN32
  1486. else if (const char* linktext = archive_entry_symlink(entry)) {
  1487. std::cerr << "cmake -E tar: warning: skipping symbolic link \""
  1488. << cm_archive_entry_pathname(entry) << "\" -> \"" << linktext
  1489. << "\"." << std::endl;
  1490. }
  1491. #endif
  1492. else {
  1493. cmSystemTools::Error("Problem with archive_write_header(): ",
  1494. archive_error_string(ext));
  1495. cmSystemTools::Error("Current file: ",
  1496. cm_archive_entry_pathname(entry).c_str());
  1497. break;
  1498. }
  1499. }
  1500. }
  1501. archive_write_free(ext);
  1502. archive_read_close(a);
  1503. archive_read_free(a);
  1504. return r == ARCHIVE_EOF || r == ARCHIVE_OK;
  1505. }
  1506. }
  1507. #endif
  1508. bool cmSystemTools::ExtractTar(const char* outFileName, bool verbose)
  1509. {
  1510. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1511. return extract_tar(outFileName, verbose, true);
  1512. #else
  1513. (void)outFileName;
  1514. (void)verbose;
  1515. return false;
  1516. #endif
  1517. }
  1518. bool cmSystemTools::ListTar(const char* outFileName, bool verbose)
  1519. {
  1520. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1521. return extract_tar(outFileName, verbose, false);
  1522. #else
  1523. (void)outFileName;
  1524. (void)verbose;
  1525. return false;
  1526. #endif
  1527. }
  1528. int cmSystemTools::WaitForLine(cmsysProcess* process, std::string& line,
  1529. double timeout, std::vector<char>& out,
  1530. std::vector<char>& err)
  1531. {
  1532. line = "";
  1533. std::vector<char>::iterator outiter = out.begin();
  1534. std::vector<char>::iterator erriter = err.begin();
  1535. cmProcessOutput processOutput;
  1536. std::string strdata;
  1537. while (1) {
  1538. // Check for a newline in stdout.
  1539. for (; outiter != out.end(); ++outiter) {
  1540. if ((*outiter == '\r') && ((outiter + 1) == out.end())) {
  1541. break;
  1542. } else if (*outiter == '\n' || *outiter == '\0') {
  1543. std::vector<char>::size_type length = outiter - out.begin();
  1544. if (length > 1 && *(outiter - 1) == '\r') {
  1545. --length;
  1546. }
  1547. if (length > 0) {
  1548. line.append(&out[0], length);
  1549. }
  1550. out.erase(out.begin(), outiter + 1);
  1551. return cmsysProcess_Pipe_STDOUT;
  1552. }
  1553. }
  1554. // Check for a newline in stderr.
  1555. for (; erriter != err.end(); ++erriter) {
  1556. if ((*erriter == '\r') && ((erriter + 1) == err.end())) {
  1557. break;
  1558. } else 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. cmSystemToolsCMakeCommand = exe_dir;
  1836. cmSystemToolsCMakeCommand += "/cmake";
  1837. cmSystemToolsCMakeCommand += cmSystemTools::GetExecutableExtension();
  1838. #ifndef CMAKE_BUILD_WITH_CMAKE
  1839. // The bootstrap cmake does not provide the other tools,
  1840. // so use the directory where they are about to be built.
  1841. exe_dir = CMAKE_BOOTSTRAP_BINARY_DIR "/bin";
  1842. #endif
  1843. cmSystemToolsCTestCommand = exe_dir;
  1844. cmSystemToolsCTestCommand += "/ctest";
  1845. cmSystemToolsCTestCommand += cmSystemTools::GetExecutableExtension();
  1846. cmSystemToolsCPackCommand = exe_dir;
  1847. cmSystemToolsCPackCommand += "/cpack";
  1848. cmSystemToolsCPackCommand += cmSystemTools::GetExecutableExtension();
  1849. cmSystemToolsCMakeGUICommand = exe_dir;
  1850. cmSystemToolsCMakeGUICommand += "/cmake-gui";
  1851. cmSystemToolsCMakeGUICommand += cmSystemTools::GetExecutableExtension();
  1852. if (!cmSystemTools::FileExists(cmSystemToolsCMakeGUICommand.c_str())) {
  1853. cmSystemToolsCMakeGUICommand = "";
  1854. }
  1855. cmSystemToolsCMakeCursesCommand = exe_dir;
  1856. cmSystemToolsCMakeCursesCommand += "/ccmake";
  1857. cmSystemToolsCMakeCursesCommand += cmSystemTools::GetExecutableExtension();
  1858. if (!cmSystemTools::FileExists(cmSystemToolsCMakeCursesCommand.c_str())) {
  1859. cmSystemToolsCMakeCursesCommand = "";
  1860. }
  1861. cmSystemToolsCMClDepsCommand = exe_dir;
  1862. cmSystemToolsCMClDepsCommand += "/cmcldeps";
  1863. cmSystemToolsCMClDepsCommand += cmSystemTools::GetExecutableExtension();
  1864. if (!cmSystemTools::FileExists(cmSystemToolsCMClDepsCommand.c_str())) {
  1865. cmSystemToolsCMClDepsCommand = "";
  1866. }
  1867. #ifdef CMAKE_BUILD_WITH_CMAKE
  1868. // Install tree has
  1869. // - "<prefix><CMAKE_BIN_DIR>/cmake"
  1870. // - "<prefix><CMAKE_DATA_DIR>"
  1871. if (cmHasSuffix(exe_dir, CMAKE_BIN_DIR)) {
  1872. std::string const prefix =
  1873. exe_dir.substr(0, exe_dir.size() - strlen(CMAKE_BIN_DIR));
  1874. cmSystemToolsCMakeRoot = prefix + CMAKE_DATA_DIR;
  1875. }
  1876. if (cmSystemToolsCMakeRoot.empty() ||
  1877. !cmSystemTools::FileExists(
  1878. (cmSystemToolsCMakeRoot + "/Modules/CMake.cmake").c_str())) {
  1879. // Build tree has "<build>/bin[/<config>]/cmake" and
  1880. // "<build>/CMakeFiles/CMakeSourceDir.txt".
  1881. std::string dir = cmSystemTools::GetFilenamePath(exe_dir);
  1882. std::string src_dir_txt = dir + "/CMakeFiles/CMakeSourceDir.txt";
  1883. cmsys::ifstream fin(src_dir_txt.c_str());
  1884. std::string src_dir;
  1885. if (fin && cmSystemTools::GetLineFromStream(fin, src_dir) &&
  1886. cmSystemTools::FileIsDirectory(src_dir)) {
  1887. cmSystemToolsCMakeRoot = src_dir;
  1888. } else {
  1889. dir = cmSystemTools::GetFilenamePath(dir);
  1890. src_dir_txt = dir + "/CMakeFiles/CMakeSourceDir.txt";
  1891. cmsys::ifstream fin2(src_dir_txt.c_str());
  1892. if (fin2 && cmSystemTools::GetLineFromStream(fin2, src_dir) &&
  1893. cmSystemTools::FileIsDirectory(src_dir)) {
  1894. cmSystemToolsCMakeRoot = src_dir;
  1895. }
  1896. }
  1897. }
  1898. #else
  1899. // Bootstrap build knows its source.
  1900. cmSystemToolsCMakeRoot = CMAKE_BOOTSTRAP_SOURCE_DIR;
  1901. #endif
  1902. }
  1903. std::string const& cmSystemTools::GetCMakeCommand()
  1904. {
  1905. return cmSystemToolsCMakeCommand;
  1906. }
  1907. std::string const& cmSystemTools::GetCTestCommand()
  1908. {
  1909. return cmSystemToolsCTestCommand;
  1910. }
  1911. std::string const& cmSystemTools::GetCPackCommand()
  1912. {
  1913. return cmSystemToolsCPackCommand;
  1914. }
  1915. std::string const& cmSystemTools::GetCMakeCursesCommand()
  1916. {
  1917. return cmSystemToolsCMakeCursesCommand;
  1918. }
  1919. std::string const& cmSystemTools::GetCMakeGUICommand()
  1920. {
  1921. return cmSystemToolsCMakeGUICommand;
  1922. }
  1923. std::string const& cmSystemTools::GetCMClDepsCommand()
  1924. {
  1925. return cmSystemToolsCMClDepsCommand;
  1926. }
  1927. std::string const& cmSystemTools::GetCMakeRoot()
  1928. {
  1929. return cmSystemToolsCMakeRoot;
  1930. }
  1931. void cmSystemTools::MakefileColorEcho(int color, const char* message,
  1932. bool newline, bool enabled)
  1933. {
  1934. // On some platforms (an MSYS prompt) cmsysTerminal may not be able
  1935. // to determine whether the stream is displayed on a tty. In this
  1936. // case it assumes no unless we tell it otherwise. Since we want
  1937. // color messages to be displayed for users we will assume yes.
  1938. // However, we can test for some situations when the answer is most
  1939. // likely no.
  1940. int assumeTTY = cmsysTerminal_Color_AssumeTTY;
  1941. if (cmSystemTools::HasEnv("DART_TEST_FROM_DART") ||
  1942. cmSystemTools::HasEnv("DASHBOARD_TEST_FROM_CTEST") ||
  1943. cmSystemTools::HasEnv("CTEST_INTERACTIVE_DEBUG_MODE")) {
  1944. // Avoid printing color escapes during dashboard builds.
  1945. assumeTTY = 0;
  1946. }
  1947. if (enabled && color != cmsysTerminal_Color_Normal) {
  1948. // Print with color. Delay the newline until later so that
  1949. // all color restore sequences appear before it.
  1950. cmsysTerminal_cfprintf(color | assumeTTY, stdout, "%s", message);
  1951. } else {
  1952. // Color is disabled. Print without color.
  1953. fprintf(stdout, "%s", message);
  1954. }
  1955. if (newline) {
  1956. fprintf(stdout, "\n");
  1957. }
  1958. }
  1959. bool cmSystemTools::GuessLibrarySOName(std::string const& fullPath,
  1960. std::string& soname)
  1961. {
  1962. // For ELF shared libraries use a real parser to get the correct
  1963. // soname.
  1964. #if defined(CMAKE_USE_ELF_PARSER)
  1965. cmELF elf(fullPath.c_str());
  1966. if (elf) {
  1967. return elf.GetSOName(soname);
  1968. }
  1969. #endif
  1970. // If the file is not a symlink we have no guess for its soname.
  1971. if (!cmSystemTools::FileIsSymlink(fullPath)) {
  1972. return false;
  1973. }
  1974. if (!cmSystemTools::ReadSymlink(fullPath, soname)) {
  1975. return false;
  1976. }
  1977. // If the symlink has a path component we have no guess for the soname.
  1978. if (!cmSystemTools::GetFilenamePath(soname).empty()) {
  1979. return false;
  1980. }
  1981. // If the symlink points at an extended version of the same name
  1982. // assume it is the soname.
  1983. std::string name = cmSystemTools::GetFilenameName(fullPath);
  1984. return soname.length() > name.length() &&
  1985. soname.compare(0, name.length(), name) == 0;
  1986. }
  1987. bool cmSystemTools::GuessLibraryInstallName(std::string const& fullPath,
  1988. std::string& soname)
  1989. {
  1990. #if defined(CMAKE_USE_MACH_PARSER)
  1991. cmMachO macho(fullPath.c_str());
  1992. if (macho) {
  1993. return macho.GetInstallName(soname);
  1994. }
  1995. #else
  1996. (void)fullPath;
  1997. (void)soname;
  1998. #endif
  1999. return false;
  2000. }
  2001. #if defined(CMAKE_USE_ELF_PARSER)
  2002. std::string::size_type cmSystemToolsFindRPath(std::string const& have,
  2003. std::string const& want)
  2004. {
  2005. std::string::size_type pos = 0;
  2006. while (pos < have.size()) {
  2007. // Look for an occurrence of the string.
  2008. std::string::size_type const beg = have.find(want, pos);
  2009. if (beg == std::string::npos) {
  2010. return std::string::npos;
  2011. }
  2012. // Make sure it is separated from preceding entries.
  2013. if (beg > 0 && have[beg - 1] != ':') {
  2014. pos = beg + 1;
  2015. continue;
  2016. }
  2017. // Make sure it is separated from following entries.
  2018. std::string::size_type const end = beg + want.size();
  2019. if (end < have.size() && have[end] != ':') {
  2020. pos = beg + 1;
  2021. continue;
  2022. }
  2023. // Return the position of the path portion.
  2024. return beg;
  2025. }
  2026. // The desired rpath was not found.
  2027. return std::string::npos;
  2028. }
  2029. #endif
  2030. #if defined(CMAKE_USE_ELF_PARSER)
  2031. struct cmSystemToolsRPathInfo
  2032. {
  2033. unsigned long Position;
  2034. unsigned long Size;
  2035. std::string Name;
  2036. std::string Value;
  2037. };
  2038. #endif
  2039. bool cmSystemTools::ChangeRPath(std::string const& file,
  2040. std::string const& oldRPath,
  2041. std::string const& newRPath, std::string* emsg,
  2042. bool* changed)
  2043. {
  2044. #if defined(CMAKE_USE_ELF_PARSER)
  2045. if (changed) {
  2046. *changed = false;
  2047. }
  2048. int rp_count = 0;
  2049. bool remove_rpath = true;
  2050. cmSystemToolsRPathInfo rp[2];
  2051. {
  2052. // Parse the ELF binary.
  2053. cmELF elf(file.c_str());
  2054. // Get the RPATH and RUNPATH entries from it.
  2055. int se_count = 0;
  2056. cmELF::StringEntry const* se[2] = { CM_NULLPTR, CM_NULLPTR };
  2057. const char* se_name[2] = { CM_NULLPTR, CM_NULLPTR };
  2058. if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
  2059. se[se_count] = se_rpath;
  2060. se_name[se_count] = "RPATH";
  2061. ++se_count;
  2062. }
  2063. if (cmELF::StringEntry const* se_runpath = elf.GetRunPath()) {
  2064. se[se_count] = se_runpath;
  2065. se_name[se_count] = "RUNPATH";
  2066. ++se_count;
  2067. }
  2068. if (se_count == 0) {
  2069. if (newRPath.empty()) {
  2070. // The new rpath is empty and there is no rpath anyway so it is
  2071. // okay.
  2072. return true;
  2073. }
  2074. if (emsg) {
  2075. *emsg = "No valid ELF RPATH or RUNPATH entry exists in the file; ";
  2076. *emsg += elf.GetErrorMessage();
  2077. }
  2078. return false;
  2079. }
  2080. for (int i = 0; i < se_count; ++i) {
  2081. // If both RPATH and RUNPATH refer to the same string literal it
  2082. // needs to be changed only once.
  2083. if (rp_count && rp[0].Position == se[i]->Position) {
  2084. continue;
  2085. }
  2086. // Make sure the current rpath contains the old rpath.
  2087. std::string::size_type pos =
  2088. cmSystemToolsFindRPath(se[i]->Value, oldRPath);
  2089. if (pos == std::string::npos) {
  2090. // If it contains the new rpath instead then it is okay.
  2091. if (cmSystemToolsFindRPath(se[i]->Value, newRPath) !=
  2092. std::string::npos) {
  2093. remove_rpath = false;
  2094. continue;
  2095. }
  2096. if (emsg) {
  2097. std::ostringstream e;
  2098. /* clang-format off */
  2099. e << "The current " << se_name[i] << " is:\n"
  2100. << " " << se[i]->Value << "\n"
  2101. << "which does not contain:\n"
  2102. << " " << oldRPath << "\n"
  2103. << "as was expected.";
  2104. /* clang-format on */
  2105. *emsg = e.str();
  2106. }
  2107. return false;
  2108. }
  2109. // Store information about the entry in the file.
  2110. rp[rp_count].Position = se[i]->Position;
  2111. rp[rp_count].Size = se[i]->Size;
  2112. rp[rp_count].Name = se_name[i];
  2113. std::string::size_type prefix_len = pos;
  2114. // If oldRPath was at the end of the file's RPath, and newRPath is empty,
  2115. // we should remove the unnecessary ':' at the end.
  2116. if (newRPath.empty() && pos > 0 && se[i]->Value[pos - 1] == ':' &&
  2117. pos + oldRPath.length() == se[i]->Value.length()) {
  2118. prefix_len--;
  2119. }
  2120. // Construct the new value which preserves the part of the path
  2121. // not being changed.
  2122. rp[rp_count].Value = se[i]->Value.substr(0, prefix_len);
  2123. rp[rp_count].Value += newRPath;
  2124. rp[rp_count].Value +=
  2125. se[i]->Value.substr(pos + oldRPath.length(), oldRPath.npos);
  2126. if (!rp[rp_count].Value.empty()) {
  2127. remove_rpath = false;
  2128. }
  2129. // Make sure there is enough room to store the new rpath and at
  2130. // least one null terminator.
  2131. if (rp[rp_count].Size < rp[rp_count].Value.length() + 1) {
  2132. if (emsg) {
  2133. *emsg = "The replacement path is too long for the ";
  2134. *emsg += se_name[i];
  2135. *emsg += " entry.";
  2136. }
  2137. return false;
  2138. }
  2139. // This entry is ready for update.
  2140. ++rp_count;
  2141. }
  2142. }
  2143. // If no runtime path needs to be changed, we are done.
  2144. if (rp_count == 0) {
  2145. return true;
  2146. }
  2147. // If the resulting rpath is empty, just remove the entire entry instead.
  2148. if (remove_rpath) {
  2149. return cmSystemTools::RemoveRPath(file, emsg, changed);
  2150. }
  2151. {
  2152. // Open the file for update.
  2153. cmsys::ofstream f(file.c_str(),
  2154. std::ios::in | std::ios::out | std::ios::binary);
  2155. if (!f) {
  2156. if (emsg) {
  2157. *emsg = "Error opening file for update.";
  2158. }
  2159. return false;
  2160. }
  2161. // Store the new RPATH and RUNPATH strings.
  2162. for (int i = 0; i < rp_count; ++i) {
  2163. // Seek to the RPATH position.
  2164. if (!f.seekp(rp[i].Position)) {
  2165. if (emsg) {
  2166. *emsg = "Error seeking to ";
  2167. *emsg += rp[i].Name;
  2168. *emsg += " position.";
  2169. }
  2170. return false;
  2171. }
  2172. // Write the new rpath. Follow it with enough null terminators to
  2173. // fill the string table entry.
  2174. f << rp[i].Value;
  2175. for (unsigned long j = rp[i].Value.length(); j < rp[i].Size; ++j) {
  2176. f << '\0';
  2177. }
  2178. // Make sure it wrote correctly.
  2179. if (!f) {
  2180. if (emsg) {
  2181. *emsg = "Error writing the new ";
  2182. *emsg += rp[i].Name;
  2183. *emsg += " string to the file.";
  2184. }
  2185. return false;
  2186. }
  2187. }
  2188. }
  2189. // Everything was updated successfully.
  2190. if (changed) {
  2191. *changed = true;
  2192. }
  2193. return true;
  2194. #else
  2195. (void)file;
  2196. (void)oldRPath;
  2197. (void)newRPath;
  2198. (void)emsg;
  2199. (void)changed;
  2200. return false;
  2201. #endif
  2202. }
  2203. bool cmSystemTools::VersionCompare(cmSystemTools::CompareOp op,
  2204. const char* lhss, const char* rhss)
  2205. {
  2206. const char* endl = lhss;
  2207. const char* endr = rhss;
  2208. unsigned long lhs, rhs;
  2209. while (((*endl >= '0') && (*endl <= '9')) ||
  2210. ((*endr >= '0') && (*endr <= '9'))) {
  2211. // Do component-wise comparison.
  2212. lhs = strtoul(endl, const_cast<char**>(&endl), 10);
  2213. rhs = strtoul(endr, const_cast<char**>(&endr), 10);
  2214. if (lhs < rhs) {
  2215. // lhs < rhs, so true if operation is LESS
  2216. return (op & cmSystemTools::OP_LESS) != 0;
  2217. }
  2218. if (lhs > rhs) {
  2219. // lhs > rhs, so true if operation is GREATER
  2220. return (op & cmSystemTools::OP_GREATER) != 0;
  2221. }
  2222. if (*endr == '.') {
  2223. endr++;
  2224. }
  2225. if (*endl == '.') {
  2226. endl++;
  2227. }
  2228. }
  2229. // lhs == rhs, so true if operation is EQUAL
  2230. return (op & cmSystemTools::OP_EQUAL) != 0;
  2231. }
  2232. bool cmSystemTools::VersionCompareEqual(std::string const& lhs,
  2233. std::string const& rhs)
  2234. {
  2235. return cmSystemTools::VersionCompare(cmSystemTools::OP_EQUAL, lhs.c_str(),
  2236. rhs.c_str());
  2237. }
  2238. bool cmSystemTools::VersionCompareGreater(std::string const& lhs,
  2239. std::string const& rhs)
  2240. {
  2241. return cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER, lhs.c_str(),
  2242. rhs.c_str());
  2243. }
  2244. bool cmSystemTools::VersionCompareGreaterEq(std::string const& lhs,
  2245. std::string const& rhs)
  2246. {
  2247. return cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
  2248. lhs.c_str(), rhs.c_str());
  2249. }
  2250. static size_t cm_strverscmp_find_first_difference_or_end(const char* lhs,
  2251. const char* rhs)
  2252. {
  2253. size_t i = 0;
  2254. /* Step forward until we find a difference or both strings end together.
  2255. The difference may lie on the null-terminator of one string. */
  2256. while (lhs[i] == rhs[i] && lhs[i] != 0) {
  2257. ++i;
  2258. }
  2259. return i;
  2260. }
  2261. static size_t cm_strverscmp_find_digits_begin(const char* s, size_t i)
  2262. {
  2263. /* Step back until we are not preceded by a digit. */
  2264. while (i > 0 && isdigit(s[i - 1])) {
  2265. --i;
  2266. }
  2267. return i;
  2268. }
  2269. static size_t cm_strverscmp_find_digits_end(const char* s, size_t i)
  2270. {
  2271. /* Step forward over digits. */
  2272. while (isdigit(s[i])) {
  2273. ++i;
  2274. }
  2275. return i;
  2276. }
  2277. static size_t cm_strverscmp_count_leading_zeros(const char* s, size_t b)
  2278. {
  2279. size_t i = b;
  2280. /* Step forward over zeros that are followed by another digit. */
  2281. while (s[i] == '0' && isdigit(s[i + 1])) {
  2282. ++i;
  2283. }
  2284. return i - b;
  2285. }
  2286. static int cm_strverscmp(const char* lhs, const char* rhs)
  2287. {
  2288. size_t const i = cm_strverscmp_find_first_difference_or_end(lhs, rhs);
  2289. if (lhs[i] != rhs[i]) {
  2290. /* The strings differ starting at 'i'. Check for a digit sequence. */
  2291. size_t const b = cm_strverscmp_find_digits_begin(lhs, i);
  2292. if (b != i || (isdigit(lhs[i]) && isdigit(rhs[i]))) {
  2293. /* A digit sequence starts at 'b', preceding or at 'i'. */
  2294. /* Look for leading zeros, implying a leading decimal point. */
  2295. size_t const lhs_zeros = cm_strverscmp_count_leading_zeros(lhs, b);
  2296. size_t const rhs_zeros = cm_strverscmp_count_leading_zeros(rhs, b);
  2297. if (lhs_zeros != rhs_zeros) {
  2298. /* The side with more leading zeros orders first. */
  2299. return rhs_zeros > lhs_zeros ? 1 : -1;
  2300. }
  2301. if (lhs_zeros == 0) {
  2302. /* No leading zeros; compare digit sequence lengths. */
  2303. size_t const lhs_end = cm_strverscmp_find_digits_end(lhs, i);
  2304. size_t const rhs_end = cm_strverscmp_find_digits_end(rhs, i);
  2305. if (lhs_end != rhs_end) {
  2306. /* The side with fewer digits orders first. */
  2307. return lhs_end > rhs_end ? 1 : -1;
  2308. }
  2309. }
  2310. }
  2311. }
  2312. /* Ordering was not decided by digit sequence lengths; compare bytes. */
  2313. return lhs[i] - rhs[i];
  2314. }
  2315. int cmSystemTools::strverscmp(std::string const& lhs, std::string const& rhs)
  2316. {
  2317. return cm_strverscmp(lhs.c_str(), rhs.c_str());
  2318. }
  2319. bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg,
  2320. bool* removed)
  2321. {
  2322. #if defined(CMAKE_USE_ELF_PARSER)
  2323. if (removed) {
  2324. *removed = false;
  2325. }
  2326. int zeroCount = 0;
  2327. unsigned long zeroPosition[2] = { 0, 0 };
  2328. unsigned long zeroSize[2] = { 0, 0 };
  2329. unsigned long bytesBegin = 0;
  2330. std::vector<char> bytes;
  2331. {
  2332. // Parse the ELF binary.
  2333. cmELF elf(file.c_str());
  2334. // Get the RPATH and RUNPATH entries from it and sort them by index
  2335. // in the dynamic section header.
  2336. int se_count = 0;
  2337. cmELF::StringEntry const* se[2] = { CM_NULLPTR, CM_NULLPTR };
  2338. if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
  2339. se[se_count++] = se_rpath;
  2340. }
  2341. if (cmELF::StringEntry const* se_runpath = elf.GetRunPath()) {
  2342. se[se_count++] = se_runpath;
  2343. }
  2344. if (se_count == 0) {
  2345. // There is no RPATH or RUNPATH anyway.
  2346. return true;
  2347. }
  2348. if (se_count == 2 && se[1]->IndexInSection < se[0]->IndexInSection) {
  2349. std::swap(se[0], se[1]);
  2350. }
  2351. // Obtain a copy of the dynamic entries
  2352. cmELF::DynamicEntryList dentries = elf.GetDynamicEntries();
  2353. if (dentries.empty()) {
  2354. // This should happen only for invalid ELF files where a DT_NULL
  2355. // appears before the end of the table.
  2356. if (emsg) {
  2357. *emsg = "DYNAMIC section contains a DT_NULL before the end.";
  2358. }
  2359. return false;
  2360. }
  2361. // Save information about the string entries to be zeroed.
  2362. zeroCount = se_count;
  2363. for (int i = 0; i < se_count; ++i) {
  2364. zeroPosition[i] = se[i]->Position;
  2365. zeroSize[i] = se[i]->Size;
  2366. }
  2367. // Get size of one DYNAMIC entry
  2368. unsigned long const sizeof_dentry =
  2369. elf.GetDynamicEntryPosition(1) - elf.GetDynamicEntryPosition(0);
  2370. // Adjust the entry list as necessary to remove the run path
  2371. unsigned long entriesErased = 0;
  2372. for (cmELF::DynamicEntryList::iterator it = dentries.begin();
  2373. it != dentries.end();) {
  2374. if (it->first == cmELF::TagRPath || it->first == cmELF::TagRunPath) {
  2375. it = dentries.erase(it);
  2376. entriesErased++;
  2377. continue;
  2378. } else {
  2379. if (cmELF::TagMipsRldMapRel != 0 &&
  2380. it->first == cmELF::TagMipsRldMapRel) {
  2381. // Background: debuggers need to know the "linker map" which contains
  2382. // the addresses each dynamic object is loaded at. Most arches use
  2383. // the DT_DEBUG tag which the dynamic linker writes to (directly) and
  2384. // contain the location of the linker map, however on MIPS the
  2385. // .dynamic section is always read-only so this is not possible. MIPS
  2386. // objects instead contain a DT_MIPS_RLD_MAP tag which contains the
  2387. // address where the dyanmic linker will write to (an indirect
  2388. // version of DT_DEBUG). Since this doesn't work when using PIE, a
  2389. // relative equivalent was created - DT_MIPS_RLD_MAP_REL. Since this
  2390. // version contains a relative offset, moving it changes the
  2391. // calculated address. This may cause the dyanmic linker to write
  2392. // into memory it should not be changing.
  2393. //
  2394. // To fix this, we adjust the value of DT_MIPS_RLD_MAP_REL here. If
  2395. // we move it up by n bytes, we add n bytes to the value of this tag.
  2396. it->second += entriesErased * sizeof_dentry;
  2397. }
  2398. it++;
  2399. }
  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. }