cmLocalUnixMakefileGenerator3.cxx 81 KB

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