cmSystemTools.h 20 KB

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