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