cmGlobalUnixMakefileGenerator3.cxx 34.8 KB
Newer Older
1 2
/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
   file Copyright.txt or https://cmake.org/licensing for details.  */
3
#include "cmGlobalUnixMakefileGenerator3.h"
4

5 6 7 8 9
#include <algorithm>
#include <functional>
#include <sstream>
#include <utility>

10
#include "cmAlgorithms.h"
11
#include "cmDocumentationEntry.h"
12 13
#include "cmGeneratedFileStream.h"
#include "cmGeneratorTarget.h"
14 15
#include "cmGlobalGenerator.h"
#include "cmLocalGenerator.h"
16 17
#include "cmLocalUnixMakefileGenerator3.h"
#include "cmMakefile.h"
18
#include "cmMakefileTargetGenerator.h"
19
#include "cmOutputConverter.h"
20 21
#include "cmState.h"
#include "cmStateDirectory.h"
22
#include "cmStateTypes.h"
23 24
#include "cmSystemTools.h"
#include "cmTargetDepend.h"
25 26
#include "cmake.h"

27
cmGlobalUnixMakefileGenerator3::cmGlobalUnixMakefileGenerator3(cmake* cm)
28
  : cmGlobalCommonGenerator(cm)
29 30
{
  // This type of makefile always requires unix style paths
31 32
  this->ForceUnixPaths = true;
  this->FindMakeProgramFile = "CMakeUnixFindMake.cmake";
33
  this->ToolSupportsColor = true;
34

35
#if defined(_WIN32) || defined(__VMS)
36 37
  this->UseLinkScript = false;
#else
38
  this->UseLinkScript = true;
39
#endif
Daniel Pfeifer's avatar
Daniel Pfeifer committed
40
  this->CommandDatabase = nullptr;
41 42

  this->IncludeDirective = "include";
43
  this->DefineWindowsNULL = false;
44
  this->PassMakeflags = false;
45
  this->UnixCD = true;
46 47
}

48 49
void cmGlobalUnixMakefileGenerator3::EnableLanguage(
  std::vector<std::string> const& languages, cmMakefile* mf, bool optional)
50
{
51
  this->cmGlobalGenerator::EnableLanguage(languages, mf, optional);
52 53
  for (std::string const& language : languages) {
    if (language == "NONE") {
Bill Hoffman's avatar
Bill Hoffman committed
54
      continue;
55
    }
56
    this->ResolveLanguageCompiler(language, mf, optional);
57
  }
58 59 60
}

///! Create a local generator appropriate to this Global Generator
61
cmLocalGenerator* cmGlobalUnixMakefileGenerator3::CreateLocalGenerator(
62
  cmMakefile* mf)
63
{
64
  return new cmLocalUnixMakefileGenerator3(this, mf);
65 66
}

67 68
void cmGlobalUnixMakefileGenerator3::GetDocumentation(
  cmDocumentationEntry& entry)
69
{
70
  entry.Name = cmGlobalUnixMakefileGenerator3::GetActualName();
71
  entry.Brief = "Generates standard UNIX makefiles.";
72 73
}

74 75 76 77
std::string cmGlobalUnixMakefileGenerator3::GetEditCacheCommand() const
{
  // If generating for an extra IDE, the edit_cache target cannot
  // launch a terminal-interactive tool, so always use cmake-gui.
78
  if (!this->GetExtraGeneratorName().empty()) {
79
    return cmSystemTools::GetCMakeGUICommand();
80
  }
81 82 83 84 85

  // Use an internal cache entry to track the latest dialog used
  // to edit the cache, and use that for the edit_cache target.
  cmake* cm = this->GetCMakeInstance();
  std::string editCacheCommand = cm->GetCMakeEditCommand();
86 87 88
  if (!cm->GetCacheDefinition("CMAKE_EDIT_COMMAND") ||
      !editCacheCommand.empty()) {
    if (editCacheCommand.empty()) {
89
      editCacheCommand = cmSystemTools::GetCMakeCursesCommand();
90 91
    }
    if (editCacheCommand.empty()) {
92 93
      editCacheCommand = cmSystemTools::GetCMakeGUICommand();
    }
94 95 96
    if (!editCacheCommand.empty()) {
      cm->AddCacheEntry("CMAKE_EDIT_COMMAND", editCacheCommand.c_str(),
                        "Path to cache edit program executable.",
97
                        cmStateEnums::INTERNAL);
98 99
    }
  }
100
  const char* edit_cmd = cm->GetCacheDefinition("CMAKE_EDIT_COMMAND");
101
  return edit_cmd ? edit_cmd : "";
102 103
}

104 105
void cmGlobalUnixMakefileGenerator3::ComputeTargetObjectDirectory(
  cmGeneratorTarget* gt) const
106 107
{
  // Compute full path to object file directory for this target.
108
  std::string dir;
109
  dir += gt->LocalGenerator->GetCurrentBinaryDirectory();
110
  dir += "/";
111
  dir += gt->LocalGenerator->GetTargetDirectory(gt);
112 113
  dir += "/";
  gt->ObjectDirectory = dir;
114 115
}

116 117 118 119 120 121 122 123
void cmGlobalUnixMakefileGenerator3::Configure()
{
  // Initialize CMAKE_EDIT_COMMAND cache entry.
  this->GetEditCacheCommand();

  this->cmGlobalGenerator::Configure();
}

