cmSystemTools.cxx 63 KB

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