cmLocalNinjaGenerator.cxx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmLocalNinjaGenerator.h"
  4. #include <algorithm>
  5. #include <cassert>
  6. #include <cstdio>
  7. #include <iterator>
  8. #include <memory>
  9. #include <sstream>
  10. #include <utility>
  11. #include "cmsys/FStream.hxx"
  12. #include "cmCryptoHash.h"
  13. #include "cmCustomCommand.h"
  14. #include "cmCustomCommandGenerator.h"
  15. #include "cmGeneratedFileStream.h"
  16. #include "cmGeneratorExpression.h"
  17. #include "cmGeneratorTarget.h"
  18. #include "cmGlobalGenerator.h"
  19. #include "cmGlobalNinjaGenerator.h"
  20. #include "cmLocalGenerator.h"
  21. #include "cmMakefile.h"
  22. #include "cmNinjaTargetGenerator.h"
  23. #include "cmProperty.h"
  24. #include "cmRulePlaceholderExpander.h"
  25. #include "cmSourceFile.h"
  26. #include "cmState.h"
  27. #include "cmStateTypes.h"
  28. #include "cmStringAlgorithms.h"
  29. #include "cmSystemTools.h"
  30. #include "cmTarget.h"
  31. #include "cmake.h"
  32. cmLocalNinjaGenerator::cmLocalNinjaGenerator(cmGlobalGenerator* gg,
  33. cmMakefile* mf)
  34. : cmLocalCommonGenerator(gg, mf, mf->GetState()->GetBinaryDirectory())
  35. , HomeRelativeOutputPath("")
  36. {
  37. }
  38. // Virtual public methods.
  39. cmRulePlaceholderExpander*
  40. cmLocalNinjaGenerator::CreateRulePlaceholderExpander() const
  41. {
  42. cmRulePlaceholderExpander* ret =
  43. this->cmLocalGenerator::CreateRulePlaceholderExpander();
  44. ret->SetTargetImpLib("$TARGET_IMPLIB");
  45. return ret;
  46. }
  47. cmLocalNinjaGenerator::~cmLocalNinjaGenerator() = default;
  48. void cmLocalNinjaGenerator::Generate()
  49. {
  50. // Compute the path to use when referencing the current output
  51. // directory from the top output directory.
  52. this->HomeRelativeOutputPath = this->MaybeConvertToRelativePath(
  53. this->GetBinaryDirectory(), this->GetCurrentBinaryDirectory());
  54. if (this->HomeRelativeOutputPath == ".") {
  55. this->HomeRelativeOutputPath.clear();
  56. }
  57. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  58. for (auto const& config : this->GetConfigNames()) {
  59. this->WriteProcessedMakefile(this->GetImplFileStream(config));
  60. }
  61. }
  62. this->WriteProcessedMakefile(this->GetCommonFileStream());
  63. #ifdef NINJA_GEN_VERBOSE_FILES
  64. this->WriteProcessedMakefile(this->GetRulesFileStream());
  65. #endif
  66. // We do that only once for the top CMakeLists.txt file.
  67. if (this->IsRootMakefile()) {
  68. this->WriteBuildFileTop();
  69. this->WritePools(this->GetRulesFileStream());
  70. const std::string& showIncludesPrefix =
  71. this->GetMakefile()->GetSafeDefinition("CMAKE_CL_SHOWINCLUDES_PREFIX");
  72. if (!showIncludesPrefix.empty()) {
  73. cmGlobalNinjaGenerator::WriteComment(this->GetRulesFileStream(),
  74. "localized /showIncludes string");
  75. this->GetRulesFileStream() << "msvc_deps_prefix = ";
  76. #ifdef WIN32
  77. // Ninja uses the ANSI Windows APIs, so strings in the rules file
  78. // typically need to be ANSI encoded. However, in this case the compiler
  79. // is being invoked using the UTF-8 codepage so the /showIncludes prefix
  80. // will be UTF-8 encoded on stdout. Ninja can't successfully compare this
  81. // UTF-8 encoded prefix to the ANSI encoded msvc_deps_prefix if it
  82. // contains any non-ASCII characters and dependency checking will fail.
  83. // As a workaround, leave the msvc_deps_prefix UTF-8 encoded even though
  84. // the rest of the file is ANSI encoded.
  85. if (GetConsoleOutputCP() == CP_UTF8 && GetACP() != CP_UTF8) {
  86. this->GetRulesFileStream().WriteRaw(showIncludesPrefix);
  87. } else {
  88. this->GetRulesFileStream() << showIncludesPrefix;
  89. }
  90. #else
  91. // It's safe to use the standard encoding on other platforms.
  92. this->GetRulesFileStream() << showIncludesPrefix;
  93. #endif
  94. this->GetRulesFileStream() << "\n\n";
  95. }
  96. }
  97. for (const auto& target : this->GetGeneratorTargets()) {
  98. if (!target->IsInBuildSystem()) {
  99. continue;
  100. }
  101. auto tg = cmNinjaTargetGenerator::New(target.get());
  102. if (tg) {
  103. if (target->Target->IsPerConfig()) {
  104. for (auto const& config : this->GetConfigNames()) {
  105. tg->Generate(config);
  106. if (target->GetType() == cmStateEnums::GLOBAL_TARGET &&
  107. this->GetGlobalGenerator()->IsMultiConfig()) {
  108. cmNinjaBuild phonyAlias("phony");
  109. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
  110. target.get(), phonyAlias.Outputs, "", DependOnTargetArtifact);
  111. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
  112. target.get(), phonyAlias.ExplicitDeps, config,
  113. DependOnTargetArtifact);
  114. this->GetGlobalNinjaGenerator()->WriteBuild(
  115. *this->GetGlobalNinjaGenerator()->GetConfigFileStream(config),
  116. phonyAlias);
  117. }
  118. }
  119. if (target->GetType() == cmStateEnums::GLOBAL_TARGET &&
  120. this->GetGlobalGenerator()->IsMultiConfig()) {
  121. if (!this->GetGlobalNinjaGenerator()->GetDefaultConfigs().empty()) {
  122. cmNinjaBuild phonyAlias("phony");
  123. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
  124. target.get(), phonyAlias.Outputs, "", DependOnTargetArtifact);
  125. for (auto const& config :
  126. this->GetGlobalNinjaGenerator()->GetDefaultConfigs()) {
  127. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
  128. target.get(), phonyAlias.ExplicitDeps, config,
  129. DependOnTargetArtifact);
  130. }
  131. this->GetGlobalNinjaGenerator()->WriteBuild(
  132. *this->GetGlobalNinjaGenerator()->GetDefaultFileStream(),
  133. phonyAlias);
  134. }
  135. cmNinjaBuild phonyAlias("phony");
  136. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
  137. target.get(), phonyAlias.Outputs, "all", DependOnTargetArtifact);
  138. for (auto const& config : this->GetConfigNames()) {
  139. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
  140. target.get(), phonyAlias.ExplicitDeps, config,
  141. DependOnTargetArtifact);
  142. }
  143. this->GetGlobalNinjaGenerator()->WriteBuild(
  144. *this->GetGlobalNinjaGenerator()->GetDefaultFileStream(),
  145. phonyAlias);
  146. }
  147. } else {
  148. tg->Generate("");
  149. }
  150. }
  151. }
  152. for (auto const& config : this->GetConfigNames()) {
  153. this->WriteCustomCommandBuildStatements(config);
  154. this->AdditionalCleanFiles(config);
  155. }
  156. }
  157. // TODO: Picked up from cmLocalUnixMakefileGenerator3. Refactor it.
  158. std::string cmLocalNinjaGenerator::GetTargetDirectory(
  159. cmGeneratorTarget const* target) const
  160. {
  161. std::string dir = cmStrCat("CMakeFiles/", target->GetName());
  162. #if defined(__VMS)
  163. dir += "_dir";
  164. #else
  165. dir += ".dir";
  166. #endif
  167. return dir;
  168. }
  169. // Non-virtual public methods.
  170. const cmGlobalNinjaGenerator* cmLocalNinjaGenerator::GetGlobalNinjaGenerator()
  171. const
  172. {
  173. return static_cast<const cmGlobalNinjaGenerator*>(
  174. this->GetGlobalGenerator());
  175. }
  176. cmGlobalNinjaGenerator* cmLocalNinjaGenerator::GetGlobalNinjaGenerator()
  177. {
  178. return static_cast<cmGlobalNinjaGenerator*>(this->GetGlobalGenerator());
  179. }
  180. // Virtual protected methods.
  181. std::string cmLocalNinjaGenerator::ConvertToIncludeReference(
  182. std::string const& path, cmOutputConverter::OutputFormat format,
  183. bool forceFullPaths)
  184. {
  185. if (forceFullPaths) {
  186. return this->ConvertToOutputFormat(
  187. cmSystemTools::CollapseFullPath(path, this->GetCurrentBinaryDirectory()),
  188. format);
  189. }
  190. return this->ConvertToOutputFormat(
  191. this->MaybeConvertToRelativePath(this->GetBinaryDirectory(), path),
  192. format);
  193. }
  194. // Private methods.
  195. cmGeneratedFileStream& cmLocalNinjaGenerator::GetImplFileStream(
  196. const std::string& config) const
  197. {
  198. return *this->GetGlobalNinjaGenerator()->GetImplFileStream(config);
  199. }
  200. cmGeneratedFileStream& cmLocalNinjaGenerator::GetCommonFileStream() const
  201. {
  202. return *this->GetGlobalNinjaGenerator()->GetCommonFileStream();
  203. }
  204. cmGeneratedFileStream& cmLocalNinjaGenerator::GetRulesFileStream() const
  205. {
  206. return *this->GetGlobalNinjaGenerator()->GetRulesFileStream();
  207. }
  208. const cmake* cmLocalNinjaGenerator::GetCMakeInstance() const
  209. {
  210. return this->GetGlobalGenerator()->GetCMakeInstance();
  211. }
  212. cmake* cmLocalNinjaGenerator::GetCMakeInstance()
  213. {
  214. return this->GetGlobalGenerator()->GetCMakeInstance();
  215. }
  216. void cmLocalNinjaGenerator::WriteBuildFileTop()
  217. {
  218. this->WriteProjectHeader(this->GetCommonFileStream());
  219. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  220. for (auto const& config : this->GetConfigNames()) {
  221. auto& stream = this->GetImplFileStream(config);
  222. this->WriteProjectHeader(stream);
  223. this->WriteNinjaRequiredVersion(stream);
  224. this->WriteNinjaConfigurationVariable(stream, config);
  225. this->WriteNinjaFilesInclusionConfig(stream);
  226. }
  227. } else {
  228. this->WriteNinjaRequiredVersion(this->GetCommonFileStream());
  229. this->WriteNinjaConfigurationVariable(this->GetCommonFileStream(),
  230. this->GetConfigNames().front());
  231. }
  232. this->WriteNinjaFilesInclusionCommon(this->GetCommonFileStream());
  233. // For the rule file.
  234. this->WriteProjectHeader(this->GetRulesFileStream());
  235. }
  236. void cmLocalNinjaGenerator::WriteProjectHeader(std::ostream& os)
  237. {
  238. cmGlobalNinjaGenerator::WriteDivider(os);
  239. os << "# Project: " << this->GetProjectName() << '\n'
  240. << "# Configurations: " << cmJoin(this->GetConfigNames(), ", ") << '\n';
  241. cmGlobalNinjaGenerator::WriteDivider(os);
  242. }
  243. void cmLocalNinjaGenerator::WriteNinjaRequiredVersion(std::ostream& os)
  244. {
  245. // Default required version
  246. std::string requiredVersion = cmGlobalNinjaGenerator::RequiredNinjaVersion();
  247. // Ninja generator uses the 'console' pool if available (>= 1.5)
  248. if (this->GetGlobalNinjaGenerator()->SupportsConsolePool()) {
  249. requiredVersion =
  250. cmGlobalNinjaGenerator::RequiredNinjaVersionForConsolePool();
  251. }
  252. // The Ninja generator writes rules which require support for restat
  253. // when rebuilding build.ninja manifest (>= 1.8)
  254. if (this->GetGlobalNinjaGenerator()->SupportsManifestRestat() &&
  255. this->GetCMakeInstance()->DoWriteGlobVerifyTarget() &&
  256. !this->GetGlobalNinjaGenerator()->GlobalSettingIsOn(
  257. "CMAKE_SUPPRESS_REGENERATION")) {
  258. requiredVersion =
  259. cmGlobalNinjaGenerator::RequiredNinjaVersionForManifestRestat();
  260. }
  261. cmGlobalNinjaGenerator::WriteComment(
  262. os, "Minimal version of Ninja required by this file");
  263. os << "ninja_required_version = " << requiredVersion << "\n\n";
  264. }
  265. void cmLocalNinjaGenerator::WriteNinjaConfigurationVariable(
  266. std::ostream& os, const std::string& config)
  267. {
  268. cmGlobalNinjaGenerator::WriteVariable(
  269. os, "CONFIGURATION", config,
  270. "Set configuration variable for custom commands.");
  271. }
  272. void cmLocalNinjaGenerator::WritePools(std::ostream& os)
  273. {
  274. cmGlobalNinjaGenerator::WriteDivider(os);
  275. cmProp jobpools =
  276. this->GetCMakeInstance()->GetState()->GetGlobalProperty("JOB_POOLS");
  277. if (!jobpools) {
  278. jobpools = this->GetMakefile()->GetDefinition("CMAKE_JOB_POOLS");
  279. }
  280. if (jobpools) {
  281. cmGlobalNinjaGenerator::WriteComment(
  282. os, "Pools defined by global property JOB_POOLS");
  283. std::vector<std::string> pools = cmExpandedList(*jobpools);
  284. for (std::string const& pool : pools) {
  285. const std::string::size_type eq = pool.find('=');
  286. unsigned int jobs;
  287. if (eq != std::string::npos &&
  288. sscanf(pool.c_str() + eq, "=%u", &jobs) == 1) {
  289. os << "pool " << pool.substr(0, eq) << "\n depth = " << jobs
  290. << "\n\n";
  291. } else {
  292. cmSystemTools::Error("Invalid pool defined by property 'JOB_POOLS': " +
  293. pool);
  294. }
  295. }
  296. }
  297. }
  298. void cmLocalNinjaGenerator::WriteNinjaFilesInclusionConfig(std::ostream& os)
  299. {
  300. cmGlobalNinjaGenerator::WriteDivider(os);
  301. os << "# Include auxiliary files.\n\n";
  302. cmGlobalNinjaGenerator* ng = this->GetGlobalNinjaGenerator();
  303. std::string const ninjaCommonFile =
  304. ng->NinjaOutputPath(cmGlobalNinjaMultiGenerator::NINJA_COMMON_FILE);
  305. std::string const commonFilePath = ng->EncodePath(ninjaCommonFile);
  306. cmGlobalNinjaGenerator::WriteInclude(os, commonFilePath,
  307. "Include common file.");
  308. os << "\n";
  309. }
  310. void cmLocalNinjaGenerator::WriteNinjaFilesInclusionCommon(std::ostream& os)
  311. {
  312. cmGlobalNinjaGenerator::WriteDivider(os);
  313. os << "# Include auxiliary files.\n\n";
  314. cmGlobalNinjaGenerator* ng = this->GetGlobalNinjaGenerator();
  315. std::string const ninjaRulesFile =
  316. ng->NinjaOutputPath(cmGlobalNinjaGenerator::NINJA_RULES_FILE);
  317. std::string const rulesFilePath = ng->EncodePath(ninjaRulesFile);
  318. cmGlobalNinjaGenerator::WriteInclude(os, rulesFilePath,
  319. "Include rules file.");
  320. os << "\n";
  321. }
  322. void cmLocalNinjaGenerator::WriteProcessedMakefile(std::ostream& os)
  323. {
  324. cmGlobalNinjaGenerator::WriteDivider(os);
  325. os << "# Write statements declared in CMakeLists.txt:\n"
  326. << "# "
  327. << cmToCStr(this->Makefile->GetDefinition("CMAKE_CURRENT_LIST_FILE"))
  328. << '\n';
  329. if (this->IsRootMakefile()) {
  330. os << "# Which is the root file.\n";
  331. }
  332. cmGlobalNinjaGenerator::WriteDivider(os);
  333. os << '\n';
  334. }
  335. void cmLocalNinjaGenerator::AppendTargetOutputs(cmGeneratorTarget* target,
  336. cmNinjaDeps& outputs,
  337. const std::string& config)
  338. {
  339. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(target, outputs, config,
  340. DependOnTargetArtifact);
  341. }
  342. void cmLocalNinjaGenerator::AppendTargetDepends(cmGeneratorTarget* target,
  343. cmNinjaDeps& outputs,
  344. const std::string& config,
  345. const std::string& fileConfig,
  346. cmNinjaTargetDepends depends)
  347. {
  348. this->GetGlobalNinjaGenerator()->AppendTargetDepends(target, outputs, config,
  349. fileConfig, depends);
  350. }
  351. void cmLocalNinjaGenerator::AppendCustomCommandDeps(
  352. cmCustomCommandGenerator const& ccg, cmNinjaDeps& ninjaDeps,
  353. const std::string& config)
  354. {
  355. for (std::string const& i : ccg.GetDepends()) {
  356. std::string dep;
  357. if (this->GetRealDependency(i, config, dep)) {
  358. ninjaDeps.push_back(
  359. this->GetGlobalNinjaGenerator()->ConvertToNinjaPath(dep));
  360. }
  361. }
  362. }
  363. std::string cmLocalNinjaGenerator::WriteCommandScript(
  364. std::vector<std::string> const& cmdLines, std::string const& customStep,
  365. cmGeneratorTarget const* target) const
  366. {
  367. std::string scriptPath;
  368. if (target) {
  369. scriptPath = target->GetSupportDirectory();
  370. } else {
  371. scriptPath = cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles");
  372. }
  373. cmSystemTools::MakeDirectory(scriptPath);
  374. scriptPath += '/';
  375. scriptPath += customStep;
  376. #ifdef _WIN32
  377. scriptPath += ".bat";
  378. #else
  379. scriptPath += ".sh";
  380. #endif
  381. cmsys::ofstream script(scriptPath.c_str());
  382. #ifdef _WIN32
  383. script << "@echo off\n";
  384. int line = 1;
  385. #else
  386. script << "set -e\n\n";
  387. #endif
  388. for (auto const& i : cmdLines) {
  389. std::string cmd = i;
  390. // The command line was built assuming it would be written to
  391. // the build.ninja file, so it uses '$$' for '$'. Remove this
  392. // for the raw shell script.
  393. cmSystemTools::ReplaceString(cmd, "$$", "$");
  394. #ifdef _WIN32
  395. script << cmd << " || (set FAIL_LINE=" << ++line << "& goto :ABORT)"
  396. << '\n';
  397. #else
  398. script << cmd << '\n';
  399. #endif
  400. }
  401. #ifdef _WIN32
  402. script << "goto :EOF\n\n"
  403. ":ABORT\n"
  404. "set ERROR_CODE=%ERRORLEVEL%\n"
  405. "echo Batch file failed at line %FAIL_LINE% "
  406. "with errorcode %ERRORLEVEL%\n"
  407. "exit /b %ERROR_CODE%";
  408. #endif
  409. return scriptPath;
  410. }
  411. std::string cmLocalNinjaGenerator::BuildCommandLine(
  412. std::vector<std::string> const& cmdLines, std::string const& customStep,
  413. cmGeneratorTarget const* target) const
  414. {
  415. // If we have no commands but we need to build a command anyway, use noop.
  416. // This happens when building a POST_BUILD value for link targets that
  417. // don't use POST_BUILD.
  418. if (cmdLines.empty()) {
  419. return cmGlobalNinjaGenerator::SHELL_NOOP;
  420. }
  421. // If this is a custom step then we will have no '$VAR' ninja placeholders.
  422. // This means we can deal with long command sequences by writing to a script.
  423. // Do this if the command lines are on the scale of the OS limit.
  424. if (!customStep.empty()) {
  425. size_t cmdLinesTotal = 0;
  426. for (std::string const& cmd : cmdLines) {
  427. cmdLinesTotal += cmd.length() + 6;
  428. }
  429. if (cmdLinesTotal > cmSystemTools::CalculateCommandLineLengthLimit() / 2) {
  430. std::string const scriptPath =
  431. this->WriteCommandScript(cmdLines, customStep, target);
  432. std::string cmd
  433. #ifndef _WIN32
  434. = "/bin/sh "
  435. #endif
  436. ;
  437. cmd += this->ConvertToOutputFormat(
  438. this->GetGlobalNinjaGenerator()->ConvertToNinjaPath(scriptPath),
  439. cmOutputConverter::SHELL);
  440. // Add an unused argument based on script content so that Ninja
  441. // knows when the command lines change.
  442. cmd += " ";
  443. cmCryptoHash hash(cmCryptoHash::AlgoSHA256);
  444. cmd += hash.HashFile(scriptPath).substr(0, 16);
  445. return cmd;
  446. }
  447. }
  448. std::ostringstream cmd;
  449. for (auto li = cmdLines.begin(); li != cmdLines.end(); ++li)
  450. #ifdef _WIN32
  451. {
  452. if (li != cmdLines.begin()) {
  453. cmd << " && ";
  454. } else if (cmdLines.size() > 1) {
  455. cmd << "cmd.exe /C \"";
  456. }
  457. // Put current cmdLine in brackets if it contains "||" because it has
  458. // higher precedence than "&&" in cmd.exe
  459. if (li->find("||") != std::string::npos) {
  460. cmd << "( " << *li << " )";
  461. } else {
  462. cmd << *li;
  463. }
  464. }
  465. if (cmdLines.size() > 1) {
  466. cmd << "\"";
  467. }
  468. #else
  469. {
  470. if (li != cmdLines.begin()) {
  471. cmd << " && ";
  472. }
  473. cmd << *li;
  474. }
  475. #endif
  476. return cmd.str();
  477. }
  478. void cmLocalNinjaGenerator::AppendCustomCommandLines(
  479. cmCustomCommandGenerator const& ccg, std::vector<std::string>& cmdLines)
  480. {
  481. auto* gg = this->GetGlobalNinjaGenerator();
  482. if (ccg.GetNumberOfCommands() > 0) {
  483. std::string wd = ccg.GetWorkingDirectory();
  484. if (wd.empty()) {
  485. wd = this->GetCurrentBinaryDirectory();
  486. }
  487. std::ostringstream cdCmd;
  488. #ifdef _WIN32
  489. std::string cdStr = "cd /D ";
  490. #else
  491. std::string cdStr = "cd ";
  492. #endif
  493. cdCmd << cdStr
  494. << this->ConvertToOutputFormat(wd, cmOutputConverter::SHELL);
  495. cmdLines.push_back(cdCmd.str());
  496. }
  497. std::string launcher = this->MakeCustomLauncher(ccg);
  498. for (unsigned i = 0; i != ccg.GetNumberOfCommands(); ++i) {
  499. cmdLines.push_back(launcher +
  500. this->ConvertToOutputFormat(
  501. ccg.GetCommand(i),
  502. gg->IsMultiConfig() ? cmOutputConverter::NINJAMULTI
  503. : cmOutputConverter::SHELL));
  504. std::string& cmd = cmdLines.back();
  505. ccg.AppendArguments(i, cmd);
  506. }
  507. }
  508. void cmLocalNinjaGenerator::WriteCustomCommandBuildStatement(
  509. cmCustomCommand const* cc, const cmNinjaDeps& orderOnlyDeps,
  510. const std::string& config)
  511. {
  512. cmGlobalNinjaGenerator* gg = this->GetGlobalNinjaGenerator();
  513. if (gg->SeenCustomCommand(cc, config)) {
  514. return;
  515. }
  516. cmCustomCommandGenerator ccg(*cc, config, this);
  517. const std::vector<std::string>& outputs = ccg.GetOutputs();
  518. const std::vector<std::string>& byproducts = ccg.GetByproducts();
  519. bool symbolic = false;
  520. for (std::string const& output : outputs) {
  521. if (cmSourceFile* sf = this->Makefile->GetSource(output)) {
  522. if (sf->GetPropertyAsBool("SYMBOLIC")) {
  523. symbolic = true;
  524. break;
  525. }
  526. }
  527. }
  528. #if 0
  529. # error TODO: Once CC in an ExternalProject target must provide the \
  530. file of each imported target that has an add_dependencies pointing \
  531. at us. How to know which ExternalProject step actually provides it?
  532. #endif
  533. cmNinjaDeps ninjaOutputs(outputs.size() + byproducts.size());
  534. std::transform(outputs.begin(), outputs.end(), ninjaOutputs.begin(),
  535. gg->MapToNinjaPath());
  536. std::transform(byproducts.begin(), byproducts.end(),
  537. ninjaOutputs.begin() + outputs.size(), gg->MapToNinjaPath());
  538. for (std::string const& ninjaOutput : ninjaOutputs) {
  539. gg->SeenCustomCommandOutput(ninjaOutput);
  540. }
  541. cmNinjaDeps ninjaDeps;
  542. this->AppendCustomCommandDeps(ccg, ninjaDeps, config);
  543. std::vector<std::string> cmdLines;
  544. this->AppendCustomCommandLines(ccg, cmdLines);
  545. if (cmdLines.empty()) {
  546. cmNinjaBuild build("phony");
  547. build.Comment = "Phony custom command for " + ninjaOutputs[0];
  548. build.Outputs = std::move(ninjaOutputs);
  549. build.ExplicitDeps = std::move(ninjaDeps);
  550. build.OrderOnlyDeps = orderOnlyDeps;
  551. gg->WriteBuild(this->GetImplFileStream(config), build);
  552. } else {
  553. std::string customStep = cmSystemTools::GetFilenameName(ninjaOutputs[0]);
  554. // Hash full path to make unique.
  555. customStep += '-';
  556. cmCryptoHash hash(cmCryptoHash::AlgoSHA256);
  557. customStep += hash.HashString(ninjaOutputs[0]).substr(0, 7);
  558. gg->WriteCustomCommandBuild(
  559. this->BuildCommandLine(cmdLines, customStep),
  560. this->ConstructComment(ccg), "Custom command for " + ninjaOutputs[0],
  561. cc->GetDepfile(), cc->GetJobPool(), cc->GetUsesTerminal(),
  562. /*restat*/ !symbolic || !byproducts.empty(), ninjaOutputs, config,
  563. ninjaDeps, orderOnlyDeps);
  564. }
  565. }
  566. void cmLocalNinjaGenerator::AddCustomCommandTarget(cmCustomCommand const* cc,
  567. cmGeneratorTarget* target)
  568. {
  569. CustomCommandTargetMap::value_type v(cc, std::set<cmGeneratorTarget*>());
  570. std::pair<CustomCommandTargetMap::iterator, bool> ins =
  571. this->CustomCommandTargets.insert(v);
  572. if (ins.second) {
  573. this->CustomCommands.push_back(cc);
  574. }
  575. ins.first->second.insert(target);
  576. }
  577. void cmLocalNinjaGenerator::WriteCustomCommandBuildStatements(
  578. const std::string& config)
  579. {
  580. for (cmCustomCommand const* customCommand : this->CustomCommands) {
  581. auto i = this->CustomCommandTargets.find(customCommand);
  582. assert(i != this->CustomCommandTargets.end());
  583. // A custom command may appear on multiple targets. However, some build
  584. // systems exist where the target dependencies on some of the targets are
  585. // overspecified, leading to a dependency cycle. If we assume all target
  586. // dependencies are a superset of the true target dependencies for this
  587. // custom command, we can take the set intersection of all target
  588. // dependencies to obtain a correct dependency list.
  589. //
  590. // FIXME: This won't work in certain obscure scenarios involving indirect
  591. // dependencies.
  592. auto j = i->second.begin();
  593. assert(j != i->second.end());
  594. std::vector<std::string> ccTargetDeps;
  595. this->GetGlobalNinjaGenerator()->AppendTargetDependsClosure(
  596. *j, ccTargetDeps, config);
  597. std::sort(ccTargetDeps.begin(), ccTargetDeps.end());
  598. ++j;
  599. for (; j != i->second.end(); ++j) {
  600. std::vector<std::string> jDeps;
  601. std::vector<std::string> depsIntersection;
  602. this->GetGlobalNinjaGenerator()->AppendTargetDependsClosure(*j, jDeps,
  603. config);
  604. std::sort(jDeps.begin(), jDeps.end());
  605. std::set_intersection(ccTargetDeps.begin(), ccTargetDeps.end(),
  606. jDeps.begin(), jDeps.end(),
  607. std::back_inserter(depsIntersection));
  608. ccTargetDeps = depsIntersection;
  609. }
  610. this->WriteCustomCommandBuildStatement(i->first, ccTargetDeps, config);
  611. }
  612. }
  613. std::string cmLocalNinjaGenerator::MakeCustomLauncher(
  614. cmCustomCommandGenerator const& ccg)
  615. {
  616. cmProp property_value = this->Makefile->GetProperty("RULE_LAUNCH_CUSTOM");
  617. if (!cmNonempty(property_value)) {
  618. return std::string();
  619. }
  620. // Expand rule variables referenced in the given launcher command.
  621. cmRulePlaceholderExpander::RuleVariables vars;
  622. std::string output;
  623. const std::vector<std::string>& outputs = ccg.GetOutputs();
  624. if (!outputs.empty()) {
  625. output = outputs[0];
  626. if (ccg.GetWorkingDirectory().empty()) {
  627. output = this->MaybeConvertToRelativePath(
  628. this->GetCurrentBinaryDirectory(), output);
  629. }
  630. output = this->ConvertToOutputFormat(output, cmOutputConverter::SHELL);
  631. }
  632. vars.Output = output.c_str();
  633. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  634. this->CreateRulePlaceholderExpander());
  635. std::string launcher = *property_value;
  636. rulePlaceholderExpander->ExpandRuleVariables(this, launcher, vars);
  637. if (!launcher.empty()) {
  638. launcher += " ";
  639. }
  640. return launcher;
  641. }
  642. void cmLocalNinjaGenerator::AdditionalCleanFiles(const std::string& config)
  643. {
  644. if (cmProp prop_value =
  645. this->Makefile->GetProperty("ADDITIONAL_CLEAN_FILES")) {
  646. std::vector<std::string> cleanFiles;
  647. {
  648. cmExpandList(cmGeneratorExpression::Evaluate(*prop_value, this, config),
  649. cleanFiles);
  650. }
  651. std::string const& binaryDir = this->GetCurrentBinaryDirectory();
  652. cmGlobalNinjaGenerator* gg = this->GetGlobalNinjaGenerator();
  653. for (std::string const& cleanFile : cleanFiles) {
  654. // Support relative paths
  655. gg->AddAdditionalCleanFile(
  656. cmSystemTools::CollapseFullPath(cleanFile, binaryDir), config);
  657. }
  658. }
  659. }