cmLocalUnixMakefileGenerator3.cxx 73 KB

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