cmLocalUnixMakefileGenerator3.cxx 74 KB

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