cmLocalUnixMakefileGenerator3.cxx 72 KB

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