cmNinjaNormalTargetGenerator.cxx 26 KB

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