cmSystemTools.cxx 91 KB

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