cmExportInstallFileGenerator.cxx 18.6 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 4
#include "cmExportInstallFileGenerator.h"

5
#include "cmAlgorithms.h"
6
#include "cmExportSet.h"
7
#include "cmExportSetMap.h"
8
#include "cmGeneratedFileStream.h"
9 10
#include "cmGeneratorExpression.h"
#include "cmGeneratorTarget.h"
11
#include "cmGlobalGenerator.h"
12 13
#include "cmInstallExportGenerator.h"
#include "cmInstallTargetGenerator.h"
14
#include "cmLocalGenerator.h"
15 16
#include "cmMakefile.h"
#include "cmPolicies.h"
17
#include "cmStateTypes.h"
18 19
#include "cmSystemTools.h"
#include "cmTarget.h"
20
#include "cmTargetExport.h"
21

22 23 24
#include <sstream>
#include <utility>

25 26 27
cmExportInstallFileGenerator::cmExportInstallFileGenerator(
  cmInstallExportGenerator* iegen)
  : IEGen(iegen)
28 29 30
{
}

31 32 33 34 35 36 37 38
std::string cmExportInstallFileGenerator::GetConfigImportFileGlob()
{
  std::string glob = this->FileBase;
  glob += "-*";
  glob += this->FileExt;
  return glob;
}

39 40
bool cmExportInstallFileGenerator::GenerateMainFile(std::ostream& os)
{
41
  std::vector<cmTargetExport*> allTargets;
42
  {
43 44
    std::string expectedTargets;
    std::string sep;
45 46 47
    for (cmTargetExport* te :
         *this->IEGen->GetExportSet()->GetTargetExports()) {
      expectedTargets += sep + this->Namespace + te->Target->GetExportName();
48 49 50 51 52 53 54 55 56
      sep = " ";
      if (this->ExportedTargets.insert(te->Target).second) {
        allTargets.push_back(te);
      } else {
        std::ostringstream e;
        e << "install(EXPORT \"" << this->IEGen->GetExportSet()->GetName()
          << "\" ...) "
          << "includes target \"" << te->Target->GetName()
          << "\" more than once in the export set.";
57
        cmSystemTools::Error(e.str());
58
        return false;
59
      }
60 61
    }

62
    this->GenerateExpectedTargetsCode(os, expectedTargets);
63 64
  }

65 66
  // Compute the relative import prefix for the file
  this->GenerateImportPrefix(os);
67

68 69
  std::vector<std::string> missingTargets;

70
  bool require2_8_12 = false;
71
  bool require3_0_0 = false;
72
  bool require3_1_0 = false;
73
  bool requiresConfigFiles = false;
74
  // Create all the imported targets.
75 76
  for (cmTargetExport* te : allTargets) {
    cmGeneratorTarget* gt = te->Target;
77
    cmStateEnums::TargetType targetType = this->GetExportTargetType(te);
78

79
    requiresConfigFiles =
80
      requiresConfigFiles || targetType != cmStateEnums::INTERFACE_LIBRARY;
81

82
    this->GenerateImportTargetCode(os, gt, targetType);
83 84 85

    ImportPropertyMap properties;

86
    this->PopulateIncludeDirectoriesInterface(
87 88
      te, cmGeneratorExpression::InstallInterface, properties, missingTargets);
    this->PopulateSourcesInterface(te, cmGeneratorExpression::InstallInterface,
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
                                   properties, missingTargets);
    this->PopulateInterfaceProperty("INTERFACE_SYSTEM_INCLUDE_DIRECTORIES", gt,
                                    cmGeneratorExpression::InstallInterface,
                                    properties, missingTargets);
    this->PopulateInterfaceProperty("INTERFACE_COMPILE_DEFINITIONS", gt,
                                    cmGeneratorExpression::InstallInterface,
                                    properties, missingTargets);
    this->PopulateInterfaceProperty("INTERFACE_COMPILE_OPTIONS", gt,
                                    cmGeneratorExpression::InstallInterface,
                                    properties, missingTargets);
    this->PopulateInterfaceProperty("INTERFACE_AUTOUIC_OPTIONS", gt,
                                    cmGeneratorExpression::InstallInterface,
                                    properties, missingTargets);
    this->PopulateInterfaceProperty("INTERFACE_COMPILE_FEATURES", gt,
                                    cmGeneratorExpression::InstallInterface,
                                    properties, missingTargets);
105 106 107
    this->PopulateInterfaceProperty("INTERFACE_LINK_OPTIONS", gt,
                                    cmGeneratorExpression::InstallInterface,
                                    properties, missingTargets);
108 109
    this->PopulateLinkDirectoriesInterface(
      te, cmGeneratorExpression::InstallInterface, properties, missingTargets);
110 111
    this->PopulateLinkDependsInterface(
      te, cmGeneratorExpression::InstallInterface, properties, missingTargets);
112

113 114
    std::string errorMessage;
    if (!this->PopulateExportProperties(gt, properties, errorMessage)) {
115
      cmSystemTools::Error(errorMessage);
116 117 118
      return false;
    }

119
    const bool newCMP0022Behavior =
120 121 122 123 124 125 126
      gt->GetPolicyStatusCMP0022() != cmPolicies::WARN &&
      gt->GetPolicyStatusCMP0022() != cmPolicies::OLD;
    if (newCMP0022Behavior) {
      if (this->PopulateInterfaceLinkLibrariesProperty(
            gt, cmGeneratorExpression::InstallInterface, properties,
            missingTargets) &&
          !this->ExportOld) {
127 128
        require2_8_12 = true;
      }
129
    }
130
    if (targetType == cmStateEnums::INTERFACE_LIBRARY) {
131
      require3_0_0 = true;
132 133
    }
    if (gt->GetProperty("INTERFACE_SOURCES")) {
134 135 136
      // We can only generate INTERFACE_SOURCES in CMake 3.3, but CMake 3.1
      // can consume them.
      require3_1_0 = true;
137
    }
138

139 140
    this->PopulateInterfaceProperty("INTERFACE_POSITION_INDEPENDENT_CODE", gt,
                                    properties);
141

142
    this->PopulateCompatibleInterfaceProperties(gt, properties);
143

144
    this->GenerateInterfaceProperties(gt, os, properties);
145
  }
146

147
  if (require3_1_0) {
148
    this->GenerateRequiredCMakeVersion(os, "3.1.0");
149
  } else if (require3_0_0) {
150
    this->GenerateRequiredCMakeVersion(os, "3.0.0");
151
  } else if (require2_8_12) {
Brad King's avatar
Brad King committed
152
    this->GenerateRequiredCMakeVersion(os, "2.8.12");
153
  }
154

155
  this->LoadConfigFiles(os);
156

157
  this->CleanupTemporaryVariables(os);
158 159
  this->GenerateImportedFileCheckLoop(os);

160
  bool result = true;
161 162
  // Generate an import file for each configuration.
  // Don't do this if we only export INTERFACE_LIBRARY targets.
163
  if (requiresConfigFiles) {
164 165
    for (std::string const& c : this->Configurations) {
      if (!this->GenerateImportFileConfig(c, missingTargets)) {
166
        result = false;
167 168
      }
    }
169
  }
170 171 172

  this->GenerateMissingTargetsCheckCode(os, missingTargets);

173 174 175
  return result;
}

