cmLocalNinjaGenerator.cxx 16 KB

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