cmLocalUnixMakefileGenerator3.cxx 82 KB

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