1 /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
2 file Copyright.txt or https://cmake.org/licensing for details. */
5 #include <cmext/algorithm>
10 #include "cmConsoleBuf.h"
11 #include "cmDuration.h"
12 #include "cmGlobalGenerator.h"
13 #include "cmLocalGenerator.h"
14 #include "cmMakefile.h"
15 #include "cmQtAutoMocUic.h"
16 #include "cmQtAutoRcc.h"
19 #include "cmStateDirectory.h"
20 #include "cmStateSnapshot.h"
21 #include "cmStringAlgorithms.h"
22 #include "cmSystemTools.h"
23 #include "cmTransformDepfile.h"
24 #include "cmUVProcessChain.h"
25 #include "cmUtils.hxx"
27 #include "cmVersion.h"
30 #if !defined(CMAKE_BOOTSTRAP)
31 # include "cmDependsFortran.h" // For -E cmake_copy_f90_mod callback.
32 # include "cmFileTime.h"
34 # include "bindexplib.h"
37 #if !defined(CMAKE_BOOTSTRAP) || defined(CMAKE_BOOTSTRAP_MAKEFILES)
40 # include "cmCMakePath.h"
41 # include "cmProcessTools.h"
44 #if !defined(CMAKE_BOOTSTRAP) && defined(_WIN32) && !defined(__CYGWIN__)
45 # include "cmVisualStudioWCEPlatformParser.h"
59 # include <fcntl.h> // for _O_BINARY
60 # include <io.h> // for _setmode
63 #include <cm/string_view>
65 #include "cmsys/Directory.hxx"
66 #include "cmsys/FStream.hxx"
67 #include "cmsys/Process.h"
68 #include "cmsys/RegularExpression.hxx"
69 #include "cmsys/Terminal.h"
71 int cmcmd_cmake_ninja_depends(std::vector<std::string>::const_iterator argBeg,
72 std::vector<std::string>::const_iterator argEnd);
73 int cmcmd_cmake_ninja_dyndep(std::vector<std::string>::const_iterator argBeg,
74 std::vector<std::string>::const_iterator argEnd);
77 void CMakeCommandUsage(std::string const& program)
79 std::ostringstream errorStream;
81 #ifndef CMAKE_BOOTSTRAP
82 /* clang-format off */
84 << "cmake version " << cmVersion::GetCMakeVersion() << "\n";
87 /* clang-format off */
89 << "cmake bootstrap\n";
92 // If you add new commands, change here,
93 // and in cmakemain.cxx in the options table
94 /* clang-format off */
96 << "Usage: " << program << " -E <command> [arguments...]\n"
97 << "Available commands: \n"
98 << " capabilities - Report capabilities built into cmake "
100 << " cat [--] <files>... - concat the files and print them to the "
102 << " chdir dir cmd [args...] - run command in a given directory\n"
103 << " compare_files [--ignore-eol] file1 file2\n"
104 << " - check if file1 is same as file2\n"
105 << " copy <file>... destination - copy files to destination "
106 "(either file or directory)\n"
107 << " copy_directory <dir>... destination - copy content of <dir>... "
108 "directories to 'destination' directory\n"
109 << " copy_if_different <file>... destination - copy files if it has "
111 << " echo [<string>...] - displays arguments as text\n"
112 << " echo_append [<string>...] - displays arguments as text but no new "
114 << " env [--unset=NAME ...] [NAME=VALUE ...] [--] <command> [<arg>...]\n"
115 << " - run command in a modified environment\n"
116 << " environment - display the current environment\n"
117 << " make_directory <dir>... - create parent and <dir> directories\n"
118 << " md5sum <file>... - create MD5 checksum of files\n"
119 << " sha1sum <file>... - create SHA1 checksum of files\n"
120 << " sha224sum <file>... - create SHA224 checksum of files\n"
121 << " sha256sum <file>... - create SHA256 checksum of files\n"
122 << " sha384sum <file>... - create SHA384 checksum of files\n"
123 << " sha512sum <file>... - create SHA512 checksum of files\n"
124 << " remove [-f] <file>... - remove the file(s), use -f to force "
125 "it (deprecated: use rm instead)\n"
126 << " remove_directory <dir>... - remove directories and their contents (deprecated: use rm instead)\n"
127 << " rename oldname newname - rename a file or directory "
129 << " rm [-rRf] [--] <file/dir>... - remove files or directories, use -f "
130 "to force it, r or R to remove directories and their contents "
132 << " sleep <number>... - sleep for given number of seconds\n"
133 << " tar [cxt][vf][zjJ] file.tar [file/dir1 file/dir2 ...]\n"
134 << " - create or extract a tar or zip archive\n"
135 << " time command [args...] - run command and display elapsed time\n"
136 << " touch <file>... - touch a <file>.\n"
137 << " touch_nocreate <file>... - touch a <file> but do not create it.\n"
138 << " create_symlink old new - create a symbolic link new -> old\n"
139 << " create_hardlink old new - create a hard link new -> old\n"
140 << " true - do nothing with an exit code of 0\n"
141 << " false - do nothing with an exit code of 1\n"
142 #if defined(_WIN32) && !defined(__CYGWIN__)
143 << "Available on Windows only:\n"
144 << " delete_regv key - delete registry value\n"
145 << " env_vs8_wince sdkname - displays a batch file which sets the "
146 "environment for the provided Windows CE SDK installed in VS2005\n"
147 << " env_vs9_wince sdkname - displays a batch file which sets the "
148 "environment for the provided Windows CE SDK installed in VS2008\n"
149 << " write_regv key value - write registry value\n"
152 /* clang-format on */
154 cmSystemTools::Error(errorStream.str());
157 bool cmTarFilesFrom(std::string const& file, std::vector<std::string>& files)
159 if (cmSystemTools::FileIsDirectory(file)) {
160 std::ostringstream e;
161 e << "-E tar --files-from= file '" << file << "' is a directory";
162 cmSystemTools::Error(e.str());
165 cmsys::ifstream fin(file.c_str());
167 std::ostringstream e;
168 e << "-E tar --files-from= file '" << file << "' not found";
169 cmSystemTools::Error(e.str());
173 while (cmSystemTools::GetLineFromStream(fin, line)) {
177 if (cmHasLiteralPrefix(line, "--add-file=")) {
178 files.push_back(line.substr(11));
179 } else if (cmHasLiteralPrefix(line, "-")) {
180 std::ostringstream e;
181 e << "-E tar --files-from='" << file << "' file invalid line:\n"
183 cmSystemTools::Error(e.str());
186 files.push_back(line);
192 void cmCatFile(const std::string& fileToAppend)
195 _setmode(fileno(stdout), _O_BINARY);
197 cmsys::ifstream source(fileToAppend.c_str(),
198 (std::ios::binary | std::ios::in));
199 std::cout << source.rdbuf();
202 bool cmRemoveDirectory(const std::string& dir, bool recursive = true)
204 if (cmSystemTools::FileIsSymlink(dir)) {
205 if (!cmSystemTools::RemoveFile(dir)) {
206 std::cerr << "Error removing directory symlink \"" << dir << "\".\n";
209 } else if (!recursive) {
210 std::cerr << "Error removing directory \"" << dir
211 << "\" without recursive option.\n";
213 } else if (!cmSystemTools::RemoveADirectory(dir)) {
214 std::cerr << "Error removing directory \"" << dir << "\".\n";
220 #if !defined(CMAKE_BOOTSTRAP) || defined(CMAKE_BOOTSTRAP_MAKEFILES)
221 class CLIncludeParser : public cmProcessTools::LineParser
224 CLIncludeParser(cm::string_view includePrefix, cmsys::ofstream& depFile,
225 std::ostream& output)
226 : IncludePrefix(includePrefix)
233 bool ProcessLine() override
235 if (cmHasPrefix(this->Line, this->IncludePrefix)) {
237 cmTrimWhitespace(this->Line.c_str() + this->IncludePrefix.size());
238 cmSystemTools::ConvertToLongPath(path);
239 this->DepFile << cmCMakePath(path).GenericString() << std::endl;
241 this->Output << this->Line << std::endl << std::flush;
247 cm::string_view IncludePrefix;
248 cmsys::ofstream& DepFile;
249 std::ostream& Output;
252 class CLOutputLogger : public cmProcessTools::OutputLogger
255 CLOutputLogger(std::ostream& log)
256 : cmProcessTools::OutputLogger(log)
260 bool ProcessLine() override
262 *this->Log << std::flush;
267 int CLCompileAndDependencies(const std::vector<std::string>& args)
270 std::string currentBinaryDir;
271 std::string filterPrefix;
272 std::vector<std::string> command;
273 for (auto it = args.cbegin() + 2; it != args.cend(); it++) {
274 if (cmHasLiteralPrefix(*it, "--dep-file=")) {
275 depFile = it->substr(11);
276 } else if (cmHasLiteralPrefix(*it, "--working-dir=")) {
277 currentBinaryDir = it->substr(14);
278 } else if (cmHasLiteralPrefix(*it, "--filter-prefix=")) {
279 filterPrefix = it->substr(16);
280 } else if (*it == "--") {
281 command.insert(command.begin(), ++it, args.cend());
288 std::unique_ptr<cmsysProcess, void (*)(cmsysProcess*)> cp(
289 cmsysProcess_New(), cmsysProcess_Delete);
290 std::vector<const char*> argv(command.size() + 1);
291 std::transform(command.begin(), command.end(), argv.begin(),
292 [](std::string const& s) { return s.c_str(); });
293 argv.back() = nullptr;
294 cmsysProcess_SetCommand(cp.get(), argv.data());
295 cmsysProcess_SetWorkingDirectory(cp.get(), currentBinaryDir.c_str());
297 cmsys::ofstream fout(depFile.c_str());
302 CLIncludeParser includeParser(filterPrefix, fout, std::cout);
303 CLOutputLogger errLogger(std::cerr);
305 // Start the process.
306 cmProcessTools::RunProcess(cp.get(), &includeParser, &errLogger);
309 // handle status of process
310 switch (cmsysProcess_GetState(cp.get())) {
311 case cmsysProcess_State_Exited:
312 status = cmsysProcess_GetExitValue(cp.get());
314 case cmsysProcess_State_Exception:
317 case cmsysProcess_State_Error:
325 // remove the dependencies file because potentially invalid
327 cmSystemTools::RemoveFile(depFile);
334 int HandleIWYU(const std::string& runCmd, const std::string& /* sourceFile */,
335 const std::vector<std::string>& orig_cmd)
337 // Construct the iwyu command line by taking what was given
338 // and adding all the arguments we give to the compiler.
339 std::vector<std::string> iwyu_cmd = cmExpandedList(runCmd, true);
340 cm::append(iwyu_cmd, orig_cmd.begin() + 1, orig_cmd.end());
341 // Run the iwyu command line. Capture its stderr and hide its stdout.
342 // Ignore its return code because the tool always returns non-zero.
345 if (!cmSystemTools::RunSingleCommand(iwyu_cmd, nullptr, &stdErr, &ret,
346 nullptr, cmSystemTools::OUTPUT_NONE)) {
347 std::cerr << "Error running '" << iwyu_cmd[0] << "': " << stdErr << "\n";
350 // Warn if iwyu reported anything.
351 if (stdErr.find("should remove these lines:") != std::string::npos ||
352 stdErr.find("should add these lines:") != std::string::npos) {
353 std::cerr << "Warning: include-what-you-use reported diagnostics:\n"
356 // always return 0 we don't want to break the compile
360 int HandleTidy(const std::string& runCmd, const std::string& sourceFile,
361 const std::vector<std::string>& orig_cmd)
363 std::vector<std::string> tidy_cmd = cmExpandedList(runCmd, true);
364 tidy_cmd.push_back(sourceFile);
366 // clang-tidy supports working out the compile commands from a
367 // compile_commands.json file in a directory given by a "-p" option, or by
368 // passing the compiler command line arguments after --. When the latter
369 // strategy is used and the build is using a compiler other than the system
370 // default, clang-tidy may erroneously use the system default compiler's
371 // headers instead of those from the custom compiler. It doesn't do that if
372 // given a compile_commands.json to work with instead, so prefer to use the
373 // compile_commands.json file when "-p" is present.
374 if (!cm::contains(tidy_cmd.cbegin(), tidy_cmd.cend() - 1, "-p")) {
375 // Construct the clang-tidy command line by taking what was given
376 // and adding our compiler command line. The clang-tidy tool will
377 // automatically skip over the compiler itself and extract the
378 // options. If the compiler is a custom compiler, clang-tidy might
379 // not correctly handle that with this approach.
380 tidy_cmd.emplace_back("--");
381 cm::append(tidy_cmd, orig_cmd);
384 // Run the tidy command line. Capture its stdout and hide its stderr.
388 if (!cmSystemTools::RunSingleCommand(tidy_cmd, &stdOut, &stdErr, &ret,
389 nullptr, cmSystemTools::OUTPUT_NONE)) {
390 std::cerr << "Error running '" << tidy_cmd[0] << "': " << stdErr << "\n";
393 // Output the stdout from clang-tidy to stderr
395 // If clang-tidy exited with an error do the same.
402 int HandleLWYU(const std::string& runCmd, const std::string& sourceFile,
403 const std::vector<std::string>&)
405 // Construct the ldd -r -u (link what you use lwyu) command line
406 // ldd -u -r lwuy target
407 std::vector<std::string> lwyu_cmd = cmExpandedList(runCmd, true);
408 lwyu_cmd.push_back(sourceFile);
410 // Run the lwyu check command line, currently ldd is expected.
411 // Capture its stdout and hide its stderr.
412 // Ignore its return code because the tool always returns non-zero
413 // if there are any warnings, but we just want to warn.
417 if (!cmSystemTools::RunSingleCommand(lwyu_cmd, &stdOut, &stdErr, &ret,
418 nullptr, cmSystemTools::OUTPUT_NONE)) {
419 std::cerr << "Error running '" << lwyu_cmd[0] << "': " << stdErr << "\n";
423 // Output the stdout from ldd -r -u to stderr
424 // Warn if lwyu reported anything.
425 if (stdOut.find("Unused direct dependencies:") != std::string::npos) {
426 std::cerr << "Warning: " << stdOut;
431 int HandleCppLint(const std::string& runCmd, const std::string& sourceFile,
432 const std::vector<std::string>&)
434 // Construct the cpplint command line.
435 std::vector<std::string> cpplint_cmd = cmExpandedList(runCmd, true);
436 cpplint_cmd.push_back(sourceFile);
438 // Run the cpplint command line. Capture its output.
441 if (!cmSystemTools::RunSingleCommand(cpplint_cmd, &stdOut, &stdOut, &ret,
442 nullptr, cmSystemTools::OUTPUT_NONE)) {
443 std::cerr << "Error running '" << cpplint_cmd[0] << "': " << stdOut
447 if (!stdOut.empty()) {
448 std::cerr << "Warning: cpplint diagnostics:\n";
449 // Output the output from cpplint to stderr
453 // always return 0 so the build can continue as cpplint returns non-zero
458 int HandleCppCheck(const std::string& runCmd, const std::string& sourceFile,
459 const std::vector<std::string>& orig_cmd)
461 // Construct the cpplint command line.
462 std::vector<std::string> cppcheck_cmd = cmExpandedList(runCmd, true);
463 // extract all the -D, -U, and -I options from the compile line
464 for (auto const& opt : orig_cmd) {
465 if (opt.size() > 2) {
466 if ((opt[0] == '-') &&
467 ((opt[1] == 'D') || (opt[1] == 'I') || (opt[1] == 'U'))) {
468 cppcheck_cmd.push_back(opt);
469 // convert cl / options to - options if needed
471 } else if ((opt[0] == '/') &&
472 ((opt[1] == 'D') || (opt[1] == 'I') || (opt[1] == 'U'))) {
473 std::string optcopy = opt;
475 cppcheck_cmd.push_back(optcopy);
480 // add the source file
481 cppcheck_cmd.push_back(sourceFile);
483 // Run the cpplint command line. Capture its output.
487 if (!cmSystemTools::RunSingleCommand(cppcheck_cmd, &stdOut, &stdErr, &ret,
488 nullptr, cmSystemTools::OUTPUT_NONE)) {
489 std::cerr << "Error running '" << cppcheck_cmd[0] << "': " << stdOut
494 // Output the output from cpplint to stderr
495 if (stdErr.find("(error)") != std::string::npos ||
496 stdErr.find("(warning)") != std::string::npos ||
497 stdErr.find("(style)") != std::string::npos ||
498 stdErr.find("(performance)") != std::string::npos ||
499 stdErr.find("(portability)") != std::string::npos ||
500 stdErr.find("(information)") != std::string::npos) {
502 std::cerr << "Warning: cppcheck reported diagnostics:\n";
504 std::cerr << "Error: cppcheck reported failure:\n";
512 using CoCompileHandler = int (*)(const std::string&, const std::string&,
513 const std::vector<std::string>&);
518 CoCompileHandler Handler;
519 bool NoOriginalCommand;
522 const std::array<CoCompiler, 5> CoCompilers = {
523 { // Table of options and handlers.
524 { "--cppcheck=", HandleCppCheck, false },
525 { "--cpplint=", HandleCppLint, false },
526 { "--iwyu=", HandleIWYU, false },
527 { "--lwyu=", HandleLWYU, true },
528 { "--tidy=", HandleTidy, false } }
534 CoCompileHandler Handler;
538 // called when args[0] == "__run_co_compile"
539 int cmcmd::HandleCoCompileCommands(std::vector<std::string> const& args)
541 std::vector<CoCompileJob> jobs;
542 std::string sourceFile; // store --source=
543 std::vector<std::string> launchers; // store --launcher=
545 // Default is to run the original command found after -- if the option
546 // does not need to do that, it should be specified here, currently only
548 bool runOriginalCmd = true;
550 std::vector<std::string> orig_cmd;
551 bool doing_options = true;
552 for (std::string const& arg : cmMakeRange(args).advance(2)) {
553 // if the arg is -- then the rest of the args after
556 doing_options = false;
557 } else if (doing_options) {
558 bool optionFound = false;
559 for (CoCompiler const& cc : CoCompilers) {
560 size_t optionLen = strlen(cc.Option);
561 if (arg.compare(0, optionLen, cc.Option) == 0) {
564 job.Command = arg.substr(optionLen);
565 job.Handler = cc.Handler;
566 jobs.push_back(std::move(job));
567 if (cc.NoOriginalCommand) {
568 runOriginalCmd = false;
573 if (cmHasLiteralPrefix(arg, "--source=")) {
574 sourceFile = arg.substr(9);
575 } else if (cmHasLiteralPrefix(arg, "--launcher=")) {
576 cmExpandList(arg.substr(11), launchers, true);
578 // if it was not a co-compiler or --source/--launcher then error
579 std::cerr << "__run_co_compile given unknown argument: " << arg
584 } else { // if not doing_options then push to orig_cmd
585 orig_cmd.push_back(arg);
589 std::cerr << "__run_co_compile missing command to run. "
590 "Looking for one or more of the following:\n";
591 for (CoCompiler const& cc : CoCompilers) {
592 std::cerr << cc.Option << "\n";
597 if (runOriginalCmd && orig_cmd.empty()) {
598 std::cerr << "__run_co_compile missing compile command after --\n";
602 for (CoCompileJob const& job : jobs) {
603 // call the command handler here
604 int ret = job.Handler(job.Command, sourceFile, orig_cmd);
606 // if the command returns non-zero then return and fail.
607 // for commands that do not want to break the build, they should return
614 // if there is no original command to run return now
615 if (!runOriginalCmd) {
619 // Prepend launcher argument(s), if any
620 if (!launchers.empty()) {
621 orig_cmd.insert(orig_cmd.begin(), launchers.begin(), launchers.end());
624 // Now run the real compiler command and return its result value
626 if (!cmSystemTools::RunSingleCommand(orig_cmd, nullptr, nullptr, &ret,
628 cmSystemTools::OUTPUT_PASSTHROUGH)) {
629 std::cerr << "Error running '" << orig_cmd[0] << "'\n";
632 // return the return value from the original compiler command
636 int cmcmd::ExecuteCMakeCommand(std::vector<std::string> const& args,
637 std::unique_ptr<cmConsoleBuf> consoleBuf)
639 // IF YOU ADD A NEW COMMAND, DOCUMENT IT ABOVE and in cmakemain.cxx
640 if (args.size() > 1) {
642 if (args[1] == "copy" && args.size() > 3) {
643 // If multiple source files specified,
644 // then destination must be directory
645 if ((args.size() > 4) &&
646 (!cmSystemTools::FileIsDirectory(args.back()))) {
647 std::cerr << "Error: Target (for copy command) \"" << args.back()
648 << "\" is not a directory.\n";
651 // If error occurs we want to continue copying next files.
652 bool return_value = false;
653 for (auto const& arg : cmMakeRange(args).advance(2).retreat(1)) {
654 if (!cmsys::SystemTools::CopyFileAlways(arg, args.back())) {
655 std::cerr << "Error copying file \"" << arg << "\" to \""
656 << args.back() << "\".\n";
663 // Copy file if different.
664 if (args[1] == "copy_if_different" && args.size() > 3) {
665 // If multiple source files specified,
666 // then destination must be directory
667 if ((args.size() > 4) &&
668 (!cmSystemTools::FileIsDirectory(args.back()))) {
669 std::cerr << "Error: Target (for copy_if_different command) \""
670 << args.back() << "\" is not a directory.\n";
673 // If error occurs we want to continue copying next files.
674 bool return_value = false;
675 for (auto const& arg : cmMakeRange(args).advance(2).retreat(1)) {
676 if (!cmSystemTools::CopyFileIfDifferent(arg, args.back())) {
677 std::cerr << "Error copying file (if different) from \"" << arg
678 << "\" to \"" << args.back() << "\".\n";
685 // Copy directory content
686 if (args[1] == "copy_directory" && args.size() > 3) {
687 // If error occurs we want to continue copying next files.
688 bool return_value = false;
689 for (auto const& arg : cmMakeRange(args).advance(2).retreat(1)) {
690 if (!cmSystemTools::CopyADirectory(arg, args.back())) {
691 std::cerr << "Error copying directory from \"" << arg << "\" to \""
692 << args.back() << "\".\n";
699 // Rename a file or directory
700 if (args[1] == "rename" && args.size() == 4) {
701 if (!cmSystemTools::RenameFile(args[2], args[3])) {
702 std::string e = cmSystemTools::GetLastSystemError();
703 std::cerr << "Error renaming from \"" << args[2] << "\" to \""
704 << args[3] << "\": " << e << "\n";
711 if (args[1] == "compare_files" && (args.size() == 4 || args.size() == 5)) {
713 if (args.size() == 4) {
714 filesDiffer = cmSystemTools::FilesDiffer(args[2], args[3]);
715 } else if (args[2] == "--ignore-eol") {
716 filesDiffer = cmsys::SystemTools::TextFilesDiffer(args[3], args[4]);
718 CMakeCommandUsage(args[0]);
728 #if !defined(CMAKE_BOOTSTRAP)
729 if (args[1] == "__create_def") {
730 if (args.size() < 4) {
731 std::cerr << "__create_def Usage: -E __create_def outfile.def "
732 "objlistfile [--nm=nm-path]\n";
735 cmsys::ifstream fin(args[3].c_str(), std::ios::in | std::ios::binary);
737 std::cerr << "could not open object list file: " << args[3] << "\n";
740 std::vector<std::string> files;
744 bool outValid = outTime.Load(args[2]);
745 while (cmSystemTools::GetLineFromStream(fin, file)) {
746 files.push_back(file);
749 outValid = inTime.Load(file) && inTime.Older(outTime);
753 // The def file already exists and all input files are older than
754 // the existing def file.
758 FILE* fout = cmsys::SystemTools::Fopen(args[2], "w+");
760 std::cerr << "could not open output .def file: " << args[2] << "\n";
764 if (args.size() >= 5) {
765 std::string const& a = args[4];
766 if (cmHasLiteralPrefix(a, "--nm=")) {
767 deffile.SetNmPath(a.substr(5));
769 std::cerr << "unknown argument: " << a << "\n";
772 for (std::string const& file : files) {
773 std::string const& ext = cmSystemTools::GetFilenameLastExtension(file);
774 if (cmSystemTools::LowerCase(ext) == ".def") {
775 if (!deffile.AddDefinitionFile(file.c_str())) {
779 if (!deffile.AddObjectFile(file.c_str())) {
784 deffile.WriteFile(fout);
789 if (args[1] == "__run_co_compile") {
790 return cmcmd::HandleCoCompileCommands(args);
794 if (args[1] == "echo") {
795 std::cout << cmJoin(cmMakeRange(args).advance(2), " ") << std::endl;
799 // Echo string no new line
800 if (args[1] == "echo_append") {
801 std::cout << cmJoin(cmMakeRange(args).advance(2), " ");
805 if (args[1] == "env") {
806 #ifndef CMAKE_BOOTSTRAP
807 cmSystemTools::EnvDiff env;
810 auto ai = args.cbegin() + 2;
811 auto ae = args.cend();
812 for (; ai != ae; ++ai) {
813 std::string const& a = *ai;
815 // Stop parsing options/environment variables; the next argument
816 // should be the command.
820 if (cmHasLiteralPrefix(a, "--unset=")) {
821 // Unset environment variable.
822 #ifdef CMAKE_BOOTSTRAP
823 cmSystemTools::UnPutEnv(a.substr(8));
825 env.UnPutEnv(a.substr(8));
827 } else if (a == "--modify") {
828 #ifdef CMAKE_BOOTSTRAP
830 << "cmake -E env: --modify not available during bootstrapping\n";
834 std::cerr << "cmake -E env: --modify missing a parameter\n";
837 std::string const& op = *ai;
838 if (!env.ParseOperation(op)) {
839 std::cerr << "cmake -E env: invalid parameter to --modify: " << op
844 } else if (!a.empty() && a[0] == '-') {
845 // Environment variable and command names cannot start in '-',
846 // so this must be an unknown option.
847 std::cerr << "cmake -E env: unknown option '" << a << "'\n";
849 } else if (a.find('=') != std::string::npos) {
850 // Set environment variable.
851 #ifdef CMAKE_BOOTSTRAP
852 cmSystemTools::PutEnv(a);
857 // This is the beginning of the command.
863 std::cerr << "cmake -E env: no command given\n";
867 #ifndef CMAKE_BOOTSTRAP
868 env.ApplyToCurrentEnv();
871 // Execute command from remaining arguments.
872 std::vector<std::string> cmd(ai, ae);
874 if (cmSystemTools::RunSingleCommand(cmd, nullptr, nullptr, &retval,
876 cmSystemTools::OUTPUT_PASSTHROUGH)) {
882 #if !defined(CMAKE_BOOTSTRAP)
883 if (args[1] == "environment") {
884 for (auto const& env : cmSystemTools::GetEnvironmentVariables()) {
885 std::cout << env << std::endl;
891 if (args[1] == "make_directory" && args.size() > 2) {
892 // If an error occurs, we want to continue making directories.
893 bool return_value = false;
894 for (auto const& arg : cmMakeRange(args).advance(2)) {
895 if (!cmSystemTools::MakeDirectory(arg)) {
896 std::cerr << "Error creating directory \"" << arg << "\".\n";
903 if (args[1] == "remove_directory" && args.size() > 2) {
904 // If an error occurs, we want to continue removing directories.
905 bool return_value = false;
906 for (auto const& arg : cmMakeRange(args).advance(2)) {
907 if (cmSystemTools::FileIsDirectory(arg)) {
908 if (!cmRemoveDirectory(arg)) {
917 if (args[1] == "remove" && args.size() > 2) {
919 for (auto const& arg : cmMakeRange(args).advance(2)) {
920 if (arg == "\\-f" || arg == "-f") {
923 // Complain if the file could not be removed, still exists,
924 // and the -f option was not given.
925 if (!cmSystemTools::RemoveFile(arg) && !force &&
926 cmSystemTools::FileExists(arg)) {
934 // Remove directories or files with rm
935 if (args[1] == "rm" && args.size() > 2) {
936 // If an error occurs, we want to continue removing the remaining
937 // files/directories.
938 int return_value = 0;
940 bool recursive = false;
941 bool doing_options = true;
942 bool at_least_one_file = false;
943 for (auto const& arg : cmMakeRange(args).advance(2)) {
944 if (doing_options && cmHasLiteralPrefix(arg, "-")) {
946 doing_options = false;
948 if (arg.find('f') != std::string::npos) {
951 if (arg.find_first_of("rR") != std::string::npos) {
954 if (arg.find_first_not_of("-frR") != std::string::npos) {
955 cmSystemTools::Error("Unknown -E rm argument: " + arg);
962 at_least_one_file = true;
963 // Complain if the -f option was not given and
964 // either file does not exist or
965 // file could not be removed and still exists
966 bool file_exists_or_forced_remove = cmSystemTools::FileExists(arg) ||
967 cmSystemTools::FileIsSymlink(arg) || force;
968 if (cmSystemTools::FileIsDirectory(arg)) {
969 if (!cmRemoveDirectory(arg, recursive)) {
972 } else if ((!file_exists_or_forced_remove) ||
973 (!cmSystemTools::RemoveFile(arg) &&
974 cmSystemTools::FileExists(arg))) {
975 if (!file_exists_or_forced_remove) {
976 cmSystemTools::Error(
977 "File to remove does not exist and force is not set: " + arg);
979 cmSystemTools::Error("File can't be removed and still exist: " +
986 if (!at_least_one_file) {
987 cmSystemTools::Error("Missing file/directory to remove");
994 if (args[1] == "touch" && args.size() > 2) {
995 for (auto const& arg : cmMakeRange(args).advance(2)) {
996 if (!cmSystemTools::Touch(arg, true)) {
997 std::cerr << "cmake -E touch: failed to update \"";
998 std::cerr << arg << "\".\n";
1006 if (args[1] == "touch_nocreate" && args.size() > 2) {
1007 for (auto const& arg : cmMakeRange(args).advance(2)) {
1008 if (!cmSystemTools::Touch(arg, false)) {
1009 std::cerr << "cmake -E touch_nocreate: failed to update \"";
1010 std::cerr << arg << "\".\n";
1018 if (args[1] == "capabilities") {
1019 if (args.size() > 2) {
1020 std::cerr << "-E capabilities accepts no additional arguments\n";
1023 cmake cm(cmake::RoleInternal, cmState::Unknown);
1024 std::cout << cm.ReportCapabilities();
1029 if (args[1] == "sleep" && args.size() > 2) {
1031 for (auto const& arg : cmMakeRange(args).advance(2)) {
1035 int n = sscanf(arg.c_str(), "%lg%c%c", &num, &unit, &extra);
1036 if ((n == 1 || (n == 2 && unit == 's')) && num >= 0) {
1039 std::cerr << "Unknown sleep time format \"" << arg << "\".\n";
1044 cmSystemTools::Delay(static_cast<unsigned int>(total * 1000));
1050 if (args[1] == "time" && args.size() > 2) {
1051 std::vector<std::string> command(args.begin() + 2, args.end());
1053 clock_t clock_start;
1054 clock_t clock_finish;
1059 clock_start = clock();
1061 cmSystemTools::RunSingleCommand(command, nullptr, nullptr, &ret);
1063 clock_finish = clock();
1066 double clocks_per_sec = static_cast<double>(CLOCKS_PER_SEC);
1067 std::cout << "Elapsed time: "
1068 << static_cast<long>(time_finish - time_start) << " s. (time)"
1070 << static_cast<double>(clock_finish - clock_start) /
1077 // Command to calculate the md5sum of a file
1078 if (args[1] == "md5sum" && args.size() >= 3) {
1079 return HashSumFile(args, cmCryptoHash::AlgoMD5);
1082 // Command to calculate the sha1sum of a file
1083 if (args[1] == "sha1sum" && args.size() >= 3) {
1084 return HashSumFile(args, cmCryptoHash::AlgoSHA1);
1087 if (args[1] == "sha224sum" && args.size() >= 3) {
1088 return HashSumFile(args, cmCryptoHash::AlgoSHA224);
1091 if (args[1] == "sha256sum" && args.size() >= 3) {
1092 return HashSumFile(args, cmCryptoHash::AlgoSHA256);
1095 if (args[1] == "sha384sum" && args.size() >= 3) {
1096 return HashSumFile(args, cmCryptoHash::AlgoSHA384);
1099 if (args[1] == "sha512sum" && args.size() >= 3) {
1100 return HashSumFile(args, cmCryptoHash::AlgoSHA512);
1103 // Command to concat files into one
1104 if (args[1] == "cat" && args.size() >= 3) {
1105 int return_value = 0;
1106 bool doing_options = true;
1107 for (auto const& arg : cmMakeRange(args).advance(2)) {
1108 if (doing_options && cmHasLiteralPrefix(arg, "-")) {
1110 doing_options = false;
1112 cmSystemTools::Error(arg + ": option not handled");
1115 } else if (!cmSystemTools::TestFileAccess(arg,
1116 cmsys::TEST_FILE_READ) &&
1117 cmSystemTools::TestFileAccess(arg, cmsys::TEST_FILE_OK)) {
1118 cmSystemTools::Error(arg + ": permission denied (ignoring)");
1120 } else if (cmSystemTools::FileIsDirectory(arg)) {
1121 cmSystemTools::Error(arg + ": is a directory (ignoring)");
1123 } else if (!cmSystemTools::FileExists(arg)) {
1124 cmSystemTools::Error(arg + ": no such file or directory (ignoring)");
1126 } else if (cmSystemTools::FileLength(arg) == 0) {
1127 // Ignore empty files, this is not an error
1129 // Destroy console buffers to drop cout/cerr encoding transform.
1134 return return_value;
1137 // Command to change directory and run a program.
1138 if (args[1] == "chdir" && args.size() >= 4) {
1139 std::string const& directory = args[2];
1140 if (!cmSystemTools::FileExists(directory)) {
1141 cmSystemTools::Error("Directory does not exist for chdir command: " +
1146 std::string command =
1147 cmWrap('"', cmMakeRange(args).advance(3), '"', " ");
1149 if (cmSystemTools::RunSingleCommand(
1150 command, nullptr, nullptr, &retval, directory.c_str(),
1151 cmSystemTools::OUTPUT_PASSTHROUGH, cmDuration::zero())) {
1158 // Command to start progress for a build
1159 if (args[1] == "cmake_progress_start" && args.size() == 4) {
1160 // basically remove the directory
1161 std::string dirName = cmStrCat(args[2], "/Progress");
1162 cmSystemTools::RemoveADirectory(dirName);
1164 // is the last argument a filename that exists?
1165 FILE* countFile = cmsys::SystemTools::Fopen(args[3], "r");
1168 if (1 != fscanf(countFile, "%i", &count)) {
1169 std::cerr << "Could not read from count file.\n";
1173 count = atoi(args[3].c_str());
1176 cmSystemTools::MakeDirectory(dirName);
1177 // write the count into the directory
1178 std::string fName = cmStrCat(dirName, "/count.txt");
1179 FILE* progFile = cmsys::SystemTools::Fopen(fName, "w");
1181 fprintf(progFile, "%i\n", count);
1188 // Command to report progress for a build
1189 if (args[1] == "cmake_progress_report" && args.size() >= 3) {
1190 // This has been superseded by cmake_echo_color --progress-*
1191 // options. We leave it here to avoid errors if somehow this
1192 // is invoked by an existing makefile without regenerating.
1196 // Command to create a symbolic link. Fails on platforms not
1198 if (args[1] == "create_symlink" && args.size() == 4) {
1199 std::string const& destinationFileName = args[3];
1200 if ((cmSystemTools::FileExists(destinationFileName) ||
1201 cmSystemTools::FileIsSymlink(destinationFileName)) &&
1202 !cmSystemTools::RemoveFile(destinationFileName)) {
1203 std::string emsg = cmSystemTools::GetLastSystemError();
1204 std::cerr << "failed to create symbolic link '" << destinationFileName
1205 << "' because existing path cannot be removed: " << emsg
1209 if (!cmSystemTools::CreateSymlink(args[2], destinationFileName)) {
1215 // Command to create a hard link. Fails on platforms not
1217 if (args[1] == "create_hardlink" && args.size() == 4) {
1218 std::string const& sourceFileName = args[2];
1219 std::string const& destinationFileName = args[3];
1221 if (!cmSystemTools::FileExists(sourceFileName)) {
1222 std::cerr << "failed to create hard link because source path '"
1223 << sourceFileName << "' does not exist \n";
1227 if ((cmSystemTools::FileExists(destinationFileName) ||
1228 cmSystemTools::FileIsSymlink(destinationFileName)) &&
1229 !cmSystemTools::RemoveFile(destinationFileName)) {
1230 std::string emsg = cmSystemTools::GetLastSystemError();
1231 std::cerr << "failed to create hard link '" << destinationFileName
1232 << "' because existing path cannot be removed: " << emsg
1237 if (!cmSystemTools::CreateLink(sourceFileName, destinationFileName)) {
1243 // Command to do nothing with an exit code of 0.
1244 if (args[1] == "true") {
1248 // Command to do nothing with an exit code of 1.
1249 if (args[1] == "false") {
1253 // Internal CMake shared library support.
1254 if (args[1] == "cmake_symlink_library" && args.size() == 5) {
1255 return cmcmd::SymlinkLibrary(args);
1258 // Internal CMake versioned executable support.
1259 if (args[1] == "cmake_symlink_executable" && args.size() == 4) {
1260 return cmcmd::SymlinkExecutable(args);
1263 // Internal CMake dependency scanning support.
1264 if (args[1] == "cmake_depends" && args.size() >= 6) {
1265 const bool verbose = isCMakeVerbose();
1267 // Create a cmake object instance to process dependencies.
1268 // All we need is the `set` command.
1269 cmake cm(cmake::RoleScript, cmState::Unknown);
1271 std::string homeDir;
1272 std::string startDir;
1273 std::string homeOutDir;
1274 std::string startOutDir;
1275 std::string depInfo;
1277 if (args.size() >= 8) {
1280 // -E cmake_depends <generator>
1281 // <home-src-dir> <start-src-dir>
1282 // <home-out-dir> <start-out-dir>
1283 // <dep-info> [--color=$(COLOR)]
1285 // All paths are provided.
1289 homeOutDir = args[5];
1290 startOutDir = args[6];
1292 if (args.size() >= 9 && cmHasLiteralPrefix(args[8], "--color=")) {
1293 // Enable or disable color based on the switch value.
1294 color = (args[8].size() == 8 || cmIsOn(args[8].substr(8)));
1297 // Support older signature for existing makefiles:
1299 // -E cmake_depends <generator>
1300 // <home-out-dir> <start-out-dir>
1303 // Just pretend the source directories are the same as the
1304 // binary directories so at least scanning will work.
1308 homeOutDir = args[3];
1309 startOutDir = args[3];
1313 // Create a local generator configured for the directory in
1314 // which dependencies will be scanned.
1315 homeDir = cmSystemTools::CollapseFullPath(homeDir);
1316 startDir = cmSystemTools::CollapseFullPath(startDir);
1317 homeOutDir = cmSystemTools::CollapseFullPath(homeOutDir);
1318 startOutDir = cmSystemTools::CollapseFullPath(startOutDir);
1319 cm.SetHomeDirectory(homeDir);
1320 cm.SetHomeOutputDirectory(homeOutDir);
1321 cm.GetCurrentSnapshot().SetDefaultDefinitions();
1322 if (auto ggd = cm.CreateGlobalGenerator(gen)) {
1323 cm.SetGlobalGenerator(std::move(ggd));
1324 cmStateSnapshot snapshot = cm.GetCurrentSnapshot();
1325 snapshot.GetDirectory().SetCurrentBinary(startOutDir);
1326 snapshot.GetDirectory().SetCurrentSource(startDir);
1327 cmMakefile mf(cm.GetGlobalGenerator(), snapshot);
1328 auto lgd = cm.GetGlobalGenerator()->CreateLocalGenerator(&mf);
1330 // FIXME: With advanced add_subdirectory usage, these are
1331 // not necessarily the same as the generator originally used.
1332 // We should pass all these directories through an info file.
1333 lgd->SetRelativePathTop(homeDir, homeOutDir);
1335 // Actually scan dependencies.
1336 return lgd->UpdateDependencies(depInfo, verbose, color) ? 0 : 2;
1341 #if !defined(CMAKE_BOOTSTRAP) || defined(CMAKE_BOOTSTRAP_MAKEFILES)
1342 // Internal CMake compiler dependencies filtering
1343 if (args[1] == "cmake_cl_compile_depends") {
1344 return CLCompileAndDependencies(args);
1348 // Internal CMake link script support.
1349 if (args[1] == "cmake_link_script" && args.size() >= 3) {
1350 return cmcmd::ExecuteLinkScript(args);
1353 #if !defined(CMAKE_BOOTSTRAP)
1354 // Internal CMake ninja dependency scanning support.
1355 if (args[1] == "cmake_ninja_depends") {
1356 return cmcmd_cmake_ninja_depends(args.begin() + 2, args.end());
1359 // Internal CMake ninja dyndep support.
1360 if (args[1] == "cmake_ninja_dyndep") {
1361 return cmcmd_cmake_ninja_dyndep(args.begin() + 2, args.end());
1365 // Internal CMake unimplemented feature notification.
1366 if (args[1] == "cmake_unimplemented_variable") {
1367 std::cerr << "Feature not implemented for this platform.";
1368 if (args.size() == 3) {
1369 std::cerr << " Variable " << args[2] << " is not set.";
1371 std::cerr << std::endl;
1375 if (args[1] == "vs_link_exe") {
1376 return cmcmd::VisualStudioLink(args, 1);
1379 if (args[1] == "vs_link_dll") {
1380 return cmcmd::VisualStudioLink(args, 2);
1383 if (args[1] == "cmake_llvm_rc") {
1384 return cmcmd::RunLLVMRC(args);
1387 // Internal CMake color makefile support.
1388 if (args[1] == "cmake_echo_color") {
1389 return cmcmd::ExecuteEchoColor(args);
1392 #ifndef CMAKE_BOOTSTRAP
1393 if ((args[1] == "cmake_autogen") && (args.size() >= 4)) {
1394 cm::string_view const infoFile = args[2];
1395 cm::string_view const config = args[3];
1396 return cmQtAutoMocUic(infoFile, config) ? 0 : 1;
1398 if ((args[1] == "cmake_autorcc") && (args.size() >= 3)) {
1399 cm::string_view const infoFile = args[2];
1400 cm::string_view const config =
1401 (args.size() > 3) ? cm::string_view(args[3]) : cm::string_view();
1402 return cmQtAutoRcc(infoFile, config) ? 0 : 1;
1407 if (args[1] == "tar" && args.size() > 3) {
1408 const char* knownFormats[] = { "7zip", "gnutar", "pax", "paxr", "zip" };
1410 std::string const& flags = args[2];
1411 std::string const& outFile = args[3];
1412 std::vector<std::string> files;
1415 cmSystemTools::cmTarExtractTimestamps extractTimestamps =
1416 cmSystemTools::cmTarExtractTimestamps::Yes;
1417 cmSystemTools::cmTarCompression compress =
1418 cmSystemTools::TarCompressNone;
1420 bool doing_options = true;
1421 for (auto const& arg : cmMakeRange(args).advance(4)) {
1422 if (doing_options && cmHasLiteralPrefix(arg, "--")) {
1424 doing_options = false;
1425 } else if (arg == "--zstd") {
1426 compress = cmSystemTools::TarCompressZstd;
1428 } else if (cmHasLiteralPrefix(arg, "--mtime=")) {
1429 mtime = arg.substr(8);
1430 } else if (cmHasLiteralPrefix(arg, "--files-from=")) {
1431 std::string const& files_from = arg.substr(13);
1432 if (!cmTarFilesFrom(files_from, files)) {
1435 } else if (cmHasLiteralPrefix(arg, "--format=")) {
1436 format = arg.substr(9);
1437 if (!cm::contains(knownFormats, format)) {
1438 cmSystemTools::Error("Unknown -E tar --format= argument: " +
1442 } else if (arg == "--touch") {
1443 extractTimestamps = cmSystemTools::cmTarExtractTimestamps::No;
1445 cmSystemTools::Error("Unknown option to -E tar: " + arg);
1449 files.push_back(arg);
1452 cmSystemTools::cmTarAction action = cmSystemTools::TarActionNone;
1453 bool verbose = false;
1455 for (auto flag : flags) {
1459 // Keep for backward compatibility. Ignored
1462 compress = cmSystemTools::TarCompressBZip2;
1466 compress = cmSystemTools::TarCompressXZ;
1470 compress = cmSystemTools::TarCompressGZip;
1477 action = cmSystemTools::TarActionList;
1480 action = cmSystemTools::TarActionCreate;
1483 action = cmSystemTools::TarActionExtract;
1486 std::cerr << "tar: Unknown argument: " << flag << "\n";
1490 if ((format == "7zip" || format == "zip") && nCompress > 0) {
1491 cmSystemTools::Error("Can not use compression flags with format: " +
1495 if (nCompress > 1) {
1496 cmSystemTools::Error("Can only compress a tar file one way; "
1497 "at most one flag of z, j, or J may be used");
1500 if (action == cmSystemTools::TarActionList) {
1501 if (!cmSystemTools::ListTar(outFile, files, verbose)) {
1502 cmSystemTools::Error("Problem listing tar: " + outFile);
1505 } else if (action == cmSystemTools::TarActionCreate) {
1506 if (files.empty()) {
1507 std::cerr << "tar: No files or directories specified\n";
1509 if (!cmSystemTools::CreateTar(outFile, files, compress, verbose, mtime,
1511 cmSystemTools::Error("Problem creating tar: " + outFile);
1514 } else if (action == cmSystemTools::TarActionExtract) {
1515 if (!cmSystemTools::ExtractTar(outFile, files, extractTimestamps,
1517 cmSystemTools::Error("Problem extracting tar: " + outFile);
1521 // OK, on windows 7 after we untar some files,
1522 // sometimes we can not rename the directory after
1523 // the untar is done. This breaks the external project
1524 // untar and rename code. So, by default we will wait
1525 // 1/10th of a second after the untar. If CMAKE_UNTAR_DELAY
1526 // is set in the env, its value will be used instead of 100.
1528 std::string delayVar;
1529 if (cmSystemTools::GetEnv("CMAKE_UNTAR_DELAY", delayVar)) {
1530 delay = atoi(delayVar.c_str());
1533 cmSystemTools::Delay(delay);
1537 cmSystemTools::Error("tar: No action specified. Please choose: 't' "
1538 "(list), 'c' (create) or 'x' (extract)");
1544 if (args[1] == "server") {
1545 cmSystemTools::Error(
1546 "CMake server mode has been removed in favor of the file-api.");
1550 #if !defined(CMAKE_BOOTSTRAP)
1551 // Internal CMake Fortran module support.
1552 if (args[1] == "cmake_copy_f90_mod" && args.size() >= 4) {
1553 return cmDependsFortran::CopyModule(args) ? 0 : 1;
1557 #if defined(_WIN32) && !defined(__CYGWIN__)
1558 // Write registry value
1559 if (args[1] == "write_regv" && args.size() > 3) {
1560 return cmSystemTools::WriteRegistryValue(args[2], args[3]) ? 0 : 1;
1563 // Delete registry value
1564 if (args[1] == "delete_regv" && args.size() > 2) {
1565 return cmSystemTools::DeleteRegistryValue(args[2]) ? 0 : 1;
1569 if (args[1] == "comspec" && args.size() > 2) {
1570 std::cerr << "Win9x helper \"cmake -E comspec\" no longer supported\n";
1574 if (args[1] == "env_vs8_wince" && args.size() == 3) {
1575 return cmcmd::WindowsCEEnvironment("8.0", args[2]);
1578 if (args[1] == "env_vs9_wince" && args.size() == 3) {
1579 return cmcmd::WindowsCEEnvironment("9.0", args[2]);
1583 // Internal depfile transformation
1584 if (args[1] == "cmake_transform_depfile" && args.size() == 10) {
1585 auto format = cmDepfileFormat::GccDepfile;
1586 if (args[3] == "gccdepfile") {
1587 format = cmDepfileFormat::GccDepfile;
1588 } else if (args[3] == "makedepfile") {
1589 format = cmDepfileFormat::MakeDepfile;
1590 } else if (args[3] == "MSBuildAdditionalInputs") {
1591 format = cmDepfileFormat::MSBuildAdditionalInputs;
1595 // Create a cmake object instance to process dependencies.
1596 // All we need is the `set` command.
1597 cmake cm(cmake::RoleScript, cmState::Unknown);
1598 std::string homeDir;
1599 std::string startDir;
1600 std::string homeOutDir;
1601 std::string startOutDir;
1602 homeDir = cmSystemTools::CollapseFullPath(args[4]);
1603 startDir = cmSystemTools::CollapseFullPath(args[5]);
1604 homeOutDir = cmSystemTools::CollapseFullPath(args[6]);
1605 startOutDir = cmSystemTools::CollapseFullPath(args[7]);
1606 cm.SetHomeDirectory(homeDir);
1607 cm.SetHomeOutputDirectory(homeOutDir);
1608 cm.GetCurrentSnapshot().SetDefaultDefinitions();
1609 if (auto ggd = cm.CreateGlobalGenerator(args[2])) {
1610 cm.SetGlobalGenerator(std::move(ggd));
1611 cmStateSnapshot snapshot = cm.GetCurrentSnapshot();
1612 snapshot.GetDirectory().SetCurrentBinary(startOutDir);
1613 snapshot.GetDirectory().SetCurrentSource(startDir);
1614 cmMakefile mf(cm.GetGlobalGenerator(), snapshot);
1615 auto lgd = cm.GetGlobalGenerator()->CreateLocalGenerator(&mf);
1617 // FIXME: With advanced add_subdirectory usage, these are
1618 // not necessarily the same as the generator originally used.
1619 // We should pass all these directories through an info file.
1620 lgd->SetRelativePathTop(homeDir, homeOutDir);
1622 return cmTransformDepfile(format, *lgd, args[8], args[9]) ? 0 : 2;
1628 CMakeCommandUsage(args[0]);
1632 int cmcmd::HashSumFile(std::vector<std::string> const& args,
1633 cmCryptoHash::Algo algo)
1635 if (args.size() < 3) {
1640 for (auto const& filename : cmMakeRange(args).advance(2)) {
1641 // Cannot compute sum of a directory
1642 if (cmSystemTools::FileIsDirectory(filename)) {
1643 std::cerr << "Error: " << filename << " is a directory" << std::endl;
1647 #ifndef CMAKE_BOOTSTRAP
1648 = cmSystemTools::ComputeFileHash(filename, algo)
1651 if (value.empty()) {
1652 // To mimic "md5sum/shasum" behavior in a shell:
1653 std::cerr << filename << ": No such file or directory" << std::endl;
1656 std::cout << value << " " << filename << std::endl;
1663 int cmcmd::SymlinkLibrary(std::vector<std::string> const& args)
1666 std::string realName = args[2];
1667 std::string soName = args[3];
1668 std::string name = args[4];
1669 cmSystemTools::ConvertToUnixSlashes(realName);
1670 cmSystemTools::ConvertToUnixSlashes(soName);
1671 cmSystemTools::ConvertToUnixSlashes(name);
1672 if (soName != realName) {
1673 cmsys::Status status = cmcmd::SymlinkInternal(realName, soName);
1675 cmSystemTools::Error(
1676 cmStrCat("cmake_symlink_library: System Error: ", status.GetString()));
1680 if (name != soName) {
1681 cmsys::Status status = cmcmd::SymlinkInternal(soName, name);
1683 cmSystemTools::Error(
1684 cmStrCat("cmake_symlink_library: System Error: ", status.GetString()));
1691 int cmcmd::SymlinkExecutable(std::vector<std::string> const& args)
1694 std::string const& realName = args[2];
1695 std::string const& name = args[3];
1696 if (name != realName) {
1697 cmsys::Status status = cmcmd::SymlinkInternal(realName, name);
1699 cmSystemTools::Error(cmStrCat("cmake_symlink_executable: System Error: ",
1700 status.GetString()));
1707 cmsys::Status cmcmd::SymlinkInternal(std::string const& file,
1708 std::string const& link)
1710 if (cmSystemTools::FileExists(link) || cmSystemTools::FileIsSymlink(link)) {
1711 cmSystemTools::RemoveFile(link);
1713 std::string linktext = cmSystemTools::GetFilenameName(file);
1714 #if defined(_WIN32) && !defined(__CYGWIN__)
1715 cmsys::Status status = cmSystemTools::CreateSymlinkQuietly(linktext, link);
1716 // Creating a symlink will fail with ERROR_PRIVILEGE_NOT_HELD if the user
1717 // does not have SeCreateSymbolicLinkPrivilege, or if developer mode is not
1718 // active. In that case, we try to copy the file.
1719 if (status.GetWindows() == ERROR_PRIVILEGE_NOT_HELD) {
1720 status = cmSystemTools::CopyFileAlways(file, link);
1721 } else if (!status) {
1722 cmSystemTools::Error(cmStrCat("failed to create symbolic link '", link,
1723 "': ", status.GetString()));
1727 return cmSystemTools::CreateSymlink(linktext, link);
1731 static void cmcmdProgressReport(std::string const& dir, std::string const& num)
1733 std::string dirName = cmStrCat(dir, "/Progress");
1738 fName = cmStrCat(dirName, "/count.txt");
1739 progFile = cmsys::SystemTools::Fopen(fName, "r");
1744 if (1 != fscanf(progFile, "%i", &count)) {
1745 std::cerr << "Could not read from progress file.\n";
1749 const char* last = num.c_str();
1750 for (const char* c = last;; ++c) {
1751 if (*c == ',' || *c == '\0') {
1753 fName = cmStrCat(dirName, '/');
1754 fName.append(last, c - last);
1755 progFile = cmsys::SystemTools::Fopen(fName, "w");
1757 fprintf(progFile, "empty");
1768 static_cast<int>(cmsys::Directory::GetNumberOfFilesInDirectory(dirName));
1770 // print the progress
1771 fprintf(stdout, "[%3i%%] ", ((fileNum - 3) * 100) / count);
1775 int cmcmd::ExecuteEchoColor(std::vector<std::string> const& args)
1777 // The arguments are
1778 // args[0] == <cmake-executable>
1779 // args[1] == cmake_echo_color
1781 bool enabled = true;
1782 int color = cmsysTerminal_Color_Normal;
1783 bool newline = true;
1784 std::string progressDir;
1785 for (auto const& arg : cmMakeRange(args).advance(2)) {
1786 if (cmHasLiteralPrefix(arg, "--switch=")) {
1787 // Enable or disable color based on the switch value.
1788 std::string value = arg.substr(9);
1789 if (!value.empty()) {
1790 enabled = cmIsOn(value);
1792 } else if (cmHasLiteralPrefix(arg, "--progress-dir=")) {
1793 progressDir = arg.substr(15);
1794 } else if (cmHasLiteralPrefix(arg, "--progress-num=")) {
1795 if (!progressDir.empty()) {
1796 std::string const& progressNum = arg.substr(15);
1797 cmcmdProgressReport(progressDir, progressNum);
1799 } else if (arg == "--normal") {
1800 color = cmsysTerminal_Color_Normal;
1801 } else if (arg == "--black") {
1802 color = cmsysTerminal_Color_ForegroundBlack;
1803 } else if (arg == "--red") {
1804 color = cmsysTerminal_Color_ForegroundRed;
1805 } else if (arg == "--green") {
1806 color = cmsysTerminal_Color_ForegroundGreen;
1807 } else if (arg == "--yellow") {
1808 color = cmsysTerminal_Color_ForegroundYellow;
1809 } else if (arg == "--blue") {
1810 color = cmsysTerminal_Color_ForegroundBlue;
1811 } else if (arg == "--magenta") {
1812 color = cmsysTerminal_Color_ForegroundMagenta;
1813 } else if (arg == "--cyan") {
1814 color = cmsysTerminal_Color_ForegroundCyan;
1815 } else if (arg == "--white") {
1816 color = cmsysTerminal_Color_ForegroundWhite;
1817 } else if (arg == "--bold") {
1818 color |= cmsysTerminal_Color_ForegroundBold;
1819 } else if (arg == "--no-newline") {
1821 } else if (arg == "--newline") {
1824 // Color is enabled. Print with the current color.
1825 cmSystemTools::MakefileColorEcho(color, arg.c_str(), newline, enabled);
1832 int cmcmd::ExecuteLinkScript(std::vector<std::string> const& args)
1834 // The arguments are
1835 // args[0] == <cmake-executable>
1836 // args[1] == cmake_link_script
1837 // args[2] == <link-script-name>
1838 // args[3] == --verbose=?
1839 bool verbose = false;
1840 if (args.size() >= 4) {
1841 if (cmHasLiteralPrefix(args[3], "--verbose=")) {
1842 if (!cmIsOff(args[3].substr(10))) {
1848 // Allocate a process instance.
1849 cmsysProcess* cp = cmsysProcess_New();
1851 std::cerr << "Error allocating process instance in link script."
1856 // Children should share stdout and stderr with this process.
1857 cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDOUT, 1);
1858 cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDERR, 1);
1860 // Run the command lines verbatim.
1861 cmsysProcess_SetOption(cp, cmsysProcess_Option_Verbatim, 1);
1863 // Read command lines from the script.
1864 cmsys::ifstream fin(args[2].c_str());
1866 std::cerr << "Error opening link script \"" << args[2] << "\""
1871 // Run one command at a time.
1872 std::string command;
1874 while (result == 0 && cmSystemTools::GetLineFromStream(fin, command)) {
1875 // Skip empty command lines.
1876 if (command.find_first_not_of(" \t") == std::string::npos) {
1880 // Setup this command line.
1881 const char* cmd[2] = { command.c_str(), nullptr };
1882 cmsysProcess_SetCommand(cp, cmd);
1884 // Report the command if verbose output is enabled.
1886 std::cout << command << std::endl;
1889 // Run the command and wait for it to exit.
1890 cmsysProcess_Execute(cp);
1891 cmsysProcess_WaitForExit(cp, nullptr);
1893 // Report failure if any.
1894 switch (cmsysProcess_GetState(cp)) {
1895 case cmsysProcess_State_Exited: {
1896 int value = cmsysProcess_GetExitValue(cp);
1901 case cmsysProcess_State_Exception:
1902 std::cerr << "Error running link command: "
1903 << cmsysProcess_GetExceptionString(cp) << std::endl;
1906 case cmsysProcess_State_Error:
1907 std::cerr << "Error running link command: "
1908 << cmsysProcess_GetErrorString(cp) << std::endl;
1916 // Free the process instance.
1917 cmsysProcess_Delete(cp);
1919 // Return the final resulting return value.
1923 int cmcmd::WindowsCEEnvironment(const char* version, const std::string& name)
1925 #if !defined(CMAKE_BOOTSTRAP) && defined(_WIN32) && !defined(__CYGWIN__)
1926 cmVisualStudioWCEPlatformParser parser(name.c_str());
1927 parser.ParseVersion(version);
1928 if (parser.Found()) {
1929 /* clang-format off */
1930 std::cout << "@echo off\n"
1931 "echo Environment Selection: " << name << "\n"
1932 "set PATH=" << parser.GetPathDirectories() << "\n"
1933 "set INCLUDE=" << parser.GetIncludeDirectories() << "\n"
1934 "set LIB=" << parser.GetLibraryDirectories() << std::endl;
1935 /* clang-format on */
1942 std::cerr << "Could not find " << name;
1946 int cmcmd::RunPreprocessor(const std::vector<std::string>& command,
1947 const std::string& intermediate_file)
1949 cmUVProcessChainBuilder builder;
1952 int preprocessedFile =
1953 uv_fs_open(nullptr, &fs_req, intermediate_file.c_str(), O_CREAT | O_RDWR,
1955 uv_fs_req_cleanup(&fs_req);
1958 .SetExternalStream(cmUVProcessChainBuilder::Stream_OUTPUT,
1960 .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR)
1961 .AddCommand(command);
1962 auto process = builder.Start();
1963 if (!process.Valid()) {
1964 std::cerr << "Failed to start preprocessor.";
1967 if (!process.Wait()) {
1968 std::cerr << "Failed to wait for preprocessor";
1971 auto status = process.GetStatus();
1972 if (!status[0] || status[0]->ExitStatus != 0) {
1973 auto* errorStream = process.ErrorStream();
1975 std::cerr << errorStream->rdbuf();
1983 int cmcmd::RunLLVMRC(std::vector<std::string> const& args)
1985 // The arguments are
1986 // args[0] == <cmake-executable>
1987 // args[1] == cmake_llvm_rc
1988 // args[2] == source_file_path
1989 // args[3] == intermediate_file
1990 // args[4..n] == preprocess+args
1992 // args[n+2...] == llvm-rc+args
1993 if (args.size() < 3) {
1994 std::cerr << "Invalid cmake_llvm_rc arguments";
1998 const std::string& intermediate_file = args[3];
1999 const std::string& source_file = args[2];
2000 std::vector<std::string> preprocess;
2001 std::vector<std::string> resource_compile;
2002 std::vector<std::string>* pArgTgt = &preprocess;
2004 static const cmsys::RegularExpression llvm_rc_only_single_arg("^[-/](N|Y)");
2005 static const cmsys::RegularExpression llvm_rc_only_double_arg(
2006 "^[-/](C|LN|L)(.)?");
2007 static const cmsys::RegularExpression common_double_arg(
2008 "^[-/](D|U|I|FO|fo|Fo)(.)?");
2009 bool acceptNextArg = false;
2010 bool skipNextArg = false;
2011 for (std::string const& arg : cmMakeRange(args).advance(4)) {
2013 skipNextArg = false;
2016 // We use ++ as separator between the preprocessing step definition and
2017 // the rc compilation step because we need to prepend a -- to separate the
2018 // source file properly from other options when using clang-cl for
2021 pArgTgt = &resource_compile;
2022 skipNextArg = false;
2023 acceptNextArg = true;
2025 cmsys::RegularExpressionMatch match;
2026 if (!acceptNextArg) {
2027 if (common_double_arg.find(arg.c_str(), match)) {
2028 acceptNextArg = match.match(2).empty();
2030 if (llvm_rc_only_single_arg.find(arg.c_str(), match)) {
2031 if (pArgTgt == &preprocess) {
2034 } else if (llvm_rc_only_double_arg.find(arg.c_str(), match)) {
2035 if (pArgTgt == &preprocess) {
2036 skipNextArg = match.match(2).empty();
2039 acceptNextArg = match.match(2).empty();
2040 } else if (pArgTgt == &resource_compile) {
2045 acceptNextArg = false;
2047 if (arg.find("SOURCE_DIR") != std::string::npos) {
2048 std::string sourceDirArg = arg;
2049 cmSystemTools::ReplaceString(
2050 sourceDirArg, "SOURCE_DIR",
2051 cmSystemTools::GetFilenamePath(source_file));
2052 pArgTgt->push_back(sourceDirArg);
2054 pArgTgt->push_back(arg);
2058 if (preprocess.empty()) {
2059 std::cerr << "Empty preprocessing command";
2062 if (resource_compile.empty()) {
2063 std::cerr << "Empty resource compilation command";
2066 // Since we might have skipped the last argument to llvm-rc
2067 // we need to make sure the llvm-rc source file is present in the
2069 if (resource_compile.back() != intermediate_file) {
2070 resource_compile.push_back(intermediate_file);
2073 auto result = RunPreprocessor(preprocess, intermediate_file);
2075 cmSystemTools::RemoveFile(intermediate_file);
2078 cmUVProcessChainBuilder builder;
2080 builder.SetBuiltinStream(cmUVProcessChainBuilder::Stream_OUTPUT)
2081 .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR)
2082 .AddCommand(resource_compile);
2083 auto process = builder.Start();
2085 if (!process.Valid()) {
2086 std::cerr << "Failed to start resource compiler.";
2089 if (!process.Wait()) {
2090 std::cerr << "Failed to wait for resource compiler";
2095 cmSystemTools::RemoveFile(intermediate_file);
2099 auto status = process.GetStatus();
2100 if (!status[0] || status[0]->ExitStatus != 0) {
2101 auto* errorStream = process.ErrorStream();
2103 std::cerr << errorStream->rdbuf();
2115 bool Incremental = false;
2116 bool LinkGeneratesManifest = true;
2117 std::vector<std::string> LinkCommand;
2118 std::vector<std::string> UserManifests;
2119 std::string LinkerManifestFile;
2120 std::string ManifestFile;
2121 std::string ManifestFileRC;
2122 std::string ManifestFileRes;
2123 std::string TargetFile;
2128 cmVSLink(int type, bool verbose)
2133 bool Parse(std::vector<std::string>::const_iterator argBeg,
2134 std::vector<std::string>::const_iterator argEnd);
2138 int LinkIncremental();
2139 int LinkNonIncremental();
2140 int RunMT(std::string const& out, bool notify);
2143 // For visual studio 2005 and newer manifest files need to be embedded into
2144 // exe and dll's. This code does that in such a way that incremental linking
2146 int cmcmd::VisualStudioLink(std::vector<std::string> const& args, int type)
2148 // Replace streambuf so we output in the system codepage. CMake is set up
2149 // to output in Unicode (see SetUTF8Pipes) but the Visual Studio linker
2150 // outputs using the system codepage so we need to change behavior when
2151 // we run the link command.
2152 cmConsoleBuf consoleBuf;
2154 if (args.size() < 2) {
2157 const bool verbose = cmSystemTools::HasEnv("VERBOSE");
2158 std::vector<std::string> expandedArgs;
2159 for (std::string const& i : args) {
2160 // check for nmake temporary files
2161 if (i[0] == '@' && !cmHasLiteralPrefix(i, "@CMakeFiles")) {
2162 cmsys::ifstream fin(i.substr(1).c_str());
2164 while (cmSystemTools::GetLineFromStream(fin, line)) {
2165 cmSystemTools::ParseWindowsCommandLine(line.c_str(), expandedArgs);
2168 expandedArgs.push_back(i);
2172 cmVSLink vsLink(type, verbose);
2173 if (!vsLink.Parse(expandedArgs.begin() + 2, expandedArgs.end())) {
2176 return vsLink.Link();
2184 struct NumberFormatter
2186 NumberFormat Format;
2188 NumberFormatter(NumberFormat format, int value)
2194 static std::ostream& operator<<(std::ostream& stream,
2195 NumberFormatter const& formatter)
2197 auto const& flags = stream.flags();
2198 if (formatter.Format == FORMAT_DECIMAL) {
2199 stream << std::dec << formatter.Value;
2201 stream << "0x" << std::hex << formatter.Value;
2203 stream.flags(flags);
2207 static bool RunCommand(const char* comment,
2208 std::vector<std::string> const& command, bool verbose,
2209 NumberFormat exitFormat, int* retCodeOut = nullptr,
2210 bool (*retCodeOkay)(int) = nullptr)
2213 std::cout << comment << ":\n";
2214 std::cout << cmJoin(command, " ") << "\n";
2218 bool commandResult = cmSystemTools::RunSingleCommand(
2219 command, &output, &output, &retCode, nullptr, cmSystemTools::OUTPUT_NONE);
2220 bool const retCodeSuccess =
2221 retCode == 0 || (retCodeOkay && retCodeOkay(retCode));
2222 bool const success = commandResult && retCodeSuccess;
2224 if (commandResult || !retCodeSuccess) {
2225 *retCodeOut = retCode;
2231 std::cout << comment << ": command \"" << cmJoin(command, " ")
2232 << "\" failed (exit code "
2233 << NumberFormatter(exitFormat, retCode)
2234 << ") with the following output:\n"
2236 } else if (verbose) {
2237 // always print the output of the command, unless
2238 // it is the dumb rc command banner
2239 if (output.find("Resource Compiler Version") == std::string::npos) {
2240 std::cout << output;
2246 bool cmVSLink::Parse(std::vector<std::string>::const_iterator argBeg,
2247 std::vector<std::string>::const_iterator argEnd)
2249 // Parse our own arguments.
2252 while (arg != argEnd && cmHasLiteralPrefix(*arg, "-")) {
2257 if (*arg == "--manifests") {
2258 for (++arg; arg != argEnd && !cmHasLiteralPrefix(*arg, "-"); ++arg) {
2259 this->UserManifests.push_back(*arg);
2261 } else if (cmHasLiteralPrefix(*arg, "--intdir=")) {
2262 intDir = arg->substr(9);
2264 } else if (cmHasLiteralPrefix(*arg, "--rc=")) {
2265 this->RcPath = arg->substr(5);
2267 } else if (cmHasLiteralPrefix(*arg, "--mt=")) {
2268 this->MtPath = arg->substr(5);
2271 std::cerr << "unknown argument '" << *arg << "'\n";
2275 if (intDir.empty()) {
2279 // The rest of the arguments form the link command.
2280 if (arg == argEnd) {
2283 this->LinkCommand.insert(this->LinkCommand.begin(), arg, argEnd);
2285 // Parse the link command to extract information we need.
2286 for (; arg != argEnd; ++arg) {
2287 if (cmSystemTools::Strucmp(arg->c_str(), "/INCREMENTAL:YES") == 0 ||
2288 cmSystemTools::Strucmp(arg->c_str(), "-INCREMENTAL:YES") == 0 ||
2289 cmSystemTools::Strucmp(arg->c_str(), "/INCREMENTAL") == 0 ||
2290 cmSystemTools::Strucmp(arg->c_str(), "-INCREMENTAL") == 0) {
2291 this->Incremental = true;
2292 } else if (cmSystemTools::Strucmp(arg->c_str(), "/MANIFEST:NO") == 0 ||
2293 cmSystemTools::Strucmp(arg->c_str(), "-MANIFEST:NO") == 0) {
2294 this->LinkGeneratesManifest = false;
2295 } else if (cmHasLiteralPrefix(*arg, "/Fe") ||
2296 cmHasLiteralPrefix(*arg, "-Fe")) {
2297 this->TargetFile = arg->substr(3);
2298 } else if (cmHasLiteralPrefix(*arg, "/out:") ||
2299 cmHasLiteralPrefix(*arg, "-out:")) {
2300 this->TargetFile = arg->substr(5);
2304 if (this->TargetFile.empty()) {
2308 this->ManifestFile = intDir + "/embed.manifest";
2309 this->LinkerManifestFile = intDir + "/intermediate.manifest";
2311 if (this->Incremental) {
2312 // We will compile a resource containing the manifest and
2313 // pass it to the link command.
2314 this->ManifestFileRC = intDir + "/manifest.rc";
2315 this->ManifestFileRes = intDir + "/manifest.res";
2316 } else if (this->UserManifests.empty()) {
2317 // Prior to support for user-specified manifests CMake placed the
2318 // linker-generated manifest next to the binary (as if it were not to be
2319 // embedded) when not linking incrementally. Preserve this behavior.
2320 this->ManifestFile = this->TargetFile + ".manifest";
2321 this->LinkerManifestFile = this->ManifestFile;
2324 if (this->LinkGeneratesManifest) {
2325 this->LinkCommand.emplace_back("/MANIFEST");
2326 this->LinkCommand.push_back("/MANIFESTFILE:" + this->LinkerManifestFile);
2332 int cmVSLink::Link()
2334 if (this->Incremental &&
2335 (this->LinkGeneratesManifest || !this->UserManifests.empty())) {
2336 if (this->Verbose) {
2337 std::cout << "Visual Studio Incremental Link with embedded manifests\n";
2339 return this->LinkIncremental();
2341 if (this->Verbose) {
2342 if (!this->Incremental) {
2343 std::cout << "Visual Studio Non-Incremental Link\n";
2345 std::cout << "Visual Studio Incremental Link without manifests\n";
2348 return this->LinkNonIncremental();
2351 static bool mtRetIsUpdate(int mtRet)
2353 // 'mt /notify_update' returns a special value (differing between
2354 // Windows and POSIX hosts) when it updated the manifest file.
2355 return mtRet == 0x41020001 || mtRet == 0xbb;
2358 int cmVSLink::LinkIncremental()
2360 // This follows the steps listed here:
2361 // http://blogs.msdn.com/zakramer/archive/2006/05/22/603558.aspx
2363 // 1. Compiler compiles the application and generates the *.obj files.
2364 // 2. An empty manifest file is generated if this is a clean build and
2365 // if not the previous one is reused.
2366 // 3. The resource compiler (rc.exe) compiles the *.manifest file to a
2368 // 4. Linker generates the binary (EXE or DLL) with the /incremental
2369 // switch and embeds the dummy manifest file. The linker also generates
2370 // the real manifest file based on the binaries that your binary depends
2372 // 5. The manifest tool (mt.exe) is then used to generate the final
2375 // If the final manifest is changed, then 6 and 7 are run, if not
2376 // they are skipped, and it is done.
2378 // 6. The resource compiler is invoked one more time.
2379 // 7. Finally, the Linker does another incremental link, but since the
2380 // only thing that has changed is the *.res file that contains the
2381 // manifest it is a short link.
2383 // Create a resource file referencing the manifest.
2384 std::string absManifestFile =
2385 cmSystemTools::CollapseFullPath(this->ManifestFile);
2386 if (this->Verbose) {
2387 std::cout << "Create " << this->ManifestFileRC << "\n";
2390 cmsys::ofstream fout(this->ManifestFileRC.c_str());
2394 // Insert a pragma statement to specify utf-8 encoding.
2395 fout << "#pragma code_page(65001)\n";
2397 << " /* CREATEPROCESS_MANIFEST_RESOURCE_ID */ "
2398 "24 /* RT_MANIFEST */ \""
2399 << absManifestFile << "\"";
2402 // If we have not previously generated a manifest file,
2403 // generate a manifest file so the resource compiler succeeds.
2404 if (!cmSystemTools::FileExists(this->ManifestFile)) {
2405 if (this->Verbose) {
2406 std::cout << "Create empty: " << this->ManifestFile << "\n";
2408 if (this->UserManifests.empty()) {
2409 // generate an empty manifest because there are no user provided
2411 cmsys::ofstream foutTmp(this->ManifestFile.c_str());
2413 this->RunMT("/out:" + this->ManifestFile, false);
2417 // Compile the resource file.
2418 std::vector<std::string> rcCommand;
2419 rcCommand.push_back(this->RcPath.empty() ? "rc" : this->RcPath);
2420 rcCommand.emplace_back("/fo");
2421 rcCommand.push_back(this->ManifestFileRes);
2422 rcCommand.push_back(this->ManifestFileRC);
2423 if (!RunCommand("RC Pass 1", rcCommand, this->Verbose, FORMAT_DECIMAL)) {
2427 // Tell the linker to use our manifest compiled into a resource.
2428 this->LinkCommand.push_back(this->ManifestFileRes);
2430 // Run the link command (possibly generates intermediate manifest).
2431 if (!RunCommand("LINK Pass 1", this->LinkCommand, this->Verbose,
2436 // Run the manifest tool to create the final manifest.
2437 int mtRet = this->RunMT("/out:" + this->ManifestFile, true);
2439 // If mt returns a special value then it updated the manifest file so
2440 // we need to embed it again. Otherwise we are done.
2441 if (!mtRetIsUpdate(mtRet)) {
2445 // Compile the resource file again.
2446 if (!RunCommand("RC Pass 2", rcCommand, this->Verbose, FORMAT_DECIMAL)) {
2450 // Link incrementally again to use the updated resource.
2451 if (!RunCommand("FINAL LINK", this->LinkCommand, this->Verbose,
2458 int cmVSLink::LinkNonIncremental()
2460 // Run the link command (possibly generates intermediate manifest).
2461 if (!RunCommand("LINK", this->LinkCommand, this->Verbose, FORMAT_DECIMAL)) {
2465 // If we have no manifest files we are done.
2466 if (!this->LinkGeneratesManifest && this->UserManifests.empty()) {
2470 // Run the manifest tool to embed the final manifest in the binary.
2472 "/outputresource:" + this->TargetFile + (this->Type == 1 ? ";#1" : ";#2");
2473 return this->RunMT(mtOut, false);
2476 int cmVSLink::RunMT(std::string const& out, bool notify)
2478 std::vector<std::string> mtCommand;
2479 mtCommand.push_back(this->MtPath.empty() ? "mt" : this->MtPath);
2480 mtCommand.emplace_back("/nologo");
2481 mtCommand.emplace_back("/manifest");
2483 // add the linker generated manifest if the file exists.
2484 if (this->LinkGeneratesManifest &&
2485 cmSystemTools::FileExists(this->LinkerManifestFile)) {
2486 mtCommand.push_back(this->LinkerManifestFile);
2488 cm::append(mtCommand, this->UserManifests);
2489 mtCommand.push_back(out);
2491 // Add an undocumented option that enables a special return
2492 // code to notify us when the manifest is modified.
2493 mtCommand.emplace_back("/notify_update");
2496 if (!RunCommand("MT", mtCommand, this->Verbose, FORMAT_HEX, &mtRet,