cmLocalNinjaGenerator.cxx 16 KB

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