cmLocalGenerator.cxx 117 KB

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