cmSystemTools.h 21 KB

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