cmNinjaNormalTargetGenerator.cxx 41 KB

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