cmSystemTools.cxx 81 KB

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