cmLocalUnixMakefileGenerator3.cxx 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090
  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", localObjectFile.first,
  228. 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(ruleFileStream,
  248. "target to preprocess a source file",
  249. (base + ".i"), 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"), 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 std::string& 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, 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 = "CMakeFiles/";
  336. makefile2 += "Makefile2";
  337. commands.push_back(this->GetRecursiveMakeCall(makefile2, localName));
  338. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  339. this->GetCurrentBinaryDirectory());
  340. this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
  341. localName, depends, commands, true);
  342. // Add a target with the canonical name (no prefix, suffix or path).
  343. if (localName != target->GetName()) {
  344. commands.clear();
  345. depends.push_back(localName);
  346. this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
  347. target->GetName(), depends, commands, true);
  348. }
  349. // Add a fast rule to build the target
  350. std::string makefileName = this->GetRelativeTargetDirectory(target);
  351. makefileName += "/build.make";
  352. // make sure the makefile name is suitable for a makefile
  353. std::string makeTargetName = this->GetRelativeTargetDirectory(target);
  354. makeTargetName += "/build";
  355. localName = target->GetName();
  356. localName += "/fast";
  357. depends.clear();
  358. commands.clear();
  359. commands.push_back(
  360. this->GetRecursiveMakeCall(makefileName, makeTargetName));
  361. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  362. this->GetCurrentBinaryDirectory());
  363. this->WriteMakeRule(ruleFileStream, "fast build rule for target.",
  364. localName, depends, commands, true);
  365. // Add a local name for the rule to relink the target before
  366. // installation.
  367. if (target->NeedRelinkBeforeInstall(this->ConfigName)) {
  368. makeTargetName = this->GetRelativeTargetDirectory(target);
  369. makeTargetName += "/preinstall";
  370. localName = target->GetName();
  371. localName += "/preinstall";
  372. depends.clear();
  373. commands.clear();
  374. commands.push_back(
  375. this->GetRecursiveMakeCall(makefile2, makeTargetName));
  376. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  377. this->GetCurrentBinaryDirectory());
  378. this->WriteMakeRule(ruleFileStream,
  379. "Manual pre-install relink rule for target.",
  380. localName, depends, commands, true);
  381. }
  382. }
  383. }
  384. }
  385. void cmLocalUnixMakefileGenerator3::WriteDirectoryInformationFile()
  386. {
  387. std::string infoFileName = this->GetCurrentBinaryDirectory();
  388. infoFileName += "/CMakeFiles";
  389. infoFileName += "/CMakeDirectoryInformation.cmake";
  390. // Open the output file.
  391. cmGeneratedFileStream infoFileStream(infoFileName);
  392. if (!infoFileStream) {
  393. return;
  394. }
  395. infoFileStream.SetCopyIfDifferent(true);
  396. // Write the do not edit header.
  397. this->WriteDisclaimer(infoFileStream);
  398. // Setup relative path conversion tops.
  399. /* clang-format off */
  400. infoFileStream
  401. << "# Relative path conversion top directories.\n"
  402. << "set(CMAKE_RELATIVE_PATH_TOP_SOURCE \""
  403. << this->StateSnapshot.GetDirectory().GetRelativePathTopSource()
  404. << "\")\n"
  405. << "set(CMAKE_RELATIVE_PATH_TOP_BINARY \""
  406. << this->StateSnapshot.GetDirectory().GetRelativePathTopBinary()
  407. << "\")\n"
  408. << "\n";
  409. /* clang-format on */
  410. // Tell the dependency scanner to use unix paths if necessary.
  411. if (cmSystemTools::GetForceUnixPaths()) {
  412. /* clang-format off */
  413. infoFileStream
  414. << "# Force unix paths in dependencies.\n"
  415. << "set(CMAKE_FORCE_UNIX_PATHS 1)\n"
  416. << "\n";
  417. /* clang-format on */
  418. }
  419. // Store the include regular expressions for this directory.
  420. infoFileStream << "\n"
  421. << "# The C and CXX include file regular expressions for "
  422. << "this directory.\n";
  423. infoFileStream << "set(CMAKE_C_INCLUDE_REGEX_SCAN ";
  424. cmLocalUnixMakefileGenerator3::WriteCMakeArgument(
  425. infoFileStream, this->Makefile->GetIncludeRegularExpression());
  426. infoFileStream << ")\n";
  427. infoFileStream << "set(CMAKE_C_INCLUDE_REGEX_COMPLAIN ";
  428. cmLocalUnixMakefileGenerator3::WriteCMakeArgument(
  429. infoFileStream, this->Makefile->GetComplainRegularExpression());
  430. infoFileStream << ")\n";
  431. infoFileStream
  432. << "set(CMAKE_CXX_INCLUDE_REGEX_SCAN ${CMAKE_C_INCLUDE_REGEX_SCAN})\n";
  433. infoFileStream << "set(CMAKE_CXX_INCLUDE_REGEX_COMPLAIN "
  434. "${CMAKE_C_INCLUDE_REGEX_COMPLAIN})\n";
  435. }
  436. std::string cmLocalUnixMakefileGenerator3::ConvertToFullPath(
  437. const std::string& localPath)
  438. {
  439. std::string dir = this->GetCurrentBinaryDirectory();
  440. dir += "/";
  441. dir += localPath;
  442. return dir;
  443. }
  444. const std::string& cmLocalUnixMakefileGenerator3::GetHomeRelativeOutputPath()
  445. {
  446. return this->HomeRelativeOutputPath;
  447. }
  448. void cmLocalUnixMakefileGenerator3::WriteMakeRule(
  449. std::ostream& os, const char* comment, const std::string& target,
  450. const std::vector<std::string>& depends,
  451. const std::vector<std::string>& commands, bool symbolic, bool in_help)
  452. {
  453. // Make sure there is a target.
  454. if (target.empty()) {
  455. cmSystemTools::Error("No target for WriteMakeRule! called with comment: ",
  456. comment);
  457. return;
  458. }
  459. std::string replace;
  460. // Write the comment describing the rule in the makefile.
  461. if (comment) {
  462. replace = comment;
  463. std::string::size_type lpos = 0;
  464. std::string::size_type rpos;
  465. while ((rpos = replace.find('\n', lpos)) != std::string::npos) {
  466. os << "# " << replace.substr(lpos, rpos - lpos) << "\n";
  467. lpos = rpos + 1;
  468. }
  469. os << "# " << replace.substr(lpos) << "\n";
  470. }
  471. // Construct the left hand side of the rule.
  472. std::string tgt = cmSystemTools::ConvertToOutputPath(
  473. this->MaybeConvertToRelativePath(this->GetBinaryDirectory(), target));
  474. const char* space = "";
  475. if (tgt.size() == 1) {
  476. // Add a space before the ":" to avoid drive letter confusion on
  477. // Windows.
  478. space = " ";
  479. }
  480. // Mark the rule as symbolic if requested.
  481. if (symbolic) {
  482. if (const char* sym =
  483. this->Makefile->GetDefinition("CMAKE_MAKE_SYMBOLIC_RULE")) {
  484. os << cmMakeSafe(tgt) << space << ": " << sym << "\n";
  485. }
  486. }
  487. // Write the rule.
  488. if (depends.empty()) {
  489. // No dependencies. The commands will always run.
  490. os << cmMakeSafe(tgt) << space << ":\n";
  491. } else {
  492. // Split dependencies into multiple rule lines. This allows for
  493. // very long dependency lists even on older make implementations.
  494. std::string binDir = this->GetBinaryDirectory();
  495. for (std::string const& depend : depends) {
  496. replace = depend;
  497. replace = cmSystemTools::ConvertToOutputPath(
  498. this->MaybeConvertToRelativePath(binDir, replace));
  499. os << cmMakeSafe(tgt) << space << ": " << cmMakeSafe(replace) << "\n";
  500. }
  501. }
  502. // Write the list of commands.
  503. os << cmWrap("\t", commands, "", "\n") << "\n";
  504. if (symbolic && !this->IsWatcomWMake()) {
  505. os << ".PHONY : " << cmMakeSafe(tgt) << "\n";
  506. }
  507. os << "\n";
  508. // Add the output to the local help if requested.
  509. if (in_help) {
  510. this->LocalHelp.push_back(target);
  511. }
  512. }
  513. std::string cmLocalUnixMakefileGenerator3::MaybeConvertWatcomShellCommand(
  514. std::string const& cmd)
  515. {
  516. if (this->IsWatcomWMake() && cmSystemTools::FileIsFullPath(cmd) &&
  517. cmd.find_first_of("( )") != std::string::npos) {
  518. // On Watcom WMake use the windows short path for the command
  519. // name. This is needed to avoid funny quoting problems on
  520. // lines with shell redirection operators.
  521. std::string scmd;
  522. if (cmSystemTools::GetShortPath(cmd, scmd)) {
  523. return this->ConvertToOutputFormat(scmd, cmOutputConverter::SHELL);
  524. }
  525. }
  526. return std::string();
  527. }
  528. void cmLocalUnixMakefileGenerator3::WriteMakeVariables(
  529. std::ostream& makefileStream)
  530. {
  531. this->WriteDivider(makefileStream);
  532. makefileStream << "# Set environment variables for the build.\n"
  533. << "\n";
  534. cmGlobalUnixMakefileGenerator3* gg =
  535. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  536. if (gg->DefineWindowsNULL) {
  537. makefileStream << "!IF \"$(OS)\" == \"Windows_NT\"\n"
  538. << "NULL=\n"
  539. << "!ELSE\n"
  540. << "NULL=nul\n"
  541. << "!ENDIF\n";
  542. }
  543. if (this->IsWindowsShell()) {
  544. makefileStream << "SHELL = cmd.exe\n"
  545. << "\n";
  546. } else {
  547. #if !defined(__VMS)
  548. /* clang-format off */
  549. makefileStream
  550. << "# The shell in which to execute make rules.\n"
  551. << "SHELL = /bin/sh\n"
  552. << "\n";
  553. /* clang-format on */
  554. #endif
  555. }
  556. std::string cmakeShellCommand =
  557. this->MaybeConvertWatcomShellCommand(cmSystemTools::GetCMakeCommand());
  558. if (cmakeShellCommand.empty()) {
  559. cmakeShellCommand = this->ConvertToOutputFormat(
  560. cmSystemTools::CollapseFullPath(cmSystemTools::GetCMakeCommand()),
  561. cmOutputConverter::SHELL);
  562. }
  563. /* clang-format off */
  564. makefileStream
  565. << "# The CMake executable.\n"
  566. << "CMAKE_COMMAND = "
  567. << cmakeShellCommand
  568. << "\n"
  569. << "\n";
  570. makefileStream
  571. << "# The command to remove a file.\n"
  572. << "RM = "
  573. << cmakeShellCommand
  574. << " -E remove -f\n"
  575. << "\n";
  576. makefileStream
  577. << "# Escaping for special characters.\n"
  578. << "EQUALS = =\n"
  579. << "\n";
  580. makefileStream
  581. << "# The top-level source directory on which CMake was run.\n"
  582. << "CMAKE_SOURCE_DIR = "
  583. << this->ConvertToOutputFormat(
  584. cmSystemTools::CollapseFullPath(this->GetSourceDirectory()),
  585. cmOutputConverter::SHELL)
  586. << "\n"
  587. << "\n";
  588. makefileStream
  589. << "# The top-level build directory on which CMake was run.\n"
  590. << "CMAKE_BINARY_DIR = "
  591. << this->ConvertToOutputFormat(
  592. cmSystemTools::CollapseFullPath(this->GetBinaryDirectory()),
  593. cmOutputConverter::SHELL)
  594. << "\n"
  595. << "\n";
  596. /* clang-format on */
  597. }
  598. void cmLocalUnixMakefileGenerator3::WriteSpecialTargetsTop(
  599. std::ostream& makefileStream)
  600. {
  601. this->WriteDivider(makefileStream);
  602. makefileStream << "# Special targets provided by cmake.\n"
  603. << "\n";
  604. std::vector<std::string> no_commands;
  605. std::vector<std::string> no_depends;
  606. // Special target to cleanup operation of make tool.
  607. // This should be the first target except for the default_target in
  608. // the interface Makefile.
  609. this->WriteMakeRule(makefileStream,
  610. "Disable implicit rules so canonical targets will work.",
  611. ".SUFFIXES", no_depends, no_commands, false);
  612. if (!this->IsNMake() && !this->IsWatcomWMake() &&
  613. !this->BorlandMakeCurlyHack) {
  614. // turn off RCS and SCCS automatic stuff from gmake
  615. makefileStream
  616. << "# Remove some rules from gmake that .SUFFIXES does not remove.\n"
  617. << "SUFFIXES =\n\n";
  618. }
  619. // Add a fake suffix to keep HP happy. Must be max 32 chars for SGI make.
  620. std::vector<std::string> depends;
  621. depends.emplace_back(".hpux_make_needs_suffix_list");
  622. this->WriteMakeRule(makefileStream, nullptr, ".SUFFIXES", depends,
  623. no_commands, false);
  624. if (this->IsWatcomWMake()) {
  625. // Switch on WMake feature, if an error or interrupt occurs during
  626. // makefile processing, the current target being made may be deleted
  627. // without prompting (the same as command line -e option).
  628. /* clang-format off */
  629. makefileStream <<
  630. "\n"
  631. ".ERASE\n"
  632. "\n"
  633. ;
  634. /* clang-format on */
  635. }
  636. if (this->Makefile->IsOn("CMAKE_VERBOSE_MAKEFILE")) {
  637. /* clang-format off */
  638. makefileStream
  639. << "# Produce verbose output by default.\n"
  640. << "VERBOSE = 1\n"
  641. << "\n";
  642. /* clang-format on */
  643. }
  644. if (this->IsWatcomWMake()) {
  645. /* clang-format off */
  646. makefileStream <<
  647. "!ifndef VERBOSE\n"
  648. ".SILENT\n"
  649. "!endif\n"
  650. "\n"
  651. ;
  652. /* clang-format on */
  653. } else {
  654. // Write special target to silence make output. This must be after
  655. // the default target in case VERBOSE is set (which changes the
  656. // name). The setting of CMAKE_VERBOSE_MAKEFILE to ON will cause a
  657. // "VERBOSE=1" to be added as a make variable which will change the
  658. // name of this special target. This gives a make-time choice to
  659. // the user.
  660. this->WriteMakeRule(makefileStream,
  661. "Suppress display of executed commands.",
  662. "$(VERBOSE).SILENT", no_depends, no_commands, false);
  663. }
  664. // Work-around for makes that drop rules that have no dependencies
  665. // or commands.
  666. cmGlobalUnixMakefileGenerator3* gg =
  667. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  668. std::string hack = gg->GetEmptyRuleHackDepends();
  669. if (!hack.empty()) {
  670. no_depends.push_back(std::move(hack));
  671. }
  672. std::string hack_cmd = gg->GetEmptyRuleHackCommand();
  673. if (!hack_cmd.empty()) {
  674. no_commands.push_back(std::move(hack_cmd));
  675. }
  676. // Special symbolic target that never exists to force dependers to
  677. // run their rules.
  678. this->WriteMakeRule(makefileStream, "A target that is always out of date.",
  679. "cmake_force", no_depends, no_commands, true);
  680. // Variables for reference by other rules.
  681. this->WriteMakeVariables(makefileStream);
  682. }
  683. void cmLocalUnixMakefileGenerator3::WriteSpecialTargetsBottom(
  684. std::ostream& makefileStream)
  685. {
  686. this->WriteDivider(makefileStream);
  687. makefileStream << "# Special targets to cleanup operation of make.\n"
  688. << "\n";
  689. // Write special "cmake_check_build_system" target to run cmake with
  690. // the --check-build-system flag.
  691. if (!this->GlobalGenerator->GlobalSettingIsOn(
  692. "CMAKE_SUPPRESS_REGENERATION")) {
  693. // Build command to run CMake to check if anything needs regenerating.
  694. std::vector<std::string> commands;
  695. cmake* cm = this->GlobalGenerator->GetCMakeInstance();
  696. if (cm->DoWriteGlobVerifyTarget()) {
  697. std::string rescanRule = "$(CMAKE_COMMAND) -P ";
  698. rescanRule += this->ConvertToOutputFormat(cm->GetGlobVerifyScript(),
  699. cmOutputConverter::SHELL);
  700. commands.push_back(rescanRule);
  701. }
  702. std::string cmakefileName = "CMakeFiles/";
  703. cmakefileName += "Makefile.cmake";
  704. std::string runRule =
  705. "$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)";
  706. runRule += " --check-build-system ";
  707. runRule +=
  708. this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL);
  709. runRule += " 0";
  710. std::vector<std::string> no_depends;
  711. commands.push_back(std::move(runRule));
  712. if (!this->IsRootMakefile()) {
  713. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  714. this->GetCurrentBinaryDirectory());
  715. }
  716. this->WriteMakeRule(makefileStream,
  717. "Special rule to run CMake to check the build system "
  718. "integrity.\n"
  719. "No rule that depends on this can have "
  720. "commands that come from listfiles\n"
  721. "because they might be regenerated.",
  722. "cmake_check_build_system", no_depends, commands,
  723. true);
  724. }
  725. }
  726. void cmLocalUnixMakefileGenerator3::WriteConvenienceRule(
  727. std::ostream& ruleFileStream, const std::string& realTarget,
  728. const std::string& helpTarget)
  729. {
  730. // A rule is only needed if the names are different.
  731. if (realTarget != helpTarget) {
  732. // The helper target depends on the real target.
  733. std::vector<std::string> depends;
  734. depends.push_back(realTarget);
  735. // There are no commands.
  736. std::vector<std::string> no_commands;
  737. // Write the rule.
  738. this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
  739. helpTarget, depends, no_commands, true);
  740. }
  741. }
  742. std::string cmLocalUnixMakefileGenerator3::GetRelativeTargetDirectory(
  743. cmGeneratorTarget* target)
  744. {
  745. std::string dir = this->HomeRelativeOutputPath;
  746. dir += this->GetTargetDirectory(target);
  747. return dir;
  748. }
  749. void cmLocalUnixMakefileGenerator3::AppendFlags(
  750. std::string& flags, const std::string& newFlags) const
  751. {
  752. if (this->IsWatcomWMake() && !newFlags.empty()) {
  753. std::string newf = newFlags;
  754. if (newf.find("\\\"") != std::string::npos) {
  755. cmSystemTools::ReplaceString(newf, "\\\"", "\"");
  756. this->cmLocalGenerator::AppendFlags(flags, newf);
  757. return;
  758. }
  759. }
  760. this->cmLocalGenerator::AppendFlags(flags, newFlags);
  761. }
  762. void cmLocalUnixMakefileGenerator3::AppendFlags(std::string& flags,
  763. const char* newFlags) const
  764. {
  765. this->cmLocalGenerator::AppendFlags(flags, newFlags);
  766. }
  767. void cmLocalUnixMakefileGenerator3::AppendRuleDepend(
  768. std::vector<std::string>& depends, const char* ruleFileName)
  769. {
  770. // Add a dependency on the rule file itself unless an option to skip
  771. // it is specifically enabled by the user or project.
  772. const char* nodep =
  773. this->Makefile->GetDefinition("CMAKE_SKIP_RULE_DEPENDENCY");
  774. if (!nodep || cmSystemTools::IsOff(nodep)) {
  775. depends.emplace_back(ruleFileName);
  776. }
  777. }
  778. void cmLocalUnixMakefileGenerator3::AppendRuleDepends(
  779. std::vector<std::string>& depends, std::vector<std::string> const& ruleFiles)
  780. {
  781. // Add a dependency on the rule file itself unless an option to skip
  782. // it is specifically enabled by the user or project.
  783. if (!this->Makefile->IsOn("CMAKE_SKIP_RULE_DEPENDENCY")) {
  784. depends.insert(depends.end(), ruleFiles.begin(), ruleFiles.end());
  785. }
  786. }
  787. void cmLocalUnixMakefileGenerator3::AppendCustomDepends(
  788. std::vector<std::string>& depends, const std::vector<cmCustomCommand>& ccs)
  789. {
  790. for (cmCustomCommand const& cc : ccs) {
  791. cmCustomCommandGenerator ccg(cc, this->ConfigName, this);
  792. this->AppendCustomDepend(depends, ccg);
  793. }
  794. }
  795. void cmLocalUnixMakefileGenerator3::AppendCustomDepend(
  796. std::vector<std::string>& depends, cmCustomCommandGenerator const& ccg)
  797. {
  798. for (std::string const& d : ccg.GetDepends()) {
  799. // Lookup the real name of the dependency in case it is a CMake target.
  800. std::string dep;
  801. if (this->GetRealDependency(d, this->ConfigName, dep)) {
  802. depends.push_back(std::move(dep));
  803. }
  804. }
  805. }
  806. void cmLocalUnixMakefileGenerator3::AppendCustomCommands(
  807. std::vector<std::string>& commands, const std::vector<cmCustomCommand>& ccs,
  808. cmGeneratorTarget* target, std::string const& relative)
  809. {
  810. for (cmCustomCommand const& cc : ccs) {
  811. cmCustomCommandGenerator ccg(cc, this->ConfigName, this);
  812. this->AppendCustomCommand(commands, ccg, target, relative, true);
  813. }
  814. }
  815. void cmLocalUnixMakefileGenerator3::AppendCustomCommand(
  816. std::vector<std::string>& commands, cmCustomCommandGenerator const& ccg,
  817. cmGeneratorTarget* target, std::string const& relative, bool echo_comment,
  818. std::ostream* content)
  819. {
  820. // Optionally create a command to display the custom command's
  821. // comment text. This is used for pre-build, pre-link, and
  822. // post-build command comments. Custom build step commands have
  823. // their comments generated elsewhere.
  824. if (echo_comment) {
  825. const char* comment = ccg.GetComment();
  826. if (comment && *comment) {
  827. this->AppendEcho(commands, comment,
  828. cmLocalUnixMakefileGenerator3::EchoGenerate);
  829. }
  830. }
  831. // if the command specified a working directory use it.
  832. std::string dir = this->GetCurrentBinaryDirectory();
  833. std::string workingDir = ccg.GetWorkingDirectory();
  834. if (!workingDir.empty()) {
  835. dir = workingDir;
  836. }
  837. if (content) {
  838. *content << dir;
  839. }
  840. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  841. this->CreateRulePlaceholderExpander());
  842. // Add each command line to the set of commands.
  843. std::vector<std::string> commands1;
  844. std::string currentBinDir = this->GetCurrentBinaryDirectory();
  845. for (unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) {
  846. // Build the command line in a single string.
  847. std::string cmd = ccg.GetCommand(c);
  848. if (!cmd.empty()) {
  849. // Use "call " before any invocations of .bat or .cmd files
  850. // invoked as custom commands in the WindowsShell.
  851. //
  852. bool useCall = false;
  853. if (this->IsWindowsShell()) {
  854. std::string suffix;
  855. if (cmd.size() > 4) {
  856. suffix = cmSystemTools::LowerCase(cmd.substr(cmd.size() - 4));
  857. if (suffix == ".bat" || suffix == ".cmd") {
  858. useCall = true;
  859. }
  860. }
  861. }
  862. cmSystemTools::ReplaceString(cmd, "/./", "/");
  863. // Convert the command to a relative path only if the current
  864. // working directory will be the start-output directory.
  865. bool had_slash = cmd.find('/') != std::string::npos;
  866. if (workingDir.empty()) {
  867. cmd = this->MaybeConvertToRelativePath(currentBinDir, cmd);
  868. }
  869. bool has_slash = cmd.find('/') != std::string::npos;
  870. if (had_slash && !has_slash) {
  871. // This command was specified as a path to a file in the
  872. // current directory. Add a leading "./" so it can run
  873. // without the current directory being in the search path.
  874. cmd = "./" + cmd;
  875. }
  876. std::string launcher;
  877. // Short-circuit if there is no launcher.
  878. const char* val = this->GetRuleLauncher(target, "RULE_LAUNCH_CUSTOM");
  879. if (val && *val) {
  880. // Expand rule variables referenced in the given launcher command.
  881. cmRulePlaceholderExpander::RuleVariables vars;
  882. vars.CMTargetName = target->GetName().c_str();
  883. vars.CMTargetType = cmState::GetTargetTypeName(target->GetType());
  884. std::string output;
  885. const std::vector<std::string>& outputs = ccg.GetOutputs();
  886. if (!outputs.empty()) {
  887. output = outputs[0];
  888. if (workingDir.empty()) {
  889. output = this->MaybeConvertToRelativePath(
  890. this->GetCurrentBinaryDirectory(), output);
  891. }
  892. output =
  893. this->ConvertToOutputFormat(output, cmOutputConverter::SHELL);
  894. }
  895. vars.Output = output.c_str();
  896. launcher = val;
  897. rulePlaceholderExpander->ExpandRuleVariables(this, launcher, vars);
  898. if (!launcher.empty()) {
  899. launcher += " ";
  900. }
  901. }
  902. std::string shellCommand = this->MaybeConvertWatcomShellCommand(cmd);
  903. if (shellCommand.empty()) {
  904. shellCommand =
  905. this->ConvertToOutputFormat(cmd, cmOutputConverter::SHELL);
  906. }
  907. cmd = launcher + shellCommand;
  908. ccg.AppendArguments(c, cmd);
  909. if (content) {
  910. // Rule content does not include the launcher.
  911. *content << (cmd.c_str() + launcher.size());
  912. }
  913. if (this->BorlandMakeCurlyHack) {
  914. // Borland Make has a very strange bug. If the first curly
  915. // brace anywhere in the command string is a left curly, it
  916. // must be written {{} instead of just {. Otherwise some
  917. // curly braces are removed. The hack can be skipped if the
  918. // first curly brace is the last character.
  919. std::string::size_type lcurly = cmd.find('{');
  920. if (lcurly != std::string::npos && lcurly < (cmd.size() - 1)) {
  921. std::string::size_type rcurly = cmd.find('}');
  922. if (rcurly == std::string::npos || rcurly > lcurly) {
  923. // The first curly is a left curly. Use the hack.
  924. std::string hack_cmd = cmd.substr(0, lcurly);
  925. hack_cmd += "{{}";
  926. hack_cmd += cmd.substr(lcurly + 1);
  927. cmd = hack_cmd;
  928. }
  929. }
  930. }
  931. if (launcher.empty()) {
  932. if (useCall) {
  933. cmd = "call " + cmd;
  934. } else if (this->IsNMake() && cmd[0] == '"') {
  935. cmd = "echo >nul && " + cmd;
  936. }
  937. }
  938. commands1.push_back(std::move(cmd));
  939. }
  940. }
  941. // Setup the proper working directory for the commands.
  942. this->CreateCDCommand(commands1, dir, relative);
  943. // push back the custom commands
  944. commands.insert(commands.end(), commands1.begin(), commands1.end());
  945. }
  946. void cmLocalUnixMakefileGenerator3::AppendCleanCommand(
  947. std::vector<std::string>& commands, const std::vector<std::string>& files,
  948. cmGeneratorTarget* target, const char* filename)
  949. {
  950. std::string currentBinDir = this->GetCurrentBinaryDirectory();
  951. std::string cleanfile = currentBinDir;
  952. cleanfile += "/";
  953. cleanfile += this->GetTargetDirectory(target);
  954. cleanfile += "/cmake_clean";
  955. if (filename) {
  956. cleanfile += "_";
  957. cleanfile += filename;
  958. }
  959. cleanfile += ".cmake";
  960. std::string cleanfilePath = cmSystemTools::CollapseFullPath(cleanfile);
  961. cmsys::ofstream fout(cleanfilePath.c_str());
  962. if (!fout) {
  963. cmSystemTools::Error("Could not create ", cleanfilePath.c_str());
  964. }
  965. if (!files.empty()) {
  966. fout << "file(REMOVE_RECURSE\n";
  967. for (std::string const& file : files) {
  968. std::string fc = this->MaybeConvertToRelativePath(currentBinDir, file);
  969. fout << " " << cmOutputConverter::EscapeForCMake(fc) << "\n";
  970. }
  971. fout << ")\n";
  972. }
  973. {
  974. std::string remove = "$(CMAKE_COMMAND) -P ";
  975. remove += this->ConvertToOutputFormat(
  976. this->MaybeConvertToRelativePath(this->GetCurrentBinaryDirectory(),
  977. cleanfile),
  978. cmOutputConverter::SHELL);
  979. commands.push_back(std::move(remove));
  980. }
  981. // For the main clean rule add per-language cleaning.
  982. if (!filename) {
  983. // Get the set of source languages in the target.
  984. std::set<std::string> languages;
  985. target->GetLanguages(
  986. languages, this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
  987. /* clang-format off */
  988. fout << "\n"
  989. << "# Per-language clean rules from dependency scanning.\n"
  990. << "foreach(lang " << cmJoin(languages, " ") << ")\n"
  991. << " include(" << this->GetTargetDirectory(target)
  992. << "/cmake_clean_${lang}.cmake OPTIONAL)\n"
  993. << "endforeach()\n";
  994. /* clang-format on */
  995. }
  996. }
  997. void cmLocalUnixMakefileGenerator3::AppendEcho(
  998. std::vector<std::string>& commands, std::string const& text, EchoColor color,
  999. EchoProgress const* progress)
  1000. {
  1001. // Choose the color for the text.
  1002. std::string color_name;
  1003. if (this->GlobalGenerator->GetToolSupportsColor() && this->ColorMakefile) {
  1004. // See cmake::ExecuteEchoColor in cmake.cxx for these options.
  1005. // This color set is readable on both black and white backgrounds.
  1006. switch (color) {
  1007. case EchoNormal:
  1008. break;
  1009. case EchoDepend:
  1010. color_name = "--magenta --bold ";
  1011. break;
  1012. case EchoBuild:
  1013. color_name = "--green ";
  1014. break;
  1015. case EchoLink:
  1016. color_name = "--green --bold ";
  1017. break;
  1018. case EchoGenerate:
  1019. color_name = "--blue --bold ";
  1020. break;
  1021. case EchoGlobal:
  1022. color_name = "--cyan ";
  1023. break;
  1024. }
  1025. }
  1026. // Echo one line at a time.
  1027. std::string line;
  1028. line.reserve(200);
  1029. for (const char* c = text.c_str();; ++c) {
  1030. if (*c == '\n' || *c == '\0') {
  1031. // Avoid writing a blank last line on end-of-string.
  1032. if (*c != '\0' || !line.empty()) {
  1033. // Add a command to echo this line.
  1034. std::string cmd;
  1035. if (color_name.empty() && !progress) {
  1036. // Use the native echo command.
  1037. cmd = "@echo ";
  1038. cmd += this->EscapeForShell(line, false, true);
  1039. } else {
  1040. // Use cmake to echo the text in color.
  1041. cmd = "@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) ";
  1042. cmd += color_name;
  1043. if (progress) {
  1044. cmd += "--progress-dir=";
  1045. cmd += this->ConvertToOutputFormat(
  1046. cmSystemTools::CollapseFullPath(progress->Dir),
  1047. cmOutputConverter::SHELL);
  1048. cmd += " ";
  1049. cmd += "--progress-num=";
  1050. cmd += progress->Arg;
  1051. cmd += " ";
  1052. }
  1053. cmd += this->EscapeForShell(line);
  1054. }
  1055. commands.push_back(std::move(cmd));
  1056. }
  1057. // Reset the line to empty.
  1058. line.clear();
  1059. // Progress appears only on first line.
  1060. progress = nullptr;
  1061. // Terminate on end-of-string.
  1062. if (*c == '\0') {
  1063. return;
  1064. }
  1065. } else if (*c != '\r') {
  1066. // Append this character to the current line.
  1067. line += *c;
  1068. }
  1069. }
  1070. }
  1071. std::string cmLocalUnixMakefileGenerator3::CreateMakeVariable(
  1072. std::string const& s, std::string const& s2)
  1073. {
  1074. std::string unmodified = s;
  1075. unmodified += s2;
  1076. // if there is no restriction on the length of make variables
  1077. // and there are no "." characters in the string, then return the
  1078. // unmodified combination.
  1079. if ((!this->MakefileVariableSize &&
  1080. unmodified.find('.') == std::string::npos) &&
  1081. (!this->MakefileVariableSize &&
  1082. unmodified.find('+') == std::string::npos) &&
  1083. (!this->MakefileVariableSize &&
  1084. unmodified.find('-') == std::string::npos)) {
  1085. return unmodified;
  1086. }
  1087. // see if the variable has been defined before and return
  1088. // the modified version of the variable
  1089. std::map<std::string, std::string>::iterator i =
  1090. this->MakeVariableMap.find(unmodified);
  1091. if (i != this->MakeVariableMap.end()) {
  1092. return i->second;
  1093. }
  1094. // start with the unmodified variable
  1095. std::string ret = unmodified;
  1096. // if this there is no value for this->MakefileVariableSize then
  1097. // the string must have bad characters in it
  1098. if (!this->MakefileVariableSize) {
  1099. std::replace(ret.begin(), ret.end(), '.', '_');
  1100. cmSystemTools::ReplaceString(ret, "-", "__");
  1101. cmSystemTools::ReplaceString(ret, "+", "___");
  1102. int ni = 0;
  1103. char buffer[5];
  1104. // make sure the _ version is not already used, if
  1105. // it is used then add number to the end of the variable
  1106. while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
  1107. ++ni;
  1108. sprintf(buffer, "%04d", ni);
  1109. ret = unmodified + buffer;
  1110. }
  1111. this->ShortMakeVariableMap[ret] = "1";
  1112. this->MakeVariableMap[unmodified] = ret;
  1113. return ret;
  1114. }
  1115. // if the string is greater than 32 chars it is an invalid variable name
  1116. // for borland make
  1117. if (static_cast<int>(ret.size()) > this->MakefileVariableSize) {
  1118. int keep = this->MakefileVariableSize - 8;
  1119. int size = keep + 3;
  1120. std::string str1 = s;
  1121. std::string str2 = s2;
  1122. // we must shorten the combined string by 4 characters
  1123. // keep no more than 24 characters from the second string
  1124. if (static_cast<int>(str2.size()) > keep) {
  1125. str2 = str2.substr(0, keep);
  1126. }
  1127. if (static_cast<int>(str1.size()) + static_cast<int>(str2.size()) > size) {
  1128. str1 = str1.substr(0, size - str2.size());
  1129. }
  1130. char buffer[5];
  1131. int ni = 0;
  1132. sprintf(buffer, "%04d", ni);
  1133. ret = str1 + str2 + buffer;
  1134. while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
  1135. ++ni;
  1136. sprintf(buffer, "%04d", ni);
  1137. ret = str1 + str2 + buffer;
  1138. }
  1139. if (ni == 1000) {
  1140. cmSystemTools::Error("Borland makefile variable length too long");
  1141. return unmodified;
  1142. }
  1143. // once an unused variable is found
  1144. this->ShortMakeVariableMap[ret] = "1";
  1145. }
  1146. // always make an entry into the unmodified to variable map
  1147. this->MakeVariableMap[unmodified] = ret;
  1148. return ret;
  1149. }
  1150. bool cmLocalUnixMakefileGenerator3::UpdateDependencies(
  1151. const std::string& tgtInfo, bool verbose, bool color)
  1152. {
  1153. // read in the target info file
  1154. if (!this->Makefile->ReadListFile(tgtInfo) ||
  1155. cmSystemTools::GetErrorOccuredFlag()) {
  1156. cmSystemTools::Error("Target DependInfo.cmake file not found");
  1157. }
  1158. // Check if any multiple output pairs have a missing file.
  1159. this->CheckMultipleOutputs(verbose);
  1160. std::string dir = cmSystemTools::GetFilenamePath(tgtInfo);
  1161. std::string internalDependFile = dir + "/depend.internal";
  1162. std::string dependFile = dir + "/depend.make";
  1163. // If the target DependInfo.cmake file has changed since the last
  1164. // time dependencies were scanned then force rescanning. This may
  1165. // happen when a new source file is added and CMake regenerates the
  1166. // project but no other sources were touched.
  1167. bool needRescanDependInfo = false;
  1168. cmFileTimeComparison* ftc =
  1169. this->GlobalGenerator->GetCMakeInstance()->GetFileComparison();
  1170. {
  1171. int result;
  1172. if (!ftc->FileTimeCompare(internalDependFile, tgtInfo, &result) ||
  1173. result < 0) {
  1174. if (verbose) {
  1175. std::ostringstream msg;
  1176. msg << "Dependee \"" << tgtInfo << "\" is newer than depender \""
  1177. << internalDependFile << "\"." << std::endl;
  1178. cmSystemTools::Stdout(msg.str());
  1179. }
  1180. needRescanDependInfo = true;
  1181. }
  1182. }
  1183. // If the directory information is newer than depend.internal, include dirs
  1184. // may have changed. In this case discard all old dependencies.
  1185. bool needRescanDirInfo = false;
  1186. std::string dirInfoFile = this->GetCurrentBinaryDirectory();
  1187. dirInfoFile += "/CMakeFiles";
  1188. dirInfoFile += "/CMakeDirectoryInformation.cmake";
  1189. {
  1190. int result;
  1191. if (!ftc->FileTimeCompare(internalDependFile, dirInfoFile, &result) ||
  1192. result < 0) {
  1193. if (verbose) {
  1194. std::ostringstream msg;
  1195. msg << "Dependee \"" << dirInfoFile << "\" is newer than depender \""
  1196. << internalDependFile << "\"." << std::endl;
  1197. cmSystemTools::Stdout(msg.str());
  1198. }
  1199. needRescanDirInfo = true;
  1200. }
  1201. }
  1202. // Check the implicit dependencies to see if they are up to date.
  1203. // The build.make file may have explicit dependencies for the object
  1204. // files but these will not affect the scanning process so they need
  1205. // not be considered.
  1206. std::map<std::string, cmDepends::DependencyVector> validDependencies;
  1207. bool needRescanDependencies = false;
  1208. if (!needRescanDirInfo) {
  1209. cmDependsC checker;
  1210. checker.SetVerbose(verbose);
  1211. checker.SetFileComparison(ftc);
  1212. // cmDependsC::Check() fills the vector validDependencies() with the
  1213. // dependencies for those files where they are still valid, i.e. neither
  1214. // the files themselves nor any files they depend on have changed.
  1215. // We don't do that if the CMakeDirectoryInformation.cmake file has
  1216. // changed, because then potentially all dependencies have changed.
  1217. // This information is given later on to cmDependsC, which then only
  1218. // rescans the files where it did not get valid dependencies via this
  1219. // dependency vector. This means that in the normal case, when only
  1220. // few or one file have been edited, then also only this one file is
  1221. // actually scanned again, instead of all files for this target.
  1222. needRescanDependencies =
  1223. !checker.Check(dependFile, internalDependFile, validDependencies);
  1224. }
  1225. if (needRescanDependInfo || needRescanDirInfo || needRescanDependencies) {
  1226. // The dependencies must be regenerated.
  1227. std::string targetName = cmSystemTools::GetFilenameName(dir);
  1228. targetName = targetName.substr(0, targetName.length() - 4);
  1229. std::string message = "Scanning dependencies of target ";
  1230. message += targetName;
  1231. cmSystemTools::MakefileColorEcho(cmsysTerminal_Color_ForegroundMagenta |
  1232. cmsysTerminal_Color_ForegroundBold,
  1233. message.c_str(), true, color);
  1234. return this->ScanDependencies(dir, validDependencies);
  1235. }
  1236. // The dependencies are already up-to-date.
  1237. return true;
  1238. }
  1239. bool cmLocalUnixMakefileGenerator3::ScanDependencies(
  1240. const std::string& targetDir,
  1241. std::map<std::string, cmDepends::DependencyVector>& validDeps)
  1242. {
  1243. // Read the directory information file.
  1244. cmMakefile* mf = this->Makefile;
  1245. bool haveDirectoryInfo = false;
  1246. std::string dirInfoFile = this->GetCurrentBinaryDirectory();
  1247. dirInfoFile += "/CMakeFiles";
  1248. dirInfoFile += "/CMakeDirectoryInformation.cmake";
  1249. if (mf->ReadListFile(dirInfoFile) && !cmSystemTools::GetErrorOccuredFlag()) {
  1250. haveDirectoryInfo = true;
  1251. }
  1252. // Lookup useful directory information.
  1253. if (haveDirectoryInfo) {
  1254. // Test whether we need to force Unix paths.
  1255. if (const char* force = mf->GetDefinition("CMAKE_FORCE_UNIX_PATHS")) {
  1256. if (!cmSystemTools::IsOff(force)) {
  1257. cmSystemTools::SetForceUnixPaths(true);
  1258. }
  1259. }
  1260. // Setup relative path top directories.
  1261. if (const char* relativePathTopSource =
  1262. mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_SOURCE")) {
  1263. this->StateSnapshot.GetDirectory().SetRelativePathTopSource(
  1264. relativePathTopSource);
  1265. }
  1266. if (const char* relativePathTopBinary =
  1267. mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_BINARY")) {
  1268. this->StateSnapshot.GetDirectory().SetRelativePathTopBinary(
  1269. relativePathTopBinary);
  1270. }
  1271. } else {
  1272. cmSystemTools::Error("Directory Information file not found");
  1273. }
  1274. // Open the make depends file. This should be copy-if-different
  1275. // because the make tool may try to reload it needlessly otherwise.
  1276. std::string ruleFileNameFull = targetDir;
  1277. ruleFileNameFull += "/depend.make";
  1278. cmGeneratedFileStream ruleFileStream(
  1279. ruleFileNameFull, false, this->GlobalGenerator->GetMakefileEncoding());
  1280. ruleFileStream.SetCopyIfDifferent(true);
  1281. if (!ruleFileStream) {
  1282. return false;
  1283. }
  1284. // Open the cmake dependency tracking file. This should not be
  1285. // copy-if-different because dependencies are re-scanned when it is
  1286. // older than the DependInfo.cmake.
  1287. std::string internalRuleFileNameFull = targetDir;
  1288. internalRuleFileNameFull += "/depend.internal";
  1289. cmGeneratedFileStream internalRuleFileStream(
  1290. internalRuleFileNameFull, false,
  1291. this->GlobalGenerator->GetMakefileEncoding());
  1292. if (!internalRuleFileStream) {
  1293. return false;
  1294. }
  1295. this->WriteDisclaimer(ruleFileStream);
  1296. this->WriteDisclaimer(internalRuleFileStream);
  1297. // for each language we need to scan, scan it
  1298. std::string const& langStr =
  1299. mf->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES");
  1300. std::vector<std::string> langs;
  1301. cmSystemTools::ExpandListArgument(langStr, langs);
  1302. for (std::string const& lang : langs) {
  1303. // construct the checker
  1304. // Create the scanner for this language
  1305. cmDepends* scanner = nullptr;
  1306. if (lang == "C" || lang == "CXX" || lang == "RC" || lang == "ASM" ||
  1307. lang == "CUDA") {
  1308. // TODO: Handle RC (resource files) dependencies correctly.
  1309. scanner = new cmDependsC(this, targetDir, lang, &validDeps);
  1310. }
  1311. #ifdef CMAKE_BUILD_WITH_CMAKE
  1312. else if (lang == "Fortran") {
  1313. ruleFileStream << "# Note that incremental build could trigger "
  1314. << "a call to cmake_copy_f90_mod on each re-build\n";
  1315. scanner = new cmDependsFortran(this);
  1316. } else if (lang == "Java") {
  1317. scanner = new cmDependsJava();
  1318. }
  1319. #endif
  1320. if (scanner) {
  1321. scanner->SetLocalGenerator(this);
  1322. scanner->SetFileComparison(
  1323. this->GlobalGenerator->GetCMakeInstance()->GetFileComparison());
  1324. scanner->SetLanguage(lang);
  1325. scanner->SetTargetDirectory(targetDir);
  1326. scanner->Write(ruleFileStream, internalRuleFileStream);
  1327. // free the scanner for this language
  1328. delete scanner;
  1329. }
  1330. }
  1331. return true;
  1332. }
  1333. void cmLocalUnixMakefileGenerator3::CheckMultipleOutputs(bool verbose)
  1334. {
  1335. cmMakefile* mf = this->Makefile;
  1336. // Get the string listing the multiple output pairs.
  1337. const char* pairs_string = mf->GetDefinition("CMAKE_MULTIPLE_OUTPUT_PAIRS");
  1338. if (!pairs_string) {
  1339. return;
  1340. }
  1341. // Convert the string to a list and preserve empty entries.
  1342. std::vector<std::string> pairs;
  1343. cmSystemTools::ExpandListArgument(pairs_string, pairs, true);
  1344. for (std::vector<std::string>::const_iterator i = pairs.begin();
  1345. i != pairs.end() && (i + 1) != pairs.end();) {
  1346. const std::string& depender = *i++;
  1347. const std::string& dependee = *i++;
  1348. // If the depender is missing then delete the dependee to make
  1349. // sure both will be regenerated.
  1350. if (cmSystemTools::FileExists(dependee) &&
  1351. !cmSystemTools::FileExists(depender)) {
  1352. if (verbose) {
  1353. std::ostringstream msg;
  1354. msg << "Deleting primary custom command output \"" << dependee
  1355. << "\" because another output \"" << depender
  1356. << "\" does not exist." << std::endl;
  1357. cmSystemTools::Stdout(msg.str());
  1358. }
  1359. cmSystemTools::RemoveFile(dependee);
  1360. }
  1361. }
  1362. }
  1363. void cmLocalUnixMakefileGenerator3::WriteLocalAllRules(
  1364. std::ostream& ruleFileStream)
  1365. {
  1366. this->WriteDisclaimer(ruleFileStream);
  1367. // Write the main entry point target. This must be the VERY first
  1368. // target so that make with no arguments will run it.
  1369. {
  1370. // Just depend on the all target to drive the build.
  1371. std::vector<std::string> depends;
  1372. std::vector<std::string> no_commands;
  1373. depends.emplace_back("all");
  1374. // Write the rule.
  1375. this->WriteMakeRule(ruleFileStream,
  1376. "Default target executed when no arguments are "
  1377. "given to make.",
  1378. "default_target", depends, no_commands, true);
  1379. // Help out users that try "gmake target1 target2 -j".
  1380. cmGlobalUnixMakefileGenerator3* gg =
  1381. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1382. if (gg->AllowNotParallel()) {
  1383. std::vector<std::string> no_depends;
  1384. this->WriteMakeRule(ruleFileStream,
  1385. "Allow only one \"make -f "
  1386. "Makefile2\" at a time, but pass "
  1387. "parallelism.",
  1388. ".NOTPARALLEL", no_depends, no_commands, false);
  1389. }
  1390. }
  1391. this->WriteSpecialTargetsTop(ruleFileStream);
  1392. // Include the progress variables for the target.
  1393. // Write all global targets
  1394. this->WriteDivider(ruleFileStream);
  1395. ruleFileStream << "# Targets provided globally by CMake.\n"
  1396. << "\n";
  1397. const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
  1398. for (cmGeneratorTarget* gt : targets) {
  1399. if (gt->GetType() == cmStateEnums::GLOBAL_TARGET) {
  1400. std::string targetString =
  1401. "Special rule for the target " + gt->GetName();
  1402. std::vector<std::string> commands;
  1403. std::vector<std::string> depends;
  1404. const char* text = gt->GetProperty("EchoString");
  1405. if (!text) {
  1406. text = "Running external command ...";
  1407. }
  1408. depends.reserve(gt->GetUtilities().size());
  1409. for (BT<std::string> const& u : gt->GetUtilities()) {
  1410. depends.push_back(u.Value);
  1411. }
  1412. this->AppendEcho(commands, text,
  1413. cmLocalUnixMakefileGenerator3::EchoGlobal);
  1414. // Global targets store their rules in pre- and post-build commands.
  1415. this->AppendCustomDepends(depends, gt->GetPreBuildCommands());
  1416. this->AppendCustomDepends(depends, gt->GetPostBuildCommands());
  1417. this->AppendCustomCommands(commands, gt->GetPreBuildCommands(), gt,
  1418. this->GetCurrentBinaryDirectory());
  1419. this->AppendCustomCommands(commands, gt->GetPostBuildCommands(), gt,
  1420. this->GetCurrentBinaryDirectory());
  1421. std::string targetName = gt->GetName();
  1422. this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
  1423. depends, commands, true);
  1424. // Provide a "/fast" version of the target.
  1425. depends.clear();
  1426. if ((targetName == "install") || (targetName == "install/local") ||
  1427. (targetName == "install/strip")) {
  1428. // Provide a fast install target that does not depend on all
  1429. // but has the same command.
  1430. depends.emplace_back("preinstall/fast");
  1431. } else {
  1432. // Just forward to the real target so at least it will work.
  1433. depends.push_back(targetName);
  1434. commands.clear();
  1435. }
  1436. targetName += "/fast";
  1437. this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
  1438. depends, commands, true);
  1439. }
  1440. }
  1441. std::vector<std::string> depends;
  1442. std::vector<std::string> commands;
  1443. // Write the all rule.
  1444. std::string recursiveTarget = this->GetCurrentBinaryDirectory();
  1445. recursiveTarget += "/all";
  1446. bool regenerate =
  1447. !this->GlobalGenerator->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION");
  1448. if (regenerate) {
  1449. depends.emplace_back("cmake_check_build_system");
  1450. }
  1451. std::string progressDir = this->GetBinaryDirectory();
  1452. progressDir += "/CMakeFiles";
  1453. {
  1454. std::ostringstream progCmd;
  1455. progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start ";
  1456. progCmd << this->ConvertToOutputFormat(
  1457. cmSystemTools::CollapseFullPath(progressDir), cmOutputConverter::SHELL);
  1458. std::string progressFile = "/CMakeFiles";
  1459. progressFile += "/progress.marks";
  1460. std::string progressFileNameFull = this->ConvertToFullPath(progressFile);
  1461. progCmd << " "
  1462. << this->ConvertToOutputFormat(
  1463. cmSystemTools::CollapseFullPath(progressFileNameFull),
  1464. cmOutputConverter::SHELL);
  1465. commands.push_back(progCmd.str());
  1466. }
  1467. std::string mf2Dir = "CMakeFiles/";
  1468. mf2Dir += "Makefile2";
  1469. commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
  1470. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1471. this->GetCurrentBinaryDirectory());
  1472. {
  1473. std::ostringstream progCmd;
  1474. progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; // # 0
  1475. progCmd << this->ConvertToOutputFormat(
  1476. cmSystemTools::CollapseFullPath(progressDir), cmOutputConverter::SHELL);
  1477. progCmd << " 0";
  1478. commands.push_back(progCmd.str());
  1479. }
  1480. this->WriteMakeRule(ruleFileStream, "The main all target", "all", depends,
  1481. commands, true);
  1482. // Write the clean rule.
  1483. recursiveTarget = this->GetCurrentBinaryDirectory();
  1484. recursiveTarget += "/clean";
  1485. commands.clear();
  1486. depends.clear();
  1487. commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
  1488. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1489. this->GetCurrentBinaryDirectory());
  1490. this->WriteMakeRule(ruleFileStream, "The main clean target", "clean",
  1491. depends, commands, true);
  1492. commands.clear();
  1493. depends.clear();
  1494. depends.emplace_back("clean");
  1495. this->WriteMakeRule(ruleFileStream, "The main clean target", "clean/fast",
  1496. depends, commands, true);
  1497. // Write the preinstall rule.
  1498. recursiveTarget = this->GetCurrentBinaryDirectory();
  1499. recursiveTarget += "/preinstall";
  1500. commands.clear();
  1501. depends.clear();
  1502. const char* noall =
  1503. this->Makefile->GetDefinition("CMAKE_SKIP_INSTALL_ALL_DEPENDENCY");
  1504. if (!noall || cmSystemTools::IsOff(noall)) {
  1505. // Drive the build before installing.
  1506. depends.emplace_back("all");
  1507. } else if (regenerate) {
  1508. // At least make sure the build system is up to date.
  1509. depends.emplace_back("cmake_check_build_system");
  1510. }
  1511. commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
  1512. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1513. this->GetCurrentBinaryDirectory());
  1514. this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
  1515. "preinstall", depends, commands, true);
  1516. depends.clear();
  1517. this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
  1518. "preinstall/fast", depends, commands, true);
  1519. if (regenerate) {
  1520. // write the depend rule, really a recompute depends rule
  1521. depends.clear();
  1522. commands.clear();
  1523. cmake* cm = this->GlobalGenerator->GetCMakeInstance();
  1524. if (cm->DoWriteGlobVerifyTarget()) {
  1525. std::string rescanRule = "$(CMAKE_COMMAND) -P ";
  1526. rescanRule += this->ConvertToOutputFormat(cm->GetGlobVerifyScript(),
  1527. cmOutputConverter::SHELL);
  1528. commands.push_back(rescanRule);
  1529. }
  1530. std::string cmakefileName = "CMakeFiles/";
  1531. cmakefileName += "Makefile.cmake";
  1532. {
  1533. std::string runRule =
  1534. "$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)";
  1535. runRule += " --check-build-system ";
  1536. runRule +=
  1537. this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL);
  1538. runRule += " 1";
  1539. commands.push_back(std::move(runRule));
  1540. }
  1541. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1542. this->GetCurrentBinaryDirectory());
  1543. this->WriteMakeRule(ruleFileStream, "clear depends", "depend", depends,
  1544. commands, true);
  1545. }
  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);
  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(std::string sourceDir, std::string binaryDir)
  1581. : SourceDir(std::move(sourceDir))
  1582. , BinaryDir(std::move(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->GetTargetDefines(target, this->ConfigName, implicitLang.first,
  1657. defines);
  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. std::string const& 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 std::string& 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 std::string& 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 = "CMakeFiles/";
  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,
  1856. const std::string& obj, const std::string& src)
  1857. {
  1858. this->ImplicitDepends[tgt->GetName()][lang][obj].push_back(src);
  1859. }
  1860. void cmLocalUnixMakefileGenerator3::CreateCDCommand(
  1861. std::vector<std::string>& commands, std::string const& 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 (!this->GetStateSnapshot().GetDirectory().ContainsBoth(base, path)) {
  1900. return path;
  1901. }
  1902. return cmSystemTools::ForceToRelativePath(base, path);
  1903. }