cmLocalNinjaGenerator.cxx 17 KB

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