cmLocalUnixMakefileGenerator3.cxx 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103
  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 <algorithm>
  5. #include <cstdio>
  6. #include <sstream>
  7. #include <utility>
  8. #include <cm/memory>
  9. #include "cmsys/FStream.hxx"
  10. #include "cmsys/Terminal.h"
  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 (const auto& target : this->GetGeneratorTargets()) {
  113. if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  114. continue;
  115. }
  116. std::unique_ptr<cmMakefileTargetGenerator> tg(
  117. cmMakefileTargetGenerator::New(target.get()));
  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 (const auto& gt : this->GetGeneratorTargets()) {
  145. if (gt->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  146. continue;
  147. }
  148. std::vector<cmSourceFile const*> objectSources;
  149. gt->GetObjectSources(objectSources, this->ConfigName);
  150. // Compute full path to object file directory for this target.
  151. std::string dir = cmStrCat(gt->LocalGenerator->GetCurrentBinaryDirectory(),
  152. '/', this->GetTargetDirectory(gt.get()), '/');
  153. // Compute the name of each object file.
  154. for (cmSourceFile const* sf : objectSources) {
  155. bool hasSourceExtension = true;
  156. std::string objectName =
  157. this->GetObjectFileNameWithoutTarget(*sf, dir, &hasSourceExtension);
  158. if (cmSystemTools::FileIsFullPath(objectName)) {
  159. objectName = cmSystemTools::GetFilenameName(objectName);
  160. }
  161. LocalObjectInfo& info = localObjectFiles[objectName];
  162. info.HasSourceExtension = hasSourceExtension;
  163. info.emplace_back(gt.get(), sf->GetLanguage());
  164. }
  165. }
  166. }
  167. void cmLocalUnixMakefileGenerator3::GetIndividualFileTargets(
  168. std::vector<std::string>& targets)
  169. {
  170. std::map<std::string, LocalObjectInfo> localObjectFiles;
  171. this->GetLocalObjectFiles(localObjectFiles);
  172. for (auto const& localObjectFile : localObjectFiles) {
  173. targets.push_back(localObjectFile.first);
  174. std::string::size_type dot_pos = localObjectFile.first.rfind(".");
  175. std::string base = localObjectFile.first.substr(0, dot_pos);
  176. if (localObjectFile.second.HasPreprocessRule) {
  177. targets.push_back(base + ".i");
  178. }
  179. if (localObjectFile.second.HasAssembleRule) {
  180. targets.push_back(base + ".s");
  181. }
  182. }
  183. }
  184. void cmLocalUnixMakefileGenerator3::WriteLocalMakefile()
  185. {
  186. // generate the includes
  187. std::string ruleFileName = "Makefile";
  188. // Open the rule file. This should be copy-if-different because the
  189. // rules may depend on this file itself.
  190. std::string ruleFileNameFull = this->ConvertToFullPath(ruleFileName);
  191. cmGeneratedFileStream ruleFileStream(
  192. ruleFileNameFull, false, this->GlobalGenerator->GetMakefileEncoding());
  193. if (!ruleFileStream) {
  194. return;
  195. }
  196. // always write the top makefile
  197. if (!this->IsRootMakefile()) {
  198. ruleFileStream.SetCopyIfDifferent(true);
  199. }
  200. // write the all rules
  201. this->WriteLocalAllRules(ruleFileStream);
  202. // only write local targets unless at the top Keep track of targets already
  203. // listed.
  204. std::set<std::string> emittedTargets;
  205. if (!this->IsRootMakefile()) {
  206. // write our targets, and while doing it collect up the object
  207. // file rules
  208. this->WriteLocalMakefileTargets(ruleFileStream, emittedTargets);
  209. } else {
  210. cmGlobalUnixMakefileGenerator3* gg =
  211. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  212. gg->WriteConvenienceRules(ruleFileStream, emittedTargets);
  213. }
  214. bool do_preprocess_rules = this->GetCreatePreprocessedSourceRules();
  215. bool do_assembly_rules = this->GetCreateAssemblySourceRules();
  216. std::map<std::string, LocalObjectInfo> localObjectFiles;
  217. this->GetLocalObjectFiles(localObjectFiles);
  218. // now write out the object rules
  219. // for each object file name
  220. for (auto& localObjectFile : localObjectFiles) {
  221. // Add a convenience rule for building the object file.
  222. this->WriteObjectConvenienceRule(
  223. ruleFileStream, "target to build an object file", localObjectFile.first,
  224. localObjectFile.second);
  225. // Check whether preprocessing and assembly rules make sense.
  226. // They make sense only for C and C++ sources.
  227. bool lang_has_preprocessor = false;
  228. bool lang_has_assembly = false;
  229. for (LocalObjectEntry const& entry : localObjectFile.second) {
  230. if (entry.Language == "C" || entry.Language == "CXX" ||
  231. entry.Language == "CUDA" || entry.Language == "Fortran") {
  232. // Right now, C, C++, Fortran and CUDA have both a preprocessor and the
  233. // ability to generate assembly code
  234. lang_has_preprocessor = true;
  235. lang_has_assembly = true;
  236. break;
  237. }
  238. }
  239. // Add convenience rules for preprocessed and assembly files.
  240. if (lang_has_preprocessor && do_preprocess_rules) {
  241. std::string::size_type dot_pos = localObjectFile.first.rfind(".");
  242. std::string base = localObjectFile.first.substr(0, dot_pos);
  243. this->WriteObjectConvenienceRule(ruleFileStream,
  244. "target to preprocess a source file",
  245. (base + ".i"), localObjectFile.second);
  246. localObjectFile.second.HasPreprocessRule = true;
  247. }
  248. if (lang_has_assembly && do_assembly_rules) {
  249. std::string::size_type dot_pos = localObjectFile.first.rfind(".");
  250. std::string base = localObjectFile.first.substr(0, dot_pos);
  251. this->WriteObjectConvenienceRule(
  252. ruleFileStream, "target to generate assembly for a file",
  253. (base + ".s"), localObjectFile.second);
  254. localObjectFile.second.HasAssembleRule = true;
  255. }
  256. }
  257. // add a help target as long as there isn;t a real target named help
  258. if (emittedTargets.insert("help").second) {
  259. cmGlobalUnixMakefileGenerator3* gg =
  260. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  261. gg->WriteHelpRule(ruleFileStream, this);
  262. }
  263. this->WriteSpecialTargetsBottom(ruleFileStream);
  264. }
  265. void cmLocalUnixMakefileGenerator3::WriteObjectConvenienceRule(
  266. std::ostream& ruleFileStream, const char* comment, const std::string& output,
  267. LocalObjectInfo const& info)
  268. {
  269. // If the rule includes the source file extension then create a
  270. // version that has the extension removed. The help should include
  271. // only the version without source extension.
  272. bool inHelp = true;
  273. if (info.HasSourceExtension) {
  274. // Remove the last extension. This should be kept.
  275. std::string outBase1 = output;
  276. std::string outExt1 = cmSplitExtension(outBase1, outBase1);
  277. // Now remove the source extension and put back the last
  278. // extension.
  279. std::string outNoExt;
  280. cmSplitExtension(outBase1, outNoExt);
  281. outNoExt += outExt1;
  282. // Add a rule to drive the rule below.
  283. std::vector<std::string> depends;
  284. depends.emplace_back(output);
  285. std::vector<std::string> no_commands;
  286. this->WriteMakeRule(ruleFileStream, nullptr, outNoExt, depends,
  287. no_commands, true, true);
  288. inHelp = false;
  289. }
  290. // Recursively make the rule for each target using the object file.
  291. std::vector<std::string> commands;
  292. for (LocalObjectEntry const& t : info) {
  293. std::string tgtMakefileName = this->GetRelativeTargetDirectory(t.Target);
  294. std::string targetName = tgtMakefileName;
  295. tgtMakefileName += "/build.make";
  296. targetName += "/";
  297. targetName += output;
  298. commands.push_back(
  299. this->GetRecursiveMakeCall(tgtMakefileName, targetName));
  300. }
  301. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  302. this->GetCurrentBinaryDirectory());
  303. // Write the rule to the makefile.
  304. std::vector<std::string> no_depends;
  305. this->WriteMakeRule(ruleFileStream, comment, output, no_depends, commands,
  306. true, inHelp);
  307. }
  308. void cmLocalUnixMakefileGenerator3::WriteLocalMakefileTargets(
  309. std::ostream& ruleFileStream, std::set<std::string>& emitted)
  310. {
  311. std::vector<std::string> depends;
  312. std::vector<std::string> commands;
  313. // for each target we just provide a rule to cd up to the top and do a make
  314. // on the target
  315. std::string localName;
  316. for (const auto& target : this->GetGeneratorTargets()) {
  317. if ((target->GetType() == cmStateEnums::EXECUTABLE) ||
  318. (target->GetType() == cmStateEnums::STATIC_LIBRARY) ||
  319. (target->GetType() == cmStateEnums::SHARED_LIBRARY) ||
  320. (target->GetType() == cmStateEnums::MODULE_LIBRARY) ||
  321. (target->GetType() == cmStateEnums::OBJECT_LIBRARY) ||
  322. (target->GetType() == cmStateEnums::UTILITY)) {
  323. emitted.insert(target->GetName());
  324. // for subdirs add a rule to build this specific target by name.
  325. localName =
  326. cmStrCat(this->GetRelativeTargetDirectory(target.get()), "/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 = cmStrCat(
  345. this->GetRelativeTargetDirectory(target.get()), "/build.make");
  346. // make sure the makefile name is suitable for a makefile
  347. std::string makeTargetName =
  348. cmStrCat(this->GetRelativeTargetDirectory(target.get()), "/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 = cmStrCat(
  362. this->GetRelativeTargetDirectory(target.get()), "/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 rm -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 const* target) const
  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. cmExpandList(cmGeneratorExpression::Evaluate(
  990. prop_value, this,
  991. this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE")),
  992. cleanFiles);
  993. }
  994. if (cleanFiles.empty()) {
  995. return;
  996. }
  997. const auto& rootLG = this->GetGlobalGenerator()->GetLocalGenerators().at(0);
  998. std::string const& binaryDir = rootLG->GetCurrentBinaryDirectory();
  999. std::string const& currentBinaryDir = this->GetCurrentBinaryDirectory();
  1000. std::string cleanfile =
  1001. cmStrCat(currentBinaryDir, "/CMakeFiles/cmake_directory_clean.cmake");
  1002. // Write clean script
  1003. {
  1004. std::string cleanfilePath = cmSystemTools::CollapseFullPath(cleanfile);
  1005. cmsys::ofstream fout(cleanfilePath.c_str());
  1006. if (!fout) {
  1007. cmSystemTools::Error("Could not create " + cleanfilePath);
  1008. return;
  1009. }
  1010. fout << "file(REMOVE_RECURSE\n";
  1011. for (std::string const& cfl : cleanFiles) {
  1012. std::string fc = rootLG->MaybeConvertToRelativePath(
  1013. binaryDir, cmSystemTools::CollapseFullPath(cfl, currentBinaryDir));
  1014. fout << " " << cmOutputConverter::EscapeForCMake(fc) << "\n";
  1015. }
  1016. fout << ")\n";
  1017. }
  1018. // Create command
  1019. {
  1020. std::string remove =
  1021. cmStrCat("$(CMAKE_COMMAND) -P ",
  1022. this->ConvertToOutputFormat(
  1023. rootLG->MaybeConvertToRelativePath(binaryDir, cleanfile),
  1024. cmOutputConverter::SHELL));
  1025. commands.push_back(std::move(remove));
  1026. }
  1027. }
  1028. void cmLocalUnixMakefileGenerator3::AppendEcho(
  1029. std::vector<std::string>& commands, std::string const& text, EchoColor color,
  1030. EchoProgress const* progress)
  1031. {
  1032. // Choose the color for the text.
  1033. std::string color_name;
  1034. if (this->GlobalGenerator->GetToolSupportsColor() && this->ColorMakefile) {
  1035. // See cmake::ExecuteEchoColor in cmake.cxx for these options.
  1036. // This color set is readable on both black and white backgrounds.
  1037. switch (color) {
  1038. case EchoNormal:
  1039. break;
  1040. case EchoDepend:
  1041. color_name = "--magenta --bold ";
  1042. break;
  1043. case EchoBuild:
  1044. color_name = "--green ";
  1045. break;
  1046. case EchoLink:
  1047. color_name = "--green --bold ";
  1048. break;
  1049. case EchoGenerate:
  1050. color_name = "--blue --bold ";
  1051. break;
  1052. case EchoGlobal:
  1053. color_name = "--cyan ";
  1054. break;
  1055. }
  1056. }
  1057. // Echo one line at a time.
  1058. std::string line;
  1059. line.reserve(200);
  1060. for (const char* c = text.c_str();; ++c) {
  1061. if (*c == '\n' || *c == '\0') {
  1062. // Avoid writing a blank last line on end-of-string.
  1063. if (*c != '\0' || !line.empty()) {
  1064. // Add a command to echo this line.
  1065. std::string cmd;
  1066. if (color_name.empty() && !progress) {
  1067. // Use the native echo command.
  1068. cmd = cmStrCat("@echo ", this->EscapeForShell(line, false, true));
  1069. } else {
  1070. // Use cmake to echo the text in color.
  1071. cmd = cmStrCat(
  1072. "@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) ",
  1073. color_name);
  1074. if (progress) {
  1075. cmd += "--progress-dir=";
  1076. cmd += this->ConvertToOutputFormat(
  1077. cmSystemTools::CollapseFullPath(progress->Dir),
  1078. cmOutputConverter::SHELL);
  1079. cmd += " ";
  1080. cmd += "--progress-num=";
  1081. cmd += progress->Arg;
  1082. cmd += " ";
  1083. }
  1084. cmd += this->EscapeForShell(line);
  1085. }
  1086. commands.push_back(std::move(cmd));
  1087. }
  1088. // Reset the line to empty.
  1089. line.clear();
  1090. // Progress appears only on first line.
  1091. progress = nullptr;
  1092. // Terminate on end-of-string.
  1093. if (*c == '\0') {
  1094. return;
  1095. }
  1096. } else if (*c != '\r') {
  1097. // Append this character to the current line.
  1098. line += *c;
  1099. }
  1100. }
  1101. }
  1102. std::string cmLocalUnixMakefileGenerator3::CreateMakeVariable(
  1103. std::string const& s, std::string const& s2)
  1104. {
  1105. std::string unmodified = cmStrCat(s, s2);
  1106. // if there is no restriction on the length of make variables
  1107. // and there are no "." characters in the string, then return the
  1108. // unmodified combination.
  1109. if ((!this->MakefileVariableSize &&
  1110. unmodified.find('.') == std::string::npos) &&
  1111. (!this->MakefileVariableSize &&
  1112. unmodified.find('+') == std::string::npos) &&
  1113. (!this->MakefileVariableSize &&
  1114. unmodified.find('-') == std::string::npos)) {
  1115. return unmodified;
  1116. }
  1117. // see if the variable has been defined before and return
  1118. // the modified version of the variable
  1119. auto i = this->MakeVariableMap.find(unmodified);
  1120. if (i != this->MakeVariableMap.end()) {
  1121. return i->second;
  1122. }
  1123. // start with the unmodified variable
  1124. std::string ret = unmodified;
  1125. // if this there is no value for this->MakefileVariableSize then
  1126. // the string must have bad characters in it
  1127. if (!this->MakefileVariableSize) {
  1128. std::replace(ret.begin(), ret.end(), '.', '_');
  1129. cmSystemTools::ReplaceString(ret, "-", "__");
  1130. cmSystemTools::ReplaceString(ret, "+", "___");
  1131. int ni = 0;
  1132. char buffer[5];
  1133. // make sure the _ version is not already used, if
  1134. // it is used then add number to the end of the variable
  1135. while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
  1136. ++ni;
  1137. sprintf(buffer, "%04d", ni);
  1138. ret = unmodified + buffer;
  1139. }
  1140. this->ShortMakeVariableMap[ret] = "1";
  1141. this->MakeVariableMap[unmodified] = ret;
  1142. return ret;
  1143. }
  1144. // if the string is greater than 32 chars it is an invalid variable name
  1145. // for borland make
  1146. if (static_cast<int>(ret.size()) > this->MakefileVariableSize) {
  1147. int keep = this->MakefileVariableSize - 8;
  1148. int size = keep + 3;
  1149. std::string str1 = s;
  1150. std::string str2 = s2;
  1151. // we must shorten the combined string by 4 characters
  1152. // keep no more than 24 characters from the second string
  1153. if (static_cast<int>(str2.size()) > keep) {
  1154. str2 = str2.substr(0, keep);
  1155. }
  1156. if (static_cast<int>(str1.size()) + static_cast<int>(str2.size()) > size) {
  1157. str1 = str1.substr(0, size - str2.size());
  1158. }
  1159. char buffer[5];
  1160. int ni = 0;
  1161. sprintf(buffer, "%04d", ni);
  1162. ret = str1 + str2 + buffer;
  1163. while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
  1164. ++ni;
  1165. sprintf(buffer, "%04d", ni);
  1166. ret = str1 + str2 + buffer;
  1167. }
  1168. if (ni == 1000) {
  1169. cmSystemTools::Error("Borland makefile variable length too long");
  1170. return unmodified;
  1171. }
  1172. // once an unused variable is found
  1173. this->ShortMakeVariableMap[ret] = "1";
  1174. }
  1175. // always make an entry into the unmodified to variable map
  1176. this->MakeVariableMap[unmodified] = ret;
  1177. return ret;
  1178. }
  1179. bool cmLocalUnixMakefileGenerator3::UpdateDependencies(
  1180. const std::string& tgtInfo, bool verbose, bool color)
  1181. {
  1182. // read in the target info file
  1183. if (!this->Makefile->ReadListFile(tgtInfo) ||
  1184. cmSystemTools::GetErrorOccuredFlag()) {
  1185. cmSystemTools::Error("Target DependInfo.cmake file not found");
  1186. }
  1187. // Check if any multiple output pairs have a missing file.
  1188. this->CheckMultipleOutputs(verbose);
  1189. std::string const targetDir = cmSystemTools::GetFilenamePath(tgtInfo);
  1190. std::string const internalDependFile = targetDir + "/depend.internal";
  1191. std::string const dependFile = targetDir + "/depend.make";
  1192. // If the target DependInfo.cmake file has changed since the last
  1193. // time dependencies were scanned then force rescanning. This may
  1194. // happen when a new source file is added and CMake regenerates the
  1195. // project but no other sources were touched.
  1196. bool needRescanDependInfo = false;
  1197. cmFileTimeCache* ftc =
  1198. this->GlobalGenerator->GetCMakeInstance()->GetFileTimeCache();
  1199. {
  1200. int result;
  1201. if (!ftc->Compare(internalDependFile, tgtInfo, &result) || result < 0) {
  1202. if (verbose) {
  1203. std::ostringstream msg;
  1204. msg << "Dependee \"" << tgtInfo << "\" is newer than depender \""
  1205. << internalDependFile << "\"." << std::endl;
  1206. cmSystemTools::Stdout(msg.str());
  1207. }
  1208. needRescanDependInfo = true;
  1209. }
  1210. }
  1211. // If the directory information is newer than depend.internal, include dirs
  1212. // may have changed. In this case discard all old dependencies.
  1213. bool needRescanDirInfo = false;
  1214. {
  1215. std::string dirInfoFile =
  1216. cmStrCat(this->GetCurrentBinaryDirectory(),
  1217. "/CMakeFiles/CMakeDirectoryInformation.cmake");
  1218. int result;
  1219. if (!ftc->Compare(internalDependFile, dirInfoFile, &result) ||
  1220. result < 0) {
  1221. if (verbose) {
  1222. std::ostringstream msg;
  1223. msg << "Dependee \"" << dirInfoFile << "\" is newer than depender \""
  1224. << internalDependFile << "\"." << std::endl;
  1225. cmSystemTools::Stdout(msg.str());
  1226. }
  1227. needRescanDirInfo = true;
  1228. }
  1229. }
  1230. // Check the implicit dependencies to see if they are up to date.
  1231. // The build.make file may have explicit dependencies for the object
  1232. // files but these will not affect the scanning process so they need
  1233. // not be considered.
  1234. cmDepends::DependencyMap validDependencies;
  1235. bool needRescanDependencies = false;
  1236. if (!needRescanDirInfo) {
  1237. cmDependsC checker;
  1238. checker.SetVerbose(verbose);
  1239. checker.SetFileTimeCache(ftc);
  1240. // cmDependsC::Check() fills the vector validDependencies() with the
  1241. // dependencies for those files where they are still valid, i.e. neither
  1242. // the files themselves nor any files they depend on have changed.
  1243. // We don't do that if the CMakeDirectoryInformation.cmake file has
  1244. // changed, because then potentially all dependencies have changed.
  1245. // This information is given later on to cmDependsC, which then only
  1246. // rescans the files where it did not get valid dependencies via this
  1247. // dependency vector. This means that in the normal case, when only
  1248. // few or one file have been edited, then also only this one file is
  1249. // actually scanned again, instead of all files for this target.
  1250. needRescanDependencies =
  1251. !checker.Check(dependFile, internalDependFile, validDependencies);
  1252. }
  1253. if (needRescanDependInfo || needRescanDirInfo || needRescanDependencies) {
  1254. // The dependencies must be regenerated.
  1255. std::string targetName = cmSystemTools::GetFilenameName(targetDir);
  1256. targetName = targetName.substr(0, targetName.length() - 4);
  1257. std::string message =
  1258. cmStrCat("Scanning dependencies of target ", targetName);
  1259. cmSystemTools::MakefileColorEcho(cmsysTerminal_Color_ForegroundMagenta |
  1260. cmsysTerminal_Color_ForegroundBold,
  1261. message.c_str(), true, color);
  1262. return this->ScanDependencies(targetDir, dependFile, internalDependFile,
  1263. validDependencies);
  1264. }
  1265. // The dependencies are already up-to-date.
  1266. return true;
  1267. }
  1268. bool cmLocalUnixMakefileGenerator3::ScanDependencies(
  1269. std::string const& targetDir, std::string const& dependFile,
  1270. std::string const& internalDependFile, cmDepends::DependencyMap& validDeps)
  1271. {
  1272. // Read the directory information file.
  1273. cmMakefile* mf = this->Makefile;
  1274. bool haveDirectoryInfo = false;
  1275. {
  1276. std::string dirInfoFile =
  1277. cmStrCat(this->GetCurrentBinaryDirectory(),
  1278. "/CMakeFiles/CMakeDirectoryInformation.cmake");
  1279. if (mf->ReadListFile(dirInfoFile) &&
  1280. !cmSystemTools::GetErrorOccuredFlag()) {
  1281. haveDirectoryInfo = true;
  1282. }
  1283. }
  1284. // Lookup useful directory information.
  1285. if (haveDirectoryInfo) {
  1286. // Test whether we need to force Unix paths.
  1287. if (const char* force = mf->GetDefinition("CMAKE_FORCE_UNIX_PATHS")) {
  1288. if (!cmIsOff(force)) {
  1289. cmSystemTools::SetForceUnixPaths(true);
  1290. }
  1291. }
  1292. // Setup relative path top directories.
  1293. if (const char* relativePathTopSource =
  1294. mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_SOURCE")) {
  1295. this->StateSnapshot.GetDirectory().SetRelativePathTopSource(
  1296. relativePathTopSource);
  1297. }
  1298. if (const char* relativePathTopBinary =
  1299. mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_BINARY")) {
  1300. this->StateSnapshot.GetDirectory().SetRelativePathTopBinary(
  1301. relativePathTopBinary);
  1302. }
  1303. } else {
  1304. cmSystemTools::Error("Directory Information file not found");
  1305. }
  1306. // Open the make depends file. This should be copy-if-different
  1307. // because the make tool may try to reload it needlessly otherwise.
  1308. cmGeneratedFileStream ruleFileStream(
  1309. dependFile, false, this->GlobalGenerator->GetMakefileEncoding());
  1310. ruleFileStream.SetCopyIfDifferent(true);
  1311. if (!ruleFileStream) {
  1312. return false;
  1313. }
  1314. // Open the cmake dependency tracking file. This should not be
  1315. // copy-if-different because dependencies are re-scanned when it is
  1316. // older than the DependInfo.cmake.
  1317. cmGeneratedFileStream internalRuleFileStream(
  1318. internalDependFile, false, this->GlobalGenerator->GetMakefileEncoding());
  1319. if (!internalRuleFileStream) {
  1320. return false;
  1321. }
  1322. this->WriteDisclaimer(ruleFileStream);
  1323. this->WriteDisclaimer(internalRuleFileStream);
  1324. // for each language we need to scan, scan it
  1325. std::vector<std::string> langs =
  1326. cmExpandedList(mf->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES"));
  1327. for (std::string const& lang : langs) {
  1328. // construct the checker
  1329. // Create the scanner for this language
  1330. std::unique_ptr<cmDepends> scanner;
  1331. if (lang == "C" || lang == "CXX" || lang == "RC" || lang == "ASM" ||
  1332. lang == "CUDA") {
  1333. // TODO: Handle RC (resource files) dependencies correctly.
  1334. scanner = cm::make_unique<cmDependsC>(this, targetDir, lang, &validDeps);
  1335. }
  1336. #ifndef CMAKE_BOOTSTRAP
  1337. else if (lang == "Fortran") {
  1338. ruleFileStream << "# Note that incremental build could trigger "
  1339. << "a call to cmake_copy_f90_mod on each re-build\n";
  1340. scanner = cm::make_unique<cmDependsFortran>(this);
  1341. } else if (lang == "Java") {
  1342. scanner = cm::make_unique<cmDependsJava>();
  1343. }
  1344. #endif
  1345. if (scanner) {
  1346. scanner->SetLocalGenerator(this);
  1347. scanner->SetFileTimeCache(
  1348. this->GlobalGenerator->GetCMakeInstance()->GetFileTimeCache());
  1349. scanner->SetLanguage(lang);
  1350. scanner->SetTargetDirectory(targetDir);
  1351. scanner->Write(ruleFileStream, internalRuleFileStream);
  1352. }
  1353. }
  1354. return true;
  1355. }
  1356. void cmLocalUnixMakefileGenerator3::CheckMultipleOutputs(bool verbose)
  1357. {
  1358. cmMakefile* mf = this->Makefile;
  1359. // Get the string listing the multiple output pairs.
  1360. const char* pairs_string = mf->GetDefinition("CMAKE_MULTIPLE_OUTPUT_PAIRS");
  1361. if (!pairs_string) {
  1362. return;
  1363. }
  1364. // Convert the string to a list and preserve empty entries.
  1365. std::vector<std::string> pairs = cmExpandedList(pairs_string, true);
  1366. for (auto i = pairs.begin(); i != pairs.end() && (i + 1) != pairs.end();) {
  1367. const std::string& depender = *i++;
  1368. const std::string& dependee = *i++;
  1369. // If the depender is missing then delete the dependee to make
  1370. // sure both will be regenerated.
  1371. if (cmSystemTools::FileExists(dependee) &&
  1372. !cmSystemTools::FileExists(depender)) {
  1373. if (verbose) {
  1374. std::ostringstream msg;
  1375. msg << "Deleting primary custom command output \"" << dependee
  1376. << "\" because another output \"" << depender
  1377. << "\" does not exist." << std::endl;
  1378. cmSystemTools::Stdout(msg.str());
  1379. }
  1380. cmSystemTools::RemoveFile(dependee);
  1381. }
  1382. }
  1383. }
  1384. void cmLocalUnixMakefileGenerator3::WriteLocalAllRules(
  1385. std::ostream& ruleFileStream)
  1386. {
  1387. this->WriteDisclaimer(ruleFileStream);
  1388. // Write the main entry point target. This must be the VERY first
  1389. // target so that make with no arguments will run it.
  1390. {
  1391. // Just depend on the all target to drive the build.
  1392. std::vector<std::string> depends;
  1393. std::vector<std::string> no_commands;
  1394. depends.emplace_back("all");
  1395. // Write the rule.
  1396. this->WriteMakeRule(ruleFileStream,
  1397. "Default target executed when no arguments are "
  1398. "given to make.",
  1399. "default_target", depends, no_commands, true);
  1400. // Help out users that try "gmake target1 target2 -j".
  1401. cmGlobalUnixMakefileGenerator3* gg =
  1402. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1403. if (gg->AllowNotParallel()) {
  1404. std::vector<std::string> no_depends;
  1405. this->WriteMakeRule(ruleFileStream,
  1406. "Allow only one \"make -f "
  1407. "Makefile2\" at a time, but pass "
  1408. "parallelism.",
  1409. ".NOTPARALLEL", no_depends, no_commands, false);
  1410. }
  1411. }
  1412. this->WriteSpecialTargetsTop(ruleFileStream);
  1413. // Include the progress variables for the target.
  1414. // Write all global targets
  1415. this->WriteDivider(ruleFileStream);
  1416. ruleFileStream << "# Targets provided globally by CMake.\n"
  1417. << "\n";
  1418. const auto& targets = this->GetGeneratorTargets();
  1419. for (const auto& gt : targets) {
  1420. if (gt->GetType() == cmStateEnums::GLOBAL_TARGET) {
  1421. std::string targetString =
  1422. "Special rule for the target " + gt->GetName();
  1423. std::vector<std::string> commands;
  1424. std::vector<std::string> depends;
  1425. const char* text = gt->GetProperty("EchoString");
  1426. if (!text) {
  1427. text = "Running external command ...";
  1428. }
  1429. depends.reserve(gt->GetUtilities().size());
  1430. for (BT<std::string> const& u : gt->GetUtilities()) {
  1431. depends.push_back(u.Value);
  1432. }
  1433. this->AppendEcho(commands, text,
  1434. cmLocalUnixMakefileGenerator3::EchoGlobal);
  1435. // Global targets store their rules in pre- and post-build commands.
  1436. this->AppendCustomDepends(depends, gt->GetPreBuildCommands());
  1437. this->AppendCustomDepends(depends, gt->GetPostBuildCommands());
  1438. this->AppendCustomCommands(commands, gt->GetPreBuildCommands(), gt.get(),
  1439. this->GetCurrentBinaryDirectory());
  1440. this->AppendCustomCommands(commands, gt->GetPostBuildCommands(),
  1441. gt.get(), this->GetCurrentBinaryDirectory());
  1442. std::string targetName = gt->GetName();
  1443. this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
  1444. depends, commands, true);
  1445. // Provide a "/fast" version of the target.
  1446. depends.clear();
  1447. if ((targetName == "install") || (targetName == "install/local") ||
  1448. (targetName == "install/strip")) {
  1449. // Provide a fast install target that does not depend on all
  1450. // but has the same command.
  1451. depends.emplace_back("preinstall/fast");
  1452. } else {
  1453. // Just forward to the real target so at least it will work.
  1454. depends.push_back(targetName);
  1455. commands.clear();
  1456. }
  1457. targetName += "/fast";
  1458. this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
  1459. depends, commands, true);
  1460. }
  1461. }
  1462. std::vector<std::string> depends;
  1463. std::vector<std::string> commands;
  1464. // Write the all rule.
  1465. std::string recursiveTarget =
  1466. cmStrCat(this->GetCurrentBinaryDirectory(), "/all");
  1467. bool regenerate =
  1468. !this->GlobalGenerator->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION");
  1469. if (regenerate) {
  1470. depends.emplace_back("cmake_check_build_system");
  1471. }
  1472. std::string progressDir =
  1473. cmStrCat(this->GetBinaryDirectory(), "/CMakeFiles");
  1474. {
  1475. std::ostringstream progCmd;
  1476. progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start ";
  1477. progCmd << this->ConvertToOutputFormat(
  1478. cmSystemTools::CollapseFullPath(progressDir), cmOutputConverter::SHELL);
  1479. std::string progressFile = "/CMakeFiles/progress.marks";
  1480. std::string progressFileNameFull = this->ConvertToFullPath(progressFile);
  1481. progCmd << " "
  1482. << this->ConvertToOutputFormat(
  1483. cmSystemTools::CollapseFullPath(progressFileNameFull),
  1484. cmOutputConverter::SHELL);
  1485. commands.push_back(progCmd.str());
  1486. }
  1487. std::string mf2Dir = "CMakeFiles/Makefile2";
  1488. commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
  1489. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1490. this->GetCurrentBinaryDirectory());
  1491. {
  1492. std::ostringstream progCmd;
  1493. progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; // # 0
  1494. progCmd << this->ConvertToOutputFormat(
  1495. cmSystemTools::CollapseFullPath(progressDir), cmOutputConverter::SHELL);
  1496. progCmd << " 0";
  1497. commands.push_back(progCmd.str());
  1498. }
  1499. this->WriteMakeRule(ruleFileStream, "The main all target", "all", depends,
  1500. commands, true);
  1501. // Write the clean rule.
  1502. recursiveTarget = cmStrCat(this->GetCurrentBinaryDirectory(), "/clean");
  1503. commands.clear();
  1504. depends.clear();
  1505. commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
  1506. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1507. this->GetCurrentBinaryDirectory());
  1508. this->WriteMakeRule(ruleFileStream, "The main clean target", "clean",
  1509. depends, commands, true);
  1510. commands.clear();
  1511. depends.clear();
  1512. depends.emplace_back("clean");
  1513. this->WriteMakeRule(ruleFileStream, "The main clean target", "clean/fast",
  1514. depends, commands, true);
  1515. // Write the preinstall rule.
  1516. recursiveTarget = cmStrCat(this->GetCurrentBinaryDirectory(), "/preinstall");
  1517. commands.clear();
  1518. depends.clear();
  1519. const char* noall =
  1520. this->Makefile->GetDefinition("CMAKE_SKIP_INSTALL_ALL_DEPENDENCY");
  1521. if (!noall || cmIsOff(noall)) {
  1522. // Drive the build before installing.
  1523. depends.emplace_back("all");
  1524. } else if (regenerate) {
  1525. // At least make sure the build system is up to date.
  1526. depends.emplace_back("cmake_check_build_system");
  1527. }
  1528. commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
  1529. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1530. this->GetCurrentBinaryDirectory());
  1531. this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
  1532. "preinstall", depends, commands, true);
  1533. depends.clear();
  1534. this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
  1535. "preinstall/fast", depends, commands, true);
  1536. if (regenerate) {
  1537. // write the depend rule, really a recompute depends rule
  1538. depends.clear();
  1539. commands.clear();
  1540. cmake* cm = this->GlobalGenerator->GetCMakeInstance();
  1541. if (cm->DoWriteGlobVerifyTarget()) {
  1542. std::string rescanRule =
  1543. cmStrCat("$(CMAKE_COMMAND) -P ",
  1544. this->ConvertToOutputFormat(cm->GetGlobVerifyScript(),
  1545. cmOutputConverter::SHELL));
  1546. commands.push_back(rescanRule);
  1547. }
  1548. std::string cmakefileName = "CMakeFiles/Makefile.cmake";
  1549. {
  1550. std::string runRule = cmStrCat(
  1551. "$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) "
  1552. "--check-build-system ",
  1553. this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL),
  1554. " 1");
  1555. commands.push_back(std::move(runRule));
  1556. }
  1557. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1558. this->GetCurrentBinaryDirectory());
  1559. this->WriteMakeRule(ruleFileStream, "clear depends", "depend", depends,
  1560. commands, true);
  1561. }
  1562. }
  1563. void cmLocalUnixMakefileGenerator3::ClearDependencies(cmMakefile* mf,
  1564. bool verbose)
  1565. {
  1566. // Get the list of target files to check
  1567. const char* infoDef = mf->GetDefinition("CMAKE_DEPEND_INFO_FILES");
  1568. if (!infoDef) {
  1569. return;
  1570. }
  1571. std::vector<std::string> files = cmExpandedList(infoDef);
  1572. // Each depend information file corresponds to a target. Clear the
  1573. // dependencies for that target.
  1574. cmDepends clearer;
  1575. clearer.SetVerbose(verbose);
  1576. for (std::string const& file : files) {
  1577. std::string dir = cmSystemTools::GetFilenamePath(file);
  1578. // Clear the implicit dependency makefile.
  1579. std::string dependFile = dir + "/depend.make";
  1580. clearer.Clear(dependFile);
  1581. // Remove the internal dependency check file to force
  1582. // regeneration.
  1583. std::string internalDependFile = dir + "/depend.internal";
  1584. cmSystemTools::RemoveFile(internalDependFile);
  1585. }
  1586. }
  1587. namespace {
  1588. // Helper predicate for removing absolute paths that don't point to the
  1589. // source or binary directory. It is used when CMAKE_DEPENDS_IN_PROJECT_ONLY
  1590. // is set ON, to only consider in-project dependencies during the build.
  1591. class NotInProjectDir
  1592. {
  1593. public:
  1594. // Constructor with the source and binary directory's path
  1595. NotInProjectDir(std::string sourceDir, std::string binaryDir)
  1596. : SourceDir(std::move(sourceDir))
  1597. , BinaryDir(std::move(binaryDir))
  1598. {
  1599. }
  1600. // Operator evaluating the predicate
  1601. bool operator()(const std::string& path) const
  1602. {
  1603. // Keep all relative paths:
  1604. if (!cmSystemTools::FileIsFullPath(path)) {
  1605. return false;
  1606. }
  1607. // If it's an absolute path, check if it starts with the source
  1608. // direcotory:
  1609. return (
  1610. !(IsInDirectory(SourceDir, path) || IsInDirectory(BinaryDir, path)));
  1611. }
  1612. private:
  1613. // Helper function used by the predicate
  1614. static bool IsInDirectory(const std::string& baseDir,
  1615. const std::string& testDir)
  1616. {
  1617. // First check if the test directory "starts with" the base directory:
  1618. if (testDir.find(baseDir) != 0) {
  1619. return false;
  1620. }
  1621. // If it does, then check that it's either the same string, or that the
  1622. // next character is a slash:
  1623. return ((testDir.size() == baseDir.size()) ||
  1624. (testDir[baseDir.size()] == '/'));
  1625. }
  1626. // The path to the source directory
  1627. std::string SourceDir;
  1628. // The path to the binary directory
  1629. std::string BinaryDir;
  1630. };
  1631. }
  1632. void cmLocalUnixMakefileGenerator3::WriteDependLanguageInfo(
  1633. std::ostream& cmakefileStream, cmGeneratorTarget* target)
  1634. {
  1635. ImplicitDependLanguageMap const& implicitLangs =
  1636. this->GetImplicitDepends(target);
  1637. // list the languages
  1638. cmakefileStream
  1639. << "# The set of languages for which implicit dependencies are needed:\n";
  1640. cmakefileStream << "set(CMAKE_DEPENDS_LANGUAGES\n";
  1641. for (auto const& implicitLang : implicitLangs) {
  1642. cmakefileStream << " \"" << implicitLang.first << "\"\n";
  1643. }
  1644. cmakefileStream << " )\n";
  1645. // now list the files for each language
  1646. cmakefileStream
  1647. << "# The set of files for implicit dependencies of each language:\n";
  1648. for (auto const& implicitLang : implicitLangs) {
  1649. cmakefileStream << "set(CMAKE_DEPENDS_CHECK_" << implicitLang.first
  1650. << "\n";
  1651. ImplicitDependFileMap const& implicitPairs = implicitLang.second;
  1652. // for each file pair
  1653. for (auto const& implicitPair : implicitPairs) {
  1654. for (auto const& di : implicitPair.second) {
  1655. cmakefileStream << " \"" << di << "\" ";
  1656. cmakefileStream << "\"" << implicitPair.first << "\"\n";
  1657. }
  1658. }
  1659. cmakefileStream << " )\n";
  1660. // Tell the dependency scanner what compiler is used.
  1661. std::string cidVar =
  1662. cmStrCat("CMAKE_", implicitLang.first, "_COMPILER_ID");
  1663. const char* cid = this->Makefile->GetDefinition(cidVar);
  1664. if (cid && *cid) {
  1665. cmakefileStream << "set(CMAKE_" << implicitLang.first
  1666. << "_COMPILER_ID \"" << cid << "\")\n";
  1667. }
  1668. if (implicitLang.first == "Fortran") {
  1669. std::string smodSep =
  1670. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_SEP");
  1671. std::string smodExt =
  1672. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_EXT");
  1673. cmakefileStream << "set(CMAKE_Fortran_SUBMODULE_SEP \"" << smodSep
  1674. << "\")\n";
  1675. cmakefileStream << "set(CMAKE_Fortran_SUBMODULE_EXT \"" << smodExt
  1676. << "\")\n";
  1677. }
  1678. // Build a list of preprocessor definitions for the target.
  1679. std::set<std::string> defines;
  1680. this->GetTargetDefines(target, this->ConfigName, implicitLang.first,
  1681. defines);
  1682. if (!defines.empty()) {
  1683. /* clang-format off */
  1684. cmakefileStream
  1685. << "\n"
  1686. << "# Preprocessor definitions for this target.\n"
  1687. << "set(CMAKE_TARGET_DEFINITIONS_" << implicitLang.first << "\n";
  1688. /* clang-format on */
  1689. for (std::string const& define : defines) {
  1690. cmakefileStream << " " << cmOutputConverter::EscapeForCMake(define)
  1691. << "\n";
  1692. }
  1693. cmakefileStream << " )\n";
  1694. }
  1695. // Target-specific include directories:
  1696. cmakefileStream << "\n"
  1697. << "# The include file search paths:\n";
  1698. cmakefileStream << "set(CMAKE_" << implicitLang.first
  1699. << "_TARGET_INCLUDE_PATH\n";
  1700. std::vector<std::string> includes;
  1701. this->GetIncludeDirectories(includes, target, implicitLang.first,
  1702. this->ConfigName);
  1703. std::string binaryDir = this->GetState()->GetBinaryDirectory();
  1704. if (this->Makefile->IsOn("CMAKE_DEPENDS_IN_PROJECT_ONLY")) {
  1705. std::string const& sourceDir = this->GetState()->GetSourceDirectory();
  1706. cmEraseIf(includes, ::NotInProjectDir(sourceDir, binaryDir));
  1707. }
  1708. for (std::string const& include : includes) {
  1709. cmakefileStream << " \""
  1710. << this->MaybeConvertToRelativePath(binaryDir, include)
  1711. << "\"\n";
  1712. }
  1713. cmakefileStream << " )\n";
  1714. }
  1715. // Store include transform rule properties. Write the directory
  1716. // rules first because they may be overridden by later target rules.
  1717. std::vector<std::string> transformRules;
  1718. if (const char* xform =
  1719. this->Makefile->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
  1720. cmExpandList(xform, transformRules);
  1721. }
  1722. if (const char* xform =
  1723. target->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
  1724. cmExpandList(xform, transformRules);
  1725. }
  1726. if (!transformRules.empty()) {
  1727. cmakefileStream << "set(CMAKE_INCLUDE_TRANSFORMS\n";
  1728. for (std::string const& tr : transformRules) {
  1729. cmakefileStream << " " << cmOutputConverter::EscapeForCMake(tr) << "\n";
  1730. }
  1731. cmakefileStream << " )\n";
  1732. }
  1733. }
  1734. void cmLocalUnixMakefileGenerator3::WriteDisclaimer(std::ostream& os)
  1735. {
  1736. os << "# CMAKE generated file: DO NOT EDIT!\n"
  1737. << "# Generated by \"" << this->GlobalGenerator->GetName() << "\""
  1738. << " Generator, CMake Version " << cmVersion::GetMajorVersion() << "."
  1739. << cmVersion::GetMinorVersion() << "\n\n";
  1740. }
  1741. std::string cmLocalUnixMakefileGenerator3::GetRecursiveMakeCall(
  1742. const std::string& makefile, const std::string& tgt)
  1743. {
  1744. // Call make on the given file.
  1745. std::string cmd = cmStrCat(
  1746. "$(MAKE) -f ",
  1747. this->ConvertToOutputFormat(makefile, cmOutputConverter::SHELL), ' ');
  1748. cmGlobalUnixMakefileGenerator3* gg =
  1749. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1750. // Pass down verbosity level.
  1751. if (!gg->MakeSilentFlag.empty()) {
  1752. cmd += gg->MakeSilentFlag;
  1753. cmd += " ";
  1754. }
  1755. // Most unix makes will pass the command line flags to make down to
  1756. // sub-invoked makes via an environment variable. However, some
  1757. // makes do not support that, so you have to pass the flags
  1758. // explicitly.
  1759. if (gg->PassMakeflags) {
  1760. cmd += "-$(MAKEFLAGS) ";
  1761. }
  1762. // Add the target.
  1763. if (!tgt.empty()) {
  1764. // The make target is always relative to the top of the build tree.
  1765. std::string tgt2 =
  1766. this->MaybeConvertToRelativePath(this->GetBinaryDirectory(), tgt);
  1767. // The target may have been written with windows paths.
  1768. cmSystemTools::ConvertToOutputSlashes(tgt2);
  1769. // Escape one extra time if the make tool requires it.
  1770. if (this->MakeCommandEscapeTargetTwice) {
  1771. tgt2 = this->EscapeForShell(tgt2, true, false);
  1772. }
  1773. // The target name is now a string that should be passed verbatim
  1774. // on the command line.
  1775. cmd += this->EscapeForShell(tgt2, true, false);
  1776. }
  1777. return cmd;
  1778. }
  1779. void cmLocalUnixMakefileGenerator3::WriteDivider(std::ostream& os)
  1780. {
  1781. os << "#======================================"
  1782. << "=======================================\n";
  1783. }
  1784. void cmLocalUnixMakefileGenerator3::WriteCMakeArgument(std::ostream& os,
  1785. const char* s)
  1786. {
  1787. // Write the given string to the stream with escaping to get it back
  1788. // into CMake through the lexical scanner.
  1789. os << "\"";
  1790. for (const char* c = s; *c; ++c) {
  1791. if (*c == '\\') {
  1792. os << "\\\\";
  1793. } else if (*c == '"') {
  1794. os << "\\\"";
  1795. } else {
  1796. os << *c;
  1797. }
  1798. }
  1799. os << "\"";
  1800. }
  1801. std::string cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(
  1802. const std::string& p, bool useWatcomQuote)
  1803. {
  1804. // Split the path into its components.
  1805. std::vector<std::string> components;
  1806. cmSystemTools::SplitPath(p, components);
  1807. // Open the quoted result.
  1808. std::string result;
  1809. if (useWatcomQuote) {
  1810. #if defined(_WIN32) && !defined(__CYGWIN__)
  1811. result = "'";
  1812. #else
  1813. result = "\"'";
  1814. #endif
  1815. } else {
  1816. result = "\"";
  1817. }
  1818. // Return an empty path if there are no components.
  1819. if (!components.empty()) {
  1820. // Choose a slash direction and fix root component.
  1821. const char* slash = "/";
  1822. #if defined(_WIN32) && !defined(__CYGWIN__)
  1823. if (!cmSystemTools::GetForceUnixPaths()) {
  1824. slash = "\\";
  1825. for (char& i : components[0]) {
  1826. if (i == '/') {
  1827. i = '\\';
  1828. }
  1829. }
  1830. }
  1831. #endif
  1832. // Begin the quoted result with the root component.
  1833. result += components[0];
  1834. if (components.size() > 1) {
  1835. // Now add the rest of the components separated by the proper slash
  1836. // direction for this platform.
  1837. auto compEnd = std::remove(components.begin() + 1, components.end() - 1,
  1838. std::string());
  1839. auto compStart = components.begin() + 1;
  1840. result += cmJoin(cmMakeRange(compStart, compEnd), slash);
  1841. // Only the last component can be empty to avoid double slashes.
  1842. result += slash;
  1843. result += components.back();
  1844. }
  1845. }
  1846. // Close the quoted result.
  1847. if (useWatcomQuote) {
  1848. #if defined(_WIN32) && !defined(__CYGWIN__)
  1849. result += "'";
  1850. #else
  1851. result += "'\"";
  1852. #endif
  1853. } else {
  1854. result += "\"";
  1855. }
  1856. return result;
  1857. }
  1858. std::string cmLocalUnixMakefileGenerator3::GetTargetDirectory(
  1859. cmGeneratorTarget const* target) const
  1860. {
  1861. std::string dir = cmStrCat("CMakeFiles/", target->GetName());
  1862. #if defined(__VMS)
  1863. dir += "_dir";
  1864. #else
  1865. dir += ".dir";
  1866. #endif
  1867. return dir;
  1868. }
  1869. cmLocalUnixMakefileGenerator3::ImplicitDependLanguageMap const&
  1870. cmLocalUnixMakefileGenerator3::GetImplicitDepends(const cmGeneratorTarget* tgt)
  1871. {
  1872. return this->ImplicitDepends[tgt->GetName()];
  1873. }
  1874. void cmLocalUnixMakefileGenerator3::AddImplicitDepends(
  1875. const cmGeneratorTarget* tgt, const std::string& lang,
  1876. const std::string& obj, const std::string& src)
  1877. {
  1878. this->ImplicitDepends[tgt->GetName()][lang][obj].push_back(src);
  1879. }
  1880. void cmLocalUnixMakefileGenerator3::CreateCDCommand(
  1881. std::vector<std::string>& commands, std::string const& tgtDir,
  1882. std::string const& relDir)
  1883. {
  1884. // do we need to cd?
  1885. if (tgtDir == relDir) {
  1886. return;
  1887. }
  1888. // In a Windows shell we must change drive letter too. The shell
  1889. // used by NMake and Borland make does not support "cd /d" so this
  1890. // feature simply cannot work with them (Borland make does not even
  1891. // support changing the drive letter with just "d:").
  1892. const char* cd_cmd = this->IsMinGWMake() ? "cd /d " : "cd ";
  1893. cmGlobalUnixMakefileGenerator3* gg =
  1894. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1895. if (!gg->UnixCD) {
  1896. // On Windows we must perform each step separately and then change
  1897. // back because the shell keeps the working directory between
  1898. // commands.
  1899. std::string cmd =
  1900. cmStrCat(cd_cmd, this->ConvertToOutputForExisting(tgtDir));
  1901. commands.insert(commands.begin(), cmd);
  1902. // Change back to the starting directory.
  1903. cmd = cmStrCat(cd_cmd, this->ConvertToOutputForExisting(relDir));
  1904. commands.push_back(std::move(cmd));
  1905. } else {
  1906. // On UNIX we must construct a single shell command to change
  1907. // directory and build because make resets the directory between
  1908. // each command.
  1909. std::string outputForExisting = this->ConvertToOutputForExisting(tgtDir);
  1910. std::string prefix = cd_cmd + outputForExisting + " && ";
  1911. std::transform(commands.begin(), commands.end(), commands.begin(),
  1912. [&prefix](std::string const& s) { return prefix + s; });
  1913. }
  1914. }