124
void cmGlobalUnixMakefileGenerator3::Generate()
Ken Martin's avatar
Ken Martin committed
125
{
126 127 128
  // first do superclass method
  this->cmGlobalGenerator::Generate();

129 130
  // initialize progress
  unsigned long total = 0;
131 132
  for (auto const& pmi : this->ProgressMap) {
    total += pmi.second.NumberOfActions;
133
  }
Ken Martin's avatar
Ken Martin committed
134

135 136 137 138 139 140 141 142
  // write each target's progress.make this loop is done twice. Bascially the
  // Generate pass counts all the actions, the first loop below determines
  // how many actions have progress updates for each target and writes to
  // corrrect variable values for everything except the all targets. The
  // second loop actually writes out correct values for the all targets as
  // well. This is because the all targets require more information that is
  // computed in the first loop.
  unsigned long current = 0;
143 144
  for (auto& pmi : this->ProgressMap) {
    pmi.second.WriteProgressVariables(total, current);
145
  }
146
  for (cmLocalGenerator* lg : this->LocalGenerators) {
147
    std::string markFileName = lg->GetCurrentBinaryDirectory();
148
    markFileName += "/";
149
    markFileName += "/CMakeFiles";
150
    markFileName += "/progress.marks";
151
    cmGeneratedFileStream markFile(markFileName);
152
    markFile << this->CountProgressMarksInAll(lg) << "\n";
153
  }
154

Ken Martin's avatar
Ken Martin committed
155
  // write the main makefile
156
  this->WriteMainMakefile2();
Ken Martin's avatar
Ken Martin committed
157
  this->WriteMainCMakefile();
158

Daniel Pfeifer's avatar
Daniel Pfeifer committed
159
  if (this->CommandDatabase != nullptr) {
160 161
    *this->CommandDatabase << std::endl << "]";
    delete this->CommandDatabase;
Daniel Pfeifer's avatar
Daniel Pfeifer committed
162
    this->CommandDatabase = nullptr;
163 164 165 166
  }
}

void cmGlobalUnixMakefileGenerator3::AddCXXCompileCommand(
167 168 169
  const std::string& sourceFile, const std::string& workingDirectory,
  const std::string& compileCommand)
{
Daniel Pfeifer's avatar
Daniel Pfeifer committed
170
  if (this->CommandDatabase == nullptr) {
171
    std::string commandDatabaseName =
172 173
      std::string(this->GetCMakeInstance()->GetHomeOutputDirectory()) +
      "/compile_commands.json";
174
    this->CommandDatabase = new cmGeneratedFileStream(commandDatabaseName);
175
    *this->CommandDatabase << "[" << std::endl;
176
  } else {
177
    *this->CommandDatabase << "," << std::endl;
178
  }
179
  *this->CommandDatabase << "{" << std::endl
180 181 182 183 184 185 186 187 188 189
                         << "  \"directory\": \""
                         << cmGlobalGenerator::EscapeJSON(workingDirectory)
                         << "\"," << std::endl
                         << "  \"command\": \""
                         << cmGlobalGenerator::EscapeJSON(compileCommand)
                         << "\"," << std::endl
                         << "  \"file\": \""
                         << cmGlobalGenerator::EscapeJSON(sourceFile) << "\""
                         << std::endl
                         << "}";
Ken Martin's avatar
Ken Martin committed
190 191
}

192 193 194 195 196
void cmGlobalUnixMakefileGenerator3::WriteMainMakefile2()
{
  // Open the output file.  This should not be copy-if-different
  // because the check-build-system step compares the makefile time to
  // see if the build system must be regenerated.
197
  std::string makefileName =
198
    this->GetCMakeInstance()->GetHomeOutputDirectory();
199
  makefileName += "/CMakeFiles";
200
  makefileName += "/Makefile2";
201
  cmGeneratedFileStream makefileStream(makefileName, false,
202
                                       this->GetMakefileEncoding());
203
  if (!makefileStream) {
204
    return;
205
  }
206

207
  // get a local generator for some useful methods
208 209
  cmLocalUnixMakefileGenerator3* lg =
    static_cast<cmLocalUnixMakefileGenerator3*>(this->LocalGenerators[0]);
210

211 212
  // Write the do not edit header.
  lg->WriteDisclaimer(makefileStream);
213

214 215 216 217 218
  // Write the main entry point target.  This must be the VERY first
  // target so that make with no arguments will run it.
  // Just depend on the all target to drive the build.
  std::vector<std::string> depends;
  std::vector<std::string> no_commands;
wahikihiki's avatar
wahikihiki committed
219
  depends.emplace_back("all");
220 221 222 223 224

  // Write the rule.
  lg->WriteMakeRule(makefileStream,
                    "Default target executed when no arguments are "
                    "given to make.",
225
                    "default_target", depends, no_commands, true);
226

227
  depends.clear();
228

229 230
  // The all and preinstall rules might never have any dependencies
  // added to them.
231
  if (!this->EmptyRuleHackDepends.empty()) {
232
    depends.push_back(this->EmptyRuleHackDepends);
233
  }
234

235
  // Write and empty all:
236
  lg->WriteMakeRule(makefileStream, "The main recursive all target", "all",
237
                    depends, no_commands, true);
238

239
  // Write an empty preinstall:
240 241
  lg->WriteMakeRule(makefileStream, "The main recursive preinstall target",
                    "preinstall", depends, no_commands, true);
242

243 244 245 246
  // Write an empty clean:
  lg->WriteMakeRule(makefileStream, "The main recursive clean target", "clean",
                    depends, no_commands, true);

247 248
  // Write out the "special" stuff
  lg->WriteSpecialTargetsTop(makefileStream);
249

250
  // write the target convenience rules
251 252
  for (cmLocalGenerator* localGen : this->LocalGenerators) {
    lg = static_cast<cmLocalUnixMakefileGenerator3*>(localGen);
253 254
    this->WriteConvenienceRules2(makefileStream, lg);
  }
255

256
  lg = static_cast<cmLocalUnixMakefileGenerator3*>(this->LocalGenerators[0]);
257 258 259
  lg->WriteSpecialTargetsBottom(makefileStream);
}

