cmLocalUnixMakefileGenerator3.cxx 80 KB

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