cmLocalNinjaGenerator.cxx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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 "cmLocalNinjaGenerator.h"
  4. #include "cmCustomCommand.h"
  5. #include "cmCustomCommandGenerator.h"
  6. #include "cmGeneratedFileStream.h"
  7. #include "cmGeneratorTarget.h"
  8. #include "cmGlobalGenerator.h"
  9. #include "cmGlobalNinjaGenerator.h"
  10. #include "cmMakefile.h"
  11. #include "cmNinjaTargetGenerator.h"
  12. #include "cmRulePlaceholderExpander.h"
  13. #include "cmSourceFile.h"
  14. #include "cmState.h"
  15. #include "cmSystemTools.h"
  16. #include "cmake.h"
  17. #include <algorithm>
  18. #include <assert.h>
  19. #include <iterator>
  20. #include <sstream>
  21. #include <stdio.h>
  22. #include <utility>
  23. cmLocalNinjaGenerator::cmLocalNinjaGenerator(cmGlobalGenerator* gg,
  24. cmMakefile* mf)
  25. : cmLocalCommonGenerator(gg, mf, mf->GetState()->GetBinaryDirectory())
  26. , HomeRelativeOutputPath("")
  27. {
  28. }
  29. // Virtual public methods.
  30. cmRulePlaceholderExpander*
  31. cmLocalNinjaGenerator::CreateRulePlaceholderExpander() const
  32. {
  33. cmRulePlaceholderExpander* ret = new cmRulePlaceholderExpander(
  34. this->Compilers, this->VariableMappings, this->CompilerSysroot);
  35. ret->SetTargetImpLib("$TARGET_IMPLIB");
  36. return ret;
  37. }
  38. cmLocalNinjaGenerator::~cmLocalNinjaGenerator()
  39. {
  40. }
  41. void cmLocalNinjaGenerator::Generate()
  42. {
  43. // Compute the path to use when referencing the current output
  44. // directory from the top output directory.
  45. this->HomeRelativeOutputPath = this->ConvertToRelativePath(
  46. this->GetBinaryDirectory(), this->GetCurrentBinaryDirectory());
  47. if (this->HomeRelativeOutputPath == ".") {
  48. this->HomeRelativeOutputPath = "";
  49. }
  50. this->SetConfigName();
  51. this->WriteProcessedMakefile(this->GetBuildFileStream());
  52. #ifdef NINJA_GEN_VERBOSE_FILES
  53. this->WriteProcessedMakefile(this->GetRulesFileStream());
  54. #endif
  55. // We do that only once for the top CMakeLists.txt file.
  56. if (this->IsRootMakefile()) {
  57. this->WriteBuildFileTop();
  58. this->WritePools(this->GetRulesFileStream());
  59. const std::string showIncludesPrefix =
  60. this->GetMakefile()->GetSafeDefinition("CMAKE_CL_SHOWINCLUDES_PREFIX");
  61. if (!showIncludesPrefix.empty()) {
  62. cmGlobalNinjaGenerator::WriteComment(this->GetRulesFileStream(),
  63. "localized /showIncludes string");
  64. this->GetRulesFileStream() << "msvc_deps_prefix = " << showIncludesPrefix
  65. << "\n\n";
  66. }
  67. }
  68. std::vector<cmGeneratorTarget*> targets = this->GetGeneratorTargets();
  69. for (std::vector<cmGeneratorTarget*>::iterator t = targets.begin();
  70. t != targets.end(); ++t) {
  71. if ((*t)->GetType() == cmState::INTERFACE_LIBRARY) {
  72. continue;
  73. }
  74. cmNinjaTargetGenerator* tg = cmNinjaTargetGenerator::New(*t);
  75. if (tg) {
  76. tg->Generate();
  77. // Add the target to "all" if required.
  78. if (!this->GetGlobalNinjaGenerator()->IsExcluded(
  79. this->GetGlobalNinjaGenerator()->GetLocalGenerators()[0], *t)) {
  80. this->GetGlobalNinjaGenerator()->AddDependencyToAll(*t);
  81. }
  82. delete tg;
  83. }
  84. }
  85. this->WriteCustomCommandBuildStatements();
  86. }
  87. // TODO: Picked up from cmLocalUnixMakefileGenerator3. Refactor it.
  88. std::string cmLocalNinjaGenerator::GetTargetDirectory(
  89. cmGeneratorTarget const* target) const
  90. {
  91. std::string dir = cmake::GetCMakeFilesDirectoryPostSlash();
  92. dir += target->GetName();
  93. #if defined(__VMS)
  94. dir += "_dir";
  95. #else
  96. dir += ".dir";
  97. #endif
  98. return dir;
  99. }
  100. // Non-virtual public methods.
  101. const cmGlobalNinjaGenerator* cmLocalNinjaGenerator::GetGlobalNinjaGenerator()
  102. const
  103. {
  104. return static_cast<const cmGlobalNinjaGenerator*>(
  105. this->GetGlobalGenerator());
  106. }
  107. cmGlobalNinjaGenerator* cmLocalNinjaGenerator::GetGlobalNinjaGenerator()
  108. {
  109. return static_cast<cmGlobalNinjaGenerator*>(this->GetGlobalGenerator());
  110. }
  111. // Virtual protected methods.
  112. std::string cmLocalNinjaGenerator::ConvertToIncludeReference(
  113. std::string const& path, cmOutputConverter::OutputFormat format,
  114. bool forceFullPaths)
  115. {
  116. if (forceFullPaths) {
  117. return this->ConvertToOutputFormat(cmSystemTools::CollapseFullPath(path),
  118. format);
  119. }
  120. return this->ConvertToOutputFormat(
  121. this->ConvertToRelativePath(this->GetBinaryDirectory(), path), format);
  122. }
  123. // Private methods.
  124. cmGeneratedFileStream& cmLocalNinjaGenerator::GetBuildFileStream() const
  125. {
  126. return *this->GetGlobalNinjaGenerator()->GetBuildFileStream();
  127. }
  128. cmGeneratedFileStream& cmLocalNinjaGenerator::GetRulesFileStream() const
  129. {
  130. return *this->GetGlobalNinjaGenerator()->GetRulesFileStream();
  131. }
  132. const cmake* cmLocalNinjaGenerator::GetCMakeInstance() const
  133. {
  134. return this->GetGlobalGenerator()->GetCMakeInstance();
  135. }
  136. cmake* cmLocalNinjaGenerator::GetCMakeInstance()
  137. {
  138. return this->GetGlobalGenerator()->GetCMakeInstance();
  139. }
  140. void cmLocalNinjaGenerator::WriteBuildFileTop()
  141. {
  142. // For the build file.
  143. this->WriteProjectHeader(this->GetBuildFileStream());
  144. this->WriteNinjaRequiredVersion(this->GetBuildFileStream());
  145. this->WriteNinjaFilesInclusion(this->GetBuildFileStream());
  146. // For the rule file.
  147. this->WriteProjectHeader(this->GetRulesFileStream());
  148. }
  149. void cmLocalNinjaGenerator::WriteProjectHeader(std::ostream& os)
  150. {
  151. cmGlobalNinjaGenerator::WriteDivider(os);
  152. os << "# Project: " << this->GetProjectName() << std::endl
  153. << "# Configuration: " << this->ConfigName << std::endl;
  154. cmGlobalNinjaGenerator::WriteDivider(os);
  155. }
  156. void cmLocalNinjaGenerator::WriteNinjaRequiredVersion(std::ostream& os)
  157. {
  158. // Default required version
  159. std::string requiredVersion =
  160. this->GetGlobalNinjaGenerator()->RequiredNinjaVersion();
  161. // Ninja generator uses the 'console' pool if available (>= 1.5)
  162. if (this->GetGlobalNinjaGenerator()->SupportsConsolePool()) {
  163. requiredVersion =
  164. this->GetGlobalNinjaGenerator()->RequiredNinjaVersionForConsolePool();
  165. }
  166. cmGlobalNinjaGenerator::WriteComment(
  167. os, "Minimal version of Ninja required by this file");
  168. os << "ninja_required_version = " << requiredVersion << std::endl
  169. << std::endl;
  170. }
  171. void cmLocalNinjaGenerator::WritePools(std::ostream& os)
  172. {
  173. cmGlobalNinjaGenerator::WriteDivider(os);
  174. const char* jobpools =
  175. this->GetCMakeInstance()->GetState()->GetGlobalProperty("JOB_POOLS");
  176. if (jobpools) {
  177. cmGlobalNinjaGenerator::WriteComment(
  178. os, "Pools defined by global property JOB_POOLS");
  179. std::vector<std::string> pools;
  180. cmSystemTools::ExpandListArgument(jobpools, pools);
  181. for (size_t i = 0; i < pools.size(); ++i) {
  182. const std::string pool = pools[i];
  183. const std::string::size_type eq = pool.find('=');
  184. unsigned int jobs;
  185. if (eq != std::string::npos &&
  186. sscanf(pool.c_str() + eq, "=%u", &jobs) == 1) {
  187. os << "pool " << pool.substr(0, eq) << std::endl;
  188. os << " depth = " << jobs << std::endl;
  189. os << std::endl;
  190. } else {
  191. cmSystemTools::Error("Invalid pool defined by property 'JOB_POOLS': ",
  192. pool.c_str());
  193. }
  194. }
  195. }
  196. }
  197. void cmLocalNinjaGenerator::WriteNinjaFilesInclusion(std::ostream& os)
  198. {
  199. cmGlobalNinjaGenerator::WriteDivider(os);
  200. os << "# Include auxiliary files.\n"
  201. << "\n";
  202. cmGlobalNinjaGenerator* ng = this->GetGlobalNinjaGenerator();
  203. std::string const ninjaRulesFile =
  204. ng->NinjaOutputPath(cmGlobalNinjaGenerator::NINJA_RULES_FILE);
  205. std::string const rulesFilePath =
  206. ng->EncodeIdent(ng->EncodePath(ninjaRulesFile), os);
  207. cmGlobalNinjaGenerator::WriteInclude(os, rulesFilePath,
  208. "Include rules file.");
  209. os << "\n";
  210. }
  211. void cmLocalNinjaGenerator::ComputeObjectFilenames(
  212. std::map<cmSourceFile const*, std::string>& mapping,
  213. cmGeneratorTarget const* gt)
  214. {
  215. for (std::map<cmSourceFile const*, std::string>::iterator si =
  216. mapping.begin();
  217. si != mapping.end(); ++si) {
  218. cmSourceFile const* sf = si->first;
  219. si->second =
  220. this->GetObjectFileNameWithoutTarget(*sf, gt->ObjectDirectory);
  221. }
  222. }
  223. void cmLocalNinjaGenerator::WriteProcessedMakefile(std::ostream& os)
  224. {
  225. cmGlobalNinjaGenerator::WriteDivider(os);
  226. os << "# Write statements declared in CMakeLists.txt:" << std::endl
  227. << "# " << this->Makefile->GetDefinition("CMAKE_CURRENT_LIST_FILE")
  228. << std::endl;
  229. if (this->IsRootMakefile()) {
  230. os << "# Which is the root file." << std::endl;
  231. }
  232. cmGlobalNinjaGenerator::WriteDivider(os);
  233. os << std::endl;
  234. }
  235. void cmLocalNinjaGenerator::AppendTargetOutputs(cmGeneratorTarget* target,
  236. cmNinjaDeps& outputs)
  237. {
  238. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(target, outputs);
  239. }
  240. void cmLocalNinjaGenerator::AppendTargetDepends(cmGeneratorTarget* target,
  241. cmNinjaDeps& outputs)
  242. {
  243. this->GetGlobalNinjaGenerator()->AppendTargetDepends(target, outputs);
  244. }
  245. void cmLocalNinjaGenerator::AppendCustomCommandDeps(
  246. cmCustomCommandGenerator const& ccg, cmNinjaDeps& ninjaDeps)
  247. {
  248. const std::vector<std::string>& deps = ccg.GetDepends();
  249. for (std::vector<std::string>::const_iterator i = deps.begin();
  250. i != deps.end(); ++i) {
  251. std::string dep;
  252. if (this->GetRealDependency(*i, this->GetConfigName(), dep)) {
  253. ninjaDeps.push_back(
  254. this->GetGlobalNinjaGenerator()->ConvertToNinjaPath(dep));
  255. }
  256. }
  257. }
  258. std::string cmLocalNinjaGenerator::BuildCommandLine(
  259. const std::vector<std::string>& cmdLines)
  260. {
  261. // If we have no commands but we need to build a command anyway, use ":".
  262. // This happens when building a POST_BUILD value for link targets that
  263. // don't use POST_BUILD.
  264. if (cmdLines.empty()) {
  265. #ifdef _WIN32
  266. return "cd .";
  267. #else
  268. return ":";
  269. #endif
  270. }
  271. std::ostringstream cmd;
  272. for (std::vector<std::string>::const_iterator li = cmdLines.begin();
  273. li != cmdLines.end(); ++li)
  274. #ifdef _WIN32
  275. {
  276. if (li != cmdLines.begin()) {
  277. cmd << " && ";
  278. } else if (cmdLines.size() > 1) {
  279. cmd << "cmd.exe /C \"";
  280. }
  281. cmd << *li;
  282. }
  283. if (cmdLines.size() > 1) {
  284. cmd << "\"";
  285. }
  286. #else
  287. {
  288. if (li != cmdLines.begin()) {
  289. cmd << " && ";
  290. }
  291. cmd << *li;
  292. }
  293. #endif
  294. return cmd.str();
  295. }
  296. void cmLocalNinjaGenerator::AppendCustomCommandLines(
  297. cmCustomCommandGenerator const& ccg, std::vector<std::string>& cmdLines)
  298. {
  299. if (ccg.GetNumberOfCommands() > 0) {
  300. std::string wd = ccg.GetWorkingDirectory();
  301. if (wd.empty()) {
  302. wd = this->GetCurrentBinaryDirectory();
  303. }
  304. std::ostringstream cdCmd;
  305. #ifdef _WIN32
  306. std::string cdStr = "cd /D ";
  307. #else
  308. std::string cdStr = "cd ";
  309. #endif
  310. cdCmd << cdStr
  311. << this->ConvertToOutputFormat(wd, cmOutputConverter::SHELL);
  312. cmdLines.push_back(cdCmd.str());
  313. }
  314. std::string launcher = this->MakeCustomLauncher(ccg);
  315. for (unsigned i = 0; i != ccg.GetNumberOfCommands(); ++i) {
  316. cmdLines.push_back(launcher +
  317. this->ConvertToOutputFormat(ccg.GetCommand(i),
  318. cmOutputConverter::SHELL));
  319. std::string& cmd = cmdLines.back();
  320. ccg.AppendArguments(i, cmd);
  321. }
  322. }
  323. void cmLocalNinjaGenerator::WriteCustomCommandBuildStatement(
  324. cmCustomCommand const* cc, const cmNinjaDeps& orderOnlyDeps)
  325. {
  326. if (this->GetGlobalNinjaGenerator()->SeenCustomCommand(cc)) {
  327. return;
  328. }
  329. cmCustomCommandGenerator ccg(*cc, this->GetConfigName(), this);
  330. const std::vector<std::string>& outputs = ccg.GetOutputs();
  331. const std::vector<std::string>& byproducts = ccg.GetByproducts();
  332. cmNinjaDeps ninjaOutputs(outputs.size() + byproducts.size()), ninjaDeps;
  333. bool symbolic = false;
  334. for (std::vector<std::string>::const_iterator o = outputs.begin();
  335. !symbolic && o != outputs.end(); ++o) {
  336. if (cmSourceFile* sf = this->Makefile->GetSource(*o)) {
  337. symbolic = sf->GetPropertyAsBool("SYMBOLIC");
  338. }
  339. }
  340. #if 0
  341. #error TODO: Once CC in an ExternalProject target must provide the \
  342. file of each imported target that has an add_dependencies pointing \
  343. at us. How to know which ExternalProject step actually provides it?
  344. #endif
  345. std::transform(outputs.begin(), outputs.end(), ninjaOutputs.begin(),
  346. this->GetGlobalNinjaGenerator()->MapToNinjaPath());
  347. std::transform(byproducts.begin(), byproducts.end(),
  348. ninjaOutputs.begin() + outputs.size(),
  349. this->GetGlobalNinjaGenerator()->MapToNinjaPath());
  350. this->AppendCustomCommandDeps(ccg, ninjaDeps);
  351. for (cmNinjaDeps::iterator i = ninjaOutputs.begin(); i != ninjaOutputs.end();
  352. ++i) {
  353. this->GetGlobalNinjaGenerator()->SeenCustomCommandOutput(*i);
  354. }
  355. std::vector<std::string> cmdLines;
  356. this->AppendCustomCommandLines(ccg, cmdLines);
  357. if (cmdLines.empty()) {
  358. this->GetGlobalNinjaGenerator()->WritePhonyBuild(
  359. this->GetBuildFileStream(),
  360. "Phony custom command for " + ninjaOutputs[0], ninjaOutputs, ninjaDeps,
  361. cmNinjaDeps(), orderOnlyDeps, cmNinjaVars());
  362. } else {
  363. this->GetGlobalNinjaGenerator()->WriteCustomCommandBuild(
  364. this->BuildCommandLine(cmdLines), this->ConstructComment(ccg),
  365. "Custom command for " + ninjaOutputs[0], cc->GetDepfile(),
  366. cc->GetUsesTerminal(),
  367. /*restat*/ !symbolic || !byproducts.empty(), ninjaOutputs, ninjaDeps,
  368. orderOnlyDeps);
  369. }
  370. }
  371. void cmLocalNinjaGenerator::AddCustomCommandTarget(cmCustomCommand const* cc,
  372. cmGeneratorTarget* target)
  373. {
  374. CustomCommandTargetMap::value_type v(cc, std::set<cmGeneratorTarget*>());
  375. std::pair<CustomCommandTargetMap::iterator, bool> ins =
  376. this->CustomCommandTargets.insert(v);
  377. if (ins.second) {
  378. this->CustomCommands.push_back(cc);
  379. }
  380. ins.first->second.insert(target);
  381. }
  382. void cmLocalNinjaGenerator::WriteCustomCommandBuildStatements()
  383. {
  384. for (std::vector<cmCustomCommand const*>::iterator vi =
  385. this->CustomCommands.begin();
  386. vi != this->CustomCommands.end(); ++vi) {
  387. CustomCommandTargetMap::iterator i = this->CustomCommandTargets.find(*vi);
  388. assert(i != this->CustomCommandTargets.end());
  389. // A custom command may appear on multiple targets. However, some build
  390. // systems exist where the target dependencies on some of the targets are
  391. // overspecified, leading to a dependency cycle. If we assume all target
  392. // dependencies are a superset of the true target dependencies for this
  393. // custom command, we can take the set intersection of all target
  394. // dependencies to obtain a correct dependency list.
  395. //
  396. // FIXME: This won't work in certain obscure scenarios involving indirect
  397. // dependencies.
  398. std::set<cmGeneratorTarget*>::iterator j = i->second.begin();
  399. assert(j != i->second.end());
  400. std::vector<std::string> ccTargetDeps;
  401. this->GetGlobalNinjaGenerator()->AppendTargetDependsClosure(*j,
  402. ccTargetDeps);
  403. std::sort(ccTargetDeps.begin(), ccTargetDeps.end());
  404. ++j;
  405. for (; j != i->second.end(); ++j) {
  406. std::vector<std::string> jDeps, depsIntersection;
  407. this->GetGlobalNinjaGenerator()->AppendTargetDependsClosure(*j, jDeps);
  408. std::sort(jDeps.begin(), jDeps.end());
  409. std::set_intersection(ccTargetDeps.begin(), ccTargetDeps.end(),
  410. jDeps.begin(), jDeps.end(),
  411. std::back_inserter(depsIntersection));
  412. ccTargetDeps = depsIntersection;
  413. }
  414. this->WriteCustomCommandBuildStatement(i->first, ccTargetDeps);
  415. }
  416. }
  417. std::string cmLocalNinjaGenerator::MakeCustomLauncher(
  418. cmCustomCommandGenerator const& ccg)
  419. {
  420. const char* property_value =
  421. this->Makefile->GetProperty("RULE_LAUNCH_CUSTOM");
  422. if (!property_value || !*property_value) {
  423. return std::string();
  424. }
  425. // Expand rules in the empty string. It may insert the launcher and
  426. // perform replacements.
  427. cmRulePlaceholderExpander::RuleVariables vars;
  428. std::string output;
  429. const std::vector<std::string>& outputs = ccg.GetOutputs();
  430. if (!outputs.empty()) {
  431. output = outputs[0];
  432. if (ccg.GetWorkingDirectory().empty()) {
  433. output =
  434. this->ConvertToRelativePath(this->GetCurrentBinaryDirectory(), output);
  435. }
  436. output = this->ConvertToOutputFormat(output, cmOutputConverter::SHELL);
  437. }
  438. vars.Output = output.c_str();
  439. std::string launcher = property_value;
  440. launcher += " ";
  441. CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander(
  442. this->CreateRulePlaceholderExpander());
  443. rulePlaceholderExpander->ExpandRuleVariables(this, launcher, vars);
  444. if (!launcher.empty()) {
  445. launcher += " ";
  446. }
  447. return launcher;
  448. }