PageRenderTime 61ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/cmake-2.8.9-rc2/Source/kwsys/SystemTools.cxx

#
C++ | 4856 lines | 4615 code | 106 blank | 135 comment | 245 complexity | 6fe2fe033c87c70c5c039e3d0ea59b61 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.0, Apache-2.0

Large files files are truncated, but you can click here to view the full file

  1. /*============================================================================
  2. KWSys - Kitware System Library
  3. Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
  4. Distributed under the OSI-approved BSD License (the "License");
  5. see accompanying file Copyright.txt for details.
  6. This software is distributed WITHOUT ANY WARRANTY; without even the
  7. implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  8. See the License for more information.
  9. ============================================================================*/
  10. #ifdef __osf__
  11. # define _OSF_SOURCE
  12. # define _POSIX_C_SOURCE 199506L
  13. # define _XOPEN_SOURCE_EXTENDED
  14. #endif
  15. #include "kwsysPrivate.h"
  16. #include KWSYS_HEADER(RegularExpression.hxx)
  17. #include KWSYS_HEADER(SystemTools.hxx)
  18. #include KWSYS_HEADER(Directory.hxx)
  19. #include KWSYS_HEADER(ios/iostream)
  20. #include KWSYS_HEADER(ios/fstream)
  21. #include KWSYS_HEADER(ios/sstream)
  22. #include KWSYS_HEADER(stl/set)
  23. // Work-around CMake dependency scanning limitation. This must
  24. // duplicate the above list of headers.
  25. #if 0
  26. # include "SystemTools.hxx.in"
  27. # include "Directory.hxx.in"
  28. # include "kwsys_ios_iostream.h.in"
  29. # include "kwsys_ios_fstream.h.in"
  30. # include "kwsys_ios_sstream.h.in"
  31. #endif
  32. #ifdef _MSC_VER
  33. # pragma warning (disable: 4786)
  34. #endif
  35. #if defined(__sgi) && !defined(__GNUC__)
  36. # pragma set woff 1375 /* base class destructor not virtual */
  37. #endif
  38. #include <ctype.h>
  39. #include <errno.h>
  40. #ifdef __QNX__
  41. # include <malloc.h> /* for malloc/free on QNX */
  42. #endif
  43. #include <stdio.h>
  44. #include <stdlib.h>
  45. #include <string.h>
  46. #include <sys/stat.h>
  47. #include <time.h>
  48. // support for realpath call
  49. #ifndef _WIN32
  50. #include <sys/time.h>
  51. #include <utime.h>
  52. #include <limits.h>
  53. #include <sys/wait.h>
  54. #include <sys/ioctl.h>
  55. #include <unistd.h>
  56. #include <pwd.h>
  57. #ifndef __VMS
  58. #include <sys/param.h>
  59. #include <termios.h>
  60. #endif
  61. #include <signal.h> /* sigprocmask */
  62. #endif
  63. // Windows API.
  64. #if defined(_WIN32)
  65. # include <windows.h>
  66. #elif defined (__CYGWIN__)
  67. # include <windows.h>
  68. # undef _WIN32
  69. #endif
  70. #if !KWSYS_CXX_HAS_ENVIRON_IN_STDLIB_H
  71. extern char **environ;
  72. #endif
  73. #ifdef __CYGWIN__
  74. extern "C" void cygwin_conv_to_win32_path(const char *path, char *win32_path);
  75. #endif
  76. // getpwnam doesn't exist on Windows and Cray Xt3/Catamount
  77. // same for TIOCGWINSZ
  78. #if defined(_WIN32) || defined (__LIBCATAMOUNT__)
  79. # undef HAVE_GETPWNAM
  80. # undef HAVE_TTY_INFO
  81. #else
  82. # define HAVE_GETPWNAM 1
  83. # define HAVE_TTY_INFO 1
  84. #endif
  85. #define VTK_URL_PROTOCOL_REGEX "([a-zA-Z0-9]*)://(.*)"
  86. #define VTK_URL_REGEX "([a-zA-Z0-9]*)://(([A-Za-z0-9]+)(:([^:@]+))?@)?([^:@/]+)(:([0-9]+))?/(.+)?"
  87. #ifdef _MSC_VER
  88. #include <sys/utime.h>
  89. #else
  90. #include <utime.h>
  91. #endif
  92. // This is a hack to prevent warnings about these functions being
  93. // declared but not referenced.
  94. #if defined(__sgi) && !defined(__GNUC__)
  95. # include <sys/termios.h>
  96. namespace KWSYS_NAMESPACE
  97. {
  98. class SystemToolsHack
  99. {
  100. public:
  101. enum
  102. {
  103. Ref1 = sizeof(cfgetospeed(0)),
  104. Ref2 = sizeof(cfgetispeed(0)),
  105. Ref3 = sizeof(tcgetattr(0, 0)),
  106. Ref4 = sizeof(tcsetattr(0, 0, 0)),
  107. Ref5 = sizeof(cfsetospeed(0,0)),
  108. Ref6 = sizeof(cfsetispeed(0,0))
  109. };
  110. };
  111. }
  112. #endif
  113. #if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) ||defined(__BORLANDC__) || defined(__MINGW32__))
  114. #include <io.h>
  115. #include <direct.h>
  116. #define _unlink unlink
  117. #endif
  118. /* The maximum length of a file name. */
  119. #if defined(PATH_MAX)
  120. # define KWSYS_SYSTEMTOOLS_MAXPATH PATH_MAX
  121. #elif defined(MAXPATHLEN)
  122. # define KWSYS_SYSTEMTOOLS_MAXPATH MAXPATHLEN
  123. #else
  124. # define KWSYS_SYSTEMTOOLS_MAXPATH 16384
  125. #endif
  126. #if defined(__WATCOMC__)
  127. #include <direct.h>
  128. #define _mkdir mkdir
  129. #define _rmdir rmdir
  130. #define _getcwd getcwd
  131. #define _chdir chdir
  132. #endif
  133. #if defined(__HAIKU__)
  134. #include <os/kernel/OS.h>
  135. #include <os/storage/Path.h>
  136. #endif
  137. #if defined(__BEOS__) && !defined(__ZETA__) && !defined(__HAIKU__)
  138. #include <be/kernel/OS.h>
  139. #include <be/storage/Path.h>
  140. // BeOS 5 doesn't have usleep(), but it has snooze(), which is identical.
  141. static inline void usleep(unsigned int msec)
  142. {
  143. ::snooze(msec);
  144. }
  145. // BeOS 5 also doesn't have realpath(), but its C++ API offers something close.
  146. static inline char *realpath(const char *path, char *resolved_path)
  147. {
  148. const size_t maxlen = KWSYS_SYSTEMTOOLS_MAXPATH;
  149. snprintf(resolved_path, maxlen, "%s", path);
  150. BPath normalized(resolved_path, NULL, true);
  151. const char *resolved = normalized.Path();
  152. if (resolved != NULL) // NULL == No such file.
  153. {
  154. if (snprintf(resolved_path, maxlen, "%s", resolved) < maxlen)
  155. {
  156. return resolved_path;
  157. }
  158. }
  159. return NULL; // something went wrong.
  160. }
  161. #endif
  162. #if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__BORLANDC__) || defined(__MINGW32__))
  163. inline int Mkdir(const char* dir)
  164. {
  165. return _mkdir(dir);
  166. }
  167. inline int Rmdir(const char* dir)
  168. {
  169. return _rmdir(dir);
  170. }
  171. inline const char* Getcwd(char* buf, unsigned int len)
  172. {
  173. const char* ret = _getcwd(buf, len);
  174. if(!ret)
  175. {
  176. fprintf(stderr, "No current working directory.\n");
  177. abort();
  178. }
  179. // make sure the drive letter is capital
  180. if(strlen(buf) > 1 && buf[1] == ':')
  181. {
  182. buf[0] = toupper(buf[0]);
  183. }
  184. return ret;
  185. }
  186. inline int Chdir(const char* dir)
  187. {
  188. #if defined(__BORLANDC__)
  189. return chdir(dir);
  190. #else
  191. return _chdir(dir);
  192. #endif
  193. }
  194. inline void Realpath(const char *path, kwsys_stl::string & resolved_path)
  195. {
  196. char *ptemp;
  197. char fullpath[MAX_PATH];
  198. if( GetFullPathName(path, sizeof(fullpath), fullpath, &ptemp) )
  199. {
  200. resolved_path = fullpath;
  201. KWSYS_NAMESPACE::SystemTools::ConvertToUnixSlashes(resolved_path);
  202. }
  203. else
  204. {
  205. resolved_path = path;
  206. }
  207. }
  208. #else
  209. #include <sys/types.h>
  210. #include <fcntl.h>
  211. #include <unistd.h>
  212. inline int Mkdir(const char* dir)
  213. {
  214. return mkdir(dir, 00777);
  215. }
  216. inline int Rmdir(const char* dir)
  217. {
  218. return rmdir(dir);
  219. }
  220. inline const char* Getcwd(char* buf, unsigned int len)
  221. {
  222. const char* ret = getcwd(buf, len);
  223. if(!ret)
  224. {
  225. fprintf(stderr, "No current working directory\n");
  226. abort();
  227. }
  228. return ret;
  229. }
  230. inline int Chdir(const char* dir)
  231. {
  232. return chdir(dir);
  233. }
  234. inline void Realpath(const char *path, kwsys_stl::string & resolved_path)
  235. {
  236. char resolved_name[KWSYS_SYSTEMTOOLS_MAXPATH];
  237. char *ret = realpath(path, resolved_name);
  238. if(ret)
  239. {
  240. resolved_path = ret;
  241. }
  242. else
  243. {
  244. // if path resolution fails, return what was passed in
  245. resolved_path = path;
  246. }
  247. }
  248. #endif
  249. #if !defined(_WIN32) && defined(__COMO__)
  250. // Hack for como strict mode to avoid defining _SVID_SOURCE or _BSD_SOURCE.
  251. extern "C"
  252. {
  253. extern FILE *popen (__const char *__command, __const char *__modes) __THROW;
  254. extern int pclose (FILE *__stream) __THROW;
  255. extern char *realpath (__const char *__restrict __name,
  256. char *__restrict __resolved) __THROW;
  257. extern char *strdup (__const char *__s) __THROW;
  258. extern int putenv (char *__string) __THROW;
  259. }
  260. #endif
  261. namespace KWSYS_NAMESPACE
  262. {
  263. double SystemTools::GetTime(void)
  264. {
  265. #if defined(_WIN32) && !defined(__CYGWIN__)
  266. FILETIME ft;
  267. GetSystemTimeAsFileTime(&ft);
  268. return (429.4967296*ft.dwHighDateTime
  269. + 0.0000001*ft.dwLowDateTime
  270. - 11644473600.0);
  271. #else
  272. struct timeval t;
  273. gettimeofday(&t, 0);
  274. return 1.0*double(t.tv_sec) + 0.000001*double(t.tv_usec);
  275. #endif
  276. }
  277. class SystemToolsTranslationMap :
  278. public kwsys_stl::map<kwsys_stl::string,kwsys_stl::string>
  279. {
  280. };
  281. // adds the elements of the env variable path to the arg passed in
  282. void SystemTools::GetPath(kwsys_stl::vector<kwsys_stl::string>& path, const char* env)
  283. {
  284. #if defined(_WIN32) && !defined(__CYGWIN__)
  285. const char* pathSep = ";";
  286. #else
  287. const char* pathSep = ":";
  288. #endif
  289. if(!env)
  290. {
  291. env = "PATH";
  292. }
  293. const char* cpathEnv = SystemTools::GetEnv(env);
  294. if ( !cpathEnv )
  295. {
  296. return;
  297. }
  298. kwsys_stl::string pathEnv = cpathEnv;
  299. // A hack to make the below algorithm work.
  300. if(!pathEnv.empty() && pathEnv[pathEnv.length()-1] != pathSep[0])
  301. {
  302. pathEnv += pathSep;
  303. }
  304. kwsys_stl::string::size_type start =0;
  305. bool done = false;
  306. while(!done)
  307. {
  308. kwsys_stl::string::size_type endpos = pathEnv.find(pathSep, start);
  309. if(endpos != kwsys_stl::string::npos)
  310. {
  311. path.push_back(pathEnv.substr(start, endpos-start));
  312. start = endpos+1;
  313. }
  314. else
  315. {
  316. done = true;
  317. }
  318. }
  319. for(kwsys_stl::vector<kwsys_stl::string>::iterator i = path.begin();
  320. i != path.end(); ++i)
  321. {
  322. SystemTools::ConvertToUnixSlashes(*i);
  323. }
  324. }
  325. const char* SystemTools::GetEnv(const char* key)
  326. {
  327. return getenv(key);
  328. }
  329. bool SystemTools::GetEnv(const char* key, kwsys_stl::string& result)
  330. {
  331. const char* v = getenv(key);
  332. if(v)
  333. {
  334. result = v;
  335. return true;
  336. }
  337. else
  338. {
  339. return false;
  340. }
  341. }
  342. //----------------------------------------------------------------------------
  343. #if defined(__CYGWIN__) || defined(__GLIBC__)
  344. # define KWSYS_PUTENV_NAME /* putenv("A") removes A. */
  345. #elif defined(_WIN32)
  346. # define KWSYS_PUTENV_EMPTY /* putenv("A=") removes A. */
  347. #endif
  348. #if KWSYS_CXX_HAS_UNSETENV
  349. /* unsetenv("A") removes A from the environment.
  350. On older platforms it returns void instead of int. */
  351. static int kwsysUnPutEnv(const char* env)
  352. {
  353. if(const char* eq = strchr(env, '='))
  354. {
  355. std::string name(env, eq-env);
  356. unsetenv(name.c_str());
  357. }
  358. else
  359. {
  360. unsetenv(env);
  361. }
  362. return 0;
  363. }
  364. #elif defined(KWSYS_PUTENV_EMPTY) || defined(KWSYS_PUTENV_NAME)
  365. /* putenv("A=") or putenv("A") removes A from the environment. */
  366. static int kwsysUnPutEnv(const char* env)
  367. {
  368. int err = 0;
  369. const char* eq = strchr(env, '=');
  370. size_t const len = eq? (size_t)(eq-env) : strlen(env);
  371. # ifdef KWSYS_PUTENV_EMPTY
  372. size_t const sz = len + 2;
  373. # else
  374. size_t const sz = len + 1;
  375. # endif
  376. char local_buf[256];
  377. char* buf = sz > sizeof(local_buf) ? (char*)malloc(sz) : local_buf;
  378. if(!buf)
  379. {
  380. return -1;
  381. }
  382. strncpy(buf, env, len);
  383. # ifdef KWSYS_PUTENV_EMPTY
  384. buf[len] = '=';
  385. buf[len+1] = 0;
  386. if(putenv(buf) < 0)
  387. {
  388. err = errno;
  389. }
  390. # else
  391. buf[len] = 0;
  392. if(putenv(buf) < 0 && errno != EINVAL)
  393. {
  394. err = errno;
  395. }
  396. # endif
  397. if(buf != local_buf)
  398. {
  399. free(buf);
  400. }
  401. if(err)
  402. {
  403. errno = err;
  404. return -1;
  405. }
  406. return 0;
  407. }
  408. #else
  409. /* Manipulate the "environ" global directly. */
  410. static int kwsysUnPutEnv(const char* env)
  411. {
  412. const char* eq = strchr(env, '=');
  413. size_t const len = eq? (size_t)(eq-env) : strlen(env);
  414. int in = 0;
  415. int out = 0;
  416. while(environ[in])
  417. {
  418. if(strlen(environ[in]) > len &&
  419. environ[in][len] == '=' &&
  420. strncmp(env, environ[in], len) == 0)
  421. {
  422. ++in;
  423. }
  424. else
  425. {
  426. environ[out++] = environ[in++];
  427. }
  428. }
  429. while(out < in)
  430. {
  431. environ[out++] = 0;
  432. }
  433. return 0;
  434. }
  435. #endif
  436. //----------------------------------------------------------------------------
  437. #if KWSYS_CXX_HAS_SETENV
  438. /* setenv("A", "B", 1) will set A=B in the environment and makes its
  439. own copies of the strings. */
  440. bool SystemTools::PutEnv(const char* env)
  441. {
  442. if(const char* eq = strchr(env, '='))
  443. {
  444. std::string name(env, eq-env);
  445. return setenv(name.c_str(), eq+1, 1) == 0;
  446. }
  447. else
  448. {
  449. return kwsysUnPutEnv(env) == 0;
  450. }
  451. }
  452. bool SystemTools::UnPutEnv(const char* env)
  453. {
  454. return kwsysUnPutEnv(env) == 0;
  455. }
  456. #else
  457. /* putenv("A=B") will set A=B in the environment. Most putenv implementations
  458. put their argument directly in the environment. They never free the memory
  459. on program exit. Keep an active set of pointers to memory we allocate and
  460. pass to putenv, one per environment key. At program exit remove any
  461. environment values that may still reference memory we allocated. Then free
  462. the memory. This will not affect any environment values we never set. */
  463. # ifdef __INTEL_COMPILER
  464. # pragma warning disable 444 /* base has non-virtual destructor */
  465. # endif
  466. /* Order by environment key only (VAR from VAR=VALUE). */
  467. struct kwsysEnvCompare
  468. {
  469. bool operator() (const char* l, const char* r) const
  470. {
  471. const char* leq = strchr(l, '=');
  472. const char* req = strchr(r, '=');
  473. size_t llen = leq? (leq-l) : strlen(l);
  474. size_t rlen = req? (req-r) : strlen(r);
  475. if(llen == rlen)
  476. {
  477. return strncmp(l,r,llen) < 0;
  478. }
  479. else
  480. {
  481. return strcmp(l,r) < 0;
  482. }
  483. }
  484. };
  485. class kwsysEnv: public kwsys_stl::set<const char*, kwsysEnvCompare>
  486. {
  487. class Free
  488. {
  489. const char* Env;
  490. public:
  491. Free(const char* env): Env(env) {}
  492. ~Free() { free(const_cast<char*>(this->Env)); }
  493. };
  494. public:
  495. typedef kwsys_stl::set<const char*, kwsysEnvCompare> derived;
  496. ~kwsysEnv()
  497. {
  498. for(derived::iterator i = this->begin(); i != this->end(); ++i)
  499. {
  500. kwsysUnPutEnv(*i);
  501. free(const_cast<char*>(*i));
  502. }
  503. }
  504. const char* Release(const char* env)
  505. {
  506. const char* old = 0;
  507. derived::iterator i = this->find(env);
  508. if(i != this->end())
  509. {
  510. old = *i;
  511. this->erase(i);
  512. }
  513. return old;
  514. }
  515. bool Put(const char* env)
  516. {
  517. Free oldEnv(this->Release(env));
  518. static_cast<void>(oldEnv);
  519. char* newEnv = strdup(env);
  520. this->insert(newEnv);
  521. return putenv(newEnv) == 0;
  522. }
  523. bool UnPut(const char* env)
  524. {
  525. Free oldEnv(this->Release(env));
  526. static_cast<void>(oldEnv);
  527. return kwsysUnPutEnv(env) == 0;
  528. }
  529. };
  530. static kwsysEnv kwsysEnvInstance;
  531. bool SystemTools::PutEnv(const char* env)
  532. {
  533. return kwsysEnvInstance.Put(env);
  534. }
  535. bool SystemTools::UnPutEnv(const char* env)
  536. {
  537. return kwsysEnvInstance.UnPut(env);
  538. }
  539. #endif
  540. //----------------------------------------------------------------------------
  541. const char* SystemTools::GetExecutableExtension()
  542. {
  543. #if defined(_WIN32) || defined(__CYGWIN__) || defined(__VMS)
  544. return ".exe";
  545. #else
  546. return "";
  547. #endif
  548. }
  549. bool SystemTools::MakeDirectory(const char* path)
  550. {
  551. if(!path)
  552. {
  553. return false;
  554. }
  555. if(SystemTools::FileExists(path))
  556. {
  557. return true;
  558. }
  559. kwsys_stl::string dir = path;
  560. if(dir.size() == 0)
  561. {
  562. return false;
  563. }
  564. SystemTools::ConvertToUnixSlashes(dir);
  565. kwsys_stl::string::size_type pos = dir.find(':');
  566. if(pos == kwsys_stl::string::npos)
  567. {
  568. pos = 0;
  569. }
  570. kwsys_stl::string topdir;
  571. while((pos = dir.find('/', pos)) != kwsys_stl::string::npos)
  572. {
  573. topdir = dir.substr(0, pos);
  574. Mkdir(topdir.c_str());
  575. pos++;
  576. }
  577. if(dir[dir.size()-1] == '/')
  578. {
  579. topdir = dir.substr(0, dir.size());
  580. }
  581. else
  582. {
  583. topdir = dir;
  584. }
  585. if(Mkdir(topdir.c_str()) != 0)
  586. {
  587. // There is a bug in the Borland Run time library which makes MKDIR
  588. // return EACCES when it should return EEXISTS
  589. // if it is some other error besides directory exists
  590. // then return false
  591. if( (errno != EEXIST)
  592. #ifdef __BORLANDC__
  593. && (errno != EACCES)
  594. #endif
  595. )
  596. {
  597. return false;
  598. }
  599. }
  600. return true;
  601. }
  602. // replace replace with with as many times as it shows up in source.
  603. // write the result into source.
  604. void SystemTools::ReplaceString(kwsys_stl::string& source,
  605. const char* replace,
  606. const char* with)
  607. {
  608. const char *src = source.c_str();
  609. char *searchPos = const_cast<char *>(strstr(src,replace));
  610. // get out quick if string is not found
  611. if (!searchPos)
  612. {
  613. return;
  614. }
  615. // perform replacements until done
  616. size_t replaceSize = strlen(replace);
  617. // do while hangs if replaceSize is 0
  618. if(replaceSize == 0)
  619. {
  620. return;
  621. }
  622. char *orig = strdup(src);
  623. char *currentPos = orig;
  624. searchPos = searchPos - src + orig;
  625. // initialize the result
  626. source.erase(source.begin(),source.end());
  627. do
  628. {
  629. *searchPos = '\0';
  630. source += currentPos;
  631. currentPos = searchPos + replaceSize;
  632. // replace
  633. source += with;
  634. searchPos = strstr(currentPos,replace);
  635. }
  636. while (searchPos);
  637. // copy any trailing text
  638. source += currentPos;
  639. free(orig);
  640. }
  641. #if defined(KEY_WOW64_32KEY) && defined(KEY_WOW64_64KEY)
  642. # define KWSYS_ST_KEY_WOW64_32KEY KEY_WOW64_32KEY
  643. # define KWSYS_ST_KEY_WOW64_64KEY KEY_WOW64_64KEY
  644. #else
  645. # define KWSYS_ST_KEY_WOW64_32KEY 0x0200
  646. # define KWSYS_ST_KEY_WOW64_64KEY 0x0100
  647. #endif
  648. #if defined(_WIN32) && !defined(__CYGWIN__)
  649. static DWORD SystemToolsMakeRegistryMode(DWORD mode,
  650. SystemTools::KeyWOW64 view)
  651. {
  652. // only add the modes when on a system that supports Wow64.
  653. static FARPROC wow64p = GetProcAddress(GetModuleHandle("kernel32"),
  654. "IsWow64Process");
  655. if(wow64p == NULL)
  656. {
  657. return mode;
  658. }
  659. if(view == SystemTools::KeyWOW64_32)
  660. {
  661. return mode | KWSYS_ST_KEY_WOW64_32KEY;
  662. }
  663. else if(view == SystemTools::KeyWOW64_64)
  664. {
  665. return mode | KWSYS_ST_KEY_WOW64_64KEY;
  666. }
  667. return mode;
  668. }
  669. #endif
  670. // Read a registry value.
  671. // Example :
  672. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  673. // => will return the data of the "default" value of the key
  674. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  675. // => will return the data of the "Root" value of the key
  676. #if defined(_WIN32) && !defined(__CYGWIN__)
  677. bool SystemTools::ReadRegistryValue(const char *key, kwsys_stl::string &value,
  678. KeyWOW64 view)
  679. {
  680. bool valueset = false;
  681. kwsys_stl::string primary = key;
  682. kwsys_stl::string second;
  683. kwsys_stl::string valuename;
  684. size_t start = primary.find("\\");
  685. if (start == kwsys_stl::string::npos)
  686. {
  687. return false;
  688. }
  689. size_t valuenamepos = primary.find(";");
  690. if (valuenamepos != kwsys_stl::string::npos)
  691. {
  692. valuename = primary.substr(valuenamepos+1);
  693. }
  694. second = primary.substr(start+1, valuenamepos-start-1);
  695. primary = primary.substr(0, start);
  696. HKEY primaryKey = HKEY_CURRENT_USER;
  697. if (primary == "HKEY_CURRENT_USER")
  698. {
  699. primaryKey = HKEY_CURRENT_USER;
  700. }
  701. if (primary == "HKEY_CURRENT_CONFIG")
  702. {
  703. primaryKey = HKEY_CURRENT_CONFIG;
  704. }
  705. if (primary == "HKEY_CLASSES_ROOT")
  706. {
  707. primaryKey = HKEY_CLASSES_ROOT;
  708. }
  709. if (primary == "HKEY_LOCAL_MACHINE")
  710. {
  711. primaryKey = HKEY_LOCAL_MACHINE;
  712. }
  713. if (primary == "HKEY_USERS")
  714. {
  715. primaryKey = HKEY_USERS;
  716. }
  717. HKEY hKey;
  718. if(RegOpenKeyEx(primaryKey,
  719. second.c_str(),
  720. 0,
  721. SystemToolsMakeRegistryMode(KEY_READ, view),
  722. &hKey) != ERROR_SUCCESS)
  723. {
  724. return false;
  725. }
  726. else
  727. {
  728. DWORD dwType, dwSize;
  729. dwSize = 1023;
  730. char data[1024];
  731. if(RegQueryValueEx(hKey,
  732. (LPTSTR)valuename.c_str(),
  733. NULL,
  734. &dwType,
  735. (BYTE *)data,
  736. &dwSize) == ERROR_SUCCESS)
  737. {
  738. if (dwType == REG_SZ)
  739. {
  740. value = data;
  741. valueset = true;
  742. }
  743. else if (dwType == REG_EXPAND_SZ)
  744. {
  745. char expanded[1024];
  746. DWORD dwExpandedSize = sizeof(expanded)/sizeof(expanded[0]);
  747. if(ExpandEnvironmentStrings(data, expanded, dwExpandedSize))
  748. {
  749. value = expanded;
  750. valueset = true;
  751. }
  752. }
  753. }
  754. RegCloseKey(hKey);
  755. }
  756. return valueset;
  757. }
  758. #else
  759. bool SystemTools::ReadRegistryValue(const char *, kwsys_stl::string &,
  760. KeyWOW64)
  761. {
  762. return false;
  763. }
  764. #endif
  765. // Write a registry value.
  766. // Example :
  767. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  768. // => will set the data of the "default" value of the key
  769. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  770. // => will set the data of the "Root" value of the key
  771. #if defined(_WIN32) && !defined(__CYGWIN__)
  772. bool SystemTools::WriteRegistryValue(const char *key, const char *value,
  773. KeyWOW64 view)
  774. {
  775. kwsys_stl::string primary = key;
  776. kwsys_stl::string second;
  777. kwsys_stl::string valuename;
  778. size_t start = primary.find("\\");
  779. if (start == kwsys_stl::string::npos)
  780. {
  781. return false;
  782. }
  783. size_t valuenamepos = primary.find(";");
  784. if (valuenamepos != kwsys_stl::string::npos)
  785. {
  786. valuename = primary.substr(valuenamepos+1);
  787. }
  788. second = primary.substr(start+1, valuenamepos-start-1);
  789. primary = primary.substr(0, start);
  790. HKEY primaryKey = HKEY_CURRENT_USER;
  791. if (primary == "HKEY_CURRENT_USER")
  792. {
  793. primaryKey = HKEY_CURRENT_USER;
  794. }
  795. if (primary == "HKEY_CURRENT_CONFIG")
  796. {
  797. primaryKey = HKEY_CURRENT_CONFIG;
  798. }
  799. if (primary == "HKEY_CLASSES_ROOT")
  800. {
  801. primaryKey = HKEY_CLASSES_ROOT;
  802. }
  803. if (primary == "HKEY_LOCAL_MACHINE")
  804. {
  805. primaryKey = HKEY_LOCAL_MACHINE;
  806. }
  807. if (primary == "HKEY_USERS")
  808. {
  809. primaryKey = HKEY_USERS;
  810. }
  811. HKEY hKey;
  812. DWORD dwDummy;
  813. char lpClass[] = "";
  814. if(RegCreateKeyEx(primaryKey,
  815. second.c_str(),
  816. 0,
  817. lpClass,
  818. REG_OPTION_NON_VOLATILE,
  819. SystemToolsMakeRegistryMode(KEY_WRITE, view),
  820. NULL,
  821. &hKey,
  822. &dwDummy) != ERROR_SUCCESS)
  823. {
  824. return false;
  825. }
  826. if(RegSetValueEx(hKey,
  827. (LPTSTR)valuename.c_str(),
  828. 0,
  829. REG_SZ,
  830. (CONST BYTE *)value,
  831. (DWORD)(strlen(value) + 1)) == ERROR_SUCCESS)
  832. {
  833. return true;
  834. }
  835. return false;
  836. }
  837. #else
  838. bool SystemTools::WriteRegistryValue(const char *, const char *, KeyWOW64)
  839. {
  840. return false;
  841. }
  842. #endif
  843. // Delete a registry value.
  844. // Example :
  845. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  846. // => will delete the data of the "default" value of the key
  847. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  848. // => will delete the data of the "Root" value of the key
  849. #if defined(_WIN32) && !defined(__CYGWIN__)
  850. bool SystemTools::DeleteRegistryValue(const char *key, KeyWOW64 view)
  851. {
  852. kwsys_stl::string primary = key;
  853. kwsys_stl::string second;
  854. kwsys_stl::string valuename;
  855. size_t start = primary.find("\\");
  856. if (start == kwsys_stl::string::npos)
  857. {
  858. return false;
  859. }
  860. size_t valuenamepos = primary.find(";");
  861. if (valuenamepos != kwsys_stl::string::npos)
  862. {
  863. valuename = primary.substr(valuenamepos+1);
  864. }
  865. second = primary.substr(start+1, valuenamepos-start-1);
  866. primary = primary.substr(0, start);
  867. HKEY primaryKey = HKEY_CURRENT_USER;
  868. if (primary == "HKEY_CURRENT_USER")
  869. {
  870. primaryKey = HKEY_CURRENT_USER;
  871. }
  872. if (primary == "HKEY_CURRENT_CONFIG")
  873. {
  874. primaryKey = HKEY_CURRENT_CONFIG;
  875. }
  876. if (primary == "HKEY_CLASSES_ROOT")
  877. {
  878. primaryKey = HKEY_CLASSES_ROOT;
  879. }
  880. if (primary == "HKEY_LOCAL_MACHINE")
  881. {
  882. primaryKey = HKEY_LOCAL_MACHINE;
  883. }
  884. if (primary == "HKEY_USERS")
  885. {
  886. primaryKey = HKEY_USERS;
  887. }
  888. HKEY hKey;
  889. if(RegOpenKeyEx(primaryKey,
  890. second.c_str(),
  891. 0,
  892. SystemToolsMakeRegistryMode(KEY_WRITE, view),
  893. &hKey) != ERROR_SUCCESS)
  894. {
  895. return false;
  896. }
  897. else
  898. {
  899. if(RegDeleteValue(hKey,
  900. (LPTSTR)valuename.c_str()) == ERROR_SUCCESS)
  901. {
  902. RegCloseKey(hKey);
  903. return true;
  904. }
  905. }
  906. return false;
  907. }
  908. #else
  909. bool SystemTools::DeleteRegistryValue(const char *, KeyWOW64)
  910. {
  911. return false;
  912. }
  913. #endif
  914. bool SystemTools::SameFile(const char* file1, const char* file2)
  915. {
  916. #ifdef _WIN32
  917. HANDLE hFile1, hFile2;
  918. hFile1 = CreateFile( file1,
  919. GENERIC_READ,
  920. FILE_SHARE_READ ,
  921. NULL,
  922. OPEN_EXISTING,
  923. FILE_FLAG_BACKUP_SEMANTICS,
  924. NULL
  925. );
  926. hFile2 = CreateFile( file2,
  927. GENERIC_READ,
  928. FILE_SHARE_READ,
  929. NULL,
  930. OPEN_EXISTING,
  931. FILE_FLAG_BACKUP_SEMANTICS,
  932. NULL
  933. );
  934. if( hFile1 == INVALID_HANDLE_VALUE || hFile2 == INVALID_HANDLE_VALUE)
  935. {
  936. if(hFile1 != INVALID_HANDLE_VALUE)
  937. {
  938. CloseHandle(hFile1);
  939. }
  940. if(hFile2 != INVALID_HANDLE_VALUE)
  941. {
  942. CloseHandle(hFile2);
  943. }
  944. return false;
  945. }
  946. BY_HANDLE_FILE_INFORMATION fiBuf1;
  947. BY_HANDLE_FILE_INFORMATION fiBuf2;
  948. GetFileInformationByHandle( hFile1, &fiBuf1 );
  949. GetFileInformationByHandle( hFile2, &fiBuf2 );
  950. CloseHandle(hFile1);
  951. CloseHandle(hFile2);
  952. return (fiBuf1.dwVolumeSerialNumber == fiBuf2.dwVolumeSerialNumber &&
  953. fiBuf1.nFileIndexHigh == fiBuf2.nFileIndexHigh &&
  954. fiBuf1.nFileIndexLow == fiBuf2.nFileIndexLow);
  955. #else
  956. struct stat fileStat1, fileStat2;
  957. if (stat(file1, &fileStat1) == 0 && stat(file2, &fileStat2) == 0)
  958. {
  959. // see if the files are the same file
  960. // check the device inode and size
  961. if(memcmp(&fileStat2.st_dev, &fileStat1.st_dev, sizeof(fileStat1.st_dev)) == 0 &&
  962. memcmp(&fileStat2.st_ino, &fileStat1.st_ino, sizeof(fileStat1.st_ino)) == 0 &&
  963. fileStat2.st_size == fileStat1.st_size
  964. )
  965. {
  966. return true;
  967. }
  968. }
  969. return false;
  970. #endif
  971. }
  972. //----------------------------------------------------------------------------
  973. #if defined(_WIN32) || defined(__CYGWIN__)
  974. static bool WindowsFileExists(const char* filename)
  975. {
  976. WIN32_FILE_ATTRIBUTE_DATA fd;
  977. return GetFileAttributesExA(filename, GetFileExInfoStandard, &fd) != 0;
  978. }
  979. #endif
  980. //----------------------------------------------------------------------------
  981. bool SystemTools::FileExists(const char* filename)
  982. {
  983. if(!(filename && *filename))
  984. {
  985. return false;
  986. }
  987. #if defined(__CYGWIN__)
  988. // Convert filename to native windows path if possible.
  989. char winpath[MAX_PATH];
  990. if(SystemTools::PathCygwinToWin32(filename, winpath))
  991. {
  992. return WindowsFileExists(winpath);
  993. }
  994. return access(filename, R_OK) == 0;
  995. #elif defined(_WIN32)
  996. return WindowsFileExists(filename);
  997. #else
  998. return access(filename, R_OK) == 0;
  999. #endif
  1000. }
  1001. //----------------------------------------------------------------------------
  1002. bool SystemTools::FileExists(const char* filename, bool isFile)
  1003. {
  1004. if(SystemTools::FileExists(filename))
  1005. {
  1006. // If isFile is set return not FileIsDirectory,
  1007. // so this will only be true if it is a file
  1008. return !isFile || !SystemTools::FileIsDirectory(filename);
  1009. }
  1010. return false;
  1011. }
  1012. //----------------------------------------------------------------------------
  1013. #ifdef __CYGWIN__
  1014. bool SystemTools::PathCygwinToWin32(const char *path, char *win32_path)
  1015. {
  1016. SystemToolsTranslationMap::iterator i =
  1017. SystemTools::Cyg2Win32Map->find(path);
  1018. if (i != SystemTools::Cyg2Win32Map->end())
  1019. {
  1020. strncpy(win32_path, i->second.c_str(), MAX_PATH);
  1021. }
  1022. else
  1023. {
  1024. cygwin_conv_to_win32_path(path, win32_path);
  1025. SystemToolsTranslationMap::value_type entry(path, win32_path);
  1026. SystemTools::Cyg2Win32Map->insert(entry);
  1027. }
  1028. return win32_path[0] != 0;
  1029. }
  1030. #endif
  1031. bool SystemTools::Touch(const char* filename, bool create)
  1032. {
  1033. if(create && !SystemTools::FileExists(filename))
  1034. {
  1035. FILE* file = fopen(filename, "a+b");
  1036. if(file)
  1037. {
  1038. fclose(file);
  1039. return true;
  1040. }
  1041. return false;
  1042. }
  1043. #ifdef _MSC_VER
  1044. #define utime _utime
  1045. #define utimbuf _utimbuf
  1046. #endif
  1047. struct stat fromStat;
  1048. if(stat(filename, &fromStat) < 0)
  1049. {
  1050. return false;
  1051. }
  1052. struct utimbuf buf;
  1053. buf.actime = fromStat.st_atime;
  1054. buf.modtime = static_cast<time_t>(SystemTools::GetTime());
  1055. if(utime(filename, &buf) < 0)
  1056. {
  1057. return false;
  1058. }
  1059. return true;
  1060. }
  1061. bool SystemTools::FileTimeCompare(const char* f1, const char* f2,
  1062. int* result)
  1063. {
  1064. // Default to same time.
  1065. *result = 0;
  1066. #if !defined(_WIN32) || defined(__CYGWIN__)
  1067. // POSIX version. Use stat function to get file modification time.
  1068. struct stat s1;
  1069. if(stat(f1, &s1) != 0)
  1070. {
  1071. return false;
  1072. }
  1073. struct stat s2;
  1074. if(stat(f2, &s2) != 0)
  1075. {
  1076. return false;
  1077. }
  1078. # if KWSYS_STAT_HAS_ST_MTIM
  1079. // Compare using nanosecond resolution.
  1080. if(s1.st_mtim.tv_sec < s2.st_mtim.tv_sec)
  1081. {
  1082. *result = -1;
  1083. }
  1084. else if(s1.st_mtim.tv_sec > s2.st_mtim.tv_sec)
  1085. {
  1086. *result = 1;
  1087. }
  1088. else if(s1.st_mtim.tv_nsec < s2.st_mtim.tv_nsec)
  1089. {
  1090. *result = -1;
  1091. }
  1092. else if(s1.st_mtim.tv_nsec > s2.st_mtim.tv_nsec)
  1093. {
  1094. *result = 1;
  1095. }
  1096. # else
  1097. // Compare using 1 second resolution.
  1098. if(s1.st_mtime < s2.st_mtime)
  1099. {
  1100. *result = -1;
  1101. }
  1102. else if(s1.st_mtime > s2.st_mtime)
  1103. {
  1104. *result = 1;
  1105. }
  1106. # endif
  1107. #else
  1108. // Windows version. Get the modification time from extended file attributes.
  1109. WIN32_FILE_ATTRIBUTE_DATA f1d;
  1110. WIN32_FILE_ATTRIBUTE_DATA f2d;
  1111. if(!GetFileAttributesEx(f1, GetFileExInfoStandard, &f1d))
  1112. {
  1113. return false;
  1114. }
  1115. if(!GetFileAttributesEx(f2, GetFileExInfoStandard, &f2d))
  1116. {
  1117. return false;
  1118. }
  1119. // Compare the file times using resolution provided by system call.
  1120. *result = (int)CompareFileTime(&f1d.ftLastWriteTime, &f2d.ftLastWriteTime);
  1121. #endif
  1122. return true;
  1123. }
  1124. // Return a capitalized string (i.e the first letter is uppercased, all other
  1125. // are lowercased)
  1126. kwsys_stl::string SystemTools::Capitalized(const kwsys_stl::string& s)
  1127. {
  1128. kwsys_stl::string n;
  1129. if(s.size() == 0)
  1130. {
  1131. return n;
  1132. }
  1133. n.resize(s.size());
  1134. n[0] = static_cast<kwsys_stl::string::value_type>(toupper(s[0]));
  1135. for (size_t i = 1; i < s.size(); i++)
  1136. {
  1137. n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
  1138. }
  1139. return n;
  1140. }
  1141. // Return capitalized words
  1142. kwsys_stl::string SystemTools::CapitalizedWords(const kwsys_stl::string& s)
  1143. {
  1144. kwsys_stl::string n(s);
  1145. for (size_t i = 0; i < s.size(); i++)
  1146. {
  1147. #if defined(_MSC_VER) && defined (_MT) && defined (_DEBUG)
  1148. // MS has an assert that will fail if s[i] < 0; setting
  1149. // LC_CTYPE using setlocale() does *not* help. Painful.
  1150. if ((int)s[i] >= 0 && isalpha(s[i]) &&
  1151. (i == 0 || ((int)s[i - 1] >= 0 && isspace(s[i - 1]))))
  1152. #else
  1153. if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
  1154. #endif
  1155. {
  1156. n[i] = static_cast<kwsys_stl::string::value_type>(toupper(s[i]));
  1157. }
  1158. }
  1159. return n;
  1160. }
  1161. // Return uncapitalized words
  1162. kwsys_stl::string SystemTools::UnCapitalizedWords(const kwsys_stl::string& s)
  1163. {
  1164. kwsys_stl::string n(s);
  1165. for (size_t i = 0; i < s.size(); i++)
  1166. {
  1167. #if defined(_MSC_VER) && defined (_MT) && defined (_DEBUG)
  1168. // MS has an assert that will fail if s[i] < 0; setting
  1169. // LC_CTYPE using setlocale() does *not* help. Painful.
  1170. if ((int)s[i] >= 0 && isalpha(s[i]) &&
  1171. (i == 0 || ((int)s[i - 1] >= 0 && isspace(s[i - 1]))))
  1172. #else
  1173. if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
  1174. #endif
  1175. {
  1176. n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
  1177. }
  1178. }
  1179. return n;
  1180. }
  1181. // only works for words with at least two letters
  1182. kwsys_stl::string SystemTools::AddSpaceBetweenCapitalizedWords(
  1183. const kwsys_stl::string& s)
  1184. {
  1185. kwsys_stl::string n;
  1186. if (s.size())
  1187. {
  1188. n.reserve(s.size());
  1189. n += s[0];
  1190. for (size_t i = 1; i < s.size(); i++)
  1191. {
  1192. if (isupper(s[i]) && !isspace(s[i - 1]) && !isupper(s[i - 1]))
  1193. {
  1194. n += ' ';
  1195. }
  1196. n += s[i];
  1197. }
  1198. }
  1199. return n;
  1200. }
  1201. char* SystemTools::AppendStrings(const char* str1, const char* str2)
  1202. {
  1203. if (!str1)
  1204. {
  1205. return SystemTools::DuplicateString(str2);
  1206. }
  1207. if (!str2)
  1208. {
  1209. return SystemTools::DuplicateString(str1);
  1210. }
  1211. size_t len1 = strlen(str1);
  1212. char *newstr = new char[len1 + strlen(str2) + 1];
  1213. if (!newstr)
  1214. {
  1215. return 0;
  1216. }
  1217. strcpy(newstr, str1);
  1218. strcat(newstr + len1, str2);
  1219. return newstr;
  1220. }
  1221. char* SystemTools::AppendStrings(
  1222. const char* str1, const char* str2, const char* str3)
  1223. {
  1224. if (!str1)
  1225. {
  1226. return SystemTools::AppendStrings(str2, str3);
  1227. }
  1228. if (!str2)
  1229. {
  1230. return SystemTools::AppendStrings(str1, str3);
  1231. }
  1232. if (!str3)
  1233. {
  1234. return SystemTools::AppendStrings(str1, str2);
  1235. }
  1236. size_t len1 = strlen(str1), len2 = strlen(str2);
  1237. char *newstr = new char[len1 + len2 + strlen(str3) + 1];
  1238. if (!newstr)
  1239. {
  1240. return 0;
  1241. }
  1242. strcpy(newstr, str1);
  1243. strcat(newstr + len1, str2);
  1244. strcat(newstr + len1 + len2, str3);
  1245. return newstr;
  1246. }
  1247. // Return a lower case string
  1248. kwsys_stl::string SystemTools::LowerCase(const kwsys_stl::string& s)
  1249. {
  1250. kwsys_stl::string n;
  1251. n.resize(s.size());
  1252. for (size_t i = 0; i < s.size(); i++)
  1253. {
  1254. n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
  1255. }
  1256. return n;
  1257. }
  1258. // Return a lower case string
  1259. kwsys_stl::string SystemTools::UpperCase(const kwsys_stl::string& s)
  1260. {
  1261. kwsys_stl::string n;
  1262. n.resize(s.size());
  1263. for (size_t i = 0; i < s.size(); i++)
  1264. {
  1265. n[i] = static_cast<kwsys_stl::string::value_type>(toupper(s[i]));
  1266. }
  1267. return n;
  1268. }
  1269. // Count char in string
  1270. size_t SystemTools::CountChar(const char* str, char c)
  1271. {
  1272. size_t count = 0;
  1273. if (str)
  1274. {
  1275. while (*str)
  1276. {
  1277. if (*str == c)
  1278. {
  1279. ++count;
  1280. }
  1281. ++str;
  1282. }
  1283. }
  1284. return count;
  1285. }
  1286. // Remove chars in string
  1287. char* SystemTools::RemoveChars(const char* str, const char *toremove)
  1288. {
  1289. if (!str)
  1290. {
  1291. return NULL;
  1292. }
  1293. char *clean_str = new char [strlen(str) + 1];
  1294. char *ptr = clean_str;
  1295. while (*str)
  1296. {
  1297. const char *str2 = toremove;
  1298. while (*str2 && *str != *str2)
  1299. {
  1300. ++str2;
  1301. }
  1302. if (!*str2)
  1303. {
  1304. *ptr++ = *str;
  1305. }
  1306. ++str;
  1307. }
  1308. *ptr = '\0';
  1309. return clean_str;
  1310. }
  1311. // Remove chars in string
  1312. char* SystemTools::RemoveCharsButUpperHex(const char* str)
  1313. {
  1314. if (!str)
  1315. {
  1316. return 0;
  1317. }
  1318. char *clean_str = new char [strlen(str) + 1];
  1319. char *ptr = clean_str;
  1320. while (*str)
  1321. {
  1322. if ((*str >= '0' && *str <= '9') || (*str >= 'A' && *str <= 'F'))
  1323. {
  1324. *ptr++ = *str;
  1325. }
  1326. ++str;
  1327. }
  1328. *ptr = '\0';
  1329. return clean_str;
  1330. }
  1331. // Replace chars in string
  1332. char* SystemTools::ReplaceChars(char* str, const char *toreplace, char replacement)
  1333. {
  1334. if (str)
  1335. {
  1336. char *ptr = str;
  1337. while (*ptr)
  1338. {
  1339. const char *ptr2 = toreplace;
  1340. while (*ptr2)
  1341. {
  1342. if (*ptr == *ptr2)
  1343. {
  1344. *ptr = replacement;
  1345. }
  1346. ++ptr2;
  1347. }
  1348. ++ptr;
  1349. }
  1350. }
  1351. return str;
  1352. }
  1353. // Returns if string starts with another string
  1354. bool SystemTools::StringStartsWith(const char* str1, const char* str2)
  1355. {
  1356. if (!str1 || !str2)
  1357. {
  1358. return false;
  1359. }
  1360. size_t len1 = strlen(str1), len2 = strlen(str2);
  1361. return len1 >= len2 && !strncmp(str1, str2, len2) ? true : false;
  1362. }
  1363. // Returns if string ends with another string
  1364. bool SystemTools::StringEndsWith(const char* str1, const char* str2)
  1365. {
  1366. if (!str1 || !str2)
  1367. {
  1368. return false;
  1369. }
  1370. size_t len1 = strlen(str1), len2 = strlen(str2);
  1371. return len1 >= len2 && !strncmp(str1 + (len1 - len2), str2, len2) ? true : false;
  1372. }
  1373. // Returns a pointer to the last occurence of str2 in str1
  1374. const char* SystemTools::FindLastString(const char* str1, const char* str2)
  1375. {
  1376. if (!str1 || !str2)
  1377. {
  1378. return NULL;
  1379. }
  1380. size_t len1 = strlen(str1), len2 = strlen(str2);
  1381. if (len1 >= len2)
  1382. {
  1383. const char *ptr = str1 + len1 - len2;
  1384. do
  1385. {
  1386. if (!strncmp(ptr, str2, len2))
  1387. {
  1388. return ptr;
  1389. }
  1390. } while (ptr-- != str1);
  1391. }
  1392. return NULL;
  1393. }
  1394. // Duplicate string
  1395. char* SystemTools::DuplicateString(const char* str)
  1396. {
  1397. if (str)
  1398. {
  1399. char *newstr = new char [strlen(str) + 1];
  1400. return strcpy(newstr, str);
  1401. }
  1402. return NULL;
  1403. }
  1404. // Return a cropped string
  1405. kwsys_stl::string SystemTools::CropString(const kwsys_stl::string& s,
  1406. size_t max_len)
  1407. {
  1408. if (!s.size() || max_len == 0 || max_len >= s.size())
  1409. {
  1410. return s;
  1411. }
  1412. kwsys_stl::string n;
  1413. n.reserve(max_len);
  1414. size_t middle = max_len / 2;
  1415. n += s.substr(0, middle);
  1416. n += s.substr(s.size() - (max_len - middle), kwsys_stl::string::npos);
  1417. if (max_len > 2)
  1418. {
  1419. n[middle] = '.';
  1420. if (max_len > 3)
  1421. {
  1422. n[middle - 1] = '.';
  1423. if (max_len > 4)
  1424. {
  1425. n[middle + 1] = '.';
  1426. }
  1427. }
  1428. }
  1429. return n;
  1430. }
  1431. //----------------------------------------------------------------------------
  1432. kwsys_stl::vector<kwsys::String> SystemTools::SplitString(const char* p, char sep, bool isPath)
  1433. {
  1434. kwsys_stl::string path = p;
  1435. kwsys_stl::vector<kwsys::String> paths;
  1436. if(path.empty())
  1437. {
  1438. return paths;
  1439. }
  1440. if(isPath && path[0] == '/')
  1441. {
  1442. path.erase(path.begin());
  1443. paths.push_back("/");
  1444. }
  1445. kwsys_stl::string::size_type pos1 = 0;
  1446. kwsys_stl::string::size_type pos2 = path.find(sep, pos1+1);
  1447. while(pos2 != kwsys_stl::string::npos)
  1448. {
  1449. paths.push_back(path.substr(pos1, pos2-pos1));
  1450. pos1 = pos2+1;
  1451. pos2 = path.find(sep, pos1+1);
  1452. }
  1453. paths.push_back(path.substr(pos1, pos2-pos1));
  1454. return paths;
  1455. }
  1456. //----------------------------------------------------------------------------
  1457. int SystemTools::EstimateFormatLength(const char *format, va_list ap)
  1458. {
  1459. if (!format)
  1460. {
  1461. return 0;
  1462. }
  1463. // Quick-hack attempt at estimating the length of the string.
  1464. // Should never under-estimate.
  1465. // Start with the length of the format string itself.
  1466. size_t length = strlen(format);
  1467. // Increase the length for every argument in the format.
  1468. const char* cur = format;
  1469. while(*cur)
  1470. {
  1471. if(*cur++ == '%')
  1472. {
  1473. // Skip "%%" since it doesn't correspond to a va_arg.
  1474. if(*cur != '%')
  1475. {
  1476. while(!int(isalpha(*cur)))
  1477. {
  1478. ++cur;
  1479. }
  1480. switch (*cur)
  1481. {
  1482. case 's':
  1483. {
  1484. // Check the length of the string.
  1485. char* s = va_arg(ap, char*);
  1486. if(s)
  1487. {
  1488. length += strlen(s);
  1489. }
  1490. } break;
  1491. case 'e':
  1492. case 'f':
  1493. case 'g':
  1494. {
  1495. // Assume the argument contributes no more than 64 characters.
  1496. length += 64;
  1497. // Eat the argument.
  1498. static_cast<void>(va_arg(ap, double));
  1499. } break;
  1500. default:
  1501. {
  1502. // Assume the argument contributes no more than 64 characters.
  1503. length += 64;
  1504. // Eat the argument.
  1505. static_cast<void>(va_arg(ap, int));
  1506. } break;
  1507. }
  1508. }
  1509. // Move past the characters just tested.
  1510. ++cur;
  1511. }
  1512. }
  1513. return static_cast<int>(length);
  1514. }
  1515. kwsys_stl::string SystemTools::EscapeChars(
  1516. const char *str,
  1517. const char *chars_to_escape,
  1518. char escape_char)
  1519. {
  1520. kwsys_stl::string n;
  1521. if (str)
  1522. {
  1523. if (!chars_to_escape | !*chars_to_escape)
  1524. {
  1525. n.append(str);
  1526. }
  1527. else
  1528. {
  1529. n.reserve(strlen(str));
  1530. while (*str)
  1531. {
  1532. const char *ptr = chars_to_escape;
  1533. while (*ptr)
  1534. {
  1535. if (*str == *ptr)
  1536. {
  1537. n += escape_char;
  1538. break;
  1539. }
  1540. ++ptr;
  1541. }
  1542. n += *str;
  1543. ++str;
  1544. }
  1545. }
  1546. }
  1547. return n;
  1548. }
  1549. #ifdef __VMS
  1550. static void ConvertVMSToUnix(kwsys_stl::string& path)
  1551. {
  1552. kwsys_stl::string::size_type rootEnd = path.find(":[");
  1553. kwsys_stl::string::size_type pathEnd = path.find("]");
  1554. if(rootEnd != path.npos)
  1555. {
  1556. kwsys_stl::string root = path.substr(0, rootEnd);
  1557. kwsys_stl::string pathPart = path.substr(rootEnd+2, pathEnd - rootEnd-2);
  1558. const char* pathCString = pathPart.c_str();
  1559. const char* pos0 = pathCString;
  1560. for (kwsys_stl::string::size_type pos = 0; *pos0; ++ pos )
  1561. {
  1562. if ( *pos0 == '.' )
  1563. {
  1564. pathPart[pos] = '/';
  1565. }
  1566. pos0 ++;
  1567. }
  1568. path = "/"+ root + "/" + pathPart;
  1569. }
  1570. }
  1571. #endif
  1572. // convert windows slashes to unix slashes
  1573. void SystemTools::ConvertToUnixSlashes(kwsys_stl::string& path)
  1574. {
  1575. const char* pathCString = path.c_str();
  1576. bool hasDoubleSlash = false;
  1577. #ifdef __VMS
  1578. ConvertVMSToUnix(path);
  1579. #else
  1580. const char* pos0 = pathCString;
  1581. const char* pos1 = pathCString+1;
  1582. for (kwsys_stl::string::size_type pos = 0; *pos0; ++ pos )
  1583. {
  1584. // make sure we don't convert an escaped space to a unix slash
  1585. if ( *pos0 == '\\' && *pos1 != ' ' )
  1586. {
  1587. path[pos] = '/';
  1588. }
  1589. // Also, reuse the loop to check for slash followed by another slash
  1590. if (*pos1 == '/' && *(pos1+1) == '/' && !hasDoubleSlash)
  1591. {
  1592. #ifdef _WIN32
  1593. // However, on windows if the first characters are both slashes,
  1594. // then keep them that way, so that network paths can be handled.
  1595. if ( pos > 0)
  1596. {
  1597. hasDoubleSlash = true;
  1598. }
  1599. #else
  1600. hasDoubleSlash = true;
  1601. #endif
  1602. }
  1603. pos0 ++;
  1604. pos1 ++;
  1605. }
  1606. if ( hasDoubleSlash )
  1607. {
  1608. SystemTools::ReplaceString(path, "//", "/");
  1609. }
  1610. #endif
  1611. // remove any trailing slash
  1612. if(!path.empty())
  1613. {
  1614. // if there is a tilda ~ then replace it with HOME
  1615. pathCString = path.c_str();
  1616. if(pathCString[0] == '~' && (pathCString[1] == '/' || pathCString[1] == '\0'))
  1617. {
  1618. const char* homeEnv = SystemTools::GetEnv("HOME");
  1619. if (homeEnv)
  1620. {
  1621. path.replace(0,1,homeEnv);
  1622. }
  1623. }
  1624. #ifdef HAVE_GETPWNAM
  1625. else if(pathCString[0] == '~')
  1626. {
  1627. kwsys_stl::string::size_type idx = path.find_first_of("/\0");
  1628. kwsys_stl::string user = path.substr(1, idx-1);
  1629. passwd* pw = getpwnam(user.c_str());
  1630. if(pw)
  1631. {
  1632. path.replace(0, idx, pw->pw_dir);
  1633. }
  1634. }
  1635. #endif
  1636. // remove trailing slash if the path is more than
  1637. // a single /
  1638. pathCString = path.c_str();
  1639. if(path.size() > 1 && *(pathCString+(path.size()-1)) == '/')
  1640. {
  1641. // if it is c:/ then do not remove the trailing slash
  1642. if(!((path.size() == 3 && pathCString[1] == ':')))
  1643. {
  1644. path = path.substr(0, path.size()-1);
  1645. }
  1646. }
  1647. }
  1648. }
  1649. // change // to /, and escape any spaces in the path
  1650. kwsys_stl::string SystemTools::ConvertToUnixOutputPath(const char* path)
  1651. {
  1652. kwsys_stl::string ret = path;
  1653. // remove // except at the beginning might be a cygwin drive
  1654. kwsys_stl::string::size_type pos=1;
  1655. while((pos = ret.find("//", pos)) != kwsys_stl::string::npos)
  1656. {
  1657. ret.erase(pos, 1);
  1658. }
  1659. // escape spaces and () in the path
  1660. if(ret.find_first_of(" ") != kwsys_stl::string::npos)
  1661. {
  1662. kwsys_stl::string result = "";
  1663. char lastch = 1;
  1664. for(const char* ch = ret.c_str(); *ch != '\0'; ++ch)
  1665. {
  1666. // if it is already escaped then don't try to escape it again
  1667. if((*ch == ' ') && lastch != '\\')
  1668. {
  1669. result += '\\';
  1670. }
  1671. result += *ch;
  1672. lastch = *ch;
  1673. }
  1674. ret = result;
  1675. }
  1676. return ret;
  1677. }
  1678. kwsys_stl::string SystemTools::ConvertToOutputPath(const char* path)
  1679. {
  1680. #if defined(_WIN32) && !defined(__CYGWIN__)
  1681. return SystemTools::ConvertToWindowsOutputPath(path);
  1682. #else
  1683. return SystemTools::ConvertToUnixOutputPath(path);
  1684. #endif
  1685. }
  1686. // remove double slashes not at the start
  1687. kwsys_stl::string SystemTools::ConvertToWindowsOutputPath(const char* path)
  1688. {
  1689. kwsys_stl::string ret;
  1690. // make it big enough for all of path and double quotes
  1691. ret.reserve(strlen(path)+3);
  1692. // put path into the string
  1693. ret.assign(path);
  1694. ret = path;
  1695. kwsys_stl::string::size_type pos = 0;
  1696. // first convert all of the slashes
  1697. while((pos = ret.find('/', pos)) != kwsys_stl::string::npos)
  1698. {
  1699. ret[pos] = '\\';
  1700. pos++;
  1701. }
  1702. // check for really small paths
  1703. if(ret.size() < 2)
  1704. {
  1705. return ret;
  1706. }
  1707. // now clean up a bit and remove double slashes
  1708. // Only if it is not the first position in the path which is a network
  1709. // path on windows
  1710. pos = 1; // start at position 1
  1711. if(ret[0] == '\"')
  1712. {
  1713. pos = 2; // if the string is already quoted then start at 2
  1714. if(ret.size() < 3)
  1715. {
  1716. return ret;
  1717. }
  1718. }
  1719. while((pos = ret.find("\\\\", pos)) != kwsys_stl::string::npos)
  1720. {
  1721. ret.erase(pos, 1);
  1722. }
  1723. // now double quote the path if it has spaces in it
  1724. // and is not already double quoted
  1725. if(ret.find(' ') != kwsys_stl::string::npos
  1726. && ret[0] != '\"')
  1727. {
  1728. ret.insert(static_cast<kwsys_stl::string::size_type>(0),
  1729. static_cast<kwsys_stl::string::size_type>(1), '\"');
  1730. ret.append(1, '\"');
  1731. }
  1732. return ret;
  1733. }
  1734. bool SystemTools::CopyFileIfDifferent(const char* source,
  1735. const char* destination)
  1736. {
  1737. // special check for a destination that is a directory
  1738. // FilesDiffer does not handle file to directory compare
  1739. if(SystemTools::FileIsDirectory(destination))
  1740. {
  1741. kwsys_stl::string new_destination = destination;
  1742. SystemTools::ConvertToUnixSlashes(new_destination);
  1743. new_destination += '/';
  1744. kwsys_stl::string source_name = source;
  1745. new_destination += SystemTools::GetFilenameName(source_name);
  1746. if(SystemTools::FilesDiffer(source, new_destination.c_str()))
  1747. {
  1748. return SystemTools::CopyFileAlways(source, destination);
  1749. }
  1750. else
  1751. {
  1752. // the files are the same so the copy is done return
  1753. // true
  1754. return true;
  1755. }
  1756. }
  1757. // source and destination are files so do a copy if they
  1758. // are different
  1759. if(SystemTools::FilesDiffer(source, destination))
  1760. {
  1761. return SystemTools::CopyFileAlways(source, destination);
  1762. }
  1763. // at this point the files must be the same so return true
  1764. return true;
  1765. }
  1766. #define KWSYS_ST_BUFFER 4096
  1767. bool SystemTools::FilesDiffer(const char* source,
  1768. const char* destination)
  1769. {
  1770. struct stat statSource;
  1771. if (stat(source, &statSource) != 0)
  1772. {
  1773. return true;
  1774. }
  1775. struct stat statDestination;
  1776. if (stat(destination, &statDestination) != 0)
  1777. {
  1778. return true;
  1779. }
  1780. if(statSource.st_size != statDestination.st_size)
  1781. {
  1782. return true;
  1783. }
  1784. if(statSource.st_size == 0)
  1785. {
  1786. return false;
  1787. }
  1788. #if defined(_WIN32) || defined(__CYGWIN__)
  1789. kwsys_ios::ifstream finSource(source, (kwsys_ios::ios::binary |
  1790. kwsys_ios::ios::in));
  1791. kwsys_ios::ifstream finDestination(destination, (kwsys_ios::ios::binary |
  1792. kwsys_ios::ios::in));
  1793. #else
  1794. kwsys_ios::ifstream finSource(source);
  1795. kwsys_ios::ifstream finDestination(destination);
  1796. #endif
  1797. if(!finSource || !finDestination)
  1798. {
  1799. return true;
  1800. }
  1801. // Compare the files a block at a time.
  1802. char source_buf[KWSYS_ST_BUFFER];
  1803. char dest_buf[KWSYS_ST_BUFFER];
  1804. off_t nleft = statSource.st_size;
  1805. while(nleft > 0)
  1806. {
  1807. // Read a block from each file.
  1808. kwsys_ios::streamsize nnext = (nleft > KWSYS_ST_BUFFER)? KWSYS_ST_BUFFER : static_cast<kwsys_ios::streamsize>(nleft);
  1809. finSource.read(source_buf, nnext);
  1810. finDestination.read(dest_buf, nnext);
  1811. // If either failed to read assume they are different.
  1812. if(static_cast<kwsys_ios::streamsize>(finSource.gcount()) != nnext ||
  1813. static_cast<kwsys_ios::streamsize>(finDestination.gcount()) != nnext)
  1814. {
  1815. return true;
  1816. }
  1817. // If this block differs the file differs.
  1818. if(memcmp(static_cast<const void*>(source_buf),
  1819. static_cast<const void*>(dest_buf),
  1820. static_cast<size_t>(nnext)) != 0)
  1821. {
  1822. return true;
  1823. }
  1824. // Update the byte count remaining.
  1825. nleft -= nnext;
  1826. }
  1827. // No differences found.
  1828. return false;
  1829. }
  1830. //----------------------------------------------------------------------------
  1831. /**
  1832. * Copy a file named by "source" to the file named by "destination".
  1833. */
  1834. bool SystemTools::CopyFileAlways(const char* source, const char* destination)
  1835. {
  1836. // If files are the same do not copy
  1837. if ( SystemTools::SameFile(source, destination) )
  1838. {
  1839. return true;
  1840. }
  1841. mode_t perm = 0;
  1842. bool perms = SystemTools::GetPermissions(source, perm);
  1843. const int bufferSize = 4096;
  1844. char buffer[bufferSize];
  1845. // If destination is a directory, try to create a file with the same
  1846. // name as the source in that directory.
  1847. kwsys_stl::string new_destination;
  1848. if(SystemTools::FileExists(destination) &&
  1849. SystemTools::FileIsDirectory(destination))
  1850. {
  1851. new_destination = destination;
  1852. SystemTools::ConvertToUnixSlashes(new_destination);
  1853. new_destination += '/';
  1854. kwsys_stl::string source_name = source;
  1855. new_destination += SystemTools::GetFilenameName(source_name);
  1856. destination = new_destination.c_str();
  1857. }
  1858. // Create destination directory
  1859. kwsys_stl::string destination_dir = destination;
  1860. destination_dir = SystemTools::GetFilenamePath(destination_dir);
  1861. SystemTools::MakeDirectory(destination_dir.c_str());
  1862. // Open files
  1863. #if defined(_WIN32) || defined(__CYGWIN__)
  1864. kwsys_ios::ifstream fin(source,
  1865. kwsys_ios::ios::binary | kwsys_ios::ios::in);
  1866. #else
  1867. kwsys_ios::ifstream fin(source);
  1868. #endif
  1869. if(!fin)
  1870. {
  1871. return false;
  1872. }
  1873. // try and remove the destination file so that read only destination files
  1874. // can be written to.
  1875. // If the remove fails continue so that files in read only directories
  1876. // that do not allow file removal can be modified.
  1877. SystemTools::RemoveFile(destination);
  1878. #if defined(_WIN32) || defined(__CYGWIN__)
  1879. kwsys_ios::ofstream fout(destination,
  1880. kwsys_ios::ios::binary | kwsys_ios::ios::out | kwsys_ios::ios::trunc);
  1881. #else
  1882. kwsys_ios::ofstream fout(destination,
  1883. kwsys_ios::ios::out | kwsys_ios::ios::trunc);
  1884. #endif
  1885. if(!fout)
  1886. {
  1887. return false;
  1888. }
  1889. // This copy loop is very sensitive on certain platforms with
  1890. // slightly broken stream libraries (like HPUX). Normally, it is
  1891. // incorrect to not check the error condition on the fin.read()
  1892. // before using the data, but the fin.gcount() will be zero if an
  1893. // error occurred. Therefore, the loop should be safe everywhere.
  1894. while(fin)
  1895. {
  1896. fin.read(buffer, bufferSize);
  1897. if(fin.gcount())
  1898. {
  1899. fout.write(buffer, fin.gcount());
  1900. }
  1901. }
  1902. /

Large files files are truncated, but you can click here to view the full file