cmSystemTools.cxx 83 KB

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