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 // Construct the clang-tidy command line by taking what was given
364 // and adding our compiler command line. The clang-tidy tool will
365 // automatically skip over the compiler itself and extract the
368 std::vector<std::string> tidy_cmd = cmExpandedList(runCmd, true);
369 tidy_cmd.push_back(sourceFile);
370 tidy_cmd.emplace_back("--");
371 cm::append(tidy_cmd, orig_cmd);
373 // Run the tidy command line. Capture its stdout and hide its stderr.
376 if (!cmSystemTools::RunSingleCommand(tidy_cmd, &stdOut, &stdErr, &ret,
377 nullptr, cmSystemTools::OUTPUT_NONE)) {
378 std::cerr << "Error running '" << tidy_cmd[0] << "': " << stdErr << "\n";
381 // Output the stdout from clang-tidy to stderr
383 // If clang-tidy exited with an error do the same.
390 int HandleLWYU(const std::string& runCmd, const std::string& sourceFile,
391 const std::vector<std::string>&)
393 // Construct the ldd -r -u (link what you use lwyu) command line
394 // ldd -u -r lwuy target
395 std::vector<std::string> lwyu_cmd = cmExpandedList(runCmd, true);
396 lwyu_cmd.push_back(sourceFile);
398 // Run the lwyu check command line, currently ldd is expected.
399 // Capture its stdout and hide its stderr.
400 // Ignore its return code because the tool always returns non-zero
401 // if there are any warnings, but we just want to warn.
405 if (!cmSystemTools::RunSingleCommand(lwyu_cmd, &stdOut, &stdErr, &ret,
406 nullptr, cmSystemTools::OUTPUT_NONE)) {
407 std::cerr << "Error running '" << lwyu_cmd[0] << "': " << stdErr << "\n";
411 // Output the stdout from ldd -r -u to stderr
412 // Warn if lwyu reported anything.
413 if (stdOut.find("Unused direct dependencies:") != std::string::npos) {
414 std::cerr << "Warning: " << stdOut;
419 int HandleCppLint(const std::string& runCmd, const std::string& sourceFile,
420 const std::vector<std::string>&)
422 // Construct the cpplint command line.
423 std::vector<std::string> cpplint_cmd = cmExpandedList(runCmd, true);
424 cpplint_cmd.push_back(sourceFile);
426 // Run the cpplint command line. Capture its output.
429 if (!cmSystemTools::RunSingleCommand(cpplint_cmd, &stdOut, &stdOut, &ret,
430 nullptr, cmSystemTools::OUTPUT_NONE)) {
431 std::cerr << "Error running '" << cpplint_cmd[0] << "': " << stdOut
435 if (!stdOut.empty()) {
436 std::cerr << "Warning: cpplint diagnostics:\n";
437 // Output the output from cpplint to stderr
441 // always return 0 so the build can continue as cpplint returns non-zero
446 int HandleCppCheck(const std::string& runCmd, const std::string& sourceFile,
447 const std::vector<std::string>& orig_cmd)
449 // Construct the cpplint command line.
450 std::vector<std::string> cppcheck_cmd = cmExpandedList(runCmd, true);
451 // extract all the -D, -U, and -I options from the compile line
452 for (auto const& opt : orig_cmd) {
453 if (opt.size() > 2) {
454 if ((opt[0] == '-') &&
455 ((opt[1] == 'D') || (opt[1] == 'I') || (opt[1] == 'U'))) {
456 cppcheck_cmd.push_back(opt);
457 // convert cl / options to - options if needed
459 } else if ((opt[0] == '/') &&
460 ((opt[1] == 'D') || (opt[1] == 'I') || (opt[1] == 'U'))) {
461 std::string optcopy = opt;
463 cppcheck_cmd.push_back(optcopy);
468 // add the source file
469 cppcheck_cmd.push_back(sourceFile);
471 // Run the cpplint command line. Capture its output.
475 if (!cmSystemTools::RunSingleCommand(cppcheck_cmd, &stdOut, &stdErr, &ret,
476 nullptr, cmSystemTools::OUTPUT_NONE)) {
477 std::cerr << "Error running '" << cppcheck_cmd[0] << "': " << stdOut
482 // Output the output from cpplint to stderr
483 if (stdErr.find("(error)") != std::string::npos ||
484 stdErr.find("(warning)") != std::string::npos ||
485 stdErr.find("(style)") != std::string::npos ||
486 stdErr.find("(performance)") != std::string::npos ||
487 stdErr.find("(portability)") != std::string::npos ||
488 stdErr.find("(information)") != std::string::npos) {
490 std::cerr << "Warning: cppcheck reported diagnostics:\n";
492 std::cerr << "Error: cppcheck reported failure:\n";
500 using CoCompileHandler = int (*)(const std::string&, const std::string&,
501 const std::vector<std::string>&);
506 CoCompileHandler Handler;
507 bool NoOriginalCommand;
510 const std::array<CoCompiler, 5> CoCompilers = {
511 { // Table of options and handlers.
512 { "--cppcheck=", HandleCppCheck, false },
513 { "--cpplint=", HandleCppLint, false },
514 { "--iwyu=", HandleIWYU, false },
515 { "--lwyu=", HandleLWYU, true },
516 { "--tidy=", HandleTidy, false } }
522 CoCompileHandler Handler;
526 // called when args[0] == "__run_co_compile"
527 int cmcmd::HandleCoCompileCommands(std::vector<std::string> const& args)
529 std::vector<CoCompileJob> jobs;
530 std::string sourceFile; // store --source=
531 std::vector<std::string> launchers; // store --launcher=
533 // Default is to run the original command found after -- if the option
534 // does not need to do that, it should be specified here, currently only
536 bool runOriginalCmd = true;
538 std::vector<std::string> orig_cmd;
539 bool doing_options = true;
540 for (std::string const& arg : cmMakeRange(args).advance(2)) {
541 // if the arg is -- then the rest of the args after
544 doing_options = false;
545 } else if (doing_options) {
546 bool optionFound = false;
547 for (CoCompiler const& cc : CoCompilers) {
548 size_t optionLen = strlen(cc.Option);
549 if (arg.compare(0, optionLen, cc.Option) == 0) {
552 job.Command = arg.substr(optionLen);
553 job.Handler = cc.Handler;
554 jobs.push_back(std::move(job));
555 if (cc.NoOriginalCommand) {
556 runOriginalCmd = false;
561 if (cmHasLiteralPrefix(arg, "--source=")) {
562 sourceFile = arg.substr(9);
563 } else if (cmHasLiteralPrefix(arg, "--launcher=")) {
564 cmExpandList(arg.substr(11), launchers, true);
566 // if it was not a co-compiler or --source/--launcher then error
567 std::cerr << "__run_co_compile given unknown argument: " << arg
572 } else { // if not doing_options then push to orig_cmd
573 orig_cmd.push_back(arg);
577 std::cerr << "__run_co_compile missing command to run. "
578 "Looking for one or more of the following:\n";
579 for (CoCompiler const& cc : CoCompilers) {
580 std::cerr << cc.Option << "\n";
585 if (runOriginalCmd && orig_cmd.empty()) {
586 std::cerr << "__run_co_compile missing compile command after --\n";
590 for (CoCompileJob const& job : jobs) {
591 // call the command handler here
592 int ret = job.Handler(job.Command, sourceFile, orig_cmd);
594 // if the command returns non-zero then return and fail.
595 // for commands that do not want to break the build, they should return
602 // if there is no original command to run return now
603 if (!runOriginalCmd) {
607 // Prepend launcher argument(s), if any
608 if (!launchers.empty()) {
609 orig_cmd.insert(orig_cmd.begin(), launchers.begin(), launchers.end());
612 // Now run the real compiler command and return its result value
614 if (!cmSystemTools::RunSingleCommand(orig_cmd, nullptr, nullptr, &ret,
616 cmSystemTools::OUTPUT_PASSTHROUGH)) {
617 std::cerr << "Error running '" << orig_cmd[0] << "'\n";
620 // return the return value from the original compiler command
624 int cmcmd::ExecuteCMakeCommand(std::vector<std::string> const& args,
625 std::unique_ptr<cmConsoleBuf> consoleBuf)
627 // IF YOU ADD A NEW COMMAND, DOCUMENT IT ABOVE and in cmakemain.cxx
628 if (args.size() > 1) {
630 if (args[1] == "copy" && args.size() > 3) {
631 // If multiple source files specified,
632 // then destination must be directory
633 if ((args.size() > 4) &&
634 (!cmSystemTools::FileIsDirectory(args.back()))) {
635 std::cerr << "Error: Target (for copy command) \"" << args.back()
636 << "\" is not a directory.\n";
639 // If error occurs we want to continue copying next files.
640 bool return_value = false;
641 for (auto const& arg : cmMakeRange(args).advance(2).retreat(1)) {
642 if (!cmsys::SystemTools::CopyFileAlways(arg, args.back())) {
643 std::cerr << "Error copying file \"" << arg << "\" to \""
644 << args.back() << "\".\n";
651 // Copy file if different.
652 if (args[1] == "copy_if_different" && args.size() > 3) {
653 // If multiple source files specified,
654 // then destination must be directory
655 if ((args.size() > 4) &&
656 (!cmSystemTools::FileIsDirectory(args.back()))) {
657 std::cerr << "Error: Target (for copy_if_different command) \""
658 << args.back() << "\" is not a directory.\n";
661 // If error occurs we want to continue copying next files.
662 bool return_value = false;
663 for (auto const& arg : cmMakeRange(args).advance(2).retreat(1)) {
664 if (!cmSystemTools::CopyFileIfDifferent(arg, args.back())) {
665 std::cerr << "Error copying file (if different) from \"" << arg
666 << "\" to \"" << args.back() << "\".\n";
673 // Copy directory content
674 if (args[1] == "copy_directory" && args.size() > 3) {
675 // If error occurs we want to continue copying next files.
676 bool return_value = false;
677 for (auto const& arg : cmMakeRange(args).advance(2).retreat(1)) {
678 if (!cmSystemTools::CopyADirectory(arg, args.back())) {
679 std::cerr << "Error copying directory from \"" << arg << "\" to \""
680 << args.back() << "\".\n";
687 // Rename a file or directory
688 if (args[1] == "rename" && args.size() == 4) {
689 if (!cmSystemTools::RenameFile(args[2], args[3])) {
690 std::string e = cmSystemTools::GetLastSystemError();
691 std::cerr << "Error renaming from \"" << args[2] << "\" to \""
692 << args[3] << "\": " << e << "\n";
699 if (args[1] == "compare_files" && (args.size() == 4 || args.size() == 5)) {
701 if (args.size() == 4) {
702 filesDiffer = cmSystemTools::FilesDiffer(args[2], args[3]);
703 } else if (args[2] == "--ignore-eol") {
704 filesDiffer = cmsys::SystemTools::TextFilesDiffer(args[3], args[4]);
706 CMakeCommandUsage(args[0]);
716 #if !defined(CMAKE_BOOTSTRAP)
717 if (args[1] == "__create_def") {
718 if (args.size() < 4) {
719 std::cerr << "__create_def Usage: -E __create_def outfile.def "
720 "objlistfile [--nm=nm-path]\n";
723 cmsys::ifstream fin(args[3].c_str(), std::ios::in | std::ios::binary);
725 std::cerr << "could not open object list file: " << args[3] << "\n";
728 std::vector<std::string> files;
732 bool outValid = outTime.Load(args[2]);
733 while (cmSystemTools::GetLineFromStream(fin, file)) {
734 files.push_back(file);
737 outValid = inTime.Load(file) && inTime.Older(outTime);
741 // The def file already exists and all input files are older than
742 // the existing def file.
746 FILE* fout = cmsys::SystemTools::Fopen(args[2], "w+");
748 std::cerr << "could not open output .def file: " << args[2] << "\n";
752 if (args.size() >= 5) {
753 std::string const& a = args[4];
754 if (cmHasLiteralPrefix(a, "--nm=")) {
755 deffile.SetNmPath(a.substr(5));
757 std::cerr << "unknown argument: " << a << "\n";
760 for (std::string const& file : files) {
761 std::string const& ext = cmSystemTools::GetFilenameLastExtension(file);
762 if (cmSystemTools::LowerCase(ext) == ".def") {
763 if (!deffile.AddDefinitionFile(file.c_str())) {
767 if (!deffile.AddObjectFile(file.c_str())) {
772 deffile.WriteFile(fout);
777 if (args[1] == "__run_co_compile") {
778 return cmcmd::HandleCoCompileCommands(args);
782 if (args[1] == "echo") {
783 std::cout << cmJoin(cmMakeRange(args).advance(2), " ") << std::endl;
787 // Echo string no new line
788 if (args[1] == "echo_append") {
789 std::cout << cmJoin(cmMakeRange(args).advance(2), " ");
793 if (args[1] == "env") {
794 auto ai = args.cbegin() + 2;
795 auto ae = args.cend();
796 for (; ai != ae; ++ai) {
797 std::string const& a = *ai;
799 // Stop parsing options/environment variables; the next argument
800 // should be the command.
804 if (cmHasLiteralPrefix(a, "--unset=")) {
805 // Unset environment variable.
806 cmSystemTools::UnPutEnv(a.substr(8));
807 } else if (!a.empty() && a[0] == '-') {
808 // Environment variable and command names cannot start in '-',
809 // so this must be an unknown option.
810 std::cerr << "cmake -E env: unknown option '" << a << '\''
813 } else if (a.find('=') != std::string::npos) {
814 // Set environment variable.
815 cmSystemTools::PutEnv(a);
817 // This is the beginning of the command.
823 std::cerr << "cmake -E env: no command given" << std::endl;
827 // Execute command from remaining arguments.
828 std::vector<std::string> cmd(ai, ae);
830 if (cmSystemTools::RunSingleCommand(cmd, nullptr, nullptr, &retval,
832 cmSystemTools::OUTPUT_PASSTHROUGH)) {
838 #if !defined(CMAKE_BOOTSTRAP)
839 if (args[1] == "environment") {
840 for (auto const& env : cmSystemTools::GetEnvironmentVariables()) {
841 std::cout << env << std::endl;
847 if (args[1] == "make_directory" && args.size() > 2) {
848 // If an error occurs, we want to continue making directories.
849 bool return_value = false;
850 for (auto const& arg : cmMakeRange(args).advance(2)) {
851 if (!cmSystemTools::MakeDirectory(arg)) {
852 std::cerr << "Error creating directory \"" << arg << "\".\n";
859 if (args[1] == "remove_directory" && args.size() > 2) {
860 // If an error occurs, we want to continue removing directories.
861 bool return_value = false;
862 for (auto const& arg : cmMakeRange(args).advance(2)) {
863 if (cmSystemTools::FileIsDirectory(arg)) {
864 if (!cmRemoveDirectory(arg)) {
873 if (args[1] == "remove" && args.size() > 2) {
875 for (auto const& arg : cmMakeRange(args).advance(2)) {
876 if (arg == "\\-f" || arg == "-f") {
879 // Complain if the file could not be removed, still exists,
880 // and the -f option was not given.
881 if (!cmSystemTools::RemoveFile(arg) && !force &&
882 cmSystemTools::FileExists(arg)) {
890 // Remove directories or files with rm
891 if (args[1] == "rm" && args.size() > 2) {
892 // If an error occurs, we want to continue removing the remaining
893 // files/directories.
894 int return_value = 0;
896 bool recursive = false;
897 bool doing_options = true;
898 bool at_least_one_file = false;
899 for (auto const& arg : cmMakeRange(args).advance(2)) {
900 if (doing_options && cmHasLiteralPrefix(arg, "-")) {
902 doing_options = false;
904 if (arg.find('f') != std::string::npos) {
907 if (arg.find_first_of("rR") != std::string::npos) {
910 if (arg.find_first_not_of("-frR") != std::string::npos) {
911 cmSystemTools::Error("Unknown -E rm argument: " + arg);
918 at_least_one_file = true;
919 // Complain if the -f option was not given and
920 // either file does not exist or
921 // file could not be removed and still exists
922 bool file_exists_or_forced_remove = cmSystemTools::FileExists(arg) ||
923 cmSystemTools::FileIsSymlink(arg) || force;
924 if (cmSystemTools::FileIsDirectory(arg)) {
925 if (!cmRemoveDirectory(arg, recursive)) {
928 } else if ((!file_exists_or_forced_remove) ||
929 (!cmSystemTools::RemoveFile(arg) &&
930 cmSystemTools::FileExists(arg))) {
931 if (!file_exists_or_forced_remove) {
932 cmSystemTools::Error(
933 "File to remove does not exist and force is not set: " + arg);
935 cmSystemTools::Error("File can't be removed and still exist: " +
942 if (!at_least_one_file) {
943 cmSystemTools::Error("Missing file/directory to remove");
950 if (args[1] == "touch" && args.size() > 2) {
951 for (auto const& arg : cmMakeRange(args).advance(2)) {
952 if (!cmSystemTools::Touch(arg, true)) {
953 std::cerr << "cmake -E touch: failed to update \"";
954 std::cerr << arg << "\".\n";
962 if (args[1] == "touch_nocreate" && args.size() > 2) {
963 for (auto const& arg : cmMakeRange(args).advance(2)) {
964 if (!cmSystemTools::Touch(arg, false)) {
965 std::cerr << "cmake -E touch_nocreate: failed to update \"";
966 std::cerr << arg << "\".\n";
974 if (args[1] == "capabilities") {
975 if (args.size() > 2) {
976 std::cerr << "-E capabilities accepts no additional arguments\n";
979 cmake cm(cmake::RoleInternal, cmState::Unknown);
980 std::cout << cm.ReportCapabilities();
985 if (args[1] == "sleep" && args.size() > 2) {
987 for (auto const& arg : cmMakeRange(args).advance(2)) {
991 int n = sscanf(arg.c_str(), "%lg%c%c", &num, &unit, &extra);
992 if ((n == 1 || (n == 2 && unit == 's')) && num >= 0) {
995 std::cerr << "Unknown sleep time format \"" << arg << "\".\n";
1000 cmSystemTools::Delay(static_cast<unsigned int>(total * 1000));
1006 if (args[1] == "time" && args.size() > 2) {
1007 std::vector<std::string> command(args.begin() + 2, args.end());
1009 clock_t clock_start;
1010 clock_t clock_finish;
1015 clock_start = clock();
1017 cmSystemTools::RunSingleCommand(command, nullptr, nullptr, &ret);
1019 clock_finish = clock();
1022 double clocks_per_sec = static_cast<double>(CLOCKS_PER_SEC);
1023 std::cout << "Elapsed time: "
1024 << static_cast<long>(time_finish - time_start) << " s. (time)"
1026 << static_cast<double>(clock_finish - clock_start) /
1033 // Command to calculate the md5sum of a file
1034 if (args[1] == "md5sum" && args.size() >= 3) {
1035 return HashSumFile(args, cmCryptoHash::AlgoMD5);
1038 // Command to calculate the sha1sum of a file
1039 if (args[1] == "sha1sum" && args.size() >= 3) {
1040 return HashSumFile(args, cmCryptoHash::AlgoSHA1);
1043 if (args[1] == "sha224sum" && args.size() >= 3) {
1044 return HashSumFile(args, cmCryptoHash::AlgoSHA224);
1047 if (args[1] == "sha256sum" && args.size() >= 3) {
1048 return HashSumFile(args, cmCryptoHash::AlgoSHA256);
1051 if (args[1] == "sha384sum" && args.size() >= 3) {
1052 return HashSumFile(args, cmCryptoHash::AlgoSHA384);
1055 if (args[1] == "sha512sum" && args.size() >= 3) {
1056 return HashSumFile(args, cmCryptoHash::AlgoSHA512);
1059 // Command to concat files into one
1060 if (args[1] == "cat" && args.size() >= 3) {
1061 int return_value = 0;
1062 bool doing_options = true;
1063 for (auto const& arg : cmMakeRange(args).advance(2)) {
1064 if (doing_options && cmHasLiteralPrefix(arg, "-")) {
1066 doing_options = false;
1068 cmSystemTools::Error(arg + ": option not handled");
1071 } else if (!cmSystemTools::TestFileAccess(arg,
1072 cmsys::TEST_FILE_READ) &&
1073 cmSystemTools::TestFileAccess(arg, cmsys::TEST_FILE_OK)) {
1074 cmSystemTools::Error(arg + ": permission denied (ignoring)");
1076 } else if (cmSystemTools::FileIsDirectory(arg)) {
1077 cmSystemTools::Error(arg + ": is a directory (ignoring)");
1079 } else if (!cmSystemTools::FileExists(arg)) {
1080 cmSystemTools::Error(arg + ": no such file or directory (ignoring)");
1082 } else if (cmSystemTools::FileLength(arg) == 0) {
1083 // Ignore empty files, this is not an error
1085 // Destroy console buffers to drop cout/cerr encoding transform.
1090 return return_value;
1093 // Command to change directory and run a program.
1094 if (args[1] == "chdir" && args.size() >= 4) {
1095 std::string const& directory = args[2];
1096 if (!cmSystemTools::FileExists(directory)) {
1097 cmSystemTools::Error("Directory does not exist for chdir command: " +
1102 std::string command =
1103 cmWrap('"', cmMakeRange(args).advance(3), '"', " ");
1105 if (cmSystemTools::RunSingleCommand(
1106 command, nullptr, nullptr, &retval, directory.c_str(),
1107 cmSystemTools::OUTPUT_PASSTHROUGH, cmDuration::zero())) {
1114 // Command to start progress for a build
1115 if (args[1] == "cmake_progress_start" && args.size() == 4) {
1116 // basically remove the directory
1117 std::string dirName = cmStrCat(args[2], "/Progress");
1118 cmSystemTools::RemoveADirectory(dirName);
1120 // is the last argument a filename that exists?
1121 FILE* countFile = cmsys::SystemTools::Fopen(args[3], "r");
1124 if (1 != fscanf(countFile, "%i", &count)) {
1125 std::cerr << "Could not read from count file.\n";
1129 count = atoi(args[3].c_str());
1132 cmSystemTools::MakeDirectory(dirName);
1133 // write the count into the directory
1134 std::string fName = cmStrCat(dirName, "/count.txt");
1135 FILE* progFile = cmsys::SystemTools::Fopen(fName, "w");
1137 fprintf(progFile, "%i\n", count);
1144 // Command to report progress for a build
1145 if (args[1] == "cmake_progress_report" && args.size() >= 3) {
1146 // This has been superseded by cmake_echo_color --progress-*
1147 // options. We leave it here to avoid errors if somehow this
1148 // is invoked by an existing makefile without regenerating.
1152 // Command to create a symbolic link. Fails on platforms not
1154 if (args[1] == "create_symlink" && args.size() == 4) {
1155 std::string const& destinationFileName = args[3];
1156 if ((cmSystemTools::FileExists(destinationFileName) ||
1157 cmSystemTools::FileIsSymlink(destinationFileName)) &&
1158 !cmSystemTools::RemoveFile(destinationFileName)) {
1159 std::string emsg = cmSystemTools::GetLastSystemError();
1160 std::cerr << "failed to create symbolic link '" << destinationFileName
1161 << "' because existing path cannot be removed: " << emsg
1165 if (!cmSystemTools::CreateSymlink(args[2], destinationFileName)) {
1171 // Command to create a hard link. Fails on platforms not
1173 if (args[1] == "create_hardlink" && args.size() == 4) {
1174 std::string const& sourceFileName = args[2];
1175 std::string const& destinationFileName = args[3];
1177 if (!cmSystemTools::FileExists(sourceFileName)) {
1178 std::cerr << "failed to create hard link because source path '"
1179 << sourceFileName << "' does not exist \n";
1183 if ((cmSystemTools::FileExists(destinationFileName) ||
1184 cmSystemTools::FileIsSymlink(destinationFileName)) &&
1185 !cmSystemTools::RemoveFile(destinationFileName)) {
1186 std::string emsg = cmSystemTools::GetLastSystemError();
1187 std::cerr << "failed to create hard link '" << destinationFileName
1188 << "' because existing path cannot be removed: " << emsg
1193 if (!cmSystemTools::CreateLink(sourceFileName, destinationFileName)) {
1199 // Command to do nothing with an exit code of 0.
1200 if (args[1] == "true") {
1204 // Command to do nothing with an exit code of 1.
1205 if (args[1] == "false") {
1209 // Internal CMake shared library support.
1210 if (args[1] == "cmake_symlink_library" && args.size() == 5) {
1211 return cmcmd::SymlinkLibrary(args);
1214 // Internal CMake versioned executable support.
1215 if (args[1] == "cmake_symlink_executable" && args.size() == 4) {
1216 return cmcmd::SymlinkExecutable(args);
1219 // Internal CMake dependency scanning support.
1220 if (args[1] == "cmake_depends" && args.size() >= 6) {
1221 const bool verbose = isCMakeVerbose();
1223 // Create a cmake object instance to process dependencies.
1224 // All we need is the `set` command.
1225 cmake cm(cmake::RoleScript, cmState::Unknown);
1227 std::string homeDir;
1228 std::string startDir;
1229 std::string homeOutDir;
1230 std::string startOutDir;
1231 std::string depInfo;
1233 if (args.size() >= 8) {
1236 // -E cmake_depends <generator>
1237 // <home-src-dir> <start-src-dir>
1238 // <home-out-dir> <start-out-dir>
1239 // <dep-info> [--color=$(COLOR)]
1241 // All paths are provided.
1245 homeOutDir = args[5];
1246 startOutDir = args[6];
1248 if (args.size() >= 9 && cmHasLiteralPrefix(args[8], "--color=")) {
1249 // Enable or disable color based on the switch value.
1250 color = (args[8].size() == 8 || cmIsOn(args[8].substr(8)));
1253 // Support older signature for existing makefiles:
1255 // -E cmake_depends <generator>
1256 // <home-out-dir> <start-out-dir>
1259 // Just pretend the source directories are the same as the
1260 // binary directories so at least scanning will work.
1264 homeOutDir = args[3];
1265 startOutDir = args[3];
1269 // Create a local generator configured for the directory in
1270 // which dependencies will be scanned.
1271 homeDir = cmSystemTools::CollapseFullPath(homeDir);
1272 startDir = cmSystemTools::CollapseFullPath(startDir);
1273 homeOutDir = cmSystemTools::CollapseFullPath(homeOutDir);
1274 startOutDir = cmSystemTools::CollapseFullPath(startOutDir);
1275 cm.SetHomeDirectory(homeDir);
1276 cm.SetHomeOutputDirectory(homeOutDir);
1277 cm.GetCurrentSnapshot().SetDefaultDefinitions();
1278 if (auto ggd = cm.CreateGlobalGenerator(gen)) {
1279 cm.SetGlobalGenerator(std::move(ggd));
1280 cmStateSnapshot snapshot = cm.GetCurrentSnapshot();
1281 snapshot.GetDirectory().SetCurrentBinary(startOutDir);
1282 snapshot.GetDirectory().SetCurrentSource(startDir);
1283 cmMakefile mf(cm.GetGlobalGenerator(), snapshot);
1284 auto lgd = cm.GetGlobalGenerator()->CreateLocalGenerator(&mf);
1286 // FIXME: With advanced add_subdirectory usage, these are
1287 // not necessarily the same as the generator originally used.
1288 // We should pass all these directories through an info file.
1289 lgd->SetRelativePathTop(homeDir, homeOutDir);
1291 // Actually scan dependencies.
1292 return lgd->UpdateDependencies(depInfo, verbose, color) ? 0 : 2;
1297 #if !defined(CMAKE_BOOTSTRAP) || defined(CMAKE_BOOTSTRAP_MAKEFILES)
1298 // Internal CMake compiler dependencies filtering
1299 if (args[1] == "cmake_cl_compile_depends") {
1300 return CLCompileAndDependencies(args);
1304 // Internal CMake link script support.
1305 if (args[1] == "cmake_link_script" && args.size() >= 3) {
1306 return cmcmd::ExecuteLinkScript(args);
1309 #if !defined(CMAKE_BOOTSTRAP)
1310 // Internal CMake ninja dependency scanning support.
1311 if (args[1] == "cmake_ninja_depends") {
1312 return cmcmd_cmake_ninja_depends(args.begin() + 2, args.end());
1315 // Internal CMake ninja dyndep support.
1316 if (args[1] == "cmake_ninja_dyndep") {
1317 return cmcmd_cmake_ninja_dyndep(args.begin() + 2, args.end());
1321 // Internal CMake unimplemented feature notification.
1322 if (args[1] == "cmake_unimplemented_variable") {
1323 std::cerr << "Feature not implemented for this platform.";
1324 if (args.size() == 3) {
1325 std::cerr << " Variable " << args[2] << " is not set.";
1327 std::cerr << std::endl;
1331 if (args[1] == "vs_link_exe") {
1332 return cmcmd::VisualStudioLink(args, 1);
1335 if (args[1] == "vs_link_dll") {
1336 return cmcmd::VisualStudioLink(args, 2);
1339 if (args[1] == "cmake_llvm_rc") {
1340 return cmcmd::RunLLVMRC(args);
1343 // Internal CMake color makefile support.
1344 if (args[1] == "cmake_echo_color") {
1345 return cmcmd::ExecuteEchoColor(args);
1348 #ifndef CMAKE_BOOTSTRAP
1349 if ((args[1] == "cmake_autogen") && (args.size() >= 4)) {
1350 cm::string_view const infoFile = args[2];
1351 cm::string_view const config = args[3];
1352 return cmQtAutoMocUic(infoFile, config) ? 0 : 1;
1354 if ((args[1] == "cmake_autorcc") && (args.size() >= 3)) {
1355 cm::string_view const infoFile = args[2];
1356 cm::string_view const config =
1357 (args.size() > 3) ? cm::string_view(args[3]) : cm::string_view();
1358 return cmQtAutoRcc(infoFile, config) ? 0 : 1;
1363 if (args[1] == "tar" && args.size() > 3) {
1364 const char* knownFormats[] = { "7zip", "gnutar", "pax", "paxr", "zip" };
1366 std::string const& flags = args[2];
1367 std::string const& outFile = args[3];
1368 std::vector<std::string> files;
1371 cmSystemTools::cmTarExtractTimestamps extractTimestamps =
1372 cmSystemTools::cmTarExtractTimestamps::Yes;
1373 cmSystemTools::cmTarCompression compress =
1374 cmSystemTools::TarCompressNone;
1376 bool doing_options = true;
1377 for (auto const& arg : cmMakeRange(args).advance(4)) {
1378 if (doing_options && cmHasLiteralPrefix(arg, "--")) {
1380 doing_options = false;
1381 } else if (arg == "--zstd") {
1382 compress = cmSystemTools::TarCompressZstd;
1384 } else if (cmHasLiteralPrefix(arg, "--mtime=")) {
1385 mtime = arg.substr(8);
1386 } else if (cmHasLiteralPrefix(arg, "--files-from=")) {
1387 std::string const& files_from = arg.substr(13);
1388 if (!cmTarFilesFrom(files_from, files)) {
1391 } else if (cmHasLiteralPrefix(arg, "--format=")) {
1392 format = arg.substr(9);
1393 if (!cm::contains(knownFormats, format)) {
1394 cmSystemTools::Error("Unknown -E tar --format= argument: " +
1398 } else if (arg == "--touch") {
1399 extractTimestamps = cmSystemTools::cmTarExtractTimestamps::No;
1401 cmSystemTools::Error("Unknown option to -E tar: " + arg);
1405 files.push_back(arg);
1408 cmSystemTools::cmTarAction action = cmSystemTools::TarActionNone;
1409 bool verbose = false;
1411 for (auto flag : flags) {
1415 // Keep for backward compatibility. Ignored
1418 compress = cmSystemTools::TarCompressBZip2;
1422 compress = cmSystemTools::TarCompressXZ;
1426 compress = cmSystemTools::TarCompressGZip;
1433 action = cmSystemTools::TarActionList;
1436 action = cmSystemTools::TarActionCreate;
1439 action = cmSystemTools::TarActionExtract;
1442 std::cerr << "tar: Unknown argument: " << flag << "\n";
1446 if ((format == "7zip" || format == "zip") && nCompress > 0) {
1447 cmSystemTools::Error("Can not use compression flags with format: " +
1451 if (nCompress > 1) {
1452 cmSystemTools::Error("Can only compress a tar file one way; "
1453 "at most one flag of z, j, or J may be used");
1456 if (action == cmSystemTools::TarActionList) {
1457 if (!cmSystemTools::ListTar(outFile, files, verbose)) {
1458 cmSystemTools::Error("Problem listing tar: " + outFile);
1461 } else if (action == cmSystemTools::TarActionCreate) {
1462 if (files.empty()) {
1463 std::cerr << "tar: No files or directories specified\n";
1465 if (!cmSystemTools::CreateTar(outFile, files, compress, verbose, mtime,
1467 cmSystemTools::Error("Problem creating tar: " + outFile);
1470 } else if (action == cmSystemTools::TarActionExtract) {
1471 if (!cmSystemTools::ExtractTar(outFile, files, extractTimestamps,
1473 cmSystemTools::Error("Problem extracting tar: " + outFile);
1477 // OK, on windows 7 after we untar some files,
1478 // sometimes we can not rename the directory after
1479 // the untar is done. This breaks the external project
1480 // untar and rename code. So, by default we will wait
1481 // 1/10th of a second after the untar. If CMAKE_UNTAR_DELAY
1482 // is set in the env, its value will be used instead of 100.
1484 std::string delayVar;
1485 if (cmSystemTools::GetEnv("CMAKE_UNTAR_DELAY", delayVar)) {
1486 delay = atoi(delayVar.c_str());
1489 cmSystemTools::Delay(delay);
1493 cmSystemTools::Error("tar: No action specified. Please choose: 't' "
1494 "(list), 'c' (create) or 'x' (extract)");
1500 if (args[1] == "server") {
1501 cmSystemTools::Error(
1502 "CMake server mode has been removed in favor of the file-api.");
1506 #if !defined(CMAKE_BOOTSTRAP)
1507 // Internal CMake Fortran module support.
1508 if (args[1] == "cmake_copy_f90_mod" && args.size() >= 4) {
1509 return cmDependsFortran::CopyModule(args) ? 0 : 1;
1513 #if defined(_WIN32) && !defined(__CYGWIN__)
1514 // Write registry value
1515 if (args[1] == "write_regv" && args.size() > 3) {
1516 return cmSystemTools::WriteRegistryValue(args[2], args[3]) ? 0 : 1;
1519 // Delete registry value
1520 if (args[1] == "delete_regv" && args.size() > 2) {
1521 return cmSystemTools::DeleteRegistryValue(args[2]) ? 0 : 1;
1525 if (args[1] == "comspec" && args.size() > 2) {
1526 std::cerr << "Win9x helper \"cmake -E comspec\" no longer supported\n";
1530 if (args[1] == "env_vs8_wince" && args.size() == 3) {
1531 return cmcmd::WindowsCEEnvironment("8.0", args[2]);
1534 if (args[1] == "env_vs9_wince" && args.size() == 3) {
1535 return cmcmd::WindowsCEEnvironment("9.0", args[2]);
1539 // Internal depfile transformation
1540 if (args[1] == "cmake_transform_depfile" && args.size() == 10) {
1541 auto format = cmDepfileFormat::GccDepfile;
1542 if (args[3] == "gccdepfile") {
1543 format = cmDepfileFormat::GccDepfile;
1544 } else if (args[3] == "makedepfile") {
1545 format = cmDepfileFormat::MakeDepfile;
1546 } else if (args[3] == "MSBuildAdditionalInputs") {
1547 format = cmDepfileFormat::MSBuildAdditionalInputs;
1551 // Create a cmake object instance to process dependencies.
1552 // All we need is the `set` command.
1553 cmake cm(cmake::RoleScript, cmState::Unknown);
1554 std::string homeDir;
1555 std::string startDir;
1556 std::string homeOutDir;
1557 std::string startOutDir;
1558 homeDir = cmSystemTools::CollapseFullPath(args[4]);
1559 startDir = cmSystemTools::CollapseFullPath(args[5]);
1560 homeOutDir = cmSystemTools::CollapseFullPath(args[6]);
1561 startOutDir = cmSystemTools::CollapseFullPath(args[7]);
1562 cm.SetHomeDirectory(homeDir);
1563 cm.SetHomeOutputDirectory(homeOutDir);
1564 cm.GetCurrentSnapshot().SetDefaultDefinitions();
1565 if (auto ggd = cm.CreateGlobalGenerator(args[2])) {
1566 cm.SetGlobalGenerator(std::move(ggd));
1567 cmStateSnapshot snapshot = cm.GetCurrentSnapshot();
1568 snapshot.GetDirectory().SetCurrentBinary(startOutDir);
1569 snapshot.GetDirectory().SetCurrentSource(startDir);
1570 cmMakefile mf(cm.GetGlobalGenerator(), snapshot);
1571 auto lgd = cm.GetGlobalGenerator()->CreateLocalGenerator(&mf);
1573 // FIXME: With advanced add_subdirectory usage, these are
1574 // not necessarily the same as the generator originally used.
1575 // We should pass all these directories through an info file.
1576 lgd->SetRelativePathTop(homeDir, homeOutDir);
1578 return cmTransformDepfile(format, *lgd, args[8], args[9]) ? 0 : 2;
1584 CMakeCommandUsage(args[0]);
1588 int cmcmd::HashSumFile(std::vector<std::string> const& args,
1589 cmCryptoHash::Algo algo)
1591 if (args.size() < 3) {
1596 for (auto const& filename : cmMakeRange(args).advance(2)) {
1597 // Cannot compute sum of a directory
1598 if (cmSystemTools::FileIsDirectory(filename)) {
1599 std::cerr << "Error: " << filename << " is a directory" << std::endl;
1603 #ifndef CMAKE_BOOTSTRAP
1604 = cmSystemTools::ComputeFileHash(filename, algo)
1607 if (value.empty()) {
1608 // To mimic "md5sum/shasum" behavior in a shell:
1609 std::cerr << filename << ": No such file or directory" << std::endl;
1612 std::cout << value << " " << filename << std::endl;
1619 int cmcmd::SymlinkLibrary(std::vector<std::string> const& args)
1622 std::string realName = args[2];
1623 std::string soName = args[3];
1624 std::string name = args[4];
1625 cmSystemTools::ConvertToUnixSlashes(realName);
1626 cmSystemTools::ConvertToUnixSlashes(soName);
1627 cmSystemTools::ConvertToUnixSlashes(name);
1628 if (soName != realName) {
1629 cmsys::Status status = cmcmd::SymlinkInternal(realName, soName);
1631 cmSystemTools::Error(
1632 cmStrCat("cmake_symlink_library: System Error: ", status.GetString()));
1636 if (name != soName) {
1637 cmsys::Status status = cmcmd::SymlinkInternal(soName, name);
1639 cmSystemTools::Error(
1640 cmStrCat("cmake_symlink_library: System Error: ", status.GetString()));
1647 int cmcmd::SymlinkExecutable(std::vector<std::string> const& args)
1650 std::string const& realName = args[2];
1651 std::string const& name = args[3];
1652 if (name != realName) {
1653 cmsys::Status status = cmcmd::SymlinkInternal(realName, name);
1655 cmSystemTools::Error(cmStrCat("cmake_symlink_executable: System Error: ",
1656 status.GetString()));
1663 cmsys::Status cmcmd::SymlinkInternal(std::string const& file,
1664 std::string const& link)
1666 if (cmSystemTools::FileExists(link) || cmSystemTools::FileIsSymlink(link)) {
1667 cmSystemTools::RemoveFile(link);
1669 std::string linktext = cmSystemTools::GetFilenameName(file);
1670 #if defined(_WIN32) && !defined(__CYGWIN__)
1671 std::string errorMessage;
1672 cmsys::Status status =
1673 cmSystemTools::CreateSymlink(linktext, link, &errorMessage);
1674 // Creating a symlink will fail with ERROR_PRIVILEGE_NOT_HELD if the user
1675 // does not have SeCreateSymbolicLinkPrivilege, or if developer mode is not
1676 // active. In that case, we try to copy the file.
1677 if (status.GetWindows() == ERROR_PRIVILEGE_NOT_HELD) {
1678 status = cmSystemTools::CopyFileAlways(file, link);
1679 } else if (!status) {
1680 cmSystemTools::Error(errorMessage);
1684 return cmSystemTools::CreateSymlink(linktext, link);
1688 static void cmcmdProgressReport(std::string const& dir, std::string const& num)
1690 std::string dirName = cmStrCat(dir, "/Progress");
1695 fName = cmStrCat(dirName, "/count.txt");
1696 progFile = cmsys::SystemTools::Fopen(fName, "r");
1701 if (1 != fscanf(progFile, "%i", &count)) {
1702 std::cerr << "Could not read from progress file.\n";
1706 const char* last = num.c_str();
1707 for (const char* c = last;; ++c) {
1708 if (*c == ',' || *c == '\0') {
1710 fName = cmStrCat(dirName, '/');
1711 fName.append(last, c - last);
1712 progFile = cmsys::SystemTools::Fopen(fName, "w");
1714 fprintf(progFile, "empty");
1725 static_cast<int>(cmsys::Directory::GetNumberOfFilesInDirectory(dirName));
1727 // print the progress
1728 fprintf(stdout, "[%3i%%] ", ((fileNum - 3) * 100) / count);
1732 int cmcmd::ExecuteEchoColor(std::vector<std::string> const& args)
1734 // The arguments are
1735 // args[0] == <cmake-executable>
1736 // args[1] == cmake_echo_color
1738 bool enabled = true;
1739 int color = cmsysTerminal_Color_Normal;
1740 bool newline = true;
1741 std::string progressDir;
1742 for (auto const& arg : cmMakeRange(args).advance(2)) {
1743 if (cmHasLiteralPrefix(arg, "--switch=")) {
1744 // Enable or disable color based on the switch value.
1745 std::string value = arg.substr(9);
1746 if (!value.empty()) {
1747 enabled = cmIsOn(value);
1749 } else if (cmHasLiteralPrefix(arg, "--progress-dir=")) {
1750 progressDir = arg.substr(15);
1751 } else if (cmHasLiteralPrefix(arg, "--progress-num=")) {
1752 if (!progressDir.empty()) {
1753 std::string const& progressNum = arg.substr(15);
1754 cmcmdProgressReport(progressDir, progressNum);
1756 } else if (arg == "--normal") {
1757 color = cmsysTerminal_Color_Normal;
1758 } else if (arg == "--black") {
1759 color = cmsysTerminal_Color_ForegroundBlack;
1760 } else if (arg == "--red") {
1761 color = cmsysTerminal_Color_ForegroundRed;
1762 } else if (arg == "--green") {
1763 color = cmsysTerminal_Color_ForegroundGreen;
1764 } else if (arg == "--yellow") {
1765 color = cmsysTerminal_Color_ForegroundYellow;
1766 } else if (arg == "--blue") {
1767 color = cmsysTerminal_Color_ForegroundBlue;
1768 } else if (arg == "--magenta") {
1769 color = cmsysTerminal_Color_ForegroundMagenta;
1770 } else if (arg == "--cyan") {
1771 color = cmsysTerminal_Color_ForegroundCyan;
1772 } else if (arg == "--white") {
1773 color = cmsysTerminal_Color_ForegroundWhite;
1774 } else if (arg == "--bold") {
1775 color |= cmsysTerminal_Color_ForegroundBold;
1776 } else if (arg == "--no-newline") {
1778 } else if (arg == "--newline") {
1781 // Color is enabled. Print with the current color.
1782 cmSystemTools::MakefileColorEcho(color, arg.c_str(), newline, enabled);
1789 int cmcmd::ExecuteLinkScript(std::vector<std::string> const& args)
1791 // The arguments are
1792 // args[0] == <cmake-executable>
1793 // args[1] == cmake_link_script
1794 // args[2] == <link-script-name>
1795 // args[3] == --verbose=?
1796 bool verbose = false;
1797 if (args.size() >= 4) {
1798 if (cmHasLiteralPrefix(args[3], "--verbose=")) {
1799 if (!cmIsOff(args[3].substr(10))) {
1805 // Allocate a process instance.
1806 cmsysProcess* cp = cmsysProcess_New();
1808 std::cerr << "Error allocating process instance in link script."
1813 // Children should share stdout and stderr with this process.
1814 cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDOUT, 1);
1815 cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDERR, 1);
1817 // Run the command lines verbatim.
1818 cmsysProcess_SetOption(cp, cmsysProcess_Option_Verbatim, 1);
1820 // Read command lines from the script.
1821 cmsys::ifstream fin(args[2].c_str());
1823 std::cerr << "Error opening link script \"" << args[2] << "\""
1828 // Run one command at a time.
1829 std::string command;
1831 while (result == 0 && cmSystemTools::GetLineFromStream(fin, command)) {
1832 // Skip empty command lines.
1833 if (command.find_first_not_of(" \t") == std::string::npos) {
1837 // Setup this command line.
1838 const char* cmd[2] = { command.c_str(), nullptr };
1839 cmsysProcess_SetCommand(cp, cmd);
1841 // Report the command if verbose output is enabled.
1843 std::cout << command << std::endl;
1846 // Run the command and wait for it to exit.
1847 cmsysProcess_Execute(cp);
1848 cmsysProcess_WaitForExit(cp, nullptr);
1850 // Report failure if any.
1851 switch (cmsysProcess_GetState(cp)) {
1852 case cmsysProcess_State_Exited: {
1853 int value = cmsysProcess_GetExitValue(cp);
1858 case cmsysProcess_State_Exception:
1859 std::cerr << "Error running link command: "
1860 << cmsysProcess_GetExceptionString(cp) << std::endl;
1863 case cmsysProcess_State_Error:
1864 std::cerr << "Error running link command: "
1865 << cmsysProcess_GetErrorString(cp) << std::endl;
1873 // Free the process instance.
1874 cmsysProcess_Delete(cp);
1876 // Return the final resulting return value.
1880 int cmcmd::WindowsCEEnvironment(const char* version, const std::string& name)
1882 #if !defined(CMAKE_BOOTSTRAP) && defined(_WIN32) && !defined(__CYGWIN__)
1883 cmVisualStudioWCEPlatformParser parser(name.c_str());
1884 parser.ParseVersion(version);
1885 if (parser.Found()) {
1886 /* clang-format off */
1887 std::cout << "@echo off\n"
1888 "echo Environment Selection: " << name << "\n"
1889 "set PATH=" << parser.GetPathDirectories() << "\n"
1890 "set INCLUDE=" << parser.GetIncludeDirectories() << "\n"
1891 "set LIB=" << parser.GetLibraryDirectories() << std::endl;
1892 /* clang-format on */
1899 std::cerr << "Could not find " << name;
1903 int cmcmd::RunPreprocessor(const std::vector<std::string>& command,
1904 const std::string& intermediate_file)
1906 cmUVProcessChainBuilder builder;
1909 int preprocessedFile =
1910 uv_fs_open(nullptr, &fs_req, intermediate_file.c_str(), O_CREAT | O_RDWR,
1912 uv_fs_req_cleanup(&fs_req);
1915 .SetExternalStream(cmUVProcessChainBuilder::Stream_OUTPUT,
1917 .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR)
1918 .AddCommand(command);
1919 auto process = builder.Start();
1920 if (!process.Valid()) {
1921 std::cerr << "Failed to start preprocessor.";
1924 if (!process.Wait()) {
1925 std::cerr << "Failed to wait for preprocessor";
1928 auto status = process.GetStatus();
1929 if (!status[0] || status[0]->ExitStatus != 0) {
1930 auto* errorStream = process.ErrorStream();
1932 std::cerr << errorStream->rdbuf();
1940 int cmcmd::RunLLVMRC(std::vector<std::string> const& args)
1942 // The arguments are
1943 // args[0] == <cmake-executable>
1944 // args[1] == cmake_llvm_rc
1945 // args[2] == source_file_path
1946 // args[3] == intermediate_file
1947 // args[4..n] == preprocess+args
1949 // args[n+2...] == llvm-rc+args
1950 if (args.size() < 3) {
1951 std::cerr << "Invalid cmake_llvm_rc arguments";
1955 const std::string& intermediate_file = args[3];
1956 const std::string& source_file = args[2];
1957 std::vector<std::string> preprocess;
1958 std::vector<std::string> resource_compile;
1959 std::vector<std::string>* pArgTgt = &preprocess;
1961 static const cmsys::RegularExpression llvm_rc_only_single_arg("^[-/](N|Y)");
1962 static const cmsys::RegularExpression llvm_rc_only_double_arg(
1963 "^[-/](C|LN|L)(.)?");
1964 static const cmsys::RegularExpression common_double_arg(
1965 "^[-/](D|U|I|FO|fo|Fo)(.)?");
1966 bool acceptNextArg = false;
1967 bool skipNextArg = false;
1968 for (std::string const& arg : cmMakeRange(args).advance(4)) {
1970 skipNextArg = false;
1973 // We use ++ as separator between the preprocessing step definition and
1974 // the rc compilation step because we need to prepend a -- to separate the
1975 // source file properly from other options when using clang-cl for
1978 pArgTgt = &resource_compile;
1979 skipNextArg = false;
1980 acceptNextArg = true;
1982 cmsys::RegularExpressionMatch match;
1983 if (!acceptNextArg) {
1984 if (common_double_arg.find(arg.c_str(), match)) {
1985 acceptNextArg = match.match(2).empty();
1987 if (llvm_rc_only_single_arg.find(arg.c_str(), match)) {
1988 if (pArgTgt == &preprocess) {
1991 } else if (llvm_rc_only_double_arg.find(arg.c_str(), match)) {
1992 if (pArgTgt == &preprocess) {
1993 skipNextArg = match.match(2).empty();
1996 acceptNextArg = match.match(2).empty();
1997 } else if (pArgTgt == &resource_compile) {
2002 acceptNextArg = false;
2004 if (arg.find("SOURCE_DIR") != std::string::npos) {
2005 std::string sourceDirArg = arg;
2006 cmSystemTools::ReplaceString(
2007 sourceDirArg, "SOURCE_DIR",
2008 cmSystemTools::GetFilenamePath(source_file));
2009 pArgTgt->push_back(sourceDirArg);
2011 pArgTgt->push_back(arg);
2015 if (preprocess.empty()) {
2016 std::cerr << "Empty preprocessing command";
2019 if (resource_compile.empty()) {
2020 std::cerr << "Empty resource compilation command";
2023 // Since we might have skipped the last argument to llvm-rc
2024 // we need to make sure the llvm-rc source file is present in the
2026 if (resource_compile.back() != intermediate_file) {
2027 resource_compile.push_back(intermediate_file);
2030 auto result = RunPreprocessor(preprocess, intermediate_file);
2032 cmSystemTools::RemoveFile(intermediate_file);
2035 cmUVProcessChainBuilder builder;
2037 builder.SetBuiltinStream(cmUVProcessChainBuilder::Stream_OUTPUT)
2038 .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR)
2039 .AddCommand(resource_compile);
2040 auto process = builder.Start();
2042 if (!process.Valid()) {
2043 std::cerr << "Failed to start resource compiler.";
2046 if (!process.Wait()) {
2047 std::cerr << "Failed to wait for resource compiler";
2052 cmSystemTools::RemoveFile(intermediate_file);
2056 auto status = process.GetStatus();
2057 if (!status[0] || status[0]->ExitStatus != 0) {
2058 auto* errorStream = process.ErrorStream();
2060 std::cerr << errorStream->rdbuf();
2072 bool Incremental = false;
2073 bool LinkGeneratesManifest = true;
2074 std::vector<std::string> LinkCommand;
2075 std::vector<std::string> UserManifests;
2076 std::string LinkerManifestFile;
2077 std::string ManifestFile;
2078 std::string ManifestFileRC;
2079 std::string ManifestFileRes;
2080 std::string TargetFile;
2085 cmVSLink(int type, bool verbose)
2090 bool Parse(std::vector<std::string>::const_iterator argBeg,
2091 std::vector<std::string>::const_iterator argEnd);
2095 int LinkIncremental();
2096 int LinkNonIncremental();
2097 int RunMT(std::string const& out, bool notify);
2100 // For visual studio 2005 and newer manifest files need to be embedded into
2101 // exe and dll's. This code does that in such a way that incremental linking
2103 int cmcmd::VisualStudioLink(std::vector<std::string> const& args, int type)
2105 // Replace streambuf so we output in the system codepage. CMake is set up
2106 // to output in Unicode (see SetUTF8Pipes) but the Visual Studio linker
2107 // outputs using the system codepage so we need to change behavior when
2108 // we run the link command.
2109 cmConsoleBuf consoleBuf;
2111 if (args.size() < 2) {
2114 const bool verbose = cmSystemTools::HasEnv("VERBOSE");
2115 std::vector<std::string> expandedArgs;
2116 for (std::string const& i : args) {
2117 // check for nmake temporary files
2118 if (i[0] == '@' && !cmHasLiteralPrefix(i, "@CMakeFiles")) {
2119 cmsys::ifstream fin(i.substr(1).c_str());
2121 while (cmSystemTools::GetLineFromStream(fin, line)) {
2122 cmSystemTools::ParseWindowsCommandLine(line.c_str(), expandedArgs);
2125 expandedArgs.push_back(i);
2129 cmVSLink vsLink(type, verbose);
2130 if (!vsLink.Parse(expandedArgs.begin() + 2, expandedArgs.end())) {
2133 return vsLink.Link();
2141 struct NumberFormatter
2143 NumberFormat Format;
2145 NumberFormatter(NumberFormat format, int value)
2151 static std::ostream& operator<<(std::ostream& stream,
2152 NumberFormatter const& formatter)
2154 auto const& flags = stream.flags();
2155 if (formatter.Format == FORMAT_DECIMAL) {
2156 stream << std::dec << formatter.Value;
2158 stream << "0x" << std::hex << formatter.Value;
2160 stream.flags(flags);
2164 static bool RunCommand(const char* comment,
2165 std::vector<std::string> const& command, bool verbose,
2166 NumberFormat exitFormat, int* retCodeOut = nullptr,
2167 bool (*retCodeOkay)(int) = nullptr)
2170 std::cout << comment << ":\n";
2171 std::cout << cmJoin(command, " ") << "\n";
2175 bool commandResult = cmSystemTools::RunSingleCommand(
2176 command, &output, &output, &retCode, nullptr, cmSystemTools::OUTPUT_NONE);
2177 bool const retCodeSuccess =
2178 retCode == 0 || (retCodeOkay && retCodeOkay(retCode));
2179 bool const success = commandResult && retCodeSuccess;
2181 if (commandResult || !retCodeSuccess) {
2182 *retCodeOut = retCode;
2188 std::cout << comment << ": command \"" << cmJoin(command, " ")
2189 << "\" failed (exit code "
2190 << NumberFormatter(exitFormat, retCode)
2191 << ") with the following output:\n"
2193 } else if (verbose) {
2194 // always print the output of the command, unless
2195 // it is the dumb rc command banner
2196 if (output.find("Resource Compiler Version") == std::string::npos) {
2197 std::cout << output;
2203 bool cmVSLink::Parse(std::vector<std::string>::const_iterator argBeg,
2204 std::vector<std::string>::const_iterator argEnd)
2206 // Parse our own arguments.
2209 while (arg != argEnd && cmHasLiteralPrefix(*arg, "-")) {
2214 if (*arg == "--manifests") {
2215 for (++arg; arg != argEnd && !cmHasLiteralPrefix(*arg, "-"); ++arg) {
2216 this->UserManifests.push_back(*arg);
2218 } else if (cmHasLiteralPrefix(*arg, "--intdir=")) {
2219 intDir = arg->substr(9);
2221 } else if (cmHasLiteralPrefix(*arg, "--rc=")) {
2222 this->RcPath = arg->substr(5);
2224 } else if (cmHasLiteralPrefix(*arg, "--mt=")) {
2225 this->MtPath = arg->substr(5);
2228 std::cerr << "unknown argument '" << *arg << "'\n";
2232 if (intDir.empty()) {
2236 // The rest of the arguments form the link command.
2237 if (arg == argEnd) {
2240 this->LinkCommand.insert(this->LinkCommand.begin(), arg, argEnd);
2242 // Parse the link command to extract information we need.
2243 for (; arg != argEnd; ++arg) {
2244 if (cmSystemTools::Strucmp(arg->c_str(), "/INCREMENTAL:YES") == 0 ||
2245 cmSystemTools::Strucmp(arg->c_str(), "/INCREMENTAL") == 0) {
2246 this->Incremental = true;
2247 } else if (cmSystemTools::Strucmp(arg->c_str(), "/MANIFEST:NO") == 0) {
2248 this->LinkGeneratesManifest = false;
2249 } else if (cmHasLiteralPrefix(*arg, "/Fe")) {
2250 this->TargetFile = arg->substr(3);
2251 } else if (cmHasLiteralPrefix(*arg, "/out:")) {
2252 this->TargetFile = arg->substr(5);
2256 if (this->TargetFile.empty()) {
2260 this->ManifestFile = intDir + "/embed.manifest";
2261 this->LinkerManifestFile = intDir + "/intermediate.manifest";
2263 if (this->Incremental) {
2264 // We will compile a resource containing the manifest and
2265 // pass it to the link command.
2266 this->ManifestFileRC = intDir + "/manifest.rc";
2267 this->ManifestFileRes = intDir + "/manifest.res";
2268 } else if (this->UserManifests.empty()) {
2269 // Prior to support for user-specified manifests CMake placed the
2270 // linker-generated manifest next to the binary (as if it were not to be
2271 // embedded) when not linking incrementally. Preserve this behavior.
2272 this->ManifestFile = this->TargetFile + ".manifest";
2273 this->LinkerManifestFile = this->ManifestFile;
2276 if (this->LinkGeneratesManifest) {
2277 this->LinkCommand.emplace_back("/MANIFEST");
2278 this->LinkCommand.push_back("/MANIFESTFILE:" + this->LinkerManifestFile);
2284 int cmVSLink::Link()
2286 if (this->Incremental &&
2287 (this->LinkGeneratesManifest || !this->UserManifests.empty())) {
2288 if (this->Verbose) {
2289 std::cout << "Visual Studio Incremental Link with embedded manifests\n";
2291 return this->LinkIncremental();
2293 if (this->Verbose) {
2294 if (!this->Incremental) {
2295 std::cout << "Visual Studio Non-Incremental Link\n";
2297 std::cout << "Visual Studio Incremental Link without manifests\n";
2300 return this->LinkNonIncremental();
2303 static bool mtRetIsUpdate(int mtRet)
2305 // 'mt /notify_update' returns a special value (differing between
2306 // Windows and POSIX hosts) when it updated the manifest file.
2307 return mtRet == 0x41020001 || mtRet == 0xbb;
2310 int cmVSLink::LinkIncremental()
2312 // This follows the steps listed here:
2313 // http://blogs.msdn.com/zakramer/archive/2006/05/22/603558.aspx
2315 // 1. Compiler compiles the application and generates the *.obj files.
2316 // 2. An empty manifest file is generated if this is a clean build and
2317 // if not the previous one is reused.
2318 // 3. The resource compiler (rc.exe) compiles the *.manifest file to a
2320 // 4. Linker generates the binary (EXE or DLL) with the /incremental
2321 // switch and embeds the dummy manifest file. The linker also generates
2322 // the real manifest file based on the binaries that your binary depends
2324 // 5. The manifest tool (mt.exe) is then used to generate the final
2327 // If the final manifest is changed, then 6 and 7 are run, if not
2328 // they are skipped, and it is done.
2330 // 6. The resource compiler is invoked one more time.
2331 // 7. Finally, the Linker does another incremental link, but since the
2332 // only thing that has changed is the *.res file that contains the
2333 // manifest it is a short link.
2335 // Create a resource file referencing the manifest.
2336 std::string absManifestFile =
2337 cmSystemTools::CollapseFullPath(this->ManifestFile);
2338 if (this->Verbose) {
2339 std::cout << "Create " << this->ManifestFileRC << "\n";
2342 cmsys::ofstream fout(this->ManifestFileRC.c_str());
2346 // Insert a pragma statement to specify utf-8 encoding.
2347 fout << "#pragma code_page(65001)\n";
2349 << " /* CREATEPROCESS_MANIFEST_RESOURCE_ID */ "
2350 "24 /* RT_MANIFEST */ \""
2351 << absManifestFile << "\"";
2354 // If we have not previously generated a manifest file,
2355 // generate a manifest file so the resource compiler succeeds.
2356 if (!cmSystemTools::FileExists(this->ManifestFile)) {
2357 if (this->Verbose) {
2358 std::cout << "Create empty: " << this->ManifestFile << "\n";
2360 if (this->UserManifests.empty()) {
2361 // generate an empty manifest because there are no user provided
2363 cmsys::ofstream foutTmp(this->ManifestFile.c_str());
2365 this->RunMT("/out:" + this->ManifestFile, false);
2369 // Compile the resource file.
2370 std::vector<std::string> rcCommand;
2371 rcCommand.push_back(this->RcPath.empty() ? "rc" : this->RcPath);
2372 rcCommand.emplace_back("/fo");
2373 rcCommand.push_back(this->ManifestFileRes);
2374 rcCommand.push_back(this->ManifestFileRC);
2375 if (!RunCommand("RC Pass 1", rcCommand, this->Verbose, FORMAT_DECIMAL)) {
2379 // Tell the linker to use our manifest compiled into a resource.
2380 this->LinkCommand.push_back(this->ManifestFileRes);
2382 // Run the link command (possibly generates intermediate manifest).
2383 if (!RunCommand("LINK Pass 1", this->LinkCommand, this->Verbose,
2388 // Run the manifest tool to create the final manifest.
2389 int mtRet = this->RunMT("/out:" + this->ManifestFile, true);
2391 // If mt returns a special value then it updated the manifest file so
2392 // we need to embed it again. Otherwise we are done.
2393 if (!mtRetIsUpdate(mtRet)) {
2397 // Compile the resource file again.
2398 if (!RunCommand("RC Pass 2", rcCommand, this->Verbose, FORMAT_DECIMAL)) {
2402 // Link incrementally again to use the updated resource.
2403 if (!RunCommand("FINAL LINK", this->LinkCommand, this->Verbose,
2410 int cmVSLink::LinkNonIncremental()
2412 // Run the link command (possibly generates intermediate manifest).
2413 if (!RunCommand("LINK", this->LinkCommand, this->Verbose, FORMAT_DECIMAL)) {
2417 // If we have no manifest files we are done.
2418 if (!this->LinkGeneratesManifest && this->UserManifests.empty()) {
2422 // Run the manifest tool to embed the final manifest in the binary.
2424 "/outputresource:" + this->TargetFile + (this->Type == 1 ? ";#1" : ";#2");
2425 return this->RunMT(mtOut, false);
2428 int cmVSLink::RunMT(std::string const& out, bool notify)
2430 std::vector<std::string> mtCommand;
2431 mtCommand.push_back(this->MtPath.empty() ? "mt" : this->MtPath);
2432 mtCommand.emplace_back("/nologo");
2433 mtCommand.emplace_back("/manifest");
2435 // add the linker generated manifest if the file exists.
2436 if (this->LinkGeneratesManifest &&
2437 cmSystemTools::FileExists(this->LinkerManifestFile)) {
2438 mtCommand.push_back(this->LinkerManifestFile);
2440 cm::append(mtCommand, this->UserManifests);
2441 mtCommand.push_back(out);
2443 // Add an undocumented option that enables a special return
2444 // code to notify us when the manifest is modified.
2445 mtCommand.emplace_back("/notify_update");
2448 if (!RunCommand("MT", mtCommand, this->Verbose, FORMAT_HEX, &mtRet,