cmLocalNinjaGenerator.cxx 16 KB

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