cmLocalUnixMakefileGenerator3.cxx 73 KB

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