260 261
void cmGlobalUnixMakefileGenerator3::WriteMainCMakefile()
{
262 263 264 265
  if (this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION")) {
    return;
  }

266 267 268
  // Open the output file.  This should not be copy-if-different
  // because the check-build-system step compares the makefile time to
  // see if the build system must be regenerated.
269
  std::string cmakefileName =
Ken Martin's avatar
Ken Martin committed
270
    this->GetCMakeInstance()->GetHomeOutputDirectory();
271
  cmakefileName += "/CMakeFiles";
272
  cmakefileName += "/Makefile.cmake";
273
  cmGeneratedFileStream cmakefileStream(cmakefileName);
274
  if (!cmakefileStream) {
275
    return;
276
  }
Ken Martin's avatar
Ken Martin committed
277

278
  std::string makefileName =
Ken Martin's avatar
Ken Martin committed
279 280
    this->GetCMakeInstance()->GetHomeOutputDirectory();
  makefileName += "/Makefile";
281

282
  // get a local generator for some useful methods
283 284
  cmLocalUnixMakefileGenerator3* lg =
    static_cast<cmLocalUnixMakefileGenerator3*>(this->LocalGenerators[0]);
285

286 287 288
  // Write the do not edit header.
  lg->WriteDisclaimer(cmakefileStream);

Ken Martin's avatar
Ken Martin committed
289
  // Save the generator name
290 291 292
  cmakefileStream << "# The generator used is:\n"
                  << "set(CMAKE_DEPENDS_GENERATOR \"" << this->GetName()
                  << "\")\n\n";
Ken Martin's avatar
Ken Martin committed
293

294 295
  // for each cmMakefile get its list of dependencies
  std::vector<std::string> lfiles;
296 297
  for (cmLocalGenerator* localGen : this->LocalGenerators) {
    lg = static_cast<cmLocalUnixMakefileGenerator3*>(localGen);
298

299
    // Get the list of files contributing to this generation step.
300
    lfiles.insert(lfiles.end(), lg->GetMakefile()->GetListFiles().begin(),
301
                  lg->GetMakefile()->GetListFiles().end());
302
  }
303 304 305 306 307 308 309

  cmake* cm = this->GetCMakeInstance();
  if (cm->DoWriteGlobVerifyTarget()) {
    lfiles.push_back(cm->GetGlobVerifyScript());
    lfiles.push_back(cm->GetGlobVerifyStamp());
  }

310 311
  // Sort the list and remove duplicates.
  std::sort(lfiles.begin(), lfiles.end(), std::less<std::string>());
312
#if !defined(__VMS) // The Compaq STL on VMS crashes, so accept duplicates.
313
  std::vector<std::string>::iterator new_end =
314
    std::unique(lfiles.begin(), lfiles.end());
315
  lfiles.erase(new_end, lfiles.end());
316
#endif
317 318

  // reset lg to the first makefile
319
  lg = static_cast<cmLocalUnixMakefileGenerator3*>(this->LocalGenerators[0]);
320

321
  std::string currentBinDir = lg->GetCurrentBinaryDirectory();
322 323 324
  // Save the list to the cmake file.
  cmakefileStream
    << "# The top level Makefile was generated from the following files:\n"
325
    << "set(CMAKE_MAKEFILE_DEPENDS\n"
326
    << "  \"CMakeCache.txt\"\n";
327
  for (std::string const& f : lfiles) {
328 329
    cmakefileStream << "  \""
                    << lg->MaybeConvertToRelativePath(currentBinDir, f)
330 331 332
                    << "\"\n";
  }
  cmakefileStream << "  )\n\n";
333 334 335

  // Build the path to the cache check file.
  std::string check = this->GetCMakeInstance()->GetHomeOutputDirectory();
336
  check += "/CMakeFiles";
337
  check += "/cmake.check_cache";
338 339

  // Set the corresponding makefile in the cmake file.
340 341 342
  cmakefileStream << "# The corresponding makefile is:\n"
                  << "set(CMAKE_MAKEFILE_OUTPUTS\n"
                  << "  \""
343 344
                  << lg->MaybeConvertToRelativePath(currentBinDir,
                                                    makefileName)
345
                  << "\"\n"
346 347
                  << "  \""
                  << lg->MaybeConvertToRelativePath(currentBinDir, check)
348
                  << "\"\n";
349
  cmakefileStream << "  )\n\n";
Ken Martin's avatar
Ken Martin committed
350

351 352
  const std::string binDir = lg->GetBinaryDirectory();

353 354
  // CMake must rerun if a byproduct is missing.
  {
355 356 357 358
    cmakefileStream << "# Byproducts of CMake generate step:\n"
                    << "set(CMAKE_MAKEFILE_PRODUCTS\n";
    const std::vector<std::string>& outfiles =
      lg->GetMakefile()->GetOutputFiles();
359
    for (std::string const& outfile : outfiles) {
360 361
      cmakefileStream << "  \""
                      << lg->MaybeConvertToRelativePath(binDir, outfile)
362 363 364 365 366
                      << "\"\n";
    }

    // add in all the directory information files
    std::string tmpStr;
367 368
    for (cmLocalGenerator* localGen : this->LocalGenerators) {
      lg = static_cast<cmLocalUnixMakefileGenerator3*>(localGen);
369
      tmpStr = lg->GetCurrentBinaryDirectory();
370
      tmpStr += "/CMakeFiles";
371
      tmpStr += "/CMakeDirectoryInformation.cmake";
372 373
      cmakefileStream << "  \""
                      << lg->MaybeConvertToRelativePath(binDir, tmpStr)
374 375 376
                      << "\"\n";
    }
    cmakefileStream << "  )\n\n";
377 378
  }

379
  this->WriteMainCMakefileLanguageRules(cmakefileStream,
Ken Martin's avatar
Ken Martin committed
380
                                        this->LocalGenerators);
381 382
}

