cmLocalUnixMakefileGenerator3.cxx 73 KB

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