cmSystemTools.cxx 69 KB

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