cmLocalNinjaGenerator.cxx 17 KB

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