176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
void cmExportInstallFileGenerator::GenerateImportPrefix(std::ostream& os)
{
  // Set an _IMPORT_PREFIX variable for import location properties
  // to reference if they are relative to the install prefix.
  std::string installPrefix =
    this->IEGen->GetLocalGenerator()->GetMakefile()->GetSafeDefinition(
      "CMAKE_INSTALL_PREFIX");
  std::string const& expDest = this->IEGen->GetDestination();
  if (cmSystemTools::FileIsFullPath(expDest)) {
    // The export file is being installed to an absolute path so the
    // package is not relocatable.  Use the configured install prefix.
    /* clang-format off */
    os <<
      "# The installation prefix configured by this project.\n"
      "set(_IMPORT_PREFIX \"" << installPrefix << "\")\n"
      "\n";
    /* clang-format on */
  } else {
    // Add code to compute the installation prefix relative to the
    // import file location.
    std::string absDest = installPrefix + "/" + expDest;
    std::string absDestS = absDest + "/";
    os << "# Compute the installation prefix relative to this file.\n"
       << "get_filename_component(_IMPORT_PREFIX"
       << " \"${CMAKE_CURRENT_LIST_FILE}\" PATH)\n";
201 202 203 204 205 206
    if (cmHasLiteralPrefix(absDestS, "/lib/") ||
        cmHasLiteralPrefix(absDestS, "/lib64/") ||
        cmHasLiteralPrefix(absDestS, "/libx32/") ||
        cmHasLiteralPrefix(absDestS, "/usr/lib/") ||
        cmHasLiteralPrefix(absDestS, "/usr/lib64/") ||
        cmHasLiteralPrefix(absDestS, "/usr/libx32/")) {
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
      // Handle "/usr move" symlinks created by some Linux distros.
      /* clang-format off */
      os <<
        "# Use original install prefix when loaded through a\n"
        "# cross-prefix symbolic link such as /lib -> /usr/lib.\n"
        "get_filename_component(_realCurr \"${_IMPORT_PREFIX}\" REALPATH)\n"
        "get_filename_component(_realOrig \"" << absDest << "\" REALPATH)\n"
        "if(_realCurr STREQUAL _realOrig)\n"
        "  set(_IMPORT_PREFIX \"" << absDest << "\")\n"
        "endif()\n"
        "unset(_realOrig)\n"
        "unset(_realCurr)\n";
      /* clang-format on */
    }
    std::string dest = expDest;
    while (!dest.empty()) {
      os << "get_filename_component(_IMPORT_PREFIX \"${_IMPORT_PREFIX}\" "
            "PATH)\n";
      dest = cmSystemTools::GetFilenamePath(dest);
    }
    os << "if(_IMPORT_PREFIX STREQUAL \"/\")\n"
       << "  set(_IMPORT_PREFIX \"\")\n"
       << "endif()\n"
       << "\n";
  }
}

