cmSystemTools.cxx 91 KB

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