cmSystemTools.cxx 82 KB

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