cmSystemTools.h 18 KB

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