cmLocalUnixMakefileGenerator3.cxx 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092
  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->Convert(scmd, cmOutputConverter::NONE,
  542. cmOutputConverter::SHELL);
  543. }
  544. }
  545. return std::string();
  546. }
  547. void cmLocalUnixMakefileGenerator3::WriteMakeVariables(
  548. std::ostream& makefileStream)
  549. {
  550. this->WriteDivider(makefileStream);
  551. makefileStream << "# Set environment variables for the build.\n"
  552. << "\n";
  553. cmGlobalUnixMakefileGenerator3* gg =
  554. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  555. if (gg->DefineWindowsNULL) {
  556. makefileStream << "!IF \"$(OS)\" == \"Windows_NT\"\n"
  557. << "NULL=\n"
  558. << "!ELSE\n"
  559. << "NULL=nul\n"
  560. << "!ENDIF\n";
  561. }
  562. if (this->IsWindowsShell()) {
  563. makefileStream << "SHELL = cmd.exe\n"
  564. << "\n";
  565. } else {
  566. #if !defined(__VMS)
  567. /* clang-format off */
  568. makefileStream
  569. << "# The shell in which to execute make rules.\n"
  570. << "SHELL = /bin/sh\n"
  571. << "\n";
  572. /* clang-format on */
  573. #endif
  574. }
  575. std::string cmakeShellCommand =
  576. this->MaybeConvertWatcomShellCommand(cmSystemTools::GetCMakeCommand());
  577. if (cmakeShellCommand.empty()) {
  578. cmakeShellCommand =
  579. this->Convert(cmSystemTools::GetCMakeCommand(), cmOutputConverter::FULL,
  580. cmOutputConverter::SHELL);
  581. }
  582. /* clang-format off */
  583. makefileStream
  584. << "# The CMake executable.\n"
  585. << "CMAKE_COMMAND = "
  586. << cmakeShellCommand
  587. << "\n"
  588. << "\n";
  589. makefileStream
  590. << "# The command to remove a file.\n"
  591. << "RM = "
  592. << cmakeShellCommand
  593. << " -E remove -f\n"
  594. << "\n";
  595. makefileStream
  596. << "# Escaping for special characters.\n"
  597. << "EQUALS = =\n"
  598. << "\n";
  599. makefileStream
  600. << "# The top-level source directory on which CMake was run.\n"
  601. << "CMAKE_SOURCE_DIR = "
  602. << this->Convert(this->GetSourceDirectory(),
  603. cmOutputConverter::FULL,
  604. cmOutputConverter::SHELL)
  605. << "\n"
  606. << "\n";
  607. makefileStream
  608. << "# The top-level build directory on which CMake was run.\n"
  609. << "CMAKE_BINARY_DIR = "
  610. << this->Convert(this->GetBinaryDirectory(),
  611. cmOutputConverter::FULL,
  612. cmOutputConverter::SHELL)
  613. << "\n"
  614. << "\n";
  615. /* clang-format on */
  616. }
  617. void cmLocalUnixMakefileGenerator3::WriteSpecialTargetsTop(
  618. std::ostream& makefileStream)
  619. {
  620. this->WriteDivider(makefileStream);
  621. makefileStream << "# Special targets provided by cmake.\n"
  622. << "\n";
  623. std::vector<std::string> no_commands;
  624. std::vector<std::string> no_depends;
  625. // Special target to cleanup operation of make tool.
  626. // This should be the first target except for the default_target in
  627. // the interface Makefile.
  628. this->WriteMakeRule(makefileStream,
  629. "Disable implicit rules so canonical targets will work.",
  630. ".SUFFIXES", no_depends, no_commands, false);
  631. if (!this->IsNMake() && !this->IsWatcomWMake() &&
  632. !this->BorlandMakeCurlyHack) {
  633. // turn off RCS and SCCS automatic stuff from gmake
  634. makefileStream
  635. << "# Remove some rules from gmake that .SUFFIXES does not remove.\n"
  636. << "SUFFIXES =\n\n";
  637. }
  638. // Add a fake suffix to keep HP happy. Must be max 32 chars for SGI make.
  639. std::vector<std::string> depends;
  640. depends.push_back(".hpux_make_needs_suffix_list");
  641. this->WriteMakeRule(makefileStream, CM_NULLPTR, ".SUFFIXES", depends,
  642. no_commands, false);
  643. if (this->IsWatcomWMake()) {
  644. // Switch on WMake feature, if an error or interrupt occurs during
  645. // makefile processing, the current target being made may be deleted
  646. // without prompting (the same as command line -e option).
  647. /* clang-format off */
  648. makefileStream <<
  649. "\n"
  650. ".ERASE\n"
  651. "\n"
  652. ;
  653. /* clang-format on */
  654. }
  655. if (this->Makefile->IsOn("CMAKE_VERBOSE_MAKEFILE")) {
  656. /* clang-format off */
  657. makefileStream
  658. << "# Produce verbose output by default.\n"
  659. << "VERBOSE = 1\n"
  660. << "\n";
  661. /* clang-format on */
  662. }
  663. if (this->IsWatcomWMake()) {
  664. /* clang-format off */
  665. makefileStream <<
  666. "!ifndef VERBOSE\n"
  667. ".SILENT\n"
  668. "!endif\n"
  669. "\n"
  670. ;
  671. /* clang-format on */
  672. } else {
  673. // Write special target to silence make output. This must be after
  674. // the default target in case VERBOSE is set (which changes the
  675. // name). The setting of CMAKE_VERBOSE_MAKEFILE to ON will cause a
  676. // "VERBOSE=1" to be added as a make variable which will change the
  677. // name of this special target. This gives a make-time choice to
  678. // the user.
  679. this->WriteMakeRule(makefileStream,
  680. "Suppress display of executed commands.",
  681. "$(VERBOSE).SILENT", no_depends, no_commands, false);
  682. }
  683. // Work-around for makes that drop rules that have no dependencies
  684. // or commands.
  685. cmGlobalUnixMakefileGenerator3* gg =
  686. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  687. std::string hack = gg->GetEmptyRuleHackDepends();
  688. if (!hack.empty()) {
  689. no_depends.push_back(hack);
  690. }
  691. std::string hack_cmd = gg->GetEmptyRuleHackCommand();
  692. if (!hack_cmd.empty()) {
  693. no_commands.push_back(hack_cmd);
  694. }
  695. // Special symbolic target that never exists to force dependers to
  696. // run their rules.
  697. this->WriteMakeRule(makefileStream, "A target that is always out of date.",
  698. "cmake_force", no_depends, no_commands, true);
  699. // Variables for reference by other rules.
  700. this->WriteMakeVariables(makefileStream);
  701. }
  702. void cmLocalUnixMakefileGenerator3::WriteSpecialTargetsBottom(
  703. std::ostream& makefileStream)
  704. {
  705. this->WriteDivider(makefileStream);
  706. makefileStream << "# Special targets to cleanup operation of make.\n"
  707. << "\n";
  708. // Write special "cmake_check_build_system" target to run cmake with
  709. // the --check-build-system flag.
  710. {
  711. // Build command to run CMake to check if anything needs regenerating.
  712. std::string cmakefileName = cmake::GetCMakeFilesDirectoryPostSlash();
  713. cmakefileName += "Makefile.cmake";
  714. std::string runRule =
  715. "$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)";
  716. runRule += " --check-build-system ";
  717. runRule += this->Convert(cmakefileName, cmOutputConverter::NONE,
  718. cmOutputConverter::SHELL);
  719. runRule += " 0";
  720. std::vector<std::string> no_depends;
  721. std::vector<std::string> commands;
  722. commands.push_back(runRule);
  723. if (!this->IsRootMakefile()) {
  724. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  725. this->GetCurrentBinaryDirectory());
  726. }
  727. this->WriteMakeRule(
  728. makefileStream, "Special rule to run CMake to check the build system "
  729. "integrity.\n"
  730. "No rule that depends on this can have "
  731. "commands that come from listfiles\n"
  732. "because they might be regenerated.",
  733. "cmake_check_build_system", no_depends, commands, true);
  734. }
  735. }
  736. void cmLocalUnixMakefileGenerator3::WriteConvenienceRule(
  737. std::ostream& ruleFileStream, const std::string& realTarget,
  738. const std::string& helpTarget)
  739. {
  740. // A rule is only needed if the names are different.
  741. if (realTarget != helpTarget) {
  742. // The helper target depends on the real target.
  743. std::vector<std::string> depends;
  744. depends.push_back(realTarget);
  745. // There are no commands.
  746. std::vector<std::string> no_commands;
  747. // Write the rule.
  748. this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
  749. helpTarget, depends, no_commands, true);
  750. }
  751. }
  752. std::string cmLocalUnixMakefileGenerator3::GetRelativeTargetDirectory(
  753. cmGeneratorTarget* target)
  754. {
  755. std::string dir = this->HomeRelativeOutputPath;
  756. dir += this->GetTargetDirectory(target);
  757. return dir;
  758. }
  759. void cmLocalUnixMakefileGenerator3::AppendFlags(std::string& flags,
  760. const std::string& newFlags)
  761. {
  762. if (this->IsWatcomWMake() && !newFlags.empty()) {
  763. std::string newf = newFlags;
  764. if (newf.find("\\\"") != newf.npos) {
  765. cmSystemTools::ReplaceString(newf, "\\\"", "\"");
  766. this->cmLocalGenerator::AppendFlags(flags, newf);
  767. return;
  768. }
  769. }
  770. this->cmLocalGenerator::AppendFlags(flags, newFlags);
  771. }
  772. void cmLocalUnixMakefileGenerator3::AppendFlags(std::string& flags,
  773. const char* newFlags)
  774. {
  775. this->cmLocalGenerator::AppendFlags(flags, newFlags);
  776. }
  777. void cmLocalUnixMakefileGenerator3::AppendRuleDepend(
  778. std::vector<std::string>& depends, const char* ruleFileName)
  779. {
  780. // Add a dependency on the rule file itself unless an option to skip
  781. // it is specifically enabled by the user or project.
  782. const char* nodep =
  783. this->Makefile->GetDefinition("CMAKE_SKIP_RULE_DEPENDENCY");
  784. if (!nodep || cmSystemTools::IsOff(nodep)) {
  785. depends.push_back(ruleFileName);
  786. }
  787. }
  788. void cmLocalUnixMakefileGenerator3::AppendRuleDepends(
  789. std::vector<std::string>& depends, std::vector<std::string> const& ruleFiles)
  790. {
  791. // Add a dependency on the rule file itself unless an option to skip
  792. // it is specifically enabled by the user or project.
  793. if (!this->Makefile->IsOn("CMAKE_SKIP_RULE_DEPENDENCY")) {
  794. depends.insert(depends.end(), ruleFiles.begin(), ruleFiles.end());
  795. }
  796. }
  797. void cmLocalUnixMakefileGenerator3::AppendCustomDepends(
  798. std::vector<std::string>& depends, const std::vector<cmCustomCommand>& ccs)
  799. {
  800. for (std::vector<cmCustomCommand>::const_iterator i = ccs.begin();
  801. i != ccs.end(); ++i) {
  802. cmCustomCommandGenerator ccg(*i, this->ConfigName, this);
  803. this->AppendCustomDepend(depends, ccg);
  804. }
  805. }
  806. void cmLocalUnixMakefileGenerator3::AppendCustomDepend(
  807. std::vector<std::string>& depends, cmCustomCommandGenerator const& ccg)
  808. {
  809. for (std::vector<std::string>::const_iterator d = ccg.GetDepends().begin();
  810. d != ccg.GetDepends().end(); ++d) {
  811. // Lookup the real name of the dependency in case it is a CMake target.
  812. std::string dep;
  813. if (this->GetRealDependency(*d, this->ConfigName, dep)) {
  814. depends.push_back(dep);
  815. }
  816. }
  817. }
  818. void cmLocalUnixMakefileGenerator3::AppendCustomCommands(
  819. std::vector<std::string>& commands, const std::vector<cmCustomCommand>& ccs,
  820. cmGeneratorTarget* target, std::string const& relative)
  821. {
  822. for (std::vector<cmCustomCommand>::const_iterator i = ccs.begin();
  823. i != ccs.end(); ++i) {
  824. cmCustomCommandGenerator ccg(*i, this->ConfigName, this);
  825. this->AppendCustomCommand(commands, ccg, target, relative, true);
  826. }
  827. }
  828. void cmLocalUnixMakefileGenerator3::AppendCustomCommand(
  829. std::vector<std::string>& commands, cmCustomCommandGenerator const& ccg,
  830. cmGeneratorTarget* target, std::string const& relative, bool echo_comment,
  831. std::ostream* content)
  832. {
  833. // Optionally create a command to display the custom command's
  834. // comment text. This is used for pre-build, pre-link, and
  835. // post-build command comments. Custom build step commands have
  836. // their comments generated elsewhere.
  837. if (echo_comment) {
  838. const char* comment = ccg.GetComment();
  839. if (comment && *comment) {
  840. this->AppendEcho(commands, comment,
  841. cmLocalUnixMakefileGenerator3::EchoGenerate);
  842. }
  843. }
  844. // if the command specified a working directory use it.
  845. std::string dir = this->GetCurrentBinaryDirectory();
  846. std::string workingDir = ccg.GetWorkingDirectory();
  847. if (!workingDir.empty()) {
  848. dir = workingDir;
  849. }
  850. if (content) {
  851. *content << dir;
  852. }
  853. // Add each command line to the set of commands.
  854. std::vector<std::string> commands1;
  855. for (unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) {
  856. // Build the command line in a single string.
  857. std::string cmd = ccg.GetCommand(c);
  858. if (!cmd.empty()) {
  859. // Use "call " before any invocations of .bat or .cmd files
  860. // invoked as custom commands in the WindowsShell.
  861. //
  862. bool useCall = false;
  863. if (this->IsWindowsShell()) {
  864. std::string suffix;
  865. if (cmd.size() > 4) {
  866. suffix = cmSystemTools::LowerCase(cmd.substr(cmd.size() - 4));
  867. if (suffix == ".bat" || suffix == ".cmd") {
  868. useCall = true;
  869. }
  870. }
  871. }
  872. cmSystemTools::ReplaceString(cmd, "/./", "/");
  873. // Convert the command to a relative path only if the current
  874. // working directory will be the start-output directory.
  875. bool had_slash = cmd.find('/') != cmd.npos;
  876. if (workingDir.empty()) {
  877. cmd = this->Convert(cmd, cmOutputConverter::START_OUTPUT);
  878. }
  879. bool has_slash = cmd.find('/') != cmd.npos;
  880. if (had_slash && !has_slash) {
  881. // This command was specified as a path to a file in the
  882. // current directory. Add a leading "./" so it can run
  883. // without the current directory being in the search path.
  884. cmd = "./" + cmd;
  885. }
  886. std::string launcher;
  887. // Short-circuit if there is no launcher.
  888. const char* prop = "RULE_LAUNCH_CUSTOM";
  889. const char* val = this->GetRuleLauncher(target, prop);
  890. if (val && *val) {
  891. // Expand rules in the empty string. It may insert the launcher and
  892. // perform replacements.
  893. RuleVariables vars;
  894. vars.RuleLauncher = prop;
  895. vars.CMTarget = target;
  896. std::string output;
  897. const std::vector<std::string>& outputs = ccg.GetOutputs();
  898. if (!outputs.empty()) {
  899. if (workingDir.empty()) {
  900. output = this->Convert(outputs[0], cmOutputConverter::START_OUTPUT,
  901. cmOutputConverter::SHELL);
  902. } else {
  903. output = this->Convert(outputs[0], cmOutputConverter::NONE,
  904. cmOutputConverter::SHELL);
  905. }
  906. }
  907. vars.Output = output.c_str();
  908. this->ExpandRuleVariables(launcher, vars);
  909. if (!launcher.empty()) {
  910. launcher += " ";
  911. }
  912. }
  913. std::string shellCommand = this->MaybeConvertWatcomShellCommand(cmd);
  914. if (shellCommand.empty()) {
  915. shellCommand = this->Convert(cmd, cmOutputConverter::NONE,
  916. cmOutputConverter::SHELL);
  917. }
  918. cmd = launcher + shellCommand;
  919. ccg.AppendArguments(c, cmd);
  920. if (content) {
  921. // Rule content does not include the launcher.
  922. *content << (cmd.c_str() + launcher.size());
  923. }
  924. if (this->BorlandMakeCurlyHack) {
  925. // Borland Make has a very strange bug. If the first curly
  926. // brace anywhere in the command string is a left curly, it
  927. // must be written {{} instead of just {. Otherwise some
  928. // curly braces are removed. The hack can be skipped if the
  929. // first curly brace is the last character.
  930. std::string::size_type lcurly = cmd.find('{');
  931. if (lcurly != cmd.npos && lcurly < (cmd.size() - 1)) {
  932. std::string::size_type rcurly = cmd.find('}');
  933. if (rcurly == cmd.npos || rcurly > lcurly) {
  934. // The first curly is a left curly. Use the hack.
  935. std::string hack_cmd = cmd.substr(0, lcurly);
  936. hack_cmd += "{{}";
  937. hack_cmd += cmd.substr(lcurly + 1);
  938. cmd = hack_cmd;
  939. }
  940. }
  941. }
  942. if (launcher.empty()) {
  943. if (useCall) {
  944. cmd = "call " + cmd;
  945. } else if (this->IsNMake() && cmd[0] == '"') {
  946. cmd = "echo >nul && " + cmd;
  947. }
  948. }
  949. commands1.push_back(cmd);
  950. }
  951. }
  952. // Setup the proper working directory for the commands.
  953. this->CreateCDCommand(commands1, dir.c_str(), relative);
  954. // push back the custom commands
  955. commands.insert(commands.end(), commands1.begin(), commands1.end());
  956. }
  957. void cmLocalUnixMakefileGenerator3::AppendCleanCommand(
  958. std::vector<std::string>& commands, const std::vector<std::string>& files,
  959. cmGeneratorTarget* target, const char* filename)
  960. {
  961. std::string cleanfile = this->GetCurrentBinaryDirectory();
  962. cleanfile += "/";
  963. cleanfile += this->GetTargetDirectory(target);
  964. cleanfile += "/cmake_clean";
  965. if (filename) {
  966. cleanfile += "_";
  967. cleanfile += filename;
  968. }
  969. cleanfile += ".cmake";
  970. std::string cleanfilePath =
  971. this->Convert(cleanfile, cmOutputConverter::FULL);
  972. cmsys::ofstream fout(cleanfilePath.c_str());
  973. if (!fout) {
  974. cmSystemTools::Error("Could not create ", cleanfilePath.c_str());
  975. }
  976. if (!files.empty()) {
  977. fout << "file(REMOVE_RECURSE\n";
  978. for (std::vector<std::string>::const_iterator f = files.begin();
  979. f != files.end(); ++f) {
  980. std::string fc = this->Convert(*f, cmOutputConverter::START_OUTPUT,
  981. cmOutputConverter::UNCHANGED);
  982. fout << " " << cmOutputConverter::EscapeForCMake(fc) << "\n";
  983. }
  984. fout << ")\n";
  985. }
  986. std::string remove = "$(CMAKE_COMMAND) -P ";
  987. remove += this->Convert(cleanfile, cmOutputConverter::START_OUTPUT,
  988. cmOutputConverter::SHELL);
  989. commands.push_back(remove);
  990. // For the main clean rule add per-language cleaning.
  991. if (!filename) {
  992. // Get the set of source languages in the target.
  993. std::set<std::string> languages;
  994. target->GetLanguages(
  995. languages, this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
  996. /* clang-format off */
  997. fout << "\n"
  998. << "# Per-language clean rules from dependency scanning.\n"
  999. << "foreach(lang " << cmJoin(languages, " ") << ")\n"
  1000. << " include(" << this->GetTargetDirectory(target)
  1001. << "/cmake_clean_${lang}.cmake OPTIONAL)\n"
  1002. << "endforeach()\n";
  1003. /* clang-format on */
  1004. }
  1005. }
  1006. void cmLocalUnixMakefileGenerator3::AppendEcho(
  1007. std::vector<std::string>& commands, std::string const& text, EchoColor color,
  1008. EchoProgress const* progress)
  1009. {
  1010. // Choose the color for the text.
  1011. std::string color_name;
  1012. if (this->GlobalGenerator->GetToolSupportsColor() && this->ColorMakefile) {
  1013. // See cmake::ExecuteEchoColor in cmake.cxx for these options.
  1014. // This color set is readable on both black and white backgrounds.
  1015. switch (color) {
  1016. case EchoNormal:
  1017. break;
  1018. case EchoDepend:
  1019. color_name = "--magenta --bold ";
  1020. break;
  1021. case EchoBuild:
  1022. color_name = "--green ";
  1023. break;
  1024. case EchoLink:
  1025. color_name = "--green --bold ";
  1026. break;
  1027. case EchoGenerate:
  1028. color_name = "--blue --bold ";
  1029. break;
  1030. case EchoGlobal:
  1031. color_name = "--cyan ";
  1032. break;
  1033. }
  1034. }
  1035. // Echo one line at a time.
  1036. std::string line;
  1037. line.reserve(200);
  1038. for (const char* c = text.c_str();; ++c) {
  1039. if (*c == '\n' || *c == '\0') {
  1040. // Avoid writing a blank last line on end-of-string.
  1041. if (*c != '\0' || !line.empty()) {
  1042. // Add a command to echo this line.
  1043. std::string cmd;
  1044. if (color_name.empty() && !progress) {
  1045. // Use the native echo command.
  1046. cmd = "@echo ";
  1047. cmd += this->EscapeForShell(line, false, true);
  1048. } else {
  1049. // Use cmake to echo the text in color.
  1050. cmd = "@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) ";
  1051. cmd += color_name;
  1052. if (progress) {
  1053. cmd += "--progress-dir=";
  1054. cmd += this->Convert(progress->Dir, cmOutputConverter::FULL,
  1055. cmOutputConverter::SHELL);
  1056. cmd += " ";
  1057. cmd += "--progress-num=";
  1058. cmd += progress->Arg;
  1059. cmd += " ";
  1060. }
  1061. cmd += this->EscapeForShell(line);
  1062. }
  1063. commands.push_back(cmd);
  1064. }
  1065. // Reset the line to emtpy.
  1066. line = "";
  1067. // Progress appears only on first line.
  1068. progress = CM_NULLPTR;
  1069. // Terminate on end-of-string.
  1070. if (*c == '\0') {
  1071. return;
  1072. }
  1073. } else if (*c != '\r') {
  1074. // Append this character to the current line.
  1075. line += *c;
  1076. }
  1077. }
  1078. }
  1079. std::string cmLocalUnixMakefileGenerator3::CreateMakeVariable(
  1080. const std::string& sin, const std::string& s2)
  1081. {
  1082. std::string s = sin;
  1083. std::string unmodified = s;
  1084. unmodified += s2;
  1085. // if there is no restriction on the length of make variables
  1086. // and there are no "." characters in the string, then return the
  1087. // unmodified combination.
  1088. if ((!this->MakefileVariableSize && unmodified.find('.') == s.npos) &&
  1089. (!this->MakefileVariableSize && unmodified.find('+') == s.npos) &&
  1090. (!this->MakefileVariableSize && unmodified.find('-') == s.npos)) {
  1091. return unmodified;
  1092. }
  1093. // see if the variable has been defined before and return
  1094. // the modified version of the variable
  1095. std::map<std::string, std::string>::iterator i =
  1096. this->MakeVariableMap.find(unmodified);
  1097. if (i != this->MakeVariableMap.end()) {
  1098. return i->second;
  1099. }
  1100. // start with the unmodified variable
  1101. std::string ret = unmodified;
  1102. // if this there is no value for this->MakefileVariableSize then
  1103. // the string must have bad characters in it
  1104. if (!this->MakefileVariableSize) {
  1105. std::replace(ret.begin(), ret.end(), '.', '_');
  1106. cmSystemTools::ReplaceString(ret, "-", "__");
  1107. cmSystemTools::ReplaceString(ret, "+", "___");
  1108. int ni = 0;
  1109. char buffer[5];
  1110. // make sure the _ version is not already used, if
  1111. // it is used then add number to the end of the variable
  1112. while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
  1113. ++ni;
  1114. sprintf(buffer, "%04d", ni);
  1115. ret = unmodified + buffer;
  1116. }
  1117. this->ShortMakeVariableMap[ret] = "1";
  1118. this->MakeVariableMap[unmodified] = ret;
  1119. return ret;
  1120. }
  1121. // if the string is greater than 32 chars it is an invalid variable name
  1122. // for borland make
  1123. if (static_cast<int>(ret.size()) > this->MakefileVariableSize) {
  1124. int keep = this->MakefileVariableSize - 8;
  1125. int size = keep + 3;
  1126. std::string str1 = s;
  1127. std::string str2 = s2;
  1128. // we must shorten the combined string by 4 characters
  1129. // keep no more than 24 characters from the second string
  1130. if (static_cast<int>(str2.size()) > keep) {
  1131. str2 = str2.substr(0, keep);
  1132. }
  1133. if (static_cast<int>(str1.size()) + static_cast<int>(str2.size()) > size) {
  1134. str1 = str1.substr(0, size - str2.size());
  1135. }
  1136. char buffer[5];
  1137. int ni = 0;
  1138. sprintf(buffer, "%04d", ni);
  1139. ret = str1 + str2 + buffer;
  1140. while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
  1141. ++ni;
  1142. sprintf(buffer, "%04d", ni);
  1143. ret = str1 + str2 + buffer;
  1144. }
  1145. if (ni == 1000) {
  1146. cmSystemTools::Error("Borland makefile variable length too long");
  1147. return unmodified;
  1148. }
  1149. // once an unused variable is found
  1150. this->ShortMakeVariableMap[ret] = "1";
  1151. }
  1152. // always make an entry into the unmodified to variable map
  1153. this->MakeVariableMap[unmodified] = ret;
  1154. return ret;
  1155. }
  1156. bool cmLocalUnixMakefileGenerator3::UpdateDependencies(const char* tgtInfo,
  1157. bool verbose,
  1158. bool color)
  1159. {
  1160. // read in the target info file
  1161. if (!this->Makefile->ReadListFile(tgtInfo) ||
  1162. cmSystemTools::GetErrorOccuredFlag()) {
  1163. cmSystemTools::Error("Target DependInfo.cmake file not found");
  1164. }
  1165. // Check if any multiple output pairs have a missing file.
  1166. this->CheckMultipleOutputs(verbose);
  1167. std::string dir = cmSystemTools::GetFilenamePath(tgtInfo);
  1168. std::string internalDependFile = dir + "/depend.internal";
  1169. std::string dependFile = dir + "/depend.make";
  1170. // If the target DependInfo.cmake file has changed since the last
  1171. // time dependencies were scanned then force rescanning. This may
  1172. // happen when a new source file is added and CMake regenerates the
  1173. // project but no other sources were touched.
  1174. bool needRescanDependInfo = false;
  1175. cmFileTimeComparison* ftc =
  1176. this->GlobalGenerator->GetCMakeInstance()->GetFileComparison();
  1177. {
  1178. int result;
  1179. if (!ftc->FileTimeCompare(internalDependFile.c_str(), tgtInfo, &result) ||
  1180. result < 0) {
  1181. if (verbose) {
  1182. std::ostringstream msg;
  1183. msg << "Dependee \"" << tgtInfo << "\" is newer than depender \""
  1184. << internalDependFile << "\"." << std::endl;
  1185. cmSystemTools::Stdout(msg.str().c_str());
  1186. }
  1187. needRescanDependInfo = true;
  1188. }
  1189. }
  1190. // If the directory information is newer than depend.internal, include dirs
  1191. // may have changed. In this case discard all old dependencies.
  1192. bool needRescanDirInfo = false;
  1193. std::string dirInfoFile = this->GetCurrentBinaryDirectory();
  1194. dirInfoFile += cmake::GetCMakeFilesDirectory();
  1195. dirInfoFile += "/CMakeDirectoryInformation.cmake";
  1196. {
  1197. int result;
  1198. if (!ftc->FileTimeCompare(internalDependFile.c_str(), dirInfoFile.c_str(),
  1199. &result) ||
  1200. result < 0) {
  1201. if (verbose) {
  1202. std::ostringstream msg;
  1203. msg << "Dependee \"" << dirInfoFile << "\" is newer than depender \""
  1204. << internalDependFile << "\"." << std::endl;
  1205. cmSystemTools::Stdout(msg.str().c_str());
  1206. }
  1207. needRescanDirInfo = true;
  1208. }
  1209. }
  1210. // Check the implicit dependencies to see if they are up to date.
  1211. // The build.make file may have explicit dependencies for the object
  1212. // files but these will not affect the scanning process so they need
  1213. // not be considered.
  1214. std::map<std::string, cmDepends::DependencyVector> validDependencies;
  1215. bool needRescanDependencies = false;
  1216. if (!needRescanDirInfo) {
  1217. cmDependsC checker;
  1218. checker.SetVerbose(verbose);
  1219. checker.SetFileComparison(ftc);
  1220. // cmDependsC::Check() fills the vector validDependencies() with the
  1221. // dependencies for those files where they are still valid, i.e. neither
  1222. // the files themselves nor any files they depend on have changed.
  1223. // We don't do that if the CMakeDirectoryInformation.cmake file has
  1224. // changed, because then potentially all dependencies have changed.
  1225. // This information is given later on to cmDependsC, which then only
  1226. // rescans the files where it did not get valid dependencies via this
  1227. // dependency vector. This means that in the normal case, when only
  1228. // few or one file have been edited, then also only this one file is
  1229. // actually scanned again, instead of all files for this target.
  1230. needRescanDependencies = !checker.Check(
  1231. dependFile.c_str(), internalDependFile.c_str(), validDependencies);
  1232. }
  1233. if (needRescanDependInfo || needRescanDirInfo || needRescanDependencies) {
  1234. // The dependencies must be regenerated.
  1235. std::string targetName = cmSystemTools::GetFilenameName(dir);
  1236. targetName = targetName.substr(0, targetName.length() - 4);
  1237. std::string message = "Scanning dependencies of target ";
  1238. message += targetName;
  1239. cmSystemTools::MakefileColorEcho(cmsysTerminal_Color_ForegroundMagenta |
  1240. cmsysTerminal_Color_ForegroundBold,
  1241. message.c_str(), true, color);
  1242. return this->ScanDependencies(dir.c_str(), validDependencies);
  1243. }
  1244. // The dependencies are already up-to-date.
  1245. return true;
  1246. }
  1247. bool cmLocalUnixMakefileGenerator3::ScanDependencies(
  1248. const char* targetDir,
  1249. std::map<std::string, cmDepends::DependencyVector>& validDeps)
  1250. {
  1251. // Read the directory information file.
  1252. cmMakefile* mf = this->Makefile;
  1253. bool haveDirectoryInfo = false;
  1254. std::string dirInfoFile = this->GetCurrentBinaryDirectory();
  1255. dirInfoFile += cmake::GetCMakeFilesDirectory();
  1256. dirInfoFile += "/CMakeDirectoryInformation.cmake";
  1257. if (mf->ReadListFile(dirInfoFile.c_str()) &&
  1258. !cmSystemTools::GetErrorOccuredFlag()) {
  1259. haveDirectoryInfo = true;
  1260. }
  1261. // Lookup useful directory information.
  1262. if (haveDirectoryInfo) {
  1263. // Test whether we need to force Unix paths.
  1264. if (const char* force = mf->GetDefinition("CMAKE_FORCE_UNIX_PATHS")) {
  1265. if (!cmSystemTools::IsOff(force)) {
  1266. cmSystemTools::SetForceUnixPaths(true);
  1267. }
  1268. }
  1269. // Setup relative path top directories.
  1270. if (const char* relativePathTopSource =
  1271. mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_SOURCE")) {
  1272. this->StateSnapshot.GetDirectory().SetRelativePathTopSource(
  1273. relativePathTopSource);
  1274. }
  1275. if (const char* relativePathTopBinary =
  1276. mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_BINARY")) {
  1277. this->StateSnapshot.GetDirectory().SetRelativePathTopBinary(
  1278. relativePathTopBinary);
  1279. }
  1280. } else {
  1281. cmSystemTools::Error("Directory Information file not found");
  1282. }
  1283. // create the file stream for the depends file
  1284. std::string dir = targetDir;
  1285. // Open the make depends file. This should be copy-if-different
  1286. // because the make tool may try to reload it needlessly otherwise.
  1287. std::string ruleFileNameFull = dir;
  1288. ruleFileNameFull += "/depend.make";
  1289. cmGeneratedFileStream ruleFileStream(ruleFileNameFull.c_str());
  1290. ruleFileStream.SetCopyIfDifferent(true);
  1291. if (!ruleFileStream) {
  1292. return false;
  1293. }
  1294. // Open the cmake dependency tracking file. This should not be
  1295. // copy-if-different because dependencies are re-scanned when it is
  1296. // older than the DependInfo.cmake.
  1297. std::string internalRuleFileNameFull = dir;
  1298. internalRuleFileNameFull += "/depend.internal";
  1299. cmGeneratedFileStream internalRuleFileStream(
  1300. internalRuleFileNameFull.c_str());
  1301. if (!internalRuleFileStream) {
  1302. return false;
  1303. }
  1304. this->WriteDisclaimer(ruleFileStream);
  1305. this->WriteDisclaimer(internalRuleFileStream);
  1306. // for each language we need to scan, scan it
  1307. const char* langStr = mf->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES");
  1308. std::vector<std::string> langs;
  1309. cmSystemTools::ExpandListArgument(langStr, langs);
  1310. for (std::vector<std::string>::iterator li = langs.begin();
  1311. li != langs.end(); ++li) {
  1312. // construct the checker
  1313. std::string lang = *li;
  1314. // Create the scanner for this language
  1315. cmDepends* scanner = CM_NULLPTR;
  1316. if (lang == "C" || lang == "CXX" || lang == "RC" || lang == "ASM") {
  1317. // TODO: Handle RC (resource files) dependencies correctly.
  1318. scanner = new cmDependsC(this, targetDir, lang, &validDeps);
  1319. }
  1320. #ifdef CMAKE_BUILD_WITH_CMAKE
  1321. else if (lang == "Fortran") {
  1322. scanner = new cmDependsFortran(this);
  1323. } else if (lang == "Java") {
  1324. scanner = new cmDependsJava();
  1325. }
  1326. #endif
  1327. if (scanner) {
  1328. scanner->SetLocalGenerator(this);
  1329. scanner->SetFileComparison(
  1330. this->GlobalGenerator->GetCMakeInstance()->GetFileComparison());
  1331. scanner->SetLanguage(lang);
  1332. scanner->SetTargetDirectory(dir.c_str());
  1333. scanner->Write(ruleFileStream, internalRuleFileStream);
  1334. // free the scanner for this language
  1335. delete scanner;
  1336. }
  1337. }
  1338. return true;
  1339. }
  1340. void cmLocalUnixMakefileGenerator3::CheckMultipleOutputs(bool verbose)
  1341. {
  1342. cmMakefile* mf = this->Makefile;
  1343. // Get the string listing the multiple output pairs.
  1344. const char* pairs_string = mf->GetDefinition("CMAKE_MULTIPLE_OUTPUT_PAIRS");
  1345. if (!pairs_string) {
  1346. return;
  1347. }
  1348. // Convert the string to a list and preserve empty entries.
  1349. std::vector<std::string> pairs;
  1350. cmSystemTools::ExpandListArgument(pairs_string, pairs, true);
  1351. for (std::vector<std::string>::const_iterator i = pairs.begin();
  1352. i != pairs.end() && (i + 1) != pairs.end();) {
  1353. const std::string& depender = *i++;
  1354. const std::string& dependee = *i++;
  1355. // If the depender is missing then delete the dependee to make
  1356. // sure both will be regenerated.
  1357. if (cmSystemTools::FileExists(dependee.c_str()) &&
  1358. !cmSystemTools::FileExists(depender.c_str())) {
  1359. if (verbose) {
  1360. std::ostringstream msg;
  1361. msg << "Deleting primary custom command output \"" << dependee
  1362. << "\" because another output \"" << depender
  1363. << "\" does not exist." << std::endl;
  1364. cmSystemTools::Stdout(msg.str().c_str());
  1365. }
  1366. cmSystemTools::RemoveFile(dependee);
  1367. }
  1368. }
  1369. }
  1370. void cmLocalUnixMakefileGenerator3::WriteLocalAllRules(
  1371. std::ostream& ruleFileStream)
  1372. {
  1373. this->WriteDisclaimer(ruleFileStream);
  1374. // Write the main entry point target. This must be the VERY first
  1375. // target so that make with no arguments will run it.
  1376. {
  1377. // Just depend on the all target to drive the build.
  1378. std::vector<std::string> depends;
  1379. std::vector<std::string> no_commands;
  1380. depends.push_back("all");
  1381. // Write the rule.
  1382. this->WriteMakeRule(ruleFileStream,
  1383. "Default target executed when no arguments are "
  1384. "given to make.",
  1385. "default_target", depends, no_commands, true);
  1386. // Help out users that try "gmake target1 target2 -j".
  1387. cmGlobalUnixMakefileGenerator3* gg =
  1388. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1389. if (gg->AllowNotParallel()) {
  1390. std::vector<std::string> no_depends;
  1391. this->WriteMakeRule(ruleFileStream, "Allow only one \"make -f "
  1392. "Makefile2\" at a time, but pass "
  1393. "parallelism.",
  1394. ".NOTPARALLEL", no_depends, no_commands, false);
  1395. }
  1396. }
  1397. this->WriteSpecialTargetsTop(ruleFileStream);
  1398. // Include the progress variables for the target.
  1399. // Write all global targets
  1400. this->WriteDivider(ruleFileStream);
  1401. ruleFileStream << "# Targets provided globally by CMake.\n"
  1402. << "\n";
  1403. std::vector<cmGeneratorTarget*> targets = this->GetGeneratorTargets();
  1404. std::vector<cmGeneratorTarget*>::iterator glIt;
  1405. for (glIt = targets.begin(); glIt != targets.end(); ++glIt) {
  1406. if ((*glIt)->GetType() == cmState::GLOBAL_TARGET) {
  1407. std::string targetString =
  1408. "Special rule for the target " + (*glIt)->GetName();
  1409. std::vector<std::string> commands;
  1410. std::vector<std::string> depends;
  1411. const char* text = (*glIt)->GetProperty("EchoString");
  1412. if (!text) {
  1413. text = "Running external command ...";
  1414. }
  1415. depends.insert(depends.end(), (*glIt)->GetUtilities().begin(),
  1416. (*glIt)->GetUtilities().end());
  1417. this->AppendEcho(commands, text,
  1418. cmLocalUnixMakefileGenerator3::EchoGlobal);
  1419. cmGeneratorTarget* gt = *glIt;
  1420. // Global targets store their rules in pre- and post-build commands.
  1421. this->AppendCustomDepends(depends, gt->GetPreBuildCommands());
  1422. this->AppendCustomDepends(depends, gt->GetPostBuildCommands());
  1423. this->AppendCustomCommands(commands, gt->GetPreBuildCommands(), gt,
  1424. this->GetCurrentBinaryDirectory());
  1425. this->AppendCustomCommands(commands, gt->GetPostBuildCommands(), gt,
  1426. this->GetCurrentBinaryDirectory());
  1427. std::string targetName = gt->GetName();
  1428. this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
  1429. depends, commands, true);
  1430. // Provide a "/fast" version of the target.
  1431. depends.clear();
  1432. if ((targetName == "install") || (targetName == "install_local") ||
  1433. (targetName == "install_strip")) {
  1434. // Provide a fast install target that does not depend on all
  1435. // but has the same command.
  1436. depends.push_back("preinstall/fast");
  1437. } else {
  1438. // Just forward to the real target so at least it will work.
  1439. depends.push_back(targetName);
  1440. commands.clear();
  1441. }
  1442. targetName += "/fast";
  1443. this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
  1444. depends, commands, true);
  1445. }
  1446. }
  1447. std::vector<std::string> depends;
  1448. std::vector<std::string> commands;
  1449. // Write the all rule.
  1450. std::string recursiveTarget = this->GetCurrentBinaryDirectory();
  1451. recursiveTarget += "/all";
  1452. depends.push_back("cmake_check_build_system");
  1453. std::string progressDir = this->GetBinaryDirectory();
  1454. progressDir += cmake::GetCMakeFilesDirectory();
  1455. {
  1456. std::ostringstream progCmd;
  1457. progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start ";
  1458. progCmd << this->Convert(progressDir, cmOutputConverter::FULL,
  1459. cmOutputConverter::SHELL);
  1460. std::string progressFile = cmake::GetCMakeFilesDirectory();
  1461. progressFile += "/progress.marks";
  1462. std::string progressFileNameFull = this->ConvertToFullPath(progressFile);
  1463. progCmd << " "
  1464. << this->Convert(progressFileNameFull, cmOutputConverter::FULL,
  1465. cmOutputConverter::SHELL);
  1466. commands.push_back(progCmd.str());
  1467. }
  1468. std::string mf2Dir = cmake::GetCMakeFilesDirectoryPostSlash();
  1469. mf2Dir += "Makefile2";
  1470. commands.push_back(
  1471. this->GetRecursiveMakeCall(mf2Dir.c_str(), recursiveTarget));
  1472. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1473. this->GetCurrentBinaryDirectory());
  1474. {
  1475. std::ostringstream progCmd;
  1476. progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; // # 0
  1477. progCmd << this->Convert(progressDir, cmOutputConverter::FULL,
  1478. cmOutputConverter::SHELL);
  1479. progCmd << " 0";
  1480. commands.push_back(progCmd.str());
  1481. }
  1482. this->WriteMakeRule(ruleFileStream, "The main all target", "all", depends,
  1483. commands, true);
  1484. // Write the clean rule.
  1485. recursiveTarget = this->GetCurrentBinaryDirectory();
  1486. recursiveTarget += "/clean";
  1487. commands.clear();
  1488. depends.clear();
  1489. commands.push_back(
  1490. this->GetRecursiveMakeCall(mf2Dir.c_str(), recursiveTarget));
  1491. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1492. this->GetCurrentBinaryDirectory());
  1493. this->WriteMakeRule(ruleFileStream, "The main clean target", "clean",
  1494. depends, commands, true);
  1495. commands.clear();
  1496. depends.clear();
  1497. depends.push_back("clean");
  1498. this->WriteMakeRule(ruleFileStream, "The main clean target", "clean/fast",
  1499. depends, commands, true);
  1500. // Write the preinstall rule.
  1501. recursiveTarget = this->GetCurrentBinaryDirectory();
  1502. recursiveTarget += "/preinstall";
  1503. commands.clear();
  1504. depends.clear();
  1505. const char* noall =
  1506. this->Makefile->GetDefinition("CMAKE_SKIP_INSTALL_ALL_DEPENDENCY");
  1507. if (!noall || cmSystemTools::IsOff(noall)) {
  1508. // Drive the build before installing.
  1509. depends.push_back("all");
  1510. } else {
  1511. // At least make sure the build system is up to date.
  1512. depends.push_back("cmake_check_build_system");
  1513. }
  1514. commands.push_back(
  1515. this->GetRecursiveMakeCall(mf2Dir.c_str(), recursiveTarget));
  1516. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1517. this->GetCurrentBinaryDirectory());
  1518. this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
  1519. "preinstall", depends, commands, true);
  1520. depends.clear();
  1521. this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
  1522. "preinstall/fast", depends, commands, true);
  1523. // write the depend rule, really a recompute depends rule
  1524. depends.clear();
  1525. commands.clear();
  1526. std::string cmakefileName = cmake::GetCMakeFilesDirectoryPostSlash();
  1527. cmakefileName += "Makefile.cmake";
  1528. std::string runRule =
  1529. "$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)";
  1530. runRule += " --check-build-system ";
  1531. runRule += this->Convert(cmakefileName, cmOutputConverter::NONE,
  1532. cmOutputConverter::SHELL);
  1533. runRule += " 1";
  1534. commands.push_back(runRule);
  1535. this->CreateCDCommand(commands, this->GetBinaryDirectory(),
  1536. this->GetCurrentBinaryDirectory());
  1537. this->WriteMakeRule(ruleFileStream, "clear depends", "depend", depends,
  1538. commands, true);
  1539. }
  1540. void cmLocalUnixMakefileGenerator3::ClearDependencies(cmMakefile* mf,
  1541. bool verbose)
  1542. {
  1543. // Get the list of target files to check
  1544. const char* infoDef = mf->GetDefinition("CMAKE_DEPEND_INFO_FILES");
  1545. if (!infoDef) {
  1546. return;
  1547. }
  1548. std::vector<std::string> files;
  1549. cmSystemTools::ExpandListArgument(infoDef, files);
  1550. // Each depend information file corresponds to a target. Clear the
  1551. // dependencies for that target.
  1552. cmDepends clearer;
  1553. clearer.SetVerbose(verbose);
  1554. for (std::vector<std::string>::iterator l = files.begin(); l != files.end();
  1555. ++l) {
  1556. std::string dir = cmSystemTools::GetFilenamePath(*l);
  1557. // Clear the implicit dependency makefile.
  1558. std::string dependFile = dir + "/depend.make";
  1559. clearer.Clear(dependFile.c_str());
  1560. // Remove the internal dependency check file to force
  1561. // regeneration.
  1562. std::string internalDependFile = dir + "/depend.internal";
  1563. cmSystemTools::RemoveFile(internalDependFile);
  1564. }
  1565. }
  1566. namespace {
  1567. // Helper predicate for removing absolute paths that don't point to the
  1568. // source or binary directory. It is used when CMAKE_DEPENDS_IN_PROJECT_ONLY
  1569. // is set ON, to only consider in-project dependencies during the build.
  1570. class NotInProjectDir
  1571. {
  1572. public:
  1573. // Constructor with the source and binary directory's path
  1574. NotInProjectDir(const std::string& sourceDir, const std::string& binaryDir)
  1575. : SourceDir(sourceDir)
  1576. , BinaryDir(binaryDir)
  1577. {
  1578. }
  1579. // Operator evaluating the predicate
  1580. bool operator()(const std::string& path) const
  1581. {
  1582. // Keep all relative paths:
  1583. if (!cmSystemTools::FileIsFullPath(path)) {
  1584. return false;
  1585. }
  1586. // If it's an absolute path, check if it starts with the source
  1587. // direcotory:
  1588. return (
  1589. !(IsInDirectory(SourceDir, path) || IsInDirectory(BinaryDir, path)));
  1590. }
  1591. private:
  1592. // Helper function used by the predicate
  1593. static bool IsInDirectory(const std::string& baseDir,
  1594. const std::string& testDir)
  1595. {
  1596. // First check if the test directory "starts with" the base directory:
  1597. if (testDir.find(baseDir) != 0) {
  1598. return false;
  1599. }
  1600. // If it does, then check that it's either the same string, or that the
  1601. // next character is a slash:
  1602. return ((testDir.size() == baseDir.size()) ||
  1603. (testDir[baseDir.size()] == '/'));
  1604. }
  1605. // The path to the source directory
  1606. std::string SourceDir;
  1607. // The path to the binary directory
  1608. std::string BinaryDir;
  1609. };
  1610. }
  1611. void cmLocalUnixMakefileGenerator3::WriteDependLanguageInfo(
  1612. std::ostream& cmakefileStream, cmGeneratorTarget* target)
  1613. {
  1614. ImplicitDependLanguageMap const& implicitLangs =
  1615. this->GetImplicitDepends(target);
  1616. // list the languages
  1617. cmakefileStream
  1618. << "# The set of languages for which implicit dependencies are needed:\n";
  1619. cmakefileStream << "set(CMAKE_DEPENDS_LANGUAGES\n";
  1620. for (ImplicitDependLanguageMap::const_iterator l = implicitLangs.begin();
  1621. l != implicitLangs.end(); ++l) {
  1622. cmakefileStream << " \"" << l->first << "\"\n";
  1623. }
  1624. cmakefileStream << " )\n";
  1625. // now list the files for each language
  1626. cmakefileStream
  1627. << "# The set of files for implicit dependencies of each language:\n";
  1628. for (ImplicitDependLanguageMap::const_iterator l = implicitLangs.begin();
  1629. l != implicitLangs.end(); ++l) {
  1630. cmakefileStream << "set(CMAKE_DEPENDS_CHECK_" << l->first << "\n";
  1631. ImplicitDependFileMap const& implicitPairs = l->second;
  1632. // for each file pair
  1633. for (ImplicitDependFileMap::const_iterator pi = implicitPairs.begin();
  1634. pi != implicitPairs.end(); ++pi) {
  1635. for (cmDepends::DependencyVector::const_iterator di = pi->second.begin();
  1636. di != pi->second.end(); ++di) {
  1637. cmakefileStream << " \"" << *di << "\" ";
  1638. cmakefileStream << "\"" << pi->first << "\"\n";
  1639. }
  1640. }
  1641. cmakefileStream << " )\n";
  1642. // Tell the dependency scanner what compiler is used.
  1643. std::string cidVar = "CMAKE_";
  1644. cidVar += l->first;
  1645. cidVar += "_COMPILER_ID";
  1646. const char* cid = this->Makefile->GetDefinition(cidVar);
  1647. if (cid && *cid) {
  1648. cmakefileStream << "set(CMAKE_" << l->first << "_COMPILER_ID \"" << cid
  1649. << "\")\n";
  1650. }
  1651. // Build a list of preprocessor definitions for the target.
  1652. std::set<std::string> defines;
  1653. this->AddCompileDefinitions(defines, target, this->ConfigName, l->first);
  1654. if (!defines.empty()) {
  1655. /* clang-format off */
  1656. cmakefileStream
  1657. << "\n"
  1658. << "# Preprocessor definitions for this target.\n"
  1659. << "set(CMAKE_TARGET_DEFINITIONS_" << l->first << "\n";
  1660. /* clang-format on */
  1661. for (std::set<std::string>::const_iterator di = defines.begin();
  1662. di != defines.end(); ++di) {
  1663. cmakefileStream << " " << cmOutputConverter::EscapeForCMake(*di)
  1664. << "\n";
  1665. }
  1666. cmakefileStream << " )\n";
  1667. }
  1668. // Target-specific include directories:
  1669. cmakefileStream << "\n"
  1670. << "# The include file search paths:\n";
  1671. cmakefileStream << "set(CMAKE_" << l->first << "_TARGET_INCLUDE_PATH\n";
  1672. std::vector<std::string> includes;
  1673. const std::string& config =
  1674. this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
  1675. this->GetIncludeDirectories(includes, target, l->first, config);
  1676. if (this->Makefile->IsOn("CMAKE_DEPENDS_IN_PROJECT_ONLY")) {
  1677. const char* sourceDir = this->GetState()->GetSourceDirectory();
  1678. const char* binaryDir = this->GetState()->GetBinaryDirectory();
  1679. std::vector<std::string>::iterator itr =
  1680. std::remove_if(includes.begin(), includes.end(),
  1681. ::NotInProjectDir(sourceDir, binaryDir));
  1682. includes.erase(itr, includes.end());
  1683. }
  1684. for (std::vector<std::string>::iterator i = includes.begin();
  1685. i != includes.end(); ++i) {
  1686. cmakefileStream << " \""
  1687. << this->Convert(*i, cmOutputConverter::HOME_OUTPUT)
  1688. << "\"\n";
  1689. }
  1690. cmakefileStream << " )\n";
  1691. }
  1692. // Store include transform rule properties. Write the directory
  1693. // rules first because they may be overridden by later target rules.
  1694. std::vector<std::string> transformRules;
  1695. if (const char* xform =
  1696. this->Makefile->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
  1697. cmSystemTools::ExpandListArgument(xform, transformRules);
  1698. }
  1699. if (const char* xform =
  1700. target->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
  1701. cmSystemTools::ExpandListArgument(xform, transformRules);
  1702. }
  1703. if (!transformRules.empty()) {
  1704. cmakefileStream << "set(CMAKE_INCLUDE_TRANSFORMS\n";
  1705. for (std::vector<std::string>::const_iterator tri = transformRules.begin();
  1706. tri != transformRules.end(); ++tri) {
  1707. cmakefileStream << " " << cmOutputConverter::EscapeForCMake(*tri)
  1708. << "\n";
  1709. }
  1710. cmakefileStream << " )\n";
  1711. }
  1712. }
  1713. void cmLocalUnixMakefileGenerator3::WriteDisclaimer(std::ostream& os)
  1714. {
  1715. os << "# CMAKE generated file: DO NOT EDIT!\n"
  1716. << "# Generated by \"" << this->GlobalGenerator->GetName() << "\""
  1717. << " Generator, CMake Version " << cmVersion::GetMajorVersion() << "."
  1718. << cmVersion::GetMinorVersion() << "\n\n";
  1719. }
  1720. std::string cmLocalUnixMakefileGenerator3::GetRecursiveMakeCall(
  1721. const char* makefile, const std::string& tgt)
  1722. {
  1723. // Call make on the given file.
  1724. std::string cmd;
  1725. cmd += "$(MAKE) -f ";
  1726. cmd +=
  1727. this->Convert(makefile, cmOutputConverter::NONE, cmOutputConverter::SHELL);
  1728. cmd += " ";
  1729. cmGlobalUnixMakefileGenerator3* gg =
  1730. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1731. // Pass down verbosity level.
  1732. if (!gg->MakeSilentFlag.empty()) {
  1733. cmd += gg->MakeSilentFlag;
  1734. cmd += " ";
  1735. }
  1736. // Most unix makes will pass the command line flags to make down to
  1737. // sub-invoked makes via an environment variable. However, some
  1738. // makes do not support that, so you have to pass the flags
  1739. // explicitly.
  1740. if (gg->PassMakeflags) {
  1741. cmd += "-$(MAKEFLAGS) ";
  1742. }
  1743. // Add the target.
  1744. if (!tgt.empty()) {
  1745. // The make target is always relative to the top of the build tree.
  1746. std::string tgt2 = this->Convert(tgt, cmOutputConverter::HOME_OUTPUT);
  1747. // The target may have been written with windows paths.
  1748. cmSystemTools::ConvertToOutputSlashes(tgt2);
  1749. // Escape one extra time if the make tool requires it.
  1750. if (this->MakeCommandEscapeTargetTwice) {
  1751. tgt2 = this->EscapeForShell(tgt2, true, false);
  1752. }
  1753. // The target name is now a string that should be passed verbatim
  1754. // on the command line.
  1755. cmd += this->EscapeForShell(tgt2, true, false);
  1756. }
  1757. return cmd;
  1758. }
  1759. void cmLocalUnixMakefileGenerator3::WriteDivider(std::ostream& os)
  1760. {
  1761. os << "#======================================"
  1762. << "=======================================\n";
  1763. }
  1764. void cmLocalUnixMakefileGenerator3::WriteCMakeArgument(std::ostream& os,
  1765. const char* s)
  1766. {
  1767. // Write the given string to the stream with escaping to get it back
  1768. // into CMake through the lexical scanner.
  1769. os << "\"";
  1770. for (const char* c = s; *c; ++c) {
  1771. if (*c == '\\') {
  1772. os << "\\\\";
  1773. } else if (*c == '"') {
  1774. os << "\\\"";
  1775. } else {
  1776. os << *c;
  1777. }
  1778. }
  1779. os << "\"";
  1780. }
  1781. std::string cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(
  1782. const char* p, bool useWatcomQuote)
  1783. {
  1784. // Split the path into its components.
  1785. std::vector<std::string> components;
  1786. cmSystemTools::SplitPath(p, components);
  1787. // Open the quoted result.
  1788. std::string result;
  1789. if (useWatcomQuote) {
  1790. #if defined(_WIN32) && !defined(__CYGWIN__)
  1791. result = "'";
  1792. #else
  1793. result = "\"'";
  1794. #endif
  1795. } else {
  1796. result = "\"";
  1797. }
  1798. // Return an empty path if there are no components.
  1799. if (!components.empty()) {
  1800. // Choose a slash direction and fix root component.
  1801. const char* slash = "/";
  1802. #if defined(_WIN32) && !defined(__CYGWIN__)
  1803. if (!cmSystemTools::GetForceUnixPaths()) {
  1804. slash = "\\";
  1805. for (std::string::iterator i = components[0].begin();
  1806. i != components[0].end(); ++i) {
  1807. if (*i == '/') {
  1808. *i = '\\';
  1809. }
  1810. }
  1811. }
  1812. #endif
  1813. // Begin the quoted result with the root component.
  1814. result += components[0];
  1815. if (components.size() > 1) {
  1816. // Now add the rest of the components separated by the proper slash
  1817. // direction for this platform.
  1818. std::vector<std::string>::const_iterator compEnd = std::remove(
  1819. components.begin() + 1, components.end() - 1, std::string());
  1820. std::vector<std::string>::const_iterator compStart =
  1821. components.begin() + 1;
  1822. result += cmJoin(cmMakeRange(compStart, compEnd), slash);
  1823. // Only the last component can be empty to avoid double slashes.
  1824. result += slash;
  1825. result += components.back();
  1826. }
  1827. }
  1828. // Close the quoted result.
  1829. if (useWatcomQuote) {
  1830. #if defined(_WIN32) && !defined(__CYGWIN__)
  1831. result += "'";
  1832. #else
  1833. result += "'\"";
  1834. #endif
  1835. } else {
  1836. result += "\"";
  1837. }
  1838. return result;
  1839. }
  1840. std::string cmLocalUnixMakefileGenerator3::GetTargetDirectory(
  1841. cmGeneratorTarget const* target) const
  1842. {
  1843. std::string dir = cmake::GetCMakeFilesDirectoryPostSlash();
  1844. dir += target->GetName();
  1845. #if defined(__VMS)
  1846. dir += "_dir";
  1847. #else
  1848. dir += ".dir";
  1849. #endif
  1850. return dir;
  1851. }
  1852. cmLocalUnixMakefileGenerator3::ImplicitDependLanguageMap const&
  1853. cmLocalUnixMakefileGenerator3::GetImplicitDepends(const cmGeneratorTarget* tgt)
  1854. {
  1855. return this->ImplicitDepends[tgt->GetName()];
  1856. }
  1857. void cmLocalUnixMakefileGenerator3::AddImplicitDepends(
  1858. const cmGeneratorTarget* tgt, const std::string& lang, const char* obj,
  1859. const char* src)
  1860. {
  1861. this->ImplicitDepends[tgt->GetName()][lang][obj].push_back(src);
  1862. }
  1863. void cmLocalUnixMakefileGenerator3::CreateCDCommand(
  1864. std::vector<std::string>& commands, const char* tgtDir,
  1865. std::string const& relDir)
  1866. {
  1867. // do we need to cd?
  1868. if (tgtDir == relDir) {
  1869. return;
  1870. }
  1871. // In a Windows shell we must change drive letter too. The shell
  1872. // used by NMake and Borland make does not support "cd /d" so this
  1873. // feature simply cannot work with them (Borland make does not even
  1874. // support changing the drive letter with just "d:").
  1875. const char* cd_cmd = this->IsMinGWMake() ? "cd /d " : "cd ";
  1876. cmGlobalUnixMakefileGenerator3* gg =
  1877. static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
  1878. if (!gg->UnixCD) {
  1879. // On Windows we must perform each step separately and then change
  1880. // back because the shell keeps the working directory between
  1881. // commands.
  1882. std::string cmd = cd_cmd;
  1883. cmd += this->ConvertToOutputForExisting(tgtDir);
  1884. commands.insert(commands.begin(), cmd);
  1885. // Change back to the starting directory.
  1886. cmd = cd_cmd;
  1887. cmd += this->ConvertToOutputForExisting(relDir);
  1888. commands.push_back(cmd);
  1889. } else {
  1890. // On UNIX we must construct a single shell command to change
  1891. // directory and build because make resets the directory between
  1892. // each command.
  1893. std::string outputForExisting = this->ConvertToOutputForExisting(tgtDir);
  1894. std::string prefix = cd_cmd + outputForExisting + " && ";
  1895. std::transform(commands.begin(), commands.end(), commands.begin(),
  1896. std::bind1st(std::plus<std::string>(), prefix));
  1897. }
  1898. }