cmLocalUnixMakefileGenerator3.cxx 72 KB

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