cmLocalGenerator.cxx 101 KB

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