cmLocalUnixMakefileGenerator3.cxx 74 KB

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