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