cmLocalUnixMakefileGenerator3.cxx 78 KB

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