cmNinjaNormalTargetGenerator.cxx 26.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
#include "cmNinjaNormalTargetGenerator.h"
Brad King's avatar
Brad King committed
4

5
#include "cmAlgorithms.h"
6
#include "cmCustomCommand.h"
7
#include "cmCustomCommandGenerator.h"
8
#include "cmGeneratedFileStream.h"
9
10
#include "cmGeneratorTarget.h"
#include "cmGlobalNinjaGenerator.h"
11
#include "cmLinkLineComputer.h"
12
#include "cmLocalGenerator.h"
13
#include "cmLocalNinjaGenerator.h"
14
#include "cmMakefile.h"
15
#include "cmNinjaTypes.h"
16
#include "cmOSXBundleGenerator.h"
17
#include "cmOutputConverter.h"
18
#include "cmSourceFile.h"
19
20
21
#include "cmState.h"
#include "cmSystemTools.h"
#include "cmake.h"
22

23
#include <algorithm>
24
#include <assert.h>
25
#include <iterator>
26
#include <limits>
27
28
29
30
#include <map>
#include <set>
#include <sstream>
#include <stddef.h>
31

32
33
34
35
#ifndef _WIN32
#include <unistd.h>
#endif

36
37
cmNinjaNormalTargetGenerator::cmNinjaNormalTargetGenerator(
  cmGeneratorTarget* target)
38
  : cmNinjaTargetGenerator(target)
39
40
41
42
43
  , TargetNameOut()
  , TargetNameSO()
  , TargetNameReal()
  , TargetNameImport()
  , TargetNamePDB()
44
  , TargetLinkLanguage("")
45
{
46
  this->TargetLinkLanguage = target->GetLinkerLanguage(this->GetConfigName());
47
  if (target->GetType() == cmState::EXECUTABLE) {
48
49
50
    this->GetGeneratorTarget()->GetExecutableNames(
      this->TargetNameOut, this->TargetNameReal, this->TargetNameImport,
      this->TargetNamePDB, GetLocalGenerator()->GetConfigName());
51
  } else {
52
53
54
55
    this->GetGeneratorTarget()->GetLibraryNames(
      this->TargetNameOut, this->TargetNameSO, this->TargetNameReal,
      this->TargetNameImport, this->TargetNamePDB,
      GetLocalGenerator()->GetConfigName());
56
  }
57
58

  if (target->GetType() != cmState::OBJECT_LIBRARY) {
59
60
    // on Windows the output dir is already needed at compile time
    // ensure the directory exists (OutDir test)
61
    EnsureDirectoryExists(target->GetDirectory(this->GetConfigName()));
62
  }
63

64
65
  this->OSXBundleGenerator =
    new cmOSXBundleGenerator(target, this->GetConfigName());
66
  this->OSXBundleGenerator->SetMacContentFolders(&this->MacContentFolders);
67
68
69
70
}

cmNinjaNormalTargetGenerator::~cmNinjaNormalTargetGenerator()
{
71
  delete this->OSXBundleGenerator;
72
73
74
75
}

void cmNinjaNormalTargetGenerator::Generate()
{
76
  if (this->TargetLinkLanguage.empty()) {
77
78
    cmSystemTools::Error("CMake can not determine linker language for "
                         "target: ",
79
                         this->GetGeneratorTarget()->GetName().c_str());
80
81
82
83
84
85
86
87
88
    return;
  }

  // Write the rules for each language.
  this->WriteLanguagesRules();

  // Write the build statements
  this->WriteObjectBuildStatements();

89
  if (this->GetGeneratorTarget()->GetType() == cmState::OBJECT_LIBRARY) {
90
    this->WriteObjectLibStatement();
91
  } else {
92
    this->WriteLinkStatement();
93
  }
94
95
96
97
}

void cmNinjaNormalTargetGenerator::WriteLanguagesRules()
{
98
#ifdef NINJA_GEN_VERBOSE_FILES
99
100
101
  cmGlobalNinjaGenerator::WriteDivider(this->GetRulesFileStream());
  this->GetRulesFileStream()
    << "# Rules for each languages for "
102
    << cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType())
103
    << " target " << this->GetTargetName() << "\n\n";
104
#endif
105

106
  // Write rules for languages compiled in this target.
107
  std::set<std::string> languages;
108
  std::vector<cmSourceFile*> sourceFiles;
