1
0

cmSystemTools.cxx 85 KB

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