cmSystemTools.cxx 90 KB

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