cmSystemTools.cxx 87 KB

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