void cmExportInstallFileGenerator::CleanupTemporaryVariables(std::ostream& os)
{
  /* clang-format off */
  os << "# Cleanup temporary variables.\n"
     << "set(_IMPORT_PREFIX)\n"
     << "\n";
  /* clang-format on */
}

void cmExportInstallFileGenerator::LoadConfigFiles(std::ostream& os)
{
  // Now load per-configuration properties for them.
  /* clang-format off */
  os << "# Load information for each installed configuration.\n"
     << "get_filename_component(_DIR \"${CMAKE_CURRENT_LIST_FILE}\" PATH)\n"
     << "file(GLOB CONFIG_FILES \"${_DIR}/"
     << this->GetConfigImportFileGlob() << "\")\n"
     << "foreach(f ${CONFIG_FILES})\n"
     << "  include(${f})\n"
     << "endforeach()\n"
     << "\n";
  /* clang-format on */
}

258
void cmExportInstallFileGenerator::ReplaceInstallPrefix(std::string& input)
259 260 261 262
{
  std::string::size_type pos = 0;
  std::string::size_type lastPos = pos;

263 264
  while ((pos = input.find("$<INSTALL_PREFIX>", lastPos)) !=
         std::string::npos) {
265 266 267
    std::string::size_type endPos = pos + sizeof("$<INSTALL_PREFIX>") - 1;
    input.replace(pos, endPos - pos, "${_IMPORT_PREFIX}");
    lastPos = endPos;
268
  }
269 270
}

271 272
bool cmExportInstallFileGenerator::GenerateImportFileConfig(
  const std::string& config, std::vector<std::string>& missingTargets)
273 274
{
  // Skip configurations not enabled for this export.
275
  if (!this->IEGen->InstallsForConfig(config)) {
276
    return true;
277
  }
278 279 280 281 282 283

  // Construct the name of the file to generate.
  std::string fileName = this->FileDir;
  fileName += "/";
  fileName += this->FileBase;
  fileName += "-";
284
  if (!config.empty()) {
285
    fileName += cmSystemTools::LowerCase(config);
286
  } else {
287
    fileName += "noconfig";
288
  }
289 290 291
  fileName += this->FileExt;

  // Open the output file to generate it.
292
  cmGeneratedFileStream exportFileStream(fileName, true);
293
  if (!exportFileStream) {
294
    std::string se = cmSystemTools::GetLastSystemError();
295
    std::ostringstream e;
296
    e << "cannot write to file \"" << fileName << "\": " << se;
297
    cmSystemTools::Error(e.str());
298
    return false;
299
  }
300 301 302 303 304 305
  std::ostream& os = exportFileStream;

  // Start with the import file header.
  this->GenerateImportHeaderCode(os, config);

  // Generate the per-config target information.
306
  this->GenerateImportConfig(os, config, missingTargets);
307 308 309 310 311 312 313 314 315 316

  // End with the import file footer.
  this->GenerateImportFooterCode(os);

  // Record this per-config import file.
  this->ConfigImportFiles[config] = fileName;

  return true;
}

317 318 319
void cmExportInstallFileGenerator::GenerateImportTargetsConfig(
  std::ostream& os, const std::string& config, std::string const& suffix,
  std::vector<std::string>& missingTargets)
