cmSystemTools.cxx 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460
  1. /*=========================================================================
  2. Program: Insight Segmentation & Registration Toolkit
  3. Module: $RCSfile$
  4. Language: C++
  5. Date: $Date$
  6. Version: $Revision$
  7. Copyright (c) 2002 Insight Consortium. All rights reserved.
  8. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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 "errno.h"
  15. #include <stdio.h>
  16. #include <sys/stat.h>
  17. #include "cmRegularExpression.h"
  18. #include <ctype.h>
  19. #include "cmDirectory.h"
  20. #include "cmMakefile.h"
  21. // support for realpath call
  22. #ifndef _WIN32
  23. #include <limits.h>
  24. #include <stdlib.h>
  25. #include <sys/param.h>
  26. #include <sys/wait.h>
  27. #endif
  28. #if defined(_WIN32) && (defined(_MSC_VER) || defined(__BORLANDC__))
  29. #include <string.h>
  30. #include <windows.h>
  31. #include <direct.h>
  32. #define _unlink unlink
  33. inline int Mkdir(const char* dir)
  34. {
  35. return _mkdir(dir);
  36. }
  37. inline const char* Getcwd(char* buf, unsigned int len)
  38. {
  39. return _getcwd(buf, len);
  40. }
  41. inline int Chdir(const char* dir)
  42. {
  43. #if defined(__BORLANDC__)
  44. return chdir(dir);
  45. #else
  46. return _chdir(dir);
  47. #endif
  48. }
  49. #else
  50. #include <sys/types.h>
  51. #include <fcntl.h>
  52. #include <unistd.h>
  53. inline int Mkdir(const char* dir)
  54. {
  55. return mkdir(dir, 00777);
  56. }
  57. inline const char* Getcwd(char* buf, unsigned int len)
  58. {
  59. return getcwd(buf, len);
  60. }
  61. inline int Chdir(const char* dir)
  62. {
  63. return chdir(dir);
  64. }
  65. #endif
  66. bool cmSystemTools::s_DisableRunCommandOutput = false;
  67. bool cmSystemTools::s_ErrorOccured = false;
  68. bool cmSystemTools::s_DisableMessages = false;
  69. std::string cmSystemTools::s_Windows9xComspecSubstitute = "command.com";
  70. void cmSystemTools::SetWindows9xComspecSubstitute(const char* str)
  71. {
  72. if ( str )
  73. {
  74. cmSystemTools::s_Windows9xComspecSubstitute = str;
  75. }
  76. }
  77. const char* cmSystemTools::GetWindows9xComspecSubstitute()
  78. {
  79. return cmSystemTools::s_Windows9xComspecSubstitute.c_str();
  80. }
  81. void (*cmSystemTools::s_ErrorCallback)(const char*, const char*, bool&, void*);
  82. void* cmSystemTools::s_ErrorCallbackClientData = 0;
  83. // adds the elements of the env variable path to the arg passed in
  84. void cmSystemTools::GetPath(std::vector<std::string>& path)
  85. {
  86. #if defined(_WIN32) && !defined(__CYGWIN__)
  87. const char* pathSep = ";";
  88. #else
  89. const char* pathSep = ":";
  90. #endif
  91. std::string pathEnv = getenv("PATH");
  92. // A hack to make the below algorithm work.
  93. if(pathEnv[pathEnv.length()-1] != ':')
  94. {
  95. pathEnv += pathSep;
  96. }
  97. std::string::size_type start =0;
  98. bool done = false;
  99. while(!done)
  100. {
  101. std::string::size_type endpos = pathEnv.find(pathSep, start);
  102. if(endpos != std::string::npos)
  103. {
  104. path.push_back(pathEnv.substr(start, endpos-start));
  105. start = endpos+1;
  106. }
  107. else
  108. {
  109. done = true;
  110. }
  111. }
  112. for(std::vector<std::string>::iterator i = path.begin();
  113. i != path.end(); ++i)
  114. {
  115. cmSystemTools::ConvertToUnixSlashes(*i);
  116. }
  117. }
  118. const char* cmSystemTools::GetExecutableExtension()
  119. {
  120. #if defined(_WIN32) || defined(__CYGWIN__)
  121. return ".exe";
  122. #else
  123. return "";
  124. #endif
  125. }
  126. bool cmSystemTools::MakeDirectory(const char* path)
  127. {
  128. if(cmSystemTools::FileExists(path))
  129. {
  130. return true;
  131. }
  132. std::string dir = path;
  133. if(dir.size() == 0)
  134. {
  135. return false;
  136. }
  137. cmSystemTools::ConvertToUnixSlashes(dir);
  138. std::string::size_type pos = dir.find(':');
  139. if(pos == std::string::npos)
  140. {
  141. pos = 0;
  142. }
  143. std::string topdir;
  144. while((pos = dir.find('/', pos)) != std::string::npos)
  145. {
  146. topdir = dir.substr(0, pos);
  147. Mkdir(topdir.c_str());
  148. pos++;
  149. }
  150. if(dir[dir.size()-1] == '/')
  151. {
  152. topdir = dir.substr(0, dir.size());
  153. }
  154. else
  155. {
  156. topdir = dir;
  157. }
  158. if(Mkdir(topdir.c_str()) != 0)
  159. {
  160. // There is a bug in the Borland Run time library which makes MKDIR
  161. // return EACCES when it should return EEXISTS
  162. // if it is some other error besides directory exists
  163. // then return false
  164. if( (errno != EEXIST)
  165. #ifdef __BORLANDC__
  166. && (errno != EACCES)
  167. #endif
  168. )
  169. {
  170. cmSystemTools::Error("Faild to create directory:", path);
  171. return false;
  172. }
  173. }
  174. return true;
  175. }
  176. // replace replace with with as many times as it shows up in source.
  177. // write the result into source.
  178. void cmSystemTools::ReplaceString(std::string& source,
  179. const char* replace,
  180. const char* with)
  181. {
  182. std::string::size_type lengthReplace = strlen(replace);
  183. std::string::size_type lengthWith = strlen(with);
  184. std::string rest;
  185. std::string::size_type start = source.find(replace);
  186. while(start != std::string::npos)
  187. {
  188. rest = source.substr(start+lengthReplace);
  189. source = source.substr(0, start);
  190. source += with;
  191. source += rest;
  192. start = source.find(replace, start + lengthWith );
  193. }
  194. }
  195. // Read a registry value.
  196. // Example :
  197. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  198. // => will return the data of the "default" value of the key
  199. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  200. // => will return the data of the "Root" value of the key
  201. #if defined(_WIN32) && !defined(__CYGWIN__)
  202. bool cmSystemTools::ReadRegistryValue(const char *key, std::string &value)
  203. {
  204. std::string primary = key;
  205. std::string second;
  206. std::string valuename;
  207. size_t start = primary.find("\\");
  208. if (start == std::string::npos)
  209. {
  210. return false;
  211. }
  212. size_t valuenamepos = primary.find(";");
  213. if (valuenamepos != std::string::npos)
  214. {
  215. valuename = primary.substr(valuenamepos+1);
  216. }
  217. second = primary.substr(start+1, valuenamepos-start-1);
  218. primary = primary.substr(0, start);
  219. HKEY primaryKey;
  220. if (primary == "HKEY_CURRENT_USER")
  221. {
  222. primaryKey = HKEY_CURRENT_USER;
  223. }
  224. if (primary == "HKEY_CURRENT_CONFIG")
  225. {
  226. primaryKey = HKEY_CURRENT_CONFIG;
  227. }
  228. if (primary == "HKEY_CLASSES_ROOT")
  229. {
  230. primaryKey = HKEY_CLASSES_ROOT;
  231. }
  232. if (primary == "HKEY_LOCAL_MACHINE")
  233. {
  234. primaryKey = HKEY_LOCAL_MACHINE;
  235. }
  236. if (primary == "HKEY_USERS")
  237. {
  238. primaryKey = HKEY_USERS;
  239. }
  240. HKEY hKey;
  241. if(RegOpenKeyEx(primaryKey,
  242. second.c_str(),
  243. 0,
  244. KEY_READ,
  245. &hKey) != ERROR_SUCCESS)
  246. {
  247. return false;
  248. }
  249. else
  250. {
  251. DWORD dwType, dwSize;
  252. dwSize = 1023;
  253. char data[1024];
  254. if(RegQueryValueEx(hKey,
  255. (LPTSTR)valuename.c_str(),
  256. NULL,
  257. &dwType,
  258. (BYTE *)data,
  259. &dwSize) == ERROR_SUCCESS)
  260. {
  261. if (dwType == REG_SZ)
  262. {
  263. value = data;
  264. return true;
  265. }
  266. }
  267. }
  268. return false;
  269. }
  270. #else
  271. bool cmSystemTools::ReadRegistryValue(const char *, std::string &)
  272. {
  273. return false;
  274. }
  275. #endif
  276. // Write a registry value.
  277. // Example :
  278. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  279. // => will set the data of the "default" value of the key
  280. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  281. // => will set the data of the "Root" value of the key
  282. #if defined(_WIN32) && !defined(__CYGWIN__)
  283. bool cmSystemTools::WriteRegistryValue(const char *key, const char *value)
  284. {
  285. std::string primary = key;
  286. std::string second;
  287. std::string valuename;
  288. size_t start = primary.find("\\");
  289. if (start == std::string::npos)
  290. {
  291. return false;
  292. }
  293. size_t valuenamepos = primary.find(";");
  294. if (valuenamepos != std::string::npos)
  295. {
  296. valuename = primary.substr(valuenamepos+1);
  297. }
  298. second = primary.substr(start+1, valuenamepos-start-1);
  299. primary = primary.substr(0, start);
  300. HKEY primaryKey;
  301. if (primary == "HKEY_CURRENT_USER")
  302. {
  303. primaryKey = HKEY_CURRENT_USER;
  304. }
  305. if (primary == "HKEY_CURRENT_CONFIG")
  306. {
  307. primaryKey = HKEY_CURRENT_CONFIG;
  308. }
  309. if (primary == "HKEY_CLASSES_ROOT")
  310. {
  311. primaryKey = HKEY_CLASSES_ROOT;
  312. }
  313. if (primary == "HKEY_LOCAL_MACHINE")
  314. {
  315. primaryKey = HKEY_LOCAL_MACHINE;
  316. }
  317. if (primary == "HKEY_USERS")
  318. {
  319. primaryKey = HKEY_USERS;
  320. }
  321. HKEY hKey;
  322. DWORD dwDummy;
  323. if(RegCreateKeyEx(primaryKey,
  324. second.c_str(),
  325. 0,
  326. "",
  327. REG_OPTION_NON_VOLATILE,
  328. KEY_WRITE,
  329. NULL,
  330. &hKey,
  331. &dwDummy) != ERROR_SUCCESS)
  332. {
  333. return false;
  334. }
  335. if(RegSetValueEx(hKey,
  336. (LPTSTR)valuename.c_str(),
  337. 0,
  338. REG_SZ,
  339. (CONST BYTE *)value,
  340. (DWORD)(strlen(value) + 1)) == ERROR_SUCCESS)
  341. {
  342. return true;
  343. }
  344. return false;
  345. }
  346. #else
  347. bool cmSystemTools::WriteRegistryValue(const char *, const char *)
  348. {
  349. return false;
  350. }
  351. #endif
  352. // Delete a registry value.
  353. // Example :
  354. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  355. // => will delete the data of the "default" value of the key
  356. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  357. // => will delete the data of the "Root" value of the key
  358. #if defined(_WIN32) && !defined(__CYGWIN__)
  359. bool cmSystemTools::DeleteRegistryValue(const char *key)
  360. {
  361. std::string primary = key;
  362. std::string second;
  363. std::string valuename;
  364. size_t start = primary.find("\\");
  365. if (start == std::string::npos)
  366. {
  367. return false;
  368. }
  369. size_t valuenamepos = primary.find(";");
  370. if (valuenamepos != std::string::npos)
  371. {
  372. valuename = primary.substr(valuenamepos+1);
  373. }
  374. second = primary.substr(start+1, valuenamepos-start-1);
  375. primary = primary.substr(0, start);
  376. HKEY primaryKey;
  377. if (primary == "HKEY_CURRENT_USER")
  378. {
  379. primaryKey = HKEY_CURRENT_USER;
  380. }
  381. if (primary == "HKEY_CURRENT_CONFIG")
  382. {
  383. primaryKey = HKEY_CURRENT_CONFIG;
  384. }
  385. if (primary == "HKEY_CLASSES_ROOT")
  386. {
  387. primaryKey = HKEY_CLASSES_ROOT;
  388. }
  389. if (primary == "HKEY_LOCAL_MACHINE")
  390. {
  391. primaryKey = HKEY_LOCAL_MACHINE;
  392. }
  393. if (primary == "HKEY_USERS")
  394. {
  395. primaryKey = HKEY_USERS;
  396. }
  397. HKEY hKey;
  398. if(RegOpenKeyEx(primaryKey,
  399. second.c_str(),
  400. 0,
  401. KEY_WRITE,
  402. &hKey) != ERROR_SUCCESS)
  403. {
  404. return false;
  405. }
  406. else
  407. {
  408. if(RegDeleteValue(hKey,
  409. (LPTSTR)valuename.c_str()) == ERROR_SUCCESS)
  410. {
  411. return true;
  412. }
  413. }
  414. return false;
  415. }
  416. #else
  417. bool cmSystemTools::DeleteRegistryValue(const char *)
  418. {
  419. return false;
  420. }
  421. #endif
  422. // replace replace with with as many times as it shows up in source.
  423. // write the result into source.
  424. #if defined(_WIN32) && !defined(__CYGWIN__)
  425. void cmSystemTools::ExpandRegistryValues(std::string& source)
  426. {
  427. // Regular expression to match anything inside [...] that begins in HKEY.
  428. // Note that there is a special rule for regular expressions to match a
  429. // close square-bracket inside a list delimited by square brackets.
  430. // The "[^]]" part of this expression will match any character except
  431. // a close square-bracket. The ']' character must be the first in the
  432. // list of characters inside the [^...] block of the expression.
  433. cmRegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  434. // check for black line or comment
  435. while (regEntry.find(source))
  436. {
  437. // the arguments are the second match
  438. std::string key = regEntry.match(1);
  439. std::string val;
  440. if (ReadRegistryValue(key.c_str(), val))
  441. {
  442. std::string reg = "[";
  443. reg += key + "]";
  444. cmSystemTools::ReplaceString(source, reg.c_str(), val.c_str());
  445. }
  446. else
  447. {
  448. std::string reg = "[";
  449. reg += key + "]";
  450. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  451. }
  452. }
  453. }
  454. #else
  455. void cmSystemTools::ExpandRegistryValues(std::string&)
  456. {
  457. }
  458. #endif
  459. std::string cmSystemTools::EscapeQuotes(const char* str)
  460. {
  461. std::string result = "";
  462. for(const char* ch = str; *ch != '\0'; ++ch)
  463. {
  464. if(*ch == '"')
  465. {
  466. result += '\\';
  467. }
  468. result += *ch;
  469. }
  470. return result;
  471. }
  472. bool cmSystemTools::SameFile(const char* file1, const char* file2)
  473. {
  474. #ifdef _WIN32
  475. HANDLE hFile1, hFile2;
  476. hFile1 = CreateFile( file1,
  477. GENERIC_READ,
  478. FILE_SHARE_READ ,
  479. NULL,
  480. OPEN_EXISTING,
  481. FILE_FLAG_BACKUP_SEMANTICS,
  482. NULL
  483. );
  484. hFile2 = CreateFile( file2,
  485. GENERIC_READ,
  486. FILE_SHARE_READ,
  487. NULL,
  488. OPEN_EXISTING,
  489. FILE_FLAG_BACKUP_SEMANTICS,
  490. NULL
  491. );
  492. if( hFile1 == INVALID_HANDLE_VALUE || hFile2 == INVALID_HANDLE_VALUE)
  493. {
  494. if(hFile1 != INVALID_HANDLE_VALUE)
  495. {
  496. CloseHandle(hFile1);
  497. }
  498. if(hFile2 != INVALID_HANDLE_VALUE)
  499. {
  500. CloseHandle(hFile2);
  501. }
  502. return false;
  503. }
  504. BY_HANDLE_FILE_INFORMATION fiBuf1;
  505. BY_HANDLE_FILE_INFORMATION fiBuf2;
  506. GetFileInformationByHandle( hFile1, &fiBuf1 );
  507. GetFileInformationByHandle( hFile2, &fiBuf2 );
  508. CloseHandle(hFile1);
  509. CloseHandle(hFile2);
  510. return (fiBuf1.nFileIndexHigh == fiBuf2.nFileIndexHigh &&
  511. fiBuf1.nFileIndexLow == fiBuf2.nFileIndexLow);
  512. #else
  513. struct stat fileStat1, fileStat2;
  514. if (stat(file1, &fileStat1) == 0 && stat(file2, &fileStat2) == 0)
  515. {
  516. // see if the files are the same file
  517. // check the device inode and size
  518. if(memcmp(&fileStat2.st_dev, &fileStat1.st_dev, sizeof(fileStat1.st_dev)) == 0 &&
  519. memcmp(&fileStat2.st_ino, &fileStat1.st_ino, sizeof(fileStat1.st_ino)) == 0 &&
  520. fileStat2.st_size == fileStat1.st_size
  521. )
  522. {
  523. return true;
  524. }
  525. }
  526. return false;
  527. #endif
  528. }
  529. // return true if the file exists
  530. bool cmSystemTools::FileExists(const char* filename)
  531. {
  532. struct stat fs;
  533. if (stat(filename, &fs) != 0)
  534. {
  535. return false;
  536. }
  537. else
  538. {
  539. return true;
  540. }
  541. }
  542. // Return a capitalized string (i.e the first letter is uppercased, all other
  543. // are lowercased)
  544. std::string cmSystemTools::Capitalized(const std::string& s)
  545. {
  546. std::string n;
  547. n.resize(s.size());
  548. n[0] = toupper(s[0]);
  549. for (size_t i = 1; i < s.size(); i++)
  550. {
  551. n[i] = tolower(s[i]);
  552. }
  553. return n;
  554. }
  555. // Return a lower case string
  556. std::string cmSystemTools::LowerCase(const std::string& s)
  557. {
  558. std::string n;
  559. n.resize(s.size());
  560. for (size_t i = 0; i < s.size(); i++)
  561. {
  562. n[i] = tolower(s[i]);
  563. }
  564. return n;
  565. }
  566. // Return a lower case string
  567. std::string cmSystemTools::UpperCase(const std::string& s)
  568. {
  569. std::string n;
  570. n.resize(s.size());
  571. for (size_t i = 0; i < s.size(); i++)
  572. {
  573. n[i] = toupper(s[i]);
  574. }
  575. return n;
  576. }
  577. // convert windows slashes to unix slashes
  578. void cmSystemTools::ConvertToUnixSlashes(std::string& path)
  579. {
  580. std::string::size_type pos = 0;
  581. while((pos = path.find('\\', pos)) != std::string::npos)
  582. {
  583. path[pos] = '/';
  584. pos++;
  585. }
  586. // remove any trailing slash
  587. if(path.size() && path[path.size()-1] == '/')
  588. {
  589. path = path.substr(0, path.size()-1);
  590. }
  591. // if there is a tilda ~ then replace it with HOME
  592. if(path.find("~") == 0)
  593. {
  594. if (getenv("HOME"))
  595. {
  596. path = std::string(getenv("HOME")) + path.substr(1);
  597. }
  598. }
  599. // if there is a /tmp_mnt in a path get rid of it!
  600. // stupid sgi's
  601. if(path.find("/tmp_mnt") == 0)
  602. {
  603. path = path.substr(8);
  604. }
  605. }
  606. // change // to /, and escape any spaces in the path
  607. std::string cmSystemTools::ConvertToUnixOutputPath(const char* path)
  608. {
  609. std::string ret = path;
  610. // remove // except at the beginning might be a cygwin drive
  611. std::string::size_type pos = 1;
  612. while((pos = ret.find("//", pos)) != std::string::npos)
  613. {
  614. ret.erase(pos, 1);
  615. }
  616. // now escape spaces if there is a space in the path
  617. if(ret.find(" ") != std::string::npos)
  618. {
  619. std::string result = "";
  620. char lastch = 1;
  621. for(const char* ch = ret.c_str(); *ch != '\0'; ++ch)
  622. {
  623. // if it is already escaped then don't try to escape it again
  624. if(*ch == ' ' && lastch != '\\')
  625. {
  626. result += '\\';
  627. }
  628. result += *ch;
  629. lastch = *ch;
  630. }
  631. ret = result;
  632. }
  633. return ret;
  634. }
  635. std::string cmSystemTools::EscapeSpaces(const char* str)
  636. {
  637. #if defined(_WIN32) && !defined(__CYGWIN__)
  638. std::string result;
  639. // if there are spaces
  640. std::string temp = str;
  641. if (temp.find(" ") != std::string::npos &&
  642. temp.find("\"")==std::string::npos)
  643. {
  644. result = "\"";
  645. result += str;
  646. result += "\"";
  647. return result;
  648. }
  649. return str;
  650. #else
  651. std::string result = "";
  652. for(const char* ch = str; *ch != '\0'; ++ch)
  653. {
  654. if(*ch == ' ')
  655. {
  656. result += '\\';
  657. }
  658. result += *ch;
  659. }
  660. return result;
  661. #endif
  662. }
  663. std::string cmSystemTools::ConvertToOutputPath(const char* path)
  664. {
  665. #if defined(_WIN32) && !defined(__CYGWIN__)
  666. return cmSystemTools::ConvertToWindowsOutputPath(path);
  667. #else
  668. return cmSystemTools::ConvertToUnixOutputPath(path);
  669. #endif
  670. }
  671. // remove double slashes not at the start
  672. std::string cmSystemTools::ConvertToWindowsOutputPath(const char* path)
  673. {
  674. std::string ret = path;
  675. std::string::size_type pos = 0;
  676. // first convert all of the slashes
  677. while((pos = ret.find('/', pos)) != std::string::npos)
  678. {
  679. ret[pos] = '\\';
  680. pos++;
  681. }
  682. // check for really small paths
  683. if(ret.size() < 2)
  684. {
  685. return ret;
  686. }
  687. // now clean up a bit and remove double slashes
  688. // Only if it is not the first position in the path which is a network
  689. // path on windows
  690. pos = 1; // start at position 1
  691. while((pos = ret.find("\\\\", pos)) != std::string::npos)
  692. {
  693. ret.erase(pos, 1);
  694. }
  695. // now double quote the path if it has spaces in it
  696. // and is not already double quoted
  697. if(ret.find(" ") != std::string::npos
  698. && ret[0] != '\"')
  699. {
  700. std::string result;
  701. result = "\"" + ret + "\"";
  702. ret = result;
  703. }
  704. return ret;
  705. }
  706. inline void RemoveComments(char* ptr)
  707. {
  708. while(*ptr)
  709. {
  710. if(*ptr == '#')
  711. {
  712. *ptr = 0;
  713. break;
  714. }
  715. ++ptr;
  716. }
  717. }
  718. bool cmSystemTools::ParseFunction(std::ifstream& fin,
  719. std::string& name,
  720. std::vector<std::string>& arguments,
  721. const char* filename,
  722. bool& parseError)
  723. {
  724. parseError = false;
  725. name = "";
  726. arguments = std::vector<std::string>();
  727. const int BUFFER_SIZE = 4096;
  728. char inbuffer[BUFFER_SIZE];
  729. if(!fin)
  730. {
  731. return false;
  732. }
  733. if(fin.getline(inbuffer, BUFFER_SIZE ) )
  734. {
  735. RemoveComments(inbuffer);
  736. cmRegularExpression blankLine("^[ \t\r]*$");
  737. // cmRegularExpression comment("^[ \t]*#.*$");
  738. cmRegularExpression oneLiner("^[ \t]*([A-Za-z_0-9]*)[ \t]*\\((.*)\\)[ \t\r]*$");
  739. cmRegularExpression multiLine("^[ \t]*([A-Za-z_0-9]*)[ \t]*\\((.*)$");
  740. cmRegularExpression lastLine("^(.*)\\)[ \t\r]*$");
  741. // check for blank line or comment
  742. if(blankLine.find(inbuffer) )
  743. {
  744. return false;
  745. }
  746. // look for a oneline fun(arg arg2)
  747. else if(oneLiner.find(inbuffer))
  748. {
  749. // the arguments are the second match
  750. std::string args = oneLiner.match(2);
  751. name = oneLiner.match(1);
  752. // break up the arguments
  753. cmSystemTools::GetArguments(args, arguments);
  754. return true;
  755. }
  756. // look for a start of a multiline with no trailing ")" fun(arg arg2
  757. else if(multiLine.find(inbuffer))
  758. {
  759. name = multiLine.match(1);
  760. std::string args = multiLine.match(2);
  761. cmSystemTools::GetArguments(args, arguments);
  762. // Read lines until the closing paren is hit
  763. bool done = false;
  764. while(!done)
  765. {
  766. // read lines until the end paren is found
  767. if(fin.getline(inbuffer, BUFFER_SIZE ) )
  768. {
  769. RemoveComments(inbuffer);
  770. // Check for comment lines and ignore them.
  771. if(blankLine.find(inbuffer))
  772. { continue; }
  773. // Is this the last line?
  774. if(lastLine.find(inbuffer))
  775. {
  776. done = true;
  777. std::string args = lastLine.match(1);
  778. cmSystemTools::GetArguments(args, arguments);
  779. }
  780. else
  781. {
  782. std::string line = inbuffer;
  783. cmSystemTools::GetArguments(line, arguments);
  784. }
  785. }
  786. else
  787. {
  788. parseError = true;
  789. cmSystemTools::Error("Parse error in read function missing end )\nIn File: ",
  790. filename, "\nCurrent line:", inbuffer);
  791. return false;
  792. }
  793. }
  794. return true;
  795. }
  796. else
  797. {
  798. parseError = true;
  799. cmSystemTools::Error("Parse error in read function\nIn file:",
  800. filename, "\nCurrent line:", inbuffer);
  801. return false;
  802. }
  803. }
  804. return false;
  805. }
  806. void cmSystemTools::GetArguments(std::string& line,
  807. std::vector<std::string>& arguments)
  808. {
  809. // Match a normal argument (not quoted, no spaces).
  810. cmRegularExpression normalArgument("[ \t]*(([^ \t\r\\]|[\\].)+)[ \t\r]*");
  811. // Match a quoted argument (surrounded by double quotes, spaces allowed).
  812. cmRegularExpression quotedArgument("[ \t]*(\"([^\"\\]|[\\].)*\")[ \t\r]*");
  813. bool done = false;
  814. while(!done)
  815. {
  816. std::string arg;
  817. std::string::size_type endpos=0;
  818. bool foundQuoted = quotedArgument.find(line.c_str());
  819. bool foundNormal = normalArgument.find(line.c_str());
  820. if(foundQuoted && foundNormal)
  821. {
  822. // Both matches were found. Take the earlier one.
  823. // Favor double-quoted version if there is a tie.
  824. if(normalArgument.start(1) < quotedArgument.start(1))
  825. {
  826. arg = normalArgument.match(1);
  827. endpos = normalArgument.end(1);
  828. }
  829. else
  830. {
  831. arg = quotedArgument.match(1);
  832. endpos = quotedArgument.end(1);
  833. // Strip off the double quotes on the ends.
  834. arg = arg.substr(1, arg.length()-2);
  835. }
  836. }
  837. else if (foundQuoted)
  838. {
  839. arg = quotedArgument.match(1);
  840. endpos = quotedArgument.end(1);
  841. // Strip off the double quotes on the ends.
  842. arg = arg.substr(1, arg.length()-2);
  843. }
  844. else if(foundNormal)
  845. {
  846. arg = normalArgument.match(1);
  847. endpos = normalArgument.end(1);
  848. }
  849. else
  850. {
  851. done = true;
  852. }
  853. if(!done)
  854. {
  855. arguments.push_back(cmSystemTools::RemoveEscapes(arg.c_str()));
  856. line = line.substr(endpos, line.length() - endpos);
  857. }
  858. }
  859. }
  860. std::string cmSystemTools::RemoveEscapes(const char* s)
  861. {
  862. std::string result = "";
  863. for(const char* ch = s; *ch; ++ch)
  864. {
  865. if(*ch == '\\' && *(ch+1) != ';')
  866. {
  867. ++ch;
  868. switch (*ch)
  869. {
  870. case '\\': result.insert(result.end(), '\\'); break;
  871. case '"': result.insert(result.end(), '"'); break;
  872. case ' ': result.insert(result.end(), ' '); break;
  873. case 't': result.insert(result.end(), '\t'); break;
  874. case 'n': result.insert(result.end(), '\n'); break;
  875. case 'r': result.insert(result.end(), '\r'); break;
  876. case '0': result.insert(result.end(), '\0'); break;
  877. case '\0':
  878. {
  879. cmSystemTools::Error("Trailing backslash in argument:\n", s);
  880. return result;
  881. }
  882. default:
  883. {
  884. std::string chStr(1, *ch);
  885. cmSystemTools::Error("Invalid escape sequence \\", chStr.c_str(),
  886. "\nin argument ", s);
  887. }
  888. }
  889. }
  890. else
  891. {
  892. result.insert(result.end(), *ch);
  893. }
  894. }
  895. return result;
  896. }
  897. void cmSystemTools::Error(const char* m1, const char* m2,
  898. const char* m3, const char* m4)
  899. {
  900. std::string message = "CMake Error: ";
  901. if(m1)
  902. {
  903. message += m1;
  904. }
  905. if(m2)
  906. {
  907. message += m2;
  908. }
  909. if(m3)
  910. {
  911. message += m3;
  912. }
  913. if(m4)
  914. {
  915. message += m4;
  916. }
  917. cmSystemTools::s_ErrorOccured = true;
  918. cmSystemTools::Message(message.c_str(),"Error");
  919. }
  920. void cmSystemTools::SetErrorCallback(ErrorCallback f, void* clientData)
  921. {
  922. s_ErrorCallback = f;
  923. s_ErrorCallbackClientData = clientData;
  924. }
  925. void cmSystemTools::Message(const char* m1, const char *title)
  926. {
  927. if(s_DisableMessages)
  928. {
  929. return;
  930. }
  931. if(s_ErrorCallback)
  932. {
  933. (*s_ErrorCallback)(m1, title, s_DisableMessages, s_ErrorCallbackClientData);
  934. return;
  935. }
  936. else
  937. {
  938. std::cerr << m1 << std::endl << std::flush;
  939. }
  940. }
  941. bool cmSystemTools::CopyFileIfDifferent(const char* source,
  942. const char* destination)
  943. {
  944. if(cmSystemTools::FilesDiffer(source, destination))
  945. {
  946. cmSystemTools::cmCopyFile(source, destination);
  947. return true;
  948. }
  949. return false;
  950. }
  951. bool cmSystemTools::FilesDiffer(const char* source,
  952. const char* destination)
  953. {
  954. struct stat statSource;
  955. if (stat(source, &statSource) != 0)
  956. {
  957. return true;
  958. }
  959. struct stat statDestination;
  960. if (stat(destination, &statDestination) != 0)
  961. {
  962. return true;
  963. }
  964. if(statSource.st_size != statDestination.st_size)
  965. {
  966. return true;
  967. }
  968. if(statSource.st_size == 0)
  969. {
  970. return false;
  971. }
  972. #if defined(_WIN32) || defined(__CYGWIN__)
  973. std::ifstream finSource(source,
  974. std::ios::binary | std::ios::in);
  975. std::ifstream finDestination(destination,
  976. std::ios::binary | std::ios::in);
  977. #else
  978. std::ifstream finSource(source);
  979. std::ifstream finDestination(destination);
  980. #endif
  981. if(!finSource || !finDestination)
  982. {
  983. return true;
  984. }
  985. char* source_buf = new char[statSource.st_size];
  986. char* dest_buf = new char[statSource.st_size];
  987. finSource.read(source_buf, statSource.st_size);
  988. finDestination.read(dest_buf, statSource.st_size);
  989. if(statSource.st_size != static_cast<long>(finSource.gcount()) ||
  990. statSource.st_size != static_cast<long>(finDestination.gcount()))
  991. {
  992. cmStringStream msg;
  993. msg << "FilesDiffer failed to read files (allocated: "
  994. << statSource.st_size << ", read source: " << finSource.gcount()
  995. << ", read dest: " << finDestination.gcount();
  996. cmSystemTools::Error(msg.str().c_str());
  997. delete [] source_buf;
  998. delete [] dest_buf;
  999. return false;
  1000. }
  1001. int ret = memcmp((const void*)source_buf,
  1002. (const void*)dest_buf,
  1003. statSource.st_size);
  1004. delete [] dest_buf;
  1005. delete [] source_buf;
  1006. return ret != 0;
  1007. }
  1008. /**
  1009. * Copy a file named by "source" to the file named by "destination".
  1010. */
  1011. void cmSystemTools::cmCopyFile(const char* source,
  1012. const char* destination)
  1013. {
  1014. const int bufferSize = 4096;
  1015. char buffer[bufferSize];
  1016. // If destination is a directory, try to create a file with the same
  1017. // name as the source in that directory.
  1018. std::string new_destination;
  1019. if(cmSystemTools::FileExists(destination) &&
  1020. cmSystemTools::FileIsDirectory(destination))
  1021. {
  1022. new_destination = destination;
  1023. cmSystemTools::ConvertToUnixSlashes(new_destination);
  1024. new_destination += '/';
  1025. std::string source_name = source;
  1026. new_destination += cmSystemTools::GetFilenameName(source_name);
  1027. destination = new_destination.c_str();
  1028. }
  1029. // Create destination directory
  1030. std::string destination_dir = destination;
  1031. destination_dir = cmSystemTools::GetFilenamePath(destination_dir);
  1032. cmSystemTools::MakeDirectory(destination_dir.c_str());
  1033. // Open files
  1034. #if defined(_WIN32) || defined(__CYGWIN__)
  1035. std::ifstream fin(source,
  1036. std::ios::binary | std::ios::in);
  1037. #else
  1038. std::ifstream fin(source);
  1039. #endif
  1040. if(!fin)
  1041. {
  1042. cmSystemTools::Error("CopyFile failed to open input file \"",
  1043. source, "\"");
  1044. return;
  1045. }
  1046. #if defined(_WIN32) || defined(__CYGWIN__)
  1047. std::ofstream fout(destination,
  1048. std::ios::binary | std::ios::out | std::ios::trunc);
  1049. #else
  1050. std::ofstream fout(destination,
  1051. std::ios::out | std::ios::trunc);
  1052. #endif
  1053. if(!fout)
  1054. {
  1055. cmSystemTools::Error("CopyFile failed to open output file \"",
  1056. destination, "\"");
  1057. return;
  1058. }
  1059. // This copy loop is very sensitive on certain platforms with
  1060. // slightly broken stream libraries (like HPUX). Normally, it is
  1061. // incorrect to not check the error condition on the fin.read()
  1062. // before using the data, but the fin.gcount() will be zero if an
  1063. // error occurred. Therefore, the loop should be safe everywhere.
  1064. while(fin)
  1065. {
  1066. fin.read(buffer, bufferSize);
  1067. if(fin.gcount())
  1068. {
  1069. fout.write(buffer, fin.gcount());
  1070. }
  1071. }
  1072. fin.close();
  1073. fout.close();
  1074. // More checks
  1075. struct stat statSource, statDestination;
  1076. if (stat(source, &statSource) != 0 ||
  1077. stat(destination, &statDestination) != 0)
  1078. {
  1079. cmSystemTools::Error("CopyFile failed to copy files!");
  1080. }
  1081. if (statSource.st_size != statDestination.st_size)
  1082. {
  1083. cmStringStream msg;
  1084. msg << "CopyFile failed to copy files (sizes differ, source: "
  1085. << statSource.st_size << " , dest: " << statDestination.st_size;
  1086. cmSystemTools::Error(msg.str().c_str());
  1087. }
  1088. }
  1089. // return true if the file exists
  1090. long int cmSystemTools::ModifiedTime(const char* filename)
  1091. {
  1092. struct stat fs;
  1093. if (stat(filename, &fs) != 0)
  1094. {
  1095. return 0;
  1096. }
  1097. else
  1098. {
  1099. return (long int)fs.st_mtime;
  1100. }
  1101. }
  1102. bool cmSystemTools::RemoveFile(const char* source)
  1103. {
  1104. return unlink(source) != 0 ? false : true;
  1105. }
  1106. bool cmSystemTools::IsOn(const char* val)
  1107. {
  1108. if (!val)
  1109. {
  1110. return false;
  1111. }
  1112. std::basic_string<char> v = val;
  1113. for(std::basic_string<char>::iterator c = v.begin();
  1114. c != v.end(); c++)
  1115. {
  1116. *c = toupper(*c);
  1117. }
  1118. return (v == "ON" || v == "1" || v == "YES" || v == "TRUE" || v == "Y");
  1119. }
  1120. bool cmSystemTools::IsOff(const char* val)
  1121. {
  1122. if (!val || strlen(val) == 0)
  1123. {
  1124. return true;
  1125. }
  1126. std::basic_string<char> v = val;
  1127. for(std::basic_string<char>::iterator c = v.begin();
  1128. c != v.end(); c++)
  1129. {
  1130. *c = toupper(*c);
  1131. }
  1132. return (v == "OFF" || v == "0" || v == "NO" || v == "FALSE" ||
  1133. v == "N" || v == "NOTFOUND" || v == "IGNORE");
  1134. }
  1135. bool cmSystemTools::RunCommand(const char* command,
  1136. std::string& output,
  1137. const char* dir,
  1138. bool verbose)
  1139. {
  1140. int foo;
  1141. return cmSystemTools::RunCommand(command, output, foo, dir, verbose);
  1142. }
  1143. #if defined(WIN32) && !defined(__CYGWIN__)
  1144. // Code from a Borland web site with the following explaination :
  1145. /* In this article, I will explain how to spawn a console application
  1146. * and redirect its standard input/output using anonymous pipes. An
  1147. * anonymous pipe is a pipe that goes only in one direction (read
  1148. * pipe, write pipe, etc.). Maybe you are asking, "why would I ever
  1149. * need to do this sort of thing?" One example would be a Windows
  1150. * telnet server, where you spawn a shell and listen on a port and
  1151. * send and receive data between the shell and the socket
  1152. * client. (Windows does not really have a built-in remote
  1153. * shell). First, we should talk about pipes. A pipe in Windows is
  1154. * simply a method of communication, often between process. The SDK
  1155. * defines a pipe as "a communication conduit with two ends;
  1156. a process
  1157. * with a handle to one end can communicate with a process having a
  1158. * handle to the other end." In our case, we are using "anonymous"
  1159. * pipes, one-way pipes that "transfer data between a parent process
  1160. * and a child process or between two child processes of the same
  1161. * parent process." It's easiest to imagine a pipe as its namesake. An
  1162. * actual pipe running between processes that can carry data. We are
  1163. * using anonymous pipes because the console app we are spawning is a
  1164. * child process. We use the CreatePipe function which will create an
  1165. * anonymous pipe and return a read handle and a write handle. We will
  1166. * create two pipes, on for stdin and one for stdout. We will then
  1167. * monitor the read end of the stdout pipe to check for display on our
  1168. * child process. Every time there is something availabe for reading,
  1169. * we will display it in our app. Consequently, we check for input in
  1170. * our app and send it off to the write end of the stdin pipe. */
  1171. inline bool IsWinNT()
  1172. //check if we're running NT
  1173. {
  1174. OSVERSIONINFO osv;
  1175. osv.dwOSVersionInfoSize = sizeof(osv);
  1176. GetVersionEx(&osv);
  1177. return (osv.dwPlatformId == VER_PLATFORM_WIN32_NT);
  1178. }
  1179. void DisplayErrorMessage()
  1180. {
  1181. LPVOID lpMsgBuf;
  1182. FormatMessage(
  1183. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  1184. FORMAT_MESSAGE_FROM_SYSTEM |
  1185. FORMAT_MESSAGE_IGNORE_INSERTS,
  1186. NULL,
  1187. GetLastError(),
  1188. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  1189. (LPTSTR) &lpMsgBuf,
  1190. 0,
  1191. NULL
  1192. );
  1193. // Process any inserts in lpMsgBuf.
  1194. // ...
  1195. // Display the string.
  1196. MessageBox( NULL, (LPCTSTR)lpMsgBuf, "Error", MB_OK | MB_ICONINFORMATION );
  1197. // Free the buffer.
  1198. LocalFree( lpMsgBuf );
  1199. }
  1200. //---------------------------------------------------------------------------
  1201. bool WindowsRunCommand(const char* command, const char* dir,
  1202. std::string& output, int& retVal, bool verbose)
  1203. {
  1204. //verbose = true;
  1205. //std::cerr << std::endl
  1206. // << "WindowsRunCommand(" << command << ")" << std::endl
  1207. // << std::flush;
  1208. const int BUFFER_SIZE = 4096;
  1209. char buf[BUFFER_SIZE];
  1210. //i/o buffer
  1211. STARTUPINFO si;
  1212. SECURITY_ATTRIBUTES sa;
  1213. SECURITY_DESCRIPTOR sd;
  1214. //security information for pipes
  1215. PROCESS_INFORMATION pi;
  1216. HANDLE newstdin,newstdout,read_stdout,write_stdin;
  1217. //pipe handles
  1218. if (IsWinNT())
  1219. //initialize security descriptor (Windows NT)
  1220. {
  1221. InitializeSecurityDescriptor(&sd,SECURITY_DESCRIPTOR_REVISION);
  1222. SetSecurityDescriptorDacl(&sd, true, NULL, false);
  1223. sa.lpSecurityDescriptor = &sd;
  1224. }
  1225. else sa.lpSecurityDescriptor = NULL;
  1226. sa.nLength = sizeof(SECURITY_ATTRIBUTES);
  1227. sa.bInheritHandle = true;
  1228. //allow inheritable handles
  1229. if (!CreatePipe(&newstdin,&write_stdin,&sa,0))
  1230. //create stdin pipe
  1231. {
  1232. std::cerr << "CreatePipe" << std::endl;
  1233. return false;
  1234. }
  1235. if (!CreatePipe(&read_stdout,&newstdout,&sa,0))
  1236. //create stdout pipe
  1237. {
  1238. std::cerr << "CreatePipe" << std::endl;
  1239. CloseHandle(newstdin);
  1240. CloseHandle(write_stdin);
  1241. return false;
  1242. }
  1243. GetStartupInfo(&si);
  1244. //set startupinfo for the spawned process
  1245. /* The dwFlags member tells CreateProcess how to make the
  1246. * process. STARTF_USESTDHANDLES validates the hStd*
  1247. * members. STARTF_USESHOWWINDOW validates the wShowWindow
  1248. * member. */
  1249. si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
  1250. si.wShowWindow = SW_HIDE;
  1251. si.hStdOutput = newstdout;
  1252. si.hStdError = newstdout;
  1253. //set the new handles for the child process si.hStdInput = newstdin;
  1254. char* commandAndArgs = strcpy(new char[strlen(command)+1], command);
  1255. if (!CreateProcess(NULL,commandAndArgs,NULL,NULL,TRUE,CREATE_NEW_CONSOLE,
  1256. NULL,dir,&si,&pi))
  1257. {
  1258. std::cerr << "CreateProcess failed " << commandAndArgs << std::endl;
  1259. CloseHandle(newstdin);
  1260. CloseHandle(newstdout);
  1261. CloseHandle(read_stdout);
  1262. CloseHandle(write_stdin);
  1263. delete [] commandAndArgs;
  1264. return false;
  1265. }
  1266. delete [] commandAndArgs;
  1267. unsigned long exit=0;
  1268. //process exit code unsigned
  1269. unsigned long bread;
  1270. //bytes read unsigned
  1271. unsigned long avail;
  1272. //bytes available
  1273. memset(buf, 0, sizeof(buf));
  1274. for(;;)
  1275. //main program loop
  1276. {
  1277. Sleep(10);
  1278. //std::cout << "Check for process..." << std::endl;
  1279. GetExitCodeProcess(pi.hProcess,&exit);
  1280. //while the process is running
  1281. if (exit != STILL_ACTIVE) break;
  1282. //check to see if there is any data to read from stdout
  1283. //std::cout << "Peek for data..." << std::endl;
  1284. PeekNamedPipe(read_stdout,buf,1023,&bread,&avail,NULL);
  1285. if (bread != 0)
  1286. {
  1287. memset(buf, 0, sizeof(buf));
  1288. if (avail > 1023)
  1289. {
  1290. while (bread >= 1023)
  1291. {
  1292. //std::cout << "Read data..." << std::endl;
  1293. ReadFile(read_stdout,buf,1023,&bread,NULL);
  1294. //read the stdout pipe
  1295. memset(buf, 0, sizeof(buf));
  1296. output += buf;
  1297. if (verbose)
  1298. {
  1299. std::cout << buf << std::flush;
  1300. }
  1301. }
  1302. output += "\n";
  1303. }
  1304. else
  1305. {
  1306. ReadFile(read_stdout,buf,1023,&bread,NULL);
  1307. output += buf;
  1308. output += "\n";
  1309. if(verbose)
  1310. {
  1311. std::cout << buf << std::flush;
  1312. }
  1313. }
  1314. }
  1315. }
  1316. CloseHandle(pi.hThread);
  1317. CloseHandle(pi.hProcess);
  1318. CloseHandle(newstdin);
  1319. //clean stuff up
  1320. CloseHandle(newstdout);
  1321. CloseHandle(read_stdout);
  1322. CloseHandle(write_stdin);
  1323. retVal = exit;
  1324. return true;
  1325. }
  1326. #include "cmWin32ProcessExecution.h"
  1327. // use this for shell commands like echo and dir
  1328. bool RunCommandViaWin32(const char* command,
  1329. const char* dir,
  1330. std::string& output,
  1331. int& retVal,
  1332. bool verbose)
  1333. {
  1334. #if defined(__BORLANDC__)
  1335. return ::WindowsRunCommand(command, dir, output, retVal, verbose);
  1336. #else // Visual studio
  1337. ::SetLastError(ERROR_SUCCESS);
  1338. if ( ! command )
  1339. {
  1340. cmSystemTools::Error("No command specified");
  1341. return false;
  1342. }
  1343. //std::cout << "Command: " << command << std::endl;
  1344. if ( dir )
  1345. {
  1346. //std::cout << "Dir: " << dir << std::endl;
  1347. }
  1348. cmWin32ProcessExecution resProc;
  1349. if ( cmSystemTools::GetWindows9xComspecSubstitute() )
  1350. {
  1351. resProc.SetConsoleSpawn(cmSystemTools::GetWindows9xComspecSubstitute() );
  1352. }
  1353. if ( !resProc.StartProcess(command, dir, verbose) )
  1354. {
  1355. std::cout << "Problem starting command" << std::endl;
  1356. return false;
  1357. }
  1358. resProc.Wait(INFINITE);
  1359. output = resProc.GetOutput();
  1360. retVal = resProc.GetExitValue();
  1361. return true;
  1362. #endif
  1363. }
  1364. // use this for shell commands like echo and dir
  1365. bool RunCommandViaSystem(const char* command,
  1366. const char* dir,
  1367. std::string& output,
  1368. int& retVal,
  1369. bool verbose)
  1370. {
  1371. std::cout << "@@ " << command << std::endl;
  1372. const int BUFFER_SIZE = 4096;
  1373. char buffer[BUFFER_SIZE];
  1374. std::string commandInDir;
  1375. if(dir)
  1376. {
  1377. commandInDir = "cd ";
  1378. commandInDir += cmSystemTools::ConvertToOutputPath(dir);
  1379. commandInDir += " && ";
  1380. commandInDir += command;
  1381. }
  1382. else
  1383. {
  1384. commandInDir = command;
  1385. }
  1386. command = commandInDir.c_str();
  1387. std::string commandToFile = command;
  1388. commandToFile += " > ";
  1389. std::string tempFile;
  1390. tempFile += _tempnam(0, "cmake");
  1391. commandToFile += tempFile;
  1392. retVal = system(commandToFile.c_str());
  1393. std::ifstream fin(tempFile.c_str());
  1394. if(!fin)
  1395. {
  1396. if(verbose)
  1397. {
  1398. std::string errormsg = "RunCommand produced no output: command: \"";
  1399. errormsg += command;
  1400. errormsg += "\"";
  1401. errormsg += "\nOutput file: ";
  1402. errormsg += tempFile;
  1403. cmSystemTools::Error(errormsg.c_str());
  1404. }
  1405. fin.close();
  1406. cmSystemTools::RemoveFile(tempFile.c_str());
  1407. return false;
  1408. }
  1409. bool multiLine = false;
  1410. while(fin)
  1411. {
  1412. fin.getline(buffer, BUFFER_SIZE);
  1413. output += buffer;
  1414. if(multiLine)
  1415. {
  1416. output += "\n";
  1417. }
  1418. multiLine = true;
  1419. }
  1420. fin.close();
  1421. cmSystemTools::RemoveFile(tempFile.c_str());
  1422. return true;
  1423. }
  1424. #endif // endif WIN32 not CYGWIN
  1425. // run a command unix uses popen (easy)
  1426. // windows uses system and ShortPath
  1427. bool cmSystemTools::RunCommand(const char* command,
  1428. std::string& output,
  1429. int &retVal,
  1430. const char* dir,
  1431. bool verbose)
  1432. {
  1433. if(s_DisableRunCommandOutput)
  1434. {
  1435. verbose = false;
  1436. }
  1437. #if defined(WIN32) && !defined(__CYGWIN__)
  1438. // if the command does not start with a quote, then
  1439. // try to find the program, and if the program can not be
  1440. // found use system to run the command as it must be a built in
  1441. // shell command like echo or dir
  1442. int count = 0;
  1443. if(command[0] == '\"')
  1444. {
  1445. // count the number of quotes
  1446. for(const char* s = command; *s != 0; ++s)
  1447. {
  1448. if(*s == '\"')
  1449. {
  1450. count++;
  1451. if(count > 2)
  1452. {
  1453. break;
  1454. }
  1455. }
  1456. }
  1457. // if there are more than two double quotes use
  1458. // GetShortPathName, the cmd.exe program in windows which
  1459. // is used by system fails to execute if there are more than
  1460. // one set of quotes in the arguments
  1461. if(count > 2)
  1462. {
  1463. cmRegularExpression quoted("^\"([^\"]*)\"[ \t](.*)");
  1464. if(quoted.find(command))
  1465. {
  1466. std::string shortCmd;
  1467. std::string cmd = quoted.match(1);
  1468. std::string args = quoted.match(2);
  1469. if(!cmSystemTools::GetShortPath(cmd.c_str(), shortCmd))
  1470. {
  1471. cmSystemTools::Error("GetShortPath failed for " , cmd.c_str());
  1472. return false;
  1473. }
  1474. shortCmd += " ";
  1475. shortCmd += args;
  1476. //return RunCommandViaSystem(shortCmd.c_str(), dir,
  1477. // output, retVal, verbose);
  1478. //return WindowsRunCommand(shortCmd.c_str(), dir,
  1479. //output, retVal, verbose);
  1480. return RunCommandViaWin32(shortCmd.c_str(), dir,
  1481. output, retVal, verbose);
  1482. }
  1483. else
  1484. {
  1485. cmSystemTools::Error("Could not parse command line with quotes ",
  1486. command);
  1487. }
  1488. }
  1489. }
  1490. // if there is only one set of quotes or no quotes then just run the command
  1491. //return RunCommandViaSystem(command, dir, output, retVal, verbose);
  1492. //return WindowsRunCommand(command, dir, output, retVal, verbose);
  1493. return RunCommandViaWin32(command, dir, output, retVal, verbose);
  1494. #else
  1495. // if only popen worked on windows.....
  1496. std::string commandInDir;
  1497. if(dir)
  1498. {
  1499. commandInDir = "cd ";
  1500. commandInDir += dir;
  1501. commandInDir += " && ";
  1502. commandInDir += command;
  1503. }
  1504. else
  1505. {
  1506. commandInDir = command;
  1507. }
  1508. commandInDir += " 2>&1";
  1509. command = commandInDir.c_str();
  1510. const int BUFFER_SIZE = 4096;
  1511. char buffer[BUFFER_SIZE];
  1512. if(verbose)
  1513. {
  1514. std::cout << "running " << command << std::endl;
  1515. }
  1516. fflush(stdout);
  1517. fflush(stderr);
  1518. FILE* cpipe = popen(command, "r");
  1519. if(!cpipe)
  1520. {
  1521. return false;
  1522. }
  1523. fgets(buffer, BUFFER_SIZE, cpipe);
  1524. while(!feof(cpipe))
  1525. {
  1526. if(verbose)
  1527. {
  1528. std::cout << buffer << std::flush;
  1529. }
  1530. output += buffer;
  1531. fgets(buffer, BUFFER_SIZE, cpipe);
  1532. }
  1533. retVal = pclose(cpipe);
  1534. if (WIFEXITED(retVal))
  1535. {
  1536. retVal = WEXITSTATUS(retVal);
  1537. return true;
  1538. }
  1539. if (WIFSIGNALED(retVal))
  1540. {
  1541. retVal = WTERMSIG(retVal);
  1542. cmStringStream error;
  1543. error << "\nProcess terminated due to ";
  1544. switch (retVal)
  1545. {
  1546. #ifdef SIGKILL
  1547. case SIGKILL:
  1548. error << "SIGKILL";
  1549. break;
  1550. #endif
  1551. #ifdef SIGFPE
  1552. case SIGFPE:
  1553. error << "SIGFPE";
  1554. break;
  1555. #endif
  1556. #ifdef SIGBUS
  1557. case SIGBUS:
  1558. error << "SIGBUS";
  1559. break;
  1560. #endif
  1561. #ifdef SIGSEGV
  1562. case SIGSEGV:
  1563. error << "SIGSEGV";
  1564. break;
  1565. #endif
  1566. default:
  1567. error << "signal " << retVal;
  1568. break;
  1569. }
  1570. output += error.str();
  1571. }
  1572. return false;
  1573. #endif
  1574. }
  1575. /**
  1576. * Find the file the given name. Searches the given path and then
  1577. * the system search path. Returns the full path to the file if it is
  1578. * found. Otherwise, the empty string is returned.
  1579. */
  1580. std::string cmSystemTools::FindFile(const char* name,
  1581. const std::vector<std::string>& userPaths)
  1582. {
  1583. // Add the system search path to our path.
  1584. std::vector<std::string> path = userPaths;
  1585. cmSystemTools::GetPath(path);
  1586. std::string tryPath;
  1587. for(std::vector<std::string>::const_iterator p = path.begin();
  1588. p != path.end(); ++p)
  1589. {
  1590. tryPath = *p;
  1591. tryPath += "/";
  1592. tryPath += name;
  1593. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1594. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1595. {
  1596. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1597. }
  1598. }
  1599. // Couldn't find the file.
  1600. return "";
  1601. }
  1602. /**
  1603. * Find the executable with the given name. Searches the given path and then
  1604. * the system search path. Returns the full path to the executable if it is
  1605. * found. Otherwise, the empty string is returned.
  1606. */
  1607. std::string cmSystemTools::FindProgram(const char* name,
  1608. const std::vector<std::string>& userPaths,
  1609. bool no_system_path)
  1610. {
  1611. // See if the executable exists as written.
  1612. if(cmSystemTools::FileExists(name) &&
  1613. !cmSystemTools::FileIsDirectory(name))
  1614. {
  1615. return cmSystemTools::CollapseFullPath(name);
  1616. }
  1617. std::string tryPath = name;
  1618. tryPath += cmSystemTools::GetExecutableExtension();
  1619. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1620. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1621. {
  1622. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1623. }
  1624. // Add the system search path to our path.
  1625. std::vector<std::string> path = userPaths;
  1626. if (!no_system_path)
  1627. {
  1628. cmSystemTools::GetPath(path);
  1629. }
  1630. for(std::vector<std::string>::const_iterator p = path.begin();
  1631. p != path.end(); ++p)
  1632. {
  1633. tryPath = *p;
  1634. tryPath += "/";
  1635. tryPath += name;
  1636. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1637. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1638. {
  1639. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1640. }
  1641. #ifdef _WIN32
  1642. tryPath += ".com";
  1643. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1644. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1645. {
  1646. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1647. }
  1648. tryPath = *p;
  1649. tryPath += "/";
  1650. tryPath += name;
  1651. #endif
  1652. tryPath += cmSystemTools::GetExecutableExtension();
  1653. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1654. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1655. {
  1656. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1657. }
  1658. }
  1659. // Couldn't find the program.
  1660. return "";
  1661. }
  1662. /**
  1663. * Find the library with the given name. Searches the given path and then
  1664. * the system search path. Returns the full path to the library if it is
  1665. * found. Otherwise, the empty string is returned.
  1666. */
  1667. std::string cmSystemTools::FindLibrary(const char* name,
  1668. const std::vector<std::string>& userPaths,
  1669. const cmMakefile *makefile)
  1670. {
  1671. // See if the executable exists as written.
  1672. if(cmSystemTools::FileExists(name))
  1673. {
  1674. return cmSystemTools::CollapseFullPath(name);
  1675. }
  1676. // Add the system search path to our path.
  1677. std::vector<std::string> path = userPaths;
  1678. cmSystemTools::GetPath(path);
  1679. // Add some lib directories specific to compilers, depending on the
  1680. // current generator, so that library that might have been stored here
  1681. // can be found too.
  1682. // i.e. Microsoft Visual Studio or .Net: path to compiler/../Lib
  1683. // Borland: path to compiler/../Lib
  1684. if (makefile)
  1685. {
  1686. const char* genName = makefile->GetDefinition("CMAKE_GENERATOR");
  1687. if (genName)
  1688. {
  1689. if (!strcmp(genName, "NMake Makefiles") ||
  1690. !strcmp(genName, "Visual Studio 6"))
  1691. {
  1692. const char* compiler = makefile->GetDefinition("CMAKE_CXX_COMPILER");
  1693. if (compiler)
  1694. {
  1695. std::string compiler_path = cmSystemTools::FindProgram(compiler);
  1696. if (compiler_path.size())
  1697. {
  1698. std::string lib_path =
  1699. cmSystemTools::GetFilenamePath(
  1700. cmSystemTools::GetFilenamePath(compiler_path)) + "/Lib";
  1701. path.push_back(lib_path);
  1702. }
  1703. }
  1704. }
  1705. else if (!strcmp(genName, "Visual Studio 7"))
  1706. {
  1707. // It is likely that the compiler won't be in the path for .Net, but
  1708. // we know where devenv is.
  1709. const char* devenv = makefile->GetDefinition("MICROSOFT_DEVENV");
  1710. if (devenv)
  1711. {
  1712. std::string devenv_path = cmSystemTools::FindProgram(devenv);
  1713. if (devenv_path.size())
  1714. {
  1715. std::string vc7_path =
  1716. cmSystemTools::GetFilenamePath(
  1717. cmSystemTools::GetFilenamePath(
  1718. cmSystemTools::GetFilenamePath(devenv_path))) + "/Vc7";
  1719. path.push_back(vc7_path + "/lib");
  1720. path.push_back(vc7_path + "/PlatformSDK/lib");
  1721. }
  1722. }
  1723. }
  1724. else if (!strcmp(genName, "Borland Makefiles"))
  1725. {
  1726. const char* bcb_bin_path = makefile->GetDefinition("BCB_BIN_PATH");
  1727. if (bcb_bin_path)
  1728. {
  1729. std::string lib_path =
  1730. cmSystemTools::GetFilenamePath(bcb_bin_path) + "/Lib";
  1731. path.push_back(lib_path);
  1732. }
  1733. }
  1734. }
  1735. }
  1736. std::string tryPath;
  1737. for(std::vector<std::string>::const_iterator p = path.begin();
  1738. p != path.end(); ++p)
  1739. {
  1740. #if defined(_WIN32) && !defined(__CYGWIN__)
  1741. tryPath = *p;
  1742. tryPath += "/";
  1743. tryPath += name;
  1744. tryPath += ".lib";
  1745. if(cmSystemTools::FileExists(tryPath.c_str()))
  1746. {
  1747. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1748. }
  1749. #else
  1750. tryPath = *p;
  1751. tryPath += "/lib";
  1752. tryPath += name;
  1753. tryPath += ".so";
  1754. if(cmSystemTools::FileExists(tryPath.c_str()))
  1755. {
  1756. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1757. }
  1758. tryPath = *p;
  1759. tryPath += "/lib";
  1760. tryPath += name;
  1761. tryPath += ".a";
  1762. if(cmSystemTools::FileExists(tryPath.c_str()))
  1763. {
  1764. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1765. }
  1766. tryPath = *p;
  1767. tryPath += "/lib";
  1768. tryPath += name;
  1769. tryPath += ".sl";
  1770. if(cmSystemTools::FileExists(tryPath.c_str()))
  1771. {
  1772. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1773. }
  1774. tryPath = *p;
  1775. tryPath += "/lib";
  1776. tryPath += name;
  1777. tryPath += ".dylib";
  1778. if(cmSystemTools::FileExists(tryPath.c_str()))
  1779. {
  1780. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1781. }
  1782. #endif
  1783. }
  1784. // Couldn't find the library.
  1785. return "";
  1786. }
  1787. bool cmSystemTools::FileIsDirectory(const char* name)
  1788. {
  1789. struct stat fs;
  1790. if(stat(name, &fs) == 0)
  1791. {
  1792. #if _WIN32
  1793. return ((fs.st_mode & _S_IFDIR) != 0);
  1794. #else
  1795. return S_ISDIR(fs.st_mode);
  1796. #endif
  1797. }
  1798. else
  1799. {
  1800. return false;
  1801. }
  1802. }
  1803. int cmSystemTools::ChangeDirectory(const char *dir)
  1804. {
  1805. return Chdir(dir);
  1806. }
  1807. std::string cmSystemTools::GetCurrentWorkingDirectory()
  1808. {
  1809. char buf[2048];
  1810. std::string path = Getcwd(buf, 2048);
  1811. return path;
  1812. }
  1813. /**
  1814. * Given the path to a program executable, get the directory part of the path with the
  1815. * file stripped off. If there is no directory part, the empty string is returned.
  1816. */
  1817. std::string cmSystemTools::GetProgramPath(const char* in_name)
  1818. {
  1819. std::string dir, file;
  1820. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1821. return dir;
  1822. }
  1823. /**
  1824. * Given the path to a program executable, get the directory part of the path
  1825. * with the file stripped off. If there is no directory part, the empty
  1826. * string is returned.
  1827. */
  1828. void cmSystemTools::SplitProgramPath(const char* in_name,
  1829. std::string& dir,
  1830. std::string& file)
  1831. {
  1832. dir = in_name;
  1833. file = "";
  1834. cmSystemTools::ConvertToUnixSlashes(dir);
  1835. if(!cmSystemTools::FileIsDirectory(dir.c_str()))
  1836. {
  1837. std::string::size_type slashPos = dir.rfind("/");
  1838. if(slashPos != std::string::npos)
  1839. {
  1840. file = dir.substr(slashPos+1);
  1841. dir = dir.substr(0, slashPos);
  1842. }
  1843. else
  1844. {
  1845. file = dir;
  1846. dir = "";
  1847. }
  1848. }
  1849. if((dir != "") && !cmSystemTools::FileIsDirectory(dir.c_str()))
  1850. {
  1851. std::string oldDir = in_name;
  1852. cmSystemTools::ConvertToUnixSlashes(oldDir);
  1853. cmSystemTools::Error("Error splitting file name off end of path:\n",
  1854. oldDir.c_str(), "\nDirectory not found: ",
  1855. dir.c_str());
  1856. dir = in_name;
  1857. return;
  1858. }
  1859. }
  1860. /**
  1861. * Given a path to a file or directory, convert it to a full path.
  1862. * This collapses away relative paths. The full path is returned.
  1863. */
  1864. std::string cmSystemTools::CollapseFullPath(const char* in_name)
  1865. {
  1866. std::string dir, file;
  1867. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1868. #ifdef _WIN32
  1869. // Ultra-hack warning:
  1870. // This changes to the target directory, saves the working directory,
  1871. // and then changes back to the original working directory.
  1872. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1873. if(dir != "") { Chdir(dir.c_str()); }
  1874. std::string newDir = cmSystemTools::GetCurrentWorkingDirectory();
  1875. Chdir(cwd.c_str());
  1876. cmSystemTools::ConvertToUnixSlashes(newDir);
  1877. std::string newPath = newDir+"/"+file;
  1878. return newPath;
  1879. #else
  1880. # ifdef MAXPATHLEN
  1881. char resolved_name[MAXPATHLEN];
  1882. # else
  1883. # ifdef PATH_MAX
  1884. char resolved_name[PATH_MAX];
  1885. # else
  1886. char resolved_name[5024];
  1887. # endif
  1888. # endif
  1889. if(dir != "")
  1890. {
  1891. realpath(dir.c_str(), resolved_name);
  1892. dir = resolved_name;
  1893. }
  1894. else
  1895. {
  1896. dir = cmSystemTools::GetCurrentWorkingDirectory();
  1897. }
  1898. if(file == "")
  1899. {
  1900. return dir;
  1901. }
  1902. return dir + "/" + file;
  1903. #endif
  1904. }
  1905. /**
  1906. * Return path of a full filename (no trailing slashes).
  1907. * Warning: returned path is converted to Unix slashes format.
  1908. */
  1909. std::string cmSystemTools::GetFilenamePath(const std::string& filename)
  1910. {
  1911. std::string fn = filename;
  1912. cmSystemTools::ConvertToUnixSlashes(fn);
  1913. std::string::size_type slash_pos = fn.rfind("/");
  1914. if(slash_pos != std::string::npos)
  1915. {
  1916. return fn.substr(0, slash_pos);
  1917. }
  1918. else
  1919. {
  1920. return "";
  1921. }
  1922. }
  1923. /**
  1924. * Return file name of a full filename (i.e. file name without path).
  1925. */
  1926. std::string cmSystemTools::GetFilenameName(const std::string& filename)
  1927. {
  1928. std::string fn = filename;
  1929. cmSystemTools::ConvertToUnixSlashes(fn);
  1930. std::string::size_type slash_pos = fn.rfind("/");
  1931. if(slash_pos != std::string::npos)
  1932. {
  1933. return fn.substr(slash_pos + 1);
  1934. }
  1935. else
  1936. {
  1937. return filename;
  1938. }
  1939. }
  1940. /**
  1941. * Return file extension of a full filename (dot included).
  1942. * Warning: this is the longest extension (for example: .tar.gz)
  1943. */
  1944. std::string cmSystemTools::GetFilenameExtension(const std::string& filename)
  1945. {
  1946. std::string name = cmSystemTools::GetFilenameName(filename);
  1947. std::string::size_type dot_pos = name.find(".");
  1948. if(dot_pos != std::string::npos)
  1949. {
  1950. return name.substr(dot_pos);
  1951. }
  1952. else
  1953. {
  1954. return "";
  1955. }
  1956. }
  1957. /**
  1958. * Return file name without extension of a full filename (i.e. without path).
  1959. * Warning: it considers the longest extension (for example: .tar.gz)
  1960. */
  1961. std::string cmSystemTools::GetFilenameWithoutExtension(const std::string& filename)
  1962. {
  1963. std::string name = cmSystemTools::GetFilenameName(filename);
  1964. std::string::size_type dot_pos = name.find(".");
  1965. if(dot_pos != std::string::npos)
  1966. {
  1967. return name.substr(0, dot_pos);
  1968. }
  1969. else
  1970. {
  1971. return name;
  1972. }
  1973. }
  1974. /**
  1975. * Return file name without extension of a full filename (i.e. without path).
  1976. * Warning: it considers the last extension (for example: removes .gz
  1977. * from .tar.gz)
  1978. */
  1979. std::string
  1980. cmSystemTools::GetFilenameWithoutLastExtension(const std::string& filename)
  1981. {
  1982. std::string name = cmSystemTools::GetFilenameName(filename);
  1983. std::string::size_type dot_pos = name.rfind(".");
  1984. if(dot_pos != std::string::npos)
  1985. {
  1986. return name.substr(0, dot_pos);
  1987. }
  1988. else
  1989. {
  1990. return name;
  1991. }
  1992. }
  1993. bool cmSystemTools::FileIsFullPath(const char* in_name)
  1994. {
  1995. std::string name = in_name;
  1996. #if defined(_WIN32)
  1997. // On Windows, the name must be at least two characters long.
  1998. if(name.length() < 2)
  1999. {
  2000. return false;
  2001. }
  2002. if(name[1] == ':')
  2003. {
  2004. return true;
  2005. }
  2006. if(name[0] == '\\')
  2007. {
  2008. return true;
  2009. }
  2010. #else
  2011. // On UNIX, the name must be at least one character long.
  2012. if(name.length() < 1)
  2013. {
  2014. return false;
  2015. }
  2016. #endif
  2017. // On UNIX, the name must begin in a '/'.
  2018. // On Windows, if the name begins in a '/', then it is a full
  2019. // network path.
  2020. if(name[0] == '/')
  2021. {
  2022. return true;
  2023. }
  2024. return false;
  2025. }
  2026. void cmSystemTools::Glob(const char *directory, const char *regexp,
  2027. std::vector<std::string>& files)
  2028. {
  2029. cmDirectory d;
  2030. cmRegularExpression reg(regexp);
  2031. if (d.Load(directory))
  2032. {
  2033. size_t numf;
  2034. unsigned int i;
  2035. numf = d.GetNumberOfFiles();
  2036. for (i = 0; i < numf; i++)
  2037. {
  2038. std::string fname = d.GetFile(i);
  2039. if (reg.find(fname))
  2040. {
  2041. files.push_back(fname);
  2042. }
  2043. }
  2044. }
  2045. }
  2046. void cmSystemTools::GlobDirs(const char *fullPath,
  2047. std::vector<std::string>& files)
  2048. {
  2049. std::string path = fullPath;
  2050. std::string::size_type pos = path.find("/*");
  2051. if(pos == std::string::npos)
  2052. {
  2053. files.push_back(fullPath);
  2054. return;
  2055. }
  2056. std::string startPath = path.substr(0, pos);
  2057. std::string finishPath = path.substr(pos+2);
  2058. cmDirectory d;
  2059. if (d.Load(startPath.c_str()))
  2060. {
  2061. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  2062. {
  2063. if((std::string(d.GetFile(i)) != ".")
  2064. && (std::string(d.GetFile(i)) != ".."))
  2065. {
  2066. std::string fname = startPath;
  2067. fname +="/";
  2068. fname += d.GetFile(i);
  2069. if(cmSystemTools::FileIsDirectory(fname.c_str()))
  2070. {
  2071. fname += finishPath;
  2072. cmSystemTools::GlobDirs(fname.c_str(), files);
  2073. }
  2074. }
  2075. }
  2076. }
  2077. }
  2078. void cmSystemTools::ExpandListArguments(std::vector<std::string> const& arguments,
  2079. std::vector<std::string>& newargs)
  2080. {
  2081. std::vector<std::string>::const_iterator i;
  2082. std::string newarg;
  2083. for(i = arguments.begin();i != arguments.end(); ++i)
  2084. {
  2085. // if there are no ; in the name then just copy the current string
  2086. if(i->find(';') == std::string::npos)
  2087. {
  2088. newargs.push_back(*i);
  2089. }
  2090. else
  2091. {
  2092. std::string::size_type start = 0;
  2093. std::string::size_type endpos = 0;
  2094. const std::string::size_type size = i->size();
  2095. // break up ; separated sections of the string into separate strings
  2096. while(endpos != size)
  2097. {
  2098. endpos = i->find(';', start);
  2099. if(endpos == std::string::npos)
  2100. {
  2101. endpos = i->size();
  2102. }
  2103. else
  2104. {
  2105. // skip right over escaped ; ( \; )
  2106. while((endpos != std::string::npos)
  2107. && (endpos > 0)
  2108. && ((*i)[endpos-1] == '\\') )
  2109. {
  2110. endpos = i->find(';', endpos+1);
  2111. }
  2112. if(endpos == std::string::npos)
  2113. {
  2114. endpos = i->size();
  2115. }
  2116. }
  2117. std::string::size_type len = endpos - start;
  2118. if (len > 0)
  2119. {
  2120. // check for a closing ] after the start position
  2121. if(i->find('[', start) == std::string::npos)
  2122. {
  2123. // if there is no [ in the string then keep it
  2124. newarg = i->substr(start, len);
  2125. }
  2126. else
  2127. {
  2128. int opencount = 0;
  2129. int closecount = 0;
  2130. for(std::string::size_type j = start; j < endpos; ++j)
  2131. {
  2132. if(i->at(j) == '[')
  2133. {
  2134. ++opencount;
  2135. }
  2136. else if (i->at(j) == ']')
  2137. {
  2138. ++closecount;
  2139. }
  2140. }
  2141. if(opencount != closecount)
  2142. {
  2143. // skip this one
  2144. endpos = i->find(';', endpos+1);
  2145. if(endpos == std::string::npos)
  2146. {
  2147. endpos = i->size();
  2148. }
  2149. len = endpos - start;
  2150. }
  2151. newarg = i->substr(start, len);
  2152. }
  2153. std::string::size_type pos = newarg.find("\\;");
  2154. if(pos != std::string::npos)
  2155. {
  2156. newarg.erase(pos, 1);
  2157. }
  2158. newargs.push_back(newarg);
  2159. }
  2160. start = endpos+1;
  2161. }
  2162. }
  2163. }
  2164. }
  2165. bool cmSystemTools::GetShortPath(const char* path, std::string& shortPath)
  2166. {
  2167. #if defined(WIN32) && !defined(__CYGWIN__)
  2168. const int size = int(strlen(path)) +1; // size of return
  2169. char *buffer = new char[size]; // create a buffer
  2170. char *tempPath = new char[size]; // create a buffer
  2171. int ret;
  2172. // if the path passed in has quotes around it, first remove the quotes
  2173. if (path[0] == '"' && path[strlen(path)-1] == '"')
  2174. {
  2175. strcpy(tempPath,path+1);
  2176. tempPath[strlen(tempPath)-1] = '\0';
  2177. }
  2178. else
  2179. {
  2180. strcpy(tempPath,path);
  2181. }
  2182. buffer[0] = 0;
  2183. ret = GetShortPathName(tempPath, buffer, size);
  2184. if(buffer[0] == 0 || ret > size)
  2185. {
  2186. if(ret < size)
  2187. {
  2188. LPVOID lpMsgBuf;
  2189. FormatMessage(
  2190. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  2191. FORMAT_MESSAGE_FROM_SYSTEM |
  2192. FORMAT_MESSAGE_IGNORE_INSERTS,
  2193. NULL,
  2194. GetLastError(),
  2195. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  2196. (LPTSTR) &lpMsgBuf,
  2197. 0,
  2198. NULL
  2199. );
  2200. cmSystemTools::Error((LPCTSTR)lpMsgBuf);
  2201. LocalFree( lpMsgBuf );
  2202. }
  2203. cmSystemTools::Error("Unable to get a short path: ", path);
  2204. delete [] tempPath;
  2205. return false;
  2206. }
  2207. else
  2208. {
  2209. shortPath = buffer;
  2210. delete [] buffer;
  2211. delete [] tempPath;
  2212. return true;
  2213. }
  2214. #else
  2215. shortPath = path;
  2216. return true;
  2217. #endif
  2218. }
  2219. cmSystemTools::e_FileFormat cmSystemTools::GetFileFormat(const char* cext)
  2220. {
  2221. if ( ! cext || *cext == 0 )
  2222. {
  2223. return cmSystemTools::NO_FILE_FORMAT;
  2224. }
  2225. std::string ext = cmSystemTools::LowerCase(cext);
  2226. if ( ext == "c" || ext == ".c" ) { return cmSystemTools::C_FILE_FORMAT; }
  2227. if ( ext == "cxx" || ext == ".cxx" ||
  2228. ext == "cpp" || ext == ".cpp" ||
  2229. ext == "c++" || ext == ".c++" ||
  2230. ext == "cc" || ext == ".cc" ) { return cmSystemTools::CXX_FILE_FORMAT; }
  2231. if ( ext == "java" || ext == ".java" ) { return cmSystemTools::JAVA_FILE_FORMAT; }
  2232. if ( ext == "h" || ext == ".h" ||
  2233. ext == "hpp" || ext == ".hpp" ||
  2234. ext == "h++" || ext == ".h++" ||
  2235. ext == "hxx" || ext == ".hxx" ) { return cmSystemTools::HEADER_FILE_FORMAT; }
  2236. if ( ext == "rc" || ext == ".rc" ) { return cmSystemTools::RESOURCE_FILE_FORMAT; }
  2237. if ( ext == "def" || ext == ".def" ) { return cmSystemTools::DEFINITION_FILE_FORMAT; }
  2238. if ( ext == "lib" || ext == ".lib" ||
  2239. ext == "a" || ext == ".a") { return cmSystemTools::STATIC_LIBRARY_FILE_FORMAT; }
  2240. if ( ext == "o" || ext == ".o" ||
  2241. ext == "obj" || ext == ".obj") { return cmSystemTools::OBJECT_FILE_FORMAT; }
  2242. #ifdef __APPLE__
  2243. if ( ext == "dylib" || ext == ".dylib" )
  2244. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  2245. if ( ext == "so" || ext == ".so" ||
  2246. ext == "bundle" || ext == ".bundle" )
  2247. { return cmSystemTools::MODULE_FILE_FORMAT; }
  2248. #else // __APPLE__
  2249. if ( ext == "so" || ext == ".so" ||
  2250. ext == "sl" || ext == ".sl" ||
  2251. ext == "dll" || ext == ".dll" )
  2252. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  2253. #endif // __APPLE__
  2254. return cmSystemTools::UNKNOWN_FILE_FORMAT;
  2255. }