cmLocalUnixMakefileGenerator3.cxx 73 KB

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