cmNinjaNormalTargetGenerator.cxx 26.3 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 "cmLocalGenerator.h"
12
#include "cmLocalNinjaGenerator.h"
13
#include "cmMakefile.h"
14
#include "cmNinjaTypes.h"
15
#include "cmOSXBundleGenerator.h"
16
#include "cmOutputConverter.h"
17
#include "cmSourceFile.h"
18
19
20
#include "cmState.h"
#include "cmSystemTools.h"
#include "cmake.h"
21

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    std::string responseFlag;
    if (!useResponseFile) {
      vars.Objects = "$in";
177
      vars.LinkLibraries = "$LINK_PATH $LINK_LIBRARIES";
178
    } else {
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
      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 = "";
202
    }
Peter Kuemmel's avatar
Peter Kuemmel committed
203
204

    vars.ObjectDir = "$OBJECT_DIR";
205

206
    vars.Target = "$TARGET_FILE";
207

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

    // Setup the target version.
    std::string targetVersionMajor;
    std::string targetVersionMinor;
    {
217
218
219
220
221
222
223
224
225
      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();
226
227
228
229
    }
    vars.TargetVersionMajor = targetVersionMajor.c_str();
    vars.TargetVersionMinor = targetVersionMinor.c_str();

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

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

240
    // Rule for linking library/executable.
241
    std::vector<std::string> linkCmds = this->ComputeLinkCmd();
242
243
    for (std::vector<std::string>::iterator i = linkCmds.begin();
         i != linkCmds.end(); ++i) {
244
      this->GetLocalGenerator()->ExpandRuleVariables(*i, vars);
245
    }
246
247
248
249
250
251
252
    {
      // 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());
    }

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

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

273
  if (this->TargetNameOut != this->TargetNameReal &&
274
      !this->GetGeneratorTarget()->IsFrameworkOnApple()) {
275
    std::string cmakeCommand =
276
      this->GetLocalGenerator()->ConvertToOutputFormat(
277
        cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
278
    if (targetType == cmState::EXECUTABLE) {
279
280
281
282
283
284
285
286
287
288
289
290
      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);
291
    } else {
292
293
294
295
296
297
298
299
300
301
302
303
      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);
304
    }
305
306
307
  }
}

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

