cmLocalUnixMakefileGenerator3.cxx 72 KB

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