cmLocalUnixMakefileGenerator3.cxx 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115
  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::AppendFlags(std::string& flags,
  756. const char* newFlags) const
  757. {
  758. this->cmLocalGenerator::AppendFlags(flags, newFlags);
  759. }
  760. void cmLocalUnixMakefileGenerator3::AppendRuleDepend(
  761. std::vector<std::string>& depends, const char* ruleFileName)
  762. {
  763. // Add a dependency on the rule file itself unless an option to skip
  764. // it is specifically enabled by the user or project.
  765. const char* nodep =
  766. this->Makefile->GetDefinition("CMAKE_SKIP_RULE_DEPENDENCY");
  767. if (!nodep || cmIsOff(nodep)) {
  768. depends.emplace_back(ruleFileName);
  769. }
  770. }
  771. void cmLocalUnixMakefileGenerator3::AppendRuleDepends(
  772. std::vector<std::string>& depends, std::vector<std::string> const& ruleFiles)
  773. {
  774. // Add a dependency on the rule file itself unless an option to skip
  775. // it is specifically enabled by the user or project.
  776. if (!this->Makefile->IsOn("CMAKE_SKIP_RULE_DEPENDENCY")) {
  777. cmAppend(depends, ruleFiles);
  778. }
  779. }
  780. void cmLocalUnixMakefileGenerator3::AppendCustomDepends(
  781. std::vector<std::string>& depends, const std::vector<cmCustomCommand>& ccs)
  782. {
  783. for (cmCustomCommand const& cc : ccs) {
  784. cmCustomCommandGenerator ccg(cc, this->ConfigName, this);
  785. this->AppendCustomDepend(depends, ccg);
  786. }
  787. }
  788. void cmLocalUnixMakefileGenerator3::AppendCustomDepend(
  789. std::vector<std::string>& depends, cmCustomCommandGenerator const& ccg)
  790. {
  791. for (std::string const& d : ccg.GetDepends()) {
  792. // Lookup the real name of the dependency in case it is a CMake target.
  793. std::string dep;
  794. if (this->GetRealDependency(d, this->ConfigName, dep)) {
  795. depends.push_back(std::move(dep));
  796. }
  797. }
  798. }
  799. void cmLocalUnixMakefileGenerator3::AppendCustomCommands(
  800. std::vector<std::string>& commands, const std::vector<cmCustomCommand>& ccs,
  801. cmGeneratorTarget* target, std::string const& relative)
  802. {
  803. for (cmCustomCommand const& cc : ccs) {
  804. cmCustomCommandGenerator ccg(cc, this->ConfigName, this);
  805. this->AppendCustomCommand(commands, ccg, target, relative, true);
  806. }
  807. }
  808. void cmLocalUnixMakefileGenerator3::AppendCustomCommand(
  809. std::vector<std::string>& commands, cmCustomCommandGenerator const& ccg,
  810. cmGeneratorTarget* target, std::string const& relative, bool echo_comment,
  811. std::ostream* content)
  812. {
  813. // Optionally create a command to display the custom command's
  814. // comment text. This is used for pre-build, pre-link, and
  815. // post-build command comments. Custom build step commands have
  816. // their comments generated elsewhere.
  817. if (echo_comment) {
  818. const char* comment = ccg.GetComment();
  819. if (comment && *comment) {
  820. this->AppendEcho(commands, comment,
  821. cmLocalUnixMakefileGenerator3::EchoGenerate);
  822. }
  823. }
  824. // if the command specified a working directory use it.
  825. std::string dir = this->GetCurrentBinaryDirectory();
  826. std::string workingDir = ccg.GetWorkingDirectory();
  827. if (!workingDir.empty()) {
  828. dir = workingDir;
  829. }
  830. if (content) {
  831. *content << dir;
  832. }
  833. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  834. this->CreateRulePlaceholderExpander());
  835. // Add each command line to the set of commands.
  836. std::vector<std::string> commands1;
  837. std::string currentBinDir = this->GetCurrentBinaryDirectory();
  838. for (unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) {
  839. // Build the command line in a single string.
  840. std::string cmd = ccg.GetCommand(c);
  841. if (!cmd.empty()) {
  842. // Use "call " before any invocations of .bat or .cmd files
  843. // invoked as custom commands in the WindowsShell.
  844. //
  845. bool useCall = false;
  846. if (this->IsWindowsShell()) {
  847. std::string suffix;
  848. if (cmd.size() > 4) {
  849. suffix = cmSystemTools::LowerCase(cmd.substr(cmd.size() - 4));
  850. if (suffix == ".bat" || suffix == ".cmd") {
  851. useCall = true;
  852. }
  853. }
  854. }
  855. cmSystemTools::ReplaceString(cmd, "/./", "/");
  856. // Convert the command to a relative path only if the current
  857. // working directory will be the start-output directory.
  858. bool had_slash = cmd.find('/') != std::string::npos;
  859. if (workingDir.empty()) {
  860. cmd = this->MaybeConvertToRelativePath(currentBinDir, cmd);
  861. }
  862. bool has_slash = cmd.find('/') != std::string::npos;
  863. if (had_slash && !has_slash) {
  864. // This command was specified as a path to a file in the
  865. // current directory. Add a leading "./" so it can run
  866. // without the current directory being in the search path.
  867. cmd = cmStrCat("./", cmd);
  868. }
  869. std::string launcher;
  870. // Short-circuit if there is no launcher.
  871. const char* val = this->GetRuleLauncher(target, "RULE_LAUNCH_CUSTOM");
  872. if (val && *val) {
  873. // Expand rule variables referenced in the given launcher command.
  874. cmRulePlaceholderExpander::RuleVariables vars;
  875. vars.CMTargetName = target->GetName().c_str();
  876. vars.CMTargetType = cmState::GetTargetTypeName(target->GetType());
  877. std::string output;
  878. const std::vector<std::string>& outputs = ccg.GetOutputs();
  879. if (!outputs.empty()) {
  880. output = outputs[0];
  881. if (workingDir.empty()) {
  882. output = this->MaybeConvertToRelativePath(
  883. this->GetCurrentBinaryDirectory(), output);
  884. }
  885. output =
  886. this->ConvertToOutputFormat(output, cmOutputConverter::SHELL);
  887. }
  888. vars.Output = output.c_str();
  889. launcher = val;
  890. rulePlaceholderExpander->ExpandRuleVariables(this, launcher, vars);
  891. if (!launcher.empty()) {
  892. launcher += " ";
  893. }
  894. }
  895. std::string shellCommand = this->MaybeConvertWatcomShellCommand(cmd);
  896. if (shellCommand.empty()) {
  897. shellCommand =
  898. this->ConvertToOutputFormat(cmd, cmOutputConverter::SHELL);
  899. }
  900. cmd = launcher + shellCommand;
  901. ccg.AppendArguments(c, cmd);
  902. if (content) {
  903. // Rule content does not include the launcher.
  904. *content << (cmd.c_str() + launcher.size());
  905. }
  906. if (this->BorlandMakeCurlyHack) {
  907. // Borland Make has a very strange bug. If the first curly
  908. // brace anywhere in the command string is a left curly, it
  909. // must be written {{} instead of just {. Otherwise some
  910. // curly braces are removed. The hack can be skipped if the
  911. // first curly brace is the last character.
  912. std::string::size_type lcurly = cmd.find('{');
  913. if (lcurly != std::string::npos && lcurly < (cmd.size() - 1)) {
  914. std::string::size_type rcurly = cmd.find('}');
  915. if (rcurly == std::string::npos || rcurly > lcurly) {
  916. // The first curly is a left curly. Use the hack.
  917. cmd =
  918. cmStrCat(cmd.substr(0, lcurly), "{{}", cmd.substr(lcurly + 1));
  919. }
  920. }
  921. }
  922. if (launcher.empty()) {
  923. if (useCall) {
  924. cmd = cmStrCat("call ", cmd);
  925. } else if (this->IsNMake() && cmd[0] == '"') {
  926. cmd = cmStrCat("echo >nul && ", cmd);
  927. }
  928. }
  929. commands1.push_back(std::move(cmd));
  930. }
  931. }
  932. // Setup the proper working directory for the commands.
  933. this->CreateCDCommand(commands1, dir, relative);
  934. // push back the custom commands
  935. cmAppend(commands, commands1);
  936. }
  937. void cmLocalUnixMakefileGenerator3::AppendCleanCommand(
  938. std::vector<std::string>& commands, const std::set<std::string>& files,
  939. cmGeneratorTarget* target, const char* filename)
  940. {
  941. std::string currentBinDir = this->GetCurrentBinaryDirectory();
  942. std::string cleanfile = cmStrCat(
  943. currentBinDir, '/', this->GetTargetDirectory(target), "/cmake_clean");
  944. if (filename) {
  945. cleanfile += "_";
  946. cleanfile += filename;
  947. }
  948. cleanfile += ".cmake";
  949. std::string cleanfilePath = cmSystemTools::CollapseFullPath(cleanfile);
  950. cmsys::ofstream fout(cleanfilePath.c_str());
  951. if (!fout) {
  952. cmSystemTools::Error("Could not create " + cleanfilePath);
  953. }
  954. if (!files.empty()) {
  955. fout << "file(REMOVE_RECURSE\n";
  956. for (std::string const& file : files) {
  957. std::string fc = this->MaybeConvertToRelativePath(currentBinDir, file);
  958. fout << " " << cmOutputConverter::EscapeForCMake(fc) << "\n";
  959. }
  960. fout << ")\n";
  961. }
  962. {
  963. std::string remove =
  964. cmStrCat("$(CMAKE_COMMAND) -P ",
  965. this->ConvertToOutputFormat(
  966. this->MaybeConvertToRelativePath(
  967. this->GetCurrentBinaryDirectory(), cleanfile),
  968. cmOutputConverter::SHELL));
  969. commands.push_back(std::move(remove));
  970. }
  971. // For the main clean rule add per-language cleaning.
  972. if (!filename) {
  973. // Get the set of source languages in the target.
  974. std::set<std::string> languages;
  975. target->GetLanguages(
  976. languages, this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
  977. /* clang-format off */
  978. fout << "\n"
  979. << "# Per-language clean rules from dependency scanning.\n"
  980. << "foreach(lang " << cmJoin(languages, " ") << ")\n"
  981. << " include(" << this->GetTargetDirectory(target)
  982. << "/cmake_clean_${lang}.cmake OPTIONAL)\n"
  983. << "endforeach()\n";
  984. /* clang-format on */
  985. }
  986. }
  987. void cmLocalUnixMakefileGenerator3::AppendDirectoryCleanCommand(
  988. std::vector<std::string>& commands)
  989. {
  990. std::vector<std::string> cleanFiles;
  991. // Look for additional files registered for cleaning in this directory.
  992. if (const char* prop_value =
  993. this->Makefile->GetProperty("ADDITIONAL_CLEAN_FILES")) {
  994. cmGeneratorExpression ge;
  995. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(prop_value);
  996. cmExpandList(
  997. cge->Evaluate(this,
  998. this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE")),
  999. cleanFiles);
  1000. }
  1001. if (cleanFiles.empty()) {
  1002. return;
  1003. }
  1004. cmLocalGenerator* rootLG =
  1005. this->GetGlobalGenerator()->GetLocalGenerators().at(0);
  1006. std::string const& binaryDir = rootLG->GetCurrentBinaryDirectory();
  1007. std::string const& currentBinaryDir = this->GetCurrentBinaryDirectory();
  1008. std::string cleanfile =
  1009. cmStrCat(currentBinaryDir, "/CMakeFiles/cmake_directory_clean.cmake");
  1010. // Write clean script
  1011. {
  1012. std::string cleanfilePath = cmSystemTools::CollapseFullPath(cleanfile);
  1013. cmsys::ofstream fout(cleanfilePath.c_str());
  1014. if (!fout) {
  1015. cmSystemTools::Error("Could not create " + cleanfilePath);
  1016. return;
  1017. }
  1018. fout << "file(REMOVE_RECURSE\n";
  1019. for (std::string const& cfl : cleanFiles) {
  1020. std::string fc = rootLG->MaybeConvertToRelativePath(
  1021. binaryDir, cmSystemTools::CollapseFullPath(cfl, currentBinaryDir));
  1022. fout << " " << cmOutputConverter::EscapeForCMake(fc) << "\n";
  1023. }
  1024. fout << ")\n";
  1025. }
  1026. // Create command
  1027. {
  1028. std::string remove =
  1029. cmStrCat("$(CMAKE_COMMAND) -P ",
  1030. this->ConvertToOutputFormat(
  1031. rootLG->MaybeConvertToRelativePath(binaryDir, cleanfile),
  1032. cmOutputConverter::SHELL));
  1033. commands.push_back(std::move(remove));
  1034. }
  1035. }
  1036. void cmLocalUnixMakefileGenerator3::AppendEcho(
  1037. std::vector<std::string>& commands, std::string const& text, EchoColor color,
  1038. EchoProgress const* progress)
  1039. {
  1040. // Choose the color for the text.
  1041. std::string color_name;
  1042. if (this->GlobalGenerator->GetToolSupportsColor() && this->ColorMakefile) {
  1043. // See cmake::ExecuteEchoColor in cmake.cxx for these options.
  1044. // This color set is readable on both black and white backgrounds.
  1045. switch (color) {
  1046. case EchoNormal:
  1047. break;
  1048. case EchoDepend:
  1049. color_name = "--magenta --bold ";
  1050. break;
  1051. case EchoBuild:
  1052. color_name = "--green ";
  1053. break;
  1054. case EchoLink:
  1055. color_name = "--green --bold ";
  1056. break;
  1057. case EchoGenerate:
  1058. color_name = "--blue --bold ";
  1059. break;
  1060. case EchoGlobal:
  1061. color_name = "--cyan ";
  1062. break;
  1063. }
  1064. }
  1065. // Echo one line at a time.
  1066. std::string line;
  1067. line.reserve(200);
  1068. for (const char* c = text.c_str();; ++c) {
  1069. if (*c == '\n' || *c == '\0') {
  1070. // Avoid writing a blank last line on end-of-string.
  1071. if (*c != '\0' || !line.empty()) {
  1072. // Add a command to echo this line.
  1073. std::string cmd;
  1074. if (color_name.empty() && !progress) {
  1075. // Use the native echo command.
  1076. cmd = cmStrCat("@echo ", this->EscapeForShell(line, false, true));
  1077. } else {
  1078. // Use cmake to echo the text in color.
  1079. cmd = cmStrCat(
  1080. "@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) ",
  1081. color_name);
  1082. if (progress) {
  1083. cmd += "--progress-dir=";
  1084. cmd += this->ConvertToOutputFormat(
  1085. cmSystemTools::CollapseFullPath(progress->Dir),
  1086. cmOutputConverter::SHELL);
  1087. cmd += " ";
  1088. cmd += "--progress-num=";
  1089. cmd += progress->Arg;
  1090. cmd += " ";
  1091. }
  1092. cmd += this->EscapeForShell(line);
  1093. }
  1094. commands.push_back(std::move(cmd));
  1095. }
  1096. // Reset the line to empty.
  1097. line.clear();
  1098. // Progress appears only on first line.
  1099. progress = nullptr;
  1100. // Terminate on end-of-string.
  1101. if (*c == '\0') {
  1102. return;
  1103. }
  1104. } else if (*c != '\r') {
  1105. // Append this character to the current line.
  1106. line += *c;
  1107. }
  1108. }
  1109. }
  1110. std::string cmLocalUnixMakefileGenerator3::CreateMakeVariable(
  1111. std::string const& s, std::string const& s2)
  1112. {
  1113. std::string unmodified = cmStrCat(s, s2);
  1114. // if there is no restriction on the length of make variables
  1115. // and there are no "." characters in the string, then return the
  1116. // unmodified combination.
  1117. if ((!this->MakefileVariableSize &&
  1118. unmodified.find('.') == std::string::npos) &&
  1119. (!this->MakefileVariableSize &&
  1120. unmodified.find('+') == std::string::npos) &&
  1121. (!this->MakefileVariableSize &&
  1122. unmodified.find('-') == std::string::npos)) {
  1123. return unmodified;
  1124. }
  1125. // see if the variable has been defined before and return
  1126. // the modified version of the variable
  1127. std::map<std::string, std::string>::iterator i =
  1128. this->MakeVariableMap.find(unmodified);
  1129. if (i != this->MakeVariableMap.end()) {
  1130. return i->second;
  1131. }
  1132. // start with the unmodified variable
  1133. std::string ret = unmodified;
  1134. // if this there is no value for this->MakefileVariableSize then
  1135. // the string must have bad characters in it
  1136. if (!this->MakefileVariableSize) {
  1137. std::replace(ret.begin(), ret.end(), '.', '_');
  1138. cmSystemTools::ReplaceString(ret, "-", "__");
  1139. cmSystemTools::ReplaceString(ret, "+", "___");
  1140. int ni = 0;
  1141. char buffer[5];
  1142. // make sure the _ version is not already used, if
  1143. // it is used then add number to the end of the variable
  1144. while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
  1145. ++ni;
  1146. sprintf(buffer, "%04d", ni);
  1147. ret = unmodified + buffer;
  1148. }
  1149. this->ShortMakeVariableMap[ret] = "1";
  1150. this->MakeVariableMap[unmodified] = ret;
  1151. return ret;
  1152. }
  1153. // if the string is greater than 32 chars it is an invalid variable name
  1154. // for borland make
  1155. if (static_cast<int>(ret.size()) > this->MakefileVariableSize) {
  1156. int keep = this->MakefileVariableSize - 8;
  1157. int size = keep + 3;
  1158. std::string str1 = s;
  1159. std::string str2 = s2;
  1160. // we must shorten the combined string by 4 characters
  1161. // keep no more than 24 characters from the second string
  1162. if (static_cast<int>(str2.size()) > keep) {
  1163. str2 = str2.substr(0, keep);
  1164. }
  1165. if (static_cast<int>(str1.size()) + static_cast<int>(str2.size()) > size) {
  1166. str1 = str1.substr(0, size - str2.size());
  1167. }
  1168. char buffer[5];
  1169. int ni = 0;
  1170. sprintf(buffer, "%04d", ni);
  1171. ret = str1 + str2 + buffer;
  1172. while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
  1173. ++ni;
  1174. sprintf(buffer, "%04d", ni);
  1175. ret = str1 + str2 + buffer;
  1176. }
  1177. if (ni == 1000) {
  1178. cmSystemTools::Error("Borland makefile variable length too long");
  1179. return unmodified;
  1180. }
  1181. // once an unused variable is found
  1182. this->ShortMakeVariableMap[ret] = "1";
  1183. }
  1184. // always make an entry into the unmodified to variable map
  1185. this->MakeVariableMap[unmodified] = ret;
  1186. return ret;
  1187. }
  1188. bool cmLocalUnixMakefileGenerator3::UpdateDependencies(
  1189. const std::string& tgtInfo, bool verbose, bool color)
  1190. {
  1191. // read in the target info file
  1192. if (!this->Makefile->ReadListFile(tgtInfo) ||
  1193. cmSystemTools::GetErrorOccuredFlag()) {
  1194. cmSystemTools::Error("Target DependInfo.cmake file not found");
  1195. }
  1196. // Check if any multiple output pairs have a missing file.
  1197. this->CheckMultipleOutputs(verbose);
  1198. std::string const targetDir = cmSystemTools::GetFilenamePath(tgtInfo);
  1199. std::string const internalDependFile = targetDir + "/depend.internal";
  1200. std::string const dependFile = targetDir + "/depend.make";
  1201. // If the target DependInfo.cmake file has changed since the last
  1202. // time dependencies were scanned then force rescanning. This may
  1203. // happen when a new source file is added and CMake regenerates the
  1204. // project but no other sources were touched.
  1205. bool needRescanDependInfo = false;
  1206. cmFileTimeCache* ftc =
  1207. this->GlobalGenerator->GetCMakeInstance()->GetFileTimeCache();
  1208. {
  1209. int result;
  1210. if (!ftc->Compare(internalDependFile, tgtInfo, &result) || result < 0) {
  1211. if (verbose) {
  1212. std::ostringstream msg;
  1213. msg << "Dependee \"" << tgtInfo << "\" is newer than depender \""
  1214. << internalDependFile << "\"." << std::endl;
  1215. cmSystemTools::Stdout(msg.str());
  1216. }
  1217. needRescanDependInfo = true;
  1218. }
  1219. }
  1220. // If the directory information is newer than depend.internal, include dirs
  1221. // may have changed. In this case discard all old dependencies.
  1222. bool needRescanDirInfo = false;
  1223. {
  1224. std::string dirInfoFile =
  1225. cmStrCat(this->GetCurrentBinaryDirectory(),
  1226. "/CMakeFiles/CMakeDirectoryInformation.cmake");
  1227. int result;
  1228. if (!ftc->Compare(internalDependFile, dirInfoFile, &result) ||
  1229. result < 0) {
  1230. if (verbose) {
  1231. std::ostringstream msg;
  1232. msg << "Dependee \"" << dirInfoFile << "\" is newer than depender \""
  1233. << internalDependFile << "\"." << std::endl;
  1234. cmSystemTools::Stdout(msg.str());
  1235. }
  1236. needRescanDirInfo = true;
  1237. }
  1238. }
  1239. // Check the implicit dependencies to see if they are up to date.
  1240. // The build.make file may have explicit dependencies for the object
  1241. // files but these will not affect the scanning process so they need
  1242. // not be considered.
  1243. cmDepends::DependencyMap validDependencies;
  1244. bool needRescanDependencies = false;
  1245. if (!needRescanDirInfo) {
  1246. cmDependsC checker;
  1247. checker.SetVerbose(verbose);
  1248. checker.SetFileTimeCache(ftc);
  1249. // cmDependsC::Check() fills the vector validDependencies() with the
  1250. // dependencies for those files where they are still valid, i.e. neither
  1251. // the files themselves nor any files they depend on have changed.
  1252. // We don't do that if the CMakeDirectoryInformation.cmake file has
  1253. // changed, because then potentially all dependencies have changed.
  1254. // This information is given later on to cmDependsC, which then only
  1255. // rescans the files where it did not get valid dependencies via this
  1256. // dependency vector. This means that in the normal case, when only
  1257. // few or one file have been edited, then also only this one file is
  1258. // actually scanned again, instead of all files for this target.
  1259. needRescanDependencies =
  1260. !checker.Check(dependFile, internalDependFile, validDependencies);
  1261. }
  1262. if (needRescanDependInfo || needRescanDirInfo || needRescanDependencies) {
  1263. // The dependencies must be regenerated.
  1264. std::string targetName = cmSystemTools::GetFilenameName(targetDir);
  1265. targetName = targetName.substr(0, targetName.length() - 4);
  1266. std::string message =
  1267. cmStrCat("Scanning dependencies of target ", targetName);
  1268. cmSystemTools::MakefileColorEcho(cmsysTerminal_Color_ForegroundMagenta |
  1269. cmsysTerminal_Color_ForegroundBold,
  1270. message.c_str(), true, color);
  1271. return this->ScanDependencies(targetDir, dependFile, internalDependFile,
  1272. validDependencies);
  1273. }
  1274. // The dependencies are already up-to-date.
  1275. return true;
  1276. }
  1277. bool cmLocalUnixMakefileGenerator3::ScanDependencies(
  1278. std::string const& targetDir, std::string const& dependFile,
  1279. std::string const& internalDependFile, cmDepends::DependencyMap& validDeps)
  1280. {
  1281. // Read the directory information file.
  1282. cmMakefile* mf = this->Makefile;
  1283. bool haveDirectoryInfo = false;
  1284. {
  1285. std::string dirInfoFile =
  1286. cmStrCat(this->GetCurrentBinaryDirectory(),
  1287. "/CMakeFiles/CMakeDirectoryInformation.cmake");
  1288. if (mf->ReadListFile(dirInfoFile) &&
  1289. !cmSystemTools::GetErrorOccuredFlag()) {
  1290. haveDirectoryInfo = true;
  1291. }
  1292. }
  1293. // Lookup useful directory information.
  1294. if (haveDirectoryInfo) {
  1295. // Test whether we need to force Unix paths.
  1296. if (const char* force = mf->GetDefinition("CMAKE_FORCE_UNIX_PATHS")) {
  1297. if (!cmIsOff(force)) {
  1298. cmSystemTools::SetForceUnixPaths(true);
  1299. }
  1300. }
  1301. // Setup relative path top directories.
  1302. if (const char* relativePathTopSource =
  1303. mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_SOURCE")) {
  1304. this->StateSnapshot.GetDirectory().SetRelativePathTopSource(
  1305. relativePathTopSource);
  1306. }
  1307. if (const char* relativePathTopBinary =
  1308. mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_BINARY")) {
  1309. this->StateSnapshot.GetDirectory().SetRelativePathTopBinary(
  1310. relativePathTopBinary);
  1311. }
  1312. } else {
  1313. cmSystemTools::Error("Directory Information file not found");
  1314. }
  1315. // Open the make depends file. This should be copy-if-different
  1316. // because the make tool may try to reload it needlessly otherwise.
  1317. cmGeneratedFileStream ruleFileStream(
  1318. dependFile, false, this->GlobalGenerator->GetMakefileEncoding());
  1319. ruleFileStream.SetCopyIfDifferent(true);
  1320. if (!ruleFileStream) {
  1321. return false;
  1322. }
  1323. // Open the cmake dependency tracking file. This should not be
  1324. // copy-if-different because dependencies are re-scanned when it is
  1325. // older than the DependInfo.cmake.
  1326. cmGeneratedFileStream internalRuleFileStream(
  1327. internalDependFile, false, this->GlobalGenerator->GetMakefileEncoding());
  1328. if (!internalRuleFileStream) {
  1329. return false;
  1330. }
  1331. this->WriteDisclaimer(ruleFileStream);
  1332. this->WriteDisclaimer(internalRuleFileStream);
  1333. // for each language we need to scan, scan it
  1334. std::vector<std::string> langs =
  1335. cmExpandedList(mf->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES"));
  1336. for (std::string const& lang : langs) {
  1337. // construct the checker
  1338. // Create the scanner for this language
  1339. std::unique_ptr<cmDepends> scanner;
  1340. if (lang == "C" || lang == "CXX" || lang == "RC" || lang == "ASM" ||
  1341. lang == "CUDA") {
  1342. // TODO: Handle RC (resource files) dependencies correctly.
  1343. scanner = cm::make_unique<cmDependsC>(this, targetDir, lang, &validDeps);
  1344. }
  1345. #ifndef CMAKE_BOOTSTRAP
  1346. else if (lang == "Fortran") {
  1347. ruleFileStream << "# Note that incremental build could trigger "
  1348. << "a call to cmake_copy_f90_mod on each re-build\n";
  1349. scanner = cm::make_unique<cmDependsFortran>(this);
  1350. } else if (lang == "Java") {
  1351. scanner = cm::make_unique<cmDependsJava>();
  1352. }
  1353. #endif
  1354. if (scanner) {
  1355. scanner->SetLocalGenerator(this);
  1356. scanner->SetFileTimeCache(
  1357. this->GlobalGenerator->GetCMakeInstance()->GetFileTimeCache());
  1358. scanner->SetLanguage(lang);
  1359. scanner->SetTargetDirectory(targetDir);
  1360. scanner->Write(ruleFileStream, internalRuleFileStream);
  1361. }
  1362. }
  1363. return true;
  1364. }
  1365. void cmLocalUnixMakefileGenerator3::CheckMultipleOutputs(bool verbose)
  1366. {
  1367. cmMakefile* mf = this->Makefile;
  1368. // Get the string listing the multiple output pairs.
  1369. const char* pairs_string = mf->GetDefinition("CMAKE_MULTIPLE_OUTPUT_PAIRS");
  1370. if (!pairs_string) {
  1371. return;
  1372. }
  1373. // Convert the string to a list and preserve empty entries.
  1374. std::vector<std::string> pairs = cmExpandedList(pairs_string, true);
  1375. for (std::vector<std::string>::const_iterator i = pairs.begin();
  1376. i != pairs.end() && (i + 1) != pairs.end();) {
  1377. const std::string& depender = *i++;
  1378. const std::string& dependee = *i++;
  1379. // If the depender is missing then delete the dependee to make
  1380. // sure both will be regenerated.
  1381. if (cmSystemTools::FileExists(dependee) &&
  1382. !cmSystemTools::FileExists(depender)) {
  1383. if (verbose) {
  1384. std::ostringstream msg;
  1385. msg << "Deleting primary custom command output \"" << dependee
  1386. << "\" because another output \"" << depender
  1387. << "\" does not exist." << std::endl;
  1388. cmSystemTools::Stdout(msg.str());
  1389. }
  1390. cmSystemTools::RemoveFile(dependee);
  1391. }
  1392. }
  1393. }
  1394. void cmLocalUnixMakefileGenerator3::WriteLocalAllRules(
  1395. std::ostream& ruleFileStream)
  1396. {
  1397. this->WriteDisclaimer(ruleFileStream);
  1398. // Write the main entry point target. This must be the VERY first
  1399. // target so that make with no arguments will run it.
  1400. {
  1401. // Just depend on the all target to drive the build.
  1402. std::vector<std::string> depends;
  1403. std::vector<std::string> no_commands;
  1404. depends.emplace_back("all");
  1405. // Write the rule.
  1406. this->WriteMakeRule(ruleFileStream,
  1407. "Default target executed when no arguments are "
  1408. "given to make.",
  1409. "default_target", depends, no_commands, true);
  1410. // Help out users that try "gmake target1 target2 -j".
  1411. cmGlobalUnixMakefileGenerator3* gg =
  1412. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1413. if (gg->AllowNotParallel()) {
  1414. std::vector<std::string> no_depends;
  1415. this->WriteMakeRule(ruleFileStream,
  1416. "Allow only one \"make -f "
  1417. "Makefile2\" at a time, but pass "
  1418. "parallelism.",
  1419. ".NOTPARALLEL", no_depends, no_commands, false);
  1420. }
  1421. }
  1422. this->WriteSpecialTargetsTop(ruleFileStream);
  1423. // Include the progress variables for the target.
  1424. // Write all global targets
  1425. this->WriteDivider(ruleFileStream);
  1426. ruleFileStream << "# Targets provided globally by CMake.\n"
  1427. << "\n";
  1428. const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
  1429. for (cmGeneratorTarget* gt : targets) {
  1430. if (gt->GetType() == cmStateEnums::GLOBAL_TARGET) {
  1431. std::string targetString =
  1432. "Special rule for the target " + gt->GetName();
  1433. std::vector<std::string> commands;
  1434. std::vector<std::string> depends;
  1435. const char* text = gt->GetProperty("EchoString");
  1436. if (!text) {
  1437. text = "Running external command ...";
  1438. }
  1439. depends.reserve(gt->GetUtilities().size());
  1440. for (BT<std::string> const& u : gt->GetUtilities()) {
  1441. depends.push_back(u.Value);
  1442. }
  1443. this->AppendEcho(commands, text,
  1444. cmLocalUnixMakefileGenerator3::EchoGlobal);
  1445. // Global targets store their rules in pre- and post-build commands.
  1446. this->AppendCustomDepends(depends, gt->GetPreBuildCommands());
  1447. this->AppendCustomDepends(depends, gt->GetPostBuildCommands());
  1448. this->AppendCustomCommands(commands, gt->GetPreBuildCommands(), gt,
  1449. this->GetCurrentBinaryDirectory());
  1450. this->AppendCustomCommands(commands, gt->GetPostBuildCommands(), gt,
  1451. this->GetCurrentBinaryDirectory());
  1452. std::string targetName = gt->GetName();
  1453. this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
  1454. depends, commands, true);
  1455. // Provide a "/fast" version of the target.
  1456. depends.clear();
  1457. if ((targetName == "install") || (targetName == "install/local") ||
  1458. (targetName == "install/strip")) {
  1459. // Provide a fast install target that does not depend on all
  1460. // but has the same command.
  1461. depends.emplace_back("preinstall/fast");
  1462. } else {
  1463. // Just forward to the real target so at least it will work.
  1464. depends.push_back(targetName);
  1465. commands.clear();
  1466. }
  1467. targetName += "/fast";
  1468. this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
  1469. depends, commands, true);
  1470. }
  1471. }
  1472. std::vector<std::string> depends;
  1473. std::vector<std::string> commands;
  1474. // Write the all rule.
  1475. std::string recursiveTarget =
  1476. cmStrCat(this->GetCurrentBinaryDirectory(), "/all");
  1477. bool regenerate =
  1478. !this->GlobalGenerator->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION");
  1479. if (regenerate) {
  1480. depends.emplace_back("cmake_check_build_system");
  1481. }
  1482. std::string progressDir =
  1483. cmStrCat(this->GetBinaryDirectory(), "/CMakeFiles");
  1484. {
  1485. std::ostringstream progCmd;
  1486. progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start ";
  1487. progCmd << this->ConvertToOutputFormat(
  1488. cmSystemTools::CollapseFullPath(progressDir), cmOutputConverter::SHELL);
  1489. std::string progressFile = "/CMakeFiles/progress.marks";
  1490. std::string progressFileNameFull = this->ConvertToFullPath(progressFile);
  1491. progCmd << " "
  1492. << this->ConvertToOutputFormat(
  1493. cmSystemTools::CollapseFullPath(progressFileNameFull),
  1494. cmOutputConverter::SHELL);
  1495. commands.push_back(progCmd.str());
  1496. }
  1497. std::string mf2Dir = "CMakeFiles/Makefile2";
  1498. commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
  1499. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1500. this->GetCurrentBinaryDirectory());
  1501. {
  1502. std::ostringstream progCmd;
  1503. progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; // # 0
  1504. progCmd << this->ConvertToOutputFormat(
  1505. cmSystemTools::CollapseFullPath(progressDir), cmOutputConverter::SHELL);
  1506. progCmd << " 0";
  1507. commands.push_back(progCmd.str());
  1508. }
  1509. this->WriteMakeRule(ruleFileStream, "The main all target", "all", depends,
  1510. commands, true);
  1511. // Write the clean rule.
  1512. recursiveTarget = cmStrCat(this->GetCurrentBinaryDirectory(), "/clean");
  1513. commands.clear();
  1514. depends.clear();
  1515. commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
  1516. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1517. this->GetCurrentBinaryDirectory());
  1518. this->WriteMakeRule(ruleFileStream, "The main clean target", "clean",
  1519. depends, commands, true);
  1520. commands.clear();
  1521. depends.clear();
  1522. depends.emplace_back("clean");
  1523. this->WriteMakeRule(ruleFileStream, "The main clean target", "clean/fast",
  1524. depends, commands, true);
  1525. // Write the preinstall rule.
  1526. recursiveTarget = cmStrCat(this->GetCurrentBinaryDirectory(), "/preinstall");
  1527. commands.clear();
  1528. depends.clear();
  1529. const char* noall =
  1530. this->Makefile->GetDefinition("CMAKE_SKIP_INSTALL_ALL_DEPENDENCY");
  1531. if (!noall || cmIsOff(noall)) {
  1532. // Drive the build before installing.
  1533. depends.emplace_back("all");
  1534. } else if (regenerate) {
  1535. // At least make sure the build system is up to date.
  1536. depends.emplace_back("cmake_check_build_system");
  1537. }
  1538. commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
  1539. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1540. this->GetCurrentBinaryDirectory());
  1541. this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
  1542. "preinstall", depends, commands, true);
  1543. depends.clear();
  1544. this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
  1545. "preinstall/fast", depends, commands, true);
  1546. if (regenerate) {
  1547. // write the depend rule, really a recompute depends rule
  1548. depends.clear();
  1549. commands.clear();
  1550. cmake* cm = this->GlobalGenerator->GetCMakeInstance();
  1551. if (cm->DoWriteGlobVerifyTarget()) {
  1552. std::string rescanRule =
  1553. cmStrCat("$(CMAKE_COMMAND) -P ",
  1554. this->ConvertToOutputFormat(cm->GetGlobVerifyScript(),
  1555. cmOutputConverter::SHELL));
  1556. commands.push_back(rescanRule);
  1557. }
  1558. std::string cmakefileName = "CMakeFiles/Makefile.cmake";
  1559. {
  1560. std::string runRule = cmStrCat(
  1561. "$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) "
  1562. "--check-build-system ",
  1563. this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL),
  1564. " 1");
  1565. commands.push_back(std::move(runRule));
  1566. }
  1567. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1568. this->GetCurrentBinaryDirectory());
  1569. this->WriteMakeRule(ruleFileStream, "clear depends", "depend", depends,
  1570. commands, true);
  1571. }
  1572. }
  1573. void cmLocalUnixMakefileGenerator3::ClearDependencies(cmMakefile* mf,
  1574. bool verbose)
  1575. {
  1576. // Get the list of target files to check
  1577. const char* infoDef = mf->GetDefinition("CMAKE_DEPEND_INFO_FILES");
  1578. if (!infoDef) {
  1579. return;
  1580. }
  1581. std::vector<std::string> files = cmExpandedList(infoDef);
  1582. // Each depend information file corresponds to a target. Clear the
  1583. // dependencies for that target.
  1584. cmDepends clearer;
  1585. clearer.SetVerbose(verbose);
  1586. for (std::string const& file : files) {
  1587. std::string dir = cmSystemTools::GetFilenamePath(file);
  1588. // Clear the implicit dependency makefile.
  1589. std::string dependFile = dir + "/depend.make";
  1590. clearer.Clear(dependFile);
  1591. // Remove the internal dependency check file to force
  1592. // regeneration.
  1593. std::string internalDependFile = dir + "/depend.internal";
  1594. cmSystemTools::RemoveFile(internalDependFile);
  1595. }
  1596. }
  1597. namespace {
  1598. // Helper predicate for removing absolute paths that don't point to the
  1599. // source or binary directory. It is used when CMAKE_DEPENDS_IN_PROJECT_ONLY
  1600. // is set ON, to only consider in-project dependencies during the build.
  1601. class NotInProjectDir
  1602. {
  1603. public:
  1604. // Constructor with the source and binary directory's path
  1605. NotInProjectDir(std::string sourceDir, std::string binaryDir)
  1606. : SourceDir(std::move(sourceDir))
  1607. , BinaryDir(std::move(binaryDir))
  1608. {
  1609. }
  1610. // Operator evaluating the predicate
  1611. bool operator()(const std::string& path) const
  1612. {
  1613. // Keep all relative paths:
  1614. if (!cmSystemTools::FileIsFullPath(path)) {
  1615. return false;
  1616. }
  1617. // If it's an absolute path, check if it starts with the source
  1618. // direcotory:
  1619. return (
  1620. !(IsInDirectory(SourceDir, path) || IsInDirectory(BinaryDir, path)));
  1621. }
  1622. private:
  1623. // Helper function used by the predicate
  1624. static bool IsInDirectory(const std::string& baseDir,
  1625. const std::string& testDir)
  1626. {
  1627. // First check if the test directory "starts with" the base directory:
  1628. if (testDir.find(baseDir) != 0) {
  1629. return false;
  1630. }
  1631. // If it does, then check that it's either the same string, or that the
  1632. // next character is a slash:
  1633. return ((testDir.size() == baseDir.size()) ||
  1634. (testDir[baseDir.size()] == '/'));
  1635. }
  1636. // The path to the source directory
  1637. std::string SourceDir;
  1638. // The path to the binary directory
  1639. std::string BinaryDir;
  1640. };
  1641. }
  1642. void cmLocalUnixMakefileGenerator3::WriteDependLanguageInfo(
  1643. std::ostream& cmakefileStream, cmGeneratorTarget* target)
  1644. {
  1645. ImplicitDependLanguageMap const& implicitLangs =
  1646. this->GetImplicitDepends(target);
  1647. // list the languages
  1648. cmakefileStream
  1649. << "# The set of languages for which implicit dependencies are needed:\n";
  1650. cmakefileStream << "set(CMAKE_DEPENDS_LANGUAGES\n";
  1651. for (auto const& implicitLang : implicitLangs) {
  1652. cmakefileStream << " \"" << implicitLang.first << "\"\n";
  1653. }
  1654. cmakefileStream << " )\n";
  1655. // now list the files for each language
  1656. cmakefileStream
  1657. << "# The set of files for implicit dependencies of each language:\n";
  1658. for (auto const& implicitLang : implicitLangs) {
  1659. cmakefileStream << "set(CMAKE_DEPENDS_CHECK_" << implicitLang.first
  1660. << "\n";
  1661. ImplicitDependFileMap const& implicitPairs = implicitLang.second;
  1662. // for each file pair
  1663. for (auto const& implicitPair : implicitPairs) {
  1664. for (auto const& di : implicitPair.second) {
  1665. cmakefileStream << " \"" << di << "\" ";
  1666. cmakefileStream << "\"" << implicitPair.first << "\"\n";
  1667. }
  1668. }
  1669. cmakefileStream << " )\n";
  1670. // Tell the dependency scanner what compiler is used.
  1671. std::string cidVar =
  1672. cmStrCat("CMAKE_", implicitLang.first, "_COMPILER_ID");
  1673. const char* cid = this->Makefile->GetDefinition(cidVar);
  1674. if (cid && *cid) {
  1675. cmakefileStream << "set(CMAKE_" << implicitLang.first
  1676. << "_COMPILER_ID \"" << cid << "\")\n";
  1677. }
  1678. if (implicitLang.first == "Fortran") {
  1679. std::string smodSep =
  1680. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_SEP");
  1681. std::string smodExt =
  1682. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_EXT");
  1683. cmakefileStream << "set(CMAKE_Fortran_SUBMODULE_SEP \"" << smodSep
  1684. << "\")\n";
  1685. cmakefileStream << "set(CMAKE_Fortran_SUBMODULE_EXT \"" << smodExt
  1686. << "\")\n";
  1687. }
  1688. // Build a list of preprocessor definitions for the target.
  1689. std::set<std::string> defines;
  1690. this->GetTargetDefines(target, this->ConfigName, implicitLang.first,
  1691. defines);
  1692. if (!defines.empty()) {
  1693. /* clang-format off */
  1694. cmakefileStream
  1695. << "\n"
  1696. << "# Preprocessor definitions for this target.\n"
  1697. << "set(CMAKE_TARGET_DEFINITIONS_" << implicitLang.first << "\n";
  1698. /* clang-format on */
  1699. for (std::string const& define : defines) {
  1700. cmakefileStream << " " << cmOutputConverter::EscapeForCMake(define)
  1701. << "\n";
  1702. }
  1703. cmakefileStream << " )\n";
  1704. }
  1705. // Target-specific include directories:
  1706. cmakefileStream << "\n"
  1707. << "# The include file search paths:\n";
  1708. cmakefileStream << "set(CMAKE_" << implicitLang.first
  1709. << "_TARGET_INCLUDE_PATH\n";
  1710. std::vector<std::string> includes;
  1711. const std::string& config =
  1712. this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
  1713. this->GetIncludeDirectories(includes, target, implicitLang.first, config);
  1714. std::string binaryDir = this->GetState()->GetBinaryDirectory();
  1715. if (this->Makefile->IsOn("CMAKE_DEPENDS_IN_PROJECT_ONLY")) {
  1716. std::string const& sourceDir = this->GetState()->GetSourceDirectory();
  1717. cmEraseIf(includes, ::NotInProjectDir(sourceDir, binaryDir));
  1718. }
  1719. for (std::string const& include : includes) {
  1720. cmakefileStream << " \""
  1721. << this->MaybeConvertToRelativePath(binaryDir, include)
  1722. << "\"\n";
  1723. }
  1724. cmakefileStream << " )\n";
  1725. }
  1726. // Store include transform rule properties. Write the directory
  1727. // rules first because they may be overridden by later target rules.
  1728. std::vector<std::string> transformRules;
  1729. if (const char* xform =
  1730. this->Makefile->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
  1731. cmExpandList(xform, transformRules);
  1732. }
  1733. if (const char* xform =
  1734. target->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
  1735. cmExpandList(xform, transformRules);
  1736. }
  1737. if (!transformRules.empty()) {
  1738. cmakefileStream << "set(CMAKE_INCLUDE_TRANSFORMS\n";
  1739. for (std::string const& tr : transformRules) {
  1740. cmakefileStream << " " << cmOutputConverter::EscapeForCMake(tr) << "\n";
  1741. }
  1742. cmakefileStream << " )\n";
  1743. }
  1744. }
  1745. void cmLocalUnixMakefileGenerator3::WriteDisclaimer(std::ostream& os)
  1746. {
  1747. os << "# CMAKE generated file: DO NOT EDIT!\n"
  1748. << "# Generated by \"" << this->GlobalGenerator->GetName() << "\""
  1749. << " Generator, CMake Version " << cmVersion::GetMajorVersion() << "."
  1750. << cmVersion::GetMinorVersion() << "\n\n";
  1751. }
  1752. std::string cmLocalUnixMakefileGenerator3::GetRecursiveMakeCall(
  1753. const std::string& makefile, const std::string& tgt)
  1754. {
  1755. // Call make on the given file.
  1756. std::string cmd = cmStrCat(
  1757. "$(MAKE) -f ",
  1758. this->ConvertToOutputFormat(makefile, cmOutputConverter::SHELL), ' ');
  1759. cmGlobalUnixMakefileGenerator3* gg =
  1760. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1761. // Pass down verbosity level.
  1762. if (!gg->MakeSilentFlag.empty()) {
  1763. cmd += gg->MakeSilentFlag;
  1764. cmd += " ";
  1765. }
  1766. // Most unix makes will pass the command line flags to make down to
  1767. // sub-invoked makes via an environment variable. However, some
  1768. // makes do not support that, so you have to pass the flags
  1769. // explicitly.
  1770. if (gg->PassMakeflags) {
  1771. cmd += "-$(MAKEFLAGS) ";
  1772. }
  1773. // Add the target.
  1774. if (!tgt.empty()) {
  1775. // The make target is always relative to the top of the build tree.
  1776. std::string tgt2 =
  1777. this->MaybeConvertToRelativePath(this->GetBinaryDirectory(), tgt);
  1778. // The target may have been written with windows paths.
  1779. cmSystemTools::ConvertToOutputSlashes(tgt2);
  1780. // Escape one extra time if the make tool requires it.
  1781. if (this->MakeCommandEscapeTargetTwice) {
  1782. tgt2 = this->EscapeForShell(tgt2, true, false);
  1783. }
  1784. // The target name is now a string that should be passed verbatim
  1785. // on the command line.
  1786. cmd += this->EscapeForShell(tgt2, true, false);
  1787. }
  1788. return cmd;
  1789. }
  1790. void cmLocalUnixMakefileGenerator3::WriteDivider(std::ostream& os)
  1791. {
  1792. os << "#======================================"
  1793. << "=======================================\n";
  1794. }
  1795. void cmLocalUnixMakefileGenerator3::WriteCMakeArgument(std::ostream& os,
  1796. const char* s)
  1797. {
  1798. // Write the given string to the stream with escaping to get it back
  1799. // into CMake through the lexical scanner.
  1800. os << "\"";
  1801. for (const char* c = s; *c; ++c) {
  1802. if (*c == '\\') {
  1803. os << "\\\\";
  1804. } else if (*c == '"') {
  1805. os << "\\\"";
  1806. } else {
  1807. os << *c;
  1808. }
  1809. }
  1810. os << "\"";
  1811. }
  1812. std::string cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(
  1813. const std::string& p, bool useWatcomQuote)
  1814. {
  1815. // Split the path into its components.
  1816. std::vector<std::string> components;
  1817. cmSystemTools::SplitPath(p, components);
  1818. // Open the quoted result.
  1819. std::string result;
  1820. if (useWatcomQuote) {
  1821. #if defined(_WIN32) && !defined(__CYGWIN__)
  1822. result = "'";
  1823. #else
  1824. result = "\"'";
  1825. #endif
  1826. } else {
  1827. result = "\"";
  1828. }
  1829. // Return an empty path if there are no components.
  1830. if (!components.empty()) {
  1831. // Choose a slash direction and fix root component.
  1832. const char* slash = "/";
  1833. #if defined(_WIN32) && !defined(__CYGWIN__)
  1834. if (!cmSystemTools::GetForceUnixPaths()) {
  1835. slash = "\\";
  1836. for (char& i : components[0]) {
  1837. if (i == '/') {
  1838. i = '\\';
  1839. }
  1840. }
  1841. }
  1842. #endif
  1843. // Begin the quoted result with the root component.
  1844. result += components[0];
  1845. if (components.size() > 1) {
  1846. // Now add the rest of the components separated by the proper slash
  1847. // direction for this platform.
  1848. std::vector<std::string>::const_iterator compEnd = std::remove(
  1849. components.begin() + 1, components.end() - 1, std::string());
  1850. std::vector<std::string>::const_iterator compStart =
  1851. components.begin() + 1;
  1852. result += cmJoin(cmMakeRange(compStart, compEnd), slash);
  1853. // Only the last component can be empty to avoid double slashes.
  1854. result += slash;
  1855. result += components.back();
  1856. }
  1857. }
  1858. // Close the quoted result.
  1859. if (useWatcomQuote) {
  1860. #if defined(_WIN32) && !defined(__CYGWIN__)
  1861. result += "'";
  1862. #else
  1863. result += "'\"";
  1864. #endif
  1865. } else {
  1866. result += "\"";
  1867. }
  1868. return result;
  1869. }
  1870. std::string cmLocalUnixMakefileGenerator3::GetTargetDirectory(
  1871. cmGeneratorTarget const* target) const
  1872. {
  1873. std::string dir = cmStrCat("CMakeFiles/", target->GetName());
  1874. #if defined(__VMS)
  1875. dir += "_dir";
  1876. #else
  1877. dir += ".dir";
  1878. #endif
  1879. return dir;
  1880. }
  1881. cmLocalUnixMakefileGenerator3::ImplicitDependLanguageMap const&
  1882. cmLocalUnixMakefileGenerator3::GetImplicitDepends(const cmGeneratorTarget* tgt)
  1883. {
  1884. return this->ImplicitDepends[tgt->GetName()];
  1885. }
  1886. void cmLocalUnixMakefileGenerator3::AddImplicitDepends(
  1887. const cmGeneratorTarget* tgt, const std::string& lang,
  1888. const std::string& obj, const std::string& src)
  1889. {
  1890. this->ImplicitDepends[tgt->GetName()][lang][obj].push_back(src);
  1891. }
  1892. void cmLocalUnixMakefileGenerator3::CreateCDCommand(
  1893. std::vector<std::string>& commands, std::string const& tgtDir,
  1894. std::string const& relDir)
  1895. {
  1896. // do we need to cd?
  1897. if (tgtDir == relDir) {
  1898. return;
  1899. }
  1900. // In a Windows shell we must change drive letter too. The shell
  1901. // used by NMake and Borland make does not support "cd /d" so this
  1902. // feature simply cannot work with them (Borland make does not even
  1903. // support changing the drive letter with just "d:").
  1904. const char* cd_cmd = this->IsMinGWMake() ? "cd /d " : "cd ";
  1905. cmGlobalUnixMakefileGenerator3* gg =
  1906. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1907. if (!gg->UnixCD) {
  1908. // On Windows we must perform each step separately and then change
  1909. // back because the shell keeps the working directory between
  1910. // commands.
  1911. std::string cmd =
  1912. cmStrCat(cd_cmd, this->ConvertToOutputForExisting(tgtDir));
  1913. commands.insert(commands.begin(), cmd);
  1914. // Change back to the starting directory.
  1915. cmd = cmStrCat(cd_cmd, this->ConvertToOutputForExisting(relDir));
  1916. commands.push_back(std::move(cmd));
  1917. } else {
  1918. // On UNIX we must construct a single shell command to change
  1919. // directory and build because make resets the directory between
  1920. // each command.
  1921. std::string outputForExisting = this->ConvertToOutputForExisting(tgtDir);
  1922. std::string prefix = cd_cmd + outputForExisting + " && ";
  1923. std::transform(commands.begin(), commands.end(), commands.begin(),
  1924. [&prefix](std::string const& s) { return prefix + s; });
  1925. }
  1926. }