cmNinjaNormalTargetGenerator.cxx 25 KB

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