cmLocalUnixMakefileGenerator3.cxx 72 KB

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