cmNinjaNormalTargetGenerator.cxx 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmNinjaNormalTargetGenerator.h"
  4. #include "cmAlgorithms.h"
  5. #include "cmCustomCommand.h"
  6. #include "cmCustomCommandGenerator.h"
  7. #include "cmGeneratedFileStream.h"
  8. #include "cmGeneratorTarget.h"
  9. #include "cmGlobalNinjaGenerator.h"
  10. #include "cmLinkLineComputer.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 "cmRulePlaceholderExpander.h"
  18. #include "cmSourceFile.h"
  19. #include "cmState.h"
  20. #include "cmStateTypes.h"
  21. #include "cmSystemTools.h"
  22. #include "cmake.h"
  23. #include <algorithm>
  24. #include <assert.h>
  25. #include <iterator>
  26. #include <limits>
  27. #include <map>
  28. #include <set>
  29. #include <sstream>
  30. #include <stddef.h>
  31. #ifndef _WIN32
  32. #include <unistd.h>
  33. #endif
  34. cmNinjaNormalTargetGenerator::cmNinjaNormalTargetGenerator(
  35. cmGeneratorTarget* target)
  36. : cmNinjaTargetGenerator(target)
  37. , TargetNameOut()
  38. , TargetNameSO()
  39. , TargetNameReal()
  40. , TargetNameImport()
  41. , TargetNamePDB()
  42. , TargetLinkLanguage("")
  43. {
  44. this->TargetLinkLanguage = target->GetLinkerLanguage(this->GetConfigName());
  45. if (target->GetType() == cmStateEnums::EXECUTABLE) {
  46. this->GetGeneratorTarget()->GetExecutableNames(
  47. this->TargetNameOut, this->TargetNameReal, this->TargetNameImport,
  48. this->TargetNamePDB, GetLocalGenerator()->GetConfigName());
  49. } else {
  50. this->GetGeneratorTarget()->GetLibraryNames(
  51. this->TargetNameOut, this->TargetNameSO, this->TargetNameReal,
  52. this->TargetNameImport, this->TargetNamePDB,
  53. GetLocalGenerator()->GetConfigName());
  54. }
  55. if (target->GetType() != cmStateEnums::OBJECT_LIBRARY) {
  56. // on Windows the output dir is already needed at compile time
  57. // ensure the directory exists (OutDir test)
  58. EnsureDirectoryExists(target->GetDirectory(this->GetConfigName()));
  59. }
  60. this->OSXBundleGenerator =
  61. new cmOSXBundleGenerator(target, this->GetConfigName());
  62. this->OSXBundleGenerator->SetMacContentFolders(&this->MacContentFolders);
  63. }
  64. cmNinjaNormalTargetGenerator::~cmNinjaNormalTargetGenerator()
  65. {
  66. delete this->OSXBundleGenerator;
  67. }
  68. void cmNinjaNormalTargetGenerator::Generate()
  69. {
  70. if (this->TargetLinkLanguage.empty()) {
  71. cmSystemTools::Error("CMake can not determine linker language for "
  72. "target: ",
  73. this->GetGeneratorTarget()->GetName().c_str());
  74. return;
  75. }
  76. // Write the rules for each language.
  77. this->WriteLanguagesRules();
  78. // Write the build statements
  79. this->WriteObjectBuildStatements();
  80. if (this->GetGeneratorTarget()->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  81. this->WriteObjectLibStatement();
  82. } else {
  83. this->WriteLinkStatement();
  84. }
  85. }
  86. void cmNinjaNormalTargetGenerator::WriteLanguagesRules()
  87. {
  88. #ifdef NINJA_GEN_VERBOSE_FILES
  89. cmGlobalNinjaGenerator::WriteDivider(this->GetRulesFileStream());
  90. this->GetRulesFileStream()
  91. << "# Rules for each languages for "
  92. << cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType())
  93. << " target " << this->GetTargetName() << "\n\n";
  94. #endif
  95. // Write rules for languages compiled in this target.
  96. std::set<std::string> languages;
  97. std::vector<cmSourceFile const*> sourceFiles;
  98. this->GetGeneratorTarget()->GetObjectSources(
  99. sourceFiles, this->GetMakefile()->GetSafeDefinition("CMAKE_BUILD_TYPE"));
  100. for (std::vector<cmSourceFile const*>::const_iterator i =
  101. sourceFiles.begin();
  102. i != sourceFiles.end(); ++i) {
  103. const std::string& lang = (*i)->GetLanguage();
  104. if (!lang.empty()) {
  105. languages.insert(lang);
  106. }
  107. }
  108. for (std::set<std::string>::const_iterator l = languages.begin();
  109. l != languages.end(); ++l) {
  110. this->WriteLanguageRules(*l);
  111. }
  112. }
  113. const char* cmNinjaNormalTargetGenerator::GetVisibleTypeName() const
  114. {
  115. switch (this->GetGeneratorTarget()->GetType()) {
  116. case cmStateEnums::STATIC_LIBRARY:
  117. return "static library";
  118. case cmStateEnums::SHARED_LIBRARY:
  119. return "shared library";
  120. case cmStateEnums::MODULE_LIBRARY:
  121. if (this->GetGeneratorTarget()->IsCFBundleOnApple()) {
  122. return "CFBundle shared module";
  123. } else {
  124. return "shared module";
  125. }
  126. case cmStateEnums::EXECUTABLE:
  127. return "executable";
  128. default:
  129. return CM_NULLPTR;
  130. }
  131. }
  132. std::string cmNinjaNormalTargetGenerator::LanguageLinkerRule() const
  133. {
  134. return this->TargetLinkLanguage + "_" +
  135. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()) +
  136. "_LINKER__" + cmGlobalNinjaGenerator::EncodeRuleName(
  137. this->GetGeneratorTarget()->GetName());
  138. }
  139. struct cmNinjaRemoveNoOpCommands
  140. {
  141. bool operator()(std::string const& cmd)
  142. {
  143. return cmd.empty() || cmd[0] == ':';
  144. }
  145. };
  146. void cmNinjaNormalTargetGenerator::WriteLinkRule(bool useResponseFile)
  147. {
  148. cmStateEnums::TargetType targetType = this->GetGeneratorTarget()->GetType();
  149. std::string ruleName = this->LanguageLinkerRule();
  150. // Select whether to use a response file for objects.
  151. std::string rspfile;
  152. std::string rspcontent;
  153. if (!this->GetGlobalGenerator()->HasRule(ruleName)) {
  154. cmRulePlaceholderExpander::RuleVariables vars;
  155. vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
  156. vars.CMTargetType =
  157. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType());
  158. vars.Language = this->TargetLinkLanguage.c_str();
  159. std::string responseFlag;
  160. if (!useResponseFile) {
  161. vars.Objects = "$in";
  162. vars.LinkLibraries = "$LINK_PATH $LINK_LIBRARIES";
  163. } else {
  164. std::string cmakeVarLang = "CMAKE_";
  165. cmakeVarLang += this->TargetLinkLanguage;
  166. // build response file name
  167. std::string cmakeLinkVar = cmakeVarLang + "_RESPONSE_FILE_LINK_FLAG";
  168. const char* flag = GetMakefile()->GetDefinition(cmakeLinkVar);
  169. if (flag) {
  170. responseFlag = flag;
  171. } else {
  172. responseFlag = "@";
  173. }
  174. rspfile = "$RSP_FILE";
  175. responseFlag += rspfile;
  176. // build response file content
  177. if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
  178. rspcontent = "$in";
  179. } else {
  180. rspcontent = "$in_newline";
  181. }
  182. rspcontent += " $LINK_PATH $LINK_LIBRARIES";
  183. vars.Objects = responseFlag.c_str();
  184. vars.LinkLibraries = "";
  185. }
  186. vars.ObjectDir = "$OBJECT_DIR";
  187. vars.Target = "$TARGET_FILE";
  188. vars.SONameFlag = "$SONAME_FLAG";
  189. vars.TargetSOName = "$SONAME";
  190. vars.TargetInstallNameDir = "$INSTALLNAME_DIR";
  191. vars.TargetPDB = "$TARGET_PDB";
  192. // Setup the target version.
  193. std::string targetVersionMajor;
  194. std::string targetVersionMinor;
  195. {
  196. std::ostringstream majorStream;
  197. std::ostringstream minorStream;
  198. int major;
  199. int minor;
  200. this->GetGeneratorTarget()->GetTargetVersion(major, minor);
  201. majorStream << major;
  202. minorStream << minor;
  203. targetVersionMajor = majorStream.str();
  204. targetVersionMinor = minorStream.str();
  205. }
  206. vars.TargetVersionMajor = targetVersionMajor.c_str();
  207. vars.TargetVersionMinor = targetVersionMinor.c_str();
  208. vars.Flags = "$FLAGS";
  209. vars.LinkFlags = "$LINK_FLAGS";
  210. vars.Manifests = "$MANIFESTS";
  211. std::string langFlags;
  212. if (targetType != cmStateEnums::EXECUTABLE) {
  213. langFlags += "$LANGUAGE_COMPILE_FLAGS $ARCH_FLAGS";
  214. vars.LanguageCompileFlags = langFlags.c_str();
  215. }
  216. std::string launcher;
  217. const char* val = this->GetLocalGenerator()->GetRuleLauncher(
  218. this->GetGeneratorTarget(), "RULE_LAUNCH_LINK");
  219. if (val && *val) {
  220. launcher = val;
  221. launcher += " ";
  222. }
  223. CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander(
  224. this->GetLocalGenerator()->CreateRulePlaceholderExpander());
  225. // Rule for linking library/executable.
  226. std::vector<std::string> linkCmds = this->ComputeLinkCmd();
  227. for (std::vector<std::string>::iterator i = linkCmds.begin();
  228. i != linkCmds.end(); ++i) {
  229. *i = launcher + *i;
  230. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
  231. *i, vars);
  232. }
  233. {
  234. // If there is no ranlib the command will be ":". Skip it.
  235. std::vector<std::string>::iterator newEnd = std::remove_if(
  236. linkCmds.begin(), linkCmds.end(), cmNinjaRemoveNoOpCommands());
  237. linkCmds.erase(newEnd, linkCmds.end());
  238. }
  239. linkCmds.insert(linkCmds.begin(), "$PRE_LINK");
  240. linkCmds.push_back("$POST_BUILD");
  241. std::string linkCmd =
  242. this->GetLocalGenerator()->BuildCommandLine(linkCmds);
  243. // Write the linker rule with response file if needed.
  244. std::ostringstream comment;
  245. comment << "Rule for linking " << this->TargetLinkLanguage << " "
  246. << this->GetVisibleTypeName() << ".";
  247. std::ostringstream description;
  248. description << "Linking " << this->TargetLinkLanguage << " "
  249. << this->GetVisibleTypeName() << " $TARGET_FILE";
  250. this->GetGlobalGenerator()->AddRule(ruleName, linkCmd, description.str(),
  251. comment.str(),
  252. /*depfile*/ "",
  253. /*deptype*/ "", rspfile, rspcontent,
  254. /*restat*/ "$RESTAT",
  255. /*generator*/ false);
  256. }
  257. if (this->TargetNameOut != this->TargetNameReal &&
  258. !this->GetGeneratorTarget()->IsFrameworkOnApple()) {
  259. std::string cmakeCommand =
  260. this->GetLocalGenerator()->ConvertToOutputFormat(
  261. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  262. if (targetType == cmStateEnums::EXECUTABLE) {
  263. this->GetGlobalGenerator()->AddRule(
  264. "CMAKE_SYMLINK_EXECUTABLE",
  265. cmakeCommand + " -E cmake_symlink_executable"
  266. " $in $out && $POST_BUILD",
  267. "Creating executable symlink $out", "Rule for creating "
  268. "executable symlink.",
  269. /*depfile*/ "",
  270. /*deptype*/ "",
  271. /*rspfile*/ "",
  272. /*rspcontent*/ "",
  273. /*restat*/ "",
  274. /*generator*/ false);
  275. } else {
  276. this->GetGlobalGenerator()->AddRule(
  277. "CMAKE_SYMLINK_LIBRARY",
  278. cmakeCommand + " -E cmake_symlink_library"
  279. " $in $SONAME $out && $POST_BUILD",
  280. "Creating library symlink $out", "Rule for creating "
  281. "library symlink.",
  282. /*depfile*/ "",
  283. /*deptype*/ "",
  284. /*rspfile*/ "",
  285. /*rspcontent*/ "",
  286. /*restat*/ "",
  287. /*generator*/ false);
  288. }
  289. }
  290. }
  291. std::vector<std::string> cmNinjaNormalTargetGenerator::ComputeLinkCmd()
  292. {
  293. std::vector<std::string> linkCmds;
  294. cmMakefile* mf = this->GetMakefile();
  295. {
  296. std::string linkCmdVar = this->GetGeneratorTarget()->GetCreateRuleVariable(
  297. this->TargetLinkLanguage, this->GetConfigName());
  298. const char* linkCmd = mf->GetDefinition(linkCmdVar);
  299. if (linkCmd) {
  300. cmSystemTools::ExpandListArgument(linkCmd, linkCmds);
  301. if (this->GetGeneratorTarget()->GetPropertyAsBool("LINK_WHAT_YOU_USE")) {
  302. std::string cmakeCommand =
  303. this->GetLocalGenerator()->ConvertToOutputFormat(
  304. cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
  305. cmakeCommand += " -E __run_iwyu --lwyu=";
  306. cmGeneratorTarget& gt = *this->GetGeneratorTarget();
  307. const std::string cfgName = this->GetConfigName();
  308. std::string targetOutput = ConvertToNinjaPath(gt.GetFullPath(cfgName));
  309. std::string targetOutputReal =
  310. this->ConvertToNinjaPath(gt.GetFullPath(cfgName,
  311. /*implib=*/false,
  312. /*realname=*/true));
  313. cmakeCommand += targetOutputReal;
  314. cmakeCommand += " || true";
  315. linkCmds.push_back(cmakeCommand);
  316. }
  317. return linkCmds;
  318. }
  319. }
  320. switch (this->GetGeneratorTarget()->GetType()) {
  321. case cmStateEnums::STATIC_LIBRARY: {
  322. // We have archive link commands set. First, delete the existing archive.
  323. {
  324. std::string cmakeCommand =
  325. this->GetLocalGenerator()->ConvertToOutputFormat(
  326. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  327. linkCmds.push_back(cmakeCommand + " -E remove $TARGET_FILE");
  328. }
  329. // TODO: Use ARCHIVE_APPEND for archives over a certain size.
  330. {
  331. std::string linkCmdVar = "CMAKE_";
  332. linkCmdVar += this->TargetLinkLanguage;
  333. linkCmdVar += "_ARCHIVE_CREATE";
  334. const char* linkCmd = mf->GetRequiredDefinition(linkCmdVar);
  335. cmSystemTools::ExpandListArgument(linkCmd, linkCmds);
  336. }
  337. {
  338. std::string linkCmdVar = "CMAKE_";
  339. linkCmdVar += this->TargetLinkLanguage;
  340. linkCmdVar += "_ARCHIVE_FINISH";
  341. const char* linkCmd = mf->GetRequiredDefinition(linkCmdVar);
  342. cmSystemTools::ExpandListArgument(linkCmd, linkCmds);
  343. }
  344. return linkCmds;
  345. }
  346. case cmStateEnums::SHARED_LIBRARY:
  347. case cmStateEnums::MODULE_LIBRARY:
  348. case cmStateEnums::EXECUTABLE:
  349. break;
  350. default:
  351. assert(0 && "Unexpected target type");
  352. }
  353. return std::vector<std::string>();
  354. }
  355. static int calculateCommandLineLengthLimit(int linkRuleLength)
  356. {
  357. static int const limits[] = {
  358. #ifdef _WIN32
  359. 8000,
  360. #endif
  361. #if defined(_SC_ARG_MAX)
  362. // for instance ARG_MAX is 2096152 on Ubuntu or 262144 on Mac
  363. ((int)sysconf(_SC_ARG_MAX)) - 1000,
  364. #endif
  365. #if defined(__linux)
  366. // #define MAX_ARG_STRLEN (PAGE_SIZE * 32) in Linux's binfmts.h
  367. ((int)sysconf(_SC_PAGESIZE) * 32) - 1000,
  368. #endif
  369. std::numeric_limits<int>::max()
  370. };
  371. size_t const arrSz = cmArraySize(limits);
  372. int const sz = *std::min_element(limits, limits + arrSz);
  373. if (sz == std::numeric_limits<int>::max()) {
  374. return 0;
  375. }
  376. return sz - linkRuleLength;
  377. }
  378. void cmNinjaNormalTargetGenerator::WriteLinkStatement()
  379. {
  380. cmGeneratorTarget& gt = *this->GetGeneratorTarget();
  381. const std::string cfgName = this->GetConfigName();
  382. std::string targetOutput = ConvertToNinjaPath(gt.GetFullPath(cfgName));
  383. std::string targetOutputReal =
  384. ConvertToNinjaPath(gt.GetFullPath(cfgName,
  385. /*implib=*/false,
  386. /*realname=*/true));
  387. std::string targetOutputImplib =
  388. ConvertToNinjaPath(gt.GetFullPath(cfgName,
  389. /*implib=*/true));
  390. if (gt.IsAppBundleOnApple()) {
  391. // Create the app bundle
  392. std::string outpath = gt.GetDirectory(cfgName);
  393. this->OSXBundleGenerator->CreateAppBundle(this->TargetNameOut, outpath);
  394. // Calculate the output path
  395. targetOutput = outpath;
  396. targetOutput += "/";
  397. targetOutput += this->TargetNameOut;
  398. targetOutput = this->ConvertToNinjaPath(targetOutput);
  399. targetOutputReal = outpath;
  400. targetOutputReal += "/";
  401. targetOutputReal += this->TargetNameReal;
  402. targetOutputReal = this->ConvertToNinjaPath(targetOutputReal);
  403. } else if (gt.IsFrameworkOnApple()) {
  404. // Create the library framework.
  405. this->OSXBundleGenerator->CreateFramework(this->TargetNameOut,
  406. gt.GetDirectory(cfgName));
  407. } else if (gt.IsCFBundleOnApple()) {
  408. // Create the core foundation bundle.
  409. this->OSXBundleGenerator->CreateCFBundle(this->TargetNameOut,
  410. gt.GetDirectory(cfgName));
  411. }
  412. // Write comments.
  413. cmGlobalNinjaGenerator::WriteDivider(this->GetBuildFileStream());
  414. const cmStateEnums::TargetType targetType = gt.GetType();
  415. this->GetBuildFileStream() << "# Link build statements for "
  416. << cmState::GetTargetTypeName(targetType)
  417. << " target " << this->GetTargetName() << "\n\n";
  418. cmNinjaDeps emptyDeps;
  419. cmNinjaVars vars;
  420. // Compute the comment.
  421. std::ostringstream comment;
  422. comment << "Link the " << this->GetVisibleTypeName() << " "
  423. << targetOutputReal;
  424. // Compute outputs.
  425. cmNinjaDeps outputs;
  426. outputs.push_back(targetOutputReal);
  427. // Compute specific libraries to link with.
  428. cmNinjaDeps explicitDeps = this->GetObjects();
  429. cmNinjaDeps implicitDeps = this->ComputeLinkDeps();
  430. cmMakefile* mf = this->GetMakefile();
  431. std::string frameworkPath;
  432. std::string linkPath;
  433. cmGeneratorTarget& genTarget = *this->GetGeneratorTarget();
  434. std::string createRule = genTarget.GetCreateRuleVariable(
  435. this->TargetLinkLanguage, this->GetConfigName());
  436. bool useWatcomQuote = mf->IsOn(createRule + "_USE_WATCOM_QUOTE");
  437. cmLocalNinjaGenerator& localGen = *this->GetLocalGenerator();
  438. vars["TARGET_FILE"] =
  439. localGen.ConvertToOutputFormat(targetOutputReal, cmOutputConverter::SHELL);
  440. CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer(
  441. this->GetGlobalGenerator()->CreateLinkLineComputer(
  442. this->GetLocalGenerator(),
  443. this->GetLocalGenerator()->GetStateSnapshot().GetDirectory()));
  444. linkLineComputer->SetUseWatcomQuote(useWatcomQuote);
  445. localGen.GetTargetFlags(
  446. linkLineComputer.get(), this->GetConfigName(), vars["LINK_LIBRARIES"],
  447. vars["FLAGS"], vars["LINK_FLAGS"], frameworkPath, linkPath, &genTarget);
  448. if (this->GetMakefile()->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS") &&
  449. (gt.GetType() == cmStateEnums::SHARED_LIBRARY ||
  450. gt.IsExecutableWithExports())) {
  451. if (gt.GetPropertyAsBool("WINDOWS_EXPORT_ALL_SYMBOLS")) {
  452. std::string name_of_def_file = gt.GetSupportDirectory();
  453. name_of_def_file += "/" + gt.GetName();
  454. name_of_def_file += ".def ";
  455. vars["LINK_FLAGS"] += " /DEF:";
  456. vars["LINK_FLAGS"] += this->GetLocalGenerator()->ConvertToOutputFormat(
  457. name_of_def_file, cmOutputConverter::SHELL);
  458. }
  459. }
  460. // Add OS X version flags, if any.
  461. if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
  462. this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  463. this->AppendOSXVerFlag(vars["LINK_FLAGS"], this->TargetLinkLanguage,
  464. "COMPATIBILITY", true);
  465. this->AppendOSXVerFlag(vars["LINK_FLAGS"], this->TargetLinkLanguage,
  466. "CURRENT", false);
  467. }
  468. this->addPoolNinjaVariable("JOB_POOL_LINK", &gt, vars);
  469. this->AddModuleDefinitionFlag(linkLineComputer.get(), vars["LINK_FLAGS"]);
  470. vars["LINK_FLAGS"] =
  471. cmGlobalNinjaGenerator::EncodeLiteral(vars["LINK_FLAGS"]);
  472. vars["MANIFESTS"] = this->GetManifests();
  473. vars["LINK_PATH"] = frameworkPath + linkPath;
  474. std::string lwyuFlags;
  475. if (genTarget.GetPropertyAsBool("LINK_WHAT_YOU_USE")) {
  476. lwyuFlags = " -Wl,--no-as-needed";
  477. }
  478. // Compute architecture specific link flags. Yes, these go into a different
  479. // variable for executables, probably due to a mistake made when duplicating
  480. // code between the Makefile executable and library generators.
  481. if (targetType == cmStateEnums::EXECUTABLE) {
  482. std::string t = vars["FLAGS"];
  483. localGen.AddArchitectureFlags(t, &genTarget, TargetLinkLanguage, cfgName);
  484. t += lwyuFlags;
  485. vars["FLAGS"] = t;
  486. } else {
  487. std::string t = vars["ARCH_FLAGS"];
  488. localGen.AddArchitectureFlags(t, &genTarget, TargetLinkLanguage, cfgName);
  489. vars["ARCH_FLAGS"] = t;
  490. t = "";
  491. t += lwyuFlags;
  492. localGen.AddLanguageFlags(t, TargetLinkLanguage, cfgName);
  493. vars["LANGUAGE_COMPILE_FLAGS"] = t;
  494. }
  495. if (this->GetGeneratorTarget()->HasSOName(cfgName)) {
  496. vars["SONAME_FLAG"] = mf->GetSONameFlag(this->TargetLinkLanguage);
  497. vars["SONAME"] = this->TargetNameSO;
  498. if (targetType == cmStateEnums::SHARED_LIBRARY) {
  499. std::string install_dir =
  500. this->GetGeneratorTarget()->GetInstallNameDirForBuildTree(cfgName);
  501. if (!install_dir.empty()) {
  502. vars["INSTALLNAME_DIR"] = localGen.ConvertToOutputFormat(
  503. install_dir, cmOutputConverter::SHELL);
  504. }
  505. }
  506. }
  507. cmNinjaDeps byproducts;
  508. if (!this->TargetNameImport.empty()) {
  509. const std::string impLibPath = localGen.ConvertToOutputFormat(
  510. targetOutputImplib, cmOutputConverter::SHELL);
  511. vars["TARGET_IMPLIB"] = impLibPath;
  512. EnsureParentDirectoryExists(impLibPath);
  513. if (genTarget.HasImportLibrary()) {
  514. byproducts.push_back(targetOutputImplib);
  515. }
  516. }
  517. if (!this->SetMsvcTargetPdbVariable(vars)) {
  518. // It is common to place debug symbols at a specific place,
  519. // so we need a plain target name in the rule available.
  520. std::string prefix;
  521. std::string base;
  522. std::string suffix;
  523. this->GetGeneratorTarget()->GetFullNameComponents(prefix, base, suffix);
  524. std::string dbg_suffix = ".dbg";
  525. // TODO: Where to document?
  526. if (mf->GetDefinition("CMAKE_DEBUG_SYMBOL_SUFFIX")) {
  527. dbg_suffix = mf->GetDefinition("CMAKE_DEBUG_SYMBOL_SUFFIX");
  528. }
  529. vars["TARGET_PDB"] = base + suffix + dbg_suffix;
  530. }
  531. const std::string objPath = GetGeneratorTarget()->GetSupportDirectory();
  532. vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  533. this->ConvertToNinjaPath(objPath), cmOutputConverter::SHELL);
  534. EnsureDirectoryExists(objPath);
  535. if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
  536. // ar.exe can't handle backslashes in rsp files (implicitly used by gcc)
  537. std::string& linkLibraries = vars["LINK_LIBRARIES"];
  538. std::replace(linkLibraries.begin(), linkLibraries.end(), '\\', '/');
  539. std::string& link_path = vars["LINK_PATH"];
  540. std::replace(link_path.begin(), link_path.end(), '\\', '/');
  541. }
  542. const std::vector<cmCustomCommand>* cmdLists[3] = {
  543. &gt.GetPreBuildCommands(), &gt.GetPreLinkCommands(),
  544. &gt.GetPostBuildCommands()
  545. };
  546. std::vector<std::string> preLinkCmdLines, postBuildCmdLines;
  547. std::vector<std::string>* cmdLineLists[3] = { &preLinkCmdLines,
  548. &preLinkCmdLines,
  549. &postBuildCmdLines };
  550. for (unsigned i = 0; i != 3; ++i) {
  551. for (std::vector<cmCustomCommand>::const_iterator ci =
  552. cmdLists[i]->begin();
  553. ci != cmdLists[i]->end(); ++ci) {
  554. cmCustomCommandGenerator ccg(*ci, cfgName, this->GetLocalGenerator());
  555. localGen.AppendCustomCommandLines(ccg, *cmdLineLists[i]);
  556. std::vector<std::string> const& ccByproducts = ccg.GetByproducts();
  557. std::transform(ccByproducts.begin(), ccByproducts.end(),
  558. std::back_inserter(byproducts), MapToNinjaPath());
  559. }
  560. }
  561. // maybe create .def file from list of objects
  562. if ((gt.GetType() == cmStateEnums::SHARED_LIBRARY ||
  563. gt.IsExecutableWithExports()) &&
  564. this->GetMakefile()->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS")) {
  565. if (gt.GetPropertyAsBool("WINDOWS_EXPORT_ALL_SYMBOLS")) {
  566. std::string cmakeCommand =
  567. this->GetLocalGenerator()->ConvertToOutputFormat(
  568. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  569. std::string name_of_def_file = gt.GetSupportDirectory();
  570. name_of_def_file += "/" + gt.GetName();
  571. name_of_def_file += ".def";
  572. std::string cmd = cmakeCommand;
  573. cmd += " -E __create_def ";
  574. cmd += this->GetLocalGenerator()->ConvertToOutputFormat(
  575. name_of_def_file, cmOutputConverter::SHELL);
  576. cmd += " ";
  577. cmNinjaDeps objs = this->GetObjects();
  578. std::string obj_list_file = name_of_def_file;
  579. obj_list_file += ".objs";
  580. cmd += this->GetLocalGenerator()->ConvertToOutputFormat(
  581. obj_list_file, cmOutputConverter::SHELL);
  582. preLinkCmdLines.push_back(cmd);
  583. // create a list of obj files for the -E __create_def to read
  584. cmGeneratedFileStream fout(obj_list_file.c_str());
  585. for (cmNinjaDeps::iterator i = objs.begin(); i != objs.end(); ++i) {
  586. if (cmHasLiteralSuffix(*i, ".obj")) {
  587. fout << *i << "\n";
  588. }
  589. }
  590. }
  591. }
  592. // If we have any PRE_LINK commands, we need to go back to CMAKE_BINARY_DIR
  593. // for
  594. // the link commands.
  595. if (!preLinkCmdLines.empty()) {
  596. const std::string homeOutDir = localGen.ConvertToOutputFormat(
  597. localGen.GetBinaryDirectory(), cmOutputConverter::SHELL);
  598. preLinkCmdLines.push_back("cd " + homeOutDir);
  599. }
  600. vars["PRE_LINK"] = localGen.BuildCommandLine(preLinkCmdLines);
  601. std::string postBuildCmdLine = localGen.BuildCommandLine(postBuildCmdLines);
  602. cmNinjaVars symlinkVars;
  603. bool const symlinkNeeded =
  604. (targetOutput != targetOutputReal && !gt.IsFrameworkOnApple());
  605. if (!symlinkNeeded) {
  606. vars["POST_BUILD"] = postBuildCmdLine;
  607. } else {
  608. vars["POST_BUILD"] = cmGlobalNinjaGenerator::SHELL_NOOP;
  609. symlinkVars["POST_BUILD"] = postBuildCmdLine;
  610. }
  611. cmGlobalNinjaGenerator& globalGen = *this->GetGlobalGenerator();
  612. int commandLineLengthLimit = -1;
  613. if (!this->ForceResponseFile()) {
  614. commandLineLengthLimit = calculateCommandLineLengthLimit(
  615. globalGen.GetRuleCmdLength(this->LanguageLinkerRule()));
  616. }
  617. const std::string rspfile =
  618. std::string(cmake::GetCMakeFilesDirectoryPostSlash()) + gt.GetName() +
  619. ".rsp";
  620. // Gather order-only dependencies.
  621. cmNinjaDeps orderOnlyDeps;
  622. this->GetLocalGenerator()->AppendTargetDepends(this->GetGeneratorTarget(),
  623. orderOnlyDeps);
  624. // Ninja should restat after linking if and only if there are byproducts.
  625. vars["RESTAT"] = byproducts.empty() ? "" : "1";
  626. for (cmNinjaDeps::const_iterator oi = byproducts.begin(),
  627. oe = byproducts.end();
  628. oi != oe; ++oi) {
  629. this->GetGlobalGenerator()->SeenCustomCommandOutput(*oi);
  630. outputs.push_back(*oi);
  631. }
  632. // Write the build statement for this target.
  633. bool usedResponseFile = false;
  634. globalGen.WriteBuild(this->GetBuildFileStream(), comment.str(),
  635. this->LanguageLinkerRule(), outputs,
  636. /*implicitOuts=*/cmNinjaDeps(), explicitDeps,
  637. implicitDeps, orderOnlyDeps, vars, rspfile,
  638. commandLineLengthLimit, &usedResponseFile);
  639. this->WriteLinkRule(usedResponseFile);
  640. if (symlinkNeeded) {
  641. if (targetType == cmStateEnums::EXECUTABLE) {
  642. globalGen.WriteBuild(
  643. this->GetBuildFileStream(),
  644. "Create executable symlink " + targetOutput,
  645. "CMAKE_SYMLINK_EXECUTABLE", cmNinjaDeps(1, targetOutput),
  646. /*implicitOuts=*/cmNinjaDeps(), cmNinjaDeps(1, targetOutputReal),
  647. emptyDeps, emptyDeps, symlinkVars);
  648. } else {
  649. cmNinjaDeps symlinks;
  650. std::string const soName =
  651. this->ConvertToNinjaPath(this->GetTargetFilePath(this->TargetNameSO));
  652. // If one link has to be created.
  653. if (targetOutputReal == soName || targetOutput == soName) {
  654. symlinkVars["SONAME"] = soName;
  655. } else {
  656. symlinkVars["SONAME"] = "";
  657. symlinks.push_back(soName);
  658. }
  659. symlinks.push_back(targetOutput);
  660. globalGen.WriteBuild(
  661. this->GetBuildFileStream(), "Create library symlink " + targetOutput,
  662. "CMAKE_SYMLINK_LIBRARY", symlinks,
  663. /*implicitOuts=*/cmNinjaDeps(), cmNinjaDeps(1, targetOutputReal),
  664. emptyDeps, emptyDeps, symlinkVars);
  665. }
  666. }
  667. // Add aliases for the file name and the target name.
  668. globalGen.AddTargetAlias(this->TargetNameOut, &gt);
  669. globalGen.AddTargetAlias(this->GetTargetName(), &gt);
  670. }
  671. void cmNinjaNormalTargetGenerator::WriteObjectLibStatement()
  672. {
  673. // Write a phony output that depends on all object files.
  674. cmNinjaDeps outputs;
  675. this->GetLocalGenerator()->AppendTargetOutputs(this->GetGeneratorTarget(),
  676. outputs);
  677. cmNinjaDeps depends = this->GetObjects();
  678. this->GetGlobalGenerator()->WritePhonyBuild(
  679. this->GetBuildFileStream(), "Object library " + this->GetTargetName(),
  680. outputs, depends);
  681. // Add aliases for the target name.
  682. this->GetGlobalGenerator()->AddTargetAlias(this->GetTargetName(),
  683. this->GetGeneratorTarget());
  684. }