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 "cmProperty.h"
  28. #include "cmRange.h"
  29. #include "cmRulePlaceholderExpander.h"
  30. #include "cmSourceFile.h"
  31. #include "cmState.h"
  32. #include "cmStateDirectory.h"
  33. #include "cmStateSnapshot.h"
  34. #include "cmStateTypes.h"
  35. #include "cmStringAlgorithms.h"
  36. #include "cmSystemTools.h"
  37. #include "cmVersion.h"
  38. #include "cmake.h"
  39. // Include dependency scanners for supported languages. Only the
  40. // C/C++ scanner is needed for bootstrapping CMake.
  41. #include "cmDependsC.h"
  42. #ifndef CMAKE_BOOTSTRAP
  43. # include "cmDependsFortran.h"
  44. # include "cmDependsJava.h"
  45. #endif
  46. // Helper function used below.
  47. static std::string cmSplitExtension(std::string const& in, std::string& base)
  48. {
  49. std::string ext;
  50. std::string::size_type dot_pos = in.rfind('.');
  51. if (dot_pos != std::string::npos) {
  52. // Remove the extension first in case &base == &in.
  53. ext = in.substr(dot_pos);
  54. base = in.substr(0, dot_pos);
  55. } else {
  56. base = in;
  57. }
  58. return ext;
  59. }
  60. cmLocalUnixMakefileGenerator3::cmLocalUnixMakefileGenerator3(
  61. cmGlobalGenerator* gg, cmMakefile* mf)
  62. : cmLocalCommonGenerator(gg, mf, mf->GetCurrentBinaryDirectory())
  63. {
  64. this->MakefileVariableSize = 0;
  65. this->ColorMakefile = false;
  66. this->SkipPreprocessedSourceRules = false;
  67. this->SkipAssemblySourceRules = false;
  68. this->MakeCommandEscapeTargetTwice = false;
  69. this->BorlandMakeCurlyHack = false;
  70. }
  71. cmLocalUnixMakefileGenerator3::~cmLocalUnixMakefileGenerator3() = default;
  72. std::string cmLocalUnixMakefileGenerator3::GetConfigName() const
  73. {
  74. auto const& configNames = this->GetConfigNames();
  75. assert(configNames.size() == 1);
  76. return configNames.front();
  77. }
  78. void cmLocalUnixMakefileGenerator3::Generate()
  79. {
  80. // Record whether some options are enabled to avoid checking many
  81. // times later.
  82. if (!this->GetGlobalGenerator()->GetCMakeInstance()->GetIsInTryCompile()) {
  83. this->ColorMakefile = this->Makefile->IsOn("CMAKE_COLOR_MAKEFILE");
  84. }
  85. this->SkipPreprocessedSourceRules =
  86. this->Makefile->IsOn("CMAKE_SKIP_PREPROCESSED_SOURCE_RULES");
  87. this->SkipAssemblySourceRules =
  88. this->Makefile->IsOn("CMAKE_SKIP_ASSEMBLY_SOURCE_RULES");
  89. // Generate the rule files for each target.
  90. cmGlobalUnixMakefileGenerator3* gg =
  91. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  92. for (const auto& target : this->GetGeneratorTargets()) {
  93. if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  94. continue;
  95. }
  96. std::unique_ptr<cmMakefileTargetGenerator> tg(
  97. cmMakefileTargetGenerator::New(target.get()));
  98. if (tg) {
  99. tg->WriteRuleFiles();
  100. gg->RecordTargetProgress(tg.get());
  101. }
  102. }
  103. // write the local Makefile
  104. this->WriteLocalMakefile();
  105. // Write the cmake file with information for this directory.
  106. this->WriteDirectoryInformationFile();
  107. }
  108. void cmLocalUnixMakefileGenerator3::ComputeHomeRelativeOutputPath()
  109. {
  110. // Compute the path to use when referencing the current output
  111. // directory from the top output directory.
  112. this->HomeRelativeOutputPath = this->MaybeConvertToRelativePath(
  113. this->GetBinaryDirectory(), this->GetCurrentBinaryDirectory());
  114. if (this->HomeRelativeOutputPath == ".") {
  115. this->HomeRelativeOutputPath.clear();
  116. }
  117. if (!this->HomeRelativeOutputPath.empty()) {
  118. this->HomeRelativeOutputPath += "/";
  119. }
  120. }
  121. void cmLocalUnixMakefileGenerator3::GetLocalObjectFiles(
  122. std::map<std::string, LocalObjectInfo>& localObjectFiles)
  123. {
  124. for (const auto& gt : this->GetGeneratorTargets()) {
  125. if (gt->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  126. continue;
  127. }
  128. std::vector<cmSourceFile const*> objectSources;
  129. gt->GetObjectSources(objectSources, this->GetConfigName());
  130. // Compute full path to object file directory for this target.
  131. std::string dir = cmStrCat(gt->LocalGenerator->GetCurrentBinaryDirectory(),
  132. '/', this->GetTargetDirectory(gt.get()), '/');
  133. // Compute the name of each object file.
  134. for (cmSourceFile const* sf : objectSources) {
  135. bool hasSourceExtension = true;
  136. std::string objectName =
  137. this->GetObjectFileNameWithoutTarget(*sf, dir, &hasSourceExtension);
  138. if (cmSystemTools::FileIsFullPath(objectName)) {
  139. objectName = cmSystemTools::GetFilenameName(objectName);
  140. }
  141. LocalObjectInfo& info = localObjectFiles[objectName];
  142. info.HasSourceExtension = hasSourceExtension;
  143. info.emplace_back(gt.get(), sf->GetLanguage());
  144. }
  145. }
  146. }
  147. void cmLocalUnixMakefileGenerator3::GetIndividualFileTargets(
  148. std::vector<std::string>& targets)
  149. {
  150. std::map<std::string, LocalObjectInfo> localObjectFiles;
  151. this->GetLocalObjectFiles(localObjectFiles);
  152. for (auto const& localObjectFile : localObjectFiles) {
  153. targets.push_back(localObjectFile.first);
  154. std::string::size_type dot_pos = localObjectFile.first.rfind(".");
  155. std::string base = localObjectFile.first.substr(0, dot_pos);
  156. if (localObjectFile.second.HasPreprocessRule) {
  157. targets.push_back(base + ".i");
  158. }
  159. if (localObjectFile.second.HasAssembleRule) {
  160. targets.push_back(base + ".s");
  161. }
  162. }
  163. }
  164. void cmLocalUnixMakefileGenerator3::WriteLocalMakefile()
  165. {
  166. // generate the includes
  167. std::string ruleFileName = "Makefile";
  168. // Open the rule file. This should be copy-if-different because the
  169. // rules may depend on this file itself.
  170. std::string ruleFileNameFull = this->ConvertToFullPath(ruleFileName);
  171. cmGeneratedFileStream ruleFileStream(
  172. ruleFileNameFull, false, this->GlobalGenerator->GetMakefileEncoding());
  173. if (!ruleFileStream) {
  174. return;
  175. }
  176. // always write the top makefile
  177. if (!this->IsRootMakefile()) {
  178. ruleFileStream.SetCopyIfDifferent(true);
  179. }
  180. // write the all rules
  181. this->WriteLocalAllRules(ruleFileStream);
  182. // only write local targets unless at the top Keep track of targets already
  183. // listed.
  184. std::set<std::string> emittedTargets;
  185. if (!this->IsRootMakefile()) {
  186. // write our targets, and while doing it collect up the object
  187. // file rules
  188. this->WriteLocalMakefileTargets(ruleFileStream, emittedTargets);
  189. } else {
  190. cmGlobalUnixMakefileGenerator3* gg =
  191. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  192. gg->WriteConvenienceRules(ruleFileStream, emittedTargets);
  193. }
  194. bool do_preprocess_rules = this->GetCreatePreprocessedSourceRules();
  195. bool do_assembly_rules = this->GetCreateAssemblySourceRules();
  196. std::map<std::string, LocalObjectInfo> localObjectFiles;
  197. this->GetLocalObjectFiles(localObjectFiles);
  198. // now write out the object rules
  199. // for each object file name
  200. for (auto& localObjectFile : localObjectFiles) {
  201. // Add a convenience rule for building the object file.
  202. this->WriteObjectConvenienceRule(
  203. ruleFileStream, "target to build an object file", localObjectFile.first,
  204. localObjectFile.second);
  205. // Check whether preprocessing and assembly rules make sense.
  206. // They make sense only for C and C++ sources.
  207. bool lang_has_preprocessor = false;
  208. bool lang_has_assembly = false;
  209. for (LocalObjectEntry const& entry : localObjectFile.second) {
  210. if (entry.Language == "C" || entry.Language == "CXX" ||
  211. entry.Language == "CUDA" || entry.Language == "Fortran") {
  212. // Right now, C, C++, Fortran and CUDA have both a preprocessor and the
  213. // ability to generate assembly code
  214. lang_has_preprocessor = true;
  215. lang_has_assembly = true;
  216. break;
  217. }
  218. }
  219. // Add convenience rules for preprocessed and assembly files.
  220. if (lang_has_preprocessor && do_preprocess_rules) {
  221. std::string::size_type dot_pos = localObjectFile.first.rfind(".");
  222. std::string base = localObjectFile.first.substr(0, dot_pos);
  223. this->WriteObjectConvenienceRule(ruleFileStream,
  224. "target to preprocess a source file",
  225. (base + ".i"), localObjectFile.second);
  226. localObjectFile.second.HasPreprocessRule = true;
  227. }
  228. if (lang_has_assembly && do_assembly_rules) {
  229. std::string::size_type dot_pos = localObjectFile.first.rfind(".");
  230. std::string base = localObjectFile.first.substr(0, dot_pos);
  231. this->WriteObjectConvenienceRule(
  232. ruleFileStream, "target to generate assembly for a file",
  233. (base + ".s"), localObjectFile.second);
  234. localObjectFile.second.HasAssembleRule = true;
  235. }
  236. }
  237. // add a help target as long as there isn;t a real target named help
  238. if (emittedTargets.insert("help").second) {
  239. cmGlobalUnixMakefileGenerator3* gg =
  240. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  241. gg->WriteHelpRule(ruleFileStream, this);
  242. }
  243. this->WriteSpecialTargetsBottom(ruleFileStream);
  244. }
  245. void cmLocalUnixMakefileGenerator3::WriteObjectConvenienceRule(
  246. std::ostream& ruleFileStream, const char* comment, const std::string& output,
  247. LocalObjectInfo const& info)
  248. {
  249. // If the rule includes the source file extension then create a
  250. // version that has the extension removed. The help should include
  251. // only the version without source extension.
  252. bool inHelp = true;
  253. if (info.HasSourceExtension) {
  254. // Remove the last extension. This should be kept.
  255. std::string outBase1 = output;
  256. std::string outExt1 = cmSplitExtension(outBase1, outBase1);
  257. // Now remove the source extension and put back the last
  258. // extension.
  259. std::string outNoExt;
  260. cmSplitExtension(outBase1, outNoExt);
  261. outNoExt += outExt1;
  262. // Add a rule to drive the rule below.
  263. std::vector<std::string> depends;
  264. depends.emplace_back(output);
  265. std::vector<std::string> no_commands;
  266. this->WriteMakeRule(ruleFileStream, nullptr, outNoExt, depends,
  267. no_commands, true, true);
  268. inHelp = false;
  269. }
  270. // Recursively make the rule for each target using the object file.
  271. std::vector<std::string> commands;
  272. for (LocalObjectEntry const& t : info) {
  273. std::string tgtMakefileName = this->GetRelativeTargetDirectory(t.Target);
  274. std::string targetName = tgtMakefileName;
  275. tgtMakefileName += "/build.make";
  276. targetName += "/";
  277. targetName += output;
  278. commands.push_back(
  279. this->GetRecursiveMakeCall(tgtMakefileName, targetName));
  280. }
  281. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  282. this->GetCurrentBinaryDirectory());
  283. // Write the rule to the makefile.
  284. std::vector<std::string> no_depends;
  285. this->WriteMakeRule(ruleFileStream, comment, output, no_depends, commands,
  286. true, inHelp);
  287. }
  288. void cmLocalUnixMakefileGenerator3::WriteLocalMakefileTargets(
  289. std::ostream& ruleFileStream, std::set<std::string>& emitted)
  290. {
  291. std::vector<std::string> depends;
  292. std::vector<std::string> commands;
  293. // for each target we just provide a rule to cd up to the top and do a make
  294. // on the target
  295. std::string localName;
  296. for (const auto& target : this->GetGeneratorTargets()) {
  297. if ((target->GetType() == cmStateEnums::EXECUTABLE) ||
  298. (target->GetType() == cmStateEnums::STATIC_LIBRARY) ||
  299. (target->GetType() == cmStateEnums::SHARED_LIBRARY) ||
  300. (target->GetType() == cmStateEnums::MODULE_LIBRARY) ||
  301. (target->GetType() == cmStateEnums::OBJECT_LIBRARY) ||
  302. (target->GetType() == cmStateEnums::UTILITY)) {
  303. emitted.insert(target->GetName());
  304. // for subdirs add a rule to build this specific target by name.
  305. localName =
  306. cmStrCat(this->GetRelativeTargetDirectory(target.get()), "/rule");
  307. commands.clear();
  308. depends.clear();
  309. // Build the target for this pass.
  310. std::string makefile2 = "CMakeFiles/Makefile2";
  311. commands.push_back(this->GetRecursiveMakeCall(makefile2, localName));
  312. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  313. this->GetCurrentBinaryDirectory());
  314. this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
  315. localName, depends, commands, true);
  316. // Add a target with the canonical name (no prefix, suffix or path).
  317. if (localName != target->GetName()) {
  318. commands.clear();
  319. depends.push_back(localName);
  320. this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
  321. target->GetName(), depends, commands, true);
  322. }
  323. // Add a fast rule to build the target
  324. std::string makefileName = cmStrCat(
  325. this->GetRelativeTargetDirectory(target.get()), "/build.make");
  326. // make sure the makefile name is suitable for a makefile
  327. std::string makeTargetName =
  328. cmStrCat(this->GetRelativeTargetDirectory(target.get()), "/build");
  329. localName = cmStrCat(target->GetName(), "/fast");
  330. depends.clear();
  331. commands.clear();
  332. commands.push_back(
  333. this->GetRecursiveMakeCall(makefileName, makeTargetName));
  334. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  335. this->GetCurrentBinaryDirectory());
  336. this->WriteMakeRule(ruleFileStream, "fast build rule for target.",
  337. localName, depends, commands, true);
  338. // Add a local name for the rule to relink the target before
  339. // installation.
  340. if (target->NeedRelinkBeforeInstall(this->GetConfigName())) {
  341. makeTargetName = cmStrCat(
  342. this->GetRelativeTargetDirectory(target.get()), "/preinstall");
  343. localName = cmStrCat(target->GetName(), "/preinstall");
  344. depends.clear();
  345. commands.clear();
  346. commands.push_back(
  347. this->GetRecursiveMakeCall(makefile2, makeTargetName));
  348. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  349. this->GetCurrentBinaryDirectory());
  350. this->WriteMakeRule(ruleFileStream,
  351. "Manual pre-install relink rule for target.",
  352. localName, depends, commands, true);
  353. }
  354. }
  355. }
  356. }
  357. void cmLocalUnixMakefileGenerator3::WriteDirectoryInformationFile()
  358. {
  359. std::string infoFileName =
  360. cmStrCat(this->GetCurrentBinaryDirectory(),
  361. "/CMakeFiles/CMakeDirectoryInformation.cmake");
  362. // Open the output file.
  363. cmGeneratedFileStream infoFileStream(infoFileName);
  364. if (!infoFileStream) {
  365. return;
  366. }
  367. infoFileStream.SetCopyIfDifferent(true);
  368. // Write the do not edit header.
  369. this->WriteDisclaimer(infoFileStream);
  370. // Setup relative path conversion tops.
  371. /* clang-format off */
  372. infoFileStream
  373. << "# Relative path conversion top directories.\n"
  374. << "set(CMAKE_RELATIVE_PATH_TOP_SOURCE \""
  375. << this->StateSnapshot.GetDirectory().GetRelativePathTopSource()
  376. << "\")\n"
  377. << "set(CMAKE_RELATIVE_PATH_TOP_BINARY \""
  378. << this->StateSnapshot.GetDirectory().GetRelativePathTopBinary()
  379. << "\")\n"
  380. << "\n";
  381. /* clang-format on */
  382. // Tell the dependency scanner to use unix paths if necessary.
  383. if (cmSystemTools::GetForceUnixPaths()) {
  384. /* clang-format off */
  385. infoFileStream
  386. << "# Force unix paths in dependencies.\n"
  387. << "set(CMAKE_FORCE_UNIX_PATHS 1)\n"
  388. << "\n";
  389. /* clang-format on */
  390. }
  391. // Store the include regular expressions for this directory.
  392. infoFileStream << "\n"
  393. << "# The C and CXX include file regular expressions for "
  394. << "this directory.\n";
  395. infoFileStream << "set(CMAKE_C_INCLUDE_REGEX_SCAN ";
  396. cmLocalUnixMakefileGenerator3::WriteCMakeArgument(
  397. infoFileStream, this->Makefile->GetIncludeRegularExpression());
  398. infoFileStream << ")\n";
  399. infoFileStream << "set(CMAKE_C_INCLUDE_REGEX_COMPLAIN ";
  400. cmLocalUnixMakefileGenerator3::WriteCMakeArgument(
  401. infoFileStream, this->Makefile->GetComplainRegularExpression());
  402. infoFileStream << ")\n";
  403. infoFileStream
  404. << "set(CMAKE_CXX_INCLUDE_REGEX_SCAN ${CMAKE_C_INCLUDE_REGEX_SCAN})\n";
  405. infoFileStream << "set(CMAKE_CXX_INCLUDE_REGEX_COMPLAIN "
  406. "${CMAKE_C_INCLUDE_REGEX_COMPLAIN})\n";
  407. }
  408. std::string cmLocalUnixMakefileGenerator3::ConvertToFullPath(
  409. const std::string& localPath)
  410. {
  411. std::string dir =
  412. cmStrCat(this->GetCurrentBinaryDirectory(), '/', localPath);
  413. return dir;
  414. }
  415. const std::string& cmLocalUnixMakefileGenerator3::GetHomeRelativeOutputPath()
  416. {
  417. return this->HomeRelativeOutputPath;
  418. }
  419. std::string cmLocalUnixMakefileGenerator3::ConvertToMakefilePath(
  420. std::string const& path) const
  421. {
  422. cmGlobalUnixMakefileGenerator3* gg =
  423. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  424. return gg->ConvertToMakefilePath(path);
  425. }
  426. void cmLocalUnixMakefileGenerator3::WriteMakeRule(
  427. std::ostream& os, const char* comment, const std::string& target,
  428. const std::vector<std::string>& depends,
  429. const std::vector<std::string>& commands, bool symbolic, bool in_help)
  430. {
  431. // Make sure there is a target.
  432. if (target.empty()) {
  433. std::string err("No target for WriteMakeRule! called with comment: ");
  434. if (comment) {
  435. err += comment;
  436. }
  437. cmSystemTools::Error(err);
  438. return;
  439. }
  440. std::string replace;
  441. // Write the comment describing the rule in the makefile.
  442. if (comment) {
  443. replace = comment;
  444. std::string::size_type lpos = 0;
  445. std::string::size_type rpos;
  446. while ((rpos = replace.find('\n', lpos)) != std::string::npos) {
  447. os << "# " << replace.substr(lpos, rpos - lpos) << "\n";
  448. lpos = rpos + 1;
  449. }
  450. os << "# " << replace.substr(lpos) << "\n";
  451. }
  452. // Construct the left hand side of the rule.
  453. std::string tgt = this->ConvertToMakefilePath(
  454. this->MaybeConvertToRelativePath(this->GetBinaryDirectory(), target));
  455. const char* space = "";
  456. if (tgt.size() == 1) {
  457. // Add a space before the ":" to avoid drive letter confusion on
  458. // Windows.
  459. space = " ";
  460. }
  461. // Mark the rule as symbolic if requested.
  462. if (symbolic) {
  463. if (const char* sym =
  464. this->Makefile->GetDefinition("CMAKE_MAKE_SYMBOLIC_RULE")) {
  465. os << tgt << space << ": " << sym << "\n";
  466. }
  467. }
  468. // Write the rule.
  469. if (depends.empty()) {
  470. // No dependencies. The commands will always run.
  471. os << tgt << space << ":\n";
  472. } else {
  473. // Split dependencies into multiple rule lines. This allows for
  474. // very long dependency lists even on older make implementations.
  475. std::string binDir = this->GetBinaryDirectory();
  476. for (std::string const& depend : depends) {
  477. os << tgt << space << ": "
  478. << this->ConvertToMakefilePath(
  479. this->MaybeConvertToRelativePath(binDir, depend))
  480. << '\n';
  481. }
  482. }
  483. // Write the list of commands.
  484. os << cmWrap("\t", commands, "", "\n") << "\n";
  485. if (symbolic && !this->IsWatcomWMake()) {
  486. os << ".PHONY : " << tgt << "\n";
  487. }
  488. os << "\n";
  489. // Add the output to the local help if requested.
  490. if (in_help) {
  491. this->LocalHelp.push_back(target);
  492. }
  493. }
  494. std::string cmLocalUnixMakefileGenerator3::MaybeConvertWatcomShellCommand(
  495. std::string const& cmd)
  496. {
  497. if (this->IsWatcomWMake() && cmSystemTools::FileIsFullPath(cmd) &&
  498. cmd.find_first_of("( )") != std::string::npos) {
  499. // On Watcom WMake use the windows short path for the command
  500. // name. This is needed to avoid funny quoting problems on
  501. // lines with shell redirection operators.
  502. std::string scmd;
  503. if (cmSystemTools::GetShortPath(cmd, scmd)) {
  504. return this->ConvertToOutputFormat(scmd, cmOutputConverter::SHELL);
  505. }
  506. }
  507. return std::string();
  508. }
  509. void cmLocalUnixMakefileGenerator3::WriteMakeVariables(
  510. std::ostream& makefileStream)
  511. {
  512. this->WriteDivider(makefileStream);
  513. makefileStream << "# Set environment variables for the build.\n"
  514. << "\n";
  515. cmGlobalUnixMakefileGenerator3* gg =
  516. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  517. if (gg->DefineWindowsNULL) {
  518. makefileStream << "!IF \"$(OS)\" == \"Windows_NT\"\n"
  519. << "NULL=\n"
  520. << "!ELSE\n"
  521. << "NULL=nul\n"
  522. << "!ENDIF\n";
  523. }
  524. if (this->IsWindowsShell()) {
  525. makefileStream << "SHELL = cmd.exe\n"
  526. << "\n";
  527. } else {
  528. #if !defined(__VMS)
  529. /* clang-format off */
  530. makefileStream
  531. << "# The shell in which to execute make rules.\n"
  532. << "SHELL = /bin/sh\n"
  533. << "\n";
  534. /* clang-format on */
  535. #endif
  536. }
  537. std::string cmakeShellCommand =
  538. this->MaybeConvertWatcomShellCommand(cmSystemTools::GetCMakeCommand());
  539. if (cmakeShellCommand.empty()) {
  540. cmakeShellCommand = this->ConvertToOutputFormat(
  541. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  542. }
  543. /* clang-format off */
  544. makefileStream
  545. << "# The CMake executable.\n"
  546. << "CMAKE_COMMAND = "
  547. << cmakeShellCommand
  548. << "\n"
  549. << "\n";
  550. makefileStream
  551. << "# The command to remove a file.\n"
  552. << "RM = "
  553. << cmakeShellCommand
  554. << " -E rm -f\n"
  555. << "\n";
  556. makefileStream
  557. << "# Escaping for special characters.\n"
  558. << "EQUALS = =\n"
  559. << "\n";
  560. makefileStream
  561. << "# The top-level source directory on which CMake was run.\n"
  562. << "CMAKE_SOURCE_DIR = "
  563. << this->ConvertToOutputFormat(
  564. this->GetSourceDirectory(), cmOutputConverter::SHELL)
  565. << "\n"
  566. << "\n";
  567. makefileStream
  568. << "# The top-level build directory on which CMake was run.\n"
  569. << "CMAKE_BINARY_DIR = "
  570. << this->ConvertToOutputFormat(
  571. this->GetBinaryDirectory(), cmOutputConverter::SHELL)
  572. << "\n"
  573. << "\n";
  574. /* clang-format on */
  575. }
  576. void cmLocalUnixMakefileGenerator3::WriteSpecialTargetsTop(
  577. std::ostream& makefileStream)
  578. {
  579. this->WriteDivider(makefileStream);
  580. makefileStream << "# Special targets provided by cmake.\n"
  581. << "\n";
  582. std::vector<std::string> no_commands;
  583. std::vector<std::string> no_depends;
  584. // Special target to cleanup operation of make tool.
  585. // This should be the first target except for the default_target in
  586. // the interface Makefile.
  587. this->WriteMakeRule(makefileStream,
  588. "Disable implicit rules so canonical targets will work.",
  589. ".SUFFIXES", no_depends, no_commands, false);
  590. if (!this->IsNMake() && !this->IsWatcomWMake() &&
  591. !this->BorlandMakeCurlyHack) {
  592. // turn off RCS and SCCS automatic stuff from gmake
  593. constexpr const char* vcs_rules[] = {
  594. "%,v", "RCS/%", "RCS/%,v", "SCCS/s.%", "s.%",
  595. };
  596. for (auto vcs_rule : vcs_rules) {
  597. std::vector<std::string> vcs_depend;
  598. vcs_depend.emplace_back(vcs_rule);
  599. this->WriteMakeRule(makefileStream, "Disable VCS-based implicit rules.",
  600. "%", vcs_depend, no_commands, false);
  601. }
  602. }
  603. // Add a fake suffix to keep HP happy. Must be max 32 chars for SGI make.
  604. std::vector<std::string> depends;
  605. depends.emplace_back(".hpux_make_needs_suffix_list");
  606. this->WriteMakeRule(makefileStream, nullptr, ".SUFFIXES", depends,
  607. no_commands, false);
  608. if (this->IsWatcomWMake()) {
  609. // Switch on WMake feature, if an error or interrupt occurs during
  610. // makefile processing, the current target being made may be deleted
  611. // without prompting (the same as command line -e option).
  612. /* clang-format off */
  613. makefileStream <<
  614. "\n"
  615. ".ERASE\n"
  616. "\n"
  617. ;
  618. /* clang-format on */
  619. }
  620. if (this->Makefile->IsOn("CMAKE_VERBOSE_MAKEFILE")) {
  621. /* clang-format off */
  622. makefileStream
  623. << "# Produce verbose output by default.\n"
  624. << "VERBOSE = 1\n"
  625. << "\n";
  626. /* clang-format on */
  627. }
  628. if (this->IsWatcomWMake()) {
  629. /* clang-format off */
  630. makefileStream <<
  631. "!ifndef VERBOSE\n"
  632. ".SILENT\n"
  633. "!endif\n"
  634. "\n"
  635. ;
  636. /* clang-format on */
  637. } else {
  638. makefileStream << "# Command-line flag to silence nested $(MAKE).\n"
  639. "$(VERBOSE)MAKESILENT = -s\n"
  640. "\n";
  641. // Write special target to silence make output. This must be after
  642. // the default target in case VERBOSE is set (which changes the
  643. // name). The setting of CMAKE_VERBOSE_MAKEFILE to ON will cause a
  644. // "VERBOSE=1" to be added as a make variable which will change the
  645. // name of this special target. This gives a make-time choice to
  646. // the user.
  647. // Write directly to the stream since WriteMakeRule escapes '$'.
  648. makefileStream << "#Suppress display of executed commands.\n"
  649. "$(VERBOSE).SILENT:\n"
  650. "\n";
  651. }
  652. // Work-around for makes that drop rules that have no dependencies
  653. // or commands.
  654. cmGlobalUnixMakefileGenerator3* gg =
  655. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  656. std::string hack = gg->GetEmptyRuleHackDepends();
  657. if (!hack.empty()) {
  658. no_depends.push_back(std::move(hack));
  659. }
  660. std::string hack_cmd = gg->GetEmptyRuleHackCommand();
  661. if (!hack_cmd.empty()) {
  662. no_commands.push_back(std::move(hack_cmd));
  663. }
  664. // Special symbolic target that never exists to force dependers to
  665. // run their rules.
  666. this->WriteMakeRule(makefileStream, "A target that is always out of date.",
  667. "cmake_force", no_depends, no_commands, true);
  668. // Variables for reference by other rules.
  669. this->WriteMakeVariables(makefileStream);
  670. }
  671. void cmLocalUnixMakefileGenerator3::WriteSpecialTargetsBottom(
  672. std::ostream& makefileStream)
  673. {
  674. this->WriteDivider(makefileStream);
  675. makefileStream << "# Special targets to cleanup operation of make.\n"
  676. << "\n";
  677. // Write special "cmake_check_build_system" target to run cmake with
  678. // the --check-build-system flag.
  679. if (!this->GlobalGenerator->GlobalSettingIsOn(
  680. "CMAKE_SUPPRESS_REGENERATION")) {
  681. // Build command to run CMake to check if anything needs regenerating.
  682. std::vector<std::string> commands;
  683. cmake* cm = this->GlobalGenerator->GetCMakeInstance();
  684. if (cm->DoWriteGlobVerifyTarget()) {
  685. std::string rescanRule =
  686. cmStrCat("$(CMAKE_COMMAND) -P ",
  687. this->ConvertToOutputFormat(cm->GetGlobVerifyScript(),
  688. cmOutputConverter::SHELL));
  689. commands.push_back(rescanRule);
  690. }
  691. std::string cmakefileName = "CMakeFiles/Makefile.cmake";
  692. std::string runRule = cmStrCat(
  693. "$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) "
  694. "--check-build-system ",
  695. this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL),
  696. " 0");
  697. std::vector<std::string> no_depends;
  698. commands.push_back(std::move(runRule));
  699. if (!this->IsRootMakefile()) {
  700. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  701. this->GetCurrentBinaryDirectory());
  702. }
  703. this->WriteMakeRule(makefileStream,
  704. "Special rule to run CMake to check the build system "
  705. "integrity.\n"
  706. "No rule that depends on this can have "
  707. "commands that come from listfiles\n"
  708. "because they might be regenerated.",
  709. "cmake_check_build_system", no_depends, commands,
  710. true);
  711. }
  712. }
  713. void cmLocalUnixMakefileGenerator3::WriteConvenienceRule(
  714. std::ostream& ruleFileStream, const std::string& realTarget,
  715. const std::string& helpTarget)
  716. {
  717. // A rule is only needed if the names are different.
  718. if (realTarget != helpTarget) {
  719. // The helper target depends on the real target.
  720. std::vector<std::string> depends;
  721. depends.push_back(realTarget);
  722. // There are no commands.
  723. std::vector<std::string> no_commands;
  724. // Write the rule.
  725. this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
  726. helpTarget, depends, no_commands, true);
  727. }
  728. }
  729. std::string cmLocalUnixMakefileGenerator3::GetRelativeTargetDirectory(
  730. cmGeneratorTarget const* target) const
  731. {
  732. std::string dir =
  733. cmStrCat(this->HomeRelativeOutputPath, this->GetTargetDirectory(target));
  734. return dir;
  735. }
  736. void cmLocalUnixMakefileGenerator3::AppendFlags(
  737. std::string& flags, const std::string& newFlags) const
  738. {
  739. if (this->IsWatcomWMake() && !newFlags.empty()) {
  740. std::string newf = newFlags;
  741. if (newf.find("\\\"") != std::string::npos) {
  742. cmSystemTools::ReplaceString(newf, "\\\"", "\"");
  743. this->cmLocalGenerator::AppendFlags(flags, newf);
  744. return;
  745. }
  746. }
  747. this->cmLocalGenerator::AppendFlags(flags, newFlags);
  748. }
  749. void cmLocalUnixMakefileGenerator3::AppendRuleDepend(
  750. std::vector<std::string>& depends, const char* ruleFileName)
  751. {
  752. // Add a dependency on the rule file itself unless an option to skip
  753. // it is specifically enabled by the user or project.
  754. const char* nodep =
  755. this->Makefile->GetDefinition("CMAKE_SKIP_RULE_DEPENDENCY");
  756. if (!nodep || cmIsOff(nodep)) {
  757. depends.emplace_back(ruleFileName);
  758. }
  759. }
  760. void cmLocalUnixMakefileGenerator3::AppendRuleDepends(
  761. std::vector<std::string>& depends, std::vector<std::string> const& ruleFiles)
  762. {
  763. // Add a dependency on the rule file itself unless an option to skip
  764. // it is specifically enabled by the user or project.
  765. if (!this->Makefile->IsOn("CMAKE_SKIP_RULE_DEPENDENCY")) {
  766. cm::append(depends, ruleFiles);
  767. }
  768. }
  769. void cmLocalUnixMakefileGenerator3::AppendCustomDepends(
  770. std::vector<std::string>& depends, const std::vector<cmCustomCommand>& ccs)
  771. {
  772. for (cmCustomCommand const& cc : ccs) {
  773. cmCustomCommandGenerator ccg(cc, this->GetConfigName(), this);
  774. this->AppendCustomDepend(depends, ccg);
  775. }
  776. }
  777. void cmLocalUnixMakefileGenerator3::AppendCustomDepend(
  778. std::vector<std::string>& depends, cmCustomCommandGenerator const& ccg)
  779. {
  780. for (std::string const& d : ccg.GetDepends()) {
  781. // Lookup the real name of the dependency in case it is a CMake target.
  782. std::string dep;
  783. if (this->GetRealDependency(d, this->GetConfigName(), dep)) {
  784. depends.push_back(std::move(dep));
  785. }
  786. }
  787. }
  788. void cmLocalUnixMakefileGenerator3::AppendCustomCommands(
  789. std::vector<std::string>& commands, const std::vector<cmCustomCommand>& ccs,
  790. cmGeneratorTarget* target, std::string const& relative)
  791. {
  792. for (cmCustomCommand const& cc : ccs) {
  793. cmCustomCommandGenerator ccg(cc, this->GetConfigName(), this);
  794. this->AppendCustomCommand(commands, ccg, target, relative, true);
  795. }
  796. }
  797. void cmLocalUnixMakefileGenerator3::AppendCustomCommand(
  798. std::vector<std::string>& commands, cmCustomCommandGenerator const& ccg,
  799. cmGeneratorTarget* target, std::string const& relative, bool echo_comment,
  800. std::ostream* content)
  801. {
  802. // Optionally create a command to display the custom command's
  803. // comment text. This is used for pre-build, pre-link, and
  804. // post-build command comments. Custom build step commands have
  805. // their comments generated elsewhere.
  806. if (echo_comment) {
  807. const char* comment = ccg.GetComment();
  808. if (comment && *comment) {
  809. this->AppendEcho(commands, comment,
  810. cmLocalUnixMakefileGenerator3::EchoGenerate);
  811. }
  812. }
  813. // if the command specified a working directory use it.
  814. std::string dir = this->GetCurrentBinaryDirectory();
  815. std::string workingDir = ccg.GetWorkingDirectory();
  816. if (!workingDir.empty()) {
  817. dir = workingDir;
  818. }
  819. if (content) {
  820. *content << dir;
  821. }
  822. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  823. this->CreateRulePlaceholderExpander());
  824. // Add each command line to the set of commands.
  825. std::vector<std::string> commands1;
  826. std::string currentBinDir = this->GetCurrentBinaryDirectory();
  827. for (unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) {
  828. // Build the command line in a single string.
  829. std::string cmd = ccg.GetCommand(c);
  830. if (!cmd.empty()) {
  831. // Use "call " before any invocations of .bat or .cmd files
  832. // invoked as custom commands in the WindowsShell.
  833. //
  834. bool useCall = false;
  835. if (this->IsWindowsShell()) {
  836. std::string suffix;
  837. if (cmd.size() > 4) {
  838. suffix = cmSystemTools::LowerCase(cmd.substr(cmd.size() - 4));
  839. if (suffix == ".bat" || suffix == ".cmd") {
  840. useCall = true;
  841. }
  842. }
  843. }
  844. cmSystemTools::ReplaceString(cmd, "/./", "/");
  845. // Convert the command to a relative path only if the current
  846. // working directory will be the start-output directory.
  847. bool had_slash = cmd.find('/') != std::string::npos;
  848. if (workingDir.empty()) {
  849. cmd = this->MaybeConvertToRelativePath(currentBinDir, cmd);
  850. }
  851. bool has_slash = cmd.find('/') != std::string::npos;
  852. if (had_slash && !has_slash) {
  853. // This command was specified as a path to a file in the
  854. // current directory. Add a leading "./" so it can run
  855. // without the current directory being in the search path.
  856. cmd = cmStrCat("./", cmd);
  857. }
  858. std::string launcher;
  859. // Short-circuit if there is no launcher.
  860. const char* val = this->GetRuleLauncher(target, "RULE_LAUNCH_CUSTOM");
  861. if (cmNonempty(val)) {
  862. // Expand rule variables referenced in the given launcher command.
  863. cmRulePlaceholderExpander::RuleVariables vars;
  864. vars.CMTargetName = target->GetName().c_str();
  865. vars.CMTargetType =
  866. cmState::GetTargetTypeName(target->GetType()).c_str();
  867. std::string output;
  868. const std::vector<std::string>& outputs = ccg.GetOutputs();
  869. if (!outputs.empty()) {
  870. output = outputs[0];
  871. if (workingDir.empty()) {
  872. output = this->MaybeConvertToRelativePath(
  873. this->GetCurrentBinaryDirectory(), output);
  874. }
  875. output =
  876. this->ConvertToOutputFormat(output, cmOutputConverter::SHELL);
  877. }
  878. vars.Output = output.c_str();
  879. launcher = val;
  880. rulePlaceholderExpander->ExpandRuleVariables(this, launcher, vars);
  881. if (!launcher.empty()) {
  882. launcher += " ";
  883. }
  884. }
  885. std::string shellCommand = this->MaybeConvertWatcomShellCommand(cmd);
  886. if (shellCommand.empty()) {
  887. shellCommand =
  888. this->ConvertToOutputFormat(cmd, cmOutputConverter::SHELL);
  889. }
  890. cmd = launcher + shellCommand;
  891. ccg.AppendArguments(c, cmd);
  892. if (content) {
  893. // Rule content does not include the launcher.
  894. *content << (cmd.c_str() + launcher.size());
  895. }
  896. if (this->BorlandMakeCurlyHack) {
  897. // Borland Make has a very strange bug. If the first curly
  898. // brace anywhere in the command string is a left curly, it
  899. // must be written {{} instead of just {. Otherwise some
  900. // curly braces are removed. The hack can be skipped if the
  901. // first curly brace is the last character.
  902. std::string::size_type lcurly = cmd.find('{');
  903. if (lcurly != std::string::npos && lcurly < (cmd.size() - 1)) {
  904. std::string::size_type rcurly = cmd.find('}');
  905. if (rcurly == std::string::npos || rcurly > lcurly) {
  906. // The first curly is a left curly. Use the hack.
  907. cmd =
  908. cmStrCat(cmd.substr(0, lcurly), "{{}", cmd.substr(lcurly + 1));
  909. }
  910. }
  911. }
  912. if (launcher.empty()) {
  913. if (useCall) {
  914. cmd = cmStrCat("call ", cmd);
  915. } else if (this->IsNMake() && cmd[0] == '"') {
  916. cmd = cmStrCat("echo >nul && ", cmd);
  917. }
  918. }
  919. commands1.push_back(std::move(cmd));
  920. }
  921. }
  922. // Setup the proper working directory for the commands.
  923. this->CreateCDCommand(commands1, dir, relative);
  924. // push back the custom commands
  925. cm::append(commands, commands1);
  926. }
  927. void cmLocalUnixMakefileGenerator3::AppendCleanCommand(
  928. std::vector<std::string>& commands, const std::set<std::string>& files,
  929. cmGeneratorTarget* target, const char* filename)
  930. {
  931. std::string currentBinDir = this->GetCurrentBinaryDirectory();
  932. std::string cleanfile = cmStrCat(
  933. currentBinDir, '/', this->GetTargetDirectory(target), "/cmake_clean");
  934. if (filename) {
  935. cleanfile += "_";
  936. cleanfile += filename;
  937. }
  938. cleanfile += ".cmake";
  939. cmsys::ofstream fout(cleanfile.c_str());
  940. if (!fout) {
  941. cmSystemTools::Error("Could not create " + cleanfile);
  942. }
  943. if (!files.empty()) {
  944. fout << "file(REMOVE_RECURSE\n";
  945. for (std::string const& file : files) {
  946. std::string fc = this->MaybeConvertToRelativePath(currentBinDir, file);
  947. fout << " " << cmOutputConverter::EscapeForCMake(fc) << "\n";
  948. }
  949. fout << ")\n";
  950. }
  951. {
  952. std::string remove =
  953. cmStrCat("$(CMAKE_COMMAND) -P ",
  954. this->ConvertToOutputFormat(
  955. this->MaybeConvertToRelativePath(
  956. this->GetCurrentBinaryDirectory(), cleanfile),
  957. cmOutputConverter::SHELL));
  958. commands.push_back(std::move(remove));
  959. }
  960. // For the main clean rule add per-language cleaning.
  961. if (!filename) {
  962. // Get the set of source languages in the target.
  963. std::set<std::string> languages;
  964. target->GetLanguages(
  965. languages, this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
  966. /* clang-format off */
  967. fout << "\n"
  968. << "# Per-language clean rules from dependency scanning.\n"
  969. << "foreach(lang " << cmJoin(languages, " ") << ")\n"
  970. << " include(" << this->GetTargetDirectory(target)
  971. << "/cmake_clean_${lang}.cmake OPTIONAL)\n"
  972. << "endforeach()\n";
  973. /* clang-format on */
  974. }
  975. }
  976. void cmLocalUnixMakefileGenerator3::AppendDirectoryCleanCommand(
  977. std::vector<std::string>& commands)
  978. {
  979. std::vector<std::string> cleanFiles;
  980. // Look for additional files registered for cleaning in this directory.
  981. if (cmProp prop_value =
  982. this->Makefile->GetProperty("ADDITIONAL_CLEAN_FILES")) {
  983. cmExpandList(cmGeneratorExpression::Evaluate(
  984. *prop_value, this,
  985. this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE")),
  986. cleanFiles);
  987. }
  988. if (cleanFiles.empty()) {
  989. return;
  990. }
  991. const auto& rootLG = this->GetGlobalGenerator()->GetLocalGenerators().at(0);
  992. std::string const& binaryDir = rootLG->GetCurrentBinaryDirectory();
  993. std::string const& currentBinaryDir = this->GetCurrentBinaryDirectory();
  994. std::string cleanfile =
  995. cmStrCat(currentBinaryDir, "/CMakeFiles/cmake_directory_clean.cmake");
  996. // Write clean script
  997. {
  998. cmsys::ofstream fout(cleanfile.c_str());
  999. if (!fout) {
  1000. cmSystemTools::Error("Could not create " + cleanfile);
  1001. return;
  1002. }
  1003. fout << "file(REMOVE_RECURSE\n";
  1004. for (std::string const& cfl : cleanFiles) {
  1005. std::string fc = rootLG->MaybeConvertToRelativePath(
  1006. binaryDir, cmSystemTools::CollapseFullPath(cfl, currentBinaryDir));
  1007. fout << " " << cmOutputConverter::EscapeForCMake(fc) << "\n";
  1008. }
  1009. fout << ")\n";
  1010. }
  1011. // Create command
  1012. {
  1013. std::string remove =
  1014. cmStrCat("$(CMAKE_COMMAND) -P ",
  1015. this->ConvertToOutputFormat(
  1016. rootLG->MaybeConvertToRelativePath(binaryDir, cleanfile),
  1017. cmOutputConverter::SHELL));
  1018. commands.push_back(std::move(remove));
  1019. }
  1020. }
  1021. void cmLocalUnixMakefileGenerator3::AppendEcho(
  1022. std::vector<std::string>& commands, std::string const& text, EchoColor color,
  1023. EchoProgress const* progress)
  1024. {
  1025. // Choose the color for the text.
  1026. std::string color_name;
  1027. if (this->GlobalGenerator->GetToolSupportsColor() && this->ColorMakefile) {
  1028. // See cmake::ExecuteEchoColor in cmake.cxx for these options.
  1029. // This color set is readable on both black and white backgrounds.
  1030. switch (color) {
  1031. case EchoNormal:
  1032. break;
  1033. case EchoDepend:
  1034. color_name = "--magenta --bold ";
  1035. break;
  1036. case EchoBuild:
  1037. color_name = "--green ";
  1038. break;
  1039. case EchoLink:
  1040. color_name = "--green --bold ";
  1041. break;
  1042. case EchoGenerate:
  1043. color_name = "--blue --bold ";
  1044. break;
  1045. case EchoGlobal:
  1046. color_name = "--cyan ";
  1047. break;
  1048. }
  1049. }
  1050. // Echo one line at a time.
  1051. std::string line;
  1052. line.reserve(200);
  1053. for (const char* c = text.c_str();; ++c) {
  1054. if (*c == '\n' || *c == '\0') {
  1055. // Avoid writing a blank last line on end-of-string.
  1056. if (*c != '\0' || !line.empty()) {
  1057. // Add a command to echo this line.
  1058. std::string cmd;
  1059. if (color_name.empty() && !progress) {
  1060. // Use the native echo command.
  1061. cmd = cmStrCat("@echo ", this->EscapeForShell(line, false, true));
  1062. } else {
  1063. // Use cmake to echo the text in color.
  1064. cmd = cmStrCat(
  1065. "@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) ",
  1066. color_name);
  1067. if (progress) {
  1068. cmd += "--progress-dir=";
  1069. cmd += this->ConvertToOutputFormat(progress->Dir,
  1070. cmOutputConverter::SHELL);
  1071. cmd += " ";
  1072. cmd += "--progress-num=";
  1073. cmd += progress->Arg;
  1074. cmd += " ";
  1075. }
  1076. cmd += this->EscapeForShell(line);
  1077. }
  1078. commands.push_back(std::move(cmd));
  1079. }
  1080. // Reset the line to empty.
  1081. line.clear();
  1082. // Progress appears only on first line.
  1083. progress = nullptr;
  1084. // Terminate on end-of-string.
  1085. if (*c == '\0') {
  1086. return;
  1087. }
  1088. } else if (*c != '\r') {
  1089. // Append this character to the current line.
  1090. line += *c;
  1091. }
  1092. }
  1093. }
  1094. std::string cmLocalUnixMakefileGenerator3::CreateMakeVariable(
  1095. std::string const& s, std::string const& s2)
  1096. {
  1097. std::string unmodified = cmStrCat(s, s2);
  1098. // if there is no restriction on the length of make variables
  1099. // and there are no "." characters in the string, then return the
  1100. // unmodified combination.
  1101. if ((!this->MakefileVariableSize &&
  1102. unmodified.find('.') == std::string::npos) &&
  1103. (!this->MakefileVariableSize &&
  1104. unmodified.find('+') == std::string::npos) &&
  1105. (!this->MakefileVariableSize &&
  1106. unmodified.find('-') == std::string::npos)) {
  1107. return unmodified;
  1108. }
  1109. // see if the variable has been defined before and return
  1110. // the modified version of the variable
  1111. auto i = this->MakeVariableMap.find(unmodified);
  1112. if (i != this->MakeVariableMap.end()) {
  1113. return i->second;
  1114. }
  1115. // start with the unmodified variable
  1116. std::string ret = unmodified;
  1117. // if this there is no value for this->MakefileVariableSize then
  1118. // the string must have bad characters in it
  1119. if (!this->MakefileVariableSize) {
  1120. std::replace(ret.begin(), ret.end(), '.', '_');
  1121. cmSystemTools::ReplaceString(ret, "-", "__");
  1122. cmSystemTools::ReplaceString(ret, "+", "___");
  1123. int ni = 0;
  1124. char buffer[5];
  1125. // make sure the _ version is not already used, if
  1126. // it is used then add number to the end of the variable
  1127. while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
  1128. ++ni;
  1129. sprintf(buffer, "%04d", ni);
  1130. ret = unmodified + buffer;
  1131. }
  1132. this->ShortMakeVariableMap[ret] = "1";
  1133. this->MakeVariableMap[unmodified] = ret;
  1134. return ret;
  1135. }
  1136. // if the string is greater than 32 chars it is an invalid variable name
  1137. // for borland make
  1138. if (static_cast<int>(ret.size()) > this->MakefileVariableSize) {
  1139. int keep = this->MakefileVariableSize - 8;
  1140. int size = keep + 3;
  1141. std::string str1 = s;
  1142. std::string str2 = s2;
  1143. // we must shorten the combined string by 4 characters
  1144. // keep no more than 24 characters from the second string
  1145. if (static_cast<int>(str2.size()) > keep) {
  1146. str2 = str2.substr(0, keep);
  1147. }
  1148. if (static_cast<int>(str1.size()) + static_cast<int>(str2.size()) > size) {
  1149. str1 = str1.substr(0, size - str2.size());
  1150. }
  1151. char buffer[5];
  1152. int ni = 0;
  1153. sprintf(buffer, "%04d", ni);
  1154. ret = str1 + str2 + buffer;
  1155. while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
  1156. ++ni;
  1157. sprintf(buffer, "%04d", ni);
  1158. ret = str1 + str2 + buffer;
  1159. }
  1160. if (ni == 1000) {
  1161. cmSystemTools::Error("Borland makefile variable length too long");
  1162. return unmodified;
  1163. }
  1164. // once an unused variable is found
  1165. this->ShortMakeVariableMap[ret] = "1";
  1166. }
  1167. // always make an entry into the unmodified to variable map
  1168. this->MakeVariableMap[unmodified] = ret;
  1169. return ret;
  1170. }
  1171. bool cmLocalUnixMakefileGenerator3::UpdateDependencies(
  1172. const std::string& tgtInfo, bool verbose, bool color)
  1173. {
  1174. // read in the target info file
  1175. if (!this->Makefile->ReadListFile(tgtInfo) ||
  1176. cmSystemTools::GetErrorOccuredFlag()) {
  1177. cmSystemTools::Error("Target DependInfo.cmake file not found");
  1178. }
  1179. // Check if any multiple output pairs have a missing file.
  1180. this->CheckMultipleOutputs(verbose);
  1181. std::string const targetDir = cmSystemTools::GetFilenamePath(tgtInfo);
  1182. std::string const internalDependFile = targetDir + "/depend.internal";
  1183. std::string const dependFile = targetDir + "/depend.make";
  1184. // If the target DependInfo.cmake file has changed since the last
  1185. // time dependencies were scanned then force rescanning. This may
  1186. // happen when a new source file is added and CMake regenerates the
  1187. // project but no other sources were touched.
  1188. bool needRescanDependInfo = false;
  1189. cmFileTimeCache* ftc =
  1190. this->GlobalGenerator->GetCMakeInstance()->GetFileTimeCache();
  1191. {
  1192. int result;
  1193. if (!ftc->Compare(internalDependFile, tgtInfo, &result) || result < 0) {
  1194. if (verbose) {
  1195. cmSystemTools::Stdout(cmStrCat("Dependee \"", tgtInfo,
  1196. "\" is newer than depender \"",
  1197. internalDependFile, "\".\n"));
  1198. }
  1199. needRescanDependInfo = true;
  1200. }
  1201. }
  1202. // If the directory information is newer than depend.internal, include dirs
  1203. // may have changed. In this case discard all old dependencies.
  1204. bool needRescanDirInfo = false;
  1205. {
  1206. std::string dirInfoFile =
  1207. cmStrCat(this->GetCurrentBinaryDirectory(),
  1208. "/CMakeFiles/CMakeDirectoryInformation.cmake");
  1209. int result;
  1210. if (!ftc->Compare(internalDependFile, dirInfoFile, &result) ||
  1211. result < 0) {
  1212. if (verbose) {
  1213. cmSystemTools::Stdout(cmStrCat("Dependee \"", dirInfoFile,
  1214. "\" is newer than depender \"",
  1215. internalDependFile, "\".\n"));
  1216. }
  1217. needRescanDirInfo = true;
  1218. }
  1219. }
  1220. // Check the implicit dependencies to see if they are up to date.
  1221. // The build.make file may have explicit dependencies for the object
  1222. // files but these will not affect the scanning process so they need
  1223. // not be considered.
  1224. cmDepends::DependencyMap validDependencies;
  1225. bool needRescanDependencies = false;
  1226. if (!needRescanDirInfo) {
  1227. cmDependsC checker;
  1228. checker.SetVerbose(verbose);
  1229. checker.SetFileTimeCache(ftc);
  1230. // cmDependsC::Check() fills the vector validDependencies() with the
  1231. // dependencies for those files where they are still valid, i.e. neither
  1232. // the files themselves nor any files they depend on have changed.
  1233. // We don't do that if the CMakeDirectoryInformation.cmake file has
  1234. // changed, because then potentially all dependencies have changed.
  1235. // This information is given later on to cmDependsC, which then only
  1236. // rescans the files where it did not get valid dependencies via this
  1237. // dependency vector. This means that in the normal case, when only
  1238. // few or one file have been edited, then also only this one file is
  1239. // actually scanned again, instead of all files for this target.
  1240. needRescanDependencies =
  1241. !checker.Check(dependFile, internalDependFile, validDependencies);
  1242. }
  1243. if (needRescanDependInfo || needRescanDirInfo || needRescanDependencies) {
  1244. // The dependencies must be regenerated.
  1245. std::string targetName = cmSystemTools::GetFilenameName(targetDir);
  1246. targetName = targetName.substr(0, targetName.length() - 4);
  1247. std::string message =
  1248. cmStrCat("Scanning dependencies of target ", targetName);
  1249. cmSystemTools::MakefileColorEcho(cmsysTerminal_Color_ForegroundMagenta |
  1250. cmsysTerminal_Color_ForegroundBold,
  1251. message.c_str(), true, color);
  1252. return this->ScanDependencies(targetDir, dependFile, internalDependFile,
  1253. validDependencies);
  1254. }
  1255. // The dependencies are already up-to-date.
  1256. return true;
  1257. }
  1258. bool cmLocalUnixMakefileGenerator3::ScanDependencies(
  1259. std::string const& targetDir, std::string const& dependFile,
  1260. std::string const& internalDependFile, cmDepends::DependencyMap& validDeps)
  1261. {
  1262. // Read the directory information file.
  1263. cmMakefile* mf = this->Makefile;
  1264. bool haveDirectoryInfo = false;
  1265. {
  1266. std::string dirInfoFile =
  1267. cmStrCat(this->GetCurrentBinaryDirectory(),
  1268. "/CMakeFiles/CMakeDirectoryInformation.cmake");
  1269. if (mf->ReadListFile(dirInfoFile) &&
  1270. !cmSystemTools::GetErrorOccuredFlag()) {
  1271. haveDirectoryInfo = true;
  1272. }
  1273. }
  1274. // Lookup useful directory information.
  1275. if (haveDirectoryInfo) {
  1276. // Test whether we need to force Unix paths.
  1277. if (const char* force = mf->GetDefinition("CMAKE_FORCE_UNIX_PATHS")) {
  1278. if (!cmIsOff(force)) {
  1279. cmSystemTools::SetForceUnixPaths(true);
  1280. }
  1281. }
  1282. // Setup relative path top directories.
  1283. if (const char* relativePathTopSource =
  1284. mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_SOURCE")) {
  1285. this->StateSnapshot.GetDirectory().SetRelativePathTopSource(
  1286. relativePathTopSource);
  1287. }
  1288. if (const char* relativePathTopBinary =
  1289. mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_BINARY")) {
  1290. this->StateSnapshot.GetDirectory().SetRelativePathTopBinary(
  1291. relativePathTopBinary);
  1292. }
  1293. } else {
  1294. cmSystemTools::Error("Directory Information file not found");
  1295. }
  1296. // Open the make depends file. This should be copy-if-different
  1297. // because the make tool may try to reload it needlessly otherwise.
  1298. cmGeneratedFileStream ruleFileStream(
  1299. dependFile, false, this->GlobalGenerator->GetMakefileEncoding());
  1300. ruleFileStream.SetCopyIfDifferent(true);
  1301. if (!ruleFileStream) {
  1302. return false;
  1303. }
  1304. // Open the cmake dependency tracking file. This should not be
  1305. // copy-if-different because dependencies are re-scanned when it is
  1306. // older than the DependInfo.cmake.
  1307. cmGeneratedFileStream internalRuleFileStream(
  1308. internalDependFile, false, this->GlobalGenerator->GetMakefileEncoding());
  1309. if (!internalRuleFileStream) {
  1310. return false;
  1311. }
  1312. this->WriteDisclaimer(ruleFileStream);
  1313. this->WriteDisclaimer(internalRuleFileStream);
  1314. // for each language we need to scan, scan it
  1315. std::vector<std::string> langs =
  1316. cmExpandedList(mf->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES"));
  1317. for (std::string const& lang : langs) {
  1318. // construct the checker
  1319. // Create the scanner for this language
  1320. std::unique_ptr<cmDepends> scanner;
  1321. if (lang == "C" || lang == "CXX" || lang == "RC" || lang == "ASM" ||
  1322. lang == "OBJC" || lang == "OBJCXX" || lang == "CUDA") {
  1323. // TODO: Handle RC (resource files) dependencies correctly.
  1324. scanner = cm::make_unique<cmDependsC>(this, targetDir, lang, &validDeps);
  1325. }
  1326. #ifndef CMAKE_BOOTSTRAP
  1327. else if (lang == "Fortran") {
  1328. ruleFileStream << "# Note that incremental build could trigger "
  1329. << "a call to cmake_copy_f90_mod on each re-build\n";
  1330. scanner = cm::make_unique<cmDependsFortran>(this);
  1331. } else if (lang == "Java") {
  1332. scanner = cm::make_unique<cmDependsJava>();
  1333. }
  1334. #endif
  1335. if (scanner) {
  1336. scanner->SetLocalGenerator(this);
  1337. scanner->SetFileTimeCache(
  1338. this->GlobalGenerator->GetCMakeInstance()->GetFileTimeCache());
  1339. scanner->SetLanguage(lang);
  1340. scanner->SetTargetDirectory(targetDir);
  1341. scanner->Write(ruleFileStream, internalRuleFileStream);
  1342. }
  1343. }
  1344. return true;
  1345. }
  1346. void cmLocalUnixMakefileGenerator3::CheckMultipleOutputs(bool verbose)
  1347. {
  1348. cmMakefile* mf = this->Makefile;
  1349. // Get the string listing the multiple output pairs.
  1350. const char* pairs_string = mf->GetDefinition("CMAKE_MULTIPLE_OUTPUT_PAIRS");
  1351. if (!pairs_string) {
  1352. return;
  1353. }
  1354. // Convert the string to a list and preserve empty entries.
  1355. std::vector<std::string> pairs = cmExpandedList(pairs_string, true);
  1356. for (auto i = pairs.begin(); 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) &&
  1362. !cmSystemTools::FileExists(depender)) {
  1363. if (verbose) {
  1364. cmSystemTools::Stdout(cmStrCat(
  1365. "Deleting primary custom command output \"", dependee,
  1366. "\" because another output \"", depender, "\" does not exist.\n"));
  1367. }
  1368. cmSystemTools::RemoveFile(dependee);
  1369. }
  1370. }
  1371. }
  1372. void cmLocalUnixMakefileGenerator3::WriteLocalAllRules(
  1373. std::ostream& ruleFileStream)
  1374. {
  1375. this->WriteDisclaimer(ruleFileStream);
  1376. // Write the main entry point target. This must be the VERY first
  1377. // target so that make with no arguments will run it.
  1378. {
  1379. // Just depend on the all target to drive the build.
  1380. std::vector<std::string> depends;
  1381. std::vector<std::string> no_commands;
  1382. depends.emplace_back("all");
  1383. // Write the rule.
  1384. this->WriteMakeRule(ruleFileStream,
  1385. "Default target executed when no arguments are "
  1386. "given to make.",
  1387. "default_target", depends, no_commands, true);
  1388. // Help out users that try "gmake target1 target2 -j".
  1389. cmGlobalUnixMakefileGenerator3* gg =
  1390. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1391. if (gg->AllowNotParallel()) {
  1392. std::vector<std::string> no_depends;
  1393. this->WriteMakeRule(ruleFileStream,
  1394. "Allow only one \"make -f "
  1395. "Makefile2\" at a time, but pass "
  1396. "parallelism.",
  1397. ".NOTPARALLEL", no_depends, no_commands, false);
  1398. }
  1399. }
  1400. this->WriteSpecialTargetsTop(ruleFileStream);
  1401. // Include the progress variables for the target.
  1402. // Write all global targets
  1403. this->WriteDivider(ruleFileStream);
  1404. ruleFileStream << "# Targets provided globally by CMake.\n"
  1405. << "\n";
  1406. const auto& targets = this->GetGeneratorTargets();
  1407. for (const auto& gt : targets) {
  1408. if (gt->GetType() == cmStateEnums::GLOBAL_TARGET) {
  1409. std::string targetString =
  1410. "Special rule for the target " + gt->GetName();
  1411. std::vector<std::string> commands;
  1412. std::vector<std::string> depends;
  1413. cmProp p = gt->GetProperty("EchoString");
  1414. const char* text = p ? p->c_str() : "Running external command ...";
  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 (cmProp 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. }