cmSystemTools.cxx 89 KB

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