cmLocalGenerator.cxx 92 KB

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