cmLocalUnixMakefileGenerator3.cxx 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122
  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::CollapseFullPath(cmSystemTools::GetCMakeCommand()),
  563. cmOutputConverter::SHELL);
  564. }
  565. /* clang-format off */
  566. makefileStream
  567. << "# The CMake executable.\n"
  568. << "CMAKE_COMMAND = "
  569. << cmakeShellCommand
  570. << "\n"
  571. << "\n";
  572. makefileStream
  573. << "# The command to remove a file.\n"
  574. << "RM = "
  575. << cmakeShellCommand
  576. << " -E rm -f\n"
  577. << "\n";
  578. makefileStream
  579. << "# Escaping for special characters.\n"
  580. << "EQUALS = =\n"
  581. << "\n";
  582. makefileStream
  583. << "# The top-level source directory on which CMake was run.\n"
  584. << "CMAKE_SOURCE_DIR = "
  585. << this->ConvertToOutputFormat(
  586. cmSystemTools::CollapseFullPath(this->GetSourceDirectory()),
  587. cmOutputConverter::SHELL)
  588. << "\n"
  589. << "\n";
  590. makefileStream
  591. << "# The top-level build directory on which CMake was run.\n"
  592. << "CMAKE_BINARY_DIR = "
  593. << this->ConvertToOutputFormat(
  594. cmSystemTools::CollapseFullPath(this->GetBinaryDirectory()),
  595. cmOutputConverter::SHELL)
  596. << "\n"
  597. << "\n";
  598. /* clang-format on */
  599. }
  600. void cmLocalUnixMakefileGenerator3::WriteSpecialTargetsTop(
  601. std::ostream& makefileStream)
  602. {
  603. this->WriteDivider(makefileStream);
  604. makefileStream << "# Special targets provided by cmake.\n"
  605. << "\n";
  606. std::vector<std::string> no_commands;
  607. std::vector<std::string> no_depends;
  608. // Special target to cleanup operation of make tool.
  609. // This should be the first target except for the default_target in
  610. // the interface Makefile.
  611. this->WriteMakeRule(makefileStream,
  612. "Disable implicit rules so canonical targets will work.",
  613. ".SUFFIXES", no_depends, no_commands, false);
  614. if (!this->IsNMake() && !this->IsWatcomWMake() &&
  615. !this->BorlandMakeCurlyHack) {
  616. // turn off RCS and SCCS automatic stuff from gmake
  617. constexpr const char* vcs_rules[] = {
  618. "%,v", "RCS/%", "RCS/%,v", "SCCS/s.%", "s.%",
  619. };
  620. for (auto vcs_rule : vcs_rules) {
  621. std::vector<std::string> vcs_depend;
  622. vcs_depend.emplace_back(vcs_rule);
  623. this->WriteMakeRule(makefileStream, "Disable VCS-based implicit rules.",
  624. "%", vcs_depend, no_commands, false);
  625. }
  626. }
  627. // Add a fake suffix to keep HP happy. Must be max 32 chars for SGI make.
  628. std::vector<std::string> depends;
  629. depends.emplace_back(".hpux_make_needs_suffix_list");
  630. this->WriteMakeRule(makefileStream, nullptr, ".SUFFIXES", depends,
  631. no_commands, false);
  632. if (this->IsWatcomWMake()) {
  633. // Switch on WMake feature, if an error or interrupt occurs during
  634. // makefile processing, the current target being made may be deleted
  635. // without prompting (the same as command line -e option).
  636. /* clang-format off */
  637. makefileStream <<
  638. "\n"
  639. ".ERASE\n"
  640. "\n"
  641. ;
  642. /* clang-format on */
  643. }
  644. if (this->Makefile->IsOn("CMAKE_VERBOSE_MAKEFILE")) {
  645. /* clang-format off */
  646. makefileStream
  647. << "# Produce verbose output by default.\n"
  648. << "VERBOSE = 1\n"
  649. << "\n";
  650. /* clang-format on */
  651. }
  652. if (this->IsWatcomWMake()) {
  653. /* clang-format off */
  654. makefileStream <<
  655. "!ifndef VERBOSE\n"
  656. ".SILENT\n"
  657. "!endif\n"
  658. "\n"
  659. ;
  660. /* clang-format on */
  661. } else {
  662. makefileStream << "# Command-line flag to silence nested $(MAKE).\n"
  663. "$(VERBOSE)MAKESILENT = -s\n"
  664. "\n";
  665. // Write special target to silence make output. This must be after
  666. // the default target in case VERBOSE is set (which changes the
  667. // name). The setting of CMAKE_VERBOSE_MAKEFILE to ON will cause a
  668. // "VERBOSE=1" to be added as a make variable which will change the
  669. // name of this special target. This gives a make-time choice to
  670. // the user.
  671. this->WriteMakeRule(makefileStream,
  672. "Suppress display of executed commands.",
  673. "$(VERBOSE).SILENT", no_depends, no_commands, false);
  674. }
  675. // Work-around for makes that drop rules that have no dependencies
  676. // or commands.
  677. cmGlobalUnixMakefileGenerator3* gg =
  678. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  679. std::string hack = gg->GetEmptyRuleHackDepends();
  680. if (!hack.empty()) {
  681. no_depends.push_back(std::move(hack));
  682. }
  683. std::string hack_cmd = gg->GetEmptyRuleHackCommand();
  684. if (!hack_cmd.empty()) {
  685. no_commands.push_back(std::move(hack_cmd));
  686. }
  687. // Special symbolic target that never exists to force dependers to
  688. // run their rules.
  689. this->WriteMakeRule(makefileStream, "A target that is always out of date.",
  690. "cmake_force", no_depends, no_commands, true);
  691. // Variables for reference by other rules.
  692. this->WriteMakeVariables(makefileStream);
  693. }
  694. void cmLocalUnixMakefileGenerator3::WriteSpecialTargetsBottom(
  695. std::ostream& makefileStream)
  696. {
  697. this->WriteDivider(makefileStream);
  698. makefileStream << "# Special targets to cleanup operation of make.\n"
  699. << "\n";
  700. // Write special "cmake_check_build_system" target to run cmake with
  701. // the --check-build-system flag.
  702. if (!this->GlobalGenerator->GlobalSettingIsOn(
  703. "CMAKE_SUPPRESS_REGENERATION")) {
  704. // Build command to run CMake to check if anything needs regenerating.
  705. std::vector<std::string> commands;
  706. cmake* cm = this->GlobalGenerator->GetCMakeInstance();
  707. if (cm->DoWriteGlobVerifyTarget()) {
  708. std::string rescanRule =
  709. cmStrCat("$(CMAKE_COMMAND) -P ",
  710. this->ConvertToOutputFormat(cm->GetGlobVerifyScript(),
  711. cmOutputConverter::SHELL));
  712. commands.push_back(rescanRule);
  713. }
  714. std::string cmakefileName = "CMakeFiles/Makefile.cmake";
  715. std::string runRule = cmStrCat(
  716. "$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) "
  717. "--check-build-system ",
  718. this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL),
  719. " 0");
  720. std::vector<std::string> no_depends;
  721. commands.push_back(std::move(runRule));
  722. if (!this->IsRootMakefile()) {
  723. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  724. this->GetCurrentBinaryDirectory());
  725. }
  726. this->WriteMakeRule(makefileStream,
  727. "Special rule to run CMake to check the build system "
  728. "integrity.\n"
  729. "No rule that depends on this can have "
  730. "commands that come from listfiles\n"
  731. "because they might be regenerated.",
  732. "cmake_check_build_system", no_depends, commands,
  733. true);
  734. }
  735. }
  736. void cmLocalUnixMakefileGenerator3::WriteConvenienceRule(
  737. std::ostream& ruleFileStream, const std::string& realTarget,
  738. const std::string& helpTarget)
  739. {
  740. // A rule is only needed if the names are different.
  741. if (realTarget != helpTarget) {
  742. // The helper target depends on the real target.
  743. std::vector<std::string> depends;
  744. depends.push_back(realTarget);
  745. // There are no commands.
  746. std::vector<std::string> no_commands;
  747. // Write the rule.
  748. this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
  749. helpTarget, depends, no_commands, true);
  750. }
  751. }
  752. std::string cmLocalUnixMakefileGenerator3::GetRelativeTargetDirectory(
  753. cmGeneratorTarget const* target) const
  754. {
  755. std::string dir =
  756. cmStrCat(this->HomeRelativeOutputPath, this->GetTargetDirectory(target));
  757. return dir;
  758. }
  759. void cmLocalUnixMakefileGenerator3::AppendFlags(
  760. std::string& flags, const std::string& newFlags) const
  761. {
  762. if (this->IsWatcomWMake() && !newFlags.empty()) {
  763. std::string newf = newFlags;
  764. if (newf.find("\\\"") != std::string::npos) {
  765. cmSystemTools::ReplaceString(newf, "\\\"", "\"");
  766. this->cmLocalGenerator::AppendFlags(flags, newf);
  767. return;
  768. }
  769. }
  770. this->cmLocalGenerator::AppendFlags(flags, newFlags);
  771. }
  772. void cmLocalUnixMakefileGenerator3::AppendRuleDepend(
  773. std::vector<std::string>& depends, const char* ruleFileName)
  774. {
  775. // Add a dependency on the rule file itself unless an option to skip
  776. // it is specifically enabled by the user or project.
  777. const char* nodep =
  778. this->Makefile->GetDefinition("CMAKE_SKIP_RULE_DEPENDENCY");
  779. if (!nodep || cmIsOff(nodep)) {
  780. depends.emplace_back(ruleFileName);
  781. }
  782. }
  783. void cmLocalUnixMakefileGenerator3::AppendRuleDepends(
  784. std::vector<std::string>& depends, std::vector<std::string> const& ruleFiles)
  785. {
  786. // Add a dependency on the rule file itself unless an option to skip
  787. // it is specifically enabled by the user or project.
  788. if (!this->Makefile->IsOn("CMAKE_SKIP_RULE_DEPENDENCY")) {
  789. cm::append(depends, ruleFiles);
  790. }
  791. }
  792. void cmLocalUnixMakefileGenerator3::AppendCustomDepends(
  793. std::vector<std::string>& depends, const std::vector<cmCustomCommand>& ccs)
  794. {
  795. for (cmCustomCommand const& cc : ccs) {
  796. cmCustomCommandGenerator ccg(cc, this->GetConfigName(), this);
  797. this->AppendCustomDepend(depends, ccg);
  798. }
  799. }
  800. void cmLocalUnixMakefileGenerator3::AppendCustomDepend(
  801. std::vector<std::string>& depends, cmCustomCommandGenerator const& ccg)
  802. {
  803. for (std::string const& d : ccg.GetDepends()) {
  804. // Lookup the real name of the dependency in case it is a CMake target.
  805. std::string dep;
  806. if (this->GetRealDependency(d, this->GetConfigName(), dep)) {
  807. depends.push_back(std::move(dep));
  808. }
  809. }
  810. }
  811. void cmLocalUnixMakefileGenerator3::AppendCustomCommands(
  812. std::vector<std::string>& commands, const std::vector<cmCustomCommand>& ccs,
  813. cmGeneratorTarget* target, std::string const& relative)
  814. {
  815. for (cmCustomCommand const& cc : ccs) {
  816. cmCustomCommandGenerator ccg(cc, this->GetConfigName(), this);
  817. this->AppendCustomCommand(commands, ccg, target, relative, true);
  818. }
  819. }
  820. void cmLocalUnixMakefileGenerator3::AppendCustomCommand(
  821. std::vector<std::string>& commands, cmCustomCommandGenerator const& ccg,
  822. cmGeneratorTarget* target, std::string const& relative, bool echo_comment,
  823. std::ostream* content)
  824. {
  825. // Optionally create a command to display the custom command's
  826. // comment text. This is used for pre-build, pre-link, and
  827. // post-build command comments. Custom build step commands have
  828. // their comments generated elsewhere.
  829. if (echo_comment) {
  830. const char* comment = ccg.GetComment();
  831. if (comment && *comment) {
  832. this->AppendEcho(commands, comment,
  833. cmLocalUnixMakefileGenerator3::EchoGenerate);
  834. }
  835. }
  836. // if the command specified a working directory use it.
  837. std::string dir = this->GetCurrentBinaryDirectory();
  838. std::string workingDir = ccg.GetWorkingDirectory();
  839. if (!workingDir.empty()) {
  840. dir = workingDir;
  841. }
  842. if (content) {
  843. *content << dir;
  844. }
  845. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  846. this->CreateRulePlaceholderExpander());
  847. // Add each command line to the set of commands.
  848. std::vector<std::string> commands1;
  849. std::string currentBinDir = this->GetCurrentBinaryDirectory();
  850. for (unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) {
  851. // Build the command line in a single string.
  852. std::string cmd = ccg.GetCommand(c);
  853. if (!cmd.empty()) {
  854. // Use "call " before any invocations of .bat or .cmd files
  855. // invoked as custom commands in the WindowsShell.
  856. //
  857. bool useCall = false;
  858. if (this->IsWindowsShell()) {
  859. std::string suffix;
  860. if (cmd.size() > 4) {
  861. suffix = cmSystemTools::LowerCase(cmd.substr(cmd.size() - 4));
  862. if (suffix == ".bat" || suffix == ".cmd") {
  863. useCall = true;
  864. }
  865. }
  866. }
  867. cmSystemTools::ReplaceString(cmd, "/./", "/");
  868. // Convert the command to a relative path only if the current
  869. // working directory will be the start-output directory.
  870. bool had_slash = cmd.find('/') != std::string::npos;
  871. if (workingDir.empty()) {
  872. cmd = this->MaybeConvertToRelativePath(currentBinDir, cmd);
  873. }
  874. bool has_slash = cmd.find('/') != std::string::npos;
  875. if (had_slash && !has_slash) {
  876. // This command was specified as a path to a file in the
  877. // current directory. Add a leading "./" so it can run
  878. // without the current directory being in the search path.
  879. cmd = cmStrCat("./", cmd);
  880. }
  881. std::string launcher;
  882. // Short-circuit if there is no launcher.
  883. const char* val = this->GetRuleLauncher(target, "RULE_LAUNCH_CUSTOM");
  884. if (val && *val) {
  885. // Expand rule variables referenced in the given launcher command.
  886. cmRulePlaceholderExpander::RuleVariables vars;
  887. vars.CMTargetName = target->GetName().c_str();
  888. vars.CMTargetType = cmState::GetTargetTypeName(target->GetType());
  889. std::string output;
  890. const std::vector<std::string>& outputs = ccg.GetOutputs();
  891. if (!outputs.empty()) {
  892. output = outputs[0];
  893. if (workingDir.empty()) {
  894. output = this->MaybeConvertToRelativePath(
  895. this->GetCurrentBinaryDirectory(), output);
  896. }
  897. output =
  898. this->ConvertToOutputFormat(output, cmOutputConverter::SHELL);
  899. }
  900. vars.Output = output.c_str();
  901. launcher = val;
  902. rulePlaceholderExpander->ExpandRuleVariables(this, launcher, vars);
  903. if (!launcher.empty()) {
  904. launcher += " ";
  905. }
  906. }
  907. std::string shellCommand = this->MaybeConvertWatcomShellCommand(cmd);
  908. if (shellCommand.empty()) {
  909. shellCommand =
  910. this->ConvertToOutputFormat(cmd, cmOutputConverter::SHELL);
  911. }
  912. cmd = launcher + shellCommand;
  913. ccg.AppendArguments(c, cmd);
  914. if (content) {
  915. // Rule content does not include the launcher.
  916. *content << (cmd.c_str() + launcher.size());
  917. }
  918. if (this->BorlandMakeCurlyHack) {
  919. // Borland Make has a very strange bug. If the first curly
  920. // brace anywhere in the command string is a left curly, it
  921. // must be written {{} instead of just {. Otherwise some
  922. // curly braces are removed. The hack can be skipped if the
  923. // first curly brace is the last character.
  924. std::string::size_type lcurly = cmd.find('{');
  925. if (lcurly != std::string::npos && lcurly < (cmd.size() - 1)) {
  926. std::string::size_type rcurly = cmd.find('}');
  927. if (rcurly == std::string::npos || rcurly > lcurly) {
  928. // The first curly is a left curly. Use the hack.
  929. cmd =
  930. cmStrCat(cmd.substr(0, lcurly), "{{}", cmd.substr(lcurly + 1));
  931. }
  932. }
  933. }
  934. if (launcher.empty()) {
  935. if (useCall) {
  936. cmd = cmStrCat("call ", cmd);
  937. } else if (this->IsNMake() && cmd[0] == '"') {
  938. cmd = cmStrCat("echo >nul && ", cmd);
  939. }
  940. }
  941. commands1.push_back(std::move(cmd));
  942. }
  943. }
  944. // Setup the proper working directory for the commands.
  945. this->CreateCDCommand(commands1, dir, relative);
  946. // push back the custom commands
  947. cm::append(commands, commands1);
  948. }
  949. void cmLocalUnixMakefileGenerator3::AppendCleanCommand(
  950. std::vector<std::string>& commands, const std::set<std::string>& files,
  951. cmGeneratorTarget* target, const char* filename)
  952. {
  953. std::string currentBinDir = this->GetCurrentBinaryDirectory();
  954. std::string cleanfile = cmStrCat(
  955. currentBinDir, '/', this->GetTargetDirectory(target), "/cmake_clean");
  956. if (filename) {
  957. cleanfile += "_";
  958. cleanfile += filename;
  959. }
  960. cleanfile += ".cmake";
  961. std::string cleanfilePath = cmSystemTools::CollapseFullPath(cleanfile);
  962. cmsys::ofstream fout(cleanfilePath.c_str());
  963. if (!fout) {
  964. cmSystemTools::Error("Could not create " + cleanfilePath);
  965. }
  966. if (!files.empty()) {
  967. fout << "file(REMOVE_RECURSE\n";
  968. for (std::string const& file : files) {
  969. std::string fc = this->MaybeConvertToRelativePath(currentBinDir, file);
  970. fout << " " << cmOutputConverter::EscapeForCMake(fc) << "\n";
  971. }
  972. fout << ")\n";
  973. }
  974. {
  975. std::string remove =
  976. cmStrCat("$(CMAKE_COMMAND) -P ",
  977. this->ConvertToOutputFormat(
  978. this->MaybeConvertToRelativePath(
  979. this->GetCurrentBinaryDirectory(), cleanfile),
  980. cmOutputConverter::SHELL));
  981. commands.push_back(std::move(remove));
  982. }
  983. // For the main clean rule add per-language cleaning.
  984. if (!filename) {
  985. // Get the set of source languages in the target.
  986. std::set<std::string> languages;
  987. target->GetLanguages(
  988. languages, this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
  989. /* clang-format off */
  990. fout << "\n"
  991. << "# Per-language clean rules from dependency scanning.\n"
  992. << "foreach(lang " << cmJoin(languages, " ") << ")\n"
  993. << " include(" << this->GetTargetDirectory(target)
  994. << "/cmake_clean_${lang}.cmake OPTIONAL)\n"
  995. << "endforeach()\n";
  996. /* clang-format on */
  997. }
  998. }
  999. void cmLocalUnixMakefileGenerator3::AppendDirectoryCleanCommand(
  1000. std::vector<std::string>& commands)
  1001. {
  1002. std::vector<std::string> cleanFiles;
  1003. // Look for additional files registered for cleaning in this directory.
  1004. if (const char* prop_value =
  1005. this->Makefile->GetProperty("ADDITIONAL_CLEAN_FILES")) {
  1006. cmExpandList(cmGeneratorExpression::Evaluate(
  1007. prop_value, this,
  1008. this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE")),
  1009. cleanFiles);
  1010. }
  1011. if (cleanFiles.empty()) {
  1012. return;
  1013. }
  1014. const auto& rootLG = this->GetGlobalGenerator()->GetLocalGenerators().at(0);
  1015. std::string const& binaryDir = rootLG->GetCurrentBinaryDirectory();
  1016. std::string const& currentBinaryDir = this->GetCurrentBinaryDirectory();
  1017. std::string cleanfile =
  1018. cmStrCat(currentBinaryDir, "/CMakeFiles/cmake_directory_clean.cmake");
  1019. // Write clean script
  1020. {
  1021. std::string cleanfilePath = cmSystemTools::CollapseFullPath(cleanfile);
  1022. cmsys::ofstream fout(cleanfilePath.c_str());
  1023. if (!fout) {
  1024. cmSystemTools::Error("Could not create " + cleanfilePath);
  1025. return;
  1026. }
  1027. fout << "file(REMOVE_RECURSE\n";
  1028. for (std::string const& cfl : cleanFiles) {
  1029. std::string fc = rootLG->MaybeConvertToRelativePath(
  1030. binaryDir, cmSystemTools::CollapseFullPath(cfl, currentBinaryDir));
  1031. fout << " " << cmOutputConverter::EscapeForCMake(fc) << "\n";
  1032. }
  1033. fout << ")\n";
  1034. }
  1035. // Create command
  1036. {
  1037. std::string remove =
  1038. cmStrCat("$(CMAKE_COMMAND) -P ",
  1039. this->ConvertToOutputFormat(
  1040. rootLG->MaybeConvertToRelativePath(binaryDir, cleanfile),
  1041. cmOutputConverter::SHELL));
  1042. commands.push_back(std::move(remove));
  1043. }
  1044. }
  1045. void cmLocalUnixMakefileGenerator3::AppendEcho(
  1046. std::vector<std::string>& commands, std::string const& text, EchoColor color,
  1047. EchoProgress const* progress)
  1048. {
  1049. // Choose the color for the text.
  1050. std::string color_name;
  1051. if (this->GlobalGenerator->GetToolSupportsColor() && this->ColorMakefile) {
  1052. // See cmake::ExecuteEchoColor in cmake.cxx for these options.
  1053. // This color set is readable on both black and white backgrounds.
  1054. switch (color) {
  1055. case EchoNormal:
  1056. break;
  1057. case EchoDepend:
  1058. color_name = "--magenta --bold ";
  1059. break;
  1060. case EchoBuild:
  1061. color_name = "--green ";
  1062. break;
  1063. case EchoLink:
  1064. color_name = "--green --bold ";
  1065. break;
  1066. case EchoGenerate:
  1067. color_name = "--blue --bold ";
  1068. break;
  1069. case EchoGlobal:
  1070. color_name = "--cyan ";
  1071. break;
  1072. }
  1073. }
  1074. // Echo one line at a time.
  1075. std::string line;
  1076. line.reserve(200);
  1077. for (const char* c = text.c_str();; ++c) {
  1078. if (*c == '\n' || *c == '\0') {
  1079. // Avoid writing a blank last line on end-of-string.
  1080. if (*c != '\0' || !line.empty()) {
  1081. // Add a command to echo this line.
  1082. std::string cmd;
  1083. if (color_name.empty() && !progress) {
  1084. // Use the native echo command.
  1085. cmd = cmStrCat("@echo ", this->EscapeForShell(line, false, true));
  1086. } else {
  1087. // Use cmake to echo the text in color.
  1088. cmd = cmStrCat(
  1089. "@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) ",
  1090. color_name);
  1091. if (progress) {
  1092. cmd += "--progress-dir=";
  1093. cmd += this->ConvertToOutputFormat(
  1094. cmSystemTools::CollapseFullPath(progress->Dir),
  1095. cmOutputConverter::SHELL);
  1096. cmd += " ";
  1097. cmd += "--progress-num=";
  1098. cmd += progress->Arg;
  1099. cmd += " ";
  1100. }
  1101. cmd += this->EscapeForShell(line);
  1102. }
  1103. commands.push_back(std::move(cmd));
  1104. }
  1105. // Reset the line to empty.
  1106. line.clear();
  1107. // Progress appears only on first line.
  1108. progress = nullptr;
  1109. // Terminate on end-of-string.
  1110. if (*c == '\0') {
  1111. return;
  1112. }
  1113. } else if (*c != '\r') {
  1114. // Append this character to the current line.
  1115. line += *c;
  1116. }
  1117. }
  1118. }
  1119. std::string cmLocalUnixMakefileGenerator3::CreateMakeVariable(
  1120. std::string const& s, std::string const& s2)
  1121. {
  1122. std::string unmodified = cmStrCat(s, s2);
  1123. // if there is no restriction on the length of make variables
  1124. // and there are no "." characters in the string, then return the
  1125. // unmodified combination.
  1126. if ((!this->MakefileVariableSize &&
  1127. unmodified.find('.') == std::string::npos) &&
  1128. (!this->MakefileVariableSize &&
  1129. unmodified.find('+') == std::string::npos) &&
  1130. (!this->MakefileVariableSize &&
  1131. unmodified.find('-') == std::string::npos)) {
  1132. return unmodified;
  1133. }
  1134. // see if the variable has been defined before and return
  1135. // the modified version of the variable
  1136. auto i = this->MakeVariableMap.find(unmodified);
  1137. if (i != this->MakeVariableMap.end()) {
  1138. return i->second;
  1139. }
  1140. // start with the unmodified variable
  1141. std::string ret = unmodified;
  1142. // if this there is no value for this->MakefileVariableSize then
  1143. // the string must have bad characters in it
  1144. if (!this->MakefileVariableSize) {
  1145. std::replace(ret.begin(), ret.end(), '.', '_');
  1146. cmSystemTools::ReplaceString(ret, "-", "__");
  1147. cmSystemTools::ReplaceString(ret, "+", "___");
  1148. int ni = 0;
  1149. char buffer[5];
  1150. // make sure the _ version is not already used, if
  1151. // it is used then add number to the end of the variable
  1152. while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
  1153. ++ni;
  1154. sprintf(buffer, "%04d", ni);
  1155. ret = unmodified + buffer;
  1156. }
  1157. this->ShortMakeVariableMap[ret] = "1";
  1158. this->MakeVariableMap[unmodified] = ret;
  1159. return ret;
  1160. }
  1161. // if the string is greater than 32 chars it is an invalid variable name
  1162. // for borland make
  1163. if (static_cast<int>(ret.size()) > this->MakefileVariableSize) {
  1164. int keep = this->MakefileVariableSize - 8;
  1165. int size = keep + 3;
  1166. std::string str1 = s;
  1167. std::string str2 = s2;
  1168. // we must shorten the combined string by 4 characters
  1169. // keep no more than 24 characters from the second string
  1170. if (static_cast<int>(str2.size()) > keep) {
  1171. str2 = str2.substr(0, keep);
  1172. }
  1173. if (static_cast<int>(str1.size()) + static_cast<int>(str2.size()) > size) {
  1174. str1 = str1.substr(0, size - str2.size());
  1175. }
  1176. char buffer[5];
  1177. int ni = 0;
  1178. sprintf(buffer, "%04d", ni);
  1179. ret = str1 + str2 + buffer;
  1180. while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
  1181. ++ni;
  1182. sprintf(buffer, "%04d", ni);
  1183. ret = str1 + str2 + buffer;
  1184. }
  1185. if (ni == 1000) {
  1186. cmSystemTools::Error("Borland makefile variable length too long");
  1187. return unmodified;
  1188. }
  1189. // once an unused variable is found
  1190. this->ShortMakeVariableMap[ret] = "1";
  1191. }
  1192. // always make an entry into the unmodified to variable map
  1193. this->MakeVariableMap[unmodified] = ret;
  1194. return ret;
  1195. }
  1196. bool cmLocalUnixMakefileGenerator3::UpdateDependencies(
  1197. const std::string& tgtInfo, bool verbose, bool color)
  1198. {
  1199. // read in the target info file
  1200. if (!this->Makefile->ReadListFile(tgtInfo) ||
  1201. cmSystemTools::GetErrorOccuredFlag()) {
  1202. cmSystemTools::Error("Target DependInfo.cmake file not found");
  1203. }
  1204. // Check if any multiple output pairs have a missing file.
  1205. this->CheckMultipleOutputs(verbose);
  1206. std::string const targetDir = cmSystemTools::GetFilenamePath(tgtInfo);
  1207. std::string const internalDependFile = targetDir + "/depend.internal";
  1208. std::string const dependFile = targetDir + "/depend.make";
  1209. // If the target DependInfo.cmake file has changed since the last
  1210. // time dependencies were scanned then force rescanning. This may
  1211. // happen when a new source file is added and CMake regenerates the
  1212. // project but no other sources were touched.
  1213. bool needRescanDependInfo = false;
  1214. cmFileTimeCache* ftc =
  1215. this->GlobalGenerator->GetCMakeInstance()->GetFileTimeCache();
  1216. {
  1217. int result;
  1218. if (!ftc->Compare(internalDependFile, tgtInfo, &result) || result < 0) {
  1219. if (verbose) {
  1220. std::ostringstream msg;
  1221. msg << "Dependee \"" << tgtInfo << "\" is newer than depender \""
  1222. << internalDependFile << "\"." << std::endl;
  1223. cmSystemTools::Stdout(msg.str());
  1224. }
  1225. needRescanDependInfo = true;
  1226. }
  1227. }
  1228. // If the directory information is newer than depend.internal, include dirs
  1229. // may have changed. In this case discard all old dependencies.
  1230. bool needRescanDirInfo = false;
  1231. {
  1232. std::string dirInfoFile =
  1233. cmStrCat(this->GetCurrentBinaryDirectory(),
  1234. "/CMakeFiles/CMakeDirectoryInformation.cmake");
  1235. int result;
  1236. if (!ftc->Compare(internalDependFile, dirInfoFile, &result) ||
  1237. result < 0) {
  1238. if (verbose) {
  1239. std::ostringstream msg;
  1240. msg << "Dependee \"" << dirInfoFile << "\" is newer than depender \""
  1241. << internalDependFile << "\"." << std::endl;
  1242. cmSystemTools::Stdout(msg.str());
  1243. }
  1244. needRescanDirInfo = true;
  1245. }
  1246. }
  1247. // Check the implicit dependencies to see if they are up to date.
  1248. // The build.make file may have explicit dependencies for the object
  1249. // files but these will not affect the scanning process so they need
  1250. // not be considered.
  1251. cmDepends::DependencyMap validDependencies;
  1252. bool needRescanDependencies = false;
  1253. if (!needRescanDirInfo) {
  1254. cmDependsC checker;
  1255. checker.SetVerbose(verbose);
  1256. checker.SetFileTimeCache(ftc);
  1257. // cmDependsC::Check() fills the vector validDependencies() with the
  1258. // dependencies for those files where they are still valid, i.e. neither
  1259. // the files themselves nor any files they depend on have changed.
  1260. // We don't do that if the CMakeDirectoryInformation.cmake file has
  1261. // changed, because then potentially all dependencies have changed.
  1262. // This information is given later on to cmDependsC, which then only
  1263. // rescans the files where it did not get valid dependencies via this
  1264. // dependency vector. This means that in the normal case, when only
  1265. // few or one file have been edited, then also only this one file is
  1266. // actually scanned again, instead of all files for this target.
  1267. needRescanDependencies =
  1268. !checker.Check(dependFile, internalDependFile, validDependencies);
  1269. }
  1270. if (needRescanDependInfo || needRescanDirInfo || needRescanDependencies) {
  1271. // The dependencies must be regenerated.
  1272. std::string targetName = cmSystemTools::GetFilenameName(targetDir);
  1273. targetName = targetName.substr(0, targetName.length() - 4);
  1274. std::string message =
  1275. cmStrCat("Scanning dependencies of target ", targetName);
  1276. cmSystemTools::MakefileColorEcho(cmsysTerminal_Color_ForegroundMagenta |
  1277. cmsysTerminal_Color_ForegroundBold,
  1278. message.c_str(), true, color);
  1279. return this->ScanDependencies(targetDir, dependFile, internalDependFile,
  1280. validDependencies);
  1281. }
  1282. // The dependencies are already up-to-date.
  1283. return true;
  1284. }
  1285. bool cmLocalUnixMakefileGenerator3::ScanDependencies(
  1286. std::string const& targetDir, std::string const& dependFile,
  1287. std::string const& internalDependFile, cmDepends::DependencyMap& validDeps)
  1288. {
  1289. // Read the directory information file.
  1290. cmMakefile* mf = this->Makefile;
  1291. bool haveDirectoryInfo = false;
  1292. {
  1293. std::string dirInfoFile =
  1294. cmStrCat(this->GetCurrentBinaryDirectory(),
  1295. "/CMakeFiles/CMakeDirectoryInformation.cmake");
  1296. if (mf->ReadListFile(dirInfoFile) &&
  1297. !cmSystemTools::GetErrorOccuredFlag()) {
  1298. haveDirectoryInfo = true;
  1299. }
  1300. }
  1301. // Lookup useful directory information.
  1302. if (haveDirectoryInfo) {
  1303. // Test whether we need to force Unix paths.
  1304. if (const char* force = mf->GetDefinition("CMAKE_FORCE_UNIX_PATHS")) {
  1305. if (!cmIsOff(force)) {
  1306. cmSystemTools::SetForceUnixPaths(true);
  1307. }
  1308. }
  1309. // Setup relative path top directories.
  1310. if (const char* relativePathTopSource =
  1311. mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_SOURCE")) {
  1312. this->StateSnapshot.GetDirectory().SetRelativePathTopSource(
  1313. relativePathTopSource);
  1314. }
  1315. if (const char* relativePathTopBinary =
  1316. mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_BINARY")) {
  1317. this->StateSnapshot.GetDirectory().SetRelativePathTopBinary(
  1318. relativePathTopBinary);
  1319. }
  1320. } else {
  1321. cmSystemTools::Error("Directory Information file not found");
  1322. }
  1323. // Open the make depends file. This should be copy-if-different
  1324. // because the make tool may try to reload it needlessly otherwise.
  1325. cmGeneratedFileStream ruleFileStream(
  1326. dependFile, false, this->GlobalGenerator->GetMakefileEncoding());
  1327. ruleFileStream.SetCopyIfDifferent(true);
  1328. if (!ruleFileStream) {
  1329. return false;
  1330. }
  1331. // Open the cmake dependency tracking file. This should not be
  1332. // copy-if-different because dependencies are re-scanned when it is
  1333. // older than the DependInfo.cmake.
  1334. cmGeneratedFileStream internalRuleFileStream(
  1335. internalDependFile, false, this->GlobalGenerator->GetMakefileEncoding());
  1336. if (!internalRuleFileStream) {
  1337. return false;
  1338. }
  1339. this->WriteDisclaimer(ruleFileStream);
  1340. this->WriteDisclaimer(internalRuleFileStream);
  1341. // for each language we need to scan, scan it
  1342. std::vector<std::string> langs =
  1343. cmExpandedList(mf->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES"));
  1344. for (std::string const& lang : langs) {
  1345. // construct the checker
  1346. // Create the scanner for this language
  1347. std::unique_ptr<cmDepends> scanner;
  1348. if (lang == "C" || lang == "CXX" || lang == "RC" || lang == "ASM" ||
  1349. lang == "OBJC" || lang == "OBJCXX" || lang == "CUDA") {
  1350. // TODO: Handle RC (resource files) dependencies correctly.
  1351. scanner = cm::make_unique<cmDependsC>(this, targetDir, lang, &validDeps);
  1352. }
  1353. #ifndef CMAKE_BOOTSTRAP
  1354. else if (lang == "Fortran") {
  1355. ruleFileStream << "# Note that incremental build could trigger "
  1356. << "a call to cmake_copy_f90_mod on each re-build\n";
  1357. scanner = cm::make_unique<cmDependsFortran>(this);
  1358. } else if (lang == "Java") {
  1359. scanner = cm::make_unique<cmDependsJava>();
  1360. }
  1361. #endif
  1362. if (scanner) {
  1363. scanner->SetLocalGenerator(this);
  1364. scanner->SetFileTimeCache(
  1365. this->GlobalGenerator->GetCMakeInstance()->GetFileTimeCache());
  1366. scanner->SetLanguage(lang);
  1367. scanner->SetTargetDirectory(targetDir);
  1368. scanner->Write(ruleFileStream, internalRuleFileStream);
  1369. }
  1370. }
  1371. return true;
  1372. }
  1373. void cmLocalUnixMakefileGenerator3::CheckMultipleOutputs(bool verbose)
  1374. {
  1375. cmMakefile* mf = this->Makefile;
  1376. // Get the string listing the multiple output pairs.
  1377. const char* pairs_string = mf->GetDefinition("CMAKE_MULTIPLE_OUTPUT_PAIRS");
  1378. if (!pairs_string) {
  1379. return;
  1380. }
  1381. // Convert the string to a list and preserve empty entries.
  1382. std::vector<std::string> pairs = cmExpandedList(pairs_string, true);
  1383. for (auto i = pairs.begin(); i != pairs.end() && (i + 1) != pairs.end();) {
  1384. const std::string& depender = *i++;
  1385. const std::string& dependee = *i++;
  1386. // If the depender is missing then delete the dependee to make
  1387. // sure both will be regenerated.
  1388. if (cmSystemTools::FileExists(dependee) &&
  1389. !cmSystemTools::FileExists(depender)) {
  1390. if (verbose) {
  1391. std::ostringstream msg;
  1392. msg << "Deleting primary custom command output \"" << dependee
  1393. << "\" because another output \"" << depender
  1394. << "\" does not exist." << std::endl;
  1395. cmSystemTools::Stdout(msg.str());
  1396. }
  1397. cmSystemTools::RemoveFile(dependee);
  1398. }
  1399. }
  1400. }
  1401. void cmLocalUnixMakefileGenerator3::WriteLocalAllRules(
  1402. std::ostream& ruleFileStream)
  1403. {
  1404. this->WriteDisclaimer(ruleFileStream);
  1405. // Write the main entry point target. This must be the VERY first
  1406. // target so that make with no arguments will run it.
  1407. {
  1408. // Just depend on the all target to drive the build.
  1409. std::vector<std::string> depends;
  1410. std::vector<std::string> no_commands;
  1411. depends.emplace_back("all");
  1412. // Write the rule.
  1413. this->WriteMakeRule(ruleFileStream,
  1414. "Default target executed when no arguments are "
  1415. "given to make.",
  1416. "default_target", depends, no_commands, true);
  1417. // Help out users that try "gmake target1 target2 -j".
  1418. cmGlobalUnixMakefileGenerator3* gg =
  1419. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1420. if (gg->AllowNotParallel()) {
  1421. std::vector<std::string> no_depends;
  1422. this->WriteMakeRule(ruleFileStream,
  1423. "Allow only one \"make -f "
  1424. "Makefile2\" at a time, but pass "
  1425. "parallelism.",
  1426. ".NOTPARALLEL", no_depends, no_commands, false);
  1427. }
  1428. }
  1429. this->WriteSpecialTargetsTop(ruleFileStream);
  1430. // Include the progress variables for the target.
  1431. // Write all global targets
  1432. this->WriteDivider(ruleFileStream);
  1433. ruleFileStream << "# Targets provided globally by CMake.\n"
  1434. << "\n";
  1435. const auto& targets = this->GetGeneratorTargets();
  1436. for (const auto& gt : targets) {
  1437. if (gt->GetType() == cmStateEnums::GLOBAL_TARGET) {
  1438. std::string targetString =
  1439. "Special rule for the target " + gt->GetName();
  1440. std::vector<std::string> commands;
  1441. std::vector<std::string> depends;
  1442. const char* text = gt->GetProperty("EchoString");
  1443. if (!text) {
  1444. text = "Running external command ...";
  1445. }
  1446. depends.reserve(gt->GetUtilities().size());
  1447. for (BT<std::pair<std::string, bool>> const& u : gt->GetUtilities()) {
  1448. depends.push_back(u.Value.first);
  1449. }
  1450. this->AppendEcho(commands, text,
  1451. cmLocalUnixMakefileGenerator3::EchoGlobal);
  1452. // Global targets store their rules in pre- and post-build commands.
  1453. this->AppendCustomDepends(depends, gt->GetPreBuildCommands());
  1454. this->AppendCustomDepends(depends, gt->GetPostBuildCommands());
  1455. this->AppendCustomCommands(commands, gt->GetPreBuildCommands(), gt.get(),
  1456. this->GetCurrentBinaryDirectory());
  1457. this->AppendCustomCommands(commands, gt->GetPostBuildCommands(),
  1458. gt.get(), this->GetCurrentBinaryDirectory());
  1459. std::string targetName = gt->GetName();
  1460. this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
  1461. depends, commands, true);
  1462. // Provide a "/fast" version of the target.
  1463. depends.clear();
  1464. if ((targetName == "install") || (targetName == "install/local") ||
  1465. (targetName == "install/strip")) {
  1466. // Provide a fast install target that does not depend on all
  1467. // but has the same command.
  1468. depends.emplace_back("preinstall/fast");
  1469. } else {
  1470. // Just forward to the real target so at least it will work.
  1471. depends.push_back(targetName);
  1472. commands.clear();
  1473. }
  1474. targetName += "/fast";
  1475. this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
  1476. depends, commands, true);
  1477. }
  1478. }
  1479. std::vector<std::string> depends;
  1480. std::vector<std::string> commands;
  1481. // Write the all rule.
  1482. std::string recursiveTarget =
  1483. cmStrCat(this->GetCurrentBinaryDirectory(), "/all");
  1484. bool regenerate =
  1485. !this->GlobalGenerator->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION");
  1486. if (regenerate) {
  1487. depends.emplace_back("cmake_check_build_system");
  1488. }
  1489. std::string progressDir =
  1490. cmStrCat(this->GetBinaryDirectory(), "/CMakeFiles");
  1491. {
  1492. std::ostringstream progCmd;
  1493. progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start ";
  1494. progCmd << this->ConvertToOutputFormat(
  1495. cmSystemTools::CollapseFullPath(progressDir), cmOutputConverter::SHELL);
  1496. std::string progressFile = "/CMakeFiles/progress.marks";
  1497. std::string progressFileNameFull = this->ConvertToFullPath(progressFile);
  1498. progCmd << " "
  1499. << this->ConvertToOutputFormat(
  1500. cmSystemTools::CollapseFullPath(progressFileNameFull),
  1501. cmOutputConverter::SHELL);
  1502. commands.push_back(progCmd.str());
  1503. }
  1504. std::string mf2Dir = "CMakeFiles/Makefile2";
  1505. commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
  1506. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1507. this->GetCurrentBinaryDirectory());
  1508. {
  1509. std::ostringstream progCmd;
  1510. progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; // # 0
  1511. progCmd << this->ConvertToOutputFormat(
  1512. cmSystemTools::CollapseFullPath(progressDir), cmOutputConverter::SHELL);
  1513. progCmd << " 0";
  1514. commands.push_back(progCmd.str());
  1515. }
  1516. this->WriteMakeRule(ruleFileStream, "The main all target", "all", depends,
  1517. commands, true);
  1518. // Write the clean rule.
  1519. recursiveTarget = cmStrCat(this->GetCurrentBinaryDirectory(), "/clean");
  1520. commands.clear();
  1521. depends.clear();
  1522. commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
  1523. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1524. this->GetCurrentBinaryDirectory());
  1525. this->WriteMakeRule(ruleFileStream, "The main clean target", "clean",
  1526. depends, commands, true);
  1527. commands.clear();
  1528. depends.clear();
  1529. depends.emplace_back("clean");
  1530. this->WriteMakeRule(ruleFileStream, "The main clean target", "clean/fast",
  1531. depends, commands, true);
  1532. // Write the preinstall rule.
  1533. recursiveTarget = cmStrCat(this->GetCurrentBinaryDirectory(), "/preinstall");
  1534. commands.clear();
  1535. depends.clear();
  1536. const char* noall =
  1537. this->Makefile->GetDefinition("CMAKE_SKIP_INSTALL_ALL_DEPENDENCY");
  1538. if (!noall || cmIsOff(noall)) {
  1539. // Drive the build before installing.
  1540. depends.emplace_back("all");
  1541. } else if (regenerate) {
  1542. // At least make sure the build system is up to date.
  1543. depends.emplace_back("cmake_check_build_system");
  1544. }
  1545. commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
  1546. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1547. this->GetCurrentBinaryDirectory());
  1548. this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
  1549. "preinstall", depends, commands, true);
  1550. depends.clear();
  1551. this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
  1552. "preinstall/fast", depends, commands, true);
  1553. if (regenerate) {
  1554. // write the depend rule, really a recompute depends rule
  1555. depends.clear();
  1556. commands.clear();
  1557. cmake* cm = this->GlobalGenerator->GetCMakeInstance();
  1558. if (cm->DoWriteGlobVerifyTarget()) {
  1559. std::string rescanRule =
  1560. cmStrCat("$(CMAKE_COMMAND) -P ",
  1561. this->ConvertToOutputFormat(cm->GetGlobVerifyScript(),
  1562. cmOutputConverter::SHELL));
  1563. commands.push_back(rescanRule);
  1564. }
  1565. std::string cmakefileName = "CMakeFiles/Makefile.cmake";
  1566. {
  1567. std::string runRule = cmStrCat(
  1568. "$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) "
  1569. "--check-build-system ",
  1570. this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL),
  1571. " 1");
  1572. commands.push_back(std::move(runRule));
  1573. }
  1574. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1575. this->GetCurrentBinaryDirectory());
  1576. this->WriteMakeRule(ruleFileStream, "clear depends", "depend", depends,
  1577. commands, true);
  1578. }
  1579. }
  1580. void cmLocalUnixMakefileGenerator3::ClearDependencies(cmMakefile* mf,
  1581. bool verbose)
  1582. {
  1583. // Get the list of target files to check
  1584. const char* infoDef = mf->GetDefinition("CMAKE_DEPEND_INFO_FILES");
  1585. if (!infoDef) {
  1586. return;
  1587. }
  1588. std::vector<std::string> files = cmExpandedList(infoDef);
  1589. // Each depend information file corresponds to a target. Clear the
  1590. // dependencies for that target.
  1591. cmDepends clearer;
  1592. clearer.SetVerbose(verbose);
  1593. for (std::string const& file : files) {
  1594. std::string dir = cmSystemTools::GetFilenamePath(file);
  1595. // Clear the implicit dependency makefile.
  1596. std::string dependFile = dir + "/depend.make";
  1597. clearer.Clear(dependFile);
  1598. // Remove the internal dependency check file to force
  1599. // regeneration.
  1600. std::string internalDependFile = dir + "/depend.internal";
  1601. cmSystemTools::RemoveFile(internalDependFile);
  1602. }
  1603. }
  1604. namespace {
  1605. // Helper predicate for removing absolute paths that don't point to the
  1606. // source or binary directory. It is used when CMAKE_DEPENDS_IN_PROJECT_ONLY
  1607. // is set ON, to only consider in-project dependencies during the build.
  1608. class NotInProjectDir
  1609. {
  1610. public:
  1611. // Constructor with the source and binary directory's path
  1612. NotInProjectDir(std::string sourceDir, std::string binaryDir)
  1613. : SourceDir(std::move(sourceDir))
  1614. , BinaryDir(std::move(binaryDir))
  1615. {
  1616. }
  1617. // Operator evaluating the predicate
  1618. bool operator()(const std::string& path) const
  1619. {
  1620. // Keep all relative paths:
  1621. if (!cmSystemTools::FileIsFullPath(path)) {
  1622. return false;
  1623. }
  1624. // If it's an absolute path, check if it starts with the source
  1625. // direcotory:
  1626. return (
  1627. !(IsInDirectory(SourceDir, path) || IsInDirectory(BinaryDir, path)));
  1628. }
  1629. private:
  1630. // Helper function used by the predicate
  1631. static bool IsInDirectory(const std::string& baseDir,
  1632. const std::string& testDir)
  1633. {
  1634. // First check if the test directory "starts with" the base directory:
  1635. if (testDir.find(baseDir) != 0) {
  1636. return false;
  1637. }
  1638. // If it does, then check that it's either the same string, or that the
  1639. // next character is a slash:
  1640. return ((testDir.size() == baseDir.size()) ||
  1641. (testDir[baseDir.size()] == '/'));
  1642. }
  1643. // The path to the source directory
  1644. std::string SourceDir;
  1645. // The path to the binary directory
  1646. std::string BinaryDir;
  1647. };
  1648. }
  1649. void cmLocalUnixMakefileGenerator3::WriteDependLanguageInfo(
  1650. std::ostream& cmakefileStream, cmGeneratorTarget* target)
  1651. {
  1652. ImplicitDependLanguageMap const& implicitLangs =
  1653. this->GetImplicitDepends(target);
  1654. // list the languages
  1655. cmakefileStream
  1656. << "# The set of languages for which implicit dependencies are needed:\n";
  1657. cmakefileStream << "set(CMAKE_DEPENDS_LANGUAGES\n";
  1658. for (auto const& implicitLang : implicitLangs) {
  1659. cmakefileStream << " \"" << implicitLang.first << "\"\n";
  1660. }
  1661. cmakefileStream << " )\n";
  1662. // now list the files for each language
  1663. cmakefileStream
  1664. << "# The set of files for implicit dependencies of each language:\n";
  1665. for (auto const& implicitLang : implicitLangs) {
  1666. cmakefileStream << "set(CMAKE_DEPENDS_CHECK_" << implicitLang.first
  1667. << "\n";
  1668. ImplicitDependFileMap const& implicitPairs = implicitLang.second;
  1669. // for each file pair
  1670. for (auto const& implicitPair : implicitPairs) {
  1671. for (auto const& di : implicitPair.second) {
  1672. cmakefileStream << " \"" << di << "\" ";
  1673. cmakefileStream << "\"" << implicitPair.first << "\"\n";
  1674. }
  1675. }
  1676. cmakefileStream << " )\n";
  1677. // Tell the dependency scanner what compiler is used.
  1678. std::string cidVar =
  1679. cmStrCat("CMAKE_", implicitLang.first, "_COMPILER_ID");
  1680. const char* cid = this->Makefile->GetDefinition(cidVar);
  1681. if (cid && *cid) {
  1682. cmakefileStream << "set(CMAKE_" << implicitLang.first
  1683. << "_COMPILER_ID \"" << cid << "\")\n";
  1684. }
  1685. if (implicitLang.first == "Fortran") {
  1686. std::string smodSep =
  1687. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_SEP");
  1688. std::string smodExt =
  1689. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_EXT");
  1690. cmakefileStream << "set(CMAKE_Fortran_SUBMODULE_SEP \"" << smodSep
  1691. << "\")\n";
  1692. cmakefileStream << "set(CMAKE_Fortran_SUBMODULE_EXT \"" << smodExt
  1693. << "\")\n";
  1694. }
  1695. // Build a list of preprocessor definitions for the target.
  1696. std::set<std::string> defines;
  1697. this->GetTargetDefines(target, this->GetConfigName(), implicitLang.first,
  1698. defines);
  1699. if (!defines.empty()) {
  1700. /* clang-format off */
  1701. cmakefileStream
  1702. << "\n"
  1703. << "# Preprocessor definitions for this target.\n"
  1704. << "set(CMAKE_TARGET_DEFINITIONS_" << implicitLang.first << "\n";
  1705. /* clang-format on */
  1706. for (std::string const& define : defines) {
  1707. cmakefileStream << " " << cmOutputConverter::EscapeForCMake(define)
  1708. << "\n";
  1709. }
  1710. cmakefileStream << " )\n";
  1711. }
  1712. // Target-specific include directories:
  1713. cmakefileStream << "\n"
  1714. << "# The include file search paths:\n";
  1715. cmakefileStream << "set(CMAKE_" << implicitLang.first
  1716. << "_TARGET_INCLUDE_PATH\n";
  1717. std::vector<std::string> includes;
  1718. this->GetIncludeDirectories(includes, target, implicitLang.first,
  1719. this->GetConfigName());
  1720. std::string binaryDir = this->GetState()->GetBinaryDirectory();
  1721. if (this->Makefile->IsOn("CMAKE_DEPENDS_IN_PROJECT_ONLY")) {
  1722. std::string const& sourceDir = this->GetState()->GetSourceDirectory();
  1723. cm::erase_if(includes, ::NotInProjectDir(sourceDir, binaryDir));
  1724. }
  1725. for (std::string const& include : includes) {
  1726. cmakefileStream << " \""
  1727. << this->MaybeConvertToRelativePath(binaryDir, include)
  1728. << "\"\n";
  1729. }
  1730. cmakefileStream << " )\n";
  1731. }
  1732. // Store include transform rule properties. Write the directory
  1733. // rules first because they may be overridden by later target rules.
  1734. std::vector<std::string> transformRules;
  1735. if (const char* xform =
  1736. this->Makefile->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
  1737. cmExpandList(xform, transformRules);
  1738. }
  1739. if (const char* xform =
  1740. target->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
  1741. cmExpandList(xform, transformRules);
  1742. }
  1743. if (!transformRules.empty()) {
  1744. cmakefileStream << "set(CMAKE_INCLUDE_TRANSFORMS\n";
  1745. for (std::string const& tr : transformRules) {
  1746. cmakefileStream << " " << cmOutputConverter::EscapeForCMake(tr) << "\n";
  1747. }
  1748. cmakefileStream << " )\n";
  1749. }
  1750. }
  1751. void cmLocalUnixMakefileGenerator3::WriteDisclaimer(std::ostream& os)
  1752. {
  1753. os << "# CMAKE generated file: DO NOT EDIT!\n"
  1754. << "# Generated by \"" << this->GlobalGenerator->GetName() << "\""
  1755. << " Generator, CMake Version " << cmVersion::GetMajorVersion() << "."
  1756. << cmVersion::GetMinorVersion() << "\n\n";
  1757. }
  1758. std::string cmLocalUnixMakefileGenerator3::GetRecursiveMakeCall(
  1759. const std::string& makefile, const std::string& tgt)
  1760. {
  1761. // Call make on the given file.
  1762. std::string cmd = cmStrCat(
  1763. "$(MAKE) $(MAKESILENT) -f ",
  1764. this->ConvertToOutputFormat(makefile, cmOutputConverter::SHELL), ' ');
  1765. cmGlobalUnixMakefileGenerator3* gg =
  1766. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1767. // Pass down verbosity level.
  1768. if (!gg->MakeSilentFlag.empty()) {
  1769. cmd += gg->MakeSilentFlag;
  1770. cmd += " ";
  1771. }
  1772. // Most unix makes will pass the command line flags to make down to
  1773. // sub-invoked makes via an environment variable. However, some
  1774. // makes do not support that, so you have to pass the flags
  1775. // explicitly.
  1776. if (gg->PassMakeflags) {
  1777. cmd += "-$(MAKEFLAGS) ";
  1778. }
  1779. // Add the target.
  1780. if (!tgt.empty()) {
  1781. // The make target is always relative to the top of the build tree.
  1782. std::string tgt2 =
  1783. this->MaybeConvertToRelativePath(this->GetBinaryDirectory(), tgt);
  1784. // The target may have been written with windows paths.
  1785. cmSystemTools::ConvertToOutputSlashes(tgt2);
  1786. // Escape one extra time if the make tool requires it.
  1787. if (this->MakeCommandEscapeTargetTwice) {
  1788. tgt2 = this->EscapeForShell(tgt2, true, false);
  1789. }
  1790. // The target name is now a string that should be passed verbatim
  1791. // on the command line.
  1792. cmd += this->EscapeForShell(tgt2, true, false);
  1793. }
  1794. return cmd;
  1795. }
  1796. void cmLocalUnixMakefileGenerator3::WriteDivider(std::ostream& os)
  1797. {
  1798. os << "#======================================"
  1799. << "=======================================\n";
  1800. }
  1801. void cmLocalUnixMakefileGenerator3::WriteCMakeArgument(std::ostream& os,
  1802. const std::string& s)
  1803. {
  1804. // Write the given string to the stream with escaping to get it back
  1805. // into CMake through the lexical scanner.
  1806. os << "\"";
  1807. for (char c : s) {
  1808. if (c == '\\') {
  1809. os << "\\\\";
  1810. } else if (c == '"') {
  1811. os << "\\\"";
  1812. } else {
  1813. os << c;
  1814. }
  1815. }
  1816. os << "\"";
  1817. }
  1818. std::string cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(
  1819. const std::string& p, bool useWatcomQuote)
  1820. {
  1821. // Split the path into its components.
  1822. std::vector<std::string> components;
  1823. cmSystemTools::SplitPath(p, components);
  1824. // Open the quoted result.
  1825. std::string result;
  1826. if (useWatcomQuote) {
  1827. #if defined(_WIN32) && !defined(__CYGWIN__)
  1828. result = "'";
  1829. #else
  1830. result = "\"'";
  1831. #endif
  1832. } else {
  1833. result = "\"";
  1834. }
  1835. // Return an empty path if there are no components.
  1836. if (!components.empty()) {
  1837. // Choose a slash direction and fix root component.
  1838. const char* slash = "/";
  1839. #if defined(_WIN32) && !defined(__CYGWIN__)
  1840. if (!cmSystemTools::GetForceUnixPaths()) {
  1841. slash = "\\";
  1842. for (char& i : components[0]) {
  1843. if (i == '/') {
  1844. i = '\\';
  1845. }
  1846. }
  1847. }
  1848. #endif
  1849. // Begin the quoted result with the root component.
  1850. result += components[0];
  1851. if (components.size() > 1) {
  1852. // Now add the rest of the components separated by the proper slash
  1853. // direction for this platform.
  1854. auto compEnd = std::remove(components.begin() + 1, components.end() - 1,
  1855. std::string());
  1856. auto compStart = components.begin() + 1;
  1857. result += cmJoin(cmMakeRange(compStart, compEnd), slash);
  1858. // Only the last component can be empty to avoid double slashes.
  1859. result += slash;
  1860. result += components.back();
  1861. }
  1862. }
  1863. // Close the quoted result.
  1864. if (useWatcomQuote) {
  1865. #if defined(_WIN32) && !defined(__CYGWIN__)
  1866. result += "'";
  1867. #else
  1868. result += "'\"";
  1869. #endif
  1870. } else {
  1871. result += "\"";
  1872. }
  1873. return result;
  1874. }
  1875. std::string cmLocalUnixMakefileGenerator3::GetTargetDirectory(
  1876. cmGeneratorTarget const* target) const
  1877. {
  1878. std::string dir = cmStrCat("CMakeFiles/", target->GetName());
  1879. #if defined(__VMS)
  1880. dir += "_dir";
  1881. #else
  1882. dir += ".dir";
  1883. #endif
  1884. return dir;
  1885. }
  1886. cmLocalUnixMakefileGenerator3::ImplicitDependLanguageMap const&
  1887. cmLocalUnixMakefileGenerator3::GetImplicitDepends(const cmGeneratorTarget* tgt)
  1888. {
  1889. return this->ImplicitDepends[tgt->GetName()];
  1890. }
  1891. void cmLocalUnixMakefileGenerator3::AddImplicitDepends(
  1892. const cmGeneratorTarget* tgt, const std::string& lang,
  1893. const std::string& obj, const std::string& src)
  1894. {
  1895. this->ImplicitDepends[tgt->GetName()][lang][obj].push_back(src);
  1896. }
  1897. void cmLocalUnixMakefileGenerator3::CreateCDCommand(
  1898. std::vector<std::string>& commands, std::string const& tgtDir,
  1899. std::string const& relDir)
  1900. {
  1901. // do we need to cd?
  1902. if (tgtDir == relDir) {
  1903. return;
  1904. }
  1905. // In a Windows shell we must change drive letter too. The shell
  1906. // used by NMake and Borland make does not support "cd /d" so this
  1907. // feature simply cannot work with them (Borland make does not even
  1908. // support changing the drive letter with just "d:").
  1909. const char* cd_cmd = this->IsMinGWMake() ? "cd /d " : "cd ";
  1910. cmGlobalUnixMakefileGenerator3* gg =
  1911. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1912. if (!gg->UnixCD) {
  1913. // On Windows we must perform each step separately and then change
  1914. // back because the shell keeps the working directory between
  1915. // commands.
  1916. std::string cmd =
  1917. cmStrCat(cd_cmd, this->ConvertToOutputForExisting(tgtDir));
  1918. commands.insert(commands.begin(), cmd);
  1919. // Change back to the starting directory.
  1920. cmd = cmStrCat(cd_cmd, this->ConvertToOutputForExisting(relDir));
  1921. commands.push_back(std::move(cmd));
  1922. } else {
  1923. // On UNIX we must construct a single shell command to change
  1924. // directory and build because make resets the directory between
  1925. // each command.
  1926. std::string outputForExisting = this->ConvertToOutputForExisting(tgtDir);
  1927. std::string prefix = cd_cmd + outputForExisting + " && ";
  1928. std::transform(commands.begin(), commands.end(), commands.begin(),
  1929. [&prefix](std::string const& s) { return prefix + s; });
  1930. }
  1931. }