cmSystemTools.cxx 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749
  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. buffer[0] = 0;
  866. fgets(buffer, BUFFER_SIZE, cpipe);
  867. }
  868. retVal = pclose(cpipe);
  869. #ifdef __BEOS__
  870. for (int i = 0; (!beos_seen_signal) && (i < 3); i++)
  871. {
  872. ::sleep(1); // signals should interrupt this...
  873. }
  874. if (!beos_seen_signal)
  875. {
  876. signal(SIGCHLD, SIG_DFL); // oh well, didn't happen. Go on anyhow.
  877. }
  878. #endif
  879. if (WIFEXITED(retVal))
  880. {
  881. retVal = WEXITSTATUS(retVal);
  882. return true;
  883. }
  884. if (WIFSIGNALED(retVal))
  885. {
  886. retVal = WTERMSIG(retVal);
  887. cmOStringStream error;
  888. error << "\nProcess terminated due to ";
  889. switch (retVal)
  890. {
  891. #ifdef SIGKILL
  892. case SIGKILL:
  893. error << "SIGKILL";
  894. break;
  895. #endif
  896. #ifdef SIGFPE
  897. case SIGFPE:
  898. error << "SIGFPE";
  899. break;
  900. #endif
  901. #ifndef __HAIKU__
  902. #ifdef SIGBUS
  903. case SIGBUS:
  904. error << "SIGBUS";
  905. break;
  906. #endif
  907. #endif
  908. #ifdef SIGSEGV
  909. case SIGSEGV:
  910. error << "SIGSEGV";
  911. break;
  912. #endif
  913. default:
  914. error << "signal " << retVal;
  915. break;
  916. }
  917. output += error.str();
  918. }
  919. return false;
  920. }
  921. #endif // endif WIN32 not CYGWIN
  922. // run a command unix uses popen (easy)
  923. // windows uses system and ShortPath
  924. bool cmSystemTools::RunCommand(const char* command,
  925. std::string& output,
  926. int &retVal,
  927. const char* dir,
  928. bool verbose,
  929. int timeout)
  930. {
  931. if(s_DisableRunCommandOutput)
  932. {
  933. verbose = false;
  934. }
  935. #if defined(WIN32) && !defined(__CYGWIN__)
  936. // if the command does not start with a quote, then
  937. // try to find the program, and if the program can not be
  938. // found use system to run the command as it must be a built in
  939. // shell command like echo or dir
  940. int count = 0;
  941. if(command[0] == '\"')
  942. {
  943. // count the number of quotes
  944. for(const char* s = command; *s != 0; ++s)
  945. {
  946. if(*s == '\"')
  947. {
  948. count++;
  949. if(count > 2)
  950. {
  951. break;
  952. }
  953. }
  954. }
  955. // if there are more than two double quotes use
  956. // GetShortPathName, the cmd.exe program in windows which
  957. // is used by system fails to execute if there are more than
  958. // one set of quotes in the arguments
  959. if(count > 2)
  960. {
  961. cmsys::RegularExpression quoted("^\"([^\"]*)\"[ \t](.*)");
  962. if(quoted.find(command))
  963. {
  964. std::string shortCmd;
  965. std::string cmd = quoted.match(1);
  966. std::string args = quoted.match(2);
  967. if(! cmSystemTools::FileExists(cmd.c_str()) )
  968. {
  969. shortCmd = cmd;
  970. }
  971. else if(!cmSystemTools::GetShortPath(cmd.c_str(), shortCmd))
  972. {
  973. cmSystemTools::Error("GetShortPath failed for " , cmd.c_str());
  974. return false;
  975. }
  976. shortCmd += " ";
  977. shortCmd += args;
  978. //return RunCommandViaSystem(shortCmd.c_str(), dir,
  979. // output, retVal, verbose);
  980. //return WindowsRunCommand(shortCmd.c_str(), dir,
  981. //output, retVal, verbose);
  982. return RunCommandViaWin32(shortCmd.c_str(), dir,
  983. output, retVal, verbose, timeout);
  984. }
  985. else
  986. {
  987. cmSystemTools::Error("Could not parse command line with quotes ",
  988. command);
  989. }
  990. }
  991. }
  992. // if there is only one set of quotes or no quotes then just run the command
  993. //return RunCommandViaSystem(command, dir, output, retVal, verbose);
  994. //return WindowsRunCommand(command, dir, output, retVal, verbose);
  995. return ::RunCommandViaWin32(command, dir, output, retVal, verbose, timeout);
  996. #else
  997. return ::RunCommandViaPopen(command, dir, output, retVal, verbose, timeout);
  998. #endif
  999. }
  1000. bool cmSystemTools::DoesFileExistWithExtensions(
  1001. const char* name,
  1002. const std::vector<std::string>& headerExts)
  1003. {
  1004. std::string hname;
  1005. for( std::vector<std::string>::const_iterator ext = headerExts.begin();
  1006. ext != headerExts.end(); ++ext )
  1007. {
  1008. hname = name;
  1009. hname += ".";
  1010. hname += *ext;
  1011. if(cmSystemTools::FileExists(hname.c_str()))
  1012. {
  1013. return true;
  1014. }
  1015. }
  1016. return false;
  1017. }
  1018. bool cmSystemTools::cmCopyFile(const char* source, const char* destination)
  1019. {
  1020. return Superclass::CopyFileAlways(source, destination);
  1021. }
  1022. bool cmSystemTools::CopyFileIfDifferent(const char* source,
  1023. const char* destination)
  1024. {
  1025. return Superclass::CopyFileIfDifferent(source, destination);
  1026. }
  1027. bool cmSystemTools::ComputeFileMD5(const char* source, char* md5out)
  1028. {
  1029. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1030. if(!cmSystemTools::FileExists(source))
  1031. {
  1032. return false;
  1033. }
  1034. // Open files
  1035. #if defined(_WIN32) || defined(__CYGWIN__)
  1036. cmsys_ios::ifstream fin(source, cmsys_ios::ios::binary | cmsys_ios::ios::in);
  1037. #else
  1038. cmsys_ios::ifstream fin(source);
  1039. #endif
  1040. if(!fin)
  1041. {
  1042. return false;
  1043. }
  1044. cmsysMD5* md5 = cmsysMD5_New();
  1045. cmsysMD5_Initialize(md5);
  1046. // Should be efficient enough on most system:
  1047. const int bufferSize = 4096;
  1048. char buffer[bufferSize];
  1049. // This copy loop is very sensitive on certain platforms with
  1050. // slightly broken stream libraries (like HPUX). Normally, it is
  1051. // incorrect to not check the error condition on the fin.read()
  1052. // before using the data, but the fin.gcount() will be zero if an
  1053. // error occurred. Therefore, the loop should be safe everywhere.
  1054. while(fin)
  1055. {
  1056. fin.read(buffer, bufferSize);
  1057. if(fin.gcount())
  1058. {
  1059. cmsysMD5_Append(md5, reinterpret_cast<unsigned char const*>(buffer),
  1060. fin.gcount());
  1061. }
  1062. }
  1063. cmsysMD5_FinalizeHex(md5, md5out);
  1064. cmsysMD5_Delete(md5);
  1065. fin.close();
  1066. return true;
  1067. #else
  1068. (void)source;
  1069. (void)md5out;
  1070. cmSystemTools::Message("md5sum not supported in bootstrapping mode","Error");
  1071. return false;
  1072. #endif
  1073. }
  1074. std::string cmSystemTools::ComputeStringMD5(const char* input)
  1075. {
  1076. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1077. char md5out[32];
  1078. cmsysMD5* md5 = cmsysMD5_New();
  1079. cmsysMD5_Initialize(md5);
  1080. cmsysMD5_Append(md5, reinterpret_cast<unsigned char const*>(input), -1);
  1081. cmsysMD5_FinalizeHex(md5, md5out);
  1082. cmsysMD5_Delete(md5);
  1083. return std::string(md5out, 32);
  1084. #else
  1085. (void)input;
  1086. cmSystemTools::Message("md5sum not supported in bootstrapping mode","Error");
  1087. return "";
  1088. #endif
  1089. }
  1090. void cmSystemTools::Glob(const char *directory, const char *regexp,
  1091. std::vector<std::string>& files)
  1092. {
  1093. cmsys::Directory d;
  1094. cmsys::RegularExpression reg(regexp);
  1095. if (d.Load(directory))
  1096. {
  1097. size_t numf;
  1098. unsigned int i;
  1099. numf = d.GetNumberOfFiles();
  1100. for (i = 0; i < numf; i++)
  1101. {
  1102. std::string fname = d.GetFile(i);
  1103. if (reg.find(fname))
  1104. {
  1105. files.push_back(fname);
  1106. }
  1107. }
  1108. }
  1109. }
  1110. void cmSystemTools::GlobDirs(const char *fullPath,
  1111. std::vector<std::string>& files)
  1112. {
  1113. std::string path = fullPath;
  1114. std::string::size_type pos = path.find("/*");
  1115. if(pos == std::string::npos)
  1116. {
  1117. files.push_back(fullPath);
  1118. return;
  1119. }
  1120. std::string startPath = path.substr(0, pos);
  1121. std::string finishPath = path.substr(pos+2);
  1122. cmsys::Directory d;
  1123. if (d.Load(startPath.c_str()))
  1124. {
  1125. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  1126. {
  1127. if((std::string(d.GetFile(i)) != ".")
  1128. && (std::string(d.GetFile(i)) != ".."))
  1129. {
  1130. std::string fname = startPath;
  1131. fname +="/";
  1132. fname += d.GetFile(i);
  1133. if(cmSystemTools::FileIsDirectory(fname.c_str()))
  1134. {
  1135. fname += finishPath;
  1136. cmSystemTools::GlobDirs(fname.c_str(), files);
  1137. }
  1138. }
  1139. }
  1140. }
  1141. }
  1142. void cmSystemTools::ExpandList(std::vector<std::string> const& arguments,
  1143. std::vector<std::string>& newargs)
  1144. {
  1145. std::vector<std::string>::const_iterator i;
  1146. for(i = arguments.begin();i != arguments.end(); ++i)
  1147. {
  1148. cmSystemTools::ExpandListArgument(*i, newargs);
  1149. }
  1150. }
  1151. void cmSystemTools::ExpandListArgument(const std::string& arg,
  1152. std::vector<std::string>& newargs,
  1153. bool emptyArgs)
  1154. {
  1155. // If argument is empty, it is an empty list.
  1156. if(arg.length() == 0 && !emptyArgs)
  1157. {
  1158. return;
  1159. }
  1160. // if there are no ; in the name then just copy the current string
  1161. if(arg.find(';') == std::string::npos)
  1162. {
  1163. newargs.push_back(arg);
  1164. return;
  1165. }
  1166. std::vector<char> newArgVec;
  1167. // Break the string at non-escaped semicolons not nested in [].
  1168. int squareNesting = 0;
  1169. for(const char* c = arg.c_str(); *c; ++c)
  1170. {
  1171. switch(*c)
  1172. {
  1173. case '\\':
  1174. {
  1175. // We only want to allow escaping of semicolons. Other
  1176. // escapes should not be processed here.
  1177. ++c;
  1178. if(*c == ';')
  1179. {
  1180. newArgVec.push_back(*c);
  1181. }
  1182. else
  1183. {
  1184. newArgVec.push_back('\\');
  1185. if(*c)
  1186. {
  1187. newArgVec.push_back(*c);
  1188. }
  1189. else
  1190. {
  1191. // Terminate the loop properly.
  1192. --c;
  1193. }
  1194. }
  1195. } break;
  1196. case '[':
  1197. {
  1198. ++squareNesting;
  1199. newArgVec.push_back(*c);
  1200. } break;
  1201. case ']':
  1202. {
  1203. --squareNesting;
  1204. newArgVec.push_back(*c);
  1205. } break;
  1206. case ';':
  1207. {
  1208. // Break the string here if we are not nested inside square
  1209. // brackets.
  1210. if(squareNesting == 0)
  1211. {
  1212. if ( newArgVec.size() || emptyArgs )
  1213. {
  1214. // Add the last argument if the string is not empty.
  1215. newArgVec.push_back(0);
  1216. newargs.push_back(&*newArgVec.begin());
  1217. newArgVec.clear();
  1218. }
  1219. }
  1220. else
  1221. {
  1222. newArgVec.push_back(*c);
  1223. }
  1224. } break;
  1225. default:
  1226. {
  1227. // Just append this character.
  1228. newArgVec.push_back(*c);
  1229. } break;
  1230. }
  1231. }
  1232. if ( newArgVec.size() || emptyArgs )
  1233. {
  1234. // Add the last argument if the string is not empty.
  1235. newArgVec.push_back(0);
  1236. newargs.push_back(&*newArgVec.begin());
  1237. }
  1238. }
  1239. bool cmSystemTools::SimpleGlob(const cmStdString& glob,
  1240. std::vector<cmStdString>& files,
  1241. int type /* = 0 */)
  1242. {
  1243. files.clear();
  1244. if ( glob[glob.size()-1] != '*' )
  1245. {
  1246. return false;
  1247. }
  1248. std::string path = cmSystemTools::GetFilenamePath(glob);
  1249. std::string ppath = cmSystemTools::GetFilenameName(glob);
  1250. ppath = ppath.substr(0, ppath.size()-1);
  1251. if ( path.size() == 0 )
  1252. {
  1253. path = "/";
  1254. }
  1255. bool res = false;
  1256. cmsys::Directory d;
  1257. if (d.Load(path.c_str()))
  1258. {
  1259. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  1260. {
  1261. if((std::string(d.GetFile(i)) != ".")
  1262. && (std::string(d.GetFile(i)) != ".."))
  1263. {
  1264. std::string fname = path;
  1265. if ( path[path.size()-1] != '/' )
  1266. {
  1267. fname +="/";
  1268. }
  1269. fname += d.GetFile(i);
  1270. std::string sfname = d.GetFile(i);
  1271. if ( type > 0 && cmSystemTools::FileIsDirectory(fname.c_str()) )
  1272. {
  1273. continue;
  1274. }
  1275. if ( type < 0 && !cmSystemTools::FileIsDirectory(fname.c_str()) )
  1276. {
  1277. continue;
  1278. }
  1279. if ( sfname.size() >= ppath.size() &&
  1280. sfname.substr(0, ppath.size()) ==
  1281. ppath )
  1282. {
  1283. files.push_back(fname);
  1284. res = true;
  1285. }
  1286. }
  1287. }
  1288. }
  1289. return res;
  1290. }
  1291. cmSystemTools::FileFormat cmSystemTools::GetFileFormat(const char* cext)
  1292. {
  1293. if ( ! cext || *cext == 0 )
  1294. {
  1295. return cmSystemTools::NO_FILE_FORMAT;
  1296. }
  1297. //std::string ext = cmSystemTools::LowerCase(cext);
  1298. std::string ext = cext;
  1299. if ( ext == "c" || ext == ".c" ||
  1300. ext == "m" || ext == ".m"
  1301. ) { return cmSystemTools::C_FILE_FORMAT; }
  1302. if (
  1303. ext == "C" || ext == ".C" ||
  1304. ext == "M" || ext == ".M" ||
  1305. ext == "c++" || ext == ".c++" ||
  1306. ext == "cc" || ext == ".cc" ||
  1307. ext == "cpp" || ext == ".cpp" ||
  1308. ext == "cxx" || ext == ".cxx" ||
  1309. ext == "mm" || ext == ".mm"
  1310. ) { return cmSystemTools::CXX_FILE_FORMAT; }
  1311. if (
  1312. ext == "f" || ext == ".f" ||
  1313. ext == "F" || ext == ".F" ||
  1314. ext == "f77" || ext == ".f77" ||
  1315. ext == "f90" || ext == ".f90" ||
  1316. ext == "for" || ext == ".for" ||
  1317. ext == "f95" || ext == ".f95"
  1318. ) { return cmSystemTools::FORTRAN_FILE_FORMAT; }
  1319. if ( ext == "java" || ext == ".java" )
  1320. { return cmSystemTools::JAVA_FILE_FORMAT; }
  1321. if (
  1322. ext == "H" || ext == ".H" ||
  1323. ext == "h" || ext == ".h" ||
  1324. ext == "h++" || ext == ".h++" ||
  1325. ext == "hm" || ext == ".hm" ||
  1326. ext == "hpp" || ext == ".hpp" ||
  1327. ext == "hxx" || ext == ".hxx" ||
  1328. ext == "in" || ext == ".in" ||
  1329. ext == "txx" || ext == ".txx"
  1330. ) { return cmSystemTools::HEADER_FILE_FORMAT; }
  1331. if ( ext == "rc" || ext == ".rc" )
  1332. { return cmSystemTools::RESOURCE_FILE_FORMAT; }
  1333. if ( ext == "def" || ext == ".def" )
  1334. { return cmSystemTools::DEFINITION_FILE_FORMAT; }
  1335. if ( ext == "lib" || ext == ".lib" ||
  1336. ext == "a" || ext == ".a")
  1337. { return cmSystemTools::STATIC_LIBRARY_FILE_FORMAT; }
  1338. if ( ext == "o" || ext == ".o" ||
  1339. ext == "obj" || ext == ".obj")
  1340. { return cmSystemTools::OBJECT_FILE_FORMAT; }
  1341. #ifdef __APPLE__
  1342. if ( ext == "dylib" || ext == ".dylib" )
  1343. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  1344. if ( ext == "so" || ext == ".so" ||
  1345. ext == "bundle" || ext == ".bundle" )
  1346. { return cmSystemTools::MODULE_FILE_FORMAT; }
  1347. #else // __APPLE__
  1348. if ( ext == "so" || ext == ".so" ||
  1349. ext == "sl" || ext == ".sl" ||
  1350. ext == "dll" || ext == ".dll" )
  1351. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  1352. #endif // __APPLE__
  1353. return cmSystemTools::UNKNOWN_FILE_FORMAT;
  1354. }
  1355. bool cmSystemTools::Split(const char* s, std::vector<cmStdString>& l)
  1356. {
  1357. std::vector<std::string> temp;
  1358. bool res = Superclass::Split(s, temp);
  1359. for(std::vector<std::string>::const_iterator i = temp.begin();
  1360. i != temp.end(); ++i)
  1361. {
  1362. l.push_back(*i);
  1363. }
  1364. return res;
  1365. }
  1366. std::string cmSystemTools::ConvertToOutputPath(const char* path)
  1367. {
  1368. #if defined(_WIN32) && !defined(__CYGWIN__)
  1369. if(s_ForceUnixPaths)
  1370. {
  1371. return cmSystemTools::ConvertToUnixOutputPath(path);
  1372. }
  1373. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1374. #else
  1375. return cmSystemTools::ConvertToUnixOutputPath(path);
  1376. #endif
  1377. }
  1378. void cmSystemTools::ConvertToOutputSlashes(std::string& path)
  1379. {
  1380. #if defined(_WIN32) && !defined(__CYGWIN__)
  1381. if(!s_ForceUnixPaths)
  1382. {
  1383. // Convert to windows slashes.
  1384. std::string::size_type pos = 0;
  1385. while((pos = path.find('/', pos)) != std::string::npos)
  1386. {
  1387. path[pos++] = '\\';
  1388. }
  1389. }
  1390. #else
  1391. static_cast<void>(path);
  1392. #endif
  1393. }
  1394. std::string cmSystemTools::ConvertToRunCommandPath(const char* path)
  1395. {
  1396. #if defined(_WIN32) && !defined(__CYGWIN__)
  1397. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1398. #else
  1399. return cmSystemTools::ConvertToUnixOutputPath(path);
  1400. #endif
  1401. }
  1402. bool cmSystemTools::StringEndsWith(const char* str1, const char* str2)
  1403. {
  1404. if ( !str1 || !str2 || strlen(str1) < strlen(str2) )
  1405. {
  1406. return 0;
  1407. }
  1408. return !strncmp(str1 + (strlen(str1)-strlen(str2)), str2, strlen(str2));
  1409. }
  1410. // compute the relative path from here to there
  1411. std::string cmSystemTools::RelativePath(const char* local, const char* remote)
  1412. {
  1413. if(!cmSystemTools::FileIsFullPath(local))
  1414. {
  1415. cmSystemTools::Error("RelativePath must be passed a full path to local: ",
  1416. local);
  1417. }
  1418. if(!cmSystemTools::FileIsFullPath(remote))
  1419. {
  1420. cmSystemTools::Error
  1421. ("RelativePath must be passed a full path to remote: ", remote);
  1422. }
  1423. return cmsys::SystemTools::RelativePath(local, remote);
  1424. }
  1425. class cmDeletingCharVector : public std::vector<char*>
  1426. {
  1427. public:
  1428. ~cmDeletingCharVector()
  1429. {
  1430. for(std::vector<char*>::iterator i = this->begin();
  1431. i != this->end(); ++i)
  1432. {
  1433. delete []*i;
  1434. }
  1435. }
  1436. };
  1437. bool cmSystemTools::PutEnv(const char* value)
  1438. {
  1439. static cmDeletingCharVector localEnvironment;
  1440. char* envVar = new char[strlen(value)+1];
  1441. strcpy(envVar, value);
  1442. int ret = putenv(envVar);
  1443. // save the pointer in the static vector so that it can
  1444. // be deleted on exit
  1445. localEnvironment.push_back(envVar);
  1446. return ret == 0;
  1447. }
  1448. #ifdef CMAKE_BUILD_WITH_CMAKE
  1449. //----------------------------------------------------------------------
  1450. bool cmSystemTools::UnsetEnv(const char* value)
  1451. {
  1452. #if !defined(HAVE_UNSETENV)
  1453. std::string var = value;
  1454. var += "=";
  1455. return cmSystemTools::PutEnv(var.c_str());
  1456. #else
  1457. unsetenv(value);
  1458. return true;
  1459. #endif
  1460. }
  1461. //----------------------------------------------------------------------
  1462. std::vector<std::string> cmSystemTools::GetEnvironmentVariables()
  1463. {
  1464. std::vector<std::string> env;
  1465. int cc;
  1466. for ( cc = 0; environ[cc]; ++ cc )
  1467. {
  1468. env.push_back(environ[cc]);
  1469. }
  1470. return env;
  1471. }
  1472. //----------------------------------------------------------------------
  1473. std::vector<std::string> cmSystemTools::AppendEnv(
  1474. std::vector<std::string>* env)
  1475. {
  1476. std::vector<std::string> origEnv = GetEnvironmentVariables();
  1477. if (env && env->size()>0)
  1478. {
  1479. std::vector<std::string>::const_iterator eit;
  1480. for (eit = env->begin(); eit!= env->end(); ++eit)
  1481. {
  1482. PutEnv(eit->c_str());
  1483. }
  1484. }
  1485. return origEnv;
  1486. }
  1487. //----------------------------------------------------------------------
  1488. void cmSystemTools::RestoreEnv(const std::vector<std::string>& env)
  1489. {
  1490. std::vector<std::string>::const_iterator eit;
  1491. // First clear everything in the current environment:
  1492. //
  1493. std::vector<std::string> currentEnv = GetEnvironmentVariables();
  1494. for (eit = currentEnv.begin(); eit!= currentEnv.end(); ++eit)
  1495. {
  1496. std::string var(*eit);
  1497. std::string::size_type pos = var.find("=");
  1498. if (pos != std::string::npos)
  1499. {
  1500. var = var.substr(0, pos);
  1501. }
  1502. UnsetEnv(var.c_str());
  1503. }
  1504. // Then put back each entry from the original environment:
  1505. //
  1506. for (eit = env.begin(); eit!= env.end(); ++eit)
  1507. {
  1508. PutEnv(eit->c_str());
  1509. }
  1510. }
  1511. #endif
  1512. void cmSystemTools::EnableVSConsoleOutput()
  1513. {
  1514. // Visual Studio 8 2005 (devenv.exe or VCExpress.exe) will not
  1515. // display output to the console unless this environment variable is
  1516. // set. We need it to capture the output of these build tools.
  1517. // Note for future work that one could pass "/out \\.\pipe\NAME" to
  1518. // either of these executables where NAME is created with
  1519. // CreateNamedPipe. This would bypass the internal buffering of the
  1520. // output and allow it to be captured on the fly.
  1521. #ifdef _WIN32
  1522. cmSystemTools::PutEnv("vsconsoleoutput=1");
  1523. #endif
  1524. }
  1525. bool cmSystemTools::IsPathToFramework(const char* path)
  1526. {
  1527. if(cmSystemTools::FileIsFullPath(path))
  1528. {
  1529. std::string libname = path;
  1530. if(libname.find(".framework") == libname.size()+1-sizeof(".framework"))
  1531. {
  1532. return true;
  1533. }
  1534. }
  1535. return false;
  1536. }
  1537. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1538. struct cmSystemToolsGZStruct
  1539. {
  1540. gzFile GZFile;
  1541. };
  1542. extern "C" {
  1543. int cmSystemToolsGZStructOpen(void* call_data, const char *pathname,
  1544. int oflags, mode_t mode);
  1545. int cmSystemToolsGZStructClose(void* call_data);
  1546. ssize_t cmSystemToolsGZStructRead(void* call_data, void* buf, size_t count);
  1547. ssize_t cmSystemToolsGZStructWrite(void* call_data, const void* buf,
  1548. size_t count);
  1549. }
  1550. int cmSystemToolsGZStructOpen(void* call_data, const char *pathname,
  1551. int oflags, mode_t mode)
  1552. {
  1553. const char *gzoflags;
  1554. int fd;
  1555. cmSystemToolsGZStruct* gzf = static_cast<cmSystemToolsGZStruct*>(call_data);
  1556. switch (oflags & O_ACCMODE)
  1557. {
  1558. case O_WRONLY:
  1559. gzoflags = "wb";
  1560. break;
  1561. case O_RDONLY:
  1562. gzoflags = "rb";
  1563. break;
  1564. default:
  1565. case O_RDWR:
  1566. errno = EINVAL;
  1567. return -1;
  1568. }
  1569. fd = open(pathname, oflags, mode);
  1570. if (fd == -1)
  1571. {
  1572. return -1;
  1573. }
  1574. // no fchmod on BeOS 5...do pathname instead.
  1575. #if defined(__BEOS__) && !defined(__ZETA__) && !defined(__HAIKU__)
  1576. if ((oflags & O_CREAT) && chmod(pathname, mode))
  1577. {
  1578. return -1;
  1579. }
  1580. #elif !defined(_WIN32) || defined(__CYGWIN__)
  1581. if ((oflags & O_CREAT) && fchmod(fd, mode))
  1582. {
  1583. return -1;
  1584. }
  1585. #endif
  1586. gzf->GZFile = gzdopen(fd, gzoflags);
  1587. if (!gzf->GZFile)
  1588. {
  1589. errno = ENOMEM;
  1590. return -1;
  1591. }
  1592. return fd;
  1593. }
  1594. int cmSystemToolsGZStructClose(void* call_data)
  1595. {
  1596. cmSystemToolsGZStruct* gzf = static_cast<cmSystemToolsGZStruct*>(call_data);
  1597. return gzclose(gzf->GZFile);
  1598. }
  1599. ssize_t cmSystemToolsGZStructRead(void* call_data, void* buf, size_t count)
  1600. {
  1601. cmSystemToolsGZStruct* gzf = static_cast<cmSystemToolsGZStruct*>(call_data);
  1602. return gzread(gzf->GZFile, buf, static_cast<int>(count));
  1603. }
  1604. ssize_t cmSystemToolsGZStructWrite(void* call_data, const void* buf,
  1605. size_t count)
  1606. {
  1607. cmSystemToolsGZStruct* gzf = static_cast<cmSystemToolsGZStruct*>(call_data);
  1608. return gzwrite(gzf->GZFile, (void*)buf, static_cast<int>(count));
  1609. }
  1610. #endif
  1611. bool cmSystemTools::CreateTar(const char* outFileName,
  1612. const std::vector<cmStdString>& files,
  1613. bool gzip, bool verbose)
  1614. {
  1615. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1616. TAR *t;
  1617. char buf[TAR_MAXPATHLEN];
  1618. char pathname[TAR_MAXPATHLEN];
  1619. cmSystemToolsGZStruct gzs;
  1620. tartype_t gztype = {
  1621. (openfunc_t)cmSystemToolsGZStructOpen,
  1622. (closefunc_t)cmSystemToolsGZStructClose,
  1623. (readfunc_t)cmSystemToolsGZStructRead,
  1624. (writefunc_t)cmSystemToolsGZStructWrite,
  1625. &gzs
  1626. };
  1627. // Ok, this libtar is not const safe. for now use auto_ptr hack
  1628. char* realName = new char[ strlen(outFileName) + 1 ];
  1629. std::auto_ptr<char> realNamePtr(realName);
  1630. strcpy(realName, outFileName);
  1631. int options = 0;
  1632. if(verbose)
  1633. {
  1634. options |= TAR_VERBOSE;
  1635. }
  1636. #ifdef __CYGWIN__
  1637. options |= TAR_GNU;
  1638. #endif
  1639. if (tar_open(&t, realName,
  1640. (gzip? &gztype : NULL),
  1641. O_WRONLY | O_CREAT, 0644,
  1642. options) == -1)
  1643. {
  1644. cmSystemTools::Error("Problem with tar_open(): ", strerror(errno));
  1645. return false;
  1646. }
  1647. std::vector<cmStdString>::const_iterator it;
  1648. for (it = files.begin(); it != files.end(); ++ it )
  1649. {
  1650. strncpy(pathname, it->c_str(), sizeof(pathname));
  1651. pathname[sizeof(pathname)-1] = 0;
  1652. strncpy(buf, pathname, sizeof(buf));
  1653. buf[sizeof(buf)-1] = 0;
  1654. if (tar_append_tree(t, buf, pathname) != 0)
  1655. {
  1656. cmOStringStream ostr;
  1657. ostr << "Problem with tar_append_tree(\"" << buf << "\", \""
  1658. << pathname << "\"): "
  1659. << strerror(errno);
  1660. cmSystemTools::Error(ostr.str().c_str());
  1661. tar_close(t);
  1662. return false;
  1663. }
  1664. }
  1665. if (tar_append_eof(t) != 0)
  1666. {
  1667. cmSystemTools::Error("Problem with tar_append_eof(): ", strerror(errno));
  1668. tar_close(t);
  1669. return false;
  1670. }
  1671. if (tar_close(t) != 0)
  1672. {
  1673. cmSystemTools::Error("Problem with tar_close(): ", strerror(errno));
  1674. return false;
  1675. }
  1676. return true;
  1677. #else
  1678. (void)outFileName;
  1679. (void)files;
  1680. (void)gzip;
  1681. (void)verbose;
  1682. return false;
  1683. #endif
  1684. }
  1685. bool cmSystemTools::ExtractTar(const char* outFileName,
  1686. const std::vector<cmStdString>& files,
  1687. bool gzip, bool verbose)
  1688. {
  1689. (void)files;
  1690. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1691. TAR *t;
  1692. cmSystemToolsGZStruct gzs;
  1693. tartype_t gztype = {
  1694. cmSystemToolsGZStructOpen,
  1695. cmSystemToolsGZStructClose,
  1696. cmSystemToolsGZStructRead,
  1697. cmSystemToolsGZStructWrite,
  1698. &gzs
  1699. };
  1700. // Ok, this libtar is not const safe. for now use auto_ptr hack
  1701. char* realName = new char[ strlen(outFileName) + 1 ];
  1702. std::auto_ptr<char> realNamePtr(realName);
  1703. strcpy(realName, outFileName);
  1704. if (tar_open(&t, realName,
  1705. (gzip? &gztype : NULL),
  1706. O_RDONLY
  1707. #ifdef _WIN32
  1708. | O_BINARY
  1709. #endif
  1710. , 0,
  1711. (verbose?TAR_VERBOSE:0)
  1712. | 0) == -1)
  1713. {
  1714. cmSystemTools::Error("Problem with tar_open(): ", strerror(errno));
  1715. return false;
  1716. }
  1717. if (tar_extract_all(t, 0) != 0)
  1718. {
  1719. cmSystemTools::Error("Problem with tar_extract_all(): ", strerror(errno));
  1720. return false;
  1721. }
  1722. if (tar_close(t) != 0)
  1723. {
  1724. cmSystemTools::Error("Problem with tar_close(): ", strerror(errno));
  1725. return false;
  1726. }
  1727. return true;
  1728. #else
  1729. (void)outFileName;
  1730. (void)gzip;
  1731. (void)verbose;
  1732. return false;
  1733. #endif
  1734. }
  1735. bool cmSystemTools::ListTar(const char* outFileName,
  1736. std::vector<cmStdString>& files, bool gzip,
  1737. bool verbose)
  1738. {
  1739. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1740. TAR *t;
  1741. cmSystemToolsGZStruct gzs;
  1742. tartype_t gztype = {
  1743. cmSystemToolsGZStructOpen,
  1744. cmSystemToolsGZStructClose,
  1745. cmSystemToolsGZStructRead,
  1746. cmSystemToolsGZStructWrite,
  1747. &gzs
  1748. };
  1749. // Ok, this libtar is not const safe. for now use auto_ptr hack
  1750. char* realName = new char[ strlen(outFileName) + 1 ];
  1751. std::auto_ptr<char> realNamePtr(realName);
  1752. strcpy(realName, outFileName);
  1753. if (tar_open(&t, realName,
  1754. (gzip? &gztype : NULL),
  1755. O_RDONLY
  1756. #ifdef _WIN32
  1757. | O_BINARY
  1758. #endif
  1759. , 0,
  1760. (verbose?TAR_VERBOSE:0)
  1761. | 0) == -1)
  1762. {
  1763. cmSystemTools::Error("Problem with tar_open(): ", strerror(errno));
  1764. return false;
  1765. }
  1766. while ((th_read(t)) == 0)
  1767. {
  1768. const char* filename = th_get_pathname(t);
  1769. files.push_back(filename);
  1770. if ( verbose )
  1771. {
  1772. th_print_long_ls(t);
  1773. }
  1774. else
  1775. {
  1776. std::cout << filename << std::endl;
  1777. }
  1778. #ifdef DEBUG
  1779. th_print(t);
  1780. #endif
  1781. if (TH_ISREG(t) && tar_skip_regfile(t) != 0)
  1782. {
  1783. cmSystemTools::Error("Problem with tar_skip_regfile(): ",
  1784. strerror(errno));
  1785. return false;
  1786. }
  1787. }
  1788. if (tar_close(t) != 0)
  1789. {
  1790. cmSystemTools::Error("Problem with tar_close(): ", strerror(errno));
  1791. return false;
  1792. }
  1793. return true;
  1794. #else
  1795. (void)outFileName;
  1796. (void)files;
  1797. (void)gzip;
  1798. (void)verbose;
  1799. return false;
  1800. #endif
  1801. }
  1802. int cmSystemTools::WaitForLine(cmsysProcess* process, std::string& line,
  1803. double timeout,
  1804. std::vector<char>& out,
  1805. std::vector<char>& err)
  1806. {
  1807. line = "";
  1808. std::vector<char>::iterator outiter = out.begin();
  1809. std::vector<char>::iterator erriter = err.begin();
  1810. while(1)
  1811. {
  1812. // Check for a newline in stdout.
  1813. for(;outiter != out.end(); ++outiter)
  1814. {
  1815. if((*outiter == '\r') && ((outiter+1) == out.end()))
  1816. {
  1817. break;
  1818. }
  1819. else if(*outiter == '\n' || *outiter == '\0')
  1820. {
  1821. int length = outiter-out.begin();
  1822. if(length > 1 && *(outiter-1) == '\r')
  1823. {
  1824. --length;
  1825. }
  1826. if(length > 0)
  1827. {
  1828. line.append(&out[0], length);
  1829. }
  1830. out.erase(out.begin(), outiter+1);
  1831. return cmsysProcess_Pipe_STDOUT;
  1832. }
  1833. }
  1834. // Check for a newline in stderr.
  1835. for(;erriter != err.end(); ++erriter)
  1836. {
  1837. if((*erriter == '\r') && ((erriter+1) == err.end()))
  1838. {
  1839. break;
  1840. }
  1841. else if(*erriter == '\n' || *erriter == '\0')
  1842. {
  1843. int length = erriter-err.begin();
  1844. if(length > 1 && *(erriter-1) == '\r')
  1845. {
  1846. --length;
  1847. }
  1848. if(length > 0)
  1849. {
  1850. line.append(&err[0], length);
  1851. }
  1852. err.erase(err.begin(), erriter+1);
  1853. return cmsysProcess_Pipe_STDERR;
  1854. }
  1855. }
  1856. // No newlines found. Wait for more data from the process.
  1857. int length;
  1858. char* data;
  1859. int pipe = cmsysProcess_WaitForData(process, &data, &length, &timeout);
  1860. if(pipe == cmsysProcess_Pipe_Timeout)
  1861. {
  1862. // Timeout has been exceeded.
  1863. return pipe;
  1864. }
  1865. else if(pipe == cmsysProcess_Pipe_STDOUT)
  1866. {
  1867. // Append to the stdout buffer.
  1868. std::vector<char>::size_type size = out.size();
  1869. out.insert(out.end(), data, data+length);
  1870. outiter = out.begin()+size;
  1871. }
  1872. else if(pipe == cmsysProcess_Pipe_STDERR)
  1873. {
  1874. // Append to the stderr buffer.
  1875. std::vector<char>::size_type size = err.size();
  1876. err.insert(err.end(), data, data+length);
  1877. erriter = err.begin()+size;
  1878. }
  1879. else if(pipe == cmsysProcess_Pipe_None)
  1880. {
  1881. // Both stdout and stderr pipes have broken. Return leftover data.
  1882. if(!out.empty())
  1883. {
  1884. line.append(&out[0], outiter-out.begin());
  1885. out.erase(out.begin(), out.end());
  1886. return cmsysProcess_Pipe_STDOUT;
  1887. }
  1888. else if(!err.empty())
  1889. {
  1890. line.append(&err[0], erriter-err.begin());
  1891. err.erase(err.begin(), err.end());
  1892. return cmsysProcess_Pipe_STDERR;
  1893. }
  1894. else
  1895. {
  1896. return cmsysProcess_Pipe_None;
  1897. }
  1898. }
  1899. }
  1900. }
  1901. void cmSystemTools::DoNotInheritStdPipes()
  1902. {
  1903. #ifdef _WIN32
  1904. // Check to see if we are attached to a console
  1905. // if so, then do not stop the inherited pipes
  1906. // or stdout and stderr will not show up in dos
  1907. // shell windows
  1908. CONSOLE_SCREEN_BUFFER_INFO hOutInfo;
  1909. HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
  1910. if(GetConsoleScreenBufferInfo(hOut, &hOutInfo))
  1911. {
  1912. return;
  1913. }
  1914. {
  1915. HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
  1916. DuplicateHandle(GetCurrentProcess(), out,
  1917. GetCurrentProcess(), &out, 0, FALSE,
  1918. DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  1919. SetStdHandle(STD_OUTPUT_HANDLE, out);
  1920. }
  1921. {
  1922. HANDLE out = GetStdHandle(STD_ERROR_HANDLE);
  1923. DuplicateHandle(GetCurrentProcess(), out,
  1924. GetCurrentProcess(), &out, 0, FALSE,
  1925. DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  1926. SetStdHandle(STD_ERROR_HANDLE, out);
  1927. }
  1928. #endif
  1929. }
  1930. //----------------------------------------------------------------------------
  1931. bool cmSystemTools::CopyFileTime(const char* fromFile, const char* toFile)
  1932. {
  1933. #if defined(_WIN32) && !defined(__CYGWIN__)
  1934. cmSystemToolsWindowsHandle hFrom =
  1935. CreateFile(fromFile, GENERIC_READ, FILE_SHARE_READ, 0,
  1936. OPEN_EXISTING, 0, 0);
  1937. cmSystemToolsWindowsHandle hTo =
  1938. CreateFile(toFile, GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
  1939. if(!hFrom || !hTo)
  1940. {
  1941. return false;
  1942. }
  1943. FILETIME timeCreation;
  1944. FILETIME timeLastAccess;
  1945. FILETIME timeLastWrite;
  1946. if(!GetFileTime(hFrom, &timeCreation, &timeLastAccess, &timeLastWrite))
  1947. {
  1948. return false;
  1949. }
  1950. if(!SetFileTime(hTo, &timeCreation, &timeLastAccess, &timeLastWrite))
  1951. {
  1952. return false;
  1953. }
  1954. #else
  1955. struct stat fromStat;
  1956. if(stat(fromFile, &fromStat) < 0)
  1957. {
  1958. return false;
  1959. }
  1960. struct utimbuf buf;
  1961. buf.actime = fromStat.st_atime;
  1962. buf.modtime = fromStat.st_mtime;
  1963. if(utime(toFile, &buf) < 0)
  1964. {
  1965. return false;
  1966. }
  1967. #endif
  1968. return true;
  1969. }
  1970. //----------------------------------------------------------------------------
  1971. cmSystemToolsFileTime* cmSystemTools::FileTimeNew()
  1972. {
  1973. return new cmSystemToolsFileTime;
  1974. }
  1975. //----------------------------------------------------------------------------
  1976. void cmSystemTools::FileTimeDelete(cmSystemToolsFileTime* t)
  1977. {
  1978. delete t;
  1979. }
  1980. //----------------------------------------------------------------------------
  1981. bool cmSystemTools::FileTimeGet(const char* fname, cmSystemToolsFileTime* t)
  1982. {
  1983. #if defined(_WIN32) && !defined(__CYGWIN__)
  1984. cmSystemToolsWindowsHandle h =
  1985. CreateFile(fname, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
  1986. if(!h)
  1987. {
  1988. return false;
  1989. }
  1990. if(!GetFileTime(h, &t->timeCreation, &t->timeLastAccess, &t->timeLastWrite))
  1991. {
  1992. return false;
  1993. }
  1994. #else
  1995. struct stat st;
  1996. if(stat(fname, &st) < 0)
  1997. {
  1998. return false;
  1999. }
  2000. t->timeBuf.actime = st.st_atime;
  2001. t->timeBuf.modtime = st.st_mtime;
  2002. #endif
  2003. return true;
  2004. }
  2005. //----------------------------------------------------------------------------
  2006. bool cmSystemTools::FileTimeSet(const char* fname, cmSystemToolsFileTime* t)
  2007. {
  2008. #if defined(_WIN32) && !defined(__CYGWIN__)
  2009. cmSystemToolsWindowsHandle h =
  2010. CreateFile(fname, GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
  2011. if(!h)
  2012. {
  2013. return false;
  2014. }
  2015. if(!SetFileTime(h, &t->timeCreation, &t->timeLastAccess, &t->timeLastWrite))
  2016. {
  2017. return false;
  2018. }
  2019. #else
  2020. if(utime(fname, &t->timeBuf) < 0)
  2021. {
  2022. return false;
  2023. }
  2024. #endif
  2025. return true;
  2026. }
  2027. //----------------------------------------------------------------------------
  2028. static std::string cmSystemToolsExecutableDirectory;
  2029. void cmSystemTools::FindExecutableDirectory(const char* argv0)
  2030. {
  2031. #if defined(_WIN32) && !defined(__CYGWIN__)
  2032. (void)argv0; // ignore this on windows
  2033. char modulepath[_MAX_PATH];
  2034. ::GetModuleFileName(NULL, modulepath, sizeof(modulepath));
  2035. cmSystemToolsExecutableDirectory =
  2036. cmSystemTools::GetFilenamePath(modulepath);
  2037. return;
  2038. #else
  2039. std::string errorMsg;
  2040. std::string exe;
  2041. if(cmSystemTools::FindProgramPath(argv0, exe, errorMsg))
  2042. {
  2043. // remove symlinks
  2044. exe = cmSystemTools::GetRealPath(exe.c_str());
  2045. cmSystemToolsExecutableDirectory =
  2046. cmSystemTools::GetFilenamePath(exe.c_str());
  2047. }
  2048. else
  2049. {
  2050. // ???
  2051. }
  2052. #endif
  2053. }
  2054. //----------------------------------------------------------------------------
  2055. const char* cmSystemTools::GetExecutableDirectory()
  2056. {
  2057. return cmSystemToolsExecutableDirectory.c_str();
  2058. }
  2059. //----------------------------------------------------------------------------
  2060. #if defined(CMAKE_BUILD_WITH_CMAKE)
  2061. void cmSystemTools::MakefileColorEcho(int color, const char* message,
  2062. bool newline, bool enabled)
  2063. {
  2064. // On some platforms (an MSYS prompt) cmsysTerminal may not be able
  2065. // to determine whether the stream is displayed on a tty. In this
  2066. // case it assumes no unless we tell it otherwise. Since we want
  2067. // color messages to be displayed for users we will assume yes.
  2068. // However, we can test for some situations when the answer is most
  2069. // likely no.
  2070. int assumeTTY = cmsysTerminal_Color_AssumeTTY;
  2071. if(cmSystemTools::GetEnv("DART_TEST_FROM_DART") ||
  2072. cmSystemTools::GetEnv("DASHBOARD_TEST_FROM_CTEST") ||
  2073. cmSystemTools::GetEnv("CTEST_INTERACTIVE_DEBUG_MODE"))
  2074. {
  2075. // Avoid printing color escapes during dashboard builds.
  2076. assumeTTY = 0;
  2077. }
  2078. if(enabled)
  2079. {
  2080. cmsysTerminal_cfprintf(color | assumeTTY, stdout, "%s%s",
  2081. message, newline? "\n" : "");
  2082. }
  2083. else
  2084. {
  2085. // Color is disabled. Print without color.
  2086. fprintf(stdout, "%s%s", message, newline? "\n" : "");
  2087. }
  2088. }
  2089. #endif
  2090. //----------------------------------------------------------------------------
  2091. bool cmSystemTools::GuessLibrarySOName(std::string const& fullPath,
  2092. std::string& soname)
  2093. {
  2094. // For ELF shared libraries use a real parser to get the correct
  2095. // soname.
  2096. #if defined(CMAKE_USE_ELF_PARSER)
  2097. cmELF elf(fullPath.c_str());
  2098. if(elf)
  2099. {
  2100. return elf.GetSOName(soname);
  2101. }
  2102. #endif
  2103. // If the file is not a symlink we have no guess for its soname.
  2104. if(!cmSystemTools::FileIsSymlink(fullPath.c_str()))
  2105. {
  2106. return false;
  2107. }
  2108. if(!cmSystemTools::ReadSymlink(fullPath.c_str(), soname))
  2109. {
  2110. return false;
  2111. }
  2112. // If the symlink has a path component we have no guess for the soname.
  2113. if(!cmSystemTools::GetFilenamePath(soname).empty())
  2114. {
  2115. return false;
  2116. }
  2117. // If the symlink points at an extended version of the same name
  2118. // assume it is the soname.
  2119. std::string name = cmSystemTools::GetFilenameName(fullPath);
  2120. if(soname.length() > name.length() &&
  2121. soname.substr(0, name.length()) == name)
  2122. {
  2123. return true;
  2124. }
  2125. return false;
  2126. }
  2127. //----------------------------------------------------------------------------
  2128. #if defined(CMAKE_USE_ELF_PARSER)
  2129. std::string::size_type cmSystemToolsFindRPath(std::string const& have,
  2130. std::string const& want)
  2131. {
  2132. // Search for the desired rpath.
  2133. std::string::size_type pos = have.find(want);
  2134. // If the path is not present we are done.
  2135. if(pos == std::string::npos)
  2136. {
  2137. return pos;
  2138. }
  2139. // Build a regex to match a properly separated path instance.
  2140. std::string regex_str = "(^|:)(";
  2141. for(std::string::const_iterator i = want.begin(); i != want.end(); ++i)
  2142. {
  2143. int ch = *i;
  2144. if(!(('a' <= ch && ch <= 'z') ||
  2145. ('A' <= ch && ch <= 'Z') ||
  2146. ('0' <= ch && ch <= '9')))
  2147. {
  2148. // Escape the non-alphanumeric character.
  2149. regex_str += "\\";
  2150. }
  2151. // Store the character.
  2152. regex_str.append(1, static_cast<char>(ch));
  2153. }
  2154. regex_str += ")(:|$)";
  2155. // Look for the separated path.
  2156. cmsys::RegularExpression regex(regex_str.c_str());
  2157. if(regex.find(have))
  2158. {
  2159. // Return the position of the path portion.
  2160. return regex.start(2);
  2161. }
  2162. else
  2163. {
  2164. // The desired rpath was not found.
  2165. return std::string::npos;
  2166. }
  2167. }
  2168. #endif
  2169. #if defined(CMAKE_USE_ELF_PARSER)
  2170. struct cmSystemToolsRPathInfo
  2171. {
  2172. unsigned long Position;
  2173. unsigned long Size;
  2174. std::string Name;
  2175. std::string Value;
  2176. };
  2177. #endif
  2178. //----------------------------------------------------------------------------
  2179. bool cmSystemTools::ChangeRPath(std::string const& file,
  2180. std::string const& oldRPath,
  2181. std::string const& newRPath,
  2182. std::string* emsg,
  2183. bool* changed)
  2184. {
  2185. #if defined(CMAKE_USE_ELF_PARSER)
  2186. if(changed)
  2187. {
  2188. *changed = false;
  2189. }
  2190. int rp_count = 0;
  2191. cmSystemToolsRPathInfo rp[2];
  2192. {
  2193. // Parse the ELF binary.
  2194. cmELF elf(file.c_str());
  2195. // Get the RPATH and RUNPATH entries from it.
  2196. int se_count = 0;
  2197. cmELF::StringEntry const* se[2] = {0, 0};
  2198. const char* se_name[2] = {0, 0};
  2199. if(cmELF::StringEntry const* se_rpath = elf.GetRPath())
  2200. {
  2201. se[se_count] = se_rpath;
  2202. se_name[se_count] = "RPATH";
  2203. ++se_count;
  2204. }
  2205. if(cmELF::StringEntry const* se_runpath = elf.GetRunPath())
  2206. {
  2207. se[se_count] = se_runpath;
  2208. se_name[se_count] = "RUNPATH";
  2209. ++se_count;
  2210. }
  2211. if(se_count == 0)
  2212. {
  2213. if(newRPath.empty())
  2214. {
  2215. // The new rpath is empty and there is no rpath anyway so it is
  2216. // okay.
  2217. return true;
  2218. }
  2219. else
  2220. {
  2221. if(emsg)
  2222. {
  2223. *emsg = "No valid ELF RPATH or RUNPATH entry exists in the file; ";
  2224. *emsg += elf.GetErrorMessage();
  2225. }
  2226. return false;
  2227. }
  2228. }
  2229. for(int i=0; i < se_count; ++i)
  2230. {
  2231. // If both RPATH and RUNPATH refer to the same string literal it
  2232. // needs to be changed only once.
  2233. if(rp_count && rp[0].Position == se[i]->Position)
  2234. {
  2235. continue;
  2236. }
  2237. // Make sure the current rpath contains the old rpath.
  2238. std::string::size_type pos =
  2239. cmSystemToolsFindRPath(se[i]->Value, oldRPath);
  2240. if(pos == std::string::npos)
  2241. {
  2242. // If it contains the new rpath instead then it is okay.
  2243. if(cmSystemToolsFindRPath(se[i]->Value, newRPath) != std::string::npos)
  2244. {
  2245. continue;
  2246. }
  2247. if(emsg)
  2248. {
  2249. cmOStringStream e;
  2250. e << "The current " << se_name[i] << " is:\n"
  2251. << " " << se[i]->Value << "\n"
  2252. << "which does not contain:\n"
  2253. << " " << oldRPath << "\n"
  2254. << "as was expected.";
  2255. *emsg = e.str();
  2256. }
  2257. return false;
  2258. }
  2259. // Store information about the entry in the file.
  2260. rp[rp_count].Position = se[i]->Position;
  2261. rp[rp_count].Size = se[i]->Size;
  2262. rp[rp_count].Name = se_name[i];
  2263. // Construct the new value which preserves the part of the path
  2264. // not being changed.
  2265. rp[rp_count].Value = se[i]->Value.substr(0, pos);
  2266. rp[rp_count].Value += newRPath;
  2267. rp[rp_count].Value += se[i]->Value.substr(pos+oldRPath.length(),
  2268. oldRPath.npos);
  2269. // Make sure there is enough room to store the new rpath and at
  2270. // least one null terminator.
  2271. if(rp[rp_count].Size < rp[rp_count].Value.length()+1)
  2272. {
  2273. if(emsg)
  2274. {
  2275. *emsg = "The replacement path is too long for the ";
  2276. *emsg += se_name[i];
  2277. *emsg += " entry.";
  2278. }
  2279. return false;
  2280. }
  2281. // This entry is ready for update.
  2282. ++rp_count;
  2283. }
  2284. }
  2285. // If no runtime path needs to be changed, we are done.
  2286. if(rp_count == 0)
  2287. {
  2288. return true;
  2289. }
  2290. {
  2291. // Open the file for update.
  2292. std::ofstream f(file.c_str(),
  2293. std::ios::in | std::ios::out | std::ios::binary);
  2294. if(!f)
  2295. {
  2296. if(emsg)
  2297. {
  2298. *emsg = "Error opening file for update.";
  2299. }
  2300. return false;
  2301. }
  2302. // Store the new RPATH and RUNPATH strings.
  2303. for(int i=0; i < rp_count; ++i)
  2304. {
  2305. // Seek to the RPATH position.
  2306. if(!f.seekp(rp[i].Position))
  2307. {
  2308. if(emsg)
  2309. {
  2310. *emsg = "Error seeking to ";
  2311. *emsg += rp[i].Name;
  2312. *emsg += " position.";
  2313. }
  2314. return false;
  2315. }
  2316. // Write the new rpath. Follow it with enough null terminators to
  2317. // fill the string table entry.
  2318. f << rp[i].Value;
  2319. for(unsigned long j=rp[i].Value.length(); j < rp[i].Size; ++j)
  2320. {
  2321. f << '\0';
  2322. }
  2323. // Make sure it wrote correctly.
  2324. if(!f)
  2325. {
  2326. if(emsg)
  2327. {
  2328. *emsg = "Error writing the new ";
  2329. *emsg += rp[i].Name;
  2330. *emsg += " string to the file.";
  2331. }
  2332. return false;
  2333. }
  2334. }
  2335. }
  2336. // Everything was updated successfully.
  2337. if(changed)
  2338. {
  2339. *changed = true;
  2340. }
  2341. return true;
  2342. #else
  2343. (void)file;
  2344. (void)oldRPath;
  2345. (void)newRPath;
  2346. (void)emsg;
  2347. (void)changed;
  2348. return false;
  2349. #endif
  2350. }
  2351. //----------------------------------------------------------------------------
  2352. bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg,
  2353. bool* removed)
  2354. {
  2355. #if defined(CMAKE_USE_ELF_PARSER)
  2356. if(removed)
  2357. {
  2358. *removed = false;
  2359. }
  2360. int zeroCount = 0;
  2361. unsigned long zeroPosition[2] = {0,0};
  2362. unsigned long zeroSize[2] = {0,0};
  2363. unsigned long bytesBegin = 0;
  2364. std::vector<char> bytes;
  2365. {
  2366. // Parse the ELF binary.
  2367. cmELF elf(file.c_str());
  2368. // Get the RPATH and RUNPATH entries from it and sort them by index
  2369. // in the dynamic section header.
  2370. int se_count = 0;
  2371. cmELF::StringEntry const* se[2] = {0, 0};
  2372. if(cmELF::StringEntry const* se_rpath = elf.GetRPath())
  2373. {
  2374. se[se_count++] = se_rpath;
  2375. }
  2376. if(cmELF::StringEntry const* se_runpath = elf.GetRunPath())
  2377. {
  2378. se[se_count++] = se_runpath;
  2379. }
  2380. if(se_count == 0)
  2381. {
  2382. // There is no RPATH or RUNPATH anyway.
  2383. return true;
  2384. }
  2385. if(se_count == 2 && se[1]->IndexInSection < se[0]->IndexInSection)
  2386. {
  2387. cmsys_stl::swap(se[0], se[1]);
  2388. }
  2389. // Get the size of the dynamic section header.
  2390. unsigned int count = elf.GetDynamicEntryCount();
  2391. if(count == 0)
  2392. {
  2393. // This should happen only for invalid ELF files where a DT_NULL
  2394. // appears before the end of the table.
  2395. if(emsg)
  2396. {
  2397. *emsg = "DYNAMIC section contains a DT_NULL before the end.";
  2398. }
  2399. return false;
  2400. }
  2401. // Save information about the string entries to be zeroed.
  2402. zeroCount = se_count;
  2403. for(int i=0; i < se_count; ++i)
  2404. {
  2405. zeroPosition[i] = se[i]->Position;
  2406. zeroSize[i] = se[i]->Size;
  2407. }
  2408. // Get the range of file positions corresponding to each entry and
  2409. // the rest of the table after them.
  2410. unsigned long entryBegin[3] = {0,0,0};
  2411. unsigned long entryEnd[2] = {0,0};
  2412. for(int i=0; i < se_count; ++i)
  2413. {
  2414. entryBegin[i] = elf.GetDynamicEntryPosition(se[i]->IndexInSection);
  2415. entryEnd[i] = elf.GetDynamicEntryPosition(se[i]->IndexInSection+1);
  2416. }
  2417. entryBegin[se_count] = elf.GetDynamicEntryPosition(count);
  2418. // The data are to be written over the old table entries starting at
  2419. // the first one being removed.
  2420. bytesBegin = entryBegin[0];
  2421. unsigned long bytesEnd = entryBegin[se_count];
  2422. // Allocate a buffer to hold the part of the file to be written.
  2423. // Initialize it with zeros.
  2424. bytes.resize(bytesEnd - bytesBegin, 0);
  2425. // Read the part of the DYNAMIC section header that will move.
  2426. // The remainder of the buffer will be left with zeros which
  2427. // represent a DT_NULL entry.
  2428. char* data = &bytes[0];
  2429. for(int i=0; i < se_count; ++i)
  2430. {
  2431. // Read data between the entries being removed.
  2432. unsigned long sz = entryBegin[i+1] - entryEnd[i];
  2433. if(sz > 0 && !elf.ReadBytes(entryEnd[i], sz, data))
  2434. {
  2435. if(emsg)
  2436. {
  2437. *emsg = "Failed to read DYNAMIC section header.";
  2438. }
  2439. return false;
  2440. }
  2441. data += sz;
  2442. }
  2443. }
  2444. // Open the file for update.
  2445. std::ofstream f(file.c_str(),
  2446. std::ios::in | std::ios::out | std::ios::binary);
  2447. if(!f)
  2448. {
  2449. if(emsg)
  2450. {
  2451. *emsg = "Error opening file for update.";
  2452. }
  2453. return false;
  2454. }
  2455. // Write the new DYNAMIC table header.
  2456. if(!f.seekp(bytesBegin))
  2457. {
  2458. if(emsg)
  2459. {
  2460. *emsg = "Error seeking to DYNAMIC table header for RPATH.";
  2461. }
  2462. return false;
  2463. }
  2464. if(!f.write(&bytes[0], bytes.size()))
  2465. {
  2466. if(emsg)
  2467. {
  2468. *emsg = "Error replacing DYNAMIC table header.";
  2469. }
  2470. return false;
  2471. }
  2472. // Fill the RPATH and RUNPATH strings with zero bytes.
  2473. for(int i=0; i < zeroCount; ++i)
  2474. {
  2475. if(!f.seekp(zeroPosition[i]))
  2476. {
  2477. if(emsg)
  2478. {
  2479. *emsg = "Error seeking to RPATH position.";
  2480. }
  2481. return false;
  2482. }
  2483. for(unsigned long j=0; j < zeroSize[i]; ++j)
  2484. {
  2485. f << '\0';
  2486. }
  2487. if(!f)
  2488. {
  2489. if(emsg)
  2490. {
  2491. *emsg = "Error writing the empty rpath string to the file.";
  2492. }
  2493. return false;
  2494. }
  2495. }
  2496. // Everything was updated successfully.
  2497. if(removed)
  2498. {
  2499. *removed = true;
  2500. }
  2501. return true;
  2502. #else
  2503. (void)file;
  2504. (void)emsg;
  2505. (void)removed;
  2506. return false;
  2507. #endif
  2508. }
  2509. //----------------------------------------------------------------------------
  2510. bool cmSystemTools::CheckRPath(std::string const& file,
  2511. std::string const& newRPath)
  2512. {
  2513. #if defined(CMAKE_USE_ELF_PARSER)
  2514. // Parse the ELF binary.
  2515. cmELF elf(file.c_str());
  2516. // Get the RPATH or RUNPATH entry from it.
  2517. cmELF::StringEntry const* se = elf.GetRPath();
  2518. if(!se)
  2519. {
  2520. se = elf.GetRunPath();
  2521. }
  2522. // Make sure the current rpath contains the new rpath.
  2523. if(newRPath.empty())
  2524. {
  2525. if(!se)
  2526. {
  2527. return true;
  2528. }
  2529. }
  2530. else
  2531. {
  2532. if(se &&
  2533. cmSystemToolsFindRPath(se->Value, newRPath) != std::string::npos)
  2534. {
  2535. return true;
  2536. }
  2537. }
  2538. return false;
  2539. #else
  2540. (void)file;
  2541. (void)newRPath;
  2542. return false;
  2543. #endif
  2544. }