cmSystemTools.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #pragma once
  4. #include "cmConfigure.h" // IWYU pragma: keep
  5. #include <cstddef>
  6. #include <functional>
  7. #include <string>
  8. #include <vector>
  9. #include <cm/string_view>
  10. #include "cmsys/Process.h"
  11. #include "cmsys/Status.hxx" // IWYU pragma: export
  12. #include "cmsys/SystemTools.hxx" // IWYU pragma: export
  13. #include "cmCryptoHash.h"
  14. #include "cmDuration.h"
  15. #include "cmProcessOutput.h"
  16. struct cmMessageMetadata;
  17. /** \class cmSystemTools
  18. * \brief A collection of useful functions for CMake.
  19. *
  20. * cmSystemTools is a class that provides helper functions
  21. * for the CMake build system.
  22. */
  23. class cmSystemTools : public cmsys::SystemTools
  24. {
  25. public:
  26. using Superclass = cmsys::SystemTools;
  27. using Encoding = cmProcessOutput::Encoding;
  28. /**
  29. * Look for and replace registry values in a string
  30. */
  31. static void ExpandRegistryValues(std::string& source,
  32. KeyWOW64 view = KeyWOW64_Default);
  33. /** Map help document name to file name. */
  34. static std::string HelpFileName(cm::string_view);
  35. using MessageCallback =
  36. std::function<void(const std::string&, const cmMessageMetadata&)>;
  37. /**
  38. * Set the function used by GUIs to display error messages
  39. * Function gets passed: message as a const char*,
  40. * title as a const char*.
  41. */
  42. static void SetMessageCallback(MessageCallback f);
  43. /**
  44. * Display an error message.
  45. */
  46. static void Error(const std::string& m);
  47. /**
  48. * Display a message.
  49. */
  50. static void Message(const std::string& m, const char* title = nullptr);
  51. static void Message(const std::string& m, const cmMessageMetadata& md);
  52. using OutputCallback = std::function<void(std::string const&)>;
  53. //! Send a string to stdout
  54. static void Stdout(const std::string& s);
  55. static void SetStdoutCallback(OutputCallback f);
  56. //! Send a string to stderr
  57. static void Stderr(const std::string& s);
  58. static void SetStderrCallback(OutputCallback f);
  59. using InterruptCallback = std::function<bool()>;
  60. static void SetInterruptCallback(InterruptCallback f);
  61. static bool GetInterruptFlag();
  62. //! Return true if there was an error at any point.
  63. static bool GetErrorOccuredFlag()
  64. {
  65. return cmSystemTools::s_ErrorOccured ||
  66. cmSystemTools::s_FatalErrorOccured || GetInterruptFlag();
  67. }
  68. //! If this is set to true, cmake stops processing commands.
  69. static void SetFatalErrorOccured()
  70. {
  71. cmSystemTools::s_FatalErrorOccured = true;
  72. }
  73. static void SetErrorOccured() { cmSystemTools::s_ErrorOccured = true; }
  74. //! Return true if there was an error at any point.
  75. static bool GetFatalErrorOccured()
  76. {
  77. return cmSystemTools::s_FatalErrorOccured || GetInterruptFlag();
  78. }
  79. //! Set the error occurred flag and fatal error back to false
  80. static void ResetErrorOccuredFlag()
  81. {
  82. cmSystemTools::s_FatalErrorOccured = false;
  83. cmSystemTools::s_ErrorOccured = false;
  84. }
  85. //! Return true if the path is a framework
  86. static bool IsPathToFramework(const std::string& path);
  87. //! Return true if the path is a macOS non-framework shared library (aka
  88. //! .dylib)
  89. static bool IsPathToMacOSSharedLibrary(const std::string& path);
  90. static bool DoesFileExistWithExtensions(
  91. const std::string& name, const std::vector<std::string>& sourceExts);
  92. /**
  93. * Check if the given file exists in one of the parent directory of the
  94. * given file or directory and if it does, return the name of the file.
  95. * Toplevel specifies the top-most directory to where it will look.
  96. */
  97. static std::string FileExistsInParentDirectories(
  98. const std::string& fname, const std::string& directory,
  99. const std::string& toplevel);
  100. static void Glob(const std::string& directory, const std::string& regexp,
  101. std::vector<std::string>& files);
  102. static void GlobDirs(const std::string& fullPath,
  103. std::vector<std::string>& files);
  104. /**
  105. * Try to find a list of files that match the "simple" globbing
  106. * expression. At this point in time the globbing expressions have
  107. * to be in form: /directory/partial_file_name*. The * character has
  108. * to be at the end of the string and it does not support ?
  109. * []... The optional argument type specifies what kind of files you
  110. * want to find. 0 means all files, -1 means directories, 1 means
  111. * files only. This method returns true if search was successful.
  112. */
  113. static bool SimpleGlob(const std::string& glob,
  114. std::vector<std::string>& files, int type = 0);
  115. enum class CopyWhen
  116. {
  117. Always,
  118. OnlyIfDifferent,
  119. };
  120. enum class CopyResult
  121. {
  122. Success,
  123. Failure,
  124. };
  125. /** Copy a file. */
  126. static bool CopySingleFile(const std::string& oldname,
  127. const std::string& newname);
  128. static CopyResult CopySingleFile(std::string const& oldname,
  129. std::string const& newname, CopyWhen when,
  130. std::string* err = nullptr);
  131. enum class Replace
  132. {
  133. Yes,
  134. No,
  135. };
  136. enum class RenameResult
  137. {
  138. Success,
  139. NoReplace,
  140. Failure,
  141. };
  142. /** Rename a file or directory within a single disk volume (atomic
  143. if possible). */
  144. static bool RenameFile(const std::string& oldname,
  145. const std::string& newname);
  146. static RenameResult RenameFile(std::string const& oldname,
  147. std::string const& newname, Replace replace,
  148. std::string* err = nullptr);
  149. //! Rename a file if contents are different, delete the source otherwise
  150. static void MoveFileIfDifferent(const std::string& source,
  151. const std::string& destination);
  152. //! Compute the hash of a file
  153. static std::string ComputeFileHash(const std::string& source,
  154. cmCryptoHash::Algo algo);
  155. /** Compute the md5sum of a string. */
  156. static std::string ComputeStringMD5(const std::string& input);
  157. //! Get the SHA thumbprint for a certificate file
  158. static std::string ComputeCertificateThumbprint(const std::string& source);
  159. /**
  160. * Run a single executable command
  161. *
  162. * Output is controlled with outputflag. If outputflag is OUTPUT_NONE, no
  163. * user-viewable output from the program being run will be generated.
  164. * OUTPUT_MERGE is the legacy behavior where stdout and stderr are merged
  165. * into stdout. OUTPUT_FORWARD copies the output to stdout/stderr as
  166. * it was received. OUTPUT_PASSTHROUGH passes through the original handles.
  167. *
  168. * If timeout is specified, the command will be terminated after
  169. * timeout expires. Timeout is specified in seconds.
  170. *
  171. * Argument retVal should be a pointer to the location where the
  172. * exit code will be stored. If the retVal is not specified and
  173. * the program exits with a code other than 0, then the this
  174. * function will return false.
  175. *
  176. * If the command has spaces in the path the caller MUST call
  177. * cmSystemTools::ConvertToRunCommandPath on the command before passing
  178. * it into this function or it will not work. The command must be correctly
  179. * escaped for this to with spaces.
  180. */
  181. enum OutputOption
  182. {
  183. OUTPUT_NONE = 0,
  184. OUTPUT_MERGE,
  185. OUTPUT_FORWARD,
  186. OUTPUT_PASSTHROUGH
  187. };
  188. static bool RunSingleCommand(const std::string& command,
  189. std::string* captureStdOut = nullptr,
  190. std::string* captureStdErr = nullptr,
  191. int* retVal = nullptr,
  192. const char* dir = nullptr,
  193. OutputOption outputflag = OUTPUT_MERGE,
  194. cmDuration timeout = cmDuration::zero());
  195. /**
  196. * In this version of RunSingleCommand, command[0] should be
  197. * the command to run, and each argument to the command should
  198. * be in command[1]...command[command.size()]
  199. */
  200. static bool RunSingleCommand(std::vector<std::string> const& command,
  201. std::string* captureStdOut = nullptr,
  202. std::string* captureStdErr = nullptr,
  203. int* retVal = nullptr,
  204. const char* dir = nullptr,
  205. OutputOption outputflag = OUTPUT_MERGE,
  206. cmDuration timeout = cmDuration::zero(),
  207. Encoding encoding = cmProcessOutput::Auto);
  208. static std::string PrintSingleCommand(std::vector<std::string> const&);
  209. /**
  210. * Parse arguments out of a single string command
  211. */
  212. static std::vector<std::string> ParseArguments(const std::string& 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. /** Split a command-line string into the parsed command and the unparsed
  220. arguments. Returns false on unfinished quoting or escaping. */
  221. static bool SplitProgramFromArgs(std::string const& command,
  222. std::string& program, std::string& args);
  223. /**
  224. * Handle response file in an argument list and return a new argument list
  225. * **/
  226. static std::vector<std::string> HandleResponseFile(
  227. std::vector<std::string>::const_iterator argBeg,
  228. std::vector<std::string>::const_iterator argEnd);
  229. static size_t CalculateCommandLineLengthLimit();
  230. static void DisableRunCommandOutput() { s_DisableRunCommandOutput = true; }
  231. static void EnableRunCommandOutput() { s_DisableRunCommandOutput = false; }
  232. static bool GetRunCommandOutput() { return s_DisableRunCommandOutput; }
  233. enum CompareOp
  234. {
  235. OP_EQUAL = 1,
  236. OP_LESS = 2,
  237. OP_GREATER = 4,
  238. OP_LESS_EQUAL = OP_LESS | OP_EQUAL,
  239. OP_GREATER_EQUAL = OP_GREATER | OP_EQUAL
  240. };
  241. /**
  242. * Compare versions
  243. */
  244. static bool VersionCompare(CompareOp op, const std::string& lhs,
  245. const std::string& rhs);
  246. static bool VersionCompare(CompareOp op, const std::string& lhs,
  247. const char rhs[]);
  248. static bool VersionCompareEqual(std::string const& lhs,
  249. std::string const& rhs);
  250. static bool VersionCompareGreater(std::string const& lhs,
  251. std::string const& rhs);
  252. static bool VersionCompareGreaterEq(std::string const& lhs,
  253. std::string const& rhs);
  254. /**
  255. * Compare two ASCII strings using natural versioning order.
  256. * Non-numerical characters are compared directly.
  257. * Numerical characters are first globbed such that, e.g.
  258. * `test000 < test01 < test0 < test1 < test10`.
  259. * Return a value less than, equal to, or greater than zero if lhs
  260. * precedes, equals, or succeeds rhs in the defined ordering.
  261. */
  262. static int strverscmp(std::string const& lhs, std::string const& rhs);
  263. /** Windows if this is true, the CreateProcess in RunCommand will
  264. * not show new console windows when running programs.
  265. */
  266. static void SetRunCommandHideConsole(bool v) { s_RunCommandHideConsole = v; }
  267. static bool GetRunCommandHideConsole() { return s_RunCommandHideConsole; }
  268. /** Call cmSystemTools::Error with the message m, plus the
  269. * result of strerror(errno)
  270. */
  271. static void ReportLastSystemError(const char* m);
  272. /** a general output handler for cmsysProcess */
  273. static int WaitForLine(cmsysProcess* process, std::string& line,
  274. cmDuration timeout, std::vector<char>& out,
  275. std::vector<char>& err);
  276. static void SetForceUnixPaths(bool v) { s_ForceUnixPaths = v; }
  277. static bool GetForceUnixPaths() { return s_ForceUnixPaths; }
  278. // ConvertToOutputPath use s_ForceUnixPaths
  279. static std::string ConvertToOutputPath(std::string const& path);
  280. static void ConvertToOutputSlashes(std::string& path);
  281. // ConvertToRunCommandPath does not use s_ForceUnixPaths and should
  282. // be used when RunCommand is called from cmake, because the
  283. // running cmake needs paths to be in its format
  284. static std::string ConvertToRunCommandPath(const std::string& path);
  285. /**
  286. * For windows computes the long path for the given path,
  287. * For Unix, it is a noop
  288. */
  289. static void ConvertToLongPath(std::string& path);
  290. /** compute the relative path from local to remote. local must
  291. be a directory. remote can be a file or a directory.
  292. Both remote and local must be full paths. Basically, if
  293. you are in directory local and you want to access the file in remote
  294. what is the relative path to do that. For example:
  295. /a/b/c/d to /a/b/c1/d1 -> ../../c1/d1
  296. from /usr/src to /usr/src/test/blah/foo.cpp -> test/blah/foo.cpp
  297. */
  298. static std::string RelativePath(std::string const& local,
  299. std::string const& remote);
  300. /**
  301. * Convert the given remote path to a relative path with respect to
  302. * the given local path. Both paths must use forward slashes and not
  303. * already be escaped or quoted.
  304. */
  305. static std::string ForceToRelativePath(std::string const& local_path,
  306. std::string const& remote_path);
  307. /**
  308. * Express the 'in' path relative to 'top' if it does not start in '../'.
  309. */
  310. static std::string RelativeIfUnder(std::string const& top,
  311. std::string const& in);
  312. #ifndef CMAKE_BOOTSTRAP
  313. /** Remove an environment variable */
  314. static bool UnsetEnv(const char* value);
  315. /** Get the list of all environment variables */
  316. static std::vector<std::string> GetEnvironmentVariables();
  317. /** Append multiple variables to the current environment. */
  318. static void AppendEnv(std::vector<std::string> const& env);
  319. /** Helper class to save and restore the environment.
  320. Instantiate this class as an automatic variable on
  321. the stack. Its constructor saves a copy of the current
  322. environment and then its destructor restores the
  323. original environment. */
  324. class SaveRestoreEnvironment
  325. {
  326. public:
  327. SaveRestoreEnvironment();
  328. ~SaveRestoreEnvironment();
  329. SaveRestoreEnvironment(SaveRestoreEnvironment const&) = delete;
  330. SaveRestoreEnvironment& operator=(SaveRestoreEnvironment const&) = delete;
  331. private:
  332. std::vector<std::string> Env;
  333. };
  334. #endif
  335. /** Setup the environment to enable VS 8 IDE output. */
  336. static void EnableVSConsoleOutput();
  337. enum cmTarAction
  338. {
  339. TarActionCreate,
  340. TarActionList,
  341. TarActionExtract,
  342. TarActionNone
  343. };
  344. /** Create tar */
  345. enum cmTarCompression
  346. {
  347. TarCompressGZip,
  348. TarCompressBZip2,
  349. TarCompressXZ,
  350. TarCompressZstd,
  351. TarCompressNone
  352. };
  353. static bool ListTar(const std::string& outFileName,
  354. const std::vector<std::string>& files, bool verbose);
  355. static bool CreateTar(const std::string& outFileName,
  356. const std::vector<std::string>& files,
  357. cmTarCompression compressType, bool verbose,
  358. std::string const& mtime = std::string(),
  359. std::string const& format = std::string(),
  360. int compressionLevel = 0);
  361. static bool ExtractTar(const std::string& inFileName,
  362. const std::vector<std::string>& files, bool verbose);
  363. // This should be called first thing in main
  364. // it will keep child processes from inheriting the
  365. // stdin and stdout of this process. This is important
  366. // if you want to be able to kill child processes and
  367. // not get stuck waiting for all the output on the pipes.
  368. static void DoNotInheritStdPipes();
  369. static void EnsureStdPipes();
  370. /** Random seed generation. */
  371. static unsigned int RandomSeed();
  372. /** Find the directory containing CMake executables. */
  373. static void FindCMakeResources(const char* argv0);
  374. /** Get the CMake resource paths, after FindCMakeResources. */
  375. static std::string const& GetCTestCommand();
  376. static std::string const& GetCPackCommand();
  377. static std::string const& GetCMakeCommand();
  378. static std::string const& GetCMakeGUICommand();
  379. static std::string const& GetCMakeCursesCommand();
  380. static std::string const& GetCMClDepsCommand();
  381. static std::string const& GetCMakeRoot();
  382. static std::string const& GetHTMLDoc();
  383. /** Get the CWD mapped through the KWSys translation map. */
  384. static std::string GetCurrentWorkingDirectory();
  385. /** Echo a message in color using KWSys's Terminal cprintf. */
  386. static void MakefileColorEcho(int color, const char* message, bool newLine,
  387. bool enabled);
  388. /** Try to guess the soname of a shared library. */
  389. static bool GuessLibrarySOName(std::string const& fullPath,
  390. std::string& soname);
  391. /** Try to guess the install name of a shared library. */
  392. static bool GuessLibraryInstallName(std::string const& fullPath,
  393. std::string& soname);
  394. /** Try to change the RPATH in an ELF binary. */
  395. static bool ChangeRPath(std::string const& file, std::string const& oldRPath,
  396. std::string const& newRPath,
  397. bool removeEnvironmentRPath,
  398. std::string* emsg = nullptr,
  399. bool* changed = nullptr);
  400. /** Try to set the RPATH in an ELF binary. */
  401. static bool SetRPath(std::string const& file, std::string const& newRPath,
  402. std::string* emsg = nullptr, bool* changed = nullptr);
  403. /** Try to remove the RPATH from an ELF binary. */
  404. static bool RemoveRPath(std::string const& file, std::string* emsg = nullptr,
  405. bool* removed = nullptr);
  406. /** Check whether the RPATH in an ELF binary contains the path
  407. given. */
  408. static bool CheckRPath(std::string const& file, std::string const& newRPath);
  409. /** Remove a directory; repeat a few times in case of locked files. */
  410. static bool RepeatedRemoveDirectory(const std::string& dir);
  411. /** Encode a string as a URL. */
  412. static std::string EncodeURL(std::string const& in,
  413. bool escapeSlashes = true);
  414. #ifdef _WIN32
  415. struct WindowsFileRetry
  416. {
  417. unsigned int Count;
  418. unsigned int Delay;
  419. };
  420. static WindowsFileRetry GetWindowsFileRetry();
  421. static WindowsFileRetry GetWindowsDirectoryRetry();
  422. #endif
  423. /** Get the real path for a given path, removing all symlinks.
  424. This variant of GetRealPath also works on Windows but will
  425. resolve subst drives too. */
  426. static std::string GetRealPathResolvingWindowsSubst(
  427. const std::string& path, std::string* errorMessage = nullptr);
  428. /** Perform one-time initialization of libuv. */
  429. static void InitializeLibUV();
  430. /** Create a symbolic link if the platform supports it. Returns whether
  431. creation succeeded. */
  432. static cmsys::Status CreateSymlink(std::string const& origName,
  433. std::string const& newName,
  434. std::string* errorMessage = nullptr);
  435. /** Create a hard link if the platform supports it. Returns whether
  436. creation succeeded. */
  437. static cmsys::Status CreateLink(std::string const& origName,
  438. std::string const& newName,
  439. std::string* errorMessage = nullptr);
  440. /** Get the system name. */
  441. static cm::string_view GetSystemName();
  442. private:
  443. static bool s_ForceUnixPaths;
  444. static bool s_RunCommandHideConsole;
  445. static bool s_ErrorOccured;
  446. static bool s_FatalErrorOccured;
  447. static bool s_DisableRunCommandOutput;
  448. };