cmNinjaNormalTargetGenerator.cxx 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  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 "cmAlgorithms.h"
  5. #include "cmCustomCommand.h"
  6. #include "cmCustomCommandGenerator.h"
  7. #include "cmGeneratedFileStream.h"
  8. #include "cmGeneratorTarget.h"
  9. #include "cmGlobalNinjaGenerator.h"
  10. #include "cmLinkLineComputer.h"
  11. #include "cmLocalGenerator.h"
  12. #include "cmLocalNinjaGenerator.h"
  13. #include "cmMakefile.h"
  14. #include "cmNinjaTypes.h"
  15. #include "cmOSXBundleGenerator.h"
  16. #include "cmOutputConverter.h"
  17. #include "cmSourceFile.h"
  18. #include "cmState.h"
  19. #include "cmSystemTools.h"
  20. #include "cmake.h"
  21. #include <algorithm>
  22. #include <assert.h>
  23. #include <iterator>
  24. #include <limits>
  25. #include <map>
  26. #include <set>
  27. #include <sstream>
  28. #include <stddef.h>
  29. #ifndef _WIN32
  30. #include <unistd.h>
  31. #endif
  32. cmNinjaNormalTargetGenerator::cmNinjaNormalTargetGenerator(
  33. cmGeneratorTarget* target)
  34. : cmNinjaTargetGenerator(target)
  35. , TargetNameOut()
  36. , TargetNameSO()
  37. , TargetNameReal()
  38. , TargetNameImport()
  39. , TargetNamePDB()
  40. , TargetLinkLanguage("")
  41. {
  42. this->TargetLinkLanguage = target->GetLinkerLanguage(this->GetConfigName());
  43. if (target->GetType() == cmState::EXECUTABLE) {
  44. this->GetGeneratorTarget()->GetExecutableNames(
  45. this->TargetNameOut, this->TargetNameReal, this->TargetNameImport,
  46. this->TargetNamePDB, GetLocalGenerator()->GetConfigName());
  47. } else {
  48. this->GetGeneratorTarget()->GetLibraryNames(
  49. this->TargetNameOut, this->TargetNameSO, this->TargetNameReal,
  50. this->TargetNameImport, this->TargetNamePDB,
  51. GetLocalGenerator()->GetConfigName());
  52. }
  53. if (target->GetType() != cmState::OBJECT_LIBRARY) {
  54. // on Windows the output dir is already needed at compile time
  55. // ensure the directory exists (OutDir test)
  56. EnsureDirectoryExists(target->GetDirectory(this->GetConfigName()));
  57. }
  58. this->OSXBundleGenerator =
  59. new cmOSXBundleGenerator(target, this->GetConfigName());
  60. this->OSXBundleGenerator->SetMacContentFolders(&this->MacContentFolders);
  61. }
  62. cmNinjaNormalTargetGenerator::~cmNinjaNormalTargetGenerator()
  63. {
  64. delete this->OSXBundleGenerator;
  65. }
  66. void cmNinjaNormalTargetGenerator::Generate()
  67. {
  68. if (this->TargetLinkLanguage.empty()) {
  69. cmSystemTools::Error("CMake can not determine linker language for "
  70. "target: ",
  71. this->GetGeneratorTarget()->GetName().c_str());
  72. return;
  73. }
  74. // Write the rules for each language.
  75. this->WriteLanguagesRules();
  76. // Write the build statements
  77. this->WriteObjectBuildStatements();
  78. if (this->GetGeneratorTarget()->GetType() == cmState::OBJECT_LIBRARY) {
  79. this->WriteObjectLibStatement();
  80. } else {
  81. this->WriteLinkStatement();
  82. }
  83. }
  84. void cmNinjaNormalTargetGenerator::WriteLanguagesRules()
  85. {
  86. #ifdef NINJA_GEN_VERBOSE_FILES
  87. cmGlobalNinjaGenerator::WriteDivider(this->GetRulesFileStream());
  88. this->GetRulesFileStream()
  89. << "# Rules for each languages for "
  90. << cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType())
  91. << " target " << this->GetTargetName() << "\n\n";
  92. #endif
  93. // Write rules for languages compiled in this target.
  94. std::set<std::string> languages;
  95. std::vector<cmSourceFile*> sourceFiles;
  96. this->GetGeneratorTarget()->GetSourceFiles(
  97. sourceFiles, this->GetMakefile()->GetSafeDefinition("CMAKE_BUILD_TYPE"));
  98. for (std::vector<cmSourceFile*>::const_iterator i = sourceFiles.begin();
  99. i != sourceFiles.end(); ++i) {
  100. const std::string& lang = (*i)->GetLanguage();
  101. if (!lang.empty()) {
  102. languages.insert(lang);
  103. }
  104. }
  105. for (std::set<std::string>::const_iterator l = languages.begin();
  106. l != languages.end(); ++l) {
  107. this->WriteLanguageRules(*l);
  108. }
  109. }
  110. const char* cmNinjaNormalTargetGenerator::GetVisibleTypeName() const
  111. {
  112. switch (this->GetGeneratorTarget()->GetType()) {
  113. case cmState::STATIC_LIBRARY:
  114. return "static library";
  115. case cmState::SHARED_LIBRARY:
  116. return "shared library";
  117. case cmState::MODULE_LIBRARY:
  118. if (this->GetGeneratorTarget()->IsCFBundleOnApple()) {
  119. return "CFBundle shared module";
  120. } else {
  121. return "shared module";
  122. }
  123. case cmState::EXECUTABLE:
  124. return "executable";
  125. default:
  126. return CM_NULLPTR;
  127. }
  128. }
  129. std::string cmNinjaNormalTargetGenerator::LanguageLinkerRule() const
  130. {
  131. return this->TargetLinkLanguage + "_" +
  132. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()) +
  133. "_LINKER__" + cmGlobalNinjaGenerator::EncodeRuleName(
  134. this->GetGeneratorTarget()->GetName());
  135. }
  136. struct cmNinjaRemoveNoOpCommands
  137. {
  138. bool operator()(std::string const& cmd)
  139. {
  140. return cmd.empty() || cmd[0] == ':';
  141. }
  142. };
  143. void cmNinjaNormalTargetGenerator::WriteLinkRule(bool useResponseFile)
  144. {
  145. cmState::TargetType targetType = this->GetGeneratorTarget()->GetType();
  146. std::string ruleName = this->LanguageLinkerRule();
  147. // Select whether to use a response file for objects.
  148. std::string rspfile;
  149. std::string rspcontent;
  150. if (!this->GetGlobalGenerator()->HasRule(ruleName)) {
  151. cmLocalGenerator::RuleVariables vars;
  152. vars.RuleLauncher = "RULE_LAUNCH_LINK";
  153. vars.CMTarget = this->GetGeneratorTarget();
  154. vars.Language = this->TargetLinkLanguage.c_str();
  155. std::string responseFlag;
  156. if (!useResponseFile) {
  157. vars.Objects = "$in";
  158. vars.LinkLibraries = "$LINK_PATH $LINK_LIBRARIES";
  159. } else {
  160. std::string cmakeVarLang = "CMAKE_";
  161. cmakeVarLang += this->TargetLinkLanguage;
  162. // build response file name
  163. std::string cmakeLinkVar = cmakeVarLang + "_RESPONSE_FILE_LINK_FLAG";
  164. const char* flag = GetMakefile()->GetDefinition(cmakeLinkVar);
  165. if (flag) {
  166. responseFlag = flag;
  167. } else {
  168. responseFlag = "@";
  169. }
  170. rspfile = "$RSP_FILE";
  171. responseFlag += rspfile;
  172. // build response file content
  173. if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
  174. rspcontent = "$in";
  175. } else {
  176. rspcontent = "$in_newline";
  177. }
  178. rspcontent += " $LINK_PATH $LINK_LIBRARIES";
  179. vars.Objects = responseFlag.c_str();
  180. vars.LinkLibraries = "";
  181. }
  182. vars.ObjectDir = "$OBJECT_DIR";
  183. vars.Target = "$TARGET_FILE";
  184. vars.SONameFlag = "$SONAME_FLAG";
  185. vars.TargetSOName = "$SONAME";
  186. vars.TargetInstallNameDir = "$INSTALLNAME_DIR";
  187. vars.TargetPDB = "$TARGET_PDB";
  188. // Setup the target version.
  189. std::string targetVersionMajor;
  190. std::string targetVersionMinor;
  191. {
  192. std::ostringstream majorStream;
  193. std::ostringstream minorStream;
  194. int major;
  195. int minor;
  196. this->GetGeneratorTarget()->GetTargetVersion(major, minor);
  197. majorStream << major;
  198. minorStream << minor;
  199. targetVersionMajor = majorStream.str();
  200. targetVersionMinor = minorStream.str();
  201. }
  202. vars.TargetVersionMajor = targetVersionMajor.c_str();
  203. vars.TargetVersionMinor = targetVersionMinor.c_str();
  204. vars.Flags = "$FLAGS";
  205. vars.LinkFlags = "$LINK_FLAGS";
  206. vars.Manifests = "$MANIFESTS";
  207. std::string langFlags;
  208. if (targetType != cmState::EXECUTABLE) {
  209. langFlags += "$LANGUAGE_COMPILE_FLAGS $ARCH_FLAGS";
  210. vars.LanguageCompileFlags = langFlags.c_str();
  211. }
  212. // Rule for linking library/executable.
  213. std::vector<std::string> linkCmds = this->ComputeLinkCmd();
  214. for (std::vector<std::string>::iterator i = linkCmds.begin();
  215. i != linkCmds.end(); ++i) {
  216. this->GetLocalGenerator()->ExpandRuleVariables(*i, vars);
  217. }
  218. {
  219. // If there is no ranlib the command will be ":". Skip it.
  220. std::vector<std::string>::iterator newEnd = std::remove_if(
  221. linkCmds.begin(), linkCmds.end(), cmNinjaRemoveNoOpCommands());
  222. linkCmds.erase(newEnd, linkCmds.end());
  223. }
  224. linkCmds.insert(linkCmds.begin(), "$PRE_LINK");
  225. linkCmds.push_back("$POST_BUILD");
  226. std::string linkCmd =
  227. this->GetLocalGenerator()->BuildCommandLine(linkCmds);
  228. // Write the linker rule with response file if needed.
  229. std::ostringstream comment;
  230. comment << "Rule for linking " << this->TargetLinkLanguage << " "
  231. << this->GetVisibleTypeName() << ".";
  232. std::ostringstream description;
  233. description << "Linking " << this->TargetLinkLanguage << " "
  234. << this->GetVisibleTypeName() << " $TARGET_FILE";
  235. this->GetGlobalGenerator()->AddRule(ruleName, linkCmd, description.str(),
  236. comment.str(),
  237. /*depfile*/ "",
  238. /*deptype*/ "", rspfile, rspcontent,
  239. /*restat*/ "$RESTAT",
  240. /*generator*/ false);
  241. }
  242. if (this->TargetNameOut != this->TargetNameReal &&
  243. !this->GetGeneratorTarget()->IsFrameworkOnApple()) {
  244. std::string cmakeCommand =
  245. this->GetLocalGenerator()->ConvertToOutputFormat(
  246. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  247. if (targetType == cmState::EXECUTABLE) {
  248. this->GetGlobalGenerator()->AddRule(
  249. "CMAKE_SYMLINK_EXECUTABLE",
  250. cmakeCommand + " -E cmake_symlink_executable"
  251. " $in $out && $POST_BUILD",
  252. "Creating executable symlink $out", "Rule for creating "
  253. "executable symlink.",
  254. /*depfile*/ "",
  255. /*deptype*/ "",
  256. /*rspfile*/ "",
  257. /*rspcontent*/ "",
  258. /*restat*/ "",
  259. /*generator*/ false);
  260. } else {
  261. this->GetGlobalGenerator()->AddRule(
  262. "CMAKE_SYMLINK_LIBRARY",
  263. cmakeCommand + " -E cmake_symlink_library"
  264. " $in $SONAME $out && $POST_BUILD",
  265. "Creating library symlink $out", "Rule for creating "
  266. "library symlink.",
  267. /*depfile*/ "",
  268. /*deptype*/ "",
  269. /*rspfile*/ "",
  270. /*rspcontent*/ "",
  271. /*restat*/ "",
  272. /*generator*/ false);
  273. }
  274. }
  275. }
  276. std::vector<std::string> cmNinjaNormalTargetGenerator::ComputeLinkCmd()
  277. {
  278. std::vector<std::string> linkCmds;
  279. cmMakefile* mf = this->GetMakefile();
  280. {
  281. std::string linkCmdVar = this->GetGeneratorTarget()->GetCreateRuleVariable(
  282. this->TargetLinkLanguage, this->GetConfigName());
  283. const char* linkCmd = mf->GetDefinition(linkCmdVar);
  284. if (linkCmd) {
  285. cmSystemTools::ExpandListArgument(linkCmd, linkCmds);
  286. if (this->GetGeneratorTarget()->GetProperty("LINK_WHAT_YOU_USE")) {
  287. std::string cmakeCommand =
  288. this->GetLocalGenerator()->ConvertToOutputFormat(
  289. cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
  290. cmakeCommand += " -E __run_iwyu --lwyu=";
  291. cmGeneratorTarget& gt = *this->GetGeneratorTarget();
  292. const std::string cfgName = this->GetConfigName();
  293. std::string targetOutput = ConvertToNinjaPath(gt.GetFullPath(cfgName));
  294. std::string targetOutputReal =
  295. this->ConvertToNinjaPath(gt.GetFullPath(cfgName,
  296. /*implib=*/false,
  297. /*realname=*/true));
  298. cmakeCommand += targetOutputReal;
  299. cmakeCommand += " || true";
  300. linkCmds.push_back(cmakeCommand);
  301. }
  302. return linkCmds;
  303. }
  304. }
  305. switch (this->GetGeneratorTarget()->GetType()) {
  306. case cmState::STATIC_LIBRARY: {
  307. // We have archive link commands set. First, delete the existing archive.
  308. {
  309. std::string cmakeCommand =
  310. this->GetLocalGenerator()->ConvertToOutputFormat(
  311. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  312. linkCmds.push_back(cmakeCommand + " -E remove $TARGET_FILE");
  313. }
  314. // TODO: Use ARCHIVE_APPEND for archives over a certain size.
  315. {
  316. std::string linkCmdVar = "CMAKE_";
  317. linkCmdVar += this->TargetLinkLanguage;
  318. linkCmdVar += "_ARCHIVE_CREATE";
  319. const char* linkCmd = mf->GetRequiredDefinition(linkCmdVar);
  320. cmSystemTools::ExpandListArgument(linkCmd, linkCmds);
  321. }
  322. {
  323. std::string linkCmdVar = "CMAKE_";
  324. linkCmdVar += this->TargetLinkLanguage;
  325. linkCmdVar += "_ARCHIVE_FINISH";
  326. const char* linkCmd = mf->GetRequiredDefinition(linkCmdVar);
  327. cmSystemTools::ExpandListArgument(linkCmd, linkCmds);
  328. }
  329. return linkCmds;
  330. }
  331. case cmState::SHARED_LIBRARY:
  332. case cmState::MODULE_LIBRARY:
  333. case cmState::EXECUTABLE:
  334. break;
  335. default:
  336. assert(0 && "Unexpected target type");
  337. }
  338. return std::vector<std::string>();
  339. }
  340. static int calculateCommandLineLengthLimit(int linkRuleLength)
  341. {
  342. static int const limits[] = {
  343. #ifdef _WIN32
  344. 8000,
  345. #endif
  346. #if defined(_SC_ARG_MAX)
  347. // for instance ARG_MAX is 2096152 on Ubuntu or 262144 on Mac
  348. ((int)sysconf(_SC_ARG_MAX)) - 1000,
  349. #endif
  350. #if defined(__linux)
  351. // #define MAX_ARG_STRLEN (PAGE_SIZE * 32) in Linux's binfmts.h
  352. ((int)sysconf(_SC_PAGESIZE) * 32) - 1000,
  353. #endif
  354. std::numeric_limits<int>::max()
  355. };
  356. size_t const arrSz = cmArraySize(limits);
  357. int const sz = *std::min_element(limits, limits + arrSz);
  358. if (sz == std::numeric_limits<int>::max()) {
  359. return 0;
  360. }
  361. return sz - linkRuleLength;
  362. }
  363. void cmNinjaNormalTargetGenerator::WriteLinkStatement()
  364. {
  365. cmGeneratorTarget& gt = *this->GetGeneratorTarget();
  366. const std::string cfgName = this->GetConfigName();
  367. std::string targetOutput = ConvertToNinjaPath(gt.GetFullPath(cfgName));
  368. std::string targetOutputReal =
  369. ConvertToNinjaPath(gt.GetFullPath(cfgName,
  370. /*implib=*/false,
  371. /*realname=*/true));
  372. std::string targetOutputImplib =
  373. ConvertToNinjaPath(gt.GetFullPath(cfgName,
  374. /*implib=*/true));
  375. if (gt.IsAppBundleOnApple()) {
  376. // Create the app bundle
  377. std::string outpath = gt.GetDirectory(cfgName);
  378. this->OSXBundleGenerator->CreateAppBundle(this->TargetNameOut, outpath);
  379. // Calculate the output path
  380. targetOutput = outpath;
  381. targetOutput += "/";
  382. targetOutput += this->TargetNameOut;
  383. targetOutput = this->ConvertToNinjaPath(targetOutput);
  384. targetOutputReal = outpath;
  385. targetOutputReal += "/";
  386. targetOutputReal += this->TargetNameReal;
  387. targetOutputReal = this->ConvertToNinjaPath(targetOutputReal);
  388. } else if (gt.IsFrameworkOnApple()) {
  389. // Create the library framework.
  390. this->OSXBundleGenerator->CreateFramework(this->TargetNameOut,
  391. gt.GetDirectory(cfgName));
  392. } else if (gt.IsCFBundleOnApple()) {
  393. // Create the core foundation bundle.
  394. this->OSXBundleGenerator->CreateCFBundle(this->TargetNameOut,
  395. gt.GetDirectory(cfgName));
  396. }
  397. // Write comments.
  398. cmGlobalNinjaGenerator::WriteDivider(this->GetBuildFileStream());
  399. const cmState::TargetType targetType = gt.GetType();
  400. this->GetBuildFileStream() << "# Link build statements for "
  401. << cmState::GetTargetTypeName(targetType)
  402. << " target " << this->GetTargetName() << "\n\n";
  403. cmNinjaDeps emptyDeps;
  404. cmNinjaVars vars;
  405. // Compute the comment.
  406. std::ostringstream comment;
  407. comment << "Link the " << this->GetVisibleTypeName() << " "
  408. << targetOutputReal;
  409. // Compute outputs.
  410. cmNinjaDeps outputs;
  411. outputs.push_back(targetOutputReal);
  412. // Compute specific libraries to link with.
  413. cmNinjaDeps explicitDeps = this->GetObjects();
  414. cmNinjaDeps implicitDeps = this->ComputeLinkDeps();
  415. cmMakefile* mf = this->GetMakefile();
  416. std::string frameworkPath;
  417. std::string linkPath;
  418. cmGeneratorTarget& genTarget = *this->GetGeneratorTarget();
  419. std::string createRule = genTarget.GetCreateRuleVariable(
  420. this->TargetLinkLanguage, this->GetConfigName());
  421. bool useWatcomQuote = mf->IsOn(createRule + "_USE_WATCOM_QUOTE");
  422. cmLocalNinjaGenerator& localGen = *this->GetLocalGenerator();
  423. vars["TARGET_FILE"] =
  424. localGen.ConvertToOutputFormat(targetOutputReal, cmOutputConverter::SHELL);
  425. CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer(
  426. this->GetGlobalGenerator()->CreateLinkLineComputer(
  427. this->GetLocalGenerator(),
  428. this->GetLocalGenerator()->GetStateSnapshot().GetDirectory()));
  429. linkLineComputer->SetUseWatcomQuote(useWatcomQuote);
  430. localGen.GetTargetFlags(
  431. linkLineComputer.get(), this->GetConfigName(), vars["LINK_LIBRARIES"],
  432. vars["FLAGS"], vars["LINK_FLAGS"], frameworkPath, linkPath, &genTarget);
  433. if (this->GetMakefile()->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS") &&
  434. (gt.GetType() == cmState::SHARED_LIBRARY ||
  435. gt.IsExecutableWithExports())) {
  436. if (gt.GetPropertyAsBool("WINDOWS_EXPORT_ALL_SYMBOLS")) {
  437. std::string name_of_def_file = gt.GetSupportDirectory();
  438. name_of_def_file += "/" + gt.GetName();
  439. name_of_def_file += ".def ";
  440. vars["LINK_FLAGS"] += " /DEF:";
  441. vars["LINK_FLAGS"] += this->GetLocalGenerator()->ConvertToOutputFormat(
  442. name_of_def_file, cmOutputConverter::SHELL);
  443. }
  444. }
  445. // Add OS X version flags, if any.
  446. if (this->GeneratorTarget->GetType() == cmState::SHARED_LIBRARY ||
  447. this->GeneratorTarget->GetType() == cmState::MODULE_LIBRARY) {
  448. this->AppendOSXVerFlag(vars["LINK_FLAGS"], this->TargetLinkLanguage,
  449. "COMPATIBILITY", true);
  450. this->AppendOSXVerFlag(vars["LINK_FLAGS"], this->TargetLinkLanguage,
  451. "CURRENT", false);
  452. }
  453. this->addPoolNinjaVariable("JOB_POOL_LINK", &gt, vars);
  454. this->AddModuleDefinitionFlag(linkLineComputer.get(), vars["LINK_FLAGS"]);
  455. vars["LINK_FLAGS"] =
  456. cmGlobalNinjaGenerator::EncodeLiteral(vars["LINK_FLAGS"]);
  457. vars["MANIFESTS"] = this->GetManifests();
  458. vars["LINK_PATH"] = frameworkPath + linkPath;
  459. std::string lwyuFlags;
  460. if (genTarget.GetProperty("LINK_WHAT_YOU_USE")) {
  461. lwyuFlags = " -Wl,--no-as-needed";
  462. }
  463. // Compute architecture specific link flags. Yes, these go into a different
  464. // variable for executables, probably due to a mistake made when duplicating
  465. // code between the Makefile executable and library generators.
  466. if (targetType == cmState::EXECUTABLE) {
  467. std::string t = vars["FLAGS"];
  468. localGen.AddArchitectureFlags(t, &genTarget, TargetLinkLanguage, cfgName);
  469. t += lwyuFlags;
  470. vars["FLAGS"] = t;
  471. } else {
  472. std::string t = vars["ARCH_FLAGS"];
  473. localGen.AddArchitectureFlags(t, &genTarget, TargetLinkLanguage, cfgName);
  474. vars["ARCH_FLAGS"] = t;
  475. t = "";
  476. t += lwyuFlags;
  477. localGen.AddLanguageFlags(t, TargetLinkLanguage, cfgName);
  478. vars["LANGUAGE_COMPILE_FLAGS"] = t;
  479. }
  480. if (this->GetGeneratorTarget()->HasSOName(cfgName)) {
  481. vars["SONAME_FLAG"] = mf->GetSONameFlag(this->TargetLinkLanguage);
  482. vars["SONAME"] = this->TargetNameSO;
  483. if (targetType == cmState::SHARED_LIBRARY) {
  484. std::string install_dir =
  485. this->GetGeneratorTarget()->GetInstallNameDirForBuildTree(cfgName);
  486. if (!install_dir.empty()) {
  487. vars["INSTALLNAME_DIR"] = localGen.ConvertToOutputFormat(
  488. install_dir, cmOutputConverter::SHELL);
  489. }
  490. }
  491. }
  492. cmNinjaDeps byproducts;
  493. if (!this->TargetNameImport.empty()) {
  494. const std::string impLibPath = localGen.ConvertToOutputFormat(
  495. targetOutputImplib, cmOutputConverter::SHELL);
  496. vars["TARGET_IMPLIB"] = impLibPath;
  497. EnsureParentDirectoryExists(impLibPath);
  498. if (genTarget.HasImportLibrary()) {
  499. byproducts.push_back(targetOutputImplib);
  500. }
  501. }
  502. if (!this->SetMsvcTargetPdbVariable(vars)) {
  503. // It is common to place debug symbols at a specific place,
  504. // so we need a plain target name in the rule available.
  505. std::string prefix;
  506. std::string base;
  507. std::string suffix;
  508. this->GetGeneratorTarget()->GetFullNameComponents(prefix, base, suffix);
  509. std::string dbg_suffix = ".dbg";
  510. // TODO: Where to document?
  511. if (mf->GetDefinition("CMAKE_DEBUG_SYMBOL_SUFFIX")) {
  512. dbg_suffix = mf->GetDefinition("CMAKE_DEBUG_SYMBOL_SUFFIX");
  513. }
  514. vars["TARGET_PDB"] = base + suffix + dbg_suffix;
  515. }
  516. const std::string objPath = GetGeneratorTarget()->GetSupportDirectory();
  517. vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  518. this->ConvertToNinjaPath(objPath), cmOutputConverter::SHELL);
  519. EnsureDirectoryExists(objPath);
  520. if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
  521. // ar.exe can't handle backslashes in rsp files (implicitly used by gcc)
  522. std::string& linkLibraries = vars["LINK_LIBRARIES"];
  523. std::replace(linkLibraries.begin(), linkLibraries.end(), '\\', '/');
  524. std::string& link_path = vars["LINK_PATH"];
  525. std::replace(link_path.begin(), link_path.end(), '\\', '/');
  526. }
  527. const std::vector<cmCustomCommand>* cmdLists[3] = {
  528. &gt.GetPreBuildCommands(), &gt.GetPreLinkCommands(),
  529. &gt.GetPostBuildCommands()
  530. };
  531. std::vector<std::string> preLinkCmdLines, postBuildCmdLines;
  532. std::vector<std::string>* cmdLineLists[3] = { &preLinkCmdLines,
  533. &preLinkCmdLines,
  534. &postBuildCmdLines };
  535. for (unsigned i = 0; i != 3; ++i) {
  536. for (std::vector<cmCustomCommand>::const_iterator ci =
  537. cmdLists[i]->begin();
  538. ci != cmdLists[i]->end(); ++ci) {
  539. cmCustomCommandGenerator ccg(*ci, cfgName, this->GetLocalGenerator());
  540. localGen.AppendCustomCommandLines(ccg, *cmdLineLists[i]);
  541. std::vector<std::string> const& ccByproducts = ccg.GetByproducts();
  542. std::transform(ccByproducts.begin(), ccByproducts.end(),
  543. std::back_inserter(byproducts), MapToNinjaPath());
  544. }
  545. }
  546. // maybe create .def file from list of objects
  547. if ((gt.GetType() == cmState::SHARED_LIBRARY ||
  548. gt.IsExecutableWithExports()) &&
  549. this->GetMakefile()->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS")) {
  550. if (gt.GetPropertyAsBool("WINDOWS_EXPORT_ALL_SYMBOLS")) {
  551. std::string cmakeCommand =
  552. this->GetLocalGenerator()->ConvertToOutputFormat(
  553. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  554. std::string name_of_def_file = gt.GetSupportDirectory();
  555. name_of_def_file += "/" + gt.GetName();
  556. name_of_def_file += ".def";
  557. std::string cmd = cmakeCommand;
  558. cmd += " -E __create_def ";
  559. cmd += this->GetLocalGenerator()->ConvertToOutputFormat(
  560. name_of_def_file, cmOutputConverter::SHELL);
  561. cmd += " ";
  562. cmNinjaDeps objs = this->GetObjects();
  563. std::string obj_list_file = name_of_def_file;
  564. obj_list_file += ".objs";
  565. cmd += this->GetLocalGenerator()->ConvertToOutputFormat(
  566. obj_list_file, cmOutputConverter::SHELL);
  567. preLinkCmdLines.push_back(cmd);
  568. // create a list of obj files for the -E __create_def to read
  569. cmGeneratedFileStream fout(obj_list_file.c_str());
  570. for (cmNinjaDeps::iterator i = objs.begin(); i != objs.end(); ++i) {
  571. if (cmHasLiteralSuffix(*i, ".obj")) {
  572. fout << *i << "\n";
  573. }
  574. }
  575. }
  576. }
  577. // If we have any PRE_LINK commands, we need to go back to CMAKE_BINARY_DIR
  578. // for
  579. // the link commands.
  580. if (!preLinkCmdLines.empty()) {
  581. const std::string homeOutDir = localGen.ConvertToOutputFormat(
  582. localGen.GetBinaryDirectory(), cmOutputConverter::SHELL);
  583. preLinkCmdLines.push_back("cd " + homeOutDir);
  584. }
  585. vars["PRE_LINK"] = localGen.BuildCommandLine(preLinkCmdLines);
  586. std::string postBuildCmdLine = localGen.BuildCommandLine(postBuildCmdLines);
  587. cmNinjaVars symlinkVars;
  588. if (targetOutput == targetOutputReal) {
  589. vars["POST_BUILD"] = postBuildCmdLine;
  590. } else {
  591. vars["POST_BUILD"] = ":";
  592. symlinkVars["POST_BUILD"] = postBuildCmdLine;
  593. }
  594. cmGlobalNinjaGenerator& globalGen = *this->GetGlobalGenerator();
  595. int commandLineLengthLimit = -1;
  596. if (!this->ForceResponseFile()) {
  597. commandLineLengthLimit = calculateCommandLineLengthLimit(
  598. globalGen.GetRuleCmdLength(this->LanguageLinkerRule()));
  599. }
  600. const std::string rspfile =
  601. std::string(cmake::GetCMakeFilesDirectoryPostSlash()) + gt.GetName() +
  602. ".rsp";
  603. // Gather order-only dependencies.
  604. cmNinjaDeps orderOnlyDeps;
  605. this->GetLocalGenerator()->AppendTargetDepends(this->GetGeneratorTarget(),
  606. orderOnlyDeps);
  607. // Ninja should restat after linking if and only if there are byproducts.
  608. vars["RESTAT"] = byproducts.empty() ? "" : "1";
  609. for (cmNinjaDeps::const_iterator oi = byproducts.begin(),
  610. oe = byproducts.end();
  611. oi != oe; ++oi) {
  612. this->GetGlobalGenerator()->SeenCustomCommandOutput(*oi);
  613. outputs.push_back(*oi);
  614. }
  615. // Write the build statement for this target.
  616. bool usedResponseFile = false;
  617. globalGen.WriteBuild(this->GetBuildFileStream(), comment.str(),
  618. this->LanguageLinkerRule(), outputs,
  619. /*implicitOuts=*/cmNinjaDeps(), explicitDeps,
  620. implicitDeps, orderOnlyDeps, vars, rspfile,
  621. commandLineLengthLimit, &usedResponseFile);
  622. this->WriteLinkRule(usedResponseFile);
  623. if (targetOutput != targetOutputReal && !gt.IsFrameworkOnApple()) {
  624. if (targetType == cmState::EXECUTABLE) {
  625. globalGen.WriteBuild(
  626. this->GetBuildFileStream(),
  627. "Create executable symlink " + targetOutput,
  628. "CMAKE_SYMLINK_EXECUTABLE", cmNinjaDeps(1, targetOutput),
  629. /*implicitOuts=*/cmNinjaDeps(), cmNinjaDeps(1, targetOutputReal),
  630. emptyDeps, emptyDeps, symlinkVars);
  631. } else {
  632. cmNinjaDeps symlinks;
  633. std::string const soName =
  634. this->ConvertToNinjaPath(this->GetTargetFilePath(this->TargetNameSO));
  635. // If one link has to be created.
  636. if (targetOutputReal == soName || targetOutput == soName) {
  637. symlinkVars["SONAME"] = soName;
  638. } else {
  639. symlinkVars["SONAME"] = "";
  640. symlinks.push_back(soName);
  641. }
  642. symlinks.push_back(targetOutput);
  643. globalGen.WriteBuild(
  644. this->GetBuildFileStream(), "Create library symlink " + targetOutput,
  645. "CMAKE_SYMLINK_LIBRARY", symlinks,
  646. /*implicitOuts=*/cmNinjaDeps(), cmNinjaDeps(1, targetOutputReal),
  647. emptyDeps, emptyDeps, symlinkVars);
  648. }
  649. }
  650. // Add aliases for the file name and the target name.
  651. globalGen.AddTargetAlias(this->TargetNameOut, &gt);
  652. globalGen.AddTargetAlias(this->GetTargetName(), &gt);
  653. }
  654. void cmNinjaNormalTargetGenerator::WriteObjectLibStatement()
  655. {
  656. // Write a phony output that depends on all object files.
  657. cmNinjaDeps outputs;
  658. this->GetLocalGenerator()->AppendTargetOutputs(this->GetGeneratorTarget(),
  659. outputs);
  660. cmNinjaDeps depends = this->GetObjects();
  661. this->GetGlobalGenerator()->WritePhonyBuild(
  662. this->GetBuildFileStream(), "Object library " + this->GetTargetName(),
  663. outputs, depends);
  664. // Add aliases for the target name.
  665. this->GetGlobalGenerator()->AddTargetAlias(this->GetTargetName(),
  666. this->GetGeneratorTarget());
  667. }