cmNinjaNormalTargetGenerator.cxx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  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 0;
  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. return linkCmds;
  282. }
  283. }
  284. switch (this->GetGeneratorTarget()->GetType()) {
  285. case cmState::STATIC_LIBRARY: {
  286. // We have archive link commands set. First, delete the existing archive.
  287. {
  288. std::string cmakeCommand =
  289. this->GetLocalGenerator()->ConvertToOutputFormat(
  290. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  291. linkCmds.push_back(cmakeCommand + " -E remove $TARGET_FILE");
  292. }
  293. // TODO: Use ARCHIVE_APPEND for archives over a certain size.
  294. {
  295. std::string linkCmdVar = "CMAKE_";
  296. linkCmdVar += this->TargetLinkLanguage;
  297. linkCmdVar += "_ARCHIVE_CREATE";
  298. const char* linkCmd = mf->GetRequiredDefinition(linkCmdVar);
  299. cmSystemTools::ExpandListArgument(linkCmd, linkCmds);
  300. }
  301. {
  302. std::string linkCmdVar = "CMAKE_";
  303. linkCmdVar += this->TargetLinkLanguage;
  304. linkCmdVar += "_ARCHIVE_FINISH";
  305. const char* linkCmd = mf->GetRequiredDefinition(linkCmdVar);
  306. cmSystemTools::ExpandListArgument(linkCmd, linkCmds);
  307. }
  308. return linkCmds;
  309. }
  310. case cmState::SHARED_LIBRARY:
  311. case cmState::MODULE_LIBRARY:
  312. case cmState::EXECUTABLE:
  313. break;
  314. default:
  315. assert(0 && "Unexpected target type");
  316. }
  317. return std::vector<std::string>();
  318. }
  319. static int calculateCommandLineLengthLimit(int linkRuleLength)
  320. {
  321. static int const limits[] = {
  322. #ifdef _WIN32
  323. 8000,
  324. #endif
  325. #if defined(__APPLE__) || defined(__HAIKU__) || defined(__linux)
  326. // for instance ARG_MAX is 2096152 on Ubuntu or 262144 on Mac
  327. ((int)sysconf(_SC_ARG_MAX)) - 1000,
  328. #endif
  329. #if defined(__linux)
  330. // #define MAX_ARG_STRLEN (PAGE_SIZE * 32) in Linux's binfmts.h
  331. ((int)sysconf(_SC_PAGESIZE) * 32) - 1000,
  332. #endif
  333. std::numeric_limits<int>::max()
  334. };
  335. size_t const arrSz = cmArraySize(limits);
  336. int const sz = *std::min_element(limits, limits + arrSz);
  337. if (sz == std::numeric_limits<int>::max()) {
  338. return -1;
  339. }
  340. return sz - linkRuleLength;
  341. }
  342. void cmNinjaNormalTargetGenerator::WriteLinkStatement()
  343. {
  344. cmGeneratorTarget& gt = *this->GetGeneratorTarget();
  345. const std::string cfgName = this->GetConfigName();
  346. std::string targetOutput = ConvertToNinjaPath(gt.GetFullPath(cfgName));
  347. std::string targetOutputReal =
  348. ConvertToNinjaPath(gt.GetFullPath(cfgName,
  349. /*implib=*/false,
  350. /*realpath=*/true));
  351. std::string targetOutputImplib =
  352. ConvertToNinjaPath(gt.GetFullPath(cfgName,
  353. /*implib=*/true));
  354. if (gt.IsAppBundleOnApple()) {
  355. // Create the app bundle
  356. std::string outpath = gt.GetDirectory(cfgName);
  357. this->OSXBundleGenerator->CreateAppBundle(this->TargetNameOut, outpath);
  358. // Calculate the output path
  359. targetOutput = outpath;
  360. targetOutput += "/";
  361. targetOutput += this->TargetNameOut;
  362. targetOutput = this->ConvertToNinjaPath(targetOutput);
  363. targetOutputReal = outpath;
  364. targetOutputReal += "/";
  365. targetOutputReal += this->TargetNameReal;
  366. targetOutputReal = this->ConvertToNinjaPath(targetOutputReal);
  367. } else if (gt.IsFrameworkOnApple()) {
  368. // Create the library framework.
  369. this->OSXBundleGenerator->CreateFramework(this->TargetNameOut,
  370. gt.GetDirectory(cfgName));
  371. } else if (gt.IsCFBundleOnApple()) {
  372. // Create the core foundation bundle.
  373. this->OSXBundleGenerator->CreateCFBundle(this->TargetNameOut,
  374. gt.GetDirectory(cfgName));
  375. }
  376. // Write comments.
  377. cmGlobalNinjaGenerator::WriteDivider(this->GetBuildFileStream());
  378. const cmState::TargetType targetType = gt.GetType();
  379. this->GetBuildFileStream() << "# Link build statements for "
  380. << cmState::GetTargetTypeName(targetType)
  381. << " target " << this->GetTargetName() << "\n\n";
  382. cmNinjaDeps emptyDeps;
  383. cmNinjaVars vars;
  384. // Compute the comment.
  385. std::ostringstream comment;
  386. comment << "Link the " << this->GetVisibleTypeName() << " "
  387. << targetOutputReal;
  388. // Compute outputs.
  389. cmNinjaDeps outputs;
  390. outputs.push_back(targetOutputReal);
  391. // Compute specific libraries to link with.
  392. cmNinjaDeps explicitDeps = this->GetObjects();
  393. cmNinjaDeps implicitDeps = this->ComputeLinkDeps();
  394. cmMakefile* mf = this->GetMakefile();
  395. std::string frameworkPath;
  396. std::string linkPath;
  397. cmGeneratorTarget& genTarget = *this->GetGeneratorTarget();
  398. std::string createRule = genTarget.GetCreateRuleVariable(
  399. this->TargetLinkLanguage, this->GetConfigName());
  400. bool useWatcomQuote = mf->IsOn(createRule + "_USE_WATCOM_QUOTE");
  401. cmLocalNinjaGenerator& localGen = *this->GetLocalGenerator();
  402. vars["TARGET_FILE"] =
  403. localGen.ConvertToOutputFormat(targetOutputReal, cmOutputConverter::SHELL);
  404. localGen.GetTargetFlags(this->GetConfigName(), vars["LINK_LIBRARIES"],
  405. vars["FLAGS"], vars["LINK_FLAGS"], frameworkPath,
  406. linkPath, &genTarget, useWatcomQuote);
  407. if (this->GetMakefile()->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS") &&
  408. gt.GetType() == cmState::SHARED_LIBRARY) {
  409. if (gt.GetPropertyAsBool("WINDOWS_EXPORT_ALL_SYMBOLS")) {
  410. std::string name_of_def_file = gt.GetSupportDirectory();
  411. name_of_def_file += "/" + gt.GetName();
  412. name_of_def_file += ".def ";
  413. vars["LINK_FLAGS"] += " /DEF:";
  414. vars["LINK_FLAGS"] += this->GetLocalGenerator()->ConvertToOutputFormat(
  415. name_of_def_file, cmOutputConverter::SHELL);
  416. }
  417. }
  418. // Add OS X version flags, if any.
  419. if (this->GeneratorTarget->GetType() == cmState::SHARED_LIBRARY ||
  420. this->GeneratorTarget->GetType() == cmState::MODULE_LIBRARY) {
  421. this->AppendOSXVerFlag(vars["LINK_FLAGS"], this->TargetLinkLanguage,
  422. "COMPATIBILITY", true);
  423. this->AppendOSXVerFlag(vars["LINK_FLAGS"], this->TargetLinkLanguage,
  424. "CURRENT", false);
  425. }
  426. this->addPoolNinjaVariable("JOB_POOL_LINK", &gt, vars);
  427. this->AddModuleDefinitionFlag(vars["LINK_FLAGS"]);
  428. vars["LINK_FLAGS"] =
  429. cmGlobalNinjaGenerator::EncodeLiteral(vars["LINK_FLAGS"]);
  430. vars["MANIFESTS"] = this->GetManifests();
  431. vars["LINK_PATH"] = frameworkPath + linkPath;
  432. // Compute architecture specific link flags. Yes, these go into a different
  433. // variable for executables, probably due to a mistake made when duplicating
  434. // code between the Makefile executable and library generators.
  435. if (targetType == cmState::EXECUTABLE) {
  436. std::string t = vars["FLAGS"];
  437. localGen.AddArchitectureFlags(t, &genTarget, TargetLinkLanguage, cfgName);
  438. vars["FLAGS"] = t;
  439. } else {
  440. std::string t = vars["ARCH_FLAGS"];
  441. localGen.AddArchitectureFlags(t, &genTarget, TargetLinkLanguage, cfgName);
  442. vars["ARCH_FLAGS"] = t;
  443. t = "";
  444. localGen.AddLanguageFlags(t, TargetLinkLanguage, cfgName);
  445. vars["LANGUAGE_COMPILE_FLAGS"] = t;
  446. }
  447. if (this->GetGeneratorTarget()->HasSOName(cfgName)) {
  448. vars["SONAME_FLAG"] = mf->GetSONameFlag(this->TargetLinkLanguage);
  449. vars["SONAME"] = this->TargetNameSO;
  450. if (targetType == cmState::SHARED_LIBRARY) {
  451. std::string install_dir =
  452. this->GetGeneratorTarget()->GetInstallNameDirForBuildTree(cfgName);
  453. if (!install_dir.empty()) {
  454. vars["INSTALLNAME_DIR"] = localGen.Convert(
  455. install_dir, cmOutputConverter::NONE, cmOutputConverter::SHELL);
  456. }
  457. }
  458. }
  459. cmNinjaDeps byproducts;
  460. if (!this->TargetNameImport.empty()) {
  461. const std::string impLibPath = localGen.ConvertToOutputFormat(
  462. targetOutputImplib, cmOutputConverter::SHELL);
  463. vars["TARGET_IMPLIB"] = impLibPath;
  464. EnsureParentDirectoryExists(impLibPath);
  465. if (genTarget.HasImportLibrary()) {
  466. byproducts.push_back(targetOutputImplib);
  467. }
  468. }
  469. if (!this->SetMsvcTargetPdbVariable(vars)) {
  470. // It is common to place debug symbols at a specific place,
  471. // so we need a plain target name in the rule available.
  472. std::string prefix;
  473. std::string base;
  474. std::string suffix;
  475. this->GetGeneratorTarget()->GetFullNameComponents(prefix, base, suffix);
  476. std::string dbg_suffix = ".dbg";
  477. // TODO: Where to document?
  478. if (mf->GetDefinition("CMAKE_DEBUG_SYMBOL_SUFFIX")) {
  479. dbg_suffix = mf->GetDefinition("CMAKE_DEBUG_SYMBOL_SUFFIX");
  480. }
  481. vars["TARGET_PDB"] = base + suffix + dbg_suffix;
  482. }
  483. const std::string objPath = GetGeneratorTarget()->GetSupportDirectory();
  484. vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  485. this->ConvertToNinjaPath(objPath), cmOutputConverter::SHELL);
  486. EnsureDirectoryExists(objPath);
  487. if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
  488. // ar.exe can't handle backslashes in rsp files (implicitly used by gcc)
  489. std::string& linkLibraries = vars["LINK_LIBRARIES"];
  490. std::replace(linkLibraries.begin(), linkLibraries.end(), '\\', '/');
  491. std::string& link_path = vars["LINK_PATH"];
  492. std::replace(link_path.begin(), link_path.end(), '\\', '/');
  493. }
  494. const std::vector<cmCustomCommand>* cmdLists[3] = {
  495. &gt.GetPreBuildCommands(), &gt.GetPreLinkCommands(),
  496. &gt.GetPostBuildCommands()
  497. };
  498. std::vector<std::string> preLinkCmdLines, postBuildCmdLines;
  499. std::vector<std::string>* cmdLineLists[3] = { &preLinkCmdLines,
  500. &preLinkCmdLines,
  501. &postBuildCmdLines };
  502. for (unsigned i = 0; i != 3; ++i) {
  503. for (std::vector<cmCustomCommand>::const_iterator ci =
  504. cmdLists[i]->begin();
  505. ci != cmdLists[i]->end(); ++ci) {
  506. cmCustomCommandGenerator ccg(*ci, cfgName, this->GetLocalGenerator());
  507. localGen.AppendCustomCommandLines(ccg, *cmdLineLists[i]);
  508. std::vector<std::string> const& ccByproducts = ccg.GetByproducts();
  509. std::transform(ccByproducts.begin(), ccByproducts.end(),
  510. std::back_inserter(byproducts), MapToNinjaPath());
  511. }
  512. }
  513. // maybe create .def file from list of objects
  514. if (gt.GetType() == cmState::SHARED_LIBRARY &&
  515. this->GetMakefile()->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS")) {
  516. if (gt.GetPropertyAsBool("WINDOWS_EXPORT_ALL_SYMBOLS")) {
  517. std::string cmakeCommand =
  518. this->GetLocalGenerator()->ConvertToOutputFormat(
  519. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  520. std::string name_of_def_file = gt.GetSupportDirectory();
  521. name_of_def_file += "/" + gt.GetName();
  522. name_of_def_file += ".def";
  523. std::string cmd = cmakeCommand;
  524. cmd += " -E __create_def ";
  525. cmd += this->GetLocalGenerator()->ConvertToOutputFormat(
  526. name_of_def_file, cmOutputConverter::SHELL);
  527. cmd += " ";
  528. cmNinjaDeps objs = this->GetObjects();
  529. std::string obj_list_file = name_of_def_file;
  530. obj_list_file += ".objs";
  531. cmd += this->GetLocalGenerator()->ConvertToOutputFormat(
  532. obj_list_file, cmOutputConverter::SHELL);
  533. preLinkCmdLines.push_back(cmd);
  534. // create a list of obj files for the -E __create_def to read
  535. cmGeneratedFileStream fout(obj_list_file.c_str());
  536. for (cmNinjaDeps::iterator i = objs.begin(); i != objs.end(); ++i) {
  537. if (cmHasLiteralSuffix(*i, ".obj")) {
  538. fout << *i << "\n";
  539. }
  540. }
  541. }
  542. }
  543. // If we have any PRE_LINK commands, we need to go back to HOME_OUTPUT for
  544. // the link commands.
  545. if (!preLinkCmdLines.empty()) {
  546. const std::string homeOutDir = localGen.ConvertToOutputFormat(
  547. localGen.GetBinaryDirectory(), cmOutputConverter::SHELL);
  548. preLinkCmdLines.push_back("cd " + homeOutDir);
  549. }
  550. vars["PRE_LINK"] = localGen.BuildCommandLine(preLinkCmdLines);
  551. std::string postBuildCmdLine = localGen.BuildCommandLine(postBuildCmdLines);
  552. cmNinjaVars symlinkVars;
  553. if (targetOutput == targetOutputReal) {
  554. vars["POST_BUILD"] = postBuildCmdLine;
  555. } else {
  556. vars["POST_BUILD"] = ":";
  557. symlinkVars["POST_BUILD"] = postBuildCmdLine;
  558. }
  559. cmGlobalNinjaGenerator& globalGen = *this->GetGlobalGenerator();
  560. int commandLineLengthLimit = -1;
  561. if (!this->ForceResponseFile()) {
  562. commandLineLengthLimit = calculateCommandLineLengthLimit(
  563. globalGen.GetRuleCmdLength(this->LanguageLinkerRule()));
  564. }
  565. const std::string rspfile =
  566. std::string(cmake::GetCMakeFilesDirectoryPostSlash()) + gt.GetName() +
  567. ".rsp";
  568. // Gather order-only dependencies.
  569. cmNinjaDeps orderOnlyDeps;
  570. this->GetLocalGenerator()->AppendTargetDepends(this->GetGeneratorTarget(),
  571. orderOnlyDeps);
  572. // Ninja should restat after linking if and only if there are byproducts.
  573. vars["RESTAT"] = byproducts.empty() ? "" : "1";
  574. for (cmNinjaDeps::const_iterator oi = byproducts.begin(),
  575. oe = byproducts.end();
  576. oi != oe; ++oi) {
  577. this->GetGlobalGenerator()->SeenCustomCommandOutput(*oi);
  578. outputs.push_back(*oi);
  579. }
  580. // Write the build statement for this target.
  581. bool usedResponseFile = false;
  582. globalGen.WriteBuild(this->GetBuildFileStream(), comment.str(),
  583. this->LanguageLinkerRule(), outputs, explicitDeps,
  584. implicitDeps, orderOnlyDeps, vars, rspfile,
  585. commandLineLengthLimit, &usedResponseFile);
  586. this->WriteLinkRule(usedResponseFile);
  587. if (targetOutput != targetOutputReal && !gt.IsFrameworkOnApple()) {
  588. if (targetType == cmState::EXECUTABLE) {
  589. globalGen.WriteBuild(
  590. this->GetBuildFileStream(),
  591. "Create executable symlink " + targetOutput,
  592. "CMAKE_SYMLINK_EXECUTABLE", cmNinjaDeps(1, targetOutput),
  593. cmNinjaDeps(1, targetOutputReal), emptyDeps, emptyDeps, symlinkVars);
  594. } else {
  595. cmNinjaDeps symlinks;
  596. std::string const soName =
  597. this->ConvertToNinjaPath(this->GetTargetFilePath(this->TargetNameSO));
  598. // If one link has to be created.
  599. if (targetOutputReal == soName || targetOutput == soName) {
  600. symlinkVars["SONAME"] = soName;
  601. } else {
  602. symlinkVars["SONAME"] = "";
  603. symlinks.push_back(soName);
  604. }
  605. symlinks.push_back(targetOutput);
  606. globalGen.WriteBuild(
  607. this->GetBuildFileStream(), "Create library symlink " + targetOutput,
  608. "CMAKE_SYMLINK_LIBRARY", symlinks, cmNinjaDeps(1, targetOutputReal),
  609. emptyDeps, emptyDeps, symlinkVars);
  610. }
  611. }
  612. // Add aliases for the file name and the target name.
  613. globalGen.AddTargetAlias(this->TargetNameOut, &gt);
  614. globalGen.AddTargetAlias(this->GetTargetName(), &gt);
  615. }
  616. void cmNinjaNormalTargetGenerator::WriteObjectLibStatement()
  617. {
  618. // Write a phony output that depends on all object files.
  619. cmNinjaDeps outputs;
  620. this->GetLocalGenerator()->AppendTargetOutputs(this->GetGeneratorTarget(),
  621. outputs);
  622. cmNinjaDeps depends = this->GetObjects();
  623. this->GetGlobalGenerator()->WritePhonyBuild(
  624. this->GetBuildFileStream(), "Object library " + this->GetTargetName(),
  625. outputs, depends);
  626. // Add aliases for the target name.
  627. this->GetGlobalGenerator()->AddTargetAlias(this->GetTargetName(),
  628. this->GetGeneratorTarget());
  629. }