cmNinjaNormalTargetGenerator.cxx 42 KB

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