383 384 385
void cmGlobalUnixMakefileGenerator3::WriteMainCMakefileLanguageRules(
  cmGeneratedFileStream& cmakefileStream,
  std::vector<cmLocalGenerator*>& lGenerators)
Ken Martin's avatar
Ken Martin committed
386
{
387
  cmLocalUnixMakefileGenerator3* lg;
Ken Martin's avatar
Ken Martin committed
388

389
  // now list all the target info files
390 391
  cmakefileStream << "# Dependency information for all targets:\n";
  cmakefileStream << "set(CMAKE_DEPEND_INFO_FILES\n";
392 393
  for (cmLocalGenerator* lGenerator : lGenerators) {
    lg = static_cast<cmLocalUnixMakefileGenerator3*>(lGenerator);
394
    // for all of out targets
395
    const std::vector<cmGeneratorTarget*>& tgts = lg->GetGeneratorTargets();
396 397 398 399 400 401 402 403
    for (cmGeneratorTarget* tgt : tgts) {
      if ((tgt->GetType() == cmStateEnums::EXECUTABLE) ||
          (tgt->GetType() == cmStateEnums::STATIC_LIBRARY) ||
          (tgt->GetType() == cmStateEnums::SHARED_LIBRARY) ||
          (tgt->GetType() == cmStateEnums::MODULE_LIBRARY) ||
          (tgt->GetType() == cmStateEnums::OBJECT_LIBRARY) ||
          (tgt->GetType() == cmStateEnums::UTILITY)) {
        cmGeneratorTarget* gt = tgt;
404
        std::string tname = lg->GetRelativeTargetDirectory(gt);
405 406
        tname += "/DependInfo.cmake";
        cmSystemTools::ConvertToUnixSlashes(tname);
407
        cmakefileStream << "  \"" << tname << "\"\n";
408 409
      }
    }
410
  }
411
  cmakefileStream << "  )\n";
412 413
}

414 415 416
void cmGlobalUnixMakefileGenerator3::WriteDirectoryRule2(
  std::ostream& ruleFileStream, cmLocalUnixMakefileGenerator3* lg,
  const char* pass, bool check_all, bool check_relink)
Ken Martin's avatar
Ken Martin committed
417
{
418
  // Get the relative path to the subdirectory from the top.
419
  std::string makeTarget = lg->GetCurrentBinaryDirectory();
420 421 422 423 424 425
  makeTarget += "/";
  makeTarget += pass;

  // The directory-level rule should depend on the target-level rules
  // for all targets in the directory.
  std::vector<std::string> depends;
426
  const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets();
427
  for (cmGeneratorTarget* gtarget : targets) {
428
    int type = gtarget->GetType();
429 430 431 432 433 434
    if ((type == cmStateEnums::EXECUTABLE) ||
        (type == cmStateEnums::STATIC_LIBRARY) ||
        (type == cmStateEnums::SHARED_LIBRARY) ||
        (type == cmStateEnums::MODULE_LIBRARY) ||
        (type == cmStateEnums::OBJECT_LIBRARY) ||
        (type == cmStateEnums::UTILITY)) {
435
      // Add this to the list of depends rules in this directory.
436 437 438
      if ((!check_all || !gtarget->GetPropertyAsBool("EXCLUDE_FROM_ALL")) &&
          (!check_relink ||
           gtarget->NeedRelinkBeforeInstall(lg->GetConfigName()))) {
439
        std::string tname = lg->GetRelativeTargetDirectory(gtarget);
440 441
        tname += "/";
        tname += pass;
442
        depends.push_back(std::move(tname));
443
      }
444
    }
445
  }
446

447 448
  // The directory-level rule should depend on the directory-level
  // rules of the subdirectories.
449
  std::vector<cmStateSnapshot> children = lg->GetStateSnapshot().GetChildren();
450 451
  for (cmStateSnapshot const& c : children) {
    std::string subdir = c.GetDirectory().GetCurrentBinary();
452 453
    subdir += "/";
    subdir += pass;
454
    depends.push_back(std::move(subdir));
455
  }
456 457 458

  // Work-around for makes that drop rules that have no dependencies
  // or commands.
459
  if (depends.empty() && !this->EmptyRuleHackDepends.empty()) {
460
    depends.push_back(this->EmptyRuleHackDepends);
461
  }
462 463 464 465 466 467

  // Write the rule.
  std::string doc = "Convenience name for \"";
  doc += pass;
  doc += "\" pass in the directory.";
  std::vector<std::string> no_commands;
468 469
  lg->WriteMakeRule(ruleFileStream, doc.c_str(), makeTarget, depends,
                    no_commands, true);
470 471
}

