cmLocalUnixMakefileGenerator3.cxx 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299
  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. auto langFileDir = cmSystemTools::GetFilenamePath(
  1041. this->MaybeRelativeToCurBinDir(cleanfile));
  1042. /* clang-format off */
  1043. fout << "\n"
  1044. "# Per-language clean rules from dependency scanning.\n"
  1045. "foreach(lang " << cmJoin(languages, " ") << ")\n"
  1046. " include(" << langFileDir
  1047. << "/cmake_clean_${lang}.cmake OPTIONAL)\n"
  1048. "endforeach()\n";
  1049. /* clang-format on */
  1050. }
  1051. }
  1052. void cmLocalUnixMakefileGenerator3::AppendDirectoryCleanCommand(
  1053. std::vector<std::string>& commands)
  1054. {
  1055. cmList cleanFiles;
  1056. // Look for additional files registered for cleaning in this directory.
  1057. if (cmValue prop_value =
  1058. this->Makefile->GetProperty("ADDITIONAL_CLEAN_FILES")) {
  1059. cleanFiles.assign(cmGeneratorExpression::Evaluate(
  1060. *prop_value, this,
  1061. this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE")));
  1062. }
  1063. if (cleanFiles.empty()) {
  1064. return;
  1065. }
  1066. auto const& rootLG = this->GetGlobalGenerator()->GetLocalGenerators().at(0);
  1067. std::string const& currentBinaryDir = this->GetCurrentBinaryDirectory();
  1068. std::string cleanfile =
  1069. cmStrCat(currentBinaryDir, "/CMakeFiles/cmake_directory_clean.cmake");
  1070. // Write clean script
  1071. {
  1072. cmsys::ofstream fout(cleanfile.c_str());
  1073. if (!fout) {
  1074. cmSystemTools::Error("Could not create " + cleanfile);
  1075. return;
  1076. }
  1077. fout << "file(REMOVE_RECURSE\n";
  1078. for (std::string const& cfl : cleanFiles) {
  1079. std::string fc = rootLG->MaybeRelativeToCurBinDir(
  1080. cmSystemTools::CollapseFullPath(cfl, currentBinaryDir));
  1081. fout << " " << cmOutputConverter::EscapeForCMake(fc) << '\n';
  1082. }
  1083. fout << ")\n";
  1084. }
  1085. // Create command
  1086. {
  1087. std::string remove = cmStrCat(
  1088. "$(CMAKE_COMMAND) -P ",
  1089. this->ConvertToOutputFormat(rootLG->MaybeRelativeToCurBinDir(cleanfile),
  1090. cmOutputConverter::SHELL));
  1091. commands.push_back(std::move(remove));
  1092. }
  1093. }
  1094. void cmLocalUnixMakefileGenerator3::AppendEcho(
  1095. std::vector<std::string>& commands, std::string const& text, EchoColor color,
  1096. EchoProgress const* progress)
  1097. {
  1098. // Choose the color for the text.
  1099. std::string color_name;
  1100. if (this->GlobalGenerator->GetToolSupportsColor() && this->ColorMakefile) {
  1101. // See cmake::ExecuteEchoColor in cmake.cxx for these options.
  1102. // This color set is readable on both black and white backgrounds.
  1103. switch (color) {
  1104. case EchoNormal:
  1105. break;
  1106. case EchoDepend:
  1107. color_name = "--magenta --bold ";
  1108. break;
  1109. case EchoBuild:
  1110. color_name = "--green ";
  1111. break;
  1112. case EchoLink:
  1113. color_name = "--green --bold ";
  1114. break;
  1115. case EchoGenerate:
  1116. color_name = "--blue --bold ";
  1117. break;
  1118. case EchoGlobal:
  1119. color_name = "--cyan ";
  1120. break;
  1121. }
  1122. }
  1123. // Echo one line at a time.
  1124. std::string line;
  1125. line.reserve(200);
  1126. for (char const* c = text.c_str();; ++c) {
  1127. if (*c == '\n' || *c == '\0') {
  1128. // Avoid writing a blank last line on end-of-string.
  1129. if (*c != '\0' || !line.empty()) {
  1130. // Add a command to echo this line.
  1131. std::string cmd;
  1132. if (color_name.empty() && !progress) {
  1133. // Use the native echo command.
  1134. cmd = cmStrCat("@echo ", this->EscapeForShell(line, false, true));
  1135. } else {
  1136. // Use cmake to echo the text in color.
  1137. cmd = cmStrCat(
  1138. "@$(CMAKE_COMMAND) -E cmake_echo_color \"--switch=$(COLOR)\" ",
  1139. color_name);
  1140. if (progress) {
  1141. cmd = cmStrCat(cmd, "--progress-dir=",
  1142. this->ConvertToOutputFormat(
  1143. progress->Dir, cmOutputConverter::SHELL),
  1144. " --progress-num=", progress->Arg, ' ');
  1145. }
  1146. cmd += this->EscapeForShell(line);
  1147. }
  1148. commands.emplace_back(std::move(cmd));
  1149. }
  1150. // Reset the line to empty.
  1151. line.clear();
  1152. // Progress appears only on first line.
  1153. progress = nullptr;
  1154. // Terminate on end-of-string.
  1155. if (*c == '\0') {
  1156. return;
  1157. }
  1158. } else if (*c != '\r') {
  1159. // Append this character to the current line.
  1160. line += *c;
  1161. }
  1162. }
  1163. }
  1164. std::string cmLocalUnixMakefileGenerator3::CreateMakeVariable(
  1165. std::string const& s, std::string const& s2)
  1166. {
  1167. std::string unmodified = cmStrCat(s, s2);
  1168. // if there is no restriction on the length of make variables
  1169. // and there are no "." characters in the string, then return the
  1170. // unmodified combination.
  1171. if ((!this->MakefileVariableSize &&
  1172. unmodified.find('.') == std::string::npos) &&
  1173. (!this->MakefileVariableSize &&
  1174. unmodified.find('+') == std::string::npos) &&
  1175. (!this->MakefileVariableSize &&
  1176. unmodified.find('-') == std::string::npos)) {
  1177. return unmodified;
  1178. }
  1179. // see if the variable has been defined before and return
  1180. // the modified version of the variable
  1181. auto i = this->MakeVariableMap.find(unmodified);
  1182. if (i != this->MakeVariableMap.end()) {
  1183. return i->second;
  1184. }
  1185. // start with the unmodified variable
  1186. std::string ret = unmodified;
  1187. // if this there is no value for this->MakefileVariableSize then
  1188. // the string must have bad characters in it
  1189. if (!this->MakefileVariableSize) {
  1190. std::replace(ret.begin(), ret.end(), '.', '_');
  1191. cmSystemTools::ReplaceString(ret, "-", "__");
  1192. cmSystemTools::ReplaceString(ret, "+", "___");
  1193. int ni = 0;
  1194. char buffer[12];
  1195. // make sure the _ version is not already used, if
  1196. // it is used then add number to the end of the variable
  1197. while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
  1198. ++ni;
  1199. snprintf(buffer, sizeof(buffer), "%04d", ni);
  1200. ret = unmodified + buffer;
  1201. }
  1202. this->ShortMakeVariableMap[ret] = "1";
  1203. this->MakeVariableMap[unmodified] = ret;
  1204. return ret;
  1205. }
  1206. // if the string is greater than 32 chars it is an invalid variable name
  1207. // for borland make
  1208. if (static_cast<int>(ret.size()) > this->MakefileVariableSize) {
  1209. int keep = this->MakefileVariableSize - 8;
  1210. int size = keep + 3;
  1211. std::string str1 = s;
  1212. std::string str2 = s2;
  1213. // we must shorten the combined string by 4 characters
  1214. // keep no more than 24 characters from the second string
  1215. if (static_cast<int>(str2.size()) > keep) {
  1216. str2 = str2.substr(0, keep);
  1217. }
  1218. if (static_cast<int>(str1.size()) + static_cast<int>(str2.size()) > size) {
  1219. str1 = str1.substr(0, size - str2.size());
  1220. }
  1221. char buffer[12];
  1222. int ni = 0;
  1223. snprintf(buffer, sizeof(buffer), "%04d", ni);
  1224. ret = str1 + str2 + buffer;
  1225. while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
  1226. ++ni;
  1227. snprintf(buffer, sizeof(buffer), "%04d", ni);
  1228. ret = str1 + str2 + buffer;
  1229. }
  1230. if (ni == 1000) {
  1231. cmSystemTools::Error("Borland makefile variable length too long");
  1232. return unmodified;
  1233. }
  1234. // once an unused variable is found
  1235. this->ShortMakeVariableMap[ret] = "1";
  1236. }
  1237. // always make an entry into the unmodified to variable map
  1238. this->MakeVariableMap[unmodified] = ret;
  1239. return ret;
  1240. }
  1241. bool cmLocalUnixMakefileGenerator3::UpdateDependencies(
  1242. std::string const& tgtInfo, bool verbose, bool color)
  1243. {
  1244. // read in the target info file
  1245. if (!this->Makefile->ReadListFile(tgtInfo) ||
  1246. cmSystemTools::GetErrorOccurredFlag()) {
  1247. cmSystemTools::Error("Target DependInfo.cmake file not found");
  1248. }
  1249. bool status = true;
  1250. // Check if any multiple output pairs have a missing file.
  1251. this->CheckMultipleOutputs(verbose);
  1252. auto echoColor = [color](std::string const& m) {
  1253. cm::StdIo::TermAttrSet attrs;
  1254. if (color) {
  1255. attrs = {
  1256. cm::StdIo::TermAttr::ForegroundMagenta,
  1257. cm::StdIo::TermAttr::ForegroundBold,
  1258. };
  1259. }
  1260. Print(cm::StdIo::Out(), attrs, m);
  1261. std::cout << std::endl;
  1262. };
  1263. std::string const targetDir = cmSystemTools::GetFilenamePath(tgtInfo);
  1264. if (!this->Makefile->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES").empty()) {
  1265. // dependencies are managed by CMake itself
  1266. std::string const internalDependFile = targetDir + "/depend.internal";
  1267. std::string const dependFile = targetDir + "/depend.make";
  1268. // If the target DependInfo.cmake file has changed since the last
  1269. // time dependencies were scanned then force rescanning. This may
  1270. // happen when a new source file is added and CMake regenerates the
  1271. // project but no other sources were touched.
  1272. bool needRescanDependInfo = false;
  1273. cmFileTimeCache* ftc =
  1274. this->GlobalGenerator->GetCMakeInstance()->GetFileTimeCache();
  1275. {
  1276. int result;
  1277. if (!ftc->Compare(internalDependFile, tgtInfo, &result) || result < 0) {
  1278. if (verbose) {
  1279. cmSystemTools::Stdout(cmStrCat("Dependee \"", tgtInfo,
  1280. "\" is newer than depender \"",
  1281. internalDependFile, "\".\n"));
  1282. }
  1283. needRescanDependInfo = true;
  1284. }
  1285. }
  1286. // If the directory information is newer than depend.internal, include
  1287. // dirs may have changed. In this case discard all old dependencies.
  1288. bool needRescanDirInfo = false;
  1289. {
  1290. std::string dirInfoFile =
  1291. cmStrCat(this->GetCurrentBinaryDirectory(),
  1292. "/CMakeFiles/CMakeDirectoryInformation.cmake");
  1293. int result;
  1294. if (!ftc->Compare(internalDependFile, dirInfoFile, &result) ||
  1295. result < 0) {
  1296. if (verbose) {
  1297. cmSystemTools::Stdout(cmStrCat("Dependee \"", dirInfoFile,
  1298. "\" is newer than depender \"",
  1299. internalDependFile, "\".\n"));
  1300. }
  1301. needRescanDirInfo = true;
  1302. }
  1303. }
  1304. // Check the implicit dependencies to see if they are up to date.
  1305. // The build.make file may have explicit dependencies for the object
  1306. // files but these will not affect the scanning process so they need
  1307. // not be considered.
  1308. cmDepends::DependencyMap validDependencies;
  1309. bool needRescanDependencies = false;
  1310. if (!needRescanDirInfo) {
  1311. cmDependsC checker;
  1312. checker.SetVerbose(verbose);
  1313. checker.SetFileTimeCache(ftc);
  1314. // cmDependsC::Check() fills the vector validDependencies() with the
  1315. // dependencies for those files where they are still valid, i.e.
  1316. // neither the files themselves nor any files they depend on have
  1317. // changed. We don't do that if the CMakeDirectoryInformation.cmake
  1318. // file has changed, because then potentially all dependencies have
  1319. // changed. This information is given later on to cmDependsC, which
  1320. // then only rescans the files where it did not get valid dependencies
  1321. // via this dependency vector. This means that in the normal case, when
  1322. // only few or one file have been edited, then also only this one file
  1323. // is actually scanned again, instead of all files for this target.
  1324. needRescanDependencies =
  1325. !checker.Check(dependFile, internalDependFile, validDependencies);
  1326. }
  1327. if (needRescanDependInfo || needRescanDirInfo || needRescanDependencies) {
  1328. // The dependencies must be regenerated.
  1329. if (verbose) {
  1330. std::string targetName = cmSystemTools::GetFilenameName(targetDir);
  1331. targetName = targetName.substr(0, targetName.length() - 4);
  1332. std::string message =
  1333. cmStrCat("Scanning dependencies of target ", targetName);
  1334. echoColor(message);
  1335. }
  1336. status = this->ScanDependencies(targetDir, dependFile,
  1337. internalDependFile, validDependencies);
  1338. }
  1339. }
  1340. auto depends =
  1341. this->Makefile->GetSafeDefinition("CMAKE_DEPENDS_DEPENDENCY_FILES");
  1342. if (!depends.empty()) {
  1343. // dependencies are managed by compiler
  1344. cmList depFiles{ depends, cmList::EmptyElements::Yes };
  1345. std::string const internalDepFile =
  1346. targetDir + "/compiler_depend.internal";
  1347. std::string const depFile = targetDir + "/compiler_depend.make";
  1348. cmDepends::DependencyMap dependencies;
  1349. cmDependsCompiler depsManager;
  1350. bool projectOnly = cmIsOn(
  1351. this->Makefile->GetSafeDefinition("CMAKE_DEPENDS_IN_PROJECT_ONLY"));
  1352. depsManager.SetVerbose(verbose);
  1353. depsManager.SetLocalGenerator(this);
  1354. if (!depsManager.CheckDependencies(
  1355. internalDepFile, depFiles, dependencies,
  1356. projectOnly ? NotInProjectDir(this->GetSourceDirectory(),
  1357. this->GetBinaryDirectory())
  1358. : std::function<bool(std::string const&)>())) {
  1359. // regenerate dependencies files
  1360. if (verbose) {
  1361. std::string targetName = cmCMakePath(targetDir)
  1362. .GetFileName()
  1363. .RemoveExtension()
  1364. .GenericString();
  1365. auto message =
  1366. cmStrCat("Consolidate compiler generated dependencies of target ",
  1367. targetName);
  1368. echoColor(message);
  1369. }
  1370. // Open the make depends file. This should be copy-if-different
  1371. // because the make tool may try to reload it needlessly otherwise.
  1372. cmGeneratedFileStream ruleFileStream(
  1373. depFile, false, this->GlobalGenerator->GetMakefileEncoding());
  1374. ruleFileStream.SetCopyIfDifferent(true);
  1375. if (!ruleFileStream) {
  1376. return false;
  1377. }
  1378. // Open the cmake dependency tracking file. This should not be
  1379. // copy-if-different because dependencies are re-scanned when it is
  1380. // older than the DependInfo.cmake.
  1381. cmGeneratedFileStream internalRuleFileStream(
  1382. internalDepFile, false, this->GlobalGenerator->GetMakefileEncoding());
  1383. if (!internalRuleFileStream) {
  1384. return false;
  1385. }
  1386. this->WriteDisclaimer(ruleFileStream);
  1387. this->WriteDisclaimer(internalRuleFileStream);
  1388. depsManager.WriteDependencies(dependencies, ruleFileStream,
  1389. internalRuleFileStream);
  1390. }
  1391. }
  1392. // The dependencies are already up-to-date.
  1393. return status;
  1394. }
  1395. bool cmLocalUnixMakefileGenerator3::ScanDependencies(
  1396. std::string const& targetDir, std::string const& dependFile,
  1397. std::string const& internalDependFile, cmDepends::DependencyMap& validDeps)
  1398. {
  1399. // Read the directory information file.
  1400. cmMakefile* mf = this->Makefile;
  1401. bool haveDirectoryInfo = false;
  1402. {
  1403. std::string dirInfoFile =
  1404. cmStrCat(this->GetCurrentBinaryDirectory(),
  1405. "/CMakeFiles/CMakeDirectoryInformation.cmake");
  1406. if (mf->ReadListFile(dirInfoFile) &&
  1407. !cmSystemTools::GetErrorOccurredFlag()) {
  1408. haveDirectoryInfo = true;
  1409. }
  1410. }
  1411. // Lookup useful directory information.
  1412. if (haveDirectoryInfo) {
  1413. // Test whether we need to force Unix paths.
  1414. if (cmValue force = mf->GetDefinition("CMAKE_FORCE_UNIX_PATHS")) {
  1415. if (!force.IsOff()) {
  1416. cmSystemTools::SetForceUnixPaths(true);
  1417. }
  1418. }
  1419. // Setup relative path top directories.
  1420. cmValue relativePathTopSource =
  1421. mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_SOURCE");
  1422. cmValue relativePathTopBinary =
  1423. mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_BINARY");
  1424. if (relativePathTopSource && relativePathTopBinary) {
  1425. this->SetRelativePathTop(*relativePathTopSource, *relativePathTopBinary);
  1426. }
  1427. } else {
  1428. cmSystemTools::Error("Directory Information file not found");
  1429. }
  1430. // Open the make depends file. This should be copy-if-different
  1431. // because the make tool may try to reload it needlessly otherwise.
  1432. cmGeneratedFileStream ruleFileStream(
  1433. dependFile, false, this->GlobalGenerator->GetMakefileEncoding());
  1434. ruleFileStream.SetCopyIfDifferent(true);
  1435. if (!ruleFileStream) {
  1436. return false;
  1437. }
  1438. // Open the cmake dependency tracking file. This should not be
  1439. // copy-if-different because dependencies are re-scanned when it is
  1440. // older than the DependInfo.cmake.
  1441. cmGeneratedFileStream internalRuleFileStream(
  1442. internalDependFile, false, this->GlobalGenerator->GetMakefileEncoding());
  1443. if (!internalRuleFileStream) {
  1444. return false;
  1445. }
  1446. this->WriteDisclaimer(ruleFileStream);
  1447. this->WriteDisclaimer(internalRuleFileStream);
  1448. // for each language we need to scan, scan it
  1449. cmList langs{ mf->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES") };
  1450. for (std::string const& lang : langs) {
  1451. // construct the checker
  1452. // Create the scanner for this language
  1453. std::unique_ptr<cmDepends> scanner;
  1454. if (lang == "C" || lang == "CXX" || lang == "RC" || lang == "ASM" ||
  1455. lang == "OBJC" || lang == "OBJCXX" || lang == "CUDA" ||
  1456. lang == "HIP" || lang == "ISPC") {
  1457. // TODO: Handle RC (resource files) dependencies correctly.
  1458. scanner = cm::make_unique<cmDependsC>(this, targetDir, lang, &validDeps);
  1459. }
  1460. #ifndef CMAKE_BOOTSTRAP
  1461. else if (lang == "Fortran") {
  1462. ruleFileStream << "# Note that incremental build could trigger "
  1463. "a call to cmake_copy_f90_mod on each re-build\n";
  1464. scanner = cm::make_unique<cmDependsFortran>(this);
  1465. } else if (lang == "Java") {
  1466. scanner = cm::make_unique<cmDependsJava>();
  1467. }
  1468. #endif
  1469. if (scanner) {
  1470. scanner->SetLocalGenerator(this);
  1471. scanner->SetFileTimeCache(
  1472. this->GlobalGenerator->GetCMakeInstance()->GetFileTimeCache());
  1473. scanner->SetLanguage(lang);
  1474. scanner->SetTargetDirectory(targetDir);
  1475. scanner->Write(ruleFileStream, internalRuleFileStream);
  1476. }
  1477. }
  1478. return true;
  1479. }
  1480. void cmLocalUnixMakefileGenerator3::CheckMultipleOutputs(bool verbose)
  1481. {
  1482. cmMakefile* mf = this->Makefile;
  1483. // Get the string listing the multiple output pairs.
  1484. cmValue pairs_string = mf->GetDefinition("CMAKE_MULTIPLE_OUTPUT_PAIRS");
  1485. if (!pairs_string) {
  1486. return;
  1487. }
  1488. // Convert the string to a list and preserve empty entries.
  1489. cmList pairs{ *pairs_string, cmList::EmptyElements::Yes };
  1490. for (auto i = pairs.begin(); i != pairs.end() && (i + 1) != pairs.end();) {
  1491. std::string const& depender = *i++;
  1492. std::string const& dependee = *i++;
  1493. // If the depender is missing then delete the dependee to make
  1494. // sure both will be regenerated.
  1495. if (cmSystemTools::FileExists(dependee) &&
  1496. !cmSystemTools::FileExists(depender)) {
  1497. if (verbose) {
  1498. cmSystemTools::Stdout(cmStrCat(
  1499. "Deleting primary custom command output \"", dependee,
  1500. "\" because another output \"", depender, "\" does not exist.\n"));
  1501. }
  1502. cmSystemTools::RemoveFile(dependee);
  1503. }
  1504. }
  1505. }
  1506. void cmLocalUnixMakefileGenerator3::WriteLocalAllRules(
  1507. std::ostream& ruleFileStream)
  1508. {
  1509. this->WriteDisclaimer(ruleFileStream);
  1510. // Write the main entry point target. This must be the VERY first
  1511. // target so that make with no arguments will run it.
  1512. {
  1513. // Just depend on the all target to drive the build.
  1514. std::vector<std::string> depends;
  1515. std::vector<std::string> no_commands;
  1516. depends.emplace_back("all");
  1517. // Write the rule.
  1518. this->WriteMakeRule(ruleFileStream,
  1519. "Default target executed when no arguments are "
  1520. "given to make.",
  1521. "default_target", depends, no_commands, true);
  1522. // Help out users that try "gmake target1 target2 -j".
  1523. cmGlobalUnixMakefileGenerator3* gg =
  1524. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1525. if (gg->AllowNotParallel()) {
  1526. std::vector<std::string> no_depends;
  1527. this->WriteMakeRule(ruleFileStream,
  1528. "Allow only one \"make -f "
  1529. "Makefile2\" at a time, but pass "
  1530. "parallelism.",
  1531. ".NOTPARALLEL", no_depends, no_commands, false);
  1532. }
  1533. }
  1534. this->WriteSpecialTargetsTop(ruleFileStream);
  1535. // Include the progress variables for the target.
  1536. // Write all global targets
  1537. this->WriteDivider(ruleFileStream);
  1538. ruleFileStream << "# Targets provided globally by CMake.\n"
  1539. "\n";
  1540. auto const& targets = this->GetGeneratorTargets();
  1541. for (auto const& gt : targets) {
  1542. if (gt->GetType() == cmStateEnums::GLOBAL_TARGET) {
  1543. std::string targetString =
  1544. "Special rule for the target " + gt->GetName();
  1545. std::vector<std::string> commands;
  1546. std::vector<std::string> depends;
  1547. cmValue p = gt->GetProperty("EchoString");
  1548. char const* text = p ? p->c_str() : "Running external command ...";
  1549. depends.reserve(gt->GetUtilities().size());
  1550. for (BT<std::pair<std::string, bool>> const& u : gt->GetUtilities()) {
  1551. depends.push_back(u.Value.first);
  1552. }
  1553. this->AppendEcho(commands, text,
  1554. cmLocalUnixMakefileGenerator3::EchoGlobal);
  1555. // Global targets store their rules in pre- and post-build commands.
  1556. this->AppendCustomDepends(depends, gt->GetPreBuildCommands());
  1557. this->AppendCustomDepends(depends, gt->GetPostBuildCommands());
  1558. this->AppendCustomCommands(commands, gt->GetPreBuildCommands(), gt.get(),
  1559. this->GetCurrentBinaryDirectory());
  1560. this->AppendCustomCommands(commands, gt->GetPostBuildCommands(),
  1561. gt.get(), this->GetCurrentBinaryDirectory());
  1562. std::string targetName = gt->GetName();
  1563. this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
  1564. depends, commands, true);
  1565. // Provide a "/fast" version of the target.
  1566. depends.clear();
  1567. if ((targetName == "install") || (targetName == "install/local") ||
  1568. (targetName == "install/strip")) {
  1569. // Provide a fast install target that does not depend on all
  1570. // but has the same command.
  1571. depends.emplace_back("preinstall/fast");
  1572. } else {
  1573. // Just forward to the real target so at least it will work.
  1574. depends.push_back(targetName);
  1575. commands.clear();
  1576. }
  1577. targetName += "/fast";
  1578. this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
  1579. depends, commands, true);
  1580. }
  1581. }
  1582. std::vector<std::string> depends;
  1583. std::vector<std::string> commands;
  1584. // Write the all rule.
  1585. std::string recursiveTarget =
  1586. cmStrCat(this->GetCurrentBinaryDirectory(), "/all");
  1587. bool regenerate =
  1588. !this->GlobalGenerator->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION");
  1589. if (regenerate) {
  1590. depends.emplace_back("cmake_check_build_system");
  1591. }
  1592. std::string const progressDir = this->ConvertToOutputFormat(
  1593. cmStrCat(this->GetBinaryDirectory(), "/CMakeFiles"),
  1594. cmOutputConverter::SHELL);
  1595. std::string const progressMarks = this->ConvertToOutputFormat(
  1596. this->ConvertToFullPath("/CMakeFiles/progress.marks"),
  1597. cmOutputConverter::SHELL);
  1598. std::string const progressStartCommand =
  1599. cmStrCat("$(CMAKE_COMMAND) -E cmake_progress_start ", progressDir, ' ',
  1600. progressMarks);
  1601. std::string const progressFinishCommand =
  1602. cmStrCat("$(CMAKE_COMMAND) -E cmake_progress_start ", progressDir, " 0");
  1603. commands.emplace_back(progressStartCommand);
  1604. std::string mf2Dir = "CMakeFiles/Makefile2";
  1605. commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
  1606. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1607. this->GetCurrentBinaryDirectory());
  1608. commands.emplace_back(progressFinishCommand);
  1609. this->WriteMakeRule(ruleFileStream, "The main all target", "all", depends,
  1610. commands, true);
  1611. // Write the codegen rule.
  1612. if (this->GetGlobalGenerator()->CheckCMP0171()) {
  1613. recursiveTarget = cmStrCat(this->GetCurrentBinaryDirectory(), "/codegen");
  1614. depends.clear();
  1615. commands.clear();
  1616. if (regenerate) {
  1617. depends.emplace_back("cmake_check_build_system");
  1618. }
  1619. commands.emplace_back(progressStartCommand);
  1620. commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
  1621. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1622. this->GetCurrentBinaryDirectory());
  1623. commands.emplace_back(progressFinishCommand);
  1624. this->WriteMakeRule(ruleFileStream, "The main codegen target", "codegen",
  1625. depends, commands, true);
  1626. }
  1627. // Write the clean rule.
  1628. recursiveTarget = cmStrCat(this->GetCurrentBinaryDirectory(), "/clean");
  1629. commands.clear();
  1630. depends.clear();
  1631. commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
  1632. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1633. this->GetCurrentBinaryDirectory());
  1634. this->WriteMakeRule(ruleFileStream, "The main clean target", "clean",
  1635. depends, commands, true);
  1636. commands.clear();
  1637. depends.clear();
  1638. depends.emplace_back("clean");
  1639. this->WriteMakeRule(ruleFileStream, "The main clean target", "clean/fast",
  1640. depends, commands, true);
  1641. // Write the preinstall rule.
  1642. recursiveTarget = cmStrCat(this->GetCurrentBinaryDirectory(), "/preinstall");
  1643. commands.clear();
  1644. depends.clear();
  1645. cmValue noall =
  1646. this->Makefile->GetDefinition("CMAKE_SKIP_INSTALL_ALL_DEPENDENCY");
  1647. if (noall.IsOff()) {
  1648. // Drive the build before installing.
  1649. depends.emplace_back("all");
  1650. } else if (regenerate) {
  1651. // At least make sure the build system is up to date.
  1652. depends.emplace_back("cmake_check_build_system");
  1653. }
  1654. commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
  1655. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1656. this->GetCurrentBinaryDirectory());
  1657. this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
  1658. "preinstall", depends, commands, true);
  1659. depends.clear();
  1660. this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
  1661. "preinstall/fast", depends, commands, true);
  1662. if (regenerate) {
  1663. // write the depend rule, really a recompute depends rule
  1664. depends.clear();
  1665. commands.clear();
  1666. cmake* cm = this->GlobalGenerator->GetCMakeInstance();
  1667. if (cm->DoWriteGlobVerifyTarget()) {
  1668. std::string rescanRule =
  1669. cmStrCat("$(CMAKE_COMMAND) -P ",
  1670. this->ConvertToOutputFormat(cm->GetGlobVerifyScript(),
  1671. cmOutputConverter::SHELL));
  1672. commands.push_back(rescanRule);
  1673. }
  1674. std::string cmakefileName = "CMakeFiles/Makefile.cmake";
  1675. {
  1676. std::string runRule = cmStrCat(
  1677. "$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) ",
  1678. cm->GetIgnoreCompileWarningAsError() ? "--compile-no-warning-as-error "
  1679. : "",
  1680. cm->GetIgnoreLinkWarningAsError() ? "--link-no-warning-as-error " : "",
  1681. "--check-build-system ",
  1682. this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL),
  1683. " 1");
  1684. commands.push_back(std::move(runRule));
  1685. #if !defined(CMAKE_BOOTSTRAP) && !defined(_WIN32)
  1686. addInstrumentationCommand(this->GetCMakeInstance()->GetInstrumentation(),
  1687. commands);
  1688. #endif
  1689. }
  1690. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1691. this->GetCurrentBinaryDirectory());
  1692. this->WriteMakeRule(ruleFileStream, "clear depends", "depend", depends,
  1693. commands, true);
  1694. }
  1695. }
  1696. void cmLocalUnixMakefileGenerator3::ClearDependencies(cmMakefile* mf,
  1697. bool verbose)
  1698. {
  1699. // Get the list of target files to check
  1700. cmValue infoDef = mf->GetDefinition("CMAKE_DEPEND_INFO_FILES");
  1701. if (!infoDef) {
  1702. return;
  1703. }
  1704. cmList files{ *infoDef };
  1705. // Each depend information file corresponds to a target. Clear the
  1706. // dependencies for that target.
  1707. cmDepends clearer;
  1708. clearer.SetVerbose(verbose);
  1709. for (std::string const& file : files) {
  1710. auto snapshot = mf->GetState()->CreateBaseSnapshot();
  1711. cmMakefile lmf(mf->GetGlobalGenerator(), snapshot);
  1712. lmf.ReadListFile(file);
  1713. if (!lmf.GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES").empty()) {
  1714. std::string dir = cmSystemTools::GetFilenamePath(file);
  1715. // Clear the implicit dependency makefile.
  1716. std::string dependFile = dir + "/depend.make";
  1717. clearer.Clear(dependFile);
  1718. // Remove the internal dependency check file to force
  1719. // regeneration.
  1720. std::string internalDependFile = dir + "/depend.internal";
  1721. cmSystemTools::RemoveFile(internalDependFile);
  1722. }
  1723. auto depsFiles = lmf.GetSafeDefinition("CMAKE_DEPENDS_DEPENDENCY_FILES");
  1724. if (!depsFiles.empty()) {
  1725. auto dir = cmCMakePath(file).GetParentPath();
  1726. // Clear the implicit dependency makefile.
  1727. auto depFile = cmCMakePath(dir).Append("compiler_depend.make");
  1728. clearer.Clear(depFile.GenericString());
  1729. // Remove the internal dependency check file
  1730. auto internalDepFile =
  1731. cmCMakePath(dir).Append("compiler_depend.internal");
  1732. cmSystemTools::RemoveFile(internalDepFile.GenericString());
  1733. // Touch timestamp file to force dependencies regeneration
  1734. auto DepTimestamp = cmCMakePath(dir).Append("compiler_depend.ts");
  1735. cmSystemTools::Touch(DepTimestamp.GenericString(), true);
  1736. // clear the dependencies files generated by the compiler
  1737. cmList dependencies{ depsFiles, cmList::EmptyElements::Yes };
  1738. cmDependsCompiler depsManager;
  1739. depsManager.SetVerbose(verbose);
  1740. depsManager.ClearDependencies(dependencies);
  1741. }
  1742. }
  1743. }
  1744. void cmLocalUnixMakefileGenerator3::WriteDependLanguageInfo(
  1745. std::ostream& cmakefileStream, cmGeneratorTarget* target)
  1746. {
  1747. // To enable dependencies filtering
  1748. cmakefileStream << "\n"
  1749. "# Consider dependencies only in project.\n"
  1750. "set(CMAKE_DEPENDS_IN_PROJECT_ONLY "
  1751. << (cmIsOn(this->Makefile->GetSafeDefinition(
  1752. "CMAKE_DEPENDS_IN_PROJECT_ONLY"))
  1753. ? "ON"
  1754. : "OFF")
  1755. << ")\n\n";
  1756. bool requireFortran = false;
  1757. if (target->HaveFortranSources(this->GetConfigName())) {
  1758. requireFortran = true;
  1759. }
  1760. auto const& implicitLangs =
  1761. this->GetImplicitDepends(target, cmDependencyScannerKind::CMake);
  1762. // list the languages
  1763. cmakefileStream << "# The set of languages for which implicit "
  1764. "dependencies are needed:\n"
  1765. "set(CMAKE_DEPENDS_LANGUAGES\n";
  1766. for (auto const& implicitLang : implicitLangs) {
  1767. cmakefileStream << " \"" << implicitLang.first << "\"\n";
  1768. if (requireFortran && implicitLang.first == "Fortran"_s) {
  1769. requireFortran = false;
  1770. }
  1771. }
  1772. if (requireFortran) {
  1773. cmakefileStream << " \"Fortran\"\n";
  1774. }
  1775. cmakefileStream << " )\n";
  1776. if (!implicitLangs.empty()) {
  1777. // now list the files for each language
  1778. cmakefileStream
  1779. << "# The set of files for implicit dependencies of each language:\n";
  1780. for (auto const& implicitLang : implicitLangs) {
  1781. auto const& lang = implicitLang.first;
  1782. cmakefileStream << "set(CMAKE_DEPENDS_CHECK_" << lang << '\n';
  1783. auto const& implicitPairs = implicitLang.second;
  1784. // for each file pair
  1785. for (auto const& implicitPair : implicitPairs) {
  1786. for (auto const& di : implicitPair.second) {
  1787. cmakefileStream << " \"" << di << "\" \"" << implicitPair.first
  1788. << "\"\n";
  1789. }
  1790. }
  1791. cmakefileStream << " )\n";
  1792. // Tell the dependency scanner what compiler is used.
  1793. std::string cidVar = cmStrCat("CMAKE_", lang, "_COMPILER_ID");
  1794. cmValue cid = this->Makefile->GetDefinition(cidVar);
  1795. if (cmNonempty(cid)) {
  1796. cmakefileStream << "set(CMAKE_" << lang << "_COMPILER_ID \"" << *cid
  1797. << "\")\n";
  1798. }
  1799. if (lang == "Fortran") {
  1800. std::string smodSep =
  1801. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_SEP");
  1802. std::string smodExt =
  1803. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_EXT");
  1804. cmakefileStream << "set(CMAKE_Fortran_SUBMODULE_SEP \"" << smodSep
  1805. << "\")\n"
  1806. "set(CMAKE_Fortran_SUBMODULE_EXT \""
  1807. << smodExt << "\")\n";
  1808. }
  1809. // Build a list of preprocessor definitions for the target.
  1810. std::set<std::string> defines;
  1811. this->GetTargetDefines(target, this->GetConfigName(), lang, defines);
  1812. if (!defines.empty()) {
  1813. cmakefileStream << "\n"
  1814. "# Preprocessor definitions for this target.\n"
  1815. "set(CMAKE_TARGET_DEFINITIONS_"
  1816. << lang << '\n';
  1817. for (std::string const& define : defines) {
  1818. cmakefileStream << " " << cmOutputConverter::EscapeForCMake(define)
  1819. << '\n';
  1820. }
  1821. cmakefileStream << " )\n";
  1822. }
  1823. // Target-specific include directories:
  1824. cmakefileStream << "\n"
  1825. "# The include file search paths:\n"
  1826. "set(CMAKE_"
  1827. << lang << "_TARGET_INCLUDE_PATH\n";
  1828. std::vector<std::string> includes;
  1829. this->GetIncludeDirectories(includes, target, lang,
  1830. this->GetConfigName());
  1831. std::string const& binaryDir = this->GetState()->GetBinaryDirectory();
  1832. if (this->Makefile->IsOn("CMAKE_DEPENDS_IN_PROJECT_ONLY")) {
  1833. std::string const& sourceDir = this->GetState()->GetSourceDirectory();
  1834. cm::erase_if(includes, ::NotInProjectDir(sourceDir, binaryDir));
  1835. }
  1836. for (std::string const& include : includes) {
  1837. cmakefileStream << " \"" << this->MaybeRelativeToTopBinDir(include)
  1838. << "\"\n";
  1839. }
  1840. cmakefileStream << " )\n";
  1841. }
  1842. // Store include transform rule properties. Write the directory
  1843. // rules first because they may be overridden by later target rules.
  1844. cmList transformRules;
  1845. if (cmValue xform =
  1846. this->Makefile->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
  1847. transformRules.assign(*xform);
  1848. }
  1849. if (cmValue xform =
  1850. target->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
  1851. transformRules.append(*xform);
  1852. }
  1853. if (!transformRules.empty()) {
  1854. cmakefileStream << "\nset(CMAKE_INCLUDE_TRANSFORMS\n";
  1855. for (std::string const& tr : transformRules) {
  1856. cmakefileStream << " " << cmOutputConverter::EscapeForCMake(tr)
  1857. << '\n';
  1858. }
  1859. cmakefileStream << " )\n";
  1860. }
  1861. }
  1862. auto const& compilerLangs =
  1863. this->GetImplicitDepends(target, cmDependencyScannerKind::Compiler);
  1864. // list the dependency files managed by the compiler
  1865. cmakefileStream << "\n# The set of dependency files which are needed:\n"
  1866. "set(CMAKE_DEPENDS_DEPENDENCY_FILES\n";
  1867. for (auto const& compilerLang : compilerLangs) {
  1868. auto const& compilerPairs = compilerLang.second;
  1869. if (compilerLang.first == "CUSTOM"_s) {
  1870. for (auto const& compilerPair : compilerPairs) {
  1871. for (auto const& src : compilerPair.second) {
  1872. cmakefileStream << R"( "" ")"
  1873. << this->MaybeRelativeToTopBinDir(compilerPair.first)
  1874. << R"(" "custom" ")"
  1875. << this->MaybeRelativeToTopBinDir(src) << "\"\n";
  1876. }
  1877. }
  1878. } else if (compilerLang.first == "LINK"_s) {
  1879. auto depFormat = this->Makefile->GetDefinition(
  1880. cmStrCat("CMAKE_", target->GetLinkerLanguage(this->GetConfigName()),
  1881. "_LINKER_DEPFILE_FORMAT"));
  1882. for (auto const& compilerPair : compilerPairs) {
  1883. for (auto const& src : compilerPair.second) {
  1884. cmakefileStream << R"( "" ")"
  1885. << this->MaybeRelativeToTopBinDir(compilerPair.first)
  1886. << "\" \"" << depFormat << "\" \""
  1887. << this->MaybeRelativeToTopBinDir(src) << "\"\n";
  1888. }
  1889. }
  1890. } else {
  1891. auto depFormat = this->Makefile->GetSafeDefinition(
  1892. cmStrCat("CMAKE_", compilerLang.first, "_DEPFILE_FORMAT"));
  1893. for (auto const& compilerPair : compilerPairs) {
  1894. for (auto const& src : compilerPair.second) {
  1895. cmakefileStream << " \"" << src << "\" \""
  1896. << this->MaybeRelativeToTopBinDir(compilerPair.first)
  1897. << "\" \"" << depFormat << "\" \""
  1898. << this->MaybeRelativeToTopBinDir(compilerPair.first)
  1899. << ".d\"\n";
  1900. }
  1901. }
  1902. }
  1903. }
  1904. cmakefileStream << " )\n";
  1905. }
  1906. void cmLocalUnixMakefileGenerator3::WriteDisclaimer(std::ostream& os)
  1907. {
  1908. os << "# CMAKE generated file: DO NOT EDIT!\n"
  1909. "# Generated by \""
  1910. << this->GlobalGenerator->GetName()
  1911. << "\""
  1912. " Generator, CMake Version "
  1913. << cmVersion::GetMajorVersion() << '.' << cmVersion::GetMinorVersion()
  1914. << "\n\n";
  1915. }
  1916. std::string cmLocalUnixMakefileGenerator3::GetRecursiveMakeCall(
  1917. std::string const& makefile, std::string const& tgt)
  1918. {
  1919. // Call make on the given file.
  1920. std::string cmd = cmStrCat(
  1921. "$(MAKE) $(MAKESILENT) -f ",
  1922. this->ConvertToOutputFormat(makefile, cmOutputConverter::SHELL), ' ');
  1923. cmGlobalUnixMakefileGenerator3* gg =
  1924. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1925. // Pass down verbosity level.
  1926. if (!gg->MakeSilentFlag.empty()) {
  1927. cmd += gg->MakeSilentFlag;
  1928. cmd += " ";
  1929. }
  1930. // Most unix makes will pass the command line flags to make down to
  1931. // sub-invoked makes via an environment variable. However, some
  1932. // makes do not support that, so you have to pass the flags
  1933. // explicitly.
  1934. if (gg->PassMakeflags) {
  1935. cmd += "-$(MAKEFLAGS) ";
  1936. }
  1937. // Add the target.
  1938. if (!tgt.empty()) {
  1939. // The make target is always relative to the top of the build tree.
  1940. std::string tgt2 = this->MaybeRelativeToTopBinDir(tgt);
  1941. // The target may have been written with windows paths.
  1942. cmSystemTools::ConvertToOutputSlashes(tgt2);
  1943. // Escape one extra time if the make tool requires it.
  1944. if (this->MakeCommandEscapeTargetTwice) {
  1945. tgt2 = this->EscapeForShell(tgt2, true, false);
  1946. }
  1947. // The target name is now a string that should be passed verbatim
  1948. // on the command line.
  1949. cmd += this->EscapeForShell(tgt2, true, false);
  1950. }
  1951. return cmd;
  1952. }
  1953. void cmLocalUnixMakefileGenerator3::WriteDivider(std::ostream& os)
  1954. {
  1955. os << "#======================================"
  1956. "=======================================\n";
  1957. }
  1958. void cmLocalUnixMakefileGenerator3::WriteCMakeArgument(std::ostream& os,
  1959. std::string const& s)
  1960. {
  1961. // Write the given string to the stream with escaping to get it back
  1962. // into CMake through the lexical scanner.
  1963. os << '"';
  1964. for (char c : s) {
  1965. if (c == '\\') {
  1966. os << "\\\\";
  1967. } else if (c == '"') {
  1968. os << "\\\"";
  1969. } else {
  1970. os << c;
  1971. }
  1972. }
  1973. os << '"';
  1974. }
  1975. std::string cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(
  1976. std::string const& p, bool useWatcomQuote)
  1977. {
  1978. // Split the path into its components.
  1979. std::vector<std::string> components;
  1980. cmSystemTools::SplitPath(p, components);
  1981. // Open the quoted result.
  1982. std::string result;
  1983. if (useWatcomQuote) {
  1984. #if defined(_WIN32) && !defined(__CYGWIN__)
  1985. result = "'";
  1986. #else
  1987. result = "\"'";
  1988. #endif
  1989. } else {
  1990. result = "\"";
  1991. }
  1992. // Return an empty path if there are no components.
  1993. if (!components.empty()) {
  1994. // Choose a slash direction and fix root component.
  1995. char const* slash = "/";
  1996. #if defined(_WIN32) && !defined(__CYGWIN__)
  1997. if (!cmSystemTools::GetForceUnixPaths()) {
  1998. slash = "\\";
  1999. for (char& i : components[0]) {
  2000. if (i == '/') {
  2001. i = '\\';
  2002. }
  2003. }
  2004. }
  2005. #endif
  2006. // Begin the quoted result with the root component.
  2007. result += components[0];
  2008. if (components.size() > 1) {
  2009. // Now add the rest of the components separated by the proper slash
  2010. // direction for this platform.
  2011. auto compEnd = std::remove(components.begin() + 1, components.end() - 1,
  2012. std::string());
  2013. auto compStart = components.begin() + 1;
  2014. result += cmJoin(cmMakeRange(compStart, compEnd), slash);
  2015. // Only the last component can be empty to avoid double slashes.
  2016. result += slash;
  2017. result += components.back();
  2018. }
  2019. }
  2020. // Close the quoted result.
  2021. if (useWatcomQuote) {
  2022. #if defined(_WIN32) && !defined(__CYGWIN__)
  2023. result += "'";
  2024. #else
  2025. result += "'\"";
  2026. #endif
  2027. } else {
  2028. result += "\"";
  2029. }
  2030. return result;
  2031. }
  2032. cmLocalUnixMakefileGenerator3::ImplicitDependLanguageMap const&
  2033. cmLocalUnixMakefileGenerator3::GetImplicitDepends(
  2034. cmGeneratorTarget const* tgt, cmDependencyScannerKind scanner)
  2035. {
  2036. return this->ImplicitDepends[tgt->GetName()][scanner];
  2037. }
  2038. void cmLocalUnixMakefileGenerator3::AddImplicitDepends(
  2039. cmGeneratorTarget const* tgt, std::string const& lang,
  2040. std::string const& obj, std::string const& src,
  2041. cmDependencyScannerKind scanner)
  2042. {
  2043. this->ImplicitDepends[tgt->GetName()][scanner][lang][obj].push_back(src);
  2044. }
  2045. void cmLocalUnixMakefileGenerator3::CreateCDCommand(
  2046. std::vector<std::string>& commands, std::string const& tgtDir,
  2047. std::string const& relDir)
  2048. {
  2049. // do we need to cd?
  2050. if (tgtDir == relDir) {
  2051. return;
  2052. }
  2053. // In a Windows shell we must change drive letter too. The shell
  2054. // used by NMake and Borland make does not support "cd /d" so this
  2055. // feature simply cannot work with them (Borland make does not even
  2056. // support changing the drive letter with just "d:").
  2057. char const* cd_cmd = this->IsMinGWMake() ? "cd /d " : "cd ";
  2058. cmGlobalUnixMakefileGenerator3* gg =
  2059. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  2060. if (!gg->UnixCD) {
  2061. // On Windows we must perform each step separately and then change
  2062. // back because the shell keeps the working directory between
  2063. // commands.
  2064. std::string cmd =
  2065. cmStrCat(cd_cmd, this->ConvertToOutputForExisting(tgtDir));
  2066. commands.insert(commands.begin(), cmd);
  2067. // Change back to the starting directory.
  2068. cmd = cmStrCat(cd_cmd, this->ConvertToOutputForExisting(relDir));
  2069. commands.push_back(std::move(cmd));
  2070. } else {
  2071. // On UNIX we must construct a single shell command to change
  2072. // directory and build because make resets the directory between
  2073. // each command.
  2074. std::string outputForExisting = this->ConvertToOutputForExisting(tgtDir);
  2075. std::string prefix = cd_cmd + outputForExisting + " && ";
  2076. std::transform(commands.begin(), commands.end(), commands.begin(),
  2077. [&prefix](std::string const& s) { return prefix + s; });
  2078. }
  2079. }