cmNinjaNormalTargetGenerator.cxx 41 KB

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