cmSystemTools.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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 arguments in the vector that have ; separated
  27. * strings into multiple arguments. 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. /** Map help document name to file name. */
  43. static std::string HelpFileName(std::string);
  44. /**
  45. * Returns a string that has whitespace removed from the start and the end.
  46. */
  47. static std::string TrimWhitespace(const std::string& s);
  48. typedef void (*ErrorCallback)(const char*, const char*, bool&, void*);
  49. /**
  50. * Set the function used by GUIs to display error messages
  51. * Function gets passed: message as a const char*,
  52. * title as a const char*, and a reference to bool that when
  53. * set to false, will disable furthur messages (cancel).
  54. */
  55. static void SetErrorCallback(ErrorCallback f, void* clientData=0);
  56. /**
  57. * Display an error message.
  58. */
  59. static void Error(const char* m, const char* m2=0,
  60. const char* m3=0, const char* m4=0);
  61. /**
  62. * Display a message.
  63. */
  64. static void Message(const char* m, const char* title=0);
  65. ///! Send a string to stdout
  66. static void Stdout(const char* s);
  67. static void Stdout(const char* s, int length);
  68. typedef void (*StdoutCallback)(const char*, int length, void*);
  69. static void SetStdoutCallback(StdoutCallback, void* clientData=0);
  70. ///! Send a string to stderr. Stdout callbacks will not be invoced.
  71. static void Stderr(const char* s, int length);
  72. typedef bool (*InterruptCallback)(void*);
  73. static void SetInterruptCallback(InterruptCallback f, void* clientData=0);
  74. static bool GetInterruptFlag();
  75. ///! Return true if there was an error at any point.
  76. static bool GetErrorOccuredFlag()
  77. {
  78. return cmSystemTools::s_ErrorOccured ||
  79. cmSystemTools::s_FatalErrorOccured ||
  80. GetInterruptFlag();
  81. }
  82. ///! If this is set to true, cmake stops processing commands.
  83. static void SetFatalErrorOccured()
  84. {
  85. cmSystemTools::s_FatalErrorOccured = true;
  86. }
  87. static void SetErrorOccured()
  88. {
  89. cmSystemTools::s_ErrorOccured = true;
  90. }
  91. ///! Return true if there was an error at any point.
  92. static bool GetFatalErrorOccured()
  93. {
  94. return cmSystemTools::s_FatalErrorOccured || GetInterruptFlag();
  95. }
  96. ///! Set the error occured flag and fatal error back to false
  97. static void ResetErrorOccuredFlag()
  98. {
  99. cmSystemTools::s_FatalErrorOccured = false;
  100. cmSystemTools::s_ErrorOccured = false;
  101. }
  102. /**
  103. * Does a string indicates that CMake/CPack/CTest internally
  104. * forced this value. This is not the same as On, but this
  105. * may be considered as "internally switched on".
  106. */
  107. static bool IsInternallyOn(const char* val);
  108. /**
  109. * does a string indicate a true or on value ? This is not the same
  110. * as ifdef.
  111. */
  112. static bool IsOn(const char* val);
  113. /**
  114. * does a string indicate a false or off value ? Note that this is
  115. * not the same as !IsOn(...) because there are a number of
  116. * ambiguous values such as "/usr/local/bin" a path will result in
  117. * IsON and IsOff both returning false. Note that the special path
  118. * NOTFOUND, *-NOTFOUND or IGNORE will cause IsOff to return true.
  119. */
  120. static bool IsOff(const char* val);
  121. ///! Return true if value is NOTFOUND or ends in -NOTFOUND.
  122. static bool IsNOTFOUND(const char* value);
  123. ///! Return true if the path is a framework
  124. static bool IsPathToFramework(const char* value);
  125. static bool DoesFileExistWithExtensions(
  126. const char *name,
  127. const std::vector<std::string>& sourceExts);
  128. /**
  129. * Check if the given file exists in one of the parent directory of the
  130. * given file or directory and if it does, return the name of the file.
  131. * Toplevel specifies the top-most directory to where it will look.
  132. */
  133. static std::string FileExistsInParentDirectories(const char* fname,
  134. const char* directory, const char* toplevel);
  135. static void Glob(const char *directory, const char *regexp,
  136. std::vector<std::string>& files);
  137. static void GlobDirs(const char *fullPath, std::vector<std::string>& files);
  138. /**
  139. * Try to find a list of files that match the "simple" globbing
  140. * expression. At this point in time the globbing expressions have
  141. * to be in form: /directory/partial_file_name*. The * character has
  142. * to be at the end of the string and it does not support ?
  143. * []... The optional argument type specifies what kind of files you
  144. * want to find. 0 means all files, -1 means directories, 1 means
  145. * files only. This method returns true if search was succesfull.
  146. */
  147. static bool SimpleGlob(const cmStdString& glob,
  148. std::vector<cmStdString>& files,
  149. int type = 0);
  150. ///! Copy a file.
  151. static bool cmCopyFile(const char* source, const char* destination);
  152. static bool CopyFileIfDifferent(const char* source,
  153. const char* destination);
  154. /** Rename a file or directory within a single disk volume (atomic
  155. if possible). */
  156. static bool RenameFile(const char* oldname, const char* newname);
  157. ///! Compute the md5sum of a file
  158. static bool ComputeFileMD5(const char* source, char* md5out);
  159. /** Compute the md5sum of a string. */
  160. static std::string ComputeStringMD5(const char* input);
  161. /**
  162. * Run a single executable command
  163. *
  164. * Output is controlled with outputflag. If outputflag is OUTPUT_NONE, no
  165. * user-viewable output from the program being run will be generated.
  166. * OUTPUT_MERGE is the legacy behaviour where stdout and stderr are merged
  167. * into stdout. OUTPUT_NORMAL passes through the output to stdout/stderr as
  168. * it was received. OUTPUT_PASSTHROUGH passes through the original handles.
  169. *
  170. * If timeout is specified, the command will be terminated after
  171. * timeout expires. Timeout is specified in seconds.
  172. *
  173. * Argument retVal should be a pointer to the location where the
  174. * exit code will be stored. If the retVal is not specified and
  175. * the program exits with a code other than 0, then the this
  176. * function will return false.
  177. *
  178. * If the command has spaces in the path the caller MUST call
  179. * cmSystemTools::ConvertToRunCommandPath on the command before passing
  180. * it into this function or it will not work. The command must be correctly
  181. * escaped for this to with spaces.
  182. */
  183. enum OutputOption
  184. {
  185. OUTPUT_NONE = 0,
  186. OUTPUT_MERGE,
  187. OUTPUT_NORMAL,
  188. OUTPUT_PASSTHROUGH
  189. };
  190. static bool RunSingleCommand(const char* command, std::string* output = 0,
  191. int* retVal = 0, const char* dir = 0,
  192. OutputOption outputflag = OUTPUT_MERGE,
  193. double timeout = 0.0);
  194. /**
  195. * In this version of RunSingleCommand, command[0] should be
  196. * the command to run, and each argument to the command should
  197. * be in comand[1]...command[command.size()]
  198. */
  199. static bool RunSingleCommand(std::vector<std::string> const& command,
  200. std::string* output = 0,
  201. int* retVal = 0, const char* dir = 0,
  202. OutputOption outputflag = OUTPUT_MERGE,
  203. double timeout = 0.0);
  204. static bool RunSingleCommand(std::vector<cmStdString> const& command,
  205. std::string* output = 0,
  206. int* retVal = 0, const char* dir = 0,
  207. OutputOption outputflag = OUTPUT_MERGE,
  208. double timeout = 0.0);
  209. /**
  210. * Parse arguments out of a single string command
  211. */
  212. static std::vector<cmStdString> ParseArguments(const char* command);
  213. /** Parse arguments out of a windows command line string. */
  214. static void ParseWindowsCommandLine(const char* command,
  215. std::vector<std::string>& args);
  216. /** Parse arguments out of a unix command line string. */
  217. static void ParseUnixCommandLine(const char* command,
  218. std::vector<std::string>& args);
  219. static void ParseUnixCommandLine(const char* command,
  220. std::vector<cmStdString>& args);
  221. /** Compute an escaped version of the given argument for use in a
  222. windows shell. See kwsys/System.h.in for details. */
  223. static std::string EscapeWindowsShellArgument(const char* arg,
  224. int shell_flags);
  225. static void EnableMessages() { s_DisableMessages = false; }
  226. static void DisableMessages() { s_DisableMessages = true; }
  227. static void DisableRunCommandOutput() {s_DisableRunCommandOutput = true; }
  228. static void EnableRunCommandOutput() {s_DisableRunCommandOutput = false; }
  229. static bool GetRunCommandOutput() { return s_DisableRunCommandOutput; }
  230. /**
  231. * Some constants for different file formats.
  232. */
  233. enum FileFormat {
  234. NO_FILE_FORMAT = 0,
  235. C_FILE_FORMAT,
  236. CXX_FILE_FORMAT,
  237. FORTRAN_FILE_FORMAT,
  238. JAVA_FILE_FORMAT,
  239. HEADER_FILE_FORMAT,
  240. RESOURCE_FILE_FORMAT,
  241. DEFINITION_FILE_FORMAT,
  242. STATIC_LIBRARY_FILE_FORMAT,
  243. SHARED_LIBRARY_FILE_FORMAT,
  244. MODULE_FILE_FORMAT,
  245. OBJECT_FILE_FORMAT,
  246. UNKNOWN_FILE_FORMAT
  247. };
  248. enum CompareOp {
  249. OP_LESS,
  250. OP_GREATER,
  251. OP_EQUAL
  252. };
  253. /**
  254. * Compare versions
  255. */
  256. static bool VersionCompare(CompareOp op, const char* lhs, const char* rhs);
  257. /**
  258. * Determine the file type based on the extension
  259. */
  260. static FileFormat GetFileFormat(const char* ext);
  261. /** Windows if this is true, the CreateProcess in RunCommand will
  262. * not show new consol windows when running programs.
  263. */
  264. static void SetRunCommandHideConsole(bool v){s_RunCommandHideConsole = v;}
  265. static bool GetRunCommandHideConsole(){ return s_RunCommandHideConsole;}
  266. /** Call cmSystemTools::Error with the message m, plus the
  267. * result of strerror(errno)
  268. */
  269. static void ReportLastSystemError(const char* m);
  270. /** a general output handler for cmsysProcess */
  271. static int WaitForLine(cmsysProcess* process, std::string& line,
  272. double timeout,
  273. std::vector<char>& out,
  274. std::vector<char>& err);
  275. /** Split a string on its newlines into multiple lines. Returns
  276. false only if the last line stored had no newline. */
  277. static bool Split(const char* s, std::vector<cmStdString>& l);
  278. static void SetForceUnixPaths(bool v)
  279. {
  280. s_ForceUnixPaths = v;
  281. }
  282. static bool GetForceUnixPaths()
  283. {
  284. return s_ForceUnixPaths;
  285. }
  286. // ConvertToOutputPath use s_ForceUnixPaths
  287. static std::string ConvertToOutputPath(const char* path);
  288. static void ConvertToOutputSlashes(std::string& path);
  289. // ConvertToRunCommandPath does not use s_ForceUnixPaths and should
  290. // be used when RunCommand is called from cmake, because the
  291. // running cmake needs paths to be in its format
  292. static std::string ConvertToRunCommandPath(const char* path);
  293. //! Check if the first string ends with the second one.
  294. static bool StringEndsWith(const char* str1, const char* str2);
  295. /** compute the relative path from local to remote. local must
  296. be a directory. remote can be a file or a directory.
  297. Both remote and local must be full paths. Basically, if
  298. you are in directory local and you want to access the file in remote
  299. what is the relative path to do that. For example:
  300. /a/b/c/d to /a/b/c1/d1 -> ../../c1/d1
  301. from /usr/src to /usr/src/test/blah/foo.cpp -> test/blah/foo.cpp
  302. */
  303. static std::string RelativePath(const char* local, const char* remote);
  304. /** Joins two paths while collapsing x/../ parts
  305. * For example CollapseCombinedPath("a/b/c", "../../d") results in "a/d"
  306. */
  307. static std::string CollapseCombinedPath(std::string const& dir,
  308. std::string const& file);
  309. #ifdef CMAKE_BUILD_WITH_CMAKE
  310. /** Remove an environment variable */
  311. static bool UnsetEnv(const char* value);
  312. /** Get the list of all environment variables */
  313. static std::vector<std::string> GetEnvironmentVariables();
  314. /** Append multiple variables to the current environment. */
  315. static void AppendEnv(std::vector<std::string> const& 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. /** Random seed generation. */
  355. static unsigned int RandomSeed();
  356. /** Find the directory containing CMake executables. */
  357. static void FindCMakeResources(const char* argv0);
  358. /** Get the CMake resource paths, after FindCMakeResources. */
  359. static std::string const& GetCTestCommand();
  360. static std::string const& GetCPackCommand();
  361. static std::string const& GetCMakeCommand();
  362. static std::string const& GetCMakeGUICommand();
  363. static std::string const& GetCMakeCursesCommand();
  364. static std::string const& GetCMakeRoot();
  365. #if defined(CMAKE_BUILD_WITH_CMAKE)
  366. /** Echo a message in color using KWSys's Terminal cprintf. */
  367. static void MakefileColorEcho(int color, const char* message,
  368. bool newLine, bool enabled);
  369. #endif
  370. /** Try to guess the soname of a shared library. */
  371. static bool GuessLibrarySOName(std::string const& fullPath,
  372. std::string& soname);
  373. /** Try to guess the install name of a shared library. */
  374. static bool GuessLibraryInstallName(std::string const& fullPath,
  375. std::string& soname);
  376. /** Try to set the RPATH in an ELF binary. */
  377. static bool ChangeRPath(std::string const& file,
  378. std::string const& oldRPath,
  379. std::string const& newRPath,
  380. std::string* emsg = 0,
  381. bool* changed = 0);
  382. /** Try to remove the RPATH from an ELF binary. */
  383. static bool RemoveRPath(std::string const& file, std::string* emsg = 0,
  384. bool* removed = 0);
  385. /** Check whether the RPATH in an ELF binary contains the path
  386. given. */
  387. static bool CheckRPath(std::string const& file,
  388. std::string const& newRPath);
  389. /** Remove a directory; repeat a few times in case of locked files. */
  390. static bool RepeatedRemoveDirectory(const char* dir);
  391. /** Tokenize a string */
  392. static std::vector<std::string> tokenize(const std::string& str,
  393. const std::string& sep);
  394. private:
  395. static bool s_ForceUnixPaths;
  396. static bool s_RunCommandHideConsole;
  397. static bool s_ErrorOccured;
  398. static bool s_FatalErrorOccured;
  399. static bool s_DisableMessages;
  400. static bool s_DisableRunCommandOutput;
  401. static ErrorCallback s_ErrorCallback;
  402. static StdoutCallback s_StdoutCallback;
  403. static InterruptCallback s_InterruptCallback;
  404. static void* s_ErrorCallbackClientData;
  405. static void* s_StdoutCallbackClientData;
  406. static void* s_InterruptCallbackClientData;
  407. };
  408. #endif