cmSystemTools.h 22 KB

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