cmLocalUnixMakefileGenerator3.cxx 73 KB

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