cmLocalGenerator.cxx 143 KB

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