cmLocalUnixMakefileGenerator3.cxx 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098
  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 "cmLocalGenerator.h"
  19. #include "cmMakefile.h"
  20. #include "cmMakefileTargetGenerator.h"
  21. #include "cmOutputConverter.h"
  22. #include "cmRulePlaceholderExpander.h"
  23. #include "cmSourceFile.h"
  24. #include "cmState.h"
  25. #include "cmStateDirectory.h"
  26. #include "cmStateSnapshot.h"
  27. #include "cmStateTypes.h"
  28. #include "cmSystemTools.h"
  29. #include "cmVersion.h"
  30. #include "cmake.h"
  31. // Include dependency scanners for supported languages. Only the
  32. // C/C++ scanner is needed for bootstrapping CMake.
  33. #include "cmDependsC.h"
  34. #ifdef CMAKE_BUILD_WITH_CMAKE
  35. # include "cmDependsFortran.h"
  36. # include "cmDependsJava.h"
  37. #endif
  38. // Escape special characters in Makefile dependency lines
  39. class cmMakeSafe
  40. {
  41. public:
  42. cmMakeSafe(const char* s)
  43. : Data(s)
  44. {
  45. }
  46. cmMakeSafe(std::string const& s)
  47. : Data(s.c_str())
  48. {
  49. }
  50. private:
  51. const char* Data;
  52. friend std::ostream& operator<<(std::ostream& os, cmMakeSafe const& self)
  53. {
  54. for (const char* c = self.Data; *c; ++c) {
  55. switch (*c) {
  56. case '=':
  57. os << "$(EQUALS)";
  58. break;
  59. default:
  60. os << *c;
  61. break;
  62. }
  63. }
  64. return os;
  65. }
  66. };
  67. // Helper function used below.
  68. static std::string cmSplitExtension(std::string const& in, std::string& base)
  69. {
  70. std::string ext;
  71. std::string::size_type dot_pos = in.rfind('.');
  72. if (dot_pos != std::string::npos) {
  73. // Remove the extension first in case &base == &in.
  74. ext = in.substr(dot_pos);
  75. base = in.substr(0, dot_pos);
  76. } else {
  77. base = in;
  78. }
  79. return ext;
  80. }
  81. cmLocalUnixMakefileGenerator3::cmLocalUnixMakefileGenerator3(
  82. cmGlobalGenerator* gg, cmMakefile* mf)
  83. : cmLocalCommonGenerator(gg, mf, mf->GetCurrentBinaryDirectory())
  84. {
  85. this->MakefileVariableSize = 0;
  86. this->ColorMakefile = false;
  87. this->SkipPreprocessedSourceRules = false;
  88. this->SkipAssemblySourceRules = false;
  89. this->MakeCommandEscapeTargetTwice = false;
  90. this->BorlandMakeCurlyHack = false;
  91. }
  92. cmLocalUnixMakefileGenerator3::~cmLocalUnixMakefileGenerator3()
  93. {
  94. }
  95. void cmLocalUnixMakefileGenerator3::Generate()
  96. {
  97. // Record whether some options are enabled to avoid checking many
  98. // times later.
  99. if (!this->GetGlobalGenerator()->GetCMakeInstance()->GetIsInTryCompile()) {
  100. this->ColorMakefile = this->Makefile->IsOn("CMAKE_COLOR_MAKEFILE");
  101. }
  102. this->SkipPreprocessedSourceRules =
  103. this->Makefile->IsOn("CMAKE_SKIP_PREPROCESSED_SOURCE_RULES");
  104. this->SkipAssemblySourceRules =
  105. this->Makefile->IsOn("CMAKE_SKIP_ASSEMBLY_SOURCE_RULES");
  106. // Generate the rule files for each target.
  107. const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
  108. cmGlobalUnixMakefileGenerator3* gg =
  109. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  110. for (cmGeneratorTarget* target : targets) {
  111. if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  112. continue;
  113. }
  114. std::unique_ptr<cmMakefileTargetGenerator> tg(
  115. cmMakefileTargetGenerator::New(target));
  116. if (tg) {
  117. tg->WriteRuleFiles();
  118. gg->RecordTargetProgress(tg.get());
  119. }
  120. }
  121. // write the local Makefile
  122. this->WriteLocalMakefile();
  123. // Write the cmake file with information for this directory.
  124. this->WriteDirectoryInformationFile();
  125. }
  126. void cmLocalUnixMakefileGenerator3::ComputeHomeRelativeOutputPath()
  127. {
  128. // Compute the path to use when referencing the current output
  129. // directory from the top output directory.
  130. this->HomeRelativeOutputPath = this->MaybeConvertToRelativePath(
  131. this->GetBinaryDirectory(), this->GetCurrentBinaryDirectory());
  132. if (this->HomeRelativeOutputPath == ".") {
  133. this->HomeRelativeOutputPath.clear();
  134. }
  135. if (!this->HomeRelativeOutputPath.empty()) {
  136. this->HomeRelativeOutputPath += "/";
  137. }
  138. }
  139. void cmLocalUnixMakefileGenerator3::GetLocalObjectFiles(
  140. std::map<std::string, LocalObjectInfo>& localObjectFiles)
  141. {
  142. const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
  143. for (cmGeneratorTarget* gt : targets) {
  144. if (gt->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  145. continue;
  146. }
  147. std::vector<cmSourceFile const*> objectSources;
  148. gt->GetObjectSources(
  149. objectSources, this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
  150. // Compute full path to object file directory for this target.
  151. std::string dir;
  152. dir += gt->LocalGenerator->GetCurrentBinaryDirectory();
  153. dir += "/";
  154. dir += this->GetTargetDirectory(gt);
  155. dir += "/";
  156. // Compute the name of each object file.
  157. for (cmSourceFile const* sf : objectSources) {
  158. bool hasSourceExtension = true;
  159. std::string objectName =
  160. this->GetObjectFileNameWithoutTarget(*sf, dir, &hasSourceExtension);
  161. if (cmSystemTools::FileIsFullPath(objectName)) {
  162. objectName = cmSystemTools::GetFilenameName(objectName);
  163. }
  164. LocalObjectInfo& info = localObjectFiles[objectName];
  165. info.HasSourceExtension = hasSourceExtension;
  166. info.emplace_back(gt, sf->GetLanguage());
  167. }
  168. }
  169. }
  170. void cmLocalUnixMakefileGenerator3::GetIndividualFileTargets(
  171. std::vector<std::string>& targets)
  172. {
  173. std::map<std::string, LocalObjectInfo> localObjectFiles;
  174. this->GetLocalObjectFiles(localObjectFiles);
  175. for (auto const& localObjectFile : localObjectFiles) {
  176. targets.push_back(localObjectFile.first);
  177. std::string::size_type dot_pos = localObjectFile.first.rfind(".");
  178. std::string base = localObjectFile.first.substr(0, dot_pos);
  179. if (localObjectFile.second.HasPreprocessRule) {
  180. targets.push_back(base + ".i");
  181. }
  182. if (localObjectFile.second.HasAssembleRule) {
  183. targets.push_back(base + ".s");
  184. }
  185. }
  186. }
  187. void cmLocalUnixMakefileGenerator3::WriteLocalMakefile()
  188. {
  189. // generate the includes
  190. std::string ruleFileName = "Makefile";
  191. // Open the rule file. This should be copy-if-different because the
  192. // rules may depend on this file itself.
  193. std::string ruleFileNameFull = this->ConvertToFullPath(ruleFileName);
  194. cmGeneratedFileStream ruleFileStream(
  195. ruleFileNameFull, false, this->GlobalGenerator->GetMakefileEncoding());
  196. if (!ruleFileStream) {
  197. return;
  198. }
  199. // always write the top makefile
  200. if (!this->IsRootMakefile()) {
  201. ruleFileStream.SetCopyIfDifferent(true);
  202. }
  203. // write the all rules
  204. this->WriteLocalAllRules(ruleFileStream);
  205. // only write local targets unless at the top Keep track of targets already
  206. // listed.
  207. std::set<std::string> emittedTargets;
  208. if (!this->IsRootMakefile()) {
  209. // write our targets, and while doing it collect up the object
  210. // file rules
  211. this->WriteLocalMakefileTargets(ruleFileStream, emittedTargets);
  212. } else {
  213. cmGlobalUnixMakefileGenerator3* gg =
  214. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  215. gg->WriteConvenienceRules(ruleFileStream, emittedTargets);
  216. }
  217. bool do_preprocess_rules = this->GetCreatePreprocessedSourceRules();
  218. bool do_assembly_rules = this->GetCreateAssemblySourceRules();
  219. std::map<std::string, LocalObjectInfo> localObjectFiles;
  220. this->GetLocalObjectFiles(localObjectFiles);
  221. // now write out the object rules
  222. // for each object file name
  223. for (auto& localObjectFile : localObjectFiles) {
  224. // Add a convenience rule for building the object file.
  225. this->WriteObjectConvenienceRule(
  226. ruleFileStream, "target to build an object file",
  227. localObjectFile.first.c_str(), localObjectFile.second);
  228. // Check whether preprocessing and assembly rules make sense.
  229. // They make sense only for C and C++ sources.
  230. bool lang_has_preprocessor = false;
  231. bool lang_has_assembly = false;
  232. for (LocalObjectEntry const& entry : localObjectFile.second) {
  233. if (entry.Language == "C" || entry.Language == "CXX" ||
  234. entry.Language == "CUDA" || entry.Language == "Fortran") {
  235. // Right now, C, C++, Fortran and CUDA have both a preprocessor and the
  236. // ability to generate assembly code
  237. lang_has_preprocessor = true;
  238. lang_has_assembly = true;
  239. break;
  240. }
  241. }
  242. // Add convenience rules for preprocessed and assembly files.
  243. if (lang_has_preprocessor && do_preprocess_rules) {
  244. std::string::size_type dot_pos = localObjectFile.first.rfind(".");
  245. std::string base = localObjectFile.first.substr(0, dot_pos);
  246. this->WriteObjectConvenienceRule(
  247. ruleFileStream, "target to preprocess a source file",
  248. (base + ".i").c_str(), localObjectFile.second);
  249. localObjectFile.second.HasPreprocessRule = true;
  250. }
  251. if (lang_has_assembly && do_assembly_rules) {
  252. std::string::size_type dot_pos = localObjectFile.first.rfind(".");
  253. std::string base = localObjectFile.first.substr(0, dot_pos);
  254. this->WriteObjectConvenienceRule(
  255. ruleFileStream, "target to generate assembly for a file",
  256. (base + ".s").c_str(), localObjectFile.second);
  257. localObjectFile.second.HasAssembleRule = true;
  258. }
  259. }
  260. // add a help target as long as there isn;t a real target named help
  261. if (emittedTargets.insert("help").second) {
  262. cmGlobalUnixMakefileGenerator3* gg =
  263. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  264. gg->WriteHelpRule(ruleFileStream, this);
  265. }
  266. this->WriteSpecialTargetsBottom(ruleFileStream);
  267. }
  268. void cmLocalUnixMakefileGenerator3::WriteObjectConvenienceRule(
  269. std::ostream& ruleFileStream, const char* comment, const char* output,
  270. LocalObjectInfo const& info)
  271. {
  272. // If the rule includes the source file extension then create a
  273. // version that has the extension removed. The help should include
  274. // only the version without source extension.
  275. bool inHelp = true;
  276. if (info.HasSourceExtension) {
  277. // Remove the last extension. This should be kept.
  278. std::string outBase1 = output;
  279. std::string outExt1 = cmSplitExtension(outBase1, outBase1);
  280. // Now remove the source extension and put back the last
  281. // extension.
  282. std::string outNoExt;
  283. cmSplitExtension(outBase1, outNoExt);
  284. outNoExt += outExt1;
  285. // Add a rule to drive the rule below.
  286. std::vector<std::string> depends;
  287. depends.push_back(output);
  288. std::vector<std::string> no_commands;
  289. this->WriteMakeRule(ruleFileStream, nullptr, outNoExt, depends,
  290. no_commands, true, true);
  291. inHelp = false;
  292. }
  293. // Recursively make the rule for each target using the object file.
  294. std::vector<std::string> commands;
  295. for (LocalObjectEntry const& t : info) {
  296. std::string tgtMakefileName = this->GetRelativeTargetDirectory(t.Target);
  297. std::string targetName = tgtMakefileName;
  298. tgtMakefileName += "/build.make";
  299. targetName += "/";
  300. targetName += output;
  301. commands.push_back(
  302. this->GetRecursiveMakeCall(tgtMakefileName.c_str(), targetName));
  303. }
  304. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  305. this->GetCurrentBinaryDirectory());
  306. // Write the rule to the makefile.
  307. std::vector<std::string> no_depends;
  308. this->WriteMakeRule(ruleFileStream, comment, output, no_depends, commands,
  309. true, inHelp);
  310. }
  311. void cmLocalUnixMakefileGenerator3::WriteLocalMakefileTargets(
  312. std::ostream& ruleFileStream, std::set<std::string>& emitted)
  313. {
  314. std::vector<std::string> depends;
  315. std::vector<std::string> commands;
  316. // for each target we just provide a rule to cd up to the top and do a make
  317. // on the target
  318. const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
  319. std::string localName;
  320. for (cmGeneratorTarget* target : targets) {
  321. if ((target->GetType() == cmStateEnums::EXECUTABLE) ||
  322. (target->GetType() == cmStateEnums::STATIC_LIBRARY) ||
  323. (target->GetType() == cmStateEnums::SHARED_LIBRARY) ||
  324. (target->GetType() == cmStateEnums::MODULE_LIBRARY) ||
  325. (target->GetType() == cmStateEnums::OBJECT_LIBRARY) ||
  326. (target->GetType() == cmStateEnums::UTILITY)) {
  327. emitted.insert(target->GetName());
  328. // for subdirs add a rule to build this specific target by name.
  329. localName = this->GetRelativeTargetDirectory(target);
  330. localName += "/rule";
  331. commands.clear();
  332. depends.clear();
  333. // Build the target for this pass.
  334. std::string makefile2 = cmake::GetCMakeFilesDirectoryPostSlash();
  335. makefile2 += "Makefile2";
  336. commands.push_back(
  337. this->GetRecursiveMakeCall(makefile2.c_str(), 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.c_str(), 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.c_str(), 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. this->WriteCMakeArgument(infoFileStream,
  425. this->Makefile->GetIncludeRegularExpression());
  426. infoFileStream << ")\n";
  427. infoFileStream << "set(CMAKE_C_INCLUDE_REGEX_COMPLAIN ";
  428. this->WriteCMakeArgument(infoFileStream,
  429. 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.push_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.push_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(const char* tgtInfo,
  1151. bool verbose,
  1152. bool color)
  1153. {
  1154. // read in the target info file
  1155. if (!this->Makefile->ReadListFile(tgtInfo) ||
  1156. cmSystemTools::GetErrorOccuredFlag()) {
  1157. cmSystemTools::Error("Target DependInfo.cmake file not found");
  1158. }
  1159. // Check if any multiple output pairs have a missing file.
  1160. this->CheckMultipleOutputs(verbose);
  1161. std::string dir = cmSystemTools::GetFilenamePath(tgtInfo);
  1162. std::string internalDependFile = dir + "/depend.internal";
  1163. std::string dependFile = dir + "/depend.make";
  1164. // If the target DependInfo.cmake file has changed since the last
  1165. // time dependencies were scanned then force rescanning. This may
  1166. // happen when a new source file is added and CMake regenerates the
  1167. // project but no other sources were touched.
  1168. bool needRescanDependInfo = false;
  1169. cmFileTimeComparison* ftc =
  1170. this->GlobalGenerator->GetCMakeInstance()->GetFileComparison();
  1171. {
  1172. int result;
  1173. if (!ftc->FileTimeCompare(internalDependFile.c_str(), tgtInfo, &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().c_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().c_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 = !checker.Check(
  1225. dependFile.c_str(), internalDependFile.c_str(), 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.c_str(), validDependencies);
  1237. }
  1238. // The dependencies are already up-to-date.
  1239. return true;
  1240. }
  1241. bool cmLocalUnixMakefileGenerator3::ScanDependencies(
  1242. const char* 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.c_str()) &&
  1252. !cmSystemTools::GetErrorOccuredFlag()) {
  1253. haveDirectoryInfo = true;
  1254. }
  1255. // Lookup useful directory information.
  1256. if (haveDirectoryInfo) {
  1257. // Test whether we need to force Unix paths.
  1258. if (const char* force = mf->GetDefinition("CMAKE_FORCE_UNIX_PATHS")) {
  1259. if (!cmSystemTools::IsOff(force)) {
  1260. cmSystemTools::SetForceUnixPaths(true);
  1261. }
  1262. }
  1263. // Setup relative path top directories.
  1264. if (const char* relativePathTopSource =
  1265. mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_SOURCE")) {
  1266. this->StateSnapshot.GetDirectory().SetRelativePathTopSource(
  1267. relativePathTopSource);
  1268. }
  1269. if (const char* relativePathTopBinary =
  1270. mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_BINARY")) {
  1271. this->StateSnapshot.GetDirectory().SetRelativePathTopBinary(
  1272. relativePathTopBinary);
  1273. }
  1274. } else {
  1275. cmSystemTools::Error("Directory Information file not found");
  1276. }
  1277. // create the file stream for the depends file
  1278. std::string dir = targetDir;
  1279. // Open the make depends file. This should be copy-if-different
  1280. // because the make tool may try to reload it needlessly otherwise.
  1281. std::string ruleFileNameFull = dir;
  1282. ruleFileNameFull += "/depend.make";
  1283. cmGeneratedFileStream ruleFileStream(
  1284. ruleFileNameFull, false, this->GlobalGenerator->GetMakefileEncoding());
  1285. ruleFileStream.SetCopyIfDifferent(true);
  1286. if (!ruleFileStream) {
  1287. return false;
  1288. }
  1289. // Open the cmake dependency tracking file. This should not be
  1290. // copy-if-different because dependencies are re-scanned when it is
  1291. // older than the DependInfo.cmake.
  1292. std::string internalRuleFileNameFull = dir;
  1293. internalRuleFileNameFull += "/depend.internal";
  1294. cmGeneratedFileStream internalRuleFileStream(
  1295. internalRuleFileNameFull, false,
  1296. this->GlobalGenerator->GetMakefileEncoding());
  1297. if (!internalRuleFileStream) {
  1298. return false;
  1299. }
  1300. this->WriteDisclaimer(ruleFileStream);
  1301. this->WriteDisclaimer(internalRuleFileStream);
  1302. // for each language we need to scan, scan it
  1303. std::string const& langStr =
  1304. mf->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES");
  1305. std::vector<std::string> langs;
  1306. cmSystemTools::ExpandListArgument(langStr, langs);
  1307. for (std::string const& lang : langs) {
  1308. // construct the checker
  1309. // Create the scanner for this language
  1310. cmDepends* scanner = nullptr;
  1311. if (lang == "C" || lang == "CXX" || lang == "RC" || lang == "ASM" ||
  1312. lang == "CUDA") {
  1313. // TODO: Handle RC (resource files) dependencies correctly.
  1314. scanner = new cmDependsC(this, targetDir, lang, &validDeps);
  1315. }
  1316. #ifdef CMAKE_BUILD_WITH_CMAKE
  1317. else if (lang == "Fortran") {
  1318. ruleFileStream << "# Note that incremental build could trigger "
  1319. << "a call to cmake_copy_f90_mod on each re-build\n";
  1320. scanner = new cmDependsFortran(this);
  1321. } else if (lang == "Java") {
  1322. scanner = new cmDependsJava();
  1323. }
  1324. #endif
  1325. if (scanner) {
  1326. scanner->SetLocalGenerator(this);
  1327. scanner->SetFileComparison(
  1328. this->GlobalGenerator->GetCMakeInstance()->GetFileComparison());
  1329. scanner->SetLanguage(lang);
  1330. scanner->SetTargetDirectory(dir.c_str());
  1331. scanner->Write(ruleFileStream, internalRuleFileStream);
  1332. // free the scanner for this language
  1333. delete scanner;
  1334. }
  1335. }
  1336. return true;
  1337. }
  1338. void cmLocalUnixMakefileGenerator3::CheckMultipleOutputs(bool verbose)
  1339. {
  1340. cmMakefile* mf = this->Makefile;
  1341. // Get the string listing the multiple output pairs.
  1342. const char* pairs_string = mf->GetDefinition("CMAKE_MULTIPLE_OUTPUT_PAIRS");
  1343. if (!pairs_string) {
  1344. return;
  1345. }
  1346. // Convert the string to a list and preserve empty entries.
  1347. std::vector<std::string> pairs;
  1348. cmSystemTools::ExpandListArgument(pairs_string, pairs, true);
  1349. for (std::vector<std::string>::const_iterator i = pairs.begin();
  1350. i != pairs.end() && (i + 1) != pairs.end();) {
  1351. const std::string& depender = *i++;
  1352. const std::string& dependee = *i++;
  1353. // If the depender is missing then delete the dependee to make
  1354. // sure both will be regenerated.
  1355. if (cmSystemTools::FileExists(dependee) &&
  1356. !cmSystemTools::FileExists(depender)) {
  1357. if (verbose) {
  1358. std::ostringstream msg;
  1359. msg << "Deleting primary custom command output \"" << dependee
  1360. << "\" because another output \"" << depender
  1361. << "\" does not exist." << std::endl;
  1362. cmSystemTools::Stdout(msg.str().c_str());
  1363. }
  1364. cmSystemTools::RemoveFile(dependee);
  1365. }
  1366. }
  1367. }
  1368. void cmLocalUnixMakefileGenerator3::WriteLocalAllRules(
  1369. std::ostream& ruleFileStream)
  1370. {
  1371. this->WriteDisclaimer(ruleFileStream);
  1372. // Write the main entry point target. This must be the VERY first
  1373. // target so that make with no arguments will run it.
  1374. {
  1375. // Just depend on the all target to drive the build.
  1376. std::vector<std::string> depends;
  1377. std::vector<std::string> no_commands;
  1378. depends.push_back("all");
  1379. // Write the rule.
  1380. this->WriteMakeRule(ruleFileStream,
  1381. "Default target executed when no arguments are "
  1382. "given to make.",
  1383. "default_target", depends, no_commands, true);
  1384. // Help out users that try "gmake target1 target2 -j".
  1385. cmGlobalUnixMakefileGenerator3* gg =
  1386. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1387. if (gg->AllowNotParallel()) {
  1388. std::vector<std::string> no_depends;
  1389. this->WriteMakeRule(ruleFileStream,
  1390. "Allow only one \"make -f "
  1391. "Makefile2\" at a time, but pass "
  1392. "parallelism.",
  1393. ".NOTPARALLEL", no_depends, no_commands, false);
  1394. }
  1395. }
  1396. this->WriteSpecialTargetsTop(ruleFileStream);
  1397. // Include the progress variables for the target.
  1398. // Write all global targets
  1399. this->WriteDivider(ruleFileStream);
  1400. ruleFileStream << "# Targets provided globally by CMake.\n"
  1401. << "\n";
  1402. const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
  1403. for (cmGeneratorTarget* gt : targets) {
  1404. if (gt->GetType() == cmStateEnums::GLOBAL_TARGET) {
  1405. std::string targetString =
  1406. "Special rule for the target " + gt->GetName();
  1407. std::vector<std::string> commands;
  1408. std::vector<std::string> depends;
  1409. const char* text = gt->GetProperty("EchoString");
  1410. if (!text) {
  1411. text = "Running external command ...";
  1412. }
  1413. depends.insert(depends.end(), gt->GetUtilities().begin(),
  1414. gt->GetUtilities().end());
  1415. this->AppendEcho(commands, text,
  1416. cmLocalUnixMakefileGenerator3::EchoGlobal);
  1417. // Global targets store their rules in pre- and post-build commands.
  1418. this->AppendCustomDepends(depends, gt->GetPreBuildCommands());
  1419. this->AppendCustomDepends(depends, gt->GetPostBuildCommands());
  1420. this->AppendCustomCommands(commands, gt->GetPreBuildCommands(), gt,
  1421. this->GetCurrentBinaryDirectory());
  1422. this->AppendCustomCommands(commands, gt->GetPostBuildCommands(), gt,
  1423. this->GetCurrentBinaryDirectory());
  1424. std::string targetName = gt->GetName();
  1425. this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
  1426. depends, commands, true);
  1427. // Provide a "/fast" version of the target.
  1428. depends.clear();
  1429. if ((targetName == "install") || (targetName == "install/local") ||
  1430. (targetName == "install/strip")) {
  1431. // Provide a fast install target that does not depend on all
  1432. // but has the same command.
  1433. depends.push_back("preinstall/fast");
  1434. } else {
  1435. // Just forward to the real target so at least it will work.
  1436. depends.push_back(targetName);
  1437. commands.clear();
  1438. }
  1439. targetName += "/fast";
  1440. this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
  1441. depends, commands, true);
  1442. }
  1443. }
  1444. std::vector<std::string> depends;
  1445. std::vector<std::string> commands;
  1446. // Write the all rule.
  1447. std::string recursiveTarget = this->GetCurrentBinaryDirectory();
  1448. recursiveTarget += "/all";
  1449. bool regenerate =
  1450. !this->GlobalGenerator->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION");
  1451. if (regenerate) {
  1452. depends.push_back("cmake_check_build_system");
  1453. }
  1454. std::string progressDir = this->GetBinaryDirectory();
  1455. progressDir += cmake::GetCMakeFilesDirectory();
  1456. {
  1457. std::ostringstream progCmd;
  1458. progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start ";
  1459. progCmd << this->ConvertToOutputFormat(
  1460. cmSystemTools::CollapseFullPath(progressDir), cmOutputConverter::SHELL);
  1461. std::string progressFile = cmake::GetCMakeFilesDirectory();
  1462. progressFile += "/progress.marks";
  1463. std::string progressFileNameFull = this->ConvertToFullPath(progressFile);
  1464. progCmd << " "
  1465. << this->ConvertToOutputFormat(
  1466. cmSystemTools::CollapseFullPath(progressFileNameFull),
  1467. cmOutputConverter::SHELL);
  1468. commands.push_back(progCmd.str());
  1469. }
  1470. std::string mf2Dir = cmake::GetCMakeFilesDirectoryPostSlash();
  1471. mf2Dir += "Makefile2";
  1472. commands.push_back(
  1473. this->GetRecursiveMakeCall(mf2Dir.c_str(), recursiveTarget));
  1474. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1475. this->GetCurrentBinaryDirectory());
  1476. {
  1477. std::ostringstream progCmd;
  1478. progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; // # 0
  1479. progCmd << this->ConvertToOutputFormat(
  1480. cmSystemTools::CollapseFullPath(progressDir), cmOutputConverter::SHELL);
  1481. progCmd << " 0";
  1482. commands.push_back(progCmd.str());
  1483. }
  1484. this->WriteMakeRule(ruleFileStream, "The main all target", "all", depends,
  1485. commands, true);
  1486. // Write the clean rule.
  1487. recursiveTarget = this->GetCurrentBinaryDirectory();
  1488. recursiveTarget += "/clean";
  1489. commands.clear();
  1490. depends.clear();
  1491. commands.push_back(
  1492. this->GetRecursiveMakeCall(mf2Dir.c_str(), recursiveTarget));
  1493. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1494. this->GetCurrentBinaryDirectory());
  1495. this->WriteMakeRule(ruleFileStream, "The main clean target", "clean",
  1496. depends, commands, true);
  1497. commands.clear();
  1498. depends.clear();
  1499. depends.push_back("clean");
  1500. this->WriteMakeRule(ruleFileStream, "The main clean target", "clean/fast",
  1501. depends, commands, true);
  1502. // Write the preinstall rule.
  1503. recursiveTarget = this->GetCurrentBinaryDirectory();
  1504. recursiveTarget += "/preinstall";
  1505. commands.clear();
  1506. depends.clear();
  1507. const char* noall =
  1508. this->Makefile->GetDefinition("CMAKE_SKIP_INSTALL_ALL_DEPENDENCY");
  1509. if (!noall || cmSystemTools::IsOff(noall)) {
  1510. // Drive the build before installing.
  1511. depends.push_back("all");
  1512. } else if (regenerate) {
  1513. // At least make sure the build system is up to date.
  1514. depends.push_back("cmake_check_build_system");
  1515. }
  1516. commands.push_back(
  1517. this->GetRecursiveMakeCall(mf2Dir.c_str(), recursiveTarget));
  1518. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1519. this->GetCurrentBinaryDirectory());
  1520. this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
  1521. "preinstall", depends, commands, true);
  1522. depends.clear();
  1523. this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
  1524. "preinstall/fast", depends, commands, true);
  1525. if (regenerate) {
  1526. // write the depend rule, really a recompute depends rule
  1527. depends.clear();
  1528. commands.clear();
  1529. cmake* cm = this->GlobalGenerator->GetCMakeInstance();
  1530. if (cm->DoWriteGlobVerifyTarget()) {
  1531. std::string rescanRule = "$(CMAKE_COMMAND) -P ";
  1532. rescanRule += this->ConvertToOutputFormat(cm->GetGlobVerifyScript(),
  1533. cmOutputConverter::SHELL);
  1534. commands.push_back(rescanRule);
  1535. }
  1536. std::string cmakefileName = cmake::GetCMakeFilesDirectoryPostSlash();
  1537. cmakefileName += "Makefile.cmake";
  1538. {
  1539. std::string runRule =
  1540. "$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)";
  1541. runRule += " --check-build-system ";
  1542. runRule +=
  1543. this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL);
  1544. runRule += " 1";
  1545. commands.push_back(std::move(runRule));
  1546. }
  1547. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1548. this->GetCurrentBinaryDirectory());
  1549. this->WriteMakeRule(ruleFileStream, "clear depends", "depend", depends,
  1550. commands, true);
  1551. }
  1552. }
  1553. void cmLocalUnixMakefileGenerator3::ClearDependencies(cmMakefile* mf,
  1554. bool verbose)
  1555. {
  1556. // Get the list of target files to check
  1557. const char* infoDef = mf->GetDefinition("CMAKE_DEPEND_INFO_FILES");
  1558. if (!infoDef) {
  1559. return;
  1560. }
  1561. std::vector<std::string> files;
  1562. cmSystemTools::ExpandListArgument(infoDef, files);
  1563. // Each depend information file corresponds to a target. Clear the
  1564. // dependencies for that target.
  1565. cmDepends clearer;
  1566. clearer.SetVerbose(verbose);
  1567. for (std::string const& file : files) {
  1568. std::string dir = cmSystemTools::GetFilenamePath(file);
  1569. // Clear the implicit dependency makefile.
  1570. std::string dependFile = dir + "/depend.make";
  1571. clearer.Clear(dependFile.c_str());
  1572. // Remove the internal dependency check file to force
  1573. // regeneration.
  1574. std::string internalDependFile = dir + "/depend.internal";
  1575. cmSystemTools::RemoveFile(internalDependFile);
  1576. }
  1577. }
  1578. namespace {
  1579. // Helper predicate for removing absolute paths that don't point to the
  1580. // source or binary directory. It is used when CMAKE_DEPENDS_IN_PROJECT_ONLY
  1581. // is set ON, to only consider in-project dependencies during the build.
  1582. class NotInProjectDir
  1583. {
  1584. public:
  1585. // Constructor with the source and binary directory's path
  1586. NotInProjectDir(const std::string& sourceDir, const std::string& binaryDir)
  1587. : SourceDir(sourceDir)
  1588. , BinaryDir(binaryDir)
  1589. {
  1590. }
  1591. // Operator evaluating the predicate
  1592. bool operator()(const std::string& path) const
  1593. {
  1594. // Keep all relative paths:
  1595. if (!cmSystemTools::FileIsFullPath(path)) {
  1596. return false;
  1597. }
  1598. // If it's an absolute path, check if it starts with the source
  1599. // direcotory:
  1600. return (
  1601. !(IsInDirectory(SourceDir, path) || IsInDirectory(BinaryDir, path)));
  1602. }
  1603. private:
  1604. // Helper function used by the predicate
  1605. static bool IsInDirectory(const std::string& baseDir,
  1606. const std::string& testDir)
  1607. {
  1608. // First check if the test directory "starts with" the base directory:
  1609. if (testDir.find(baseDir) != 0) {
  1610. return false;
  1611. }
  1612. // If it does, then check that it's either the same string, or that the
  1613. // next character is a slash:
  1614. return ((testDir.size() == baseDir.size()) ||
  1615. (testDir[baseDir.size()] == '/'));
  1616. }
  1617. // The path to the source directory
  1618. std::string SourceDir;
  1619. // The path to the binary directory
  1620. std::string BinaryDir;
  1621. };
  1622. }
  1623. void cmLocalUnixMakefileGenerator3::WriteDependLanguageInfo(
  1624. std::ostream& cmakefileStream, cmGeneratorTarget* target)
  1625. {
  1626. ImplicitDependLanguageMap const& implicitLangs =
  1627. this->GetImplicitDepends(target);
  1628. // list the languages
  1629. cmakefileStream
  1630. << "# The set of languages for which implicit dependencies are needed:\n";
  1631. cmakefileStream << "set(CMAKE_DEPENDS_LANGUAGES\n";
  1632. for (auto const& implicitLang : implicitLangs) {
  1633. cmakefileStream << " \"" << implicitLang.first << "\"\n";
  1634. }
  1635. cmakefileStream << " )\n";
  1636. // now list the files for each language
  1637. cmakefileStream
  1638. << "# The set of files for implicit dependencies of each language:\n";
  1639. for (auto const& implicitLang : implicitLangs) {
  1640. cmakefileStream << "set(CMAKE_DEPENDS_CHECK_" << implicitLang.first
  1641. << "\n";
  1642. ImplicitDependFileMap const& implicitPairs = implicitLang.second;
  1643. // for each file pair
  1644. for (auto const& implicitPair : implicitPairs) {
  1645. for (auto const& di : implicitPair.second) {
  1646. cmakefileStream << " \"" << di << "\" ";
  1647. cmakefileStream << "\"" << implicitPair.first << "\"\n";
  1648. }
  1649. }
  1650. cmakefileStream << " )\n";
  1651. // Tell the dependency scanner what compiler is used.
  1652. std::string cidVar = "CMAKE_";
  1653. cidVar += implicitLang.first;
  1654. cidVar += "_COMPILER_ID";
  1655. const char* cid = this->Makefile->GetDefinition(cidVar);
  1656. if (cid && *cid) {
  1657. cmakefileStream << "set(CMAKE_" << implicitLang.first
  1658. << "_COMPILER_ID \"" << cid << "\")\n";
  1659. }
  1660. // Build a list of preprocessor definitions for the target.
  1661. std::set<std::string> defines;
  1662. this->GetTargetDefines(target, this->ConfigName, implicitLang.first,
  1663. defines);
  1664. if (!defines.empty()) {
  1665. /* clang-format off */
  1666. cmakefileStream
  1667. << "\n"
  1668. << "# Preprocessor definitions for this target.\n"
  1669. << "set(CMAKE_TARGET_DEFINITIONS_" << implicitLang.first << "\n";
  1670. /* clang-format on */
  1671. for (std::string const& define : defines) {
  1672. cmakefileStream << " " << cmOutputConverter::EscapeForCMake(define)
  1673. << "\n";
  1674. }
  1675. cmakefileStream << " )\n";
  1676. }
  1677. // Target-specific include directories:
  1678. cmakefileStream << "\n"
  1679. << "# The include file search paths:\n";
  1680. cmakefileStream << "set(CMAKE_" << implicitLang.first
  1681. << "_TARGET_INCLUDE_PATH\n";
  1682. std::vector<std::string> includes;
  1683. const std::string& config =
  1684. this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
  1685. this->GetIncludeDirectories(includes, target, implicitLang.first, config);
  1686. std::string binaryDir = this->GetState()->GetBinaryDirectory();
  1687. if (this->Makefile->IsOn("CMAKE_DEPENDS_IN_PROJECT_ONLY")) {
  1688. std::string const& sourceDir = this->GetState()->GetSourceDirectory();
  1689. cmEraseIf(includes, ::NotInProjectDir(sourceDir, binaryDir));
  1690. }
  1691. for (std::string const& include : includes) {
  1692. cmakefileStream << " \""
  1693. << this->MaybeConvertToRelativePath(binaryDir, include)
  1694. << "\"\n";
  1695. }
  1696. cmakefileStream << " )\n";
  1697. }
  1698. // Store include transform rule properties. Write the directory
  1699. // rules first because they may be overridden by later target rules.
  1700. std::vector<std::string> transformRules;
  1701. if (const char* xform =
  1702. this->Makefile->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
  1703. cmSystemTools::ExpandListArgument(xform, transformRules);
  1704. }
  1705. if (const char* xform =
  1706. target->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
  1707. cmSystemTools::ExpandListArgument(xform, transformRules);
  1708. }
  1709. if (!transformRules.empty()) {
  1710. cmakefileStream << "set(CMAKE_INCLUDE_TRANSFORMS\n";
  1711. for (std::string const& tr : transformRules) {
  1712. cmakefileStream << " " << cmOutputConverter::EscapeForCMake(tr) << "\n";
  1713. }
  1714. cmakefileStream << " )\n";
  1715. }
  1716. }
  1717. void cmLocalUnixMakefileGenerator3::WriteDisclaimer(std::ostream& os)
  1718. {
  1719. os << "# CMAKE generated file: DO NOT EDIT!\n"
  1720. << "# Generated by \"" << this->GlobalGenerator->GetName() << "\""
  1721. << " Generator, CMake Version " << cmVersion::GetMajorVersion() << "."
  1722. << cmVersion::GetMinorVersion() << "\n\n";
  1723. }
  1724. std::string cmLocalUnixMakefileGenerator3::GetRecursiveMakeCall(
  1725. const char* makefile, const std::string& tgt)
  1726. {
  1727. // Call make on the given file.
  1728. std::string cmd;
  1729. cmd += "$(MAKE) -f ";
  1730. cmd += this->ConvertToOutputFormat(makefile, cmOutputConverter::SHELL);
  1731. cmd += " ";
  1732. cmGlobalUnixMakefileGenerator3* gg =
  1733. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1734. // Pass down verbosity level.
  1735. if (!gg->MakeSilentFlag.empty()) {
  1736. cmd += gg->MakeSilentFlag;
  1737. cmd += " ";
  1738. }
  1739. // Most unix makes will pass the command line flags to make down to
  1740. // sub-invoked makes via an environment variable. However, some
  1741. // makes do not support that, so you have to pass the flags
  1742. // explicitly.
  1743. if (gg->PassMakeflags) {
  1744. cmd += "-$(MAKEFLAGS) ";
  1745. }
  1746. // Add the target.
  1747. if (!tgt.empty()) {
  1748. // The make target is always relative to the top of the build tree.
  1749. std::string tgt2 =
  1750. this->MaybeConvertToRelativePath(this->GetBinaryDirectory(), tgt);
  1751. // The target may have been written with windows paths.
  1752. cmSystemTools::ConvertToOutputSlashes(tgt2);
  1753. // Escape one extra time if the make tool requires it.
  1754. if (this->MakeCommandEscapeTargetTwice) {
  1755. tgt2 = this->EscapeForShell(tgt2, true, false);
  1756. }
  1757. // The target name is now a string that should be passed verbatim
  1758. // on the command line.
  1759. cmd += this->EscapeForShell(tgt2, true, false);
  1760. }
  1761. return cmd;
  1762. }
  1763. void cmLocalUnixMakefileGenerator3::WriteDivider(std::ostream& os)
  1764. {
  1765. os << "#======================================"
  1766. << "=======================================\n";
  1767. }
  1768. void cmLocalUnixMakefileGenerator3::WriteCMakeArgument(std::ostream& os,
  1769. const char* s)
  1770. {
  1771. // Write the given string to the stream with escaping to get it back
  1772. // into CMake through the lexical scanner.
  1773. os << "\"";
  1774. for (const char* c = s; *c; ++c) {
  1775. if (*c == '\\') {
  1776. os << "\\\\";
  1777. } else if (*c == '"') {
  1778. os << "\\\"";
  1779. } else {
  1780. os << *c;
  1781. }
  1782. }
  1783. os << "\"";
  1784. }
  1785. std::string cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(
  1786. const char* p, bool useWatcomQuote)
  1787. {
  1788. // Split the path into its components.
  1789. std::vector<std::string> components;
  1790. cmSystemTools::SplitPath(p, components);
  1791. // Open the quoted result.
  1792. std::string result;
  1793. if (useWatcomQuote) {
  1794. #if defined(_WIN32) && !defined(__CYGWIN__)
  1795. result = "'";
  1796. #else
  1797. result = "\"'";
  1798. #endif
  1799. } else {
  1800. result = "\"";
  1801. }
  1802. // Return an empty path if there are no components.
  1803. if (!components.empty()) {
  1804. // Choose a slash direction and fix root component.
  1805. const char* slash = "/";
  1806. #if defined(_WIN32) && !defined(__CYGWIN__)
  1807. if (!cmSystemTools::GetForceUnixPaths()) {
  1808. slash = "\\";
  1809. for (char& i : components[0]) {
  1810. if (i == '/') {
  1811. i = '\\';
  1812. }
  1813. }
  1814. }
  1815. #endif
  1816. // Begin the quoted result with the root component.
  1817. result += components[0];
  1818. if (components.size() > 1) {
  1819. // Now add the rest of the components separated by the proper slash
  1820. // direction for this platform.
  1821. std::vector<std::string>::const_iterator compEnd = std::remove(
  1822. components.begin() + 1, components.end() - 1, std::string());
  1823. std::vector<std::string>::const_iterator compStart =
  1824. components.begin() + 1;
  1825. result += cmJoin(cmMakeRange(compStart, compEnd), slash);
  1826. // Only the last component can be empty to avoid double slashes.
  1827. result += slash;
  1828. result += components.back();
  1829. }
  1830. }
  1831. // Close the quoted result.
  1832. if (useWatcomQuote) {
  1833. #if defined(_WIN32) && !defined(__CYGWIN__)
  1834. result += "'";
  1835. #else
  1836. result += "'\"";
  1837. #endif
  1838. } else {
  1839. result += "\"";
  1840. }
  1841. return result;
  1842. }
  1843. std::string cmLocalUnixMakefileGenerator3::GetTargetDirectory(
  1844. cmGeneratorTarget const* target) const
  1845. {
  1846. std::string dir = cmake::GetCMakeFilesDirectoryPostSlash();
  1847. dir += target->GetName();
  1848. #if defined(__VMS)
  1849. dir += "_dir";
  1850. #else
  1851. dir += ".dir";
  1852. #endif
  1853. return dir;
  1854. }
  1855. cmLocalUnixMakefileGenerator3::ImplicitDependLanguageMap const&
  1856. cmLocalUnixMakefileGenerator3::GetImplicitDepends(const cmGeneratorTarget* tgt)
  1857. {
  1858. return this->ImplicitDepends[tgt->GetName()];
  1859. }
  1860. void cmLocalUnixMakefileGenerator3::AddImplicitDepends(
  1861. const cmGeneratorTarget* tgt, const std::string& lang, const char* obj,
  1862. const char* src)
  1863. {
  1864. this->ImplicitDepends[tgt->GetName()][lang][obj].push_back(src);
  1865. }
  1866. void cmLocalUnixMakefileGenerator3::CreateCDCommand(
  1867. std::vector<std::string>& commands, std::string const& tgtDir,
  1868. std::string const& relDir)
  1869. {
  1870. // do we need to cd?
  1871. if (tgtDir == relDir) {
  1872. return;
  1873. }
  1874. // In a Windows shell we must change drive letter too. The shell
  1875. // used by NMake and Borland make does not support "cd /d" so this
  1876. // feature simply cannot work with them (Borland make does not even
  1877. // support changing the drive letter with just "d:").
  1878. const char* cd_cmd = this->IsMinGWMake() ? "cd /d " : "cd ";
  1879. cmGlobalUnixMakefileGenerator3* gg =
  1880. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1881. if (!gg->UnixCD) {
  1882. // On Windows we must perform each step separately and then change
  1883. // back because the shell keeps the working directory between
  1884. // commands.
  1885. std::string cmd = cd_cmd;
  1886. cmd += this->ConvertToOutputForExisting(tgtDir);
  1887. commands.insert(commands.begin(), cmd);
  1888. // Change back to the starting directory.
  1889. cmd = cd_cmd;
  1890. cmd += this->ConvertToOutputForExisting(relDir);
  1891. commands.push_back(std::move(cmd));
  1892. } else {
  1893. // On UNIX we must construct a single shell command to change
  1894. // directory and build because make resets the directory between
  1895. // each command.
  1896. std::string outputForExisting = this->ConvertToOutputForExisting(tgtDir);
  1897. std::string prefix = cd_cmd + outputForExisting + " && ";
  1898. std::transform(commands.begin(), commands.end(), commands.begin(),
  1899. [&prefix](std::string const& s) { return prefix + s; });
  1900. }
  1901. }
  1902. std::string cmLocalUnixMakefileGenerator3::MaybeConvertToRelativePath(
  1903. std::string const& base, std::string const& path)
  1904. {
  1905. if (!cmOutputConverter::ContainedInDirectory(
  1906. base, path, this->GetStateSnapshot().GetDirectory())) {
  1907. return path;
  1908. }
  1909. return cmOutputConverter::ForceToRelativePath(base, path);
  1910. }