cmLocalUnixMakefileGenerator3.cxx 73 KB

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