cmLocalUnixMakefileGenerator3.cxx 74 KB

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