cmLocalUnixMakefileGenerator3.cxx 73 KB

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