cmLocalUnixMakefileGenerator3.cxx 73 KB

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