1
0

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