cmLocalUnixMakefileGenerator3.cxx 73 KB

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