cmNinjaNormalTargetGenerator.cxx 27 KB

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