cmLocalUnixMakefileGenerator3.cxx 73 KB

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