cmLocalGenerator.cxx 119 KB

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