cmLocalUnixMakefileGenerator3.cxx 83 KB

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