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