cmLocalUnixMakefileGenerator3.cxx 72 KB

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