cmLocalUnixMakefileGenerator3.cxx 73 KB

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