cmLocalUnixMakefileGenerator3.cxx 73 KB

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