cmSystemTools.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. /*============================================================================
  2. CMake - Cross Platform Makefile Generator
  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. #ifndef cmSystemTools_h
  11. #define cmSystemTools_h
  12. #include "cmStandardIncludes.h"
  13. #include <cmsys/SystemTools.hxx>
  14. #include <cmsys/Process.h>
  15. class cmSystemToolsFileTime;
  16. /** \class cmSystemTools
  17. * \brief A collection of useful functions for CMake.
  18. *
  19. * cmSystemTools is a class that provides helper functions
  20. * for the CMake build system.
  21. */
  22. class cmSystemTools: public cmsys::SystemTools
  23. {
  24. public:
  25. typedef cmsys::SystemTools Superclass;
  26. /** Expand out any arguements in the vector that have ; separated
  27. * strings into multiple arguements. A new vector is created
  28. * containing the expanded versions of all arguments in argsIn.
  29. */
  30. static void ExpandList(std::vector<std::string> const& argsIn,
  31. std::vector<std::string>& argsOut);
  32. static void ExpandListArgument(const std::string& arg,
  33. std::vector<std::string>& argsOut,
  34. bool emptyArgs=false);
  35. /**
  36. * Look for and replace registry values in a string
  37. */
  38. static void ExpandRegistryValues(std::string& source,
  39. KeyWOW64 view = KeyWOW64_Default);
  40. ///! Escape quotes in a string.
  41. static std::string EscapeQuotes(const char* str);
  42. typedef void (*ErrorCallback)(const char*, const char*, bool&, void*);
  43. /**
  44. * Set the function used by GUI's to display error messages
  45. * Function gets passed: message as a const char*,
  46. * title as a const char*, and a reference to bool that when
  47. * set to false, will disable furthur messages (cancel).
  48. */
  49. static void SetErrorCallback(ErrorCallback f, void* clientData=0);
  50. /**
  51. * Display an error message.
  52. */
  53. static void Error(const char* m, const char* m2=0,
  54. const char* m3=0, const char* m4=0);
  55. /**
  56. * Display a message.
  57. */
  58. static void Message(const char* m, const char* title=0);
  59. ///! Send a string to stdout
  60. static void Stdout(const char* s);
  61. static void Stdout(const char* s, int length);
  62. typedef void (*StdoutCallback)(const char*, int length, void*);
  63. static void SetStdoutCallback(StdoutCallback, void* clientData=0);
  64. ///! Return true if there was an error at any point.
  65. static bool GetErrorOccuredFlag()
  66. {
  67. return cmSystemTools::s_ErrorOccured ||
  68. cmSystemTools::s_FatalErrorOccured;
  69. }
  70. ///! If this is set to true, cmake stops processing commands.
  71. static void SetFatalErrorOccured()
  72. {
  73. cmSystemTools::s_FatalErrorOccured = true;
  74. }
  75. static void SetErrorOccured()
  76. {
  77. cmSystemTools::s_ErrorOccured = true;
  78. }
  79. ///! Return true if there was an error at any point.
  80. static bool GetFatalErrorOccured()
  81. {
  82. return cmSystemTools::s_FatalErrorOccured;
  83. }
  84. ///! Set the error occured flag and fatal error back to false
  85. static void ResetErrorOccuredFlag()
  86. {
  87. cmSystemTools::s_FatalErrorOccured = false;
  88. cmSystemTools::s_ErrorOccured = false;
  89. }
  90. /**
  91. * Does a string indicates that CMake/CPack/CTest internally
  92. * forced this value. This is not the same as On, but this
  93. * may be considered as "internally switched on".
  94. */
  95. static bool IsInternallyOn(const char* val);
  96. /**
  97. * does a string indicate a true or on value ? This is not the same
  98. * as ifdef.
  99. */
  100. static bool IsOn(const char* val);
  101. /**
  102. * does a string indicate a false or off value ? Note that this is
  103. * not the same as !IsOn(...) because there are a number of
  104. * ambiguous values such as "/usr/local/bin" a path will result in
  105. * IsON and IsOff both returning false. Note that the special path
  106. * NOTFOUND, *-NOTFOUND or IGNORE will cause IsOff to return true.
  107. */
  108. static bool IsOff(const char* val);
  109. ///! Return true if value is NOTFOUND or ends in -NOTFOUND.
  110. static bool IsNOTFOUND(const char* value);
  111. ///! Return true if the path is a framework
  112. static bool IsPathToFramework(const char* value);
  113. static bool DoesFileExistWithExtensions(
  114. const char *name,
  115. const std::vector<std::string>& sourceExts);
  116. /**
  117. * Check if the given file exists in one of the parent directory of the
  118. * given file or directory and if it does, return the name of the file.
  119. * Toplevel specifies the top-most directory to where it will look.
  120. */
  121. static std::string FileExistsInParentDirectories(const char* fname,
  122. const char* directory, const char* toplevel);
  123. static void Glob(const char *directory, const char *regexp,
  124. std::vector<std::string>& files);
  125. static void GlobDirs(const char *fullPath, std::vector<std::string>& files);
  126. /**
  127. * Try to find a list of files that match the "simple" globbing
  128. * expression. At this point in time the globbing expressions have
  129. * to be in form: /directory/partial_file_name*. The * character has
  130. * to be at the end of the string and it does not support ?
  131. * []... The optional argument type specifies what kind of files you
  132. * want to find. 0 means all files, -1 means directories, 1 means
  133. * files only. This method returns true if search was succesfull.
  134. */
  135. static bool SimpleGlob(const cmStdString& glob,
  136. std::vector<cmStdString>& files,
  137. int type = 0);
  138. ///! Copy a file.
  139. static bool cmCopyFile(const char* source, const char* destination);
  140. static bool CopyFileIfDifferent(const char* source,
  141. const char* destination);
  142. /** Rename a file or directory within a single disk volume (atomic
  143. if possible). */
  144. static bool RenameFile(const char* oldname, const char* newname);
  145. ///! Compute the md5sum of a file
  146. static bool ComputeFileMD5(const char* source, char* md5out);
  147. /** Compute the md5sum of a string. */
  148. static std::string ComputeStringMD5(const char* input);
  149. /**
  150. * Run an executable command and put the stdout in output.
  151. * A temporary file is created in the binaryDir for storing the
  152. * output because windows does not have popen.
  153. *
  154. * If verbose is false, no user-viewable output from the program
  155. * being run will be generated.
  156. *
  157. * If timeout is specified, the command will be terminated after
  158. * timeout expires.
  159. */
  160. static bool RunCommand(const char* command, std::string& output,
  161. const char* directory = 0,
  162. bool verbose = true, int timeout = 0);
  163. static bool RunCommand(const char* command, std::string& output,
  164. int &retVal, const char* directory = 0,
  165. bool verbose = true, int timeout = 0);
  166. /**
  167. * Run a single executable command and put the stdout and stderr
  168. * in output.
  169. *
  170. * If verbose is false, no user-viewable output from the program
  171. * being run will be generated.
  172. *
  173. * If timeout is specified, the command will be terminated after
  174. * timeout expires. Timeout is specified in seconds.
  175. *
  176. * Argument retVal should be a pointer to the location where the
  177. * exit code will be stored. If the retVal is not specified and
  178. * the program exits with a code other than 0, then the this
  179. * function will return false.
  180. *
  181. * If the command has spaces in the path the caller MUST call
  182. * cmSystemTools::ConvertToRunCommandPath on the command before passing
  183. * it into this function or it will not work. The command must be correctly
  184. * escaped for this to with spaces.
  185. */
  186. static bool RunSingleCommand(const char* command, std::string* output = 0,
  187. int* retVal = 0, const char* dir = 0,
  188. bool verbose = true,
  189. double timeout = 0.0);
  190. /**
  191. * In this version of RunSingleCommand, command[0] should be
  192. * the command to run, and each argument to the command should
  193. * be in comand[1]...command[command.size()]
  194. */
  195. static bool RunSingleCommand(std::vector<cmStdString> const& command,
  196. std::string* output = 0,
  197. int* retVal = 0, const char* dir = 0,
  198. bool verbose = true,
  199. double timeout = 0.0);
  200. /**
  201. * Parse arguments out of a single string command
  202. */
  203. static std::vector<cmStdString> ParseArguments(const char* command);
  204. /** Parse arguments out of a windows command line string. */
  205. static void ParseWindowsCommandLine(const char* command,
  206. std::vector<std::string>& args);
  207. /** Parse arguments out of a unix command line string. */
  208. static void ParseUnixCommandLine(const char* command,
  209. std::vector<std::string>& args);
  210. static void ParseUnixCommandLine(const char* command,
  211. std::vector<cmStdString>& args);
  212. /** Compute an escaped version of the given argument for use in a
  213. windows shell. See kwsys/System.h.in for details. */
  214. static std::string EscapeWindowsShellArgument(const char* arg,
  215. int shell_flags);
  216. static void EnableMessages() { s_DisableMessages = false; }
  217. static void DisableMessages() { s_DisableMessages = true; }
  218. static void DisableRunCommandOutput() {s_DisableRunCommandOutput = true; }
  219. static void EnableRunCommandOutput() {s_DisableRunCommandOutput = false; }
  220. static bool GetRunCommandOutput() { return s_DisableRunCommandOutput; }
  221. /**
  222. * Come constants for different file formats.
  223. */
  224. enum FileFormat {
  225. NO_FILE_FORMAT = 0,
  226. C_FILE_FORMAT,
  227. CXX_FILE_FORMAT,
  228. FORTRAN_FILE_FORMAT,
  229. JAVA_FILE_FORMAT,
  230. HEADER_FILE_FORMAT,
  231. RESOURCE_FILE_FORMAT,
  232. DEFINITION_FILE_FORMAT,
  233. STATIC_LIBRARY_FILE_FORMAT,
  234. SHARED_LIBRARY_FILE_FORMAT,
  235. MODULE_FILE_FORMAT,
  236. OBJECT_FILE_FORMAT,
  237. UNKNOWN_FILE_FORMAT
  238. };
  239. enum CompareOp {
  240. OP_LESS,
  241. OP_GREATER,
  242. OP_EQUAL
  243. };
  244. /**
  245. * Compare versions
  246. */
  247. static bool VersionCompare(CompareOp op, const char* lhs, const char* rhs);
  248. /**
  249. * Determine the file type based on the extension
  250. */
  251. static FileFormat GetFileFormat(const char* ext);
  252. /**
  253. * On Windows 9x we need a comspec (command.com) substitute to run
  254. * programs correctly. This string has to be constant available
  255. * through the running of program. This method does not create a copy.
  256. */
  257. static void SetWindows9xComspecSubstitute(const char*);
  258. static const char* GetWindows9xComspecSubstitute();
  259. /** Windows if this is true, the CreateProcess in RunCommand will
  260. * not show new consol windows when running programs.
  261. */
  262. static void SetRunCommandHideConsole(bool v){s_RunCommandHideConsole = v;}
  263. static bool GetRunCommandHideConsole(){ return s_RunCommandHideConsole;}
  264. /** Call cmSystemTools::Error with the message m, plus the
  265. * result of strerror(errno)
  266. */
  267. static void ReportLastSystemError(const char* m);
  268. /** a general output handler for cmsysProcess */
  269. static int WaitForLine(cmsysProcess* process, std::string& line,
  270. double timeout,
  271. std::vector<char>& out,
  272. std::vector<char>& err);
  273. /** Split a string on its newlines into multiple lines. Returns
  274. false only if the last line stored had no newline. */
  275. static bool Split(const char* s, std::vector<cmStdString>& l);
  276. static void SetForceUnixPaths(bool v)
  277. {
  278. s_ForceUnixPaths = v;
  279. }
  280. static bool GetForceUnixPaths()
  281. {
  282. return s_ForceUnixPaths;
  283. }
  284. // ConvertToOutputPath use s_ForceUnixPaths
  285. static std::string ConvertToOutputPath(const char* path);
  286. static void ConvertToOutputSlashes(std::string& path);
  287. // ConvertToRunCommandPath does not use s_ForceUnixPaths and should
  288. // be used when RunCommand is called from cmake, because the
  289. // running cmake needs paths to be in its format
  290. static std::string ConvertToRunCommandPath(const char* path);
  291. //! Check if the first string ends with the second one.
  292. static bool StringEndsWith(const char* str1, const char* str2);
  293. /** compute the relative path from local to remote. local must
  294. be a directory. remote can be a file or a directory.
  295. Both remote and local must be full paths. Basically, if
  296. you are in directory local and you want to access the file in remote
  297. what is the relative path to do that. For example:
  298. /a/b/c/d to /a/b/c1/d1 -> ../../c1/d1
  299. from /usr/src to /usr/src/test/blah/foo.cpp -> test/blah/foo.cpp
  300. */
  301. static std::string RelativePath(const char* local, const char* remote);
  302. #ifdef CMAKE_BUILD_WITH_CMAKE
  303. /** Remove an environment variable */
  304. static bool UnsetEnv(const char* value);
  305. /** Get the list of all environment variables */
  306. static std::vector<std::string> GetEnvironmentVariables();
  307. /** Append multiple variables to the current environment.
  308. Return the original environment, as it was before the
  309. append. */
  310. static std::vector<std::string> AppendEnv(
  311. std::vector<std::string>* env);
  312. /** Restore the full environment to "env" - use after
  313. AppendEnv to put the environment back to the way it
  314. was. */
  315. static void RestoreEnv(const std::vector<std::string>& env);
  316. /** Helper class to save and restore the environment.
  317. Instantiate this class as an automatic variable on
  318. the stack. Its constructor saves a copy of the current
  319. environment and then its destructor restores the
  320. original environment. */
  321. class SaveRestoreEnvironment
  322. {
  323. public:
  324. SaveRestoreEnvironment();
  325. virtual ~SaveRestoreEnvironment();
  326. private:
  327. std::vector<std::string> Env;
  328. };
  329. #endif
  330. /** Setup the environment to enable VS 8 IDE output. */
  331. static void EnableVSConsoleOutput();
  332. /** Create tar */
  333. static bool ListTar(const char* outFileName,
  334. bool gzip, bool verbose);
  335. static bool CreateTar(const char* outFileName,
  336. const std::vector<cmStdString>& files, bool gzip,
  337. bool bzip2, bool verbose);
  338. static bool ExtractTar(const char* inFileName, bool gzip,
  339. bool verbose);
  340. // This should be called first thing in main
  341. // it will keep child processes from inheriting the
  342. // stdin and stdout of this process. This is important
  343. // if you want to be able to kill child processes and
  344. // not get stuck waiting for all the output on the pipes.
  345. static void DoNotInheritStdPipes();
  346. /** Copy the file create/access/modify times from the file named by
  347. the first argument to that named by the second. */
  348. static bool CopyFileTime(const char* fromFile, const char* toFile);
  349. /** Save and restore file times. */
  350. static cmSystemToolsFileTime* FileTimeNew();
  351. static void FileTimeDelete(cmSystemToolsFileTime*);
  352. static bool FileTimeGet(const char* fname, cmSystemToolsFileTime* t);
  353. static bool FileTimeSet(const char* fname, cmSystemToolsFileTime* t);
  354. /** Find the directory containing the running executable. Save it
  355. in a global location to be queried by GetExecutableDirectory
  356. later. */
  357. static void FindExecutableDirectory(const char* argv0);
  358. /** Get the directory containing the currently running executable. */
  359. static const char* GetExecutableDirectory();
  360. #if defined(CMAKE_BUILD_WITH_CMAKE)
  361. /** Echo a message in color using KWSys's Terminal cprintf. */
  362. static void MakefileColorEcho(int color, const char* message,
  363. bool newLine, bool enabled);
  364. #endif
  365. /** Try to guess the soname of a shared library. */
  366. static bool GuessLibrarySOName(std::string const& fullPath,
  367. std::string& soname);
  368. /** Try to set the RPATH in an ELF binary. */
  369. static bool ChangeRPath(std::string const& file,
  370. std::string const& oldRPath,
  371. std::string const& newRPath,
  372. std::string* emsg = 0,
  373. bool* changed = 0);
  374. /** Try to remove the RPATH from an ELF binary. */
  375. static bool RemoveRPath(std::string const& file, std::string* emsg = 0,
  376. bool* removed = 0);
  377. /** Check whether the RPATH in an ELF binary contains the path
  378. given. */
  379. static bool CheckRPath(std::string const& file,
  380. std::string const& newRPath);
  381. /** Remove a directory; repeat a few times in case of locked files. */
  382. static bool RepeatedRemoveDirectory(const char* dir);
  383. private:
  384. static bool s_ForceUnixPaths;
  385. static bool s_RunCommandHideConsole;
  386. static bool s_ErrorOccured;
  387. static bool s_FatalErrorOccured;
  388. static bool s_DisableMessages;
  389. static bool s_DisableRunCommandOutput;
  390. static ErrorCallback s_ErrorCallback;
  391. static StdoutCallback s_StdoutCallback;
  392. static void* s_ErrorCallbackClientData;
  393. static void* s_StdoutCallbackClientData;
  394. static std::string s_Windows9xComspecSubstitute;
  395. };
  396. #endif