cmLocalUnixMakefileGenerator3.cxx 82 KB

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