cmGlobalUnixMakefileGenerator3.cxx 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  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 "cmGlobalUnixMakefileGenerator3.h"
  4. #include <algorithm>
  5. #include <functional>
  6. #include <sstream>
  7. #include <utility>
  8. #include <cm/memory>
  9. #include <cmext/algorithm>
  10. #include <cmext/memory>
  11. #include "cmDocumentationEntry.h"
  12. #include "cmGeneratedFileStream.h"
  13. #include "cmGeneratorTarget.h"
  14. #include "cmGlobalGenerator.h"
  15. #include "cmLocalGenerator.h"
  16. #include "cmLocalUnixMakefileGenerator3.h"
  17. #include "cmMakefile.h"
  18. #include "cmMakefileTargetGenerator.h"
  19. #include "cmOutputConverter.h"
  20. #include "cmProperty.h"
  21. #include "cmState.h"
  22. #include "cmStateDirectory.h"
  23. #include "cmStateTypes.h"
  24. #include "cmStringAlgorithms.h"
  25. #include "cmSystemTools.h"
  26. #include "cmTargetDepend.h"
  27. #include "cmake.h"
  28. cmGlobalUnixMakefileGenerator3::cmGlobalUnixMakefileGenerator3(cmake* cm)
  29. : cmGlobalCommonGenerator(cm)
  30. {
  31. // This type of makefile always requires unix style paths
  32. this->ForceUnixPaths = true;
  33. this->FindMakeProgramFile = "CMakeUnixFindMake.cmake";
  34. this->ToolSupportsColor = true;
  35. #if defined(_WIN32) || defined(__VMS)
  36. this->UseLinkScript = false;
  37. #else
  38. this->UseLinkScript = true;
  39. #endif
  40. this->IncludeDirective = "include";
  41. this->LineContinueDirective = "\\\n";
  42. this->DefineWindowsNULL = false;
  43. this->PassMakeflags = false;
  44. this->UnixCD = true;
  45. }
  46. cmGlobalUnixMakefileGenerator3::~cmGlobalUnixMakefileGenerator3() = default;
  47. void cmGlobalUnixMakefileGenerator3::EnableLanguage(
  48. std::vector<std::string> const& languages, cmMakefile* mf, bool optional)
  49. {
  50. this->cmGlobalGenerator::EnableLanguage(languages, mf, optional);
  51. for (std::string const& language : languages) {
  52. if (language == "NONE") {
  53. continue;
  54. }
  55. this->ResolveLanguageCompiler(language, mf, optional);
  56. }
  57. }
  58. //! Create a local generator appropriate to this Global Generator
  59. std::unique_ptr<cmLocalGenerator>
  60. cmGlobalUnixMakefileGenerator3::CreateLocalGenerator(cmMakefile* mf)
  61. {
  62. return std::unique_ptr<cmLocalGenerator>(
  63. cm::make_unique<cmLocalUnixMakefileGenerator3>(this, mf));
  64. }
  65. void cmGlobalUnixMakefileGenerator3::GetDocumentation(
  66. cmDocumentationEntry& entry)
  67. {
  68. entry.Name = cmGlobalUnixMakefileGenerator3::GetActualName();
  69. entry.Brief = "Generates standard UNIX makefiles.";
  70. }
  71. std::string cmGlobalUnixMakefileGenerator3::GetEditCacheCommand() const
  72. {
  73. // If generating for an extra IDE, the edit_cache target cannot
  74. // launch a terminal-interactive tool, so always use cmake-gui.
  75. if (!this->GetExtraGeneratorName().empty()) {
  76. return cmSystemTools::GetCMakeGUICommand();
  77. }
  78. // Use an internal cache entry to track the latest dialog used
  79. // to edit the cache, and use that for the edit_cache target.
  80. cmake* cm = this->GetCMakeInstance();
  81. std::string editCacheCommand = cm->GetCMakeEditCommand();
  82. if (!cm->GetCacheDefinition("CMAKE_EDIT_COMMAND") ||
  83. !editCacheCommand.empty()) {
  84. if (editCacheCommand.empty()) {
  85. editCacheCommand = cmSystemTools::GetCMakeCursesCommand();
  86. }
  87. if (editCacheCommand.empty()) {
  88. editCacheCommand = cmSystemTools::GetCMakeGUICommand();
  89. }
  90. if (!editCacheCommand.empty()) {
  91. cm->AddCacheEntry("CMAKE_EDIT_COMMAND", editCacheCommand.c_str(),
  92. "Path to cache edit program executable.",
  93. cmStateEnums::INTERNAL);
  94. }
  95. }
  96. cmProp edit_cmd = cm->GetCacheDefinition("CMAKE_EDIT_COMMAND");
  97. return edit_cmd ? *edit_cmd : std::string();
  98. }
  99. void cmGlobalUnixMakefileGenerator3::ComputeTargetObjectDirectory(
  100. cmGeneratorTarget* gt) const
  101. {
  102. // Compute full path to object file directory for this target.
  103. std::string dir =
  104. cmStrCat(gt->LocalGenerator->GetCurrentBinaryDirectory(), '/',
  105. gt->LocalGenerator->GetTargetDirectory(gt), '/');
  106. gt->ObjectDirectory = dir;
  107. }
  108. bool cmGlobalUnixMakefileGenerator3::CanEscapeOctothorpe() const
  109. {
  110. // Make tools that use UNIX-style '/' paths also support '\' escaping.
  111. return this->ForceUnixPaths;
  112. }
  113. void cmGlobalUnixMakefileGenerator3::Configure()
  114. {
  115. // Initialize CMAKE_EDIT_COMMAND cache entry.
  116. this->GetEditCacheCommand();
  117. this->cmGlobalGenerator::Configure();
  118. }
  119. void cmGlobalUnixMakefileGenerator3::Generate()
  120. {
  121. // first do superclass method
  122. this->cmGlobalGenerator::Generate();
  123. // initialize progress
  124. unsigned long total = 0;
  125. for (auto const& pmi : this->ProgressMap) {
  126. total += pmi.second.NumberOfActions;
  127. }
  128. // write each target's progress.make this loop is done twice. Basically the
  129. // Generate pass counts all the actions, the first loop below determines
  130. // how many actions have progress updates for each target and writes to
  131. // corrrect variable values for everything except the all targets. The
  132. // second loop actually writes out correct values for the all targets as
  133. // well. This is because the all targets require more information that is
  134. // computed in the first loop.
  135. unsigned long current = 0;
  136. for (auto& pmi : this->ProgressMap) {
  137. pmi.second.WriteProgressVariables(total, current);
  138. }
  139. for (const auto& lg : this->LocalGenerators) {
  140. std::string markFileName =
  141. cmStrCat(lg->GetCurrentBinaryDirectory(), "/CMakeFiles/progress.marks");
  142. cmGeneratedFileStream markFile(markFileName);
  143. markFile << this->CountProgressMarksInAll(*lg) << "\n";
  144. }
  145. // write the main makefile
  146. this->WriteMainMakefile2();
  147. this->WriteMainCMakefile();
  148. if (this->CommandDatabase) {
  149. *this->CommandDatabase << "\n]";
  150. this->CommandDatabase.reset();
  151. }
  152. }
  153. void cmGlobalUnixMakefileGenerator3::AddCXXCompileCommand(
  154. const std::string& sourceFile, const std::string& workingDirectory,
  155. const std::string& compileCommand)
  156. {
  157. if (!this->CommandDatabase) {
  158. std::string commandDatabaseName =
  159. this->GetCMakeInstance()->GetHomeOutputDirectory() +
  160. "/compile_commands.json";
  161. this->CommandDatabase =
  162. cm::make_unique<cmGeneratedFileStream>(commandDatabaseName);
  163. *this->CommandDatabase << "[\n";
  164. } else {
  165. *this->CommandDatabase << ",\n";
  166. }
  167. *this->CommandDatabase << "{\n"
  168. << R"( "directory": ")"
  169. << cmGlobalGenerator::EscapeJSON(workingDirectory)
  170. << "\",\n"
  171. << R"( "command": ")"
  172. << cmGlobalGenerator::EscapeJSON(compileCommand)
  173. << "\",\n"
  174. << R"( "file": ")"
  175. << cmGlobalGenerator::EscapeJSON(sourceFile)
  176. << "\"\n}";
  177. }
  178. void cmGlobalUnixMakefileGenerator3::WriteMainMakefile2()
  179. {
  180. // Open the output file. This should not be copy-if-different
  181. // because the check-build-system step compares the makefile time to
  182. // see if the build system must be regenerated.
  183. std::string makefileName =
  184. cmStrCat(this->GetCMakeInstance()->GetHomeOutputDirectory(),
  185. "/CMakeFiles/Makefile2");
  186. cmGeneratedFileStream makefileStream(makefileName, false,
  187. this->GetMakefileEncoding());
  188. if (!makefileStream) {
  189. return;
  190. }
  191. // get a local generator for some useful methods
  192. auto& lg = cm::static_reference_cast<cmLocalUnixMakefileGenerator3>(
  193. this->LocalGenerators[0]);
  194. // Write the do not edit header.
  195. lg.WriteDisclaimer(makefileStream);
  196. // Write the main entry point target. This must be the VERY first
  197. // target so that make with no arguments will run it.
  198. // Just depend on the all target to drive the build.
  199. std::vector<std::string> depends;
  200. std::vector<std::string> no_commands;
  201. depends.emplace_back("all");
  202. // Write the rule.
  203. lg.WriteMakeRule(makefileStream,
  204. "Default target executed when no arguments are "
  205. "given to make.",
  206. "default_target", depends, no_commands, true);
  207. depends.clear();
  208. // The all and preinstall rules might never have any dependencies
  209. // added to them.
  210. if (!this->EmptyRuleHackDepends.empty()) {
  211. depends.push_back(this->EmptyRuleHackDepends);
  212. }
  213. // Write out the "special" stuff
  214. lg.WriteSpecialTargetsTop(makefileStream);
  215. // Write the directory level rules.
  216. for (auto const& it : this->ComputeDirectoryTargets()) {
  217. this->WriteDirectoryRules2(makefileStream, it.second);
  218. }
  219. // Write the target convenience rules
  220. for (const auto& localGen : this->LocalGenerators) {
  221. this->WriteConvenienceRules2(
  222. makefileStream,
  223. cm::static_reference_cast<cmLocalUnixMakefileGenerator3>(localGen));
  224. }
  225. // Write special bottom targets
  226. lg.WriteSpecialTargetsBottom(makefileStream);
  227. }
  228. void cmGlobalUnixMakefileGenerator3::WriteMainCMakefile()
  229. {
  230. if (this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION")) {
  231. return;
  232. }
  233. // Open the output file. This should not be copy-if-different
  234. // because the check-build-system step compares the makefile time to
  235. // see if the build system must be regenerated.
  236. std::string cmakefileName =
  237. cmStrCat(this->GetCMakeInstance()->GetHomeOutputDirectory(),
  238. "/CMakeFiles/Makefile.cmake");
  239. cmGeneratedFileStream cmakefileStream(cmakefileName);
  240. if (!cmakefileStream) {
  241. return;
  242. }
  243. std::string makefileName =
  244. cmStrCat(this->GetCMakeInstance()->GetHomeOutputDirectory(), "/Makefile");
  245. {
  246. // get a local generator for some useful methods
  247. auto& lg = cm::static_reference_cast<cmLocalUnixMakefileGenerator3>(
  248. this->LocalGenerators[0]);
  249. // Write the do not edit header.
  250. lg.WriteDisclaimer(cmakefileStream);
  251. }
  252. // Save the generator name
  253. cmakefileStream << "# The generator used is:\n"
  254. << "set(CMAKE_DEPENDS_GENERATOR \"" << this->GetName()
  255. << "\")\n\n";
  256. // for each cmMakefile get its list of dependencies
  257. std::vector<std::string> lfiles;
  258. for (const auto& localGen : this->LocalGenerators) {
  259. // Get the list of files contributing to this generation step.
  260. cm::append(lfiles, localGen->GetMakefile()->GetListFiles());
  261. }
  262. cmake* cm = this->GetCMakeInstance();
  263. if (cm->DoWriteGlobVerifyTarget()) {
  264. lfiles.push_back(cm->GetGlobVerifyScript());
  265. lfiles.push_back(cm->GetGlobVerifyStamp());
  266. }
  267. // Sort the list and remove duplicates.
  268. std::sort(lfiles.begin(), lfiles.end(), std::less<std::string>());
  269. #if !defined(__VMS) // The Compaq STL on VMS crashes, so accept duplicates.
  270. auto new_end = std::unique(lfiles.begin(), lfiles.end());
  271. lfiles.erase(new_end, lfiles.end());
  272. #endif
  273. {
  274. // reset lg to the first makefile
  275. const auto& lg = cm::static_reference_cast<cmLocalUnixMakefileGenerator3>(
  276. this->LocalGenerators[0]);
  277. const std::string& currentBinDir = lg.GetCurrentBinaryDirectory();
  278. // Save the list to the cmake file.
  279. cmakefileStream
  280. << "# The top level Makefile was generated from the following files:\n"
  281. << "set(CMAKE_MAKEFILE_DEPENDS\n"
  282. << " \"CMakeCache.txt\"\n";
  283. for (std::string const& f : lfiles) {
  284. cmakefileStream << " \""
  285. << lg.MaybeConvertToRelativePath(currentBinDir, f)
  286. << "\"\n";
  287. }
  288. cmakefileStream << " )\n\n";
  289. // Build the path to the cache check file.
  290. std::string check =
  291. cmStrCat(this->GetCMakeInstance()->GetHomeOutputDirectory(),
  292. "/CMakeFiles/cmake.check_cache");
  293. // Set the corresponding makefile in the cmake file.
  294. cmakefileStream << "# The corresponding makefile is:\n"
  295. << "set(CMAKE_MAKEFILE_OUTPUTS\n"
  296. << " \""
  297. << lg.MaybeConvertToRelativePath(currentBinDir,
  298. makefileName)
  299. << "\"\n"
  300. << " \""
  301. << lg.MaybeConvertToRelativePath(currentBinDir, check)
  302. << "\"\n";
  303. cmakefileStream << " )\n\n";
  304. const std::string& binDir = lg.GetBinaryDirectory();
  305. // CMake must rerun if a byproduct is missing.
  306. cmakefileStream << "# Byproducts of CMake generate step:\n"
  307. << "set(CMAKE_MAKEFILE_PRODUCTS\n";
  308. // add in any byproducts and all the directory information files
  309. std::string tmpStr;
  310. for (const auto& localGen : this->LocalGenerators) {
  311. for (std::string const& outfile :
  312. localGen->GetMakefile()->GetOutputFiles()) {
  313. cmakefileStream << " \""
  314. << lg.MaybeConvertToRelativePath(binDir, outfile)
  315. << "\"\n";
  316. }
  317. tmpStr = cmStrCat(localGen->GetCurrentBinaryDirectory(),
  318. "/CMakeFiles/CMakeDirectoryInformation.cmake");
  319. cmakefileStream << " \""
  320. << localGen->MaybeConvertToRelativePath(binDir, tmpStr)
  321. << "\"\n";
  322. }
  323. cmakefileStream << " )\n\n";
  324. }
  325. this->WriteMainCMakefileLanguageRules(cmakefileStream,
  326. this->LocalGenerators);
  327. }
  328. void cmGlobalUnixMakefileGenerator3::WriteMainCMakefileLanguageRules(
  329. cmGeneratedFileStream& cmakefileStream,
  330. std::vector<std::unique_ptr<cmLocalGenerator>>& lGenerators)
  331. {
  332. // now list all the target info files
  333. cmakefileStream << "# Dependency information for all targets:\n";
  334. cmakefileStream << "set(CMAKE_DEPEND_INFO_FILES\n";
  335. for (const auto& lGenerator : lGenerators) {
  336. const auto& lg =
  337. cm::static_reference_cast<cmLocalUnixMakefileGenerator3>(lGenerator);
  338. // for all of out targets
  339. for (const auto& tgt : lg.GetGeneratorTargets()) {
  340. if (tgt->IsInBuildSystem() &&
  341. tgt->GetType() != cmStateEnums::GLOBAL_TARGET) {
  342. std::string tname = cmStrCat(lg.GetRelativeTargetDirectory(tgt.get()),
  343. "/DependInfo.cmake");
  344. cmSystemTools::ConvertToUnixSlashes(tname);
  345. cmakefileStream << " \"" << tname << "\"\n";
  346. }
  347. }
  348. }
  349. cmakefileStream << " )\n";
  350. }
  351. void cmGlobalUnixMakefileGenerator3::WriteDirectoryRule2(
  352. std::ostream& ruleFileStream, DirectoryTarget const& dt, const char* pass,
  353. bool check_all, bool check_relink, std::vector<std::string> const& commands)
  354. {
  355. auto* lg = static_cast<cmLocalUnixMakefileGenerator3*>(dt.LG);
  356. std::string makeTarget =
  357. cmStrCat(lg->GetCurrentBinaryDirectory(), '/', pass);
  358. // The directory-level rule should depend on the target-level rules
  359. // for all targets in the directory.
  360. std::vector<std::string> depends;
  361. for (DirectoryTarget::Target const& t : dt.Targets) {
  362. // Add this to the list of depends rules in this directory.
  363. if ((!check_all || t.ExcludedFromAllInConfigs.empty()) &&
  364. (!check_relink ||
  365. t.GT->NeedRelinkBeforeInstall(lg->GetConfigName()))) {
  366. // The target may be from a different directory; use its local gen.
  367. auto const* tlg = static_cast<cmLocalUnixMakefileGenerator3 const*>(
  368. t.GT->GetLocalGenerator());
  369. std::string tname =
  370. cmStrCat(tlg->GetRelativeTargetDirectory(t.GT), '/', pass);
  371. depends.push_back(std::move(tname));
  372. }
  373. }
  374. // The directory-level rule should depend on the directory-level
  375. // rules of the subdirectories.
  376. for (DirectoryTarget::Dir const& d : dt.Children) {
  377. if (check_all && d.ExcludeFromAll) {
  378. continue;
  379. }
  380. std::string subdir = cmStrCat(d.Path, '/', pass);
  381. depends.push_back(std::move(subdir));
  382. }
  383. // Work-around for makes that drop rules that have no dependencies
  384. // or commands.
  385. if (depends.empty() && !this->EmptyRuleHackDepends.empty()) {
  386. depends.push_back(this->EmptyRuleHackDepends);
  387. }
  388. // Write the rule.
  389. std::string doc;
  390. if (lg->IsRootMakefile()) {
  391. doc = cmStrCat("The main recursive \"", pass, "\" target.");
  392. } else {
  393. doc = cmStrCat("Recursive \"", pass, "\" directory target.");
  394. }
  395. lg->WriteMakeRule(ruleFileStream, doc.c_str(), makeTarget, depends, commands,
  396. true);
  397. }
  398. void cmGlobalUnixMakefileGenerator3::WriteDirectoryRules2(
  399. std::ostream& ruleFileStream, DirectoryTarget const& dt)
  400. {
  401. auto* lg = static_cast<cmLocalUnixMakefileGenerator3*>(dt.LG);
  402. // Begin the directory-level rules section.
  403. {
  404. std::string dir =
  405. cmSystemTools::ConvertToOutputPath(lg->MaybeConvertToRelativePath(
  406. lg->GetBinaryDirectory(), lg->GetCurrentBinaryDirectory()));
  407. lg->WriteDivider(ruleFileStream);
  408. if (lg->IsRootMakefile()) {
  409. ruleFileStream << "# Directory level rules for the build root directory";
  410. } else {
  411. ruleFileStream << "# Directory level rules for directory " << dir;
  412. }
  413. ruleFileStream << "\n\n";
  414. }
  415. // Write directory-level rules for "all".
  416. this->WriteDirectoryRule2(ruleFileStream, dt, "all", true, false);
  417. // Write directory-level rules for "preinstall".
  418. this->WriteDirectoryRule2(ruleFileStream, dt, "preinstall", true, true);
  419. // Write directory-level rules for "clean".
  420. {
  421. std::vector<std::string> cmds;
  422. lg->AppendDirectoryCleanCommand(cmds);
  423. this->WriteDirectoryRule2(ruleFileStream, dt, "clean", false, false, cmds);
  424. }
  425. }
  426. namespace {
  427. std::string ConvertToMakefilePathForUnix(std::string const& path)
  428. {
  429. std::string result;
  430. result.reserve(path.size());
  431. for (char c : path) {
  432. switch (c) {
  433. case '=':
  434. // We provide 'EQUALS = =' to encode '=' in a non-assignment case.
  435. result.append("$(EQUALS)");
  436. break;
  437. case '$':
  438. result.append("$$");
  439. break;
  440. case '\\':
  441. case ' ':
  442. case '#':
  443. result.push_back('\\');
  444. CM_FALLTHROUGH;
  445. default:
  446. result.push_back(c);
  447. break;
  448. }
  449. }
  450. return result;
  451. }
  452. #if defined(_WIN32) && !defined(__CYGWIN__)
  453. std::string ConvertToMakefilePathForWindows(std::string const& path)
  454. {
  455. bool const quote = path.find_first_of(" #") != std::string::npos;
  456. std::string result;
  457. result.reserve(path.size() + (quote ? 2 : 0));
  458. if (quote) {
  459. result.push_back('"');
  460. }
  461. for (char c : path) {
  462. switch (c) {
  463. case '=':
  464. // We provide 'EQUALS = =' to encode '=' in a non-assignment case.
  465. result.append("$(EQUALS)");
  466. break;
  467. case '$':
  468. result.append("$$");
  469. break;
  470. case '/':
  471. result.push_back('\\');
  472. break;
  473. default:
  474. result.push_back(c);
  475. break;
  476. }
  477. }
  478. if (quote) {
  479. result.push_back('"');
  480. }
  481. return result;
  482. }
  483. #endif
  484. }
  485. std::string cmGlobalUnixMakefileGenerator3::ConvertToMakefilePath(
  486. std::string const& path) const
  487. {
  488. #if defined(_WIN32) && !defined(__CYGWIN__)
  489. if (!this->ForceUnixPaths) {
  490. return ConvertToMakefilePathForWindows(path);
  491. }
  492. #endif
  493. return ConvertToMakefilePathForUnix(path);
  494. }
  495. std::vector<cmGlobalGenerator::GeneratedMakeCommand>
  496. cmGlobalUnixMakefileGenerator3::GenerateBuildCommand(
  497. const std::string& makeProgram, const std::string& /*projectName*/,
  498. const std::string& /*projectDir*/,
  499. std::vector<std::string> const& targetNames, const std::string& /*config*/,
  500. bool fast, int jobs, bool verbose,
  501. std::vector<std::string> const& makeOptions)
  502. {
  503. std::unique_ptr<cmMakefile> mfu;
  504. cmMakefile* mf;
  505. if (!this->Makefiles.empty()) {
  506. mf = this->Makefiles[0].get();
  507. } else {
  508. cmStateSnapshot snapshot = this->CMakeInstance->GetCurrentSnapshot();
  509. snapshot.GetDirectory().SetCurrentSource(
  510. this->CMakeInstance->GetHomeDirectory());
  511. snapshot.GetDirectory().SetCurrentBinary(
  512. this->CMakeInstance->GetHomeOutputDirectory());
  513. snapshot.SetDefaultDefinitions();
  514. mfu = cm::make_unique<cmMakefile>(this, snapshot);
  515. mf = mfu.get();
  516. }
  517. GeneratedMakeCommand makeCommand;
  518. // Make it possible to set verbosity also from command line
  519. if (verbose) {
  520. makeCommand.Add(cmSystemTools::GetCMakeCommand());
  521. makeCommand.Add("-E");
  522. makeCommand.Add("env");
  523. makeCommand.Add("VERBOSE=1");
  524. }
  525. makeCommand.Add(this->SelectMakeProgram(makeProgram));
  526. // Explicitly tell the make tool to use the Makefile written by
  527. // cmLocalUnixMakefileGenerator3::WriteLocalMakefile
  528. makeCommand.Add("-f");
  529. makeCommand.Add("Makefile");
  530. if (jobs != cmake::NO_BUILD_PARALLEL_LEVEL) {
  531. if (jobs == cmake::DEFAULT_BUILD_PARALLEL_LEVEL) {
  532. makeCommand.Add("-j");
  533. } else {
  534. makeCommand.Add("-j" + std::to_string(jobs));
  535. }
  536. }
  537. makeCommand.Add(makeOptions.begin(), makeOptions.end());
  538. for (auto tname : targetNames) {
  539. if (!tname.empty()) {
  540. if (fast) {
  541. tname += "/fast";
  542. }
  543. tname =
  544. mf->GetStateSnapshot().GetDirectory().ConvertToRelPathIfNotContained(
  545. mf->GetState()->GetBinaryDirectory(), tname);
  546. cmSystemTools::ConvertToOutputSlashes(tname);
  547. makeCommand.Add(std::move(tname));
  548. }
  549. }
  550. return { std::move(makeCommand) };
  551. }
  552. void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules(
  553. std::ostream& ruleFileStream, std::set<std::string>& emitted)
  554. {
  555. std::vector<std::string> depends;
  556. std::vector<std::string> commands;
  557. bool regenerate = !this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION");
  558. if (regenerate) {
  559. depends.emplace_back("cmake_check_build_system");
  560. }
  561. // write the target convenience rules
  562. for (const auto& localGen : this->LocalGenerators) {
  563. auto& lg =
  564. cm::static_reference_cast<cmLocalUnixMakefileGenerator3>(localGen);
  565. // for each target Generate the rule files for each target.
  566. for (const auto& gtarget : lg.GetGeneratorTargets()) {
  567. // Don't emit the same rule twice (e.g. two targets with the same
  568. // simple name)
  569. std::string name = gtarget->GetName();
  570. if (!name.empty() && emitted.insert(name).second &&
  571. // Handle user targets here. Global targets are handled in
  572. // the local generator on a per-directory basis.
  573. (gtarget->IsInBuildSystem() &&
  574. gtarget->GetType() != cmStateEnums::GLOBAL_TARGET)) {
  575. // Add a rule to build the target by name.
  576. lg.WriteDivider(ruleFileStream);
  577. ruleFileStream << "# Target rules for targets named " << name
  578. << "\n\n";
  579. // Write the rule.
  580. commands.clear();
  581. std::string tmp = "CMakeFiles/Makefile2";
  582. commands.push_back(lg.GetRecursiveMakeCall(tmp, name));
  583. depends.clear();
  584. if (regenerate) {
  585. depends.emplace_back("cmake_check_build_system");
  586. }
  587. lg.WriteMakeRule(ruleFileStream, "Build rule for target.", name,
  588. depends, commands, true);
  589. // Add a fast rule to build the target
  590. std::string localName = lg.GetRelativeTargetDirectory(gtarget.get());
  591. std::string makefileName;
  592. makefileName = cmStrCat(localName, "/build.make");
  593. depends.clear();
  594. commands.clear();
  595. std::string makeTargetName = cmStrCat(localName, "/build");
  596. localName = cmStrCat(name, "/fast");
  597. commands.push_back(
  598. lg.GetRecursiveMakeCall(makefileName, makeTargetName));
  599. lg.WriteMakeRule(ruleFileStream, "fast build rule for target.",
  600. localName, depends, commands, true);
  601. // Add a local name for the rule to relink the target before
  602. // installation.
  603. if (gtarget->NeedRelinkBeforeInstall(lg.GetConfigName())) {
  604. makeTargetName = cmStrCat(
  605. lg.GetRelativeTargetDirectory(gtarget.get()), "/preinstall");
  606. localName = cmStrCat(name, "/preinstall");
  607. depends.clear();
  608. commands.clear();
  609. commands.push_back(
  610. lg.GetRecursiveMakeCall(makefileName, makeTargetName));
  611. lg.WriteMakeRule(ruleFileStream,
  612. "Manual pre-install relink rule for target.",
  613. localName, depends, commands, true);
  614. }
  615. }
  616. }
  617. }
  618. }
  619. void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules2(
  620. std::ostream& ruleFileStream, cmLocalUnixMakefileGenerator3& lg)
  621. {
  622. std::vector<std::string> depends;
  623. std::vector<std::string> commands;
  624. std::string localName;
  625. std::string makeTargetName;
  626. bool regenerate = !this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION");
  627. if (regenerate) {
  628. depends.emplace_back("cmake_check_build_system");
  629. }
  630. // for each target Generate the rule files for each target.
  631. for (const auto& gtarget : lg.GetGeneratorTargets()) {
  632. std::string name = gtarget->GetName();
  633. if (!name.empty() &&
  634. (gtarget->IsInBuildSystem() &&
  635. gtarget->GetType() != cmStateEnums::GLOBAL_TARGET)) {
  636. std::string makefileName;
  637. // Add a rule to build the target by name.
  638. localName = lg.GetRelativeTargetDirectory(gtarget.get());
  639. makefileName = cmStrCat(localName, "/build.make");
  640. lg.WriteDivider(ruleFileStream);
  641. ruleFileStream << "# Target rules for target " << localName << "\n\n";
  642. commands.clear();
  643. makeTargetName = cmStrCat(localName, "/depend");
  644. commands.push_back(
  645. lg.GetRecursiveMakeCall(makefileName, makeTargetName));
  646. makeTargetName = cmStrCat(localName, "/build");
  647. commands.push_back(
  648. lg.GetRecursiveMakeCall(makefileName, makeTargetName));
  649. // Write the rule.
  650. localName += "/all";
  651. depends.clear();
  652. cmLocalUnixMakefileGenerator3::EchoProgress progress;
  653. progress.Dir = cmStrCat(lg.GetBinaryDirectory(), "/CMakeFiles");
  654. {
  655. std::ostringstream progressArg;
  656. const char* sep = "";
  657. for (unsigned long progFile : this->ProgressMap[gtarget.get()].Marks) {
  658. progressArg << sep << progFile;
  659. sep = ",";
  660. }
  661. progress.Arg = progressArg.str();
  662. }
  663. bool targetMessages = true;
  664. if (cmProp tgtMsg =
  665. this->GetCMakeInstance()->GetState()->GetGlobalProperty(
  666. "TARGET_MESSAGES")) {
  667. targetMessages = cmIsOn(*tgtMsg);
  668. }
  669. if (targetMessages) {
  670. lg.AppendEcho(commands, "Built target " + name,
  671. cmLocalUnixMakefileGenerator3::EchoNormal, &progress);
  672. }
  673. this->AppendGlobalTargetDepends(depends, gtarget.get());
  674. lg.WriteMakeRule(ruleFileStream, "All Build rule for target.", localName,
  675. depends, commands, true);
  676. // Write the rule.
  677. commands.clear();
  678. {
  679. // TODO: Convert the total progress count to a make variable.
  680. std::ostringstream progCmd;
  681. progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start ";
  682. // # in target
  683. progCmd << lg.ConvertToOutputFormat(progress.Dir,
  684. cmOutputConverter::SHELL);
  685. //
  686. std::set<cmGeneratorTarget const*> emitted;
  687. progCmd << " "
  688. << this->CountProgressMarksInTarget(gtarget.get(), emitted);
  689. commands.push_back(progCmd.str());
  690. }
  691. std::string tmp = "CMakeFiles/Makefile2";
  692. commands.push_back(lg.GetRecursiveMakeCall(tmp, localName));
  693. {
  694. std::ostringstream progCmd;
  695. progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; // # 0
  696. progCmd << lg.ConvertToOutputFormat(progress.Dir,
  697. cmOutputConverter::SHELL);
  698. progCmd << " 0";
  699. commands.push_back(progCmd.str());
  700. }
  701. depends.clear();
  702. if (regenerate) {
  703. depends.emplace_back("cmake_check_build_system");
  704. }
  705. localName =
  706. cmStrCat(lg.GetRelativeTargetDirectory(gtarget.get()), "/rule");
  707. lg.WriteMakeRule(ruleFileStream,
  708. "Build rule for subdir invocation for target.",
  709. localName, depends, commands, true);
  710. // Add a target with the canonical name (no prefix, suffix or path).
  711. commands.clear();
  712. depends.clear();
  713. depends.push_back(localName);
  714. lg.WriteMakeRule(ruleFileStream, "Convenience name for target.", name,
  715. depends, commands, true);
  716. // Add rules to prepare the target for installation.
  717. if (gtarget->NeedRelinkBeforeInstall(lg.GetConfigName())) {
  718. localName = cmStrCat(lg.GetRelativeTargetDirectory(gtarget.get()),
  719. "/preinstall");
  720. depends.clear();
  721. commands.clear();
  722. commands.push_back(lg.GetRecursiveMakeCall(makefileName, localName));
  723. lg.WriteMakeRule(ruleFileStream, "Pre-install relink rule for target.",
  724. localName, depends, commands, true);
  725. }
  726. // add the clean rule
  727. localName = lg.GetRelativeTargetDirectory(gtarget.get());
  728. makeTargetName = cmStrCat(localName, "/clean");
  729. depends.clear();
  730. commands.clear();
  731. commands.push_back(
  732. lg.GetRecursiveMakeCall(makefileName, makeTargetName));
  733. lg.WriteMakeRule(ruleFileStream, "clean rule for target.",
  734. makeTargetName, depends, commands, true);
  735. commands.clear();
  736. }
  737. }
  738. }
  739. // Build a map that contains the set of targets used by each local
  740. // generator directory level.
  741. void cmGlobalUnixMakefileGenerator3::InitializeProgressMarks()
  742. {
  743. this->DirectoryTargetsMap.clear();
  744. // Loop over all targets in all local generators.
  745. for (const auto& lg : this->LocalGenerators) {
  746. for (const auto& gt : lg->GetGeneratorTargets()) {
  747. cmLocalGenerator* tlg = gt->GetLocalGenerator();
  748. if (!gt->IsInBuildSystem() || IsExcluded(lg.get(), gt.get())) {
  749. continue;
  750. }
  751. cmStateSnapshot csnp = lg->GetStateSnapshot();
  752. cmStateSnapshot tsnp = tlg->GetStateSnapshot();
  753. // Consider the directory containing the target and all its
  754. // parents until something excludes the target.
  755. for (; csnp.IsValid() && !this->IsExcluded(csnp, tsnp);
  756. csnp = csnp.GetBuildsystemDirectoryParent()) {
  757. // This local generator includes the target.
  758. std::set<cmGeneratorTarget const*>& targetSet =
  759. this->DirectoryTargetsMap[csnp];
  760. targetSet.insert(gt.get());
  761. // Add dependencies of the included target. An excluded
  762. // target may still be included if it is a dependency of a
  763. // non-excluded target.
  764. for (cmTargetDepend const& tgtdep :
  765. this->GetTargetDirectDepends(gt.get())) {
  766. targetSet.insert(tgtdep);
  767. }
  768. }
  769. }
  770. }
  771. }
  772. size_t cmGlobalUnixMakefileGenerator3::CountProgressMarksInTarget(
  773. cmGeneratorTarget const* target, std::set<cmGeneratorTarget const*>& emitted)
  774. {
  775. size_t count = 0;
  776. if (emitted.insert(target).second) {
  777. count = this->ProgressMap[target].Marks.size();
  778. for (cmTargetDepend const& depend : this->GetTargetDirectDepends(target)) {
  779. if (!depend->IsInBuildSystem()) {
  780. continue;
  781. }
  782. count += this->CountProgressMarksInTarget(depend, emitted);
  783. }
  784. }
  785. return count;
  786. }
  787. size_t cmGlobalUnixMakefileGenerator3::CountProgressMarksInAll(
  788. const cmLocalGenerator& lg)
  789. {
  790. size_t count = 0;
  791. std::set<cmGeneratorTarget const*> emitted;
  792. for (cmGeneratorTarget const* target :
  793. this->DirectoryTargetsMap[lg.GetStateSnapshot()]) {
  794. count += this->CountProgressMarksInTarget(target, emitted);
  795. }
  796. return count;
  797. }
  798. void cmGlobalUnixMakefileGenerator3::RecordTargetProgress(
  799. cmMakefileTargetGenerator* tg)
  800. {
  801. TargetProgress& tp = this->ProgressMap[tg->GetGeneratorTarget()];
  802. tp.NumberOfActions = tg->GetNumberOfProgressActions();
  803. tp.VariableFile = tg->GetProgressFileNameFull();
  804. }
  805. void cmGlobalUnixMakefileGenerator3::TargetProgress::WriteProgressVariables(
  806. unsigned long total, unsigned long& current)
  807. {
  808. cmGeneratedFileStream fout(this->VariableFile);
  809. for (unsigned long i = 1; i <= this->NumberOfActions; ++i) {
  810. fout << "CMAKE_PROGRESS_" << i << " = ";
  811. if (total <= 100) {
  812. unsigned long num = i + current;
  813. fout << num;
  814. this->Marks.push_back(num);
  815. } else if (((i + current) * 100) / total >
  816. ((i - 1 + current) * 100) / total) {
  817. unsigned long num = ((i + current) * 100) / total;
  818. fout << num;
  819. this->Marks.push_back(num);
  820. }
  821. fout << "\n";
  822. }
  823. fout << "\n";
  824. current += this->NumberOfActions;
  825. }
  826. void cmGlobalUnixMakefileGenerator3::AppendGlobalTargetDepends(
  827. std::vector<std::string>& depends, cmGeneratorTarget* target)
  828. {
  829. for (cmTargetDepend const& i : this->GetTargetDirectDepends(target)) {
  830. // Create the target-level dependency.
  831. cmGeneratorTarget const* dep = i;
  832. if (!dep->IsInBuildSystem()) {
  833. continue;
  834. }
  835. cmLocalUnixMakefileGenerator3* lg3 =
  836. static_cast<cmLocalUnixMakefileGenerator3*>(dep->GetLocalGenerator());
  837. std::string tgtName = cmStrCat(
  838. lg3->GetRelativeTargetDirectory(const_cast<cmGeneratorTarget*>(dep)),
  839. "/all");
  840. depends.push_back(tgtName);
  841. }
  842. }
  843. void cmGlobalUnixMakefileGenerator3::WriteHelpRule(
  844. std::ostream& ruleFileStream, cmLocalUnixMakefileGenerator3* lg)
  845. {
  846. // add the help target
  847. std::string path;
  848. std::vector<std::string> no_depends;
  849. std::vector<std::string> commands;
  850. lg->AppendEcho(commands,
  851. "The following are some of the valid targets "
  852. "for this Makefile:");
  853. lg->AppendEcho(commands, "... all (the default if no target is provided)");
  854. lg->AppendEcho(commands, "... clean");
  855. if (!this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION")) {
  856. lg->AppendEcho(commands, "... depend");
  857. }
  858. // Keep track of targets already listed.
  859. std::set<std::string> emittedTargets;
  860. std::set<std::string> utility_targets;
  861. std::set<std::string> globals_targets;
  862. std::set<std::string> project_targets;
  863. // for each local generator
  864. for (const auto& localGen : this->LocalGenerators) {
  865. const auto& lg2 =
  866. cm::static_reference_cast<cmLocalUnixMakefileGenerator3>(localGen);
  867. // for the passed in makefile or if this is the top Makefile wripte out
  868. // the targets
  869. if (&lg2 == lg || lg->IsRootMakefile()) {
  870. // for each target Generate the rule files for each target.
  871. for (const auto& target : lg2.GetGeneratorTargets()) {
  872. cmStateEnums::TargetType type = target->GetType();
  873. if ((type == cmStateEnums::EXECUTABLE) ||
  874. (type == cmStateEnums::STATIC_LIBRARY) ||
  875. (type == cmStateEnums::SHARED_LIBRARY) ||
  876. (type == cmStateEnums::MODULE_LIBRARY) ||
  877. (type == cmStateEnums::OBJECT_LIBRARY) ||
  878. (type == cmStateEnums::INTERFACE_LIBRARY &&
  879. target->IsInBuildSystem())) {
  880. project_targets.insert(target->GetName());
  881. } else if (type == cmStateEnums::GLOBAL_TARGET) {
  882. globals_targets.insert(target->GetName());
  883. } else if (type == cmStateEnums::UTILITY) {
  884. utility_targets.insert(target->GetName());
  885. }
  886. }
  887. }
  888. }
  889. for (std::string const& name : globals_targets) {
  890. path = cmStrCat("... ", name);
  891. lg->AppendEcho(commands, path);
  892. }
  893. for (std::string const& name : utility_targets) {
  894. path = cmStrCat("... ", name);
  895. lg->AppendEcho(commands, path);
  896. }
  897. for (std::string const& name : project_targets) {
  898. path = cmStrCat("... ", name);
  899. lg->AppendEcho(commands, path);
  900. }
  901. for (std::string const& o : lg->GetLocalHelp()) {
  902. path = cmStrCat("... ", o);
  903. lg->AppendEcho(commands, path);
  904. }
  905. lg->WriteMakeRule(ruleFileStream, "Help Target", "help", no_depends,
  906. commands, true);
  907. ruleFileStream << "\n\n";
  908. }