cmNinjaNormalTargetGenerator.cxx 42 KB

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