109
110
111
112
  this->GetGeneratorTarget()->GetSourceFiles(
    sourceFiles, this->GetMakefile()->GetSafeDefinition("CMAKE_BUILD_TYPE"));
  for (std::vector<cmSourceFile*>::const_iterator i = sourceFiles.begin();
       i != sourceFiles.end(); ++i) {
113
    const std::string& lang = (*i)->GetLanguage();
114
    if (!lang.empty()) {
115
116
      languages.insert(lang);
    }
117
118
119
  }
  for (std::set<std::string>::const_iterator l = languages.begin();
       l != languages.end(); ++l) {
120
    this->WriteLanguageRules(*l);
121
  }
122
123
}

124
const char* cmNinjaNormalTargetGenerator::GetVisibleTypeName() const
125
{
126
  switch (this->GetGeneratorTarget()->GetType()) {
127
    case cmState::STATIC_LIBRARY:
128
      return "static library";
129
    case cmState::SHARED_LIBRARY:
130
      return "shared library";
131
    case cmState::MODULE_LIBRARY:
132
      if (this->GetGeneratorTarget()->IsCFBundleOnApple()) {
133
        return "CFBundle shared module";
134
      } else {
135
        return "shared module";
136
      }
137
    case cmState::EXECUTABLE:
138
139
      return "executable";
    default:
Daniel Pfeifer's avatar
Daniel Pfeifer committed
140
      return CM_NULLPTR;
141
142
143
  }
}

144
std::string cmNinjaNormalTargetGenerator::LanguageLinkerRule() const
145
{
146
147
148
149
  return this->TargetLinkLanguage + "_" +
    cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()) +
    "_LINKER__" + cmGlobalNinjaGenerator::EncodeRuleName(
                    this->GetGeneratorTarget()->GetName());
150
151
}

152
153
154
155
156
157
158
159
struct cmNinjaRemoveNoOpCommands
{
  bool operator()(std::string const& cmd)
  {
    return cmd.empty() || cmd[0] == ':';
  }
};

