cmNinjaNormalTargetGenerator.cxx 42 KB

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