cmNinjaNormalTargetGenerator.cxx 26 KB

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