472 473
void cmGlobalUnixMakefileGenerator3::WriteDirectoryRules2(
  std::ostream& ruleFileStream, cmLocalUnixMakefileGenerator3* lg)
474
{
475
  // Only subdirectories need these rules.
476
  if (lg->IsRootMakefile()) {
477
    return;
478
  }
479

480
  // Begin the directory-level rules section.
481
  std::string dir =
482
    cmSystemTools::ConvertToOutputPath(lg->MaybeConvertToRelativePath(
483
      lg->GetBinaryDirectory(), lg->GetCurrentBinaryDirectory()));
484
  lg->WriteDivider(ruleFileStream);
485
  ruleFileStream << "# Directory level rules for directory " << dir << "\n\n";
486 487 488 489 490 491 492 493

  // Write directory-level rules for "all".
  this->WriteDirectoryRule2(ruleFileStream, lg, "all", true, false);

  // Write directory-level rules for "clean".
  this->WriteDirectoryRule2(ruleFileStream, lg, "clean", false, false);

  // Write directory-level rules for "preinstall".
494
  this->WriteDirectoryRule2(ruleFileStream, lg, "preinstall", true, true);
495 496
}

497
void cmGlobalUnixMakefileGenerator3::GenerateBuildCommand(
498
  GeneratedMakeCommand& makeCommand, const std::string& makeProgram,
499 500
  const std::string& /*projectName*/, const std::string& /*projectDir*/,
  const std::string& targetName, const std::string& /*config*/, bool fast,
501
  int jobs, bool verbose, std::vector<std::string> const& makeOptions)
502
{
503
  std::unique_ptr<cmMakefile> mfu;
504 505 506 507 508 509 510 511 512 513
  cmMakefile* mf;
  if (!this->Makefiles.empty()) {
    mf = this->Makefiles[0];
  } else {
    cmStateSnapshot snapshot = this->CMakeInstance->GetCurrentSnapshot();
    snapshot.GetDirectory().SetCurrentSource(
      this->CMakeInstance->GetHomeDirectory());
    snapshot.GetDirectory().SetCurrentBinary(
      this->CMakeInstance->GetHomeOutputDirectory());
    snapshot.SetDefaultDefinitions();
514 515
    mfu = cm::make_unique<cmMakefile>(this, snapshot);
    mf = mfu.get();
516 517
  }

518 519 520 521 522 523 524
  // Make it possible to set verbosity also from command line
  if (verbose) {
    makeCommand.add(cmSystemTools::GetCMakeCommand());
    makeCommand.add("-E");
    makeCommand.add("env");
    makeCommand.add("VERBOSE=1");
  }
525
  makeCommand.add(this->SelectMakeProgram(makeProgram));
526

527
  if (jobs != cmake::NO_BUILD_PARALLEL_LEVEL) {
528
    makeCommand.add("-j");
529
    if (jobs != cmake::DEFAULT_BUILD_PARALLEL_LEVEL) {
530
      makeCommand.add(std::to_string(jobs));
531
    }
532
  }
533

534
  makeCommand.add(makeOptions.begin(), makeOptions.end());
535
  if (!targetName.empty()) {
536
    std::string tname = targetName;
537
    if (fast) {
538
      tname += "/fast";
539
    }
540
    tname =
541 542
      mf->GetStateSnapshot().GetDirectory().ConvertToRelPathIfNotContained(
        mf->GetState()->GetBinaryDirectory(), tname);
543
    cmSystemTools::ConvertToOutputSlashes(tname);
544
    makeCommand.add(std::move(tname));
545
  }
546 547
}

548 549
void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules(
  std::ostream& ruleFileStream, std::set<std::string>& emitted)
