cmLocalUnixMakefileGenerator3.cxx 81 KB

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