cmSystemTools.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #ifndef cmSystemTools_h
  4. #define cmSystemTools_h
  5. #include "cmConfigure.h" // IWYU pragma: keep
  6. #include "cmProcessOutput.h"
  7. #include "cmsys/Process.h"
  8. #include "cmsys/SystemTools.hxx" // IWYU pragma: export
  9. #include <stddef.h>
  10. #include <string>
  11. #include <vector>
  12. class cmSystemToolsFileTime;
  13. /** \class cmSystemTools
  14. * \brief A collection of useful functions for CMake.
  15. *
  16. * cmSystemTools is a class that provides helper functions
  17. * for the CMake build system.
  18. */
  19. class cmSystemTools : public cmsys::SystemTools
  20. {
  21. public:
  22. typedef cmsys::SystemTools Superclass;
  23. typedef cmProcessOutput::Encoding Encoding;
  24. /** Expand out any arguments in the vector that have ; separated
  25. * strings into multiple arguments. A new vector is created
  26. * containing the expanded versions of all arguments in argsIn.
  27. */
  28. static void ExpandList(std::vector<std::string> const& argsIn,
  29. std::vector<std::string>& argsOut);
  30. static void ExpandListArgument(const std::string& arg,
  31. std::vector<std::string>& argsOut,
  32. bool emptyArgs = false);
  33. /**
  34. * Look for and replace registry values in a string
  35. */
  36. static void ExpandRegistryValues(std::string& source,
  37. KeyWOW64 view = KeyWOW64_Default);
  38. ///! Escape quotes in a string.
  39. static std::string EscapeQuotes(const std::string& str);
  40. /** Map help document name to file name. */
  41. static std::string HelpFileName(std::string);
  42. /**
  43. * Returns a string that has whitespace removed from the start and the end.
  44. */
  45. static std::string TrimWhitespace(const std::string& s);
  46. typedef void (*MessageCallback)(const char*, const char*, bool&, void*);
  47. /**
  48. * Set the function used by GUIs to display error messages
  49. * Function gets passed: message as a const char*,
  50. * title as a const char*, and a reference to bool that when
  51. * set to false, will disable furthur messages (cancel).
  52. */
  53. static void SetMessageCallback(MessageCallback f,
  54. void* clientData = CM_NULLPTR);
  55. /**
  56. * Display an error message.
  57. */
  58. static void Error(const char* m, const char* m2 = CM_NULLPTR,
  59. const char* m3 = CM_NULLPTR, const char* m4 = CM_NULLPTR);
  60. /**
  61. * Display a message.
  62. */
  63. static void Message(const char* m, const char* title = CM_NULLPTR);
  64. typedef void (*OutputCallback)(const char*, size_t length, void*);
  65. ///! Send a string to stdout
  66. static void Stdout(const char* s);
  67. static void Stdout(const char* s, size_t length);
  68. static void SetStdoutCallback(OutputCallback, void* clientData = CM_NULLPTR);
  69. ///! Send a string to stderr
  70. static void Stderr(const char* s);
  71. static void Stderr(const char* s, size_t length);
  72. static void SetStderrCallback(OutputCallback, void* clientData = CM_NULLPTR);
  73. typedef bool (*InterruptCallback)(void*);
  74. static void SetInterruptCallback(InterruptCallback f,
  75. void* clientData = CM_NULLPTR);
  76. static bool GetInterruptFlag();
  77. ///! Return true if there was an error at any point.
  78. static bool GetErrorOccuredFlag()
  79. {
  80. return cmSystemTools::s_ErrorOccured ||
  81. cmSystemTools::s_FatalErrorOccured || GetInterruptFlag();
  82. }
  83. ///! If this is set to true, cmake stops processing commands.
  84. static void SetFatalErrorOccured()
  85. {
  86. cmSystemTools::s_FatalErrorOccured = true;
  87. }
  88. static void SetErrorOccured() { cmSystemTools::s_ErrorOccured = true; }
  89. ///! Return true if there was an error at any point.
  90. static bool GetFatalErrorOccured()
  91. {
  92. return cmSystemTools::s_FatalErrorOccured || GetInterruptFlag();
  93. }
  94. ///! Set the error occurred flag and fatal error back to false
  95. static void ResetErrorOccuredFlag()
  96. {
  97. cmSystemTools::s_FatalErrorOccured = false;
  98. cmSystemTools::s_ErrorOccured = false;
  99. }
  100. /**
  101. * Does a string indicates that CMake/CPack/CTest internally
  102. * forced this value. This is not the same as On, but this
  103. * may be considered as "internally switched on".
  104. */
  105. static bool IsInternallyOn(const char* val);
  106. /**
  107. * does a string indicate a true or on value ? This is not the same
  108. * as ifdef.
  109. */
  110. static bool IsOn(const char* val);
  111. /**
  112. * does a string indicate a false or off value ? Note that this is
  113. * not the same as !IsOn(...) because there are a number of
  114. * ambiguous values such as "/usr/local/bin" a path will result in
  115. * IsON and IsOff both returning false. Note that the special path
  116. * NOTFOUND, *-NOTFOUND or IGNORE will cause IsOff to return true.
  117. */
  118. static bool IsOff(const char* val);
  119. ///! Return true if value is NOTFOUND or ends in -NOTFOUND.
  120. static bool IsNOTFOUND(const char* value);
  121. ///! Return true if the path is a framework
  122. static bool IsPathToFramework(const char* value);
  123. static bool DoesFileExistWithExtensions(
  124. const char* name, const std::vector<std::string>& sourceExts);
  125. /**
  126. * Check if the given file exists in one of the parent directory of the
  127. * given file or directory and if it does, return the name of the file.
  128. * Toplevel specifies the top-most directory to where it will look.
  129. */
  130. static std::string FileExistsInParentDirectories(const char* fname,
  131. const char* directory,
  132. const char* toplevel);
  133. static void Glob(const std::string& directory, const std::string& regexp,
  134. std::vector<std::string>& files);
  135. static void GlobDirs(const std::string& fullPath,
  136. std::vector<std::string>& files);
  137. /**
  138. * Try to find a list of files that match the "simple" globbing
  139. * expression. At this point in time the globbing expressions have
  140. * to be in form: /directory/partial_file_name*. The * character has
  141. * to be at the end of the string and it does not support ?
  142. * []... The optional argument type specifies what kind of files you
  143. * want to find. 0 means all files, -1 means directories, 1 means
  144. * files only. This method returns true if search was succesfull.
  145. */
  146. static bool SimpleGlob(const std::string& glob,
  147. std::vector<std::string>& files, int type = 0);
  148. ///! Copy a file.
  149. static bool cmCopyFile(const char* source, const char* destination);
  150. static bool CopyFileIfDifferent(const char* source, const char* destination);
  151. /** Rename a file or directory within a single disk volume (atomic
  152. if possible). */
  153. static bool RenameFile(const char* oldname, const char* newname);
  154. ///! Compute the md5sum of a file
  155. static bool ComputeFileMD5(const std::string& source, char* md5out);
  156. /** Compute the md5sum of a string. */
  157. static std::string ComputeStringMD5(const std::string& input);
  158. ///! Get the SHA thumbprint for a certificate file
  159. static std::string ComputeCertificateThumbprint(const std::string& source);
  160. /**
  161. * Run a single executable command
  162. *
  163. * Output is controlled with outputflag. If outputflag is OUTPUT_NONE, no
  164. * user-viewable output from the program being run will be generated.
  165. * OUTPUT_MERGE is the legacy behaviour where stdout and stderr are merged
  166. * into stdout. OUTPUT_FORWARD copies the output to stdout/stderr as
  167. * it was received. OUTPUT_PASSTHROUGH passes through the original handles.
  168. *
  169. * If timeout is specified, the command will be terminated after
  170. * timeout expires. Timeout is specified in seconds.
  171. *
  172. * Argument retVal should be a pointer to the location where the
  173. * exit code will be stored. If the retVal is not specified and
  174. * the program exits with a code other than 0, then the this
  175. * function will return false.
  176. *
  177. * If the command has spaces in the path the caller MUST call
  178. * cmSystemTools::ConvertToRunCommandPath on the command before passing
  179. * it into this function or it will not work. The command must be correctly
  180. * escaped for this to with spaces.
  181. */
  182. enum OutputOption
  183. {
  184. OUTPUT_NONE = 0,
  185. OUTPUT_MERGE,
  186. OUTPUT_FORWARD,
  187. OUTPUT_PASSTHROUGH
  188. };
  189. static bool RunSingleCommand(const char* command,
  190. std::string* captureStdOut = CM_NULLPTR,
  191. std::string* captureStdErr = CM_NULLPTR,
  192. int* retVal = CM_NULLPTR,
  193. const char* dir = CM_NULLPTR,
  194. OutputOption outputflag = OUTPUT_MERGE,
  195. double timeout = 0.0);
  196. /**
  197. * In this version of RunSingleCommand, command[0] should be
  198. * the command to run, and each argument to the command should
  199. * be in comand[1]...command[command.size()]
  200. */
  201. static bool RunSingleCommand(std::vector<std::string> const& command,
  202. std::string* captureStdOut = CM_NULLPTR,
  203. std::string* captureStdErr = CM_NULLPTR,
  204. int* retVal = CM_NULLPTR,
  205. const char* dir = CM_NULLPTR,
  206. OutputOption outputflag = OUTPUT_MERGE,
  207. double timeout = 0.0,
  208. Encoding encoding = cmProcessOutput::Auto);
  209. static std::string PrintSingleCommand(std::vector<std::string> const&);
  210. /**
  211. * Parse arguments out of a single string command
  212. */
  213. static std::vector<std::string> ParseArguments(const char* command);
  214. /** Parse arguments out of a windows command line string. */
  215. static void ParseWindowsCommandLine(const char* command,
  216. std::vector<std::string>& args);
  217. /** Parse arguments out of a unix command line string. */
  218. static void ParseUnixCommandLine(const char* command,
  219. std::vector<std::string>& args);
  220. static size_t CalculateCommandLineLengthLimit();
  221. static void EnableMessages() { s_DisableMessages = false; }
  222. static void DisableMessages() { s_DisableMessages = true; }
  223. static void DisableRunCommandOutput() { s_DisableRunCommandOutput = true; }
  224. static void EnableRunCommandOutput() { s_DisableRunCommandOutput = false; }
  225. static bool GetRunCommandOutput() { return s_DisableRunCommandOutput; }
  226. /**
  227. * Some constants for different file formats.
  228. */
  229. enum FileFormat
  230. {
  231. NO_FILE_FORMAT = 0,
  232. C_FILE_FORMAT,
  233. CXX_FILE_FORMAT,
  234. FORTRAN_FILE_FORMAT,
  235. JAVA_FILE_FORMAT,
  236. HEADER_FILE_FORMAT,
  237. RESOURCE_FILE_FORMAT,
  238. DEFINITION_FILE_FORMAT,
  239. STATIC_LIBRARY_FILE_FORMAT,
  240. SHARED_LIBRARY_FILE_FORMAT,
  241. MODULE_FILE_FORMAT,
  242. OBJECT_FILE_FORMAT,
  243. UNKNOWN_FILE_FORMAT
  244. };
  245. enum CompareOp
  246. {
  247. OP_EQUAL = 1,
  248. OP_LESS = 2,
  249. OP_GREATER = 4,
  250. OP_LESS_EQUAL = OP_LESS | OP_EQUAL,
  251. OP_GREATER_EQUAL = OP_GREATER | OP_EQUAL
  252. };
  253. /**
  254. * Compare versions
  255. */
  256. static bool VersionCompare(CompareOp op, const char* lhs, const char* rhs);
  257. static bool VersionCompareEqual(std::string const& lhs,
  258. std::string const& rhs);
  259. static bool VersionCompareGreater(std::string const& lhs,
  260. std::string const& rhs);
  261. static bool VersionCompareGreaterEq(std::string const& lhs,
  262. std::string const& rhs);
  263. /**
  264. * Compare two ASCII strings using natural versioning order.
  265. * Non-numerical characters are compared directly.
  266. * Numerical characters are first globbed such that, e.g.
  267. * `test000 < test01 < test0 < test1 < test10`.
  268. * Return a value less than, equal to, or greater than zero if lhs
  269. * precedes, equals, or succeeds rhs in the defined ordering.
  270. */
  271. static int strverscmp(std::string const& lhs, std::string const& rhs);
  272. /**
  273. * Determine the file type based on the extension
  274. */
  275. static FileFormat GetFileFormat(const char* ext);
  276. /** Windows if this is true, the CreateProcess in RunCommand will
  277. * not show new consol windows when running programs.
  278. */
  279. static void SetRunCommandHideConsole(bool v) { s_RunCommandHideConsole = v; }
  280. static bool GetRunCommandHideConsole() { return s_RunCommandHideConsole; }
  281. /** Call cmSystemTools::Error with the message m, plus the
  282. * result of strerror(errno)
  283. */
  284. static void ReportLastSystemError(const char* m);
  285. /** a general output handler for cmsysProcess */
  286. static int WaitForLine(cmsysProcess* process, std::string& line,
  287. double timeout, std::vector<char>& out,
  288. std::vector<char>& err);
  289. /** Split a string on its newlines into multiple lines. Returns
  290. false only if the last line stored had no newline. */
  291. static bool Split(const char* s, std::vector<std::string>& l);
  292. static void SetForceUnixPaths(bool v) { s_ForceUnixPaths = v; }
  293. static bool GetForceUnixPaths() { return s_ForceUnixPaths; }
  294. // ConvertToOutputPath use s_ForceUnixPaths
  295. static std::string ConvertToOutputPath(const char* path);
  296. static void ConvertToOutputSlashes(std::string& path);
  297. // ConvertToRunCommandPath does not use s_ForceUnixPaths and should
  298. // be used when RunCommand is called from cmake, because the
  299. // running cmake needs paths to be in its format
  300. static std::string ConvertToRunCommandPath(const char* path);
  301. /** compute the relative path from local to remote. local must
  302. be a directory. remote can be a file or a directory.
  303. Both remote and local must be full paths. Basically, if
  304. you are in directory local and you want to access the file in remote
  305. what is the relative path to do that. For example:
  306. /a/b/c/d to /a/b/c1/d1 -> ../../c1/d1
  307. from /usr/src to /usr/src/test/blah/foo.cpp -> test/blah/foo.cpp
  308. */
  309. static std::string RelativePath(const char* local, const char* remote);
  310. /** Joins two paths while collapsing x/../ parts
  311. * For example CollapseCombinedPath("a/b/c", "../../d") results in "a/d"
  312. */
  313. static std::string CollapseCombinedPath(std::string const& dir,
  314. std::string const& file);
  315. #ifdef CMAKE_BUILD_WITH_CMAKE
  316. /** Remove an environment variable */
  317. static bool UnsetEnv(const char* value);
  318. /** Get the list of all environment variables */
  319. static std::vector<std::string> GetEnvironmentVariables();
  320. /** Append multiple variables to the current environment. */
  321. static void AppendEnv(std::vector<std::string> const& env);
  322. /** Helper class to save and restore the environment.
  323. Instantiate this class as an automatic variable on
  324. the stack. Its constructor saves a copy of the current
  325. environment and then its destructor restores the
  326. original environment. */
  327. class SaveRestoreEnvironment
  328. {
  329. public:
  330. SaveRestoreEnvironment();
  331. virtual ~SaveRestoreEnvironment();
  332. private:
  333. std::vector<std::string> Env;
  334. };
  335. #endif
  336. /** Setup the environment to enable VS 8 IDE output. */
  337. static void EnableVSConsoleOutput();
  338. /** Create tar */
  339. enum cmTarCompression
  340. {
  341. TarCompressGZip,
  342. TarCompressBZip2,
  343. TarCompressXZ,
  344. TarCompressNone
  345. };
  346. static bool ListTar(const char* outFileName, bool verbose);
  347. static bool CreateTar(const char* outFileName,
  348. const std::vector<std::string>& files,
  349. cmTarCompression compressType, bool verbose,
  350. std::string const& mtime = std::string(),
  351. std::string const& format = std::string());
  352. static bool ExtractTar(const char* inFileName, bool verbose);
  353. // This should be called first thing in main
  354. // it will keep child processes from inheriting the
  355. // stdin and stdout of this process. This is important
  356. // if you want to be able to kill child processes and
  357. // not get stuck waiting for all the output on the pipes.
  358. static void DoNotInheritStdPipes();
  359. /** Copy the file create/access/modify times from the file named by
  360. the first argument to that named by the second. */
  361. static bool CopyFileTime(const char* fromFile, const char* toFile);
  362. /** Save and restore file times. */
  363. static cmSystemToolsFileTime* FileTimeNew();
  364. static void FileTimeDelete(cmSystemToolsFileTime*);
  365. static bool FileTimeGet(const char* fname, cmSystemToolsFileTime* t);
  366. static bool FileTimeSet(const char* fname, cmSystemToolsFileTime* t);
  367. /** Random seed generation. */
  368. static unsigned int RandomSeed();
  369. /** Find the directory containing CMake executables. */
  370. static void FindCMakeResources(const char* argv0);
  371. /** Get the CMake resource paths, after FindCMakeResources. */
  372. static std::string const& GetCTestCommand();
  373. static std::string const& GetCPackCommand();
  374. static std::string const& GetCMakeCommand();
  375. static std::string const& GetCMakeGUICommand();
  376. static std::string const& GetCMakeCursesCommand();
  377. static std::string const& GetCMClDepsCommand();
  378. static std::string const& GetCMakeRoot();
  379. /** Echo a message in color using KWSys's Terminal cprintf. */
  380. static void MakefileColorEcho(int color, const char* message, bool newLine,
  381. bool enabled);
  382. /** Try to guess the soname of a shared library. */
  383. static bool GuessLibrarySOName(std::string const& fullPath,
  384. std::string& soname);
  385. /** Try to guess the install name of a shared library. */
  386. static bool GuessLibraryInstallName(std::string const& fullPath,
  387. std::string& soname);
  388. /** Try to set the RPATH in an ELF binary. */
  389. static bool ChangeRPath(std::string const& file, std::string const& oldRPath,
  390. std::string const& newRPath,
  391. std::string* emsg = CM_NULLPTR,
  392. bool* changed = CM_NULLPTR);
  393. /** Try to remove the RPATH from an ELF binary. */
  394. static bool RemoveRPath(std::string const& file,
  395. std::string* emsg = CM_NULLPTR,
  396. bool* removed = CM_NULLPTR);
  397. /** Check whether the RPATH in an ELF binary contains the path
  398. given. */
  399. static bool CheckRPath(std::string const& file, std::string const& newRPath);
  400. /** Remove a directory; repeat a few times in case of locked files. */
  401. static bool RepeatedRemoveDirectory(const char* dir);
  402. /** Tokenize a string */
  403. static std::vector<std::string> tokenize(const std::string& str,
  404. const std::string& sep);
  405. /** Convert string to long. Expected that the whole string is an integer */
  406. static bool StringToLong(const char* str, long* value);
  407. static bool StringToULong(const char* str, unsigned long* value);
  408. #ifdef _WIN32
  409. struct WindowsFileRetry
  410. {
  411. unsigned int Count;
  412. unsigned int Delay;
  413. };
  414. static WindowsFileRetry GetWindowsFileRetry();
  415. #endif
  416. private:
  417. static bool s_ForceUnixPaths;
  418. static bool s_RunCommandHideConsole;
  419. static bool s_ErrorOccured;
  420. static bool s_FatalErrorOccured;
  421. static bool s_DisableMessages;
  422. static bool s_DisableRunCommandOutput;
  423. static MessageCallback s_MessageCallback;
  424. static OutputCallback s_StdoutCallback;
  425. static OutputCallback s_StderrCallback;
  426. static InterruptCallback s_InterruptCallback;
  427. static void* s_MessageCallbackClientData;
  428. static void* s_StdoutCallbackClientData;
  429. static void* s_StderrCallbackClientData;
  430. static void* s_InterruptCallbackClientData;
  431. };
  432. #endif