cmLocalNinjaGenerator.cxx 17 KB

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