cmSystemTools.cxx 76 KB

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