cmSystemTools.cxx 88 KB

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