cmLocalUnixMakefileGenerator3.cxx 83 KB

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