cmSystemTools.cxx 77 KB

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