cmLocalUnixMakefileGenerator3.cxx 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093
  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 "cmLocalUnixMakefileGenerator3.h"
  4. #include <algorithm>
  5. #include <cassert>
  6. #include <cstdio>
  7. #include <sstream>
  8. #include <utility>
  9. #include <cm/memory>
  10. #include <cm/string_view>
  11. #include <cm/vector>
  12. #include <cmext/algorithm>
  13. #include "cmsys/FStream.hxx"
  14. #include "cmsys/Terminal.h"
  15. #include "cmCMakePath.h"
  16. #include "cmCustomCommand.h" // IWYU pragma: keep
  17. #include "cmCustomCommandGenerator.h"
  18. #include "cmFileTimeCache.h"
  19. #include "cmGeneratedFileStream.h"
  20. #include "cmGeneratorExpression.h"
  21. #include "cmGeneratorTarget.h"
  22. #include "cmGlobalGenerator.h"
  23. #include "cmGlobalUnixMakefileGenerator3.h"
  24. #include "cmListFileCache.h"
  25. #include "cmLocalGenerator.h"
  26. #include "cmMakefile.h"
  27. #include "cmMakefileTargetGenerator.h"
  28. #include "cmOutputConverter.h"
  29. #include "cmProperty.h"
  30. #include "cmRange.h"
  31. #include "cmRulePlaceholderExpander.h"
  32. #include "cmSourceFile.h"
  33. #include "cmState.h"
  34. #include "cmStateDirectory.h"
  35. #include "cmStateSnapshot.h"
  36. #include "cmStateTypes.h"
  37. #include "cmStringAlgorithms.h"
  38. #include "cmSystemTools.h"
  39. #include "cmTargetDepend.h"
  40. #include "cmVersion.h"
  41. #include "cmake.h"
  42. // Include dependency scanners for supported languages. Only the
  43. // C/C++ scanner is needed for bootstrapping CMake.
  44. #include "cmDependsC.h"
  45. #ifndef CMAKE_BOOTSTRAP
  46. # include "cmDependsFortran.h"
  47. # include "cmDependsJava.h"
  48. #endif
  49. // Helper function used below.
  50. static std::string cmSplitExtension(std::string const& in, std::string& base)
  51. {
  52. std::string ext;
  53. std::string::size_type dot_pos = in.rfind('.');
  54. if (dot_pos != std::string::npos) {
  55. // Remove the extension first in case &base == &in.
  56. ext = in.substr(dot_pos);
  57. base = in.substr(0, dot_pos);
  58. } else {
  59. base = in;
  60. }
  61. return ext;
  62. }
  63. cmLocalUnixMakefileGenerator3::cmLocalUnixMakefileGenerator3(
  64. cmGlobalGenerator* gg, cmMakefile* mf)
  65. : cmLocalCommonGenerator(gg, mf, mf->GetCurrentBinaryDirectory())
  66. {
  67. this->MakefileVariableSize = 0;
  68. this->ColorMakefile = false;
  69. this->SkipPreprocessedSourceRules = false;
  70. this->SkipAssemblySourceRules = false;
  71. this->MakeCommandEscapeTargetTwice = false;
  72. this->BorlandMakeCurlyHack = false;
  73. }
  74. cmLocalUnixMakefileGenerator3::~cmLocalUnixMakefileGenerator3() = default;
  75. std::string cmLocalUnixMakefileGenerator3::GetConfigName() const
  76. {
  77. auto const& configNames = this->GetConfigNames();
  78. assert(configNames.size() == 1);
  79. return configNames.front();
  80. }
  81. void cmLocalUnixMakefileGenerator3::Generate()
  82. {
  83. // Record whether some options are enabled to avoid checking many
  84. // times later.
  85. if (!this->GetGlobalGenerator()->GetCMakeInstance()->GetIsInTryCompile()) {
  86. this->ColorMakefile = this->Makefile->IsOn("CMAKE_COLOR_MAKEFILE");
  87. }
  88. this->SkipPreprocessedSourceRules =
  89. this->Makefile->IsOn("CMAKE_SKIP_PREPROCESSED_SOURCE_RULES");
  90. this->SkipAssemblySourceRules =
  91. this->Makefile->IsOn("CMAKE_SKIP_ASSEMBLY_SOURCE_RULES");
  92. // Generate the rule files for each target.
  93. cmGlobalUnixMakefileGenerator3* gg =
  94. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  95. for (cmGeneratorTarget* gt :
  96. this->GlobalGenerator->GetLocalGeneratorTargetsInOrder(this)) {
  97. if (!gt->IsInBuildSystem()) {
  98. continue;
  99. }
  100. auto& gtVisited = this->GetCommandsVisited(gt);
  101. auto& deps = this->GlobalGenerator->GetTargetDirectDepends(gt);
  102. for (auto& d : deps) {
  103. // Take the union of visited source files of custom commands
  104. auto depVisited = this->GetCommandsVisited(d);
  105. gtVisited.insert(depVisited.begin(), depVisited.end());
  106. }
  107. std::unique_ptr<cmMakefileTargetGenerator> tg(
  108. cmMakefileTargetGenerator::New(gt));
  109. if (tg) {
  110. tg->WriteRuleFiles();
  111. gg->RecordTargetProgress(tg.get());
  112. }
  113. }
  114. // write the local Makefile
  115. this->WriteLocalMakefile();
  116. // Write the cmake file with information for this directory.
  117. this->WriteDirectoryInformationFile();
  118. }
  119. void cmLocalUnixMakefileGenerator3::ComputeHomeRelativeOutputPath()
  120. {
  121. // Compute the path to use when referencing the current output
  122. // directory from the top output directory.
  123. this->HomeRelativeOutputPath = this->MaybeConvertToRelativePath(
  124. this->GetBinaryDirectory(), this->GetCurrentBinaryDirectory());
  125. if (this->HomeRelativeOutputPath == ".") {
  126. this->HomeRelativeOutputPath.clear();
  127. }
  128. if (!this->HomeRelativeOutputPath.empty()) {
  129. this->HomeRelativeOutputPath += "/";
  130. }
  131. }
  132. void cmLocalUnixMakefileGenerator3::GetLocalObjectFiles(
  133. std::map<std::string, LocalObjectInfo>& localObjectFiles)
  134. {
  135. for (const auto& gt : this->GetGeneratorTargets()) {
  136. if (!gt->CanCompileSources()) {
  137. continue;
  138. }
  139. std::vector<cmSourceFile const*> objectSources;
  140. gt->GetObjectSources(objectSources, this->GetConfigName());
  141. // Compute full path to object file directory for this target.
  142. std::string dir = cmStrCat(gt->LocalGenerator->GetCurrentBinaryDirectory(),
  143. '/', this->GetTargetDirectory(gt.get()), '/');
  144. // Compute the name of each object file.
  145. for (cmSourceFile const* sf : objectSources) {
  146. bool hasSourceExtension = true;
  147. std::string objectName =
  148. this->GetObjectFileNameWithoutTarget(*sf, dir, &hasSourceExtension);
  149. if (cmSystemTools::FileIsFullPath(objectName)) {
  150. objectName = cmSystemTools::GetFilenameName(objectName);
  151. }
  152. LocalObjectInfo& info = localObjectFiles[objectName];
  153. info.HasSourceExtension = hasSourceExtension;
  154. info.emplace_back(gt.get(), sf->GetLanguage());
  155. }
  156. }
  157. }
  158. void cmLocalUnixMakefileGenerator3::GetIndividualFileTargets(
  159. std::vector<std::string>& targets)
  160. {
  161. std::map<std::string, LocalObjectInfo> localObjectFiles;
  162. this->GetLocalObjectFiles(localObjectFiles);
  163. for (auto const& localObjectFile : localObjectFiles) {
  164. targets.push_back(localObjectFile.first);
  165. std::string::size_type dot_pos = localObjectFile.first.rfind(".");
  166. std::string base = localObjectFile.first.substr(0, dot_pos);
  167. if (localObjectFile.second.HasPreprocessRule) {
  168. targets.push_back(base + ".i");
  169. }
  170. if (localObjectFile.second.HasAssembleRule) {
  171. targets.push_back(base + ".s");
  172. }
  173. }
  174. }
  175. void cmLocalUnixMakefileGenerator3::WriteLocalMakefile()
  176. {
  177. // generate the includes
  178. std::string ruleFileName = "Makefile";
  179. // Open the rule file. This should be copy-if-different because the
  180. // rules may depend on this file itself.
  181. std::string ruleFileNameFull = this->ConvertToFullPath(ruleFileName);
  182. cmGeneratedFileStream ruleFileStream(
  183. ruleFileNameFull, false, this->GlobalGenerator->GetMakefileEncoding());
  184. if (!ruleFileStream) {
  185. return;
  186. }
  187. // always write the top makefile
  188. if (!this->IsRootMakefile()) {
  189. ruleFileStream.SetCopyIfDifferent(true);
  190. }
  191. // write the all rules
  192. this->WriteLocalAllRules(ruleFileStream);
  193. // only write local targets unless at the top Keep track of targets already
  194. // listed.
  195. std::set<std::string> emittedTargets;
  196. if (!this->IsRootMakefile()) {
  197. // write our targets, and while doing it collect up the object
  198. // file rules
  199. this->WriteLocalMakefileTargets(ruleFileStream, emittedTargets);
  200. } else {
  201. cmGlobalUnixMakefileGenerator3* gg =
  202. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  203. gg->WriteConvenienceRules(ruleFileStream, emittedTargets);
  204. }
  205. bool do_preprocess_rules = this->GetCreatePreprocessedSourceRules();
  206. bool do_assembly_rules = this->GetCreateAssemblySourceRules();
  207. std::map<std::string, LocalObjectInfo> localObjectFiles;
  208. this->GetLocalObjectFiles(localObjectFiles);
  209. // now write out the object rules
  210. // for each object file name
  211. for (auto& localObjectFile : localObjectFiles) {
  212. // Add a convenience rule for building the object file.
  213. this->WriteObjectConvenienceRule(
  214. ruleFileStream, "target to build an object file", localObjectFile.first,
  215. localObjectFile.second);
  216. // Check whether preprocessing and assembly rules make sense.
  217. // They make sense only for C and C++ sources.
  218. bool lang_has_preprocessor = false;
  219. bool lang_has_assembly = false;
  220. for (LocalObjectEntry const& entry : localObjectFile.second) {
  221. if (entry.Language == "C" || entry.Language == "CXX" ||
  222. entry.Language == "CUDA" || entry.Language == "Fortran" ||
  223. entry.Language == "ISPC") {
  224. // Right now, C, C++, Fortran and CUDA have both a preprocessor and the
  225. // ability to generate assembly code
  226. lang_has_preprocessor = true;
  227. lang_has_assembly = true;
  228. break;
  229. }
  230. }
  231. // Add convenience rules for preprocessed and assembly files.
  232. if (lang_has_preprocessor && do_preprocess_rules) {
  233. std::string::size_type dot_pos = localObjectFile.first.rfind(".");
  234. std::string base = localObjectFile.first.substr(0, dot_pos);
  235. this->WriteObjectConvenienceRule(ruleFileStream,
  236. "target to preprocess a source file",
  237. (base + ".i"), localObjectFile.second);
  238. localObjectFile.second.HasPreprocessRule = true;
  239. }
  240. if (lang_has_assembly && do_assembly_rules) {
  241. std::string::size_type dot_pos = localObjectFile.first.rfind(".");
  242. std::string base = localObjectFile.first.substr(0, dot_pos);
  243. this->WriteObjectConvenienceRule(
  244. ruleFileStream, "target to generate assembly for a file",
  245. (base + ".s"), localObjectFile.second);
  246. localObjectFile.second.HasAssembleRule = true;
  247. }
  248. }
  249. // add a help target as long as there isn;t a real target named help
  250. if (emittedTargets.insert("help").second) {
  251. cmGlobalUnixMakefileGenerator3* gg =
  252. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  253. gg->WriteHelpRule(ruleFileStream, this);
  254. }
  255. this->WriteSpecialTargetsBottom(ruleFileStream);
  256. }
  257. void cmLocalUnixMakefileGenerator3::WriteObjectConvenienceRule(
  258. std::ostream& ruleFileStream, const char* comment, const std::string& output,
  259. LocalObjectInfo const& info)
  260. {
  261. // If the rule includes the source file extension then create a
  262. // version that has the extension removed. The help should include
  263. // only the version without source extension.
  264. bool inHelp = true;
  265. if (info.HasSourceExtension) {
  266. // Remove the last extension. This should be kept.
  267. std::string outBase1 = output;
  268. std::string outExt1 = cmSplitExtension(outBase1, outBase1);
  269. // Now remove the source extension and put back the last
  270. // extension.
  271. std::string outNoExt;
  272. cmSplitExtension(outBase1, outNoExt);
  273. outNoExt += outExt1;
  274. // Add a rule to drive the rule below.
  275. std::vector<std::string> depends;
  276. depends.emplace_back(output);
  277. std::vector<std::string> no_commands;
  278. this->WriteMakeRule(ruleFileStream, nullptr, outNoExt, depends,
  279. no_commands, true, true);
  280. inHelp = false;
  281. }
  282. // Recursively make the rule for each target using the object file.
  283. std::vector<std::string> commands;
  284. for (LocalObjectEntry const& t : info) {
  285. std::string tgtMakefileName = this->GetRelativeTargetDirectory(t.Target);
  286. std::string targetName = tgtMakefileName;
  287. tgtMakefileName += "/build.make";
  288. targetName += "/";
  289. targetName += output;
  290. commands.push_back(
  291. this->GetRecursiveMakeCall(tgtMakefileName, targetName));
  292. }
  293. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  294. this->GetCurrentBinaryDirectory());
  295. // Write the rule to the makefile.
  296. std::vector<std::string> no_depends;
  297. this->WriteMakeRule(ruleFileStream, comment, output, no_depends, commands,
  298. true, inHelp);
  299. }
  300. void cmLocalUnixMakefileGenerator3::WriteLocalMakefileTargets(
  301. std::ostream& ruleFileStream, std::set<std::string>& emitted)
  302. {
  303. std::vector<std::string> depends;
  304. std::vector<std::string> commands;
  305. // for each target we just provide a rule to cd up to the top and do a make
  306. // on the target
  307. std::string localName;
  308. for (const auto& target : this->GetGeneratorTargets()) {
  309. if ((target->GetType() == cmStateEnums::EXECUTABLE) ||
  310. (target->GetType() == cmStateEnums::STATIC_LIBRARY) ||
  311. (target->GetType() == cmStateEnums::SHARED_LIBRARY) ||
  312. (target->GetType() == cmStateEnums::MODULE_LIBRARY) ||
  313. (target->GetType() == cmStateEnums::OBJECT_LIBRARY) ||
  314. (target->GetType() == cmStateEnums::UTILITY)) {
  315. emitted.insert(target->GetName());
  316. // for subdirs add a rule to build this specific target by name.
  317. localName =
  318. cmStrCat(this->GetRelativeTargetDirectory(target.get()), "/rule");
  319. commands.clear();
  320. depends.clear();
  321. // Build the target for this pass.
  322. std::string makefile2 = "CMakeFiles/Makefile2";
  323. commands.push_back(this->GetRecursiveMakeCall(makefile2, localName));
  324. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  325. this->GetCurrentBinaryDirectory());
  326. this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
  327. localName, depends, commands, true);
  328. // Add a target with the canonical name (no prefix, suffix or path).
  329. if (localName != target->GetName()) {
  330. commands.clear();
  331. depends.push_back(localName);
  332. this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
  333. target->GetName(), depends, commands, true);
  334. }
  335. // Add a fast rule to build the target
  336. std::string makefileName = cmStrCat(
  337. this->GetRelativeTargetDirectory(target.get()), "/build.make");
  338. // make sure the makefile name is suitable for a makefile
  339. std::string makeTargetName =
  340. cmStrCat(this->GetRelativeTargetDirectory(target.get()), "/build");
  341. localName = cmStrCat(target->GetName(), "/fast");
  342. depends.clear();
  343. commands.clear();
  344. commands.push_back(
  345. this->GetRecursiveMakeCall(makefileName, makeTargetName));
  346. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  347. this->GetCurrentBinaryDirectory());
  348. this->WriteMakeRule(ruleFileStream, "fast build rule for target.",
  349. localName, depends, commands, true);
  350. // Add a local name for the rule to relink the target before
  351. // installation.
  352. if (target->NeedRelinkBeforeInstall(this->GetConfigName())) {
  353. makeTargetName = cmStrCat(
  354. this->GetRelativeTargetDirectory(target.get()), "/preinstall");
  355. localName = cmStrCat(target->GetName(), "/preinstall");
  356. depends.clear();
  357. commands.clear();
  358. commands.push_back(
  359. this->GetRecursiveMakeCall(makefile2, makeTargetName));
  360. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  361. this->GetCurrentBinaryDirectory());
  362. this->WriteMakeRule(ruleFileStream,
  363. "Manual pre-install relink rule for target.",
  364. localName, depends, commands, true);
  365. }
  366. }
  367. }
  368. }
  369. void cmLocalUnixMakefileGenerator3::WriteDirectoryInformationFile()
  370. {
  371. std::string infoFileName =
  372. cmStrCat(this->GetCurrentBinaryDirectory(),
  373. "/CMakeFiles/CMakeDirectoryInformation.cmake");
  374. // Open the output file.
  375. cmGeneratedFileStream infoFileStream(infoFileName);
  376. if (!infoFileStream) {
  377. return;
  378. }
  379. infoFileStream.SetCopyIfDifferent(true);
  380. // Write the do not edit header.
  381. this->WriteDisclaimer(infoFileStream);
  382. // Setup relative path conversion tops.
  383. /* clang-format off */
  384. infoFileStream
  385. << "# Relative path conversion top directories.\n"
  386. << "set(CMAKE_RELATIVE_PATH_TOP_SOURCE \""
  387. << this->StateSnapshot.GetDirectory().GetRelativePathTopSource()
  388. << "\")\n"
  389. << "set(CMAKE_RELATIVE_PATH_TOP_BINARY \""
  390. << this->StateSnapshot.GetDirectory().GetRelativePathTopBinary()
  391. << "\")\n"
  392. << "\n";
  393. /* clang-format on */
  394. // Tell the dependency scanner to use unix paths if necessary.
  395. if (cmSystemTools::GetForceUnixPaths()) {
  396. /* clang-format off */
  397. infoFileStream
  398. << "# Force unix paths in dependencies.\n"
  399. << "set(CMAKE_FORCE_UNIX_PATHS 1)\n"
  400. << "\n";
  401. /* clang-format on */
  402. }
  403. // Store the include regular expressions for this directory.
  404. infoFileStream << "\n"
  405. << "# The C and CXX include file regular expressions for "
  406. << "this directory.\n";
  407. infoFileStream << "set(CMAKE_C_INCLUDE_REGEX_SCAN ";
  408. cmLocalUnixMakefileGenerator3::WriteCMakeArgument(
  409. infoFileStream, this->Makefile->GetIncludeRegularExpression());
  410. infoFileStream << ")\n";
  411. infoFileStream << "set(CMAKE_C_INCLUDE_REGEX_COMPLAIN ";
  412. cmLocalUnixMakefileGenerator3::WriteCMakeArgument(
  413. infoFileStream, this->Makefile->GetComplainRegularExpression());
  414. infoFileStream << ")\n";
  415. infoFileStream
  416. << "set(CMAKE_CXX_INCLUDE_REGEX_SCAN ${CMAKE_C_INCLUDE_REGEX_SCAN})\n";
  417. infoFileStream << "set(CMAKE_CXX_INCLUDE_REGEX_COMPLAIN "
  418. "${CMAKE_C_INCLUDE_REGEX_COMPLAIN})\n";
  419. }
  420. std::string cmLocalUnixMakefileGenerator3::ConvertToFullPath(
  421. const std::string& localPath)
  422. {
  423. std::string dir =
  424. cmStrCat(this->GetCurrentBinaryDirectory(), '/', localPath);
  425. return dir;
  426. }
  427. const std::string& cmLocalUnixMakefileGenerator3::GetHomeRelativeOutputPath()
  428. {
  429. return this->HomeRelativeOutputPath;
  430. }
  431. std::string cmLocalUnixMakefileGenerator3::ConvertToMakefilePath(
  432. std::string const& path) const
  433. {
  434. cmGlobalUnixMakefileGenerator3* gg =
  435. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  436. return gg->ConvertToMakefilePath(path);
  437. }
  438. void cmLocalUnixMakefileGenerator3::WriteMakeRule(
  439. std::ostream& os, const char* comment, const std::string& target,
  440. const std::vector<std::string>& depends,
  441. const std::vector<std::string>& commands, bool symbolic, bool in_help)
  442. {
  443. // Make sure there is a target.
  444. if (target.empty()) {
  445. std::string err("No target for WriteMakeRule! called with comment: ");
  446. if (comment) {
  447. err += comment;
  448. }
  449. cmSystemTools::Error(err);
  450. return;
  451. }
  452. std::string replace;
  453. // Write the comment describing the rule in the makefile.
  454. if (comment) {
  455. replace = comment;
  456. std::string::size_type lpos = 0;
  457. std::string::size_type rpos;
  458. while ((rpos = replace.find('\n', lpos)) != std::string::npos) {
  459. os << "# " << replace.substr(lpos, rpos - lpos) << "\n";
  460. lpos = rpos + 1;
  461. }
  462. os << "# " << replace.substr(lpos) << "\n";
  463. }
  464. // Construct the left hand side of the rule.
  465. std::string tgt = this->ConvertToMakefilePath(
  466. this->MaybeConvertToRelativePath(this->GetBinaryDirectory(), target));
  467. const char* space = "";
  468. if (tgt.size() == 1) {
  469. // Add a space before the ":" to avoid drive letter confusion on
  470. // Windows.
  471. space = " ";
  472. }
  473. // Mark the rule as symbolic if requested.
  474. if (symbolic) {
  475. if (cmProp sym =
  476. this->Makefile->GetDefinition("CMAKE_MAKE_SYMBOLIC_RULE")) {
  477. os << tgt << space << ": " << *sym << "\n";
  478. }
  479. }
  480. // Write the rule.
  481. if (depends.empty()) {
  482. // No dependencies. The commands will always run.
  483. os << tgt << space << ":\n";
  484. } else {
  485. // Split dependencies into multiple rule lines. This allows for
  486. // very long dependency lists even on older make implementations.
  487. std::string binDir = this->GetBinaryDirectory();
  488. for (std::string const& depend : depends) {
  489. os << tgt << space << ": "
  490. << this->ConvertToMakefilePath(
  491. this->MaybeConvertToRelativePath(binDir, depend))
  492. << '\n';
  493. }
  494. }
  495. // Write the list of commands.
  496. os << cmWrap("\t", commands, "", "\n") << "\n";
  497. if (symbolic && !this->IsWatcomWMake()) {
  498. os << ".PHONY : " << tgt << "\n";
  499. }
  500. os << "\n";
  501. // Add the output to the local help if requested.
  502. if (in_help) {
  503. this->LocalHelp.push_back(target);
  504. }
  505. }
  506. std::string cmLocalUnixMakefileGenerator3::MaybeConvertWatcomShellCommand(
  507. std::string const& cmd)
  508. {
  509. if (this->IsWatcomWMake() && cmSystemTools::FileIsFullPath(cmd) &&
  510. cmd.find_first_of("( )") != std::string::npos) {
  511. // On Watcom WMake use the windows short path for the command
  512. // name. This is needed to avoid funny quoting problems on
  513. // lines with shell redirection operators.
  514. std::string scmd;
  515. if (cmSystemTools::GetShortPath(cmd, scmd)) {
  516. return this->ConvertToOutputFormat(scmd, cmOutputConverter::SHELL);
  517. }
  518. }
  519. return std::string();
  520. }
  521. void cmLocalUnixMakefileGenerator3::WriteMakeVariables(
  522. std::ostream& makefileStream)
  523. {
  524. this->WriteDivider(makefileStream);
  525. makefileStream << "# Set environment variables for the build.\n"
  526. << "\n";
  527. cmGlobalUnixMakefileGenerator3* gg =
  528. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  529. if (gg->DefineWindowsNULL) {
  530. makefileStream << "!IF \"$(OS)\" == \"Windows_NT\"\n"
  531. << "NULL=\n"
  532. << "!ELSE\n"
  533. << "NULL=nul\n"
  534. << "!ENDIF\n";
  535. }
  536. if (this->IsWindowsShell()) {
  537. makefileStream << "SHELL = cmd.exe\n"
  538. << "\n";
  539. } else {
  540. #if !defined(__VMS)
  541. /* clang-format off */
  542. makefileStream
  543. << "# The shell in which to execute make rules.\n"
  544. << "SHELL = /bin/sh\n"
  545. << "\n";
  546. /* clang-format on */
  547. #endif
  548. }
  549. std::string cmakeShellCommand =
  550. this->MaybeConvertWatcomShellCommand(cmSystemTools::GetCMakeCommand());
  551. if (cmakeShellCommand.empty()) {
  552. cmakeShellCommand = this->ConvertToOutputFormat(
  553. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  554. }
  555. /* clang-format off */
  556. makefileStream
  557. << "# The CMake executable.\n"
  558. << "CMAKE_COMMAND = "
  559. << cmakeShellCommand
  560. << "\n"
  561. << "\n";
  562. makefileStream
  563. << "# The command to remove a file.\n"
  564. << "RM = "
  565. << cmakeShellCommand
  566. << " -E rm -f\n"
  567. << "\n";
  568. makefileStream
  569. << "# Escaping for special characters.\n"
  570. << "EQUALS = =\n"
  571. << "\n";
  572. makefileStream
  573. << "# The top-level source directory on which CMake was run.\n"
  574. << "CMAKE_SOURCE_DIR = "
  575. << this->ConvertToOutputFormat(
  576. this->GetSourceDirectory(), cmOutputConverter::SHELL)
  577. << "\n"
  578. << "\n";
  579. makefileStream
  580. << "# The top-level build directory on which CMake was run.\n"
  581. << "CMAKE_BINARY_DIR = "
  582. << this->ConvertToOutputFormat(
  583. this->GetBinaryDirectory(), cmOutputConverter::SHELL)
  584. << "\n"
  585. << "\n";
  586. /* clang-format on */
  587. }
  588. void cmLocalUnixMakefileGenerator3::WriteSpecialTargetsTop(
  589. std::ostream& makefileStream)
  590. {
  591. this->WriteDivider(makefileStream);
  592. makefileStream << "# Special targets provided by cmake.\n"
  593. << "\n";
  594. std::vector<std::string> no_commands;
  595. std::vector<std::string> no_depends;
  596. // Special target to cleanup operation of make tool.
  597. // This should be the first target except for the default_target in
  598. // the interface Makefile.
  599. this->WriteMakeRule(makefileStream,
  600. "Disable implicit rules so canonical targets will work.",
  601. ".SUFFIXES", no_depends, no_commands, false);
  602. if (!this->IsNMake() && !this->IsWatcomWMake() &&
  603. !this->BorlandMakeCurlyHack) {
  604. // turn off RCS and SCCS automatic stuff from gmake
  605. constexpr const char* vcs_rules[] = {
  606. "%,v", "RCS/%", "RCS/%,v", "SCCS/s.%", "s.%",
  607. };
  608. for (auto vcs_rule : vcs_rules) {
  609. std::vector<std::string> vcs_depend;
  610. vcs_depend.emplace_back(vcs_rule);
  611. this->WriteMakeRule(makefileStream, "Disable VCS-based implicit rules.",
  612. "%", vcs_depend, no_commands, false);
  613. }
  614. }
  615. // Add a fake suffix to keep HP happy. Must be max 32 chars for SGI make.
  616. std::vector<std::string> depends;
  617. depends.emplace_back(".hpux_make_needs_suffix_list");
  618. this->WriteMakeRule(makefileStream, nullptr, ".SUFFIXES", depends,
  619. no_commands, false);
  620. if (this->IsWatcomWMake()) {
  621. // Switch on WMake feature, if an error or interrupt occurs during
  622. // makefile processing, the current target being made may be deleted
  623. // without prompting (the same as command line -e option).
  624. /* clang-format off */
  625. makefileStream <<
  626. "\n"
  627. ".ERASE\n"
  628. "\n"
  629. ;
  630. /* clang-format on */
  631. }
  632. if (this->Makefile->IsOn("CMAKE_VERBOSE_MAKEFILE")) {
  633. /* clang-format off */
  634. makefileStream
  635. << "# Produce verbose output by default.\n"
  636. << "VERBOSE = 1\n"
  637. << "\n";
  638. /* clang-format on */
  639. }
  640. if (this->IsWatcomWMake()) {
  641. /* clang-format off */
  642. makefileStream <<
  643. "!ifndef VERBOSE\n"
  644. ".SILENT\n"
  645. "!endif\n"
  646. "\n"
  647. ;
  648. /* clang-format on */
  649. } else {
  650. makefileStream << "# Command-line flag to silence nested $(MAKE).\n"
  651. "$(VERBOSE)MAKESILENT = -s\n"
  652. "\n";
  653. // Write special target to silence make output. This must be after
  654. // the default target in case VERBOSE is set (which changes the
  655. // name). The setting of CMAKE_VERBOSE_MAKEFILE to ON will cause a
  656. // "VERBOSE=1" to be added as a make variable which will change the
  657. // name of this special target. This gives a make-time choice to
  658. // the user.
  659. // Write directly to the stream since WriteMakeRule escapes '$'.
  660. makefileStream << "#Suppress display of executed commands.\n"
  661. "$(VERBOSE).SILENT:\n"
  662. "\n";
  663. }
  664. // Work-around for makes that drop rules that have no dependencies
  665. // or commands.
  666. cmGlobalUnixMakefileGenerator3* gg =
  667. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  668. std::string hack = gg->GetEmptyRuleHackDepends();
  669. if (!hack.empty()) {
  670. no_depends.push_back(std::move(hack));
  671. }
  672. std::string hack_cmd = gg->GetEmptyRuleHackCommand();
  673. if (!hack_cmd.empty()) {
  674. no_commands.push_back(std::move(hack_cmd));
  675. }
  676. // Special symbolic target that never exists to force dependers to
  677. // run their rules.
  678. this->WriteMakeRule(makefileStream, "A target that is always out of date.",
  679. "cmake_force", no_depends, no_commands, true);
  680. // Variables for reference by other rules.
  681. this->WriteMakeVariables(makefileStream);
  682. }
  683. void cmLocalUnixMakefileGenerator3::WriteSpecialTargetsBottom(
  684. std::ostream& makefileStream)
  685. {
  686. this->WriteDivider(makefileStream);
  687. makefileStream << "# Special targets to cleanup operation of make.\n"
  688. << "\n";
  689. // Write special "cmake_check_build_system" target to run cmake with
  690. // the --check-build-system flag.
  691. if (!this->GlobalGenerator->GlobalSettingIsOn(
  692. "CMAKE_SUPPRESS_REGENERATION")) {
  693. // Build command to run CMake to check if anything needs regenerating.
  694. std::vector<std::string> commands;
  695. cmake* cm = this->GlobalGenerator->GetCMakeInstance();
  696. if (cm->DoWriteGlobVerifyTarget()) {
  697. std::string rescanRule =
  698. cmStrCat("$(CMAKE_COMMAND) -P ",
  699. this->ConvertToOutputFormat(cm->GetGlobVerifyScript(),
  700. cmOutputConverter::SHELL));
  701. commands.push_back(rescanRule);
  702. }
  703. std::string cmakefileName = "CMakeFiles/Makefile.cmake";
  704. std::string runRule = cmStrCat(
  705. "$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) "
  706. "--check-build-system ",
  707. this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL),
  708. " 0");
  709. std::vector<std::string> no_depends;
  710. commands.push_back(std::move(runRule));
  711. if (!this->IsRootMakefile()) {
  712. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  713. this->GetCurrentBinaryDirectory());
  714. }
  715. this->WriteMakeRule(makefileStream,
  716. "Special rule to run CMake to check the build system "
  717. "integrity.\n"
  718. "No rule that depends on this can have "
  719. "commands that come from listfiles\n"
  720. "because they might be regenerated.",
  721. "cmake_check_build_system", no_depends, commands,
  722. true);
  723. }
  724. }
  725. void cmLocalUnixMakefileGenerator3::WriteConvenienceRule(
  726. std::ostream& ruleFileStream, const std::string& realTarget,
  727. const std::string& helpTarget)
  728. {
  729. // A rule is only needed if the names are different.
  730. if (realTarget != helpTarget) {
  731. // The helper target depends on the real target.
  732. std::vector<std::string> depends;
  733. depends.push_back(realTarget);
  734. // There are no commands.
  735. std::vector<std::string> no_commands;
  736. // Write the rule.
  737. this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
  738. helpTarget, depends, no_commands, true);
  739. }
  740. }
  741. std::string cmLocalUnixMakefileGenerator3::GetRelativeTargetDirectory(
  742. cmGeneratorTarget const* target) const
  743. {
  744. std::string dir =
  745. cmStrCat(this->HomeRelativeOutputPath, this->GetTargetDirectory(target));
  746. return dir;
  747. }
  748. void cmLocalUnixMakefileGenerator3::AppendFlags(
  749. std::string& flags, const std::string& newFlags) const
  750. {
  751. if (this->IsWatcomWMake() && !newFlags.empty()) {
  752. std::string newf = newFlags;
  753. if (newf.find("\\\"") != std::string::npos) {
  754. cmSystemTools::ReplaceString(newf, "\\\"", "\"");
  755. this->cmLocalGenerator::AppendFlags(flags, newf);
  756. return;
  757. }
  758. }
  759. this->cmLocalGenerator::AppendFlags(flags, newFlags);
  760. }
  761. void cmLocalUnixMakefileGenerator3::AppendRuleDepend(
  762. std::vector<std::string>& depends, const char* ruleFileName)
  763. {
  764. // Add a dependency on the rule file itself unless an option to skip
  765. // it is specifically enabled by the user or project.
  766. cmProp nodep = this->Makefile->GetDefinition("CMAKE_SKIP_RULE_DEPENDENCY");
  767. if (cmIsOff(nodep)) {
  768. depends.emplace_back(ruleFileName);
  769. }
  770. }
  771. void cmLocalUnixMakefileGenerator3::AppendRuleDepends(
  772. std::vector<std::string>& depends, std::vector<std::string> const& ruleFiles)
  773. {
  774. // Add a dependency on the rule file itself unless an option to skip
  775. // it is specifically enabled by the user or project.
  776. if (!this->Makefile->IsOn("CMAKE_SKIP_RULE_DEPENDENCY")) {
  777. cm::append(depends, ruleFiles);
  778. }
  779. }
  780. void cmLocalUnixMakefileGenerator3::AppendCustomDepends(
  781. std::vector<std::string>& depends, const std::vector<cmCustomCommand>& ccs)
  782. {
  783. for (cmCustomCommand const& cc : ccs) {
  784. cmCustomCommandGenerator ccg(cc, this->GetConfigName(), this);
  785. this->AppendCustomDepend(depends, ccg);
  786. }
  787. }
  788. void cmLocalUnixMakefileGenerator3::AppendCustomDepend(
  789. std::vector<std::string>& depends, cmCustomCommandGenerator const& ccg)
  790. {
  791. for (std::string const& d : ccg.GetDepends()) {
  792. // Lookup the real name of the dependency in case it is a CMake target.
  793. std::string dep;
  794. if (this->GetRealDependency(d, this->GetConfigName(), dep)) {
  795. depends.push_back(std::move(dep));
  796. }
  797. }
  798. }
  799. void cmLocalUnixMakefileGenerator3::AppendCustomCommands(
  800. std::vector<std::string>& commands, const std::vector<cmCustomCommand>& ccs,
  801. cmGeneratorTarget* target, std::string const& relative)
  802. {
  803. for (cmCustomCommand const& cc : ccs) {
  804. cmCustomCommandGenerator ccg(cc, this->GetConfigName(), this);
  805. this->AppendCustomCommand(commands, ccg, target, relative, true);
  806. }
  807. }
  808. void cmLocalUnixMakefileGenerator3::AppendCustomCommand(
  809. std::vector<std::string>& commands, cmCustomCommandGenerator const& ccg,
  810. cmGeneratorTarget* target, std::string const& relative, bool echo_comment,
  811. std::ostream* content)
  812. {
  813. // Optionally create a command to display the custom command's
  814. // comment text. This is used for pre-build, pre-link, and
  815. // post-build command comments. Custom build step commands have
  816. // their comments generated elsewhere.
  817. if (echo_comment) {
  818. const char* comment = ccg.GetComment();
  819. if (comment && *comment) {
  820. this->AppendEcho(commands, comment,
  821. cmLocalUnixMakefileGenerator3::EchoGenerate);
  822. }
  823. }
  824. // if the command specified a working directory use it.
  825. std::string dir = this->GetCurrentBinaryDirectory();
  826. std::string workingDir = ccg.GetWorkingDirectory();
  827. if (!workingDir.empty()) {
  828. dir = workingDir;
  829. }
  830. if (content) {
  831. *content << dir;
  832. }
  833. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  834. this->CreateRulePlaceholderExpander());
  835. // Add each command line to the set of commands.
  836. std::vector<std::string> commands1;
  837. std::string currentBinDir = this->GetCurrentBinaryDirectory();
  838. for (unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) {
  839. // Build the command line in a single string.
  840. std::string cmd = ccg.GetCommand(c);
  841. if (!cmd.empty()) {
  842. // Use "call " before any invocations of .bat or .cmd files
  843. // invoked as custom commands in the WindowsShell.
  844. //
  845. bool useCall = false;
  846. if (this->IsWindowsShell()) {
  847. std::string suffix;
  848. if (cmd.size() > 4) {
  849. suffix = cmSystemTools::LowerCase(cmd.substr(cmd.size() - 4));
  850. if (suffix == ".bat" || suffix == ".cmd") {
  851. useCall = true;
  852. }
  853. }
  854. }
  855. cmSystemTools::ReplaceString(cmd, "/./", "/");
  856. // Convert the command to a relative path only if the current
  857. // working directory will be the start-output directory.
  858. bool had_slash = cmd.find('/') != std::string::npos;
  859. if (workingDir.empty()) {
  860. cmd = this->MaybeConvertToRelativePath(currentBinDir, cmd);
  861. }
  862. bool has_slash = cmd.find('/') != std::string::npos;
  863. if (had_slash && !has_slash) {
  864. // This command was specified as a path to a file in the
  865. // current directory. Add a leading "./" so it can run
  866. // without the current directory being in the search path.
  867. cmd = cmStrCat("./", cmd);
  868. }
  869. std::string launcher;
  870. // Short-circuit if there is no launcher.
  871. cmProp val = this->GetRuleLauncher(target, "RULE_LAUNCH_CUSTOM");
  872. if (cmNonempty(val)) {
  873. // Expand rule variables referenced in the given launcher command.
  874. cmRulePlaceholderExpander::RuleVariables vars;
  875. vars.CMTargetName = target->GetName().c_str();
  876. vars.CMTargetType =
  877. cmState::GetTargetTypeName(target->GetType()).c_str();
  878. std::string output;
  879. const std::vector<std::string>& outputs = ccg.GetOutputs();
  880. if (!outputs.empty()) {
  881. output = outputs[0];
  882. if (workingDir.empty()) {
  883. output = this->MaybeConvertToRelativePath(
  884. this->GetCurrentBinaryDirectory(), output);
  885. }
  886. output =
  887. this->ConvertToOutputFormat(output, cmOutputConverter::SHELL);
  888. }
  889. vars.Output = output.c_str();
  890. launcher = *val;
  891. rulePlaceholderExpander->ExpandRuleVariables(this, launcher, vars);
  892. if (!launcher.empty()) {
  893. launcher += " ";
  894. }
  895. }
  896. std::string shellCommand = this->MaybeConvertWatcomShellCommand(cmd);
  897. if (shellCommand.empty()) {
  898. shellCommand =
  899. this->ConvertToOutputFormat(cmd, cmOutputConverter::SHELL);
  900. }
  901. cmd = launcher + shellCommand;
  902. ccg.AppendArguments(c, cmd);
  903. if (content) {
  904. // Rule content does not include the launcher.
  905. *content << (cmd.c_str() + launcher.size());
  906. }
  907. if (this->BorlandMakeCurlyHack) {
  908. // Borland Make has a very strange bug. If the first curly
  909. // brace anywhere in the command string is a left curly, it
  910. // must be written {{} instead of just {. Otherwise some
  911. // curly braces are removed. The hack can be skipped if the
  912. // first curly brace is the last character.
  913. std::string::size_type lcurly = cmd.find('{');
  914. if (lcurly != std::string::npos && lcurly < (cmd.size() - 1)) {
  915. std::string::size_type rcurly = cmd.find('}');
  916. if (rcurly == std::string::npos || rcurly > lcurly) {
  917. // The first curly is a left curly. Use the hack.
  918. cmd =
  919. cmStrCat(cmd.substr(0, lcurly), "{{}", cmd.substr(lcurly + 1));
  920. }
  921. }
  922. }
  923. if (launcher.empty()) {
  924. if (useCall) {
  925. cmd = cmStrCat("call ", cmd);
  926. } else if (this->IsNMake() && cmd[0] == '"') {
  927. cmd = cmStrCat("echo >nul && ", cmd);
  928. }
  929. }
  930. commands1.push_back(std::move(cmd));
  931. }
  932. }
  933. // Setup the proper working directory for the commands.
  934. this->CreateCDCommand(commands1, dir, relative);
  935. // push back the custom commands
  936. cm::append(commands, commands1);
  937. }
  938. void cmLocalUnixMakefileGenerator3::AppendCleanCommand(
  939. std::vector<std::string>& commands, const std::set<std::string>& files,
  940. cmGeneratorTarget* target, const char* filename)
  941. {
  942. std::string currentBinDir = this->GetCurrentBinaryDirectory();
  943. std::string cleanfile = cmStrCat(
  944. currentBinDir, '/', this->GetTargetDirectory(target), "/cmake_clean");
  945. if (filename) {
  946. cleanfile += "_";
  947. cleanfile += filename;
  948. }
  949. cleanfile += ".cmake";
  950. cmsys::ofstream fout(cleanfile.c_str());
  951. if (!fout) {
  952. cmSystemTools::Error("Could not create " + cleanfile);
  953. }
  954. if (!files.empty()) {
  955. fout << "file(REMOVE_RECURSE\n";
  956. for (std::string const& file : files) {
  957. std::string fc = this->MaybeConvertToRelativePath(currentBinDir, file);
  958. fout << " " << cmOutputConverter::EscapeForCMake(fc) << "\n";
  959. }
  960. fout << ")\n";
  961. }
  962. {
  963. std::string remove =
  964. cmStrCat("$(CMAKE_COMMAND) -P ",
  965. this->ConvertToOutputFormat(
  966. this->MaybeConvertToRelativePath(
  967. this->GetCurrentBinaryDirectory(), cleanfile),
  968. cmOutputConverter::SHELL));
  969. commands.push_back(std::move(remove));
  970. }
  971. // For the main clean rule add per-language cleaning.
  972. if (!filename) {
  973. // Get the set of source languages in the target.
  974. std::set<std::string> languages;
  975. target->GetLanguages(
  976. languages, this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
  977. /* clang-format off */
  978. fout << "\n"
  979. << "# Per-language clean rules from dependency scanning.\n"
  980. << "foreach(lang " << cmJoin(languages, " ") << ")\n"
  981. << " include(" << this->GetTargetDirectory(target)
  982. << "/cmake_clean_${lang}.cmake OPTIONAL)\n"
  983. << "endforeach()\n";
  984. /* clang-format on */
  985. }
  986. }
  987. void cmLocalUnixMakefileGenerator3::AppendDirectoryCleanCommand(
  988. std::vector<std::string>& commands)
  989. {
  990. std::vector<std::string> cleanFiles;
  991. // Look for additional files registered for cleaning in this directory.
  992. if (cmProp prop_value =
  993. this->Makefile->GetProperty("ADDITIONAL_CLEAN_FILES")) {
  994. cmExpandList(cmGeneratorExpression::Evaluate(
  995. *prop_value, this,
  996. this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE")),
  997. cleanFiles);
  998. }
  999. if (cleanFiles.empty()) {
  1000. return;
  1001. }
  1002. const auto& rootLG = this->GetGlobalGenerator()->GetLocalGenerators().at(0);
  1003. std::string const& binaryDir = rootLG->GetCurrentBinaryDirectory();
  1004. std::string const& currentBinaryDir = this->GetCurrentBinaryDirectory();
  1005. std::string cleanfile =
  1006. cmStrCat(currentBinaryDir, "/CMakeFiles/cmake_directory_clean.cmake");
  1007. // Write clean script
  1008. {
  1009. cmsys::ofstream fout(cleanfile.c_str());
  1010. if (!fout) {
  1011. cmSystemTools::Error("Could not create " + cleanfile);
  1012. return;
  1013. }
  1014. fout << "file(REMOVE_RECURSE\n";
  1015. for (std::string const& cfl : cleanFiles) {
  1016. std::string fc = rootLG->MaybeConvertToRelativePath(
  1017. binaryDir, cmSystemTools::CollapseFullPath(cfl, currentBinaryDir));
  1018. fout << " " << cmOutputConverter::EscapeForCMake(fc) << "\n";
  1019. }
  1020. fout << ")\n";
  1021. }
  1022. // Create command
  1023. {
  1024. std::string remove =
  1025. cmStrCat("$(CMAKE_COMMAND) -P ",
  1026. this->ConvertToOutputFormat(
  1027. rootLG->MaybeConvertToRelativePath(binaryDir, cleanfile),
  1028. cmOutputConverter::SHELL));
  1029. commands.push_back(std::move(remove));
  1030. }
  1031. }
  1032. void cmLocalUnixMakefileGenerator3::AppendEcho(
  1033. std::vector<std::string>& commands, std::string const& text, EchoColor color,
  1034. EchoProgress const* progress)
  1035. {
  1036. // Choose the color for the text.
  1037. std::string color_name;
  1038. if (this->GlobalGenerator->GetToolSupportsColor() && this->ColorMakefile) {
  1039. // See cmake::ExecuteEchoColor in cmake.cxx for these options.
  1040. // This color set is readable on both black and white backgrounds.
  1041. switch (color) {
  1042. case EchoNormal:
  1043. break;
  1044. case EchoDepend:
  1045. color_name = "--magenta --bold ";
  1046. break;
  1047. case EchoBuild:
  1048. color_name = "--green ";
  1049. break;
  1050. case EchoLink:
  1051. color_name = "--green --bold ";
  1052. break;
  1053. case EchoGenerate:
  1054. color_name = "--blue --bold ";
  1055. break;
  1056. case EchoGlobal:
  1057. color_name = "--cyan ";
  1058. break;
  1059. }
  1060. }
  1061. // Echo one line at a time.
  1062. std::string line;
  1063. line.reserve(200);
  1064. for (const char* c = text.c_str();; ++c) {
  1065. if (*c == '\n' || *c == '\0') {
  1066. // Avoid writing a blank last line on end-of-string.
  1067. if (*c != '\0' || !line.empty()) {
  1068. // Add a command to echo this line.
  1069. std::string cmd;
  1070. if (color_name.empty() && !progress) {
  1071. // Use the native echo command.
  1072. cmd = cmStrCat("@echo ", this->EscapeForShell(line, false, true));
  1073. } else {
  1074. // Use cmake to echo the text in color.
  1075. cmd = cmStrCat(
  1076. "@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) ",
  1077. color_name);
  1078. if (progress) {
  1079. cmd += "--progress-dir=";
  1080. cmd += this->ConvertToOutputFormat(progress->Dir,
  1081. cmOutputConverter::SHELL);
  1082. cmd += " ";
  1083. cmd += "--progress-num=";
  1084. cmd += progress->Arg;
  1085. cmd += " ";
  1086. }
  1087. cmd += this->EscapeForShell(line);
  1088. }
  1089. commands.push_back(std::move(cmd));
  1090. }
  1091. // Reset the line to empty.
  1092. line.clear();
  1093. // Progress appears only on first line.
  1094. progress = nullptr;
  1095. // Terminate on end-of-string.
  1096. if (*c == '\0') {
  1097. return;
  1098. }
  1099. } else if (*c != '\r') {
  1100. // Append this character to the current line.
  1101. line += *c;
  1102. }
  1103. }
  1104. }
  1105. std::string cmLocalUnixMakefileGenerator3::CreateMakeVariable(
  1106. std::string const& s, std::string const& s2)
  1107. {
  1108. std::string unmodified = cmStrCat(s, s2);
  1109. // if there is no restriction on the length of make variables
  1110. // and there are no "." characters in the string, then return the
  1111. // unmodified combination.
  1112. if ((!this->MakefileVariableSize &&
  1113. unmodified.find('.') == std::string::npos) &&
  1114. (!this->MakefileVariableSize &&
  1115. unmodified.find('+') == std::string::npos) &&
  1116. (!this->MakefileVariableSize &&
  1117. unmodified.find('-') == std::string::npos)) {
  1118. return unmodified;
  1119. }
  1120. // see if the variable has been defined before and return
  1121. // the modified version of the variable
  1122. auto i = this->MakeVariableMap.find(unmodified);
  1123. if (i != this->MakeVariableMap.end()) {
  1124. return i->second;
  1125. }
  1126. // start with the unmodified variable
  1127. std::string ret = unmodified;
  1128. // if this there is no value for this->MakefileVariableSize then
  1129. // the string must have bad characters in it
  1130. if (!this->MakefileVariableSize) {
  1131. std::replace(ret.begin(), ret.end(), '.', '_');
  1132. cmSystemTools::ReplaceString(ret, "-", "__");
  1133. cmSystemTools::ReplaceString(ret, "+", "___");
  1134. int ni = 0;
  1135. char buffer[5];
  1136. // make sure the _ version is not already used, if
  1137. // it is used then add number to the end of the variable
  1138. while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
  1139. ++ni;
  1140. sprintf(buffer, "%04d", ni);
  1141. ret = unmodified + buffer;
  1142. }
  1143. this->ShortMakeVariableMap[ret] = "1";
  1144. this->MakeVariableMap[unmodified] = ret;
  1145. return ret;
  1146. }
  1147. // if the string is greater than 32 chars it is an invalid variable name
  1148. // for borland make
  1149. if (static_cast<int>(ret.size()) > this->MakefileVariableSize) {
  1150. int keep = this->MakefileVariableSize - 8;
  1151. int size = keep + 3;
  1152. std::string str1 = s;
  1153. std::string str2 = s2;
  1154. // we must shorten the combined string by 4 characters
  1155. // keep no more than 24 characters from the second string
  1156. if (static_cast<int>(str2.size()) > keep) {
  1157. str2 = str2.substr(0, keep);
  1158. }
  1159. if (static_cast<int>(str1.size()) + static_cast<int>(str2.size()) > size) {
  1160. str1 = str1.substr(0, size - str2.size());
  1161. }
  1162. char buffer[5];
  1163. int ni = 0;
  1164. sprintf(buffer, "%04d", ni);
  1165. ret = str1 + str2 + buffer;
  1166. while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
  1167. ++ni;
  1168. sprintf(buffer, "%04d", ni);
  1169. ret = str1 + str2 + buffer;
  1170. }
  1171. if (ni == 1000) {
  1172. cmSystemTools::Error("Borland makefile variable length too long");
  1173. return unmodified;
  1174. }
  1175. // once an unused variable is found
  1176. this->ShortMakeVariableMap[ret] = "1";
  1177. }
  1178. // always make an entry into the unmodified to variable map
  1179. this->MakeVariableMap[unmodified] = ret;
  1180. return ret;
  1181. }
  1182. bool cmLocalUnixMakefileGenerator3::UpdateDependencies(
  1183. const std::string& tgtInfo, bool verbose, bool color)
  1184. {
  1185. // read in the target info file
  1186. if (!this->Makefile->ReadListFile(tgtInfo) ||
  1187. cmSystemTools::GetErrorOccuredFlag()) {
  1188. cmSystemTools::Error("Target DependInfo.cmake file not found");
  1189. }
  1190. // Check if any multiple output pairs have a missing file.
  1191. this->CheckMultipleOutputs(verbose);
  1192. std::string const targetDir = cmSystemTools::GetFilenamePath(tgtInfo);
  1193. std::string const internalDependFile = targetDir + "/depend.internal";
  1194. std::string const dependFile = targetDir + "/depend.make";
  1195. // If the target DependInfo.cmake file has changed since the last
  1196. // time dependencies were scanned then force rescanning. This may
  1197. // happen when a new source file is added and CMake regenerates the
  1198. // project but no other sources were touched.
  1199. bool needRescanDependInfo = false;
  1200. cmFileTimeCache* ftc =
  1201. this->GlobalGenerator->GetCMakeInstance()->GetFileTimeCache();
  1202. {
  1203. int result;
  1204. if (!ftc->Compare(internalDependFile, tgtInfo, &result) || result < 0) {
  1205. if (verbose) {
  1206. cmSystemTools::Stdout(cmStrCat("Dependee \"", tgtInfo,
  1207. "\" is newer than depender \"",
  1208. internalDependFile, "\".\n"));
  1209. }
  1210. needRescanDependInfo = true;
  1211. }
  1212. }
  1213. // If the directory information is newer than depend.internal, include dirs
  1214. // may have changed. In this case discard all old dependencies.
  1215. bool needRescanDirInfo = false;
  1216. {
  1217. std::string dirInfoFile =
  1218. cmStrCat(this->GetCurrentBinaryDirectory(),
  1219. "/CMakeFiles/CMakeDirectoryInformation.cmake");
  1220. int result;
  1221. if (!ftc->Compare(internalDependFile, dirInfoFile, &result) ||
  1222. result < 0) {
  1223. if (verbose) {
  1224. cmSystemTools::Stdout(cmStrCat("Dependee \"", dirInfoFile,
  1225. "\" is newer than depender \"",
  1226. internalDependFile, "\".\n"));
  1227. }
  1228. needRescanDirInfo = true;
  1229. }
  1230. }
  1231. // Check the implicit dependencies to see if they are up to date.
  1232. // The build.make file may have explicit dependencies for the object
  1233. // files but these will not affect the scanning process so they need
  1234. // not be considered.
  1235. cmDepends::DependencyMap validDependencies;
  1236. bool needRescanDependencies = false;
  1237. if (!needRescanDirInfo) {
  1238. cmDependsC checker;
  1239. checker.SetVerbose(verbose);
  1240. checker.SetFileTimeCache(ftc);
  1241. // cmDependsC::Check() fills the vector validDependencies() with the
  1242. // dependencies for those files where they are still valid, i.e. neither
  1243. // the files themselves nor any files they depend on have changed.
  1244. // We don't do that if the CMakeDirectoryInformation.cmake file has
  1245. // changed, because then potentially all dependencies have changed.
  1246. // This information is given later on to cmDependsC, which then only
  1247. // rescans the files where it did not get valid dependencies via this
  1248. // dependency vector. This means that in the normal case, when only
  1249. // few or one file have been edited, then also only this one file is
  1250. // actually scanned again, instead of all files for this target.
  1251. needRescanDependencies =
  1252. !checker.Check(dependFile, internalDependFile, validDependencies);
  1253. }
  1254. if (needRescanDependInfo || needRescanDirInfo || needRescanDependencies) {
  1255. // The dependencies must be regenerated.
  1256. std::string targetName = cmSystemTools::GetFilenameName(targetDir);
  1257. targetName = targetName.substr(0, targetName.length() - 4);
  1258. std::string message =
  1259. cmStrCat("Scanning dependencies of target ", targetName);
  1260. cmSystemTools::MakefileColorEcho(cmsysTerminal_Color_ForegroundMagenta |
  1261. cmsysTerminal_Color_ForegroundBold,
  1262. message.c_str(), true, color);
  1263. return this->ScanDependencies(targetDir, dependFile, internalDependFile,
  1264. validDependencies);
  1265. }
  1266. // The dependencies are already up-to-date.
  1267. return true;
  1268. }
  1269. bool cmLocalUnixMakefileGenerator3::ScanDependencies(
  1270. std::string const& targetDir, std::string const& dependFile,
  1271. std::string const& internalDependFile, cmDepends::DependencyMap& validDeps)
  1272. {
  1273. // Read the directory information file.
  1274. cmMakefile* mf = this->Makefile;
  1275. bool haveDirectoryInfo = false;
  1276. {
  1277. std::string dirInfoFile =
  1278. cmStrCat(this->GetCurrentBinaryDirectory(),
  1279. "/CMakeFiles/CMakeDirectoryInformation.cmake");
  1280. if (mf->ReadListFile(dirInfoFile) &&
  1281. !cmSystemTools::GetErrorOccuredFlag()) {
  1282. haveDirectoryInfo = true;
  1283. }
  1284. }
  1285. // Lookup useful directory information.
  1286. if (haveDirectoryInfo) {
  1287. // Test whether we need to force Unix paths.
  1288. if (cmProp force = mf->GetDefinition("CMAKE_FORCE_UNIX_PATHS")) {
  1289. if (!cmIsOff(force)) {
  1290. cmSystemTools::SetForceUnixPaths(true);
  1291. }
  1292. }
  1293. // Setup relative path top directories.
  1294. if (cmProp relativePathTopSource =
  1295. mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_SOURCE")) {
  1296. this->StateSnapshot.GetDirectory().SetRelativePathTopSource(
  1297. relativePathTopSource->c_str());
  1298. }
  1299. if (cmProp relativePathTopBinary =
  1300. mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_BINARY")) {
  1301. this->StateSnapshot.GetDirectory().SetRelativePathTopBinary(
  1302. relativePathTopBinary->c_str());
  1303. }
  1304. } else {
  1305. cmSystemTools::Error("Directory Information file not found");
  1306. }
  1307. // Open the make depends file. This should be copy-if-different
  1308. // because the make tool may try to reload it needlessly otherwise.
  1309. cmGeneratedFileStream ruleFileStream(
  1310. dependFile, false, this->GlobalGenerator->GetMakefileEncoding());
  1311. ruleFileStream.SetCopyIfDifferent(true);
  1312. if (!ruleFileStream) {
  1313. return false;
  1314. }
  1315. // Open the cmake dependency tracking file. This should not be
  1316. // copy-if-different because dependencies are re-scanned when it is
  1317. // older than the DependInfo.cmake.
  1318. cmGeneratedFileStream internalRuleFileStream(
  1319. internalDependFile, false, this->GlobalGenerator->GetMakefileEncoding());
  1320. if (!internalRuleFileStream) {
  1321. return false;
  1322. }
  1323. this->WriteDisclaimer(ruleFileStream);
  1324. this->WriteDisclaimer(internalRuleFileStream);
  1325. // for each language we need to scan, scan it
  1326. std::vector<std::string> langs =
  1327. cmExpandedList(mf->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES"));
  1328. for (std::string const& lang : langs) {
  1329. // construct the checker
  1330. // Create the scanner for this language
  1331. std::unique_ptr<cmDepends> scanner;
  1332. if (lang == "C" || lang == "CXX" || lang == "RC" || lang == "ASM" ||
  1333. lang == "OBJC" || lang == "OBJCXX" || lang == "CUDA" ||
  1334. lang == "ISPC") {
  1335. // TODO: Handle RC (resource files) dependencies correctly.
  1336. scanner = cm::make_unique<cmDependsC>(this, targetDir, lang, &validDeps);
  1337. }
  1338. #ifndef CMAKE_BOOTSTRAP
  1339. else if (lang == "Fortran") {
  1340. ruleFileStream << "# Note that incremental build could trigger "
  1341. << "a call to cmake_copy_f90_mod on each re-build\n";
  1342. scanner = cm::make_unique<cmDependsFortran>(this);
  1343. } else if (lang == "Java") {
  1344. scanner = cm::make_unique<cmDependsJava>();
  1345. }
  1346. #endif
  1347. if (scanner) {
  1348. scanner->SetLocalGenerator(this);
  1349. scanner->SetFileTimeCache(
  1350. this->GlobalGenerator->GetCMakeInstance()->GetFileTimeCache());
  1351. scanner->SetLanguage(lang);
  1352. scanner->SetTargetDirectory(targetDir);
  1353. scanner->Write(ruleFileStream, internalRuleFileStream);
  1354. }
  1355. }
  1356. return true;
  1357. }
  1358. void cmLocalUnixMakefileGenerator3::CheckMultipleOutputs(bool verbose)
  1359. {
  1360. cmMakefile* mf = this->Makefile;
  1361. // Get the string listing the multiple output pairs.
  1362. cmProp pairs_string = mf->GetDefinition("CMAKE_MULTIPLE_OUTPUT_PAIRS");
  1363. if (!pairs_string) {
  1364. return;
  1365. }
  1366. // Convert the string to a list and preserve empty entries.
  1367. std::vector<std::string> pairs = cmExpandedList(*pairs_string, true);
  1368. for (auto i = pairs.begin(); i != pairs.end() && (i + 1) != pairs.end();) {
  1369. const std::string& depender = *i++;
  1370. const std::string& dependee = *i++;
  1371. // If the depender is missing then delete the dependee to make
  1372. // sure both will be regenerated.
  1373. if (cmSystemTools::FileExists(dependee) &&
  1374. !cmSystemTools::FileExists(depender)) {
  1375. if (verbose) {
  1376. cmSystemTools::Stdout(cmStrCat(
  1377. "Deleting primary custom command output \"", dependee,
  1378. "\" because another output \"", depender, "\" does not exist.\n"));
  1379. }
  1380. cmSystemTools::RemoveFile(dependee);
  1381. }
  1382. }
  1383. }
  1384. void cmLocalUnixMakefileGenerator3::WriteLocalAllRules(
  1385. std::ostream& ruleFileStream)
  1386. {
  1387. this->WriteDisclaimer(ruleFileStream);
  1388. // Write the main entry point target. This must be the VERY first
  1389. // target so that make with no arguments will run it.
  1390. {
  1391. // Just depend on the all target to drive the build.
  1392. std::vector<std::string> depends;
  1393. std::vector<std::string> no_commands;
  1394. depends.emplace_back("all");
  1395. // Write the rule.
  1396. this->WriteMakeRule(ruleFileStream,
  1397. "Default target executed when no arguments are "
  1398. "given to make.",
  1399. "default_target", depends, no_commands, true);
  1400. // Help out users that try "gmake target1 target2 -j".
  1401. cmGlobalUnixMakefileGenerator3* gg =
  1402. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1403. if (gg->AllowNotParallel()) {
  1404. std::vector<std::string> no_depends;
  1405. this->WriteMakeRule(ruleFileStream,
  1406. "Allow only one \"make -f "
  1407. "Makefile2\" at a time, but pass "
  1408. "parallelism.",
  1409. ".NOTPARALLEL", no_depends, no_commands, false);
  1410. }
  1411. }
  1412. this->WriteSpecialTargetsTop(ruleFileStream);
  1413. // Include the progress variables for the target.
  1414. // Write all global targets
  1415. this->WriteDivider(ruleFileStream);
  1416. ruleFileStream << "# Targets provided globally by CMake.\n"
  1417. << "\n";
  1418. const auto& targets = this->GetGeneratorTargets();
  1419. for (const auto& gt : targets) {
  1420. if (gt->GetType() == cmStateEnums::GLOBAL_TARGET) {
  1421. std::string targetString =
  1422. "Special rule for the target " + gt->GetName();
  1423. std::vector<std::string> commands;
  1424. std::vector<std::string> depends;
  1425. cmProp p = gt->GetProperty("EchoString");
  1426. const char* text = p ? p->c_str() : "Running external command ...";
  1427. depends.reserve(gt->GetUtilities().size());
  1428. for (BT<std::pair<std::string, bool>> const& u : gt->GetUtilities()) {
  1429. depends.push_back(u.Value.first);
  1430. }
  1431. this->AppendEcho(commands, text,
  1432. cmLocalUnixMakefileGenerator3::EchoGlobal);
  1433. // Global targets store their rules in pre- and post-build commands.
  1434. this->AppendCustomDepends(depends, gt->GetPreBuildCommands());
  1435. this->AppendCustomDepends(depends, gt->GetPostBuildCommands());
  1436. this->AppendCustomCommands(commands, gt->GetPreBuildCommands(), gt.get(),
  1437. this->GetCurrentBinaryDirectory());
  1438. this->AppendCustomCommands(commands, gt->GetPostBuildCommands(),
  1439. gt.get(), this->GetCurrentBinaryDirectory());
  1440. std::string targetName = gt->GetName();
  1441. this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
  1442. depends, commands, true);
  1443. // Provide a "/fast" version of the target.
  1444. depends.clear();
  1445. if ((targetName == "install") || (targetName == "install/local") ||
  1446. (targetName == "install/strip")) {
  1447. // Provide a fast install target that does not depend on all
  1448. // but has the same command.
  1449. depends.emplace_back("preinstall/fast");
  1450. } else {
  1451. // Just forward to the real target so at least it will work.
  1452. depends.push_back(targetName);
  1453. commands.clear();
  1454. }
  1455. targetName += "/fast";
  1456. this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
  1457. depends, commands, true);
  1458. }
  1459. }
  1460. std::vector<std::string> depends;
  1461. std::vector<std::string> commands;
  1462. // Write the all rule.
  1463. std::string recursiveTarget =
  1464. cmStrCat(this->GetCurrentBinaryDirectory(), "/all");
  1465. bool regenerate =
  1466. !this->GlobalGenerator->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION");
  1467. if (regenerate) {
  1468. depends.emplace_back("cmake_check_build_system");
  1469. }
  1470. std::string progressDir =
  1471. cmStrCat(this->GetBinaryDirectory(), "/CMakeFiles");
  1472. {
  1473. std::ostringstream progCmd;
  1474. progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start ";
  1475. progCmd << this->ConvertToOutputFormat(progressDir,
  1476. cmOutputConverter::SHELL);
  1477. std::string progressFile = "/CMakeFiles/progress.marks";
  1478. std::string progressFileNameFull = this->ConvertToFullPath(progressFile);
  1479. progCmd << " "
  1480. << this->ConvertToOutputFormat(progressFileNameFull,
  1481. cmOutputConverter::SHELL);
  1482. commands.push_back(progCmd.str());
  1483. }
  1484. std::string mf2Dir = "CMakeFiles/Makefile2";
  1485. commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
  1486. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1487. this->GetCurrentBinaryDirectory());
  1488. {
  1489. std::ostringstream progCmd;
  1490. progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; // # 0
  1491. progCmd << this->ConvertToOutputFormat(progressDir,
  1492. cmOutputConverter::SHELL);
  1493. progCmd << " 0";
  1494. commands.push_back(progCmd.str());
  1495. }
  1496. this->WriteMakeRule(ruleFileStream, "The main all target", "all", depends,
  1497. commands, true);
  1498. // Write the clean rule.
  1499. recursiveTarget = cmStrCat(this->GetCurrentBinaryDirectory(), "/clean");
  1500. commands.clear();
  1501. depends.clear();
  1502. commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
  1503. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1504. this->GetCurrentBinaryDirectory());
  1505. this->WriteMakeRule(ruleFileStream, "The main clean target", "clean",
  1506. depends, commands, true);
  1507. commands.clear();
  1508. depends.clear();
  1509. depends.emplace_back("clean");
  1510. this->WriteMakeRule(ruleFileStream, "The main clean target", "clean/fast",
  1511. depends, commands, true);
  1512. // Write the preinstall rule.
  1513. recursiveTarget = cmStrCat(this->GetCurrentBinaryDirectory(), "/preinstall");
  1514. commands.clear();
  1515. depends.clear();
  1516. cmProp noall =
  1517. this->Makefile->GetDefinition("CMAKE_SKIP_INSTALL_ALL_DEPENDENCY");
  1518. if (cmIsOff(noall)) {
  1519. // Drive the build before installing.
  1520. depends.emplace_back("all");
  1521. } else if (regenerate) {
  1522. // At least make sure the build system is up to date.
  1523. depends.emplace_back("cmake_check_build_system");
  1524. }
  1525. commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
  1526. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1527. this->GetCurrentBinaryDirectory());
  1528. this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
  1529. "preinstall", depends, commands, true);
  1530. depends.clear();
  1531. this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
  1532. "preinstall/fast", depends, commands, true);
  1533. if (regenerate) {
  1534. // write the depend rule, really a recompute depends rule
  1535. depends.clear();
  1536. commands.clear();
  1537. cmake* cm = this->GlobalGenerator->GetCMakeInstance();
  1538. if (cm->DoWriteGlobVerifyTarget()) {
  1539. std::string rescanRule =
  1540. cmStrCat("$(CMAKE_COMMAND) -P ",
  1541. this->ConvertToOutputFormat(cm->GetGlobVerifyScript(),
  1542. cmOutputConverter::SHELL));
  1543. commands.push_back(rescanRule);
  1544. }
  1545. std::string cmakefileName = "CMakeFiles/Makefile.cmake";
  1546. {
  1547. std::string runRule = cmStrCat(
  1548. "$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) "
  1549. "--check-build-system ",
  1550. this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL),
  1551. " 1");
  1552. commands.push_back(std::move(runRule));
  1553. }
  1554. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1555. this->GetCurrentBinaryDirectory());
  1556. this->WriteMakeRule(ruleFileStream, "clear depends", "depend", depends,
  1557. commands, true);
  1558. }
  1559. }
  1560. void cmLocalUnixMakefileGenerator3::ClearDependencies(cmMakefile* mf,
  1561. bool verbose)
  1562. {
  1563. // Get the list of target files to check
  1564. cmProp infoDef = mf->GetDefinition("CMAKE_DEPEND_INFO_FILES");
  1565. if (!infoDef) {
  1566. return;
  1567. }
  1568. std::vector<std::string> files = cmExpandedList(*infoDef);
  1569. // Each depend information file corresponds to a target. Clear the
  1570. // dependencies for that target.
  1571. cmDepends clearer;
  1572. clearer.SetVerbose(verbose);
  1573. for (std::string const& file : files) {
  1574. std::string dir = cmSystemTools::GetFilenamePath(file);
  1575. // Clear the implicit dependency makefile.
  1576. std::string dependFile = dir + "/depend.make";
  1577. clearer.Clear(dependFile);
  1578. // Remove the internal dependency check file to force
  1579. // regeneration.
  1580. std::string internalDependFile = dir + "/depend.internal";
  1581. cmSystemTools::RemoveFile(internalDependFile);
  1582. }
  1583. }
  1584. namespace {
  1585. // Helper predicate for removing absolute paths that don't point to the
  1586. // source or binary directory. It is used when CMAKE_DEPENDS_IN_PROJECT_ONLY
  1587. // is set ON, to only consider in-project dependencies during the build.
  1588. class NotInProjectDir
  1589. {
  1590. public:
  1591. // Constructor with the source and binary directory's path
  1592. NotInProjectDir(cm::string_view sourceDir, cm::string_view binaryDir)
  1593. : SourceDir(sourceDir)
  1594. , BinaryDir(binaryDir)
  1595. {
  1596. }
  1597. // Operator evaluating the predicate
  1598. bool operator()(const std::string& p) const
  1599. {
  1600. auto path = cmCMakePath(p).Normal();
  1601. // Keep all relative paths:
  1602. if (path.IsRelative()) {
  1603. return false;
  1604. }
  1605. // If it's an absolute path, check if it starts with the source
  1606. // directory:
  1607. return !(cmCMakePath(SourceDir).IsPrefix(path) ||
  1608. cmCMakePath(BinaryDir).IsPrefix(path));
  1609. }
  1610. private:
  1611. // The path to the source directory
  1612. cm::string_view SourceDir;
  1613. // The path to the binary directory
  1614. cm::string_view BinaryDir;
  1615. };
  1616. }
  1617. void cmLocalUnixMakefileGenerator3::WriteDependLanguageInfo(
  1618. std::ostream& cmakefileStream, cmGeneratorTarget* target)
  1619. {
  1620. ImplicitDependLanguageMap const& implicitLangs =
  1621. this->GetImplicitDepends(target);
  1622. // list the languages
  1623. cmakefileStream
  1624. << "# The set of languages for which implicit dependencies are needed:\n";
  1625. cmakefileStream << "set(CMAKE_DEPENDS_LANGUAGES\n";
  1626. for (auto const& implicitLang : implicitLangs) {
  1627. cmakefileStream << " \"" << implicitLang.first << "\"\n";
  1628. }
  1629. cmakefileStream << " )\n";
  1630. // now list the files for each language
  1631. cmakefileStream
  1632. << "# The set of files for implicit dependencies of each language:\n";
  1633. for (auto const& implicitLang : implicitLangs) {
  1634. cmakefileStream << "set(CMAKE_DEPENDS_CHECK_" << implicitLang.first
  1635. << "\n";
  1636. ImplicitDependFileMap const& implicitPairs = implicitLang.second;
  1637. // for each file pair
  1638. for (auto const& implicitPair : implicitPairs) {
  1639. for (auto const& di : implicitPair.second) {
  1640. cmakefileStream << " \"" << di << "\" ";
  1641. cmakefileStream << "\"" << implicitPair.first << "\"\n";
  1642. }
  1643. }
  1644. cmakefileStream << " )\n";
  1645. // Tell the dependency scanner what compiler is used.
  1646. std::string cidVar =
  1647. cmStrCat("CMAKE_", implicitLang.first, "_COMPILER_ID");
  1648. cmProp cid = this->Makefile->GetDefinition(cidVar);
  1649. if (cmNonempty(cid)) {
  1650. cmakefileStream << "set(CMAKE_" << implicitLang.first
  1651. << "_COMPILER_ID \"" << *cid << "\")\n";
  1652. }
  1653. if (implicitLang.first == "Fortran") {
  1654. std::string smodSep =
  1655. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_SEP");
  1656. std::string smodExt =
  1657. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_EXT");
  1658. cmakefileStream << "set(CMAKE_Fortran_SUBMODULE_SEP \"" << smodSep
  1659. << "\")\n";
  1660. cmakefileStream << "set(CMAKE_Fortran_SUBMODULE_EXT \"" << smodExt
  1661. << "\")\n";
  1662. }
  1663. // Build a list of preprocessor definitions for the target.
  1664. std::set<std::string> defines;
  1665. this->GetTargetDefines(target, this->GetConfigName(), implicitLang.first,
  1666. defines);
  1667. if (!defines.empty()) {
  1668. /* clang-format off */
  1669. cmakefileStream
  1670. << "\n"
  1671. << "# Preprocessor definitions for this target.\n"
  1672. << "set(CMAKE_TARGET_DEFINITIONS_" << implicitLang.first << "\n";
  1673. /* clang-format on */
  1674. for (std::string const& define : defines) {
  1675. cmakefileStream << " " << cmOutputConverter::EscapeForCMake(define)
  1676. << "\n";
  1677. }
  1678. cmakefileStream << " )\n";
  1679. }
  1680. // Target-specific include directories:
  1681. cmakefileStream << "\n"
  1682. << "# The include file search paths:\n";
  1683. cmakefileStream << "set(CMAKE_" << implicitLang.first
  1684. << "_TARGET_INCLUDE_PATH\n";
  1685. std::vector<std::string> includes;
  1686. this->GetIncludeDirectories(includes, target, implicitLang.first,
  1687. this->GetConfigName());
  1688. std::string const& binaryDir = this->GetState()->GetBinaryDirectory();
  1689. if (this->Makefile->IsOn("CMAKE_DEPENDS_IN_PROJECT_ONLY")) {
  1690. std::string const& sourceDir = this->GetState()->GetSourceDirectory();
  1691. cm::erase_if(includes, ::NotInProjectDir(sourceDir, binaryDir));
  1692. }
  1693. for (std::string const& include : includes) {
  1694. cmakefileStream << " \""
  1695. << this->MaybeConvertToRelativePath(binaryDir, include)
  1696. << "\"\n";
  1697. }
  1698. cmakefileStream << " )\n";
  1699. }
  1700. // Store include transform rule properties. Write the directory
  1701. // rules first because they may be overridden by later target rules.
  1702. std::vector<std::string> transformRules;
  1703. if (cmProp xform =
  1704. this->Makefile->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
  1705. cmExpandList(*xform, transformRules);
  1706. }
  1707. if (cmProp xform =
  1708. target->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
  1709. cmExpandList(*xform, transformRules);
  1710. }
  1711. if (!transformRules.empty()) {
  1712. cmakefileStream << "set(CMAKE_INCLUDE_TRANSFORMS\n";
  1713. for (std::string const& tr : transformRules) {
  1714. cmakefileStream << " " << cmOutputConverter::EscapeForCMake(tr) << "\n";
  1715. }
  1716. cmakefileStream << " )\n";
  1717. }
  1718. }
  1719. void cmLocalUnixMakefileGenerator3::WriteDisclaimer(std::ostream& os)
  1720. {
  1721. os << "# CMAKE generated file: DO NOT EDIT!\n"
  1722. << "# Generated by \"" << this->GlobalGenerator->GetName() << "\""
  1723. << " Generator, CMake Version " << cmVersion::GetMajorVersion() << "."
  1724. << cmVersion::GetMinorVersion() << "\n\n";
  1725. }
  1726. std::string cmLocalUnixMakefileGenerator3::GetRecursiveMakeCall(
  1727. const std::string& makefile, const std::string& tgt)
  1728. {
  1729. // Call make on the given file.
  1730. std::string cmd = cmStrCat(
  1731. "$(MAKE) $(MAKESILENT) -f ",
  1732. this->ConvertToOutputFormat(makefile, cmOutputConverter::SHELL), ' ');
  1733. cmGlobalUnixMakefileGenerator3* gg =
  1734. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1735. // Pass down verbosity level.
  1736. if (!gg->MakeSilentFlag.empty()) {
  1737. cmd += gg->MakeSilentFlag;
  1738. cmd += " ";
  1739. }
  1740. // Most unix makes will pass the command line flags to make down to
  1741. // sub-invoked makes via an environment variable. However, some
  1742. // makes do not support that, so you have to pass the flags
  1743. // explicitly.
  1744. if (gg->PassMakeflags) {
  1745. cmd += "-$(MAKEFLAGS) ";
  1746. }
  1747. // Add the target.
  1748. if (!tgt.empty()) {
  1749. // The make target is always relative to the top of the build tree.
  1750. std::string tgt2 =
  1751. this->MaybeConvertToRelativePath(this->GetBinaryDirectory(), tgt);
  1752. // The target may have been written with windows paths.
  1753. cmSystemTools::ConvertToOutputSlashes(tgt2);
  1754. // Escape one extra time if the make tool requires it.
  1755. if (this->MakeCommandEscapeTargetTwice) {
  1756. tgt2 = this->EscapeForShell(tgt2, true, false);
  1757. }
  1758. // The target name is now a string that should be passed verbatim
  1759. // on the command line.
  1760. cmd += this->EscapeForShell(tgt2, true, false);
  1761. }
  1762. return cmd;
  1763. }
  1764. void cmLocalUnixMakefileGenerator3::WriteDivider(std::ostream& os)
  1765. {
  1766. os << "#======================================"
  1767. "=======================================\n";
  1768. }
  1769. void cmLocalUnixMakefileGenerator3::WriteCMakeArgument(std::ostream& os,
  1770. const std::string& s)
  1771. {
  1772. // Write the given string to the stream with escaping to get it back
  1773. // into CMake through the lexical scanner.
  1774. os << '"';
  1775. for (char c : s) {
  1776. if (c == '\\') {
  1777. os << "\\\\";
  1778. } else if (c == '"') {
  1779. os << "\\\"";
  1780. } else {
  1781. os << c;
  1782. }
  1783. }
  1784. os << '"';
  1785. }
  1786. std::string cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(
  1787. const std::string& p, bool useWatcomQuote)
  1788. {
  1789. // Split the path into its components.
  1790. std::vector<std::string> components;
  1791. cmSystemTools::SplitPath(p, components);
  1792. // Open the quoted result.
  1793. std::string result;
  1794. if (useWatcomQuote) {
  1795. #if defined(_WIN32) && !defined(__CYGWIN__)
  1796. result = "'";
  1797. #else
  1798. result = "\"'";
  1799. #endif
  1800. } else {
  1801. result = "\"";
  1802. }
  1803. // Return an empty path if there are no components.
  1804. if (!components.empty()) {
  1805. // Choose a slash direction and fix root component.
  1806. const char* slash = "/";
  1807. #if defined(_WIN32) && !defined(__CYGWIN__)
  1808. if (!cmSystemTools::GetForceUnixPaths()) {
  1809. slash = "\\";
  1810. for (char& i : components[0]) {
  1811. if (i == '/') {
  1812. i = '\\';
  1813. }
  1814. }
  1815. }
  1816. #endif
  1817. // Begin the quoted result with the root component.
  1818. result += components[0];
  1819. if (components.size() > 1) {
  1820. // Now add the rest of the components separated by the proper slash
  1821. // direction for this platform.
  1822. auto compEnd = std::remove(components.begin() + 1, components.end() - 1,
  1823. std::string());
  1824. auto compStart = components.begin() + 1;
  1825. result += cmJoin(cmMakeRange(compStart, compEnd), slash);
  1826. // Only the last component can be empty to avoid double slashes.
  1827. result += slash;
  1828. result += components.back();
  1829. }
  1830. }
  1831. // Close the quoted result.
  1832. if (useWatcomQuote) {
  1833. #if defined(_WIN32) && !defined(__CYGWIN__)
  1834. result += "'";
  1835. #else
  1836. result += "'\"";
  1837. #endif
  1838. } else {
  1839. result += "\"";
  1840. }
  1841. return result;
  1842. }
  1843. std::string cmLocalUnixMakefileGenerator3::GetTargetDirectory(
  1844. cmGeneratorTarget const* target) const
  1845. {
  1846. std::string dir = cmStrCat("CMakeFiles/", target->GetName());
  1847. #if defined(__VMS)
  1848. dir += "_dir";
  1849. #else
  1850. dir += ".dir";
  1851. #endif
  1852. return dir;
  1853. }
  1854. cmLocalUnixMakefileGenerator3::ImplicitDependLanguageMap const&
  1855. cmLocalUnixMakefileGenerator3::GetImplicitDepends(
  1856. const cmGeneratorTarget* tgt, cmDependencyScannerKind scanner)
  1857. {
  1858. return this->ImplicitDepends[tgt->GetName()][scanner];
  1859. }
  1860. void cmLocalUnixMakefileGenerator3::AddImplicitDepends(
  1861. const cmGeneratorTarget* tgt, const std::string& lang,
  1862. const std::string& obj, const std::string& src,
  1863. cmDependencyScannerKind scanner)
  1864. {
  1865. this->ImplicitDepends[tgt->GetName()][scanner][lang][obj].push_back(src);
  1866. }
  1867. void cmLocalUnixMakefileGenerator3::CreateCDCommand(
  1868. std::vector<std::string>& commands, std::string const& tgtDir,
  1869. std::string const& relDir)
  1870. {
  1871. // do we need to cd?
  1872. if (tgtDir == relDir) {
  1873. return;
  1874. }
  1875. // In a Windows shell we must change drive letter too. The shell
  1876. // used by NMake and Borland make does not support "cd /d" so this
  1877. // feature simply cannot work with them (Borland make does not even
  1878. // support changing the drive letter with just "d:").
  1879. const char* cd_cmd = this->IsMinGWMake() ? "cd /d " : "cd ";
  1880. cmGlobalUnixMakefileGenerator3* gg =
  1881. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1882. if (!gg->UnixCD) {
  1883. // On Windows we must perform each step separately and then change
  1884. // back because the shell keeps the working directory between
  1885. // commands.
  1886. std::string cmd =
  1887. cmStrCat(cd_cmd, this->ConvertToOutputForExisting(tgtDir));
  1888. commands.insert(commands.begin(), cmd);
  1889. // Change back to the starting directory.
  1890. cmd = cmStrCat(cd_cmd, this->ConvertToOutputForExisting(relDir));
  1891. commands.push_back(std::move(cmd));
  1892. } else {
  1893. // On UNIX we must construct a single shell command to change
  1894. // directory and build because make resets the directory between
  1895. // each command.
  1896. std::string outputForExisting = this->ConvertToOutputForExisting(tgtDir);
  1897. std::string prefix = cd_cmd + outputForExisting + " && ";
  1898. std::transform(commands.begin(), commands.end(), commands.begin(),
  1899. [&prefix](std::string const& s) { return prefix + s; });
  1900. }
  1901. }