cmNinjaNormalTargetGenerator.cxx 41 KB

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