cmSystemTools.cxx 86 KB

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