cmSystemTools.h 20 KB

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