160
void cmNinjaNormalTargetGenerator::WriteLinkRule(bool useResponseFile)
161
{
162
  cmState::TargetType targetType = this->GetGeneratorTarget()->GetType();
163
164
  std::string ruleName = this->LanguageLinkerRule();

165
166
  // Select whether to use a response file for objects.
  std::string rspfile;
167
  std::string rspcontent;
168
169
170
171

  if (!this->GetGlobalGenerator()->HasRule(ruleName)) {
    cmLocalGenerator::RuleVariables vars;
    vars.RuleLauncher = "RULE_LAUNCH_LINK";
172
    vars.CMTarget = this->GetGeneratorTarget();
173
    vars.Language = this->TargetLinkLanguage.c_str();
174
175
176
177

    std::string responseFlag;
    if (!useResponseFile) {
      vars.Objects = "$in";
178
      vars.LinkLibraries = "$LINK_PATH $LINK_LIBRARIES";
179
    } else {
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
      std::string cmakeVarLang = "CMAKE_";
      cmakeVarLang += this->TargetLinkLanguage;

      // build response file name
      std::string cmakeLinkVar = cmakeVarLang + "_RESPONSE_FILE_LINK_FLAG";
      const char* flag = GetMakefile()->GetDefinition(cmakeLinkVar);
      if (flag) {
        responseFlag = flag;
      } else {
        responseFlag = "@";
      }
      rspfile = "$RSP_FILE";
      responseFlag += rspfile;

      // build response file content
      if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
        rspcontent = "$in";
      } else {
        rspcontent = "$in_newline";
      }
      rspcontent += " $LINK_PATH $LINK_LIBRARIES";
      vars.Objects = responseFlag.c_str();
      vars.LinkLibraries = "";
203
    }
Peter Kuemmel's avatar
Peter Kuemmel committed
204
205

    vars.ObjectDir = "$OBJECT_DIR";
206

207
    vars.Target = "$TARGET_FILE";
208

209
    vars.SONameFlag = "$SONAME_FLAG";
210
211
    vars.TargetSOName = "$SONAME";
    vars.TargetInstallNameDir = "$INSTALLNAME_DIR";
212
    vars.TargetPDB = "$TARGET_PDB";
213
214
215
216
217

    // Setup the target version.
    std::string targetVersionMajor;
    std::string targetVersionMinor;
    {
218
219
220
221
222
223
224
225
226
      std::ostringstream majorStream;
      std::ostringstream minorStream;
      int major;
      int minor;
      this->GetGeneratorTarget()->GetTargetVersion(major, minor);
      majorStream << major;
      minorStream << minor;
      targetVersionMajor = majorStream.str();
      targetVersionMinor = minorStream.str();
227
228
229
230
    }
    vars.TargetVersionMajor = targetVersionMajor.c_str();
    vars.TargetVersionMinor = targetVersionMinor.c_str();

231
    vars.Flags = "$FLAGS";
232
    vars.LinkFlags = "$LINK_FLAGS";
233
    vars.Manifests = "$MANIFESTS";
234
235

    std::string langFlags;
236
    if (targetType != cmState::EXECUTABLE) {
237
      langFlags += "$LANGUAGE_COMPILE_FLAGS $ARCH_FLAGS";
238
      vars.LanguageCompileFlags = langFlags.c_str();
239
    }
240

241
    // Rule for linking library/executable.
242
    std::vector<std::string> linkCmds = this->ComputeLinkCmd();
243
244
    for (std::vector<std::string>::iterator i = linkCmds.begin();
         i != linkCmds.end(); ++i) {
245
      this->GetLocalGenerator()->ExpandRuleVariables(*i, vars);
246
    }
247
248
249
250
251
252
253
    {
      // If there is no ranlib the command will be ":".  Skip it.
      std::vector<std::string>::iterator newEnd = std::remove_if(
        linkCmds.begin(), linkCmds.end(), cmNinjaRemoveNoOpCommands());
      linkCmds.erase(newEnd, linkCmds.end());
    }

254
255
256
257
258
    linkCmds.insert(linkCmds.begin(), "$PRE_LINK");
    linkCmds.push_back("$POST_BUILD");
    std::string linkCmd =
      this->GetLocalGenerator()->BuildCommandLine(linkCmds);

259
    // Write the linker rule with response file if needed.
260
    std::ostringstream comment;
261
262
    comment << "Rule for linking " << this->TargetLinkLanguage << " "
            << this->GetVisibleTypeName() << ".";
263
    std::ostringstream description;
264
    description << "Linking " << this->TargetLinkLanguage << " "
265
                << this->GetVisibleTypeName() << " $TARGET_FILE";
266
    this->GetGlobalGenerator()->AddRule(ruleName, linkCmd, description.str(),
267
268
                                        comment.str(),
                                        /*depfile*/ "",
269
                                        /*deptype*/ "", rspfile, rspcontent,
270
                                        /*restat*/ "$RESTAT",
271
                                        /*generator*/ false);
272
273
  }

274
  if (this->TargetNameOut != this->TargetNameReal &&
275
      !this->GetGeneratorTarget()->IsFrameworkOnApple()) {
276
    std::string cmakeCommand =
277
      this->GetLocalGenerator()->ConvertToOutputFormat(
278
        cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
279
    if (targetType == cmState::EXECUTABLE) {
280
281
282
283
284
285
286
287
288
289
290
291
      this->GetGlobalGenerator()->AddRule(
        "CMAKE_SYMLINK_EXECUTABLE",
        cmakeCommand + " -E cmake_symlink_executable"
                       " $in $out && $POST_BUILD",
        "Creating executable symlink $out", "Rule for creating "
                                            "executable symlink.",
        /*depfile*/ "",
        /*deptype*/ "",
        /*rspfile*/ "",
        /*rspcontent*/ "",
        /*restat*/ "",
        /*generator*/ false);
292
    } else {
293
294
295
296
297
298
299
300
301
302
303
304
      this->GetGlobalGenerator()->AddRule(
        "CMAKE_SYMLINK_LIBRARY",
        cmakeCommand + " -E cmake_symlink_library"
                       " $in $SONAME $out && $POST_BUILD",
        "Creating library symlink $out", "Rule for creating "
                                         "library symlink.",
        /*depfile*/ "",
        /*deptype*/ "",
        /*rspfile*/ "",
        /*rspcontent*/ "",
        /*restat*/ "",
        /*generator*/ false);
305
    }
306
307
308
  }
}

