cmSystemTools.h 22 KB

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