550
{
551
  std::vector<std::string> depends;
552 553
  std::vector<std::string> commands;

554 555
  bool regenerate = !this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION");
  if (regenerate) {
wahikihiki's avatar
wahikihiki committed
556
    depends.emplace_back("cmake_check_build_system");
557
  }
558

559
  // write the target convenience rules
560 561 562
  for (cmLocalGenerator* localGen : this->LocalGenerators) {
    cmLocalUnixMakefileGenerator3* lg =
      static_cast<cmLocalUnixMakefileGenerator3*>(localGen);
563
    // for each target Generate the rule files for each target.
564
    const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets();
565
    for (cmGeneratorTarget* gtarget : targets) {
566 567
      // Don't emit the same rule twice (e.g. two targets with the same
      // simple name)
568 569
      int type = gtarget->GetType();
      std::string name = gtarget->GetName();
570 571 572
      if (!name.empty() && emitted.insert(name).second &&
          // Handle user targets here.  Global targets are handled in
          // the local generator on a per-directory basis.
573 574 575 576 577 578
          ((type == cmStateEnums::EXECUTABLE) ||
           (type == cmStateEnums::STATIC_LIBRARY) ||
           (type == cmStateEnums::SHARED_LIBRARY) ||
           (type == cmStateEnums::MODULE_LIBRARY) ||
           (type == cmStateEnums::OBJECT_LIBRARY) ||
           (type == cmStateEnums::UTILITY))) {
579 580
        // Add a rule to build the target by name.
        lg->WriteDivider(ruleFileStream);
581 582
        ruleFileStream << "# Target rules for targets named " << name
                       << "\n\n";
583

584 585
        // Write the rule.
        commands.clear();
586
        std::string tmp = "CMakeFiles/";
587
        tmp += "Makefile2";
588
        commands.push_back(lg->GetRecursiveMakeCall(tmp, name));
589
        depends.clear();
590
        if (regenerate) {
wahikihiki's avatar
wahikihiki committed
591
          depends.emplace_back("cmake_check_build_system");
592
        }
593 594
        lg->WriteMakeRule(ruleFileStream, "Build rule for target.", name,
                          depends, commands, true);
595

596
        // Add a fast rule to build the target
597
        std::string localName = lg->GetRelativeTargetDirectory(gtarget);
598 599
        std::string makefileName;
        makefileName = localName;
600
        makefileName += "/build.make";
601 602 603 604
        depends.clear();
        commands.clear();
        std::string makeTargetName = localName;
        makeTargetName += "/build";
605
        localName = name;
606
        localName += "/fast";
607
        commands.push_back(
608
          lg->GetRecursiveMakeCall(makefileName, makeTargetName));
609
        lg->WriteMakeRule(ruleFileStream, "fast build rule for target.",
610
                          localName, depends, commands, true);
611 612 613

        // Add a local name for the rule to relink the target before
        // installation.
614
        if (gtarget->NeedRelinkBeforeInstall(lg->GetConfigName())) {
615
          makeTargetName = lg->GetRelativeTargetDirectory(gtarget);
616
          makeTargetName += "/preinstall";
617
          localName = name;
618 619 620
          localName += "/preinstall";
          depends.clear();
          commands.clear();
621
          commands.push_back(
622
            lg->GetRecursiveMakeCall(makefileName, makeTargetName));
623 624
          lg->WriteMakeRule(ruleFileStream,
                            "Manual pre-install relink rule for target.",
625
                            localName, depends, commands, true);
626
        }
627 628
      }
    }
629
  }
630 631
}

632 633
void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules2(
  std::ostream& ruleFileStream, cmLocalUnixMakefileGenerator3* lg)
