cmSystemTools.cxx 90 KB

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