cmNinjaNormalTargetGenerator.cxx 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118
  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 <map>
  8. #include <memory> // IWYU pragma: keep
  9. #include <set>
  10. #include <sstream>
  11. #include <utility>
  12. #include "cmAlgorithms.h"
  13. #include "cmCustomCommand.h" // IWYU pragma: keep
  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 "cmNinjaLinkLineDeviceComputer.h"
  23. #include "cmNinjaTypes.h"
  24. #include "cmOSXBundleGenerator.h"
  25. #include "cmOutputConverter.h"
  26. #include "cmRulePlaceholderExpander.h"
  27. #include "cmSourceFile.h"
  28. #include "cmState.h"
  29. #include "cmStateDirectory.h"
  30. #include "cmStateSnapshot.h"
  31. #include "cmStateTypes.h"
  32. #include "cmSystemTools.h"
  33. cmNinjaNormalTargetGenerator::cmNinjaNormalTargetGenerator(
  34. cmGeneratorTarget* target)
  35. : cmNinjaTargetGenerator(target)
  36. , TargetLinkLanguage("")
  37. {
  38. this->TargetLinkLanguage = target->GetLinkerLanguage(this->GetConfigName());
  39. if (target->GetType() == cmStateEnums::EXECUTABLE) {
  40. this->TargetNames = this->GetGeneratorTarget()->GetExecutableNames(
  41. GetLocalGenerator()->GetConfigName());
  42. } else {
  43. this->TargetNames = this->GetGeneratorTarget()->GetLibraryNames(
  44. GetLocalGenerator()->GetConfigName());
  45. }
  46. if (target->GetType() != cmStateEnums::OBJECT_LIBRARY) {
  47. // on Windows the output dir is already needed at compile time
  48. // ensure the directory exists (OutDir test)
  49. EnsureDirectoryExists(target->GetDirectory(this->GetConfigName()));
  50. }
  51. this->OSXBundleGenerator =
  52. cm::make_unique<cmOSXBundleGenerator>(target, this->GetConfigName());
  53. this->OSXBundleGenerator->SetMacContentFolders(&this->MacContentFolders);
  54. }
  55. cmNinjaNormalTargetGenerator::~cmNinjaNormalTargetGenerator() = default;
  56. void cmNinjaNormalTargetGenerator::Generate()
  57. {
  58. if (this->TargetLinkLanguage.empty()) {
  59. cmSystemTools::Error("CMake can not determine linker language for "
  60. "target: " +
  61. this->GetGeneratorTarget()->GetName());
  62. return;
  63. }
  64. // Write the rules for each language.
  65. this->WriteLanguagesRules();
  66. // Write the build statements
  67. this->WriteObjectBuildStatements();
  68. if (this->GetGeneratorTarget()->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  69. this->WriteObjectLibStatement();
  70. } else {
  71. // If this target has cuda language link inputs, and we need to do
  72. // device linking
  73. this->WriteDeviceLinkStatement();
  74. this->WriteLinkStatement();
  75. }
  76. this->AdditionalCleanFiles();
  77. }
  78. void cmNinjaNormalTargetGenerator::WriteLanguagesRules()
  79. {
  80. #ifdef NINJA_GEN_VERBOSE_FILES
  81. cmGlobalNinjaGenerator::WriteDivider(this->GetRulesFileStream());
  82. this->GetRulesFileStream()
  83. << "# Rules for each languages for "
  84. << cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType())
  85. << " target " << this->GetTargetName() << "\n\n";
  86. #endif
  87. // Write rules for languages compiled in this target.
  88. std::set<std::string> languages;
  89. std::vector<cmSourceFile const*> sourceFiles;
  90. this->GetGeneratorTarget()->GetObjectSources(
  91. sourceFiles, this->GetMakefile()->GetSafeDefinition("CMAKE_BUILD_TYPE"));
  92. for (cmSourceFile const* sf : sourceFiles) {
  93. std::string const lang = sf->GetLanguage();
  94. if (!lang.empty()) {
  95. languages.insert(lang);
  96. }
  97. }
  98. for (std::string const& language : languages) {
  99. this->WriteLanguageRules(language);
  100. }
  101. }
  102. const char* cmNinjaNormalTargetGenerator::GetVisibleTypeName() const
  103. {
  104. switch (this->GetGeneratorTarget()->GetType()) {
  105. case cmStateEnums::STATIC_LIBRARY:
  106. return "static library";
  107. case cmStateEnums::SHARED_LIBRARY:
  108. return "shared library";
  109. case cmStateEnums::MODULE_LIBRARY:
  110. if (this->GetGeneratorTarget()->IsCFBundleOnApple()) {
  111. return "CFBundle shared module";
  112. } else {
  113. return "shared module";
  114. }
  115. case cmStateEnums::EXECUTABLE:
  116. return "executable";
  117. default:
  118. return nullptr;
  119. }
  120. }
  121. std::string cmNinjaNormalTargetGenerator::LanguageLinkerRule() const
  122. {
  123. return this->TargetLinkLanguage + "_" +
  124. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()) +
  125. "_LINKER__" +
  126. cmGlobalNinjaGenerator::EncodeRuleName(
  127. this->GetGeneratorTarget()->GetName());
  128. }
  129. std::string cmNinjaNormalTargetGenerator::LanguageLinkerDeviceRule() const
  130. {
  131. return this->TargetLinkLanguage + "_" +
  132. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()) +
  133. "_DEVICE_LINKER__" +
  134. 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::WriteDeviceLinkRule(bool useResponseFile)
  145. {
  146. cmStateEnums::TargetType targetType = this->GetGeneratorTarget()->GetType();
  147. std::string ruleName = this->LanguageLinkerDeviceRule();
  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 = "CUDA";
  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_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.TargetPDB = "$TARGET_PDB";
  189. vars.TargetCompilePDB = "$TARGET_COMPILE_PDB";
  190. vars.Flags = "$FLAGS";
  191. vars.LinkFlags = "$LINK_FLAGS";
  192. vars.Manifests = "$MANIFESTS";
  193. std::string langFlags;
  194. if (targetType != cmStateEnums::EXECUTABLE) {
  195. langFlags += "$LANGUAGE_COMPILE_FLAGS $ARCH_FLAGS";
  196. vars.LanguageCompileFlags = langFlags.c_str();
  197. }
  198. std::string launcher;
  199. const char* val = this->GetLocalGenerator()->GetRuleLauncher(
  200. this->GetGeneratorTarget(), "RULE_LAUNCH_LINK");
  201. if (val && *val) {
  202. launcher = val;
  203. launcher += " ";
  204. }
  205. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  206. this->GetLocalGenerator()->CreateRulePlaceholderExpander());
  207. // Rule for linking library/executable.
  208. std::vector<std::string> linkCmds = this->ComputeDeviceLinkCmd();
  209. for (std::string& linkCmd : linkCmds) {
  210. linkCmd = launcher + linkCmd;
  211. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
  212. linkCmd, vars);
  213. }
  214. // If there is no ranlib the command will be ":". Skip it.
  215. cmEraseIf(linkCmds, cmNinjaRemoveNoOpCommands());
  216. std::string linkCmd =
  217. this->GetLocalGenerator()->BuildCommandLine(linkCmds);
  218. // Write the linker rule with response file if needed.
  219. std::ostringstream comment;
  220. comment << "Rule for linking " << this->TargetLinkLanguage << " "
  221. << this->GetVisibleTypeName() << ".";
  222. std::ostringstream description;
  223. description << "Linking " << this->TargetLinkLanguage << " "
  224. << this->GetVisibleTypeName() << " $TARGET_FILE";
  225. this->GetGlobalGenerator()->AddRule(ruleName, linkCmd, description.str(),
  226. comment.str(),
  227. /*depfile*/ "",
  228. /*deptype*/ "", rspfile, rspcontent,
  229. /*restat*/ "$RESTAT",
  230. /*generator*/ false);
  231. }
  232. }
  233. void cmNinjaNormalTargetGenerator::WriteLinkRule(bool useResponseFile)
  234. {
  235. cmStateEnums::TargetType targetType = this->GetGeneratorTarget()->GetType();
  236. std::string ruleName = this->LanguageLinkerRule();
  237. // Select whether to use a response file for objects.
  238. std::string rspfile;
  239. std::string rspcontent;
  240. if (!this->GetGlobalGenerator()->HasRule(ruleName)) {
  241. cmRulePlaceholderExpander::RuleVariables vars;
  242. vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
  243. vars.CMTargetType =
  244. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType());
  245. vars.Language = this->TargetLinkLanguage.c_str();
  246. if (this->TargetLinkLanguage == "Swift") {
  247. vars.SwiftPartialModules = "$SWIFT_PARTIAL_MODULES";
  248. vars.TargetSwiftModule = "$TARGET_SWIFT_MODULE";
  249. vars.TargetSwiftDoc = "$TARGET_SWIFT_DOC";
  250. }
  251. std::string responseFlag;
  252. if (!useResponseFile) {
  253. vars.Objects = "$in";
  254. vars.LinkLibraries = "$LINK_PATH $LINK_LIBRARIES";
  255. } else {
  256. std::string cmakeVarLang = "CMAKE_";
  257. cmakeVarLang += this->TargetLinkLanguage;
  258. // build response file name
  259. std::string cmakeLinkVar = cmakeVarLang + "_RESPONSE_FILE_LINK_FLAG";
  260. const char* flag = GetMakefile()->GetDefinition(cmakeLinkVar);
  261. if (flag) {
  262. responseFlag = flag;
  263. } else {
  264. responseFlag = "@";
  265. }
  266. rspfile = "$RSP_FILE";
  267. responseFlag += rspfile;
  268. // build response file content
  269. if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
  270. rspcontent = "$in";
  271. } else {
  272. rspcontent = "$in_newline";
  273. }
  274. rspcontent += " $LINK_PATH $LINK_LIBRARIES";
  275. vars.Objects = responseFlag.c_str();
  276. vars.LinkLibraries = "";
  277. }
  278. vars.ObjectDir = "$OBJECT_DIR";
  279. vars.Target = "$TARGET_FILE";
  280. vars.SONameFlag = "$SONAME_FLAG";
  281. vars.TargetSOName = "$SONAME";
  282. vars.TargetInstallNameDir = "$INSTALLNAME_DIR";
  283. vars.TargetPDB = "$TARGET_PDB";
  284. // Setup the target version.
  285. std::string targetVersionMajor;
  286. std::string targetVersionMinor;
  287. {
  288. std::ostringstream majorStream;
  289. std::ostringstream minorStream;
  290. int major;
  291. int minor;
  292. this->GetGeneratorTarget()->GetTargetVersion(major, minor);
  293. majorStream << major;
  294. minorStream << minor;
  295. targetVersionMajor = majorStream.str();
  296. targetVersionMinor = minorStream.str();
  297. }
  298. vars.TargetVersionMajor = targetVersionMajor.c_str();
  299. vars.TargetVersionMinor = targetVersionMinor.c_str();
  300. vars.Flags = "$FLAGS";
  301. vars.LinkFlags = "$LINK_FLAGS";
  302. vars.Manifests = "$MANIFESTS";
  303. std::string langFlags;
  304. if (targetType != cmStateEnums::EXECUTABLE) {
  305. langFlags += "$LANGUAGE_COMPILE_FLAGS $ARCH_FLAGS";
  306. vars.LanguageCompileFlags = langFlags.c_str();
  307. }
  308. std::string launcher;
  309. const char* val = this->GetLocalGenerator()->GetRuleLauncher(
  310. this->GetGeneratorTarget(), "RULE_LAUNCH_LINK");
  311. if (val && *val) {
  312. launcher = val;
  313. launcher += " ";
  314. }
  315. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  316. this->GetLocalGenerator()->CreateRulePlaceholderExpander());
  317. // Rule for linking library/executable.
  318. std::vector<std::string> linkCmds = this->ComputeLinkCmd();
  319. for (std::string& linkCmd : linkCmds) {
  320. linkCmd = launcher + linkCmd;
  321. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
  322. linkCmd, vars);
  323. }
  324. // If there is no ranlib the command will be ":". Skip it.
  325. cmEraseIf(linkCmds, cmNinjaRemoveNoOpCommands());
  326. linkCmds.insert(linkCmds.begin(), "$PRE_LINK");
  327. linkCmds.emplace_back("$POST_BUILD");
  328. std::string linkCmd =
  329. this->GetLocalGenerator()->BuildCommandLine(linkCmds);
  330. // Write the linker rule with response file if needed.
  331. std::ostringstream comment;
  332. comment << "Rule for linking " << this->TargetLinkLanguage << " "
  333. << this->GetVisibleTypeName() << ".";
  334. std::ostringstream description;
  335. description << "Linking " << this->TargetLinkLanguage << " "
  336. << this->GetVisibleTypeName() << " $TARGET_FILE";
  337. this->GetGlobalGenerator()->AddRule(ruleName, linkCmd, description.str(),
  338. comment.str(),
  339. /*depfile*/ "",
  340. /*deptype*/ "", rspfile, rspcontent,
  341. /*restat*/ "$RESTAT",
  342. /*generator*/ false);
  343. }
  344. if (this->TargetNames.Output != this->TargetNames.Real &&
  345. !this->GetGeneratorTarget()->IsFrameworkOnApple()) {
  346. std::string cmakeCommand =
  347. this->GetLocalGenerator()->ConvertToOutputFormat(
  348. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  349. if (targetType == cmStateEnums::EXECUTABLE) {
  350. std::vector<std::string> commandLines;
  351. commandLines.push_back(cmakeCommand +
  352. " -E cmake_symlink_executable $in $out");
  353. commandLines.emplace_back("$POST_BUILD");
  354. this->GetGlobalGenerator()->AddRule(
  355. "CMAKE_SYMLINK_EXECUTABLE",
  356. this->GetLocalGenerator()->BuildCommandLine(commandLines),
  357. "Creating executable symlink $out",
  358. "Rule for creating "
  359. "executable symlink.",
  360. /*depfile*/ "",
  361. /*deptype*/ "",
  362. /*rspfile*/ "",
  363. /*rspcontent*/ "",
  364. /*restat*/ "",
  365. /*generator*/ false);
  366. } else {
  367. std::vector<std::string> commandLines;
  368. commandLines.push_back(cmakeCommand +
  369. " -E cmake_symlink_library $in $SONAME $out");
  370. commandLines.emplace_back("$POST_BUILD");
  371. this->GetGlobalGenerator()->AddRule(
  372. "CMAKE_SYMLINK_LIBRARY",
  373. this->GetLocalGenerator()->BuildCommandLine(commandLines),
  374. "Creating library symlink $out",
  375. "Rule for creating "
  376. "library symlink.",
  377. /*depfile*/ "",
  378. /*deptype*/ "",
  379. /*rspfile*/ "",
  380. /*rspcontent*/ "",
  381. /*restat*/ "",
  382. /*generator*/ false);
  383. }
  384. }
  385. }
  386. std::vector<std::string> cmNinjaNormalTargetGenerator::ComputeDeviceLinkCmd()
  387. {
  388. std::vector<std::string> linkCmds;
  389. // this target requires separable cuda compilation
  390. // now build the correct command depending on if the target is
  391. // an executable or a dynamic library.
  392. std::string linkCmd;
  393. switch (this->GetGeneratorTarget()->GetType()) {
  394. case cmStateEnums::STATIC_LIBRARY:
  395. case cmStateEnums::SHARED_LIBRARY:
  396. case cmStateEnums::MODULE_LIBRARY: {
  397. const std::string cudaLinkCmd(
  398. this->GetMakefile()->GetDefinition("CMAKE_CUDA_DEVICE_LINK_LIBRARY"));
  399. cmSystemTools::ExpandListArgument(cudaLinkCmd, linkCmds);
  400. } break;
  401. case cmStateEnums::EXECUTABLE: {
  402. const std::string cudaLinkCmd(this->GetMakefile()->GetDefinition(
  403. "CMAKE_CUDA_DEVICE_LINK_EXECUTABLE"));
  404. cmSystemTools::ExpandListArgument(cudaLinkCmd, linkCmds);
  405. } break;
  406. default:
  407. break;
  408. }
  409. return linkCmds;
  410. }
  411. std::vector<std::string> cmNinjaNormalTargetGenerator::ComputeLinkCmd()
  412. {
  413. std::vector<std::string> linkCmds;
  414. cmMakefile* mf = this->GetMakefile();
  415. {
  416. // If we have a rule variable prefer it. In the case of static libraries
  417. // this occurs when things like IPO is enabled, and we need to use the
  418. // CMAKE_<lang>_CREATE_STATIC_LIBRARY_IPO define instead.
  419. std::string linkCmdVar = this->GetGeneratorTarget()->GetCreateRuleVariable(
  420. this->TargetLinkLanguage, this->GetConfigName());
  421. const char* linkCmd = mf->GetDefinition(linkCmdVar);
  422. if (linkCmd) {
  423. std::string linkCmdStr = linkCmd;
  424. if (this->GetGeneratorTarget()->HasImplibGNUtoMS(this->ConfigName)) {
  425. std::string ruleVar = "CMAKE_";
  426. ruleVar += this->GeneratorTarget->GetLinkerLanguage(this->ConfigName);
  427. ruleVar += "_GNUtoMS_RULE";
  428. if (const char* rule = this->Makefile->GetDefinition(ruleVar)) {
  429. linkCmdStr += rule;
  430. }
  431. }
  432. cmSystemTools::ExpandListArgument(linkCmdStr, linkCmds);
  433. if (this->GetGeneratorTarget()->GetPropertyAsBool("LINK_WHAT_YOU_USE")) {
  434. std::string cmakeCommand =
  435. this->GetLocalGenerator()->ConvertToOutputFormat(
  436. cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
  437. cmakeCommand += " -E __run_co_compile --lwyu=";
  438. cmGeneratorTarget& gt = *this->GetGeneratorTarget();
  439. const std::string cfgName = this->GetConfigName();
  440. std::string targetOutputReal = this->ConvertToNinjaPath(
  441. gt.GetFullPath(cfgName, cmStateEnums::RuntimeBinaryArtifact,
  442. /*realname=*/true));
  443. cmakeCommand += targetOutputReal;
  444. linkCmds.push_back(std::move(cmakeCommand));
  445. }
  446. return linkCmds;
  447. }
  448. }
  449. switch (this->GetGeneratorTarget()->GetType()) {
  450. case cmStateEnums::STATIC_LIBRARY: {
  451. // We have archive link commands set. First, delete the existing archive.
  452. {
  453. std::string cmakeCommand =
  454. this->GetLocalGenerator()->ConvertToOutputFormat(
  455. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  456. linkCmds.push_back(cmakeCommand + " -E remove $TARGET_FILE");
  457. }
  458. // TODO: Use ARCHIVE_APPEND for archives over a certain size.
  459. {
  460. std::string linkCmdVar = "CMAKE_";
  461. linkCmdVar += this->TargetLinkLanguage;
  462. linkCmdVar += "_ARCHIVE_CREATE";
  463. linkCmdVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable(
  464. linkCmdVar, this->TargetLinkLanguage, this->GetConfigName());
  465. std::string const& linkCmd = mf->GetRequiredDefinition(linkCmdVar);
  466. cmSystemTools::ExpandListArgument(linkCmd, linkCmds);
  467. }
  468. {
  469. std::string linkCmdVar = "CMAKE_";
  470. linkCmdVar += this->TargetLinkLanguage;
  471. linkCmdVar += "_ARCHIVE_FINISH";
  472. linkCmdVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable(
  473. linkCmdVar, this->TargetLinkLanguage, this->GetConfigName());
  474. std::string const& linkCmd = mf->GetRequiredDefinition(linkCmdVar);
  475. cmSystemTools::ExpandListArgument(linkCmd, linkCmds);
  476. }
  477. #ifdef __APPLE__
  478. // On macOS ranlib truncates the fractional part of the static archive
  479. // file modification time. If the archive and at least one contained
  480. // object file were created within the same second this will make look
  481. // the archive older than the object file. On subsequent ninja runs this
  482. // leads to re-achiving and updating dependent targets.
  483. // As a work-around we touch the archive after ranlib (see #19222).
  484. {
  485. std::string cmakeCommand =
  486. this->GetLocalGenerator()->ConvertToOutputFormat(
  487. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  488. linkCmds.push_back(cmakeCommand + " -E touch $TARGET_FILE");
  489. }
  490. #endif
  491. return linkCmds;
  492. }
  493. case cmStateEnums::SHARED_LIBRARY:
  494. case cmStateEnums::MODULE_LIBRARY:
  495. case cmStateEnums::EXECUTABLE:
  496. break;
  497. default:
  498. assert(false && "Unexpected target type");
  499. }
  500. return std::vector<std::string>();
  501. }
  502. void cmNinjaNormalTargetGenerator::WriteDeviceLinkStatement()
  503. {
  504. if (!this->GetGlobalGenerator()->GetLanguageEnabled("CUDA")) {
  505. return;
  506. }
  507. cmGeneratorTarget& genTarget = *this->GetGeneratorTarget();
  508. // determine if we need to do any device linking for this target
  509. const std::string cuda_lang("CUDA");
  510. cmGeneratorTarget::LinkClosure const* closure =
  511. genTarget.GetLinkClosure(this->GetConfigName());
  512. const bool hasCUDA =
  513. (std::find(closure->Languages.begin(), closure->Languages.end(),
  514. cuda_lang) != closure->Languages.end());
  515. bool doDeviceLinking = false;
  516. if (const char* resolveDeviceSymbols =
  517. genTarget.GetProperty("CUDA_RESOLVE_DEVICE_SYMBOLS")) {
  518. doDeviceLinking = cmSystemTools::IsOn(resolveDeviceSymbols);
  519. } else {
  520. switch (genTarget.GetType()) {
  521. case cmStateEnums::SHARED_LIBRARY:
  522. case cmStateEnums::MODULE_LIBRARY:
  523. case cmStateEnums::EXECUTABLE:
  524. doDeviceLinking = true;
  525. break;
  526. default:
  527. break;
  528. }
  529. }
  530. if (!(doDeviceLinking && hasCUDA)) {
  531. return;
  532. }
  533. // Now we can do device linking
  534. // First and very important step is to make sure while inside this
  535. // step our link language is set to CUDA
  536. std::string cudaLinkLanguage = "CUDA";
  537. std::string const objExt =
  538. this->Makefile->GetSafeDefinition("CMAKE_CUDA_OUTPUT_EXTENSION");
  539. std::string const cfgName = this->GetConfigName();
  540. std::string const targetOutputReal = ConvertToNinjaPath(
  541. genTarget.ObjectDirectory + "cmake_device_link" + objExt);
  542. std::string const targetOutputImplib = ConvertToNinjaPath(
  543. genTarget.GetFullPath(cfgName, cmStateEnums::ImportLibraryArtifact));
  544. this->DeviceLinkObject = targetOutputReal;
  545. // Write comments.
  546. cmGlobalNinjaGenerator::WriteDivider(this->GetBuildFileStream());
  547. const cmStateEnums::TargetType targetType = genTarget.GetType();
  548. this->GetBuildFileStream() << "# Device Link build statements for "
  549. << cmState::GetTargetTypeName(targetType)
  550. << " target " << this->GetTargetName() << "\n\n";
  551. // Compute the comment.
  552. std::ostringstream comment;
  553. comment << "Link the " << this->GetVisibleTypeName() << " "
  554. << targetOutputReal;
  555. cmNinjaDeps emptyDeps;
  556. cmNinjaVars vars;
  557. // Compute outputs.
  558. cmNinjaDeps outputs;
  559. outputs.push_back(targetOutputReal);
  560. // Compute specific libraries to link with.
  561. cmNinjaDeps explicitDeps = this->GetObjects();
  562. cmNinjaDeps implicitDeps = this->ComputeLinkDeps(this->TargetLinkLanguage);
  563. std::string frameworkPath;
  564. std::string linkPath;
  565. std::string createRule = genTarget.GetCreateRuleVariable(
  566. this->TargetLinkLanguage, this->GetConfigName());
  567. const bool useWatcomQuote =
  568. this->GetMakefile()->IsOn(createRule + "_USE_WATCOM_QUOTE");
  569. cmLocalNinjaGenerator& localGen = *this->GetLocalGenerator();
  570. vars["TARGET_FILE"] =
  571. localGen.ConvertToOutputFormat(targetOutputReal, cmOutputConverter::SHELL);
  572. std::unique_ptr<cmLinkLineComputer> linkLineComputer(
  573. new cmNinjaLinkLineDeviceComputer(
  574. this->GetLocalGenerator(),
  575. this->GetLocalGenerator()->GetStateSnapshot().GetDirectory(),
  576. this->GetGlobalGenerator()));
  577. linkLineComputer->SetUseWatcomQuote(useWatcomQuote);
  578. localGen.GetTargetFlags(
  579. linkLineComputer.get(), this->GetConfigName(), vars["LINK_LIBRARIES"],
  580. vars["FLAGS"], vars["LINK_FLAGS"], frameworkPath, linkPath, &genTarget);
  581. this->addPoolNinjaVariable("JOB_POOL_LINK", &genTarget, vars);
  582. vars["LINK_FLAGS"] =
  583. cmGlobalNinjaGenerator::EncodeLiteral(vars["LINK_FLAGS"]);
  584. vars["MANIFESTS"] = this->GetManifests();
  585. vars["LINK_PATH"] = frameworkPath + linkPath;
  586. // Compute architecture specific link flags. Yes, these go into a different
  587. // variable for executables, probably due to a mistake made when duplicating
  588. // code between the Makefile executable and library generators.
  589. if (targetType == cmStateEnums::EXECUTABLE) {
  590. std::string t = vars["FLAGS"];
  591. localGen.AddArchitectureFlags(t, &genTarget, cudaLinkLanguage, cfgName);
  592. vars["FLAGS"] = t;
  593. } else {
  594. std::string t = vars["ARCH_FLAGS"];
  595. localGen.AddArchitectureFlags(t, &genTarget, cudaLinkLanguage, cfgName);
  596. vars["ARCH_FLAGS"] = t;
  597. t.clear();
  598. localGen.AddLanguageFlagsForLinking(t, &genTarget, cudaLinkLanguage,
  599. cfgName);
  600. vars["LANGUAGE_COMPILE_FLAGS"] = t;
  601. }
  602. if (this->GetGeneratorTarget()->HasSOName(cfgName)) {
  603. vars["SONAME_FLAG"] =
  604. this->GetMakefile()->GetSONameFlag(this->TargetLinkLanguage);
  605. vars["SONAME"] = this->TargetNames.SharedObject;
  606. if (targetType == cmStateEnums::SHARED_LIBRARY) {
  607. std::string install_dir =
  608. this->GetGeneratorTarget()->GetInstallNameDirForBuildTree(cfgName);
  609. if (!install_dir.empty()) {
  610. vars["INSTALLNAME_DIR"] = localGen.ConvertToOutputFormat(
  611. install_dir, cmOutputConverter::SHELL);
  612. }
  613. }
  614. }
  615. if (!this->TargetNames.ImportLibrary.empty()) {
  616. const std::string impLibPath = localGen.ConvertToOutputFormat(
  617. targetOutputImplib, cmOutputConverter::SHELL);
  618. vars["TARGET_IMPLIB"] = impLibPath;
  619. EnsureParentDirectoryExists(impLibPath);
  620. }
  621. const std::string objPath = GetGeneratorTarget()->GetSupportDirectory();
  622. vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  623. this->ConvertToNinjaPath(objPath), cmOutputConverter::SHELL);
  624. EnsureDirectoryExists(objPath);
  625. this->SetMsvcTargetPdbVariable(vars);
  626. if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
  627. // ar.exe can't handle backslashes in rsp files (implicitly used by gcc)
  628. std::string& linkLibraries = vars["LINK_LIBRARIES"];
  629. std::replace(linkLibraries.begin(), linkLibraries.end(), '\\', '/');
  630. std::string& link_path = vars["LINK_PATH"];
  631. std::replace(link_path.begin(), link_path.end(), '\\', '/');
  632. }
  633. cmGlobalNinjaGenerator& globalGen = *this->GetGlobalGenerator();
  634. // Device linking currently doesn't support response files so
  635. // do not check if the user has explicitly forced a response file.
  636. int const commandLineLengthLimit =
  637. static_cast<int>(cmSystemTools::CalculateCommandLineLengthLimit()) -
  638. globalGen.GetRuleCmdLength(this->LanguageLinkerDeviceRule());
  639. const std::string rspfile = this->ConvertToNinjaPath(
  640. std::string("CMakeFiles/") + genTarget.GetName() + ".rsp");
  641. // Gather order-only dependencies.
  642. cmNinjaDeps orderOnlyDeps;
  643. this->GetLocalGenerator()->AppendTargetDepends(this->GetGeneratorTarget(),
  644. orderOnlyDeps);
  645. // Write the build statement for this target.
  646. bool usedResponseFile = false;
  647. globalGen.WriteBuild(this->GetBuildFileStream(), comment.str(),
  648. this->LanguageLinkerDeviceRule(), outputs,
  649. /*implicitOuts=*/cmNinjaDeps(), explicitDeps,
  650. implicitDeps, orderOnlyDeps, vars, rspfile,
  651. commandLineLengthLimit, &usedResponseFile);
  652. this->WriteDeviceLinkRule(false);
  653. }
  654. void cmNinjaNormalTargetGenerator::WriteLinkStatement()
  655. {
  656. cmGeneratorTarget& gt = *this->GetGeneratorTarget();
  657. const std::string cfgName = this->GetConfigName();
  658. std::string targetOutput = ConvertToNinjaPath(gt.GetFullPath(cfgName));
  659. std::string targetOutputReal = ConvertToNinjaPath(
  660. gt.GetFullPath(cfgName, cmStateEnums::RuntimeBinaryArtifact,
  661. /*realname=*/true));
  662. std::string targetOutputImplib = ConvertToNinjaPath(
  663. gt.GetFullPath(cfgName, cmStateEnums::ImportLibraryArtifact));
  664. if (gt.IsAppBundleOnApple()) {
  665. // Create the app bundle
  666. std::string outpath = gt.GetDirectory(cfgName);
  667. this->OSXBundleGenerator->CreateAppBundle(this->TargetNames.Output,
  668. outpath);
  669. // Calculate the output path
  670. targetOutput = outpath;
  671. targetOutput += "/";
  672. targetOutput += this->TargetNames.Output;
  673. targetOutput = this->ConvertToNinjaPath(targetOutput);
  674. targetOutputReal = outpath;
  675. targetOutputReal += "/";
  676. targetOutputReal += this->TargetNames.Real;
  677. targetOutputReal = this->ConvertToNinjaPath(targetOutputReal);
  678. } else if (gt.IsFrameworkOnApple()) {
  679. // Create the library framework.
  680. this->OSXBundleGenerator->CreateFramework(this->TargetNames.Output,
  681. gt.GetDirectory(cfgName));
  682. } else if (gt.IsCFBundleOnApple()) {
  683. // Create the core foundation bundle.
  684. this->OSXBundleGenerator->CreateCFBundle(this->TargetNames.Output,
  685. gt.GetDirectory(cfgName));
  686. }
  687. // Write comments.
  688. cmGlobalNinjaGenerator::WriteDivider(this->GetBuildFileStream());
  689. const cmStateEnums::TargetType targetType = gt.GetType();
  690. this->GetBuildFileStream()
  691. << "# Link build statements for " << cmState::GetTargetTypeName(targetType)
  692. << " target " << this->GetTargetName() << "\n\n";
  693. cmNinjaDeps emptyDeps;
  694. cmNinjaVars vars;
  695. // Compute the comment.
  696. std::ostringstream comment;
  697. comment << "Link the " << this->GetVisibleTypeName() << " "
  698. << targetOutputReal;
  699. // Compute outputs.
  700. cmNinjaDeps outputs;
  701. outputs.push_back(targetOutputReal);
  702. if (this->TargetLinkLanguage == "Swift") {
  703. if (const char* name = gt.GetProperty("SWIFT_MODULE_NAME")) {
  704. vars["TARGET_SWIFT_DOC"] = std::string(name) + ".swiftdoc";
  705. vars["TARGET_SWIFT_MODULE"] = std::string(name) + ".swiftmodule";
  706. } else {
  707. vars["TARGET_SWIFT_DOC"] = gt.GetName() + ".swiftdoc";
  708. vars["TARGET_SWIFT_MODULE"] = gt.GetName() + ".swiftmodule";
  709. }
  710. outputs.push_back(vars["TARGET_SWIFT_DOC"]);
  711. outputs.push_back(vars["TARGET_SWIFT_MODULE"]);
  712. cmLocalNinjaGenerator& localGen = *this->GetLocalGenerator();
  713. std::string partials;
  714. std::vector<cmSourceFile const*> sources;
  715. gt.GetObjectSources(sources, this->GetConfigName());
  716. for (cmSourceFile const* source : sources) {
  717. partials += " ";
  718. if (const char* partial = source->GetProperty("SWIFT_PARTIAL_MODULE")) {
  719. partials += partial;
  720. } else {
  721. partials += localGen.GetTargetDirectory(&gt) + "/" +
  722. gt.GetObjectName(source) + ".swiftmodule";
  723. }
  724. }
  725. vars["SWIFT_PARTIAL_MODULES"] = partials;
  726. }
  727. // Compute specific libraries to link with.
  728. cmNinjaDeps explicitDeps = this->GetObjects();
  729. cmNinjaDeps implicitDeps = this->ComputeLinkDeps(this->TargetLinkLanguage);
  730. if (!this->DeviceLinkObject.empty()) {
  731. explicitDeps.push_back(this->DeviceLinkObject);
  732. }
  733. cmMakefile* mf = this->GetMakefile();
  734. std::string frameworkPath;
  735. std::string linkPath;
  736. std::string createRule =
  737. gt.GetCreateRuleVariable(this->TargetLinkLanguage, this->GetConfigName());
  738. bool useWatcomQuote = mf->IsOn(createRule + "_USE_WATCOM_QUOTE");
  739. cmLocalNinjaGenerator& localGen = *this->GetLocalGenerator();
  740. vars["TARGET_FILE"] =
  741. localGen.ConvertToOutputFormat(targetOutputReal, cmOutputConverter::SHELL);
  742. std::unique_ptr<cmLinkLineComputer> linkLineComputer(
  743. this->GetGlobalGenerator()->CreateLinkLineComputer(
  744. this->GetLocalGenerator(),
  745. this->GetLocalGenerator()->GetStateSnapshot().GetDirectory()));
  746. linkLineComputer->SetUseWatcomQuote(useWatcomQuote);
  747. localGen.GetTargetFlags(linkLineComputer.get(), this->GetConfigName(),
  748. vars["LINK_LIBRARIES"], vars["FLAGS"],
  749. vars["LINK_FLAGS"], frameworkPath, linkPath, &gt);
  750. // Add OS X version flags, if any.
  751. if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
  752. this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  753. this->AppendOSXVerFlag(vars["LINK_FLAGS"], this->TargetLinkLanguage,
  754. "COMPATIBILITY", true);
  755. this->AppendOSXVerFlag(vars["LINK_FLAGS"], this->TargetLinkLanguage,
  756. "CURRENT", false);
  757. }
  758. this->addPoolNinjaVariable("JOB_POOL_LINK", &gt, vars);
  759. this->AddModuleDefinitionFlag(linkLineComputer.get(), vars["LINK_FLAGS"]);
  760. vars["LINK_FLAGS"] =
  761. cmGlobalNinjaGenerator::EncodeLiteral(vars["LINK_FLAGS"]);
  762. vars["MANIFESTS"] = this->GetManifests();
  763. vars["LINK_PATH"] = frameworkPath + linkPath;
  764. std::string lwyuFlags;
  765. if (gt.GetPropertyAsBool("LINK_WHAT_YOU_USE")) {
  766. lwyuFlags = " -Wl,--no-as-needed";
  767. }
  768. // Compute architecture specific link flags. Yes, these go into a different
  769. // variable for executables, probably due to a mistake made when duplicating
  770. // code between the Makefile executable and library generators.
  771. if (targetType == cmStateEnums::EXECUTABLE) {
  772. std::string t = vars["FLAGS"];
  773. localGen.AddArchitectureFlags(t, &gt, TargetLinkLanguage, cfgName);
  774. t += lwyuFlags;
  775. vars["FLAGS"] = t;
  776. } else {
  777. std::string t = vars["ARCH_FLAGS"];
  778. localGen.AddArchitectureFlags(t, &gt, TargetLinkLanguage, cfgName);
  779. vars["ARCH_FLAGS"] = t;
  780. t.clear();
  781. t += lwyuFlags;
  782. localGen.AddLanguageFlagsForLinking(t, &gt, TargetLinkLanguage, cfgName);
  783. vars["LANGUAGE_COMPILE_FLAGS"] = t;
  784. }
  785. if (this->GetGeneratorTarget()->HasSOName(cfgName)) {
  786. vars["SONAME_FLAG"] = mf->GetSONameFlag(this->TargetLinkLanguage);
  787. vars["SONAME"] = this->TargetNames.SharedObject;
  788. if (targetType == cmStateEnums::SHARED_LIBRARY) {
  789. std::string install_dir =
  790. this->GetGeneratorTarget()->GetInstallNameDirForBuildTree(cfgName);
  791. if (!install_dir.empty()) {
  792. vars["INSTALLNAME_DIR"] = localGen.ConvertToOutputFormat(
  793. install_dir, cmOutputConverter::SHELL);
  794. }
  795. }
  796. }
  797. cmNinjaDeps byproducts;
  798. if (!this->TargetNames.ImportLibrary.empty()) {
  799. const std::string impLibPath = localGen.ConvertToOutputFormat(
  800. targetOutputImplib, cmOutputConverter::SHELL);
  801. vars["TARGET_IMPLIB"] = impLibPath;
  802. EnsureParentDirectoryExists(impLibPath);
  803. if (gt.HasImportLibrary(cfgName)) {
  804. byproducts.push_back(targetOutputImplib);
  805. }
  806. }
  807. if (!this->SetMsvcTargetPdbVariable(vars)) {
  808. // It is common to place debug symbols at a specific place,
  809. // so we need a plain target name in the rule available.
  810. std::string prefix;
  811. std::string base;
  812. std::string suffix;
  813. this->GetGeneratorTarget()->GetFullNameComponents(prefix, base, suffix);
  814. std::string dbg_suffix = ".dbg";
  815. // TODO: Where to document?
  816. if (mf->GetDefinition("CMAKE_DEBUG_SYMBOL_SUFFIX")) {
  817. dbg_suffix = mf->GetDefinition("CMAKE_DEBUG_SYMBOL_SUFFIX");
  818. }
  819. vars["TARGET_PDB"] = base + suffix + dbg_suffix;
  820. }
  821. const std::string objPath = GetGeneratorTarget()->GetSupportDirectory();
  822. vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  823. this->ConvertToNinjaPath(objPath), cmOutputConverter::SHELL);
  824. EnsureDirectoryExists(objPath);
  825. if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
  826. // ar.exe can't handle backslashes in rsp files (implicitly used by gcc)
  827. std::string& linkLibraries = vars["LINK_LIBRARIES"];
  828. std::replace(linkLibraries.begin(), linkLibraries.end(), '\\', '/');
  829. std::string& link_path = vars["LINK_PATH"];
  830. std::replace(link_path.begin(), link_path.end(), '\\', '/');
  831. }
  832. const std::vector<cmCustomCommand>* cmdLists[3] = {
  833. &gt.GetPreBuildCommands(), &gt.GetPreLinkCommands(),
  834. &gt.GetPostBuildCommands()
  835. };
  836. std::vector<std::string> preLinkCmdLines, postBuildCmdLines;
  837. std::vector<std::string>* cmdLineLists[3] = { &preLinkCmdLines,
  838. &preLinkCmdLines,
  839. &postBuildCmdLines };
  840. for (unsigned i = 0; i != 3; ++i) {
  841. for (cmCustomCommand const& cc : *cmdLists[i]) {
  842. cmCustomCommandGenerator ccg(cc, cfgName, this->GetLocalGenerator());
  843. localGen.AppendCustomCommandLines(ccg, *cmdLineLists[i]);
  844. std::vector<std::string> const& ccByproducts = ccg.GetByproducts();
  845. std::transform(ccByproducts.begin(), ccByproducts.end(),
  846. std::back_inserter(byproducts), MapToNinjaPath());
  847. }
  848. }
  849. // maybe create .def file from list of objects
  850. cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  851. gt.GetModuleDefinitionInfo(this->GetConfigName());
  852. if (mdi && mdi->DefFileGenerated) {
  853. std::string cmakeCommand =
  854. this->GetLocalGenerator()->ConvertToOutputFormat(
  855. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  856. std::string cmd = cmakeCommand;
  857. cmd += " -E __create_def ";
  858. cmd += this->GetLocalGenerator()->ConvertToOutputFormat(
  859. mdi->DefFile, cmOutputConverter::SHELL);
  860. cmd += " ";
  861. std::string obj_list_file = mdi->DefFile + ".objs";
  862. cmd += this->GetLocalGenerator()->ConvertToOutputFormat(
  863. obj_list_file, cmOutputConverter::SHELL);
  864. preLinkCmdLines.push_back(std::move(cmd));
  865. // create a list of obj files for the -E __create_def to read
  866. cmGeneratedFileStream fout(obj_list_file);
  867. if (mdi->WindowsExportAllSymbols) {
  868. cmNinjaDeps objs = this->GetObjects();
  869. for (std::string const& obj : objs) {
  870. if (cmHasLiteralSuffix(obj, ".obj")) {
  871. fout << obj << "\n";
  872. }
  873. }
  874. }
  875. for (cmSourceFile const* src : mdi->Sources) {
  876. fout << src->GetFullPath() << "\n";
  877. }
  878. }
  879. // If we have any PRE_LINK commands, we need to go back to CMAKE_BINARY_DIR
  880. // for
  881. // the link commands.
  882. if (!preLinkCmdLines.empty()) {
  883. const std::string homeOutDir = localGen.ConvertToOutputFormat(
  884. localGen.GetBinaryDirectory(), cmOutputConverter::SHELL);
  885. preLinkCmdLines.push_back("cd " + homeOutDir);
  886. }
  887. vars["PRE_LINK"] = localGen.BuildCommandLine(preLinkCmdLines, "pre-link",
  888. this->GeneratorTarget);
  889. std::string postBuildCmdLine = localGen.BuildCommandLine(
  890. postBuildCmdLines, "post-build", this->GeneratorTarget);
  891. cmNinjaVars symlinkVars;
  892. bool const symlinkNeeded =
  893. (targetOutput != targetOutputReal && !gt.IsFrameworkOnApple());
  894. if (!symlinkNeeded) {
  895. vars["POST_BUILD"] = postBuildCmdLine;
  896. } else {
  897. vars["POST_BUILD"] = cmGlobalNinjaGenerator::SHELL_NOOP;
  898. symlinkVars["POST_BUILD"] = postBuildCmdLine;
  899. }
  900. cmGlobalNinjaGenerator& globalGen = *this->GetGlobalGenerator();
  901. bool const lang_supports_response =
  902. !(this->TargetLinkLanguage == "RC" || this->TargetLinkLanguage == "CUDA");
  903. int commandLineLengthLimit = -1;
  904. if (!lang_supports_response || !this->ForceResponseFile()) {
  905. commandLineLengthLimit =
  906. static_cast<int>(cmSystemTools::CalculateCommandLineLengthLimit()) -
  907. globalGen.GetRuleCmdLength(this->LanguageLinkerRule());
  908. }
  909. const std::string rspfile = this->ConvertToNinjaPath(
  910. std::string("CMakeFiles/") + gt.GetName() + ".rsp");
  911. // Gather order-only dependencies.
  912. cmNinjaDeps orderOnlyDeps;
  913. this->GetLocalGenerator()->AppendTargetDepends(this->GetGeneratorTarget(),
  914. orderOnlyDeps);
  915. // Ninja should restat after linking if and only if there are byproducts.
  916. vars["RESTAT"] = byproducts.empty() ? "" : "1";
  917. for (std::string const& o : byproducts) {
  918. this->GetGlobalGenerator()->SeenCustomCommandOutput(o);
  919. outputs.push_back(o);
  920. }
  921. // Write the build statement for this target.
  922. bool usedResponseFile = false;
  923. globalGen.WriteBuild(this->GetBuildFileStream(), comment.str(),
  924. this->LanguageLinkerRule(), outputs,
  925. /*implicitOuts=*/cmNinjaDeps(), explicitDeps,
  926. implicitDeps, orderOnlyDeps, vars, rspfile,
  927. commandLineLengthLimit, &usedResponseFile);
  928. this->WriteLinkRule(usedResponseFile);
  929. if (symlinkNeeded) {
  930. if (targetType == cmStateEnums::EXECUTABLE) {
  931. globalGen.WriteBuild(
  932. this->GetBuildFileStream(),
  933. "Create executable symlink " + targetOutput,
  934. "CMAKE_SYMLINK_EXECUTABLE", cmNinjaDeps(1, targetOutput),
  935. /*implicitOuts=*/cmNinjaDeps(), cmNinjaDeps(1, targetOutputReal),
  936. emptyDeps, emptyDeps, symlinkVars);
  937. } else {
  938. cmNinjaDeps symlinks;
  939. std::string const soName = this->ConvertToNinjaPath(
  940. this->GetTargetFilePath(this->TargetNames.SharedObject));
  941. // If one link has to be created.
  942. if (targetOutputReal == soName || targetOutput == soName) {
  943. symlinkVars["SONAME"] = soName;
  944. } else {
  945. symlinkVars["SONAME"].clear();
  946. symlinks.push_back(soName);
  947. }
  948. symlinks.push_back(targetOutput);
  949. globalGen.WriteBuild(
  950. this->GetBuildFileStream(), "Create library symlink " + targetOutput,
  951. "CMAKE_SYMLINK_LIBRARY", symlinks,
  952. /*implicitOuts=*/cmNinjaDeps(), cmNinjaDeps(1, targetOutputReal),
  953. emptyDeps, emptyDeps, symlinkVars);
  954. }
  955. }
  956. // Add aliases for the file name and the target name.
  957. globalGen.AddTargetAlias(this->TargetNames.Output, &gt);
  958. globalGen.AddTargetAlias(this->GetTargetName(), &gt);
  959. }
  960. void cmNinjaNormalTargetGenerator::WriteObjectLibStatement()
  961. {
  962. // Write a phony output that depends on all object files.
  963. cmNinjaDeps outputs;
  964. this->GetLocalGenerator()->AppendTargetOutputs(this->GetGeneratorTarget(),
  965. outputs);
  966. cmNinjaDeps depends = this->GetObjects();
  967. this->GetGlobalGenerator()->WritePhonyBuild(
  968. this->GetBuildFileStream(), "Object library " + this->GetTargetName(),
  969. outputs, depends);
  970. // Add aliases for the target name.
  971. this->GetGlobalGenerator()->AddTargetAlias(this->GetTargetName(),
  972. this->GetGeneratorTarget());
  973. }