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