cmSystemTools.cxx 80 KB

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