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