cmNinjaNormalTargetGenerator.cxx 41 KB

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