cmLocalUnixMakefileGenerator3.cxx 73 KB

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