cmSystemTools.cxx 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455
  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. printf("%s",buf);
  1296. memset(buf, 0, sizeof(buf));
  1297. }
  1298. }
  1299. else
  1300. {
  1301. ReadFile(read_stdout,buf,1023,&bread,NULL);
  1302. output += buf;
  1303. output += "\n";
  1304. if(verbose)
  1305. {
  1306. std::cerr << verbose << " [{" << buf << "}]"
  1307. << std::endl << std::flush;
  1308. }
  1309. }
  1310. }
  1311. }
  1312. CloseHandle(pi.hThread);
  1313. CloseHandle(pi.hProcess);
  1314. CloseHandle(newstdin);
  1315. //clean stuff up
  1316. CloseHandle(newstdout);
  1317. CloseHandle(read_stdout);
  1318. CloseHandle(write_stdin);
  1319. retVal = exit;
  1320. std::cerr << std::endl << "End of WindowsRunCommand(" << command << ")" << std::endl << std::flush;
  1321. return true;
  1322. }
  1323. #include "cmWin32ProcessExecution.h"
  1324. // use this for shell commands like echo and dir
  1325. bool RunCommandViaWin32(const char* command,
  1326. const char* dir,
  1327. std::string& output,
  1328. int& retVal,
  1329. bool verbose)
  1330. {
  1331. ::SetLastError(ERROR_SUCCESS);
  1332. if ( ! command )
  1333. {
  1334. cmSystemTools::Error("No command specified");
  1335. return false;
  1336. }
  1337. //std::cout << "Command: " << command << std::endl;
  1338. if ( dir )
  1339. {
  1340. //std::cout << "Dir: " << dir << std::endl;
  1341. }
  1342. cmWin32ProcessExecution resProc;
  1343. if ( cmSystemTools::GetWindows9xComspecSubstitute() )
  1344. {
  1345. resProc.SetConsoleSpawn(cmSystemTools::GetWindows9xComspecSubstitute() );
  1346. }
  1347. if ( !resProc.StartProcess(command, dir, verbose) )
  1348. {
  1349. std::cout << "Problem starting command" << std::endl;
  1350. return false;
  1351. }
  1352. resProc.Wait(INFINITE);
  1353. output = resProc.GetOutput();
  1354. retVal = resProc.GetExitValue();
  1355. return true;
  1356. }
  1357. // use this for shell commands like echo and dir
  1358. bool RunCommandViaSystem(const char* command,
  1359. const char* dir,
  1360. std::string& output,
  1361. int& retVal,
  1362. bool verbose)
  1363. {
  1364. std::cout << "@@ " << command << std::endl;
  1365. const int BUFFER_SIZE = 4096;
  1366. char buffer[BUFFER_SIZE];
  1367. std::string commandInDir;
  1368. if(dir)
  1369. {
  1370. commandInDir = "cd ";
  1371. commandInDir += cmSystemTools::ConvertToOutputPath(dir);
  1372. commandInDir += " && ";
  1373. commandInDir += command;
  1374. }
  1375. else
  1376. {
  1377. commandInDir = command;
  1378. }
  1379. command = commandInDir.c_str();
  1380. std::string commandToFile = command;
  1381. commandToFile += " > ";
  1382. std::string tempFile;
  1383. tempFile += _tempnam(0, "cmake");
  1384. commandToFile += tempFile;
  1385. retVal = system(commandToFile.c_str());
  1386. std::ifstream fin(tempFile.c_str());
  1387. if(!fin)
  1388. {
  1389. if(verbose)
  1390. {
  1391. std::string errormsg = "RunCommand produced no output: command: \"";
  1392. errormsg += command;
  1393. errormsg += "\"";
  1394. errormsg += "\nOutput file: ";
  1395. errormsg += tempFile;
  1396. cmSystemTools::Error(errormsg.c_str());
  1397. }
  1398. fin.close();
  1399. cmSystemTools::RemoveFile(tempFile.c_str());
  1400. return false;
  1401. }
  1402. bool multiLine = false;
  1403. while(fin)
  1404. {
  1405. fin.getline(buffer, BUFFER_SIZE);
  1406. output += buffer;
  1407. if(multiLine)
  1408. {
  1409. output += "\n";
  1410. }
  1411. multiLine = true;
  1412. }
  1413. fin.close();
  1414. cmSystemTools::RemoveFile(tempFile.c_str());
  1415. return true;
  1416. }
  1417. #endif // endif WIN32 not CYGWIN
  1418. // run a command unix uses popen (easy)
  1419. // windows uses system and ShortPath
  1420. bool cmSystemTools::RunCommand(const char* command,
  1421. std::string& output,
  1422. int &retVal,
  1423. const char* dir,
  1424. bool verbose)
  1425. {
  1426. if(s_DisableRunCommandOutput)
  1427. {
  1428. verbose = false;
  1429. }
  1430. #if defined(WIN32) && !defined(__CYGWIN__)
  1431. // if the command does not start with a quote, then
  1432. // try to find the program, and if the program can not be
  1433. // found use system to run the command as it must be a built in
  1434. // shell command like echo or dir
  1435. int count = 0;
  1436. if(command[0] == '\"')
  1437. {
  1438. // count the number of quotes
  1439. for(const char* s = command; *s != 0; ++s)
  1440. {
  1441. if(*s == '\"')
  1442. {
  1443. count++;
  1444. if(count > 2)
  1445. {
  1446. break;
  1447. }
  1448. }
  1449. }
  1450. // if there are more than two double quotes use
  1451. // GetShortPathName, the cmd.exe program in windows which
  1452. // is used by system fails to execute if there are more than
  1453. // one set of quotes in the arguments
  1454. if(count > 2)
  1455. {
  1456. cmRegularExpression quoted("^\"([^\"]*)\"[ \t](.*)");
  1457. if(quoted.find(command))
  1458. {
  1459. std::string shortCmd;
  1460. std::string cmd = quoted.match(1);
  1461. std::string args = quoted.match(2);
  1462. if(!cmSystemTools::GetShortPath(cmd.c_str(), shortCmd))
  1463. {
  1464. cmSystemTools::Error("GetShortPath failed for " , cmd.c_str());
  1465. return false;
  1466. }
  1467. shortCmd += " ";
  1468. shortCmd += args;
  1469. //return RunCommandViaSystem(shortCmd.c_str(), dir,
  1470. // output, retVal, verbose);
  1471. //return WindowsRunCommand(shortCmd.c_str(), dir,
  1472. //output, retVal, verbose);
  1473. return RunCommandViaWin32(shortCmd.c_str(), dir,
  1474. output, retVal, verbose);
  1475. }
  1476. else
  1477. {
  1478. cmSystemTools::Error("Could not parse command line with quotes ",
  1479. command);
  1480. }
  1481. }
  1482. }
  1483. // if there is only one set of quotes or no quotes then just run the command
  1484. //return RunCommandViaSystem(command, dir, output, retVal, verbose);
  1485. //return WindowsRunCommand(command, dir, output, retVal, verbose);
  1486. return RunCommandViaWin32(command, dir, output, retVal, verbose);
  1487. #else
  1488. // if only popen worked on windows.....
  1489. std::string commandInDir;
  1490. if(dir)
  1491. {
  1492. commandInDir = "cd ";
  1493. commandInDir += dir;
  1494. commandInDir += " && ";
  1495. commandInDir += command;
  1496. }
  1497. else
  1498. {
  1499. commandInDir = command;
  1500. }
  1501. commandInDir += " 2>&1";
  1502. command = commandInDir.c_str();
  1503. const int BUFFER_SIZE = 4096;
  1504. char buffer[BUFFER_SIZE];
  1505. if(verbose)
  1506. {
  1507. std::cout << "running " << command << std::endl;
  1508. }
  1509. fflush(stdout);
  1510. fflush(stderr);
  1511. FILE* cpipe = popen(command, "r");
  1512. if(!cpipe)
  1513. {
  1514. return false;
  1515. }
  1516. fgets(buffer, BUFFER_SIZE, cpipe);
  1517. while(!feof(cpipe))
  1518. {
  1519. if(verbose)
  1520. {
  1521. std::cout << buffer << std::flush;
  1522. }
  1523. output += buffer;
  1524. fgets(buffer, BUFFER_SIZE, cpipe);
  1525. }
  1526. retVal = pclose(cpipe);
  1527. if (WIFEXITED(retVal))
  1528. {
  1529. retVal = WEXITSTATUS(retVal);
  1530. return true;
  1531. }
  1532. if (WIFSIGNALED(retVal))
  1533. {
  1534. retVal = WTERMSIG(retVal);
  1535. cmStringStream error;
  1536. error << "\nProcess terminated due to ";
  1537. switch (retVal)
  1538. {
  1539. #ifdef SIGKILL
  1540. case SIGKILL:
  1541. error << "SIGKILL";
  1542. break;
  1543. #endif
  1544. #ifdef SIGFPE
  1545. case SIGFPE:
  1546. error << "SIGFPE";
  1547. break;
  1548. #endif
  1549. #ifdef SIGBUS
  1550. case SIGBUS:
  1551. error << "SIGBUS";
  1552. break;
  1553. #endif
  1554. #ifdef SIGSEGV
  1555. case SIGSEGV:
  1556. error << "SIGSEGV";
  1557. break;
  1558. #endif
  1559. default:
  1560. error << "signal " << retVal;
  1561. break;
  1562. }
  1563. output += error.str();
  1564. }
  1565. return false;
  1566. #endif
  1567. }
  1568. /**
  1569. * Find the file the given name. Searches the given path and then
  1570. * the system search path. Returns the full path to the file if it is
  1571. * found. Otherwise, the empty string is returned.
  1572. */
  1573. std::string cmSystemTools::FindFile(const char* name,
  1574. const std::vector<std::string>& userPaths)
  1575. {
  1576. // Add the system search path to our path.
  1577. std::vector<std::string> path = userPaths;
  1578. cmSystemTools::GetPath(path);
  1579. std::string tryPath;
  1580. for(std::vector<std::string>::const_iterator p = path.begin();
  1581. p != path.end(); ++p)
  1582. {
  1583. tryPath = *p;
  1584. tryPath += "/";
  1585. tryPath += name;
  1586. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1587. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1588. {
  1589. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1590. }
  1591. }
  1592. // Couldn't find the file.
  1593. return "";
  1594. }
  1595. /**
  1596. * Find the executable with the given name. Searches the given path and then
  1597. * the system search path. Returns the full path to the executable if it is
  1598. * found. Otherwise, the empty string is returned.
  1599. */
  1600. std::string cmSystemTools::FindProgram(const char* name,
  1601. const std::vector<std::string>& userPaths,
  1602. bool no_system_path)
  1603. {
  1604. // See if the executable exists as written.
  1605. if(cmSystemTools::FileExists(name) &&
  1606. !cmSystemTools::FileIsDirectory(name))
  1607. {
  1608. return cmSystemTools::CollapseFullPath(name);
  1609. }
  1610. std::string tryPath = name;
  1611. tryPath += cmSystemTools::GetExecutableExtension();
  1612. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1613. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1614. {
  1615. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1616. }
  1617. // Add the system search path to our path.
  1618. std::vector<std::string> path = userPaths;
  1619. if (!no_system_path)
  1620. {
  1621. cmSystemTools::GetPath(path);
  1622. }
  1623. for(std::vector<std::string>::const_iterator p = path.begin();
  1624. p != path.end(); ++p)
  1625. {
  1626. tryPath = *p;
  1627. tryPath += "/";
  1628. tryPath += name;
  1629. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1630. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1631. {
  1632. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1633. }
  1634. #ifdef _WIN32
  1635. tryPath += ".com";
  1636. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1637. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1638. {
  1639. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1640. }
  1641. tryPath = *p;
  1642. tryPath += "/";
  1643. tryPath += name;
  1644. #endif
  1645. tryPath += cmSystemTools::GetExecutableExtension();
  1646. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1647. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1648. {
  1649. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1650. }
  1651. }
  1652. // Couldn't find the program.
  1653. return "";
  1654. }
  1655. /**
  1656. * Find the library with the given name. Searches the given path and then
  1657. * the system search path. Returns the full path to the library if it is
  1658. * found. Otherwise, the empty string is returned.
  1659. */
  1660. std::string cmSystemTools::FindLibrary(const char* name,
  1661. const std::vector<std::string>& userPaths,
  1662. const cmMakefile *makefile)
  1663. {
  1664. // See if the executable exists as written.
  1665. if(cmSystemTools::FileExists(name))
  1666. {
  1667. return cmSystemTools::CollapseFullPath(name);
  1668. }
  1669. // Add the system search path to our path.
  1670. std::vector<std::string> path = userPaths;
  1671. cmSystemTools::GetPath(path);
  1672. // Add some lib directories specific to compilers, depending on the
  1673. // current generator, so that library that might have been stored here
  1674. // can be found too.
  1675. // i.e. Microsoft Visual Studio or .Net: path to compiler/../Lib
  1676. // Borland: path to compiler/../Lib
  1677. if (makefile)
  1678. {
  1679. const char* genName = makefile->GetDefinition("CMAKE_GENERATOR");
  1680. if (genName)
  1681. {
  1682. if (!strcmp(genName, "NMake Makefiles") ||
  1683. !strcmp(genName, "Visual Studio 6"))
  1684. {
  1685. const char* compiler = makefile->GetDefinition("CMAKE_CXX_COMPILER");
  1686. if (compiler)
  1687. {
  1688. std::string compiler_path = cmSystemTools::FindProgram(compiler);
  1689. if (compiler_path.size())
  1690. {
  1691. std::string lib_path =
  1692. cmSystemTools::GetFilenamePath(
  1693. cmSystemTools::GetFilenamePath(compiler_path)) + "/Lib";
  1694. path.push_back(lib_path);
  1695. }
  1696. }
  1697. }
  1698. else if (!strcmp(genName, "Visual Studio 7"))
  1699. {
  1700. // It is likely that the compiler won't be in the path for .Net, but
  1701. // we know where devenv is.
  1702. const char* devenv = makefile->GetDefinition("MICROSOFT_DEVENV");
  1703. if (devenv)
  1704. {
  1705. std::string devenv_path = cmSystemTools::FindProgram(devenv);
  1706. if (devenv_path.size())
  1707. {
  1708. std::string vc7_path =
  1709. cmSystemTools::GetFilenamePath(
  1710. cmSystemTools::GetFilenamePath(
  1711. cmSystemTools::GetFilenamePath(devenv_path))) + "/Vc7";
  1712. path.push_back(vc7_path + "/lib");
  1713. path.push_back(vc7_path + "/PlatformSDK/lib");
  1714. }
  1715. }
  1716. }
  1717. else if (!strcmp(genName, "Borland Makefiles"))
  1718. {
  1719. const char* bcb_bin_path = makefile->GetDefinition("BCB_BIN_PATH");
  1720. if (bcb_bin_path)
  1721. {
  1722. std::string lib_path =
  1723. cmSystemTools::GetFilenamePath(bcb_bin_path) + "/Lib";
  1724. path.push_back(lib_path);
  1725. }
  1726. }
  1727. }
  1728. }
  1729. std::string tryPath;
  1730. for(std::vector<std::string>::const_iterator p = path.begin();
  1731. p != path.end(); ++p)
  1732. {
  1733. #if defined(_WIN32) && !defined(__CYGWIN__)
  1734. tryPath = *p;
  1735. tryPath += "/";
  1736. tryPath += name;
  1737. tryPath += ".lib";
  1738. if(cmSystemTools::FileExists(tryPath.c_str()))
  1739. {
  1740. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1741. }
  1742. #else
  1743. tryPath = *p;
  1744. tryPath += "/lib";
  1745. tryPath += name;
  1746. tryPath += ".so";
  1747. if(cmSystemTools::FileExists(tryPath.c_str()))
  1748. {
  1749. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1750. }
  1751. tryPath = *p;
  1752. tryPath += "/lib";
  1753. tryPath += name;
  1754. tryPath += ".a";
  1755. if(cmSystemTools::FileExists(tryPath.c_str()))
  1756. {
  1757. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1758. }
  1759. tryPath = *p;
  1760. tryPath += "/lib";
  1761. tryPath += name;
  1762. tryPath += ".sl";
  1763. if(cmSystemTools::FileExists(tryPath.c_str()))
  1764. {
  1765. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1766. }
  1767. tryPath = *p;
  1768. tryPath += "/lib";
  1769. tryPath += name;
  1770. tryPath += ".dylib";
  1771. if(cmSystemTools::FileExists(tryPath.c_str()))
  1772. {
  1773. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1774. }
  1775. #endif
  1776. }
  1777. // Couldn't find the library.
  1778. return "";
  1779. }
  1780. bool cmSystemTools::FileIsDirectory(const char* name)
  1781. {
  1782. struct stat fs;
  1783. if(stat(name, &fs) == 0)
  1784. {
  1785. #if _WIN32
  1786. return ((fs.st_mode & _S_IFDIR) != 0);
  1787. #else
  1788. return S_ISDIR(fs.st_mode);
  1789. #endif
  1790. }
  1791. else
  1792. {
  1793. return false;
  1794. }
  1795. }
  1796. int cmSystemTools::ChangeDirectory(const char *dir)
  1797. {
  1798. return Chdir(dir);
  1799. }
  1800. std::string cmSystemTools::GetCurrentWorkingDirectory()
  1801. {
  1802. char buf[2048];
  1803. std::string path = Getcwd(buf, 2048);
  1804. return path;
  1805. }
  1806. /**
  1807. * Given the path to a program executable, get the directory part of the path with the
  1808. * file stripped off. If there is no directory part, the empty string is returned.
  1809. */
  1810. std::string cmSystemTools::GetProgramPath(const char* in_name)
  1811. {
  1812. std::string dir, file;
  1813. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1814. return dir;
  1815. }
  1816. /**
  1817. * Given the path to a program executable, get the directory part of the path
  1818. * with the file stripped off. If there is no directory part, the empty
  1819. * string is returned.
  1820. */
  1821. void cmSystemTools::SplitProgramPath(const char* in_name,
  1822. std::string& dir,
  1823. std::string& file)
  1824. {
  1825. dir = in_name;
  1826. file = "";
  1827. cmSystemTools::ConvertToUnixSlashes(dir);
  1828. if(!cmSystemTools::FileIsDirectory(dir.c_str()))
  1829. {
  1830. std::string::size_type slashPos = dir.rfind("/");
  1831. if(slashPos != std::string::npos)
  1832. {
  1833. file = dir.substr(slashPos+1);
  1834. dir = dir.substr(0, slashPos);
  1835. }
  1836. else
  1837. {
  1838. file = dir;
  1839. dir = "";
  1840. }
  1841. }
  1842. if((dir != "") && !cmSystemTools::FileIsDirectory(dir.c_str()))
  1843. {
  1844. std::string oldDir = in_name;
  1845. cmSystemTools::ConvertToUnixSlashes(oldDir);
  1846. cmSystemTools::Error("Error splitting file name off end of path:\n",
  1847. oldDir.c_str(), "\nDirectory not found: ",
  1848. dir.c_str());
  1849. dir = in_name;
  1850. return;
  1851. }
  1852. }
  1853. /**
  1854. * Given a path to a file or directory, convert it to a full path.
  1855. * This collapses away relative paths. The full path is returned.
  1856. */
  1857. std::string cmSystemTools::CollapseFullPath(const char* in_name)
  1858. {
  1859. std::string dir, file;
  1860. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1861. #ifdef _WIN32
  1862. // Ultra-hack warning:
  1863. // This changes to the target directory, saves the working directory,
  1864. // and then changes back to the original working directory.
  1865. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1866. if(dir != "") { Chdir(dir.c_str()); }
  1867. std::string newDir = cmSystemTools::GetCurrentWorkingDirectory();
  1868. Chdir(cwd.c_str());
  1869. cmSystemTools::ConvertToUnixSlashes(newDir);
  1870. std::string newPath = newDir+"/"+file;
  1871. return newPath;
  1872. #else
  1873. # ifdef MAXPATHLEN
  1874. char resolved_name[MAXPATHLEN];
  1875. # else
  1876. # ifdef PATH_MAX
  1877. char resolved_name[PATH_MAX];
  1878. # else
  1879. char resolved_name[5024];
  1880. # endif
  1881. # endif
  1882. if(dir != "")
  1883. {
  1884. realpath(dir.c_str(), resolved_name);
  1885. dir = resolved_name;
  1886. }
  1887. else
  1888. {
  1889. dir = cmSystemTools::GetCurrentWorkingDirectory();
  1890. }
  1891. if(file == "")
  1892. {
  1893. return dir;
  1894. }
  1895. return dir + "/" + file;
  1896. #endif
  1897. }
  1898. /**
  1899. * Return path of a full filename (no trailing slashes).
  1900. * Warning: returned path is converted to Unix slashes format.
  1901. */
  1902. std::string cmSystemTools::GetFilenamePath(const std::string& filename)
  1903. {
  1904. std::string fn = filename;
  1905. cmSystemTools::ConvertToUnixSlashes(fn);
  1906. std::string::size_type slash_pos = fn.rfind("/");
  1907. if(slash_pos != std::string::npos)
  1908. {
  1909. return fn.substr(0, slash_pos);
  1910. }
  1911. else
  1912. {
  1913. return "";
  1914. }
  1915. }
  1916. /**
  1917. * Return file name of a full filename (i.e. file name without path).
  1918. */
  1919. std::string cmSystemTools::GetFilenameName(const std::string& filename)
  1920. {
  1921. std::string fn = filename;
  1922. cmSystemTools::ConvertToUnixSlashes(fn);
  1923. std::string::size_type slash_pos = fn.rfind("/");
  1924. if(slash_pos != std::string::npos)
  1925. {
  1926. return fn.substr(slash_pos + 1);
  1927. }
  1928. else
  1929. {
  1930. return filename;
  1931. }
  1932. }
  1933. /**
  1934. * Return file extension of a full filename (dot included).
  1935. * Warning: this is the longest extension (for example: .tar.gz)
  1936. */
  1937. std::string cmSystemTools::GetFilenameExtension(const std::string& filename)
  1938. {
  1939. std::string name = cmSystemTools::GetFilenameName(filename);
  1940. std::string::size_type dot_pos = name.find(".");
  1941. if(dot_pos != std::string::npos)
  1942. {
  1943. return name.substr(dot_pos);
  1944. }
  1945. else
  1946. {
  1947. return "";
  1948. }
  1949. }
  1950. /**
  1951. * Return file name without extension of a full filename (i.e. without path).
  1952. * Warning: it considers the longest extension (for example: .tar.gz)
  1953. */
  1954. std::string cmSystemTools::GetFilenameWithoutExtension(const std::string& filename)
  1955. {
  1956. std::string name = cmSystemTools::GetFilenameName(filename);
  1957. std::string::size_type dot_pos = name.find(".");
  1958. if(dot_pos != std::string::npos)
  1959. {
  1960. return name.substr(0, dot_pos);
  1961. }
  1962. else
  1963. {
  1964. return name;
  1965. }
  1966. }
  1967. /**
  1968. * Return file name without extension of a full filename (i.e. without path).
  1969. * Warning: it considers the last extension (for example: removes .gz
  1970. * from .tar.gz)
  1971. */
  1972. std::string
  1973. cmSystemTools::GetFilenameWithoutLastExtension(const std::string& filename)
  1974. {
  1975. std::string name = cmSystemTools::GetFilenameName(filename);
  1976. std::string::size_type dot_pos = name.rfind(".");
  1977. if(dot_pos != std::string::npos)
  1978. {
  1979. return name.substr(0, dot_pos);
  1980. }
  1981. else
  1982. {
  1983. return name;
  1984. }
  1985. }
  1986. bool cmSystemTools::FileIsFullPath(const char* in_name)
  1987. {
  1988. std::string name = in_name;
  1989. #if defined(_WIN32)
  1990. // On Windows, the name must be at least two characters long.
  1991. if(name.length() < 2)
  1992. {
  1993. return false;
  1994. }
  1995. if(name[1] == ':')
  1996. {
  1997. return true;
  1998. }
  1999. if(name[0] == '\\')
  2000. {
  2001. return true;
  2002. }
  2003. #else
  2004. // On UNIX, the name must be at least one character long.
  2005. if(name.length() < 1)
  2006. {
  2007. return false;
  2008. }
  2009. #endif
  2010. // On UNIX, the name must begin in a '/'.
  2011. // On Windows, if the name begins in a '/', then it is a full
  2012. // network path.
  2013. if(name[0] == '/')
  2014. {
  2015. return true;
  2016. }
  2017. return false;
  2018. }
  2019. void cmSystemTools::Glob(const char *directory, const char *regexp,
  2020. std::vector<std::string>& files)
  2021. {
  2022. cmDirectory d;
  2023. cmRegularExpression reg(regexp);
  2024. if (d.Load(directory))
  2025. {
  2026. size_t numf;
  2027. unsigned int i;
  2028. numf = d.GetNumberOfFiles();
  2029. for (i = 0; i < numf; i++)
  2030. {
  2031. std::string fname = d.GetFile(i);
  2032. if (reg.find(fname))
  2033. {
  2034. files.push_back(fname);
  2035. }
  2036. }
  2037. }
  2038. }
  2039. void cmSystemTools::GlobDirs(const char *fullPath,
  2040. std::vector<std::string>& files)
  2041. {
  2042. std::string path = fullPath;
  2043. std::string::size_type pos = path.find("/*");
  2044. if(pos == std::string::npos)
  2045. {
  2046. files.push_back(fullPath);
  2047. return;
  2048. }
  2049. std::string startPath = path.substr(0, pos);
  2050. std::string finishPath = path.substr(pos+2);
  2051. cmDirectory d;
  2052. if (d.Load(startPath.c_str()))
  2053. {
  2054. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  2055. {
  2056. if((std::string(d.GetFile(i)) != ".")
  2057. && (std::string(d.GetFile(i)) != ".."))
  2058. {
  2059. std::string fname = startPath;
  2060. fname +="/";
  2061. fname += d.GetFile(i);
  2062. if(cmSystemTools::FileIsDirectory(fname.c_str()))
  2063. {
  2064. fname += finishPath;
  2065. cmSystemTools::GlobDirs(fname.c_str(), files);
  2066. }
  2067. }
  2068. }
  2069. }
  2070. }
  2071. void cmSystemTools::ExpandListArguments(std::vector<std::string> const& arguments,
  2072. std::vector<std::string>& newargs)
  2073. {
  2074. std::vector<std::string>::const_iterator i;
  2075. std::string newarg;
  2076. for(i = arguments.begin();i != arguments.end(); ++i)
  2077. {
  2078. // if there are no ; in the name then just copy the current string
  2079. if(i->find(';') == std::string::npos)
  2080. {
  2081. newargs.push_back(*i);
  2082. }
  2083. else
  2084. {
  2085. std::string::size_type start = 0;
  2086. std::string::size_type endpos = 0;
  2087. const std::string::size_type size = i->size();
  2088. // break up ; separated sections of the string into separate strings
  2089. while(endpos != size)
  2090. {
  2091. endpos = i->find(';', start);
  2092. if(endpos == std::string::npos)
  2093. {
  2094. endpos = i->size();
  2095. }
  2096. else
  2097. {
  2098. // skip right over escaped ; ( \; )
  2099. while((endpos != std::string::npos)
  2100. && (endpos > 0)
  2101. && ((*i)[endpos-1] == '\\') )
  2102. {
  2103. endpos = i->find(';', endpos+1);
  2104. }
  2105. if(endpos == std::string::npos)
  2106. {
  2107. endpos = i->size();
  2108. }
  2109. }
  2110. std::string::size_type len = endpos - start;
  2111. if (len > 0)
  2112. {
  2113. // check for a closing ] after the start position
  2114. if(i->find('[', start) == std::string::npos)
  2115. {
  2116. // if there is no [ in the string then keep it
  2117. newarg = i->substr(start, len);
  2118. }
  2119. else
  2120. {
  2121. int opencount = 0;
  2122. int closecount = 0;
  2123. for(std::string::size_type j = start; j < endpos; ++j)
  2124. {
  2125. if(i->at(j) == '[')
  2126. {
  2127. ++opencount;
  2128. }
  2129. else if (i->at(j) == ']')
  2130. {
  2131. ++closecount;
  2132. }
  2133. }
  2134. if(opencount != closecount)
  2135. {
  2136. // skip this one
  2137. endpos = i->find(';', endpos+1);
  2138. if(endpos == std::string::npos)
  2139. {
  2140. endpos = i->size();
  2141. }
  2142. len = endpos - start;
  2143. }
  2144. newarg = i->substr(start, len);
  2145. }
  2146. std::string::size_type pos = newarg.find("\\;");
  2147. if(pos != std::string::npos)
  2148. {
  2149. newarg.erase(pos, 1);
  2150. }
  2151. newargs.push_back(newarg);
  2152. }
  2153. start = endpos+1;
  2154. }
  2155. }
  2156. }
  2157. }
  2158. bool cmSystemTools::GetShortPath(const char* path, std::string& shortPath)
  2159. {
  2160. #if defined(WIN32) && !defined(__CYGWIN__)
  2161. const int size = int(strlen(path)) +1; // size of return
  2162. char *buffer = new char[size]; // create a buffer
  2163. char *tempPath = new char[size]; // create a buffer
  2164. int ret;
  2165. // if the path passed in has quotes around it, first remove the quotes
  2166. if (path[0] == '"' && path[strlen(path)-1] == '"')
  2167. {
  2168. strcpy(tempPath,path+1);
  2169. tempPath[strlen(tempPath)-1] = '\0';
  2170. }
  2171. else
  2172. {
  2173. strcpy(tempPath,path);
  2174. }
  2175. buffer[0] = 0;
  2176. ret = GetShortPathName(tempPath, buffer, size);
  2177. if(buffer[0] == 0 || ret > size)
  2178. {
  2179. if(ret < size)
  2180. {
  2181. LPVOID lpMsgBuf;
  2182. FormatMessage(
  2183. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  2184. FORMAT_MESSAGE_FROM_SYSTEM |
  2185. FORMAT_MESSAGE_IGNORE_INSERTS,
  2186. NULL,
  2187. GetLastError(),
  2188. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  2189. (LPTSTR) &lpMsgBuf,
  2190. 0,
  2191. NULL
  2192. );
  2193. cmSystemTools::Error((LPCTSTR)lpMsgBuf);
  2194. LocalFree( lpMsgBuf );
  2195. }
  2196. cmSystemTools::Error("Unable to get a short path: ", path);
  2197. delete [] tempPath;
  2198. return false;
  2199. }
  2200. else
  2201. {
  2202. shortPath = buffer;
  2203. delete [] buffer;
  2204. delete [] tempPath;
  2205. return true;
  2206. }
  2207. #else
  2208. shortPath = path;
  2209. return true;
  2210. #endif
  2211. }
  2212. cmSystemTools::e_FileFormat cmSystemTools::GetFileFormat(const char* cext)
  2213. {
  2214. if ( ! cext || *cext == 0 )
  2215. {
  2216. return cmSystemTools::NO_FILE_FORMAT;
  2217. }
  2218. std::string ext = cmSystemTools::LowerCase(cext);
  2219. if ( ext == "c" || ext == ".c" ) { return cmSystemTools::C_FILE_FORMAT; }
  2220. if ( ext == "cxx" || ext == ".cxx" ||
  2221. ext == "cpp" || ext == ".cpp" ||
  2222. ext == "c++" || ext == ".c++" ||
  2223. ext == "cc" || ext == ".cc" ) { return cmSystemTools::CXX_FILE_FORMAT; }
  2224. if ( ext == "java" || ext == ".java" ) { return cmSystemTools::JAVA_FILE_FORMAT; }
  2225. if ( ext == "h" || ext == ".h" ||
  2226. ext == "hpp" || ext == ".hpp" ||
  2227. ext == "h++" || ext == ".h++" ||
  2228. ext == "hxx" || ext == ".hxx" ) { return cmSystemTools::HEADER_FILE_FORMAT; }
  2229. if ( ext == "rc" || ext == ".rc" ) { return cmSystemTools::RESOURCE_FILE_FORMAT; }
  2230. if ( ext == "def" || ext == ".def" ) { return cmSystemTools::DEFINITION_FILE_FORMAT; }
  2231. if ( ext == "lib" || ext == ".lib" ||
  2232. ext == "a" || ext == ".a") { return cmSystemTools::STATIC_LIBRARY_FILE_FORMAT; }
  2233. if ( ext == "o" || ext == ".o" ||
  2234. ext == "obj" || ext == ".obj") { return cmSystemTools::OBJECT_FILE_FORMAT; }
  2235. #ifdef __APPLE__
  2236. if ( ext == "dylib" || ext == ".dylib" )
  2237. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  2238. if ( ext == "so" || ext == ".so" ||
  2239. ext == "bundle" || ext == ".bundle" )
  2240. { return cmSystemTools::MODULE_FILE_FORMAT; }
  2241. #else // __APPLE__
  2242. if ( ext == "so" || ext == ".so" ||
  2243. ext == "sl" || ext == ".sl" ||
  2244. ext == "dll" || ext == ".dll" )
  2245. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  2246. #endif // __APPLE__
  2247. return cmSystemTools::UNKNOWN_FILE_FORMAT;
  2248. }