cmLocalUnixMakefileGenerator3.cxx 72 KB

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