cmNinjaNormalTargetGenerator.cxx 27 KB

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