cmLocalUnixMakefileGenerator3.cxx 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109
  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. std::map<std::string, std::string>::iterator i =
  1123. this->MakeVariableMap.find(unmodified);
  1124. if (i != this->MakeVariableMap.end()) {
  1125. return i->second;
  1126. }
  1127. // start with the unmodified variable
  1128. std::string ret = unmodified;
  1129. // if this there is no value for this->MakefileVariableSize then
  1130. // the string must have bad characters in it
  1131. if (!this->MakefileVariableSize) {
  1132. std::replace(ret.begin(), ret.end(), '.', '_');
  1133. cmSystemTools::ReplaceString(ret, "-", "__");
  1134. cmSystemTools::ReplaceString(ret, "+", "___");
  1135. int ni = 0;
  1136. char buffer[5];
  1137. // make sure the _ version is not already used, if
  1138. // it is used then add number to the end of the variable
  1139. while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
  1140. ++ni;
  1141. sprintf(buffer, "%04d", ni);
  1142. ret = unmodified + buffer;
  1143. }
  1144. this->ShortMakeVariableMap[ret] = "1";
  1145. this->MakeVariableMap[unmodified] = ret;
  1146. return ret;
  1147. }
  1148. // if the string is greater than 32 chars it is an invalid variable name
  1149. // for borland make
  1150. if (static_cast<int>(ret.size()) > this->MakefileVariableSize) {
  1151. int keep = this->MakefileVariableSize - 8;
  1152. int size = keep + 3;
  1153. std::string str1 = s;
  1154. std::string str2 = s2;
  1155. // we must shorten the combined string by 4 characters
  1156. // keep no more than 24 characters from the second string
  1157. if (static_cast<int>(str2.size()) > keep) {
  1158. str2 = str2.substr(0, keep);
  1159. }
  1160. if (static_cast<int>(str1.size()) + static_cast<int>(str2.size()) > size) {
  1161. str1 = str1.substr(0, size - str2.size());
  1162. }
  1163. char buffer[5];
  1164. int ni = 0;
  1165. sprintf(buffer, "%04d", ni);
  1166. ret = str1 + str2 + buffer;
  1167. while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
  1168. ++ni;
  1169. sprintf(buffer, "%04d", ni);
  1170. ret = str1 + str2 + buffer;
  1171. }
  1172. if (ni == 1000) {
  1173. cmSystemTools::Error("Borland makefile variable length too long");
  1174. return unmodified;
  1175. }
  1176. // once an unused variable is found
  1177. this->ShortMakeVariableMap[ret] = "1";
  1178. }
  1179. // always make an entry into the unmodified to variable map
  1180. this->MakeVariableMap[unmodified] = ret;
  1181. return ret;
  1182. }
  1183. bool cmLocalUnixMakefileGenerator3::UpdateDependencies(
  1184. const std::string& tgtInfo, bool verbose, bool color)
  1185. {
  1186. // read in the target info file
  1187. if (!this->Makefile->ReadListFile(tgtInfo) ||
  1188. cmSystemTools::GetErrorOccuredFlag()) {
  1189. cmSystemTools::Error("Target DependInfo.cmake file not found");
  1190. }
  1191. // Check if any multiple output pairs have a missing file.
  1192. this->CheckMultipleOutputs(verbose);
  1193. std::string const targetDir = cmSystemTools::GetFilenamePath(tgtInfo);
  1194. std::string const internalDependFile = targetDir + "/depend.internal";
  1195. std::string const dependFile = targetDir + "/depend.make";
  1196. // If the target DependInfo.cmake file has changed since the last
  1197. // time dependencies were scanned then force rescanning. This may
  1198. // happen when a new source file is added and CMake regenerates the
  1199. // project but no other sources were touched.
  1200. bool needRescanDependInfo = false;
  1201. cmFileTimeCache* ftc =
  1202. this->GlobalGenerator->GetCMakeInstance()->GetFileTimeCache();
  1203. {
  1204. int result;
  1205. if (!ftc->Compare(internalDependFile, tgtInfo, &result) || result < 0) {
  1206. if (verbose) {
  1207. std::ostringstream msg;
  1208. msg << "Dependee \"" << tgtInfo << "\" is newer than depender \""
  1209. << internalDependFile << "\"." << std::endl;
  1210. cmSystemTools::Stdout(msg.str());
  1211. }
  1212. needRescanDependInfo = true;
  1213. }
  1214. }
  1215. // If the directory information is newer than depend.internal, include dirs
  1216. // may have changed. In this case discard all old dependencies.
  1217. bool needRescanDirInfo = false;
  1218. {
  1219. std::string dirInfoFile =
  1220. cmStrCat(this->GetCurrentBinaryDirectory(),
  1221. "/CMakeFiles/CMakeDirectoryInformation.cmake");
  1222. int result;
  1223. if (!ftc->Compare(internalDependFile, dirInfoFile, &result) ||
  1224. result < 0) {
  1225. if (verbose) {
  1226. std::ostringstream msg;
  1227. msg << "Dependee \"" << dirInfoFile << "\" is newer than depender \""
  1228. << internalDependFile << "\"." << std::endl;
  1229. cmSystemTools::Stdout(msg.str());
  1230. }
  1231. needRescanDirInfo = true;
  1232. }
  1233. }
  1234. // Check the implicit dependencies to see if they are up to date.
  1235. // The build.make file may have explicit dependencies for the object
  1236. // files but these will not affect the scanning process so they need
  1237. // not be considered.
  1238. cmDepends::DependencyMap validDependencies;
  1239. bool needRescanDependencies = false;
  1240. if (!needRescanDirInfo) {
  1241. cmDependsC checker;
  1242. checker.SetVerbose(verbose);
  1243. checker.SetFileTimeCache(ftc);
  1244. // cmDependsC::Check() fills the vector validDependencies() with the
  1245. // dependencies for those files where they are still valid, i.e. neither
  1246. // the files themselves nor any files they depend on have changed.
  1247. // We don't do that if the CMakeDirectoryInformation.cmake file has
  1248. // changed, because then potentially all dependencies have changed.
  1249. // This information is given later on to cmDependsC, which then only
  1250. // rescans the files where it did not get valid dependencies via this
  1251. // dependency vector. This means that in the normal case, when only
  1252. // few or one file have been edited, then also only this one file is
  1253. // actually scanned again, instead of all files for this target.
  1254. needRescanDependencies =
  1255. !checker.Check(dependFile, internalDependFile, validDependencies);
  1256. }
  1257. if (needRescanDependInfo || needRescanDirInfo || needRescanDependencies) {
  1258. // The dependencies must be regenerated.
  1259. std::string targetName = cmSystemTools::GetFilenameName(targetDir);
  1260. targetName = targetName.substr(0, targetName.length() - 4);
  1261. std::string message =
  1262. cmStrCat("Scanning dependencies of target ", targetName);
  1263. cmSystemTools::MakefileColorEcho(cmsysTerminal_Color_ForegroundMagenta |
  1264. cmsysTerminal_Color_ForegroundBold,
  1265. message.c_str(), true, color);
  1266. return this->ScanDependencies(targetDir, dependFile, internalDependFile,
  1267. validDependencies);
  1268. }
  1269. // The dependencies are already up-to-date.
  1270. return true;
  1271. }
  1272. bool cmLocalUnixMakefileGenerator3::ScanDependencies(
  1273. std::string const& targetDir, std::string const& dependFile,
  1274. std::string const& internalDependFile, cmDepends::DependencyMap& validDeps)
  1275. {
  1276. // Read the directory information file.
  1277. cmMakefile* mf = this->Makefile;
  1278. bool haveDirectoryInfo = false;
  1279. {
  1280. std::string dirInfoFile =
  1281. cmStrCat(this->GetCurrentBinaryDirectory(),
  1282. "/CMakeFiles/CMakeDirectoryInformation.cmake");
  1283. if (mf->ReadListFile(dirInfoFile) &&
  1284. !cmSystemTools::GetErrorOccuredFlag()) {
  1285. haveDirectoryInfo = true;
  1286. }
  1287. }
  1288. // Lookup useful directory information.
  1289. if (haveDirectoryInfo) {
  1290. // Test whether we need to force Unix paths.
  1291. if (const char* force = mf->GetDefinition("CMAKE_FORCE_UNIX_PATHS")) {
  1292. if (!cmIsOff(force)) {
  1293. cmSystemTools::SetForceUnixPaths(true);
  1294. }
  1295. }
  1296. // Setup relative path top directories.
  1297. if (const char* relativePathTopSource =
  1298. mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_SOURCE")) {
  1299. this->StateSnapshot.GetDirectory().SetRelativePathTopSource(
  1300. relativePathTopSource);
  1301. }
  1302. if (const char* relativePathTopBinary =
  1303. mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_BINARY")) {
  1304. this->StateSnapshot.GetDirectory().SetRelativePathTopBinary(
  1305. relativePathTopBinary);
  1306. }
  1307. } else {
  1308. cmSystemTools::Error("Directory Information file not found");
  1309. }
  1310. // Open the make depends file. This should be copy-if-different
  1311. // because the make tool may try to reload it needlessly otherwise.
  1312. cmGeneratedFileStream ruleFileStream(
  1313. dependFile, false, this->GlobalGenerator->GetMakefileEncoding());
  1314. ruleFileStream.SetCopyIfDifferent(true);
  1315. if (!ruleFileStream) {
  1316. return false;
  1317. }
  1318. // Open the cmake dependency tracking file. This should not be
  1319. // copy-if-different because dependencies are re-scanned when it is
  1320. // older than the DependInfo.cmake.
  1321. cmGeneratedFileStream internalRuleFileStream(
  1322. internalDependFile, false, this->GlobalGenerator->GetMakefileEncoding());
  1323. if (!internalRuleFileStream) {
  1324. return false;
  1325. }
  1326. this->WriteDisclaimer(ruleFileStream);
  1327. this->WriteDisclaimer(internalRuleFileStream);
  1328. // for each language we need to scan, scan it
  1329. std::vector<std::string> langs =
  1330. cmExpandedList(mf->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES"));
  1331. for (std::string const& lang : langs) {
  1332. // construct the checker
  1333. // Create the scanner for this language
  1334. std::unique_ptr<cmDepends> scanner;
  1335. if (lang == "C" || lang == "CXX" || lang == "RC" || lang == "ASM" ||
  1336. lang == "CUDA") {
  1337. // TODO: Handle RC (resource files) dependencies correctly.
  1338. scanner = cm::make_unique<cmDependsC>(this, targetDir, lang, &validDeps);
  1339. }
  1340. #ifndef CMAKE_BOOTSTRAP
  1341. else if (lang == "Fortran") {
  1342. ruleFileStream << "# Note that incremental build could trigger "
  1343. << "a call to cmake_copy_f90_mod on each re-build\n";
  1344. scanner = cm::make_unique<cmDependsFortran>(this);
  1345. } else if (lang == "Java") {
  1346. scanner = cm::make_unique<cmDependsJava>();
  1347. }
  1348. #endif
  1349. if (scanner) {
  1350. scanner->SetLocalGenerator(this);
  1351. scanner->SetFileTimeCache(
  1352. this->GlobalGenerator->GetCMakeInstance()->GetFileTimeCache());
  1353. scanner->SetLanguage(lang);
  1354. scanner->SetTargetDirectory(targetDir);
  1355. scanner->Write(ruleFileStream, internalRuleFileStream);
  1356. }
  1357. }
  1358. return true;
  1359. }
  1360. void cmLocalUnixMakefileGenerator3::CheckMultipleOutputs(bool verbose)
  1361. {
  1362. cmMakefile* mf = this->Makefile;
  1363. // Get the string listing the multiple output pairs.
  1364. const char* pairs_string = mf->GetDefinition("CMAKE_MULTIPLE_OUTPUT_PAIRS");
  1365. if (!pairs_string) {
  1366. return;
  1367. }
  1368. // Convert the string to a list and preserve empty entries.
  1369. std::vector<std::string> pairs = cmExpandedList(pairs_string, true);
  1370. for (std::vector<std::string>::const_iterator i = pairs.begin();
  1371. i != pairs.end() && (i + 1) != pairs.end();) {
  1372. const std::string& depender = *i++;
  1373. const std::string& dependee = *i++;
  1374. // If the depender is missing then delete the dependee to make
  1375. // sure both will be regenerated.
  1376. if (cmSystemTools::FileExists(dependee) &&
  1377. !cmSystemTools::FileExists(depender)) {
  1378. if (verbose) {
  1379. std::ostringstream msg;
  1380. msg << "Deleting primary custom command output \"" << dependee
  1381. << "\" because another output \"" << depender
  1382. << "\" does not exist." << std::endl;
  1383. cmSystemTools::Stdout(msg.str());
  1384. }
  1385. cmSystemTools::RemoveFile(dependee);
  1386. }
  1387. }
  1388. }
  1389. void cmLocalUnixMakefileGenerator3::WriteLocalAllRules(
  1390. std::ostream& ruleFileStream)
  1391. {
  1392. this->WriteDisclaimer(ruleFileStream);
  1393. // Write the main entry point target. This must be the VERY first
  1394. // target so that make with no arguments will run it.
  1395. {
  1396. // Just depend on the all target to drive the build.
  1397. std::vector<std::string> depends;
  1398. std::vector<std::string> no_commands;
  1399. depends.emplace_back("all");
  1400. // Write the rule.
  1401. this->WriteMakeRule(ruleFileStream,
  1402. "Default target executed when no arguments are "
  1403. "given to make.",
  1404. "default_target", depends, no_commands, true);
  1405. // Help out users that try "gmake target1 target2 -j".
  1406. cmGlobalUnixMakefileGenerator3* gg =
  1407. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1408. if (gg->AllowNotParallel()) {
  1409. std::vector<std::string> no_depends;
  1410. this->WriteMakeRule(ruleFileStream,
  1411. "Allow only one \"make -f "
  1412. "Makefile2\" at a time, but pass "
  1413. "parallelism.",
  1414. ".NOTPARALLEL", no_depends, no_commands, false);
  1415. }
  1416. }
  1417. this->WriteSpecialTargetsTop(ruleFileStream);
  1418. // Include the progress variables for the target.
  1419. // Write all global targets
  1420. this->WriteDivider(ruleFileStream);
  1421. ruleFileStream << "# Targets provided globally by CMake.\n"
  1422. << "\n";
  1423. const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
  1424. for (cmGeneratorTarget* gt : targets) {
  1425. if (gt->GetType() == cmStateEnums::GLOBAL_TARGET) {
  1426. std::string targetString =
  1427. "Special rule for the target " + gt->GetName();
  1428. std::vector<std::string> commands;
  1429. std::vector<std::string> depends;
  1430. const char* text = gt->GetProperty("EchoString");
  1431. if (!text) {
  1432. text = "Running external command ...";
  1433. }
  1434. depends.reserve(gt->GetUtilities().size());
  1435. for (BT<std::string> const& u : gt->GetUtilities()) {
  1436. depends.push_back(u.Value);
  1437. }
  1438. this->AppendEcho(commands, text,
  1439. cmLocalUnixMakefileGenerator3::EchoGlobal);
  1440. // Global targets store their rules in pre- and post-build commands.
  1441. this->AppendCustomDepends(depends, gt->GetPreBuildCommands());
  1442. this->AppendCustomDepends(depends, gt->GetPostBuildCommands());
  1443. this->AppendCustomCommands(commands, gt->GetPreBuildCommands(), gt,
  1444. this->GetCurrentBinaryDirectory());
  1445. this->AppendCustomCommands(commands, gt->GetPostBuildCommands(), gt,
  1446. this->GetCurrentBinaryDirectory());
  1447. std::string targetName = gt->GetName();
  1448. this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
  1449. depends, commands, true);
  1450. // Provide a "/fast" version of the target.
  1451. depends.clear();
  1452. if ((targetName == "install") || (targetName == "install/local") ||
  1453. (targetName == "install/strip")) {
  1454. // Provide a fast install target that does not depend on all
  1455. // but has the same command.
  1456. depends.emplace_back("preinstall/fast");
  1457. } else {
  1458. // Just forward to the real target so at least it will work.
  1459. depends.push_back(targetName);
  1460. commands.clear();
  1461. }
  1462. targetName += "/fast";
  1463. this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
  1464. depends, commands, true);
  1465. }
  1466. }
  1467. std::vector<std::string> depends;
  1468. std::vector<std::string> commands;
  1469. // Write the all rule.
  1470. std::string recursiveTarget =
  1471. cmStrCat(this->GetCurrentBinaryDirectory(), "/all");
  1472. bool regenerate =
  1473. !this->GlobalGenerator->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION");
  1474. if (regenerate) {
  1475. depends.emplace_back("cmake_check_build_system");
  1476. }
  1477. std::string progressDir =
  1478. cmStrCat(this->GetBinaryDirectory(), "/CMakeFiles");
  1479. {
  1480. std::ostringstream progCmd;
  1481. progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start ";
  1482. progCmd << this->ConvertToOutputFormat(
  1483. cmSystemTools::CollapseFullPath(progressDir), cmOutputConverter::SHELL);
  1484. std::string progressFile = "/CMakeFiles/progress.marks";
  1485. std::string progressFileNameFull = this->ConvertToFullPath(progressFile);
  1486. progCmd << " "
  1487. << this->ConvertToOutputFormat(
  1488. cmSystemTools::CollapseFullPath(progressFileNameFull),
  1489. cmOutputConverter::SHELL);
  1490. commands.push_back(progCmd.str());
  1491. }
  1492. std::string mf2Dir = "CMakeFiles/Makefile2";
  1493. commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
  1494. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1495. this->GetCurrentBinaryDirectory());
  1496. {
  1497. std::ostringstream progCmd;
  1498. progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; // # 0
  1499. progCmd << this->ConvertToOutputFormat(
  1500. cmSystemTools::CollapseFullPath(progressDir), cmOutputConverter::SHELL);
  1501. progCmd << " 0";
  1502. commands.push_back(progCmd.str());
  1503. }
  1504. this->WriteMakeRule(ruleFileStream, "The main all target", "all", depends,
  1505. commands, true);
  1506. // Write the clean rule.
  1507. recursiveTarget = cmStrCat(this->GetCurrentBinaryDirectory(), "/clean");
  1508. commands.clear();
  1509. depends.clear();
  1510. commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
  1511. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1512. this->GetCurrentBinaryDirectory());
  1513. this->WriteMakeRule(ruleFileStream, "The main clean target", "clean",
  1514. depends, commands, true);
  1515. commands.clear();
  1516. depends.clear();
  1517. depends.emplace_back("clean");
  1518. this->WriteMakeRule(ruleFileStream, "The main clean target", "clean/fast",
  1519. depends, commands, true);
  1520. // Write the preinstall rule.
  1521. recursiveTarget = cmStrCat(this->GetCurrentBinaryDirectory(), "/preinstall");
  1522. commands.clear();
  1523. depends.clear();
  1524. const char* noall =
  1525. this->Makefile->GetDefinition("CMAKE_SKIP_INSTALL_ALL_DEPENDENCY");
  1526. if (!noall || cmIsOff(noall)) {
  1527. // Drive the build before installing.
  1528. depends.emplace_back("all");
  1529. } else if (regenerate) {
  1530. // At least make sure the build system is up to date.
  1531. depends.emplace_back("cmake_check_build_system");
  1532. }
  1533. commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
  1534. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1535. this->GetCurrentBinaryDirectory());
  1536. this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
  1537. "preinstall", depends, commands, true);
  1538. depends.clear();
  1539. this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
  1540. "preinstall/fast", depends, commands, true);
  1541. if (regenerate) {
  1542. // write the depend rule, really a recompute depends rule
  1543. depends.clear();
  1544. commands.clear();
  1545. cmake* cm = this->GlobalGenerator->GetCMakeInstance();
  1546. if (cm->DoWriteGlobVerifyTarget()) {
  1547. std::string rescanRule =
  1548. cmStrCat("$(CMAKE_COMMAND) -P ",
  1549. this->ConvertToOutputFormat(cm->GetGlobVerifyScript(),
  1550. cmOutputConverter::SHELL));
  1551. commands.push_back(rescanRule);
  1552. }
  1553. std::string cmakefileName = "CMakeFiles/Makefile.cmake";
  1554. {
  1555. std::string runRule = cmStrCat(
  1556. "$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) "
  1557. "--check-build-system ",
  1558. this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL),
  1559. " 1");
  1560. commands.push_back(std::move(runRule));
  1561. }
  1562. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1563. this->GetCurrentBinaryDirectory());
  1564. this->WriteMakeRule(ruleFileStream, "clear depends", "depend", depends,
  1565. commands, true);
  1566. }
  1567. }
  1568. void cmLocalUnixMakefileGenerator3::ClearDependencies(cmMakefile* mf,
  1569. bool verbose)
  1570. {
  1571. // Get the list of target files to check
  1572. const char* infoDef = mf->GetDefinition("CMAKE_DEPEND_INFO_FILES");
  1573. if (!infoDef) {
  1574. return;
  1575. }
  1576. std::vector<std::string> files = cmExpandedList(infoDef);
  1577. // Each depend information file corresponds to a target. Clear the
  1578. // dependencies for that target.
  1579. cmDepends clearer;
  1580. clearer.SetVerbose(verbose);
  1581. for (std::string const& file : files) {
  1582. std::string dir = cmSystemTools::GetFilenamePath(file);
  1583. // Clear the implicit dependency makefile.
  1584. std::string dependFile = dir + "/depend.make";
  1585. clearer.Clear(dependFile);
  1586. // Remove the internal dependency check file to force
  1587. // regeneration.
  1588. std::string internalDependFile = dir + "/depend.internal";
  1589. cmSystemTools::RemoveFile(internalDependFile);
  1590. }
  1591. }
  1592. namespace {
  1593. // Helper predicate for removing absolute paths that don't point to the
  1594. // source or binary directory. It is used when CMAKE_DEPENDS_IN_PROJECT_ONLY
  1595. // is set ON, to only consider in-project dependencies during the build.
  1596. class NotInProjectDir
  1597. {
  1598. public:
  1599. // Constructor with the source and binary directory's path
  1600. NotInProjectDir(std::string sourceDir, std::string binaryDir)
  1601. : SourceDir(std::move(sourceDir))
  1602. , BinaryDir(std::move(binaryDir))
  1603. {
  1604. }
  1605. // Operator evaluating the predicate
  1606. bool operator()(const std::string& path) const
  1607. {
  1608. // Keep all relative paths:
  1609. if (!cmSystemTools::FileIsFullPath(path)) {
  1610. return false;
  1611. }
  1612. // If it's an absolute path, check if it starts with the source
  1613. // direcotory:
  1614. return (
  1615. !(IsInDirectory(SourceDir, path) || IsInDirectory(BinaryDir, path)));
  1616. }
  1617. private:
  1618. // Helper function used by the predicate
  1619. static bool IsInDirectory(const std::string& baseDir,
  1620. const std::string& testDir)
  1621. {
  1622. // First check if the test directory "starts with" the base directory:
  1623. if (testDir.find(baseDir) != 0) {
  1624. return false;
  1625. }
  1626. // If it does, then check that it's either the same string, or that the
  1627. // next character is a slash:
  1628. return ((testDir.size() == baseDir.size()) ||
  1629. (testDir[baseDir.size()] == '/'));
  1630. }
  1631. // The path to the source directory
  1632. std::string SourceDir;
  1633. // The path to the binary directory
  1634. std::string BinaryDir;
  1635. };
  1636. }
  1637. void cmLocalUnixMakefileGenerator3::WriteDependLanguageInfo(
  1638. std::ostream& cmakefileStream, cmGeneratorTarget* target)
  1639. {
  1640. ImplicitDependLanguageMap const& implicitLangs =
  1641. this->GetImplicitDepends(target);
  1642. // list the languages
  1643. cmakefileStream
  1644. << "# The set of languages for which implicit dependencies are needed:\n";
  1645. cmakefileStream << "set(CMAKE_DEPENDS_LANGUAGES\n";
  1646. for (auto const& implicitLang : implicitLangs) {
  1647. cmakefileStream << " \"" << implicitLang.first << "\"\n";
  1648. }
  1649. cmakefileStream << " )\n";
  1650. // now list the files for each language
  1651. cmakefileStream
  1652. << "# The set of files for implicit dependencies of each language:\n";
  1653. for (auto const& implicitLang : implicitLangs) {
  1654. cmakefileStream << "set(CMAKE_DEPENDS_CHECK_" << implicitLang.first
  1655. << "\n";
  1656. ImplicitDependFileMap const& implicitPairs = implicitLang.second;
  1657. // for each file pair
  1658. for (auto const& implicitPair : implicitPairs) {
  1659. for (auto const& di : implicitPair.second) {
  1660. cmakefileStream << " \"" << di << "\" ";
  1661. cmakefileStream << "\"" << implicitPair.first << "\"\n";
  1662. }
  1663. }
  1664. cmakefileStream << " )\n";
  1665. // Tell the dependency scanner what compiler is used.
  1666. std::string cidVar =
  1667. cmStrCat("CMAKE_", implicitLang.first, "_COMPILER_ID");
  1668. const char* cid = this->Makefile->GetDefinition(cidVar);
  1669. if (cid && *cid) {
  1670. cmakefileStream << "set(CMAKE_" << implicitLang.first
  1671. << "_COMPILER_ID \"" << cid << "\")\n";
  1672. }
  1673. if (implicitLang.first == "Fortran") {
  1674. std::string smodSep =
  1675. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_SEP");
  1676. std::string smodExt =
  1677. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_EXT");
  1678. cmakefileStream << "set(CMAKE_Fortran_SUBMODULE_SEP \"" << smodSep
  1679. << "\")\n";
  1680. cmakefileStream << "set(CMAKE_Fortran_SUBMODULE_EXT \"" << smodExt
  1681. << "\")\n";
  1682. }
  1683. // Build a list of preprocessor definitions for the target.
  1684. std::set<std::string> defines;
  1685. this->GetTargetDefines(target, this->ConfigName, implicitLang.first,
  1686. defines);
  1687. if (!defines.empty()) {
  1688. /* clang-format off */
  1689. cmakefileStream
  1690. << "\n"
  1691. << "# Preprocessor definitions for this target.\n"
  1692. << "set(CMAKE_TARGET_DEFINITIONS_" << implicitLang.first << "\n";
  1693. /* clang-format on */
  1694. for (std::string const& define : defines) {
  1695. cmakefileStream << " " << cmOutputConverter::EscapeForCMake(define)
  1696. << "\n";
  1697. }
  1698. cmakefileStream << " )\n";
  1699. }
  1700. // Target-specific include directories:
  1701. cmakefileStream << "\n"
  1702. << "# The include file search paths:\n";
  1703. cmakefileStream << "set(CMAKE_" << implicitLang.first
  1704. << "_TARGET_INCLUDE_PATH\n";
  1705. std::vector<std::string> includes;
  1706. const std::string& config =
  1707. this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
  1708. this->GetIncludeDirectories(includes, target, implicitLang.first, config);
  1709. std::string binaryDir = this->GetState()->GetBinaryDirectory();
  1710. if (this->Makefile->IsOn("CMAKE_DEPENDS_IN_PROJECT_ONLY")) {
  1711. std::string const& sourceDir = this->GetState()->GetSourceDirectory();
  1712. cmEraseIf(includes, ::NotInProjectDir(sourceDir, binaryDir));
  1713. }
  1714. for (std::string const& include : includes) {
  1715. cmakefileStream << " \""
  1716. << this->MaybeConvertToRelativePath(binaryDir, include)
  1717. << "\"\n";
  1718. }
  1719. cmakefileStream << " )\n";
  1720. }
  1721. // Store include transform rule properties. Write the directory
  1722. // rules first because they may be overridden by later target rules.
  1723. std::vector<std::string> transformRules;
  1724. if (const char* xform =
  1725. this->Makefile->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
  1726. cmExpandList(xform, transformRules);
  1727. }
  1728. if (const char* xform =
  1729. target->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
  1730. cmExpandList(xform, transformRules);
  1731. }
  1732. if (!transformRules.empty()) {
  1733. cmakefileStream << "set(CMAKE_INCLUDE_TRANSFORMS\n";
  1734. for (std::string const& tr : transformRules) {
  1735. cmakefileStream << " " << cmOutputConverter::EscapeForCMake(tr) << "\n";
  1736. }
  1737. cmakefileStream << " )\n";
  1738. }
  1739. }
  1740. void cmLocalUnixMakefileGenerator3::WriteDisclaimer(std::ostream& os)
  1741. {
  1742. os << "# CMAKE generated file: DO NOT EDIT!\n"
  1743. << "# Generated by \"" << this->GlobalGenerator->GetName() << "\""
  1744. << " Generator, CMake Version " << cmVersion::GetMajorVersion() << "."
  1745. << cmVersion::GetMinorVersion() << "\n\n";
  1746. }
  1747. std::string cmLocalUnixMakefileGenerator3::GetRecursiveMakeCall(
  1748. const std::string& makefile, const std::string& tgt)
  1749. {
  1750. // Call make on the given file.
  1751. std::string cmd = cmStrCat(
  1752. "$(MAKE) -f ",
  1753. this->ConvertToOutputFormat(makefile, cmOutputConverter::SHELL), ' ');
  1754. cmGlobalUnixMakefileGenerator3* gg =
  1755. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1756. // Pass down verbosity level.
  1757. if (!gg->MakeSilentFlag.empty()) {
  1758. cmd += gg->MakeSilentFlag;
  1759. cmd += " ";
  1760. }
  1761. // Most unix makes will pass the command line flags to make down to
  1762. // sub-invoked makes via an environment variable. However, some
  1763. // makes do not support that, so you have to pass the flags
  1764. // explicitly.
  1765. if (gg->PassMakeflags) {
  1766. cmd += "-$(MAKEFLAGS) ";
  1767. }
  1768. // Add the target.
  1769. if (!tgt.empty()) {
  1770. // The make target is always relative to the top of the build tree.
  1771. std::string tgt2 =
  1772. this->MaybeConvertToRelativePath(this->GetBinaryDirectory(), tgt);
  1773. // The target may have been written with windows paths.
  1774. cmSystemTools::ConvertToOutputSlashes(tgt2);
  1775. // Escape one extra time if the make tool requires it.
  1776. if (this->MakeCommandEscapeTargetTwice) {
  1777. tgt2 = this->EscapeForShell(tgt2, true, false);
  1778. }
  1779. // The target name is now a string that should be passed verbatim
  1780. // on the command line.
  1781. cmd += this->EscapeForShell(tgt2, true, false);
  1782. }
  1783. return cmd;
  1784. }
  1785. void cmLocalUnixMakefileGenerator3::WriteDivider(std::ostream& os)
  1786. {
  1787. os << "#======================================"
  1788. << "=======================================\n";
  1789. }
  1790. void cmLocalUnixMakefileGenerator3::WriteCMakeArgument(std::ostream& os,
  1791. const char* s)
  1792. {
  1793. // Write the given string to the stream with escaping to get it back
  1794. // into CMake through the lexical scanner.
  1795. os << "\"";
  1796. for (const char* c = s; *c; ++c) {
  1797. if (*c == '\\') {
  1798. os << "\\\\";
  1799. } else if (*c == '"') {
  1800. os << "\\\"";
  1801. } else {
  1802. os << *c;
  1803. }
  1804. }
  1805. os << "\"";
  1806. }
  1807. std::string cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(
  1808. const std::string& p, bool useWatcomQuote)
  1809. {
  1810. // Split the path into its components.
  1811. std::vector<std::string> components;
  1812. cmSystemTools::SplitPath(p, components);
  1813. // Open the quoted result.
  1814. std::string result;
  1815. if (useWatcomQuote) {
  1816. #if defined(_WIN32) && !defined(__CYGWIN__)
  1817. result = "'";
  1818. #else
  1819. result = "\"'";
  1820. #endif
  1821. } else {
  1822. result = "\"";
  1823. }
  1824. // Return an empty path if there are no components.
  1825. if (!components.empty()) {
  1826. // Choose a slash direction and fix root component.
  1827. const char* slash = "/";
  1828. #if defined(_WIN32) && !defined(__CYGWIN__)
  1829. if (!cmSystemTools::GetForceUnixPaths()) {
  1830. slash = "\\";
  1831. for (char& i : components[0]) {
  1832. if (i == '/') {
  1833. i = '\\';
  1834. }
  1835. }
  1836. }
  1837. #endif
  1838. // Begin the quoted result with the root component.
  1839. result += components[0];
  1840. if (components.size() > 1) {
  1841. // Now add the rest of the components separated by the proper slash
  1842. // direction for this platform.
  1843. std::vector<std::string>::const_iterator compEnd = std::remove(
  1844. components.begin() + 1, components.end() - 1, std::string());
  1845. std::vector<std::string>::const_iterator compStart =
  1846. components.begin() + 1;
  1847. result += cmJoin(cmMakeRange(compStart, compEnd), slash);
  1848. // Only the last component can be empty to avoid double slashes.
  1849. result += slash;
  1850. result += components.back();
  1851. }
  1852. }
  1853. // Close the quoted result.
  1854. if (useWatcomQuote) {
  1855. #if defined(_WIN32) && !defined(__CYGWIN__)
  1856. result += "'";
  1857. #else
  1858. result += "'\"";
  1859. #endif
  1860. } else {
  1861. result += "\"";
  1862. }
  1863. return result;
  1864. }
  1865. std::string cmLocalUnixMakefileGenerator3::GetTargetDirectory(
  1866. cmGeneratorTarget const* target) const
  1867. {
  1868. std::string dir = cmStrCat("CMakeFiles/", target->GetName());
  1869. #if defined(__VMS)
  1870. dir += "_dir";
  1871. #else
  1872. dir += ".dir";
  1873. #endif
  1874. return dir;
  1875. }
  1876. cmLocalUnixMakefileGenerator3::ImplicitDependLanguageMap const&
  1877. cmLocalUnixMakefileGenerator3::GetImplicitDepends(const cmGeneratorTarget* tgt)
  1878. {
  1879. return this->ImplicitDepends[tgt->GetName()];
  1880. }
  1881. void cmLocalUnixMakefileGenerator3::AddImplicitDepends(
  1882. const cmGeneratorTarget* tgt, const std::string& lang,
  1883. const std::string& obj, const std::string& src)
  1884. {
  1885. this->ImplicitDepends[tgt->GetName()][lang][obj].push_back(src);
  1886. }
  1887. void cmLocalUnixMakefileGenerator3::CreateCDCommand(
  1888. std::vector<std::string>& commands, std::string const& tgtDir,
  1889. std::string const& relDir)
  1890. {
  1891. // do we need to cd?
  1892. if (tgtDir == relDir) {
  1893. return;
  1894. }
  1895. // In a Windows shell we must change drive letter too. The shell
  1896. // used by NMake and Borland make does not support "cd /d" so this
  1897. // feature simply cannot work with them (Borland make does not even
  1898. // support changing the drive letter with just "d:").
  1899. const char* cd_cmd = this->IsMinGWMake() ? "cd /d " : "cd ";
  1900. cmGlobalUnixMakefileGenerator3* gg =
  1901. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1902. if (!gg->UnixCD) {
  1903. // On Windows we must perform each step separately and then change
  1904. // back because the shell keeps the working directory between
  1905. // commands.
  1906. std::string cmd =
  1907. cmStrCat(cd_cmd, this->ConvertToOutputForExisting(tgtDir));
  1908. commands.insert(commands.begin(), cmd);
  1909. // Change back to the starting directory.
  1910. cmd = cmStrCat(cd_cmd, this->ConvertToOutputForExisting(relDir));
  1911. commands.push_back(std::move(cmd));
  1912. } else {
  1913. // On UNIX we must construct a single shell command to change
  1914. // directory and build because make resets the directory between
  1915. // each command.
  1916. std::string outputForExisting = this->ConvertToOutputForExisting(tgtDir);
  1917. std::string prefix = cd_cmd + outputForExisting + " && ";
  1918. std::transform(commands.begin(), commands.end(), commands.begin(),
  1919. [&prefix](std::string const& s) { return prefix + s; });
  1920. }
  1921. }