cmSystemTools.cxx 75 KB

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