cmSystemTools.cxx 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010
  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. # ifndef INVALID_FILE_ATTRIBUTES
  1098. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  1099. # endif
  1100. /* Windows MoveFileEx may not replace read-only or in-use files. If it
  1101. fails then remove the read-only attribute from any existing destination.
  1102. Try multiple times since we may be racing against another process
  1103. creating/opening the destination file just before our MoveFileEx. */
  1104. int tries = 5;
  1105. while(!MoveFileEx(oldname, newname, MOVEFILE_REPLACE_EXISTING) && --tries)
  1106. {
  1107. // Try again only if failure was due to access permissions.
  1108. if(GetLastError() != ERROR_ACCESS_DENIED)
  1109. {
  1110. return false;
  1111. }
  1112. DWORD attrs = GetFileAttributes(newname);
  1113. if((attrs != INVALID_FILE_ATTRIBUTES) &&
  1114. (attrs & FILE_ATTRIBUTE_READONLY))
  1115. {
  1116. // Remove the read-only attribute from the destination file.
  1117. SetFileAttributes(newname, attrs & ~FILE_ATTRIBUTE_READONLY);
  1118. }
  1119. else
  1120. {
  1121. // The file may be temporarily in use so wait a bit.
  1122. cmSystemTools::Delay(100);
  1123. }
  1124. }
  1125. return tries > 0;
  1126. #else
  1127. /* On UNIX we have an OS-provided call to do this atomically. */
  1128. return rename(oldname, newname) == 0;
  1129. #endif
  1130. }
  1131. bool cmSystemTools::ComputeFileMD5(const char* source, char* md5out)
  1132. {
  1133. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1134. cmCryptoHashMD5 md5;
  1135. std::string str = md5.HashFile(source);
  1136. strncpy(md5out, str.c_str(), 32);
  1137. return !str.empty();
  1138. #else
  1139. (void)source;
  1140. (void)md5out;
  1141. cmSystemTools::Message("md5sum not supported in bootstrapping mode","Error");
  1142. return false;
  1143. #endif
  1144. }
  1145. std::string cmSystemTools::ComputeStringMD5(const char* input)
  1146. {
  1147. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1148. cmCryptoHashMD5 md5;
  1149. return md5.HashString(input);
  1150. #else
  1151. (void)input;
  1152. cmSystemTools::Message("md5sum not supported in bootstrapping mode","Error");
  1153. return "";
  1154. #endif
  1155. }
  1156. void cmSystemTools::Glob(const char *directory, const char *regexp,
  1157. std::vector<std::string>& files)
  1158. {
  1159. cmsys::Directory d;
  1160. cmsys::RegularExpression reg(regexp);
  1161. if (d.Load(directory))
  1162. {
  1163. size_t numf;
  1164. unsigned int i;
  1165. numf = d.GetNumberOfFiles();
  1166. for (i = 0; i < numf; i++)
  1167. {
  1168. std::string fname = d.GetFile(i);
  1169. if (reg.find(fname))
  1170. {
  1171. files.push_back(fname);
  1172. }
  1173. }
  1174. }
  1175. }
  1176. void cmSystemTools::GlobDirs(const char *fullPath,
  1177. std::vector<std::string>& files)
  1178. {
  1179. std::string path = fullPath;
  1180. std::string::size_type pos = path.find("/*");
  1181. if(pos == std::string::npos)
  1182. {
  1183. files.push_back(fullPath);
  1184. return;
  1185. }
  1186. std::string startPath = path.substr(0, pos);
  1187. std::string finishPath = path.substr(pos+2);
  1188. cmsys::Directory d;
  1189. if (d.Load(startPath.c_str()))
  1190. {
  1191. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  1192. {
  1193. if((std::string(d.GetFile(i)) != ".")
  1194. && (std::string(d.GetFile(i)) != ".."))
  1195. {
  1196. std::string fname = startPath;
  1197. fname +="/";
  1198. fname += d.GetFile(i);
  1199. if(cmSystemTools::FileIsDirectory(fname.c_str()))
  1200. {
  1201. fname += finishPath;
  1202. cmSystemTools::GlobDirs(fname.c_str(), files);
  1203. }
  1204. }
  1205. }
  1206. }
  1207. }
  1208. void cmSystemTools::ExpandList(std::vector<std::string> const& arguments,
  1209. std::vector<std::string>& newargs)
  1210. {
  1211. std::vector<std::string>::const_iterator i;
  1212. for(i = arguments.begin();i != arguments.end(); ++i)
  1213. {
  1214. cmSystemTools::ExpandListArgument(*i, newargs);
  1215. }
  1216. }
  1217. void cmSystemTools::ExpandListArgument(const std::string& arg,
  1218. std::vector<std::string>& newargs,
  1219. bool emptyArgs)
  1220. {
  1221. // If argument is empty, it is an empty list.
  1222. if(arg.length() == 0 && !emptyArgs)
  1223. {
  1224. return;
  1225. }
  1226. // if there are no ; in the name then just copy the current string
  1227. if(arg.find(';') == std::string::npos)
  1228. {
  1229. newargs.push_back(arg);
  1230. return;
  1231. }
  1232. std::vector<char> newArgVec;
  1233. // Break the string at non-escaped semicolons not nested in [].
  1234. int squareNesting = 0;
  1235. for(const char* c = arg.c_str(); *c; ++c)
  1236. {
  1237. switch(*c)
  1238. {
  1239. case '\\':
  1240. {
  1241. // We only want to allow escaping of semicolons. Other
  1242. // escapes should not be processed here.
  1243. ++c;
  1244. if(*c == ';')
  1245. {
  1246. newArgVec.push_back(*c);
  1247. }
  1248. else
  1249. {
  1250. newArgVec.push_back('\\');
  1251. if(*c)
  1252. {
  1253. newArgVec.push_back(*c);
  1254. }
  1255. else
  1256. {
  1257. // Terminate the loop properly.
  1258. --c;
  1259. }
  1260. }
  1261. } break;
  1262. case '[':
  1263. {
  1264. ++squareNesting;
  1265. newArgVec.push_back(*c);
  1266. } break;
  1267. case ']':
  1268. {
  1269. --squareNesting;
  1270. newArgVec.push_back(*c);
  1271. } break;
  1272. case ';':
  1273. {
  1274. // Break the string here if we are not nested inside square
  1275. // brackets.
  1276. if(squareNesting == 0)
  1277. {
  1278. if ( newArgVec.size() || emptyArgs )
  1279. {
  1280. // Add the last argument if the string is not empty.
  1281. newArgVec.push_back(0);
  1282. newargs.push_back(&*newArgVec.begin());
  1283. newArgVec.clear();
  1284. }
  1285. }
  1286. else
  1287. {
  1288. newArgVec.push_back(*c);
  1289. }
  1290. } break;
  1291. default:
  1292. {
  1293. // Just append this character.
  1294. newArgVec.push_back(*c);
  1295. } break;
  1296. }
  1297. }
  1298. if ( newArgVec.size() || emptyArgs )
  1299. {
  1300. // Add the last argument if the string is not empty.
  1301. newArgVec.push_back(0);
  1302. newargs.push_back(&*newArgVec.begin());
  1303. }
  1304. }
  1305. bool cmSystemTools::SimpleGlob(const cmStdString& glob,
  1306. std::vector<cmStdString>& files,
  1307. int type /* = 0 */)
  1308. {
  1309. files.clear();
  1310. if ( glob[glob.size()-1] != '*' )
  1311. {
  1312. return false;
  1313. }
  1314. std::string path = cmSystemTools::GetFilenamePath(glob);
  1315. std::string ppath = cmSystemTools::GetFilenameName(glob);
  1316. ppath = ppath.substr(0, ppath.size()-1);
  1317. if ( path.size() == 0 )
  1318. {
  1319. path = "/";
  1320. }
  1321. bool res = false;
  1322. cmsys::Directory d;
  1323. if (d.Load(path.c_str()))
  1324. {
  1325. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  1326. {
  1327. if((std::string(d.GetFile(i)) != ".")
  1328. && (std::string(d.GetFile(i)) != ".."))
  1329. {
  1330. std::string fname = path;
  1331. if ( path[path.size()-1] != '/' )
  1332. {
  1333. fname +="/";
  1334. }
  1335. fname += d.GetFile(i);
  1336. std::string sfname = d.GetFile(i);
  1337. if ( type > 0 && cmSystemTools::FileIsDirectory(fname.c_str()) )
  1338. {
  1339. continue;
  1340. }
  1341. if ( type < 0 && !cmSystemTools::FileIsDirectory(fname.c_str()) )
  1342. {
  1343. continue;
  1344. }
  1345. if ( sfname.size() >= ppath.size() &&
  1346. sfname.substr(0, ppath.size()) ==
  1347. ppath )
  1348. {
  1349. files.push_back(fname);
  1350. res = true;
  1351. }
  1352. }
  1353. }
  1354. }
  1355. return res;
  1356. }
  1357. cmSystemTools::FileFormat cmSystemTools::GetFileFormat(const char* cext)
  1358. {
  1359. if ( ! cext || *cext == 0 )
  1360. {
  1361. return cmSystemTools::NO_FILE_FORMAT;
  1362. }
  1363. //std::string ext = cmSystemTools::LowerCase(cext);
  1364. std::string ext = cext;
  1365. if ( ext == "c" || ext == ".c" ||
  1366. ext == "m" || ext == ".m"
  1367. ) { return cmSystemTools::C_FILE_FORMAT; }
  1368. if (
  1369. ext == "C" || ext == ".C" ||
  1370. ext == "M" || ext == ".M" ||
  1371. ext == "c++" || ext == ".c++" ||
  1372. ext == "cc" || ext == ".cc" ||
  1373. ext == "cpp" || ext == ".cpp" ||
  1374. ext == "cxx" || ext == ".cxx" ||
  1375. ext == "mm" || ext == ".mm"
  1376. ) { return cmSystemTools::CXX_FILE_FORMAT; }
  1377. if (
  1378. ext == "f" || ext == ".f" ||
  1379. ext == "F" || ext == ".F" ||
  1380. ext == "f77" || ext == ".f77" ||
  1381. ext == "f90" || ext == ".f90" ||
  1382. ext == "for" || ext == ".for" ||
  1383. ext == "f95" || ext == ".f95"
  1384. ) { return cmSystemTools::FORTRAN_FILE_FORMAT; }
  1385. if ( ext == "java" || ext == ".java" )
  1386. { return cmSystemTools::JAVA_FILE_FORMAT; }
  1387. if (
  1388. ext == "H" || ext == ".H" ||
  1389. ext == "h" || ext == ".h" ||
  1390. ext == "h++" || ext == ".h++" ||
  1391. ext == "hm" || ext == ".hm" ||
  1392. ext == "hpp" || ext == ".hpp" ||
  1393. ext == "hxx" || ext == ".hxx" ||
  1394. ext == "in" || ext == ".in" ||
  1395. ext == "txx" || ext == ".txx"
  1396. ) { return cmSystemTools::HEADER_FILE_FORMAT; }
  1397. if ( ext == "rc" || ext == ".rc" )
  1398. { return cmSystemTools::RESOURCE_FILE_FORMAT; }
  1399. if ( ext == "def" || ext == ".def" )
  1400. { return cmSystemTools::DEFINITION_FILE_FORMAT; }
  1401. if ( ext == "lib" || ext == ".lib" ||
  1402. ext == "a" || ext == ".a")
  1403. { return cmSystemTools::STATIC_LIBRARY_FILE_FORMAT; }
  1404. if ( ext == "o" || ext == ".o" ||
  1405. ext == "obj" || ext == ".obj")
  1406. { return cmSystemTools::OBJECT_FILE_FORMAT; }
  1407. #ifdef __APPLE__
  1408. if ( ext == "dylib" || ext == ".dylib" )
  1409. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  1410. if ( ext == "so" || ext == ".so" ||
  1411. ext == "bundle" || ext == ".bundle" )
  1412. { return cmSystemTools::MODULE_FILE_FORMAT; }
  1413. #else // __APPLE__
  1414. if ( ext == "so" || ext == ".so" ||
  1415. ext == "sl" || ext == ".sl" ||
  1416. ext == "dll" || ext == ".dll" )
  1417. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  1418. #endif // __APPLE__
  1419. return cmSystemTools::UNKNOWN_FILE_FORMAT;
  1420. }
  1421. bool cmSystemTools::Split(const char* s, std::vector<cmStdString>& l)
  1422. {
  1423. std::vector<std::string> temp;
  1424. bool res = Superclass::Split(s, temp);
  1425. for(std::vector<std::string>::const_iterator i = temp.begin();
  1426. i != temp.end(); ++i)
  1427. {
  1428. l.push_back(*i);
  1429. }
  1430. return res;
  1431. }
  1432. std::string cmSystemTools::ConvertToOutputPath(const char* path)
  1433. {
  1434. #if defined(_WIN32) && !defined(__CYGWIN__)
  1435. if(s_ForceUnixPaths)
  1436. {
  1437. return cmSystemTools::ConvertToUnixOutputPath(path);
  1438. }
  1439. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1440. #else
  1441. return cmSystemTools::ConvertToUnixOutputPath(path);
  1442. #endif
  1443. }
  1444. void cmSystemTools::ConvertToOutputSlashes(std::string& path)
  1445. {
  1446. #if defined(_WIN32) && !defined(__CYGWIN__)
  1447. if(!s_ForceUnixPaths)
  1448. {
  1449. // Convert to windows slashes.
  1450. std::string::size_type pos = 0;
  1451. while((pos = path.find('/', pos)) != std::string::npos)
  1452. {
  1453. path[pos++] = '\\';
  1454. }
  1455. }
  1456. #else
  1457. static_cast<void>(path);
  1458. #endif
  1459. }
  1460. std::string cmSystemTools::ConvertToRunCommandPath(const char* path)
  1461. {
  1462. #if defined(_WIN32) && !defined(__CYGWIN__)
  1463. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1464. #else
  1465. return cmSystemTools::ConvertToUnixOutputPath(path);
  1466. #endif
  1467. }
  1468. bool cmSystemTools::StringEndsWith(const char* str1, const char* str2)
  1469. {
  1470. if ( !str1 || !str2 || strlen(str1) < strlen(str2) )
  1471. {
  1472. return 0;
  1473. }
  1474. return !strncmp(str1 + (strlen(str1)-strlen(str2)), str2, strlen(str2));
  1475. }
  1476. // compute the relative path from here to there
  1477. std::string cmSystemTools::RelativePath(const char* local, const char* remote)
  1478. {
  1479. if(!cmSystemTools::FileIsFullPath(local))
  1480. {
  1481. cmSystemTools::Error("RelativePath must be passed a full path to local: ",
  1482. local);
  1483. }
  1484. if(!cmSystemTools::FileIsFullPath(remote))
  1485. {
  1486. cmSystemTools::Error
  1487. ("RelativePath must be passed a full path to remote: ", remote);
  1488. }
  1489. return cmsys::SystemTools::RelativePath(local, remote);
  1490. }
  1491. std::string cmSystemTools::CollapseCombinedPath(std::string const& dir,
  1492. std::string const& file)
  1493. {
  1494. if(dir.empty() || dir == ".")
  1495. {
  1496. return file;
  1497. }
  1498. std::vector<std::string> dirComponents;
  1499. std::vector<std::string> fileComponents;
  1500. cmSystemTools::SplitPath(dir.c_str(), dirComponents);
  1501. cmSystemTools::SplitPath(file.c_str(), fileComponents);
  1502. if(fileComponents.empty())
  1503. {
  1504. return dir;
  1505. }
  1506. if(fileComponents[0] != "")
  1507. {
  1508. // File is not a relative path.
  1509. return file;
  1510. }
  1511. std::vector<std::string>::iterator i = fileComponents.begin()+1;
  1512. while(i != fileComponents.end() && *i == ".." && dirComponents.size() > 1)
  1513. {
  1514. ++i; // Remove ".." file component.
  1515. dirComponents.pop_back(); // Remove last dir component.
  1516. }
  1517. dirComponents.insert(dirComponents.end(), i, fileComponents.end());
  1518. return cmSystemTools::JoinPath(dirComponents);
  1519. }
  1520. #ifdef CMAKE_BUILD_WITH_CMAKE
  1521. //----------------------------------------------------------------------
  1522. bool cmSystemTools::UnsetEnv(const char* value)
  1523. {
  1524. #if !defined(HAVE_UNSETENV)
  1525. std::string var = value;
  1526. var += "=";
  1527. return cmSystemTools::PutEnv(var.c_str());
  1528. #else
  1529. unsetenv(value);
  1530. return true;
  1531. #endif
  1532. }
  1533. //----------------------------------------------------------------------
  1534. std::vector<std::string> cmSystemTools::GetEnvironmentVariables()
  1535. {
  1536. std::vector<std::string> env;
  1537. int cc;
  1538. for ( cc = 0; environ[cc]; ++ cc )
  1539. {
  1540. env.push_back(environ[cc]);
  1541. }
  1542. return env;
  1543. }
  1544. //----------------------------------------------------------------------
  1545. void cmSystemTools::AppendEnv(std::vector<std::string> const& env)
  1546. {
  1547. for(std::vector<std::string>::const_iterator eit = env.begin();
  1548. eit != env.end(); ++eit)
  1549. {
  1550. cmSystemTools::PutEnv(eit->c_str());
  1551. }
  1552. }
  1553. //----------------------------------------------------------------------
  1554. cmSystemTools::SaveRestoreEnvironment::SaveRestoreEnvironment()
  1555. {
  1556. this->Env = cmSystemTools::GetEnvironmentVariables();
  1557. }
  1558. //----------------------------------------------------------------------
  1559. cmSystemTools::SaveRestoreEnvironment::~SaveRestoreEnvironment()
  1560. {
  1561. // First clear everything in the current environment:
  1562. std::vector<std::string> currentEnv = GetEnvironmentVariables();
  1563. for(std::vector<std::string>::const_iterator
  1564. eit = currentEnv.begin(); eit != currentEnv.end(); ++eit)
  1565. {
  1566. std::string var(*eit);
  1567. std::string::size_type pos = var.find("=");
  1568. if (pos != std::string::npos)
  1569. {
  1570. var = var.substr(0, pos);
  1571. }
  1572. cmSystemTools::UnsetEnv(var.c_str());
  1573. }
  1574. // Then put back each entry from the original environment:
  1575. cmSystemTools::AppendEnv(this->Env);
  1576. }
  1577. #endif
  1578. void cmSystemTools::EnableVSConsoleOutput()
  1579. {
  1580. #ifdef _WIN32
  1581. // Visual Studio 8 2005 (devenv.exe or VCExpress.exe) will not
  1582. // display output to the console unless this environment variable is
  1583. // set. We need it to capture the output of these build tools.
  1584. // Note for future work that one could pass "/out \\.\pipe\NAME" to
  1585. // either of these executables where NAME is created with
  1586. // CreateNamedPipe. This would bypass the internal buffering of the
  1587. // output and allow it to be captured on the fly.
  1588. cmSystemTools::PutEnv("vsconsoleoutput=1");
  1589. # ifdef CMAKE_BUILD_WITH_CMAKE
  1590. // VS sets an environment variable to tell MS tools like "cl" to report
  1591. // output through a backdoor pipe instead of stdout/stderr. Unset the
  1592. // environment variable to close this backdoor for any path of process
  1593. // invocations that passes through CMake so we can capture the output.
  1594. cmSystemTools::UnsetEnv("VS_UNICODE_OUTPUT");
  1595. # endif
  1596. #endif
  1597. }
  1598. bool cmSystemTools::IsPathToFramework(const char* path)
  1599. {
  1600. if(cmSystemTools::FileIsFullPath(path))
  1601. {
  1602. std::string libname = path;
  1603. if(libname.find(".framework") == libname.size()+1-sizeof(".framework"))
  1604. {
  1605. return true;
  1606. }
  1607. }
  1608. return false;
  1609. }
  1610. bool cmSystemTools::CreateTar(const char* outFileName,
  1611. const std::vector<cmStdString>& files,
  1612. bool gzip, bool bzip2, bool verbose)
  1613. {
  1614. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1615. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1616. std::ofstream fout(outFileName, std::ios::out | cmsys_ios_binary);
  1617. if(!fout)
  1618. {
  1619. std::string e = "Cannot open output file \"";
  1620. e += outFileName;
  1621. e += "\": ";
  1622. e += cmSystemTools::GetLastSystemError();
  1623. cmSystemTools::Error(e.c_str());
  1624. return false;
  1625. }
  1626. cmArchiveWrite a(fout, (gzip? cmArchiveWrite::CompressGZip :
  1627. (bzip2? cmArchiveWrite::CompressBZip2 :
  1628. cmArchiveWrite::CompressNone)),
  1629. cmArchiveWrite::TypeTAR);
  1630. a.SetVerbose(verbose);
  1631. for(std::vector<cmStdString>::const_iterator i = files.begin();
  1632. i != files.end(); ++i)
  1633. {
  1634. std::string path = *i;
  1635. if(cmSystemTools::FileIsFullPath(path.c_str()))
  1636. {
  1637. // Get the relative path to the file.
  1638. path = cmSystemTools::RelativePath(cwd.c_str(), path.c_str());
  1639. }
  1640. if(!a.Add(path))
  1641. {
  1642. break;
  1643. }
  1644. }
  1645. if(!a)
  1646. {
  1647. cmSystemTools::Error(a.GetError().c_str());
  1648. return false;
  1649. }
  1650. return true;
  1651. #else
  1652. (void)outFileName;
  1653. (void)files;
  1654. (void)gzip;
  1655. (void)verbose;
  1656. return false;
  1657. #endif
  1658. }
  1659. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1660. namespace{
  1661. #define BSDTAR_FILESIZE_PRINTF "%lu"
  1662. #define BSDTAR_FILESIZE_TYPE unsigned long
  1663. void
  1664. list_item_verbose(FILE *out, struct archive_entry *entry)
  1665. {
  1666. char tmp[100];
  1667. size_t w;
  1668. const char *p;
  1669. const char *fmt;
  1670. time_t tim;
  1671. static time_t now;
  1672. size_t u_width = 6;
  1673. size_t gs_width = 13;
  1674. /*
  1675. * We avoid collecting the entire list in memory at once by
  1676. * listing things as we see them. However, that also means we can't
  1677. * just pre-compute the field widths. Instead, we start with guesses
  1678. * and just widen them as necessary. These numbers are completely
  1679. * arbitrary.
  1680. */
  1681. if (!now)
  1682. {
  1683. time(&now);
  1684. }
  1685. fprintf(out, "%s %d ",
  1686. archive_entry_strmode(entry),
  1687. archive_entry_nlink(entry));
  1688. /* Use uname if it's present, else uid. */
  1689. p = archive_entry_uname(entry);
  1690. if ((p == NULL) || (*p == '\0'))
  1691. {
  1692. sprintf(tmp, "%lu ",
  1693. (unsigned long)archive_entry_uid(entry));
  1694. p = tmp;
  1695. }
  1696. w = strlen(p);
  1697. if (w > u_width)
  1698. {
  1699. u_width = w;
  1700. }
  1701. fprintf(out, "%-*s ", (int)u_width, p);
  1702. /* Use gname if it's present, else gid. */
  1703. p = archive_entry_gname(entry);
  1704. if (p != NULL && p[0] != '\0')
  1705. {
  1706. fprintf(out, "%s", p);
  1707. w = strlen(p);
  1708. }
  1709. else
  1710. {
  1711. sprintf(tmp, "%lu",
  1712. (unsigned long)archive_entry_gid(entry));
  1713. w = strlen(tmp);
  1714. fprintf(out, "%s", tmp);
  1715. }
  1716. /*
  1717. * Print device number or file size, right-aligned so as to make
  1718. * total width of group and devnum/filesize fields be gs_width.
  1719. * If gs_width is too small, grow it.
  1720. */
  1721. if (archive_entry_filetype(entry) == AE_IFCHR
  1722. || archive_entry_filetype(entry) == AE_IFBLK)
  1723. {
  1724. sprintf(tmp, "%lu,%lu",
  1725. (unsigned long)archive_entry_rdevmajor(entry),
  1726. (unsigned long)archive_entry_rdevminor(entry));
  1727. }
  1728. else
  1729. {
  1730. /*
  1731. * Note the use of platform-dependent macros to format
  1732. * the filesize here. We need the format string and the
  1733. * corresponding type for the cast.
  1734. */
  1735. sprintf(tmp, BSDTAR_FILESIZE_PRINTF,
  1736. (BSDTAR_FILESIZE_TYPE)archive_entry_size(entry));
  1737. }
  1738. if (w + strlen(tmp) >= gs_width)
  1739. {
  1740. gs_width = w+strlen(tmp)+1;
  1741. }
  1742. fprintf(out, "%*s", (int)(gs_width - w), tmp);
  1743. /* Format the time using 'ls -l' conventions. */
  1744. tim = archive_entry_mtime(entry);
  1745. #define HALF_YEAR (time_t)365 * 86400 / 2
  1746. #if defined(_WIN32) && !defined(__CYGWIN__)
  1747. /* Windows' strftime function does not support %e format. */
  1748. #define DAY_FMT "%d"
  1749. #else
  1750. #define DAY_FMT "%e" /* Day number without leading zeros */
  1751. #endif
  1752. if (tim < now - HALF_YEAR || tim > now + HALF_YEAR)
  1753. {
  1754. fmt = DAY_FMT " %b %Y";
  1755. }
  1756. else
  1757. {
  1758. fmt = DAY_FMT " %b %H:%M";
  1759. }
  1760. strftime(tmp, sizeof(tmp), fmt, localtime(&tim));
  1761. fprintf(out, " %s ", tmp);
  1762. fprintf(out, "%s", archive_entry_pathname(entry));
  1763. /* Extra information for links. */
  1764. if (archive_entry_hardlink(entry)) /* Hard link */
  1765. {
  1766. fprintf(out, " link to %s",
  1767. archive_entry_hardlink(entry));
  1768. }
  1769. else if (archive_entry_symlink(entry)) /* Symbolic link */
  1770. {
  1771. fprintf(out, " -> %s", archive_entry_symlink(entry));
  1772. }
  1773. }
  1774. #ifdef __BORLANDC__
  1775. # pragma warn -8066 /* unreachable code */
  1776. #endif
  1777. long copy_data(struct archive *ar, struct archive *aw)
  1778. {
  1779. long r;
  1780. const void *buff;
  1781. size_t size;
  1782. #if defined(ARCHIVE_VERSION_NUMBER) && ARCHIVE_VERSION_NUMBER >= 3000000
  1783. __LA_INT64_T offset;
  1784. #else
  1785. off_t offset;
  1786. #endif
  1787. for (;;)
  1788. {
  1789. r = archive_read_data_block(ar, &buff, &size, &offset);
  1790. if (r == ARCHIVE_EOF)
  1791. {
  1792. return (ARCHIVE_OK);
  1793. }
  1794. if (r != ARCHIVE_OK)
  1795. {
  1796. return (r);
  1797. }
  1798. r = archive_write_data_block(aw, buff, size, offset);
  1799. if (r != ARCHIVE_OK)
  1800. {
  1801. cmSystemTools::Message("archive_write_data_block()",
  1802. archive_error_string(aw));
  1803. return (r);
  1804. }
  1805. }
  1806. return r;
  1807. }
  1808. bool extract_tar(const char* outFileName, bool verbose,
  1809. bool extract)
  1810. {
  1811. struct archive* a = archive_read_new();
  1812. struct archive *ext = archive_write_disk_new();
  1813. archive_read_support_compression_all(a);
  1814. archive_read_support_format_all(a);
  1815. struct archive_entry *entry;
  1816. int r = archive_read_open_file(a, outFileName, 10240);
  1817. if(r)
  1818. {
  1819. cmSystemTools::Error("Problem with archive_read_open_file(): ",
  1820. archive_error_string(a));
  1821. return false;
  1822. }
  1823. for (;;)
  1824. {
  1825. r = archive_read_next_header(a, &entry);
  1826. if (r == ARCHIVE_EOF)
  1827. {
  1828. break;
  1829. }
  1830. if (r != ARCHIVE_OK)
  1831. {
  1832. cmSystemTools::Error("Problem with archive_read_next_header(): ",
  1833. archive_error_string(a));
  1834. break;
  1835. }
  1836. if (verbose && extract)
  1837. {
  1838. cmSystemTools::Stdout("x ");
  1839. cmSystemTools::Stdout(archive_entry_pathname(entry));
  1840. }
  1841. if(verbose && !extract)
  1842. {
  1843. list_item_verbose(stdout, entry);
  1844. }
  1845. else if(!extract)
  1846. {
  1847. cmSystemTools::Stdout(archive_entry_pathname(entry));
  1848. }
  1849. if(extract)
  1850. {
  1851. r = archive_write_disk_set_options(ext, ARCHIVE_EXTRACT_TIME);
  1852. if (r != ARCHIVE_OK)
  1853. {
  1854. cmSystemTools::Error(
  1855. "Problem with archive_write_disk_set_options(): ",
  1856. archive_error_string(ext));
  1857. break;
  1858. }
  1859. r = archive_write_header(ext, entry);
  1860. if (r != ARCHIVE_OK)
  1861. {
  1862. cmSystemTools::Error("Problem with archive_write_header(): ",
  1863. archive_error_string(ext));
  1864. cmSystemTools::Error("Current file: ",
  1865. archive_entry_pathname(entry));
  1866. break;
  1867. }
  1868. else
  1869. {
  1870. copy_data(a, ext);
  1871. r = archive_write_finish_entry(ext);
  1872. if (r != ARCHIVE_OK)
  1873. {
  1874. cmSystemTools::Error("Problem with archive_write_finish_entry(): ",
  1875. archive_error_string(ext));
  1876. break;
  1877. }
  1878. }
  1879. }
  1880. if (verbose || !extract)
  1881. {
  1882. cmSystemTools::Stdout("\n");
  1883. }
  1884. }
  1885. archive_read_close(a);
  1886. archive_read_finish(a);
  1887. return r == ARCHIVE_EOF || r == ARCHIVE_OK;
  1888. }
  1889. }
  1890. #endif
  1891. bool cmSystemTools::ExtractTar(const char* outFileName,
  1892. bool , bool verbose)
  1893. {
  1894. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1895. return extract_tar(outFileName, verbose, true);
  1896. #else
  1897. (void)outFileName;
  1898. (void)verbose;
  1899. return false;
  1900. #endif
  1901. }
  1902. bool cmSystemTools::ListTar(const char* outFileName,
  1903. bool ,
  1904. bool verbose)
  1905. {
  1906. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1907. return extract_tar(outFileName, verbose, false);
  1908. #else
  1909. (void)outFileName;
  1910. (void)verbose;
  1911. return false;
  1912. #endif
  1913. }
  1914. int cmSystemTools::WaitForLine(cmsysProcess* process, std::string& line,
  1915. double timeout,
  1916. std::vector<char>& out,
  1917. std::vector<char>& err)
  1918. {
  1919. line = "";
  1920. std::vector<char>::iterator outiter = out.begin();
  1921. std::vector<char>::iterator erriter = err.begin();
  1922. while(1)
  1923. {
  1924. // Check for a newline in stdout.
  1925. for(;outiter != out.end(); ++outiter)
  1926. {
  1927. if((*outiter == '\r') && ((outiter+1) == out.end()))
  1928. {
  1929. break;
  1930. }
  1931. else if(*outiter == '\n' || *outiter == '\0')
  1932. {
  1933. std::vector<char>::size_type length = outiter-out.begin();
  1934. if(length > 1 && *(outiter-1) == '\r')
  1935. {
  1936. --length;
  1937. }
  1938. if(length > 0)
  1939. {
  1940. line.append(&out[0], length);
  1941. }
  1942. out.erase(out.begin(), outiter+1);
  1943. return cmsysProcess_Pipe_STDOUT;
  1944. }
  1945. }
  1946. // Check for a newline in stderr.
  1947. for(;erriter != err.end(); ++erriter)
  1948. {
  1949. if((*erriter == '\r') && ((erriter+1) == err.end()))
  1950. {
  1951. break;
  1952. }
  1953. else if(*erriter == '\n' || *erriter == '\0')
  1954. {
  1955. std::vector<char>::size_type length = erriter-err.begin();
  1956. if(length > 1 && *(erriter-1) == '\r')
  1957. {
  1958. --length;
  1959. }
  1960. if(length > 0)
  1961. {
  1962. line.append(&err[0], length);
  1963. }
  1964. err.erase(err.begin(), erriter+1);
  1965. return cmsysProcess_Pipe_STDERR;
  1966. }
  1967. }
  1968. // No newlines found. Wait for more data from the process.
  1969. int length;
  1970. char* data;
  1971. int pipe = cmsysProcess_WaitForData(process, &data, &length, &timeout);
  1972. if(pipe == cmsysProcess_Pipe_Timeout)
  1973. {
  1974. // Timeout has been exceeded.
  1975. return pipe;
  1976. }
  1977. else if(pipe == cmsysProcess_Pipe_STDOUT)
  1978. {
  1979. // Append to the stdout buffer.
  1980. std::vector<char>::size_type size = out.size();
  1981. out.insert(out.end(), data, data+length);
  1982. outiter = out.begin()+size;
  1983. }
  1984. else if(pipe == cmsysProcess_Pipe_STDERR)
  1985. {
  1986. // Append to the stderr buffer.
  1987. std::vector<char>::size_type size = err.size();
  1988. err.insert(err.end(), data, data+length);
  1989. erriter = err.begin()+size;
  1990. }
  1991. else if(pipe == cmsysProcess_Pipe_None)
  1992. {
  1993. // Both stdout and stderr pipes have broken. Return leftover data.
  1994. if(!out.empty())
  1995. {
  1996. line.append(&out[0], outiter-out.begin());
  1997. out.erase(out.begin(), out.end());
  1998. return cmsysProcess_Pipe_STDOUT;
  1999. }
  2000. else if(!err.empty())
  2001. {
  2002. line.append(&err[0], erriter-err.begin());
  2003. err.erase(err.begin(), err.end());
  2004. return cmsysProcess_Pipe_STDERR;
  2005. }
  2006. else
  2007. {
  2008. return cmsysProcess_Pipe_None;
  2009. }
  2010. }
  2011. }
  2012. }
  2013. void cmSystemTools::DoNotInheritStdPipes()
  2014. {
  2015. #ifdef _WIN32
  2016. // Check to see if we are attached to a console
  2017. // if so, then do not stop the inherited pipes
  2018. // or stdout and stderr will not show up in dos
  2019. // shell windows
  2020. CONSOLE_SCREEN_BUFFER_INFO hOutInfo;
  2021. HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
  2022. if(GetConsoleScreenBufferInfo(hOut, &hOutInfo))
  2023. {
  2024. return;
  2025. }
  2026. {
  2027. HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
  2028. DuplicateHandle(GetCurrentProcess(), out,
  2029. GetCurrentProcess(), &out, 0, FALSE,
  2030. DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  2031. SetStdHandle(STD_OUTPUT_HANDLE, out);
  2032. }
  2033. {
  2034. HANDLE out = GetStdHandle(STD_ERROR_HANDLE);
  2035. DuplicateHandle(GetCurrentProcess(), out,
  2036. GetCurrentProcess(), &out, 0, FALSE,
  2037. DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  2038. SetStdHandle(STD_ERROR_HANDLE, out);
  2039. }
  2040. #endif
  2041. }
  2042. //----------------------------------------------------------------------------
  2043. bool cmSystemTools::CopyFileTime(const char* fromFile, const char* toFile)
  2044. {
  2045. #if defined(_WIN32) && !defined(__CYGWIN__)
  2046. cmSystemToolsWindowsHandle hFrom =
  2047. CreateFile(fromFile, GENERIC_READ, FILE_SHARE_READ, 0,
  2048. OPEN_EXISTING, 0, 0);
  2049. cmSystemToolsWindowsHandle hTo =
  2050. CreateFile(toFile, GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
  2051. if(!hFrom || !hTo)
  2052. {
  2053. return false;
  2054. }
  2055. FILETIME timeCreation;
  2056. FILETIME timeLastAccess;
  2057. FILETIME timeLastWrite;
  2058. if(!GetFileTime(hFrom, &timeCreation, &timeLastAccess, &timeLastWrite))
  2059. {
  2060. return false;
  2061. }
  2062. if(!SetFileTime(hTo, &timeCreation, &timeLastAccess, &timeLastWrite))
  2063. {
  2064. return false;
  2065. }
  2066. #else
  2067. struct stat fromStat;
  2068. if(stat(fromFile, &fromStat) < 0)
  2069. {
  2070. return false;
  2071. }
  2072. struct utimbuf buf;
  2073. buf.actime = fromStat.st_atime;
  2074. buf.modtime = fromStat.st_mtime;
  2075. if(utime(toFile, &buf) < 0)
  2076. {
  2077. return false;
  2078. }
  2079. #endif
  2080. return true;
  2081. }
  2082. //----------------------------------------------------------------------------
  2083. cmSystemToolsFileTime* cmSystemTools::FileTimeNew()
  2084. {
  2085. return new cmSystemToolsFileTime;
  2086. }
  2087. //----------------------------------------------------------------------------
  2088. void cmSystemTools::FileTimeDelete(cmSystemToolsFileTime* t)
  2089. {
  2090. delete t;
  2091. }
  2092. //----------------------------------------------------------------------------
  2093. bool cmSystemTools::FileTimeGet(const char* fname, cmSystemToolsFileTime* t)
  2094. {
  2095. #if defined(_WIN32) && !defined(__CYGWIN__)
  2096. cmSystemToolsWindowsHandle h =
  2097. CreateFile(fname, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
  2098. if(!h)
  2099. {
  2100. return false;
  2101. }
  2102. if(!GetFileTime(h, &t->timeCreation, &t->timeLastAccess, &t->timeLastWrite))
  2103. {
  2104. return false;
  2105. }
  2106. #else
  2107. struct stat st;
  2108. if(stat(fname, &st) < 0)
  2109. {
  2110. return false;
  2111. }
  2112. t->timeBuf.actime = st.st_atime;
  2113. t->timeBuf.modtime = st.st_mtime;
  2114. #endif
  2115. return true;
  2116. }
  2117. //----------------------------------------------------------------------------
  2118. bool cmSystemTools::FileTimeSet(const char* fname, cmSystemToolsFileTime* t)
  2119. {
  2120. #if defined(_WIN32) && !defined(__CYGWIN__)
  2121. cmSystemToolsWindowsHandle h =
  2122. CreateFile(fname, GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
  2123. if(!h)
  2124. {
  2125. return false;
  2126. }
  2127. if(!SetFileTime(h, &t->timeCreation, &t->timeLastAccess, &t->timeLastWrite))
  2128. {
  2129. return false;
  2130. }
  2131. #else
  2132. if(utime(fname, &t->timeBuf) < 0)
  2133. {
  2134. return false;
  2135. }
  2136. #endif
  2137. return true;
  2138. }
  2139. //----------------------------------------------------------------------------
  2140. #ifdef _WIN32
  2141. # ifndef CRYPT_SILENT
  2142. # define CRYPT_SILENT 0x40 /* Not defined by VS 6 version of header. */
  2143. # endif
  2144. static int WinCryptRandom(void* data, size_t size)
  2145. {
  2146. int result = 0;
  2147. HCRYPTPROV hProvider = 0;
  2148. if(CryptAcquireContextW(&hProvider, 0, 0, PROV_RSA_FULL,
  2149. CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
  2150. {
  2151. result = CryptGenRandom(hProvider, (DWORD)size, (BYTE*)data)? 1:0;
  2152. CryptReleaseContext(hProvider, 0);
  2153. }
  2154. return result;
  2155. }
  2156. #endif
  2157. //----------------------------------------------------------------------------
  2158. unsigned int cmSystemTools::RandomSeed()
  2159. {
  2160. #if defined(_WIN32) && !defined(__CYGWIN__)
  2161. unsigned int seed = 0;
  2162. // Try using a real random source.
  2163. if(WinCryptRandom(&seed, sizeof(seed)))
  2164. {
  2165. return seed;
  2166. }
  2167. // Fall back to the time and pid.
  2168. FILETIME ft;
  2169. GetSystemTimeAsFileTime(&ft);
  2170. unsigned int t1 = static_cast<unsigned int>(ft.dwHighDateTime);
  2171. unsigned int t2 = static_cast<unsigned int>(ft.dwLowDateTime);
  2172. unsigned int pid = static_cast<unsigned int>(GetCurrentProcessId());
  2173. return t1 ^ t2 ^ pid;
  2174. #else
  2175. union
  2176. {
  2177. unsigned int integer;
  2178. char bytes[sizeof(unsigned int)];
  2179. } seed;
  2180. // Try using a real random source.
  2181. std::ifstream fin("/dev/urandom");
  2182. if(fin && fin.read(seed.bytes, sizeof(seed)) &&
  2183. fin.gcount() == sizeof(seed))
  2184. {
  2185. return seed.integer;
  2186. }
  2187. // Fall back to the time and pid.
  2188. struct timeval t;
  2189. gettimeofday(&t, 0);
  2190. unsigned int pid = static_cast<unsigned int>(getpid());
  2191. unsigned int tv_sec = static_cast<unsigned int>(t.tv_sec);
  2192. unsigned int tv_usec = static_cast<unsigned int>(t.tv_usec);
  2193. // Since tv_usec never fills more than 11 bits we shift it to fill
  2194. // in the slow-changing high-order bits of tv_sec.
  2195. return tv_sec ^ (tv_usec << 21) ^ pid;
  2196. #endif
  2197. }
  2198. //----------------------------------------------------------------------------
  2199. static std::string cmSystemToolsExecutableDirectory;
  2200. void cmSystemTools::FindExecutableDirectory(const char* argv0)
  2201. {
  2202. #if defined(_WIN32) && !defined(__CYGWIN__)
  2203. (void)argv0; // ignore this on windows
  2204. char modulepath[_MAX_PATH];
  2205. ::GetModuleFileName(NULL, modulepath, sizeof(modulepath));
  2206. cmSystemToolsExecutableDirectory =
  2207. cmSystemTools::GetFilenamePath(modulepath);
  2208. return;
  2209. #else
  2210. std::string errorMsg;
  2211. std::string exe;
  2212. if(cmSystemTools::FindProgramPath(argv0, exe, errorMsg))
  2213. {
  2214. // remove symlinks
  2215. exe = cmSystemTools::GetRealPath(exe.c_str());
  2216. cmSystemToolsExecutableDirectory =
  2217. cmSystemTools::GetFilenamePath(exe.c_str());
  2218. }
  2219. else
  2220. {
  2221. // ???
  2222. }
  2223. #endif
  2224. }
  2225. //----------------------------------------------------------------------------
  2226. const char* cmSystemTools::GetExecutableDirectory()
  2227. {
  2228. return cmSystemToolsExecutableDirectory.c_str();
  2229. }
  2230. //----------------------------------------------------------------------------
  2231. #if defined(CMAKE_BUILD_WITH_CMAKE)
  2232. void cmSystemTools::MakefileColorEcho(int color, const char* message,
  2233. bool newline, bool enabled)
  2234. {
  2235. // On some platforms (an MSYS prompt) cmsysTerminal may not be able
  2236. // to determine whether the stream is displayed on a tty. In this
  2237. // case it assumes no unless we tell it otherwise. Since we want
  2238. // color messages to be displayed for users we will assume yes.
  2239. // However, we can test for some situations when the answer is most
  2240. // likely no.
  2241. int assumeTTY = cmsysTerminal_Color_AssumeTTY;
  2242. if(cmSystemTools::GetEnv("DART_TEST_FROM_DART") ||
  2243. cmSystemTools::GetEnv("DASHBOARD_TEST_FROM_CTEST") ||
  2244. cmSystemTools::GetEnv("CTEST_INTERACTIVE_DEBUG_MODE"))
  2245. {
  2246. // Avoid printing color escapes during dashboard builds.
  2247. assumeTTY = 0;
  2248. }
  2249. if(enabled)
  2250. {
  2251. cmsysTerminal_cfprintf(color | assumeTTY, stdout, "%s%s",
  2252. message, newline? "\n" : "");
  2253. }
  2254. else
  2255. {
  2256. // Color is disabled. Print without color.
  2257. fprintf(stdout, "%s%s", message, newline? "\n" : "");
  2258. }
  2259. }
  2260. #endif
  2261. //----------------------------------------------------------------------------
  2262. bool cmSystemTools::GuessLibrarySOName(std::string const& fullPath,
  2263. std::string& soname)
  2264. {
  2265. // For ELF shared libraries use a real parser to get the correct
  2266. // soname.
  2267. #if defined(CMAKE_USE_ELF_PARSER)
  2268. cmELF elf(fullPath.c_str());
  2269. if(elf)
  2270. {
  2271. return elf.GetSOName(soname);
  2272. }
  2273. #endif
  2274. // If the file is not a symlink we have no guess for its soname.
  2275. if(!cmSystemTools::FileIsSymlink(fullPath.c_str()))
  2276. {
  2277. return false;
  2278. }
  2279. if(!cmSystemTools::ReadSymlink(fullPath.c_str(), soname))
  2280. {
  2281. return false;
  2282. }
  2283. // If the symlink has a path component we have no guess for the soname.
  2284. if(!cmSystemTools::GetFilenamePath(soname).empty())
  2285. {
  2286. return false;
  2287. }
  2288. // If the symlink points at an extended version of the same name
  2289. // assume it is the soname.
  2290. std::string name = cmSystemTools::GetFilenameName(fullPath);
  2291. if(soname.length() > name.length() &&
  2292. soname.substr(0, name.length()) == name)
  2293. {
  2294. return true;
  2295. }
  2296. return false;
  2297. }
  2298. //----------------------------------------------------------------------------
  2299. bool cmSystemTools::GuessLibraryInstallName(std::string const& fullPath,
  2300. std::string& soname)
  2301. {
  2302. std::vector<cmStdString> cmds;
  2303. cmds.push_back("otool");
  2304. cmds.push_back("-D");
  2305. cmds.push_back(fullPath.c_str());
  2306. std::string output;
  2307. RunSingleCommand(cmds, &output, 0, 0, OUTPUT_NONE);
  2308. std::vector<std::string> strs = cmSystemTools::tokenize(output, "\n");
  2309. // otool returns extra lines reporting multiple install names
  2310. // in case the binary is multi-arch and none of the architectures
  2311. // is native (e.g. i386;ppc on x86_64)
  2312. if(strs.size() >= 2)
  2313. {
  2314. soname = strs[1];
  2315. return true;
  2316. }
  2317. return false;
  2318. }
  2319. //----------------------------------------------------------------------------
  2320. #if defined(CMAKE_USE_ELF_PARSER)
  2321. std::string::size_type cmSystemToolsFindRPath(std::string const& have,
  2322. std::string const& want)
  2323. {
  2324. // Search for the desired rpath.
  2325. std::string::size_type pos = have.find(want);
  2326. // If the path is not present we are done.
  2327. if(pos == std::string::npos)
  2328. {
  2329. return pos;
  2330. }
  2331. // Build a regex to match a properly separated path instance.
  2332. std::string regex_str = "(^|:)(";
  2333. for(std::string::const_iterator i = want.begin(); i != want.end(); ++i)
  2334. {
  2335. int ch = *i;
  2336. if(!(('a' <= ch && ch <= 'z') ||
  2337. ('A' <= ch && ch <= 'Z') ||
  2338. ('0' <= ch && ch <= '9')))
  2339. {
  2340. // Escape the non-alphanumeric character.
  2341. regex_str += "\\";
  2342. }
  2343. // Store the character.
  2344. regex_str.append(1, static_cast<char>(ch));
  2345. }
  2346. regex_str += ")(:|$)";
  2347. // Look for the separated path.
  2348. cmsys::RegularExpression regex(regex_str.c_str());
  2349. if(regex.find(have))
  2350. {
  2351. // Return the position of the path portion.
  2352. return regex.start(2);
  2353. }
  2354. else
  2355. {
  2356. // The desired rpath was not found.
  2357. return std::string::npos;
  2358. }
  2359. }
  2360. #endif
  2361. #if defined(CMAKE_USE_ELF_PARSER)
  2362. struct cmSystemToolsRPathInfo
  2363. {
  2364. unsigned long Position;
  2365. unsigned long Size;
  2366. std::string Name;
  2367. std::string Value;
  2368. };
  2369. #endif
  2370. //----------------------------------------------------------------------------
  2371. bool cmSystemTools::ChangeRPath(std::string const& file,
  2372. std::string const& oldRPath,
  2373. std::string const& newRPath,
  2374. std::string* emsg,
  2375. bool* changed)
  2376. {
  2377. #if defined(CMAKE_USE_ELF_PARSER)
  2378. if(changed)
  2379. {
  2380. *changed = false;
  2381. }
  2382. int rp_count = 0;
  2383. cmSystemToolsRPathInfo rp[2];
  2384. {
  2385. // Parse the ELF binary.
  2386. cmELF elf(file.c_str());
  2387. // Get the RPATH and RUNPATH entries from it.
  2388. int se_count = 0;
  2389. cmELF::StringEntry const* se[2] = {0, 0};
  2390. const char* se_name[2] = {0, 0};
  2391. if(cmELF::StringEntry const* se_rpath = elf.GetRPath())
  2392. {
  2393. se[se_count] = se_rpath;
  2394. se_name[se_count] = "RPATH";
  2395. ++se_count;
  2396. }
  2397. if(cmELF::StringEntry const* se_runpath = elf.GetRunPath())
  2398. {
  2399. se[se_count] = se_runpath;
  2400. se_name[se_count] = "RUNPATH";
  2401. ++se_count;
  2402. }
  2403. if(se_count == 0)
  2404. {
  2405. if(newRPath.empty())
  2406. {
  2407. // The new rpath is empty and there is no rpath anyway so it is
  2408. // okay.
  2409. return true;
  2410. }
  2411. else
  2412. {
  2413. if(emsg)
  2414. {
  2415. *emsg = "No valid ELF RPATH or RUNPATH entry exists in the file; ";
  2416. *emsg += elf.GetErrorMessage();
  2417. }
  2418. return false;
  2419. }
  2420. }
  2421. for(int i=0; i < se_count; ++i)
  2422. {
  2423. // If both RPATH and RUNPATH refer to the same string literal it
  2424. // needs to be changed only once.
  2425. if(rp_count && rp[0].Position == se[i]->Position)
  2426. {
  2427. continue;
  2428. }
  2429. // Make sure the current rpath contains the old rpath.
  2430. std::string::size_type pos =
  2431. cmSystemToolsFindRPath(se[i]->Value, oldRPath);
  2432. if(pos == std::string::npos)
  2433. {
  2434. // If it contains the new rpath instead then it is okay.
  2435. if(cmSystemToolsFindRPath(se[i]->Value, newRPath) != std::string::npos)
  2436. {
  2437. continue;
  2438. }
  2439. if(emsg)
  2440. {
  2441. cmOStringStream e;
  2442. e << "The current " << se_name[i] << " is:\n"
  2443. << " " << se[i]->Value << "\n"
  2444. << "which does not contain:\n"
  2445. << " " << oldRPath << "\n"
  2446. << "as was expected.";
  2447. *emsg = e.str();
  2448. }
  2449. return false;
  2450. }
  2451. // Store information about the entry in the file.
  2452. rp[rp_count].Position = se[i]->Position;
  2453. rp[rp_count].Size = se[i]->Size;
  2454. rp[rp_count].Name = se_name[i];
  2455. // Construct the new value which preserves the part of the path
  2456. // not being changed.
  2457. rp[rp_count].Value = se[i]->Value.substr(0, pos);
  2458. rp[rp_count].Value += newRPath;
  2459. rp[rp_count].Value += se[i]->Value.substr(pos+oldRPath.length(),
  2460. oldRPath.npos);
  2461. // Make sure there is enough room to store the new rpath and at
  2462. // least one null terminator.
  2463. if(rp[rp_count].Size < rp[rp_count].Value.length()+1)
  2464. {
  2465. if(emsg)
  2466. {
  2467. *emsg = "The replacement path is too long for the ";
  2468. *emsg += se_name[i];
  2469. *emsg += " entry.";
  2470. }
  2471. return false;
  2472. }
  2473. // This entry is ready for update.
  2474. ++rp_count;
  2475. }
  2476. }
  2477. // If no runtime path needs to be changed, we are done.
  2478. if(rp_count == 0)
  2479. {
  2480. return true;
  2481. }
  2482. {
  2483. // Open the file for update.
  2484. std::ofstream f(file.c_str(),
  2485. std::ios::in | std::ios::out | std::ios::binary);
  2486. if(!f)
  2487. {
  2488. if(emsg)
  2489. {
  2490. *emsg = "Error opening file for update.";
  2491. }
  2492. return false;
  2493. }
  2494. // Store the new RPATH and RUNPATH strings.
  2495. for(int i=0; i < rp_count; ++i)
  2496. {
  2497. // Seek to the RPATH position.
  2498. if(!f.seekp(rp[i].Position))
  2499. {
  2500. if(emsg)
  2501. {
  2502. *emsg = "Error seeking to ";
  2503. *emsg += rp[i].Name;
  2504. *emsg += " position.";
  2505. }
  2506. return false;
  2507. }
  2508. // Write the new rpath. Follow it with enough null terminators to
  2509. // fill the string table entry.
  2510. f << rp[i].Value;
  2511. for(unsigned long j=rp[i].Value.length(); j < rp[i].Size; ++j)
  2512. {
  2513. f << '\0';
  2514. }
  2515. // Make sure it wrote correctly.
  2516. if(!f)
  2517. {
  2518. if(emsg)
  2519. {
  2520. *emsg = "Error writing the new ";
  2521. *emsg += rp[i].Name;
  2522. *emsg += " string to the file.";
  2523. }
  2524. return false;
  2525. }
  2526. }
  2527. }
  2528. // Everything was updated successfully.
  2529. if(changed)
  2530. {
  2531. *changed = true;
  2532. }
  2533. return true;
  2534. #else
  2535. (void)file;
  2536. (void)oldRPath;
  2537. (void)newRPath;
  2538. (void)emsg;
  2539. (void)changed;
  2540. return false;
  2541. #endif
  2542. }
  2543. //----------------------------------------------------------------------------
  2544. bool cmSystemTools::VersionCompare(cmSystemTools::CompareOp op,
  2545. const char* lhss, const char* rhss)
  2546. {
  2547. // Parse out up to 8 components.
  2548. unsigned int lhs[8] = {0,0,0,0,0,0,0,0};
  2549. unsigned int rhs[8] = {0,0,0,0,0,0,0,0};
  2550. sscanf(lhss, "%u.%u.%u.%u.%u.%u.%u.%u",
  2551. &lhs[0], &lhs[1], &lhs[2], &lhs[3],
  2552. &lhs[4], &lhs[5], &lhs[6], &lhs[7]);
  2553. sscanf(rhss, "%u.%u.%u.%u.%u.%u.%u.%u",
  2554. &rhs[0], &rhs[1], &rhs[2], &rhs[3],
  2555. &rhs[4], &rhs[5], &rhs[6], &rhs[7]);
  2556. // Do component-wise comparison.
  2557. for(unsigned int i=0; i < 8; ++i)
  2558. {
  2559. if(lhs[i] < rhs[i])
  2560. {
  2561. // lhs < rhs, so true if operation is LESS
  2562. return op == cmSystemTools::OP_LESS;
  2563. }
  2564. else if(lhs[i] > rhs[i])
  2565. {
  2566. // lhs > rhs, so true if operation is GREATER
  2567. return op == cmSystemTools::OP_GREATER;
  2568. }
  2569. }
  2570. // lhs == rhs, so true if operation is EQUAL
  2571. return op == cmSystemTools::OP_EQUAL;
  2572. }
  2573. //----------------------------------------------------------------------------
  2574. bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg,
  2575. bool* removed)
  2576. {
  2577. #if defined(CMAKE_USE_ELF_PARSER)
  2578. if(removed)
  2579. {
  2580. *removed = false;
  2581. }
  2582. int zeroCount = 0;
  2583. unsigned long zeroPosition[2] = {0,0};
  2584. unsigned long zeroSize[2] = {0,0};
  2585. unsigned long bytesBegin = 0;
  2586. std::vector<char> bytes;
  2587. {
  2588. // Parse the ELF binary.
  2589. cmELF elf(file.c_str());
  2590. // Get the RPATH and RUNPATH entries from it and sort them by index
  2591. // in the dynamic section header.
  2592. int se_count = 0;
  2593. cmELF::StringEntry const* se[2] = {0, 0};
  2594. if(cmELF::StringEntry const* se_rpath = elf.GetRPath())
  2595. {
  2596. se[se_count++] = se_rpath;
  2597. }
  2598. if(cmELF::StringEntry const* se_runpath = elf.GetRunPath())
  2599. {
  2600. se[se_count++] = se_runpath;
  2601. }
  2602. if(se_count == 0)
  2603. {
  2604. // There is no RPATH or RUNPATH anyway.
  2605. return true;
  2606. }
  2607. if(se_count == 2 && se[1]->IndexInSection < se[0]->IndexInSection)
  2608. {
  2609. cmsys_stl::swap(se[0], se[1]);
  2610. }
  2611. // Get the size of the dynamic section header.
  2612. unsigned int count = elf.GetDynamicEntryCount();
  2613. if(count == 0)
  2614. {
  2615. // This should happen only for invalid ELF files where a DT_NULL
  2616. // appears before the end of the table.
  2617. if(emsg)
  2618. {
  2619. *emsg = "DYNAMIC section contains a DT_NULL before the end.";
  2620. }
  2621. return false;
  2622. }
  2623. // Save information about the string entries to be zeroed.
  2624. zeroCount = se_count;
  2625. for(int i=0; i < se_count; ++i)
  2626. {
  2627. zeroPosition[i] = se[i]->Position;
  2628. zeroSize[i] = se[i]->Size;
  2629. }
  2630. // Get the range of file positions corresponding to each entry and
  2631. // the rest of the table after them.
  2632. unsigned long entryBegin[3] = {0,0,0};
  2633. unsigned long entryEnd[2] = {0,0};
  2634. for(int i=0; i < se_count; ++i)
  2635. {
  2636. entryBegin[i] = elf.GetDynamicEntryPosition(se[i]->IndexInSection);
  2637. entryEnd[i] = elf.GetDynamicEntryPosition(se[i]->IndexInSection+1);
  2638. }
  2639. entryBegin[se_count] = elf.GetDynamicEntryPosition(count);
  2640. // The data are to be written over the old table entries starting at
  2641. // the first one being removed.
  2642. bytesBegin = entryBegin[0];
  2643. unsigned long bytesEnd = entryBegin[se_count];
  2644. // Allocate a buffer to hold the part of the file to be written.
  2645. // Initialize it with zeros.
  2646. bytes.resize(bytesEnd - bytesBegin, 0);
  2647. // Read the part of the DYNAMIC section header that will move.
  2648. // The remainder of the buffer will be left with zeros which
  2649. // represent a DT_NULL entry.
  2650. char* data = &bytes[0];
  2651. for(int i=0; i < se_count; ++i)
  2652. {
  2653. // Read data between the entries being removed.
  2654. unsigned long sz = entryBegin[i+1] - entryEnd[i];
  2655. if(sz > 0 && !elf.ReadBytes(entryEnd[i], sz, data))
  2656. {
  2657. if(emsg)
  2658. {
  2659. *emsg = "Failed to read DYNAMIC section header.";
  2660. }
  2661. return false;
  2662. }
  2663. data += sz;
  2664. }
  2665. }
  2666. // Open the file for update.
  2667. std::ofstream f(file.c_str(),
  2668. std::ios::in | std::ios::out | std::ios::binary);
  2669. if(!f)
  2670. {
  2671. if(emsg)
  2672. {
  2673. *emsg = "Error opening file for update.";
  2674. }
  2675. return false;
  2676. }
  2677. // Write the new DYNAMIC table header.
  2678. if(!f.seekp(bytesBegin))
  2679. {
  2680. if(emsg)
  2681. {
  2682. *emsg = "Error seeking to DYNAMIC table header for RPATH.";
  2683. }
  2684. return false;
  2685. }
  2686. if(!f.write(&bytes[0], bytes.size()))
  2687. {
  2688. if(emsg)
  2689. {
  2690. *emsg = "Error replacing DYNAMIC table header.";
  2691. }
  2692. return false;
  2693. }
  2694. // Fill the RPATH and RUNPATH strings with zero bytes.
  2695. for(int i=0; i < zeroCount; ++i)
  2696. {
  2697. if(!f.seekp(zeroPosition[i]))
  2698. {
  2699. if(emsg)
  2700. {
  2701. *emsg = "Error seeking to RPATH position.";
  2702. }
  2703. return false;
  2704. }
  2705. for(unsigned long j=0; j < zeroSize[i]; ++j)
  2706. {
  2707. f << '\0';
  2708. }
  2709. if(!f)
  2710. {
  2711. if(emsg)
  2712. {
  2713. *emsg = "Error writing the empty rpath string to the file.";
  2714. }
  2715. return false;
  2716. }
  2717. }
  2718. // Everything was updated successfully.
  2719. if(removed)
  2720. {
  2721. *removed = true;
  2722. }
  2723. return true;
  2724. #else
  2725. (void)file;
  2726. (void)emsg;
  2727. (void)removed;
  2728. return false;
  2729. #endif
  2730. }
  2731. //----------------------------------------------------------------------------
  2732. bool cmSystemTools::CheckRPath(std::string const& file,
  2733. std::string const& newRPath)
  2734. {
  2735. #if defined(CMAKE_USE_ELF_PARSER)
  2736. // Parse the ELF binary.
  2737. cmELF elf(file.c_str());
  2738. // Get the RPATH or RUNPATH entry from it.
  2739. cmELF::StringEntry const* se = elf.GetRPath();
  2740. if(!se)
  2741. {
  2742. se = elf.GetRunPath();
  2743. }
  2744. // Make sure the current rpath contains the new rpath.
  2745. if(newRPath.empty())
  2746. {
  2747. if(!se)
  2748. {
  2749. return true;
  2750. }
  2751. }
  2752. else
  2753. {
  2754. if(se &&
  2755. cmSystemToolsFindRPath(se->Value, newRPath) != std::string::npos)
  2756. {
  2757. return true;
  2758. }
  2759. }
  2760. return false;
  2761. #else
  2762. (void)file;
  2763. (void)newRPath;
  2764. return false;
  2765. #endif
  2766. }
  2767. //----------------------------------------------------------------------------
  2768. bool cmSystemTools::RepeatedRemoveDirectory(const char* dir)
  2769. {
  2770. // Windows sometimes locks files temporarily so try a few times.
  2771. for(int i = 0; i < 10; ++i)
  2772. {
  2773. if(cmSystemTools::RemoveADirectory(dir))
  2774. {
  2775. return true;
  2776. }
  2777. cmSystemTools::Delay(100);
  2778. }
  2779. return false;
  2780. }
  2781. //----------------------------------------------------------------------------
  2782. std::vector<std::string> cmSystemTools::tokenize(const std::string& str,
  2783. const std::string& sep)
  2784. {
  2785. std::vector<std::string> tokens;
  2786. std::string::size_type tokend = 0;
  2787. do
  2788. {
  2789. std::string::size_type tokstart=str.find_first_not_of(sep, tokend);
  2790. if (tokstart==std::string::npos)
  2791. {
  2792. break; // no more tokens
  2793. }
  2794. tokend=str.find_first_of(sep,tokstart);
  2795. if (tokend==std::string::npos)
  2796. {
  2797. tokens.push_back(str.substr(tokstart));
  2798. }
  2799. else
  2800. {
  2801. tokens.push_back(str.substr(tokstart,tokend-tokstart));
  2802. }
  2803. } while (tokend!=std::string::npos);
  2804. if (tokens.empty())
  2805. {
  2806. tokens.push_back("");
  2807. }
  2808. return tokens;
  2809. }