320 321
{
  // Add each target in the set to the export.
322
  for (cmTargetExport* te : *this->IEGen->GetExportSet()->GetTargetExports()) {
323
    // Collect import properties for this target.
324
    if (this->GetExportTargetType(te) == cmStateEnums::INTERFACE_LIBRARY) {
325
      continue;
326
    }
327 328 329 330

    ImportPropertyMap properties;
    std::set<std::string> importedLocations;

331 332 333 334
    this->SetImportLocationProperty(config, suffix, te->ArchiveGenerator,
                                    properties, importedLocations);
    this->SetImportLocationProperty(config, suffix, te->LibraryGenerator,
                                    properties, importedLocations);
335 336
    this->SetImportLocationProperty(config, suffix, te->RuntimeGenerator,
                                    properties, importedLocations);
337 338
    this->SetImportLocationProperty(config, suffix, te->ObjectsGenerator,
                                    properties, importedLocations);
339 340 341 342
    this->SetImportLocationProperty(config, suffix, te->FrameworkGenerator,
                                    properties, importedLocations);
    this->SetImportLocationProperty(config, suffix, te->BundleGenerator,
                                    properties, importedLocations);
343 344 345

    // If any file location was set for the target add it to the
    // import file.
346
    if (!properties.empty()) {
347
      // Get the rest of the target details.
348 349 350
      cmGeneratorTarget* gtgt = te->Target;
      this->SetImportDetailProperties(config, suffix, gtgt, properties,
                                      missingTargets);
351

352 353
      this->SetImportLinkInterface(config, suffix,
                                   cmGeneratorExpression::InstallInterface,
354
                                   gtgt, properties, missingTargets);
355

luz.paz's avatar
luz.paz committed
356
      // TODO: PUBLIC_HEADER_LOCATION
357 358
      // This should wait until the build feature propagation stuff
      // is done.  Then this can be a propagated include directory.
359 360 361 362
      // this->GenerateImportProperty(config, te->HeaderGenerator,
      //                              properties);

      // Generate code in the export file.
363 364
      this->GenerateImportPropertyCode(os, config, gtgt, properties);
      this->GenerateImportedFileChecksCode(os, gtgt, properties,
365
                                           importedLocations);
366
    }
367
  }
368 369
}

370 371 372 373
void cmExportInstallFileGenerator::SetImportLocationProperty(
  const std::string& config, std::string const& suffix,
  cmInstallTargetGenerator* itgen, ImportPropertyMap& properties,
  std::set<std::string>& importedLocations)
374 375
{
  // Skip rules that do not match this configuration.
376
  if (!(itgen && itgen->InstallsForConfig(config))) {
377
    return;
378
  }
379

380
  // Get the target to be installed.
381
  cmGeneratorTarget* target = itgen->GetTarget();
382 383

  // Construct the installed location of the target.
384
  std::string dest = itgen->GetDestination(config);
385
  std::string value;
386
  if (!cmSystemTools::FileIsFullPath(dest)) {
387
    // The target is installed relative to the installation prefix.
388
    value = "${_IMPORT_PREFIX}/";
389
  }
390 391 392
  value += dest;
  value += "/";

393
  if (itgen->IsImportLibrary()) {
394 395 396 397 398
    // Construct the property name.
    std::string prop = "IMPORTED_IMPLIB";
    prop += suffix;

    // Append the installed file name.
399 400
    value += cmInstallTargetGenerator::GetInstallFilename(
      target, config, cmInstallTargetGenerator::NameImplib);
401 402 403

    // Store the property.
    properties[prop] = value;
404
    importedLocations.insert(prop);
405 406 407 408 409 410 411 412 413
  } else if (itgen->GetTarget()->GetType() == cmStateEnums::OBJECT_LIBRARY) {
    // Construct the property name.
    std::string prop = "IMPORTED_OBJECTS";
    prop += suffix;

    // Compute all the object files inside this target and setup
    // IMPORTED_OBJECTS as a list of object files
    std::vector<std::string> objects;
    itgen->GetInstallObjectNames(config, objects);
414 415
    for (std::string& obj : objects) {
      obj = value + obj;
416 417 418 419 420
    }

    // Store the property.
    properties[prop] = cmJoin(objects, ";");
    importedLocations.insert(prop);
421
  } else {
422 423 424
    // Construct the property name.
    std::string prop = "IMPORTED_LOCATION";
    prop += suffix;
425

426
    // Append the installed file name.
427
    if (target->IsAppBundleOnApple()) {
428
      value += cmInstallTargetGenerator::GetInstallFilename(target, config);
429
      value += ".app/Contents/MacOS/";
430
      value += cmInstallTargetGenerator::GetInstallFilename(target, config);
431
    } else {
432 433
      value += cmInstallTargetGenerator::GetInstallFilename(
        target, config, cmInstallTargetGenerator::NameReal);
434
    }
435 436 437

    // Store the property.
    properties[prop] = value;
438
    importedLocations.insert(prop);
439
  }
440 441
}

