cmGlobalUnixMakefileGenerator3.cxx 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  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. // Explicitly tell the make tool to use the Makefile written by
  526. // cmLocalUnixMakefileGenerator3::WriteLocalMakefile
  527. makeCommand.Add("-f");
  528. makeCommand.Add("Makefile");
  529. if (jobs != cmake::NO_BUILD_PARALLEL_LEVEL) {
  530. if (jobs == cmake::DEFAULT_BUILD_PARALLEL_LEVEL) {
  531. makeCommand.Add("-j");
  532. } else {
  533. makeCommand.Add("-j" + std::to_string(jobs));
  534. }
  535. }
  536. makeCommand.Add(makeOptions.begin(), makeOptions.end());
  537. for (auto tname : targetNames) {
  538. if (!tname.empty()) {
  539. if (fast) {
  540. tname += "/fast";
  541. }
  542. tname =
  543. mf->GetStateSnapshot().GetDirectory().ConvertToRelPathIfNotContained(
  544. mf->GetState()->GetBinaryDirectory(), tname);
  545. cmSystemTools::ConvertToOutputSlashes(tname);
  546. makeCommand.Add(std::move(tname));
  547. }
  548. }
  549. return { std::move(makeCommand) };
  550. }
  551. void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules(
  552. std::ostream& ruleFileStream, std::set<std::string>& emitted)
  553. {
  554. std::vector<std::string> depends;
  555. std::vector<std::string> commands;
  556. bool regenerate = !this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION");
  557. if (regenerate) {
  558. depends.emplace_back("cmake_check_build_system");
  559. }
  560. // write the target convenience rules
  561. for (const auto& localGen : this->LocalGenerators) {
  562. auto& lg =
  563. cm::static_reference_cast<cmLocalUnixMakefileGenerator3>(localGen);
  564. // for each target Generate the rule files for each target.
  565. for (const auto& gtarget : lg.GetGeneratorTargets()) {
  566. // Don't emit the same rule twice (e.g. two targets with the same
  567. // simple name)
  568. std::string name = gtarget->GetName();
  569. if (!name.empty() && emitted.insert(name).second &&
  570. // Handle user targets here. Global targets are handled in
  571. // the local generator on a per-directory basis.
  572. (gtarget->IsInBuildSystem() &&
  573. gtarget->GetType() != cmStateEnums::GLOBAL_TARGET)) {
  574. // Add a rule to build the target by name.
  575. lg.WriteDivider(ruleFileStream);
  576. ruleFileStream << "# Target rules for targets named " << name
  577. << "\n\n";
  578. // Write the rule.
  579. commands.clear();
  580. std::string tmp = "CMakeFiles/Makefile2";
  581. commands.push_back(lg.GetRecursiveMakeCall(tmp, name));
  582. depends.clear();
  583. if (regenerate) {
  584. depends.emplace_back("cmake_check_build_system");
  585. }
  586. lg.WriteMakeRule(ruleFileStream, "Build rule for target.", name,
  587. depends, commands, true);
  588. // Add a fast rule to build the target
  589. std::string localName = lg.GetRelativeTargetDirectory(gtarget.get());
  590. std::string makefileName;
  591. makefileName = cmStrCat(localName, "/build.make");
  592. depends.clear();
  593. commands.clear();
  594. std::string makeTargetName = cmStrCat(localName, "/build");
  595. localName = cmStrCat(name, "/fast");
  596. commands.push_back(
  597. lg.GetRecursiveMakeCall(makefileName, makeTargetName));
  598. lg.WriteMakeRule(ruleFileStream, "fast build rule for target.",
  599. localName, depends, commands, true);
  600. // Add a local name for the rule to relink the target before
  601. // installation.
  602. if (gtarget->NeedRelinkBeforeInstall(lg.GetConfigName())) {
  603. makeTargetName = cmStrCat(
  604. lg.GetRelativeTargetDirectory(gtarget.get()), "/preinstall");
  605. localName = cmStrCat(name, "/preinstall");
  606. depends.clear();
  607. commands.clear();
  608. commands.push_back(
  609. lg.GetRecursiveMakeCall(makefileName, makeTargetName));
  610. lg.WriteMakeRule(ruleFileStream,
  611. "Manual pre-install relink rule for target.",
  612. localName, depends, commands, true);
  613. }
  614. }
  615. }
  616. }
  617. }
  618. void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules2(
  619. std::ostream& ruleFileStream, cmLocalUnixMakefileGenerator3& lg)
  620. {
  621. std::vector<std::string> depends;
  622. std::vector<std::string> commands;
  623. std::string localName;
  624. std::string makeTargetName;
  625. bool regenerate = !this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION");
  626. if (regenerate) {
  627. depends.emplace_back("cmake_check_build_system");
  628. }
  629. // for each target Generate the rule files for each target.
  630. for (const auto& gtarget : lg.GetGeneratorTargets()) {
  631. std::string name = gtarget->GetName();
  632. if (!name.empty() &&
  633. (gtarget->IsInBuildSystem() &&
  634. gtarget->GetType() != cmStateEnums::GLOBAL_TARGET)) {
  635. std::string makefileName;
  636. // Add a rule to build the target by name.
  637. localName = lg.GetRelativeTargetDirectory(gtarget.get());
  638. makefileName = cmStrCat(localName, "/build.make");
  639. lg.WriteDivider(ruleFileStream);
  640. ruleFileStream << "# Target rules for target " << localName << "\n\n";
  641. commands.clear();
  642. makeTargetName = cmStrCat(localName, "/depend");
  643. commands.push_back(
  644. lg.GetRecursiveMakeCall(makefileName, makeTargetName));
  645. makeTargetName = cmStrCat(localName, "/build");
  646. commands.push_back(
  647. lg.GetRecursiveMakeCall(makefileName, makeTargetName));
  648. // Write the rule.
  649. localName += "/all";
  650. depends.clear();
  651. cmLocalUnixMakefileGenerator3::EchoProgress progress;
  652. progress.Dir = cmStrCat(lg.GetBinaryDirectory(), "/CMakeFiles");
  653. {
  654. std::ostringstream progressArg;
  655. const char* sep = "";
  656. for (unsigned long progFile : this->ProgressMap[gtarget.get()].Marks) {
  657. progressArg << sep << progFile;
  658. sep = ",";
  659. }
  660. progress.Arg = progressArg.str();
  661. }
  662. bool targetMessages = true;
  663. if (cmProp tgtMsg =
  664. this->GetCMakeInstance()->GetState()->GetGlobalProperty(
  665. "TARGET_MESSAGES")) {
  666. targetMessages = cmIsOn(*tgtMsg);
  667. }
  668. if (targetMessages) {
  669. lg.AppendEcho(commands, "Built target " + name,
  670. cmLocalUnixMakefileGenerator3::EchoNormal, &progress);
  671. }
  672. this->AppendGlobalTargetDepends(depends, gtarget.get());
  673. lg.WriteMakeRule(ruleFileStream, "All Build rule for target.", localName,
  674. depends, commands, true);
  675. // Write the rule.
  676. commands.clear();
  677. {
  678. // TODO: Convert the total progress count to a make variable.
  679. std::ostringstream progCmd;
  680. progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start ";
  681. // # in target
  682. progCmd << lg.ConvertToOutputFormat(progress.Dir,
  683. cmOutputConverter::SHELL);
  684. //
  685. std::set<cmGeneratorTarget const*> emitted;
  686. progCmd << " "
  687. << this->CountProgressMarksInTarget(gtarget.get(), emitted);
  688. commands.push_back(progCmd.str());
  689. }
  690. std::string tmp = "CMakeFiles/Makefile2";
  691. commands.push_back(lg.GetRecursiveMakeCall(tmp, localName));
  692. {
  693. std::ostringstream progCmd;
  694. progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; // # 0
  695. progCmd << lg.ConvertToOutputFormat(progress.Dir,
  696. cmOutputConverter::SHELL);
  697. progCmd << " 0";
  698. commands.push_back(progCmd.str());
  699. }
  700. depends.clear();
  701. if (regenerate) {
  702. depends.emplace_back("cmake_check_build_system");
  703. }
  704. localName =
  705. cmStrCat(lg.GetRelativeTargetDirectory(gtarget.get()), "/rule");
  706. lg.WriteMakeRule(ruleFileStream,
  707. "Build rule for subdir invocation for target.",
  708. localName, depends, commands, true);
  709. // Add a target with the canonical name (no prefix, suffix or path).
  710. commands.clear();
  711. depends.clear();
  712. depends.push_back(localName);
  713. lg.WriteMakeRule(ruleFileStream, "Convenience name for target.", name,
  714. depends, commands, true);
  715. // Add rules to prepare the target for installation.
  716. if (gtarget->NeedRelinkBeforeInstall(lg.GetConfigName())) {
  717. localName = cmStrCat(lg.GetRelativeTargetDirectory(gtarget.get()),
  718. "/preinstall");
  719. depends.clear();
  720. commands.clear();
  721. commands.push_back(lg.GetRecursiveMakeCall(makefileName, localName));
  722. lg.WriteMakeRule(ruleFileStream, "Pre-install relink rule for target.",
  723. localName, depends, commands, true);
  724. }
  725. // add the clean rule
  726. localName = lg.GetRelativeTargetDirectory(gtarget.get());
  727. makeTargetName = cmStrCat(localName, "/clean");
  728. depends.clear();
  729. commands.clear();
  730. commands.push_back(
  731. lg.GetRecursiveMakeCall(makefileName, makeTargetName));
  732. lg.WriteMakeRule(ruleFileStream, "clean rule for target.",
  733. makeTargetName, depends, commands, true);
  734. commands.clear();
  735. }
  736. }
  737. }
  738. // Build a map that contains the set of targets used by each local
  739. // generator directory level.
  740. void cmGlobalUnixMakefileGenerator3::InitializeProgressMarks()
  741. {
  742. this->DirectoryTargetsMap.clear();
  743. // Loop over all targets in all local generators.
  744. for (const auto& lg : this->LocalGenerators) {
  745. for (const auto& gt : lg->GetGeneratorTargets()) {
  746. cmLocalGenerator* tlg = gt->GetLocalGenerator();
  747. if (!gt->IsInBuildSystem() || IsExcluded(lg.get(), gt.get())) {
  748. continue;
  749. }
  750. cmStateSnapshot csnp = lg->GetStateSnapshot();
  751. cmStateSnapshot tsnp = tlg->GetStateSnapshot();
  752. // Consider the directory containing the target and all its
  753. // parents until something excludes the target.
  754. for (; csnp.IsValid() && !this->IsExcluded(csnp, tsnp);
  755. csnp = csnp.GetBuildsystemDirectoryParent()) {
  756. // This local generator includes the target.
  757. std::set<cmGeneratorTarget const*>& targetSet =
  758. this->DirectoryTargetsMap[csnp];
  759. targetSet.insert(gt.get());
  760. // Add dependencies of the included target. An excluded
  761. // target may still be included if it is a dependency of a
  762. // non-excluded target.
  763. for (cmTargetDepend const& tgtdep :
  764. this->GetTargetDirectDepends(gt.get())) {
  765. targetSet.insert(tgtdep);
  766. }
  767. }
  768. }
  769. }
  770. }
  771. size_t cmGlobalUnixMakefileGenerator3::CountProgressMarksInTarget(
  772. cmGeneratorTarget const* target, std::set<cmGeneratorTarget const*>& emitted)
  773. {
  774. size_t count = 0;
  775. if (emitted.insert(target).second) {
  776. count = this->ProgressMap[target].Marks.size();
  777. for (cmTargetDepend const& depend : this->GetTargetDirectDepends(target)) {
  778. if (!depend->IsInBuildSystem()) {
  779. continue;
  780. }
  781. count += this->CountProgressMarksInTarget(depend, emitted);
  782. }
  783. }
  784. return count;
  785. }
  786. size_t cmGlobalUnixMakefileGenerator3::CountProgressMarksInAll(
  787. const cmLocalGenerator& lg)
  788. {
  789. size_t count = 0;
  790. std::set<cmGeneratorTarget const*> emitted;
  791. for (cmGeneratorTarget const* target :
  792. this->DirectoryTargetsMap[lg.GetStateSnapshot()]) {
  793. count += this->CountProgressMarksInTarget(target, emitted);
  794. }
  795. return count;
  796. }
  797. void cmGlobalUnixMakefileGenerator3::RecordTargetProgress(
  798. cmMakefileTargetGenerator* tg)
  799. {
  800. TargetProgress& tp = this->ProgressMap[tg->GetGeneratorTarget()];
  801. tp.NumberOfActions = tg->GetNumberOfProgressActions();
  802. tp.VariableFile = tg->GetProgressFileNameFull();
  803. }
  804. void cmGlobalUnixMakefileGenerator3::TargetProgress::WriteProgressVariables(
  805. unsigned long total, unsigned long& current)
  806. {
  807. cmGeneratedFileStream fout(this->VariableFile);
  808. for (unsigned long i = 1; i <= this->NumberOfActions; ++i) {
  809. fout << "CMAKE_PROGRESS_" << i << " = ";
  810. if (total <= 100) {
  811. unsigned long num = i + current;
  812. fout << num;
  813. this->Marks.push_back(num);
  814. } else if (((i + current) * 100) / total >
  815. ((i - 1 + current) * 100) / total) {
  816. unsigned long num = ((i + current) * 100) / total;
  817. fout << num;
  818. this->Marks.push_back(num);
  819. }
  820. fout << "\n";
  821. }
  822. fout << "\n";
  823. current += this->NumberOfActions;
  824. }
  825. void cmGlobalUnixMakefileGenerator3::AppendGlobalTargetDepends(
  826. std::vector<std::string>& depends, cmGeneratorTarget* target)
  827. {
  828. for (cmTargetDepend const& i : this->GetTargetDirectDepends(target)) {
  829. // Create the target-level dependency.
  830. cmGeneratorTarget const* dep = i;
  831. if (!dep->IsInBuildSystem()) {
  832. continue;
  833. }
  834. cmLocalUnixMakefileGenerator3* lg3 =
  835. static_cast<cmLocalUnixMakefileGenerator3*>(dep->GetLocalGenerator());
  836. std::string tgtName = cmStrCat(
  837. lg3->GetRelativeTargetDirectory(const_cast<cmGeneratorTarget*>(dep)),
  838. "/all");
  839. depends.push_back(tgtName);
  840. }
  841. }
  842. void cmGlobalUnixMakefileGenerator3::WriteHelpRule(
  843. std::ostream& ruleFileStream, cmLocalUnixMakefileGenerator3* lg)
  844. {
  845. // add the help target
  846. std::string path;
  847. std::vector<std::string> no_depends;
  848. std::vector<std::string> commands;
  849. lg->AppendEcho(commands,
  850. "The following are some of the valid targets "
  851. "for this Makefile:");
  852. lg->AppendEcho(commands, "... all (the default if no target is provided)");
  853. lg->AppendEcho(commands, "... clean");
  854. if (!this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION")) {
  855. lg->AppendEcho(commands, "... depend");
  856. }
  857. // Keep track of targets already listed.
  858. std::set<std::string> emittedTargets;
  859. std::set<std::string> utility_targets;
  860. std::set<std::string> globals_targets;
  861. std::set<std::string> project_targets;
  862. // for each local generator
  863. for (const auto& localGen : this->LocalGenerators) {
  864. const auto& lg2 =
  865. cm::static_reference_cast<cmLocalUnixMakefileGenerator3>(localGen);
  866. // for the passed in makefile or if this is the top Makefile wripte out
  867. // the targets
  868. if (&lg2 == lg || lg->IsRootMakefile()) {
  869. // for each target Generate the rule files for each target.
  870. for (const auto& target : lg2.GetGeneratorTargets()) {
  871. cmStateEnums::TargetType type = target->GetType();
  872. if ((type == cmStateEnums::EXECUTABLE) ||
  873. (type == cmStateEnums::STATIC_LIBRARY) ||
  874. (type == cmStateEnums::SHARED_LIBRARY) ||
  875. (type == cmStateEnums::MODULE_LIBRARY) ||
  876. (type == cmStateEnums::OBJECT_LIBRARY) ||
  877. (type == cmStateEnums::INTERFACE_LIBRARY &&
  878. target->IsInBuildSystem())) {
  879. project_targets.insert(target->GetName());
  880. } else if (type == cmStateEnums::GLOBAL_TARGET) {
  881. globals_targets.insert(target->GetName());
  882. } else if (type == cmStateEnums::UTILITY) {
  883. utility_targets.insert(target->GetName());
  884. }
  885. }
  886. }
  887. }
  888. for (std::string const& name : globals_targets) {
  889. path = cmStrCat("... ", name);
  890. lg->AppendEcho(commands, path);
  891. }
  892. for (std::string const& name : utility_targets) {
  893. path = cmStrCat("... ", name);
  894. lg->AppendEcho(commands, path);
  895. }
  896. for (std::string const& name : project_targets) {
  897. path = cmStrCat("... ", name);
  898. lg->AppendEcho(commands, path);
  899. }
  900. for (std::string const& o : lg->GetLocalHelp()) {
  901. path = cmStrCat("... ", o);
  902. lg->AppendEcho(commands, path);
  903. }
  904. lg->WriteMakeRule(ruleFileStream, "Help Target", "help", no_depends,
  905. commands, true);
  906. ruleFileStream << "\n\n";
  907. }