cmNinjaNormalTargetGenerator.cxx 46 KB

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