cmSystemTools.cxx 83 KB

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