cmLocalUnixMakefileGenerator3.cxx 73 KB

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