cmSystemTools.cxx 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452
  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 <errno.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. if(ret[0] == '\"')
  750. {
  751. pos = 2; // if the string is already quoted then start at 2
  752. if(ret.size() < 3)
  753. {
  754. return ret;
  755. }
  756. }
  757. while((pos = ret.find("\\\\", pos)) != std::string::npos)
  758. {
  759. ret.erase(pos, 1);
  760. }
  761. // now double quote the path if it has spaces in it
  762. // and is not already double quoted
  763. if(ret.find(" ") != std::string::npos
  764. && ret[0] != '\"')
  765. {
  766. std::string result;
  767. result = "\"" + ret + "\"";
  768. ret = result;
  769. }
  770. return ret;
  771. }
  772. inline void RemoveComments(char* ptr)
  773. {
  774. while(*ptr)
  775. {
  776. if(*ptr == '#')
  777. {
  778. *ptr = 0;
  779. break;
  780. }
  781. ++ptr;
  782. }
  783. }
  784. bool cmSystemTools::ParseFunction(std::ifstream& fin,
  785. std::string& name,
  786. std::vector<std::string>& arguments,
  787. const char* filename,
  788. bool& parseError)
  789. {
  790. parseError = false;
  791. name = "";
  792. arguments = std::vector<std::string>();
  793. const int BUFFER_SIZE = 4096;
  794. char inbuffer[BUFFER_SIZE];
  795. if(!fin)
  796. {
  797. return false;
  798. }
  799. if(fin.getline(inbuffer, BUFFER_SIZE ) )
  800. {
  801. RemoveComments(inbuffer);
  802. cmRegularExpression blankLine("^[ \t\r]*$");
  803. // cmRegularExpression comment("^[ \t]*#.*$");
  804. cmRegularExpression oneLiner("^[ \t]*([A-Za-z_0-9]*)[ \t]*\\((.*)\\)[ \t\r]*$");
  805. cmRegularExpression multiLine("^[ \t]*([A-Za-z_0-9]*)[ \t]*\\((.*)$");
  806. cmRegularExpression lastLine("^(.*)\\)[ \t\r]*$");
  807. // check for blank line or comment
  808. if(blankLine.find(inbuffer) )
  809. {
  810. return false;
  811. }
  812. // look for a oneline fun(arg arg2)
  813. else if(oneLiner.find(inbuffer))
  814. {
  815. // the arguments are the second match
  816. std::string args = oneLiner.match(2);
  817. name = oneLiner.match(1);
  818. // break up the arguments
  819. cmSystemTools::GetArguments(args, arguments);
  820. return true;
  821. }
  822. // look for a start of a multiline with no trailing ")" fun(arg arg2
  823. else if(multiLine.find(inbuffer))
  824. {
  825. name = multiLine.match(1);
  826. std::string args = multiLine.match(2);
  827. cmSystemTools::GetArguments(args, arguments);
  828. // Read lines until the closing paren is hit
  829. bool done = false;
  830. while(!done)
  831. {
  832. // read lines until the end paren is found
  833. if(fin.getline(inbuffer, BUFFER_SIZE ) )
  834. {
  835. RemoveComments(inbuffer);
  836. // Check for comment lines and ignore them.
  837. if(blankLine.find(inbuffer))
  838. { continue; }
  839. // Is this the last line?
  840. if(lastLine.find(inbuffer))
  841. {
  842. done = true;
  843. std::string gargs = lastLine.match(1);
  844. cmSystemTools::GetArguments(gargs, arguments);
  845. }
  846. else
  847. {
  848. std::string line = inbuffer;
  849. cmSystemTools::GetArguments(line, arguments);
  850. }
  851. }
  852. else
  853. {
  854. parseError = true;
  855. cmSystemTools::Error("Parse error in read function missing end )\nIn File: ",
  856. filename, "\nCurrent line:", inbuffer);
  857. return false;
  858. }
  859. }
  860. return true;
  861. }
  862. else
  863. {
  864. parseError = true;
  865. cmSystemTools::Error("Parse error in read function\nIn file:",
  866. filename, "\nCurrent line:", inbuffer);
  867. return false;
  868. }
  869. }
  870. return false;
  871. }
  872. void cmSystemTools::GetArguments(std::string& line,
  873. std::vector<std::string>& arguments)
  874. {
  875. // Match a normal argument (not quoted, no spaces).
  876. cmRegularExpression normalArgument("[ \t]*(([^ \t\r\\]|[\\].)+)[ \t\r]*");
  877. // Match a quoted argument (surrounded by double quotes, spaces allowed).
  878. cmRegularExpression quotedArgument("[ \t]*(\"([^\"\\]|[\\].)*\")[ \t\r]*");
  879. bool done = false;
  880. while(!done)
  881. {
  882. std::string arg;
  883. std::string::size_type endpos=0;
  884. bool foundQuoted = quotedArgument.find(line.c_str());
  885. bool foundNormal = normalArgument.find(line.c_str());
  886. if(foundQuoted && foundNormal)
  887. {
  888. // Both matches were found. Take the earlier one.
  889. // Favor double-quoted version if there is a tie.
  890. if(normalArgument.start(1) < quotedArgument.start(1))
  891. {
  892. arg = normalArgument.match(1);
  893. endpos = normalArgument.end(1);
  894. }
  895. else
  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. }
  903. else if (foundQuoted)
  904. {
  905. arg = quotedArgument.match(1);
  906. endpos = quotedArgument.end(1);
  907. // Strip off the double quotes on the ends.
  908. arg = arg.substr(1, arg.length()-2);
  909. }
  910. else if(foundNormal)
  911. {
  912. arg = normalArgument.match(1);
  913. endpos = normalArgument.end(1);
  914. }
  915. else
  916. {
  917. done = true;
  918. }
  919. if(!done)
  920. {
  921. arguments.push_back(cmSystemTools::RemoveEscapes(arg.c_str()));
  922. line = line.substr(endpos, line.length() - endpos);
  923. }
  924. }
  925. }
  926. std::string cmSystemTools::RemoveEscapes(const char* s)
  927. {
  928. std::string result = "";
  929. for(const char* ch = s; *ch; ++ch)
  930. {
  931. if(*ch == '\\' && *(ch+1) != ';')
  932. {
  933. ++ch;
  934. switch (*ch)
  935. {
  936. case '\\': result.insert(result.end(), '\\'); break;
  937. case '"': result.insert(result.end(), '"'); break;
  938. case ' ': result.insert(result.end(), ' '); break;
  939. case 't': result.insert(result.end(), '\t'); break;
  940. case 'n': result.insert(result.end(), '\n'); break;
  941. case 'r': result.insert(result.end(), '\r'); break;
  942. case '0': result.insert(result.end(), '\0'); break;
  943. case '\0':
  944. {
  945. cmSystemTools::Error("Trailing backslash in argument:\n", s);
  946. return result;
  947. }
  948. default:
  949. {
  950. std::string chStr(1, *ch);
  951. cmSystemTools::Error("Invalid escape sequence \\", chStr.c_str(),
  952. "\nin argument ", s);
  953. }
  954. }
  955. }
  956. else
  957. {
  958. result.insert(result.end(), *ch);
  959. }
  960. }
  961. return result;
  962. }
  963. void cmSystemTools::Error(const char* m1, const char* m2,
  964. const char* m3, const char* m4)
  965. {
  966. std::string message = "CMake Error: ";
  967. if(m1)
  968. {
  969. message += m1;
  970. }
  971. if(m2)
  972. {
  973. message += m2;
  974. }
  975. if(m3)
  976. {
  977. message += m3;
  978. }
  979. if(m4)
  980. {
  981. message += m4;
  982. }
  983. cmSystemTools::s_ErrorOccured = true;
  984. cmSystemTools::Message(message.c_str(),"Error");
  985. }
  986. void cmSystemTools::SetErrorCallback(ErrorCallback f, void* clientData)
  987. {
  988. s_ErrorCallback = f;
  989. s_ErrorCallbackClientData = clientData;
  990. }
  991. void cmSystemTools::Message(const char* m1, const char *title)
  992. {
  993. if(s_DisableMessages)
  994. {
  995. return;
  996. }
  997. if(s_ErrorCallback)
  998. {
  999. (*s_ErrorCallback)(m1, title, s_DisableMessages, s_ErrorCallbackClientData);
  1000. return;
  1001. }
  1002. else
  1003. {
  1004. std::cerr << m1 << std::endl << std::flush;
  1005. }
  1006. }
  1007. bool cmSystemTools::CopyFileIfDifferent(const char* source,
  1008. const char* destination)
  1009. {
  1010. if(cmSystemTools::FilesDiffer(source, destination))
  1011. {
  1012. cmSystemTools::cmCopyFile(source, destination);
  1013. return true;
  1014. }
  1015. return false;
  1016. }
  1017. bool cmSystemTools::FilesDiffer(const char* source,
  1018. const char* destination)
  1019. {
  1020. struct stat statSource;
  1021. if (stat(source, &statSource) != 0)
  1022. {
  1023. return true;
  1024. }
  1025. struct stat statDestination;
  1026. if (stat(destination, &statDestination) != 0)
  1027. {
  1028. return true;
  1029. }
  1030. if(statSource.st_size != statDestination.st_size)
  1031. {
  1032. return true;
  1033. }
  1034. if(statSource.st_size == 0)
  1035. {
  1036. return false;
  1037. }
  1038. #if defined(_WIN32) || defined(__CYGWIN__)
  1039. std::ifstream finSource(source,
  1040. std::ios::binary | std::ios::in);
  1041. std::ifstream finDestination(destination,
  1042. std::ios::binary | std::ios::in);
  1043. #else
  1044. std::ifstream finSource(source);
  1045. std::ifstream finDestination(destination);
  1046. #endif
  1047. if(!finSource || !finDestination)
  1048. {
  1049. return true;
  1050. }
  1051. char* source_buf = new char[statSource.st_size];
  1052. char* dest_buf = new char[statSource.st_size];
  1053. finSource.read(source_buf, statSource.st_size);
  1054. finDestination.read(dest_buf, statSource.st_size);
  1055. if(statSource.st_size != static_cast<long>(finSource.gcount()) ||
  1056. statSource.st_size != static_cast<long>(finDestination.gcount()))
  1057. {
  1058. cmOStringStream msg;
  1059. msg << "FilesDiffer failed to read files (allocated: "
  1060. << statSource.st_size << ", read source: " << finSource.gcount()
  1061. << ", read dest: " << finDestination.gcount();
  1062. cmSystemTools::Error(msg.str().c_str());
  1063. delete [] source_buf;
  1064. delete [] dest_buf;
  1065. return false;
  1066. }
  1067. int ret = memcmp((const void*)source_buf,
  1068. (const void*)dest_buf,
  1069. statSource.st_size);
  1070. delete [] dest_buf;
  1071. delete [] source_buf;
  1072. return ret != 0;
  1073. }
  1074. /**
  1075. * Copy a file named by "source" to the file named by "destination".
  1076. */
  1077. void cmSystemTools::cmCopyFile(const char* source,
  1078. const char* destination)
  1079. {
  1080. const int bufferSize = 4096;
  1081. char buffer[bufferSize];
  1082. // If destination is a directory, try to create a file with the same
  1083. // name as the source in that directory.
  1084. std::string new_destination;
  1085. if(cmSystemTools::FileExists(destination) &&
  1086. cmSystemTools::FileIsDirectory(destination))
  1087. {
  1088. new_destination = destination;
  1089. cmSystemTools::ConvertToUnixSlashes(new_destination);
  1090. new_destination += '/';
  1091. std::string source_name = source;
  1092. new_destination += cmSystemTools::GetFilenameName(source_name);
  1093. destination = new_destination.c_str();
  1094. }
  1095. // Create destination directory
  1096. std::string destination_dir = destination;
  1097. destination_dir = cmSystemTools::GetFilenamePath(destination_dir);
  1098. cmSystemTools::MakeDirectory(destination_dir.c_str());
  1099. // Open files
  1100. #if defined(_WIN32) || defined(__CYGWIN__)
  1101. std::ifstream fin(source,
  1102. std::ios::binary | std::ios::in);
  1103. #else
  1104. std::ifstream fin(source);
  1105. #endif
  1106. if(!fin)
  1107. {
  1108. std::string m = "CopyFile failed to open input file \"";
  1109. m += source;
  1110. m += "\"";
  1111. m += " System Error: ";
  1112. m += strerror(errno);
  1113. cmSystemTools::Error(m.c_str());
  1114. return;
  1115. }
  1116. #if defined(_WIN32) || defined(__CYGWIN__)
  1117. std::ofstream fout(destination,
  1118. std::ios::binary | std::ios::out | std::ios::trunc);
  1119. #else
  1120. std::ofstream fout(destination,
  1121. std::ios::out | std::ios::trunc);
  1122. #endif
  1123. if(!fout)
  1124. {
  1125. std::string m = "CopyFile failed to open output file \"";
  1126. m += destination;
  1127. m += "\"";
  1128. m += " System Error: ";
  1129. m += strerror(errno);
  1130. cmSystemTools::Error(m.c_str());
  1131. return;
  1132. }
  1133. // This copy loop is very sensitive on certain platforms with
  1134. // slightly broken stream libraries (like HPUX). Normally, it is
  1135. // incorrect to not check the error condition on the fin.read()
  1136. // before using the data, but the fin.gcount() will be zero if an
  1137. // error occurred. Therefore, the loop should be safe everywhere.
  1138. while(fin)
  1139. {
  1140. fin.read(buffer, bufferSize);
  1141. if(fin.gcount())
  1142. {
  1143. fout.write(buffer, fin.gcount());
  1144. }
  1145. }
  1146. // Make sure the operating system has finished writing the file
  1147. // before closing it. This will ensure the file is finished before
  1148. // the check below.
  1149. fout.flush();
  1150. fin.close();
  1151. fout.close();
  1152. // More checks
  1153. struct stat statSource, statDestination;
  1154. if (stat(source, &statSource) != 0 ||
  1155. stat(destination, &statDestination) != 0)
  1156. {
  1157. cmSystemTools::Error("CopyFile failed to copy files!");
  1158. }
  1159. else
  1160. {
  1161. if (statSource.st_size != statDestination.st_size)
  1162. {
  1163. cmOStringStream msg;
  1164. msg << "CopyFile failed to copy files (sizes differ, source: "
  1165. << statSource.st_size << " , dest: " << statDestination.st_size;
  1166. cmSystemTools::Error(msg.str().c_str());
  1167. }
  1168. }
  1169. }
  1170. // return true if the file exists
  1171. long int cmSystemTools::ModifiedTime(const char* filename)
  1172. {
  1173. struct stat fs;
  1174. if (stat(filename, &fs) != 0)
  1175. {
  1176. return 0;
  1177. }
  1178. else
  1179. {
  1180. return (long int)fs.st_mtime;
  1181. }
  1182. }
  1183. bool cmSystemTools::RemoveFile(const char* source)
  1184. {
  1185. return unlink(source) != 0 ? false : true;
  1186. }
  1187. bool cmSystemTools::IsOn(const char* val)
  1188. {
  1189. if (!val)
  1190. {
  1191. return false;
  1192. }
  1193. std::basic_string<char> v = val;
  1194. for(std::basic_string<char>::iterator c = v.begin();
  1195. c != v.end(); c++)
  1196. {
  1197. *c = toupper(*c);
  1198. }
  1199. return (v == "ON" || v == "1" || v == "YES" || v == "TRUE" || v == "Y");
  1200. }
  1201. bool cmSystemTools::IsOff(const char* val)
  1202. {
  1203. if (!val || strlen(val) == 0)
  1204. {
  1205. return true;
  1206. }
  1207. std::basic_string<char> v = val;
  1208. for(std::basic_string<char>::iterator c = v.begin();
  1209. c != v.end(); c++)
  1210. {
  1211. *c = toupper(*c);
  1212. }
  1213. return (v == "OFF" || v == "0" || v == "NO" || v == "FALSE" ||
  1214. v == "N" || v == "NOTFOUND" || v == "IGNORE");
  1215. }
  1216. bool cmSystemTools::RunCommand(const char* command,
  1217. std::string& output,
  1218. const char* dir,
  1219. bool verbose,
  1220. int timeout)
  1221. {
  1222. int dummy;
  1223. return cmSystemTools::RunCommand(command, output, dummy,
  1224. dir, verbose, timeout);
  1225. }
  1226. #if defined(WIN32) && !defined(__CYGWIN__)
  1227. #include "cmWin32ProcessExecution.h"
  1228. // use this for shell commands like echo and dir
  1229. bool RunCommandViaWin32(const char* command,
  1230. const char* dir,
  1231. std::string& output,
  1232. int& retVal,
  1233. bool verbose,
  1234. int timeout)
  1235. {
  1236. #if defined(__BORLANDC__)
  1237. return cmWin32ProcessExecution::BorlandRunCommand(command, dir, output,
  1238. retVal,
  1239. verbose, timeout,
  1240. cmSystemTools::GetRunCommandHideConsole());
  1241. #else // Visual studio
  1242. ::SetLastError(ERROR_SUCCESS);
  1243. if ( ! command )
  1244. {
  1245. cmSystemTools::Error("No command specified");
  1246. return false;
  1247. }
  1248. cmWin32ProcessExecution resProc;
  1249. if(cmSystemTools::GetRunCommandHideConsole())
  1250. {
  1251. resProc.SetHideWindows(true);
  1252. }
  1253. if ( cmSystemTools::GetWindows9xComspecSubstitute() )
  1254. {
  1255. resProc.SetConsoleSpawn(cmSystemTools::GetWindows9xComspecSubstitute() );
  1256. }
  1257. if ( !resProc.StartProcess(command, dir, verbose) )
  1258. {
  1259. std::cout << "Problem starting command" << std::endl;
  1260. return false;
  1261. }
  1262. resProc.Wait(timeout);
  1263. output = resProc.GetOutput();
  1264. retVal = resProc.GetExitValue();
  1265. return true;
  1266. #endif
  1267. }
  1268. // use this for shell commands like echo and dir
  1269. bool RunCommandViaSystem(const char* command,
  1270. const char* dir,
  1271. std::string& output,
  1272. int& retVal,
  1273. bool verbose)
  1274. {
  1275. std::cout << "@@ " << command << std::endl;
  1276. const int BUFFER_SIZE = 4096;
  1277. char buffer[BUFFER_SIZE];
  1278. std::string commandInDir;
  1279. if(dir)
  1280. {
  1281. commandInDir = "cd ";
  1282. commandInDir += cmSystemTools::ConvertToOutputPath(dir);
  1283. commandInDir += " && ";
  1284. commandInDir += command;
  1285. }
  1286. else
  1287. {
  1288. commandInDir = command;
  1289. }
  1290. command = commandInDir.c_str();
  1291. std::string commandToFile = command;
  1292. commandToFile += " > ";
  1293. std::string tempFile;
  1294. tempFile += _tempnam(0, "cmake");
  1295. commandToFile += tempFile;
  1296. retVal = system(commandToFile.c_str());
  1297. std::ifstream fin(tempFile.c_str());
  1298. if(!fin)
  1299. {
  1300. if(verbose)
  1301. {
  1302. std::string errormsg = "RunCommand produced no output: command: \"";
  1303. errormsg += command;
  1304. errormsg += "\"";
  1305. errormsg += "\nOutput file: ";
  1306. errormsg += tempFile;
  1307. cmSystemTools::Error(errormsg.c_str());
  1308. }
  1309. fin.close();
  1310. cmSystemTools::RemoveFile(tempFile.c_str());
  1311. return false;
  1312. }
  1313. bool multiLine = false;
  1314. while(fin)
  1315. {
  1316. fin.getline(buffer, BUFFER_SIZE);
  1317. output += buffer;
  1318. if(multiLine)
  1319. {
  1320. output += "\n";
  1321. }
  1322. multiLine = true;
  1323. }
  1324. fin.close();
  1325. cmSystemTools::RemoveFile(tempFile.c_str());
  1326. return true;
  1327. }
  1328. #else // We have popen
  1329. bool RunCommandViaPopen(const char* command,
  1330. const char* dir,
  1331. std::string& output,
  1332. int& retVal,
  1333. bool verbose,
  1334. int /*timeout*/)
  1335. {
  1336. // if only popen worked on windows.....
  1337. std::string commandInDir;
  1338. if(dir)
  1339. {
  1340. commandInDir = "cd \"";
  1341. commandInDir += dir;
  1342. commandInDir += "\" && ";
  1343. commandInDir += command;
  1344. }
  1345. else
  1346. {
  1347. commandInDir = command;
  1348. }
  1349. commandInDir += " 2>&1";
  1350. command = commandInDir.c_str();
  1351. const int BUFFER_SIZE = 4096;
  1352. char buffer[BUFFER_SIZE];
  1353. if(verbose)
  1354. {
  1355. std::cout << "running " << command << std::endl;
  1356. }
  1357. fflush(stdout);
  1358. fflush(stderr);
  1359. FILE* cpipe = popen(command, "r");
  1360. if(!cpipe)
  1361. {
  1362. return false;
  1363. }
  1364. fgets(buffer, BUFFER_SIZE, cpipe);
  1365. while(!feof(cpipe))
  1366. {
  1367. if(verbose)
  1368. {
  1369. std::cout << buffer << std::flush;
  1370. }
  1371. output += buffer;
  1372. fgets(buffer, BUFFER_SIZE, cpipe);
  1373. }
  1374. retVal = pclose(cpipe);
  1375. if (WIFEXITED(retVal))
  1376. {
  1377. retVal = WEXITSTATUS(retVal);
  1378. return true;
  1379. }
  1380. if (WIFSIGNALED(retVal))
  1381. {
  1382. retVal = WTERMSIG(retVal);
  1383. cmOStringStream error;
  1384. error << "\nProcess terminated due to ";
  1385. switch (retVal)
  1386. {
  1387. #ifdef SIGKILL
  1388. case SIGKILL:
  1389. error << "SIGKILL";
  1390. break;
  1391. #endif
  1392. #ifdef SIGFPE
  1393. case SIGFPE:
  1394. error << "SIGFPE";
  1395. break;
  1396. #endif
  1397. #ifdef SIGBUS
  1398. case SIGBUS:
  1399. error << "SIGBUS";
  1400. break;
  1401. #endif
  1402. #ifdef SIGSEGV
  1403. case SIGSEGV:
  1404. error << "SIGSEGV";
  1405. break;
  1406. #endif
  1407. default:
  1408. error << "signal " << retVal;
  1409. break;
  1410. }
  1411. output += error.str();
  1412. }
  1413. return false;
  1414. }
  1415. #endif // endif WIN32 not CYGWIN
  1416. // run a command unix uses popen (easy)
  1417. // windows uses system and ShortPath
  1418. bool cmSystemTools::RunCommand(const char* command,
  1419. std::string& output,
  1420. int &retVal,
  1421. const char* dir,
  1422. bool verbose,
  1423. int timeout)
  1424. {
  1425. if(s_DisableRunCommandOutput)
  1426. {
  1427. verbose = false;
  1428. }
  1429. #if defined(WIN32) && !defined(__CYGWIN__)
  1430. // if the command does not start with a quote, then
  1431. // try to find the program, and if the program can not be
  1432. // found use system to run the command as it must be a built in
  1433. // shell command like echo or dir
  1434. int count = 0;
  1435. if(command[0] == '\"')
  1436. {
  1437. // count the number of quotes
  1438. for(const char* s = command; *s != 0; ++s)
  1439. {
  1440. if(*s == '\"')
  1441. {
  1442. count++;
  1443. if(count > 2)
  1444. {
  1445. break;
  1446. }
  1447. }
  1448. }
  1449. // if there are more than two double quotes use
  1450. // GetShortPathName, the cmd.exe program in windows which
  1451. // is used by system fails to execute if there are more than
  1452. // one set of quotes in the arguments
  1453. if(count > 2)
  1454. {
  1455. cmRegularExpression quoted("^\"([^\"]*)\"[ \t](.*)");
  1456. if(quoted.find(command))
  1457. {
  1458. std::string shortCmd;
  1459. std::string cmd = quoted.match(1);
  1460. std::string args = quoted.match(2);
  1461. if(! cmSystemTools::FileExists(cmd.c_str()) )
  1462. {
  1463. shortCmd = cmd;
  1464. }
  1465. else if(!cmSystemTools::GetShortPath(cmd.c_str(), shortCmd))
  1466. {
  1467. cmSystemTools::Error("GetShortPath failed for " , cmd.c_str());
  1468. return false;
  1469. }
  1470. shortCmd += " ";
  1471. shortCmd += args;
  1472. //return RunCommandViaSystem(shortCmd.c_str(), dir,
  1473. // output, retVal, verbose);
  1474. //return WindowsRunCommand(shortCmd.c_str(), dir,
  1475. //output, retVal, verbose);
  1476. return RunCommandViaWin32(shortCmd.c_str(), dir,
  1477. output, retVal, verbose, timeout);
  1478. }
  1479. else
  1480. {
  1481. cmSystemTools::Error("Could not parse command line with quotes ",
  1482. command);
  1483. }
  1484. }
  1485. }
  1486. // if there is only one set of quotes or no quotes then just run the command
  1487. //return RunCommandViaSystem(command, dir, output, retVal, verbose);
  1488. //return WindowsRunCommand(command, dir, output, retVal, verbose);
  1489. return ::RunCommandViaWin32(command, dir, output, retVal, verbose, timeout);
  1490. #else
  1491. return ::RunCommandViaPopen(command, dir, output, retVal, verbose, timeout);
  1492. #endif
  1493. }
  1494. /**
  1495. * Find the file the given name. Searches the given path and then
  1496. * the system search path. Returns the full path to the file if it is
  1497. * found. Otherwise, the empty string is returned.
  1498. */
  1499. std::string cmSystemTools::FindFile(const char* name,
  1500. const std::vector<std::string>& userPaths)
  1501. {
  1502. // Add the system search path to our path.
  1503. std::vector<std::string> path = userPaths;
  1504. cmSystemTools::GetPath(path);
  1505. std::string tryPath;
  1506. for(std::vector<std::string>::const_iterator p = path.begin();
  1507. p != path.end(); ++p)
  1508. {
  1509. tryPath = *p;
  1510. tryPath += "/";
  1511. tryPath += name;
  1512. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1513. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1514. {
  1515. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1516. }
  1517. }
  1518. // Couldn't find the file.
  1519. return "";
  1520. }
  1521. /**
  1522. * Find the executable with the given name. Searches the given path and then
  1523. * the system search path. Returns the full path to the executable if it is
  1524. * found. Otherwise, the empty string is returned.
  1525. */
  1526. std::string cmSystemTools::FindProgram(const char* name,
  1527. const std::vector<std::string>& userPaths,
  1528. bool no_system_path)
  1529. {
  1530. // See if the executable exists as written.
  1531. if(cmSystemTools::FileExists(name) &&
  1532. !cmSystemTools::FileIsDirectory(name))
  1533. {
  1534. return cmSystemTools::CollapseFullPath(name);
  1535. }
  1536. std::string tryPath = name;
  1537. tryPath += cmSystemTools::GetExecutableExtension();
  1538. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1539. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1540. {
  1541. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1542. }
  1543. // Add the system search path to our path.
  1544. std::vector<std::string> path = userPaths;
  1545. if (!no_system_path)
  1546. {
  1547. cmSystemTools::GetPath(path);
  1548. }
  1549. for(std::vector<std::string>::const_iterator p = path.begin();
  1550. p != path.end(); ++p)
  1551. {
  1552. tryPath = *p;
  1553. tryPath += "/";
  1554. tryPath += name;
  1555. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1556. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1557. {
  1558. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1559. }
  1560. #ifdef _WIN32
  1561. tryPath += ".com";
  1562. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1563. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1564. {
  1565. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1566. }
  1567. tryPath = *p;
  1568. tryPath += "/";
  1569. tryPath += name;
  1570. #endif
  1571. tryPath += cmSystemTools::GetExecutableExtension();
  1572. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1573. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1574. {
  1575. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1576. }
  1577. }
  1578. // Couldn't find the program.
  1579. return "";
  1580. }
  1581. /**
  1582. * Find the library with the given name. Searches the given path and then
  1583. * the system search path. Returns the full path to the library if it is
  1584. * found. Otherwise, the empty string is returned.
  1585. */
  1586. std::string cmSystemTools::FindLibrary(const char* name,
  1587. const std::vector<std::string>& userPaths)
  1588. {
  1589. // See if the executable exists as written.
  1590. if(cmSystemTools::FileExists(name))
  1591. {
  1592. return cmSystemTools::CollapseFullPath(name);
  1593. }
  1594. // Add the system search path to our path.
  1595. std::vector<std::string> path = userPaths;
  1596. cmSystemTools::GetPath(path);
  1597. std::string tryPath;
  1598. for(std::vector<std::string>::const_iterator p = path.begin();
  1599. p != path.end(); ++p)
  1600. {
  1601. #if defined(_WIN32) && !defined(__CYGWIN__)
  1602. tryPath = *p;
  1603. tryPath += "/";
  1604. tryPath += name;
  1605. tryPath += ".lib";
  1606. if(cmSystemTools::FileExists(tryPath.c_str()))
  1607. {
  1608. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1609. }
  1610. #else
  1611. tryPath = *p;
  1612. tryPath += "/lib";
  1613. tryPath += name;
  1614. tryPath += ".so";
  1615. if(cmSystemTools::FileExists(tryPath.c_str()))
  1616. {
  1617. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1618. }
  1619. tryPath = *p;
  1620. tryPath += "/lib";
  1621. tryPath += name;
  1622. tryPath += ".a";
  1623. if(cmSystemTools::FileExists(tryPath.c_str()))
  1624. {
  1625. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1626. }
  1627. tryPath = *p;
  1628. tryPath += "/lib";
  1629. tryPath += name;
  1630. tryPath += ".sl";
  1631. if(cmSystemTools::FileExists(tryPath.c_str()))
  1632. {
  1633. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1634. }
  1635. tryPath = *p;
  1636. tryPath += "/lib";
  1637. tryPath += name;
  1638. tryPath += ".dylib";
  1639. if(cmSystemTools::FileExists(tryPath.c_str()))
  1640. {
  1641. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1642. }
  1643. #endif
  1644. }
  1645. // Couldn't find the library.
  1646. return "";
  1647. }
  1648. bool cmSystemTools::FileIsDirectory(const char* name)
  1649. {
  1650. struct stat fs;
  1651. if(stat(name, &fs) == 0)
  1652. {
  1653. #if _WIN32
  1654. return ((fs.st_mode & _S_IFDIR) != 0);
  1655. #else
  1656. return S_ISDIR(fs.st_mode);
  1657. #endif
  1658. }
  1659. else
  1660. {
  1661. return false;
  1662. }
  1663. }
  1664. int cmSystemTools::ChangeDirectory(const char *dir)
  1665. {
  1666. return Chdir(dir);
  1667. }
  1668. std::string cmSystemTools::GetCurrentWorkingDirectory()
  1669. {
  1670. char buf[2048];
  1671. std::string path = Getcwd(buf, 2048);
  1672. return path;
  1673. }
  1674. /**
  1675. * Given the path to a program executable, get the directory part of the path with the
  1676. * file stripped off. If there is no directory part, the empty string is returned.
  1677. */
  1678. std::string cmSystemTools::GetProgramPath(const char* in_name)
  1679. {
  1680. std::string dir, file;
  1681. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1682. return dir;
  1683. }
  1684. /**
  1685. * Given the path to a program executable, get the directory part of the path
  1686. * with the file stripped off. If there is no directory part, the empty
  1687. * string is returned.
  1688. */
  1689. void cmSystemTools::SplitProgramPath(const char* in_name,
  1690. std::string& dir,
  1691. std::string& file)
  1692. {
  1693. dir = in_name;
  1694. file = "";
  1695. cmSystemTools::ConvertToUnixSlashes(dir);
  1696. if(!cmSystemTools::FileIsDirectory(dir.c_str()))
  1697. {
  1698. std::string::size_type slashPos = dir.rfind("/");
  1699. if(slashPos != std::string::npos)
  1700. {
  1701. file = dir.substr(slashPos+1);
  1702. dir = dir.substr(0, slashPos);
  1703. }
  1704. else
  1705. {
  1706. file = dir;
  1707. dir = "";
  1708. }
  1709. }
  1710. if((dir != "") && !cmSystemTools::FileIsDirectory(dir.c_str()))
  1711. {
  1712. std::string oldDir = in_name;
  1713. cmSystemTools::ConvertToUnixSlashes(oldDir);
  1714. cmSystemTools::Error("Error splitting file name off end of path:\n",
  1715. oldDir.c_str(), "\nDirectory not found: ",
  1716. dir.c_str());
  1717. dir = in_name;
  1718. return;
  1719. }
  1720. }
  1721. /**
  1722. * Given a path to a file or directory, convert it to a full path.
  1723. * This collapses away relative paths. The full path is returned.
  1724. */
  1725. std::string cmSystemTools::CollapseFullPath(const char* in_name)
  1726. {
  1727. std::string dir, file;
  1728. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1729. #ifdef _WIN32
  1730. // Ultra-hack warning:
  1731. // This changes to the target directory, saves the working directory,
  1732. // and then changes back to the original working directory.
  1733. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1734. if(dir != "") { Chdir(dir.c_str()); }
  1735. std::string newDir = cmSystemTools::GetCurrentWorkingDirectory();
  1736. Chdir(cwd.c_str());
  1737. cmSystemTools::ConvertToUnixSlashes(newDir);
  1738. std::string newPath = newDir+"/"+file;
  1739. return newPath;
  1740. #else
  1741. # ifdef MAXPATHLEN
  1742. char resolved_name[MAXPATHLEN];
  1743. # else
  1744. # ifdef PATH_MAX
  1745. char resolved_name[PATH_MAX];
  1746. # else
  1747. char resolved_name[5024];
  1748. # endif
  1749. # endif
  1750. if(dir != "")
  1751. {
  1752. realpath(dir.c_str(), resolved_name);
  1753. dir = resolved_name;
  1754. }
  1755. else
  1756. {
  1757. dir = cmSystemTools::GetCurrentWorkingDirectory();
  1758. }
  1759. if(file == "")
  1760. {
  1761. return dir;
  1762. }
  1763. return dir + "/" + file;
  1764. #endif
  1765. }
  1766. bool cmSystemTools::Split(const char* str, std::vector<cmStdString>& lines)
  1767. {
  1768. std::string data(str);
  1769. std::string::size_type lpos = 0;
  1770. while(lpos < data.length())
  1771. {
  1772. std::string::size_type rpos = data.find_first_of("\n", lpos);
  1773. if(rpos == std::string::npos)
  1774. {
  1775. // Line ends at end of string without a newline.
  1776. lines.push_back(data.substr(lpos));
  1777. return false;
  1778. }
  1779. if((rpos > lpos) && (data[rpos-1] == '\r'))
  1780. {
  1781. // Line ends in a "\r\n" pair, remove both characters.
  1782. lines.push_back(data.substr(lpos, (rpos-1)-lpos));
  1783. }
  1784. else
  1785. {
  1786. // Line ends in a "\n", remove the character.
  1787. lines.push_back(data.substr(lpos, rpos-lpos));
  1788. }
  1789. lpos = rpos+1;
  1790. }
  1791. return true;
  1792. }
  1793. /**
  1794. * Return path of a full filename (no trailing slashes).
  1795. * Warning: returned path is converted to Unix slashes format.
  1796. */
  1797. std::string cmSystemTools::GetFilenamePath(const std::string& filename)
  1798. {
  1799. std::string fn = filename;
  1800. cmSystemTools::ConvertToUnixSlashes(fn);
  1801. std::string::size_type slash_pos = fn.rfind("/");
  1802. if(slash_pos != std::string::npos)
  1803. {
  1804. return fn.substr(0, slash_pos);
  1805. }
  1806. else
  1807. {
  1808. return "";
  1809. }
  1810. }
  1811. /**
  1812. * Return file name of a full filename (i.e. file name without path).
  1813. */
  1814. std::string cmSystemTools::GetFilenameName(const std::string& filename)
  1815. {
  1816. std::string fn = filename;
  1817. cmSystemTools::ConvertToUnixSlashes(fn);
  1818. std::string::size_type slash_pos = fn.rfind("/");
  1819. if(slash_pos != std::string::npos)
  1820. {
  1821. return fn.substr(slash_pos + 1);
  1822. }
  1823. else
  1824. {
  1825. return filename;
  1826. }
  1827. }
  1828. /**
  1829. * Return file extension of a full filename (dot included).
  1830. * Warning: this is the longest extension (for example: .tar.gz)
  1831. */
  1832. std::string cmSystemTools::GetFilenameExtension(const std::string& filename)
  1833. {
  1834. std::string name = cmSystemTools::GetFilenameName(filename);
  1835. std::string::size_type dot_pos = name.find(".");
  1836. if(dot_pos != std::string::npos)
  1837. {
  1838. return name.substr(dot_pos);
  1839. }
  1840. else
  1841. {
  1842. return "";
  1843. }
  1844. }
  1845. /**
  1846. * Return file name without extension of a full filename (i.e. without path).
  1847. * Warning: it considers the longest extension (for example: .tar.gz)
  1848. */
  1849. std::string cmSystemTools::GetFilenameWithoutExtension(const std::string& filename)
  1850. {
  1851. std::string name = cmSystemTools::GetFilenameName(filename);
  1852. std::string::size_type dot_pos = name.find(".");
  1853. if(dot_pos != std::string::npos)
  1854. {
  1855. return name.substr(0, dot_pos);
  1856. }
  1857. else
  1858. {
  1859. return name;
  1860. }
  1861. }
  1862. /**
  1863. * Return file name without extension of a full filename (i.e. without path).
  1864. * Warning: it considers the last extension (for example: removes .gz
  1865. * from .tar.gz)
  1866. */
  1867. std::string
  1868. cmSystemTools::GetFilenameWithoutLastExtension(const std::string& filename)
  1869. {
  1870. std::string name = cmSystemTools::GetFilenameName(filename);
  1871. std::string::size_type dot_pos = name.rfind(".");
  1872. if(dot_pos != std::string::npos)
  1873. {
  1874. return name.substr(0, dot_pos);
  1875. }
  1876. else
  1877. {
  1878. return name;
  1879. }
  1880. }
  1881. bool cmSystemTools::FileIsFullPath(const char* in_name)
  1882. {
  1883. std::string name = in_name;
  1884. #if defined(_WIN32)
  1885. // On Windows, the name must be at least two characters long.
  1886. if(name.length() < 2)
  1887. {
  1888. return false;
  1889. }
  1890. if(name[1] == ':')
  1891. {
  1892. return true;
  1893. }
  1894. if(name[0] == '\\')
  1895. {
  1896. return true;
  1897. }
  1898. #else
  1899. // On UNIX, the name must be at least one character long.
  1900. if(name.length() < 1)
  1901. {
  1902. return false;
  1903. }
  1904. #endif
  1905. // On UNIX, the name must begin in a '/'.
  1906. // On Windows, if the name begins in a '/', then it is a full
  1907. // network path.
  1908. if(name[0] == '/')
  1909. {
  1910. return true;
  1911. }
  1912. return false;
  1913. }
  1914. void cmSystemTools::Glob(const char *directory, const char *regexp,
  1915. std::vector<std::string>& files)
  1916. {
  1917. cmDirectory d;
  1918. cmRegularExpression reg(regexp);
  1919. if (d.Load(directory))
  1920. {
  1921. size_t numf;
  1922. unsigned int i;
  1923. numf = d.GetNumberOfFiles();
  1924. for (i = 0; i < numf; i++)
  1925. {
  1926. std::string fname = d.GetFile(i);
  1927. if (reg.find(fname))
  1928. {
  1929. files.push_back(fname);
  1930. }
  1931. }
  1932. }
  1933. }
  1934. void cmSystemTools::GlobDirs(const char *fullPath,
  1935. std::vector<std::string>& files)
  1936. {
  1937. std::string path = fullPath;
  1938. std::string::size_type pos = path.find("/*");
  1939. if(pos == std::string::npos)
  1940. {
  1941. files.push_back(fullPath);
  1942. return;
  1943. }
  1944. std::string startPath = path.substr(0, pos);
  1945. std::string finishPath = path.substr(pos+2);
  1946. cmDirectory d;
  1947. if (d.Load(startPath.c_str()))
  1948. {
  1949. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  1950. {
  1951. if((std::string(d.GetFile(i)) != ".")
  1952. && (std::string(d.GetFile(i)) != ".."))
  1953. {
  1954. std::string fname = startPath;
  1955. fname +="/";
  1956. fname += d.GetFile(i);
  1957. if(cmSystemTools::FileIsDirectory(fname.c_str()))
  1958. {
  1959. fname += finishPath;
  1960. cmSystemTools::GlobDirs(fname.c_str(), files);
  1961. }
  1962. }
  1963. }
  1964. }
  1965. }
  1966. void cmSystemTools::ExpandListArguments(std::vector<std::string> const& arguments,
  1967. std::vector<std::string>& newargs)
  1968. {
  1969. std::vector<std::string>::const_iterator i;
  1970. std::string newarg;
  1971. for(i = arguments.begin();i != arguments.end(); ++i)
  1972. {
  1973. // if there are no ; in the name then just copy the current string
  1974. if(i->find(';') == std::string::npos)
  1975. {
  1976. newargs.push_back(*i);
  1977. }
  1978. else
  1979. {
  1980. std::string::size_type start = 0;
  1981. std::string::size_type endpos = 0;
  1982. const std::string::size_type size = i->size();
  1983. // break up ; separated sections of the string into separate strings
  1984. while(endpos != size)
  1985. {
  1986. endpos = i->find(';', start);
  1987. if(endpos == std::string::npos)
  1988. {
  1989. endpos = i->size();
  1990. }
  1991. else
  1992. {
  1993. // skip right over escaped ; ( \; )
  1994. while((endpos != std::string::npos)
  1995. && (endpos > 0)
  1996. && ((*i)[endpos-1] == '\\') )
  1997. {
  1998. endpos = i->find(';', endpos+1);
  1999. }
  2000. if(endpos == std::string::npos)
  2001. {
  2002. endpos = i->size();
  2003. }
  2004. }
  2005. std::string::size_type len = endpos - start;
  2006. if (len > 0)
  2007. {
  2008. // check for a closing ] after the start position
  2009. if(i->find('[', start) == std::string::npos)
  2010. {
  2011. // if there is no [ in the string then keep it
  2012. newarg = i->substr(start, len);
  2013. }
  2014. else
  2015. {
  2016. int opencount = 0;
  2017. int closecount = 0;
  2018. for(std::string::size_type j = start; j < endpos; ++j)
  2019. {
  2020. if(i->at(j) == '[')
  2021. {
  2022. ++opencount;
  2023. }
  2024. else if (i->at(j) == ']')
  2025. {
  2026. ++closecount;
  2027. }
  2028. }
  2029. if(opencount != closecount)
  2030. {
  2031. // skip this one
  2032. endpos = i->find(';', endpos+1);
  2033. if(endpos == std::string::npos)
  2034. {
  2035. endpos = i->size();
  2036. }
  2037. len = endpos - start;
  2038. }
  2039. newarg = i->substr(start, len);
  2040. }
  2041. std::string::size_type pos = newarg.find("\\;");
  2042. if(pos != std::string::npos)
  2043. {
  2044. newarg.erase(pos, 1);
  2045. }
  2046. newargs.push_back(newarg);
  2047. }
  2048. start = endpos+1;
  2049. }
  2050. }
  2051. }
  2052. }
  2053. bool cmSystemTools::GetShortPath(const char* path, std::string& shortPath)
  2054. {
  2055. #if defined(WIN32) && !defined(__CYGWIN__)
  2056. const int size = int(strlen(path)) +1; // size of return
  2057. char *buffer = new char[size]; // create a buffer
  2058. char *tempPath = new char[size]; // create a buffer
  2059. int ret;
  2060. // if the path passed in has quotes around it, first remove the quotes
  2061. if (path[0] == '"' && path[strlen(path)-1] == '"')
  2062. {
  2063. strcpy(tempPath,path+1);
  2064. tempPath[strlen(tempPath)-1] = '\0';
  2065. }
  2066. else
  2067. {
  2068. strcpy(tempPath,path);
  2069. }
  2070. buffer[0] = 0;
  2071. ret = GetShortPathName(tempPath, buffer, size);
  2072. if(buffer[0] == 0 || ret > size)
  2073. {
  2074. if(ret < size)
  2075. {
  2076. LPVOID lpMsgBuf;
  2077. FormatMessage(
  2078. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  2079. FORMAT_MESSAGE_FROM_SYSTEM |
  2080. FORMAT_MESSAGE_IGNORE_INSERTS,
  2081. NULL,
  2082. GetLastError(),
  2083. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  2084. (LPTSTR) &lpMsgBuf,
  2085. 0,
  2086. NULL
  2087. );
  2088. cmSystemTools::Error((LPCTSTR)lpMsgBuf);
  2089. LocalFree( lpMsgBuf );
  2090. }
  2091. cmSystemTools::Error("Unable to get a short path: ", path);
  2092. delete [] tempPath;
  2093. return false;
  2094. }
  2095. else
  2096. {
  2097. shortPath = buffer;
  2098. delete [] buffer;
  2099. delete [] tempPath;
  2100. return true;
  2101. }
  2102. #else
  2103. shortPath = path;
  2104. return true;
  2105. #endif
  2106. }
  2107. bool cmSystemTools::SimpleGlob(const std::string& glob,
  2108. std::vector<std::string>& files,
  2109. int type /* = 0 */)
  2110. {
  2111. files.clear();
  2112. if ( glob[glob.size()-1] != '*' )
  2113. {
  2114. return false;
  2115. }
  2116. std::string path = cmSystemTools::GetFilenamePath(glob);
  2117. std::string ppath = cmSystemTools::GetFilenameName(glob);
  2118. ppath = ppath.substr(0, ppath.size()-1);
  2119. if ( path.size() == 0 )
  2120. {
  2121. path = "/";
  2122. }
  2123. bool res = false;
  2124. cmDirectory d;
  2125. if (d.Load(path.c_str()))
  2126. {
  2127. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  2128. {
  2129. if((std::string(d.GetFile(i)) != ".")
  2130. && (std::string(d.GetFile(i)) != ".."))
  2131. {
  2132. std::string fname = path;
  2133. if ( path[path.size()-1] != '/' )
  2134. {
  2135. fname +="/";
  2136. }
  2137. fname += d.GetFile(i);
  2138. std::string sfname = d.GetFile(i);
  2139. if ( type > 0 && cmSystemTools::FileIsDirectory(fname.c_str()) )
  2140. {
  2141. continue;
  2142. }
  2143. if ( type < 0 && !cmSystemTools::FileIsDirectory(fname.c_str()) )
  2144. {
  2145. continue;
  2146. }
  2147. if ( sfname.size() >= ppath.size() &&
  2148. sfname.substr(0, ppath.size()) ==
  2149. ppath )
  2150. {
  2151. files.push_back(fname);
  2152. res = true;
  2153. }
  2154. }
  2155. }
  2156. }
  2157. return res;
  2158. }
  2159. cmSystemTools::FileFormat cmSystemTools::GetFileFormat(const char* cext)
  2160. {
  2161. if ( ! cext || *cext == 0 )
  2162. {
  2163. return cmSystemTools::NO_FILE_FORMAT;
  2164. }
  2165. std::string ext = cmSystemTools::LowerCase(cext);
  2166. if ( ext == "c" || ext == ".c" ) { return cmSystemTools::C_FILE_FORMAT; }
  2167. if ( ext == "cxx" || ext == ".cxx" ||
  2168. ext == "cpp" || ext == ".cpp" ||
  2169. ext == "c++" || ext == ".c++" ||
  2170. ext == "mm" || ext == ".mm" ||
  2171. ext == "cc" || ext == ".cc" ) { return cmSystemTools::CXX_FILE_FORMAT; }
  2172. if ( ext == "java" || ext == ".java" ) { return cmSystemTools::JAVA_FILE_FORMAT; }
  2173. if ( ext == "h" || ext == ".h" ||
  2174. ext == "hpp" || ext == ".hpp" ||
  2175. ext == "h++" || ext == ".h++" ||
  2176. ext == "hxx" || ext == ".hxx" ) { return cmSystemTools::HEADER_FILE_FORMAT; }
  2177. if ( ext == "rc" || ext == ".rc" ) { return cmSystemTools::RESOURCE_FILE_FORMAT; }
  2178. if ( ext == "def" || ext == ".def" ) { return cmSystemTools::DEFINITION_FILE_FORMAT; }
  2179. if ( ext == "lib" || ext == ".lib" ||
  2180. ext == "a" || ext == ".a") { return cmSystemTools::STATIC_LIBRARY_FILE_FORMAT; }
  2181. if ( ext == "o" || ext == ".o" ||
  2182. ext == "obj" || ext == ".obj") { return cmSystemTools::OBJECT_FILE_FORMAT; }
  2183. #ifdef __APPLE__
  2184. if ( ext == "dylib" || ext == ".dylib" )
  2185. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  2186. if ( ext == "so" || ext == ".so" ||
  2187. ext == "bundle" || ext == ".bundle" )
  2188. { return cmSystemTools::MODULE_FILE_FORMAT; }
  2189. #else // __APPLE__
  2190. if ( ext == "so" || ext == ".so" ||
  2191. ext == "sl" || ext == ".sl" ||
  2192. ext == "dll" || ext == ".dll" )
  2193. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  2194. #endif // __APPLE__
  2195. return cmSystemTools::UNKNOWN_FILE_FORMAT;
  2196. }
  2197. void cmSystemTools::SplitProgramFromArgs(const char* path,
  2198. std::string& program, std::string& args)
  2199. {
  2200. if(cmSystemTools::FileExists(path))
  2201. {
  2202. program = path;
  2203. args = "";
  2204. return;
  2205. }
  2206. std::vector<std::string> e;
  2207. std::string findProg = cmSystemTools::FindProgram(path, e);
  2208. if(findProg.size())
  2209. {
  2210. program = findProg;
  2211. args = "";
  2212. return;
  2213. }
  2214. std::string dir = path;
  2215. std::string::size_type spacePos = dir.rfind(' ');
  2216. if(spacePos == std::string::npos)
  2217. {
  2218. program = "";
  2219. args = "";
  2220. return;
  2221. }
  2222. while(spacePos != std::string::npos)
  2223. {
  2224. std::string tryProg = dir.substr(0, spacePos);
  2225. if(cmSystemTools::FileExists(tryProg.c_str()))
  2226. {
  2227. program = tryProg;
  2228. args = dir.substr(spacePos, dir.size()-spacePos);
  2229. return;
  2230. }
  2231. findProg = cmSystemTools::FindProgram(tryProg.c_str(), e);
  2232. if(findProg.size())
  2233. {
  2234. program = findProg;
  2235. args = dir.substr(spacePos, dir.size()-spacePos);
  2236. return;
  2237. }
  2238. spacePos = dir.rfind(' ', spacePos--);
  2239. }
  2240. program = "";
  2241. args = "";
  2242. }
  2243. #if defined(_MSC_VER) && defined(_DEBUG)
  2244. # include <crtdbg.h>
  2245. # include <stdio.h>
  2246. # include <stdlib.h>
  2247. static int cmSystemToolsDebugReport(int, char* message, int*)
  2248. {
  2249. fprintf(stderr, message);
  2250. exit(1);
  2251. return 0;
  2252. }
  2253. void cmSystemTools::EnableMSVCDebugHook()
  2254. {
  2255. if(getenv("DART_TEST_FROM_DART"))
  2256. {
  2257. _CrtSetReportHook(cmSystemToolsDebugReport);
  2258. }
  2259. }
  2260. #else
  2261. void cmSystemTools::EnableMSVCDebugHook()
  2262. {
  2263. }
  2264. #endif