cmGlobalUnixMakefileGenerator3.cxx 34 KB

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