cmLocalGenerator.cxx 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712
  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 "cmLocalGenerator.h"
  4. #include "cmAlgorithms.h"
  5. #include "cmComputeLinkInformation.h"
  6. #include "cmCustomCommandGenerator.h"
  7. #include "cmGeneratedFileStream.h"
  8. #include "cmGeneratorExpressionEvaluationFile.h"
  9. #include "cmGeneratorTarget.h"
  10. #include "cmGlobalGenerator.h"
  11. #include "cmInstallGenerator.h"
  12. #include "cmInstallScriptGenerator.h"
  13. #include "cmInstallTargetGenerator.h"
  14. #include "cmLinkLineComputer.h"
  15. #include "cmMakefile.h"
  16. #include "cmRulePlaceholderExpander.h"
  17. #include "cmSourceFile.h"
  18. #include "cmSourceFileLocation.h"
  19. #include "cmState.h"
  20. #include "cmStateDirectory.h"
  21. #include "cmStateTypes.h"
  22. #include "cmSystemTools.h"
  23. #include "cmTarget.h"
  24. #include "cmTestGenerator.h"
  25. #include "cmVersion.h"
  26. #include "cmake.h"
  27. #if defined(CMAKE_BUILD_WITH_CMAKE)
  28. # define CM_LG_ENCODE_OBJECT_NAMES
  29. # include "cmCryptoHash.h"
  30. #endif
  31. #include "cmsys/RegularExpression.hxx"
  32. #include <algorithm>
  33. #include <assert.h>
  34. #include <iterator>
  35. #include <sstream>
  36. #include <stdio.h>
  37. #include <string.h>
  38. #include <unordered_set>
  39. #include <utility>
  40. #if defined(__HAIKU__)
  41. # include <FindDirectory.h>
  42. # include <StorageDefs.h>
  43. #endif
  44. // List of variables that are replaced when
  45. // rules are expanced. These variables are
  46. // replaced in the form <var> with GetSafeDefinition(var).
  47. // ${LANG} is replaced in the variable first with all enabled
  48. // languages.
  49. static const char* ruleReplaceVars[] = {
  50. "CMAKE_${LANG}_COMPILER",
  51. "CMAKE_SHARED_LIBRARY_CREATE_${LANG}_FLAGS",
  52. "CMAKE_SHARED_MODULE_CREATE_${LANG}_FLAGS",
  53. "CMAKE_SHARED_MODULE_${LANG}_FLAGS",
  54. "CMAKE_SHARED_LIBRARY_${LANG}_FLAGS",
  55. "CMAKE_${LANG}_LINK_FLAGS",
  56. "CMAKE_SHARED_LIBRARY_SONAME_${LANG}_FLAG",
  57. "CMAKE_${LANG}_ARCHIVE",
  58. "CMAKE_AR",
  59. "CMAKE_CURRENT_SOURCE_DIR",
  60. "CMAKE_CURRENT_BINARY_DIR",
  61. "CMAKE_RANLIB",
  62. "CMAKE_LINKER",
  63. "CMAKE_CUDA_HOST_COMPILER",
  64. "CMAKE_CUDA_HOST_LINK_LAUNCHER",
  65. "CMAKE_CL_SHOWINCLUDES_PREFIX"
  66. };
  67. cmLocalGenerator::cmLocalGenerator(cmGlobalGenerator* gg, cmMakefile* makefile)
  68. : cmOutputConverter(makefile->GetStateSnapshot())
  69. , StateSnapshot(makefile->GetStateSnapshot())
  70. , DirectoryBacktrace(makefile->GetBacktrace())
  71. {
  72. this->GlobalGenerator = gg;
  73. this->Makefile = makefile;
  74. this->AliasTargets = makefile->GetAliasTargets();
  75. this->EmitUniversalBinaryFlags = true;
  76. this->BackwardsCompatibility = 0;
  77. this->BackwardsCompatibilityFinal = false;
  78. this->ComputeObjectMaxPath();
  79. std::vector<std::string> enabledLanguages =
  80. this->GetState()->GetEnabledLanguages();
  81. if (const char* sysrootCompile =
  82. this->Makefile->GetDefinition("CMAKE_SYSROOT_COMPILE")) {
  83. this->CompilerSysroot = sysrootCompile;
  84. } else {
  85. this->CompilerSysroot = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
  86. }
  87. if (const char* sysrootLink =
  88. this->Makefile->GetDefinition("CMAKE_SYSROOT_LINK")) {
  89. this->LinkerSysroot = sysrootLink;
  90. } else {
  91. this->LinkerSysroot = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
  92. }
  93. for (std::string const& lang : enabledLanguages) {
  94. if (lang == "NONE") {
  95. continue;
  96. }
  97. this->Compilers["CMAKE_" + lang + "_COMPILER"] = lang;
  98. this->VariableMappings["CMAKE_" + lang + "_COMPILER"] =
  99. this->Makefile->GetSafeDefinition("CMAKE_" + lang + "_COMPILER");
  100. std::string const& compilerArg1 = "CMAKE_" + lang + "_COMPILER_ARG1";
  101. std::string const& compilerTarget = "CMAKE_" + lang + "_COMPILER_TARGET";
  102. std::string const& compilerOptionTarget =
  103. "CMAKE_" + lang + "_COMPILE_OPTIONS_TARGET";
  104. std::string const& compilerExternalToolchain =
  105. "CMAKE_" + lang + "_COMPILER_EXTERNAL_TOOLCHAIN";
  106. std::string const& compilerOptionExternalToolchain =
  107. "CMAKE_" + lang + "_COMPILE_OPTIONS_EXTERNAL_TOOLCHAIN";
  108. std::string const& compilerOptionSysroot =
  109. "CMAKE_" + lang + "_COMPILE_OPTIONS_SYSROOT";
  110. this->VariableMappings[compilerArg1] =
  111. this->Makefile->GetSafeDefinition(compilerArg1);
  112. this->VariableMappings[compilerTarget] =
  113. this->Makefile->GetSafeDefinition(compilerTarget);
  114. this->VariableMappings[compilerOptionTarget] =
  115. this->Makefile->GetSafeDefinition(compilerOptionTarget);
  116. this->VariableMappings[compilerExternalToolchain] =
  117. this->Makefile->GetSafeDefinition(compilerExternalToolchain);
  118. this->VariableMappings[compilerOptionExternalToolchain] =
  119. this->Makefile->GetSafeDefinition(compilerOptionExternalToolchain);
  120. this->VariableMappings[compilerOptionSysroot] =
  121. this->Makefile->GetSafeDefinition(compilerOptionSysroot);
  122. for (const char* const* replaceIter = cm::cbegin(ruleReplaceVars);
  123. replaceIter != cm::cend(ruleReplaceVars); ++replaceIter) {
  124. std::string actualReplace = *replaceIter;
  125. if (actualReplace.find("${LANG}") != std::string::npos) {
  126. cmSystemTools::ReplaceString(actualReplace, "${LANG}", lang);
  127. }
  128. this->VariableMappings[actualReplace] =
  129. this->Makefile->GetSafeDefinition(actualReplace);
  130. }
  131. }
  132. }
  133. cmRulePlaceholderExpander* cmLocalGenerator::CreateRulePlaceholderExpander()
  134. const
  135. {
  136. return new cmRulePlaceholderExpander(this->Compilers, this->VariableMappings,
  137. this->CompilerSysroot,
  138. this->LinkerSysroot);
  139. }
  140. cmLocalGenerator::~cmLocalGenerator()
  141. {
  142. cmDeleteAll(this->GeneratorTargets);
  143. cmDeleteAll(this->OwnedImportedGeneratorTargets);
  144. }
  145. void cmLocalGenerator::IssueMessage(cmake::MessageType t,
  146. std::string const& text) const
  147. {
  148. this->GetCMakeInstance()->IssueMessage(t, text, this->DirectoryBacktrace);
  149. }
  150. void cmLocalGenerator::ComputeObjectMaxPath()
  151. {
  152. // Choose a maximum object file name length.
  153. #if defined(_WIN32) || defined(__CYGWIN__)
  154. this->ObjectPathMax = 250;
  155. #else
  156. this->ObjectPathMax = 1000;
  157. #endif
  158. const char* plen = this->Makefile->GetDefinition("CMAKE_OBJECT_PATH_MAX");
  159. if (plen && *plen) {
  160. unsigned int pmax;
  161. if (sscanf(plen, "%u", &pmax) == 1) {
  162. if (pmax >= 128) {
  163. this->ObjectPathMax = pmax;
  164. } else {
  165. std::ostringstream w;
  166. w << "CMAKE_OBJECT_PATH_MAX is set to " << pmax
  167. << ", which is less than the minimum of 128. "
  168. << "The value will be ignored.";
  169. this->IssueMessage(cmake::AUTHOR_WARNING, w.str());
  170. }
  171. } else {
  172. std::ostringstream w;
  173. w << "CMAKE_OBJECT_PATH_MAX is set to \"" << plen
  174. << "\", which fails to parse as a positive integer. "
  175. << "The value will be ignored.";
  176. this->IssueMessage(cmake::AUTHOR_WARNING, w.str());
  177. }
  178. }
  179. this->ObjectMaxPathViolations.clear();
  180. }
  181. void cmLocalGenerator::MoveSystemIncludesToEnd(
  182. std::vector<std::string>& includeDirs, const std::string& config,
  183. const std::string& lang, const cmGeneratorTarget* target) const
  184. {
  185. if (!target) {
  186. return;
  187. }
  188. std::stable_sort(
  189. includeDirs.begin(), includeDirs.end(),
  190. [&target, &config, &lang](std::string const& a, std::string const& b) {
  191. return !target->IsSystemIncludeDirectory(a, config, lang) &&
  192. target->IsSystemIncludeDirectory(b, config, lang);
  193. });
  194. }
  195. void cmLocalGenerator::TraceDependencies()
  196. {
  197. std::vector<std::string> configs;
  198. this->Makefile->GetConfigurations(configs);
  199. if (configs.empty()) {
  200. configs.emplace_back();
  201. }
  202. for (std::string const& c : configs) {
  203. this->GlobalGenerator->CreateEvaluationSourceFiles(c);
  204. }
  205. // Generate the rule files for each target.
  206. const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
  207. for (cmGeneratorTarget* target : targets) {
  208. if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  209. continue;
  210. }
  211. target->TraceDependencies();
  212. }
  213. }
  214. void cmLocalGenerator::GenerateTestFiles()
  215. {
  216. if (!this->Makefile->IsOn("CMAKE_TESTING_ENABLED")) {
  217. return;
  218. }
  219. // Compute the set of configurations.
  220. std::vector<std::string> configurationTypes;
  221. const std::string& config =
  222. this->Makefile->GetConfigurations(configurationTypes, false);
  223. std::string file = this->StateSnapshot.GetDirectory().GetCurrentBinary();
  224. file += "/";
  225. file += "CTestTestfile.cmake";
  226. cmGeneratedFileStream fout(file.c_str());
  227. fout.SetCopyIfDifferent(true);
  228. fout << "# CMake generated Testfile for " << std::endl
  229. << "# Source directory: "
  230. << this->StateSnapshot.GetDirectory().GetCurrentSource() << std::endl
  231. << "# Build directory: "
  232. << this->StateSnapshot.GetDirectory().GetCurrentBinary() << std::endl
  233. << "# " << std::endl
  234. << "# This file includes the relevant testing commands "
  235. << "required for " << std::endl
  236. << "# testing this directory and lists subdirectories to "
  237. << "be tested as well." << std::endl;
  238. const char* testIncludeFile =
  239. this->Makefile->GetProperty("TEST_INCLUDE_FILE");
  240. if (testIncludeFile) {
  241. fout << "include(\"" << testIncludeFile << "\")" << std::endl;
  242. }
  243. const char* testIncludeFiles =
  244. this->Makefile->GetProperty("TEST_INCLUDE_FILES");
  245. if (testIncludeFiles) {
  246. std::vector<std::string> includesList;
  247. cmSystemTools::ExpandListArgument(testIncludeFiles, includesList);
  248. for (std::string const& i : includesList) {
  249. fout << "include(\"" << i << "\")" << std::endl;
  250. }
  251. }
  252. // Ask each test generator to write its code.
  253. std::vector<cmTestGenerator*> const& testers =
  254. this->Makefile->GetTestGenerators();
  255. for (cmTestGenerator* tester : testers) {
  256. tester->Compute(this);
  257. tester->Generate(fout, config, configurationTypes);
  258. }
  259. typedef std::vector<cmStateSnapshot> vec_t;
  260. vec_t const& children = this->Makefile->GetStateSnapshot().GetChildren();
  261. std::string parentBinDir = this->GetCurrentBinaryDirectory();
  262. for (cmStateSnapshot const& i : children) {
  263. // TODO: Use add_subdirectory instead?
  264. std::string outP = i.GetDirectory().GetCurrentBinary();
  265. outP = this->ConvertToRelativePath(parentBinDir, outP);
  266. outP = cmOutputConverter::EscapeForCMake(outP);
  267. fout << "subdirs(" << outP << ")" << std::endl;
  268. }
  269. // Add directory labels property
  270. const char* directoryLabels =
  271. this->Makefile->GetDefinition("CMAKE_DIRECTORY_LABELS");
  272. const char* labels = this->Makefile->GetProperty("LABELS");
  273. if (labels || directoryLabels) {
  274. fout << "set_directory_properties(PROPERTIES LABELS ";
  275. if (labels) {
  276. fout << cmOutputConverter::EscapeForCMake(labels);
  277. }
  278. if (labels && directoryLabels) {
  279. fout << ";";
  280. }
  281. if (directoryLabels) {
  282. fout << cmOutputConverter::EscapeForCMake(directoryLabels);
  283. }
  284. fout << ")" << std::endl;
  285. }
  286. }
  287. void cmLocalGenerator::CreateEvaluationFileOutputs(std::string const& config)
  288. {
  289. std::vector<cmGeneratorExpressionEvaluationFile*> ef =
  290. this->Makefile->GetEvaluationFiles();
  291. for (cmGeneratorExpressionEvaluationFile* geef : ef) {
  292. geef->CreateOutputFile(this, config);
  293. }
  294. }
  295. void cmLocalGenerator::ProcessEvaluationFiles(
  296. std::vector<std::string>& generatedFiles)
  297. {
  298. std::vector<cmGeneratorExpressionEvaluationFile*> ef =
  299. this->Makefile->GetEvaluationFiles();
  300. for (cmGeneratorExpressionEvaluationFile* geef : ef) {
  301. geef->Generate(this);
  302. if (cmSystemTools::GetFatalErrorOccured()) {
  303. return;
  304. }
  305. std::vector<std::string> files = geef->GetFiles();
  306. std::sort(files.begin(), files.end());
  307. std::vector<std::string> intersection;
  308. std::set_intersection(files.begin(), files.end(), generatedFiles.begin(),
  309. generatedFiles.end(),
  310. std::back_inserter(intersection));
  311. if (!intersection.empty()) {
  312. cmSystemTools::Error("Files to be generated by multiple different "
  313. "commands: ",
  314. cmWrap('"', intersection, '"', " ").c_str());
  315. return;
  316. }
  317. generatedFiles.insert(generatedFiles.end(), files.begin(), files.end());
  318. std::vector<std::string>::iterator newIt =
  319. generatedFiles.end() - files.size();
  320. std::inplace_merge(generatedFiles.begin(), newIt, generatedFiles.end());
  321. }
  322. }
  323. void cmLocalGenerator::GenerateInstallRules()
  324. {
  325. // Compute the install prefix.
  326. const char* prefix = this->Makefile->GetDefinition("CMAKE_INSTALL_PREFIX");
  327. #if defined(_WIN32) && !defined(__CYGWIN__)
  328. std::string prefix_win32;
  329. if (!prefix) {
  330. if (!cmSystemTools::GetEnv("SystemDrive", prefix_win32)) {
  331. prefix_win32 = "C:";
  332. }
  333. const char* project_name = this->Makefile->GetDefinition("PROJECT_NAME");
  334. if (project_name && project_name[0]) {
  335. prefix_win32 += "/Program Files/";
  336. prefix_win32 += project_name;
  337. } else {
  338. prefix_win32 += "/InstalledCMakeProject";
  339. }
  340. prefix = prefix_win32.c_str();
  341. }
  342. #elif defined(__HAIKU__)
  343. char dir[B_PATH_NAME_LENGTH];
  344. if (!prefix) {
  345. if (find_directory(B_SYSTEM_DIRECTORY, -1, false, dir, sizeof(dir)) ==
  346. B_OK) {
  347. prefix = dir;
  348. } else {
  349. prefix = "/boot/system";
  350. }
  351. }
  352. #else
  353. if (!prefix) {
  354. prefix = "/usr/local";
  355. }
  356. #endif
  357. if (const char* stagingPrefix =
  358. this->Makefile->GetDefinition("CMAKE_STAGING_PREFIX")) {
  359. prefix = stagingPrefix;
  360. }
  361. // Compute the set of configurations.
  362. std::vector<std::string> configurationTypes;
  363. const std::string& config =
  364. this->Makefile->GetConfigurations(configurationTypes, false);
  365. // Choose a default install configuration.
  366. std::string default_config = config;
  367. const char* default_order[] = { "RELEASE", "MINSIZEREL", "RELWITHDEBINFO",
  368. "DEBUG", nullptr };
  369. for (const char** c = default_order; *c && default_config.empty(); ++c) {
  370. for (std::string const& configurationType : configurationTypes) {
  371. if (cmSystemTools::UpperCase(configurationType) == *c) {
  372. default_config = configurationType;
  373. }
  374. }
  375. }
  376. if (default_config.empty() && !configurationTypes.empty()) {
  377. default_config = configurationTypes[0];
  378. }
  379. // Create the install script file.
  380. std::string file = this->StateSnapshot.GetDirectory().GetCurrentBinary();
  381. std::string homedir = this->GetState()->GetBinaryDirectory();
  382. int toplevel_install = 0;
  383. if (file == homedir) {
  384. toplevel_install = 1;
  385. }
  386. file += "/cmake_install.cmake";
  387. cmGeneratedFileStream fout(file.c_str());
  388. fout.SetCopyIfDifferent(true);
  389. // Write the header.
  390. fout << "# Install script for directory: "
  391. << this->StateSnapshot.GetDirectory().GetCurrentSource() << std::endl
  392. << std::endl;
  393. fout << "# Set the install prefix" << std::endl
  394. << "if(NOT DEFINED CMAKE_INSTALL_PREFIX)" << std::endl
  395. << " set(CMAKE_INSTALL_PREFIX \"" << prefix << "\")" << std::endl
  396. << "endif()" << std::endl
  397. << "string(REGEX REPLACE \"/$\" \"\" CMAKE_INSTALL_PREFIX "
  398. << "\"${CMAKE_INSTALL_PREFIX}\")" << std::endl
  399. << std::endl;
  400. // Write support code for generating per-configuration install rules.
  401. /* clang-format off */
  402. fout <<
  403. "# Set the install configuration name.\n"
  404. "if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)\n"
  405. " if(BUILD_TYPE)\n"
  406. " string(REGEX REPLACE \"^[^A-Za-z0-9_]+\" \"\"\n"
  407. " CMAKE_INSTALL_CONFIG_NAME \"${BUILD_TYPE}\")\n"
  408. " else()\n"
  409. " set(CMAKE_INSTALL_CONFIG_NAME \"" << default_config << "\")\n"
  410. " endif()\n"
  411. " message(STATUS \"Install configuration: "
  412. "\\\"${CMAKE_INSTALL_CONFIG_NAME}\\\"\")\n"
  413. "endif()\n"
  414. "\n";
  415. /* clang-format on */
  416. // Write support code for dealing with component-specific installs.
  417. /* clang-format off */
  418. fout <<
  419. "# Set the component getting installed.\n"
  420. "if(NOT CMAKE_INSTALL_COMPONENT)\n"
  421. " if(COMPONENT)\n"
  422. " message(STATUS \"Install component: \\\"${COMPONENT}\\\"\")\n"
  423. " set(CMAKE_INSTALL_COMPONENT \"${COMPONENT}\")\n"
  424. " else()\n"
  425. " set(CMAKE_INSTALL_COMPONENT)\n"
  426. " endif()\n"
  427. "endif()\n"
  428. "\n";
  429. /* clang-format on */
  430. // Copy user-specified install options to the install code.
  431. if (const char* so_no_exe =
  432. this->Makefile->GetDefinition("CMAKE_INSTALL_SO_NO_EXE")) {
  433. /* clang-format off */
  434. fout <<
  435. "# Install shared libraries without execute permission?\n"
  436. "if(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE)\n"
  437. " set(CMAKE_INSTALL_SO_NO_EXE \"" << so_no_exe << "\")\n"
  438. "endif()\n"
  439. "\n";
  440. /* clang-format on */
  441. }
  442. // Copy cmake cross compile state to install code.
  443. if (const char* crosscompiling =
  444. this->Makefile->GetDefinition("CMAKE_CROSSCOMPILING")) {
  445. /* clang-format off */
  446. fout <<
  447. "# Is this installation the result of a crosscompile?\n"
  448. "if(NOT DEFINED CMAKE_CROSSCOMPILING)\n"
  449. " set(CMAKE_CROSSCOMPILING \"" << crosscompiling << "\")\n"
  450. "endif()\n"
  451. "\n";
  452. /* clang-format on */
  453. }
  454. // Write default directory permissions.
  455. if (const char* defaultDirPermissions = this->Makefile->GetDefinition(
  456. "CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS")) {
  457. /* clang-format off */
  458. fout <<
  459. "# Set default install directory permissions.\n"
  460. "if(NOT DEFINED CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS)\n"
  461. " set(CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS \""
  462. << defaultDirPermissions << "\")\n"
  463. "endif()\n"
  464. "\n";
  465. /* clang-format on */
  466. }
  467. // Ask each install generator to write its code.
  468. std::vector<cmInstallGenerator*> const& installers =
  469. this->Makefile->GetInstallGenerators();
  470. for (cmInstallGenerator* installer : installers) {
  471. installer->Generate(fout, config, configurationTypes);
  472. }
  473. // Write rules from old-style specification stored in targets.
  474. this->GenerateTargetInstallRules(fout, config, configurationTypes);
  475. // Include install scripts from subdirectories.
  476. std::vector<cmStateSnapshot> children =
  477. this->Makefile->GetStateSnapshot().GetChildren();
  478. if (!children.empty()) {
  479. fout << "if(NOT CMAKE_INSTALL_LOCAL_ONLY)\n";
  480. fout << " # Include the install script for each subdirectory.\n";
  481. for (cmStateSnapshot const& c : children) {
  482. if (!c.GetDirectory().GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
  483. std::string odir = c.GetDirectory().GetCurrentBinary();
  484. cmSystemTools::ConvertToUnixSlashes(odir);
  485. fout << " include(\"" << odir << "/cmake_install.cmake\")"
  486. << std::endl;
  487. }
  488. }
  489. fout << "\n";
  490. fout << "endif()\n\n";
  491. }
  492. // Record the install manifest.
  493. if (toplevel_install) {
  494. /* clang-format off */
  495. fout <<
  496. "if(CMAKE_INSTALL_COMPONENT)\n"
  497. " set(CMAKE_INSTALL_MANIFEST \"install_manifest_"
  498. "${CMAKE_INSTALL_COMPONENT}.txt\")\n"
  499. "else()\n"
  500. " set(CMAKE_INSTALL_MANIFEST \"install_manifest.txt\")\n"
  501. "endif()\n"
  502. "\n"
  503. "string(REPLACE \";\" \"\\n\" CMAKE_INSTALL_MANIFEST_CONTENT\n"
  504. " \"${CMAKE_INSTALL_MANIFEST_FILES}\")\n"
  505. "file(WRITE \"" << homedir << "/${CMAKE_INSTALL_MANIFEST}\"\n"
  506. " \"${CMAKE_INSTALL_MANIFEST_CONTENT}\")\n";
  507. /* clang-format on */
  508. }
  509. }
  510. void cmLocalGenerator::AddGeneratorTarget(cmGeneratorTarget* gt)
  511. {
  512. this->GeneratorTargets.push_back(gt);
  513. this->GeneratorTargetSearchIndex.emplace(gt->GetName(), gt);
  514. this->GlobalGenerator->IndexGeneratorTarget(gt);
  515. }
  516. void cmLocalGenerator::AddImportedGeneratorTarget(cmGeneratorTarget* gt)
  517. {
  518. this->ImportedGeneratorTargets.emplace(gt->GetName(), gt);
  519. this->GlobalGenerator->IndexGeneratorTarget(gt);
  520. }
  521. void cmLocalGenerator::AddOwnedImportedGeneratorTarget(cmGeneratorTarget* gt)
  522. {
  523. this->OwnedImportedGeneratorTargets.push_back(gt);
  524. }
  525. cmGeneratorTarget* cmLocalGenerator::FindLocalNonAliasGeneratorTarget(
  526. const std::string& name) const
  527. {
  528. GeneratorTargetMap::const_iterator ti =
  529. this->GeneratorTargetSearchIndex.find(name);
  530. if (ti != this->GeneratorTargetSearchIndex.end()) {
  531. return ti->second;
  532. }
  533. return nullptr;
  534. }
  535. void cmLocalGenerator::ComputeTargetManifest()
  536. {
  537. // Collect the set of configuration types.
  538. std::vector<std::string> configNames;
  539. this->Makefile->GetConfigurations(configNames);
  540. if (configNames.empty()) {
  541. configNames.emplace_back();
  542. }
  543. // Add our targets to the manifest for each configuration.
  544. const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
  545. for (cmGeneratorTarget* target : targets) {
  546. if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  547. continue;
  548. }
  549. for (std::string const& c : configNames) {
  550. target->ComputeTargetManifest(c);
  551. }
  552. }
  553. }
  554. bool cmLocalGenerator::ComputeTargetCompileFeatures()
  555. {
  556. // Collect the set of configuration types.
  557. std::vector<std::string> configNames;
  558. this->Makefile->GetConfigurations(configNames);
  559. if (configNames.empty()) {
  560. configNames.emplace_back();
  561. }
  562. // Process compile features of all targets.
  563. const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
  564. for (cmGeneratorTarget* target : targets) {
  565. for (std::string const& c : configNames) {
  566. if (!target->ComputeCompileFeatures(c)) {
  567. return false;
  568. }
  569. }
  570. }
  571. return true;
  572. }
  573. bool cmLocalGenerator::IsRootMakefile() const
  574. {
  575. return !this->StateSnapshot.GetBuildsystemDirectoryParent().IsValid();
  576. }
  577. cmState* cmLocalGenerator::GetState() const
  578. {
  579. return this->GlobalGenerator->GetCMakeInstance()->GetState();
  580. }
  581. cmStateSnapshot cmLocalGenerator::GetStateSnapshot() const
  582. {
  583. return this->Makefile->GetStateSnapshot();
  584. }
  585. const char* cmLocalGenerator::GetRuleLauncher(cmGeneratorTarget* target,
  586. const std::string& prop)
  587. {
  588. if (target) {
  589. return target->GetProperty(prop);
  590. }
  591. return this->Makefile->GetProperty(prop);
  592. }
  593. std::string cmLocalGenerator::ConvertToIncludeReference(
  594. std::string const& path, OutputFormat format, bool forceFullPaths)
  595. {
  596. static_cast<void>(forceFullPaths);
  597. return this->ConvertToOutputForExisting(path, format);
  598. }
  599. std::string cmLocalGenerator::GetIncludeFlags(
  600. const std::vector<std::string>& includeDirs, cmGeneratorTarget* target,
  601. const std::string& lang, bool forceFullPaths, bool forResponseFile,
  602. const std::string& config)
  603. {
  604. if (lang.empty()) {
  605. return "";
  606. }
  607. std::vector<std::string> includes = includeDirs;
  608. this->MoveSystemIncludesToEnd(includes, config, lang, target);
  609. OutputFormat shellFormat = forResponseFile ? RESPONSE : SHELL;
  610. std::ostringstream includeFlags;
  611. std::string flagVar = "CMAKE_INCLUDE_FLAG_";
  612. flagVar += lang;
  613. const char* includeFlag = this->Makefile->GetSafeDefinition(flagVar);
  614. flagVar = "CMAKE_INCLUDE_FLAG_SEP_";
  615. flagVar += lang;
  616. const char* sep = this->Makefile->GetDefinition(flagVar);
  617. bool quotePaths = false;
  618. if (this->Makefile->GetDefinition("CMAKE_QUOTE_INCLUDE_PATHS")) {
  619. quotePaths = true;
  620. }
  621. bool repeatFlag = true;
  622. // should the include flag be repeated like ie. -IA -IB
  623. if (!sep) {
  624. sep = " ";
  625. } else {
  626. // if there is a separator then the flag is not repeated but is only
  627. // given once i.e. -classpath a:b:c
  628. repeatFlag = false;
  629. }
  630. // Support special system include flag if it is available and the
  631. // normal flag is repeated for each directory.
  632. std::string sysFlagVar = "CMAKE_INCLUDE_SYSTEM_FLAG_";
  633. sysFlagVar += lang;
  634. const char* sysIncludeFlag = nullptr;
  635. if (repeatFlag) {
  636. sysIncludeFlag = this->Makefile->GetDefinition(sysFlagVar);
  637. }
  638. std::string fwSearchFlagVar = "CMAKE_";
  639. fwSearchFlagVar += lang;
  640. fwSearchFlagVar += "_FRAMEWORK_SEARCH_FLAG";
  641. const char* fwSearchFlag = this->Makefile->GetDefinition(fwSearchFlagVar);
  642. std::string sysFwSearchFlagVar = "CMAKE_";
  643. sysFwSearchFlagVar += lang;
  644. sysFwSearchFlagVar += "_SYSTEM_FRAMEWORK_SEARCH_FLAG";
  645. const char* sysFwSearchFlag =
  646. this->Makefile->GetDefinition(sysFwSearchFlagVar);
  647. bool flagUsed = false;
  648. std::set<std::string> emitted;
  649. #ifdef __APPLE__
  650. emitted.insert("/System/Library/Frameworks");
  651. #endif
  652. for (std::string const& i : includes) {
  653. if (fwSearchFlag && *fwSearchFlag && this->Makefile->IsOn("APPLE") &&
  654. cmSystemTools::IsPathToFramework(i.c_str())) {
  655. std::string frameworkDir = i;
  656. frameworkDir += "/../";
  657. frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
  658. if (emitted.insert(frameworkDir).second) {
  659. if (sysFwSearchFlag && target &&
  660. target->IsSystemIncludeDirectory(i, config, lang)) {
  661. includeFlags << sysFwSearchFlag;
  662. } else {
  663. includeFlags << fwSearchFlag;
  664. }
  665. includeFlags << this->ConvertToOutputFormat(frameworkDir, shellFormat)
  666. << " ";
  667. }
  668. continue;
  669. }
  670. if (!flagUsed || repeatFlag) {
  671. if (sysIncludeFlag && target &&
  672. target->IsSystemIncludeDirectory(i, config, lang)) {
  673. includeFlags << sysIncludeFlag;
  674. } else {
  675. includeFlags << includeFlag;
  676. }
  677. flagUsed = true;
  678. }
  679. std::string includePath =
  680. this->ConvertToIncludeReference(i, shellFormat, forceFullPaths);
  681. if (quotePaths && !includePath.empty() && includePath[0] != '\"') {
  682. includeFlags << "\"";
  683. }
  684. includeFlags << includePath;
  685. if (quotePaths && !includePath.empty() && includePath[0] != '\"') {
  686. includeFlags << "\"";
  687. }
  688. includeFlags << sep;
  689. }
  690. std::string flags = includeFlags.str();
  691. // remove trailing separators
  692. if ((sep[0] != ' ') && !flags.empty() && flags[flags.size() - 1] == sep[0]) {
  693. flags[flags.size() - 1] = ' ';
  694. }
  695. return flags;
  696. }
  697. void cmLocalGenerator::AddCompileDefinitions(std::set<std::string>& defines,
  698. cmGeneratorTarget const* target,
  699. const std::string& config,
  700. const std::string& lang) const
  701. {
  702. std::vector<std::string> targetDefines;
  703. target->GetCompileDefinitions(targetDefines, config, lang);
  704. this->AppendDefines(defines, targetDefines);
  705. }
  706. void cmLocalGenerator::AddCompileOptions(std::string& flags,
  707. cmGeneratorTarget* target,
  708. const std::string& lang,
  709. const std::string& config)
  710. {
  711. std::string langFlagRegexVar = std::string("CMAKE_") + lang + "_FLAG_REGEX";
  712. if (const char* langFlagRegexStr =
  713. this->Makefile->GetDefinition(langFlagRegexVar)) {
  714. // Filter flags acceptable to this language.
  715. std::vector<std::string> opts;
  716. if (const char* targetFlags = target->GetProperty("COMPILE_FLAGS")) {
  717. cmSystemTools::ParseWindowsCommandLine(targetFlags, opts);
  718. }
  719. target->GetCompileOptions(opts, config, lang);
  720. // (Re-)Escape these flags. COMPILE_FLAGS were already parsed
  721. // as a command line above, and COMPILE_OPTIONS are escaped.
  722. this->AppendCompileOptions(flags, opts, langFlagRegexStr);
  723. } else {
  724. // Use all flags.
  725. if (const char* targetFlags = target->GetProperty("COMPILE_FLAGS")) {
  726. // COMPILE_FLAGS are not escaped for historical reasons.
  727. this->AppendFlags(flags, targetFlags);
  728. }
  729. std::vector<std::string> opts;
  730. target->GetCompileOptions(opts, config, lang);
  731. // COMPILE_OPTIONS are escaped.
  732. this->AppendCompileOptions(flags, opts);
  733. }
  734. for (auto const& it : target->GetMaxLanguageStandards()) {
  735. const char* standard = target->GetProperty(it.first + "_STANDARD");
  736. if (!standard) {
  737. continue;
  738. }
  739. if (this->Makefile->IsLaterStandard(it.first, standard, it.second)) {
  740. std::ostringstream e;
  741. e << "The COMPILE_FEATURES property of target \"" << target->GetName()
  742. << "\" was evaluated when computing the link "
  743. "implementation, and the \""
  744. << it.first << "_STANDARD\" was \"" << it.second
  745. << "\" for that computation. Computing the "
  746. "COMPILE_FEATURES based on the link implementation resulted in a "
  747. "higher \""
  748. << it.first << "_STANDARD\" \"" << standard
  749. << "\". "
  750. "This is not permitted. The COMPILE_FEATURES may not both depend "
  751. "on "
  752. "and be depended on by the link implementation."
  753. << std::endl;
  754. this->IssueMessage(cmake::FATAL_ERROR, e.str());
  755. return;
  756. }
  757. }
  758. this->AddCompilerRequirementFlag(flags, target, lang);
  759. }
  760. void cmLocalGenerator::GetIncludeDirectories(std::vector<std::string>& dirs,
  761. cmGeneratorTarget const* target,
  762. const std::string& lang,
  763. const std::string& config,
  764. bool stripImplicitInclDirs) const
  765. {
  766. // Need to decide whether to automatically include the source and
  767. // binary directories at the beginning of the include path.
  768. bool includeSourceDir = false;
  769. bool includeBinaryDir = false;
  770. // When automatic include directories are requested for a build then
  771. // include the source and binary directories at the beginning of the
  772. // include path to approximate include file behavior for an
  773. // in-source build. This does not account for the case of a source
  774. // file in a subdirectory of the current source directory but we
  775. // cannot fix this because not all native build tools support
  776. // per-source-file include paths.
  777. if (this->Makefile->IsOn("CMAKE_INCLUDE_CURRENT_DIR")) {
  778. includeSourceDir = true;
  779. includeBinaryDir = true;
  780. }
  781. // Do not repeat an include path.
  782. std::set<std::string> emitted;
  783. // Store the automatic include paths.
  784. if (includeBinaryDir) {
  785. std::string binDir = this->StateSnapshot.GetDirectory().GetCurrentBinary();
  786. if (emitted.find(binDir) == emitted.end()) {
  787. dirs.push_back(binDir);
  788. emitted.insert(binDir);
  789. }
  790. }
  791. if (includeSourceDir) {
  792. std::string srcDir = this->StateSnapshot.GetDirectory().GetCurrentSource();
  793. if (emitted.find(srcDir) == emitted.end()) {
  794. dirs.push_back(srcDir);
  795. emitted.insert(srcDir);
  796. }
  797. }
  798. if (!target) {
  799. return;
  800. }
  801. std::string rootPath;
  802. if (const char* sysrootCompile =
  803. this->Makefile->GetDefinition("CMAKE_SYSROOT_COMPILE")) {
  804. rootPath = sysrootCompile;
  805. } else {
  806. rootPath = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
  807. }
  808. std::vector<std::string> implicitDirs;
  809. // Load implicit include directories for this language.
  810. std::string impDirVar = "CMAKE_";
  811. impDirVar += lang;
  812. impDirVar += "_IMPLICIT_INCLUDE_DIRECTORIES";
  813. if (const char* value = this->Makefile->GetDefinition(impDirVar)) {
  814. std::vector<std::string> impDirVec;
  815. cmSystemTools::ExpandListArgument(value, impDirVec);
  816. for (std::string const& i : impDirVec) {
  817. std::string d = rootPath + i;
  818. cmSystemTools::ConvertToUnixSlashes(d);
  819. emitted.insert(std::move(d));
  820. if (!stripImplicitInclDirs) {
  821. implicitDirs.push_back(i);
  822. }
  823. }
  824. }
  825. // Get the target-specific include directories.
  826. std::vector<std::string> includes;
  827. includes = target->GetIncludeDirectories(config, lang);
  828. // Support putting all the in-project include directories first if
  829. // it is requested by the project.
  830. if (this->Makefile->IsOn("CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE")) {
  831. std::string const &topSourceDir = this->GetState()->GetSourceDirectory(),
  832. &topBinaryDir = this->GetState()->GetBinaryDirectory();
  833. for (std::string const& i : includes) {
  834. // Emit this directory only if it is a subdirectory of the
  835. // top-level source or binary tree.
  836. if (cmSystemTools::ComparePath(i, topSourceDir) ||
  837. cmSystemTools::ComparePath(i, topBinaryDir) ||
  838. cmSystemTools::IsSubDirectory(i, topSourceDir) ||
  839. cmSystemTools::IsSubDirectory(i, topBinaryDir)) {
  840. if (emitted.insert(i).second) {
  841. dirs.push_back(i);
  842. }
  843. }
  844. }
  845. }
  846. // Construct the final ordered include directory list.
  847. for (std::string const& i : includes) {
  848. if (emitted.insert(i).second) {
  849. dirs.push_back(i);
  850. }
  851. }
  852. this->MoveSystemIncludesToEnd(dirs, config, lang, target);
  853. // Add standard include directories for this language.
  854. // We do not filter out implicit directories here.
  855. std::string const standardIncludesVar =
  856. "CMAKE_" + lang + "_STANDARD_INCLUDE_DIRECTORIES";
  857. std::string const standardIncludes =
  858. this->Makefile->GetSafeDefinition(standardIncludesVar);
  859. std::vector<std::string>::size_type const before = includes.size();
  860. cmSystemTools::ExpandListArgument(standardIncludes, includes);
  861. for (std::vector<std::string>::iterator i = includes.begin() + before;
  862. i != includes.end(); ++i) {
  863. cmSystemTools::ConvertToUnixSlashes(*i);
  864. dirs.push_back(*i);
  865. }
  866. for (std::string const& i : implicitDirs) {
  867. if (std::find(includes.begin(), includes.end(), i) != includes.end()) {
  868. dirs.push_back(i);
  869. }
  870. }
  871. }
  872. void cmLocalGenerator::GetStaticLibraryFlags(std::string& flags,
  873. std::string const& config,
  874. cmGeneratorTarget* target)
  875. {
  876. this->AppendFlags(
  877. flags, this->Makefile->GetSafeDefinition("CMAKE_STATIC_LINKER_FLAGS"));
  878. if (!config.empty()) {
  879. std::string name = "CMAKE_STATIC_LINKER_FLAGS_" + config;
  880. this->AppendFlags(flags, this->Makefile->GetSafeDefinition(name));
  881. }
  882. this->AppendFlags(flags, target->GetProperty("STATIC_LIBRARY_FLAGS"));
  883. if (!config.empty()) {
  884. std::string name = "STATIC_LIBRARY_FLAGS_" + config;
  885. this->AppendFlags(flags, target->GetProperty(name));
  886. }
  887. }
  888. void cmLocalGenerator::GetTargetFlags(
  889. cmLinkLineComputer* linkLineComputer, const std::string& config,
  890. std::string& linkLibs, std::string& flags, std::string& linkFlags,
  891. std::string& frameworkPath, std::string& linkPath, cmGeneratorTarget* target)
  892. {
  893. const std::string buildType = cmSystemTools::UpperCase(config);
  894. cmComputeLinkInformation* pcli = target->GetLinkInformation(config);
  895. const char* libraryLinkVariable =
  896. "CMAKE_SHARED_LINKER_FLAGS"; // default to shared library
  897. const std::string linkLanguage =
  898. linkLineComputer->GetLinkerLanguage(target, buildType);
  899. switch (target->GetType()) {
  900. case cmStateEnums::STATIC_LIBRARY:
  901. this->GetStaticLibraryFlags(linkFlags, buildType, target);
  902. break;
  903. case cmStateEnums::MODULE_LIBRARY:
  904. libraryLinkVariable = "CMAKE_MODULE_LINKER_FLAGS";
  905. CM_FALLTHROUGH;
  906. case cmStateEnums::SHARED_LIBRARY: {
  907. linkFlags = this->Makefile->GetSafeDefinition(libraryLinkVariable);
  908. linkFlags += " ";
  909. if (!buildType.empty()) {
  910. std::string build = libraryLinkVariable;
  911. build += "_";
  912. build += buildType;
  913. linkFlags += this->Makefile->GetSafeDefinition(build);
  914. linkFlags += " ";
  915. }
  916. if (this->Makefile->IsOn("WIN32") &&
  917. !(this->Makefile->IsOn("CYGWIN") || this->Makefile->IsOn("MINGW"))) {
  918. std::vector<cmSourceFile*> sources;
  919. target->GetSourceFiles(sources, buildType);
  920. std::string defFlag =
  921. this->Makefile->GetSafeDefinition("CMAKE_LINK_DEF_FILE_FLAG");
  922. for (cmSourceFile* sf : sources) {
  923. if (sf->GetExtension() == "def") {
  924. linkFlags += defFlag;
  925. linkFlags += this->ConvertToOutputFormat(
  926. cmSystemTools::CollapseFullPath(sf->GetFullPath()), SHELL);
  927. linkFlags += " ";
  928. }
  929. }
  930. }
  931. const char* targetLinkFlags = target->GetProperty("LINK_FLAGS");
  932. if (targetLinkFlags) {
  933. linkFlags += targetLinkFlags;
  934. linkFlags += " ";
  935. }
  936. if (!buildType.empty()) {
  937. std::string configLinkFlags = "LINK_FLAGS_";
  938. configLinkFlags += buildType;
  939. targetLinkFlags = target->GetProperty(configLinkFlags);
  940. if (targetLinkFlags) {
  941. linkFlags += targetLinkFlags;
  942. linkFlags += " ";
  943. }
  944. }
  945. std::vector<std::string> opts;
  946. target->GetLinkOptions(opts, config, linkLanguage);
  947. // LINK_OPTIONS are escaped.
  948. this->AppendCompileOptions(linkFlags, opts);
  949. if (pcli) {
  950. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  951. frameworkPath, linkPath);
  952. }
  953. } break;
  954. case cmStateEnums::EXECUTABLE: {
  955. linkFlags += this->Makefile->GetSafeDefinition("CMAKE_EXE_LINKER_FLAGS");
  956. linkFlags += " ";
  957. if (!buildType.empty()) {
  958. std::string build = "CMAKE_EXE_LINKER_FLAGS_";
  959. build += buildType;
  960. linkFlags += this->Makefile->GetSafeDefinition(build);
  961. linkFlags += " ";
  962. }
  963. if (linkLanguage.empty()) {
  964. cmSystemTools::Error(
  965. "CMake can not determine linker language for target: ",
  966. target->GetName().c_str());
  967. return;
  968. }
  969. this->AddLanguageFlagsForLinking(flags, target, linkLanguage, buildType);
  970. if (pcli) {
  971. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  972. frameworkPath, linkPath);
  973. }
  974. if (cmSystemTools::IsOn(
  975. this->Makefile->GetDefinition("BUILD_SHARED_LIBS"))) {
  976. std::string sFlagVar = std::string("CMAKE_SHARED_BUILD_") +
  977. linkLanguage + std::string("_FLAGS");
  978. linkFlags += this->Makefile->GetSafeDefinition(sFlagVar);
  979. linkFlags += " ";
  980. }
  981. if (target->GetPropertyAsBool("WIN32_EXECUTABLE")) {
  982. linkFlags +=
  983. this->Makefile->GetSafeDefinition("CMAKE_CREATE_WIN32_EXE");
  984. linkFlags += " ";
  985. } else {
  986. linkFlags +=
  987. this->Makefile->GetSafeDefinition("CMAKE_CREATE_CONSOLE_EXE");
  988. linkFlags += " ";
  989. }
  990. if (target->IsExecutableWithExports()) {
  991. std::string exportFlagVar = "CMAKE_EXE_EXPORTS_";
  992. exportFlagVar += linkLanguage;
  993. exportFlagVar += "_FLAG";
  994. linkFlags += this->Makefile->GetSafeDefinition(exportFlagVar);
  995. linkFlags += " ";
  996. }
  997. std::string cmp0065Flags =
  998. this->GetLinkLibsCMP0065(linkLanguage, *target);
  999. if (!cmp0065Flags.empty()) {
  1000. linkFlags += cmp0065Flags;
  1001. linkFlags += " ";
  1002. }
  1003. const char* targetLinkFlags = target->GetProperty("LINK_FLAGS");
  1004. if (targetLinkFlags) {
  1005. linkFlags += targetLinkFlags;
  1006. linkFlags += " ";
  1007. }
  1008. if (!buildType.empty()) {
  1009. std::string configLinkFlags = "LINK_FLAGS_";
  1010. configLinkFlags += buildType;
  1011. targetLinkFlags = target->GetProperty(configLinkFlags);
  1012. if (targetLinkFlags) {
  1013. linkFlags += targetLinkFlags;
  1014. linkFlags += " ";
  1015. }
  1016. }
  1017. std::vector<std::string> opts;
  1018. target->GetLinkOptions(opts, config, linkLanguage);
  1019. // LINK_OPTIONS are escaped.
  1020. this->AppendCompileOptions(linkFlags, opts);
  1021. } break;
  1022. default:
  1023. break;
  1024. }
  1025. this->AppendIPOLinkerFlags(linkFlags, target, config, linkLanguage);
  1026. }
  1027. void cmLocalGenerator::GetTargetCompileFlags(cmGeneratorTarget* target,
  1028. std::string const& config,
  1029. std::string const& lang,
  1030. std::string& flags)
  1031. {
  1032. cmMakefile* mf = this->GetMakefile();
  1033. // Add language-specific flags.
  1034. this->AddLanguageFlags(flags, target, lang, config);
  1035. this->AddArchitectureFlags(flags, target, lang, config);
  1036. if (lang == "Fortran") {
  1037. this->AppendFlags(flags, this->GetTargetFortranFlags(target, config));
  1038. }
  1039. this->AddCMP0018Flags(flags, target, lang, config);
  1040. this->AddVisibilityPresetFlags(flags, target, lang);
  1041. this->AppendFlags(flags, mf->GetDefineFlags());
  1042. this->AppendFlags(flags, this->GetFrameworkFlags(lang, config, target));
  1043. this->AddCompileOptions(flags, target, lang, config);
  1044. }
  1045. static std::string GetFrameworkFlags(const std::string& lang,
  1046. const std::string& config,
  1047. cmGeneratorTarget* target)
  1048. {
  1049. cmLocalGenerator* lg = target->GetLocalGenerator();
  1050. cmMakefile* mf = lg->GetMakefile();
  1051. if (!mf->IsOn("APPLE")) {
  1052. return std::string();
  1053. }
  1054. std::string fwSearchFlagVar = "CMAKE_" + lang + "_FRAMEWORK_SEARCH_FLAG";
  1055. const char* fwSearchFlag = mf->GetDefinition(fwSearchFlagVar);
  1056. if (!(fwSearchFlag && *fwSearchFlag)) {
  1057. return std::string();
  1058. }
  1059. std::set<std::string> emitted;
  1060. #ifdef __APPLE__ /* don't insert this when crosscompiling e.g. to iphone */
  1061. emitted.insert("/System/Library/Frameworks");
  1062. #endif
  1063. std::vector<std::string> includes;
  1064. lg->GetIncludeDirectories(includes, target, "C", config);
  1065. // check all include directories for frameworks as this
  1066. // will already have added a -F for the framework
  1067. for (std::string const& include : includes) {
  1068. if (lg->GetGlobalGenerator()->NameResolvesToFramework(include)) {
  1069. std::string frameworkDir = include;
  1070. frameworkDir += "/../";
  1071. frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
  1072. emitted.insert(frameworkDir);
  1073. }
  1074. }
  1075. std::string flags;
  1076. if (cmComputeLinkInformation* cli = target->GetLinkInformation(config)) {
  1077. std::vector<std::string> const& frameworks = cli->GetFrameworkPaths();
  1078. for (std::string const& framework : frameworks) {
  1079. if (emitted.insert(framework).second) {
  1080. flags += fwSearchFlag;
  1081. flags +=
  1082. lg->ConvertToOutputFormat(framework, cmOutputConverter::SHELL);
  1083. flags += " ";
  1084. }
  1085. }
  1086. }
  1087. return flags;
  1088. }
  1089. std::string cmLocalGenerator::GetFrameworkFlags(std::string const& l,
  1090. std::string const& config,
  1091. cmGeneratorTarget* target)
  1092. {
  1093. return ::GetFrameworkFlags(l, config, target);
  1094. }
  1095. void cmLocalGenerator::GetTargetDefines(cmGeneratorTarget const* target,
  1096. std::string const& config,
  1097. std::string const& lang,
  1098. std::set<std::string>& defines) const
  1099. {
  1100. // Add the export symbol definition for shared library objects.
  1101. if (const char* exportMacro = target->GetExportMacro()) {
  1102. this->AppendDefines(defines, exportMacro);
  1103. }
  1104. // Add preprocessor definitions for this target and configuration.
  1105. this->AddCompileDefinitions(defines, target, config, lang);
  1106. }
  1107. std::string cmLocalGenerator::GetTargetFortranFlags(
  1108. cmGeneratorTarget const* /*unused*/, std::string const& /*unused*/)
  1109. {
  1110. // Implemented by specific generators that override this.
  1111. return std::string();
  1112. }
  1113. /**
  1114. * Output the linking rules on a command line. For executables,
  1115. * targetLibrary should be a NULL pointer. For libraries, it should point
  1116. * to the name of the library. This will not link a library against itself.
  1117. */
  1118. void cmLocalGenerator::OutputLinkLibraries(
  1119. cmComputeLinkInformation* pcli, cmLinkLineComputer* linkLineComputer,
  1120. std::string& linkLibraries, std::string& frameworkPath,
  1121. std::string& linkPath)
  1122. {
  1123. cmComputeLinkInformation& cli = *pcli;
  1124. std::string linkLanguage = cli.GetLinkLanguage();
  1125. std::string libPathFlag =
  1126. this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_FLAG");
  1127. std::string libPathTerminator =
  1128. this->Makefile->GetSafeDefinition("CMAKE_LIBRARY_PATH_TERMINATOR");
  1129. // Add standard libraries for this language.
  1130. std::string standardLibsVar = "CMAKE_";
  1131. standardLibsVar += cli.GetLinkLanguage();
  1132. standardLibsVar += "_STANDARD_LIBRARIES";
  1133. std::string stdLibString;
  1134. if (const char* stdLibs = this->Makefile->GetDefinition(standardLibsVar)) {
  1135. stdLibString = stdLibs;
  1136. }
  1137. // Append the framework search path flags.
  1138. std::string fwSearchFlagVar = "CMAKE_";
  1139. fwSearchFlagVar += linkLanguage;
  1140. fwSearchFlagVar += "_FRAMEWORK_SEARCH_FLAG";
  1141. std::string fwSearchFlag =
  1142. this->Makefile->GetSafeDefinition(fwSearchFlagVar);
  1143. frameworkPath = linkLineComputer->ComputeFrameworkPath(cli, fwSearchFlag);
  1144. linkPath =
  1145. linkLineComputer->ComputeLinkPath(cli, libPathFlag, libPathTerminator);
  1146. linkLibraries = linkLineComputer->ComputeLinkLibraries(cli, stdLibString);
  1147. }
  1148. std::string cmLocalGenerator::GetLinkLibsCMP0065(
  1149. std::string const& linkLanguage, cmGeneratorTarget& tgt) const
  1150. {
  1151. std::string linkFlags;
  1152. // Flags to link an executable to shared libraries.
  1153. if (tgt.GetType() == cmStateEnums::EXECUTABLE &&
  1154. this->StateSnapshot.GetState()->GetGlobalPropertyAsBool(
  1155. "TARGET_SUPPORTS_SHARED_LIBS")) {
  1156. bool add_shlib_flags = false;
  1157. switch (tgt.GetPolicyStatusCMP0065()) {
  1158. case cmPolicies::WARN:
  1159. if (!tgt.GetPropertyAsBool("ENABLE_EXPORTS") &&
  1160. this->Makefile->PolicyOptionalWarningEnabled(
  1161. "CMAKE_POLICY_WARNING_CMP0065")) {
  1162. std::ostringstream w;
  1163. /* clang-format off */
  1164. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0065) << "\n"
  1165. "For compatibility with older versions of CMake, "
  1166. "additional flags may be added to export symbols on all "
  1167. "executables regardless of their ENABLE_EXPORTS property.";
  1168. /* clang-format on */
  1169. this->IssueMessage(cmake::AUTHOR_WARNING, w.str());
  1170. }
  1171. CM_FALLTHROUGH;
  1172. case cmPolicies::OLD:
  1173. // OLD behavior is to always add the flags
  1174. add_shlib_flags = true;
  1175. break;
  1176. case cmPolicies::REQUIRED_IF_USED:
  1177. case cmPolicies::REQUIRED_ALWAYS:
  1178. this->IssueMessage(
  1179. cmake::FATAL_ERROR,
  1180. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0065));
  1181. CM_FALLTHROUGH;
  1182. case cmPolicies::NEW:
  1183. // NEW behavior is to only add the flags if ENABLE_EXPORTS is on
  1184. add_shlib_flags = tgt.GetPropertyAsBool("ENABLE_EXPORTS");
  1185. break;
  1186. }
  1187. if (add_shlib_flags) {
  1188. std::string linkFlagsVar = "CMAKE_SHARED_LIBRARY_LINK_";
  1189. linkFlagsVar += linkLanguage;
  1190. linkFlagsVar += "_FLAGS";
  1191. linkFlags = this->Makefile->GetSafeDefinition(linkFlagsVar);
  1192. }
  1193. }
  1194. return linkFlags;
  1195. }
  1196. void cmLocalGenerator::AddArchitectureFlags(std::string& flags,
  1197. cmGeneratorTarget const* target,
  1198. const std::string& lang,
  1199. const std::string& config)
  1200. {
  1201. // Only add Mac OS X specific flags on Darwin platforms (OSX and iphone):
  1202. if (this->Makefile->IsOn("APPLE") && this->EmitUniversalBinaryFlags) {
  1203. std::vector<std::string> archs;
  1204. target->GetAppleArchs(config, archs);
  1205. const char* sysroot = this->Makefile->GetDefinition("CMAKE_OSX_SYSROOT");
  1206. if (sysroot && sysroot[0] == '/' && !sysroot[1]) {
  1207. sysroot = nullptr;
  1208. }
  1209. std::string sysrootFlagVar =
  1210. std::string("CMAKE_") + lang + "_SYSROOT_FLAG";
  1211. const char* sysrootFlag = this->Makefile->GetDefinition(sysrootFlagVar);
  1212. const char* deploymentTarget =
  1213. this->Makefile->GetDefinition("CMAKE_OSX_DEPLOYMENT_TARGET");
  1214. std::string deploymentTargetFlagVar =
  1215. std::string("CMAKE_") + lang + "_OSX_DEPLOYMENT_TARGET_FLAG";
  1216. const char* deploymentTargetFlag =
  1217. this->Makefile->GetDefinition(deploymentTargetFlagVar);
  1218. if (!archs.empty() && !lang.empty() &&
  1219. (lang[0] == 'C' || lang[0] == 'F')) {
  1220. for (std::string const& arch : archs) {
  1221. flags += " -arch ";
  1222. flags += arch;
  1223. }
  1224. }
  1225. if (sysrootFlag && *sysrootFlag && sysroot && *sysroot) {
  1226. flags += " ";
  1227. flags += sysrootFlag;
  1228. flags += " ";
  1229. flags += this->ConvertToOutputFormat(sysroot, SHELL);
  1230. }
  1231. if (deploymentTargetFlag && *deploymentTargetFlag && deploymentTarget &&
  1232. *deploymentTarget) {
  1233. flags += " ";
  1234. flags += deploymentTargetFlag;
  1235. flags += deploymentTarget;
  1236. }
  1237. }
  1238. }
  1239. void cmLocalGenerator::AddLanguageFlags(std::string& flags,
  1240. cmGeneratorTarget const* target,
  1241. const std::string& lang,
  1242. const std::string& config)
  1243. {
  1244. // Add language-specific flags.
  1245. std::string flagsVar = "CMAKE_";
  1246. flagsVar += lang;
  1247. flagsVar += "_FLAGS";
  1248. this->AddConfigVariableFlags(flags, flagsVar, config);
  1249. if (target->IsIPOEnabled(lang, config)) {
  1250. this->AppendFeatureOptions(flags, lang, "IPO");
  1251. }
  1252. }
  1253. void cmLocalGenerator::AddLanguageFlagsForLinking(
  1254. std::string& flags, cmGeneratorTarget const* target, const std::string& lang,
  1255. const std::string& config)
  1256. {
  1257. if (this->Makefile->IsOn("CMAKE_" + lang +
  1258. "_LINK_WITH_STANDARD_COMPILE_OPTION")) {
  1259. // This toolchain requires use of the language standard flag
  1260. // when linking in order to use the matching standard library.
  1261. // FIXME: If CMake gains an abstraction for standard library
  1262. // selection, this will have to be reconciled with it.
  1263. this->AddCompilerRequirementFlag(flags, target, lang);
  1264. }
  1265. this->AddLanguageFlags(flags, target, lang, config);
  1266. }
  1267. cmGeneratorTarget* cmLocalGenerator::FindGeneratorTargetToUse(
  1268. const std::string& name) const
  1269. {
  1270. GeneratorTargetMap::const_iterator imported =
  1271. this->ImportedGeneratorTargets.find(name);
  1272. if (imported != this->ImportedGeneratorTargets.end()) {
  1273. return imported->second;
  1274. }
  1275. if (cmGeneratorTarget* t = this->FindLocalNonAliasGeneratorTarget(name)) {
  1276. return t;
  1277. }
  1278. return this->GetGlobalGenerator()->FindGeneratorTarget(name);
  1279. }
  1280. bool cmLocalGenerator::GetRealDependency(const std::string& inName,
  1281. const std::string& config,
  1282. std::string& dep)
  1283. {
  1284. // Older CMake code may specify the dependency using the target
  1285. // output file rather than the target name. Such code would have
  1286. // been written before there was support for target properties that
  1287. // modify the name so stripping down to just the file name should
  1288. // produce the target name in this case.
  1289. std::string name = cmSystemTools::GetFilenameName(inName);
  1290. // If the input name is the empty string, there is no real
  1291. // dependency. Short-circuit the other checks:
  1292. if (name.empty()) {
  1293. return false;
  1294. }
  1295. if (cmSystemTools::GetFilenameLastExtension(name) == ".exe") {
  1296. name = cmSystemTools::GetFilenameWithoutLastExtension(name);
  1297. }
  1298. // Look for a CMake target with the given name.
  1299. if (cmGeneratorTarget* target = this->FindGeneratorTargetToUse(name)) {
  1300. // make sure it is not just a coincidence that the target name
  1301. // found is part of the inName
  1302. if (cmSystemTools::FileIsFullPath(inName)) {
  1303. std::string tLocation;
  1304. if (target->GetType() >= cmStateEnums::EXECUTABLE &&
  1305. target->GetType() <= cmStateEnums::MODULE_LIBRARY) {
  1306. tLocation = target->GetLocation(config);
  1307. tLocation = cmSystemTools::GetFilenamePath(tLocation);
  1308. tLocation = cmSystemTools::CollapseFullPath(tLocation);
  1309. }
  1310. std::string depLocation =
  1311. cmSystemTools::GetFilenamePath(std::string(inName));
  1312. depLocation = cmSystemTools::CollapseFullPath(depLocation);
  1313. if (depLocation != tLocation) {
  1314. // it is a full path to a depend that has the same name
  1315. // as a target but is in a different location so do not use
  1316. // the target as the depend
  1317. dep = inName;
  1318. return true;
  1319. }
  1320. }
  1321. switch (target->GetType()) {
  1322. case cmStateEnums::EXECUTABLE:
  1323. case cmStateEnums::STATIC_LIBRARY:
  1324. case cmStateEnums::SHARED_LIBRARY:
  1325. case cmStateEnums::MODULE_LIBRARY:
  1326. case cmStateEnums::UNKNOWN_LIBRARY:
  1327. dep = target->GetLocation(config);
  1328. return true;
  1329. case cmStateEnums::OBJECT_LIBRARY:
  1330. // An object library has no single file on which to depend.
  1331. // This was listed to get the target-level dependency.
  1332. return false;
  1333. case cmStateEnums::INTERFACE_LIBRARY:
  1334. // An interface library has no file on which to depend.
  1335. // This was listed to get the target-level dependency.
  1336. return false;
  1337. case cmStateEnums::UTILITY:
  1338. case cmStateEnums::GLOBAL_TARGET:
  1339. // A utility target has no file on which to depend. This was listed
  1340. // only to get the target-level dependency.
  1341. return false;
  1342. }
  1343. }
  1344. // The name was not that of a CMake target. It must name a file.
  1345. if (cmSystemTools::FileIsFullPath(inName)) {
  1346. // This is a full path. Return it as given.
  1347. dep = inName;
  1348. return true;
  1349. }
  1350. // Check for a source file in this directory that matches the
  1351. // dependency.
  1352. if (cmSourceFile* sf = this->Makefile->GetSource(inName)) {
  1353. dep = sf->GetFullPath();
  1354. return true;
  1355. }
  1356. // Treat the name as relative to the source directory in which it
  1357. // was given.
  1358. dep = this->StateSnapshot.GetDirectory().GetCurrentSource();
  1359. dep += "/";
  1360. dep += inName;
  1361. return true;
  1362. }
  1363. void cmLocalGenerator::AddSharedFlags(std::string& flags,
  1364. const std::string& lang, bool shared)
  1365. {
  1366. std::string flagsVar;
  1367. // Add flags for dealing with shared libraries for this language.
  1368. if (shared) {
  1369. flagsVar = "CMAKE_SHARED_LIBRARY_";
  1370. flagsVar += lang;
  1371. flagsVar += "_FLAGS";
  1372. this->AppendFlags(flags, this->Makefile->GetDefinition(flagsVar));
  1373. }
  1374. }
  1375. void cmLocalGenerator::AddCompilerRequirementFlag(
  1376. std::string& flags, cmGeneratorTarget const* target, const std::string& lang)
  1377. {
  1378. if (lang.empty()) {
  1379. return;
  1380. }
  1381. const char* defaultStd =
  1382. this->Makefile->GetDefinition("CMAKE_" + lang + "_STANDARD_DEFAULT");
  1383. if (!defaultStd || !*defaultStd) {
  1384. // This compiler has no notion of language standard levels.
  1385. return;
  1386. }
  1387. std::string extProp = lang + "_EXTENSIONS";
  1388. bool ext = true;
  1389. if (const char* extPropValue = target->GetProperty(extProp)) {
  1390. if (cmSystemTools::IsOff(extPropValue)) {
  1391. ext = false;
  1392. }
  1393. }
  1394. std::string stdProp = lang + "_STANDARD";
  1395. const char* standardProp = target->GetProperty(stdProp);
  1396. if (!standardProp) {
  1397. if (ext) {
  1398. // No language standard is specified and extensions are not disabled.
  1399. // Check if this compiler needs a flag to enable extensions.
  1400. std::string const option_flag =
  1401. "CMAKE_" + lang + "_EXTENSION_COMPILE_OPTION";
  1402. if (const char* opt =
  1403. target->Target->GetMakefile()->GetDefinition(option_flag)) {
  1404. std::vector<std::string> optVec;
  1405. cmSystemTools::ExpandListArgument(opt, optVec);
  1406. for (std::string const& i : optVec) {
  1407. this->AppendFlagEscape(flags, i);
  1408. }
  1409. }
  1410. }
  1411. return;
  1412. }
  1413. std::string const type = ext ? "EXTENSION" : "STANDARD";
  1414. if (target->GetPropertyAsBool(lang + "_STANDARD_REQUIRED")) {
  1415. std::string option_flag =
  1416. "CMAKE_" + lang + standardProp + "_" + type + "_COMPILE_OPTION";
  1417. const char* opt =
  1418. target->Target->GetMakefile()->GetDefinition(option_flag);
  1419. if (!opt) {
  1420. std::ostringstream e;
  1421. e << "Target \"" << target->GetName()
  1422. << "\" requires the language "
  1423. "dialect \""
  1424. << lang << standardProp << "\" "
  1425. << (ext ? "(with compiler extensions)" : "")
  1426. << ", but CMake "
  1427. "does not know the compile flags to use to enable it.";
  1428. this->IssueMessage(cmake::FATAL_ERROR, e.str());
  1429. } else {
  1430. std::vector<std::string> optVec;
  1431. cmSystemTools::ExpandListArgument(opt, optVec);
  1432. for (std::string const& i : optVec) {
  1433. this->AppendFlagEscape(flags, i);
  1434. }
  1435. }
  1436. return;
  1437. }
  1438. static std::map<std::string, std::vector<std::string>> langStdMap;
  1439. if (langStdMap.empty()) {
  1440. // Maintain sorted order, most recent first.
  1441. langStdMap["CXX"].push_back("20");
  1442. langStdMap["CXX"].push_back("17");
  1443. langStdMap["CXX"].push_back("14");
  1444. langStdMap["CXX"].push_back("11");
  1445. langStdMap["CXX"].push_back("98");
  1446. langStdMap["C"].push_back("11");
  1447. langStdMap["C"].push_back("99");
  1448. langStdMap["C"].push_back("90");
  1449. langStdMap["CUDA"].push_back("14");
  1450. langStdMap["CUDA"].push_back("11");
  1451. langStdMap["CUDA"].push_back("98");
  1452. }
  1453. std::string standard(standardProp);
  1454. std::vector<std::string>& stds = langStdMap[lang];
  1455. std::vector<std::string>::const_iterator stdIt =
  1456. std::find(stds.begin(), stds.end(), standard);
  1457. if (stdIt == stds.end()) {
  1458. std::string e =
  1459. lang + "_STANDARD is set to invalid value '" + standard + "'";
  1460. this->GetGlobalGenerator()->GetCMakeInstance()->IssueMessage(
  1461. cmake::FATAL_ERROR, e, target->GetBacktrace());
  1462. return;
  1463. }
  1464. std::vector<std::string>::const_iterator defaultStdIt =
  1465. std::find(stds.begin(), stds.end(), defaultStd);
  1466. if (defaultStdIt == stds.end()) {
  1467. std::string e = "CMAKE_" + lang +
  1468. "_STANDARD_DEFAULT is set to invalid value '" + std::string(defaultStd) +
  1469. "'";
  1470. this->IssueMessage(cmake::INTERNAL_ERROR, e);
  1471. return;
  1472. }
  1473. // If the standard requested is older than the compiler's default
  1474. // then we need to use a flag to change it. The comparison is
  1475. // greater-or-equal because the standards are stored in backward
  1476. // chronological order.
  1477. if (stdIt >= defaultStdIt) {
  1478. std::string option_flag =
  1479. "CMAKE_" + lang + *stdIt + "_" + type + "_COMPILE_OPTION";
  1480. const char* opt =
  1481. target->Target->GetMakefile()->GetRequiredDefinition(option_flag);
  1482. std::vector<std::string> optVec;
  1483. cmSystemTools::ExpandListArgument(opt, optVec);
  1484. for (std::string const& i : optVec) {
  1485. this->AppendFlagEscape(flags, i);
  1486. }
  1487. return;
  1488. }
  1489. // The standard requested is at least as new as the compiler's default,
  1490. // and the standard request is not required. Decay to the newest standard
  1491. // for which a flag is defined.
  1492. for (; stdIt < defaultStdIt; ++stdIt) {
  1493. std::string option_flag =
  1494. "CMAKE_" + lang + *stdIt + "_" + type + "_COMPILE_OPTION";
  1495. if (const char* opt =
  1496. target->Target->GetMakefile()->GetDefinition(option_flag)) {
  1497. std::vector<std::string> optVec;
  1498. cmSystemTools::ExpandListArgument(opt, optVec);
  1499. for (std::string const& i : optVec) {
  1500. this->AppendFlagEscape(flags, i);
  1501. }
  1502. return;
  1503. }
  1504. }
  1505. }
  1506. static void AddVisibilityCompileOption(std::string& flags,
  1507. cmGeneratorTarget const* target,
  1508. cmLocalGenerator* lg,
  1509. const std::string& lang,
  1510. std::string* warnCMP0063)
  1511. {
  1512. std::string compileOption = "CMAKE_" + lang + "_COMPILE_OPTIONS_VISIBILITY";
  1513. const char* opt = lg->GetMakefile()->GetDefinition(compileOption);
  1514. if (!opt) {
  1515. return;
  1516. }
  1517. std::string flagDefine = lang + "_VISIBILITY_PRESET";
  1518. const char* prop = target->GetProperty(flagDefine);
  1519. if (!prop) {
  1520. return;
  1521. }
  1522. if (warnCMP0063) {
  1523. *warnCMP0063 += " " + flagDefine + "\n";
  1524. return;
  1525. }
  1526. if (strcmp(prop, "hidden") != 0 && strcmp(prop, "default") != 0 &&
  1527. strcmp(prop, "protected") != 0 && strcmp(prop, "internal") != 0) {
  1528. std::ostringstream e;
  1529. e << "Target " << target->GetName() << " uses unsupported value \"" << prop
  1530. << "\" for " << flagDefine << ".";
  1531. cmSystemTools::Error(e.str().c_str());
  1532. return;
  1533. }
  1534. std::string option = std::string(opt) + prop;
  1535. lg->AppendFlags(flags, option);
  1536. }
  1537. static void AddInlineVisibilityCompileOption(std::string& flags,
  1538. cmGeneratorTarget const* target,
  1539. cmLocalGenerator* lg,
  1540. std::string* warnCMP0063)
  1541. {
  1542. std::string compileOption =
  1543. "CMAKE_CXX_COMPILE_OPTIONS_VISIBILITY_INLINES_HIDDEN";
  1544. const char* opt = lg->GetMakefile()->GetDefinition(compileOption);
  1545. if (!opt) {
  1546. return;
  1547. }
  1548. bool prop = target->GetPropertyAsBool("VISIBILITY_INLINES_HIDDEN");
  1549. if (!prop) {
  1550. return;
  1551. }
  1552. if (warnCMP0063) {
  1553. *warnCMP0063 += " VISIBILITY_INLINES_HIDDEN\n";
  1554. return;
  1555. }
  1556. lg->AppendFlags(flags, opt);
  1557. }
  1558. void cmLocalGenerator::AddVisibilityPresetFlags(
  1559. std::string& flags, cmGeneratorTarget const* target, const std::string& lang)
  1560. {
  1561. if (lang.empty()) {
  1562. return;
  1563. }
  1564. std::string warnCMP0063;
  1565. std::string* pWarnCMP0063 = nullptr;
  1566. if (target->GetType() != cmStateEnums::SHARED_LIBRARY &&
  1567. target->GetType() != cmStateEnums::MODULE_LIBRARY &&
  1568. !target->IsExecutableWithExports()) {
  1569. switch (target->GetPolicyStatusCMP0063()) {
  1570. case cmPolicies::OLD:
  1571. return;
  1572. case cmPolicies::WARN:
  1573. pWarnCMP0063 = &warnCMP0063;
  1574. break;
  1575. default:
  1576. break;
  1577. }
  1578. }
  1579. AddVisibilityCompileOption(flags, target, this, lang, pWarnCMP0063);
  1580. if (lang == "CXX") {
  1581. AddInlineVisibilityCompileOption(flags, target, this, pWarnCMP0063);
  1582. }
  1583. if (!warnCMP0063.empty() && this->WarnCMP0063.insert(target).second) {
  1584. std::ostringstream w;
  1585. /* clang-format off */
  1586. w <<
  1587. cmPolicies::GetPolicyWarning(cmPolicies::CMP0063) << "\n"
  1588. "Target \"" << target->GetName() << "\" of "
  1589. "type \"" << cmState::GetTargetTypeName(target->GetType()) << "\" "
  1590. "has the following visibility properties set for " << lang << ":\n" <<
  1591. warnCMP0063 <<
  1592. "For compatibility CMake is not honoring them for this target.";
  1593. /* clang-format on */
  1594. target->GetLocalGenerator()->GetCMakeInstance()->IssueMessage(
  1595. cmake::AUTHOR_WARNING, w.str(), target->GetBacktrace());
  1596. }
  1597. }
  1598. void cmLocalGenerator::AddCMP0018Flags(std::string& flags,
  1599. cmGeneratorTarget const* target,
  1600. std::string const& lang,
  1601. const std::string& config)
  1602. {
  1603. int targetType = target->GetType();
  1604. bool shared = ((targetType == cmStateEnums::SHARED_LIBRARY) ||
  1605. (targetType == cmStateEnums::MODULE_LIBRARY));
  1606. if (this->GetShouldUseOldFlags(shared, lang)) {
  1607. this->AddSharedFlags(flags, lang, shared);
  1608. } else {
  1609. if (target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  1610. if (target->GetPropertyAsBool("POSITION_INDEPENDENT_CODE")) {
  1611. this->AddPositionIndependentFlags(flags, lang, targetType);
  1612. }
  1613. return;
  1614. }
  1615. if (target->GetLinkInterfaceDependentBoolProperty(
  1616. "POSITION_INDEPENDENT_CODE", config)) {
  1617. this->AddPositionIndependentFlags(flags, lang, targetType);
  1618. }
  1619. if (shared) {
  1620. this->AppendFeatureOptions(flags, lang, "DLL");
  1621. }
  1622. }
  1623. }
  1624. bool cmLocalGenerator::GetShouldUseOldFlags(bool shared,
  1625. const std::string& lang) const
  1626. {
  1627. std::string originalFlags =
  1628. this->GlobalGenerator->GetSharedLibFlagsForLanguage(lang);
  1629. if (shared) {
  1630. std::string flagsVar = "CMAKE_SHARED_LIBRARY_";
  1631. flagsVar += lang;
  1632. flagsVar += "_FLAGS";
  1633. const char* flags = this->Makefile->GetSafeDefinition(flagsVar);
  1634. if (flags && flags != originalFlags) {
  1635. switch (this->GetPolicyStatus(cmPolicies::CMP0018)) {
  1636. case cmPolicies::WARN: {
  1637. std::ostringstream e;
  1638. e << "Variable " << flagsVar
  1639. << " has been modified. CMake "
  1640. "will ignore the POSITION_INDEPENDENT_CODE target property for "
  1641. "shared libraries and will use the "
  1642. << flagsVar
  1643. << " variable "
  1644. "instead. This may cause errors if the original content of "
  1645. << flagsVar << " was removed.\n"
  1646. << cmPolicies::GetPolicyWarning(cmPolicies::CMP0018);
  1647. this->IssueMessage(cmake::AUTHOR_WARNING, e.str());
  1648. CM_FALLTHROUGH;
  1649. }
  1650. case cmPolicies::OLD:
  1651. return true;
  1652. case cmPolicies::REQUIRED_IF_USED:
  1653. case cmPolicies::REQUIRED_ALWAYS:
  1654. case cmPolicies::NEW:
  1655. return false;
  1656. }
  1657. }
  1658. }
  1659. return false;
  1660. }
  1661. void cmLocalGenerator::AddPositionIndependentFlags(std::string& flags,
  1662. std::string const& lang,
  1663. int targetType)
  1664. {
  1665. const char* picFlags = nullptr;
  1666. if (targetType == cmStateEnums::EXECUTABLE) {
  1667. std::string flagsVar = "CMAKE_";
  1668. flagsVar += lang;
  1669. flagsVar += "_COMPILE_OPTIONS_PIE";
  1670. picFlags = this->Makefile->GetSafeDefinition(flagsVar);
  1671. }
  1672. if (!picFlags) {
  1673. std::string flagsVar = "CMAKE_";
  1674. flagsVar += lang;
  1675. flagsVar += "_COMPILE_OPTIONS_PIC";
  1676. picFlags = this->Makefile->GetSafeDefinition(flagsVar);
  1677. }
  1678. if (picFlags) {
  1679. std::vector<std::string> options;
  1680. cmSystemTools::ExpandListArgument(picFlags, options);
  1681. for (std::string const& o : options) {
  1682. this->AppendFlagEscape(flags, o);
  1683. }
  1684. }
  1685. }
  1686. void cmLocalGenerator::AddConfigVariableFlags(std::string& flags,
  1687. const std::string& var,
  1688. const std::string& config)
  1689. {
  1690. // Add the flags from the variable itself.
  1691. std::string flagsVar = var;
  1692. this->AppendFlags(flags, this->Makefile->GetDefinition(flagsVar));
  1693. // Add the flags from the build-type specific variable.
  1694. if (!config.empty()) {
  1695. flagsVar += "_";
  1696. flagsVar += cmSystemTools::UpperCase(config);
  1697. this->AppendFlags(flags, this->Makefile->GetDefinition(flagsVar));
  1698. }
  1699. }
  1700. void cmLocalGenerator::AppendFlags(std::string& flags,
  1701. const std::string& newFlags) const
  1702. {
  1703. if (!newFlags.empty()) {
  1704. if (!flags.empty()) {
  1705. flags += " ";
  1706. }
  1707. flags += newFlags;
  1708. }
  1709. }
  1710. void cmLocalGenerator::AppendFlags(std::string& flags,
  1711. const char* newFlags) const
  1712. {
  1713. if (newFlags && *newFlags) {
  1714. this->AppendFlags(flags, std::string(newFlags));
  1715. }
  1716. }
  1717. void cmLocalGenerator::AppendFlagEscape(std::string& flags,
  1718. const std::string& rawFlag) const
  1719. {
  1720. this->AppendFlags(flags, this->EscapeForShell(rawFlag));
  1721. }
  1722. void cmLocalGenerator::AppendIPOLinkerFlags(std::string& flags,
  1723. cmGeneratorTarget* target,
  1724. const std::string& config,
  1725. const std::string& lang)
  1726. {
  1727. if (!target->IsIPOEnabled(lang, config)) {
  1728. return;
  1729. }
  1730. switch (target->GetType()) {
  1731. case cmStateEnums::EXECUTABLE:
  1732. case cmStateEnums::SHARED_LIBRARY:
  1733. case cmStateEnums::MODULE_LIBRARY:
  1734. break;
  1735. default:
  1736. return;
  1737. }
  1738. const std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_IPO";
  1739. const char* rawFlagsList = this->Makefile->GetDefinition(name);
  1740. if (rawFlagsList == nullptr) {
  1741. return;
  1742. }
  1743. std::vector<std::string> flagsList;
  1744. cmSystemTools::ExpandListArgument(rawFlagsList, flagsList);
  1745. for (std::string const& o : flagsList) {
  1746. this->AppendFlagEscape(flags, o);
  1747. }
  1748. }
  1749. void cmLocalGenerator::AppendCompileOptions(std::string& options,
  1750. const char* options_list,
  1751. const char* regex) const
  1752. {
  1753. // Short-circuit if there are no options.
  1754. if (!options_list) {
  1755. return;
  1756. }
  1757. // Expand the list of options.
  1758. std::vector<std::string> options_vec;
  1759. cmSystemTools::ExpandListArgument(options_list, options_vec);
  1760. this->AppendCompileOptions(options, options_vec, regex);
  1761. }
  1762. void cmLocalGenerator::AppendCompileOptions(
  1763. std::string& options, const std::vector<std::string>& options_vec,
  1764. const char* regex) const
  1765. {
  1766. if (regex != nullptr) {
  1767. // Filter flags upon specified reges.
  1768. cmsys::RegularExpression r(regex);
  1769. for (std::string const& opt : options_vec) {
  1770. if (r.find(opt.c_str())) {
  1771. this->AppendFlagEscape(options, opt);
  1772. }
  1773. }
  1774. } else {
  1775. for (std::string const& opt : options_vec) {
  1776. this->AppendFlagEscape(options, opt);
  1777. }
  1778. }
  1779. }
  1780. void cmLocalGenerator::AppendIncludeDirectories(
  1781. std::vector<std::string>& includes, const char* includes_list,
  1782. const cmSourceFile& sourceFile) const
  1783. {
  1784. // Short-circuit if there are no includes.
  1785. if (!includes_list) {
  1786. return;
  1787. }
  1788. // Expand the list of includes.
  1789. std::vector<std::string> includes_vec;
  1790. cmSystemTools::ExpandListArgument(includes_list, includes_vec);
  1791. this->AppendIncludeDirectories(includes, includes_vec, sourceFile);
  1792. }
  1793. void cmLocalGenerator::AppendIncludeDirectories(
  1794. std::vector<std::string>& includes,
  1795. const std::vector<std::string>& includes_vec,
  1796. const cmSourceFile& sourceFile) const
  1797. {
  1798. std::unordered_set<std::string> uniqueIncludes;
  1799. for (const std::string& include : includes_vec) {
  1800. if (!cmSystemTools::FileIsFullPath(include)) {
  1801. std::ostringstream e;
  1802. e << "Found relative path while evaluating include directories of "
  1803. "\""
  1804. << sourceFile.GetLocation().GetName() << "\":\n \"" << include
  1805. << "\"\n";
  1806. this->IssueMessage(cmake::FATAL_ERROR, e.str());
  1807. return;
  1808. }
  1809. std::string inc = include;
  1810. if (!cmSystemTools::IsOff(inc.c_str())) {
  1811. cmSystemTools::ConvertToUnixSlashes(inc);
  1812. }
  1813. if (uniqueIncludes.insert(inc).second) {
  1814. includes.push_back(std::move(inc));
  1815. }
  1816. }
  1817. }
  1818. void cmLocalGenerator::AppendDefines(std::set<std::string>& defines,
  1819. const char* defines_list) const
  1820. {
  1821. // Short-circuit if there are no definitions.
  1822. if (!defines_list) {
  1823. return;
  1824. }
  1825. // Expand the list of definitions.
  1826. std::vector<std::string> defines_vec;
  1827. cmSystemTools::ExpandListArgument(defines_list, defines_vec);
  1828. this->AppendDefines(defines, defines_vec);
  1829. }
  1830. void cmLocalGenerator::AppendDefines(
  1831. std::set<std::string>& defines,
  1832. const std::vector<std::string>& defines_vec) const
  1833. {
  1834. for (std::string const& d : defines_vec) {
  1835. // Skip unsupported definitions.
  1836. if (!this->CheckDefinition(d)) {
  1837. continue;
  1838. }
  1839. defines.insert(d);
  1840. }
  1841. }
  1842. void cmLocalGenerator::JoinDefines(const std::set<std::string>& defines,
  1843. std::string& definesString,
  1844. const std::string& lang)
  1845. {
  1846. // Lookup the define flag for the current language.
  1847. std::string dflag = "-D";
  1848. if (!lang.empty()) {
  1849. std::string defineFlagVar = "CMAKE_";
  1850. defineFlagVar += lang;
  1851. defineFlagVar += "_DEFINE_FLAG";
  1852. const char* df = this->Makefile->GetDefinition(defineFlagVar);
  1853. if (df && *df) {
  1854. dflag = df;
  1855. }
  1856. }
  1857. std::set<std::string>::const_iterator defineIt = defines.begin();
  1858. const std::set<std::string>::const_iterator defineEnd = defines.end();
  1859. const char* itemSeparator = definesString.empty() ? "" : " ";
  1860. for (; defineIt != defineEnd; ++defineIt) {
  1861. // Append the definition with proper escaping.
  1862. std::string def = dflag;
  1863. if (this->GetState()->UseWatcomWMake()) {
  1864. // The Watcom compiler does its own command line parsing instead
  1865. // of using the windows shell rules. Definitions are one of
  1866. // -DNAME
  1867. // -DNAME=<cpp-token>
  1868. // -DNAME="c-string with spaces and other characters(?@#$)"
  1869. //
  1870. // Watcom will properly parse each of these cases from the
  1871. // command line without any escapes. However we still have to
  1872. // get the '$' and '#' characters through WMake as '$$' and
  1873. // '$#'.
  1874. for (const char* c = defineIt->c_str(); *c; ++c) {
  1875. if (*c == '$' || *c == '#') {
  1876. def += '$';
  1877. }
  1878. def += *c;
  1879. }
  1880. } else {
  1881. // Make the definition appear properly on the command line. Use
  1882. // -DNAME="value" instead of -D"NAME=value" for historical reasons.
  1883. std::string::size_type eq = defineIt->find("=");
  1884. def += defineIt->substr(0, eq);
  1885. if (eq != std::string::npos) {
  1886. def += "=";
  1887. def += this->EscapeForShell(defineIt->c_str() + eq + 1, true);
  1888. }
  1889. }
  1890. definesString += itemSeparator;
  1891. itemSeparator = " ";
  1892. definesString += def;
  1893. }
  1894. }
  1895. void cmLocalGenerator::AppendFeatureOptions(std::string& flags,
  1896. const std::string& lang,
  1897. const char* feature)
  1898. {
  1899. std::string optVar = "CMAKE_";
  1900. optVar += lang;
  1901. optVar += "_COMPILE_OPTIONS_";
  1902. optVar += feature;
  1903. if (const char* optionList = this->Makefile->GetDefinition(optVar)) {
  1904. std::vector<std::string> options;
  1905. cmSystemTools::ExpandListArgument(optionList, options);
  1906. for (std::string const& o : options) {
  1907. this->AppendFlagEscape(flags, o);
  1908. }
  1909. }
  1910. }
  1911. const char* cmLocalGenerator::GetFeature(const std::string& feature,
  1912. const std::string& config)
  1913. {
  1914. std::string featureName = feature;
  1915. // TODO: Define accumulation policy for features (prepend, append, replace).
  1916. // Currently we always replace.
  1917. if (!config.empty()) {
  1918. featureName += "_";
  1919. featureName += cmSystemTools::UpperCase(config);
  1920. }
  1921. cmStateSnapshot snp = this->StateSnapshot;
  1922. while (snp.IsValid()) {
  1923. if (const char* value = snp.GetDirectory().GetProperty(featureName)) {
  1924. return value;
  1925. }
  1926. snp = snp.GetBuildsystemDirectoryParent();
  1927. }
  1928. return nullptr;
  1929. }
  1930. std::string cmLocalGenerator::GetProjectName() const
  1931. {
  1932. return this->StateSnapshot.GetProjectName();
  1933. }
  1934. std::string cmLocalGenerator::ConstructComment(
  1935. cmCustomCommandGenerator const& ccg, const char* default_comment)
  1936. {
  1937. // Check for a comment provided with the command.
  1938. if (ccg.GetComment()) {
  1939. return ccg.GetComment();
  1940. }
  1941. // Construct a reasonable default comment if possible.
  1942. if (!ccg.GetOutputs().empty()) {
  1943. std::string comment;
  1944. comment = "Generating ";
  1945. const char* sep = "";
  1946. std::string currentBinaryDir = this->GetCurrentBinaryDirectory();
  1947. for (std::string const& o : ccg.GetOutputs()) {
  1948. comment += sep;
  1949. comment += this->ConvertToRelativePath(currentBinaryDir, o);
  1950. sep = ", ";
  1951. }
  1952. return comment;
  1953. }
  1954. // Otherwise use the provided default.
  1955. return default_comment;
  1956. }
  1957. class cmInstallTargetGeneratorLocal : public cmInstallTargetGenerator
  1958. {
  1959. public:
  1960. cmInstallTargetGeneratorLocal(cmLocalGenerator* lg, std::string const& t,
  1961. const char* dest, bool implib)
  1962. : cmInstallTargetGenerator(
  1963. t, dest, implib, "", std::vector<std::string>(), "Unspecified",
  1964. cmInstallGenerator::SelectMessageLevel(lg->GetMakefile()), false,
  1965. false)
  1966. {
  1967. this->Compute(lg);
  1968. }
  1969. };
  1970. void cmLocalGenerator::GenerateTargetInstallRules(
  1971. std::ostream& os, const std::string& config,
  1972. std::vector<std::string> const& configurationTypes)
  1973. {
  1974. // Convert the old-style install specification from each target to
  1975. // an install generator and run it.
  1976. const std::vector<cmGeneratorTarget*>& tgts = this->GetGeneratorTargets();
  1977. for (cmGeneratorTarget* l : tgts) {
  1978. if (l->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  1979. continue;
  1980. }
  1981. // Include the user-specified pre-install script for this target.
  1982. if (const char* preinstall = l->GetProperty("PRE_INSTALL_SCRIPT")) {
  1983. cmInstallScriptGenerator g(preinstall, false, nullptr, false);
  1984. g.Generate(os, config, configurationTypes);
  1985. }
  1986. // Install this target if a destination is given.
  1987. if (!l->Target->GetInstallPath().empty()) {
  1988. // Compute the full install destination. Note that converting
  1989. // to unix slashes also removes any trailing slash.
  1990. // We also skip over the leading slash given by the user.
  1991. std::string destination = l->Target->GetInstallPath().substr(1);
  1992. cmSystemTools::ConvertToUnixSlashes(destination);
  1993. if (destination.empty()) {
  1994. destination = ".";
  1995. }
  1996. // Generate the proper install generator for this target type.
  1997. switch (l->GetType()) {
  1998. case cmStateEnums::EXECUTABLE:
  1999. case cmStateEnums::STATIC_LIBRARY:
  2000. case cmStateEnums::MODULE_LIBRARY: {
  2001. // Use a target install generator.
  2002. cmInstallTargetGeneratorLocal g(this, l->GetName(),
  2003. destination.c_str(), false);
  2004. g.Generate(os, config, configurationTypes);
  2005. } break;
  2006. case cmStateEnums::SHARED_LIBRARY: {
  2007. #if defined(_WIN32) || defined(__CYGWIN__)
  2008. // Special code to handle DLL. Install the import library
  2009. // to the normal destination and the DLL to the runtime
  2010. // destination.
  2011. cmInstallTargetGeneratorLocal g1(this, l->GetName(),
  2012. destination.c_str(), true);
  2013. g1.Generate(os, config, configurationTypes);
  2014. // We also skip over the leading slash given by the user.
  2015. destination = l->Target->GetRuntimeInstallPath().substr(1);
  2016. cmSystemTools::ConvertToUnixSlashes(destination);
  2017. cmInstallTargetGeneratorLocal g2(this, l->GetName(),
  2018. destination.c_str(), false);
  2019. g2.Generate(os, config, configurationTypes);
  2020. #else
  2021. // Use a target install generator.
  2022. cmInstallTargetGeneratorLocal g(this, l->GetName(),
  2023. destination.c_str(), false);
  2024. g.Generate(os, config, configurationTypes);
  2025. #endif
  2026. } break;
  2027. default:
  2028. break;
  2029. }
  2030. }
  2031. // Include the user-specified post-install script for this target.
  2032. if (const char* postinstall = l->GetProperty("POST_INSTALL_SCRIPT")) {
  2033. cmInstallScriptGenerator g(postinstall, false, nullptr, false);
  2034. g.Generate(os, config, configurationTypes);
  2035. }
  2036. }
  2037. }
  2038. #if defined(CM_LG_ENCODE_OBJECT_NAMES)
  2039. static bool cmLocalGeneratorShortenObjectName(std::string& objName,
  2040. std::string::size_type max_len)
  2041. {
  2042. // Replace the beginning of the path portion of the object name with
  2043. // its own md5 sum.
  2044. std::string::size_type pos =
  2045. objName.find('/', objName.size() - max_len + 32);
  2046. if (pos != std::string::npos) {
  2047. cmCryptoHash md5(cmCryptoHash::AlgoMD5);
  2048. std::string md5name = md5.HashString(objName.substr(0, pos));
  2049. md5name += objName.substr(pos);
  2050. objName = md5name;
  2051. // The object name is now short enough.
  2052. return true;
  2053. }
  2054. // The object name could not be shortened enough.
  2055. return false;
  2056. }
  2057. bool cmLocalGeneratorCheckObjectName(std::string& objName,
  2058. std::string::size_type dir_len,
  2059. std::string::size_type max_total_len)
  2060. {
  2061. // Enforce the maximum file name length if possible.
  2062. std::string::size_type max_obj_len = max_total_len;
  2063. if (dir_len < max_total_len) {
  2064. max_obj_len = max_total_len - dir_len;
  2065. if (objName.size() > max_obj_len) {
  2066. // The current object file name is too long. Try to shorten it.
  2067. return cmLocalGeneratorShortenObjectName(objName, max_obj_len);
  2068. }
  2069. // The object file name is short enough.
  2070. return true;
  2071. }
  2072. // The build directory in which the object will be stored is
  2073. // already too deep.
  2074. return false;
  2075. }
  2076. #endif
  2077. std::string& cmLocalGenerator::CreateSafeUniqueObjectFileName(
  2078. const std::string& sin, std::string const& dir_max)
  2079. {
  2080. // Look for an existing mapped name for this object file.
  2081. std::map<std::string, std::string>::iterator it =
  2082. this->UniqueObjectNamesMap.find(sin);
  2083. // If no entry exists create one.
  2084. if (it == this->UniqueObjectNamesMap.end()) {
  2085. // Start with the original name.
  2086. std::string ssin = sin;
  2087. // Avoid full paths by removing leading slashes.
  2088. ssin.erase(0, ssin.find_first_not_of('/'));
  2089. // Avoid full paths by removing colons.
  2090. std::replace(ssin.begin(), ssin.end(), ':', '_');
  2091. // Avoid relative paths that go up the tree.
  2092. cmSystemTools::ReplaceString(ssin, "../", "__/");
  2093. // Avoid spaces.
  2094. std::replace(ssin.begin(), ssin.end(), ' ', '_');
  2095. // Mangle the name if necessary.
  2096. if (this->Makefile->IsOn("CMAKE_MANGLE_OBJECT_FILE_NAMES")) {
  2097. bool done;
  2098. int cc = 0;
  2099. char rpstr[100];
  2100. sprintf(rpstr, "_p_");
  2101. cmSystemTools::ReplaceString(ssin, "+", rpstr);
  2102. std::string sssin = sin;
  2103. do {
  2104. done = true;
  2105. for (it = this->UniqueObjectNamesMap.begin();
  2106. it != this->UniqueObjectNamesMap.end(); ++it) {
  2107. if (it->second == ssin) {
  2108. done = false;
  2109. }
  2110. }
  2111. if (done) {
  2112. break;
  2113. }
  2114. sssin = ssin;
  2115. cmSystemTools::ReplaceString(ssin, "_p_", rpstr);
  2116. sprintf(rpstr, "_p%d_", cc++);
  2117. } while (!done);
  2118. }
  2119. #if defined(CM_LG_ENCODE_OBJECT_NAMES)
  2120. if (!cmLocalGeneratorCheckObjectName(ssin, dir_max.size(),
  2121. this->ObjectPathMax)) {
  2122. // Warn if this is the first time the path has been seen.
  2123. if (this->ObjectMaxPathViolations.insert(dir_max).second) {
  2124. std::ostringstream m;
  2125. /* clang-format off */
  2126. m << "The object file directory\n"
  2127. << " " << dir_max << "\n"
  2128. << "has " << dir_max.size() << " characters. "
  2129. << "The maximum full path to an object file is "
  2130. << this->ObjectPathMax << " characters "
  2131. << "(see CMAKE_OBJECT_PATH_MAX). "
  2132. << "Object file\n"
  2133. << " " << ssin << "\n"
  2134. << "cannot be safely placed under this directory. "
  2135. << "The build may not work correctly.";
  2136. /* clang-format on */
  2137. this->IssueMessage(cmake::WARNING, m.str());
  2138. }
  2139. }
  2140. #else
  2141. (void)dir_max;
  2142. #endif
  2143. // Insert the newly mapped object file name.
  2144. std::map<std::string, std::string>::value_type e(sin, ssin);
  2145. it = this->UniqueObjectNamesMap.insert(e).first;
  2146. }
  2147. // Return the map entry.
  2148. return it->second;
  2149. }
  2150. void cmLocalGenerator::ComputeObjectFilenames(
  2151. std::map<cmSourceFile const*, std::string>& /*unused*/,
  2152. cmGeneratorTarget const* /*unused*/)
  2153. {
  2154. }
  2155. bool cmLocalGenerator::IsWindowsShell() const
  2156. {
  2157. return this->GetState()->UseWindowsShell();
  2158. }
  2159. bool cmLocalGenerator::IsWatcomWMake() const
  2160. {
  2161. return this->GetState()->UseWatcomWMake();
  2162. }
  2163. bool cmLocalGenerator::IsMinGWMake() const
  2164. {
  2165. return this->GetState()->UseMinGWMake();
  2166. }
  2167. bool cmLocalGenerator::IsNMake() const
  2168. {
  2169. return this->GetState()->UseNMake();
  2170. }
  2171. std::string cmLocalGenerator::GetObjectFileNameWithoutTarget(
  2172. const cmSourceFile& source, std::string const& dir_max,
  2173. bool* hasSourceExtension, char const* customOutputExtension)
  2174. {
  2175. // Construct the object file name using the full path to the source
  2176. // file which is its only unique identification.
  2177. std::string const& fullPath = source.GetFullPath();
  2178. // Try referencing the source relative to the source tree.
  2179. std::string relFromSource =
  2180. this->ConvertToRelativePath(this->GetCurrentSourceDirectory(), fullPath);
  2181. assert(!relFromSource.empty());
  2182. bool relSource = !cmSystemTools::FileIsFullPath(relFromSource);
  2183. bool subSource = relSource && relFromSource[0] != '.';
  2184. // Try referencing the source relative to the binary tree.
  2185. std::string relFromBinary =
  2186. this->ConvertToRelativePath(this->GetCurrentBinaryDirectory(), fullPath);
  2187. assert(!relFromBinary.empty());
  2188. bool relBinary = !cmSystemTools::FileIsFullPath(relFromBinary);
  2189. bool subBinary = relBinary && relFromBinary[0] != '.';
  2190. // Select a nice-looking reference to the source file to construct
  2191. // the object file name.
  2192. std::string objectName;
  2193. if ((relSource && !relBinary) || (subSource && !subBinary)) {
  2194. objectName = relFromSource;
  2195. } else if ((relBinary && !relSource) || (subBinary && !subSource)) {
  2196. objectName = relFromBinary;
  2197. } else if (relFromBinary.length() < relFromSource.length()) {
  2198. objectName = relFromBinary;
  2199. } else {
  2200. objectName = relFromSource;
  2201. }
  2202. // if it is still a full path check for the try compile case
  2203. // try compile never have in source sources, and should not
  2204. // have conflicting source file names in the same target
  2205. if (cmSystemTools::FileIsFullPath(objectName)) {
  2206. if (this->GetGlobalGenerator()->GetCMakeInstance()->GetIsInTryCompile()) {
  2207. objectName = cmSystemTools::GetFilenameName(source.GetFullPath());
  2208. }
  2209. }
  2210. // Replace the original source file extension with the object file
  2211. // extension.
  2212. bool keptSourceExtension = true;
  2213. if (!source.GetPropertyAsBool("KEEP_EXTENSION")) {
  2214. // Decide whether this language wants to replace the source
  2215. // extension with the object extension. For CMake 2.4
  2216. // compatibility do this by default.
  2217. bool replaceExt = this->NeedBackwardsCompatibility_2_4();
  2218. if (!replaceExt) {
  2219. std::string lang = source.GetLanguage();
  2220. if (!lang.empty()) {
  2221. std::string repVar = "CMAKE_";
  2222. repVar += lang;
  2223. repVar += "_OUTPUT_EXTENSION_REPLACE";
  2224. replaceExt = this->Makefile->IsOn(repVar);
  2225. }
  2226. }
  2227. // Remove the source extension if it is to be replaced.
  2228. if (replaceExt || customOutputExtension) {
  2229. keptSourceExtension = false;
  2230. std::string::size_type dot_pos = objectName.rfind('.');
  2231. if (dot_pos != std::string::npos) {
  2232. objectName = objectName.substr(0, dot_pos);
  2233. }
  2234. }
  2235. // Store the new extension.
  2236. if (customOutputExtension) {
  2237. objectName += customOutputExtension;
  2238. } else {
  2239. objectName += this->GlobalGenerator->GetLanguageOutputExtension(source);
  2240. }
  2241. }
  2242. if (hasSourceExtension) {
  2243. *hasSourceExtension = keptSourceExtension;
  2244. }
  2245. // Convert to a safe name.
  2246. return this->CreateSafeUniqueObjectFileName(objectName, dir_max);
  2247. }
  2248. std::string cmLocalGenerator::GetSourceFileLanguage(const cmSourceFile& source)
  2249. {
  2250. return source.GetLanguage();
  2251. }
  2252. cmake* cmLocalGenerator::GetCMakeInstance() const
  2253. {
  2254. return this->GlobalGenerator->GetCMakeInstance();
  2255. }
  2256. std::string const& cmLocalGenerator::GetSourceDirectory() const
  2257. {
  2258. return this->GetCMakeInstance()->GetHomeDirectory();
  2259. }
  2260. std::string const& cmLocalGenerator::GetBinaryDirectory() const
  2261. {
  2262. return this->GetCMakeInstance()->GetHomeOutputDirectory();
  2263. }
  2264. const char* cmLocalGenerator::GetCurrentBinaryDirectory() const
  2265. {
  2266. return this->StateSnapshot.GetDirectory().GetCurrentBinary();
  2267. }
  2268. const char* cmLocalGenerator::GetCurrentSourceDirectory() const
  2269. {
  2270. return this->StateSnapshot.GetDirectory().GetCurrentSource();
  2271. }
  2272. std::string cmLocalGenerator::GetTargetDirectory(
  2273. const cmGeneratorTarget* /*unused*/) const
  2274. {
  2275. cmSystemTools::Error("GetTargetDirectory"
  2276. " called on cmLocalGenerator");
  2277. return "";
  2278. }
  2279. KWIML_INT_uint64_t cmLocalGenerator::GetBackwardsCompatibility()
  2280. {
  2281. // The computed version may change until the project is fully
  2282. // configured.
  2283. if (!this->BackwardsCompatibilityFinal) {
  2284. unsigned int major = 0;
  2285. unsigned int minor = 0;
  2286. unsigned int patch = 0;
  2287. if (const char* value =
  2288. this->Makefile->GetDefinition("CMAKE_BACKWARDS_COMPATIBILITY")) {
  2289. switch (sscanf(value, "%u.%u.%u", &major, &minor, &patch)) {
  2290. case 2:
  2291. patch = 0;
  2292. break;
  2293. case 1:
  2294. minor = 0;
  2295. patch = 0;
  2296. break;
  2297. default:
  2298. break;
  2299. }
  2300. }
  2301. this->BackwardsCompatibility = CMake_VERSION_ENCODE(major, minor, patch);
  2302. this->BackwardsCompatibilityFinal = true;
  2303. }
  2304. return this->BackwardsCompatibility;
  2305. }
  2306. bool cmLocalGenerator::NeedBackwardsCompatibility_2_4()
  2307. {
  2308. // Check the policy to decide whether to pay attention to this
  2309. // variable.
  2310. switch (this->GetPolicyStatus(cmPolicies::CMP0001)) {
  2311. case cmPolicies::WARN:
  2312. // WARN is just OLD without warning because user code does not
  2313. // always affect whether this check is done.
  2314. case cmPolicies::OLD:
  2315. // Old behavior is to check the variable.
  2316. break;
  2317. case cmPolicies::NEW:
  2318. // New behavior is to ignore the variable.
  2319. return false;
  2320. case cmPolicies::REQUIRED_IF_USED:
  2321. case cmPolicies::REQUIRED_ALWAYS:
  2322. // This will never be the case because the only way to require
  2323. // the setting is to require the user to specify version policy
  2324. // 2.6 or higher. Once we add that requirement then this whole
  2325. // method can be removed anyway.
  2326. return false;
  2327. }
  2328. // Compatibility is needed if CMAKE_BACKWARDS_COMPATIBILITY is set
  2329. // equal to or lower than the given version.
  2330. KWIML_INT_uint64_t actual_compat = this->GetBackwardsCompatibility();
  2331. return (actual_compat && actual_compat <= CMake_VERSION_ENCODE(2, 4, 255));
  2332. }
  2333. cmPolicies::PolicyStatus cmLocalGenerator::GetPolicyStatus(
  2334. cmPolicies::PolicyID id) const
  2335. {
  2336. return this->Makefile->GetPolicyStatus(id);
  2337. }
  2338. bool cmLocalGenerator::CheckDefinition(std::string const& define) const
  2339. {
  2340. // Many compilers do not support -DNAME(arg)=sdf so we disable it.
  2341. std::string::size_type pos = define.find_first_of("(=");
  2342. if (pos != std::string::npos) {
  2343. if (define[pos] == '(') {
  2344. std::ostringstream e;
  2345. /* clang-format off */
  2346. e << "WARNING: Function-style preprocessor definitions may not be "
  2347. << "passed on the compiler command line because many compilers "
  2348. << "do not support it.\n"
  2349. << "CMake is dropping a preprocessor definition: " << define << "\n"
  2350. << "Consider defining the macro in a (configured) header file.\n";
  2351. /* clang-format on */
  2352. cmSystemTools::Message(e.str().c_str());
  2353. return false;
  2354. }
  2355. }
  2356. // Many compilers do not support # in the value so we disable it.
  2357. if (define.find_first_of('#') != std::string::npos) {
  2358. std::ostringstream e;
  2359. /* clang-format off */
  2360. e << "WARNING: Preprocessor definitions containing '#' may not be "
  2361. << "passed on the compiler command line because many compilers "
  2362. << "do not support it.\n"
  2363. << "CMake is dropping a preprocessor definition: " << define << "\n"
  2364. << "Consider defining the macro in a (configured) header file.\n";
  2365. /* clang-format on */
  2366. cmSystemTools::Message(e.str().c_str());
  2367. return false;
  2368. }
  2369. // Assume it is supported.
  2370. return true;
  2371. }
  2372. static void cmLGInfoProp(cmMakefile* mf, cmGeneratorTarget* target,
  2373. const std::string& prop)
  2374. {
  2375. if (const char* val = target->GetProperty(prop)) {
  2376. mf->AddDefinition(prop, val);
  2377. }
  2378. }
  2379. void cmLocalGenerator::GenerateAppleInfoPList(cmGeneratorTarget* target,
  2380. const std::string& targetName,
  2381. const char* fname)
  2382. {
  2383. // Find the Info.plist template.
  2384. const char* in = target->GetProperty("MACOSX_BUNDLE_INFO_PLIST");
  2385. std::string inFile = (in && *in) ? in : "MacOSXBundleInfo.plist.in";
  2386. if (!cmSystemTools::FileIsFullPath(inFile)) {
  2387. std::string inMod = this->Makefile->GetModulesFile(inFile.c_str());
  2388. if (!inMod.empty()) {
  2389. inFile = inMod;
  2390. }
  2391. }
  2392. if (!cmSystemTools::FileExists(inFile, true)) {
  2393. std::ostringstream e;
  2394. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  2395. << "\" could not be found.";
  2396. cmSystemTools::Error(e.str().c_str());
  2397. return;
  2398. }
  2399. // Convert target properties to variables in an isolated makefile
  2400. // scope to configure the file. If properties are set they will
  2401. // override user make variables. If not the configuration will fall
  2402. // back to the directory-level values set by the user.
  2403. cmMakefile* mf = this->Makefile;
  2404. cmMakefile::ScopePushPop varScope(mf);
  2405. mf->AddDefinition("MACOSX_BUNDLE_EXECUTABLE_NAME", targetName.c_str());
  2406. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_INFO_STRING");
  2407. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_ICON_FILE");
  2408. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_GUI_IDENTIFIER");
  2409. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_LONG_VERSION_STRING");
  2410. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_NAME");
  2411. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_SHORT_VERSION_STRING");
  2412. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_VERSION");
  2413. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_COPYRIGHT");
  2414. mf->ConfigureFile(inFile.c_str(), fname, false, false, false);
  2415. }
  2416. void cmLocalGenerator::GenerateFrameworkInfoPList(
  2417. cmGeneratorTarget* target, const std::string& targetName, const char* fname)
  2418. {
  2419. // Find the Info.plist template.
  2420. const char* in = target->GetProperty("MACOSX_FRAMEWORK_INFO_PLIST");
  2421. std::string inFile = (in && *in) ? in : "MacOSXFrameworkInfo.plist.in";
  2422. if (!cmSystemTools::FileIsFullPath(inFile)) {
  2423. std::string inMod = this->Makefile->GetModulesFile(inFile.c_str());
  2424. if (!inMod.empty()) {
  2425. inFile = inMod;
  2426. }
  2427. }
  2428. if (!cmSystemTools::FileExists(inFile, true)) {
  2429. std::ostringstream e;
  2430. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  2431. << "\" could not be found.";
  2432. cmSystemTools::Error(e.str().c_str());
  2433. return;
  2434. }
  2435. // Convert target properties to variables in an isolated makefile
  2436. // scope to configure the file. If properties are set they will
  2437. // override user make variables. If not the configuration will fall
  2438. // back to the directory-level values set by the user.
  2439. cmMakefile* mf = this->Makefile;
  2440. cmMakefile::ScopePushPop varScope(mf);
  2441. mf->AddDefinition("MACOSX_FRAMEWORK_NAME", targetName.c_str());
  2442. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_ICON_FILE");
  2443. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_IDENTIFIER");
  2444. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_SHORT_VERSION_STRING");
  2445. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_BUNDLE_VERSION");
  2446. mf->ConfigureFile(inFile.c_str(), fname, false, false, false);
  2447. }