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>
11 #include "cmAlgorithms.h"
12 #include "cmDuration.h"
13 #include "cmGlobalGenerator.h"
14 #include "cmLocalGenerator.h"
15 #include "cmMakefile.h"
16 #include "cmQtAutoMocUic.h"
17 #include "cmQtAutoRcc.h"
20 #include "cmStateDirectory.h"
21 #include "cmStateSnapshot.h"
22 #include "cmStringAlgorithms.h"
23 #include "cmSystemTools.h"
24 #include "cmUVProcessChain.h"
25 #include "cmUtils.hxx"
26 #include "cmVersion.h"
29 #if !defined(CMAKE_BOOTSTRAP)
30 # include "cmDependsFortran.h" // For -E cmake_copy_f90_mod callback.
31 # include "cmFileTime.h"
32 # include "cmServer.h"
33 # include "cmServerConnection.h"
35 # include "bindexplib.h"
38 #if !defined(CMAKE_BOOTSTRAP) && defined(_WIN32)
39 # include "cmsys/ConsoleBuf.hxx"
42 #if !defined(CMAKE_BOOTSTRAP) && defined(_WIN32) && !defined(__CYGWIN__)
43 # include "cmVisualStudioWCEPlatformParser.h"
56 #include <cm/string_view>
58 #include "cmsys/Directory.hxx"
59 #include "cmsys/FStream.hxx"
60 #include "cmsys/Process.h"
61 #include "cmsys/Terminal.h"
65 int cmcmd_cmake_ninja_depends(std::vector<std::string>::const_iterator argBeg,
66 std::vector<std::string>::const_iterator argEnd);
67 int cmcmd_cmake_ninja_dyndep(std::vector<std::string>::const_iterator argBeg,
68 std::vector<std::string>::const_iterator argEnd);
70 void CMakeCommandUsage(const char* program)
72 std::ostringstream errorStream;
74 #ifndef CMAKE_BOOTSTRAP
75 /* clang-format off */
77 << "cmake version " << cmVersion::GetCMakeVersion() << "\n";
80 /* clang-format off */
82 << "cmake bootstrap\n";
85 // If you add new commands, change here,
86 // and in cmakemain.cxx in the options table
87 /* clang-format off */
89 << "Usage: " << program << " -E <command> [arguments...]\n"
90 << "Available commands: \n"
91 << " capabilities - Report capabilities built into cmake "
93 << " chdir dir cmd [args...] - run command in a given directory\n"
94 << " compare_files [--ignore-eol] file1 file2\n"
95 << " - check if file1 is same as file2\n"
96 << " copy <file>... destination - copy files to destination "
97 "(either file or directory)\n"
98 << " copy_directory <dir>... destination - copy content of <dir>... "
99 "directories to 'destination' directory\n"
100 << " copy_if_different <file>... destination - copy files if it has "
102 << " echo [<string>...] - displays arguments as text\n"
103 << " echo_append [<string>...] - displays arguments as text but no new "
105 << " env [--unset=NAME]... [NAME=VALUE]... COMMAND [ARG]...\n"
106 << " - run command in a modified environment\n"
107 << " environment - display the current environment\n"
108 << " make_directory <dir>... - create parent and <dir> directories\n"
109 << " md5sum <file>... - create MD5 checksum of files\n"
110 << " sha1sum <file>... - create SHA1 checksum of files\n"
111 << " sha224sum <file>... - create SHA224 checksum of files\n"
112 << " sha256sum <file>... - create SHA256 checksum of files\n"
113 << " sha384sum <file>... - create SHA384 checksum of files\n"
114 << " sha512sum <file>... - create SHA512 checksum of files\n"
115 << " remove [-f] <file>... - remove the file(s), use -f to force "
116 "it (deprecated: use rm instead)\n"
117 << " remove_directory <dir>... - remove directories and their contents (deprecated: use rm instead)\n"
118 << " rename oldname newname - rename a file or directory "
120 << " rm [-rRf] <file/dir>... - remove files or directories, use -f to "
121 "force it, r or R to remove directories and their contents recursively\n"
122 << " server - start cmake in server mode\n"
123 << " sleep <number>... - sleep for given number of seconds\n"
124 << " tar [cxt][vf][zjJ] file.tar [file/dir1 file/dir2 ...]\n"
125 << " - create or extract a tar or zip archive\n"
126 << " time command [args...] - run command and display elapsed time\n"
127 << " touch <file>... - touch a <file>.\n"
128 << " touch_nocreate <file>... - touch a <file> but do not create it.\n"
129 << " create_symlink old new - create a symbolic link new -> old\n"
130 << " true - do nothing with an exit code of 0\n"
131 << " false - do nothing with an exit code of 1\n"
132 #if defined(_WIN32) && !defined(__CYGWIN__)
133 << "Available on Windows only:\n"
134 << " delete_regv key - delete registry value\n"
135 << " env_vs8_wince sdkname - displays a batch file which sets the "
136 "environment for the provided Windows CE SDK installed in VS2005\n"
137 << " env_vs9_wince sdkname - displays a batch file which sets the "
138 "environment for the provided Windows CE SDK installed in VS2008\n"
139 << " write_regv key value - write registry value\n"
142 /* clang-format on */
144 cmSystemTools::Error(errorStream.str());
147 static bool cmTarFilesFrom(std::string const& file,
148 std::vector<std::string>& files)
150 if (cmSystemTools::FileIsDirectory(file)) {
151 std::ostringstream e;
152 e << "-E tar --files-from= file '" << file << "' is a directory";
153 cmSystemTools::Error(e.str());
156 cmsys::ifstream fin(file.c_str());
158 std::ostringstream e;
159 e << "-E tar --files-from= file '" << file << "' not found";
160 cmSystemTools::Error(e.str());
164 while (cmSystemTools::GetLineFromStream(fin, line)) {
168 if (cmHasLiteralPrefix(line, "--add-file=")) {
169 files.push_back(line.substr(11));
170 } else if (cmHasLiteralPrefix(line, "-")) {
171 std::ostringstream e;
172 e << "-E tar --files-from='" << file << "' file invalid line:\n"
174 cmSystemTools::Error(e.str());
177 files.push_back(line);
183 static bool cmRemoveDirectory(const std::string& dir, bool recursive = true)
185 if (cmSystemTools::FileIsSymlink(dir)) {
186 if (!cmSystemTools::RemoveFile(dir)) {
187 std::cerr << "Error removing directory symlink \"" << dir << "\".\n";
190 } else if (!recursive) {
191 std::cerr << "Error removing directory \"" << dir
192 << "\" without recursive option.\n";
194 } else if (!cmSystemTools::RemoveADirectory(dir)) {
195 std::cerr << "Error removing directory \"" << dir << "\".\n";
201 static int HandleIWYU(const std::string& runCmd,
202 const std::string& /* sourceFile */,
203 const std::vector<std::string>& orig_cmd)
205 // Construct the iwyu command line by taking what was given
206 // and adding all the arguments we give to the compiler.
207 std::vector<std::string> iwyu_cmd = cmExpandedList(runCmd, true);
208 cm::append(iwyu_cmd, orig_cmd.begin() + 1, orig_cmd.end());
209 // Run the iwyu command line. Capture its stderr and hide its stdout.
210 // Ignore its return code because the tool always returns non-zero.
213 if (!cmSystemTools::RunSingleCommand(iwyu_cmd, nullptr, &stdErr, &ret,
214 nullptr, cmSystemTools::OUTPUT_NONE)) {
215 std::cerr << "Error running '" << iwyu_cmd[0] << "': " << stdErr << "\n";
218 // Warn if iwyu reported anything.
219 if (stdErr.find("should remove these lines:") != std::string::npos ||
220 stdErr.find("should add these lines:") != std::string::npos) {
221 std::cerr << "Warning: include-what-you-use reported diagnostics:\n"
224 // always return 0 we don't want to break the compile
228 static int HandleTidy(const std::string& runCmd, const std::string& sourceFile,
229 const std::vector<std::string>& orig_cmd)
231 // Construct the clang-tidy command line by taking what was given
232 // and adding our compiler command line. The clang-tidy tool will
233 // automatically skip over the compiler itself and extract the
236 std::vector<std::string> tidy_cmd = cmExpandedList(runCmd, true);
237 tidy_cmd.push_back(sourceFile);
238 tidy_cmd.emplace_back("--");
239 cm::append(tidy_cmd, orig_cmd);
241 // Run the tidy command line. Capture its stdout and hide its stderr.
244 if (!cmSystemTools::RunSingleCommand(tidy_cmd, &stdOut, &stdErr, &ret,
245 nullptr, cmSystemTools::OUTPUT_NONE)) {
246 std::cerr << "Error running '" << tidy_cmd[0] << "': " << stdErr << "\n";
249 // Output the stdout from clang-tidy to stderr
251 // If clang-tidy exited with an error do the same.
258 static int HandleLWYU(const std::string& runCmd,
259 const std::string& /* sourceFile */,
260 const std::vector<std::string>&)
262 // Construct the ldd -r -u (link what you use lwyu) command line
263 // ldd -u -r lwuy target
264 std::vector<std::string> lwyu_cmd;
265 lwyu_cmd.emplace_back("ldd");
266 lwyu_cmd.emplace_back("-u");
267 lwyu_cmd.emplace_back("-r");
268 lwyu_cmd.push_back(runCmd);
270 // Run the ldd -u -r command line.
271 // Capture its stdout and hide its stderr.
272 // Ignore its return code because the tool always returns non-zero
273 // if there are any warnings, but we just want to warn.
277 if (!cmSystemTools::RunSingleCommand(lwyu_cmd, &stdOut, &stdErr, &ret,
278 nullptr, cmSystemTools::OUTPUT_NONE)) {
279 std::cerr << "Error running '" << lwyu_cmd[0] << "': " << stdErr << "\n";
283 // Output the stdout from ldd -r -u to stderr
284 // Warn if lwyu reported anything.
285 if (stdOut.find("Unused direct dependencies:") != std::string::npos) {
286 std::cerr << "Warning: " << stdOut;
291 static int HandleCppLint(const std::string& runCmd,
292 const std::string& sourceFile,
293 const std::vector<std::string>&)
295 // Construct the cpplint command line.
296 std::vector<std::string> cpplint_cmd = cmExpandedList(runCmd, true);
297 cpplint_cmd.push_back(sourceFile);
299 // Run the cpplint command line. Capture its output.
302 if (!cmSystemTools::RunSingleCommand(cpplint_cmd, &stdOut, &stdOut, &ret,
303 nullptr, cmSystemTools::OUTPUT_NONE)) {
304 std::cerr << "Error running '" << cpplint_cmd[0] << "': " << stdOut
308 if (!stdOut.empty()) {
309 std::cerr << "Warning: cpplint diagnostics:\n";
310 // Output the output from cpplint to stderr
314 // always return 0 so the build can continue as cpplint returns non-zero
319 static int HandleCppCheck(const std::string& runCmd,
320 const std::string& sourceFile,
321 const std::vector<std::string>& orig_cmd)
323 // Construct the cpplint command line.
324 std::vector<std::string> cppcheck_cmd = cmExpandedList(runCmd, true);
325 // extract all the -D, -U, and -I options from the compile line
326 for (auto const& opt : orig_cmd) {
327 if (opt.size() > 2) {
328 if ((opt[0] == '-') &&
329 ((opt[1] == 'D') || (opt[1] == 'I') || (opt[1] == 'U'))) {
330 cppcheck_cmd.push_back(opt);
331 // convert cl / options to - options if needed
333 } else if ((opt[0] == '/') &&
334 ((opt[1] == 'D') || (opt[1] == 'I') || (opt[1] == 'U'))) {
335 std::string optcopy = opt;
337 cppcheck_cmd.push_back(optcopy);
342 // add the source file
343 cppcheck_cmd.push_back(sourceFile);
345 // Run the cpplint command line. Capture its output.
349 if (!cmSystemTools::RunSingleCommand(cppcheck_cmd, &stdOut, &stdErr, &ret,
350 nullptr, cmSystemTools::OUTPUT_NONE)) {
351 std::cerr << "Error running '" << cppcheck_cmd[0] << "': " << stdOut
356 // Output the output from cpplint to stderr
357 if (stdErr.find("(error)") != std::string::npos ||
358 stdErr.find("(warning)") != std::string::npos ||
359 stdErr.find("(style)") != std::string::npos ||
360 stdErr.find("(performance)") != std::string::npos ||
361 stdErr.find("(portability)") != std::string::npos ||
362 stdErr.find("(information)") != std::string::npos) {
364 std::cerr << "Warning: cppcheck reported diagnostics:\n";
366 std::cerr << "Error: cppcheck reported failure:\n";
374 using CoCompileHandler = int (*)(const std::string&, const std::string&,
375 const std::vector<std::string>&);
380 CoCompileHandler Handler;
381 bool NoOriginalCommand;
384 static const std::array<CoCompiler, 5> CoCompilers = {
385 { // Table of options and handlers.
386 { "--cppcheck=", HandleCppCheck, false },
387 { "--cpplint=", HandleCppLint, false },
388 { "--iwyu=", HandleIWYU, false },
389 { "--lwyu=", HandleLWYU, true },
390 { "--tidy=", HandleTidy, false } }
396 CoCompileHandler Handler;
399 // called when args[0] == "__run_co_compile"
400 int cmcmd::HandleCoCompileCommands(std::vector<std::string> const& args)
402 std::vector<CoCompileJob> jobs;
403 std::string sourceFile; // store --source=
404 std::vector<std::string> launchers; // store --launcher=
406 // Default is to run the original command found after -- if the option
407 // does not need to do that, it should be specified here, currently only
409 bool runOriginalCmd = true;
411 std::vector<std::string> orig_cmd;
412 bool doing_options = true;
413 for (std::string const& arg : cmMakeRange(args).advance(2)) {
414 // if the arg is -- then the rest of the args after
417 doing_options = false;
418 } else if (doing_options) {
419 bool optionFound = false;
420 for (CoCompiler const& cc : CoCompilers) {
421 size_t optionLen = strlen(cc.Option);
422 if (arg.compare(0, optionLen, cc.Option) == 0) {
425 job.Command = arg.substr(optionLen);
426 job.Handler = cc.Handler;
427 jobs.push_back(std::move(job));
428 if (cc.NoOriginalCommand) {
429 runOriginalCmd = false;
434 if (cmHasLiteralPrefix(arg, "--source=")) {
435 sourceFile = arg.substr(9);
436 } else if (cmHasLiteralPrefix(arg, "--launcher=")) {
437 cmExpandList(arg.substr(11), launchers, true);
439 // if it was not a co-compiler or --source/--launcher then error
440 std::cerr << "__run_co_compile given unknown argument: " << arg
445 } else { // if not doing_options then push to orig_cmd
446 orig_cmd.push_back(arg);
450 std::cerr << "__run_co_compile missing command to run. "
451 "Looking for one or more of the following:\n";
452 for (CoCompiler const& cc : CoCompilers) {
453 std::cerr << cc.Option << "\n";
458 if (runOriginalCmd && orig_cmd.empty()) {
459 std::cerr << "__run_co_compile missing compile command after --\n";
463 for (CoCompileJob const& job : jobs) {
464 // call the command handler here
465 int ret = job.Handler(job.Command, sourceFile, orig_cmd);
467 // if the command returns non-zero then return and fail.
468 // for commands that do not want to break the build, they should return
475 // if there is no original command to run return now
476 if (!runOriginalCmd) {
480 // Prepend launcher argument(s), if any
481 if (!launchers.empty()) {
482 orig_cmd.insert(orig_cmd.begin(), launchers.begin(), launchers.end());
485 // Now run the real compiler command and return its result value
487 if (!cmSystemTools::RunSingleCommand(orig_cmd, nullptr, nullptr, &ret,
489 cmSystemTools::OUTPUT_PASSTHROUGH)) {
490 std::cerr << "Error running '" << orig_cmd[0] << "'\n";
493 // return the return value from the original compiler command
497 int cmcmd::ExecuteCMakeCommand(std::vector<std::string> const& args)
499 // IF YOU ADD A NEW COMMAND, DOCUMENT IT ABOVE and in cmakemain.cxx
500 if (args.size() > 1) {
502 if (args[1] == "copy" && args.size() > 3) {
503 // If multiple source files specified,
504 // then destination must be directory
505 if ((args.size() > 4) &&
506 (!cmSystemTools::FileIsDirectory(args.back()))) {
507 std::cerr << "Error: Target (for copy command) \"" << args.back()
508 << "\" is not a directory.\n";
511 // If error occurs we want to continue copying next files.
512 bool return_value = false;
513 for (auto const& arg : cmMakeRange(args).advance(2).retreat(1)) {
514 if (!cmsys::SystemTools::CopyFileAlways(arg, args.back())) {
515 std::cerr << "Error copying file \"" << arg << "\" to \""
516 << args.back() << "\".\n";
523 // Copy file if different.
524 if (args[1] == "copy_if_different" && args.size() > 3) {
525 // If multiple source files specified,
526 // then destination must be directory
527 if ((args.size() > 4) &&
528 (!cmSystemTools::FileIsDirectory(args.back()))) {
529 std::cerr << "Error: Target (for copy_if_different command) \""
530 << args.back() << "\" is not a directory.\n";
533 // If error occurs we want to continue copying next files.
534 bool return_value = false;
535 for (auto const& arg : cmMakeRange(args).advance(2).retreat(1)) {
536 if (!cmSystemTools::CopyFileIfDifferent(arg, args.back())) {
537 std::cerr << "Error copying file (if different) from \"" << arg
538 << "\" to \"" << args.back() << "\".\n";
545 // Copy directory content
546 if (args[1] == "copy_directory" && args.size() > 3) {
547 // If error occurs we want to continue copying next files.
548 bool return_value = false;
549 for (auto const& arg : cmMakeRange(args).advance(2).retreat(1)) {
550 if (!cmSystemTools::CopyADirectory(arg, args.back())) {
551 std::cerr << "Error copying directory from \"" << arg << "\" to \""
552 << args.back() << "\".\n";
559 // Rename a file or directory
560 if (args[1] == "rename" && args.size() == 4) {
561 if (!cmSystemTools::RenameFile(args[2], args[3])) {
562 std::string e = cmSystemTools::GetLastSystemError();
563 std::cerr << "Error renaming from \"" << args[2] << "\" to \""
564 << args[3] << "\": " << e << "\n";
571 if (args[1] == "compare_files" && (args.size() == 4 || args.size() == 5)) {
573 if (args.size() == 4) {
574 filesDiffer = cmSystemTools::FilesDiffer(args[2], args[3]);
575 } else if (args[2] == "--ignore-eol") {
576 filesDiffer = cmsys::SystemTools::TextFilesDiffer(args[3], args[4]);
578 ::CMakeCommandUsage(args[0].c_str());
583 std::cerr << "Files \"" << args[args.size() - 2] << "\" to \""
584 << args[args.size() - 1] << "\" are different.\n";
590 #if !defined(CMAKE_BOOTSTRAP)
591 if (args[1] == "__create_def") {
592 if (args.size() < 4) {
593 std::cerr << "__create_def Usage: -E __create_def outfile.def "
594 "objlistfile [--nm=nm-path]\n";
597 cmsys::ifstream fin(args[3].c_str(), std::ios::in | std::ios::binary);
599 std::cerr << "could not open object list file: " << args[3].c_str()
603 std::vector<std::string> files;
607 bool outValid = outTime.Load(args[2]);
608 while (cmSystemTools::GetLineFromStream(fin, file)) {
609 files.push_back(file);
612 outValid = inTime.Load(file) && inTime.Older(outTime);
616 // The def file already exists and all input files are older than the
617 // existing def file.
621 FILE* fout = cmsys::SystemTools::Fopen(args[2], "w+");
623 std::cerr << "could not open output .def file: " << args[2].c_str()
628 if (args.size() >= 5) {
630 if (cmHasLiteralPrefix(a, "--nm=")) {
631 deffile.SetNmPath(a.substr(5));
632 std::cerr << a.substr(5) << "\n";
634 std::cerr << "unknown argument: " << a << "\n";
637 for (auto const& file : files) {
638 std::string const& ext = cmSystemTools::GetFilenameLastExtension(file);
639 if (cmSystemTools::LowerCase(ext) == ".def") {
640 if (!deffile.AddDefinitionFile(file.c_str())) {
644 if (!deffile.AddObjectFile(file.c_str())) {
649 deffile.WriteFile(fout);
654 if (args[1] == "__run_co_compile") {
655 return cmcmd::HandleCoCompileCommands(args);
659 if (args[1] == "echo") {
660 std::cout << cmJoin(cmMakeRange(args).advance(2), " ") << std::endl;
664 // Echo string no new line
665 if (args[1] == "echo_append") {
666 std::cout << cmJoin(cmMakeRange(args).advance(2), " ");
670 if (args[1] == "env") {
671 auto ai = args.cbegin() + 2;
672 auto ae = args.cend();
673 for (; ai != ae; ++ai) {
674 std::string const& a = *ai;
675 if (cmHasLiteralPrefix(a, "--unset=")) {
676 // Unset environment variable.
677 cmSystemTools::UnPutEnv(a.substr(8));
678 } else if (!a.empty() && a[0] == '-') {
679 // Environment variable and command names cannot start in '-',
680 // so this must be an unknown option.
681 std::cerr << "cmake -E env: unknown option '" << a << "'"
684 } else if (a.find('=') != std::string::npos) {
685 // Set environment variable.
686 cmSystemTools::PutEnv(a);
688 // This is the beginning of the command.
694 std::cerr << "cmake -E env: no command given" << std::endl;
698 // Execute command from remaining arguments.
699 std::vector<std::string> cmd(ai, ae);
701 if (cmSystemTools::RunSingleCommand(cmd, nullptr, nullptr, &retval,
703 cmSystemTools::OUTPUT_PASSTHROUGH)) {
709 #if !defined(CMAKE_BOOTSTRAP)
710 if (args[1] == "environment") {
711 for (auto const& env : cmSystemTools::GetEnvironmentVariables()) {
712 std::cout << env << std::endl;
718 if (args[1] == "make_directory" && args.size() > 2) {
719 // If an error occurs, we want to continue making directories.
720 bool return_value = false;
721 for (auto const& arg : cmMakeRange(args).advance(2)) {
722 if (!cmSystemTools::MakeDirectory(arg)) {
723 std::cerr << "Error creating directory \"" << arg << "\".\n";
730 if (args[1] == "remove_directory" && args.size() > 2) {
731 // If an error occurs, we want to continue removing directories.
732 bool return_value = false;
733 for (auto const& arg : cmMakeRange(args).advance(2)) {
734 if (cmSystemTools::FileIsDirectory(arg)) {
735 if (!cmRemoveDirectory(arg)) {
744 if (args[1] == "remove" && args.size() > 2) {
746 for (auto const& arg : cmMakeRange(args).advance(2)) {
747 if (arg == "\\-f" || arg == "-f") {
750 // Complain if the file could not be removed, still exists,
751 // and the -f option was not given.
752 if (!cmSystemTools::RemoveFile(arg) && !force &&
753 cmSystemTools::FileExists(arg)) {
761 // Remove directories or files with rm
762 if (args[1] == "rm" && args.size() > 2) {
763 // If an error occurs, we want to continue removing the remaining
764 // files/directories.
765 int return_value = 0;
767 bool recursive = false;
768 bool doing_options = true;
769 bool at_least_one_file = false;
770 for (auto const& arg : cmMakeRange(args).advance(2)) {
771 if (doing_options && cmHasLiteralPrefix(arg, "-")) {
773 doing_options = false;
775 if (arg.find('f') != std::string::npos) {
778 if (arg.find_first_of("rR") != std::string::npos) {
781 if (arg.find_first_not_of("-frR") != std::string::npos) {
782 cmSystemTools::Error("Unknown -E rm argument: " + arg);
789 at_least_one_file = true;
790 // Complain if the -f option was not given and
791 // either file does not exist or
792 // file could not be removed and still exists
793 bool file_exists_or_forced_remove = cmSystemTools::FileExists(arg) ||
794 cmSystemTools::FileIsSymlink(arg) || force;
795 if (cmSystemTools::FileIsDirectory(arg)) {
796 if (!cmRemoveDirectory(arg, recursive)) {
799 } else if ((!file_exists_or_forced_remove) ||
800 (!cmSystemTools::RemoveFile(arg) &&
801 cmSystemTools::FileExists(arg))) {
802 if (!file_exists_or_forced_remove) {
803 cmSystemTools::Error(
804 "File to remove does not exist and force is not set: " + arg);
806 cmSystemTools::Error("File can't be removed and still exist: " +
813 if (!at_least_one_file) {
814 cmSystemTools::Error("Missing file/directory to remove");
821 if (args[1] == "touch" && args.size() > 2) {
822 for (auto const& arg : cmMakeRange(args).advance(2)) {
823 if (!cmSystemTools::Touch(arg, true)) {
824 std::cerr << "cmake -E touch: failed to update \"";
825 std::cerr << arg << "\".\n";
833 if (args[1] == "touch_nocreate" && args.size() > 2) {
834 for (auto const& arg : cmMakeRange(args).advance(2)) {
835 if (!cmSystemTools::Touch(arg, false)) {
836 std::cerr << "cmake -E touch_nocreate: failed to update \"";
837 std::cerr << arg << "\".\n";
845 if (args[1] == "capabilities") {
846 if (args.size() > 2) {
847 std::cerr << "-E capabilities accepts no additional arguments\n";
850 cmake cm(cmake::RoleInternal, cmState::Unknown);
851 std::cout << cm.ReportCapabilities();
856 if (args[1] == "sleep" && args.size() > 2) {
858 for (auto const& arg : cmMakeRange(args).advance(2)) {
862 int n = sscanf(arg.c_str(), "%lg%c%c", &num, &unit, &extra);
863 if ((n == 1 || (n == 2 && unit == 's')) && num >= 0) {
866 std::cerr << "Unknown sleep time format \"" << arg << "\".\n";
871 cmSystemTools::Delay(static_cast<unsigned int>(total * 1000));
877 if (args[1] == "time" && args.size() > 2) {
878 std::vector<std::string> command(args.begin() + 2, args.end());
881 clock_t clock_finish;
886 clock_start = clock();
888 cmSystemTools::RunSingleCommand(command, nullptr, nullptr, &ret);
890 clock_finish = clock();
893 double clocks_per_sec = static_cast<double>(CLOCKS_PER_SEC);
894 std::cout << "Elapsed time: "
895 << static_cast<long>(time_finish - time_start) << " s. (time)"
897 << static_cast<double>(clock_finish - clock_start) /
904 // Command to calculate the md5sum of a file
905 if (args[1] == "md5sum" && args.size() >= 3) {
906 return HashSumFile(args, cmCryptoHash::AlgoMD5);
909 // Command to calculate the sha1sum of a file
910 if (args[1] == "sha1sum" && args.size() >= 3) {
911 return HashSumFile(args, cmCryptoHash::AlgoSHA1);
914 if (args[1] == "sha224sum" && args.size() >= 3) {
915 return HashSumFile(args, cmCryptoHash::AlgoSHA224);
918 if (args[1] == "sha256sum" && args.size() >= 3) {
919 return HashSumFile(args, cmCryptoHash::AlgoSHA256);
922 if (args[1] == "sha384sum" && args.size() >= 3) {
923 return HashSumFile(args, cmCryptoHash::AlgoSHA384);
926 if (args[1] == "sha512sum" && args.size() >= 3) {
927 return HashSumFile(args, cmCryptoHash::AlgoSHA512);
930 // Command to change directory and run a program.
931 if (args[1] == "chdir" && args.size() >= 4) {
932 std::string const& directory = args[2];
933 if (!cmSystemTools::FileExists(directory)) {
934 cmSystemTools::Error("Directory does not exist for chdir command: " +
939 std::string command =
940 cmWrap('"', cmMakeRange(args).advance(3), '"', " ");
942 if (cmSystemTools::RunSingleCommand(
943 command, nullptr, nullptr, &retval, directory.c_str(),
944 cmSystemTools::OUTPUT_PASSTHROUGH, cmDuration::zero())) {
951 // Command to start progress for a build
952 if (args[1] == "cmake_progress_start" && args.size() == 4) {
953 // basically remove the directory
954 std::string dirName = cmStrCat(args[2], "/Progress");
955 cmSystemTools::RemoveADirectory(dirName);
957 // is the last argument a filename that exists?
958 FILE* countFile = cmsys::SystemTools::Fopen(args[3], "r");
961 if (1 != fscanf(countFile, "%i", &count)) {
962 cmSystemTools::Message("Could not read from count file.");
966 count = atoi(args[3].c_str());
969 cmSystemTools::MakeDirectory(dirName);
970 // write the count into the directory
971 std::string fName = cmStrCat(dirName, "/count.txt");
972 FILE* progFile = cmsys::SystemTools::Fopen(fName, "w");
974 fprintf(progFile, "%i\n", count);
981 // Command to report progress for a build
982 if (args[1] == "cmake_progress_report" && args.size() >= 3) {
983 // This has been superseded by cmake_echo_color --progress-*
984 // options. We leave it here to avoid errors if somehow this
985 // is invoked by an existing makefile without regenerating.
989 // Command to create a symbolic link. Fails on platforms not
991 if (args[1] == "create_symlink" && args.size() == 4) {
992 const char* destinationFileName = args[3].c_str();
993 if ((cmSystemTools::FileExists(destinationFileName) ||
994 cmSystemTools::FileIsSymlink(destinationFileName)) &&
995 !cmSystemTools::RemoveFile(destinationFileName)) {
996 std::string emsg = cmSystemTools::GetLastSystemError();
997 std::cerr << "failed to create symbolic link '" << destinationFileName
998 << "' because existing path cannot be removed: " << emsg
1002 if (!cmSystemTools::CreateSymlink(args[2], args[3])) {
1008 // Command to do nothing with an exit code of 0.
1009 if (args[1] == "true") {
1013 // Command to do nothing with an exit code of 1.
1014 if (args[1] == "false") {
1018 // Internal CMake shared library support.
1019 if (args[1] == "cmake_symlink_library" && args.size() == 5) {
1020 return cmcmd::SymlinkLibrary(args);
1023 // Internal CMake versioned executable support.
1024 if (args[1] == "cmake_symlink_executable" && args.size() == 4) {
1025 return cmcmd::SymlinkExecutable(args);
1028 // Internal CMake dependency scanning support.
1029 if (args[1] == "cmake_depends" && args.size() >= 6) {
1030 const bool verbose = isCMakeVerbose();
1032 // Create a cmake object instance to process dependencies.
1033 // All we need is the `set` command.
1034 cmake cm(cmake::RoleScript, cmState::Unknown);
1036 std::string homeDir;
1037 std::string startDir;
1038 std::string homeOutDir;
1039 std::string startOutDir;
1040 std::string depInfo;
1042 if (args.size() >= 8) {
1045 // -E cmake_depends <generator>
1046 // <home-src-dir> <start-src-dir>
1047 // <home-out-dir> <start-out-dir>
1048 // <dep-info> [--color=$(COLOR)]
1050 // All paths are provided.
1054 homeOutDir = args[5];
1055 startOutDir = args[6];
1057 if (args.size() >= 9 && args[8].length() >= 8 &&
1058 args[8].substr(0, 8) == "--color=") {
1059 // Enable or disable color based on the switch value.
1060 color = (args[8].size() == 8 || cmIsOn(args[8].substr(8)));
1063 // Support older signature for existing makefiles:
1065 // -E cmake_depends <generator>
1066 // <home-out-dir> <start-out-dir>
1069 // Just pretend the source directories are the same as the
1070 // binary directories so at least scanning will work.
1074 homeOutDir = args[3];
1075 startOutDir = args[3];
1079 // Create a local generator configured for the directory in
1080 // which dependencies will be scanned.
1081 homeDir = cmSystemTools::CollapseFullPath(homeDir);
1082 startDir = cmSystemTools::CollapseFullPath(startDir);
1083 homeOutDir = cmSystemTools::CollapseFullPath(homeOutDir);
1084 startOutDir = cmSystemTools::CollapseFullPath(startOutDir);
1085 cm.SetHomeDirectory(homeDir);
1086 cm.SetHomeOutputDirectory(homeOutDir);
1087 cm.GetCurrentSnapshot().SetDefaultDefinitions();
1088 if (auto ggd = cm.CreateGlobalGenerator(gen)) {
1089 cm.SetGlobalGenerator(std::move(ggd));
1090 cmStateSnapshot snapshot = cm.GetCurrentSnapshot();
1091 snapshot.GetDirectory().SetCurrentBinary(startOutDir);
1092 snapshot.GetDirectory().SetCurrentSource(startDir);
1093 cmMakefile mf(cm.GetGlobalGenerator(), snapshot);
1094 auto lgd = cm.GetGlobalGenerator()->CreateLocalGenerator(&mf);
1096 // Actually scan dependencies.
1097 return lgd->UpdateDependencies(depInfo, verbose, color) ? 0 : 2;
1102 // Internal CMake link script support.
1103 if (args[1] == "cmake_link_script" && args.size() >= 3) {
1104 return cmcmd::ExecuteLinkScript(args);
1107 #ifndef CMAKE_BOOTSTRAP
1108 // Internal CMake ninja dependency scanning support.
1109 if (args[1] == "cmake_ninja_depends") {
1110 return cmcmd_cmake_ninja_depends(args.begin() + 2, args.end());
1113 // Internal CMake ninja dyndep support.
1114 if (args[1] == "cmake_ninja_dyndep") {
1115 return cmcmd_cmake_ninja_dyndep(args.begin() + 2, args.end());
1119 // Internal CMake unimplemented feature notification.
1120 if (args[1] == "cmake_unimplemented_variable") {
1121 std::cerr << "Feature not implemented for this platform.";
1122 if (args.size() == 3) {
1123 std::cerr << " Variable " << args[2] << " is not set.";
1125 std::cerr << std::endl;
1129 if (args[1] == "vs_link_exe") {
1130 return cmcmd::VisualStudioLink(args, 1);
1133 if (args[1] == "vs_link_dll") {
1134 return cmcmd::VisualStudioLink(args, 2);
1137 if (args[1] == "cmake_llvm_rc") {
1138 return cmcmd::RunLLVMRC(args);
1141 // Internal CMake color makefile support.
1142 if (args[1] == "cmake_echo_color") {
1143 return cmcmd::ExecuteEchoColor(args);
1146 #ifndef CMAKE_BOOTSTRAP
1147 if ((args[1] == "cmake_autogen") && (args.size() >= 4)) {
1148 cm::string_view const infoFile = args[2];
1149 cm::string_view const config = args[3];
1150 return cmQtAutoMocUic(infoFile, config) ? 0 : 1;
1152 if ((args[1] == "cmake_autorcc") && (args.size() >= 3)) {
1153 cm::string_view const infoFile = args[2];
1154 cm::string_view const config =
1155 (args.size() > 3) ? cm::string_view(args[3]) : cm::string_view();
1156 return cmQtAutoRcc(infoFile, config) ? 0 : 1;
1161 if (args[1] == "tar" && args.size() > 3) {
1162 const char* knownFormats[] = { "7zip", "gnutar", "pax", "paxr", "zip" };
1164 std::string const& flags = args[2];
1165 std::string const& outFile = args[3];
1166 std::vector<std::string> files;
1169 cmSystemTools::cmTarCompression compress =
1170 cmSystemTools::TarCompressNone;
1172 bool doing_options = true;
1173 for (auto const& arg : cmMakeRange(args).advance(4)) {
1174 if (doing_options && cmHasLiteralPrefix(arg, "--")) {
1176 doing_options = false;
1177 } else if (arg == "--zstd") {
1178 compress = cmSystemTools::TarCompressZstd;
1180 } else if (cmHasLiteralPrefix(arg, "--mtime=")) {
1181 mtime = arg.substr(8);
1182 } else if (cmHasLiteralPrefix(arg, "--files-from=")) {
1183 std::string const& files_from = arg.substr(13);
1184 if (!cmTarFilesFrom(files_from, files)) {
1187 } else if (cmHasLiteralPrefix(arg, "--format=")) {
1188 format = arg.substr(9);
1189 if (!cmContains(knownFormats, format)) {
1190 cmSystemTools::Error("Unknown -E tar --format= argument: " +
1195 cmSystemTools::Error("Unknown option to -E tar: " + arg);
1199 files.push_back(arg);
1202 cmSystemTools::cmTarAction action = cmSystemTools::TarActionNone;
1203 bool verbose = false;
1205 for (auto flag : flags) {
1209 // Keep for backward compatibility. Ignored
1212 compress = cmSystemTools::TarCompressBZip2;
1216 compress = cmSystemTools::TarCompressXZ;
1220 compress = cmSystemTools::TarCompressGZip;
1227 action = cmSystemTools::TarActionList;
1230 action = cmSystemTools::TarActionCreate;
1233 action = cmSystemTools::TarActionExtract;
1236 cmSystemTools::Message(
1237 std::string("tar: Unknown argument: ") + flag, "Warning");
1241 if ((format == "7zip" || format == "zip") && nCompress > 0) {
1242 cmSystemTools::Error("Can not use compression flags with format: " +
1246 if (nCompress > 1) {
1247 cmSystemTools::Error("Can only compress a tar file one way; "
1248 "at most one flag of z, j, or J may be used");
1251 if (action == cmSystemTools::TarActionList) {
1252 if (!cmSystemTools::ListTar(outFile, files, verbose)) {
1253 cmSystemTools::Error("Problem listing tar: " + outFile);
1256 } else if (action == cmSystemTools::TarActionCreate) {
1257 if (files.empty()) {
1258 cmSystemTools::Message("tar: No files or directories specified",
1261 if (!cmSystemTools::CreateTar(outFile, files, compress, verbose, mtime,
1263 cmSystemTools::Error("Problem creating tar: " + outFile);
1266 } else if (action == cmSystemTools::TarActionExtract) {
1267 if (!cmSystemTools::ExtractTar(outFile, files, verbose)) {
1268 cmSystemTools::Error("Problem extracting tar: " + outFile);
1272 // OK, on windows 7 after we untar some files,
1273 // sometimes we can not rename the directory after
1274 // the untar is done. This breaks the external project
1275 // untar and rename code. So, by default we will wait
1276 // 1/10th of a second after the untar. If CMAKE_UNTAR_DELAY
1277 // is set in the env, its value will be used instead of 100.
1279 std::string delayVar;
1280 if (cmSystemTools::GetEnv("CMAKE_UNTAR_DELAY", delayVar)) {
1281 delay = atoi(delayVar.c_str());
1284 cmSystemTools::Delay(delay);
1288 cmSystemTools::Error("tar: No action specified. Please choose: 't' "
1289 "(list), 'c' (create) or 'x' (extract)");
1295 if (args[1] == "server") {
1296 const std::string pipePrefix = "--pipe=";
1297 bool supportExperimental = false;
1298 bool isDebug = false;
1301 for (auto const& arg : cmMakeRange(args).advance(2)) {
1302 if (arg == "--experimental") {
1303 supportExperimental = true;
1304 } else if (arg == "--debug") {
1307 } else if (arg.substr(0, pipePrefix.size()) == pipePrefix) {
1309 pipe = arg.substr(pipePrefix.size());
1311 cmSystemTools::Error("No pipe given after --pipe=");
1315 cmSystemTools::Error("Unknown argument for server mode");
1319 #if !defined(CMAKE_BOOTSTRAP)
1322 conn = new cmServerStdIoConnection;
1324 conn = new cmServerPipeConnection(pipe);
1326 cmServer server(conn, supportExperimental);
1327 std::string errorMessage;
1328 if (server.Serve(&errorMessage)) {
1331 cmSystemTools::Error(errorMessage);
1333 static_cast<void>(supportExperimental);
1334 static_cast<void>(isDebug);
1335 cmSystemTools::Error("CMake was not built with server mode enabled");
1340 #if !defined(CMAKE_BOOTSTRAP)
1341 // Internal CMake Fortran module support.
1342 if (args[1] == "cmake_copy_f90_mod" && args.size() >= 4) {
1343 return cmDependsFortran::CopyModule(args) ? 0 : 1;
1347 #if defined(_WIN32) && !defined(__CYGWIN__)
1348 // Write registry value
1349 if (args[1] == "write_regv" && args.size() > 3) {
1350 return cmSystemTools::WriteRegistryValue(args[2].c_str(),
1356 // Delete registry value
1357 if (args[1] == "delete_regv" && args.size() > 2) {
1358 return cmSystemTools::DeleteRegistryValue(args[2].c_str()) ? 0 : 1;
1362 if (args[1] == "comspec" && args.size() > 2) {
1363 std::cerr << "Win9x helper \"cmake -E comspec\" no longer supported\n";
1367 if (args[1] == "env_vs8_wince" && args.size() == 3) {
1368 return cmcmd::WindowsCEEnvironment("8.0", args[2]);
1371 if (args[1] == "env_vs9_wince" && args.size() == 3) {
1372 return cmcmd::WindowsCEEnvironment("9.0", args[2]);
1377 ::CMakeCommandUsage(args[0].c_str());
1381 int cmcmd::HashSumFile(std::vector<std::string> const& args,
1382 cmCryptoHash::Algo algo)
1384 if (args.size() < 3) {
1389 for (auto const& filename : cmMakeRange(args).advance(2)) {
1390 // Cannot compute sum of a directory
1391 if (cmSystemTools::FileIsDirectory(filename)) {
1392 std::cerr << "Error: " << filename << " is a directory" << std::endl;
1395 std::string value = cmSystemTools::ComputeFileHash(filename, algo);
1396 if (value.empty()) {
1397 // To mimic "md5sum/shasum" behavior in a shell:
1398 std::cerr << filename << ": No such file or directory" << std::endl;
1401 std::cout << value << " " << filename << std::endl;
1408 int cmcmd::SymlinkLibrary(std::vector<std::string> const& args)
1411 std::string realName = args[2];
1412 std::string soName = args[3];
1413 std::string name = args[4];
1414 cmSystemTools::ConvertToUnixSlashes(realName);
1415 cmSystemTools::ConvertToUnixSlashes(soName);
1416 cmSystemTools::ConvertToUnixSlashes(name);
1417 if (soName != realName) {
1418 if (!cmcmd::SymlinkInternal(realName, soName)) {
1419 cmSystemTools::ReportLastSystemError("cmake_symlink_library");
1423 if (name != soName) {
1424 if (!cmcmd::SymlinkInternal(soName, name)) {
1425 cmSystemTools::ReportLastSystemError("cmake_symlink_library");
1432 int cmcmd::SymlinkExecutable(std::vector<std::string> const& args)
1435 std::string const& realName = args[2];
1436 std::string const& name = args[3];
1437 if (name != realName) {
1438 if (!cmcmd::SymlinkInternal(realName, name)) {
1439 cmSystemTools::ReportLastSystemError("cmake_symlink_executable");
1446 bool cmcmd::SymlinkInternal(std::string const& file, std::string const& link)
1448 if (cmSystemTools::FileExists(link) || cmSystemTools::FileIsSymlink(link)) {
1449 cmSystemTools::RemoveFile(link);
1451 #if defined(_WIN32) && !defined(__CYGWIN__)
1452 return cmSystemTools::CopyFileAlways(file, link);
1454 std::string linktext = cmSystemTools::GetFilenameName(file);
1455 return cmSystemTools::CreateSymlink(linktext, link);
1459 static void cmcmdProgressReport(std::string const& dir, std::string const& num)
1461 std::string dirName = cmStrCat(dir, "/Progress");
1466 fName = cmStrCat(dirName, "/count.txt");
1467 progFile = cmsys::SystemTools::Fopen(fName, "r");
1472 if (1 != fscanf(progFile, "%i", &count)) {
1473 cmSystemTools::Message("Could not read from progress file.");
1477 const char* last = num.c_str();
1478 for (const char* c = last;; ++c) {
1479 if (*c == ',' || *c == '\0') {
1481 fName = cmStrCat(dirName, '/');
1482 fName.append(last, c - last);
1483 progFile = cmsys::SystemTools::Fopen(fName, "w");
1485 fprintf(progFile, "empty");
1496 static_cast<int>(cmsys::Directory::GetNumberOfFilesInDirectory(dirName));
1498 // print the progress
1499 fprintf(stdout, "[%3i%%] ", ((fileNum - 3) * 100) / count);
1503 int cmcmd::ExecuteEchoColor(std::vector<std::string> const& args)
1505 // The arguments are
1506 // args[0] == <cmake-executable>
1507 // args[1] == cmake_echo_color
1509 bool enabled = true;
1510 int color = cmsysTerminal_Color_Normal;
1511 bool newline = true;
1512 std::string progressDir;
1513 for (auto const& arg : cmMakeRange(args).advance(2)) {
1514 if (arg.find("--switch=") == 0) {
1515 // Enable or disable color based on the switch value.
1516 std::string value = arg.substr(9);
1517 if (!value.empty()) {
1518 enabled = cmIsOn(value);
1520 } else if (cmHasLiteralPrefix(arg, "--progress-dir=")) {
1521 progressDir = arg.substr(15);
1522 } else if (cmHasLiteralPrefix(arg, "--progress-num=")) {
1523 if (!progressDir.empty()) {
1524 std::string const& progressNum = arg.substr(15);
1525 cmcmdProgressReport(progressDir, progressNum);
1527 } else if (arg == "--normal") {
1528 color = cmsysTerminal_Color_Normal;
1529 } else if (arg == "--black") {
1530 color = cmsysTerminal_Color_ForegroundBlack;
1531 } else if (arg == "--red") {
1532 color = cmsysTerminal_Color_ForegroundRed;
1533 } else if (arg == "--green") {
1534 color = cmsysTerminal_Color_ForegroundGreen;
1535 } else if (arg == "--yellow") {
1536 color = cmsysTerminal_Color_ForegroundYellow;
1537 } else if (arg == "--blue") {
1538 color = cmsysTerminal_Color_ForegroundBlue;
1539 } else if (arg == "--magenta") {
1540 color = cmsysTerminal_Color_ForegroundMagenta;
1541 } else if (arg == "--cyan") {
1542 color = cmsysTerminal_Color_ForegroundCyan;
1543 } else if (arg == "--white") {
1544 color = cmsysTerminal_Color_ForegroundWhite;
1545 } else if (arg == "--bold") {
1546 color |= cmsysTerminal_Color_ForegroundBold;
1547 } else if (arg == "--no-newline") {
1549 } else if (arg == "--newline") {
1552 // Color is enabled. Print with the current color.
1553 cmSystemTools::MakefileColorEcho(color, arg.c_str(), newline, enabled);
1560 int cmcmd::ExecuteLinkScript(std::vector<std::string> const& args)
1562 // The arguments are
1563 // args[0] == <cmake-executable>
1564 // args[1] == cmake_link_script
1565 // args[2] == <link-script-name>
1566 // args[3] == --verbose=?
1567 bool verbose = false;
1568 if (args.size() >= 4) {
1569 if (args[3].find("--verbose=") == 0) {
1570 if (!cmIsOff(args[3].substr(10))) {
1576 // Allocate a process instance.
1577 cmsysProcess* cp = cmsysProcess_New();
1579 std::cerr << "Error allocating process instance in link script."
1584 // Children should share stdout and stderr with this process.
1585 cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDOUT, 1);
1586 cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDERR, 1);
1588 // Run the command lines verbatim.
1589 cmsysProcess_SetOption(cp, cmsysProcess_Option_Verbatim, 1);
1591 // Read command lines from the script.
1592 cmsys::ifstream fin(args[2].c_str());
1594 std::cerr << "Error opening link script \"" << args[2] << "\""
1599 // Run one command at a time.
1600 std::string command;
1602 while (result == 0 && cmSystemTools::GetLineFromStream(fin, command)) {
1603 // Skip empty command lines.
1604 if (command.find_first_not_of(" \t") == std::string::npos) {
1608 // Setup this command line.
1609 const char* cmd[2] = { command.c_str(), nullptr };
1610 cmsysProcess_SetCommand(cp, cmd);
1612 // Report the command if verbose output is enabled.
1614 std::cout << command << std::endl;
1617 // Run the command and wait for it to exit.
1618 cmsysProcess_Execute(cp);
1619 cmsysProcess_WaitForExit(cp, nullptr);
1621 // Report failure if any.
1622 switch (cmsysProcess_GetState(cp)) {
1623 case cmsysProcess_State_Exited: {
1624 int value = cmsysProcess_GetExitValue(cp);
1629 case cmsysProcess_State_Exception:
1630 std::cerr << "Error running link command: "
1631 << cmsysProcess_GetExceptionString(cp) << std::endl;
1634 case cmsysProcess_State_Error:
1635 std::cerr << "Error running link command: "
1636 << cmsysProcess_GetErrorString(cp) << std::endl;
1644 // Free the process instance.
1645 cmsysProcess_Delete(cp);
1647 // Return the final resulting return value.
1651 int cmcmd::WindowsCEEnvironment(const char* version, const std::string& name)
1653 #if !defined(CMAKE_BOOTSTRAP) && defined(_WIN32) && !defined(__CYGWIN__)
1654 cmVisualStudioWCEPlatformParser parser(name.c_str());
1655 parser.ParseVersion(version);
1656 if (parser.Found()) {
1657 std::cout << "@echo off" << std::endl;
1658 std::cout << "echo Environment Selection: " << name << std::endl;
1659 std::cout << "set PATH=" << parser.GetPathDirectories() << std::endl;
1660 std::cout << "set INCLUDE=" << parser.GetIncludeDirectories() << std::endl;
1661 std::cout << "set LIB=" << parser.GetLibraryDirectories() << std::endl;
1668 std::cerr << "Could not find " << name;
1672 int cmcmd::RunPreprocessor(const std::vector<std::string>& command,
1673 const std::string& intermediate_file)
1676 cmUVProcessChainBuilder builder;
1679 int preprocessedFile =
1680 uv_fs_open(nullptr, &fs_req, intermediate_file.c_str(), O_CREAT | O_RDWR,
1682 uv_fs_req_cleanup(&fs_req);
1685 .SetExternalStream(cmUVProcessChainBuilder::Stream_OUTPUT,
1687 .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR)
1688 .AddCommand(command);
1689 auto process = builder.Start();
1690 if (!process.Valid()) {
1691 std::cerr << "Failed to start preprocessor.";
1694 if (!process.Wait()) {
1695 std::cerr << "Failed to wait for preprocessor";
1698 auto status = process.GetStatus();
1699 if (!status[0] || status[0]->ExitStatus != 0) {
1700 auto errorStream = process.ErrorStream();
1702 std::cerr << errorStream->rdbuf();
1711 int cmcmd::RunLLVMRC(std::vector<std::string> const& args)
1713 // The arguments are
1714 // args[0] == <cmake-executable>
1715 // args[1] == cmake_llvm_rc
1716 // args[2] == source_file_path
1717 // args[3] == intermediate_file
1718 // args[4..n] == preprocess+args
1720 // args[n+2...] == llvm-rc+args
1721 if (args.size() < 3) {
1722 std::cerr << "Invalid cmake_llvm_rc arguments";
1725 const std::string& intermediate_file = args[3];
1726 const std::string& source_file = args[2];
1727 std::vector<std::string> preprocess;
1728 std::vector<std::string> resource_compile;
1729 std::vector<std::string>* pArgTgt = &preprocess;
1730 for (std::string const& arg : cmMakeRange(args).advance(4)) {
1732 pArgTgt = &resource_compile;
1734 if (arg.find("SOURCE_DIR") != std::string::npos) {
1735 std::string sourceDirArg = arg;
1736 cmSystemTools::ReplaceString(
1737 sourceDirArg, "SOURCE_DIR",
1738 cmSystemTools::GetFilenamePath(source_file));
1739 pArgTgt->push_back(sourceDirArg);
1741 pArgTgt->push_back(arg);
1745 if (preprocess.empty()) {
1746 std::cerr << "Empty preprocessing command";
1749 if (resource_compile.empty()) {
1750 std::cerr << "Empty resource compilation command";
1754 auto result = RunPreprocessor(preprocess, intermediate_file);
1757 cmSystemTools::RemoveFile(intermediate_file);
1760 cmUVProcessChainBuilder builder;
1762 builder.SetBuiltinStream(cmUVProcessChainBuilder::Stream_OUTPUT)
1763 .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR)
1764 .AddCommand(resource_compile);
1765 auto process = builder.Start();
1767 if (!process.Valid()) {
1768 std::cerr << "Failed to start resource compiler.";
1771 if (!process.Wait()) {
1772 std::cerr << "Failed to wait for resource compiler";
1777 cmSystemTools::RemoveFile(intermediate_file);
1781 auto status = process.GetStatus();
1782 if (!status[0] || status[0]->ExitStatus != 0) {
1783 auto errorStream = process.ErrorStream();
1785 std::cerr << errorStream->rdbuf();
1798 bool LinkGeneratesManifest;
1799 std::vector<std::string> LinkCommand;
1800 std::vector<std::string> UserManifests;
1801 std::string LinkerManifestFile;
1802 std::string ManifestFile;
1803 std::string ManifestFileRC;
1804 std::string ManifestFileRes;
1805 std::string TargetFile;
1810 cmVSLink(int type, bool verbose)
1813 , Incremental(false)
1814 , LinkGeneratesManifest(true)
1817 bool Parse(std::vector<std::string>::const_iterator argBeg,
1818 std::vector<std::string>::const_iterator argEnd);
1822 int LinkIncremental();
1823 int LinkNonIncremental();
1824 int RunMT(std::string const& out, bool notify);
1827 // For visual studio 2005 and newer manifest files need to be embedded into
1828 // exe and dll's. This code does that in such a way that incremental linking
1830 int cmcmd::VisualStudioLink(std::vector<std::string> const& args, int type)
1832 #if defined(_WIN32) && !defined(CMAKE_BOOTSTRAP)
1833 // Replace streambuf so we output in the system codepage. CMake is set up
1834 // to output in Unicode (see SetUTF8Pipes) but the Visual Studio linker
1835 // outputs using the system codepage so we need to change behavior when
1836 // we run the link command.
1837 cmsys::ConsoleBuf::Manager consoleOut(std::cout);
1838 cmsys::ConsoleBuf::Manager consoleErr(std::cerr, true);
1841 if (args.size() < 2) {
1844 const bool verbose = cmSystemTools::HasEnv("VERBOSE");
1845 std::vector<std::string> expandedArgs;
1846 for (std::string const& i : args) {
1847 // check for nmake temporary files
1848 if (i[0] == '@' && i.find("@CMakeFiles") != 0) {
1849 cmsys::ifstream fin(i.substr(1).c_str());
1851 while (cmSystemTools::GetLineFromStream(fin, line)) {
1852 cmSystemTools::ParseWindowsCommandLine(line.c_str(), expandedArgs);
1855 expandedArgs.push_back(i);
1859 cmVSLink vsLink(type, verbose);
1860 if (!vsLink.Parse(expandedArgs.begin() + 2, expandedArgs.end())) {
1863 return vsLink.Link();
1871 struct NumberFormatter
1873 NumberFormat Format;
1875 NumberFormatter(NumberFormat format, int value)
1881 std::ostream& operator<<(std::ostream& stream,
1882 NumberFormatter const& formatter)
1884 auto const& flags = stream.flags();
1885 if (formatter.Format == FORMAT_DECIMAL) {
1886 stream << std::dec << formatter.Value;
1888 stream << "0x" << std::hex << formatter.Value;
1890 stream.flags(flags);
1894 static bool RunCommand(const char* comment,
1895 std::vector<std::string> const& command, bool verbose,
1896 NumberFormat exitFormat, int* retCodeOut = nullptr,
1897 bool (*retCodeOkay)(int) = nullptr)
1900 std::cout << comment << ":\n";
1901 std::cout << cmJoin(command, " ") << "\n";
1905 bool commandResult = cmSystemTools::RunSingleCommand(
1906 command, &output, &output, &retCode, nullptr, cmSystemTools::OUTPUT_NONE);
1907 bool const retCodeSuccess =
1908 retCode == 0 || (retCodeOkay && retCodeOkay(retCode));
1909 bool const success = commandResult && retCodeSuccess;
1911 if (commandResult || !retCodeSuccess) {
1912 *retCodeOut = retCode;
1918 std::cout << comment << ": command \"" << cmJoin(command, " ")
1919 << "\" failed (exit code "
1920 << NumberFormatter(exitFormat, retCode)
1921 << ") with the following output:\n"
1924 // always print the output of the command, unless
1925 // it is the dumb rc command banner
1926 if (output.find("Resource Compiler Version") == std::string::npos) {
1927 std::cout << output;
1933 bool cmVSLink::Parse(std::vector<std::string>::const_iterator argBeg,
1934 std::vector<std::string>::const_iterator argEnd)
1936 // Parse our own arguments.
1939 while (arg != argEnd && cmHasLiteralPrefix(*arg, "-")) {
1944 if (*arg == "--manifests") {
1945 for (++arg; arg != argEnd && !cmHasLiteralPrefix(*arg, "-"); ++arg) {
1946 this->UserManifests.push_back(*arg);
1948 } else if (cmHasLiteralPrefix(*arg, "--intdir=")) {
1949 intDir = arg->substr(9);
1951 } else if (cmHasLiteralPrefix(*arg, "--rc=")) {
1952 this->RcPath = arg->substr(5);
1954 } else if (cmHasLiteralPrefix(*arg, "--mt=")) {
1955 this->MtPath = arg->substr(5);
1958 std::cerr << "unknown argument '" << *arg << "'\n";
1962 if (intDir.empty()) {
1966 // The rest of the arguments form the link command.
1967 if (arg == argEnd) {
1970 this->LinkCommand.insert(this->LinkCommand.begin(), arg, argEnd);
1972 // Parse the link command to extract information we need.
1973 for (; arg != argEnd; ++arg) {
1974 if (cmSystemTools::Strucmp(arg->c_str(), "/INCREMENTAL:YES") == 0) {
1975 this->Incremental = true;
1976 } else if (cmSystemTools::Strucmp(arg->c_str(), "/INCREMENTAL") == 0) {
1977 this->Incremental = true;
1978 } else if (cmSystemTools::Strucmp(arg->c_str(), "/MANIFEST:NO") == 0) {
1979 this->LinkGeneratesManifest = false;
1980 } else if (cmHasLiteralPrefix(*arg, "/Fe")) {
1981 this->TargetFile = arg->substr(3);
1982 } else if (cmHasLiteralPrefix(*arg, "/out:")) {
1983 this->TargetFile = arg->substr(5);
1987 if (this->TargetFile.empty()) {
1991 this->ManifestFile = intDir + "/embed.manifest";
1992 this->LinkerManifestFile = intDir + "/intermediate.manifest";
1994 if (this->Incremental) {
1995 // We will compile a resource containing the manifest and
1996 // pass it to the link command.
1997 this->ManifestFileRC = intDir + "/manifest.rc";
1998 this->ManifestFileRes = intDir + "/manifest.res";
1999 } else if (this->UserManifests.empty()) {
2000 // Prior to support for user-specified manifests CMake placed the
2001 // linker-generated manifest next to the binary (as if it were not to be
2002 // embedded) when not linking incrementally. Preserve this behavior.
2003 this->ManifestFile = this->TargetFile + ".manifest";
2004 this->LinkerManifestFile = this->ManifestFile;
2007 if (this->LinkGeneratesManifest) {
2008 this->LinkCommand.emplace_back("/MANIFEST");
2009 this->LinkCommand.push_back("/MANIFESTFILE:" + this->LinkerManifestFile);
2015 int cmVSLink::Link()
2017 if (this->Incremental &&
2018 (this->LinkGeneratesManifest || !this->UserManifests.empty())) {
2019 if (this->Verbose) {
2020 std::cout << "Visual Studio Incremental Link with embedded manifests\n";
2022 return LinkIncremental();
2024 if (this->Verbose) {
2025 if (!this->Incremental) {
2026 std::cout << "Visual Studio Non-Incremental Link\n";
2028 std::cout << "Visual Studio Incremental Link without manifests\n";
2031 return LinkNonIncremental();
2034 static bool mtRetIsUpdate(int mtRet)
2036 // 'mt /notify_update' returns a special value (differing between
2037 // Windows and POSIX hosts) when it updated the manifest file.
2038 return mtRet == 0x41020001 || mtRet == 0xbb;
2041 int cmVSLink::LinkIncremental()
2043 // This follows the steps listed here:
2044 // http://blogs.msdn.com/zakramer/archive/2006/05/22/603558.aspx
2046 // 1. Compiler compiles the application and generates the *.obj files.
2047 // 2. An empty manifest file is generated if this is a clean build and if
2048 // not the previous one is reused.
2049 // 3. The resource compiler (rc.exe) compiles the *.manifest file to a
2051 // 4. Linker generates the binary (EXE or DLL) with the /incremental
2052 // switch and embeds the dummy manifest file. The linker also generates
2053 // the real manifest file based on the binaries that your binary depends
2055 // 5. The manifest tool (mt.exe) is then used to generate the final
2058 // If the final manifest is changed, then 6 and 7 are run, if not
2059 // they are skipped, and it is done.
2061 // 6. The resource compiler is invoked one more time.
2062 // 7. Finally, the Linker does another incremental link, but since the
2063 // only thing that has changed is the *.res file that contains the
2064 // manifest it is a short link.
2066 // Create a resource file referencing the manifest.
2067 std::string absManifestFile =
2068 cmSystemTools::CollapseFullPath(this->ManifestFile);
2069 if (this->Verbose) {
2070 std::cout << "Create " << this->ManifestFileRC << "\n";
2073 cmsys::ofstream fout(this->ManifestFileRC.c_str());
2077 // Insert a pragma statement to specify utf-8 encoding.
2078 fout << "#pragma code_page(65001)\n";
2080 << " /* CREATEPROCESS_MANIFEST_RESOURCE_ID */ "
2081 "24 /* RT_MANIFEST */ \""
2082 << absManifestFile << "\"";
2085 // If we have not previously generated a manifest file,
2086 // generate an empty one so the resource compiler succeeds.
2087 if (!cmSystemTools::FileExists(this->ManifestFile)) {
2088 if (this->Verbose) {
2089 std::cout << "Create empty: " << this->ManifestFile << "\n";
2091 cmsys::ofstream foutTmp(this->ManifestFile.c_str());
2094 // Compile the resource file.
2095 std::vector<std::string> rcCommand;
2096 rcCommand.push_back(this->RcPath.empty() ? "rc" : this->RcPath);
2097 rcCommand.emplace_back("/fo");
2098 rcCommand.push_back(this->ManifestFileRes);
2099 rcCommand.push_back(this->ManifestFileRC);
2100 if (!RunCommand("RC Pass 1", rcCommand, this->Verbose, FORMAT_DECIMAL)) {
2104 // Tell the linker to use our manifest compiled into a resource.
2105 this->LinkCommand.push_back(this->ManifestFileRes);
2107 // Run the link command (possibly generates intermediate manifest).
2108 if (!RunCommand("LINK Pass 1", this->LinkCommand, this->Verbose,
2113 // Run the manifest tool to create the final manifest.
2114 int mtRet = this->RunMT("/out:" + this->ManifestFile, true);
2116 // If mt returns a special value then it updated the manifest file so
2117 // we need to embed it again. Otherwise we are done.
2118 if (!mtRetIsUpdate(mtRet)) {
2122 // Compile the resource file again.
2123 if (!RunCommand("RC Pass 2", rcCommand, this->Verbose, FORMAT_DECIMAL)) {
2127 // Link incrementally again to use the updated resource.
2128 if (!RunCommand("FINAL LINK", this->LinkCommand, this->Verbose,
2135 int cmVSLink::LinkNonIncremental()
2137 // Run the link command (possibly generates intermediate manifest).
2138 if (!RunCommand("LINK", this->LinkCommand, this->Verbose, FORMAT_DECIMAL)) {
2142 // If we have no manifest files we are done.
2143 if (!this->LinkGeneratesManifest && this->UserManifests.empty()) {
2147 // Run the manifest tool to embed the final manifest in the binary.
2149 "/outputresource:" + this->TargetFile + (this->Type == 1 ? ";#1" : ";#2");
2150 return this->RunMT(mtOut, false);
2153 int cmVSLink::RunMT(std::string const& out, bool notify)
2155 std::vector<std::string> mtCommand;
2156 mtCommand.push_back(this->MtPath.empty() ? "mt" : this->MtPath);
2157 mtCommand.emplace_back("/nologo");
2158 mtCommand.emplace_back("/manifest");
2159 if (this->LinkGeneratesManifest) {
2160 mtCommand.push_back(this->LinkerManifestFile);
2162 cm::append(mtCommand, this->UserManifests);
2163 mtCommand.push_back(out);
2165 // Add an undocumented option that enables a special return
2166 // code to notify us when the manifest is modified.
2167 mtCommand.emplace_back("/notify_update");
2170 if (!RunCommand("MT", mtCommand, this->Verbose, FORMAT_HEX, &mtRet,