cmSystemTools.cxx 91 KB

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