cmNinjaNormalTargetGenerator.cxx 43 KB

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