cmSystemTools.cxx 82 KB

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