cmLocalUnixMakefileGenerator3.cxx 81 KB

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