cmLocalNinjaGenerator.cxx 16 KB

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