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