cmNinjaNormalTargetGenerator.cxx 42 KB

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