cmLocalUnixMakefileGenerator3.cxx 73 KB

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