cmSystemTools.cxx 69 KB

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