cmLocalNinjaGenerator.cxx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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 "cmSourceFile.h"
  13. #include "cmState.h"
  14. #include "cmSystemTools.h"
  15. #include "cmake.h"
  16. #include <algorithm>
  17. #include <assert.h>
  18. #include <iterator>
  19. #include <sstream>
  20. #include <stdio.h>
  21. #include <utility>
  22. cmLocalNinjaGenerator::cmLocalNinjaGenerator(cmGlobalGenerator* gg,
  23. cmMakefile* mf)
  24. : cmLocalCommonGenerator(gg, mf, mf->GetState()->GetBinaryDirectory())
  25. , HomeRelativeOutputPath("")
  26. {
  27. this->TargetImplib = "$TARGET_IMPLIB";
  28. }
  29. // Virtual public methods.
  30. cmLocalNinjaGenerator::~cmLocalNinjaGenerator()
  31. {
  32. }
  33. void cmLocalNinjaGenerator::Generate()
  34. {
  35. // Compute the path to use when referencing the current output
  36. // directory from the top output directory.
  37. this->HomeRelativeOutputPath = this->ConvertToRelativePath(
  38. this->GetBinaryDirectory(), this->GetCurrentBinaryDirectory());
  39. if (this->HomeRelativeOutputPath == ".") {
  40. this->HomeRelativeOutputPath = "";
  41. }
  42. this->SetConfigName();
  43. this->WriteProcessedMakefile(this->GetBuildFileStream());
  44. #ifdef NINJA_GEN_VERBOSE_FILES
  45. this->WriteProcessedMakefile(this->GetRulesFileStream());
  46. #endif
  47. // We do that only once for the top CMakeLists.txt file.
  48. if (this->IsRootMakefile()) {
  49. this->WriteBuildFileTop();
  50. this->WritePools(this->GetRulesFileStream());
  51. const std::string showIncludesPrefix =
  52. this->GetMakefile()->GetSafeDefinition("CMAKE_CL_SHOWINCLUDES_PREFIX");
  53. if (!showIncludesPrefix.empty()) {
  54. cmGlobalNinjaGenerator::WriteComment(this->GetRulesFileStream(),
  55. "localized /showIncludes string");
  56. this->GetRulesFileStream() << "msvc_deps_prefix = " << showIncludesPrefix
  57. << "\n\n";
  58. }
  59. }
  60. std::vector<cmGeneratorTarget*> targets = this->GetGeneratorTargets();
  61. for (std::vector<cmGeneratorTarget*>::iterator t = targets.begin();
  62. t != targets.end(); ++t) {
  63. if ((*t)->GetType() == cmState::INTERFACE_LIBRARY) {
  64. continue;
  65. }
  66. cmNinjaTargetGenerator* tg = cmNinjaTargetGenerator::New(*t);
  67. if (tg) {
  68. tg->Generate();
  69. // Add the target to "all" if required.
  70. if (!this->GetGlobalNinjaGenerator()->IsExcluded(
  71. this->GetGlobalNinjaGenerator()->GetLocalGenerators()[0], *t)) {
  72. this->GetGlobalNinjaGenerator()->AddDependencyToAll(*t);
  73. }
  74. delete tg;
  75. }
  76. }
  77. this->WriteCustomCommandBuildStatements();
  78. }
  79. // TODO: Picked up from cmLocalUnixMakefileGenerator3. Refactor it.
  80. std::string cmLocalNinjaGenerator::GetTargetDirectory(
  81. cmGeneratorTarget const* target) const
  82. {
  83. std::string dir = cmake::GetCMakeFilesDirectoryPostSlash();
  84. dir += target->GetName();
  85. #if defined(__VMS)
  86. dir += "_dir";
  87. #else
  88. dir += ".dir";
  89. #endif
  90. return dir;
  91. }
  92. // Non-virtual public methods.
  93. const cmGlobalNinjaGenerator* cmLocalNinjaGenerator::GetGlobalNinjaGenerator()
  94. const
  95. {
  96. return static_cast<const cmGlobalNinjaGenerator*>(
  97. this->GetGlobalGenerator());
  98. }
  99. cmGlobalNinjaGenerator* cmLocalNinjaGenerator::GetGlobalNinjaGenerator()
  100. {
  101. return static_cast<cmGlobalNinjaGenerator*>(this->GetGlobalGenerator());
  102. }
  103. // Virtual protected methods.
  104. std::string cmLocalNinjaGenerator::ConvertToLinkReference(
  105. std::string const& lib, cmOutputConverter::OutputFormat format)
  106. {
  107. std::string path = this->GetGlobalNinjaGenerator()->ConvertToNinjaPath(lib);
  108. return this->ConvertToOutputFormat(path, format);
  109. }
  110. std::string cmLocalNinjaGenerator::ConvertToIncludeReference(
  111. std::string const& path, cmOutputConverter::OutputFormat format,
  112. bool forceFullPaths)
  113. {
  114. if (forceFullPaths) {
  115. return this->ConvertToOutputFormat(cmSystemTools::CollapseFullPath(path),
  116. format);
  117. }
  118. return this->ConvertToOutputFormat(
  119. this->ConvertToRelativePath(this->GetBinaryDirectory(), path), format);
  120. }
  121. // Private methods.
  122. cmGeneratedFileStream& cmLocalNinjaGenerator::GetBuildFileStream() const
  123. {
  124. return *this->GetGlobalNinjaGenerator()->GetBuildFileStream();
  125. }
  126. cmGeneratedFileStream& cmLocalNinjaGenerator::GetRulesFileStream() const
  127. {
  128. return *this->GetGlobalNinjaGenerator()->GetRulesFileStream();
  129. }
  130. const cmake* cmLocalNinjaGenerator::GetCMakeInstance() const
  131. {
  132. return this->GetGlobalGenerator()->GetCMakeInstance();
  133. }
  134. cmake* cmLocalNinjaGenerator::GetCMakeInstance()
  135. {
  136. return this->GetGlobalGenerator()->GetCMakeInstance();
  137. }
  138. void cmLocalNinjaGenerator::WriteBuildFileTop()
  139. {
  140. // For the build file.
  141. this->WriteProjectHeader(this->GetBuildFileStream());
  142. this->WriteNinjaRequiredVersion(this->GetBuildFileStream());
  143. this->WriteNinjaFilesInclusion(this->GetBuildFileStream());
  144. // For the rule file.
  145. this->WriteProjectHeader(this->GetRulesFileStream());
  146. }
  147. void cmLocalNinjaGenerator::WriteProjectHeader(std::ostream& os)
  148. {
  149. cmGlobalNinjaGenerator::WriteDivider(os);
  150. os << "# Project: " << this->GetProjectName() << std::endl
  151. << "# Configuration: " << this->ConfigName << std::endl;
  152. cmGlobalNinjaGenerator::WriteDivider(os);
  153. }
  154. void cmLocalNinjaGenerator::WriteNinjaRequiredVersion(std::ostream& os)
  155. {
  156. // Default required version
  157. std::string requiredVersion =
  158. this->GetGlobalNinjaGenerator()->RequiredNinjaVersion();
  159. // Ninja generator uses the 'console' pool if available (>= 1.5)
  160. if (this->GetGlobalNinjaGenerator()->SupportsConsolePool()) {
  161. requiredVersion =
  162. this->GetGlobalNinjaGenerator()->RequiredNinjaVersionForConsolePool();
  163. }
  164. cmGlobalNinjaGenerator::WriteComment(
  165. os, "Minimal version of Ninja required by this file");
  166. os << "ninja_required_version = " << requiredVersion << std::endl
  167. << std::endl;
  168. }
  169. void cmLocalNinjaGenerator::WritePools(std::ostream& os)
  170. {
  171. cmGlobalNinjaGenerator::WriteDivider(os);
  172. const char* jobpools =
  173. this->GetCMakeInstance()->GetState()->GetGlobalProperty("JOB_POOLS");
  174. if (jobpools) {
  175. cmGlobalNinjaGenerator::WriteComment(
  176. os, "Pools defined by global property JOB_POOLS");
  177. std::vector<std::string> pools;
  178. cmSystemTools::ExpandListArgument(jobpools, pools);
  179. for (size_t i = 0; i < pools.size(); ++i) {
  180. const std::string pool = pools[i];
  181. const std::string::size_type eq = pool.find('=');
  182. unsigned int jobs;
  183. if (eq != std::string::npos &&
  184. sscanf(pool.c_str() + eq, "=%u", &jobs) == 1) {
  185. os << "pool " << pool.substr(0, eq) << std::endl;
  186. os << " depth = " << jobs << std::endl;
  187. os << std::endl;
  188. } else {
  189. cmSystemTools::Error("Invalid pool defined by property 'JOB_POOLS': ",
  190. pool.c_str());
  191. }
  192. }
  193. }
  194. }
  195. void cmLocalNinjaGenerator::WriteNinjaFilesInclusion(std::ostream& os)
  196. {
  197. cmGlobalNinjaGenerator::WriteDivider(os);
  198. os << "# Include auxiliary files.\n"
  199. << "\n";
  200. cmGlobalNinjaGenerator* ng = this->GetGlobalNinjaGenerator();
  201. std::string const ninjaRulesFile =
  202. ng->NinjaOutputPath(cmGlobalNinjaGenerator::NINJA_RULES_FILE);
  203. std::string const rulesFilePath =
  204. ng->EncodeIdent(ng->EncodePath(ninjaRulesFile), os);
  205. cmGlobalNinjaGenerator::WriteInclude(os, rulesFilePath,
  206. "Include rules file.");
  207. os << "\n";
  208. }
  209. void cmLocalNinjaGenerator::ComputeObjectFilenames(
  210. std::map<cmSourceFile const*, std::string>& mapping,
  211. cmGeneratorTarget const* gt)
  212. {
  213. for (std::map<cmSourceFile const*, std::string>::iterator si =
  214. mapping.begin();
  215. si != mapping.end(); ++si) {
  216. cmSourceFile const* sf = si->first;
  217. si->second =
  218. this->GetObjectFileNameWithoutTarget(*sf, gt->ObjectDirectory);
  219. }
  220. }
  221. void cmLocalNinjaGenerator::WriteProcessedMakefile(std::ostream& os)
  222. {
  223. cmGlobalNinjaGenerator::WriteDivider(os);
  224. os << "# Write statements declared in CMakeLists.txt:" << std::endl
  225. << "# " << this->Makefile->GetDefinition("CMAKE_CURRENT_LIST_FILE")
  226. << std::endl;
  227. if (this->IsRootMakefile()) {
  228. os << "# Which is the root file." << std::endl;
  229. }
  230. cmGlobalNinjaGenerator::WriteDivider(os);
  231. os << std::endl;
  232. }
  233. void cmLocalNinjaGenerator::AppendTargetOutputs(cmGeneratorTarget* target,
  234. cmNinjaDeps& outputs)
  235. {
  236. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(target, outputs);
  237. }
  238. void cmLocalNinjaGenerator::AppendTargetDepends(cmGeneratorTarget* target,
  239. cmNinjaDeps& outputs)
  240. {
  241. this->GetGlobalNinjaGenerator()->AppendTargetDepends(target, outputs);
  242. }
  243. void cmLocalNinjaGenerator::AppendCustomCommandDeps(
  244. cmCustomCommandGenerator const& ccg, cmNinjaDeps& ninjaDeps)
  245. {
  246. const std::vector<std::string>& deps = ccg.GetDepends();
  247. for (std::vector<std::string>::const_iterator i = deps.begin();
  248. i != deps.end(); ++i) {
  249. std::string dep;
  250. if (this->GetRealDependency(*i, this->GetConfigName(), dep)) {
  251. ninjaDeps.push_back(
  252. this->GetGlobalNinjaGenerator()->ConvertToNinjaPath(dep));
  253. }
  254. }
  255. }
  256. std::string cmLocalNinjaGenerator::BuildCommandLine(
  257. const std::vector<std::string>& cmdLines)
  258. {
  259. // If we have no commands but we need to build a command anyway, use ":".
  260. // This happens when building a POST_BUILD value for link targets that
  261. // don't use POST_BUILD.
  262. if (cmdLines.empty()) {
  263. #ifdef _WIN32
  264. return "cd .";
  265. #else
  266. return ":";
  267. #endif
  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 = "RULE_LAUNCH_CUSTOM";
  419. const char* property_value = this->Makefile->GetProperty(property);
  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. RuleVariables vars;
  426. vars.RuleLauncher = property;
  427. std::string output;
  428. const std::vector<std::string>& outputs = ccg.GetOutputs();
  429. if (!outputs.empty()) {
  430. if (ccg.GetWorkingDirectory().empty()) {
  431. output = this->ConvertToOutputFormat(
  432. this->ConvertToRelativePath(this->GetCurrentBinaryDirectory(),
  433. outputs[0]),
  434. cmOutputConverter::SHELL);
  435. } else {
  436. output =
  437. this->ConvertToOutputFormat(outputs[0], cmOutputConverter::SHELL);
  438. }
  439. }
  440. vars.Output = output.c_str();
  441. std::string launcher;
  442. this->ExpandRuleVariables(launcher, vars);
  443. if (!launcher.empty()) {
  444. launcher += " ";
  445. }
  446. return launcher;
  447. }