cmLocalUnixMakefileGenerator3.cxx 83 KB

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