373
static int calculateCommandLineLengthLimit(int linkRuleLength)
374
{
375
  static int const limits[] = {
376
#ifdef _WIN32
377
    8000,
378
#endif
379
#if defined(_SC_ARG_MAX)
380
381
382
383
384
385
386
387
388
389
390
391
    // 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);
392
  if (sz == std::numeric_limits<int>::max()) {
393
    return 0;
394
  }
395
396

  return sz - linkRuleLength;
397
398
399
400
}

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

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

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

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

  cmNinjaDeps emptyDeps;
  cmNinjaVars vars;

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

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

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

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

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

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

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

473
474
475
  localGen.GetTargetFlags(this->GetConfigName(), vars["LINK_LIBRARIES"],
                          vars["FLAGS"], vars["LINK_FLAGS"], frameworkPath,
                          linkPath, &genTarget, useWatcomQuote);
476
  if (this->GetMakefile()->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS") &&
477
478
      (gt.GetType() == cmState::SHARED_LIBRARY ||
       gt.IsExecutableWithExports())) {
479
480
    if (gt.GetPropertyAsBool("WINDOWS_EXPORT_ALL_SYMBOLS")) {
      std::string name_of_def_file = gt.GetSupportDirectory();
481
      name_of_def_file += "/" + gt.GetName();
482
483
      name_of_def_file += ".def ";
      vars["LINK_FLAGS"] += " /DEF:";
484
      vars["LINK_FLAGS"] += this->GetLocalGenerator()->ConvertToOutputFormat(
485
        name_of_def_file, cmOutputConverter::SHELL);
486
    }
487
  }
488

489
  // Add OS X version flags, if any.
490
491
  if (this->GeneratorTarget->GetType() == cmState::SHARED_LIBRARY ||
      this->GeneratorTarget->GetType() == cmState::MODULE_LIBRARY) {
492
493
494
495
    this->AppendOSXVerFlag(vars["LINK_FLAGS"], this->TargetLinkLanguage,
                           "COMPATIBILITY", true);
    this->AppendOSXVerFlag(vars["LINK_FLAGS"], this->TargetLinkLanguage,
                           "CURRENT", false);
496
  }
497

498
  this->addPoolNinjaVariable("JOB_POOL_LINK", &gt, vars);
499

500
  this->AddModuleDefinitionFlag(vars["LINK_FLAGS"]);
501
502
  vars["LINK_FLAGS"] =
    cmGlobalNinjaGenerator::EncodeLiteral(vars["LINK_FLAGS"]);
503

504
505
  vars["MANIFESTS"] = this->GetManifests();

506
  vars["LINK_PATH"] = frameworkPath + linkPath;
507
  std::string lwyuFlags;
508
  if (genTarget.GetPropertyAsBool("LINK_WHAT_YOU_USE")) {
509
510
    lwyuFlags = " -Wl,--no-as-needed";
  }
511

512
513
514
  // 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.
515
  if (targetType == cmState::EXECUTABLE) {
516
517
    std::string t = vars["FLAGS"];
    localGen.AddArchitectureFlags(t, &genTarget, TargetLinkLanguage, cfgName);
518
    t += lwyuFlags;
519
    vars["FLAGS"] = t;
520
  } else {
521
522
523
524
    std::string t = vars["ARCH_FLAGS"];
    localGen.AddArchitectureFlags(t, &genTarget, TargetLinkLanguage, cfgName);
    vars["ARCH_FLAGS"] = t;
    t = "";
525
    t += lwyuFlags;
526
527
    localGen.AddLanguageFlags(t, TargetLinkLanguage, cfgName);
    vars["LANGUAGE_COMPILE_FLAGS"] = t;
528
529
  }
  if (this->GetGeneratorTarget()->HasSOName(cfgName)) {
530
    vars["SONAME_FLAG"] = mf->GetSONameFlag(this->TargetLinkLanguage);
531
    vars["SONAME"] = this->TargetNameSO;
532
    if (targetType == cmState::SHARED_LIBRARY) {
533
      std::string install_dir =
534
535
        this->GetGeneratorTarget()->GetInstallNameDirForBuildTree(cfgName);
      if (!install_dir.empty()) {
536
537
        vars["INSTALLNAME_DIR"] = localGen.ConvertToOutputFormat(
          install_dir, cmOutputConverter::SHELL);
538
      }
539
    }
540
  }
541

542
543
  cmNinjaDeps byproducts;

544
  if (!this->TargetNameImport.empty()) {
545
    const std::string impLibPath = localGen.ConvertToOutputFormat(
546
      targetOutputImplib, cmOutputConverter::SHELL);
547
548
    vars["TARGET_IMPLIB"] = impLibPath;
    EnsureParentDirectoryExists(impLibPath);
549
    if (genTarget.HasImportLibrary()) {
550
      byproducts.push_back(targetOutputImplib);
551
    }
552
  }
553

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

569
  const std::string objPath = GetGeneratorTarget()->GetSupportDirectory();
570
  vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
571
    this->ConvertToNinjaPath(objPath), cmOutputConverter::SHELL);
572
573
  EnsureDirectoryExists(objPath);

574
  if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
575
    // ar.exe can't handle backslashes in rsp files (implicitly used by gcc)
576
577
    std::string& linkLibraries = vars["LINK_LIBRARIES"];
    std::replace(linkLibraries.begin(), linkLibraries.end(), '\\', '/');
578
579
    std::string& link_path = vars["LINK_PATH"];
    std::replace(link_path.begin(), link_path.end(), '\\', '/');
580
  }
581

582
583
  const std::vector<cmCustomCommand>* cmdLists[3] = {
    &gt.GetPreBuildCommands(), &gt.GetPreLinkCommands(),
584
    &gt.GetPostBuildCommands()
585
586
587
  };

  std::vector<std::string> preLinkCmdLines, postBuildCmdLines;
588
589
590
591
592
593
594
595
  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) {
596
      cmCustomCommandGenerator ccg(*ci, cfgName, this->GetLocalGenerator());
597
      localGen.AppendCustomCommandLines(ccg, *cmdLineLists[i]);
598
599
600
      std::vector<std::string> const& ccByproducts = ccg.GetByproducts();
      std::transform(ccByproducts.begin(), ccByproducts.end(),
                     std::back_inserter(byproducts), MapToNinjaPath());
601
    }
602
  }
603

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

644
645
  vars["PRE_LINK"] = localGen.BuildCommandLine(preLinkCmdLines);
  std::string postBuildCmdLine = localGen.BuildCommandLine(postBuildCmdLines);