634
{
635
  std::vector<std::string> depends;
636 637 638 639 640
  std::vector<std::string> commands;
  std::string localName;
  std::string makeTargetName;

  // write the directory level rules for this local gen
641
  this->WriteDirectoryRules2(ruleFileStream, lg);
642

643 644
  bool regenerate = !this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION");
  if (regenerate) {
wahikihiki's avatar
wahikihiki committed
645
    depends.emplace_back("cmake_check_build_system");
646
  }
647

Ken Martin's avatar
Ken Martin committed
648
  // for each target Generate the rule files for each target.
649
  const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets();
650
  for (cmGeneratorTarget* gtarget : targets) {
651 652
    int type = gtarget->GetType();
    std::string name = gtarget->GetName();
653 654 655 656 657 658 659
    if (!name.empty() &&
        ((type == cmStateEnums::EXECUTABLE) ||
         (type == cmStateEnums::STATIC_LIBRARY) ||
         (type == cmStateEnums::SHARED_LIBRARY) ||
         (type == cmStateEnums::MODULE_LIBRARY) ||
         (type == cmStateEnums::OBJECT_LIBRARY) ||
         (type == cmStateEnums::UTILITY))) {
660
      std::string makefileName;
Ken Martin's avatar
Ken Martin committed
661
      // Add a rule to build the target by name.
662
      localName = lg->GetRelativeTargetDirectory(gtarget);
663
      makefileName = localName;
664
      makefileName += "/build.make";
665

666
      lg->WriteDivider(ruleFileStream);
667
      ruleFileStream << "# Target rules for target " << localName << "\n\n";
668 669

      commands.clear();
670 671
      makeTargetName = localName;
      makeTargetName += "/depend";
672
      commands.push_back(
673
        lg->GetRecursiveMakeCall(makefileName, makeTargetName));
674

675 676
      makeTargetName = localName;
      makeTargetName += "/build";
677
      commands.push_back(
678
        lg->GetRecursiveMakeCall(makefileName, makeTargetName));
679

680 681 682
      // Write the rule.
      localName += "/all";
      depends.clear();
683

684
      cmLocalUnixMakefileGenerator3::EchoProgress progress;
685
      progress.Dir = lg->GetBinaryDirectory();
686
      progress.Dir += "/CMakeFiles";
687
      {
688 689
        std::ostringstream progressArg;
        const char* sep = "";
690
        std::vector<unsigned long> const& progFiles =
691
          this->ProgressMap[gtarget].Marks;
692 693
        for (unsigned long progFile : progFiles) {
          progressArg << sep << progFile;
694
          sep = ",";
695
        }
696
        progress.Arg = progressArg.str();
697
      }
698 699

      bool targetMessages = true;
700 701 702
      if (const char* tgtMsg =
            this->GetCMakeInstance()->GetState()->GetGlobalProperty(
              "TARGET_MESSAGES")) {
703
        targetMessages = cmSystemTools::IsOn(tgtMsg);
704
      }
705

706
      if (targetMessages) {
707
        lg->AppendEcho(commands, "Built target " + name,
708 709
                       cmLocalUnixMakefileGenerator3::EchoNormal, &progress);
      }
710

711
      this->AppendGlobalTargetDepends(depends, gtarget);
712
      lg->WriteMakeRule(ruleFileStream, "All Build rule for target.",
713
                        localName, depends, commands, true);
714

715
      // add the all/all dependency
716
      if (!this->IsExcluded(gtarget)) {
717 718
        depends.clear();
        depends.push_back(localName);
719
        commands.clear();
720 721 722
        lg->WriteMakeRule(ruleFileStream, "Include target in all.", "all",
                          depends, commands, true);
      }
723

724 725
      // Write the rule.
      commands.clear();
726

727
      {
728 729 730 731
        // TODO: Convert the total progress count to a make variable.
        std::ostringstream progCmd;
        progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start ";
        // # in target
732 733 734
        progCmd << lg->ConvertToOutputFormat(
          cmSystemTools::CollapseFullPath(progress.Dir),
          cmOutputConverter::SHELL);
735 736 737 738
        //
        std::set<cmGeneratorTarget const*> emitted;
        progCmd << " " << this->CountProgressMarksInTarget(gtarget, emitted);
        commands.push_back(progCmd.str());
739
      }
740
      std::string tmp = "CMakeFiles/";
741
      tmp += "Makefile2";
742
      commands.push_back(lg->GetRecursiveMakeCall(tmp, localName));
743
      {
744 745
        std::ostringstream progCmd;
        progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; // # 0
746 747 748
        progCmd << lg->ConvertToOutputFormat(
          cmSystemTools::CollapseFullPath(progress.Dir),
          cmOutputConverter::SHELL);
749 750
        progCmd << " 0";
        commands.push_back(progCmd.str());
751
      }
752
      depends.clear();
753
      if (regenerate) {
wahikihiki's avatar
wahikihiki committed
754
        depends.emplace_back("cmake_check_build_system");
755
      }
756
      localName = lg->GetRelativeTargetDirectory(gtarget);
757
      localName += "/rule";
758
      lg->WriteMakeRule(ruleFileStream,
759
                        "Build rule for subdir invocation for target.",
760
                        localName, depends, commands, true);
761

762 763 764 765
      // Add a target with the canonical name (no prefix, suffix or path).
      commands.clear();
      depends.clear();
      depends.push_back(localName);
766 767
      lg->WriteMakeRule(ruleFileStream, "Convenience name for target.", name,
                        depends, commands, true);
768

769
      // Add rules to prepare the target for installation.
770
      if (gtarget->NeedRelinkBeforeInstall(lg->GetConfigName())) {
771
        localName = lg->GetRelativeTargetDirectory(gtarget);
772
        localName += "/preinstall";
773 774
        depends.clear();
        commands.clear();
775
        commands.push_back(lg->GetRecursiveMakeCall(makefileName, localName));
776
        lg->WriteMakeRule(ruleFileStream,
777 778
                          "Pre-install relink rule for target.", localName,
                          depends, commands, true);
779

780
        if (!this->IsExcluded(gtarget)) {
781 782 783 784 785
          depends.clear();
          depends.push_back(localName);
          commands.clear();
          lg->WriteMakeRule(ruleFileStream, "Prepare target for install.",
                            "preinstall", depends, commands, true);
786
        }
787
      }
788

789
      // add the clean rule
790
      localName = lg->GetRelativeTargetDirectory(gtarget);
791 792 793 794
      makeTargetName = localName;
      makeTargetName += "/clean";
      depends.clear();
      commands.clear();
795
      commands.push_back(
796
        lg->GetRecursiveMakeCall(makefileName, makeTargetName));
797
      lg->WriteMakeRule(ruleFileStream, "clean rule for target.",
798
                        makeTargetName, depends, commands, true);
799 800
      commands.clear();
      depends.push_back(makeTargetName);
801 802
      lg->WriteMakeRule(ruleFileStream, "clean rule for target.", "clean",
                        depends, commands, true);
803
    }
804
  }
805 806
}

807
// Build a map that contains the set of targets used by each local
808
// generator directory level.
809
void cmGlobalUnixMakefileGenerator3::InitializeProgressMarks()
810
{
811
  this->DirectoryTargetsMap.clear();
812
  // Loop over all targets in all local generators.
813
  for (cmLocalGenerator* lg : this->LocalGenerators) {
814
    const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets();
815
    for (cmGeneratorTarget* gt : targets) {
816 817
      cmLocalGenerator* tlg = gt->GetLocalGenerator();

818
      if (gt->GetType() == cmStateEnums::INTERFACE_LIBRARY ||
819
          gt->GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
820
        continue;
821
      }
822

823 824
      cmStateSnapshot csnp = lg->GetStateSnapshot();
      cmStateSnapshot tsnp = tlg->GetStateSnapshot();
825

826 827
      // Consider the directory containing the target and all its
      // parents until something excludes the target.
828 829
      for (; csnp.IsValid() && !this->IsExcluded(csnp, tsnp);
           csnp = csnp.GetBuildsystemDirectoryParent()) {
830 831
        // This local generator includes the target.
        std::set<cmGeneratorTarget const*>& targetSet =
832
          this->DirectoryTargetsMap[csnp];
833 834 835 836 837 838
        targetSet.insert(gt);

        // Add dependencies of the included target.  An excluded
        // target may still be included if it is a dependency of a
        // non-excluded target.
        TargetDependSet const& tgtdeps = this->GetTargetDirectDepends(gt);
839 840
        for (cmTargetDepend const& tgtdep : tgtdeps) {
          targetSet.insert(tgtdep);
841 842 843
        }
      }
    }
844
  }
845 846
}

