You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

580 lines
21 KiB

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