cmLocalUnixMakefileGenerator3.cxx 73 KB

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