309
std::vector<std::string> cmNinjaNormalTargetGenerator::ComputeLinkCmd()
310
{
311
  std::vector<std::string> linkCmds;
312
313
  cmMakefile* mf = this->GetMakefile();
  {
314
315
316
317
318
    std::string linkCmdVar = this->GetGeneratorTarget()->GetCreateRuleVariable(
      this->TargetLinkLanguage, this->GetConfigName());
    const char* linkCmd = mf->GetDefinition(linkCmdVar);
    if (linkCmd) {
      cmSystemTools::ExpandListArgument(linkCmd, linkCmds);
319
      if (this->GetGeneratorTarget()->GetPropertyAsBool("LINK_WHAT_YOU_USE")) {
320
321
322
323
324
325
326
327
328
329
        std::string cmakeCommand =
          this->GetLocalGenerator()->ConvertToOutputFormat(
            cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
        cmakeCommand += " -E __run_iwyu --lwyu=";
        cmGeneratorTarget& gt = *this->GetGeneratorTarget();
        const std::string cfgName = this->GetConfigName();
        std::string targetOutput = ConvertToNinjaPath(gt.GetFullPath(cfgName));
        std::string targetOutputReal =
          this->ConvertToNinjaPath(gt.GetFullPath(cfgName,
                                                  /*implib=*/false,
330
                                                  /*realname=*/true));
331
332
333
334
        cmakeCommand += targetOutputReal;
        cmakeCommand += " || true";
        linkCmds.push_back(cmakeCommand);
      }
335
      return linkCmds;
336
337
    }
  }
338
  switch (this->GetGeneratorTarget()->GetType()) {
339
    case cmState::STATIC_LIBRARY: {
340
      // We have archive link commands set. First, delete the existing archive.
341
      {
342
343
        std::string cmakeCommand =
          this->GetLocalGenerator()->ConvertToOutputFormat(
344
            cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
345
        linkCmds.push_back(cmakeCommand + " -E remove $TARGET_FILE");
346
      }
347
348
      // TODO: Use ARCHIVE_APPEND for archives over a certain size.
      {
349
350
351
352
353
        std::string linkCmdVar = "CMAKE_";
        linkCmdVar += this->TargetLinkLanguage;
        linkCmdVar += "_ARCHIVE_CREATE";
        const char* linkCmd = mf->GetRequiredDefinition(linkCmdVar);
        cmSystemTools::ExpandListArgument(linkCmd, linkCmds);
354
355
      }
      {
356
357
358
359
360
        std::string linkCmdVar = "CMAKE_";
        linkCmdVar += this->TargetLinkLanguage;
        linkCmdVar += "_ARCHIVE_FINISH";
        const char* linkCmd = mf->GetRequiredDefinition(linkCmdVar);
        cmSystemTools::ExpandListArgument(linkCmd, linkCmds);
361
362
363
      }
      return linkCmds;
    }
364
365
366
    case cmState::SHARED_LIBRARY:
    case cmState::MODULE_LIBRARY:
    case cmState::EXECUTABLE:
367
      break;
368
369
370
    default:
      assert(0 && "Unexpected target type");
  }
371
  return std::vector<std::string>();
372
373
}

374
static int calculateCommandLineLengthLimit(int linkRuleLength)
375
{
376
  static int const limits[] = {
377
#ifdef _WIN32
378
    8000,
379
#endif
380
#if defined(_SC_ARG_MAX)
381
382
383
384
385
386
387
388
389
390
391
392
    // for instance ARG_MAX is 2096152 on Ubuntu or 262144 on Mac
    ((int)sysconf(_SC_ARG_MAX)) - 1000,
#endif
#if defined(__linux)
    // #define MAX_ARG_STRLEN (PAGE_SIZE * 32) in Linux's binfmts.h
    ((int)sysconf(_SC_PAGESIZE) * 32) - 1000,
#endif
    std::numeric_limits<int>::max()
  };

  size_t const arrSz = cmArraySize(limits);
  int const sz = *std::min_element(limits, limits + arrSz);
393
  if (sz == std::numeric_limits<int>::max()) {
394
    return 0;
395
  }
396
397

  return sz - linkRuleLength;
398
399
400
401
}

void cmNinjaNormalTargetGenerator::WriteLinkStatement()
{
402
  cmGeneratorTarget& gt = *this->GetGeneratorTarget();
403
  const std::string cfgName = this->GetConfigName();
404
405
406
  std::string targetOutput = ConvertToNinjaPath(gt.GetFullPath(cfgName));
  std::string targetOutputReal =
    ConvertToNinjaPath(gt.GetFullPath(cfgName,
407
                                      /*implib=*/false,
408
                                      /*realname=*/true));
409
410
411
  std::string targetOutputImplib =
    ConvertToNinjaPath(gt.GetFullPath(cfgName,
                                      /*implib=*/true));
412

413
  if (gt.IsAppBundleOnApple()) {
414
    // Create the app bundle
415
    std::string outpath = gt.GetDirectory(cfgName);
416
    this->OSXBundleGenerator->CreateAppBundle(this->TargetNameOut, outpath);
417
418

    // Calculate the output path
419
420
421
    targetOutput = outpath;
    targetOutput += "/";
    targetOutput += this->TargetNameOut;
422
    targetOutput = this->ConvertToNinjaPath(targetOutput);
423
424
425
    targetOutputReal = outpath;
    targetOutputReal += "/";
    targetOutputReal += this->TargetNameReal;
426
    targetOutputReal = this->ConvertToNinjaPath(targetOutputReal);
427
  } else if (gt.IsFrameworkOnApple()) {
428
    // Create the library framework.
429
    this->OSXBundleGenerator->CreateFramework(this->TargetNameOut,
430
                                              gt.GetDirectory(cfgName));
431
  } else if (gt.IsCFBundleOnApple()) {
432
    // Create the core foundation bundle.
433
    this->OSXBundleGenerator->CreateCFBundle(this->TargetNameOut,
434
                                             gt.GetDirectory(cfgName));
435
  }
436

437
438
  // Write comments.
  cmGlobalNinjaGenerator::WriteDivider(this->GetBuildFileStream());
439
  const cmState::TargetType targetType = gt.GetType();
440
441
442
  this->GetBuildFileStream() << "# Link build statements for "
                             << cmState::GetTargetTypeName(targetType)
                             << " target " << this->GetTargetName() << "\n\n";
443
444
445
446
447

  cmNinjaDeps emptyDeps;
  cmNinjaVars vars;

  // Compute the comment.
448
  std::ostringstream comment;
449
450
  comment << "Link the " << this->GetVisibleTypeName() << " "
          << targetOutputReal;
451
452
453
454
455
456

  // Compute outputs.
  cmNinjaDeps outputs;
  outputs.push_back(targetOutputReal);

  // Compute specific libraries to link with.
457
458
  cmNinjaDeps explicitDeps = this->GetObjects();
  cmNinjaDeps implicitDeps = this->ComputeLinkDeps();
459

460
461
  cmMakefile* mf = this->GetMakefile();

462
463
  std::string frameworkPath;
  std::string linkPath;
464
  cmGeneratorTarget& genTarget = *this->GetGeneratorTarget();
465

466
467
468
  std::string createRule = genTarget.GetCreateRuleVariable(
    this->TargetLinkLanguage, this->GetConfigName());
  bool useWatcomQuote = mf->IsOn(createRule + "_USE_WATCOM_QUOTE");
469
  cmLocalNinjaGenerator& localGen = *this->GetLocalGenerator();
470
471

  vars["TARGET_FILE"] =
472
    localGen.ConvertToOutputFormat(targetOutputReal, cmOutputConverter::SHELL);
473

474
475
  CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer(
    this->GetGlobalGenerator()->CreateLinkLineComputer(
476
477
      this->GetLocalGenerator(),
      this->GetLocalGenerator()->GetStateSnapshot().GetDirectory()));
478
  linkLineComputer->SetUseWatcomQuote(useWatcomQuote);
479

480
481
482
  localGen.GetTargetFlags(
    linkLineComputer.get(), this->GetConfigName(), vars["LINK_LIBRARIES"],
    vars["FLAGS"], vars["LINK_FLAGS"], frameworkPath, linkPath, &genTarget);
483
  if (this->GetMakefile()->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS") &&
484
485
      (gt.GetType() == cmState::SHARED_LIBRARY ||
       gt.IsExecutableWithExports())) {
486
487
    if (gt.GetPropertyAsBool("WINDOWS_EXPORT_ALL_SYMBOLS")) {
      std::string name_of_def_file = gt.GetSupportDirectory();
488
      name_of_def_file += "/" + gt.GetName();
489
490
      name_of_def_file += ".def ";
      vars["LINK_FLAGS"] += " /DEF:";
491
      vars["LINK_FLAGS"] += this->GetLocalGenerator()->ConvertToOutputFormat(
492
        name_of_def_file, cmOutputConverter::SHELL);
493
    }
494
  }
495

496
  // Add OS X version flags, if any.
497
498
  if (this->GeneratorTarget->GetType() == cmState::SHARED_LIBRARY ||
      this->GeneratorTarget->GetType() == cmState::MODULE_LIBRARY) {
499
500
501
502
    this->AppendOSXVerFlag(vars["LINK_FLAGS"], this->TargetLinkLanguage,
                           "COMPATIBILITY", true);
    this->AppendOSXVerFlag(vars["LINK_FLAGS"], this->TargetLinkLanguage,
                           "CURRENT", false);
503
  }
504

505
  this->addPoolNinjaVariable("JOB_POOL_LINK", &gt, vars);
506

507
  this->AddModuleDefinitionFlag(linkLineComputer.get(), vars["LINK_FLAGS"]);
508
509
  vars["LINK_FLAGS"] =
    cmGlobalNinjaGenerator::EncodeLiteral(vars["LINK_FLAGS"]);
510

511
512
  vars["MANIFESTS"] = this->GetManifests();

513
  vars["LINK_PATH"] = frameworkPath + linkPath;
514
  std::string lwyuFlags;
515
  if (genTarget.GetPropertyAsBool("LINK_WHAT_YOU_USE")) {
516
517
    lwyuFlags = " -Wl,--no-as-needed";
  }
518

519
520
521
  // Compute architecture specific link flags.  Yes, these go into a different
  // variable for executables, probably due to a mistake made when duplicating
  // code between the Makefile executable and library generators.
522
  if (targetType == cmState::EXECUTABLE) {
523
524
    std::string t = vars["FLAGS"];
    localGen.AddArchitectureFlags(t, &genTarget, TargetLinkLanguage, cfgName);
525
    t += lwyuFlags;
526
    vars["FLAGS"] = t;
527
  } else {
528
529
530
531
    std::string t = vars["ARCH_FLAGS"];
    localGen.AddArchitectureFlags(t, &genTarget, TargetLinkLanguage, cfgName);
    vars["ARCH_FLAGS"] = t;
    t = "";
532
    t += lwyuFlags;
533
534
    localGen.AddLanguageFlags(t, TargetLinkLanguage, cfgName);
    vars["LANGUAGE_COMPILE_FLAGS"] = t;
535
536
  }
  if (this->GetGeneratorTarget()->HasSOName(cfgName)) {
537
    vars["SONAME_FLAG"] = mf->GetSONameFlag(this->TargetLinkLanguage);
538
    vars["SONAME"] = this->TargetNameSO;
539
    if (targetType == cmState::SHARED_LIBRARY) {
540
      std::string install_dir =
541
542
        this->GetGeneratorTarget()->GetInstallNameDirForBuildTree(cfgName);
      if (!install_dir.empty()) {
543
544
        vars["INSTALLNAME_DIR"] = localGen.ConvertToOutputFormat(
          install_dir, cmOutputConverter::SHELL);
545
      }
546
    }
547
  }
548

549
550
  cmNinjaDeps byproducts;

551
  if (!this->TargetNameImport.empty()) {
552
    const std::string impLibPath = localGen.ConvertToOutputFormat(
553
      targetOutputImplib, cmOutputConverter::SHELL);
554
555
    vars["TARGET_IMPLIB"] = impLibPath;
    EnsureParentDirectoryExists(impLibPath);
556
    if (genTarget.HasImportLibrary()) {
557
      byproducts.push_back(targetOutputImplib);
558
    }
559
  }
560

561
  if (!this->SetMsvcTargetPdbVariable(vars)) {
562
563
    // It is common to place debug symbols at a specific place,
    // so we need a plain target name in the rule available.
564
    std::string prefix;
565
566
    std::string base;
    std::string suffix;
567
    this->GetGeneratorTarget()->GetFullNameComponents(prefix, base, suffix);
568
569
    std::string dbg_suffix = ".dbg";
    // TODO: Where to document?
570
    if (mf->GetDefinition("CMAKE_DEBUG_SYMBOL_SUFFIX")) {
571
      dbg_suffix = mf->GetDefinition("CMAKE_DEBUG_SYMBOL_SUFFIX");
572
    }
573
574
    vars["TARGET_PDB"] = base + suffix + dbg_suffix;
  }
Peter Kuemmel's avatar
Peter Kuemmel committed
575

576
  const std::string objPath = GetGeneratorTarget()->GetSupportDirectory();
577
  vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
578
    this->ConvertToNinjaPath(objPath), cmOutputConverter::SHELL);
579
580
  EnsureDirectoryExists(objPath);

581
  if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
582
    // ar.exe can't handle backslashes in rsp files (implicitly used by gcc)
583
584
    std::string& linkLibraries = vars["LINK_LIBRARIES"];
    std::replace(linkLibraries.begin(), linkLibraries.end(), '\\', '/');
585
586
    std::string& link_path = vars["LINK_PATH"];
    std::replace(link_path.begin(), link_path.end(), '\\', '/');
587
  }
588

589
590
  const std::vector<cmCustomCommand>* cmdLists[3] = {
    &gt.GetPreBuildCommands(), &gt.GetPreLinkCommands(),
591
    &gt.GetPostBuildCommands()
592
593
594
  };

  std::vector<std::string> preLinkCmdLines, postBuildCmdLines;
595
596
597
598
599
600
601
602
  std::vector<std::string>* cmdLineLists[3] = { &preLinkCmdLines,
                                                &preLinkCmdLines,
                                                &postBuildCmdLines };

  for (unsigned i = 0; i != 3; ++i) {
    for (std::vector<cmCustomCommand>::const_iterator ci =
           cmdLists[i]->begin();
         ci != cmdLists[i]->end(); ++ci) {
603
      cmCustomCommandGenerator ccg(*ci, cfgName, this->GetLocalGenerator());
604
      localGen.AppendCustomCommandLines(ccg, *cmdLineLists[i]);
605
606
607
      std::vector<std::string> const& ccByproducts = ccg.GetByproducts();
      std::transform(ccByproducts.begin(), ccByproducts.end(),
                     std::back_inserter(byproducts), MapToNinjaPath());
608
    }
609
  }
610

611
  // maybe create .def file from list of objects
612
613
  if ((gt.GetType() == cmState::SHARED_LIBRARY ||
       gt.IsExecutableWithExports()) &&
614
615
      this->GetMakefile()->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS")) {
    if (gt.GetPropertyAsBool("WINDOWS_EXPORT_ALL_SYMBOLS")) {
616
      std::string cmakeCommand =
617
        this->GetLocalGenerator()->ConvertToOutputFormat(
618
          cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
619
      std::string name_of_def_file = gt.GetSupportDirectory();
620
      name_of_def_file += "/" + gt.GetName();
621
622
623
      name_of_def_file += ".def";
      std::string cmd = cmakeCommand;
      cmd += " -E __create_def ";
624
      cmd += this->GetLocalGenerator()->ConvertToOutputFormat(
625
        name_of_def_file, cmOutputConverter::SHELL);
626
627
628
629
      cmd += " ";
      cmNinjaDeps objs = this->GetObjects();
      std::string obj_list_file = name_of_def_file;
      obj_list_file += ".objs";
630
      cmd += this->GetLocalGenerator()->ConvertToOutputFormat(
631
        obj_list_file, cmOutputConverter::SHELL);
632
633
634
      preLinkCmdLines.push_back(cmd);
      // create a list of obj files for the -E __create_def to read
      cmGeneratedFileStream fout(obj_list_file.c_str());
635
636
      for (cmNinjaDeps::iterator i = objs.begin(); i != objs.end(); ++i) {
        if (cmHasLiteralSuffix(*i, ".obj")) {
637
638
639
640
          fout << *i << "\n";
        }
      }
    }
641
  }
642
643
  // If we have any PRE_LINK commands, we need to go back to CMAKE_BINARY_DIR
  // for
644
  // the link commands.
645
  if (!preLinkCmdLines.empty()) {
646
    const std::string homeOutDir = localGen.ConvertToOutputFormat(
647
      localGen.GetBinaryDirectory(), cmOutputConverter::SHELL);
648
    preLinkCmdLines.push_back("cd " + homeOutDir);
649
  }
650

651
652
  vars["PRE_LINK"] = localGen.BuildCommandLine(preLinkCmdLines);
  std::string postBuildCmdLine = localGen.BuildCommandLine(postBuildCmdLines);
653
654

  cmNinjaVars symlinkVars;
655
656
657
  bool const symlinkNeeded =
    (targetOutput != targetOutputReal && !gt.IsFrameworkOnApple());
  if (!symlinkNeeded) {
658
    vars["POST_BUILD"] = postBuildCmdLine;
659
  } else {
660
661
    vars["POST_BUILD"] = ":";
    symlinkVars["POST_BUILD"] = postBuildCmdLine;
662
  }
663
  cmGlobalNinjaGenerator& globalGen = *this->GetGlobalGenerator();
664

665
  int commandLineLengthLimit = -1;
666
  if (!this->ForceResponseFile()) {
667
    commandLineLengthLimit = calculateCommandLineLengthLimit(
668
669
      globalGen.GetRuleCmdLength(this->LanguageLinkerRule()));
  }
670

671
  const std::string rspfile =
672
673
    std::string(cmake::GetCMakeFilesDirectoryPostSlash()) + gt.GetName() +
    ".rsp";
674

675
676
  // Gather order-only dependencies.
  cmNinjaDeps orderOnlyDeps;
677
  this->GetLocalGenerator()->AppendTargetDepends(this->GetGeneratorTarget(),
678
                                                 orderOnlyDeps);
679

680
  // Ninja should restat after linking if and only if there are byproducts.
681
  vars["RESTAT"] = byproducts.empty() ? "" : "1";
682
683

  for (cmNinjaDeps::const_iterator oi = byproducts.begin(),
684
685
                                   oe = byproducts.end();
       oi != oe; ++oi) {
686
687
    this->GetGlobalGenerator()->SeenCustomCommandOutput(*oi);
    outputs.push_back(*oi);
688
  }
689

690
  // Write the build statement for this target.
691
  bool usedResponseFile = false;
692
  globalGen.WriteBuild(this->GetBuildFileStream(), comment.str(),
693
694
                       this->LanguageLinkerRule(), outputs,
                       /*implicitOuts=*/cmNinjaDeps(), explicitDeps,
695
696
                       implicitDeps, orderOnlyDeps, vars, rspfile,
                       commandLineLengthLimit, &usedResponseFile);
697
  this->WriteLinkRule(usedResponseFile);
698

699
  if (symlinkNeeded) {
700
701
702
703
704
    if (targetType == cmState::EXECUTABLE) {
      globalGen.WriteBuild(
        this->GetBuildFileStream(),
        "Create executable symlink " + targetOutput,
        "CMAKE_SYMLINK_EXECUTABLE", cmNinjaDeps(1, targetOutput),
705
706
        /*implicitOuts=*/cmNinjaDeps(), cmNinjaDeps(1, targetOutputReal),
        emptyDeps, emptyDeps, symlinkVars);
707
    } else {
708
      cmNinjaDeps symlinks;
709
710
      std::string const soName =
        this->ConvertToNinjaPath(this->GetTargetFilePath(this->TargetNameSO));
711
      // If one link has to be created.
712
      if (targetOutputReal == soName || targetOutput == soName) {
713
        symlinkVars["SONAME"] = soName;
714
      } else {
715
        symlinkVars["SONAME"] = "";
716
        symlinks.push_back(soName);
717
      }
718
719
720
      symlinks.push_back(targetOutput);
      globalGen.WriteBuild(
        this->GetBuildFileStream(), "Create library symlink " + targetOutput,
721
722
        "CMAKE_SYMLINK_LIBRARY", symlinks,
        /*implicitOuts=*/cmNinjaDeps(), cmNinjaDeps(1, targetOutputReal),
723
        emptyDeps, emptyDeps, symlinkVars);
724
    }
725
  }
726

727
  // Add aliases for the file name and the target name.
728
729
  globalGen.AddTargetAlias(this->TargetNameOut, &gt);
  globalGen.AddTargetAlias(this->GetTargetName(), &gt);
730
}
731
732
733
734
735

void cmNinjaNormalTargetGenerator::WriteObjectLibStatement()
{
  // Write a phony output that depends on all object files.
  cmNinjaDeps outputs;
736
737
  this->GetLocalGenerator()->AppendTargetOutputs(this->GetGeneratorTarget(),
                                                 outputs);
738
  cmNinjaDeps depends = this->GetObjects();
739
740
741
  this->GetGlobalGenerator()->WritePhonyBuild(
    this->GetBuildFileStream(), "Object library " + this->GetTargetName(),
    outputs, depends);
742
743
744

  // Add aliases for the target name.
  this->GetGlobalGenerator()->AddTargetAlias(this->GetTargetName(),
745
                                             this->GetGeneratorTarget());
746
}