cmLocalGenerator.cxx 149 KB

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