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.

2452 lines
79 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
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmcmd.h"
  4. #include <cmext/algorithm>
  5. #include <cm3p/uv.h>
  6. #include <fcntl.h>
  7. #include "cmConsoleBuf.h"
  8. #include "cmDuration.h"
  9. #include "cmGlobalGenerator.h"
  10. #include "cmLocalGenerator.h"
  11. #include "cmMakefile.h"
  12. #include "cmQtAutoMocUic.h"
  13. #include "cmQtAutoRcc.h"
  14. #include "cmRange.h"
  15. #include "cmState.h"
  16. #include "cmStateDirectory.h"
  17. #include "cmStateSnapshot.h"
  18. #include "cmStringAlgorithms.h"
  19. #include "cmSystemTools.h"
  20. #include "cmTransformDepfile.h"
  21. #include "cmUVProcessChain.h"
  22. #include "cmUtils.hxx"
  23. #include "cmValue.h"
  24. #include "cmVersion.h"
  25. #include "cmake.h"
  26. #if !defined(CMAKE_BOOTSTRAP)
  27. # include "cmDependsFortran.h" // For -E cmake_copy_f90_mod callback.
  28. # include "cmFileTime.h"
  29. # include "bindexplib.h"
  30. #endif
  31. #if !defined(CMAKE_BOOTSTRAP) || defined(CMAKE_BOOTSTRAP_MAKEFILES)
  32. # include <algorithm>
  33. # include "cmCMakePath.h"
  34. # include "cmProcessTools.h"
  35. #endif
  36. #if !defined(CMAKE_BOOTSTRAP) && defined(_WIN32) && !defined(__CYGWIN__)
  37. # include "cmVisualStudioWCEPlatformParser.h"
  38. #endif
  39. #include <array>
  40. #include <cstdio>
  41. #include <cstdlib>
  42. #include <cstring>
  43. #include <ctime>
  44. #include <iostream>
  45. #include <memory>
  46. #include <sstream>
  47. #include <utility>
  48. #ifdef _WIN32
  49. # include <fcntl.h> // for _O_BINARY
  50. # include <io.h> // for _setmode
  51. #endif
  52. #include <cm/string_view>
  53. #include "cmsys/Directory.hxx"
  54. #include "cmsys/FStream.hxx"
  55. #include "cmsys/Process.h"
  56. #include "cmsys/RegularExpression.hxx"
  57. #include "cmsys/Terminal.h"
  58. int cmcmd_cmake_ninja_depends(std::vector<std::string>::const_iterator argBeg,
  59. std::vector<std::string>::const_iterator argEnd);
  60. int cmcmd_cmake_ninja_dyndep(std::vector<std::string>::const_iterator argBeg,
  61. std::vector<std::string>::const_iterator argEnd);
  62. namespace {
  63. void CMakeCommandUsage(std::string const& program)
  64. {
  65. std::ostringstream errorStream;
  66. #ifndef CMAKE_BOOTSTRAP
  67. /* clang-format off */
  68. errorStream
  69. << "cmake version " << cmVersion::GetCMakeVersion() << "\n";
  70. /* clang-format on */
  71. #else
  72. /* clang-format off */
  73. errorStream
  74. << "cmake bootstrap\n";
  75. /* clang-format on */
  76. #endif
  77. // If you add new commands, change here,
  78. // and in cmakemain.cxx in the options table
  79. /* clang-format off */
  80. errorStream
  81. << "Usage: " << program << " -E <command> [arguments...]\n"
  82. << "Available commands: \n"
  83. << " capabilities - Report capabilities built into cmake "
  84. "in JSON format\n"
  85. << " cat [--] <files>... - concat the files and print them to the "
  86. "standard output\n"
  87. << " chdir dir cmd [args...] - run command in a given directory\n"
  88. << " compare_files [--ignore-eol] file1 file2\n"
  89. << " - check if file1 is same as file2\n"
  90. << " copy <file>... destination - copy files to destination "
  91. "(either file or directory)\n"
  92. << " copy_directory <dir>... destination - copy content of <dir>... "
  93. "directories to 'destination' directory\n"
  94. << " copy_if_different <file>... destination - copy files if it has "
  95. "changed\n"
  96. << " echo [<string>...] - displays arguments as text\n"
  97. << " echo_append [<string>...] - displays arguments as text but no new "
  98. "line\n"
  99. << " env [--unset=NAME ...] [NAME=VALUE ...] [--] <command> [<arg>...]\n"
  100. << " - run command in a modified environment\n"
  101. << " environment - display the current environment\n"
  102. << " make_directory <dir>... - create parent and <dir> directories\n"
  103. << " md5sum <file>... - create MD5 checksum of files\n"
  104. << " sha1sum <file>... - create SHA1 checksum of files\n"
  105. << " sha224sum <file>... - create SHA224 checksum of files\n"
  106. << " sha256sum <file>... - create SHA256 checksum of files\n"
  107. << " sha384sum <file>... - create SHA384 checksum of files\n"
  108. << " sha512sum <file>... - create SHA512 checksum of files\n"
  109. << " remove [-f] <file>... - remove the file(s), use -f to force "
  110. "it (deprecated: use rm instead)\n"
  111. << " remove_directory <dir>... - remove directories and their contents (deprecated: use rm instead)\n"
  112. << " rename oldname newname - rename a file or directory "
  113. "(on one volume)\n"
  114. << " rm [-rRf] [--] <file/dir>... - remove files or directories, use -f "
  115. "to force it, r or R to remove directories and their contents "
  116. "recursively\n"
  117. << " sleep <number>... - sleep for given number of seconds\n"
  118. << " tar [cxt][vf][zjJ] file.tar [file/dir1 file/dir2 ...]\n"
  119. << " - create or extract a tar or zip archive\n"
  120. << " time command [args...] - run command and display elapsed time\n"
  121. << " touch <file>... - touch a <file>.\n"
  122. << " touch_nocreate <file>... - touch a <file> but do not create it.\n"
  123. << " create_symlink old new - create a symbolic link new -> old\n"
  124. << " create_hardlink old new - create a hard link new -> old\n"
  125. << " true - do nothing with an exit code of 0\n"
  126. << " false - do nothing with an exit code of 1\n"
  127. #if defined(_WIN32) && !defined(__CYGWIN__)
  128. << "Available on Windows only:\n"
  129. << " delete_regv key - delete registry value\n"
  130. << " env_vs8_wince sdkname - displays a batch file which sets the "
  131. "environment for the provided Windows CE SDK installed in VS2005\n"
  132. << " env_vs9_wince sdkname - displays a batch file which sets the "
  133. "environment for the provided Windows CE SDK installed in VS2008\n"
  134. << " write_regv key value - write registry value\n"
  135. #endif
  136. ;
  137. /* clang-format on */
  138. cmSystemTools::Error(errorStream.str());
  139. }
  140. bool cmTarFilesFrom(std::string const& file, std::vector<std::string>& files)
  141. {
  142. if (cmSystemTools::FileIsDirectory(file)) {
  143. std::ostringstream e;
  144. e << "-E tar --files-from= file '" << file << "' is a directory";
  145. cmSystemTools::Error(e.str());
  146. return false;
  147. }
  148. cmsys::ifstream fin(file.c_str());
  149. if (!fin) {
  150. std::ostringstream e;
  151. e << "-E tar --files-from= file '" << file << "' not found";
  152. cmSystemTools::Error(e.str());
  153. return false;
  154. }
  155. std::string line;
  156. while (cmSystemTools::GetLineFromStream(fin, line)) {
  157. if (line.empty()) {
  158. continue;
  159. }
  160. if (cmHasLiteralPrefix(line, "--add-file=")) {
  161. files.push_back(line.substr(11));
  162. } else if (cmHasLiteralPrefix(line, "-")) {
  163. std::ostringstream e;
  164. e << "-E tar --files-from='" << file << "' file invalid line:\n"
  165. << line << "\n";
  166. cmSystemTools::Error(e.str());
  167. return false;
  168. } else {
  169. files.push_back(line);
  170. }
  171. }
  172. return true;
  173. }
  174. void cmCatFile(const std::string& fileToAppend)
  175. {
  176. #ifdef _WIN32
  177. _setmode(fileno(stdout), _O_BINARY);
  178. #endif
  179. cmsys::ifstream source(fileToAppend.c_str(),
  180. (std::ios::binary | std::ios::in));
  181. std::cout << source.rdbuf();
  182. }
  183. bool cmRemoveDirectory(const std::string& dir, bool recursive = true)
  184. {
  185. if (cmSystemTools::FileIsSymlink(dir)) {
  186. if (!cmSystemTools::RemoveFile(dir)) {
  187. std::cerr << "Error removing directory symlink \"" << dir << "\".\n";
  188. return false;
  189. }
  190. } else if (!recursive) {
  191. std::cerr << "Error removing directory \"" << dir
  192. << "\" without recursive option.\n";
  193. return false;
  194. } else if (!cmSystemTools::RemoveADirectory(dir)) {
  195. std::cerr << "Error removing directory \"" << dir << "\".\n";
  196. return false;
  197. }
  198. return true;
  199. }
  200. #if !defined(CMAKE_BOOTSTRAP) || defined(CMAKE_BOOTSTRAP_MAKEFILES)
  201. class CLIncludeParser : public cmProcessTools::LineParser
  202. {
  203. public:
  204. CLIncludeParser(cm::string_view includePrefix, cmsys::ofstream& depFile,
  205. std::ostream& output)
  206. : IncludePrefix(includePrefix)
  207. , DepFile(depFile)
  208. , Output(output)
  209. {
  210. }
  211. private:
  212. bool ProcessLine() override
  213. {
  214. if (cmHasPrefix(this->Line, this->IncludePrefix)) {
  215. auto path =
  216. cmTrimWhitespace(this->Line.c_str() + this->IncludePrefix.size());
  217. cmSystemTools::ConvertToLongPath(path);
  218. this->DepFile << cmCMakePath(path).GenericString() << std::endl;
  219. } else {
  220. this->Output << this->Line << std::endl << std::flush;
  221. }
  222. return true;
  223. }
  224. cm::string_view IncludePrefix;
  225. cmsys::ofstream& DepFile;
  226. std::ostream& Output;
  227. };
  228. class CLOutputLogger : public cmProcessTools::OutputLogger
  229. {
  230. public:
  231. CLOutputLogger(std::ostream& log)
  232. : cmProcessTools::OutputLogger(log)
  233. {
  234. }
  235. bool ProcessLine() override
  236. {
  237. *this->Log << std::flush;
  238. return true;
  239. }
  240. };
  241. int CLCompileAndDependencies(const std::vector<std::string>& args)
  242. {
  243. std::string depFile;
  244. std::string currentBinaryDir;
  245. std::string filterPrefix;
  246. std::vector<std::string> command;
  247. for (auto it = args.cbegin() + 2; it != args.cend(); it++) {
  248. if (cmHasLiteralPrefix(*it, "--dep-file=")) {
  249. depFile = it->substr(11);
  250. } else if (cmHasLiteralPrefix(*it, "--working-dir=")) {
  251. currentBinaryDir = it->substr(14);
  252. } else if (cmHasLiteralPrefix(*it, "--filter-prefix=")) {
  253. filterPrefix = it->substr(16);
  254. } else if (*it == "--") {
  255. command.insert(command.begin(), ++it, args.cend());
  256. break;
  257. } else {
  258. return 1;
  259. }
  260. }
  261. std::unique_ptr<cmsysProcess, void (*)(cmsysProcess*)> cp(
  262. cmsysProcess_New(), cmsysProcess_Delete);
  263. std::vector<const char*> argv(command.size() + 1);
  264. std::transform(command.begin(), command.end(), argv.begin(),
  265. [](std::string const& s) { return s.c_str(); });
  266. argv.back() = nullptr;
  267. cmsysProcess_SetCommand(cp.get(), argv.data());
  268. cmsysProcess_SetWorkingDirectory(cp.get(), currentBinaryDir.c_str());
  269. cmsys::ofstream fout(depFile.c_str());
  270. if (!fout) {
  271. return 3;
  272. }
  273. CLIncludeParser includeParser(filterPrefix, fout, std::cout);
  274. CLOutputLogger errLogger(std::cerr);
  275. // Start the process.
  276. cmProcessTools::RunProcess(cp.get(), &includeParser, &errLogger);
  277. int status = 0;
  278. // handle status of process
  279. switch (cmsysProcess_GetState(cp.get())) {
  280. case cmsysProcess_State_Exited:
  281. status = cmsysProcess_GetExitValue(cp.get());
  282. break;
  283. case cmsysProcess_State_Exception:
  284. status = 1;
  285. break;
  286. case cmsysProcess_State_Error:
  287. status = 2;
  288. break;
  289. default:
  290. break;
  291. }
  292. if (status != 0) {
  293. // remove the dependencies file because potentially invalid
  294. fout.close();
  295. cmSystemTools::RemoveFile(depFile);
  296. }
  297. return status;
  298. }
  299. #endif
  300. int HandleIWYU(const std::string& runCmd, const std::string& /* sourceFile */,
  301. const std::vector<std::string>& orig_cmd)
  302. {
  303. // Construct the iwyu command line by taking what was given
  304. // and adding all the arguments we give to the compiler.
  305. std::vector<std::string> iwyu_cmd = cmExpandedList(runCmd, true);
  306. cm::append(iwyu_cmd, orig_cmd.begin() + 1, orig_cmd.end());
  307. // Run the iwyu command line. Capture its stderr and hide its stdout.
  308. // Ignore its return code because the tool always returns non-zero.
  309. std::string stdErr;
  310. int ret;
  311. if (!cmSystemTools::RunSingleCommand(iwyu_cmd, nullptr, &stdErr, &ret,
  312. nullptr, cmSystemTools::OUTPUT_NONE)) {
  313. std::cerr << "Error running '" << iwyu_cmd[0] << "': " << stdErr << "\n";
  314. return 1;
  315. }
  316. // Warn if iwyu reported anything.
  317. if (stdErr.find("should remove these lines:") != std::string::npos ||
  318. stdErr.find("should add these lines:") != std::string::npos) {
  319. std::cerr << "Warning: include-what-you-use reported diagnostics:\n"
  320. << stdErr << "\n";
  321. }
  322. // always return 0 we don't want to break the compile
  323. return 0;
  324. }
  325. int HandleTidy(const std::string& runCmd, const std::string& sourceFile,
  326. const std::vector<std::string>& orig_cmd)
  327. {
  328. // Construct the clang-tidy command line by taking what was given
  329. // and adding our compiler command line. The clang-tidy tool will
  330. // automatically skip over the compiler itself and extract the
  331. // options.
  332. int ret;
  333. std::vector<std::string> tidy_cmd = cmExpandedList(runCmd, true);
  334. tidy_cmd.push_back(sourceFile);
  335. tidy_cmd.emplace_back("--");
  336. cm::append(tidy_cmd, orig_cmd);
  337. // Run the tidy command line. Capture its stdout and hide its stderr.
  338. std::string stdOut;
  339. std::string stdErr;
  340. if (!cmSystemTools::RunSingleCommand(tidy_cmd, &stdOut, &stdErr, &ret,
  341. nullptr, cmSystemTools::OUTPUT_NONE)) {
  342. std::cerr << "Error running '" << tidy_cmd[0] << "': " << stdErr << "\n";
  343. return 1;
  344. }
  345. // Output the stdout from clang-tidy to stderr
  346. std::cerr << stdOut;
  347. // If clang-tidy exited with an error do the same.
  348. if (ret != 0) {
  349. std::cerr << stdErr;
  350. }
  351. return ret;
  352. }
  353. int HandleLWYU(const std::string& runCmd, const std::string& sourceFile,
  354. const std::vector<std::string>&)
  355. {
  356. // Construct the ldd -r -u (link what you use lwyu) command line
  357. // ldd -u -r lwuy target
  358. std::vector<std::string> lwyu_cmd = cmExpandedList(runCmd, true);
  359. lwyu_cmd.push_back(sourceFile);
  360. // Run the lwyu check command line, currently ldd is expected.
  361. // Capture its stdout and hide its stderr.
  362. // Ignore its return code because the tool always returns non-zero
  363. // if there are any warnings, but we just want to warn.
  364. std::string stdOut;
  365. std::string stdErr;
  366. int ret;
  367. if (!cmSystemTools::RunSingleCommand(lwyu_cmd, &stdOut, &stdErr, &ret,
  368. nullptr, cmSystemTools::OUTPUT_NONE)) {
  369. std::cerr << "Error running '" << lwyu_cmd[0] << "': " << stdErr << "\n";
  370. return 1;
  371. }
  372. // Output the stdout from ldd -r -u to stderr
  373. // Warn if lwyu reported anything.
  374. if (stdOut.find("Unused direct dependencies:") != std::string::npos) {
  375. std::cerr << "Warning: " << stdOut;
  376. }
  377. return 0;
  378. }
  379. int HandleCppLint(const std::string& runCmd, const std::string& sourceFile,
  380. const std::vector<std::string>&)
  381. {
  382. // Construct the cpplint command line.
  383. std::vector<std::string> cpplint_cmd = cmExpandedList(runCmd, true);
  384. cpplint_cmd.push_back(sourceFile);
  385. // Run the cpplint command line. Capture its output.
  386. std::string stdOut;
  387. int ret;
  388. if (!cmSystemTools::RunSingleCommand(cpplint_cmd, &stdOut, &stdOut, &ret,
  389. nullptr, cmSystemTools::OUTPUT_NONE)) {
  390. std::cerr << "Error running '" << cpplint_cmd[0] << "': " << stdOut
  391. << "\n";
  392. return 1;
  393. }
  394. if (!stdOut.empty()) {
  395. std::cerr << "Warning: cpplint diagnostics:\n";
  396. // Output the output from cpplint to stderr
  397. std::cerr << stdOut;
  398. }
  399. // always return 0 so the build can continue as cpplint returns non-zero
  400. // for any warning
  401. return 0;
  402. }
  403. int HandleCppCheck(const std::string& runCmd, const std::string& sourceFile,
  404. const std::vector<std::string>& orig_cmd)
  405. {
  406. // Construct the cpplint command line.
  407. std::vector<std::string> cppcheck_cmd = cmExpandedList(runCmd, true);
  408. // extract all the -D, -U, and -I options from the compile line
  409. for (auto const& opt : orig_cmd) {
  410. if (opt.size() > 2) {
  411. if ((opt[0] == '-') &&
  412. ((opt[1] == 'D') || (opt[1] == 'I') || (opt[1] == 'U'))) {
  413. cppcheck_cmd.push_back(opt);
  414. // convert cl / options to - options if needed
  415. #if defined(_WIN32)
  416. } else if ((opt[0] == '/') &&
  417. ((opt[1] == 'D') || (opt[1] == 'I') || (opt[1] == 'U'))) {
  418. std::string optcopy = opt;
  419. optcopy[0] = '-';
  420. cppcheck_cmd.push_back(optcopy);
  421. #endif
  422. }
  423. }
  424. }
  425. // add the source file
  426. cppcheck_cmd.push_back(sourceFile);
  427. // Run the cpplint command line. Capture its output.
  428. std::string stdOut;
  429. std::string stdErr;
  430. int ret;
  431. if (!cmSystemTools::RunSingleCommand(cppcheck_cmd, &stdOut, &stdErr, &ret,
  432. nullptr, cmSystemTools::OUTPUT_NONE)) {
  433. std::cerr << "Error running '" << cppcheck_cmd[0] << "': " << stdOut
  434. << "\n";
  435. return 1;
  436. }
  437. std::cerr << stdOut;
  438. // Output the output from cpplint to stderr
  439. if (stdErr.find("(error)") != std::string::npos ||
  440. stdErr.find("(warning)") != std::string::npos ||
  441. stdErr.find("(style)") != std::string::npos ||
  442. stdErr.find("(performance)") != std::string::npos ||
  443. stdErr.find("(portability)") != std::string::npos ||
  444. stdErr.find("(information)") != std::string::npos) {
  445. if (ret == 0) {
  446. std::cerr << "Warning: cppcheck reported diagnostics:\n";
  447. } else {
  448. std::cerr << "Error: cppcheck reported failure:\n";
  449. }
  450. }
  451. std::cerr << stdErr;
  452. return ret;
  453. }
  454. using CoCompileHandler = int (*)(const std::string&, const std::string&,
  455. const std::vector<std::string>&);
  456. struct CoCompiler
  457. {
  458. const char* Option;
  459. CoCompileHandler Handler;
  460. bool NoOriginalCommand;
  461. };
  462. const std::array<CoCompiler, 5> CoCompilers = {
  463. { // Table of options and handlers.
  464. { "--cppcheck=", HandleCppCheck, false },
  465. { "--cpplint=", HandleCppLint, false },
  466. { "--iwyu=", HandleIWYU, false },
  467. { "--lwyu=", HandleLWYU, true },
  468. { "--tidy=", HandleTidy, false } }
  469. };
  470. struct CoCompileJob
  471. {
  472. std::string Command;
  473. CoCompileHandler Handler;
  474. };
  475. }
  476. // called when args[0] == "__run_co_compile"
  477. int cmcmd::HandleCoCompileCommands(std::vector<std::string> const& args)
  478. {
  479. std::vector<CoCompileJob> jobs;
  480. std::string sourceFile; // store --source=
  481. std::vector<std::string> launchers; // store --launcher=
  482. // Default is to run the original command found after -- if the option
  483. // does not need to do that, it should be specified here, currently only
  484. // lwyu does that.
  485. bool runOriginalCmd = true;
  486. std::vector<std::string> orig_cmd;
  487. bool doing_options = true;
  488. for (std::string const& arg : cmMakeRange(args).advance(2)) {
  489. // if the arg is -- then the rest of the args after
  490. // go into orig_cmd
  491. if (arg == "--") {
  492. doing_options = false;
  493. } else if (doing_options) {
  494. bool optionFound = false;
  495. for (CoCompiler const& cc : CoCompilers) {
  496. size_t optionLen = strlen(cc.Option);
  497. if (arg.compare(0, optionLen, cc.Option) == 0) {
  498. optionFound = true;
  499. CoCompileJob job;
  500. job.Command = arg.substr(optionLen);
  501. job.Handler = cc.Handler;
  502. jobs.push_back(std::move(job));
  503. if (cc.NoOriginalCommand) {
  504. runOriginalCmd = false;
  505. }
  506. }
  507. }
  508. if (!optionFound) {
  509. if (cmHasLiteralPrefix(arg, "--source=")) {
  510. sourceFile = arg.substr(9);
  511. } else if (cmHasLiteralPrefix(arg, "--launcher=")) {
  512. cmExpandList(arg.substr(11), launchers, true);
  513. } else {
  514. // if it was not a co-compiler or --source/--launcher then error
  515. std::cerr << "__run_co_compile given unknown argument: " << arg
  516. << "\n";
  517. return 1;
  518. }
  519. }
  520. } else { // if not doing_options then push to orig_cmd
  521. orig_cmd.push_back(arg);
  522. }
  523. }
  524. if (jobs.empty()) {
  525. std::cerr << "__run_co_compile missing command to run. "
  526. "Looking for one or more of the following:\n";
  527. for (CoCompiler const& cc : CoCompilers) {
  528. std::cerr << cc.Option << "\n";
  529. }
  530. return 1;
  531. }
  532. if (runOriginalCmd && orig_cmd.empty()) {
  533. std::cerr << "__run_co_compile missing compile command after --\n";
  534. return 1;
  535. }
  536. for (CoCompileJob const& job : jobs) {
  537. // call the command handler here
  538. int ret = job.Handler(job.Command, sourceFile, orig_cmd);
  539. // if the command returns non-zero then return and fail.
  540. // for commands that do not want to break the build, they should return
  541. // 0 no matter what.
  542. if (ret != 0) {
  543. return ret;
  544. }
  545. }
  546. // if there is no original command to run return now
  547. if (!runOriginalCmd) {
  548. return 0;
  549. }
  550. // Prepend launcher argument(s), if any
  551. if (!launchers.empty()) {
  552. orig_cmd.insert(orig_cmd.begin(), launchers.begin(), launchers.end());
  553. }
  554. // Now run the real compiler command and return its result value
  555. int ret;
  556. if (!cmSystemTools::RunSingleCommand(orig_cmd, nullptr, nullptr, &ret,
  557. nullptr,
  558. cmSystemTools::OUTPUT_PASSTHROUGH)) {
  559. std::cerr << "Error running '" << orig_cmd[0] << "'\n";
  560. return 1;
  561. }
  562. // return the return value from the original compiler command
  563. return ret;
  564. }
  565. int cmcmd::ExecuteCMakeCommand(std::vector<std::string> const& args,
  566. std::unique_ptr<cmConsoleBuf> consoleBuf)
  567. {
  568. // IF YOU ADD A NEW COMMAND, DOCUMENT IT ABOVE and in cmakemain.cxx
  569. if (args.size() > 1) {
  570. // Copy file
  571. if (args[1] == "copy" && args.size() > 3) {
  572. // If multiple source files specified,
  573. // then destination must be directory
  574. if ((args.size() > 4) &&
  575. (!cmSystemTools::FileIsDirectory(args.back()))) {
  576. std::cerr << "Error: Target (for copy command) \"" << args.back()
  577. << "\" is not a directory.\n";
  578. return 1;
  579. }
  580. // If error occurs we want to continue copying next files.
  581. bool return_value = false;
  582. for (auto const& arg : cmMakeRange(args).advance(2).retreat(1)) {
  583. if (!cmsys::SystemTools::CopyFileAlways(arg, args.back())) {
  584. std::cerr << "Error copying file \"" << arg << "\" to \""
  585. << args.back() << "\".\n";
  586. return_value = true;
  587. }
  588. }
  589. return return_value;
  590. }
  591. // Copy file if different.
  592. if (args[1] == "copy_if_different" && args.size() > 3) {
  593. // If multiple source files specified,
  594. // then destination must be directory
  595. if ((args.size() > 4) &&
  596. (!cmSystemTools::FileIsDirectory(args.back()))) {
  597. std::cerr << "Error: Target (for copy_if_different command) \""
  598. << args.back() << "\" is not a directory.\n";
  599. return 1;
  600. }
  601. // If error occurs we want to continue copying next files.
  602. bool return_value = false;
  603. for (auto const& arg : cmMakeRange(args).advance(2).retreat(1)) {
  604. if (!cmSystemTools::CopyFileIfDifferent(arg, args.back())) {
  605. std::cerr << "Error copying file (if different) from \"" << arg
  606. << "\" to \"" << args.back() << "\".\n";
  607. return_value = true;
  608. }
  609. }
  610. return return_value;
  611. }
  612. // Copy directory content
  613. if (args[1] == "copy_directory" && args.size() > 3) {
  614. // If error occurs we want to continue copying next files.
  615. bool return_value = false;
  616. for (auto const& arg : cmMakeRange(args).advance(2).retreat(1)) {
  617. if (!cmSystemTools::CopyADirectory(arg, args.back())) {
  618. std::cerr << "Error copying directory from \"" << arg << "\" to \""
  619. << args.back() << "\".\n";
  620. return_value = true;
  621. }
  622. }
  623. return return_value;
  624. }
  625. // Rename a file or directory
  626. if (args[1] == "rename" && args.size() == 4) {
  627. if (!cmSystemTools::RenameFile(args[2], args[3])) {
  628. std::string e = cmSystemTools::GetLastSystemError();
  629. std::cerr << "Error renaming from \"" << args[2] << "\" to \""
  630. << args[3] << "\": " << e << "\n";
  631. return 1;
  632. }
  633. return 0;
  634. }
  635. // Compare files
  636. if (args[1] == "compare_files" && (args.size() == 4 || args.size() == 5)) {
  637. bool filesDiffer;
  638. if (args.size() == 4) {
  639. filesDiffer = cmSystemTools::FilesDiffer(args[2], args[3]);
  640. } else if (args[2] == "--ignore-eol") {
  641. filesDiffer = cmsys::SystemTools::TextFilesDiffer(args[3], args[4]);
  642. } else {
  643. CMakeCommandUsage(args[0]);
  644. return 2;
  645. }
  646. if (filesDiffer) {
  647. return 1;
  648. }
  649. return 0;
  650. }
  651. #if !defined(CMAKE_BOOTSTRAP)
  652. if (args[1] == "__create_def") {
  653. if (args.size() < 4) {
  654. std::cerr << "__create_def Usage: -E __create_def outfile.def "
  655. "objlistfile [--nm=nm-path]\n";
  656. return 1;
  657. }
  658. cmsys::ifstream fin(args[3].c_str(), std::ios::in | std::ios::binary);
  659. if (!fin) {
  660. std::cerr << "could not open object list file: " << args[3] << "\n";
  661. return 1;
  662. }
  663. std::vector<std::string> files;
  664. {
  665. std::string file;
  666. cmFileTime outTime;
  667. bool outValid = outTime.Load(args[2]);
  668. while (cmSystemTools::GetLineFromStream(fin, file)) {
  669. files.push_back(file);
  670. if (outValid) {
  671. cmFileTime inTime;
  672. outValid = inTime.Load(file) && inTime.Older(outTime);
  673. }
  674. }
  675. if (outValid) {
  676. // The def file already exists and all input files are older than
  677. // the existing def file.
  678. return 0;
  679. }
  680. }
  681. FILE* fout = cmsys::SystemTools::Fopen(args[2], "w+");
  682. if (!fout) {
  683. std::cerr << "could not open output .def file: " << args[2] << "\n";
  684. return 1;
  685. }
  686. bindexplib deffile;
  687. if (args.size() >= 5) {
  688. std::string const& a = args[4];
  689. if (cmHasLiteralPrefix(a, "--nm=")) {
  690. deffile.SetNmPath(a.substr(5));
  691. } else {
  692. std::cerr << "unknown argument: " << a << "\n";
  693. }
  694. }
  695. for (std::string const& file : files) {
  696. std::string const& ext = cmSystemTools::GetFilenameLastExtension(file);
  697. if (cmSystemTools::LowerCase(ext) == ".def") {
  698. if (!deffile.AddDefinitionFile(file.c_str())) {
  699. return 1;
  700. }
  701. } else {
  702. if (!deffile.AddObjectFile(file.c_str())) {
  703. return 1;
  704. }
  705. }
  706. }
  707. deffile.WriteFile(fout);
  708. fclose(fout);
  709. return 0;
  710. }
  711. #endif
  712. if (args[1] == "__run_co_compile") {
  713. return cmcmd::HandleCoCompileCommands(args);
  714. }
  715. // Echo string
  716. if (args[1] == "echo") {
  717. std::cout << cmJoin(cmMakeRange(args).advance(2), " ") << std::endl;
  718. return 0;
  719. }
  720. // Echo string no new line
  721. if (args[1] == "echo_append") {
  722. std::cout << cmJoin(cmMakeRange(args).advance(2), " ");
  723. return 0;
  724. }
  725. if (args[1] == "env") {
  726. auto ai = args.cbegin() + 2;
  727. auto ae = args.cend();
  728. for (; ai != ae; ++ai) {
  729. std::string const& a = *ai;
  730. if (a == "--") {
  731. // Stop parsing options/environment variables; the next argument
  732. // should be the command.
  733. ++ai;
  734. break;
  735. }
  736. if (cmHasLiteralPrefix(a, "--unset=")) {
  737. // Unset environment variable.
  738. cmSystemTools::UnPutEnv(a.substr(8));
  739. } else if (!a.empty() && a[0] == '-') {
  740. // Environment variable and command names cannot start in '-',
  741. // so this must be an unknown option.
  742. std::cerr << "cmake -E env: unknown option '" << a << '\''
  743. << std::endl;
  744. return 1;
  745. } else if (a.find('=') != std::string::npos) {
  746. // Set environment variable.
  747. cmSystemTools::PutEnv(a);
  748. } else {
  749. // This is the beginning of the command.
  750. break;
  751. }
  752. }
  753. if (ai == ae) {
  754. std::cerr << "cmake -E env: no command given" << std::endl;
  755. return 1;
  756. }
  757. // Execute command from remaining arguments.
  758. std::vector<std::string> cmd(ai, ae);
  759. int retval;
  760. if (cmSystemTools::RunSingleCommand(cmd, nullptr, nullptr, &retval,
  761. nullptr,
  762. cmSystemTools::OUTPUT_PASSTHROUGH)) {
  763. return retval;
  764. }
  765. return 1;
  766. }
  767. #if !defined(CMAKE_BOOTSTRAP)
  768. if (args[1] == "environment") {
  769. for (auto const& env : cmSystemTools::GetEnvironmentVariables()) {
  770. std::cout << env << std::endl;
  771. }
  772. return 0;
  773. }
  774. #endif
  775. if (args[1] == "make_directory" && args.size() > 2) {
  776. // If an error occurs, we want to continue making directories.
  777. bool return_value = false;
  778. for (auto const& arg : cmMakeRange(args).advance(2)) {
  779. if (!cmSystemTools::MakeDirectory(arg)) {
  780. std::cerr << "Error creating directory \"" << arg << "\".\n";
  781. return_value = true;
  782. }
  783. }
  784. return return_value;
  785. }
  786. if (args[1] == "remove_directory" && args.size() > 2) {
  787. // If an error occurs, we want to continue removing directories.
  788. bool return_value = false;
  789. for (auto const& arg : cmMakeRange(args).advance(2)) {
  790. if (cmSystemTools::FileIsDirectory(arg)) {
  791. if (!cmRemoveDirectory(arg)) {
  792. return_value = true;
  793. }
  794. }
  795. }
  796. return return_value;
  797. }
  798. // Remove file
  799. if (args[1] == "remove" && args.size() > 2) {
  800. bool force = false;
  801. for (auto const& arg : cmMakeRange(args).advance(2)) {
  802. if (arg == "\\-f" || arg == "-f") {
  803. force = true;
  804. } else {
  805. // Complain if the file could not be removed, still exists,
  806. // and the -f option was not given.
  807. if (!cmSystemTools::RemoveFile(arg) && !force &&
  808. cmSystemTools::FileExists(arg)) {
  809. return 1;
  810. }
  811. }
  812. }
  813. return 0;
  814. }
  815. // Remove directories or files with rm
  816. if (args[1] == "rm" && args.size() > 2) {
  817. // If an error occurs, we want to continue removing the remaining
  818. // files/directories.
  819. int return_value = 0;
  820. bool force = false;
  821. bool recursive = false;
  822. bool doing_options = true;
  823. bool at_least_one_file = false;
  824. for (auto const& arg : cmMakeRange(args).advance(2)) {
  825. if (doing_options && cmHasLiteralPrefix(arg, "-")) {
  826. if (arg == "--") {
  827. doing_options = false;
  828. }
  829. if (arg.find('f') != std::string::npos) {
  830. force = true;
  831. }
  832. if (arg.find_first_of("rR") != std::string::npos) {
  833. recursive = true;
  834. }
  835. if (arg.find_first_not_of("-frR") != std::string::npos) {
  836. cmSystemTools::Error("Unknown -E rm argument: " + arg);
  837. return 1;
  838. }
  839. } else {
  840. if (arg.empty()) {
  841. continue;
  842. }
  843. at_least_one_file = true;
  844. // Complain if the -f option was not given and
  845. // either file does not exist or
  846. // file could not be removed and still exists
  847. bool file_exists_or_forced_remove = cmSystemTools::FileExists(arg) ||
  848. cmSystemTools::FileIsSymlink(arg) || force;
  849. if (cmSystemTools::FileIsDirectory(arg)) {
  850. if (!cmRemoveDirectory(arg, recursive)) {
  851. return_value = 1;
  852. }
  853. } else if ((!file_exists_or_forced_remove) ||
  854. (!cmSystemTools::RemoveFile(arg) &&
  855. cmSystemTools::FileExists(arg))) {
  856. if (!file_exists_or_forced_remove) {
  857. cmSystemTools::Error(
  858. "File to remove does not exist and force is not set: " + arg);
  859. } else {
  860. cmSystemTools::Error("File can't be removed and still exist: " +
  861. arg);
  862. }
  863. return_value = 1;
  864. }
  865. }
  866. }
  867. if (!at_least_one_file) {
  868. cmSystemTools::Error("Missing file/directory to remove");
  869. return 1;
  870. }
  871. return return_value;
  872. }
  873. // Touch file
  874. if (args[1] == "touch" && args.size() > 2) {
  875. for (auto const& arg : cmMakeRange(args).advance(2)) {
  876. if (!cmSystemTools::Touch(arg, true)) {
  877. std::cerr << "cmake -E touch: failed to update \"";
  878. std::cerr << arg << "\".\n";
  879. return 1;
  880. }
  881. }
  882. return 0;
  883. }
  884. // Touch file
  885. if (args[1] == "touch_nocreate" && args.size() > 2) {
  886. for (auto const& arg : cmMakeRange(args).advance(2)) {
  887. if (!cmSystemTools::Touch(arg, false)) {
  888. std::cerr << "cmake -E touch_nocreate: failed to update \"";
  889. std::cerr << arg << "\".\n";
  890. return 1;
  891. }
  892. }
  893. return 0;
  894. }
  895. // capabilities
  896. if (args[1] == "capabilities") {
  897. if (args.size() > 2) {
  898. std::cerr << "-E capabilities accepts no additional arguments\n";
  899. return 1;
  900. }
  901. cmake cm(cmake::RoleInternal, cmState::Unknown);
  902. std::cout << cm.ReportCapabilities();
  903. return 0;
  904. }
  905. // Sleep command
  906. if (args[1] == "sleep" && args.size() > 2) {
  907. double total = 0;
  908. for (auto const& arg : cmMakeRange(args).advance(2)) {
  909. double num = 0.0;
  910. char unit;
  911. char extra;
  912. int n = sscanf(arg.c_str(), "%lg%c%c", &num, &unit, &extra);
  913. if ((n == 1 || (n == 2 && unit == 's')) && num >= 0) {
  914. total += num;
  915. } else {
  916. std::cerr << "Unknown sleep time format \"" << arg << "\".\n";
  917. return 1;
  918. }
  919. }
  920. if (total > 0) {
  921. cmSystemTools::Delay(static_cast<unsigned int>(total * 1000));
  922. }
  923. return 0;
  924. }
  925. // Clock command
  926. if (args[1] == "time" && args.size() > 2) {
  927. std::vector<std::string> command(args.begin() + 2, args.end());
  928. clock_t clock_start;
  929. clock_t clock_finish;
  930. time_t time_start;
  931. time_t time_finish;
  932. time(&time_start);
  933. clock_start = clock();
  934. int ret = 0;
  935. cmSystemTools::RunSingleCommand(command, nullptr, nullptr, &ret);
  936. clock_finish = clock();
  937. time(&time_finish);
  938. double clocks_per_sec = static_cast<double>(CLOCKS_PER_SEC);
  939. std::cout << "Elapsed time: "
  940. << static_cast<long>(time_finish - time_start) << " s. (time)"
  941. << ", "
  942. << static_cast<double>(clock_finish - clock_start) /
  943. clocks_per_sec
  944. << " s. (clock)"
  945. << "\n";
  946. return ret;
  947. }
  948. // Command to calculate the md5sum of a file
  949. if (args[1] == "md5sum" && args.size() >= 3) {
  950. return HashSumFile(args, cmCryptoHash::AlgoMD5);
  951. }
  952. // Command to calculate the sha1sum of a file
  953. if (args[1] == "sha1sum" && args.size() >= 3) {
  954. return HashSumFile(args, cmCryptoHash::AlgoSHA1);
  955. }
  956. if (args[1] == "sha224sum" && args.size() >= 3) {
  957. return HashSumFile(args, cmCryptoHash::AlgoSHA224);
  958. }
  959. if (args[1] == "sha256sum" && args.size() >= 3) {
  960. return HashSumFile(args, cmCryptoHash::AlgoSHA256);
  961. }
  962. if (args[1] == "sha384sum" && args.size() >= 3) {
  963. return HashSumFile(args, cmCryptoHash::AlgoSHA384);
  964. }
  965. if (args[1] == "sha512sum" && args.size() >= 3) {
  966. return HashSumFile(args, cmCryptoHash::AlgoSHA512);
  967. }
  968. // Command to concat files into one
  969. if (args[1] == "cat" && args.size() >= 3) {
  970. int return_value = 0;
  971. bool doing_options = true;
  972. for (auto const& arg : cmMakeRange(args).advance(2)) {
  973. if (doing_options && cmHasLiteralPrefix(arg, "-")) {
  974. if (arg == "--") {
  975. doing_options = false;
  976. } else {
  977. cmSystemTools::Error(arg + ": option not handled");
  978. return_value = 1;
  979. }
  980. } else if (!cmSystemTools::TestFileAccess(arg,
  981. cmsys::TEST_FILE_READ) &&
  982. cmSystemTools::TestFileAccess(arg, cmsys::TEST_FILE_OK)) {
  983. cmSystemTools::Error(arg + ": permission denied (ignoring)");
  984. return_value = 1;
  985. } else if (cmSystemTools::FileIsDirectory(arg)) {
  986. cmSystemTools::Error(arg + ": is a directory (ignoring)");
  987. return_value = 1;
  988. } else if (!cmSystemTools::FileExists(arg)) {
  989. cmSystemTools::Error(arg + ": no such file or directory (ignoring)");
  990. return_value = 1;
  991. } else if (cmSystemTools::FileLength(arg) == 0) {
  992. // Ignore empty files, this is not an error
  993. } else {
  994. // Destroy console buffers to drop cout/cerr encoding transform.
  995. consoleBuf.reset();
  996. cmCatFile(arg);
  997. }
  998. }
  999. return return_value;
  1000. }
  1001. // Command to change directory and run a program.
  1002. if (args[1] == "chdir" && args.size() >= 4) {
  1003. std::string const& directory = args[2];
  1004. if (!cmSystemTools::FileExists(directory)) {
  1005. cmSystemTools::Error("Directory does not exist for chdir command: " +
  1006. directory);
  1007. return 1;
  1008. }
  1009. std::string command =
  1010. cmWrap('"', cmMakeRange(args).advance(3), '"', " ");
  1011. int retval = 0;
  1012. if (cmSystemTools::RunSingleCommand(
  1013. command, nullptr, nullptr, &retval, directory.c_str(),
  1014. cmSystemTools::OUTPUT_PASSTHROUGH, cmDuration::zero())) {
  1015. return retval;
  1016. }
  1017. return 1;
  1018. }
  1019. // Command to start progress for a build
  1020. if (args[1] == "cmake_progress_start" && args.size() == 4) {
  1021. // basically remove the directory
  1022. std::string dirName = cmStrCat(args[2], "/Progress");
  1023. cmSystemTools::RemoveADirectory(dirName);
  1024. // is the last argument a filename that exists?
  1025. FILE* countFile = cmsys::SystemTools::Fopen(args[3], "r");
  1026. int count;
  1027. if (countFile) {
  1028. if (1 != fscanf(countFile, "%i", &count)) {
  1029. std::cerr << "Could not read from count file.\n";
  1030. }
  1031. fclose(countFile);
  1032. } else {
  1033. count = atoi(args[3].c_str());
  1034. }
  1035. if (count) {
  1036. cmSystemTools::MakeDirectory(dirName);
  1037. // write the count into the directory
  1038. std::string fName = cmStrCat(dirName, "/count.txt");
  1039. FILE* progFile = cmsys::SystemTools::Fopen(fName, "w");
  1040. if (progFile) {
  1041. fprintf(progFile, "%i\n", count);
  1042. fclose(progFile);
  1043. }
  1044. }
  1045. return 0;
  1046. }
  1047. // Command to report progress for a build
  1048. if (args[1] == "cmake_progress_report" && args.size() >= 3) {
  1049. // This has been superseded by cmake_echo_color --progress-*
  1050. // options. We leave it here to avoid errors if somehow this
  1051. // is invoked by an existing makefile without regenerating.
  1052. return 0;
  1053. }
  1054. // Command to create a symbolic link. Fails on platforms not
  1055. // supporting them.
  1056. if (args[1] == "create_symlink" && args.size() == 4) {
  1057. std::string const& destinationFileName = args[3];
  1058. if ((cmSystemTools::FileExists(destinationFileName) ||
  1059. cmSystemTools::FileIsSymlink(destinationFileName)) &&
  1060. !cmSystemTools::RemoveFile(destinationFileName)) {
  1061. std::string emsg = cmSystemTools::GetLastSystemError();
  1062. std::cerr << "failed to create symbolic link '" << destinationFileName
  1063. << "' because existing path cannot be removed: " << emsg
  1064. << "\n";
  1065. return 1;
  1066. }
  1067. if (!cmSystemTools::CreateSymlink(args[2], destinationFileName)) {
  1068. return 1;
  1069. }
  1070. return 0;
  1071. }
  1072. // Command to create a hard link. Fails on platforms not
  1073. // supporting them.
  1074. if (args[1] == "create_hardlink" && args.size() == 4) {
  1075. std::string const& sourceFileName = args[2];
  1076. std::string const& destinationFileName = args[3];
  1077. if (!cmSystemTools::FileExists(sourceFileName)) {
  1078. std::cerr << "failed to create hard link because source path '"
  1079. << sourceFileName << "' does not exist \n";
  1080. return 1;
  1081. }
  1082. if ((cmSystemTools::FileExists(destinationFileName) ||
  1083. cmSystemTools::FileIsSymlink(destinationFileName)) &&
  1084. !cmSystemTools::RemoveFile(destinationFileName)) {
  1085. std::string emsg = cmSystemTools::GetLastSystemError();
  1086. std::cerr << "failed to create hard link '" << destinationFileName
  1087. << "' because existing path cannot be removed: " << emsg
  1088. << "\n";
  1089. return 1;
  1090. }
  1091. if (!cmSystemTools::CreateLink(sourceFileName, destinationFileName)) {
  1092. return 1;
  1093. }
  1094. return 0;
  1095. }
  1096. // Command to do nothing with an exit code of 0.
  1097. if (args[1] == "true") {
  1098. return 0;
  1099. }
  1100. // Command to do nothing with an exit code of 1.
  1101. if (args[1] == "false") {
  1102. return 1;
  1103. }
  1104. // Internal CMake shared library support.
  1105. if (args[1] == "cmake_symlink_library" && args.size() == 5) {
  1106. return cmcmd::SymlinkLibrary(args);
  1107. }
  1108. // Internal CMake versioned executable support.
  1109. if (args[1] == "cmake_symlink_executable" && args.size() == 4) {
  1110. return cmcmd::SymlinkExecutable(args);
  1111. }
  1112. // Internal CMake dependency scanning support.
  1113. if (args[1] == "cmake_depends" && args.size() >= 6) {
  1114. const bool verbose = isCMakeVerbose();
  1115. // Create a cmake object instance to process dependencies.
  1116. // All we need is the `set` command.
  1117. cmake cm(cmake::RoleScript, cmState::Unknown);
  1118. std::string gen;
  1119. std::string homeDir;
  1120. std::string startDir;
  1121. std::string homeOutDir;
  1122. std::string startOutDir;
  1123. std::string depInfo;
  1124. bool color = false;
  1125. if (args.size() >= 8) {
  1126. // Full signature:
  1127. //
  1128. // -E cmake_depends <generator>
  1129. // <home-src-dir> <start-src-dir>
  1130. // <home-out-dir> <start-out-dir>
  1131. // <dep-info> [--color=$(COLOR)]
  1132. //
  1133. // All paths are provided.
  1134. gen = args[2];
  1135. homeDir = args[3];
  1136. startDir = args[4];
  1137. homeOutDir = args[5];
  1138. startOutDir = args[6];
  1139. depInfo = args[7];
  1140. if (args.size() >= 9 && cmHasLiteralPrefix(args[8], "--color=")) {
  1141. // Enable or disable color based on the switch value.
  1142. color = (args[8].size() == 8 || cmIsOn(args[8].substr(8)));
  1143. }
  1144. } else {
  1145. // Support older signature for existing makefiles:
  1146. //
  1147. // -E cmake_depends <generator>
  1148. // <home-out-dir> <start-out-dir>
  1149. // <dep-info>
  1150. //
  1151. // Just pretend the source directories are the same as the
  1152. // binary directories so at least scanning will work.
  1153. gen = args[2];
  1154. homeDir = args[3];
  1155. startDir = args[4];
  1156. homeOutDir = args[3];
  1157. startOutDir = args[3];
  1158. depInfo = args[5];
  1159. }
  1160. // Create a local generator configured for the directory in
  1161. // which dependencies will be scanned.
  1162. homeDir = cmSystemTools::CollapseFullPath(homeDir);
  1163. startDir = cmSystemTools::CollapseFullPath(startDir);
  1164. homeOutDir = cmSystemTools::CollapseFullPath(homeOutDir);
  1165. startOutDir = cmSystemTools::CollapseFullPath(startOutDir);
  1166. cm.SetHomeDirectory(homeDir);
  1167. cm.SetHomeOutputDirectory(homeOutDir);
  1168. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  1169. if (auto ggd = cm.CreateGlobalGenerator(gen)) {
  1170. cm.SetGlobalGenerator(std::move(ggd));
  1171. cmStateSnapshot snapshot = cm.GetCurrentSnapshot();
  1172. snapshot.GetDirectory().SetCurrentBinary(startOutDir);
  1173. snapshot.GetDirectory().SetCurrentSource(startDir);
  1174. cmMakefile mf(cm.GetGlobalGenerator(), snapshot);
  1175. auto lgd = cm.GetGlobalGenerator()->CreateLocalGenerator(&mf);
  1176. // FIXME: With advanced add_subdirectory usage, these are
  1177. // not necessarily the same as the generator originally used.
  1178. // We should pass all these directories through an info file.
  1179. lgd->SetRelativePathTopSource(homeDir);
  1180. lgd->SetRelativePathTopBinary(homeOutDir);
  1181. // Actually scan dependencies.
  1182. return lgd->UpdateDependencies(depInfo, verbose, color) ? 0 : 2;
  1183. }
  1184. return 1;
  1185. }
  1186. #if !defined(CMAKE_BOOTSTRAP) || defined(CMAKE_BOOTSTRAP_MAKEFILES)
  1187. // Internal CMake compiler dependencies filtering
  1188. if (args[1] == "cmake_cl_compile_depends") {
  1189. return CLCompileAndDependencies(args);
  1190. }
  1191. #endif
  1192. // Internal CMake link script support.
  1193. if (args[1] == "cmake_link_script" && args.size() >= 3) {
  1194. return cmcmd::ExecuteLinkScript(args);
  1195. }
  1196. #if !defined(CMAKE_BOOTSTRAP)
  1197. // Internal CMake ninja dependency scanning support.
  1198. if (args[1] == "cmake_ninja_depends") {
  1199. return cmcmd_cmake_ninja_depends(args.begin() + 2, args.end());
  1200. }
  1201. // Internal CMake ninja dyndep support.
  1202. if (args[1] == "cmake_ninja_dyndep") {
  1203. return cmcmd_cmake_ninja_dyndep(args.begin() + 2, args.end());
  1204. }
  1205. #endif
  1206. // Internal CMake unimplemented feature notification.
  1207. if (args[1] == "cmake_unimplemented_variable") {
  1208. std::cerr << "Feature not implemented for this platform.";
  1209. if (args.size() == 3) {
  1210. std::cerr << " Variable " << args[2] << " is not set.";
  1211. }
  1212. std::cerr << std::endl;
  1213. return 1;
  1214. }
  1215. if (args[1] == "vs_link_exe") {
  1216. return cmcmd::VisualStudioLink(args, 1);
  1217. }
  1218. if (args[1] == "vs_link_dll") {
  1219. return cmcmd::VisualStudioLink(args, 2);
  1220. }
  1221. if (args[1] == "cmake_llvm_rc") {
  1222. return cmcmd::RunLLVMRC(args);
  1223. }
  1224. // Internal CMake color makefile support.
  1225. if (args[1] == "cmake_echo_color") {
  1226. return cmcmd::ExecuteEchoColor(args);
  1227. }
  1228. #ifndef CMAKE_BOOTSTRAP
  1229. if ((args[1] == "cmake_autogen") && (args.size() >= 4)) {
  1230. cm::string_view const infoFile = args[2];
  1231. cm::string_view const config = args[3];
  1232. return cmQtAutoMocUic(infoFile, config) ? 0 : 1;
  1233. }
  1234. if ((args[1] == "cmake_autorcc") && (args.size() >= 3)) {
  1235. cm::string_view const infoFile = args[2];
  1236. cm::string_view const config =
  1237. (args.size() > 3) ? cm::string_view(args[3]) : cm::string_view();
  1238. return cmQtAutoRcc(infoFile, config) ? 0 : 1;
  1239. }
  1240. #endif
  1241. // Tar files
  1242. if (args[1] == "tar" && args.size() > 3) {
  1243. const char* knownFormats[] = { "7zip", "gnutar", "pax", "paxr", "zip" };
  1244. std::string const& flags = args[2];
  1245. std::string const& outFile = args[3];
  1246. std::vector<std::string> files;
  1247. std::string mtime;
  1248. std::string format;
  1249. cmSystemTools::cmTarCompression compress =
  1250. cmSystemTools::TarCompressNone;
  1251. int nCompress = 0;
  1252. bool doing_options = true;
  1253. for (auto const& arg : cmMakeRange(args).advance(4)) {
  1254. if (doing_options && cmHasLiteralPrefix(arg, "--")) {
  1255. if (arg == "--") {
  1256. doing_options = false;
  1257. } else if (arg == "--zstd") {
  1258. compress = cmSystemTools::TarCompressZstd;
  1259. ++nCompress;
  1260. } else if (cmHasLiteralPrefix(arg, "--mtime=")) {
  1261. mtime = arg.substr(8);
  1262. } else if (cmHasLiteralPrefix(arg, "--files-from=")) {
  1263. std::string const& files_from = arg.substr(13);
  1264. if (!cmTarFilesFrom(files_from, files)) {
  1265. return 1;
  1266. }
  1267. } else if (cmHasLiteralPrefix(arg, "--format=")) {
  1268. format = arg.substr(9);
  1269. if (!cm::contains(knownFormats, format)) {
  1270. cmSystemTools::Error("Unknown -E tar --format= argument: " +
  1271. format);
  1272. return 1;
  1273. }
  1274. } else {
  1275. cmSystemTools::Error("Unknown option to -E tar: " + arg);
  1276. return 1;
  1277. }
  1278. } else {
  1279. files.push_back(arg);
  1280. }
  1281. }
  1282. cmSystemTools::cmTarAction action = cmSystemTools::TarActionNone;
  1283. bool verbose = false;
  1284. for (auto flag : flags) {
  1285. switch (flag) {
  1286. case '-':
  1287. case 'f': {
  1288. // Keep for backward compatibility. Ignored
  1289. } break;
  1290. case 'j': {
  1291. compress = cmSystemTools::TarCompressBZip2;
  1292. ++nCompress;
  1293. } break;
  1294. case 'J': {
  1295. compress = cmSystemTools::TarCompressXZ;
  1296. ++nCompress;
  1297. } break;
  1298. case 'z': {
  1299. compress = cmSystemTools::TarCompressGZip;
  1300. ++nCompress;
  1301. } break;
  1302. case 'v': {
  1303. verbose = true;
  1304. } break;
  1305. case 't': {
  1306. action = cmSystemTools::TarActionList;
  1307. } break;
  1308. case 'c': {
  1309. action = cmSystemTools::TarActionCreate;
  1310. } break;
  1311. case 'x': {
  1312. action = cmSystemTools::TarActionExtract;
  1313. } break;
  1314. default: {
  1315. std::cerr << "tar: Unknown argument: " << flag << "\n";
  1316. }
  1317. }
  1318. }
  1319. if ((format == "7zip" || format == "zip") && nCompress > 0) {
  1320. cmSystemTools::Error("Can not use compression flags with format: " +
  1321. format);
  1322. return 1;
  1323. }
  1324. if (nCompress > 1) {
  1325. cmSystemTools::Error("Can only compress a tar file one way; "
  1326. "at most one flag of z, j, or J may be used");
  1327. return 1;
  1328. }
  1329. if (action == cmSystemTools::TarActionList) {
  1330. if (!cmSystemTools::ListTar(outFile, files, verbose)) {
  1331. cmSystemTools::Error("Problem listing tar: " + outFile);
  1332. return 1;
  1333. }
  1334. } else if (action == cmSystemTools::TarActionCreate) {
  1335. if (files.empty()) {
  1336. std::cerr << "tar: No files or directories specified\n";
  1337. }
  1338. if (!cmSystemTools::CreateTar(outFile, files, compress, verbose, mtime,
  1339. format)) {
  1340. cmSystemTools::Error("Problem creating tar: " + outFile);
  1341. return 1;
  1342. }
  1343. } else if (action == cmSystemTools::TarActionExtract) {
  1344. if (!cmSystemTools::ExtractTar(outFile, files, verbose)) {
  1345. cmSystemTools::Error("Problem extracting tar: " + outFile);
  1346. return 1;
  1347. }
  1348. #ifdef _WIN32
  1349. // OK, on windows 7 after we untar some files,
  1350. // sometimes we can not rename the directory after
  1351. // the untar is done. This breaks the external project
  1352. // untar and rename code. So, by default we will wait
  1353. // 1/10th of a second after the untar. If CMAKE_UNTAR_DELAY
  1354. // is set in the env, its value will be used instead of 100.
  1355. int delay = 100;
  1356. std::string delayVar;
  1357. if (cmSystemTools::GetEnv("CMAKE_UNTAR_DELAY", delayVar)) {
  1358. delay = atoi(delayVar.c_str());
  1359. }
  1360. if (delay) {
  1361. cmSystemTools::Delay(delay);
  1362. }
  1363. #endif
  1364. } else {
  1365. cmSystemTools::Error("tar: No action specified. Please choose: 't' "
  1366. "(list), 'c' (create) or 'x' (extract)");
  1367. return 1;
  1368. }
  1369. return 0;
  1370. }
  1371. if (args[1] == "server") {
  1372. cmSystemTools::Error(
  1373. "CMake server mode has been removed in favor of the file-api.");
  1374. return 1;
  1375. }
  1376. #if !defined(CMAKE_BOOTSTRAP)
  1377. // Internal CMake Fortran module support.
  1378. if (args[1] == "cmake_copy_f90_mod" && args.size() >= 4) {
  1379. return cmDependsFortran::CopyModule(args) ? 0 : 1;
  1380. }
  1381. #endif
  1382. #if defined(_WIN32) && !defined(__CYGWIN__)
  1383. // Write registry value
  1384. if (args[1] == "write_regv" && args.size() > 3) {
  1385. return cmSystemTools::WriteRegistryValue(args[2], args[3]) ? 0 : 1;
  1386. }
  1387. // Delete registry value
  1388. if (args[1] == "delete_regv" && args.size() > 2) {
  1389. return cmSystemTools::DeleteRegistryValue(args[2]) ? 0 : 1;
  1390. }
  1391. // Remove file
  1392. if (args[1] == "comspec" && args.size() > 2) {
  1393. std::cerr << "Win9x helper \"cmake -E comspec\" no longer supported\n";
  1394. return 1;
  1395. }
  1396. if (args[1] == "env_vs8_wince" && args.size() == 3) {
  1397. return cmcmd::WindowsCEEnvironment("8.0", args[2]);
  1398. }
  1399. if (args[1] == "env_vs9_wince" && args.size() == 3) {
  1400. return cmcmd::WindowsCEEnvironment("9.0", args[2]);
  1401. }
  1402. #endif
  1403. // Internal depfile transformation
  1404. if (args[1] == "cmake_transform_depfile" && args.size() == 10) {
  1405. auto format = cmDepfileFormat::GccDepfile;
  1406. if (args[3] == "gccdepfile") {
  1407. format = cmDepfileFormat::GccDepfile;
  1408. } else if (args[3] == "makedepfile") {
  1409. format = cmDepfileFormat::MakeDepfile;
  1410. } else if (args[3] == "MSBuildAdditionalInputs") {
  1411. format = cmDepfileFormat::MSBuildAdditionalInputs;
  1412. } else {
  1413. return 1;
  1414. }
  1415. // Create a cmake object instance to process dependencies.
  1416. // All we need is the `set` command.
  1417. cmake cm(cmake::RoleScript, cmState::Unknown);
  1418. std::string homeDir;
  1419. std::string startDir;
  1420. std::string homeOutDir;
  1421. std::string startOutDir;
  1422. homeDir = cmSystemTools::CollapseFullPath(args[4]);
  1423. startDir = cmSystemTools::CollapseFullPath(args[5]);
  1424. homeOutDir = cmSystemTools::CollapseFullPath(args[6]);
  1425. startOutDir = cmSystemTools::CollapseFullPath(args[7]);
  1426. cm.SetHomeDirectory(homeDir);
  1427. cm.SetHomeOutputDirectory(homeOutDir);
  1428. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  1429. if (auto ggd = cm.CreateGlobalGenerator(args[2])) {
  1430. cm.SetGlobalGenerator(std::move(ggd));
  1431. cmStateSnapshot snapshot = cm.GetCurrentSnapshot();
  1432. snapshot.GetDirectory().SetCurrentBinary(startOutDir);
  1433. snapshot.GetDirectory().SetCurrentSource(startDir);
  1434. cmMakefile mf(cm.GetGlobalGenerator(), snapshot);
  1435. auto lgd = cm.GetGlobalGenerator()->CreateLocalGenerator(&mf);
  1436. // FIXME: With advanced add_subdirectory usage, these are
  1437. // not necessarily the same as the generator originally used.
  1438. // We should pass all these directories through an info file.
  1439. lgd->SetRelativePathTopSource(homeDir);
  1440. lgd->SetRelativePathTopBinary(homeOutDir);
  1441. return cmTransformDepfile(format, *lgd, args[8], args[9]) ? 0 : 2;
  1442. }
  1443. return 1;
  1444. }
  1445. }
  1446. CMakeCommandUsage(args[0]);
  1447. return 1;
  1448. }
  1449. int cmcmd::HashSumFile(std::vector<std::string> const& args,
  1450. cmCryptoHash::Algo algo)
  1451. {
  1452. if (args.size() < 3) {
  1453. return -1;
  1454. }
  1455. int retval = 0;
  1456. for (auto const& filename : cmMakeRange(args).advance(2)) {
  1457. // Cannot compute sum of a directory
  1458. if (cmSystemTools::FileIsDirectory(filename)) {
  1459. std::cerr << "Error: " << filename << " is a directory" << std::endl;
  1460. retval++;
  1461. } else {
  1462. std::string value
  1463. #ifndef CMAKE_BOOTSTRAP
  1464. = cmSystemTools::ComputeFileHash(filename, algo)
  1465. #endif
  1466. ;
  1467. if (value.empty()) {
  1468. // To mimic "md5sum/shasum" behavior in a shell:
  1469. std::cerr << filename << ": No such file or directory" << std::endl;
  1470. retval++;
  1471. } else {
  1472. std::cout << value << " " << filename << std::endl;
  1473. }
  1474. }
  1475. }
  1476. return retval;
  1477. }
  1478. int cmcmd::SymlinkLibrary(std::vector<std::string> const& args)
  1479. {
  1480. int result = 0;
  1481. std::string realName = args[2];
  1482. std::string soName = args[3];
  1483. std::string name = args[4];
  1484. cmSystemTools::ConvertToUnixSlashes(realName);
  1485. cmSystemTools::ConvertToUnixSlashes(soName);
  1486. cmSystemTools::ConvertToUnixSlashes(name);
  1487. if (soName != realName) {
  1488. cmsys::Status status = cmcmd::SymlinkInternal(realName, soName);
  1489. if (!status) {
  1490. cmSystemTools::Error(
  1491. cmStrCat("cmake_symlink_library: System Error: ", status.GetString()));
  1492. result = 1;
  1493. }
  1494. }
  1495. if (name != soName) {
  1496. cmsys::Status status = cmcmd::SymlinkInternal(soName, name);
  1497. if (!status) {
  1498. cmSystemTools::Error(
  1499. cmStrCat("cmake_symlink_library: System Error: ", status.GetString()));
  1500. result = 1;
  1501. }
  1502. }
  1503. return result;
  1504. }
  1505. int cmcmd::SymlinkExecutable(std::vector<std::string> const& args)
  1506. {
  1507. int result = 0;
  1508. std::string const& realName = args[2];
  1509. std::string const& name = args[3];
  1510. if (name != realName) {
  1511. cmsys::Status status = cmcmd::SymlinkInternal(realName, name);
  1512. if (!status) {
  1513. cmSystemTools::Error(cmStrCat("cmake_symlink_executable: System Error: ",
  1514. status.GetString()));
  1515. result = 1;
  1516. }
  1517. }
  1518. return result;
  1519. }
  1520. cmsys::Status cmcmd::SymlinkInternal(std::string const& file,
  1521. std::string const& link)
  1522. {
  1523. if (cmSystemTools::FileExists(link) || cmSystemTools::FileIsSymlink(link)) {
  1524. cmSystemTools::RemoveFile(link);
  1525. }
  1526. std::string linktext = cmSystemTools::GetFilenameName(file);
  1527. #if defined(_WIN32) && !defined(__CYGWIN__)
  1528. std::string errorMessage;
  1529. cmsys::Status status =
  1530. cmSystemTools::CreateSymlink(linktext, link, &errorMessage);
  1531. // Creating a symlink will fail with ERROR_PRIVILEGE_NOT_HELD if the user
  1532. // does not have SeCreateSymbolicLinkPrivilege, or if developer mode is not
  1533. // active. In that case, we try to copy the file.
  1534. if (status.GetWindows() == ERROR_PRIVILEGE_NOT_HELD) {
  1535. status = cmSystemTools::CopyFileAlways(file, link);
  1536. } else if (!status) {
  1537. cmSystemTools::Error(errorMessage);
  1538. }
  1539. return status;
  1540. #else
  1541. return cmSystemTools::CreateSymlink(linktext, link);
  1542. #endif
  1543. }
  1544. static void cmcmdProgressReport(std::string const& dir, std::string const& num)
  1545. {
  1546. std::string dirName = cmStrCat(dir, "/Progress");
  1547. std::string fName;
  1548. FILE* progFile;
  1549. // read the count
  1550. fName = cmStrCat(dirName, "/count.txt");
  1551. progFile = cmsys::SystemTools::Fopen(fName, "r");
  1552. int count = 0;
  1553. if (!progFile) {
  1554. return;
  1555. }
  1556. if (1 != fscanf(progFile, "%i", &count)) {
  1557. std::cerr << "Could not read from progress file.\n";
  1558. }
  1559. fclose(progFile);
  1560. const char* last = num.c_str();
  1561. for (const char* c = last;; ++c) {
  1562. if (*c == ',' || *c == '\0') {
  1563. if (c != last) {
  1564. fName = cmStrCat(dirName, '/');
  1565. fName.append(last, c - last);
  1566. progFile = cmsys::SystemTools::Fopen(fName, "w");
  1567. if (progFile) {
  1568. fprintf(progFile, "empty");
  1569. fclose(progFile);
  1570. }
  1571. }
  1572. if (*c == '\0') {
  1573. break;
  1574. }
  1575. last = c + 1;
  1576. }
  1577. }
  1578. int fileNum =
  1579. static_cast<int>(cmsys::Directory::GetNumberOfFilesInDirectory(dirName));
  1580. if (count > 0) {
  1581. // print the progress
  1582. fprintf(stdout, "[%3i%%] ", ((fileNum - 3) * 100) / count);
  1583. }
  1584. }
  1585. int cmcmd::ExecuteEchoColor(std::vector<std::string> const& args)
  1586. {
  1587. // The arguments are
  1588. // args[0] == <cmake-executable>
  1589. // args[1] == cmake_echo_color
  1590. bool enabled = true;
  1591. int color = cmsysTerminal_Color_Normal;
  1592. bool newline = true;
  1593. std::string progressDir;
  1594. for (auto const& arg : cmMakeRange(args).advance(2)) {
  1595. if (cmHasLiteralPrefix(arg, "--switch=")) {
  1596. // Enable or disable color based on the switch value.
  1597. std::string value = arg.substr(9);
  1598. if (!value.empty()) {
  1599. enabled = cmIsOn(value);
  1600. }
  1601. } else if (cmHasLiteralPrefix(arg, "--progress-dir=")) {
  1602. progressDir = arg.substr(15);
  1603. } else if (cmHasLiteralPrefix(arg, "--progress-num=")) {
  1604. if (!progressDir.empty()) {
  1605. std::string const& progressNum = arg.substr(15);
  1606. cmcmdProgressReport(progressDir, progressNum);
  1607. }
  1608. } else if (arg == "--normal") {
  1609. color = cmsysTerminal_Color_Normal;
  1610. } else if (arg == "--black") {
  1611. color = cmsysTerminal_Color_ForegroundBlack;
  1612. } else if (arg == "--red") {
  1613. color = cmsysTerminal_Color_ForegroundRed;
  1614. } else if (arg == "--green") {
  1615. color = cmsysTerminal_Color_ForegroundGreen;
  1616. } else if (arg == "--yellow") {
  1617. color = cmsysTerminal_Color_ForegroundYellow;
  1618. } else if (arg == "--blue") {
  1619. color = cmsysTerminal_Color_ForegroundBlue;
  1620. } else if (arg == "--magenta") {
  1621. color = cmsysTerminal_Color_ForegroundMagenta;
  1622. } else if (arg == "--cyan") {
  1623. color = cmsysTerminal_Color_ForegroundCyan;
  1624. } else if (arg == "--white") {
  1625. color = cmsysTerminal_Color_ForegroundWhite;
  1626. } else if (arg == "--bold") {
  1627. color |= cmsysTerminal_Color_ForegroundBold;
  1628. } else if (arg == "--no-newline") {
  1629. newline = false;
  1630. } else if (arg == "--newline") {
  1631. newline = true;
  1632. } else {
  1633. // Color is enabled. Print with the current color.
  1634. cmSystemTools::MakefileColorEcho(color, arg.c_str(), newline, enabled);
  1635. }
  1636. }
  1637. return 0;
  1638. }
  1639. int cmcmd::ExecuteLinkScript(std::vector<std::string> const& args)
  1640. {
  1641. // The arguments are
  1642. // args[0] == <cmake-executable>
  1643. // args[1] == cmake_link_script
  1644. // args[2] == <link-script-name>
  1645. // args[3] == --verbose=?
  1646. bool verbose = false;
  1647. if (args.size() >= 4) {
  1648. if (cmHasLiteralPrefix(args[3], "--verbose=")) {
  1649. if (!cmIsOff(args[3].substr(10))) {
  1650. verbose = true;
  1651. }
  1652. }
  1653. }
  1654. // Allocate a process instance.
  1655. cmsysProcess* cp = cmsysProcess_New();
  1656. if (!cp) {
  1657. std::cerr << "Error allocating process instance in link script."
  1658. << std::endl;
  1659. return 1;
  1660. }
  1661. // Children should share stdout and stderr with this process.
  1662. cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDOUT, 1);
  1663. cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDERR, 1);
  1664. // Run the command lines verbatim.
  1665. cmsysProcess_SetOption(cp, cmsysProcess_Option_Verbatim, 1);
  1666. // Read command lines from the script.
  1667. cmsys::ifstream fin(args[2].c_str());
  1668. if (!fin) {
  1669. std::cerr << "Error opening link script \"" << args[2] << "\""
  1670. << std::endl;
  1671. return 1;
  1672. }
  1673. // Run one command at a time.
  1674. std::string command;
  1675. int result = 0;
  1676. while (result == 0 && cmSystemTools::GetLineFromStream(fin, command)) {
  1677. // Skip empty command lines.
  1678. if (command.find_first_not_of(" \t") == std::string::npos) {
  1679. continue;
  1680. }
  1681. // Setup this command line.
  1682. const char* cmd[2] = { command.c_str(), nullptr };
  1683. cmsysProcess_SetCommand(cp, cmd);
  1684. // Report the command if verbose output is enabled.
  1685. if (verbose) {
  1686. std::cout << command << std::endl;
  1687. }
  1688. // Run the command and wait for it to exit.
  1689. cmsysProcess_Execute(cp);
  1690. cmsysProcess_WaitForExit(cp, nullptr);
  1691. // Report failure if any.
  1692. switch (cmsysProcess_GetState(cp)) {
  1693. case cmsysProcess_State_Exited: {
  1694. int value = cmsysProcess_GetExitValue(cp);
  1695. if (value != 0) {
  1696. result = value;
  1697. }
  1698. } break;
  1699. case cmsysProcess_State_Exception:
  1700. std::cerr << "Error running link command: "
  1701. << cmsysProcess_GetExceptionString(cp) << std::endl;
  1702. result = 1;
  1703. break;
  1704. case cmsysProcess_State_Error:
  1705. std::cerr << "Error running link command: "
  1706. << cmsysProcess_GetErrorString(cp) << std::endl;
  1707. result = 2;
  1708. break;
  1709. default:
  1710. break;
  1711. }
  1712. }
  1713. // Free the process instance.
  1714. cmsysProcess_Delete(cp);
  1715. // Return the final resulting return value.
  1716. return result;
  1717. }
  1718. int cmcmd::WindowsCEEnvironment(const char* version, const std::string& name)
  1719. {
  1720. #if !defined(CMAKE_BOOTSTRAP) && defined(_WIN32) && !defined(__CYGWIN__)
  1721. cmVisualStudioWCEPlatformParser parser(name.c_str());
  1722. parser.ParseVersion(version);
  1723. if (parser.Found()) {
  1724. /* clang-format off */
  1725. std::cout << "@echo off\n"
  1726. "echo Environment Selection: " << name << "\n"
  1727. "set PATH=" << parser.GetPathDirectories() << "\n"
  1728. "set INCLUDE=" << parser.GetIncludeDirectories() << "\n"
  1729. "set LIB=" << parser.GetLibraryDirectories() << std::endl;
  1730. /* clang-format on */
  1731. return 0;
  1732. }
  1733. #else
  1734. (void)version;
  1735. #endif
  1736. std::cerr << "Could not find " << name;
  1737. return -1;
  1738. }
  1739. int cmcmd::RunPreprocessor(const std::vector<std::string>& command,
  1740. const std::string& intermediate_file)
  1741. {
  1742. cmUVProcessChainBuilder builder;
  1743. uv_fs_t fs_req;
  1744. int preprocessedFile =
  1745. uv_fs_open(nullptr, &fs_req, intermediate_file.c_str(), O_CREAT | O_RDWR,
  1746. 0644, nullptr);
  1747. uv_fs_req_cleanup(&fs_req);
  1748. builder
  1749. .SetExternalStream(cmUVProcessChainBuilder::Stream_OUTPUT,
  1750. preprocessedFile)
  1751. .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR)
  1752. .AddCommand(command);
  1753. auto process = builder.Start();
  1754. if (!process.Valid()) {
  1755. std::cerr << "Failed to start preprocessor.";
  1756. return 1;
  1757. }
  1758. if (!process.Wait()) {
  1759. std::cerr << "Failed to wait for preprocessor";
  1760. return 1;
  1761. }
  1762. auto status = process.GetStatus();
  1763. if (!status[0] || status[0]->ExitStatus != 0) {
  1764. auto* errorStream = process.ErrorStream();
  1765. if (errorStream) {
  1766. std::cerr << errorStream->rdbuf();
  1767. }
  1768. return 1;
  1769. }
  1770. return 0;
  1771. }
  1772. int cmcmd::RunLLVMRC(std::vector<std::string> const& args)
  1773. {
  1774. // The arguments are
  1775. // args[0] == <cmake-executable>
  1776. // args[1] == cmake_llvm_rc
  1777. // args[2] == source_file_path
  1778. // args[3] == intermediate_file
  1779. // args[4..n] == preprocess+args
  1780. // args[n+1] == ++
  1781. // args[n+2...] == llvm-rc+args
  1782. if (args.size() < 3) {
  1783. std::cerr << "Invalid cmake_llvm_rc arguments";
  1784. return 1;
  1785. }
  1786. const std::string& intermediate_file = args[3];
  1787. const std::string& source_file = args[2];
  1788. std::vector<std::string> preprocess;
  1789. std::vector<std::string> resource_compile;
  1790. std::vector<std::string>* pArgTgt = &preprocess;
  1791. static const cmsys::RegularExpression llvm_rc_only_single_arg("^[-/](N|Y)");
  1792. static const cmsys::RegularExpression llvm_rc_only_double_arg(
  1793. "^[-/](C|LN|L)(.)?");
  1794. static const cmsys::RegularExpression common_double_arg(
  1795. "^[-/](D|U|I|FO|fo|Fo)(.)?");
  1796. bool acceptNextArg = false;
  1797. bool skipNextArg = false;
  1798. for (std::string const& arg : cmMakeRange(args).advance(4)) {
  1799. if (skipNextArg) {
  1800. skipNextArg = false;
  1801. continue;
  1802. }
  1803. // We use ++ as separator between the preprocessing step definition and
  1804. // the rc compilation step because we need to prepend a -- to separate the
  1805. // source file properly from other options when using clang-cl for
  1806. // preprocessing.
  1807. if (arg == "++") {
  1808. pArgTgt = &resource_compile;
  1809. skipNextArg = false;
  1810. acceptNextArg = true;
  1811. } else {
  1812. cmsys::RegularExpressionMatch match;
  1813. if (!acceptNextArg) {
  1814. if (common_double_arg.find(arg.c_str(), match)) {
  1815. acceptNextArg = match.match(2).empty();
  1816. } else {
  1817. if (llvm_rc_only_single_arg.find(arg.c_str(), match)) {
  1818. if (pArgTgt == &preprocess) {
  1819. continue;
  1820. }
  1821. } else if (llvm_rc_only_double_arg.find(arg.c_str(), match)) {
  1822. if (pArgTgt == &preprocess) {
  1823. skipNextArg = match.match(2).empty();
  1824. continue;
  1825. }
  1826. acceptNextArg = match.match(2).empty();
  1827. } else if (pArgTgt == &resource_compile) {
  1828. continue;
  1829. }
  1830. }
  1831. } else {
  1832. acceptNextArg = false;
  1833. }
  1834. if (arg.find("SOURCE_DIR") != std::string::npos) {
  1835. std::string sourceDirArg = arg;
  1836. cmSystemTools::ReplaceString(
  1837. sourceDirArg, "SOURCE_DIR",
  1838. cmSystemTools::GetFilenamePath(source_file));
  1839. pArgTgt->push_back(sourceDirArg);
  1840. } else {
  1841. pArgTgt->push_back(arg);
  1842. }
  1843. }
  1844. }
  1845. if (preprocess.empty()) {
  1846. std::cerr << "Empty preprocessing command";
  1847. return 1;
  1848. }
  1849. if (resource_compile.empty()) {
  1850. std::cerr << "Empty resource compilation command";
  1851. return 1;
  1852. }
  1853. // Since we might have skipped the last argument to llvm-rc
  1854. // we need to make sure the llvm-rc source file is present in the
  1855. // commandline
  1856. if (resource_compile.back() != intermediate_file) {
  1857. resource_compile.push_back(intermediate_file);
  1858. }
  1859. auto result = RunPreprocessor(preprocess, intermediate_file);
  1860. if (result != 0) {
  1861. cmSystemTools::RemoveFile(intermediate_file);
  1862. return result;
  1863. }
  1864. cmUVProcessChainBuilder builder;
  1865. builder.SetBuiltinStream(cmUVProcessChainBuilder::Stream_OUTPUT)
  1866. .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR)
  1867. .AddCommand(resource_compile);
  1868. auto process = builder.Start();
  1869. result = 0;
  1870. if (!process.Valid()) {
  1871. std::cerr << "Failed to start resource compiler.";
  1872. result = 1;
  1873. } else {
  1874. if (!process.Wait()) {
  1875. std::cerr << "Failed to wait for resource compiler";
  1876. result = 1;
  1877. }
  1878. }
  1879. cmSystemTools::RemoveFile(intermediate_file);
  1880. if (result != 0) {
  1881. return result;
  1882. }
  1883. auto status = process.GetStatus();
  1884. if (!status[0] || status[0]->ExitStatus != 0) {
  1885. auto* errorStream = process.ErrorStream();
  1886. if (errorStream) {
  1887. std::cerr << errorStream->rdbuf();
  1888. }
  1889. return 1;
  1890. }
  1891. return 0;
  1892. }
  1893. class cmVSLink
  1894. {
  1895. int Type;
  1896. bool Verbose;
  1897. bool Incremental;
  1898. bool LinkGeneratesManifest;
  1899. std::vector<std::string> LinkCommand;
  1900. std::vector<std::string> UserManifests;
  1901. std::string LinkerManifestFile;
  1902. std::string ManifestFile;
  1903. std::string ManifestFileRC;
  1904. std::string ManifestFileRes;
  1905. std::string TargetFile;
  1906. std::string MtPath;
  1907. std::string RcPath;
  1908. public:
  1909. cmVSLink(int type, bool verbose)
  1910. : Type(type)
  1911. , Verbose(verbose)
  1912. , Incremental(false)
  1913. , LinkGeneratesManifest(true)
  1914. {
  1915. }
  1916. bool Parse(std::vector<std::string>::const_iterator argBeg,
  1917. std::vector<std::string>::const_iterator argEnd);
  1918. int Link();
  1919. private:
  1920. int LinkIncremental();
  1921. int LinkNonIncremental();
  1922. int RunMT(std::string const& out, bool notify);
  1923. };
  1924. // For visual studio 2005 and newer manifest files need to be embedded into
  1925. // exe and dll's. This code does that in such a way that incremental linking
  1926. // still works.
  1927. int cmcmd::VisualStudioLink(std::vector<std::string> const& args, int type)
  1928. {
  1929. // Replace streambuf so we output in the system codepage. CMake is set up
  1930. // to output in Unicode (see SetUTF8Pipes) but the Visual Studio linker
  1931. // outputs using the system codepage so we need to change behavior when
  1932. // we run the link command.
  1933. cmConsoleBuf consoleBuf;
  1934. if (args.size() < 2) {
  1935. return -1;
  1936. }
  1937. const bool verbose = cmSystemTools::HasEnv("VERBOSE");
  1938. std::vector<std::string> expandedArgs;
  1939. for (std::string const& i : args) {
  1940. // check for nmake temporary files
  1941. if (i[0] == '@' && !cmHasLiteralPrefix(i, "@CMakeFiles")) {
  1942. cmsys::ifstream fin(i.substr(1).c_str());
  1943. std::string line;
  1944. while (cmSystemTools::GetLineFromStream(fin, line)) {
  1945. cmSystemTools::ParseWindowsCommandLine(line.c_str(), expandedArgs);
  1946. }
  1947. } else {
  1948. expandedArgs.push_back(i);
  1949. }
  1950. }
  1951. cmVSLink vsLink(type, verbose);
  1952. if (!vsLink.Parse(expandedArgs.begin() + 2, expandedArgs.end())) {
  1953. return -1;
  1954. }
  1955. return vsLink.Link();
  1956. }
  1957. enum NumberFormat
  1958. {
  1959. FORMAT_DECIMAL,
  1960. FORMAT_HEX
  1961. };
  1962. struct NumberFormatter
  1963. {
  1964. NumberFormat Format;
  1965. int Value;
  1966. NumberFormatter(NumberFormat format, int value)
  1967. : Format(format)
  1968. , Value(value)
  1969. {
  1970. }
  1971. };
  1972. static std::ostream& operator<<(std::ostream& stream,
  1973. NumberFormatter const& formatter)
  1974. {
  1975. auto const& flags = stream.flags();
  1976. if (formatter.Format == FORMAT_DECIMAL) {
  1977. stream << std::dec << formatter.Value;
  1978. } else {
  1979. stream << "0x" << std::hex << formatter.Value;
  1980. }
  1981. stream.flags(flags);
  1982. return stream;
  1983. }
  1984. static bool RunCommand(const char* comment,
  1985. std::vector<std::string> const& command, bool verbose,
  1986. NumberFormat exitFormat, int* retCodeOut = nullptr,
  1987. bool (*retCodeOkay)(int) = nullptr)
  1988. {
  1989. if (verbose) {
  1990. std::cout << comment << ":\n";
  1991. std::cout << cmJoin(command, " ") << "\n";
  1992. }
  1993. std::string output;
  1994. int retCode = 0;
  1995. bool commandResult = cmSystemTools::RunSingleCommand(
  1996. command, &output, &output, &retCode, nullptr, cmSystemTools::OUTPUT_NONE);
  1997. bool const retCodeSuccess =
  1998. retCode == 0 || (retCodeOkay && retCodeOkay(retCode));
  1999. bool const success = commandResult && retCodeSuccess;
  2000. if (retCodeOut) {
  2001. if (commandResult || !retCodeSuccess) {
  2002. *retCodeOut = retCode;
  2003. } else {
  2004. *retCodeOut = -1;
  2005. }
  2006. }
  2007. if (!success) {
  2008. std::cout << comment << ": command \"" << cmJoin(command, " ")
  2009. << "\" failed (exit code "
  2010. << NumberFormatter(exitFormat, retCode)
  2011. << ") with the following output:\n"
  2012. << output;
  2013. } else if (verbose) {
  2014. // always print the output of the command, unless
  2015. // it is the dumb rc command banner
  2016. if (output.find("Resource Compiler Version") == std::string::npos) {
  2017. std::cout << output;
  2018. }
  2019. }
  2020. return success;
  2021. }
  2022. bool cmVSLink::Parse(std::vector<std::string>::const_iterator argBeg,
  2023. std::vector<std::string>::const_iterator argEnd)
  2024. {
  2025. // Parse our own arguments.
  2026. std::string intDir;
  2027. auto arg = argBeg;
  2028. while (arg != argEnd && cmHasLiteralPrefix(*arg, "-")) {
  2029. if (*arg == "--") {
  2030. ++arg;
  2031. break;
  2032. }
  2033. if (*arg == "--manifests") {
  2034. for (++arg; arg != argEnd && !cmHasLiteralPrefix(*arg, "-"); ++arg) {
  2035. this->UserManifests.push_back(*arg);
  2036. }
  2037. } else if (cmHasLiteralPrefix(*arg, "--intdir=")) {
  2038. intDir = arg->substr(9);
  2039. ++arg;
  2040. } else if (cmHasLiteralPrefix(*arg, "--rc=")) {
  2041. this->RcPath = arg->substr(5);
  2042. ++arg;
  2043. } else if (cmHasLiteralPrefix(*arg, "--mt=")) {
  2044. this->MtPath = arg->substr(5);
  2045. ++arg;
  2046. } else {
  2047. std::cerr << "unknown argument '" << *arg << "'\n";
  2048. return false;
  2049. }
  2050. }
  2051. if (intDir.empty()) {
  2052. return false;
  2053. }
  2054. // The rest of the arguments form the link command.
  2055. if (arg == argEnd) {
  2056. return false;
  2057. }
  2058. this->LinkCommand.insert(this->LinkCommand.begin(), arg, argEnd);
  2059. // Parse the link command to extract information we need.
  2060. for (; arg != argEnd; ++arg) {
  2061. if (cmSystemTools::Strucmp(arg->c_str(), "/INCREMENTAL:YES") == 0 ||
  2062. cmSystemTools::Strucmp(arg->c_str(), "/INCREMENTAL") == 0) {
  2063. this->Incremental = true;
  2064. } else if (cmSystemTools::Strucmp(arg->c_str(), "/MANIFEST:NO") == 0) {
  2065. this->LinkGeneratesManifest = false;
  2066. } else if (cmHasLiteralPrefix(*arg, "/Fe")) {
  2067. this->TargetFile = arg->substr(3);
  2068. } else if (cmHasLiteralPrefix(*arg, "/out:")) {
  2069. this->TargetFile = arg->substr(5);
  2070. }
  2071. }
  2072. if (this->TargetFile.empty()) {
  2073. return false;
  2074. }
  2075. this->ManifestFile = intDir + "/embed.manifest";
  2076. this->LinkerManifestFile = intDir + "/intermediate.manifest";
  2077. if (this->Incremental) {
  2078. // We will compile a resource containing the manifest and
  2079. // pass it to the link command.
  2080. this->ManifestFileRC = intDir + "/manifest.rc";
  2081. this->ManifestFileRes = intDir + "/manifest.res";
  2082. } else if (this->UserManifests.empty()) {
  2083. // Prior to support for user-specified manifests CMake placed the
  2084. // linker-generated manifest next to the binary (as if it were not to be
  2085. // embedded) when not linking incrementally. Preserve this behavior.
  2086. this->ManifestFile = this->TargetFile + ".manifest";
  2087. this->LinkerManifestFile = this->ManifestFile;
  2088. }
  2089. if (this->LinkGeneratesManifest) {
  2090. this->LinkCommand.emplace_back("/MANIFEST");
  2091. this->LinkCommand.push_back("/MANIFESTFILE:" + this->LinkerManifestFile);
  2092. }
  2093. return true;
  2094. }
  2095. int cmVSLink::Link()
  2096. {
  2097. if (this->Incremental &&
  2098. (this->LinkGeneratesManifest || !this->UserManifests.empty())) {
  2099. if (this->Verbose) {
  2100. std::cout << "Visual Studio Incremental Link with embedded manifests\n";
  2101. }
  2102. return this->LinkIncremental();
  2103. }
  2104. if (this->Verbose) {
  2105. if (!this->Incremental) {
  2106. std::cout << "Visual Studio Non-Incremental Link\n";
  2107. } else {
  2108. std::cout << "Visual Studio Incremental Link without manifests\n";
  2109. }
  2110. }
  2111. return this->LinkNonIncremental();
  2112. }
  2113. static bool mtRetIsUpdate(int mtRet)
  2114. {
  2115. // 'mt /notify_update' returns a special value (differing between
  2116. // Windows and POSIX hosts) when it updated the manifest file.
  2117. return mtRet == 0x41020001 || mtRet == 0xbb;
  2118. }
  2119. int cmVSLink::LinkIncremental()
  2120. {
  2121. // This follows the steps listed here:
  2122. // http://blogs.msdn.com/zakramer/archive/2006/05/22/603558.aspx
  2123. // 1. Compiler compiles the application and generates the *.obj files.
  2124. // 2. An empty manifest file is generated if this is a clean build and
  2125. // if not the previous one is reused.
  2126. // 3. The resource compiler (rc.exe) compiles the *.manifest file to a
  2127. // *.res file.
  2128. // 4. Linker generates the binary (EXE or DLL) with the /incremental
  2129. // switch and embeds the dummy manifest file. The linker also generates
  2130. // the real manifest file based on the binaries that your binary depends
  2131. // on.
  2132. // 5. The manifest tool (mt.exe) is then used to generate the final
  2133. // manifest.
  2134. // If the final manifest is changed, then 6 and 7 are run, if not
  2135. // they are skipped, and it is done.
  2136. // 6. The resource compiler is invoked one more time.
  2137. // 7. Finally, the Linker does another incremental link, but since the
  2138. // only thing that has changed is the *.res file that contains the
  2139. // manifest it is a short link.
  2140. // Create a resource file referencing the manifest.
  2141. std::string absManifestFile =
  2142. cmSystemTools::CollapseFullPath(this->ManifestFile);
  2143. if (this->Verbose) {
  2144. std::cout << "Create " << this->ManifestFileRC << "\n";
  2145. }
  2146. {
  2147. cmsys::ofstream fout(this->ManifestFileRC.c_str());
  2148. if (!fout) {
  2149. return -1;
  2150. }
  2151. // Insert a pragma statement to specify utf-8 encoding.
  2152. fout << "#pragma code_page(65001)\n";
  2153. fout << this->Type
  2154. << " /* CREATEPROCESS_MANIFEST_RESOURCE_ID */ "
  2155. "24 /* RT_MANIFEST */ \""
  2156. << absManifestFile << "\"";
  2157. }
  2158. // If we have not previously generated a manifest file,
  2159. // generate a manifest file so the resource compiler succeeds.
  2160. if (!cmSystemTools::FileExists(this->ManifestFile)) {
  2161. if (this->Verbose) {
  2162. std::cout << "Create empty: " << this->ManifestFile << "\n";
  2163. }
  2164. if (this->UserManifests.empty()) {
  2165. // generate an empty manifest because there are no user provided
  2166. // manifest files.
  2167. cmsys::ofstream foutTmp(this->ManifestFile.c_str());
  2168. } else {
  2169. this->RunMT("/out:" + this->ManifestFile, false);
  2170. }
  2171. }
  2172. // Compile the resource file.
  2173. std::vector<std::string> rcCommand;
  2174. rcCommand.push_back(this->RcPath.empty() ? "rc" : this->RcPath);
  2175. rcCommand.emplace_back("/fo");
  2176. rcCommand.push_back(this->ManifestFileRes);
  2177. rcCommand.push_back(this->ManifestFileRC);
  2178. if (!RunCommand("RC Pass 1", rcCommand, this->Verbose, FORMAT_DECIMAL)) {
  2179. return -1;
  2180. }
  2181. // Tell the linker to use our manifest compiled into a resource.
  2182. this->LinkCommand.push_back(this->ManifestFileRes);
  2183. // Run the link command (possibly generates intermediate manifest).
  2184. if (!RunCommand("LINK Pass 1", this->LinkCommand, this->Verbose,
  2185. FORMAT_DECIMAL)) {
  2186. return -1;
  2187. }
  2188. // Run the manifest tool to create the final manifest.
  2189. int mtRet = this->RunMT("/out:" + this->ManifestFile, true);
  2190. // If mt returns a special value then it updated the manifest file so
  2191. // we need to embed it again. Otherwise we are done.
  2192. if (!mtRetIsUpdate(mtRet)) {
  2193. return mtRet;
  2194. }
  2195. // Compile the resource file again.
  2196. if (!RunCommand("RC Pass 2", rcCommand, this->Verbose, FORMAT_DECIMAL)) {
  2197. return -1;
  2198. }
  2199. // Link incrementally again to use the updated resource.
  2200. if (!RunCommand("FINAL LINK", this->LinkCommand, this->Verbose,
  2201. FORMAT_DECIMAL)) {
  2202. return -1;
  2203. }
  2204. return 0;
  2205. }
  2206. int cmVSLink::LinkNonIncremental()
  2207. {
  2208. // Run the link command (possibly generates intermediate manifest).
  2209. if (!RunCommand("LINK", this->LinkCommand, this->Verbose, FORMAT_DECIMAL)) {
  2210. return -1;
  2211. }
  2212. // If we have no manifest files we are done.
  2213. if (!this->LinkGeneratesManifest && this->UserManifests.empty()) {
  2214. return 0;
  2215. }
  2216. // Run the manifest tool to embed the final manifest in the binary.
  2217. std::string mtOut =
  2218. "/outputresource:" + this->TargetFile + (this->Type == 1 ? ";#1" : ";#2");
  2219. return this->RunMT(mtOut, false);
  2220. }
  2221. int cmVSLink::RunMT(std::string const& out, bool notify)
  2222. {
  2223. std::vector<std::string> mtCommand;
  2224. mtCommand.push_back(this->MtPath.empty() ? "mt" : this->MtPath);
  2225. mtCommand.emplace_back("/nologo");
  2226. mtCommand.emplace_back("/manifest");
  2227. // add the linker generated manifest if the file exists.
  2228. if (this->LinkGeneratesManifest &&
  2229. cmSystemTools::FileExists(this->LinkerManifestFile)) {
  2230. mtCommand.push_back(this->LinkerManifestFile);
  2231. }
  2232. cm::append(mtCommand, this->UserManifests);
  2233. mtCommand.push_back(out);
  2234. if (notify) {
  2235. // Add an undocumented option that enables a special return
  2236. // code to notify us when the manifest is modified.
  2237. mtCommand.emplace_back("/notify_update");
  2238. }
  2239. int mtRet = 0;
  2240. if (!RunCommand("MT", mtCommand, this->Verbose, FORMAT_HEX, &mtRet,
  2241. mtRetIsUpdate)) {
  2242. return -1;
  2243. }
  2244. return mtRet;
  2245. }