cmLocalNinjaGenerator.cxx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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 =
  36. new cmRulePlaceholderExpander(this->Compilers, this->VariableMappings,
  37. this->CompilerSysroot, this->LinkerSysroot);
  38. ret->SetTargetImpLib("$TARGET_IMPLIB");
  39. return ret;
  40. }
  41. cmLocalNinjaGenerator::~cmLocalNinjaGenerator()
  42. {
  43. }
  44. void cmLocalNinjaGenerator::Generate()
  45. {
  46. // Compute the path to use when referencing the current output
  47. // directory from the top output directory.
  48. this->HomeRelativeOutputPath = this->ConvertToRelativePath(
  49. this->GetBinaryDirectory(), this->GetCurrentBinaryDirectory());
  50. if (this->HomeRelativeOutputPath == ".") {
  51. this->HomeRelativeOutputPath = "";
  52. }
  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. const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
  71. for (std::vector<cmGeneratorTarget*>::const_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. std::string const& 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. // Determine if these object files should use a custom extension
  218. char const* custom_ext = gt->GetCustomObjectExtension();
  219. for (std::map<cmSourceFile const*, std::string>::iterator si =
  220. mapping.begin();
  221. si != mapping.end(); ++si) {
  222. cmSourceFile const* sf = si->first;
  223. bool keptSourceExtension;
  224. si->second = this->GetObjectFileNameWithoutTarget(
  225. *sf, gt->ObjectDirectory, &keptSourceExtension, custom_ext);
  226. }
  227. }
  228. void cmLocalNinjaGenerator::WriteProcessedMakefile(std::ostream& os)
  229. {
  230. cmGlobalNinjaGenerator::WriteDivider(os);
  231. os << "# Write statements declared in CMakeLists.txt:" << std::endl
  232. << "# " << this->Makefile->GetDefinition("CMAKE_CURRENT_LIST_FILE")
  233. << std::endl;
  234. if (this->IsRootMakefile()) {
  235. os << "# Which is the root file." << std::endl;
  236. }
  237. cmGlobalNinjaGenerator::WriteDivider(os);
  238. os << std::endl;
  239. }
  240. void cmLocalNinjaGenerator::AppendTargetOutputs(cmGeneratorTarget* target,
  241. cmNinjaDeps& outputs)
  242. {
  243. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(target, outputs);
  244. }
  245. void cmLocalNinjaGenerator::AppendTargetDepends(cmGeneratorTarget* target,
  246. cmNinjaDeps& outputs,
  247. cmNinjaTargetDepends depends)
  248. {
  249. this->GetGlobalNinjaGenerator()->AppendTargetDepends(target, outputs,
  250. depends);
  251. }
  252. void cmLocalNinjaGenerator::AppendCustomCommandDeps(
  253. cmCustomCommandGenerator const& ccg, cmNinjaDeps& ninjaDeps)
  254. {
  255. const std::vector<std::string>& deps = ccg.GetDepends();
  256. for (std::vector<std::string>::const_iterator i = deps.begin();
  257. i != deps.end(); ++i) {
  258. std::string dep;
  259. if (this->GetRealDependency(*i, this->GetConfigName(), dep)) {
  260. ninjaDeps.push_back(
  261. this->GetGlobalNinjaGenerator()->ConvertToNinjaPath(dep));
  262. }
  263. }
  264. }
  265. std::string cmLocalNinjaGenerator::BuildCommandLine(
  266. const std::vector<std::string>& cmdLines)
  267. {
  268. // If we have no commands but we need to build a command anyway, use noop.
  269. // This happens when building a POST_BUILD value for link targets that
  270. // don't use POST_BUILD.
  271. if (cmdLines.empty()) {
  272. return cmGlobalNinjaGenerator::SHELL_NOOP;
  273. }
  274. std::ostringstream cmd;
  275. for (std::vector<std::string>::const_iterator li = cmdLines.begin();
  276. li != cmdLines.end(); ++li)
  277. #ifdef _WIN32
  278. {
  279. if (li != cmdLines.begin()) {
  280. cmd << " && ";
  281. } else if (cmdLines.size() > 1) {
  282. cmd << "cmd.exe /C \"";
  283. }
  284. // Put current cmdLine in brackets if it contains "||" because it has
  285. // higher precedence than "&&" in cmd.exe
  286. if (li->find("||") != std::string::npos) {
  287. cmd << "( " << *li << " )";
  288. } else {
  289. cmd << *li;
  290. }
  291. }
  292. if (cmdLines.size() > 1) {
  293. cmd << "\"";
  294. }
  295. #else
  296. {
  297. if (li != cmdLines.begin()) {
  298. cmd << " && ";
  299. }
  300. cmd << *li;
  301. }
  302. #endif
  303. return cmd.str();
  304. }
  305. void cmLocalNinjaGenerator::AppendCustomCommandLines(
  306. cmCustomCommandGenerator const& ccg, std::vector<std::string>& cmdLines)
  307. {
  308. if (ccg.GetNumberOfCommands() > 0) {
  309. std::string wd = ccg.GetWorkingDirectory();
  310. if (wd.empty()) {
  311. wd = this->GetCurrentBinaryDirectory();
  312. }
  313. std::ostringstream cdCmd;
  314. #ifdef _WIN32
  315. std::string cdStr = "cd /D ";
  316. #else
  317. std::string cdStr = "cd ";
  318. #endif
  319. cdCmd << cdStr
  320. << this->ConvertToOutputFormat(wd, cmOutputConverter::SHELL);
  321. cmdLines.push_back(cdCmd.str());
  322. }
  323. std::string launcher = this->MakeCustomLauncher(ccg);
  324. for (unsigned i = 0; i != ccg.GetNumberOfCommands(); ++i) {
  325. cmdLines.push_back(launcher +
  326. this->ConvertToOutputFormat(ccg.GetCommand(i),
  327. cmOutputConverter::SHELL));
  328. std::string& cmd = cmdLines.back();
  329. ccg.AppendArguments(i, cmd);
  330. }
  331. }
  332. void cmLocalNinjaGenerator::WriteCustomCommandBuildStatement(
  333. cmCustomCommand const* cc, const cmNinjaDeps& orderOnlyDeps)
  334. {
  335. if (this->GetGlobalNinjaGenerator()->SeenCustomCommand(cc)) {
  336. return;
  337. }
  338. cmCustomCommandGenerator ccg(*cc, this->GetConfigName(), this);
  339. const std::vector<std::string>& outputs = ccg.GetOutputs();
  340. const std::vector<std::string>& byproducts = ccg.GetByproducts();
  341. cmNinjaDeps ninjaOutputs(outputs.size() + byproducts.size()), ninjaDeps;
  342. bool symbolic = false;
  343. for (std::vector<std::string>::const_iterator o = outputs.begin();
  344. !symbolic && o != outputs.end(); ++o) {
  345. if (cmSourceFile* sf = this->Makefile->GetSource(*o)) {
  346. symbolic = sf->GetPropertyAsBool("SYMBOLIC");
  347. }
  348. }
  349. #if 0
  350. #error TODO: Once CC in an ExternalProject target must provide the \
  351. file of each imported target that has an add_dependencies pointing \
  352. at us. How to know which ExternalProject step actually provides it?
  353. #endif
  354. std::transform(outputs.begin(), outputs.end(), ninjaOutputs.begin(),
  355. this->GetGlobalNinjaGenerator()->MapToNinjaPath());
  356. std::transform(byproducts.begin(), byproducts.end(),
  357. ninjaOutputs.begin() + outputs.size(),
  358. this->GetGlobalNinjaGenerator()->MapToNinjaPath());
  359. this->AppendCustomCommandDeps(ccg, ninjaDeps);
  360. for (cmNinjaDeps::iterator i = ninjaOutputs.begin(); i != ninjaOutputs.end();
  361. ++i) {
  362. this->GetGlobalNinjaGenerator()->SeenCustomCommandOutput(*i);
  363. }
  364. std::vector<std::string> cmdLines;
  365. this->AppendCustomCommandLines(ccg, cmdLines);
  366. if (cmdLines.empty()) {
  367. this->GetGlobalNinjaGenerator()->WritePhonyBuild(
  368. this->GetBuildFileStream(),
  369. "Phony custom command for " + ninjaOutputs[0], ninjaOutputs, ninjaDeps,
  370. cmNinjaDeps(), orderOnlyDeps, cmNinjaVars());
  371. } else {
  372. this->GetGlobalNinjaGenerator()->WriteCustomCommandBuild(
  373. this->BuildCommandLine(cmdLines), this->ConstructComment(ccg),
  374. "Custom command for " + ninjaOutputs[0], cc->GetDepfile(),
  375. cc->GetUsesTerminal(),
  376. /*restat*/ !symbolic || !byproducts.empty(), ninjaOutputs, ninjaDeps,
  377. orderOnlyDeps);
  378. }
  379. }
  380. void cmLocalNinjaGenerator::AddCustomCommandTarget(cmCustomCommand const* cc,
  381. cmGeneratorTarget* target)
  382. {
  383. CustomCommandTargetMap::value_type v(cc, std::set<cmGeneratorTarget*>());
  384. std::pair<CustomCommandTargetMap::iterator, bool> ins =
  385. this->CustomCommandTargets.insert(v);
  386. if (ins.second) {
  387. this->CustomCommands.push_back(cc);
  388. }
  389. ins.first->second.insert(target);
  390. }
  391. void cmLocalNinjaGenerator::WriteCustomCommandBuildStatements()
  392. {
  393. for (std::vector<cmCustomCommand const*>::iterator vi =
  394. this->CustomCommands.begin();
  395. vi != this->CustomCommands.end(); ++vi) {
  396. CustomCommandTargetMap::iterator i = this->CustomCommandTargets.find(*vi);
  397. assert(i != this->CustomCommandTargets.end());
  398. // A custom command may appear on multiple targets. However, some build
  399. // systems exist where the target dependencies on some of the targets are
  400. // overspecified, leading to a dependency cycle. If we assume all target
  401. // dependencies are a superset of the true target dependencies for this
  402. // custom command, we can take the set intersection of all target
  403. // dependencies to obtain a correct dependency list.
  404. //
  405. // FIXME: This won't work in certain obscure scenarios involving indirect
  406. // dependencies.
  407. std::set<cmGeneratorTarget*>::iterator j = i->second.begin();
  408. assert(j != i->second.end());
  409. std::vector<std::string> ccTargetDeps;
  410. this->GetGlobalNinjaGenerator()->AppendTargetDependsClosure(*j,
  411. ccTargetDeps);
  412. std::sort(ccTargetDeps.begin(), ccTargetDeps.end());
  413. ++j;
  414. for (; j != i->second.end(); ++j) {
  415. std::vector<std::string> jDeps, depsIntersection;
  416. this->GetGlobalNinjaGenerator()->AppendTargetDependsClosure(*j, jDeps);
  417. std::sort(jDeps.begin(), jDeps.end());
  418. std::set_intersection(ccTargetDeps.begin(), ccTargetDeps.end(),
  419. jDeps.begin(), jDeps.end(),
  420. std::back_inserter(depsIntersection));
  421. ccTargetDeps = depsIntersection;
  422. }
  423. this->WriteCustomCommandBuildStatement(i->first, ccTargetDeps);
  424. }
  425. }
  426. std::string cmLocalNinjaGenerator::MakeCustomLauncher(
  427. cmCustomCommandGenerator const& ccg)
  428. {
  429. const char* property_value =
  430. this->Makefile->GetProperty("RULE_LAUNCH_CUSTOM");
  431. if (!property_value || !*property_value) {
  432. return std::string();
  433. }
  434. // Expand rules in the empty string. It may insert the launcher and
  435. // perform replacements.
  436. cmRulePlaceholderExpander::RuleVariables vars;
  437. std::string output;
  438. const std::vector<std::string>& outputs = ccg.GetOutputs();
  439. if (!outputs.empty()) {
  440. output = outputs[0];
  441. if (ccg.GetWorkingDirectory().empty()) {
  442. output =
  443. this->ConvertToRelativePath(this->GetCurrentBinaryDirectory(), output);
  444. }
  445. output = this->ConvertToOutputFormat(output, cmOutputConverter::SHELL);
  446. }
  447. vars.Output = output.c_str();
  448. std::string launcher = property_value;
  449. launcher += " ";
  450. CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander(
  451. this->CreateRulePlaceholderExpander());
  452. rulePlaceholderExpander->ExpandRuleVariables(this, launcher, vars);
  453. if (!launcher.empty()) {
  454. launcher += " ";
  455. }
  456. return launcher;
  457. }