442 443 444 445 446 447 448 449 450 451 452 453 454
cmStateEnums::TargetType cmExportInstallFileGenerator::GetExportTargetType(
  cmTargetExport const* targetExport) const
{
  cmStateEnums::TargetType targetType = targetExport->Target->GetType();
  // An OBJECT library installed with no OBJECTS DESTINATION
  // is transformed to an INTERFACE library.
  if (targetType == cmStateEnums::OBJECT_LIBRARY &&
      targetExport->ObjectsGenerator == nullptr) {
    targetType = cmStateEnums::INTERFACE_LIBRARY;
  }
  return targetType;
}

455 456
void cmExportInstallFileGenerator::HandleMissingTarget(
  std::string& link_libs, std::vector<std::string>& missingTargets,
457
  cmGeneratorTarget* depender, cmGeneratorTarget* dependee)
458
{
459
  const std::string name = dependee->GetName();
460
  cmGlobalGenerator* gg = dependee->GetLocalGenerator()->GetGlobalGenerator();
461
  std::vector<std::string> namespaces = this->FindNamespaces(gg, name);
Daniel Pfeifer's avatar
Daniel Pfeifer committed
462
  int targetOccurrences = static_cast<int>(namespaces.size());
463
  if (targetOccurrences == 1) {
464
    std::string missingTarget = namespaces[0];
465

466
    missingTarget += dependee->GetExportName();
467
    link_libs += missingTarget;
468
    missingTargets.push_back(std::move(missingTarget));
469
  } else {
470 471
    // All exported targets should be known here and should be unique.
    // This is probably user-error.
472
    this->ComplainAboutMissingTarget(depender, dependee, targetOccurrences);
473
  }
474 475
}

476 477
std::vector<std::string> cmExportInstallFileGenerator::FindNamespaces(
  cmGlobalGenerator* gg, const std::string& name)
478 479 480 481
{
  std::vector<std::string> namespaces;
  const cmExportSetMap& exportSets = gg->GetExportSets();

482 483
  for (auto const& expIt : exportSets) {
    const cmExportSet* exportSet = expIt.second;
484
    std::vector<cmTargetExport*> const* targets =
485
      exportSet->GetTargetExports();
486 487

    bool containsTarget = false;
488 489
    for (cmTargetExport* target : *targets) {
      if (name == target->TargetName) {
490 491 492
        containsTarget = true;
        break;
      }
493
    }
494

495
    if (containsTarget) {
496
      std::vector<cmInstallExportGenerator const*> const* installs =
497
        exportSet->GetInstallations();
498 499
      for (cmInstallExportGenerator const* install : *installs) {
        namespaces.push_back(install->GetNamespace());
500 501
      }
    }
502
  }
503 504 505 506

  return namespaces;
}

507 508
void cmExportInstallFileGenerator::ComplainAboutMissingTarget(
  cmGeneratorTarget* depender, cmGeneratorTarget* dependee, int occurrences)
509
{
510
  std::ostringstream e;
511
  e << "install(EXPORT \"" << this->IEGen->GetExportSet()->GetName()
512
    << "\" ...) "
513
    << "includes target \"" << depender->GetName()
514
    << "\" which requires target \"" << dependee->GetName() << "\" ";
515
  if (occurrences == 0) {
516
    e << "that is not in the export set.";
517
  } else {
518
    e << "that is not in this export set, but " << occurrences
519 520
      << " times in others.";
  }
521
  cmSystemTools::Error(e.str());
522
}
523

524
std::string cmExportInstallFileGenerator::InstallNameDir(
525
  cmGeneratorTarget* target, const std::string& /*config*/)
526 527 528
{
  std::string install_name_dir;

529
  cmMakefile* mf = target->Target->GetMakefile();
530 531 532
  if (mf->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME")) {
    install_name_dir = target->GetInstallNameDirForInstallTree();
  }
533 534 535

  return install_name_dir;
}