cmLocalUnixMakefileGenerator3.cxx 73 KB

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