cmLocalUnixMakefileGenerator3.cxx 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118
  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 <cm/vector>
  11. #include <cmext/algorithm>
  12. #include "cmsys/FStream.hxx"
  13. #include "cmsys/Terminal.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. constexpr const char* vcs_rules[] = {
  618. "%,v", "RCS/%", "RCS/%,v", "SCCS/s.%", "s.%",
  619. };
  620. for (auto vcs_rule : vcs_rules) {
  621. std::vector<std::string> vcs_depend;
  622. vcs_depend.emplace_back(vcs_rule);
  623. this->WriteMakeRule(makefileStream, "Disable VCS-based implicit rules.",
  624. "%", vcs_depend, no_commands, false);
  625. }
  626. }
  627. // Add a fake suffix to keep HP happy. Must be max 32 chars for SGI make.
  628. std::vector<std::string> depends;
  629. depends.emplace_back(".hpux_make_needs_suffix_list");
  630. this->WriteMakeRule(makefileStream, nullptr, ".SUFFIXES", depends,
  631. no_commands, false);
  632. if (this->IsWatcomWMake()) {
  633. // Switch on WMake feature, if an error or interrupt occurs during
  634. // makefile processing, the current target being made may be deleted
  635. // without prompting (the same as command line -e option).
  636. /* clang-format off */
  637. makefileStream <<
  638. "\n"
  639. ".ERASE\n"
  640. "\n"
  641. ;
  642. /* clang-format on */
  643. }
  644. if (this->Makefile->IsOn("CMAKE_VERBOSE_MAKEFILE")) {
  645. /* clang-format off */
  646. makefileStream
  647. << "# Produce verbose output by default.\n"
  648. << "VERBOSE = 1\n"
  649. << "\n";
  650. /* clang-format on */
  651. }
  652. if (this->IsWatcomWMake()) {
  653. /* clang-format off */
  654. makefileStream <<
  655. "!ifndef VERBOSE\n"
  656. ".SILENT\n"
  657. "!endif\n"
  658. "\n"
  659. ;
  660. /* clang-format on */
  661. } else {
  662. // Write special target to silence make output. This must be after
  663. // the default target in case VERBOSE is set (which changes the
  664. // name). The setting of CMAKE_VERBOSE_MAKEFILE to ON will cause a
  665. // "VERBOSE=1" to be added as a make variable which will change the
  666. // name of this special target. This gives a make-time choice to
  667. // the user.
  668. this->WriteMakeRule(makefileStream,
  669. "Suppress display of executed commands.",
  670. "$(VERBOSE).SILENT", no_depends, no_commands, false);
  671. }
  672. // Work-around for makes that drop rules that have no dependencies
  673. // or commands.
  674. cmGlobalUnixMakefileGenerator3* gg =
  675. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  676. std::string hack = gg->GetEmptyRuleHackDepends();
  677. if (!hack.empty()) {
  678. no_depends.push_back(std::move(hack));
  679. }
  680. std::string hack_cmd = gg->GetEmptyRuleHackCommand();
  681. if (!hack_cmd.empty()) {
  682. no_commands.push_back(std::move(hack_cmd));
  683. }
  684. // Special symbolic target that never exists to force dependers to
  685. // run their rules.
  686. this->WriteMakeRule(makefileStream, "A target that is always out of date.",
  687. "cmake_force", no_depends, no_commands, true);
  688. // Variables for reference by other rules.
  689. this->WriteMakeVariables(makefileStream);
  690. }
  691. void cmLocalUnixMakefileGenerator3::WriteSpecialTargetsBottom(
  692. std::ostream& makefileStream)
  693. {
  694. this->WriteDivider(makefileStream);
  695. makefileStream << "# Special targets to cleanup operation of make.\n"
  696. << "\n";
  697. // Write special "cmake_check_build_system" target to run cmake with
  698. // the --check-build-system flag.
  699. if (!this->GlobalGenerator->GlobalSettingIsOn(
  700. "CMAKE_SUPPRESS_REGENERATION")) {
  701. // Build command to run CMake to check if anything needs regenerating.
  702. std::vector<std::string> commands;
  703. cmake* cm = this->GlobalGenerator->GetCMakeInstance();
  704. if (cm->DoWriteGlobVerifyTarget()) {
  705. std::string rescanRule =
  706. cmStrCat("$(CMAKE_COMMAND) -P ",
  707. this->ConvertToOutputFormat(cm->GetGlobVerifyScript(),
  708. cmOutputConverter::SHELL));
  709. commands.push_back(rescanRule);
  710. }
  711. std::string cmakefileName = "CMakeFiles/Makefile.cmake";
  712. std::string runRule = cmStrCat(
  713. "$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) "
  714. "--check-build-system ",
  715. this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL),
  716. " 0");
  717. std::vector<std::string> no_depends;
  718. commands.push_back(std::move(runRule));
  719. if (!this->IsRootMakefile()) {
  720. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  721. this->GetCurrentBinaryDirectory());
  722. }
  723. this->WriteMakeRule(makefileStream,
  724. "Special rule to run CMake to check the build system "
  725. "integrity.\n"
  726. "No rule that depends on this can have "
  727. "commands that come from listfiles\n"
  728. "because they might be regenerated.",
  729. "cmake_check_build_system", no_depends, commands,
  730. true);
  731. }
  732. }
  733. void cmLocalUnixMakefileGenerator3::WriteConvenienceRule(
  734. std::ostream& ruleFileStream, const std::string& realTarget,
  735. const std::string& helpTarget)
  736. {
  737. // A rule is only needed if the names are different.
  738. if (realTarget != helpTarget) {
  739. // The helper target depends on the real target.
  740. std::vector<std::string> depends;
  741. depends.push_back(realTarget);
  742. // There are no commands.
  743. std::vector<std::string> no_commands;
  744. // Write the rule.
  745. this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
  746. helpTarget, depends, no_commands, true);
  747. }
  748. }
  749. std::string cmLocalUnixMakefileGenerator3::GetRelativeTargetDirectory(
  750. cmGeneratorTarget const* target) const
  751. {
  752. std::string dir =
  753. cmStrCat(this->HomeRelativeOutputPath, this->GetTargetDirectory(target));
  754. return dir;
  755. }
  756. void cmLocalUnixMakefileGenerator3::AppendFlags(
  757. std::string& flags, const std::string& newFlags) const
  758. {
  759. if (this->IsWatcomWMake() && !newFlags.empty()) {
  760. std::string newf = newFlags;
  761. if (newf.find("\\\"") != std::string::npos) {
  762. cmSystemTools::ReplaceString(newf, "\\\"", "\"");
  763. this->cmLocalGenerator::AppendFlags(flags, newf);
  764. return;
  765. }
  766. }
  767. this->cmLocalGenerator::AppendFlags(flags, newFlags);
  768. }
  769. void cmLocalUnixMakefileGenerator3::AppendRuleDepend(
  770. std::vector<std::string>& depends, const char* ruleFileName)
  771. {
  772. // Add a dependency on the rule file itself unless an option to skip
  773. // it is specifically enabled by the user or project.
  774. const char* nodep =
  775. this->Makefile->GetDefinition("CMAKE_SKIP_RULE_DEPENDENCY");
  776. if (!nodep || cmIsOff(nodep)) {
  777. depends.emplace_back(ruleFileName);
  778. }
  779. }
  780. void cmLocalUnixMakefileGenerator3::AppendRuleDepends(
  781. std::vector<std::string>& depends, std::vector<std::string> const& ruleFiles)
  782. {
  783. // Add a dependency on the rule file itself unless an option to skip
  784. // it is specifically enabled by the user or project.
  785. if (!this->Makefile->IsOn("CMAKE_SKIP_RULE_DEPENDENCY")) {
  786. cm::append(depends, ruleFiles);
  787. }
  788. }
  789. void cmLocalUnixMakefileGenerator3::AppendCustomDepends(
  790. std::vector<std::string>& depends, const std::vector<cmCustomCommand>& ccs)
  791. {
  792. for (cmCustomCommand const& cc : ccs) {
  793. cmCustomCommandGenerator ccg(cc, this->GetConfigName(), this);
  794. this->AppendCustomDepend(depends, ccg);
  795. }
  796. }
  797. void cmLocalUnixMakefileGenerator3::AppendCustomDepend(
  798. std::vector<std::string>& depends, cmCustomCommandGenerator const& ccg)
  799. {
  800. for (std::string const& d : ccg.GetDepends()) {
  801. // Lookup the real name of the dependency in case it is a CMake target.
  802. std::string dep;
  803. if (this->GetRealDependency(d, this->GetConfigName(), dep)) {
  804. depends.push_back(std::move(dep));
  805. }
  806. }
  807. }
  808. void cmLocalUnixMakefileGenerator3::AppendCustomCommands(
  809. std::vector<std::string>& commands, const std::vector<cmCustomCommand>& ccs,
  810. cmGeneratorTarget* target, std::string const& relative)
  811. {
  812. for (cmCustomCommand const& cc : ccs) {
  813. cmCustomCommandGenerator ccg(cc, this->GetConfigName(), this);
  814. this->AppendCustomCommand(commands, ccg, target, relative, true);
  815. }
  816. }
  817. void cmLocalUnixMakefileGenerator3::AppendCustomCommand(
  818. std::vector<std::string>& commands, cmCustomCommandGenerator const& ccg,
  819. cmGeneratorTarget* target, std::string const& relative, bool echo_comment,
  820. std::ostream* content)
  821. {
  822. // Optionally create a command to display the custom command's
  823. // comment text. This is used for pre-build, pre-link, and
  824. // post-build command comments. Custom build step commands have
  825. // their comments generated elsewhere.
  826. if (echo_comment) {
  827. const char* comment = ccg.GetComment();
  828. if (comment && *comment) {
  829. this->AppendEcho(commands, comment,
  830. cmLocalUnixMakefileGenerator3::EchoGenerate);
  831. }
  832. }
  833. // if the command specified a working directory use it.
  834. std::string dir = this->GetCurrentBinaryDirectory();
  835. std::string workingDir = ccg.GetWorkingDirectory();
  836. if (!workingDir.empty()) {
  837. dir = workingDir;
  838. }
  839. if (content) {
  840. *content << dir;
  841. }
  842. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  843. this->CreateRulePlaceholderExpander());
  844. // Add each command line to the set of commands.
  845. std::vector<std::string> commands1;
  846. std::string currentBinDir = this->GetCurrentBinaryDirectory();
  847. for (unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) {
  848. // Build the command line in a single string.
  849. std::string cmd = ccg.GetCommand(c);
  850. if (!cmd.empty()) {
  851. // Use "call " before any invocations of .bat or .cmd files
  852. // invoked as custom commands in the WindowsShell.
  853. //
  854. bool useCall = false;
  855. if (this->IsWindowsShell()) {
  856. std::string suffix;
  857. if (cmd.size() > 4) {
  858. suffix = cmSystemTools::LowerCase(cmd.substr(cmd.size() - 4));
  859. if (suffix == ".bat" || suffix == ".cmd") {
  860. useCall = true;
  861. }
  862. }
  863. }
  864. cmSystemTools::ReplaceString(cmd, "/./", "/");
  865. // Convert the command to a relative path only if the current
  866. // working directory will be the start-output directory.
  867. bool had_slash = cmd.find('/') != std::string::npos;
  868. if (workingDir.empty()) {
  869. cmd = this->MaybeConvertToRelativePath(currentBinDir, cmd);
  870. }
  871. bool has_slash = cmd.find('/') != std::string::npos;
  872. if (had_slash && !has_slash) {
  873. // This command was specified as a path to a file in the
  874. // current directory. Add a leading "./" so it can run
  875. // without the current directory being in the search path.
  876. cmd = cmStrCat("./", cmd);
  877. }
  878. std::string launcher;
  879. // Short-circuit if there is no launcher.
  880. const char* val = this->GetRuleLauncher(target, "RULE_LAUNCH_CUSTOM");
  881. if (val && *val) {
  882. // Expand rule variables referenced in the given launcher command.
  883. cmRulePlaceholderExpander::RuleVariables vars;
  884. vars.CMTargetName = target->GetName().c_str();
  885. vars.CMTargetType = cmState::GetTargetTypeName(target->GetType());
  886. std::string output;
  887. const std::vector<std::string>& outputs = ccg.GetOutputs();
  888. if (!outputs.empty()) {
  889. output = outputs[0];
  890. if (workingDir.empty()) {
  891. output = this->MaybeConvertToRelativePath(
  892. this->GetCurrentBinaryDirectory(), output);
  893. }
  894. output =
  895. this->ConvertToOutputFormat(output, cmOutputConverter::SHELL);
  896. }
  897. vars.Output = output.c_str();
  898. launcher = val;
  899. rulePlaceholderExpander->ExpandRuleVariables(this, launcher, vars);
  900. if (!launcher.empty()) {
  901. launcher += " ";
  902. }
  903. }
  904. std::string shellCommand = this->MaybeConvertWatcomShellCommand(cmd);
  905. if (shellCommand.empty()) {
  906. shellCommand =
  907. this->ConvertToOutputFormat(cmd, cmOutputConverter::SHELL);
  908. }
  909. cmd = launcher + shellCommand;
  910. ccg.AppendArguments(c, cmd);
  911. if (content) {
  912. // Rule content does not include the launcher.
  913. *content << (cmd.c_str() + launcher.size());
  914. }
  915. if (this->BorlandMakeCurlyHack) {
  916. // Borland Make has a very strange bug. If the first curly
  917. // brace anywhere in the command string is a left curly, it
  918. // must be written {{} instead of just {. Otherwise some
  919. // curly braces are removed. The hack can be skipped if the
  920. // first curly brace is the last character.
  921. std::string::size_type lcurly = cmd.find('{');
  922. if (lcurly != std::string::npos && lcurly < (cmd.size() - 1)) {
  923. std::string::size_type rcurly = cmd.find('}');
  924. if (rcurly == std::string::npos || rcurly > lcurly) {
  925. // The first curly is a left curly. Use the hack.
  926. cmd =
  927. cmStrCat(cmd.substr(0, lcurly), "{{}", cmd.substr(lcurly + 1));
  928. }
  929. }
  930. }
  931. if (launcher.empty()) {
  932. if (useCall) {
  933. cmd = cmStrCat("call ", cmd);
  934. } else if (this->IsNMake() && cmd[0] == '"') {
  935. cmd = cmStrCat("echo >nul && ", cmd);
  936. }
  937. }
  938. commands1.push_back(std::move(cmd));
  939. }
  940. }
  941. // Setup the proper working directory for the commands.
  942. this->CreateCDCommand(commands1, dir, relative);
  943. // push back the custom commands
  944. cm::append(commands, commands1);
  945. }
  946. void cmLocalUnixMakefileGenerator3::AppendCleanCommand(
  947. std::vector<std::string>& commands, const std::set<std::string>& files,
  948. cmGeneratorTarget* target, const char* filename)
  949. {
  950. std::string currentBinDir = this->GetCurrentBinaryDirectory();
  951. std::string cleanfile = cmStrCat(
  952. currentBinDir, '/', this->GetTargetDirectory(target), "/cmake_clean");
  953. if (filename) {
  954. cleanfile += "_";
  955. cleanfile += filename;
  956. }
  957. cleanfile += ".cmake";
  958. std::string cleanfilePath = cmSystemTools::CollapseFullPath(cleanfile);
  959. cmsys::ofstream fout(cleanfilePath.c_str());
  960. if (!fout) {
  961. cmSystemTools::Error("Could not create " + cleanfilePath);
  962. }
  963. if (!files.empty()) {
  964. fout << "file(REMOVE_RECURSE\n";
  965. for (std::string const& file : files) {
  966. std::string fc = this->MaybeConvertToRelativePath(currentBinDir, file);
  967. fout << " " << cmOutputConverter::EscapeForCMake(fc) << "\n";
  968. }
  969. fout << ")\n";
  970. }
  971. {
  972. std::string remove =
  973. cmStrCat("$(CMAKE_COMMAND) -P ",
  974. this->ConvertToOutputFormat(
  975. this->MaybeConvertToRelativePath(
  976. this->GetCurrentBinaryDirectory(), 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::AppendDirectoryCleanCommand(
  997. std::vector<std::string>& commands)
  998. {
  999. std::vector<std::string> cleanFiles;
  1000. // Look for additional files registered for cleaning in this directory.
  1001. if (const char* prop_value =
  1002. this->Makefile->GetProperty("ADDITIONAL_CLEAN_FILES")) {
  1003. cmExpandList(cmGeneratorExpression::Evaluate(
  1004. prop_value, this,
  1005. this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE")),
  1006. cleanFiles);
  1007. }
  1008. if (cleanFiles.empty()) {
  1009. return;
  1010. }
  1011. const auto& rootLG = this->GetGlobalGenerator()->GetLocalGenerators().at(0);
  1012. std::string const& binaryDir = rootLG->GetCurrentBinaryDirectory();
  1013. std::string const& currentBinaryDir = this->GetCurrentBinaryDirectory();
  1014. std::string cleanfile =
  1015. cmStrCat(currentBinaryDir, "/CMakeFiles/cmake_directory_clean.cmake");
  1016. // Write clean script
  1017. {
  1018. std::string cleanfilePath = cmSystemTools::CollapseFullPath(cleanfile);
  1019. cmsys::ofstream fout(cleanfilePath.c_str());
  1020. if (!fout) {
  1021. cmSystemTools::Error("Could not create " + cleanfilePath);
  1022. return;
  1023. }
  1024. fout << "file(REMOVE_RECURSE\n";
  1025. for (std::string const& cfl : cleanFiles) {
  1026. std::string fc = rootLG->MaybeConvertToRelativePath(
  1027. binaryDir, cmSystemTools::CollapseFullPath(cfl, currentBinaryDir));
  1028. fout << " " << cmOutputConverter::EscapeForCMake(fc) << "\n";
  1029. }
  1030. fout << ")\n";
  1031. }
  1032. // Create command
  1033. {
  1034. std::string remove =
  1035. cmStrCat("$(CMAKE_COMMAND) -P ",
  1036. this->ConvertToOutputFormat(
  1037. rootLG->MaybeConvertToRelativePath(binaryDir, cleanfile),
  1038. cmOutputConverter::SHELL));
  1039. commands.push_back(std::move(remove));
  1040. }
  1041. }
  1042. void cmLocalUnixMakefileGenerator3::AppendEcho(
  1043. std::vector<std::string>& commands, std::string const& text, EchoColor color,
  1044. EchoProgress const* progress)
  1045. {
  1046. // Choose the color for the text.
  1047. std::string color_name;
  1048. if (this->GlobalGenerator->GetToolSupportsColor() && this->ColorMakefile) {
  1049. // See cmake::ExecuteEchoColor in cmake.cxx for these options.
  1050. // This color set is readable on both black and white backgrounds.
  1051. switch (color) {
  1052. case EchoNormal:
  1053. break;
  1054. case EchoDepend:
  1055. color_name = "--magenta --bold ";
  1056. break;
  1057. case EchoBuild:
  1058. color_name = "--green ";
  1059. break;
  1060. case EchoLink:
  1061. color_name = "--green --bold ";
  1062. break;
  1063. case EchoGenerate:
  1064. color_name = "--blue --bold ";
  1065. break;
  1066. case EchoGlobal:
  1067. color_name = "--cyan ";
  1068. break;
  1069. }
  1070. }
  1071. // Echo one line at a time.
  1072. std::string line;
  1073. line.reserve(200);
  1074. for (const char* c = text.c_str();; ++c) {
  1075. if (*c == '\n' || *c == '\0') {
  1076. // Avoid writing a blank last line on end-of-string.
  1077. if (*c != '\0' || !line.empty()) {
  1078. // Add a command to echo this line.
  1079. std::string cmd;
  1080. if (color_name.empty() && !progress) {
  1081. // Use the native echo command.
  1082. cmd = cmStrCat("@echo ", this->EscapeForShell(line, false, true));
  1083. } else {
  1084. // Use cmake to echo the text in color.
  1085. cmd = cmStrCat(
  1086. "@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) ",
  1087. color_name);
  1088. if (progress) {
  1089. cmd += "--progress-dir=";
  1090. cmd += this->ConvertToOutputFormat(
  1091. cmSystemTools::CollapseFullPath(progress->Dir),
  1092. cmOutputConverter::SHELL);
  1093. cmd += " ";
  1094. cmd += "--progress-num=";
  1095. cmd += progress->Arg;
  1096. cmd += " ";
  1097. }
  1098. cmd += this->EscapeForShell(line);
  1099. }
  1100. commands.push_back(std::move(cmd));
  1101. }
  1102. // Reset the line to empty.
  1103. line.clear();
  1104. // Progress appears only on first line.
  1105. progress = nullptr;
  1106. // Terminate on end-of-string.
  1107. if (*c == '\0') {
  1108. return;
  1109. }
  1110. } else if (*c != '\r') {
  1111. // Append this character to the current line.
  1112. line += *c;
  1113. }
  1114. }
  1115. }
  1116. std::string cmLocalUnixMakefileGenerator3::CreateMakeVariable(
  1117. std::string const& s, std::string const& s2)
  1118. {
  1119. std::string unmodified = cmStrCat(s, s2);
  1120. // if there is no restriction on the length of make variables
  1121. // and there are no "." characters in the string, then return the
  1122. // unmodified combination.
  1123. if ((!this->MakefileVariableSize &&
  1124. unmodified.find('.') == std::string::npos) &&
  1125. (!this->MakefileVariableSize &&
  1126. unmodified.find('+') == std::string::npos) &&
  1127. (!this->MakefileVariableSize &&
  1128. unmodified.find('-') == std::string::npos)) {
  1129. return unmodified;
  1130. }
  1131. // see if the variable has been defined before and return
  1132. // the modified version of the variable
  1133. auto i = this->MakeVariableMap.find(unmodified);
  1134. if (i != this->MakeVariableMap.end()) {
  1135. return i->second;
  1136. }
  1137. // start with the unmodified variable
  1138. std::string ret = unmodified;
  1139. // if this there is no value for this->MakefileVariableSize then
  1140. // the string must have bad characters in it
  1141. if (!this->MakefileVariableSize) {
  1142. std::replace(ret.begin(), ret.end(), '.', '_');
  1143. cmSystemTools::ReplaceString(ret, "-", "__");
  1144. cmSystemTools::ReplaceString(ret, "+", "___");
  1145. int ni = 0;
  1146. char buffer[5];
  1147. // make sure the _ version is not already used, if
  1148. // it is used then add number to the end of the variable
  1149. while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
  1150. ++ni;
  1151. sprintf(buffer, "%04d", ni);
  1152. ret = unmodified + buffer;
  1153. }
  1154. this->ShortMakeVariableMap[ret] = "1";
  1155. this->MakeVariableMap[unmodified] = ret;
  1156. return ret;
  1157. }
  1158. // if the string is greater than 32 chars it is an invalid variable name
  1159. // for borland make
  1160. if (static_cast<int>(ret.size()) > this->MakefileVariableSize) {
  1161. int keep = this->MakefileVariableSize - 8;
  1162. int size = keep + 3;
  1163. std::string str1 = s;
  1164. std::string str2 = s2;
  1165. // we must shorten the combined string by 4 characters
  1166. // keep no more than 24 characters from the second string
  1167. if (static_cast<int>(str2.size()) > keep) {
  1168. str2 = str2.substr(0, keep);
  1169. }
  1170. if (static_cast<int>(str1.size()) + static_cast<int>(str2.size()) > size) {
  1171. str1 = str1.substr(0, size - str2.size());
  1172. }
  1173. char buffer[5];
  1174. int ni = 0;
  1175. sprintf(buffer, "%04d", ni);
  1176. ret = str1 + str2 + buffer;
  1177. while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
  1178. ++ni;
  1179. sprintf(buffer, "%04d", ni);
  1180. ret = str1 + str2 + buffer;
  1181. }
  1182. if (ni == 1000) {
  1183. cmSystemTools::Error("Borland makefile variable length too long");
  1184. return unmodified;
  1185. }
  1186. // once an unused variable is found
  1187. this->ShortMakeVariableMap[ret] = "1";
  1188. }
  1189. // always make an entry into the unmodified to variable map
  1190. this->MakeVariableMap[unmodified] = ret;
  1191. return ret;
  1192. }
  1193. bool cmLocalUnixMakefileGenerator3::UpdateDependencies(
  1194. const std::string& tgtInfo, bool verbose, bool color)
  1195. {
  1196. // read in the target info file
  1197. if (!this->Makefile->ReadListFile(tgtInfo) ||
  1198. cmSystemTools::GetErrorOccuredFlag()) {
  1199. cmSystemTools::Error("Target DependInfo.cmake file not found");
  1200. }
  1201. // Check if any multiple output pairs have a missing file.
  1202. this->CheckMultipleOutputs(verbose);
  1203. std::string const targetDir = cmSystemTools::GetFilenamePath(tgtInfo);
  1204. std::string const internalDependFile = targetDir + "/depend.internal";
  1205. std::string const dependFile = targetDir + "/depend.make";
  1206. // If the target DependInfo.cmake file has changed since the last
  1207. // time dependencies were scanned then force rescanning. This may
  1208. // happen when a new source file is added and CMake regenerates the
  1209. // project but no other sources were touched.
  1210. bool needRescanDependInfo = false;
  1211. cmFileTimeCache* ftc =
  1212. this->GlobalGenerator->GetCMakeInstance()->GetFileTimeCache();
  1213. {
  1214. int result;
  1215. if (!ftc->Compare(internalDependFile, tgtInfo, &result) || result < 0) {
  1216. if (verbose) {
  1217. std::ostringstream msg;
  1218. msg << "Dependee \"" << tgtInfo << "\" is newer than depender \""
  1219. << internalDependFile << "\"." << std::endl;
  1220. cmSystemTools::Stdout(msg.str());
  1221. }
  1222. needRescanDependInfo = true;
  1223. }
  1224. }
  1225. // If the directory information is newer than depend.internal, include dirs
  1226. // may have changed. In this case discard all old dependencies.
  1227. bool needRescanDirInfo = false;
  1228. {
  1229. std::string dirInfoFile =
  1230. cmStrCat(this->GetCurrentBinaryDirectory(),
  1231. "/CMakeFiles/CMakeDirectoryInformation.cmake");
  1232. int result;
  1233. if (!ftc->Compare(internalDependFile, dirInfoFile, &result) ||
  1234. result < 0) {
  1235. if (verbose) {
  1236. std::ostringstream msg;
  1237. msg << "Dependee \"" << dirInfoFile << "\" is newer than depender \""
  1238. << internalDependFile << "\"." << std::endl;
  1239. cmSystemTools::Stdout(msg.str());
  1240. }
  1241. needRescanDirInfo = true;
  1242. }
  1243. }
  1244. // Check the implicit dependencies to see if they are up to date.
  1245. // The build.make file may have explicit dependencies for the object
  1246. // files but these will not affect the scanning process so they need
  1247. // not be considered.
  1248. cmDepends::DependencyMap validDependencies;
  1249. bool needRescanDependencies = false;
  1250. if (!needRescanDirInfo) {
  1251. cmDependsC checker;
  1252. checker.SetVerbose(verbose);
  1253. checker.SetFileTimeCache(ftc);
  1254. // cmDependsC::Check() fills the vector validDependencies() with the
  1255. // dependencies for those files where they are still valid, i.e. neither
  1256. // the files themselves nor any files they depend on have changed.
  1257. // We don't do that if the CMakeDirectoryInformation.cmake file has
  1258. // changed, because then potentially all dependencies have changed.
  1259. // This information is given later on to cmDependsC, which then only
  1260. // rescans the files where it did not get valid dependencies via this
  1261. // dependency vector. This means that in the normal case, when only
  1262. // few or one file have been edited, then also only this one file is
  1263. // actually scanned again, instead of all files for this target.
  1264. needRescanDependencies =
  1265. !checker.Check(dependFile, internalDependFile, validDependencies);
  1266. }
  1267. if (needRescanDependInfo || needRescanDirInfo || needRescanDependencies) {
  1268. // The dependencies must be regenerated.
  1269. std::string targetName = cmSystemTools::GetFilenameName(targetDir);
  1270. targetName = targetName.substr(0, targetName.length() - 4);
  1271. std::string message =
  1272. cmStrCat("Scanning dependencies of target ", targetName);
  1273. cmSystemTools::MakefileColorEcho(cmsysTerminal_Color_ForegroundMagenta |
  1274. cmsysTerminal_Color_ForegroundBold,
  1275. message.c_str(), true, color);
  1276. return this->ScanDependencies(targetDir, dependFile, internalDependFile,
  1277. validDependencies);
  1278. }
  1279. // The dependencies are already up-to-date.
  1280. return true;
  1281. }
  1282. bool cmLocalUnixMakefileGenerator3::ScanDependencies(
  1283. std::string const& targetDir, std::string const& dependFile,
  1284. std::string const& internalDependFile, cmDepends::DependencyMap& validDeps)
  1285. {
  1286. // Read the directory information file.
  1287. cmMakefile* mf = this->Makefile;
  1288. bool haveDirectoryInfo = false;
  1289. {
  1290. std::string dirInfoFile =
  1291. cmStrCat(this->GetCurrentBinaryDirectory(),
  1292. "/CMakeFiles/CMakeDirectoryInformation.cmake");
  1293. if (mf->ReadListFile(dirInfoFile) &&
  1294. !cmSystemTools::GetErrorOccuredFlag()) {
  1295. haveDirectoryInfo = true;
  1296. }
  1297. }
  1298. // Lookup useful directory information.
  1299. if (haveDirectoryInfo) {
  1300. // Test whether we need to force Unix paths.
  1301. if (const char* force = mf->GetDefinition("CMAKE_FORCE_UNIX_PATHS")) {
  1302. if (!cmIsOff(force)) {
  1303. cmSystemTools::SetForceUnixPaths(true);
  1304. }
  1305. }
  1306. // Setup relative path top directories.
  1307. if (const char* relativePathTopSource =
  1308. mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_SOURCE")) {
  1309. this->StateSnapshot.GetDirectory().SetRelativePathTopSource(
  1310. relativePathTopSource);
  1311. }
  1312. if (const char* relativePathTopBinary =
  1313. mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_BINARY")) {
  1314. this->StateSnapshot.GetDirectory().SetRelativePathTopBinary(
  1315. relativePathTopBinary);
  1316. }
  1317. } else {
  1318. cmSystemTools::Error("Directory Information file not found");
  1319. }
  1320. // Open the make depends file. This should be copy-if-different
  1321. // because the make tool may try to reload it needlessly otherwise.
  1322. cmGeneratedFileStream ruleFileStream(
  1323. dependFile, false, this->GlobalGenerator->GetMakefileEncoding());
  1324. ruleFileStream.SetCopyIfDifferent(true);
  1325. if (!ruleFileStream) {
  1326. return false;
  1327. }
  1328. // Open the cmake dependency tracking file. This should not be
  1329. // copy-if-different because dependencies are re-scanned when it is
  1330. // older than the DependInfo.cmake.
  1331. cmGeneratedFileStream internalRuleFileStream(
  1332. internalDependFile, false, this->GlobalGenerator->GetMakefileEncoding());
  1333. if (!internalRuleFileStream) {
  1334. return false;
  1335. }
  1336. this->WriteDisclaimer(ruleFileStream);
  1337. this->WriteDisclaimer(internalRuleFileStream);
  1338. // for each language we need to scan, scan it
  1339. std::vector<std::string> langs =
  1340. cmExpandedList(mf->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES"));
  1341. for (std::string const& lang : langs) {
  1342. // construct the checker
  1343. // Create the scanner for this language
  1344. std::unique_ptr<cmDepends> scanner;
  1345. if (lang == "C" || lang == "CXX" || lang == "RC" || lang == "ASM" ||
  1346. lang == "CUDA") {
  1347. // TODO: Handle RC (resource files) dependencies correctly.
  1348. scanner = cm::make_unique<cmDependsC>(this, targetDir, lang, &validDeps);
  1349. }
  1350. #ifndef CMAKE_BOOTSTRAP
  1351. else if (lang == "Fortran") {
  1352. ruleFileStream << "# Note that incremental build could trigger "
  1353. << "a call to cmake_copy_f90_mod on each re-build\n";
  1354. scanner = cm::make_unique<cmDependsFortran>(this);
  1355. } else if (lang == "Java") {
  1356. scanner = cm::make_unique<cmDependsJava>();
  1357. }
  1358. #endif
  1359. if (scanner) {
  1360. scanner->SetLocalGenerator(this);
  1361. scanner->SetFileTimeCache(
  1362. this->GlobalGenerator->GetCMakeInstance()->GetFileTimeCache());
  1363. scanner->SetLanguage(lang);
  1364. scanner->SetTargetDirectory(targetDir);
  1365. scanner->Write(ruleFileStream, internalRuleFileStream);
  1366. }
  1367. }
  1368. return true;
  1369. }
  1370. void cmLocalUnixMakefileGenerator3::CheckMultipleOutputs(bool verbose)
  1371. {
  1372. cmMakefile* mf = this->Makefile;
  1373. // Get the string listing the multiple output pairs.
  1374. const char* pairs_string = mf->GetDefinition("CMAKE_MULTIPLE_OUTPUT_PAIRS");
  1375. if (!pairs_string) {
  1376. return;
  1377. }
  1378. // Convert the string to a list and preserve empty entries.
  1379. std::vector<std::string> pairs = cmExpandedList(pairs_string, true);
  1380. for (auto i = pairs.begin(); i != pairs.end() && (i + 1) != pairs.end();) {
  1381. const std::string& depender = *i++;
  1382. const std::string& dependee = *i++;
  1383. // If the depender is missing then delete the dependee to make
  1384. // sure both will be regenerated.
  1385. if (cmSystemTools::FileExists(dependee) &&
  1386. !cmSystemTools::FileExists(depender)) {
  1387. if (verbose) {
  1388. std::ostringstream msg;
  1389. msg << "Deleting primary custom command output \"" << dependee
  1390. << "\" because another output \"" << depender
  1391. << "\" does not exist." << std::endl;
  1392. cmSystemTools::Stdout(msg.str());
  1393. }
  1394. cmSystemTools::RemoveFile(dependee);
  1395. }
  1396. }
  1397. }
  1398. void cmLocalUnixMakefileGenerator3::WriteLocalAllRules(
  1399. std::ostream& ruleFileStream)
  1400. {
  1401. this->WriteDisclaimer(ruleFileStream);
  1402. // Write the main entry point target. This must be the VERY first
  1403. // target so that make with no arguments will run it.
  1404. {
  1405. // Just depend on the all target to drive the build.
  1406. std::vector<std::string> depends;
  1407. std::vector<std::string> no_commands;
  1408. depends.emplace_back("all");
  1409. // Write the rule.
  1410. this->WriteMakeRule(ruleFileStream,
  1411. "Default target executed when no arguments are "
  1412. "given to make.",
  1413. "default_target", depends, no_commands, true);
  1414. // Help out users that try "gmake target1 target2 -j".
  1415. cmGlobalUnixMakefileGenerator3* gg =
  1416. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1417. if (gg->AllowNotParallel()) {
  1418. std::vector<std::string> no_depends;
  1419. this->WriteMakeRule(ruleFileStream,
  1420. "Allow only one \"make -f "
  1421. "Makefile2\" at a time, but pass "
  1422. "parallelism.",
  1423. ".NOTPARALLEL", no_depends, no_commands, false);
  1424. }
  1425. }
  1426. this->WriteSpecialTargetsTop(ruleFileStream);
  1427. // Include the progress variables for the target.
  1428. // Write all global targets
  1429. this->WriteDivider(ruleFileStream);
  1430. ruleFileStream << "# Targets provided globally by CMake.\n"
  1431. << "\n";
  1432. const auto& targets = this->GetGeneratorTargets();
  1433. for (const auto& gt : targets) {
  1434. if (gt->GetType() == cmStateEnums::GLOBAL_TARGET) {
  1435. std::string targetString =
  1436. "Special rule for the target " + gt->GetName();
  1437. std::vector<std::string> commands;
  1438. std::vector<std::string> depends;
  1439. const char* text = gt->GetProperty("EchoString");
  1440. if (!text) {
  1441. text = "Running external command ...";
  1442. }
  1443. depends.reserve(gt->GetUtilities().size());
  1444. for (BT<std::string> const& u : gt->GetUtilities()) {
  1445. depends.push_back(u.Value);
  1446. }
  1447. this->AppendEcho(commands, text,
  1448. cmLocalUnixMakefileGenerator3::EchoGlobal);
  1449. // Global targets store their rules in pre- and post-build commands.
  1450. this->AppendCustomDepends(depends, gt->GetPreBuildCommands());
  1451. this->AppendCustomDepends(depends, gt->GetPostBuildCommands());
  1452. this->AppendCustomCommands(commands, gt->GetPreBuildCommands(), gt.get(),
  1453. this->GetCurrentBinaryDirectory());
  1454. this->AppendCustomCommands(commands, gt->GetPostBuildCommands(),
  1455. gt.get(), this->GetCurrentBinaryDirectory());
  1456. std::string targetName = gt->GetName();
  1457. this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
  1458. depends, commands, true);
  1459. // Provide a "/fast" version of the target.
  1460. depends.clear();
  1461. if ((targetName == "install") || (targetName == "install/local") ||
  1462. (targetName == "install/strip")) {
  1463. // Provide a fast install target that does not depend on all
  1464. // but has the same command.
  1465. depends.emplace_back("preinstall/fast");
  1466. } else {
  1467. // Just forward to the real target so at least it will work.
  1468. depends.push_back(targetName);
  1469. commands.clear();
  1470. }
  1471. targetName += "/fast";
  1472. this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
  1473. depends, commands, true);
  1474. }
  1475. }
  1476. std::vector<std::string> depends;
  1477. std::vector<std::string> commands;
  1478. // Write the all rule.
  1479. std::string recursiveTarget =
  1480. cmStrCat(this->GetCurrentBinaryDirectory(), "/all");
  1481. bool regenerate =
  1482. !this->GlobalGenerator->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION");
  1483. if (regenerate) {
  1484. depends.emplace_back("cmake_check_build_system");
  1485. }
  1486. std::string progressDir =
  1487. cmStrCat(this->GetBinaryDirectory(), "/CMakeFiles");
  1488. {
  1489. std::ostringstream progCmd;
  1490. progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start ";
  1491. progCmd << this->ConvertToOutputFormat(
  1492. cmSystemTools::CollapseFullPath(progressDir), cmOutputConverter::SHELL);
  1493. std::string progressFile = "/CMakeFiles/progress.marks";
  1494. std::string progressFileNameFull = this->ConvertToFullPath(progressFile);
  1495. progCmd << " "
  1496. << this->ConvertToOutputFormat(
  1497. cmSystemTools::CollapseFullPath(progressFileNameFull),
  1498. cmOutputConverter::SHELL);
  1499. commands.push_back(progCmd.str());
  1500. }
  1501. std::string mf2Dir = "CMakeFiles/Makefile2";
  1502. commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
  1503. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1504. this->GetCurrentBinaryDirectory());
  1505. {
  1506. std::ostringstream progCmd;
  1507. progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; // # 0
  1508. progCmd << this->ConvertToOutputFormat(
  1509. cmSystemTools::CollapseFullPath(progressDir), cmOutputConverter::SHELL);
  1510. progCmd << " 0";
  1511. commands.push_back(progCmd.str());
  1512. }
  1513. this->WriteMakeRule(ruleFileStream, "The main all target", "all", depends,
  1514. commands, true);
  1515. // Write the clean rule.
  1516. recursiveTarget = cmStrCat(this->GetCurrentBinaryDirectory(), "/clean");
  1517. commands.clear();
  1518. depends.clear();
  1519. commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
  1520. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1521. this->GetCurrentBinaryDirectory());
  1522. this->WriteMakeRule(ruleFileStream, "The main clean target", "clean",
  1523. depends, commands, true);
  1524. commands.clear();
  1525. depends.clear();
  1526. depends.emplace_back("clean");
  1527. this->WriteMakeRule(ruleFileStream, "The main clean target", "clean/fast",
  1528. depends, commands, true);
  1529. // Write the preinstall rule.
  1530. recursiveTarget = cmStrCat(this->GetCurrentBinaryDirectory(), "/preinstall");
  1531. commands.clear();
  1532. depends.clear();
  1533. const char* noall =
  1534. this->Makefile->GetDefinition("CMAKE_SKIP_INSTALL_ALL_DEPENDENCY");
  1535. if (!noall || cmIsOff(noall)) {
  1536. // Drive the build before installing.
  1537. depends.emplace_back("all");
  1538. } else if (regenerate) {
  1539. // At least make sure the build system is up to date.
  1540. depends.emplace_back("cmake_check_build_system");
  1541. }
  1542. commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
  1543. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1544. this->GetCurrentBinaryDirectory());
  1545. this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
  1546. "preinstall", depends, commands, true);
  1547. depends.clear();
  1548. this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
  1549. "preinstall/fast", depends, commands, true);
  1550. if (regenerate) {
  1551. // write the depend rule, really a recompute depends rule
  1552. depends.clear();
  1553. commands.clear();
  1554. cmake* cm = this->GlobalGenerator->GetCMakeInstance();
  1555. if (cm->DoWriteGlobVerifyTarget()) {
  1556. std::string rescanRule =
  1557. cmStrCat("$(CMAKE_COMMAND) -P ",
  1558. this->ConvertToOutputFormat(cm->GetGlobVerifyScript(),
  1559. cmOutputConverter::SHELL));
  1560. commands.push_back(rescanRule);
  1561. }
  1562. std::string cmakefileName = "CMakeFiles/Makefile.cmake";
  1563. {
  1564. std::string runRule = cmStrCat(
  1565. "$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) "
  1566. "--check-build-system ",
  1567. this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL),
  1568. " 1");
  1569. commands.push_back(std::move(runRule));
  1570. }
  1571. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1572. this->GetCurrentBinaryDirectory());
  1573. this->WriteMakeRule(ruleFileStream, "clear depends", "depend", depends,
  1574. commands, true);
  1575. }
  1576. }
  1577. void cmLocalUnixMakefileGenerator3::ClearDependencies(cmMakefile* mf,
  1578. bool verbose)
  1579. {
  1580. // Get the list of target files to check
  1581. const char* infoDef = mf->GetDefinition("CMAKE_DEPEND_INFO_FILES");
  1582. if (!infoDef) {
  1583. return;
  1584. }
  1585. std::vector<std::string> files = cmExpandedList(infoDef);
  1586. // Each depend information file corresponds to a target. Clear the
  1587. // dependencies for that target.
  1588. cmDepends clearer;
  1589. clearer.SetVerbose(verbose);
  1590. for (std::string const& file : files) {
  1591. std::string dir = cmSystemTools::GetFilenamePath(file);
  1592. // Clear the implicit dependency makefile.
  1593. std::string dependFile = dir + "/depend.make";
  1594. clearer.Clear(dependFile);
  1595. // Remove the internal dependency check file to force
  1596. // regeneration.
  1597. std::string internalDependFile = dir + "/depend.internal";
  1598. cmSystemTools::RemoveFile(internalDependFile);
  1599. }
  1600. }
  1601. namespace {
  1602. // Helper predicate for removing absolute paths that don't point to the
  1603. // source or binary directory. It is used when CMAKE_DEPENDS_IN_PROJECT_ONLY
  1604. // is set ON, to only consider in-project dependencies during the build.
  1605. class NotInProjectDir
  1606. {
  1607. public:
  1608. // Constructor with the source and binary directory's path
  1609. NotInProjectDir(std::string sourceDir, std::string binaryDir)
  1610. : SourceDir(std::move(sourceDir))
  1611. , BinaryDir(std::move(binaryDir))
  1612. {
  1613. }
  1614. // Operator evaluating the predicate
  1615. bool operator()(const std::string& path) const
  1616. {
  1617. // Keep all relative paths:
  1618. if (!cmSystemTools::FileIsFullPath(path)) {
  1619. return false;
  1620. }
  1621. // If it's an absolute path, check if it starts with the source
  1622. // direcotory:
  1623. return (
  1624. !(IsInDirectory(SourceDir, path) || IsInDirectory(BinaryDir, path)));
  1625. }
  1626. private:
  1627. // Helper function used by the predicate
  1628. static bool IsInDirectory(const std::string& baseDir,
  1629. const std::string& testDir)
  1630. {
  1631. // First check if the test directory "starts with" the base directory:
  1632. if (testDir.find(baseDir) != 0) {
  1633. return false;
  1634. }
  1635. // If it does, then check that it's either the same string, or that the
  1636. // next character is a slash:
  1637. return ((testDir.size() == baseDir.size()) ||
  1638. (testDir[baseDir.size()] == '/'));
  1639. }
  1640. // The path to the source directory
  1641. std::string SourceDir;
  1642. // The path to the binary directory
  1643. std::string BinaryDir;
  1644. };
  1645. }
  1646. void cmLocalUnixMakefileGenerator3::WriteDependLanguageInfo(
  1647. std::ostream& cmakefileStream, cmGeneratorTarget* target)
  1648. {
  1649. ImplicitDependLanguageMap const& implicitLangs =
  1650. this->GetImplicitDepends(target);
  1651. // list the languages
  1652. cmakefileStream
  1653. << "# The set of languages for which implicit dependencies are needed:\n";
  1654. cmakefileStream << "set(CMAKE_DEPENDS_LANGUAGES\n";
  1655. for (auto const& implicitLang : implicitLangs) {
  1656. cmakefileStream << " \"" << implicitLang.first << "\"\n";
  1657. }
  1658. cmakefileStream << " )\n";
  1659. // now list the files for each language
  1660. cmakefileStream
  1661. << "# The set of files for implicit dependencies of each language:\n";
  1662. for (auto const& implicitLang : implicitLangs) {
  1663. cmakefileStream << "set(CMAKE_DEPENDS_CHECK_" << implicitLang.first
  1664. << "\n";
  1665. ImplicitDependFileMap const& implicitPairs = implicitLang.second;
  1666. // for each file pair
  1667. for (auto const& implicitPair : implicitPairs) {
  1668. for (auto const& di : implicitPair.second) {
  1669. cmakefileStream << " \"" << di << "\" ";
  1670. cmakefileStream << "\"" << implicitPair.first << "\"\n";
  1671. }
  1672. }
  1673. cmakefileStream << " )\n";
  1674. // Tell the dependency scanner what compiler is used.
  1675. std::string cidVar =
  1676. cmStrCat("CMAKE_", implicitLang.first, "_COMPILER_ID");
  1677. const char* cid = this->Makefile->GetDefinition(cidVar);
  1678. if (cid && *cid) {
  1679. cmakefileStream << "set(CMAKE_" << implicitLang.first
  1680. << "_COMPILER_ID \"" << cid << "\")\n";
  1681. }
  1682. if (implicitLang.first == "Fortran") {
  1683. std::string smodSep =
  1684. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_SEP");
  1685. std::string smodExt =
  1686. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_EXT");
  1687. cmakefileStream << "set(CMAKE_Fortran_SUBMODULE_SEP \"" << smodSep
  1688. << "\")\n";
  1689. cmakefileStream << "set(CMAKE_Fortran_SUBMODULE_EXT \"" << smodExt
  1690. << "\")\n";
  1691. }
  1692. // Build a list of preprocessor definitions for the target.
  1693. std::set<std::string> defines;
  1694. this->GetTargetDefines(target, this->GetConfigName(), implicitLang.first,
  1695. defines);
  1696. if (!defines.empty()) {
  1697. /* clang-format off */
  1698. cmakefileStream
  1699. << "\n"
  1700. << "# Preprocessor definitions for this target.\n"
  1701. << "set(CMAKE_TARGET_DEFINITIONS_" << implicitLang.first << "\n";
  1702. /* clang-format on */
  1703. for (std::string const& define : defines) {
  1704. cmakefileStream << " " << cmOutputConverter::EscapeForCMake(define)
  1705. << "\n";
  1706. }
  1707. cmakefileStream << " )\n";
  1708. }
  1709. // Target-specific include directories:
  1710. cmakefileStream << "\n"
  1711. << "# The include file search paths:\n";
  1712. cmakefileStream << "set(CMAKE_" << implicitLang.first
  1713. << "_TARGET_INCLUDE_PATH\n";
  1714. std::vector<std::string> includes;
  1715. this->GetIncludeDirectories(includes, target, implicitLang.first,
  1716. this->GetConfigName());
  1717. std::string binaryDir = this->GetState()->GetBinaryDirectory();
  1718. if (this->Makefile->IsOn("CMAKE_DEPENDS_IN_PROJECT_ONLY")) {
  1719. std::string const& sourceDir = this->GetState()->GetSourceDirectory();
  1720. cm::erase_if(includes, ::NotInProjectDir(sourceDir, binaryDir));
  1721. }
  1722. for (std::string const& include : includes) {
  1723. cmakefileStream << " \""
  1724. << this->MaybeConvertToRelativePath(binaryDir, include)
  1725. << "\"\n";
  1726. }
  1727. cmakefileStream << " )\n";
  1728. }
  1729. // Store include transform rule properties. Write the directory
  1730. // rules first because they may be overridden by later target rules.
  1731. std::vector<std::string> transformRules;
  1732. if (const char* xform =
  1733. this->Makefile->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
  1734. cmExpandList(xform, transformRules);
  1735. }
  1736. if (const char* xform =
  1737. target->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
  1738. cmExpandList(xform, transformRules);
  1739. }
  1740. if (!transformRules.empty()) {
  1741. cmakefileStream << "set(CMAKE_INCLUDE_TRANSFORMS\n";
  1742. for (std::string const& tr : transformRules) {
  1743. cmakefileStream << " " << cmOutputConverter::EscapeForCMake(tr) << "\n";
  1744. }
  1745. cmakefileStream << " )\n";
  1746. }
  1747. }
  1748. void cmLocalUnixMakefileGenerator3::WriteDisclaimer(std::ostream& os)
  1749. {
  1750. os << "# CMAKE generated file: DO NOT EDIT!\n"
  1751. << "# Generated by \"" << this->GlobalGenerator->GetName() << "\""
  1752. << " Generator, CMake Version " << cmVersion::GetMajorVersion() << "."
  1753. << cmVersion::GetMinorVersion() << "\n\n";
  1754. }
  1755. std::string cmLocalUnixMakefileGenerator3::GetRecursiveMakeCall(
  1756. const std::string& makefile, const std::string& tgt)
  1757. {
  1758. // Call make on the given file.
  1759. std::string cmd = cmStrCat(
  1760. "$(MAKE) -f ",
  1761. this->ConvertToOutputFormat(makefile, cmOutputConverter::SHELL), ' ');
  1762. cmGlobalUnixMakefileGenerator3* gg =
  1763. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1764. // Pass down verbosity level.
  1765. if (!gg->MakeSilentFlag.empty()) {
  1766. cmd += gg->MakeSilentFlag;
  1767. cmd += " ";
  1768. }
  1769. // Most unix makes will pass the command line flags to make down to
  1770. // sub-invoked makes via an environment variable. However, some
  1771. // makes do not support that, so you have to pass the flags
  1772. // explicitly.
  1773. if (gg->PassMakeflags) {
  1774. cmd += "-$(MAKEFLAGS) ";
  1775. }
  1776. // Add the target.
  1777. if (!tgt.empty()) {
  1778. // The make target is always relative to the top of the build tree.
  1779. std::string tgt2 =
  1780. this->MaybeConvertToRelativePath(this->GetBinaryDirectory(), tgt);
  1781. // The target may have been written with windows paths.
  1782. cmSystemTools::ConvertToOutputSlashes(tgt2);
  1783. // Escape one extra time if the make tool requires it.
  1784. if (this->MakeCommandEscapeTargetTwice) {
  1785. tgt2 = this->EscapeForShell(tgt2, true, false);
  1786. }
  1787. // The target name is now a string that should be passed verbatim
  1788. // on the command line.
  1789. cmd += this->EscapeForShell(tgt2, true, false);
  1790. }
  1791. return cmd;
  1792. }
  1793. void cmLocalUnixMakefileGenerator3::WriteDivider(std::ostream& os)
  1794. {
  1795. os << "#======================================"
  1796. << "=======================================\n";
  1797. }
  1798. void cmLocalUnixMakefileGenerator3::WriteCMakeArgument(std::ostream& os,
  1799. const char* s)
  1800. {
  1801. // Write the given string to the stream with escaping to get it back
  1802. // into CMake through the lexical scanner.
  1803. os << "\"";
  1804. for (const char* c = s; *c; ++c) {
  1805. if (*c == '\\') {
  1806. os << "\\\\";
  1807. } else if (*c == '"') {
  1808. os << "\\\"";
  1809. } else {
  1810. os << *c;
  1811. }
  1812. }
  1813. os << "\"";
  1814. }
  1815. std::string cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(
  1816. const std::string& p, bool useWatcomQuote)
  1817. {
  1818. // Split the path into its components.
  1819. std::vector<std::string> components;
  1820. cmSystemTools::SplitPath(p, components);
  1821. // Open the quoted result.
  1822. std::string result;
  1823. if (useWatcomQuote) {
  1824. #if defined(_WIN32) && !defined(__CYGWIN__)
  1825. result = "'";
  1826. #else
  1827. result = "\"'";
  1828. #endif
  1829. } else {
  1830. result = "\"";
  1831. }
  1832. // Return an empty path if there are no components.
  1833. if (!components.empty()) {
  1834. // Choose a slash direction and fix root component.
  1835. const char* slash = "/";
  1836. #if defined(_WIN32) && !defined(__CYGWIN__)
  1837. if (!cmSystemTools::GetForceUnixPaths()) {
  1838. slash = "\\";
  1839. for (char& i : components[0]) {
  1840. if (i == '/') {
  1841. i = '\\';
  1842. }
  1843. }
  1844. }
  1845. #endif
  1846. // Begin the quoted result with the root component.
  1847. result += components[0];
  1848. if (components.size() > 1) {
  1849. // Now add the rest of the components separated by the proper slash
  1850. // direction for this platform.
  1851. auto compEnd = std::remove(components.begin() + 1, components.end() - 1,
  1852. std::string());
  1853. auto compStart = components.begin() + 1;
  1854. result += cmJoin(cmMakeRange(compStart, compEnd), slash);
  1855. // Only the last component can be empty to avoid double slashes.
  1856. result += slash;
  1857. result += components.back();
  1858. }
  1859. }
  1860. // Close the quoted result.
  1861. if (useWatcomQuote) {
  1862. #if defined(_WIN32) && !defined(__CYGWIN__)
  1863. result += "'";
  1864. #else
  1865. result += "'\"";
  1866. #endif
  1867. } else {
  1868. result += "\"";
  1869. }
  1870. return result;
  1871. }
  1872. std::string cmLocalUnixMakefileGenerator3::GetTargetDirectory(
  1873. cmGeneratorTarget const* target) const
  1874. {
  1875. std::string dir = cmStrCat("CMakeFiles/", target->GetName());
  1876. #if defined(__VMS)
  1877. dir += "_dir";
  1878. #else
  1879. dir += ".dir";
  1880. #endif
  1881. return dir;
  1882. }
  1883. cmLocalUnixMakefileGenerator3::ImplicitDependLanguageMap const&
  1884. cmLocalUnixMakefileGenerator3::GetImplicitDepends(const cmGeneratorTarget* tgt)
  1885. {
  1886. return this->ImplicitDepends[tgt->GetName()];
  1887. }
  1888. void cmLocalUnixMakefileGenerator3::AddImplicitDepends(
  1889. const cmGeneratorTarget* tgt, const std::string& lang,
  1890. const std::string& obj, const std::string& src)
  1891. {
  1892. this->ImplicitDepends[tgt->GetName()][lang][obj].push_back(src);
  1893. }
  1894. void cmLocalUnixMakefileGenerator3::CreateCDCommand(
  1895. std::vector<std::string>& commands, std::string const& tgtDir,
  1896. std::string const& relDir)
  1897. {
  1898. // do we need to cd?
  1899. if (tgtDir == relDir) {
  1900. return;
  1901. }
  1902. // In a Windows shell we must change drive letter too. The shell
  1903. // used by NMake and Borland make does not support "cd /d" so this
  1904. // feature simply cannot work with them (Borland make does not even
  1905. // support changing the drive letter with just "d:").
  1906. const char* cd_cmd = this->IsMinGWMake() ? "cd /d " : "cd ";
  1907. cmGlobalUnixMakefileGenerator3* gg =
  1908. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1909. if (!gg->UnixCD) {
  1910. // On Windows we must perform each step separately and then change
  1911. // back because the shell keeps the working directory between
  1912. // commands.
  1913. std::string cmd =
  1914. cmStrCat(cd_cmd, this->ConvertToOutputForExisting(tgtDir));
  1915. commands.insert(commands.begin(), cmd);
  1916. // Change back to the starting directory.
  1917. cmd = cmStrCat(cd_cmd, this->ConvertToOutputForExisting(relDir));
  1918. commands.push_back(std::move(cmd));
  1919. } else {
  1920. // On UNIX we must construct a single shell command to change
  1921. // directory and build because make resets the directory between
  1922. // each command.
  1923. std::string outputForExisting = this->ConvertToOutputForExisting(tgtDir);
  1924. std::string prefix = cd_cmd + outputForExisting + " && ";
  1925. std::transform(commands.begin(), commands.end(), commands.begin(),
  1926. [&prefix](std::string const& s) { return prefix + s; });
  1927. }
  1928. }