cmLocalNinjaGenerator.cxx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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 "cmCustomCommandGenerator.h"
  13. #include "cmMakefile.h"
  14. #include "cmGlobalNinjaGenerator.h"
  15. #include "cmNinjaTargetGenerator.h"
  16. #include "cmGeneratedFileStream.h"
  17. #include "cmSourceFile.h"
  18. #include "cmake.h"
  19. #include "cmState.h"
  20. #include <assert.h>
  21. cmLocalNinjaGenerator::cmLocalNinjaGenerator(cmGlobalGenerator* gg,
  22. cmLocalGenerator* parent,
  23. cmState::Snapshot snapshot)
  24. : cmLocalCommonGenerator(gg, parent, snapshot)
  25. , HomeRelativeOutputPath("")
  26. {
  27. this->TargetImplib = "$TARGET_IMPLIB";
  28. }
  29. //----------------------------------------------------------------------------
  30. // Virtual public methods.
  31. cmLocalNinjaGenerator::~cmLocalNinjaGenerator()
  32. {
  33. }
  34. void cmLocalNinjaGenerator::Generate()
  35. {
  36. // Compute the path to use when referencing the current output
  37. // directory from the top output directory.
  38. this->HomeRelativeOutputPath =
  39. this->Convert(this->Makefile->GetCurrentBinaryDirectory(), HOME_OUTPUT);
  40. if(this->HomeRelativeOutputPath == ".")
  41. {
  42. this->HomeRelativeOutputPath = "";
  43. }
  44. this->SetConfigName();
  45. this->WriteProcessedMakefile(this->GetBuildFileStream());
  46. #ifdef NINJA_GEN_VERBOSE_FILES
  47. this->WriteProcessedMakefile(this->GetRulesFileStream());
  48. #endif
  49. // We do that only once for the top CMakeLists.txt file.
  50. if(this->Makefile->IsRootMakefile())
  51. {
  52. this->WriteBuildFileTop();
  53. this->WritePools(this->GetRulesFileStream());
  54. const std::string showIncludesPrefix = this->GetMakefile()
  55. ->GetSafeDefinition("CMAKE_CL_SHOWINCLUDES_PREFIX");
  56. if (!showIncludesPrefix.empty())
  57. {
  58. cmGlobalNinjaGenerator::WriteComment(this->GetRulesFileStream(),
  59. "localized /showIncludes string");
  60. this->GetRulesFileStream()
  61. << "msvc_deps_prefix = " << showIncludesPrefix << "\n\n";
  62. }
  63. }
  64. cmGeneratorTargetsType targets = this->GetMakefile()->GetGeneratorTargets();
  65. for(cmGeneratorTargetsType::iterator t = targets.begin();
  66. t != targets.end(); ++t)
  67. {
  68. if (t->second->Target->GetType() == cmTarget::INTERFACE_LIBRARY
  69. || t->second->Target->IsImported())
  70. {
  71. continue;
  72. }
  73. cmNinjaTargetGenerator* tg = cmNinjaTargetGenerator::New(t->second);
  74. if(tg)
  75. {
  76. tg->Generate();
  77. // Add the target to "all" if required.
  78. if (!this->GetGlobalNinjaGenerator()->IsExcluded(
  79. this->GetGlobalNinjaGenerator()->GetLocalGenerators()[0],
  80. *t->second->Target))
  81. this->GetGlobalNinjaGenerator()->AddDependencyToAll(t->second->Target);
  82. delete tg;
  83. }
  84. }
  85. this->WriteCustomCommandBuildStatements();
  86. }
  87. // TODO: Picked up from cmLocalUnixMakefileGenerator3. Refactor it.
  88. std::string cmLocalNinjaGenerator
  89. ::GetTargetDirectory(cmTarget 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. //----------------------------------------------------------------------------
  101. // Non-virtual public methods.
  102. const cmGlobalNinjaGenerator*
  103. cmLocalNinjaGenerator::GetGlobalNinjaGenerator() const
  104. {
  105. return
  106. static_cast<const cmGlobalNinjaGenerator*>(this->GetGlobalGenerator());
  107. }
  108. cmGlobalNinjaGenerator* cmLocalNinjaGenerator::GetGlobalNinjaGenerator()
  109. {
  110. return static_cast<cmGlobalNinjaGenerator*>(this->GetGlobalGenerator());
  111. }
  112. //----------------------------------------------------------------------------
  113. // Virtual protected methods.
  114. std::string
  115. cmLocalNinjaGenerator::ConvertToLinkReference(std::string const& lib,
  116. OutputFormat format)
  117. {
  118. return this->Convert(lib, HOME_OUTPUT, format);
  119. }
  120. std::string
  121. cmLocalNinjaGenerator::ConvertToIncludeReference(std::string const& path,
  122. OutputFormat format,
  123. bool forceFullPaths)
  124. {
  125. return this->Convert(path, forceFullPaths? FULL : HOME_OUTPUT, format);
  126. }
  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
  158. << "# Project: " << this->GetMakefile()->GetProjectName() << std::endl
  159. << "# Configuration: " << this->ConfigName << std::endl
  160. ;
  161. cmGlobalNinjaGenerator::WriteDivider(os);
  162. }
  163. void cmLocalNinjaGenerator::WriteNinjaRequiredVersion(std::ostream& os)
  164. {
  165. // Default required version
  166. // Ninja generator uses 'deps' and 'msvc_deps_prefix' introduced in 1.3
  167. std::string requiredVersion = "1.3";
  168. // Ninja generator uses the 'console' pool if available (>= 1.5)
  169. std::string usedVersion = this->GetGlobalNinjaGenerator()->ninjaVersion();
  170. if(cmSystemTools::VersionCompare(cmSystemTools::OP_LESS,
  171. usedVersion.c_str(),
  172. "1.5") == false)
  173. {
  174. requiredVersion = "1.5";
  175. }
  176. cmGlobalNinjaGenerator::WriteComment(os,
  177. "Minimal version of Ninja required by this file");
  178. os
  179. << "ninja_required_version = "
  180. << requiredVersion
  181. << std::endl << std::endl
  182. ;
  183. }
  184. void cmLocalNinjaGenerator::WritePools(std::ostream& os)
  185. {
  186. cmGlobalNinjaGenerator::WriteDivider(os);
  187. const char* jobpools = this->GetCMakeInstance()->GetState()
  188. ->GetGlobalProperty("JOB_POOLS");
  189. if (jobpools)
  190. {
  191. cmGlobalNinjaGenerator::WriteComment(os,
  192. "Pools defined by global property JOB_POOLS");
  193. std::vector<std::string> pools;
  194. cmSystemTools::ExpandListArgument(jobpools, pools);
  195. for (size_t i = 0; i < pools.size(); ++i)
  196. {
  197. const std::string pool = pools[i];
  198. const std::string::size_type eq = pool.find("=");
  199. unsigned int jobs;
  200. if (eq != std::string::npos &&
  201. sscanf(pool.c_str() + eq, "=%u", &jobs) == 1)
  202. {
  203. os << "pool " << pool.substr(0, eq) << std::endl;
  204. os << " depth = " << jobs << std::endl;
  205. os << std::endl;
  206. }
  207. else
  208. {
  209. cmSystemTools::Error("Invalid pool defined by property 'JOB_POOLS': ",
  210. pool.c_str());
  211. }
  212. }
  213. }
  214. }
  215. void cmLocalNinjaGenerator::WriteNinjaFilesInclusion(std::ostream& os)
  216. {
  217. cmGlobalNinjaGenerator::WriteDivider(os);
  218. os
  219. << "# Include auxiliary files.\n"
  220. << "\n"
  221. ;
  222. cmGlobalNinjaGenerator::WriteInclude(os,
  223. cmGlobalNinjaGenerator::NINJA_RULES_FILE,
  224. "Include rules file.");
  225. os << "\n";
  226. }
  227. //----------------------------------------------------------------------------
  228. void cmLocalNinjaGenerator::ComputeObjectFilenames(
  229. std::map<cmSourceFile const*, std::string>& mapping,
  230. cmGeneratorTarget const* gt)
  231. {
  232. for(std::map<cmSourceFile const*, std::string>::iterator
  233. si = mapping.begin(); si != mapping.end(); ++si)
  234. {
  235. cmSourceFile const* sf = si->first;
  236. si->second = this->GetObjectFileNameWithoutTarget(*sf,
  237. gt->ObjectDirectory);
  238. }
  239. }
  240. void cmLocalNinjaGenerator::WriteProcessedMakefile(std::ostream& os)
  241. {
  242. cmGlobalNinjaGenerator::WriteDivider(os);
  243. os
  244. << "# Write statements declared in CMakeLists.txt:" << std::endl
  245. << "# "
  246. << this->Makefile->GetDefinition("CMAKE_CURRENT_LIST_FILE") << std::endl;
  247. if(this->Makefile->IsRootMakefile())
  248. os << "# Which is the root file." << std::endl;
  249. cmGlobalNinjaGenerator::WriteDivider(os);
  250. os << std::endl;
  251. }
  252. std::string cmLocalNinjaGenerator::ConvertToNinjaPath(const std::string& path)
  253. {
  254. std::string convPath = this->Convert(path, cmLocalGenerator::HOME_OUTPUT);
  255. #ifdef _WIN32
  256. cmSystemTools::ReplaceString(convPath, "/", "\\");
  257. #endif
  258. return convPath;
  259. }
  260. void
  261. cmLocalNinjaGenerator
  262. ::AppendTargetOutputs(cmTarget* target, cmNinjaDeps& outputs)
  263. {
  264. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(target, outputs);
  265. }
  266. void
  267. cmLocalNinjaGenerator
  268. ::AppendTargetDepends(cmTarget* target, cmNinjaDeps& outputs)
  269. {
  270. this->GetGlobalNinjaGenerator()->AppendTargetDepends(target, outputs);
  271. }
  272. void cmLocalNinjaGenerator::AppendCustomCommandDeps(
  273. cmCustomCommandGenerator const& ccg,
  274. cmNinjaDeps &ninjaDeps)
  275. {
  276. const std::vector<std::string> &deps = ccg.GetDepends();
  277. for (std::vector<std::string>::const_iterator i = deps.begin();
  278. i != deps.end(); ++i) {
  279. std::string dep;
  280. if (this->GetRealDependency(*i, this->GetConfigName(), dep))
  281. ninjaDeps.push_back(ConvertToNinjaPath(dep));
  282. }
  283. }
  284. std::string cmLocalNinjaGenerator::BuildCommandLine(
  285. const std::vector<std::string> &cmdLines)
  286. {
  287. // If we have no commands but we need to build a command anyway, use ":".
  288. // This happens when building a POST_BUILD value for link targets that
  289. // don't use POST_BUILD.
  290. if (cmdLines.empty())
  291. #ifdef _WIN32
  292. return "cd .";
  293. #else
  294. return ":";
  295. #endif
  296. std::ostringstream cmd;
  297. for (std::vector<std::string>::const_iterator li = cmdLines.begin();
  298. li != cmdLines.end(); ++li)
  299. #ifdef _WIN32
  300. {
  301. if (li != cmdLines.begin())
  302. {
  303. cmd << " && ";
  304. }
  305. else if (cmdLines.size() > 1)
  306. {
  307. cmd << "cmd.exe /C \"";
  308. }
  309. cmd << *li;
  310. }
  311. if (cmdLines.size() > 1)
  312. {
  313. cmd << "\"";
  314. }
  315. #else
  316. {
  317. if (li != cmdLines.begin())
  318. {
  319. cmd << " && ";
  320. }
  321. cmd << *li;
  322. }
  323. #endif
  324. return cmd.str();
  325. }
  326. void cmLocalNinjaGenerator::AppendCustomCommandLines(
  327. cmCustomCommandGenerator const& ccg,
  328. std::vector<std::string> &cmdLines)
  329. {
  330. if (ccg.GetNumberOfCommands() > 0) {
  331. std::string wd = ccg.GetWorkingDirectory();
  332. if (wd.empty())
  333. wd = this->GetMakefile()->GetCurrentBinaryDirectory();
  334. std::ostringstream cdCmd;
  335. #ifdef _WIN32
  336. std::string cdStr = "cd /D ";
  337. #else
  338. std::string cdStr = "cd ";
  339. #endif
  340. cdCmd << cdStr << this->ConvertToOutputFormat(wd, SHELL);
  341. cmdLines.push_back(cdCmd.str());
  342. }
  343. std::string launcher = this->MakeCustomLauncher(ccg);
  344. for (unsigned i = 0; i != ccg.GetNumberOfCommands(); ++i) {
  345. cmdLines.push_back(launcher +
  346. this->ConvertToOutputFormat(ccg.GetCommand(i), SHELL));
  347. std::string& cmd = cmdLines.back();
  348. ccg.AppendArguments(i, cmd);
  349. }
  350. }
  351. void
  352. cmLocalNinjaGenerator::WriteCustomCommandBuildStatement(
  353. cmCustomCommand const *cc, const cmNinjaDeps& orderOnlyDeps)
  354. {
  355. if (this->GetGlobalNinjaGenerator()->SeenCustomCommand(cc))
  356. return;
  357. cmCustomCommandGenerator ccg(*cc, this->GetConfigName(), this->Makefile);
  358. const std::vector<std::string> &outputs = ccg.GetOutputs();
  359. const std::vector<std::string> &byproducts = ccg.GetByproducts();
  360. cmNinjaDeps ninjaOutputs(outputs.size()+byproducts.size()), ninjaDeps;
  361. #if 0
  362. #error TODO: Once CC in an ExternalProject target must provide the \
  363. file of each imported target that has an add_dependencies pointing \
  364. at us. How to know which ExternalProject step actually provides it?
  365. #endif
  366. std::transform(outputs.begin(), outputs.end(),
  367. ninjaOutputs.begin(), MapToNinjaPath());
  368. std::transform(byproducts.begin(), byproducts.end(),
  369. ninjaOutputs.begin() + outputs.size(), MapToNinjaPath());
  370. this->AppendCustomCommandDeps(ccg, ninjaDeps);
  371. for (cmNinjaDeps::iterator i = ninjaOutputs.begin(); i != ninjaOutputs.end();
  372. ++i)
  373. this->GetGlobalNinjaGenerator()->SeenCustomCommandOutput(*i);
  374. std::vector<std::string> cmdLines;
  375. this->AppendCustomCommandLines(ccg, cmdLines);
  376. if (cmdLines.empty()) {
  377. this->GetGlobalNinjaGenerator()->WritePhonyBuild(
  378. this->GetBuildFileStream(),
  379. "Phony custom command for " +
  380. ninjaOutputs[0],
  381. ninjaOutputs,
  382. ninjaDeps,
  383. cmNinjaDeps(),
  384. orderOnlyDeps,
  385. cmNinjaVars());
  386. } else {
  387. this->GetGlobalNinjaGenerator()->WriteCustomCommandBuild(
  388. this->BuildCommandLine(cmdLines),
  389. this->ConstructComment(ccg),
  390. "Custom command for " + ninjaOutputs[0],
  391. cc->GetUsesTerminal(),
  392. ninjaOutputs,
  393. ninjaDeps,
  394. orderOnlyDeps);
  395. }
  396. }
  397. void cmLocalNinjaGenerator::AddCustomCommandTarget(cmCustomCommand const* cc,
  398. cmTarget* target)
  399. {
  400. this->CustomCommandTargets[cc].insert(target);
  401. }
  402. void cmLocalNinjaGenerator::WriteCustomCommandBuildStatements()
  403. {
  404. for (CustomCommandTargetMap::iterator i = this->CustomCommandTargets.begin();
  405. i != this->CustomCommandTargets.end(); ++i) {
  406. // A custom command may appear on multiple targets. However, some build
  407. // systems exist where the target dependencies on some of the targets are
  408. // overspecified, leading to a dependency cycle. If we assume all target
  409. // dependencies are a superset of the true target dependencies for this
  410. // custom command, we can take the set intersection of all target
  411. // dependencies to obtain a correct dependency list.
  412. //
  413. // FIXME: This won't work in certain obscure scenarios involving indirect
  414. // dependencies.
  415. std::set<cmTarget*>::iterator j = i->second.begin();
  416. assert(j != i->second.end());
  417. std::vector<std::string> ccTargetDeps;
  418. this->AppendTargetDepends(*j, ccTargetDeps);
  419. std::sort(ccTargetDeps.begin(), ccTargetDeps.end());
  420. ++j;
  421. for (; j != i->second.end(); ++j) {
  422. std::vector<std::string> jDeps, depsIntersection;
  423. this->AppendTargetDepends(*j, jDeps);
  424. std::sort(jDeps.begin(), jDeps.end());
  425. std::set_intersection(ccTargetDeps.begin(), ccTargetDeps.end(),
  426. jDeps.begin(), jDeps.end(),
  427. std::back_inserter(depsIntersection));
  428. ccTargetDeps = depsIntersection;
  429. }
  430. this->WriteCustomCommandBuildStatement(i->first, ccTargetDeps);
  431. }
  432. }
  433. std::string cmLocalNinjaGenerator::MakeCustomLauncher(
  434. cmCustomCommandGenerator const& ccg)
  435. {
  436. const char* property = "RULE_LAUNCH_CUSTOM";
  437. const char* property_value = this->Makefile->GetProperty(property);
  438. if(!property_value || !*property_value)
  439. {
  440. return std::string();
  441. }
  442. // Expand rules in the empty string. It may insert the launcher and
  443. // perform replacements.
  444. RuleVariables vars;
  445. vars.RuleLauncher = property;
  446. std::string output;
  447. const std::vector<std::string>& outputs = ccg.GetOutputs();
  448. if(!outputs.empty())
  449. {
  450. RelativeRoot relative_root =
  451. ccg.GetWorkingDirectory().empty() ? START_OUTPUT : NONE;
  452. output = this->Convert(outputs[0], relative_root, SHELL);
  453. }
  454. vars.Output = output.c_str();
  455. std::string launcher;
  456. this->ExpandRuleVariables(launcher, vars);
  457. if(!launcher.empty())
  458. {
  459. launcher += " ";
  460. }
  461. return launcher;
  462. }