cmSystemTools.cxx 68 KB

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