cmSystemTools.cxx 75 KB

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