cmLocalUnixMakefileGenerator3.cxx 73 KB

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