cmSystemTools.cxx 84 KB

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