cmLocalUnixMakefileGenerator3.cxx 72 KB

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