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