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