cmSystemTools.cxx 89 KB

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