cmSystemTools.cxx 75 KB

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