cmNinjaNormalTargetGenerator.cxx 47 KB

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