cmNinjaNormalTargetGenerator.cxx 41 KB

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