cmLocalUnixMakefileGenerator3.cxx 73 KB

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