cmSystemTools.cxx 60 KB

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