cmSystemTools.cxx 76 KB

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