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