cmLocalUnixMakefileGenerator3.cxx 73 KB

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