cmLocalUnixMakefileGenerator3.cxx 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmLocalUnixMakefileGenerator3.h"
  4. #include "cmsys/FStream.hxx"
  5. #include "cmsys/Terminal.h"
  6. #include <algorithm>
  7. #include <sstream>
  8. #include <stdio.h>
  9. #include <utility>
  10. #include "cm_memory.hxx"
  11. #include "cmAlgorithms.h"
  12. #include "cmCustomCommand.h" // IWYU pragma: keep
  13. #include "cmCustomCommandGenerator.h"
  14. #include "cmFileTimeCache.h"
  15. #include "cmGeneratedFileStream.h"
  16. #include "cmGeneratorExpression.h"
  17. #include "cmGeneratorTarget.h"
  18. #include "cmGlobalGenerator.h"
  19. #include "cmGlobalUnixMakefileGenerator3.h"
  20. #include "cmListFileCache.h"
  21. #include "cmLocalGenerator.h"
  22. #include "cmMakefile.h"
  23. #include "cmMakefileTargetGenerator.h"
  24. #include "cmOutputConverter.h"
  25. #include "cmRange.h"
  26. #include "cmRulePlaceholderExpander.h"
  27. #include "cmSourceFile.h"
  28. #include "cmState.h"
  29. #include "cmStateDirectory.h"
  30. #include "cmStateSnapshot.h"
  31. #include "cmStateTypes.h"
  32. #include "cmStringAlgorithms.h"
  33. #include "cmSystemTools.h"
  34. #include "cmVersion.h"
  35. #include "cmake.h"
  36. // Include dependency scanners for supported languages. Only the
  37. // C/C++ scanner is needed for bootstrapping CMake.
  38. #include "cmDependsC.h"
  39. #ifndef CMAKE_BOOTSTRAP
  40. # include "cmDependsFortran.h"
  41. # include "cmDependsJava.h"
  42. #endif
  43. // Escape special characters in Makefile dependency lines
  44. class cmMakeSafe
  45. {
  46. public:
  47. cmMakeSafe(const char* s)
  48. : Data(s)
  49. {
  50. }
  51. cmMakeSafe(std::string const& s)
  52. : Data(s.c_str())
  53. {
  54. }
  55. private:
  56. const char* Data;
  57. friend std::ostream& operator<<(std::ostream& os, cmMakeSafe const& self)
  58. {
  59. for (const char* c = self.Data; *c; ++c) {
  60. switch (*c) {
  61. case '=':
  62. os << "$(EQUALS)";
  63. break;
  64. default:
  65. os << *c;
  66. break;
  67. }
  68. }
  69. return os;
  70. }
  71. };
  72. // Helper function used below.
  73. static std::string cmSplitExtension(std::string const& in, std::string& base)
  74. {
  75. std::string ext;
  76. std::string::size_type dot_pos = in.rfind('.');
  77. if (dot_pos != std::string::npos) {
  78. // Remove the extension first in case &base == &in.
  79. ext = in.substr(dot_pos);
  80. base = in.substr(0, dot_pos);
  81. } else {
  82. base = in;
  83. }
  84. return ext;
  85. }
  86. cmLocalUnixMakefileGenerator3::cmLocalUnixMakefileGenerator3(
  87. cmGlobalGenerator* gg, cmMakefile* mf)
  88. : cmLocalCommonGenerator(gg, mf, mf->GetCurrentBinaryDirectory())
  89. {
  90. this->MakefileVariableSize = 0;
  91. this->ColorMakefile = false;
  92. this->SkipPreprocessedSourceRules = false;
  93. this->SkipAssemblySourceRules = false;
  94. this->MakeCommandEscapeTargetTwice = false;
  95. this->BorlandMakeCurlyHack = false;
  96. }
  97. cmLocalUnixMakefileGenerator3::~cmLocalUnixMakefileGenerator3() = default;
  98. void cmLocalUnixMakefileGenerator3::Generate()
  99. {
  100. // Record whether some options are enabled to avoid checking many
  101. // times later.
  102. if (!this->GetGlobalGenerator()->GetCMakeInstance()->GetIsInTryCompile()) {
  103. this->ColorMakefile = this->Makefile->IsOn("CMAKE_COLOR_MAKEFILE");
  104. }
  105. this->SkipPreprocessedSourceRules =
  106. this->Makefile->IsOn("CMAKE_SKIP_PREPROCESSED_SOURCE_RULES");
  107. this->SkipAssemblySourceRules =
  108. this->Makefile->IsOn("CMAKE_SKIP_ASSEMBLY_SOURCE_RULES");
  109. // Generate the rule files for each target.
  110. cmGlobalUnixMakefileGenerator3* gg =
  111. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  112. for (cmGeneratorTarget* target : this->GetGeneratorTargets()) {
  113. if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  114. continue;
  115. }
  116. std::unique_ptr<cmMakefileTargetGenerator> tg(
  117. cmMakefileTargetGenerator::New(target));
  118. if (tg) {
  119. tg->WriteRuleFiles();
  120. gg->RecordTargetProgress(tg.get());
  121. }
  122. }
  123. // write the local Makefile
  124. this->WriteLocalMakefile();
  125. // Write the cmake file with information for this directory.
  126. this->WriteDirectoryInformationFile();
  127. }
  128. void cmLocalUnixMakefileGenerator3::ComputeHomeRelativeOutputPath()
  129. {
  130. // Compute the path to use when referencing the current output
  131. // directory from the top output directory.
  132. this->HomeRelativeOutputPath = this->MaybeConvertToRelativePath(
  133. this->GetBinaryDirectory(), this->GetCurrentBinaryDirectory());
  134. if (this->HomeRelativeOutputPath == ".") {
  135. this->HomeRelativeOutputPath.clear();
  136. }
  137. if (!this->HomeRelativeOutputPath.empty()) {
  138. this->HomeRelativeOutputPath += "/";
  139. }
  140. }
  141. void cmLocalUnixMakefileGenerator3::GetLocalObjectFiles(
  142. std::map<std::string, LocalObjectInfo>& localObjectFiles)
  143. {
  144. for (cmGeneratorTarget* gt : this->GetGeneratorTargets()) {
  145. if (gt->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  146. continue;
  147. }
  148. std::vector<cmSourceFile const*> objectSources;
  149. gt->GetObjectSources(
  150. objectSources, this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
  151. // Compute full path to object file directory for this target.
  152. std::string dir;
  153. dir += gt->LocalGenerator->GetCurrentBinaryDirectory();
  154. dir += "/";
  155. dir += this->GetTargetDirectory(gt);
  156. dir += "/";
  157. // Compute the name of each object file.
  158. for (cmSourceFile const* sf : objectSources) {
  159. bool hasSourceExtension = true;
  160. std::string objectName =
  161. this->GetObjectFileNameWithoutTarget(*sf, dir, &hasSourceExtension);
  162. if (cmSystemTools::FileIsFullPath(objectName)) {
  163. objectName = cmSystemTools::GetFilenameName(objectName);
  164. }
  165. LocalObjectInfo& info = localObjectFiles[objectName];
  166. info.HasSourceExtension = hasSourceExtension;
  167. info.emplace_back(gt, sf->GetLanguage());
  168. }
  169. }
  170. }
  171. void cmLocalUnixMakefileGenerator3::GetIndividualFileTargets(
  172. std::vector<std::string>& targets)
  173. {
  174. std::map<std::string, LocalObjectInfo> localObjectFiles;
  175. this->GetLocalObjectFiles(localObjectFiles);
  176. for (auto const& localObjectFile : localObjectFiles) {
  177. targets.push_back(localObjectFile.first);
  178. std::string::size_type dot_pos = localObjectFile.first.rfind(".");
  179. std::string base = localObjectFile.first.substr(0, dot_pos);
  180. if (localObjectFile.second.HasPreprocessRule) {
  181. targets.push_back(base + ".i");
  182. }
  183. if (localObjectFile.second.HasAssembleRule) {
  184. targets.push_back(base + ".s");
  185. }
  186. }
  187. }
  188. void cmLocalUnixMakefileGenerator3::WriteLocalMakefile()
  189. {
  190. // generate the includes
  191. std::string ruleFileName = "Makefile";
  192. // Open the rule file. This should be copy-if-different because the
  193. // rules may depend on this file itself.
  194. std::string ruleFileNameFull = this->ConvertToFullPath(ruleFileName);
  195. cmGeneratedFileStream ruleFileStream(
  196. ruleFileNameFull, false, this->GlobalGenerator->GetMakefileEncoding());
  197. if (!ruleFileStream) {
  198. return;
  199. }
  200. // always write the top makefile
  201. if (!this->IsRootMakefile()) {
  202. ruleFileStream.SetCopyIfDifferent(true);
  203. }
  204. // write the all rules
  205. this->WriteLocalAllRules(ruleFileStream);
  206. // only write local targets unless at the top Keep track of targets already
  207. // listed.
  208. std::set<std::string> emittedTargets;
  209. if (!this->IsRootMakefile()) {
  210. // write our targets, and while doing it collect up the object
  211. // file rules
  212. this->WriteLocalMakefileTargets(ruleFileStream, emittedTargets);
  213. } else {
  214. cmGlobalUnixMakefileGenerator3* gg =
  215. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  216. gg->WriteConvenienceRules(ruleFileStream, emittedTargets);
  217. }
  218. bool do_preprocess_rules = this->GetCreatePreprocessedSourceRules();
  219. bool do_assembly_rules = this->GetCreateAssemblySourceRules();
  220. std::map<std::string, LocalObjectInfo> localObjectFiles;
  221. this->GetLocalObjectFiles(localObjectFiles);
  222. // now write out the object rules
  223. // for each object file name
  224. for (auto& localObjectFile : localObjectFiles) {
  225. // Add a convenience rule for building the object file.
  226. this->WriteObjectConvenienceRule(
  227. ruleFileStream, "target to build an object file", localObjectFile.first,
  228. localObjectFile.second);
  229. // Check whether preprocessing and assembly rules make sense.
  230. // They make sense only for C and C++ sources.
  231. bool lang_has_preprocessor = false;
  232. bool lang_has_assembly = false;
  233. for (LocalObjectEntry const& entry : localObjectFile.second) {
  234. if (entry.Language == "C" || entry.Language == "CXX" ||
  235. entry.Language == "CUDA" || entry.Language == "Fortran") {
  236. // Right now, C, C++, Fortran and CUDA have both a preprocessor and the
  237. // ability to generate assembly code
  238. lang_has_preprocessor = true;
  239. lang_has_assembly = true;
  240. break;
  241. }
  242. }
  243. // Add convenience rules for preprocessed and assembly files.
  244. if (lang_has_preprocessor && do_preprocess_rules) {
  245. std::string::size_type dot_pos = localObjectFile.first.rfind(".");
  246. std::string base = localObjectFile.first.substr(0, dot_pos);
  247. this->WriteObjectConvenienceRule(ruleFileStream,
  248. "target to preprocess a source file",
  249. (base + ".i"), localObjectFile.second);
  250. localObjectFile.second.HasPreprocessRule = true;
  251. }
  252. if (lang_has_assembly && do_assembly_rules) {
  253. std::string::size_type dot_pos = localObjectFile.first.rfind(".");
  254. std::string base = localObjectFile.first.substr(0, dot_pos);
  255. this->WriteObjectConvenienceRule(
  256. ruleFileStream, "target to generate assembly for a file",
  257. (base + ".s"), localObjectFile.second);
  258. localObjectFile.second.HasAssembleRule = true;
  259. }
  260. }
  261. // add a help target as long as there isn;t a real target named help
  262. if (emittedTargets.insert("help").second) {
  263. cmGlobalUnixMakefileGenerator3* gg =
  264. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  265. gg->WriteHelpRule(ruleFileStream, this);
  266. }
  267. this->WriteSpecialTargetsBottom(ruleFileStream);
  268. }
  269. void cmLocalUnixMakefileGenerator3::WriteObjectConvenienceRule(
  270. std::ostream& ruleFileStream, const char* comment, const std::string& output,
  271. LocalObjectInfo const& info)
  272. {
  273. // If the rule includes the source file extension then create a
  274. // version that has the extension removed. The help should include
  275. // only the version without source extension.
  276. bool inHelp = true;
  277. if (info.HasSourceExtension) {
  278. // Remove the last extension. This should be kept.
  279. std::string outBase1 = output;
  280. std::string outExt1 = cmSplitExtension(outBase1, outBase1);
  281. // Now remove the source extension and put back the last
  282. // extension.
  283. std::string outNoExt;
  284. cmSplitExtension(outBase1, outNoExt);
  285. outNoExt += outExt1;
  286. // Add a rule to drive the rule below.
  287. std::vector<std::string> depends;
  288. depends.emplace_back(output);
  289. std::vector<std::string> no_commands;
  290. this->WriteMakeRule(ruleFileStream, nullptr, outNoExt, depends,
  291. no_commands, true, true);
  292. inHelp = false;
  293. }
  294. // Recursively make the rule for each target using the object file.
  295. std::vector<std::string> commands;
  296. for (LocalObjectEntry const& t : info) {
  297. std::string tgtMakefileName = this->GetRelativeTargetDirectory(t.Target);
  298. std::string targetName = tgtMakefileName;
  299. tgtMakefileName += "/build.make";
  300. targetName += "/";
  301. targetName += output;
  302. commands.push_back(
  303. this->GetRecursiveMakeCall(tgtMakefileName, targetName));
  304. }
  305. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  306. this->GetCurrentBinaryDirectory());
  307. // Write the rule to the makefile.
  308. std::vector<std::string> no_depends;
  309. this->WriteMakeRule(ruleFileStream, comment, output, no_depends, commands,
  310. true, inHelp);
  311. }
  312. void cmLocalUnixMakefileGenerator3::WriteLocalMakefileTargets(
  313. std::ostream& ruleFileStream, std::set<std::string>& emitted)
  314. {
  315. std::vector<std::string> depends;
  316. std::vector<std::string> commands;
  317. // for each target we just provide a rule to cd up to the top and do a make
  318. // on the target
  319. std::string localName;
  320. for (cmGeneratorTarget* target : this->GetGeneratorTargets()) {
  321. if ((target->GetType() == cmStateEnums::EXECUTABLE) ||
  322. (target->GetType() == cmStateEnums::STATIC_LIBRARY) ||
  323. (target->GetType() == cmStateEnums::SHARED_LIBRARY) ||
  324. (target->GetType() == cmStateEnums::MODULE_LIBRARY) ||
  325. (target->GetType() == cmStateEnums::OBJECT_LIBRARY) ||
  326. (target->GetType() == cmStateEnums::UTILITY)) {
  327. emitted.insert(target->GetName());
  328. // for subdirs add a rule to build this specific target by name.
  329. localName = this->GetRelativeTargetDirectory(target);
  330. localName += "/rule";
  331. commands.clear();
  332. depends.clear();
  333. // Build the target for this pass.
  334. std::string makefile2 = "CMakeFiles/";
  335. makefile2 += "Makefile2";
  336. commands.push_back(this->GetRecursiveMakeCall(makefile2, localName));
  337. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  338. this->GetCurrentBinaryDirectory());
  339. this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
  340. localName, depends, commands, true);
  341. // Add a target with the canonical name (no prefix, suffix or path).
  342. if (localName != target->GetName()) {
  343. commands.clear();
  344. depends.push_back(localName);
  345. this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
  346. target->GetName(), depends, commands, true);
  347. }
  348. // Add a fast rule to build the target
  349. std::string makefileName = this->GetRelativeTargetDirectory(target);
  350. makefileName += "/build.make";
  351. // make sure the makefile name is suitable for a makefile
  352. std::string makeTargetName = this->GetRelativeTargetDirectory(target);
  353. makeTargetName += "/build";
  354. localName = target->GetName();
  355. localName += "/fast";
  356. depends.clear();
  357. commands.clear();
  358. commands.push_back(
  359. this->GetRecursiveMakeCall(makefileName, makeTargetName));
  360. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  361. this->GetCurrentBinaryDirectory());
  362. this->WriteMakeRule(ruleFileStream, "fast build rule for target.",
  363. localName, depends, commands, true);
  364. // Add a local name for the rule to relink the target before
  365. // installation.
  366. if (target->NeedRelinkBeforeInstall(this->ConfigName)) {
  367. makeTargetName = this->GetRelativeTargetDirectory(target);
  368. makeTargetName += "/preinstall";
  369. localName = target->GetName();
  370. localName += "/preinstall";
  371. depends.clear();
  372. commands.clear();
  373. commands.push_back(
  374. this->GetRecursiveMakeCall(makefile2, makeTargetName));
  375. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  376. this->GetCurrentBinaryDirectory());
  377. this->WriteMakeRule(ruleFileStream,
  378. "Manual pre-install relink rule for target.",
  379. localName, depends, commands, true);
  380. }
  381. }
  382. }
  383. }
  384. void cmLocalUnixMakefileGenerator3::WriteDirectoryInformationFile()
  385. {
  386. std::string infoFileName = this->GetCurrentBinaryDirectory();
  387. infoFileName += "/CMakeFiles";
  388. infoFileName += "/CMakeDirectoryInformation.cmake";
  389. // Open the output file.
  390. cmGeneratedFileStream infoFileStream(infoFileName);
  391. if (!infoFileStream) {
  392. return;
  393. }
  394. infoFileStream.SetCopyIfDifferent(true);
  395. // Write the do not edit header.
  396. this->WriteDisclaimer(infoFileStream);
  397. // Setup relative path conversion tops.
  398. /* clang-format off */
  399. infoFileStream
  400. << "# Relative path conversion top directories.\n"
  401. << "set(CMAKE_RELATIVE_PATH_TOP_SOURCE \""
  402. << this->StateSnapshot.GetDirectory().GetRelativePathTopSource()
  403. << "\")\n"
  404. << "set(CMAKE_RELATIVE_PATH_TOP_BINARY \""
  405. << this->StateSnapshot.GetDirectory().GetRelativePathTopBinary()
  406. << "\")\n"
  407. << "\n";
  408. /* clang-format on */
  409. // Tell the dependency scanner to use unix paths if necessary.
  410. if (cmSystemTools::GetForceUnixPaths()) {
  411. /* clang-format off */
  412. infoFileStream
  413. << "# Force unix paths in dependencies.\n"
  414. << "set(CMAKE_FORCE_UNIX_PATHS 1)\n"
  415. << "\n";
  416. /* clang-format on */
  417. }
  418. // Store the include regular expressions for this directory.
  419. infoFileStream << "\n"
  420. << "# The C and CXX include file regular expressions for "
  421. << "this directory.\n";
  422. infoFileStream << "set(CMAKE_C_INCLUDE_REGEX_SCAN ";
  423. cmLocalUnixMakefileGenerator3::WriteCMakeArgument(
  424. infoFileStream, this->Makefile->GetIncludeRegularExpression());
  425. infoFileStream << ")\n";
  426. infoFileStream << "set(CMAKE_C_INCLUDE_REGEX_COMPLAIN ";
  427. cmLocalUnixMakefileGenerator3::WriteCMakeArgument(
  428. infoFileStream, this->Makefile->GetComplainRegularExpression());
  429. infoFileStream << ")\n";
  430. infoFileStream
  431. << "set(CMAKE_CXX_INCLUDE_REGEX_SCAN ${CMAKE_C_INCLUDE_REGEX_SCAN})\n";
  432. infoFileStream << "set(CMAKE_CXX_INCLUDE_REGEX_COMPLAIN "
  433. "${CMAKE_C_INCLUDE_REGEX_COMPLAIN})\n";
  434. }
  435. std::string cmLocalUnixMakefileGenerator3::ConvertToFullPath(
  436. const std::string& localPath)
  437. {
  438. std::string dir = this->GetCurrentBinaryDirectory();
  439. dir += "/";
  440. dir += localPath;
  441. return dir;
  442. }
  443. const std::string& cmLocalUnixMakefileGenerator3::GetHomeRelativeOutputPath()
  444. {
  445. return this->HomeRelativeOutputPath;
  446. }
  447. void cmLocalUnixMakefileGenerator3::WriteMakeRule(
  448. std::ostream& os, const char* comment, const std::string& target,
  449. const std::vector<std::string>& depends,
  450. const std::vector<std::string>& commands, bool symbolic, bool in_help)
  451. {
  452. // Make sure there is a target.
  453. if (target.empty()) {
  454. 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 remove -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 = "$(CMAKE_COMMAND) -P ";
  700. rescanRule += this->ConvertToOutputFormat(cm->GetGlobVerifyScript(),
  701. cmOutputConverter::SHELL);
  702. commands.push_back(rescanRule);
  703. }
  704. std::string cmakefileName = "CMakeFiles/";
  705. cmakefileName += "Makefile.cmake";
  706. std::string runRule =
  707. "$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)";
  708. runRule += " --check-build-system ";
  709. runRule +=
  710. this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL);
  711. runRule += " 0";
  712. std::vector<std::string> no_depends;
  713. commands.push_back(std::move(runRule));
  714. if (!this->IsRootMakefile()) {
  715. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  716. this->GetCurrentBinaryDirectory());
  717. }
  718. this->WriteMakeRule(makefileStream,
  719. "Special rule to run CMake to check the build system "
  720. "integrity.\n"
  721. "No rule that depends on this can have "
  722. "commands that come from listfiles\n"
  723. "because they might be regenerated.",
  724. "cmake_check_build_system", no_depends, commands,
  725. true);
  726. }
  727. }
  728. void cmLocalUnixMakefileGenerator3::WriteConvenienceRule(
  729. std::ostream& ruleFileStream, const std::string& realTarget,
  730. const std::string& helpTarget)
  731. {
  732. // A rule is only needed if the names are different.
  733. if (realTarget != helpTarget) {
  734. // The helper target depends on the real target.
  735. std::vector<std::string> depends;
  736. depends.push_back(realTarget);
  737. // There are no commands.
  738. std::vector<std::string> no_commands;
  739. // Write the rule.
  740. this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
  741. helpTarget, depends, no_commands, true);
  742. }
  743. }
  744. std::string cmLocalUnixMakefileGenerator3::GetRelativeTargetDirectory(
  745. cmGeneratorTarget* target)
  746. {
  747. std::string dir = this->HomeRelativeOutputPath;
  748. dir += this->GetTargetDirectory(target);
  749. return dir;
  750. }
  751. void cmLocalUnixMakefileGenerator3::AppendFlags(
  752. std::string& flags, const std::string& newFlags) const
  753. {
  754. if (this->IsWatcomWMake() && !newFlags.empty()) {
  755. std::string newf = newFlags;
  756. if (newf.find("\\\"") != std::string::npos) {
  757. cmSystemTools::ReplaceString(newf, "\\\"", "\"");
  758. this->cmLocalGenerator::AppendFlags(flags, newf);
  759. return;
  760. }
  761. }
  762. this->cmLocalGenerator::AppendFlags(flags, newFlags);
  763. }
  764. void cmLocalUnixMakefileGenerator3::AppendFlags(std::string& flags,
  765. const char* newFlags) const
  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. cmAppend(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->ConfigName, 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->ConfigName, 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->ConfigName, 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. cmAppend(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 = currentBinDir;
  952. cleanfile += "/";
  953. cleanfile += this->GetTargetDirectory(target);
  954. cleanfile += "/cmake_clean";
  955. if (filename) {
  956. cleanfile += "_";
  957. cleanfile += filename;
  958. }
  959. cleanfile += ".cmake";
  960. std::string cleanfilePath = cmSystemTools::CollapseFullPath(cleanfile);
  961. cmsys::ofstream fout(cleanfilePath.c_str());
  962. if (!fout) {
  963. cmSystemTools::Error("Could not create " + cleanfilePath);
  964. }
  965. if (!files.empty()) {
  966. fout << "file(REMOVE_RECURSE\n";
  967. for (std::string const& file : files) {
  968. std::string fc = this->MaybeConvertToRelativePath(currentBinDir, file);
  969. fout << " " << cmOutputConverter::EscapeForCMake(fc) << "\n";
  970. }
  971. fout << ")\n";
  972. }
  973. {
  974. std::string remove = "$(CMAKE_COMMAND) -P ";
  975. remove += this->ConvertToOutputFormat(
  976. this->MaybeConvertToRelativePath(this->GetCurrentBinaryDirectory(),
  977. cleanfile),
  978. cmOutputConverter::SHELL);
  979. commands.push_back(std::move(remove));
  980. }
  981. // For the main clean rule add per-language cleaning.
  982. if (!filename) {
  983. // Get the set of source languages in the target.
  984. std::set<std::string> languages;
  985. target->GetLanguages(
  986. languages, this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
  987. /* clang-format off */
  988. fout << "\n"
  989. << "# Per-language clean rules from dependency scanning.\n"
  990. << "foreach(lang " << cmJoin(languages, " ") << ")\n"
  991. << " include(" << this->GetTargetDirectory(target)
  992. << "/cmake_clean_${lang}.cmake OPTIONAL)\n"
  993. << "endforeach()\n";
  994. /* clang-format on */
  995. }
  996. }
  997. void cmLocalUnixMakefileGenerator3::AppendDirectoryCleanCommand(
  998. std::vector<std::string>& commands)
  999. {
  1000. std::vector<std::string> cleanFiles;
  1001. // Look for additional files registered for cleaning in this directory.
  1002. if (const char* prop_value =
  1003. this->Makefile->GetProperty("ADDITIONAL_CLEAN_FILES")) {
  1004. cmGeneratorExpression ge;
  1005. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(prop_value);
  1006. cmExpandList(
  1007. cge->Evaluate(this,
  1008. this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE")),
  1009. cleanFiles);
  1010. }
  1011. if (cleanFiles.empty()) {
  1012. return;
  1013. }
  1014. cmLocalGenerator* rootLG =
  1015. this->GetGlobalGenerator()->GetLocalGenerators().at(0);
  1016. std::string const& binaryDir = rootLG->GetCurrentBinaryDirectory();
  1017. std::string const& currentBinaryDir = this->GetCurrentBinaryDirectory();
  1018. std::string cleanfile = currentBinaryDir;
  1019. cleanfile += "/CMakeFiles/cmake_directory_clean.cmake";
  1020. // Write clean script
  1021. {
  1022. std::string cleanfilePath = cmSystemTools::CollapseFullPath(cleanfile);
  1023. cmsys::ofstream fout(cleanfilePath.c_str());
  1024. if (!fout) {
  1025. cmSystemTools::Error("Could not create " + cleanfilePath);
  1026. return;
  1027. }
  1028. fout << "file(REMOVE_RECURSE\n";
  1029. for (std::string const& cfl : cleanFiles) {
  1030. std::string fc = rootLG->MaybeConvertToRelativePath(
  1031. binaryDir, cmSystemTools::CollapseFullPath(cfl, currentBinaryDir));
  1032. fout << " " << cmOutputConverter::EscapeForCMake(fc) << "\n";
  1033. }
  1034. fout << ")\n";
  1035. }
  1036. // Create command
  1037. {
  1038. std::string remove = "$(CMAKE_COMMAND) -P ";
  1039. remove += this->ConvertToOutputFormat(
  1040. rootLG->MaybeConvertToRelativePath(binaryDir, cleanfile),
  1041. cmOutputConverter::SHELL);
  1042. commands.push_back(std::move(remove));
  1043. }
  1044. }
  1045. void cmLocalUnixMakefileGenerator3::AppendEcho(
  1046. std::vector<std::string>& commands, std::string const& text, EchoColor color,
  1047. EchoProgress const* progress)
  1048. {
  1049. // Choose the color for the text.
  1050. std::string color_name;
  1051. if (this->GlobalGenerator->GetToolSupportsColor() && this->ColorMakefile) {
  1052. // See cmake::ExecuteEchoColor in cmake.cxx for these options.
  1053. // This color set is readable on both black and white backgrounds.
  1054. switch (color) {
  1055. case EchoNormal:
  1056. break;
  1057. case EchoDepend:
  1058. color_name = "--magenta --bold ";
  1059. break;
  1060. case EchoBuild:
  1061. color_name = "--green ";
  1062. break;
  1063. case EchoLink:
  1064. color_name = "--green --bold ";
  1065. break;
  1066. case EchoGenerate:
  1067. color_name = "--blue --bold ";
  1068. break;
  1069. case EchoGlobal:
  1070. color_name = "--cyan ";
  1071. break;
  1072. }
  1073. }
  1074. // Echo one line at a time.
  1075. std::string line;
  1076. line.reserve(200);
  1077. for (const char* c = text.c_str();; ++c) {
  1078. if (*c == '\n' || *c == '\0') {
  1079. // Avoid writing a blank last line on end-of-string.
  1080. if (*c != '\0' || !line.empty()) {
  1081. // Add a command to echo this line.
  1082. std::string cmd;
  1083. if (color_name.empty() && !progress) {
  1084. // Use the native echo command.
  1085. cmd = "@echo ";
  1086. cmd += this->EscapeForShell(line, false, true);
  1087. } else {
  1088. // Use cmake to echo the text in color.
  1089. cmd = "@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) ";
  1090. cmd += color_name;
  1091. if (progress) {
  1092. cmd += "--progress-dir=";
  1093. cmd += this->ConvertToOutputFormat(
  1094. cmSystemTools::CollapseFullPath(progress->Dir),
  1095. cmOutputConverter::SHELL);
  1096. cmd += " ";
  1097. cmd += "--progress-num=";
  1098. cmd += progress->Arg;
  1099. cmd += " ";
  1100. }
  1101. cmd += this->EscapeForShell(line);
  1102. }
  1103. commands.push_back(std::move(cmd));
  1104. }
  1105. // Reset the line to empty.
  1106. line.clear();
  1107. // Progress appears only on first line.
  1108. progress = nullptr;
  1109. // Terminate on end-of-string.
  1110. if (*c == '\0') {
  1111. return;
  1112. }
  1113. } else if (*c != '\r') {
  1114. // Append this character to the current line.
  1115. line += *c;
  1116. }
  1117. }
  1118. }
  1119. std::string cmLocalUnixMakefileGenerator3::CreateMakeVariable(
  1120. std::string const& s, std::string const& s2)
  1121. {
  1122. std::string unmodified = s;
  1123. unmodified += s2;
  1124. // if there is no restriction on the length of make variables
  1125. // and there are no "." characters in the string, then return the
  1126. // unmodified combination.
  1127. if ((!this->MakefileVariableSize &&
  1128. unmodified.find('.') == std::string::npos) &&
  1129. (!this->MakefileVariableSize &&
  1130. unmodified.find('+') == std::string::npos) &&
  1131. (!this->MakefileVariableSize &&
  1132. unmodified.find('-') == std::string::npos)) {
  1133. return unmodified;
  1134. }
  1135. // see if the variable has been defined before and return
  1136. // the modified version of the variable
  1137. std::map<std::string, std::string>::iterator i =
  1138. this->MakeVariableMap.find(unmodified);
  1139. if (i != this->MakeVariableMap.end()) {
  1140. return i->second;
  1141. }
  1142. // start with the unmodified variable
  1143. std::string ret = unmodified;
  1144. // if this there is no value for this->MakefileVariableSize then
  1145. // the string must have bad characters in it
  1146. if (!this->MakefileVariableSize) {
  1147. std::replace(ret.begin(), ret.end(), '.', '_');
  1148. cmSystemTools::ReplaceString(ret, "-", "__");
  1149. cmSystemTools::ReplaceString(ret, "+", "___");
  1150. int ni = 0;
  1151. char buffer[5];
  1152. // make sure the _ version is not already used, if
  1153. // it is used then add number to the end of the variable
  1154. while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
  1155. ++ni;
  1156. sprintf(buffer, "%04d", ni);
  1157. ret = unmodified + buffer;
  1158. }
  1159. this->ShortMakeVariableMap[ret] = "1";
  1160. this->MakeVariableMap[unmodified] = ret;
  1161. return ret;
  1162. }
  1163. // if the string is greater than 32 chars it is an invalid variable name
  1164. // for borland make
  1165. if (static_cast<int>(ret.size()) > this->MakefileVariableSize) {
  1166. int keep = this->MakefileVariableSize - 8;
  1167. int size = keep + 3;
  1168. std::string str1 = s;
  1169. std::string str2 = s2;
  1170. // we must shorten the combined string by 4 characters
  1171. // keep no more than 24 characters from the second string
  1172. if (static_cast<int>(str2.size()) > keep) {
  1173. str2 = str2.substr(0, keep);
  1174. }
  1175. if (static_cast<int>(str1.size()) + static_cast<int>(str2.size()) > size) {
  1176. str1 = str1.substr(0, size - str2.size());
  1177. }
  1178. char buffer[5];
  1179. int ni = 0;
  1180. sprintf(buffer, "%04d", ni);
  1181. ret = str1 + str2 + buffer;
  1182. while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
  1183. ++ni;
  1184. sprintf(buffer, "%04d", ni);
  1185. ret = str1 + str2 + buffer;
  1186. }
  1187. if (ni == 1000) {
  1188. cmSystemTools::Error("Borland makefile variable length too long");
  1189. return unmodified;
  1190. }
  1191. // once an unused variable is found
  1192. this->ShortMakeVariableMap[ret] = "1";
  1193. }
  1194. // always make an entry into the unmodified to variable map
  1195. this->MakeVariableMap[unmodified] = ret;
  1196. return ret;
  1197. }
  1198. bool cmLocalUnixMakefileGenerator3::UpdateDependencies(
  1199. const std::string& tgtInfo, bool verbose, bool color)
  1200. {
  1201. // read in the target info file
  1202. if (!this->Makefile->ReadListFile(tgtInfo) ||
  1203. cmSystemTools::GetErrorOccuredFlag()) {
  1204. cmSystemTools::Error("Target DependInfo.cmake file not found");
  1205. }
  1206. // Check if any multiple output pairs have a missing file.
  1207. this->CheckMultipleOutputs(verbose);
  1208. std::string const targetDir = cmSystemTools::GetFilenamePath(tgtInfo);
  1209. std::string const internalDependFile = targetDir + "/depend.internal";
  1210. std::string const dependFile = targetDir + "/depend.make";
  1211. // If the target DependInfo.cmake file has changed since the last
  1212. // time dependencies were scanned then force rescanning. This may
  1213. // happen when a new source file is added and CMake regenerates the
  1214. // project but no other sources were touched.
  1215. bool needRescanDependInfo = false;
  1216. cmFileTimeCache* ftc =
  1217. this->GlobalGenerator->GetCMakeInstance()->GetFileTimeCache();
  1218. {
  1219. int result;
  1220. if (!ftc->Compare(internalDependFile, tgtInfo, &result) || result < 0) {
  1221. if (verbose) {
  1222. std::ostringstream msg;
  1223. msg << "Dependee \"" << tgtInfo << "\" is newer than depender \""
  1224. << internalDependFile << "\"." << std::endl;
  1225. cmSystemTools::Stdout(msg.str());
  1226. }
  1227. needRescanDependInfo = true;
  1228. }
  1229. }
  1230. // If the directory information is newer than depend.internal, include dirs
  1231. // may have changed. In this case discard all old dependencies.
  1232. bool needRescanDirInfo = false;
  1233. {
  1234. std::string dirInfoFile = this->GetCurrentBinaryDirectory();
  1235. dirInfoFile += "/CMakeFiles";
  1236. dirInfoFile += "/CMakeDirectoryInformation.cmake";
  1237. int result;
  1238. if (!ftc->Compare(internalDependFile, dirInfoFile, &result) ||
  1239. result < 0) {
  1240. if (verbose) {
  1241. std::ostringstream msg;
  1242. msg << "Dependee \"" << dirInfoFile << "\" is newer than depender \""
  1243. << internalDependFile << "\"." << std::endl;
  1244. cmSystemTools::Stdout(msg.str());
  1245. }
  1246. needRescanDirInfo = true;
  1247. }
  1248. }
  1249. // Check the implicit dependencies to see if they are up to date.
  1250. // The build.make file may have explicit dependencies for the object
  1251. // files but these will not affect the scanning process so they need
  1252. // not be considered.
  1253. cmDepends::DependencyMap validDependencies;
  1254. bool needRescanDependencies = false;
  1255. if (!needRescanDirInfo) {
  1256. cmDependsC checker;
  1257. checker.SetVerbose(verbose);
  1258. checker.SetFileTimeCache(ftc);
  1259. // cmDependsC::Check() fills the vector validDependencies() with the
  1260. // dependencies for those files where they are still valid, i.e. neither
  1261. // the files themselves nor any files they depend on have changed.
  1262. // We don't do that if the CMakeDirectoryInformation.cmake file has
  1263. // changed, because then potentially all dependencies have changed.
  1264. // This information is given later on to cmDependsC, which then only
  1265. // rescans the files where it did not get valid dependencies via this
  1266. // dependency vector. This means that in the normal case, when only
  1267. // few or one file have been edited, then also only this one file is
  1268. // actually scanned again, instead of all files for this target.
  1269. needRescanDependencies =
  1270. !checker.Check(dependFile, internalDependFile, validDependencies);
  1271. }
  1272. if (needRescanDependInfo || needRescanDirInfo || needRescanDependencies) {
  1273. // The dependencies must be regenerated.
  1274. std::string targetName = cmSystemTools::GetFilenameName(targetDir);
  1275. targetName = targetName.substr(0, targetName.length() - 4);
  1276. std::string message = "Scanning dependencies of target ";
  1277. message += targetName;
  1278. cmSystemTools::MakefileColorEcho(cmsysTerminal_Color_ForegroundMagenta |
  1279. cmsysTerminal_Color_ForegroundBold,
  1280. message.c_str(), true, color);
  1281. return this->ScanDependencies(targetDir, dependFile, internalDependFile,
  1282. validDependencies);
  1283. }
  1284. // The dependencies are already up-to-date.
  1285. return true;
  1286. }
  1287. bool cmLocalUnixMakefileGenerator3::ScanDependencies(
  1288. std::string const& targetDir, std::string const& dependFile,
  1289. std::string const& internalDependFile, cmDepends::DependencyMap& validDeps)
  1290. {
  1291. // Read the directory information file.
  1292. cmMakefile* mf = this->Makefile;
  1293. bool haveDirectoryInfo = false;
  1294. {
  1295. std::string dirInfoFile = this->GetCurrentBinaryDirectory();
  1296. dirInfoFile += "/CMakeFiles";
  1297. dirInfoFile += "/CMakeDirectoryInformation.cmake";
  1298. if (mf->ReadListFile(dirInfoFile) &&
  1299. !cmSystemTools::GetErrorOccuredFlag()) {
  1300. haveDirectoryInfo = true;
  1301. }
  1302. }
  1303. // Lookup useful directory information.
  1304. if (haveDirectoryInfo) {
  1305. // Test whether we need to force Unix paths.
  1306. if (const char* force = mf->GetDefinition("CMAKE_FORCE_UNIX_PATHS")) {
  1307. if (!cmIsOff(force)) {
  1308. cmSystemTools::SetForceUnixPaths(true);
  1309. }
  1310. }
  1311. // Setup relative path top directories.
  1312. if (const char* relativePathTopSource =
  1313. mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_SOURCE")) {
  1314. this->StateSnapshot.GetDirectory().SetRelativePathTopSource(
  1315. relativePathTopSource);
  1316. }
  1317. if (const char* relativePathTopBinary =
  1318. mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_BINARY")) {
  1319. this->StateSnapshot.GetDirectory().SetRelativePathTopBinary(
  1320. relativePathTopBinary);
  1321. }
  1322. } else {
  1323. cmSystemTools::Error("Directory Information file not found");
  1324. }
  1325. // Open the make depends file. This should be copy-if-different
  1326. // because the make tool may try to reload it needlessly otherwise.
  1327. cmGeneratedFileStream ruleFileStream(
  1328. dependFile, false, this->GlobalGenerator->GetMakefileEncoding());
  1329. ruleFileStream.SetCopyIfDifferent(true);
  1330. if (!ruleFileStream) {
  1331. return false;
  1332. }
  1333. // Open the cmake dependency tracking file. This should not be
  1334. // copy-if-different because dependencies are re-scanned when it is
  1335. // older than the DependInfo.cmake.
  1336. cmGeneratedFileStream internalRuleFileStream(
  1337. internalDependFile, false, this->GlobalGenerator->GetMakefileEncoding());
  1338. if (!internalRuleFileStream) {
  1339. return false;
  1340. }
  1341. this->WriteDisclaimer(ruleFileStream);
  1342. this->WriteDisclaimer(internalRuleFileStream);
  1343. // for each language we need to scan, scan it
  1344. std::vector<std::string> langs;
  1345. cmExpandList(mf->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES"), langs);
  1346. for (std::string const& lang : langs) {
  1347. // construct the checker
  1348. // Create the scanner for this language
  1349. std::unique_ptr<cmDepends> scanner;
  1350. if (lang == "C" || lang == "CXX" || lang == "RC" || lang == "ASM" ||
  1351. lang == "CUDA") {
  1352. // TODO: Handle RC (resource files) dependencies correctly.
  1353. scanner = cm::make_unique<cmDependsC>(this, targetDir, lang, &validDeps);
  1354. }
  1355. #ifndef CMAKE_BOOTSTRAP
  1356. else if (lang == "Fortran") {
  1357. ruleFileStream << "# Note that incremental build could trigger "
  1358. << "a call to cmake_copy_f90_mod on each re-build\n";
  1359. scanner = cm::make_unique<cmDependsFortran>(this);
  1360. } else if (lang == "Java") {
  1361. scanner = cm::make_unique<cmDependsJava>();
  1362. }
  1363. #endif
  1364. if (scanner) {
  1365. scanner->SetLocalGenerator(this);
  1366. scanner->SetFileTimeCache(
  1367. this->GlobalGenerator->GetCMakeInstance()->GetFileTimeCache());
  1368. scanner->SetLanguage(lang);
  1369. scanner->SetTargetDirectory(targetDir);
  1370. scanner->Write(ruleFileStream, internalRuleFileStream);
  1371. }
  1372. }
  1373. return true;
  1374. }
  1375. void cmLocalUnixMakefileGenerator3::CheckMultipleOutputs(bool verbose)
  1376. {
  1377. cmMakefile* mf = this->Makefile;
  1378. // Get the string listing the multiple output pairs.
  1379. const char* pairs_string = mf->GetDefinition("CMAKE_MULTIPLE_OUTPUT_PAIRS");
  1380. if (!pairs_string) {
  1381. return;
  1382. }
  1383. // Convert the string to a list and preserve empty entries.
  1384. std::vector<std::string> pairs;
  1385. cmExpandList(pairs_string, pairs, true);
  1386. for (std::vector<std::string>::const_iterator i = pairs.begin();
  1387. i != pairs.end() && (i + 1) != pairs.end();) {
  1388. const std::string& depender = *i++;
  1389. const std::string& dependee = *i++;
  1390. // If the depender is missing then delete the dependee to make
  1391. // sure both will be regenerated.
  1392. if (cmSystemTools::FileExists(dependee) &&
  1393. !cmSystemTools::FileExists(depender)) {
  1394. if (verbose) {
  1395. std::ostringstream msg;
  1396. msg << "Deleting primary custom command output \"" << dependee
  1397. << "\" because another output \"" << depender
  1398. << "\" does not exist." << std::endl;
  1399. cmSystemTools::Stdout(msg.str());
  1400. }
  1401. cmSystemTools::RemoveFile(dependee);
  1402. }
  1403. }
  1404. }
  1405. void cmLocalUnixMakefileGenerator3::WriteLocalAllRules(
  1406. std::ostream& ruleFileStream)
  1407. {
  1408. this->WriteDisclaimer(ruleFileStream);
  1409. // Write the main entry point target. This must be the VERY first
  1410. // target so that make with no arguments will run it.
  1411. {
  1412. // Just depend on the all target to drive the build.
  1413. std::vector<std::string> depends;
  1414. std::vector<std::string> no_commands;
  1415. depends.emplace_back("all");
  1416. // Write the rule.
  1417. this->WriteMakeRule(ruleFileStream,
  1418. "Default target executed when no arguments are "
  1419. "given to make.",
  1420. "default_target", depends, no_commands, true);
  1421. // Help out users that try "gmake target1 target2 -j".
  1422. cmGlobalUnixMakefileGenerator3* gg =
  1423. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1424. if (gg->AllowNotParallel()) {
  1425. std::vector<std::string> no_depends;
  1426. this->WriteMakeRule(ruleFileStream,
  1427. "Allow only one \"make -f "
  1428. "Makefile2\" at a time, but pass "
  1429. "parallelism.",
  1430. ".NOTPARALLEL", no_depends, no_commands, false);
  1431. }
  1432. }
  1433. this->WriteSpecialTargetsTop(ruleFileStream);
  1434. // Include the progress variables for the target.
  1435. // Write all global targets
  1436. this->WriteDivider(ruleFileStream);
  1437. ruleFileStream << "# Targets provided globally by CMake.\n"
  1438. << "\n";
  1439. const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
  1440. for (cmGeneratorTarget* gt : targets) {
  1441. if (gt->GetType() == cmStateEnums::GLOBAL_TARGET) {
  1442. std::string targetString =
  1443. "Special rule for the target " + gt->GetName();
  1444. std::vector<std::string> commands;
  1445. std::vector<std::string> depends;
  1446. const char* text = gt->GetProperty("EchoString");
  1447. if (!text) {
  1448. text = "Running external command ...";
  1449. }
  1450. depends.reserve(gt->GetUtilities().size());
  1451. for (BT<std::string> const& u : gt->GetUtilities()) {
  1452. depends.push_back(u.Value);
  1453. }
  1454. this->AppendEcho(commands, text,
  1455. cmLocalUnixMakefileGenerator3::EchoGlobal);
  1456. // Global targets store their rules in pre- and post-build commands.
  1457. this->AppendCustomDepends(depends, gt->GetPreBuildCommands());
  1458. this->AppendCustomDepends(depends, gt->GetPostBuildCommands());
  1459. this->AppendCustomCommands(commands, gt->GetPreBuildCommands(), gt,
  1460. this->GetCurrentBinaryDirectory());
  1461. this->AppendCustomCommands(commands, gt->GetPostBuildCommands(), gt,
  1462. this->GetCurrentBinaryDirectory());
  1463. std::string targetName = gt->GetName();
  1464. this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
  1465. depends, commands, true);
  1466. // Provide a "/fast" version of the target.
  1467. depends.clear();
  1468. if ((targetName == "install") || (targetName == "install/local") ||
  1469. (targetName == "install/strip")) {
  1470. // Provide a fast install target that does not depend on all
  1471. // but has the same command.
  1472. depends.emplace_back("preinstall/fast");
  1473. } else {
  1474. // Just forward to the real target so at least it will work.
  1475. depends.push_back(targetName);
  1476. commands.clear();
  1477. }
  1478. targetName += "/fast";
  1479. this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
  1480. depends, commands, true);
  1481. }
  1482. }
  1483. std::vector<std::string> depends;
  1484. std::vector<std::string> commands;
  1485. // Write the all rule.
  1486. std::string recursiveTarget = this->GetCurrentBinaryDirectory();
  1487. recursiveTarget += "/all";
  1488. bool regenerate =
  1489. !this->GlobalGenerator->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION");
  1490. if (regenerate) {
  1491. depends.emplace_back("cmake_check_build_system");
  1492. }
  1493. std::string progressDir = this->GetBinaryDirectory();
  1494. progressDir += "/CMakeFiles";
  1495. {
  1496. std::ostringstream progCmd;
  1497. progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start ";
  1498. progCmd << this->ConvertToOutputFormat(
  1499. cmSystemTools::CollapseFullPath(progressDir), cmOutputConverter::SHELL);
  1500. std::string progressFile = "/CMakeFiles";
  1501. progressFile += "/progress.marks";
  1502. std::string progressFileNameFull = this->ConvertToFullPath(progressFile);
  1503. progCmd << " "
  1504. << this->ConvertToOutputFormat(
  1505. cmSystemTools::CollapseFullPath(progressFileNameFull),
  1506. cmOutputConverter::SHELL);
  1507. commands.push_back(progCmd.str());
  1508. }
  1509. std::string mf2Dir = "CMakeFiles/";
  1510. mf2Dir += "Makefile2";
  1511. commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
  1512. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1513. this->GetCurrentBinaryDirectory());
  1514. {
  1515. std::ostringstream progCmd;
  1516. progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; // # 0
  1517. progCmd << this->ConvertToOutputFormat(
  1518. cmSystemTools::CollapseFullPath(progressDir), cmOutputConverter::SHELL);
  1519. progCmd << " 0";
  1520. commands.push_back(progCmd.str());
  1521. }
  1522. this->WriteMakeRule(ruleFileStream, "The main all target", "all", depends,
  1523. commands, true);
  1524. // Write the clean rule.
  1525. recursiveTarget = this->GetCurrentBinaryDirectory();
  1526. recursiveTarget += "/clean";
  1527. commands.clear();
  1528. depends.clear();
  1529. commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
  1530. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1531. this->GetCurrentBinaryDirectory());
  1532. this->WriteMakeRule(ruleFileStream, "The main clean target", "clean",
  1533. depends, commands, true);
  1534. commands.clear();
  1535. depends.clear();
  1536. depends.emplace_back("clean");
  1537. this->WriteMakeRule(ruleFileStream, "The main clean target", "clean/fast",
  1538. depends, commands, true);
  1539. // Write the preinstall rule.
  1540. recursiveTarget = this->GetCurrentBinaryDirectory();
  1541. recursiveTarget += "/preinstall";
  1542. commands.clear();
  1543. depends.clear();
  1544. const char* noall =
  1545. this->Makefile->GetDefinition("CMAKE_SKIP_INSTALL_ALL_DEPENDENCY");
  1546. if (!noall || cmIsOff(noall)) {
  1547. // Drive the build before installing.
  1548. depends.emplace_back("all");
  1549. } else if (regenerate) {
  1550. // At least make sure the build system is up to date.
  1551. depends.emplace_back("cmake_check_build_system");
  1552. }
  1553. commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
  1554. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1555. this->GetCurrentBinaryDirectory());
  1556. this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
  1557. "preinstall", depends, commands, true);
  1558. depends.clear();
  1559. this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
  1560. "preinstall/fast", depends, commands, true);
  1561. if (regenerate) {
  1562. // write the depend rule, really a recompute depends rule
  1563. depends.clear();
  1564. commands.clear();
  1565. cmake* cm = this->GlobalGenerator->GetCMakeInstance();
  1566. if (cm->DoWriteGlobVerifyTarget()) {
  1567. std::string rescanRule = "$(CMAKE_COMMAND) -P ";
  1568. rescanRule += this->ConvertToOutputFormat(cm->GetGlobVerifyScript(),
  1569. cmOutputConverter::SHELL);
  1570. commands.push_back(rescanRule);
  1571. }
  1572. std::string cmakefileName = "CMakeFiles/";
  1573. cmakefileName += "Makefile.cmake";
  1574. {
  1575. std::string runRule =
  1576. "$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)";
  1577. runRule += " --check-build-system ";
  1578. runRule +=
  1579. this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL);
  1580. runRule += " 1";
  1581. commands.push_back(std::move(runRule));
  1582. }
  1583. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1584. this->GetCurrentBinaryDirectory());
  1585. this->WriteMakeRule(ruleFileStream, "clear depends", "depend", depends,
  1586. commands, true);
  1587. }
  1588. }
  1589. void cmLocalUnixMakefileGenerator3::ClearDependencies(cmMakefile* mf,
  1590. bool verbose)
  1591. {
  1592. // Get the list of target files to check
  1593. const char* infoDef = mf->GetDefinition("CMAKE_DEPEND_INFO_FILES");
  1594. if (!infoDef) {
  1595. return;
  1596. }
  1597. std::vector<std::string> files;
  1598. cmExpandList(infoDef, files);
  1599. // Each depend information file corresponds to a target. Clear the
  1600. // dependencies for that target.
  1601. cmDepends clearer;
  1602. clearer.SetVerbose(verbose);
  1603. for (std::string const& file : files) {
  1604. std::string dir = cmSystemTools::GetFilenamePath(file);
  1605. // Clear the implicit dependency makefile.
  1606. std::string dependFile = dir + "/depend.make";
  1607. clearer.Clear(dependFile);
  1608. // Remove the internal dependency check file to force
  1609. // regeneration.
  1610. std::string internalDependFile = dir + "/depend.internal";
  1611. cmSystemTools::RemoveFile(internalDependFile);
  1612. }
  1613. }
  1614. namespace {
  1615. // Helper predicate for removing absolute paths that don't point to the
  1616. // source or binary directory. It is used when CMAKE_DEPENDS_IN_PROJECT_ONLY
  1617. // is set ON, to only consider in-project dependencies during the build.
  1618. class NotInProjectDir
  1619. {
  1620. public:
  1621. // Constructor with the source and binary directory's path
  1622. NotInProjectDir(std::string sourceDir, std::string binaryDir)
  1623. : SourceDir(std::move(sourceDir))
  1624. , BinaryDir(std::move(binaryDir))
  1625. {
  1626. }
  1627. // Operator evaluating the predicate
  1628. bool operator()(const std::string& path) const
  1629. {
  1630. // Keep all relative paths:
  1631. if (!cmSystemTools::FileIsFullPath(path)) {
  1632. return false;
  1633. }
  1634. // If it's an absolute path, check if it starts with the source
  1635. // direcotory:
  1636. return (
  1637. !(IsInDirectory(SourceDir, path) || IsInDirectory(BinaryDir, path)));
  1638. }
  1639. private:
  1640. // Helper function used by the predicate
  1641. static bool IsInDirectory(const std::string& baseDir,
  1642. const std::string& testDir)
  1643. {
  1644. // First check if the test directory "starts with" the base directory:
  1645. if (testDir.find(baseDir) != 0) {
  1646. return false;
  1647. }
  1648. // If it does, then check that it's either the same string, or that the
  1649. // next character is a slash:
  1650. return ((testDir.size() == baseDir.size()) ||
  1651. (testDir[baseDir.size()] == '/'));
  1652. }
  1653. // The path to the source directory
  1654. std::string SourceDir;
  1655. // The path to the binary directory
  1656. std::string BinaryDir;
  1657. };
  1658. }
  1659. void cmLocalUnixMakefileGenerator3::WriteDependLanguageInfo(
  1660. std::ostream& cmakefileStream, cmGeneratorTarget* target)
  1661. {
  1662. ImplicitDependLanguageMap const& implicitLangs =
  1663. this->GetImplicitDepends(target);
  1664. // list the languages
  1665. cmakefileStream
  1666. << "# The set of languages for which implicit dependencies are needed:\n";
  1667. cmakefileStream << "set(CMAKE_DEPENDS_LANGUAGES\n";
  1668. for (auto const& implicitLang : implicitLangs) {
  1669. cmakefileStream << " \"" << implicitLang.first << "\"\n";
  1670. }
  1671. cmakefileStream << " )\n";
  1672. // now list the files for each language
  1673. cmakefileStream
  1674. << "# The set of files for implicit dependencies of each language:\n";
  1675. for (auto const& implicitLang : implicitLangs) {
  1676. cmakefileStream << "set(CMAKE_DEPENDS_CHECK_" << implicitLang.first
  1677. << "\n";
  1678. ImplicitDependFileMap const& implicitPairs = implicitLang.second;
  1679. // for each file pair
  1680. for (auto const& implicitPair : implicitPairs) {
  1681. for (auto const& di : implicitPair.second) {
  1682. cmakefileStream << " \"" << di << "\" ";
  1683. cmakefileStream << "\"" << implicitPair.first << "\"\n";
  1684. }
  1685. }
  1686. cmakefileStream << " )\n";
  1687. // Tell the dependency scanner what compiler is used.
  1688. std::string cidVar = "CMAKE_";
  1689. cidVar += implicitLang.first;
  1690. cidVar += "_COMPILER_ID";
  1691. const char* cid = this->Makefile->GetDefinition(cidVar);
  1692. if (cid && *cid) {
  1693. cmakefileStream << "set(CMAKE_" << implicitLang.first
  1694. << "_COMPILER_ID \"" << cid << "\")\n";
  1695. }
  1696. if (implicitLang.first == "Fortran") {
  1697. std::string smodSep =
  1698. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_SEP");
  1699. std::string smodExt =
  1700. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_EXT");
  1701. cmakefileStream << "set(CMAKE_Fortran_SUBMODULE_SEP \"" << smodSep
  1702. << "\")\n";
  1703. cmakefileStream << "set(CMAKE_Fortran_SUBMODULE_EXT \"" << smodExt
  1704. << "\")\n";
  1705. }
  1706. // Build a list of preprocessor definitions for the target.
  1707. std::set<std::string> defines;
  1708. this->GetTargetDefines(target, this->ConfigName, implicitLang.first,
  1709. defines);
  1710. if (!defines.empty()) {
  1711. /* clang-format off */
  1712. cmakefileStream
  1713. << "\n"
  1714. << "# Preprocessor definitions for this target.\n"
  1715. << "set(CMAKE_TARGET_DEFINITIONS_" << implicitLang.first << "\n";
  1716. /* clang-format on */
  1717. for (std::string const& define : defines) {
  1718. cmakefileStream << " " << cmOutputConverter::EscapeForCMake(define)
  1719. << "\n";
  1720. }
  1721. cmakefileStream << " )\n";
  1722. }
  1723. // Target-specific include directories:
  1724. cmakefileStream << "\n"
  1725. << "# The include file search paths:\n";
  1726. cmakefileStream << "set(CMAKE_" << implicitLang.first
  1727. << "_TARGET_INCLUDE_PATH\n";
  1728. std::vector<std::string> includes;
  1729. const std::string& config =
  1730. this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
  1731. this->GetIncludeDirectories(includes, target, implicitLang.first, config);
  1732. std::string binaryDir = this->GetState()->GetBinaryDirectory();
  1733. if (this->Makefile->IsOn("CMAKE_DEPENDS_IN_PROJECT_ONLY")) {
  1734. std::string const& sourceDir = this->GetState()->GetSourceDirectory();
  1735. cmEraseIf(includes, ::NotInProjectDir(sourceDir, binaryDir));
  1736. }
  1737. for (std::string const& include : includes) {
  1738. cmakefileStream << " \""
  1739. << this->MaybeConvertToRelativePath(binaryDir, include)
  1740. << "\"\n";
  1741. }
  1742. cmakefileStream << " )\n";
  1743. }
  1744. // Store include transform rule properties. Write the directory
  1745. // rules first because they may be overridden by later target rules.
  1746. std::vector<std::string> transformRules;
  1747. if (const char* xform =
  1748. this->Makefile->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
  1749. cmExpandList(xform, transformRules);
  1750. }
  1751. if (const char* xform =
  1752. target->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
  1753. cmExpandList(xform, transformRules);
  1754. }
  1755. if (!transformRules.empty()) {
  1756. cmakefileStream << "set(CMAKE_INCLUDE_TRANSFORMS\n";
  1757. for (std::string const& tr : transformRules) {
  1758. cmakefileStream << " " << cmOutputConverter::EscapeForCMake(tr) << "\n";
  1759. }
  1760. cmakefileStream << " )\n";
  1761. }
  1762. }
  1763. void cmLocalUnixMakefileGenerator3::WriteDisclaimer(std::ostream& os)
  1764. {
  1765. os << "# CMAKE generated file: DO NOT EDIT!\n"
  1766. << "# Generated by \"" << this->GlobalGenerator->GetName() << "\""
  1767. << " Generator, CMake Version " << cmVersion::GetMajorVersion() << "."
  1768. << cmVersion::GetMinorVersion() << "\n\n";
  1769. }
  1770. std::string cmLocalUnixMakefileGenerator3::GetRecursiveMakeCall(
  1771. const std::string& makefile, const std::string& tgt)
  1772. {
  1773. // Call make on the given file.
  1774. std::string cmd;
  1775. cmd += "$(MAKE) -f ";
  1776. cmd += this->ConvertToOutputFormat(makefile, cmOutputConverter::SHELL);
  1777. cmd += " ";
  1778. cmGlobalUnixMakefileGenerator3* gg =
  1779. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1780. // Pass down verbosity level.
  1781. if (!gg->MakeSilentFlag.empty()) {
  1782. cmd += gg->MakeSilentFlag;
  1783. cmd += " ";
  1784. }
  1785. // Most unix makes will pass the command line flags to make down to
  1786. // sub-invoked makes via an environment variable. However, some
  1787. // makes do not support that, so you have to pass the flags
  1788. // explicitly.
  1789. if (gg->PassMakeflags) {
  1790. cmd += "-$(MAKEFLAGS) ";
  1791. }
  1792. // Add the target.
  1793. if (!tgt.empty()) {
  1794. // The make target is always relative to the top of the build tree.
  1795. std::string tgt2 =
  1796. this->MaybeConvertToRelativePath(this->GetBinaryDirectory(), tgt);
  1797. // The target may have been written with windows paths.
  1798. cmSystemTools::ConvertToOutputSlashes(tgt2);
  1799. // Escape one extra time if the make tool requires it.
  1800. if (this->MakeCommandEscapeTargetTwice) {
  1801. tgt2 = this->EscapeForShell(tgt2, true, false);
  1802. }
  1803. // The target name is now a string that should be passed verbatim
  1804. // on the command line.
  1805. cmd += this->EscapeForShell(tgt2, true, false);
  1806. }
  1807. return cmd;
  1808. }
  1809. void cmLocalUnixMakefileGenerator3::WriteDivider(std::ostream& os)
  1810. {
  1811. os << "#======================================"
  1812. << "=======================================\n";
  1813. }
  1814. void cmLocalUnixMakefileGenerator3::WriteCMakeArgument(std::ostream& os,
  1815. const char* s)
  1816. {
  1817. // Write the given string to the stream with escaping to get it back
  1818. // into CMake through the lexical scanner.
  1819. os << "\"";
  1820. for (const char* c = s; *c; ++c) {
  1821. if (*c == '\\') {
  1822. os << "\\\\";
  1823. } else if (*c == '"') {
  1824. os << "\\\"";
  1825. } else {
  1826. os << *c;
  1827. }
  1828. }
  1829. os << "\"";
  1830. }
  1831. std::string cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(
  1832. const std::string& p, bool useWatcomQuote)
  1833. {
  1834. // Split the path into its components.
  1835. std::vector<std::string> components;
  1836. cmSystemTools::SplitPath(p, components);
  1837. // Open the quoted result.
  1838. std::string result;
  1839. if (useWatcomQuote) {
  1840. #if defined(_WIN32) && !defined(__CYGWIN__)
  1841. result = "'";
  1842. #else
  1843. result = "\"'";
  1844. #endif
  1845. } else {
  1846. result = "\"";
  1847. }
  1848. // Return an empty path if there are no components.
  1849. if (!components.empty()) {
  1850. // Choose a slash direction and fix root component.
  1851. const char* slash = "/";
  1852. #if defined(_WIN32) && !defined(__CYGWIN__)
  1853. if (!cmSystemTools::GetForceUnixPaths()) {
  1854. slash = "\\";
  1855. for (char& i : components[0]) {
  1856. if (i == '/') {
  1857. i = '\\';
  1858. }
  1859. }
  1860. }
  1861. #endif
  1862. // Begin the quoted result with the root component.
  1863. result += components[0];
  1864. if (components.size() > 1) {
  1865. // Now add the rest of the components separated by the proper slash
  1866. // direction for this platform.
  1867. std::vector<std::string>::const_iterator compEnd = std::remove(
  1868. components.begin() + 1, components.end() - 1, std::string());
  1869. std::vector<std::string>::const_iterator compStart =
  1870. components.begin() + 1;
  1871. result += cmJoin(cmMakeRange(compStart, compEnd), slash);
  1872. // Only the last component can be empty to avoid double slashes.
  1873. result += slash;
  1874. result += components.back();
  1875. }
  1876. }
  1877. // Close the quoted result.
  1878. if (useWatcomQuote) {
  1879. #if defined(_WIN32) && !defined(__CYGWIN__)
  1880. result += "'";
  1881. #else
  1882. result += "'\"";
  1883. #endif
  1884. } else {
  1885. result += "\"";
  1886. }
  1887. return result;
  1888. }
  1889. std::string cmLocalUnixMakefileGenerator3::GetTargetDirectory(
  1890. cmGeneratorTarget const* target) const
  1891. {
  1892. std::string dir = "CMakeFiles/";
  1893. dir += target->GetName();
  1894. #if defined(__VMS)
  1895. dir += "_dir";
  1896. #else
  1897. dir += ".dir";
  1898. #endif
  1899. return dir;
  1900. }
  1901. cmLocalUnixMakefileGenerator3::ImplicitDependLanguageMap const&
  1902. cmLocalUnixMakefileGenerator3::GetImplicitDepends(const cmGeneratorTarget* tgt)
  1903. {
  1904. return this->ImplicitDepends[tgt->GetName()];
  1905. }
  1906. void cmLocalUnixMakefileGenerator3::AddImplicitDepends(
  1907. const cmGeneratorTarget* tgt, const std::string& lang,
  1908. const std::string& obj, const std::string& src)
  1909. {
  1910. this->ImplicitDepends[tgt->GetName()][lang][obj].push_back(src);
  1911. }
  1912. void cmLocalUnixMakefileGenerator3::CreateCDCommand(
  1913. std::vector<std::string>& commands, std::string const& tgtDir,
  1914. std::string const& relDir)
  1915. {
  1916. // do we need to cd?
  1917. if (tgtDir == relDir) {
  1918. return;
  1919. }
  1920. // In a Windows shell we must change drive letter too. The shell
  1921. // used by NMake and Borland make does not support "cd /d" so this
  1922. // feature simply cannot work with them (Borland make does not even
  1923. // support changing the drive letter with just "d:").
  1924. const char* cd_cmd = this->IsMinGWMake() ? "cd /d " : "cd ";
  1925. cmGlobalUnixMakefileGenerator3* gg =
  1926. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1927. if (!gg->UnixCD) {
  1928. // On Windows we must perform each step separately and then change
  1929. // back because the shell keeps the working directory between
  1930. // commands.
  1931. std::string cmd = cd_cmd;
  1932. cmd += this->ConvertToOutputForExisting(tgtDir);
  1933. commands.insert(commands.begin(), cmd);
  1934. // Change back to the starting directory.
  1935. cmd = cd_cmd;
  1936. cmd += this->ConvertToOutputForExisting(relDir);
  1937. commands.push_back(std::move(cmd));
  1938. } else {
  1939. // On UNIX we must construct a single shell command to change
  1940. // directory and build because make resets the directory between
  1941. // each command.
  1942. std::string outputForExisting = this->ConvertToOutputForExisting(tgtDir);
  1943. std::string prefix = cd_cmd + outputForExisting + " && ";
  1944. std::transform(commands.begin(), commands.end(), commands.begin(),
  1945. [&prefix](std::string const& s) { return prefix + s; });
  1946. }
  1947. }