847 848
size_t cmGlobalUnixMakefileGenerator3::CountProgressMarksInTarget(
  cmGeneratorTarget const* target, std::set<cmGeneratorTarget const*>& emitted)
849
{
850
  size_t count = 0;
851
  if (emitted.insert(target).second) {
852
    count = this->ProgressMap[target].Marks.size();
853
    TargetDependSet const& depends = this->GetTargetDirectDepends(target);
854 855
    for (cmTargetDepend const& depend : depends) {
      if (depend->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
856
        continue;
857
      }
858
      count += this->CountProgressMarksInTarget(depend, emitted);
859
    }
860
  }
861
  return count;
862 863
}

864 865
size_t cmGlobalUnixMakefileGenerator3::CountProgressMarksInAll(
  cmLocalGenerator* lg)
866
{
867
  size_t count = 0;
868
  std::set<cmGeneratorTarget const*> emitted;
869 870
  std::set<cmGeneratorTarget const*> const& targets =
    this->DirectoryTargetsMap[lg->GetStateSnapshot()];
871 872
  for (cmGeneratorTarget const* target : targets) {
    count += this->CountProgressMarksInTarget(target, emitted);
873
  }
874
  return count;
875 876
}

877
void cmGlobalUnixMakefileGenerator3::RecordTargetProgress(
878 879
  cmMakefileTargetGenerator* tg)
{
880
  TargetProgress& tp = this->ProgressMap[tg->GetGeneratorTarget()];
881 882 883 884
  tp.NumberOfActions = tg->GetNumberOfProgressActions();
  tp.VariableFile = tg->GetProgressFileNameFull();
}

885 886
void cmGlobalUnixMakefileGenerator3::TargetProgress::WriteProgressVariables(
  unsigned long total, unsigned long& current)
887
{
888
  cmGeneratedFileStream fout(this->VariableFile);
889
  for (unsigned long i = 1; i <= this->NumberOfActions; ++i) {
890
    fout << "CMAKE_PROGRESS_" << i << " = ";
891
    if (total <= 100) {
892 893 894
      unsigned long num = i + current;
      fout << num;
      this->Marks.push_back(num);
895 896 897
    } else if (((i + current) * 100) / total >
               ((i - 1 + current) * 100) / total) {
      unsigned long num = ((i + current) * 100) / total;
898 899 900
      fout << num;
      this->Marks.push_back(num);
    }
901 902
    fout << "\n";
  }
903 904 905
  fout << "\n";
  current += this->NumberOfActions;
}
906

907 908
void cmGlobalUnixMakefileGenerator3::AppendGlobalTargetDepends(
  std::vector<std::string>& depends, cmGeneratorTarget* target)
909
{
910
  TargetDependSet const& depends_set = this->GetTargetDirectDepends(target);
911
  for (cmTargetDepend const& i : depends_set) {
912
    // Create the target-level dependency.
913
    cmGeneratorTarget const* dep = i;
914
    if (dep->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
915
      continue;
916
    }
917
    cmLocalUnixMakefileGenerator3* lg3 =
918
      static_cast<cmLocalUnixMakefileGenerator3*>(dep->GetLocalGenerator());
919
    std::string tgtName =
920
      lg3->GetRelativeTargetDirectory(const_cast<cmGeneratorTarget*>(dep));
921 922
    tgtName += "/all";
    depends.push_back(tgtName);
923
  }
924
}
925

926 927
void cmGlobalUnixMakefileGenerator3::WriteHelpRule(
  std::ostream& ruleFileStream, cmLocalUnixMakefileGenerator3* lg)
928 929 930 931 932
{
  // add the help target
  std::string path;
  std::vector<std::string> no_depends;
  std::vector<std::string> commands;
933 934 935
  lg->AppendEcho(commands,
                 "The following are some of the valid targets "
                 "for this Makefile:");
936 937
  lg->AppendEcho(commands, "... all (the default if no target is provided)");
  lg->AppendEcho(commands, "... clean");
938 939 940
  if (!this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION")) {
    lg->AppendEcho(commands, "... depend");
  }
941

942
  // Keep track of targets already listed.
943
  std::set<std::string> emittedTargets;
944

945
  // for each local generator
946 947 948
  for (cmLocalGenerator* localGen : this->LocalGenerators) {
    cmLocalUnixMakefileGenerator3* lg2 =
      static_cast<cmLocalUnixMakefileGenerator3*>(localGen);
949 950
    // for the passed in makefile or if this is the top Makefile wripte out
    // the targets
951
    if (lg2 == lg || lg->IsRootMakefile()) {
952
      // for each target Generate the rule files for each target.
953 954
      const std::vector<cmGeneratorTarget*>& targets =
        lg2->GetGeneratorTargets();