cmLocalNinjaGenerator.cxx 17 KB

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