cmSystemTools.cxx 61 KB

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