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