cmLocalUnixMakefileGenerator3.cxx 73 KB

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