cmLocalUnixMakefileGenerator3.cxx 78 KB

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