646
647

  cmNinjaVars symlinkVars;
648
  if (targetOutput == targetOutputReal) {
649
    vars["POST_BUILD"] = postBuildCmdLine;
650
  } else {
651
652
    vars["POST_BUILD"] = ":";
    symlinkVars["POST_BUILD"] = postBuildCmdLine;
653
  }
654
  cmGlobalNinjaGenerator& globalGen = *this->GetGlobalGenerator();
655

656
  int commandLineLengthLimit = -1;
657
  if (!this->ForceResponseFile()) {
658
    commandLineLengthLimit = calculateCommandLineLengthLimit(
659
660
      globalGen.GetRuleCmdLength(this->LanguageLinkerRule()));
  }
661

662
  const std::string rspfile =
663
664
    std::string(cmake::GetCMakeFilesDirectoryPostSlash()) + gt.GetName() +
    ".rsp";
665

666
667
  // Gather order-only dependencies.
  cmNinjaDeps orderOnlyDeps;
668
  this->GetLocalGenerator()->AppendTargetDepends(this->GetGeneratorTarget(),
669
                                                 orderOnlyDeps);
670

671
  // Ninja should restat after linking if and only if there are byproducts.
672
  vars["RESTAT"] = byproducts.empty() ? "" : "1";
673
674

  for (cmNinjaDeps::const_iterator oi = byproducts.begin(),
675
676
                                   oe = byproducts.end();
       oi != oe; ++oi) {
677
678
    this->GetGlobalGenerator()->SeenCustomCommandOutput(*oi);
    outputs.push_back(*oi);
679
  }
680

681
  // Write the build statement for this target.
682
  bool usedResponseFile = false;
683
  globalGen.WriteBuild(this->GetBuildFileStream(), comment.str(),
684
685
                       this->LanguageLinkerRule(), outputs,
                       /*implicitOuts=*/cmNinjaDeps(), explicitDeps,
686
687
                       implicitDeps, orderOnlyDeps, vars, rspfile,
                       commandLineLengthLimit, &usedResponseFile);
688
  this->WriteLinkRule(usedResponseFile);
689

690
691
692
693
694
695
  if (targetOutput != targetOutputReal && !gt.IsFrameworkOnApple()) {
    if (targetType == cmState::EXECUTABLE) {
      globalGen.WriteBuild(
        this->GetBuildFileStream(),
        "Create executable symlink " + targetOutput,
        "CMAKE_SYMLINK_EXECUTABLE", cmNinjaDeps(1, targetOutput),
696
697
        /*implicitOuts=*/cmNinjaDeps(), cmNinjaDeps(1, targetOutputReal),
        emptyDeps, emptyDeps, symlinkVars);
698
    } else {
699
      cmNinjaDeps symlinks;
700
701
      std::string const soName =
        this->ConvertToNinjaPath(this->GetTargetFilePath(this->TargetNameSO));
702
      // If one link has to be created.
703
      if (targetOutputReal == soName || targetOutput == soName) {
704
        symlinkVars["SONAME"] = soName;
705
      } else {
706
        symlinkVars["SONAME"] = "";
707
        symlinks.push_back(soName);
708
      }
709
710
711
      symlinks.push_back(targetOutput);
      globalGen.WriteBuild(
        this->GetBuildFileStream(), "Create library symlink " + targetOutput,
712
713
        "CMAKE_SYMLINK_LIBRARY", symlinks,
        /*implicitOuts=*/cmNinjaDeps(), cmNinjaDeps(1, targetOutputReal),
714
        emptyDeps, emptyDeps, symlinkVars);
715
    }
716
  }
717

718
  // Add aliases for the file name and the target name.
719
720
  globalGen.AddTargetAlias(this->TargetNameOut, &gt);
  globalGen.AddTargetAlias(this->GetTargetName(), &gt);
721
}
722
723
724
725
726

void cmNinjaNormalTargetGenerator::WriteObjectLibStatement()
{
  // Write a phony output that depends on all object files.
  cmNinjaDeps outputs;
727
728
  this->GetLocalGenerator()->AppendTargetOutputs(this->GetGeneratorTarget(),
                                                 outputs);
729
  cmNinjaDeps depends = this->GetObjects();
730
731
732
  this->GetGlobalGenerator()->WritePhonyBuild(
    this->GetBuildFileStream(), "Object library " + this->GetTargetName(),
    outputs, depends);
733
734
735

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