cmSystemTools.cxx 85 KB

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