cmLocalGenerator.cxx 175 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987
  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 <array>
  6. #include <cassert>
  7. #include <cctype>
  8. #include <cstdio>
  9. #include <cstdlib>
  10. #include <initializer_list>
  11. #include <iterator>
  12. #include <sstream>
  13. #include <type_traits>
  14. #include <unordered_set>
  15. #include <utility>
  16. #include <vector>
  17. #include <cm/memory>
  18. #include <cm/optional>
  19. #include <cm/string_view>
  20. #include <cmext/algorithm>
  21. #include <cmext/string_view>
  22. #include "cmsys/RegularExpression.hxx"
  23. #include "cmAlgorithms.h"
  24. #include "cmComputeLinkInformation.h"
  25. #include "cmCryptoHash.h"
  26. #include "cmCustomCommand.h"
  27. #include "cmCustomCommandGenerator.h"
  28. #include "cmCustomCommandLines.h"
  29. #include "cmCustomCommandTypes.h"
  30. #include "cmGeneratedFileStream.h"
  31. #include "cmGeneratorExpression.h"
  32. #include "cmGeneratorExpressionEvaluationFile.h"
  33. #include "cmGeneratorTarget.h"
  34. #include "cmGlobalGenerator.h"
  35. #include "cmInstallGenerator.h"
  36. #include "cmInstallScriptGenerator.h"
  37. #include "cmInstallTargetGenerator.h"
  38. #include "cmLinkLineComputer.h"
  39. #include "cmLinkLineDeviceComputer.h"
  40. #include "cmList.h"
  41. #include "cmMakefile.h"
  42. #include "cmMessageType.h"
  43. #include "cmRange.h"
  44. #include "cmRulePlaceholderExpander.h"
  45. #include "cmSourceFile.h"
  46. #include "cmSourceFileLocation.h"
  47. #include "cmSourceFileLocationKind.h"
  48. #include "cmStandardLevelResolver.h"
  49. #include "cmState.h"
  50. #include "cmStateDirectory.h"
  51. #include "cmStateTypes.h"
  52. #include "cmStringAlgorithms.h"
  53. #include "cmSystemTools.h"
  54. #include "cmTarget.h"
  55. #include "cmTestGenerator.h"
  56. #include "cmValue.h"
  57. #include "cmVersion.h"
  58. #include "cmake.h"
  59. #if defined(__HAIKU__)
  60. # include <FindDirectory.h>
  61. # include <StorageDefs.h>
  62. #endif
  63. // List of variables that are replaced when
  64. // rules are expanded. These variables are
  65. // replaced in the form <var> with GetSafeDefinition(var).
  66. // ${LANG} is replaced in the variable first with all enabled
  67. // languages.
  68. static auto ruleReplaceVars = { "CMAKE_${LANG}_COMPILER",
  69. "CMAKE_SHARED_LIBRARY_CREATE_${LANG}_FLAGS",
  70. "CMAKE_SHARED_MODULE_CREATE_${LANG}_FLAGS",
  71. "CMAKE_SHARED_MODULE_${LANG}_FLAGS",
  72. "CMAKE_SHARED_LIBRARY_${LANG}_FLAGS",
  73. "CMAKE_${LANG}_LINK_FLAGS",
  74. "CMAKE_SHARED_LIBRARY_SONAME_${LANG}_FLAG",
  75. "CMAKE_${LANG}_ARCHIVE",
  76. "CMAKE_AR",
  77. "CMAKE_CURRENT_SOURCE_DIR",
  78. "CMAKE_CURRENT_BINARY_DIR",
  79. "CMAKE_RANLIB",
  80. "CMAKE_MT",
  81. "CMAKE_TAPI",
  82. "CMAKE_CUDA_HOST_COMPILER",
  83. "CMAKE_CUDA_HOST_LINK_LAUNCHER",
  84. "CMAKE_HIP_HOST_COMPILER",
  85. "CMAKE_HIP_HOST_LINK_LAUNCHER",
  86. "CMAKE_CL_SHOWINCLUDES_PREFIX" };
  87. cmLocalGenerator::cmLocalGenerator(cmGlobalGenerator* gg, cmMakefile* makefile)
  88. : cmOutputConverter(makefile->GetStateSnapshot())
  89. , DirectoryBacktrace(makefile->GetBacktrace())
  90. {
  91. this->GlobalGenerator = gg;
  92. this->Makefile = makefile;
  93. this->AliasTargets = makefile->GetAliasTargets();
  94. this->EmitUniversalBinaryFlags = true;
  95. this->BackwardsCompatibility = 0;
  96. this->BackwardsCompatibilityFinal = false;
  97. this->ComputeObjectMaxPath();
  98. // Canonicalize entries of the CPATH environment variable the same
  99. // way detection of CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES does.
  100. {
  101. std::vector<std::string> cpath;
  102. cmSystemTools::GetPath(cpath, "CPATH");
  103. for (std::string const& cp : cpath) {
  104. if (cmSystemTools::FileIsFullPath(cp)) {
  105. this->EnvCPATH.emplace_back(cmSystemTools::CollapseFullPath(cp));
  106. }
  107. }
  108. }
  109. std::vector<std::string> enabledLanguages =
  110. this->GetState()->GetEnabledLanguages();
  111. if (cmValue sysrootCompile =
  112. this->Makefile->GetDefinition("CMAKE_SYSROOT_COMPILE")) {
  113. this->CompilerSysroot = *sysrootCompile;
  114. } else {
  115. this->CompilerSysroot = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
  116. }
  117. if (cmValue sysrootLink =
  118. this->Makefile->GetDefinition("CMAKE_SYSROOT_LINK")) {
  119. this->LinkerSysroot = *sysrootLink;
  120. } else {
  121. this->LinkerSysroot = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
  122. }
  123. // OSX SYSROOT can be required by some tools, like tapi
  124. {
  125. cmValue osxSysroot = this->Makefile->GetDefinition("CMAKE_OSX_SYSROOT");
  126. this->VariableMappings["CMAKE_OSX_SYSROOT"] =
  127. osxSysroot.IsEmpty() ? "/" : this->EscapeForShell(*osxSysroot, true);
  128. }
  129. if (cmValue appleArchSysroots =
  130. this->Makefile->GetDefinition("CMAKE_APPLE_ARCH_SYSROOTS")) {
  131. std::string const& appleArchs =
  132. this->Makefile->GetSafeDefinition("CMAKE_OSX_ARCHITECTURES");
  133. cmList archs(appleArchs);
  134. cmList sysroots{ appleArchSysroots, cmList::EmptyElements::Yes };
  135. if (archs.size() == sysroots.size()) {
  136. for (cmList::size_type i = 0; i < archs.size(); ++i) {
  137. this->AppleArchSysroots[archs[i]] = sysroots[i];
  138. }
  139. } else {
  140. std::string const e =
  141. cmStrCat("CMAKE_APPLE_ARCH_SYSROOTS:\n ", *appleArchSysroots,
  142. "\n"
  143. "is not the same length as CMAKE_OSX_ARCHITECTURES:\n ",
  144. appleArchs);
  145. this->IssueMessage(MessageType::FATAL_ERROR, e);
  146. }
  147. }
  148. for (std::string const& lang : enabledLanguages) {
  149. if (lang == "NONE") {
  150. continue;
  151. }
  152. this->Compilers["CMAKE_" + lang + "_COMPILER"] = lang;
  153. this->VariableMappings["CMAKE_" + lang + "_COMPILER"] =
  154. this->Makefile->GetSafeDefinition("CMAKE_" + lang + "_COMPILER");
  155. std::string const& compilerArg1 = "CMAKE_" + lang + "_COMPILER_ARG1";
  156. std::string const& compilerTarget = "CMAKE_" + lang + "_COMPILER_TARGET";
  157. std::string const& compilerOptionTarget =
  158. "CMAKE_" + lang + "_COMPILE_OPTIONS_TARGET";
  159. std::string const& compilerExternalToolchain =
  160. "CMAKE_" + lang + "_COMPILER_EXTERNAL_TOOLCHAIN";
  161. std::string const& compilerOptionExternalToolchain =
  162. "CMAKE_" + lang + "_COMPILE_OPTIONS_EXTERNAL_TOOLCHAIN";
  163. std::string const& compilerOptionSysroot =
  164. "CMAKE_" + lang + "_COMPILE_OPTIONS_SYSROOT";
  165. this->VariableMappings[compilerArg1] =
  166. this->Makefile->GetSafeDefinition(compilerArg1);
  167. this->VariableMappings[compilerTarget] =
  168. this->Makefile->GetSafeDefinition(compilerTarget);
  169. this->VariableMappings[compilerOptionTarget] =
  170. this->Makefile->GetSafeDefinition(compilerOptionTarget);
  171. this->VariableMappings[compilerExternalToolchain] =
  172. this->Makefile->GetSafeDefinition(compilerExternalToolchain);
  173. this->VariableMappings[compilerOptionExternalToolchain] =
  174. this->Makefile->GetSafeDefinition(compilerOptionExternalToolchain);
  175. this->VariableMappings[compilerOptionSysroot] =
  176. this->Makefile->GetSafeDefinition(compilerOptionSysroot);
  177. for (std::string replaceVar : ruleReplaceVars) {
  178. if (replaceVar.find("${LANG}") != std::string::npos) {
  179. cmSystemTools::ReplaceString(replaceVar, "${LANG}", lang);
  180. }
  181. this->VariableMappings[replaceVar] =
  182. this->Makefile->GetSafeDefinition(replaceVar);
  183. }
  184. }
  185. }
  186. std::unique_ptr<cmRulePlaceholderExpander>
  187. cmLocalGenerator::CreateRulePlaceholderExpander() const
  188. {
  189. return cm::make_unique<cmRulePlaceholderExpander>(
  190. this->Compilers, this->VariableMappings, this->CompilerSysroot,
  191. this->LinkerSysroot);
  192. }
  193. cmLocalGenerator::~cmLocalGenerator() = default;
  194. void cmLocalGenerator::IssueMessage(MessageType t,
  195. std::string const& text) const
  196. {
  197. this->GetCMakeInstance()->IssueMessage(t, text, this->DirectoryBacktrace);
  198. }
  199. void cmLocalGenerator::ComputeObjectMaxPath()
  200. {
  201. // Choose a maximum object file name length.
  202. #if defined(_WIN32) || defined(__CYGWIN__)
  203. this->ObjectPathMax = 250;
  204. #else
  205. this->ObjectPathMax = 1000;
  206. #endif
  207. cmValue plen = this->Makefile->GetDefinition("CMAKE_OBJECT_PATH_MAX");
  208. if (cmNonempty(plen)) {
  209. unsigned int pmax;
  210. if (sscanf(plen->c_str(), "%u", &pmax) == 1) {
  211. if (pmax >= 128) {
  212. this->ObjectPathMax = pmax;
  213. } else {
  214. std::ostringstream w;
  215. w << "CMAKE_OBJECT_PATH_MAX is set to " << pmax
  216. << ", which is less than the minimum of 128. "
  217. << "The value will be ignored.";
  218. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  219. }
  220. } else {
  221. std::ostringstream w;
  222. w << "CMAKE_OBJECT_PATH_MAX is set to \"" << *plen
  223. << "\", which fails to parse as a positive integer. "
  224. << "The value will be ignored.";
  225. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  226. }
  227. }
  228. this->ObjectMaxPathViolations.clear();
  229. }
  230. static void MoveSystemIncludesToEnd(std::vector<std::string>& includeDirs,
  231. const std::string& config,
  232. const std::string& lang,
  233. const cmGeneratorTarget* target)
  234. {
  235. if (!target) {
  236. return;
  237. }
  238. std::stable_sort(
  239. includeDirs.begin(), includeDirs.end(),
  240. [&target, &config, &lang](std::string const& a, std::string const& b) {
  241. return !target->IsSystemIncludeDirectory(a, config, lang) &&
  242. target->IsSystemIncludeDirectory(b, config, lang);
  243. });
  244. }
  245. static void MoveSystemIncludesToEnd(std::vector<BT<std::string>>& includeDirs,
  246. const std::string& config,
  247. const std::string& lang,
  248. const cmGeneratorTarget* target)
  249. {
  250. if (!target) {
  251. return;
  252. }
  253. std::stable_sort(includeDirs.begin(), includeDirs.end(),
  254. [target, &config, &lang](BT<std::string> const& a,
  255. BT<std::string> const& b) {
  256. return !target->IsSystemIncludeDirectory(a.Value, config,
  257. lang) &&
  258. target->IsSystemIncludeDirectory(b.Value, config, lang);
  259. });
  260. }
  261. void cmLocalGenerator::TraceDependencies() const
  262. {
  263. // Generate the rule files for each target.
  264. const auto& targets = this->GetGeneratorTargets();
  265. for (const auto& target : targets) {
  266. if (!target->IsInBuildSystem()) {
  267. continue;
  268. }
  269. target->TraceDependencies();
  270. }
  271. }
  272. void cmLocalGenerator::GenerateTestFiles()
  273. {
  274. if (!this->Makefile->IsOn("CMAKE_TESTING_ENABLED")) {
  275. return;
  276. }
  277. // Compute the set of configurations.
  278. std::vector<std::string> configurationTypes =
  279. this->Makefile->GetGeneratorConfigs(cmMakefile::OnlyMultiConfig);
  280. std::string config = this->Makefile->GetDefaultConfiguration();
  281. std::string file =
  282. cmStrCat(this->StateSnapshot.GetDirectory().GetCurrentBinary(),
  283. "/CTestTestfile.cmake");
  284. cmGeneratedFileStream fout(file);
  285. fout.SetCopyIfDifferent(true);
  286. fout << "# CMake generated Testfile for \n"
  287. "# Source directory: "
  288. << this->StateSnapshot.GetDirectory().GetCurrentSource()
  289. << "\n"
  290. "# Build directory: "
  291. << this->StateSnapshot.GetDirectory().GetCurrentBinary()
  292. << "\n"
  293. "# \n"
  294. "# This file includes the relevant testing commands "
  295. "required for \n"
  296. "# testing this directory and lists subdirectories to "
  297. "be tested as well.\n";
  298. std::string resourceSpecFile =
  299. this->Makefile->GetSafeDefinition("CTEST_RESOURCE_SPEC_FILE");
  300. if (!resourceSpecFile.empty()) {
  301. fout << "set(CTEST_RESOURCE_SPEC_FILE \"" << resourceSpecFile << "\")\n";
  302. }
  303. cmValue testIncludeFile = this->Makefile->GetProperty("TEST_INCLUDE_FILE");
  304. if (testIncludeFile) {
  305. fout << "include(\"" << *testIncludeFile << "\")\n";
  306. }
  307. cmValue testIncludeFiles = this->Makefile->GetProperty("TEST_INCLUDE_FILES");
  308. if (testIncludeFiles) {
  309. cmList includesList{ *testIncludeFiles };
  310. for (std::string const& i : includesList) {
  311. fout << "include(\"" << i << "\")\n";
  312. }
  313. }
  314. // Ask each test generator to write its code.
  315. for (const auto& tester : this->Makefile->GetTestGenerators()) {
  316. tester->Compute(this);
  317. tester->Generate(fout, config, configurationTypes);
  318. }
  319. using vec_t = std::vector<cmStateSnapshot>;
  320. vec_t const& children = this->Makefile->GetStateSnapshot().GetChildren();
  321. for (cmStateSnapshot const& i : children) {
  322. // TODO: Use add_subdirectory instead?
  323. std::string outP = i.GetDirectory().GetCurrentBinary();
  324. outP = this->MaybeRelativeToCurBinDir(outP);
  325. outP = cmOutputConverter::EscapeForCMake(outP);
  326. fout << "subdirs(" << outP << ")\n";
  327. }
  328. // Add directory labels property
  329. cmValue directoryLabels =
  330. this->Makefile->GetDefinition("CMAKE_DIRECTORY_LABELS");
  331. cmValue labels = this->Makefile->GetProperty("LABELS");
  332. if (labels || directoryLabels) {
  333. fout << "set_directory_properties(PROPERTIES LABELS ";
  334. if (labels) {
  335. fout << cmOutputConverter::EscapeForCMake(*labels);
  336. }
  337. if (labels && directoryLabels) {
  338. fout << ";";
  339. }
  340. if (directoryLabels) {
  341. fout << cmOutputConverter::EscapeForCMake(*directoryLabels);
  342. }
  343. fout << ")\n";
  344. }
  345. }
  346. void cmLocalGenerator::CreateEvaluationFileOutputs()
  347. {
  348. std::vector<std::string> const& configs =
  349. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  350. for (std::string const& c : configs) {
  351. this->CreateEvaluationFileOutputs(c);
  352. }
  353. }
  354. void cmLocalGenerator::CreateEvaluationFileOutputs(std::string const& config)
  355. {
  356. for (const auto& geef : this->Makefile->GetEvaluationFiles()) {
  357. geef->CreateOutputFile(this, config);
  358. }
  359. }
  360. void cmLocalGenerator::ProcessEvaluationFiles(
  361. std::vector<std::string>& generatedFiles)
  362. {
  363. for (const auto& geef : this->Makefile->GetEvaluationFiles()) {
  364. geef->Generate(this);
  365. if (cmSystemTools::GetFatalErrorOccurred()) {
  366. return;
  367. }
  368. std::vector<std::string> files = geef->GetFiles();
  369. std::sort(files.begin(), files.end());
  370. std::vector<std::string> intersection;
  371. std::set_intersection(files.begin(), files.end(), generatedFiles.begin(),
  372. generatedFiles.end(),
  373. std::back_inserter(intersection));
  374. if (!intersection.empty()) {
  375. cmSystemTools::Error("Files to be generated by multiple different "
  376. "commands: " +
  377. cmWrap('"', intersection, '"', " "));
  378. return;
  379. }
  380. cm::append(generatedFiles, files);
  381. std::inplace_merge(generatedFiles.begin(),
  382. generatedFiles.end() - files.size(),
  383. generatedFiles.end());
  384. }
  385. }
  386. void cmLocalGenerator::GenerateInstallRules()
  387. {
  388. // Compute the install prefix.
  389. cmValue installPrefix =
  390. this->Makefile->GetDefinition("CMAKE_INSTALL_PREFIX");
  391. std::string prefix = *installPrefix;
  392. #if defined(_WIN32) && !defined(__CYGWIN__)
  393. if (!installPrefix) {
  394. if (!cmSystemTools::GetEnv("SystemDrive", prefix)) {
  395. prefix = "C:";
  396. }
  397. cmValue project_name = this->Makefile->GetDefinition("PROJECT_NAME");
  398. if (cmNonempty(project_name)) {
  399. prefix += "/Program Files/";
  400. prefix += *project_name;
  401. } else {
  402. prefix += "/InstalledCMakeProject";
  403. }
  404. }
  405. #elif defined(__HAIKU__)
  406. char dir[B_PATH_NAME_LENGTH];
  407. if (!installPrefix) {
  408. if (find_directory(B_SYSTEM_DIRECTORY, -1, false, dir, sizeof(dir)) ==
  409. B_OK) {
  410. prefix = dir;
  411. } else {
  412. prefix = "/boot/system";
  413. }
  414. }
  415. #else
  416. if (!installPrefix) {
  417. prefix = "/usr/local";
  418. }
  419. #endif
  420. if (cmValue stagingPrefix =
  421. this->Makefile->GetDefinition("CMAKE_STAGING_PREFIX")) {
  422. prefix = *stagingPrefix;
  423. }
  424. // Compute the set of configurations.
  425. std::vector<std::string> configurationTypes =
  426. this->Makefile->GetGeneratorConfigs(cmMakefile::OnlyMultiConfig);
  427. std::string config = this->Makefile->GetDefaultConfiguration();
  428. // Choose a default install configuration.
  429. std::string default_config = config;
  430. const char* default_order[] = { "RELEASE", "MINSIZEREL", "RELWITHDEBINFO",
  431. "DEBUG", nullptr };
  432. for (const char** c = default_order; *c && default_config.empty(); ++c) {
  433. for (std::string const& configurationType : configurationTypes) {
  434. if (cmSystemTools::UpperCase(configurationType) == *c) {
  435. default_config = configurationType;
  436. }
  437. }
  438. }
  439. if (default_config.empty() && !configurationTypes.empty()) {
  440. default_config = configurationTypes[0];
  441. }
  442. // Create the install script file.
  443. std::string file = this->StateSnapshot.GetDirectory().GetCurrentBinary();
  444. std::string homedir = this->GetState()->GetBinaryDirectory();
  445. int toplevel_install = 0;
  446. if (file == homedir) {
  447. toplevel_install = 1;
  448. }
  449. file += "/cmake_install.cmake";
  450. this->GetGlobalGenerator()->AddInstallScript(file);
  451. cmGeneratedFileStream fout(file);
  452. fout.SetCopyIfDifferent(true);
  453. // Write the header.
  454. /* clang-format off */
  455. fout << "# Install script for directory: "
  456. << this->StateSnapshot.GetDirectory().GetCurrentSource()
  457. << "\n\n"
  458. "# Set the install prefix\n"
  459. "if(NOT DEFINED CMAKE_INSTALL_PREFIX)\n"
  460. " set(CMAKE_INSTALL_PREFIX \"" << prefix << "\")\n"
  461. "endif()\n"
  462. << R"(string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX )"
  463. << "\"${CMAKE_INSTALL_PREFIX}\")\n\n";
  464. /* clang-format on */
  465. // Write support code for generating per-configuration install rules.
  466. /* clang-format off */
  467. fout <<
  468. "# Set the install configuration name.\n"
  469. "if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)\n"
  470. " if(BUILD_TYPE)\n"
  471. " string(REGEX REPLACE \"^[^A-Za-z0-9_]+\" \"\"\n"
  472. " CMAKE_INSTALL_CONFIG_NAME \"${BUILD_TYPE}\")\n"
  473. " else()\n"
  474. " set(CMAKE_INSTALL_CONFIG_NAME \"" << default_config << "\")\n"
  475. " endif()\n"
  476. " message(STATUS \"Install configuration: "
  477. "\\\"${CMAKE_INSTALL_CONFIG_NAME}\\\"\")\n"
  478. "endif()\n"
  479. "\n";
  480. /* clang-format on */
  481. // Write support code for dealing with component-specific installs.
  482. /* clang-format off */
  483. fout <<
  484. "# Set the component getting installed.\n"
  485. "if(NOT CMAKE_INSTALL_COMPONENT)\n"
  486. " if(COMPONENT)\n"
  487. " message(STATUS \"Install component: \\\"${COMPONENT}\\\"\")\n"
  488. " set(CMAKE_INSTALL_COMPONENT \"${COMPONENT}\")\n"
  489. " else()\n"
  490. " set(CMAKE_INSTALL_COMPONENT)\n"
  491. " endif()\n"
  492. "endif()\n"
  493. "\n";
  494. /* clang-format on */
  495. // Copy user-specified install options to the install code.
  496. if (cmValue so_no_exe =
  497. this->Makefile->GetDefinition("CMAKE_INSTALL_SO_NO_EXE")) {
  498. /* clang-format off */
  499. fout <<
  500. "# Install shared libraries without execute permission?\n"
  501. "if(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE)\n"
  502. " set(CMAKE_INSTALL_SO_NO_EXE \"" << *so_no_exe << "\")\n"
  503. "endif()\n"
  504. "\n";
  505. /* clang-format on */
  506. }
  507. // Copy cmake cross compile state to install code.
  508. if (cmValue crosscompiling =
  509. this->Makefile->GetDefinition("CMAKE_CROSSCOMPILING")) {
  510. /* clang-format off */
  511. fout <<
  512. "# Is this installation the result of a crosscompile?\n"
  513. "if(NOT DEFINED CMAKE_CROSSCOMPILING)\n"
  514. " set(CMAKE_CROSSCOMPILING \"" << *crosscompiling << "\")\n"
  515. "endif()\n"
  516. "\n";
  517. /* clang-format on */
  518. }
  519. // Write default directory permissions.
  520. if (cmValue defaultDirPermissions = this->Makefile->GetDefinition(
  521. "CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS")) {
  522. /* clang-format off */
  523. fout <<
  524. "# Set default install directory permissions.\n"
  525. "if(NOT DEFINED CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS)\n"
  526. " set(CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS \""
  527. << *defaultDirPermissions << "\")\n"
  528. "endif()\n"
  529. "\n";
  530. /* clang-format on */
  531. }
  532. // Write out CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM so that
  533. // installed code that uses `file(GET_RUNTIME_DEPENDENCIES)`
  534. // has same platform variable as when running cmake
  535. if (cmValue platform = this->Makefile->GetDefinition(
  536. "CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM")) {
  537. /* clang-format off */
  538. fout <<
  539. "# Set OS and executable format for runtime-dependencies.\n"
  540. "if(NOT DEFINED CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM)\n"
  541. " set(CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM \""
  542. << *platform << "\")\n"
  543. "endif()\n"
  544. "\n";
  545. /* clang-format on */
  546. }
  547. // Write out CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL so that
  548. // installed code that uses `file(GET_RUNTIME_DEPENDENCIES)`
  549. // has same tool selected as when running cmake
  550. if (cmValue command =
  551. this->Makefile->GetDefinition("CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL")) {
  552. /* clang-format off */
  553. fout <<
  554. "# Set tool for dependency-resolution of runtime-dependencies.\n"
  555. "if(NOT DEFINED CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL)\n"
  556. " set(CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL \""
  557. << *command << "\")\n"
  558. "endif()\n"
  559. "\n";
  560. /* clang-format on */
  561. }
  562. // Write out CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND so that
  563. // installed code that uses `file(GET_RUNTIME_DEPENDENCIES)`
  564. // has same path to the tool as when running cmake
  565. if (cmValue command = this->Makefile->GetDefinition(
  566. "CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND")) {
  567. /* clang-format off */
  568. fout <<
  569. "# Set path to tool for dependency-resolution of runtime-dependencies.\n"
  570. "if(NOT DEFINED CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND)\n"
  571. " set(CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND \""
  572. << *command << "\")\n"
  573. "endif()\n"
  574. "\n";
  575. /* clang-format on */
  576. }
  577. // Write out CMAKE_OBJDUMP so that installed code that uses
  578. // `file(GET_RUNTIME_DEPENDENCIES)` and hasn't specified
  579. // CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND has consistent
  580. // logic to fallback to CMAKE_OBJDUMP when `objdump` is
  581. // not on the path
  582. if (cmValue command = this->Makefile->GetDefinition("CMAKE_OBJDUMP")) {
  583. /* clang-format off */
  584. fout <<
  585. "# Set path to fallback-tool for dependency-resolution.\n"
  586. "if(NOT DEFINED CMAKE_OBJDUMP)\n"
  587. " set(CMAKE_OBJDUMP \""
  588. << *command << "\")\n"
  589. "endif()\n"
  590. "\n";
  591. /* clang-format on */
  592. }
  593. this->AddGeneratorSpecificInstallSetup(fout);
  594. // Ask each install generator to write its code.
  595. cmPolicies::PolicyStatus status = this->GetPolicyStatus(cmPolicies::CMP0082);
  596. auto const& installers = this->Makefile->GetInstallGenerators();
  597. bool haveSubdirectoryInstall = false;
  598. bool haveInstallAfterSubdirectory = false;
  599. if (status == cmPolicies::WARN) {
  600. for (const auto& installer : installers) {
  601. installer->CheckCMP0082(haveSubdirectoryInstall,
  602. haveInstallAfterSubdirectory);
  603. installer->Generate(fout, config, configurationTypes);
  604. }
  605. } else {
  606. for (const auto& installer : installers) {
  607. installer->Generate(fout, config, configurationTypes);
  608. }
  609. }
  610. // Write rules from old-style specification stored in targets.
  611. this->GenerateTargetInstallRules(fout, config, configurationTypes);
  612. // Include install scripts from subdirectories.
  613. switch (status) {
  614. case cmPolicies::WARN:
  615. if (haveInstallAfterSubdirectory &&
  616. this->Makefile->PolicyOptionalWarningEnabled(
  617. "CMAKE_POLICY_WARNING_CMP0082")) {
  618. std::ostringstream e;
  619. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0082) << "\n";
  620. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  621. }
  622. CM_FALLTHROUGH;
  623. case cmPolicies::OLD: {
  624. std::vector<cmStateSnapshot> children =
  625. this->Makefile->GetStateSnapshot().GetChildren();
  626. if (!children.empty()) {
  627. fout << "if(NOT CMAKE_INSTALL_LOCAL_ONLY)\n";
  628. fout << " # Include the install script for each subdirectory.\n";
  629. for (cmStateSnapshot const& c : children) {
  630. if (!c.GetDirectory().GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
  631. std::string odir = c.GetDirectory().GetCurrentBinary();
  632. cmSystemTools::ConvertToUnixSlashes(odir);
  633. fout << " include(\"" << odir << "/cmake_install.cmake\")\n";
  634. }
  635. }
  636. fout << "\n";
  637. fout << "endif()\n\n";
  638. }
  639. } break;
  640. case cmPolicies::REQUIRED_IF_USED:
  641. case cmPolicies::REQUIRED_ALWAYS:
  642. case cmPolicies::NEW:
  643. // NEW behavior is handled in
  644. // cmInstallSubdirectoryGenerator::GenerateScript()
  645. break;
  646. }
  647. /* clang-format off */
  648. fout <<
  649. "string(REPLACE \";\" \"\\n\" CMAKE_INSTALL_MANIFEST_CONTENT\n"
  650. " \"${CMAKE_INSTALL_MANIFEST_FILES}\")\n"
  651. "if(CMAKE_INSTALL_LOCAL_ONLY)\n"
  652. " file(WRITE \"" <<
  653. this->StateSnapshot.GetDirectory().GetCurrentBinary() <<
  654. "/install_local_manifest.txt\"\n"
  655. " \"${CMAKE_INSTALL_MANIFEST_CONTENT}\")\n"
  656. "endif()\n";
  657. if (toplevel_install) {
  658. fout <<
  659. "if(CMAKE_INSTALL_COMPONENT)\n"
  660. " if(CMAKE_INSTALL_COMPONENT MATCHES \"^[a-zA-Z0-9_.+-]+$\")\n"
  661. " set(CMAKE_INSTALL_MANIFEST \"install_manifest_"
  662. "${CMAKE_INSTALL_COMPONENT}.txt\")\n"
  663. " else()\n"
  664. " string(MD5 CMAKE_INST_COMP_HASH \"${CMAKE_INSTALL_COMPONENT}\")\n"
  665. " set(CMAKE_INSTALL_MANIFEST \"install_manifest_"
  666. "${CMAKE_INST_COMP_HASH}.txt\")\n"
  667. " unset(CMAKE_INST_COMP_HASH)\n"
  668. " endif()\n"
  669. "else()\n"
  670. " set(CMAKE_INSTALL_MANIFEST \"install_manifest.txt\")\n"
  671. "endif()\n"
  672. "\n"
  673. "if(NOT CMAKE_INSTALL_LOCAL_ONLY)\n"
  674. " file(WRITE \"" << homedir << "/${CMAKE_INSTALL_MANIFEST}\"\n"
  675. " \"${CMAKE_INSTALL_MANIFEST_CONTENT}\")\n"
  676. "endif()\n";
  677. }
  678. /* clang-format on */
  679. }
  680. void cmLocalGenerator::AddGeneratorTarget(
  681. std::unique_ptr<cmGeneratorTarget> gt)
  682. {
  683. cmGeneratorTarget* gt_ptr = gt.get();
  684. this->GeneratorTargets.push_back(std::move(gt));
  685. this->GeneratorTargetSearchIndex.emplace(gt_ptr->GetName(), gt_ptr);
  686. this->GlobalGenerator->IndexGeneratorTarget(gt_ptr);
  687. }
  688. void cmLocalGenerator::AddImportedGeneratorTarget(cmGeneratorTarget* gt)
  689. {
  690. this->ImportedGeneratorTargets.emplace(gt->GetName(), gt);
  691. this->GlobalGenerator->IndexGeneratorTarget(gt);
  692. }
  693. void cmLocalGenerator::AddOwnedImportedGeneratorTarget(
  694. std::unique_ptr<cmGeneratorTarget> gt)
  695. {
  696. this->OwnedImportedGeneratorTargets.push_back(std::move(gt));
  697. }
  698. cmGeneratorTarget* cmLocalGenerator::FindLocalNonAliasGeneratorTarget(
  699. const std::string& name) const
  700. {
  701. auto ti = this->GeneratorTargetSearchIndex.find(name);
  702. if (ti != this->GeneratorTargetSearchIndex.end()) {
  703. return ti->second;
  704. }
  705. return nullptr;
  706. }
  707. void cmLocalGenerator::ComputeTargetManifest()
  708. {
  709. // Collect the set of configuration types.
  710. std::vector<std::string> configNames =
  711. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  712. // Add our targets to the manifest for each configuration.
  713. const auto& targets = this->GetGeneratorTargets();
  714. for (const auto& target : targets) {
  715. if (!target->IsInBuildSystem()) {
  716. continue;
  717. }
  718. for (std::string const& c : configNames) {
  719. target->ComputeTargetManifest(c);
  720. }
  721. }
  722. }
  723. bool cmLocalGenerator::ComputeTargetCompileFeatures()
  724. {
  725. // Collect the set of configuration types.
  726. std::vector<std::string> configNames =
  727. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  728. using LanguagePair = std::pair<std::string, std::string>;
  729. std::vector<LanguagePair> pairedLanguages{
  730. { "OBJC", "C" }, { "OBJCXX", "CXX" }, { "CUDA", "CXX" }, { "HIP", "CXX" }
  731. };
  732. std::set<LanguagePair> inferredEnabledLanguages;
  733. for (auto const& lang : pairedLanguages) {
  734. if (this->Makefile->GetState()->GetLanguageEnabled(lang.first)) {
  735. inferredEnabledLanguages.insert(lang);
  736. }
  737. }
  738. // Process compile features of all targets.
  739. const auto& targets = this->GetGeneratorTargets();
  740. for (const auto& target : targets) {
  741. for (std::string const& c : configNames) {
  742. if (!target->ComputeCompileFeatures(c)) {
  743. return false;
  744. }
  745. }
  746. // Now that C/C++ _STANDARD values have been computed
  747. // set the values to ObjC/ObjCXX _STANDARD variables
  748. if (target->CanCompileSources()) {
  749. for (std::string const& c : configNames) {
  750. target->ComputeCompileFeatures(c, inferredEnabledLanguages);
  751. }
  752. }
  753. }
  754. return true;
  755. }
  756. bool cmLocalGenerator::IsRootMakefile() const
  757. {
  758. return !this->StateSnapshot.GetBuildsystemDirectoryParent().IsValid();
  759. }
  760. cmState* cmLocalGenerator::GetState() const
  761. {
  762. return this->GlobalGenerator->GetCMakeInstance()->GetState();
  763. }
  764. cmStateSnapshot cmLocalGenerator::GetStateSnapshot() const
  765. {
  766. return this->Makefile->GetStateSnapshot();
  767. }
  768. std::string cmLocalGenerator::GetRuleLauncher(cmGeneratorTarget* target,
  769. const std::string& prop,
  770. const std::string& config)
  771. {
  772. cmValue value = this->Makefile->GetProperty(prop);
  773. if (target) {
  774. value = target->GetProperty(prop);
  775. }
  776. if (value) {
  777. return cmGeneratorExpression::Evaluate(*value, this, config, target);
  778. }
  779. return "";
  780. }
  781. std::string cmLocalGenerator::ConvertToIncludeReference(
  782. std::string const& path, OutputFormat format)
  783. {
  784. return this->ConvertToOutputForExisting(path, format);
  785. }
  786. std::string cmLocalGenerator::GetIncludeFlags(
  787. std::vector<std::string> const& includeDirs, cmGeneratorTarget* target,
  788. std::string const& lang, std::string const& config, bool forResponseFile)
  789. {
  790. if (lang.empty()) {
  791. return "";
  792. }
  793. std::vector<std::string> includes = includeDirs;
  794. MoveSystemIncludesToEnd(includes, config, lang, target);
  795. OutputFormat shellFormat = forResponseFile ? RESPONSE : SHELL;
  796. std::ostringstream includeFlags;
  797. std::string const& includeFlag =
  798. this->Makefile->GetSafeDefinition(cmStrCat("CMAKE_INCLUDE_FLAG_", lang));
  799. bool quotePaths = false;
  800. if (this->Makefile->GetDefinition("CMAKE_QUOTE_INCLUDE_PATHS")) {
  801. quotePaths = true;
  802. }
  803. std::string sep = " ";
  804. bool repeatFlag = true;
  805. // should the include flag be repeated like ie. -IA -IB
  806. if (cmValue incSep = this->Makefile->GetDefinition(
  807. cmStrCat("CMAKE_INCLUDE_FLAG_SEP_", lang))) {
  808. // if there is a separator then the flag is not repeated but is only
  809. // given once i.e. -classpath a:b:c
  810. sep = *incSep;
  811. repeatFlag = false;
  812. }
  813. // Support special system include flag if it is available and the
  814. // normal flag is repeated for each directory.
  815. cmValue sysIncludeFlag = nullptr;
  816. cmValue sysIncludeFlagWarning = nullptr;
  817. if (repeatFlag) {
  818. sysIncludeFlag = this->Makefile->GetDefinition(
  819. cmStrCat("CMAKE_INCLUDE_SYSTEM_FLAG_", lang));
  820. sysIncludeFlagWarning = this->Makefile->GetDefinition(
  821. cmStrCat("CMAKE_INCLUDE_SYSTEM_FLAG_", lang, "_WARNING"));
  822. }
  823. cmValue fwSearchFlag = this->Makefile->GetDefinition(
  824. cmStrCat("CMAKE_", lang, "_FRAMEWORK_SEARCH_FLAG"));
  825. cmValue sysFwSearchFlag = this->Makefile->GetDefinition(
  826. cmStrCat("CMAKE_", lang, "_SYSTEM_FRAMEWORK_SEARCH_FLAG"));
  827. bool flagUsed = false;
  828. bool sysIncludeFlagUsed = false;
  829. std::set<std::string> emitted;
  830. #ifdef __APPLE__
  831. emitted.insert("/System/Library/Frameworks");
  832. #endif
  833. for (std::string const& i : includes) {
  834. if (cmNonempty(fwSearchFlag) && this->Makefile->IsOn("APPLE") &&
  835. cmSystemTools::IsPathToFramework(i)) {
  836. std::string const frameworkDir = cmSystemTools::GetFilenamePath(i);
  837. if (emitted.insert(frameworkDir).second) {
  838. if (sysFwSearchFlag && target &&
  839. target->IsSystemIncludeDirectory(frameworkDir, config, lang)) {
  840. includeFlags << *sysFwSearchFlag;
  841. } else {
  842. includeFlags << *fwSearchFlag;
  843. }
  844. includeFlags << this->ConvertToOutputFormat(frameworkDir, shellFormat)
  845. << " ";
  846. }
  847. continue;
  848. }
  849. if (!flagUsed || repeatFlag) {
  850. if (sysIncludeFlag && target &&
  851. target->IsSystemIncludeDirectory(i, config, lang)) {
  852. includeFlags << *sysIncludeFlag;
  853. sysIncludeFlagUsed = true;
  854. } else {
  855. includeFlags << includeFlag;
  856. }
  857. flagUsed = true;
  858. }
  859. std::string includePath = this->ConvertToIncludeReference(i, shellFormat);
  860. if (quotePaths && !includePath.empty() && includePath.front() != '\"') {
  861. includeFlags << "\"";
  862. }
  863. includeFlags << includePath;
  864. if (quotePaths && !includePath.empty() && includePath.front() != '\"') {
  865. includeFlags << "\"";
  866. }
  867. includeFlags << sep;
  868. }
  869. if (sysIncludeFlagUsed && sysIncludeFlagWarning) {
  870. includeFlags << *sysIncludeFlagWarning;
  871. }
  872. std::string flags = includeFlags.str();
  873. // remove trailing separators
  874. if ((sep[0] != ' ') && !flags.empty() && flags.back() == sep[0]) {
  875. flags.back() = ' ';
  876. }
  877. return cmTrimWhitespace(flags);
  878. }
  879. void cmLocalGenerator::AddCompileOptions(std::string& flags,
  880. cmGeneratorTarget* target,
  881. const std::string& lang,
  882. const std::string& config)
  883. {
  884. std::vector<BT<std::string>> tmpFlags;
  885. this->AddCompileOptions(tmpFlags, target, lang, config);
  886. this->AppendFlags(flags, tmpFlags);
  887. }
  888. void cmLocalGenerator::AddCompileOptions(std::vector<BT<std::string>>& flags,
  889. cmGeneratorTarget* target,
  890. const std::string& lang,
  891. const std::string& config)
  892. {
  893. std::string langFlagRegexVar = cmStrCat("CMAKE_", lang, "_FLAG_REGEX");
  894. if (cmValue langFlagRegexStr =
  895. this->Makefile->GetDefinition(langFlagRegexVar)) {
  896. // Filter flags acceptable to this language.
  897. if (cmValue targetFlags = target->GetProperty("COMPILE_FLAGS")) {
  898. std::vector<std::string> opts;
  899. cmSystemTools::ParseWindowsCommandLine(targetFlags->c_str(), opts);
  900. // Re-escape these flags since COMPILE_FLAGS were already parsed
  901. // as a command line above.
  902. std::string compileOpts;
  903. this->AppendCompileOptions(compileOpts, opts, langFlagRegexStr->c_str());
  904. if (!compileOpts.empty()) {
  905. flags.emplace_back(std::move(compileOpts));
  906. }
  907. }
  908. std::vector<BT<std::string>> targetCompileOpts =
  909. target->GetCompileOptions(config, lang);
  910. // COMPILE_OPTIONS are escaped.
  911. this->AppendCompileOptions(flags, targetCompileOpts,
  912. langFlagRegexStr->c_str());
  913. } else {
  914. // Use all flags.
  915. if (cmValue targetFlags = target->GetProperty("COMPILE_FLAGS")) {
  916. // COMPILE_FLAGS are not escaped for historical reasons.
  917. std::string compileFlags;
  918. this->AppendFlags(compileFlags, *targetFlags);
  919. if (!compileFlags.empty()) {
  920. flags.emplace_back(std::move(compileFlags));
  921. }
  922. }
  923. std::vector<BT<std::string>> targetCompileOpts =
  924. target->GetCompileOptions(config, lang);
  925. // COMPILE_OPTIONS are escaped.
  926. this->AppendCompileOptions(flags, targetCompileOpts);
  927. }
  928. cmStandardLevelResolver standardResolver(this->Makefile);
  929. for (auto const& it : target->GetMaxLanguageStandards()) {
  930. cmValue standard = target->GetLanguageStandard(it.first, config);
  931. if (!standard) {
  932. continue;
  933. }
  934. if (standardResolver.IsLaterStandard(it.first, *standard, it.second)) {
  935. std::ostringstream e;
  936. e << "The COMPILE_FEATURES property of target \"" << target->GetName()
  937. << "\" was evaluated when computing the link "
  938. "implementation, and the \""
  939. << it.first << "_STANDARD\" was \"" << it.second
  940. << "\" for that computation. Computing the "
  941. "COMPILE_FEATURES based on the link implementation resulted in a "
  942. "higher \""
  943. << it.first << "_STANDARD\" \"" << *standard
  944. << "\". "
  945. "This is not permitted. The COMPILE_FEATURES may not both depend "
  946. "on "
  947. "and be depended on by the link implementation.\n";
  948. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  949. return;
  950. }
  951. }
  952. // Add Warning as errors flags
  953. if (!this->GetCMakeInstance()->GetIgnoreWarningAsError()) {
  954. const cmValue wError = target->GetProperty("COMPILE_WARNING_AS_ERROR");
  955. const cmValue wErrorOpts = this->Makefile->GetDefinition(
  956. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_WARNING_AS_ERROR"));
  957. if (wError.IsOn() && wErrorOpts.IsSet()) {
  958. std::string wErrorFlags;
  959. this->AppendCompileOptions(wErrorFlags, *wErrorOpts);
  960. if (!wErrorFlags.empty()) {
  961. flags.emplace_back(std::move(wErrorFlags));
  962. }
  963. }
  964. }
  965. // Add compile flag for the MSVC compiler only.
  966. cmMakefile* mf = this->GetMakefile();
  967. if (cmValue jmc =
  968. mf->GetDefinition("CMAKE_" + lang + "_COMPILE_OPTIONS_JMC")) {
  969. // Handle Just My Code debugging flags, /JMC.
  970. // If the target is a Managed C++ one, /JMC is not compatible.
  971. if (target->GetManagedType(config) !=
  972. cmGeneratorTarget::ManagedType::Managed) {
  973. // add /JMC flags if target property VS_JUST_MY_CODE_DEBUGGING is set
  974. // to ON
  975. if (cmValue jmcExprGen =
  976. target->GetProperty("VS_JUST_MY_CODE_DEBUGGING")) {
  977. std::string isJMCEnabled =
  978. cmGeneratorExpression::Evaluate(*jmcExprGen, this, config);
  979. if (cmIsOn(isJMCEnabled)) {
  980. cmList optList{ *jmc };
  981. std::string jmcFlags;
  982. this->AppendCompileOptions(jmcFlags, optList);
  983. if (!jmcFlags.empty()) {
  984. flags.emplace_back(std::move(jmcFlags));
  985. }
  986. }
  987. }
  988. }
  989. }
  990. }
  991. cmTarget* cmLocalGenerator::AddCustomCommandToTarget(
  992. const std::string& target, cmCustomCommandType type,
  993. std::unique_ptr<cmCustomCommand> cc, cmObjectLibraryCommands objLibCommands)
  994. {
  995. cmTarget* t = this->Makefile->GetCustomCommandTarget(
  996. target, objLibCommands, this->DirectoryBacktrace);
  997. if (!t) {
  998. return nullptr;
  999. }
  1000. cc->SetBacktrace(this->DirectoryBacktrace);
  1001. detail::AddCustomCommandToTarget(*this, cmCommandOrigin::Generator, t, type,
  1002. std::move(cc));
  1003. return t;
  1004. }
  1005. cmSourceFile* cmLocalGenerator::AddCustomCommandToOutput(
  1006. std::unique_ptr<cmCustomCommand> cc, bool replace)
  1007. {
  1008. // Make sure there is at least one output.
  1009. if (cc->GetOutputs().empty()) {
  1010. cmSystemTools::Error("Attempt to add a custom rule with no output!");
  1011. return nullptr;
  1012. }
  1013. cc->SetBacktrace(this->DirectoryBacktrace);
  1014. return detail::AddCustomCommandToOutput(*this, cmCommandOrigin::Generator,
  1015. std::move(cc), replace);
  1016. }
  1017. cmTarget* cmLocalGenerator::AddUtilityCommand(
  1018. const std::string& utilityName, bool excludeFromAll,
  1019. std::unique_ptr<cmCustomCommand> cc)
  1020. {
  1021. cmTarget* target =
  1022. this->Makefile->AddNewUtilityTarget(utilityName, excludeFromAll);
  1023. target->SetIsGeneratorProvided(true);
  1024. if (cc->GetCommandLines().empty() && cc->GetDepends().empty()) {
  1025. return target;
  1026. }
  1027. cc->SetBacktrace(this->DirectoryBacktrace);
  1028. detail::AddUtilityCommand(*this, cmCommandOrigin::Generator, target,
  1029. std::move(cc));
  1030. return target;
  1031. }
  1032. std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectoriesImplicit(
  1033. cmGeneratorTarget const* target, std::string const& lang,
  1034. std::string const& config, bool stripImplicitDirs,
  1035. bool appendAllImplicitDirs) const
  1036. {
  1037. std::vector<BT<std::string>> result;
  1038. // Do not repeat an include path.
  1039. std::set<std::string> emitted;
  1040. auto emitDir = [&result, &emitted](std::string const& dir) {
  1041. if (emitted.insert(dir).second) {
  1042. result.emplace_back(dir);
  1043. }
  1044. };
  1045. auto emitBT = [&result, &emitted](BT<std::string> const& dir) {
  1046. if (emitted.insert(dir.Value).second) {
  1047. result.emplace_back(dir);
  1048. }
  1049. };
  1050. // When automatic include directories are requested for a build then
  1051. // include the source and binary directories at the beginning of the
  1052. // include path to approximate include file behavior for an
  1053. // in-source build. This does not account for the case of a source
  1054. // file in a subdirectory of the current source directory but we
  1055. // cannot fix this because not all native build tools support
  1056. // per-source-file include paths.
  1057. if (this->Makefile->IsOn("CMAKE_INCLUDE_CURRENT_DIR")) {
  1058. // Current binary directory
  1059. emitDir(this->StateSnapshot.GetDirectory().GetCurrentBinary());
  1060. // Current source directory
  1061. emitDir(this->StateSnapshot.GetDirectory().GetCurrentSource());
  1062. }
  1063. if (!target) {
  1064. return result;
  1065. }
  1066. // Standard include directories to be added unconditionally at the end.
  1067. // These are intended to simulate additional implicit include directories.
  1068. cmList userStandardDirs;
  1069. {
  1070. std::string const value = this->Makefile->GetSafeDefinition(
  1071. cmStrCat("CMAKE_", lang, "_STANDARD_INCLUDE_DIRECTORIES"));
  1072. userStandardDirs.assign(value);
  1073. for (std::string& usd : userStandardDirs) {
  1074. cmSystemTools::ConvertToUnixSlashes(usd);
  1075. }
  1076. }
  1077. // Implicit include directories
  1078. std::vector<std::string> implicitDirs;
  1079. std::set<std::string> implicitSet;
  1080. // Include directories to be excluded as if they were implicit.
  1081. std::set<std::string> implicitExclude;
  1082. {
  1083. // Raw list of implicit include directories
  1084. // Start with "standard" directories that we unconditionally add below.
  1085. std::vector<std::string> impDirVec = userStandardDirs;
  1086. // Load implicit include directories for this language.
  1087. // We ignore this for Fortran because:
  1088. // * There are no standard library headers to avoid overriding.
  1089. // * Compilers like gfortran do not search their own implicit include
  1090. // directories for modules ('.mod' files).
  1091. if (lang != "Fortran") {
  1092. size_t const impDirVecOldSize = impDirVec.size();
  1093. cmList::append(impDirVec,
  1094. this->Makefile->GetDefinition(cmStrCat(
  1095. "CMAKE_", lang, "_IMPLICIT_INCLUDE_DIRECTORIES")));
  1096. // FIXME: Use cmRange with 'advance()' when it supports non-const.
  1097. for (size_t i = impDirVecOldSize; i < impDirVec.size(); ++i) {
  1098. cmSystemTools::ConvertToUnixSlashes(impDirVec[i]);
  1099. }
  1100. // The CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES are computed using
  1101. // try_compile in CMAKE_DETERMINE_COMPILER_ABI, but the implicit include
  1102. // directories are not known during that try_compile. This can be a
  1103. // problem when the HIP runtime include path is /usr/include because the
  1104. // runtime include path is always added to the userDirs and the compiler
  1105. // includes standard library headers via "__clang_hip_runtime_wrapper.h".
  1106. if (lang == "HIP" && impDirVec.size() == impDirVecOldSize &&
  1107. !cm::contains(impDirVec, "/usr/include")) {
  1108. implicitExclude.emplace("/usr/include");
  1109. }
  1110. }
  1111. // The Platform/UnixPaths module used to hard-code /usr/include for C, CXX,
  1112. // and CUDA in CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES, but those
  1113. // variables are now computed. On macOS the /usr/include directory is
  1114. // inside the platform SDK so the computed value does not contain it
  1115. // directly. In this case adding -I/usr/include can hide SDK headers so we
  1116. // must still exclude it.
  1117. if ((lang == "C" || lang == "CXX" || lang == "CUDA") &&
  1118. !cm::contains(impDirVec, "/usr/include") &&
  1119. std::find_if(impDirVec.begin(), impDirVec.end(),
  1120. [](std::string const& d) {
  1121. return cmHasLiteralSuffix(d, "/usr/include");
  1122. }) != impDirVec.end()) {
  1123. // Only exclude this hard coded path for backwards compatibility.
  1124. implicitExclude.emplace("/usr/include");
  1125. }
  1126. for (std::string const& i : impDirVec) {
  1127. if (implicitSet.insert(this->GlobalGenerator->GetRealPath(i)).second) {
  1128. implicitDirs.emplace_back(i);
  1129. }
  1130. }
  1131. }
  1132. bool const isCorCxx = (lang == "C" || lang == "CXX");
  1133. // Resolve symlinks in CPATH for comparison with resolved include paths.
  1134. // We do this here instead of when EnvCPATH is populated in case symlinks
  1135. // on disk have changed in the meantime.
  1136. std::set<std::string> resolvedEnvCPATH;
  1137. if (isCorCxx) {
  1138. for (std::string const& i : this->EnvCPATH) {
  1139. resolvedEnvCPATH.emplace(this->GlobalGenerator->GetRealPath(i));
  1140. }
  1141. }
  1142. // Checks if this is not an excluded (implicit) include directory.
  1143. auto notExcluded = [this, &implicitSet, &implicitExclude, &resolvedEnvCPATH,
  1144. isCorCxx](std::string const& dir) -> bool {
  1145. std::string const& real_dir = this->GlobalGenerator->GetRealPath(dir);
  1146. return
  1147. // Do not exclude directories that are not in any excluded set.
  1148. !(cm::contains(implicitSet, real_dir) ||
  1149. cm::contains(implicitExclude, dir))
  1150. // Do not exclude entries of the CPATH environment variable even though
  1151. // they are implicitly searched by the compiler. They are meant to be
  1152. // user-specified directories that can be re-ordered or converted to
  1153. // -isystem without breaking real compiler builtin headers.
  1154. || (isCorCxx && cm::contains(resolvedEnvCPATH, real_dir));
  1155. };
  1156. // Get the target-specific include directories.
  1157. std::vector<BT<std::string>> userDirs =
  1158. target->GetIncludeDirectories(config, lang);
  1159. // Support putting all the in-project include directories first if
  1160. // it is requested by the project.
  1161. if (this->Makefile->IsOn("CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE")) {
  1162. std::string const& topSourceDir = this->GetState()->GetSourceDirectory();
  1163. std::string const& topBinaryDir = this->GetState()->GetBinaryDirectory();
  1164. for (BT<std::string> const& udr : userDirs) {
  1165. // Emit this directory only if it is a subdirectory of the
  1166. // top-level source or binary tree.
  1167. if (cmSystemTools::ComparePath(udr.Value, topSourceDir) ||
  1168. cmSystemTools::ComparePath(udr.Value, topBinaryDir) ||
  1169. cmSystemTools::IsSubDirectory(udr.Value, topSourceDir) ||
  1170. cmSystemTools::IsSubDirectory(udr.Value, topBinaryDir)) {
  1171. if (notExcluded(udr.Value)) {
  1172. emitBT(udr);
  1173. }
  1174. }
  1175. }
  1176. }
  1177. // Emit remaining non implicit user directories.
  1178. for (BT<std::string> const& udr : userDirs) {
  1179. if (notExcluded(udr.Value)) {
  1180. emitBT(udr);
  1181. }
  1182. }
  1183. // Sort result
  1184. MoveSystemIncludesToEnd(result, config, lang, target);
  1185. // Append standard include directories for this language.
  1186. userDirs.reserve(userDirs.size() + userStandardDirs.size());
  1187. for (std::string& usd : userStandardDirs) {
  1188. emitDir(usd);
  1189. userDirs.emplace_back(std::move(usd));
  1190. }
  1191. // Append compiler implicit include directories
  1192. if (!stripImplicitDirs) {
  1193. // Append implicit directories that were requested by the user only
  1194. for (BT<std::string> const& udr : userDirs) {
  1195. if (cm::contains(implicitSet, cmSystemTools::GetRealPath(udr.Value))) {
  1196. emitBT(udr);
  1197. }
  1198. }
  1199. // Append remaining implicit directories (on demand)
  1200. if (appendAllImplicitDirs) {
  1201. for (std::string& imd : implicitDirs) {
  1202. emitDir(imd);
  1203. }
  1204. }
  1205. }
  1206. return result;
  1207. }
  1208. void cmLocalGenerator::GetIncludeDirectoriesImplicit(
  1209. std::vector<std::string>& dirs, cmGeneratorTarget const* target,
  1210. const std::string& lang, const std::string& config, bool stripImplicitDirs,
  1211. bool appendAllImplicitDirs) const
  1212. {
  1213. std::vector<BT<std::string>> tmp = this->GetIncludeDirectoriesImplicit(
  1214. target, lang, config, stripImplicitDirs, appendAllImplicitDirs);
  1215. dirs.reserve(dirs.size() + tmp.size());
  1216. for (BT<std::string>& v : tmp) {
  1217. dirs.emplace_back(std::move(v.Value));
  1218. }
  1219. }
  1220. std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectories(
  1221. cmGeneratorTarget const* target, std::string const& lang,
  1222. std::string const& config) const
  1223. {
  1224. return this->GetIncludeDirectoriesImplicit(target, lang, config);
  1225. }
  1226. void cmLocalGenerator::GetIncludeDirectories(std::vector<std::string>& dirs,
  1227. cmGeneratorTarget const* target,
  1228. const std::string& lang,
  1229. const std::string& config) const
  1230. {
  1231. this->GetIncludeDirectoriesImplicit(dirs, target, lang, config);
  1232. }
  1233. void cmLocalGenerator::GetStaticLibraryFlags(std::string& flags,
  1234. std::string const& config,
  1235. std::string const& linkLanguage,
  1236. cmGeneratorTarget* target)
  1237. {
  1238. std::vector<BT<std::string>> tmpFlags =
  1239. this->GetStaticLibraryFlags(config, linkLanguage, target);
  1240. this->AppendFlags(flags, tmpFlags);
  1241. }
  1242. std::vector<BT<std::string>> cmLocalGenerator::GetStaticLibraryFlags(
  1243. std::string const& config, std::string const& linkLanguage,
  1244. cmGeneratorTarget* target)
  1245. {
  1246. const std::string configUpper = cmSystemTools::UpperCase(config);
  1247. std::vector<BT<std::string>> flags;
  1248. if (linkLanguage != "Swift" && !this->IsSplitSwiftBuild()) {
  1249. std::string staticLibFlags;
  1250. this->AppendFlags(
  1251. staticLibFlags,
  1252. this->Makefile->GetSafeDefinition("CMAKE_STATIC_LINKER_FLAGS"));
  1253. if (!configUpper.empty()) {
  1254. std::string name = "CMAKE_STATIC_LINKER_FLAGS_" + configUpper;
  1255. this->AppendFlags(staticLibFlags,
  1256. this->Makefile->GetSafeDefinition(name));
  1257. }
  1258. if (!staticLibFlags.empty()) {
  1259. flags.emplace_back(std::move(staticLibFlags));
  1260. }
  1261. }
  1262. std::string staticLibFlags;
  1263. this->AppendFlags(staticLibFlags,
  1264. target->GetSafeProperty("STATIC_LIBRARY_FLAGS"));
  1265. if (!configUpper.empty()) {
  1266. std::string name = "STATIC_LIBRARY_FLAGS_" + configUpper;
  1267. this->AppendFlags(staticLibFlags, target->GetSafeProperty(name));
  1268. }
  1269. if (!staticLibFlags.empty()) {
  1270. flags.emplace_back(std::move(staticLibFlags));
  1271. }
  1272. std::vector<BT<std::string>> staticLibOpts =
  1273. target->GetStaticLibraryLinkOptions(config, linkLanguage);
  1274. // STATIC_LIBRARY_OPTIONS are escaped.
  1275. this->AppendCompileOptions(flags, staticLibOpts);
  1276. return flags;
  1277. }
  1278. void cmLocalGenerator::GetDeviceLinkFlags(
  1279. cmLinkLineDeviceComputer& linkLineComputer, const std::string& config,
  1280. std::string& linkLibs, std::string& linkFlags, std::string& frameworkPath,
  1281. std::string& linkPath, cmGeneratorTarget* target)
  1282. {
  1283. cmGeneratorTarget::DeviceLinkSetter setter(*target);
  1284. cmComputeLinkInformation* pcli = target->GetLinkInformation(config);
  1285. auto linklang = linkLineComputer.GetLinkerLanguage(target, config);
  1286. auto ipoEnabled = target->IsIPOEnabled(linklang, config);
  1287. if (!ipoEnabled) {
  1288. ipoEnabled = linkLineComputer.ComputeRequiresDeviceLinkingIPOFlag(*pcli);
  1289. }
  1290. if (ipoEnabled) {
  1291. if (cmValue cudaIPOFlags = this->Makefile->GetDefinition(
  1292. "CMAKE_CUDA_DEVICE_LINK_OPTIONS_IPO")) {
  1293. linkFlags += *cudaIPOFlags;
  1294. }
  1295. }
  1296. if (pcli) {
  1297. // Compute the required device link libraries when
  1298. // resolving gpu lang device symbols
  1299. this->OutputLinkLibraries(pcli, &linkLineComputer, linkLibs, frameworkPath,
  1300. linkPath);
  1301. }
  1302. this->AddVisibilityPresetFlags(linkFlags, target, "CUDA");
  1303. this->GetGlobalGenerator()->EncodeLiteral(linkFlags);
  1304. std::vector<std::string> linkOpts;
  1305. target->GetLinkOptions(linkOpts, config, "CUDA");
  1306. this->SetLinkScriptShell(this->GetGlobalGenerator()->GetUseLinkScript());
  1307. // LINK_OPTIONS are escaped.
  1308. this->AppendCompileOptions(linkFlags, linkOpts);
  1309. this->SetLinkScriptShell(false);
  1310. }
  1311. void cmLocalGenerator::GetTargetFlags(
  1312. cmLinkLineComputer* linkLineComputer, const std::string& config,
  1313. std::string& linkLibs, std::string& flags, std::string& linkFlags,
  1314. std::string& frameworkPath, std::string& linkPath, cmGeneratorTarget* target)
  1315. {
  1316. std::vector<BT<std::string>> linkFlagsList;
  1317. std::vector<BT<std::string>> linkPathList;
  1318. std::vector<BT<std::string>> linkLibsList;
  1319. this->GetTargetFlags(linkLineComputer, config, linkLibsList, flags,
  1320. linkFlagsList, frameworkPath, linkPathList, target);
  1321. this->AppendFlags(linkFlags, linkFlagsList);
  1322. this->AppendFlags(linkPath, linkPathList);
  1323. this->AppendFlags(linkLibs, linkLibsList);
  1324. }
  1325. void cmLocalGenerator::GetTargetFlags(
  1326. cmLinkLineComputer* linkLineComputer, const std::string& config,
  1327. std::vector<BT<std::string>>& linkLibs, std::string& flags,
  1328. std::vector<BT<std::string>>& linkFlags, std::string& frameworkPath,
  1329. std::vector<BT<std::string>>& linkPath, cmGeneratorTarget* target)
  1330. {
  1331. const std::string configUpper = cmSystemTools::UpperCase(config);
  1332. cmComputeLinkInformation* pcli = target->GetLinkInformation(config);
  1333. const char* libraryLinkVariable =
  1334. "CMAKE_SHARED_LINKER_FLAGS"; // default to shared library
  1335. const std::string linkLanguage =
  1336. linkLineComputer->GetLinkerLanguage(target, config);
  1337. switch (target->GetType()) {
  1338. case cmStateEnums::STATIC_LIBRARY:
  1339. linkFlags = this->GetStaticLibraryFlags(config, linkLanguage, target);
  1340. break;
  1341. case cmStateEnums::MODULE_LIBRARY:
  1342. libraryLinkVariable = "CMAKE_MODULE_LINKER_FLAGS";
  1343. CM_FALLTHROUGH;
  1344. case cmStateEnums::SHARED_LIBRARY: {
  1345. std::string sharedLibFlags;
  1346. if (this->IsSplitSwiftBuild() || linkLanguage != "Swift") {
  1347. sharedLibFlags = cmStrCat(
  1348. this->Makefile->GetSafeDefinition(libraryLinkVariable), ' ');
  1349. if (!configUpper.empty()) {
  1350. std::string build = cmStrCat(libraryLinkVariable, '_', configUpper);
  1351. sharedLibFlags += this->Makefile->GetSafeDefinition(build);
  1352. sharedLibFlags += " ";
  1353. }
  1354. }
  1355. cmValue targetLinkFlags = target->GetProperty("LINK_FLAGS");
  1356. if (targetLinkFlags) {
  1357. sharedLibFlags += *targetLinkFlags;
  1358. sharedLibFlags += " ";
  1359. }
  1360. if (!configUpper.empty()) {
  1361. targetLinkFlags =
  1362. target->GetProperty(cmStrCat("LINK_FLAGS_", configUpper));
  1363. if (targetLinkFlags) {
  1364. sharedLibFlags += *targetLinkFlags;
  1365. sharedLibFlags += " ";
  1366. }
  1367. }
  1368. if (!sharedLibFlags.empty()) {
  1369. this->GetGlobalGenerator()->EncodeLiteral(sharedLibFlags);
  1370. linkFlags.emplace_back(std::move(sharedLibFlags));
  1371. }
  1372. std::vector<BT<std::string>> linkOpts =
  1373. target->GetLinkOptions(config, linkLanguage);
  1374. this->SetLinkScriptShell(this->GetGlobalGenerator()->GetUseLinkScript());
  1375. // LINK_OPTIONS are escaped.
  1376. this->AppendCompileOptions(linkFlags, linkOpts);
  1377. this->SetLinkScriptShell(false);
  1378. if (pcli) {
  1379. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1380. frameworkPath, linkPath);
  1381. }
  1382. } break;
  1383. case cmStateEnums::EXECUTABLE: {
  1384. std::string exeFlags;
  1385. if (linkLanguage.empty()) {
  1386. cmSystemTools::Error(
  1387. "CMake can not determine linker language for target: " +
  1388. target->GetName());
  1389. return;
  1390. }
  1391. if (linkLanguage != "Swift") {
  1392. exeFlags = this->Makefile->GetSafeDefinition("CMAKE_EXE_LINKER_FLAGS");
  1393. exeFlags += " ";
  1394. if (!configUpper.empty()) {
  1395. exeFlags += this->Makefile->GetSafeDefinition(
  1396. cmStrCat("CMAKE_EXE_LINKER_FLAGS_", configUpper));
  1397. exeFlags += " ";
  1398. }
  1399. }
  1400. if (target->IsWin32Executable(config)) {
  1401. exeFlags += this->Makefile->GetSafeDefinition(
  1402. cmStrCat("CMAKE_", linkLanguage, "_CREATE_WIN32_EXE"));
  1403. exeFlags += " ";
  1404. } else {
  1405. exeFlags += this->Makefile->GetSafeDefinition(
  1406. cmStrCat("CMAKE_", linkLanguage, "_CREATE_CONSOLE_EXE"));
  1407. exeFlags += " ";
  1408. }
  1409. if (target->IsExecutableWithExports()) {
  1410. exeFlags += this->Makefile->GetSafeDefinition(
  1411. cmStrCat("CMAKE_EXE_EXPORTS_", linkLanguage, "_FLAG"));
  1412. exeFlags += " ";
  1413. }
  1414. this->AddLanguageFlagsForLinking(flags, target, linkLanguage, config);
  1415. if (pcli) {
  1416. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1417. frameworkPath, linkPath);
  1418. }
  1419. if (this->Makefile->IsOn("BUILD_SHARED_LIBS")) {
  1420. std::string sFlagVar = "CMAKE_SHARED_BUILD_" + linkLanguage + "_FLAGS";
  1421. exeFlags += this->Makefile->GetSafeDefinition(sFlagVar);
  1422. exeFlags += " ";
  1423. }
  1424. std::string cmp0065Flags =
  1425. this->GetLinkLibsCMP0065(linkLanguage, *target);
  1426. if (!cmp0065Flags.empty()) {
  1427. exeFlags += cmp0065Flags;
  1428. exeFlags += " ";
  1429. }
  1430. cmValue targetLinkFlags = target->GetProperty("LINK_FLAGS");
  1431. if (targetLinkFlags) {
  1432. exeFlags += *targetLinkFlags;
  1433. exeFlags += " ";
  1434. }
  1435. if (!configUpper.empty()) {
  1436. targetLinkFlags =
  1437. target->GetProperty(cmStrCat("LINK_FLAGS_", configUpper));
  1438. if (targetLinkFlags) {
  1439. exeFlags += *targetLinkFlags;
  1440. exeFlags += " ";
  1441. }
  1442. }
  1443. if (!exeFlags.empty()) {
  1444. this->GetGlobalGenerator()->EncodeLiteral(exeFlags);
  1445. linkFlags.emplace_back(std::move(exeFlags));
  1446. }
  1447. std::vector<BT<std::string>> linkOpts =
  1448. target->GetLinkOptions(config, linkLanguage);
  1449. this->SetLinkScriptShell(this->GetGlobalGenerator()->GetUseLinkScript());
  1450. // LINK_OPTIONS are escaped.
  1451. this->AppendCompileOptions(linkFlags, linkOpts);
  1452. this->SetLinkScriptShell(false);
  1453. } break;
  1454. default:
  1455. break;
  1456. }
  1457. std::string extraLinkFlags;
  1458. this->AppendLinkerTypeFlags(extraLinkFlags, target, config, linkLanguage);
  1459. this->AppendPositionIndependentLinkerFlags(extraLinkFlags, target, config,
  1460. linkLanguage);
  1461. this->AppendIPOLinkerFlags(extraLinkFlags, target, config, linkLanguage);
  1462. this->AppendDependencyInfoLinkerFlags(extraLinkFlags, target, config,
  1463. linkLanguage);
  1464. this->AppendModuleDefinitionFlag(extraLinkFlags, target, linkLineComputer,
  1465. config);
  1466. if (!extraLinkFlags.empty()) {
  1467. this->GetGlobalGenerator()->EncodeLiteral(extraLinkFlags);
  1468. linkFlags.emplace_back(std::move(extraLinkFlags));
  1469. }
  1470. }
  1471. void cmLocalGenerator::GetTargetCompileFlags(cmGeneratorTarget* target,
  1472. std::string const& config,
  1473. std::string const& lang,
  1474. std::string& flags,
  1475. std::string const& arch)
  1476. {
  1477. std::vector<BT<std::string>> tmpFlags =
  1478. this->GetTargetCompileFlags(target, config, lang, arch);
  1479. this->AppendFlags(flags, tmpFlags);
  1480. }
  1481. std::vector<BT<std::string>> cmLocalGenerator::GetTargetCompileFlags(
  1482. cmGeneratorTarget* target, std::string const& config,
  1483. std::string const& lang, std::string const& arch)
  1484. {
  1485. std::vector<BT<std::string>> flags;
  1486. std::string compileFlags;
  1487. cmMakefile* mf = this->GetMakefile();
  1488. // Add language-specific flags.
  1489. this->AddLanguageFlags(compileFlags, target, cmBuildStep::Compile, lang,
  1490. config);
  1491. if (target->IsIPOEnabled(lang, config)) {
  1492. this->AppendFeatureOptions(compileFlags, lang, "IPO");
  1493. }
  1494. this->AddArchitectureFlags(compileFlags, target, lang, config, arch);
  1495. if (lang == "Fortran") {
  1496. this->AppendFlags(compileFlags,
  1497. this->GetTargetFortranFlags(target, config));
  1498. } else if (lang == "Swift") {
  1499. // Only set the compile mode if CMP0157 is set
  1500. if (cm::optional<cmSwiftCompileMode> swiftCompileMode =
  1501. this->GetSwiftCompileMode(target, config)) {
  1502. std::string swiftCompileModeFlag;
  1503. switch (*swiftCompileMode) {
  1504. case cmSwiftCompileMode::Incremental: {
  1505. swiftCompileModeFlag = "-incremental";
  1506. if (cmValue flag =
  1507. mf->GetDefinition("CMAKE_Swift_COMPILE_OPTIONS_INCREMENTAL")) {
  1508. swiftCompileModeFlag = *flag;
  1509. }
  1510. break;
  1511. }
  1512. case cmSwiftCompileMode::Wholemodule: {
  1513. swiftCompileModeFlag = "-wmo";
  1514. if (cmValue flag =
  1515. mf->GetDefinition("CMAKE_Swift_COMPILE_OPTIONS_WMO")) {
  1516. swiftCompileModeFlag = *flag;
  1517. }
  1518. break;
  1519. }
  1520. case cmSwiftCompileMode::Singlefile:
  1521. break;
  1522. case cmSwiftCompileMode::Unknown: {
  1523. this->IssueMessage(
  1524. MessageType::AUTHOR_WARNING,
  1525. cmStrCat("Unknown Swift_COMPILATION_MODE on target '",
  1526. target->GetName(), "'"));
  1527. }
  1528. }
  1529. this->AppendFlags(compileFlags, swiftCompileModeFlag);
  1530. }
  1531. }
  1532. this->AddCMP0018Flags(compileFlags, target, lang, config);
  1533. this->AddVisibilityPresetFlags(compileFlags, target, lang);
  1534. this->AddColorDiagnosticsFlags(compileFlags, lang);
  1535. this->AppendFlags(compileFlags, mf->GetDefineFlags());
  1536. this->AppendFlags(compileFlags,
  1537. this->GetFrameworkFlags(lang, config, target));
  1538. this->AppendFlags(compileFlags,
  1539. this->GetXcFrameworkFlags(lang, config, target));
  1540. if (!compileFlags.empty()) {
  1541. flags.emplace_back(std::move(compileFlags));
  1542. }
  1543. this->AddCompileOptions(flags, target, lang, config);
  1544. return flags;
  1545. }
  1546. std::string cmLocalGenerator::GetFrameworkFlags(std::string const& lang,
  1547. std::string const& config,
  1548. cmGeneratorTarget* target)
  1549. {
  1550. cmLocalGenerator* lg = target->GetLocalGenerator();
  1551. cmMakefile* mf = lg->GetMakefile();
  1552. if (!target->IsApple()) {
  1553. return std::string();
  1554. }
  1555. cmValue fwSearchFlag =
  1556. mf->GetDefinition(cmStrCat("CMAKE_", lang, "_FRAMEWORK_SEARCH_FLAG"));
  1557. cmValue sysFwSearchFlag = mf->GetDefinition(
  1558. cmStrCat("CMAKE_", lang, "_SYSTEM_FRAMEWORK_SEARCH_FLAG"));
  1559. if (!fwSearchFlag && !sysFwSearchFlag) {
  1560. return std::string{};
  1561. }
  1562. std::set<std::string> emitted;
  1563. #ifdef __APPLE__ /* don't insert this when crosscompiling e.g. to iphone */
  1564. emitted.insert("/System/Library/Frameworks");
  1565. #endif
  1566. std::vector<std::string> includes;
  1567. lg->GetIncludeDirectories(includes, target, "C", config);
  1568. // check all include directories for frameworks as this
  1569. // will already have added a -F for the framework
  1570. for (std::string const& include : includes) {
  1571. if (lg->GetGlobalGenerator()->NameResolvesToFramework(include)) {
  1572. std::string frameworkDir = cmStrCat(include, "/../");
  1573. frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
  1574. emitted.insert(frameworkDir);
  1575. }
  1576. }
  1577. std::string flags;
  1578. if (cmComputeLinkInformation* cli = target->GetLinkInformation(config)) {
  1579. std::vector<std::string> const& frameworks = cli->GetFrameworkPaths();
  1580. for (std::string const& framework : frameworks) {
  1581. if (emitted.insert(framework).second) {
  1582. if (sysFwSearchFlag &&
  1583. target->IsSystemIncludeDirectory(framework, config, lang)) {
  1584. flags += *sysFwSearchFlag;
  1585. } else {
  1586. flags += *fwSearchFlag;
  1587. }
  1588. flags +=
  1589. lg->ConvertToOutputFormat(framework, cmOutputConverter::SHELL);
  1590. flags += " ";
  1591. }
  1592. }
  1593. }
  1594. return flags;
  1595. }
  1596. std::string cmLocalGenerator::GetXcFrameworkFlags(std::string const& lang,
  1597. std::string const& config,
  1598. cmGeneratorTarget* target)
  1599. {
  1600. cmLocalGenerator* lg = target->GetLocalGenerator();
  1601. cmMakefile* mf = lg->GetMakefile();
  1602. if (!target->IsApple()) {
  1603. return std::string();
  1604. }
  1605. cmValue includeSearchFlag =
  1606. mf->GetDefinition(cmStrCat("CMAKE_INCLUDE_FLAG_", lang));
  1607. cmValue sysIncludeSearchFlag =
  1608. mf->GetDefinition(cmStrCat("CMAKE_INCLUDE_SYSTEM_FLAG_", lang));
  1609. if (!includeSearchFlag && !sysIncludeSearchFlag) {
  1610. return std::string{};
  1611. }
  1612. std::string flags;
  1613. if (cmComputeLinkInformation* cli = target->GetLinkInformation(config)) {
  1614. std::vector<std::string> const& paths = cli->GetXcFrameworkHeaderPaths();
  1615. for (std::string const& path : paths) {
  1616. if (sysIncludeSearchFlag &&
  1617. target->IsSystemIncludeDirectory(path, config, lang)) {
  1618. flags += *sysIncludeSearchFlag;
  1619. } else {
  1620. flags += *includeSearchFlag;
  1621. }
  1622. flags += lg->ConvertToOutputFormat(path, cmOutputConverter::SHELL);
  1623. flags += " ";
  1624. }
  1625. }
  1626. return flags;
  1627. }
  1628. void cmLocalGenerator::GetTargetDefines(cmGeneratorTarget const* target,
  1629. std::string const& config,
  1630. std::string const& lang,
  1631. std::set<std::string>& defines) const
  1632. {
  1633. std::set<BT<std::string>> tmp = this->GetTargetDefines(target, config, lang);
  1634. for (BT<std::string> const& v : tmp) {
  1635. defines.emplace(v.Value);
  1636. }
  1637. }
  1638. std::set<BT<std::string>> cmLocalGenerator::GetTargetDefines(
  1639. cmGeneratorTarget const* target, std::string const& config,
  1640. std::string const& lang) const
  1641. {
  1642. std::set<BT<std::string>> defines;
  1643. // Add the export symbol definition for shared library objects.
  1644. if (const std::string* exportMacro = target->GetExportMacro()) {
  1645. this->AppendDefines(defines, *exportMacro);
  1646. }
  1647. // Add preprocessor definitions for this target and configuration.
  1648. std::vector<BT<std::string>> targetDefines =
  1649. target->GetCompileDefinitions(config, lang);
  1650. this->AppendDefines(defines, targetDefines);
  1651. return defines;
  1652. }
  1653. std::string cmLocalGenerator::GetTargetFortranFlags(
  1654. cmGeneratorTarget const* /*unused*/, std::string const& /*unused*/)
  1655. {
  1656. // Implemented by specific generators that override this.
  1657. return std::string();
  1658. }
  1659. /**
  1660. * Output the linking rules on a command line. For executables,
  1661. * targetLibrary should be a NULL pointer. For libraries, it should point
  1662. * to the name of the library. This will not link a library against itself.
  1663. */
  1664. void cmLocalGenerator::OutputLinkLibraries(
  1665. cmComputeLinkInformation* pcli, cmLinkLineComputer* linkLineComputer,
  1666. std::string& linkLibraries, std::string& frameworkPath,
  1667. std::string& linkPath)
  1668. {
  1669. std::vector<BT<std::string>> linkLibrariesList;
  1670. std::vector<BT<std::string>> linkPathList;
  1671. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibrariesList,
  1672. frameworkPath, linkPathList);
  1673. pcli->AppendValues(linkLibraries, linkLibrariesList);
  1674. pcli->AppendValues(linkPath, linkPathList);
  1675. }
  1676. void cmLocalGenerator::OutputLinkLibraries(
  1677. cmComputeLinkInformation* pcli, cmLinkLineComputer* linkLineComputer,
  1678. std::vector<BT<std::string>>& linkLibraries, std::string& frameworkPath,
  1679. std::vector<BT<std::string>>& linkPath)
  1680. {
  1681. cmComputeLinkInformation& cli = *pcli;
  1682. std::string linkLanguage = cli.GetLinkLanguage();
  1683. std::string libPathFlag;
  1684. if (cmValue value = this->Makefile->GetDefinition(
  1685. "CMAKE_" + cli.GetLinkLanguage() + "_LIBRARY_PATH_FLAG")) {
  1686. libPathFlag = *value;
  1687. } else {
  1688. libPathFlag =
  1689. this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_FLAG");
  1690. }
  1691. std::string libPathTerminator;
  1692. if (cmValue value = this->Makefile->GetDefinition(
  1693. "CMAKE_" + cli.GetLinkLanguage() + "_LIBRARY_PATH_TERMINATOR")) {
  1694. libPathTerminator = *value;
  1695. } else {
  1696. libPathTerminator =
  1697. this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_TERMINATOR");
  1698. }
  1699. // Add standard link directories for this language
  1700. std::string stdLinkDirString = this->Makefile->GetSafeDefinition(
  1701. cmStrCat("CMAKE_", cli.GetLinkLanguage(), "_STANDARD_LINK_DIRECTORIES"));
  1702. // Add standard libraries for this language.
  1703. std::string stdLibString = this->Makefile->GetSafeDefinition(
  1704. cmStrCat("CMAKE_", cli.GetLinkLanguage(), "_STANDARD_LIBRARIES"));
  1705. // Append the framework search path flags.
  1706. cmValue fwSearchFlag = this->Makefile->GetDefinition(
  1707. cmStrCat("CMAKE_", linkLanguage, "_FRAMEWORK_SEARCH_FLAG"));
  1708. frameworkPath = linkLineComputer->ComputeFrameworkPath(cli, fwSearchFlag);
  1709. linkLineComputer->ComputeLinkPath(cli, libPathFlag, libPathTerminator,
  1710. stdLinkDirString, linkPath);
  1711. linkLineComputer->ComputeLinkLibraries(cli, stdLibString, linkLibraries);
  1712. }
  1713. std::string cmLocalGenerator::GetLinkLibsCMP0065(
  1714. std::string const& linkLanguage, cmGeneratorTarget& tgt) const
  1715. {
  1716. std::string linkFlags;
  1717. // Flags to link an executable to shared libraries.
  1718. if (tgt.GetType() == cmStateEnums::EXECUTABLE &&
  1719. this->StateSnapshot.GetState()->GetGlobalPropertyAsBool(
  1720. "TARGET_SUPPORTS_SHARED_LIBS")) {
  1721. bool add_shlib_flags = false;
  1722. switch (tgt.GetPolicyStatusCMP0065()) {
  1723. case cmPolicies::WARN:
  1724. if (!tgt.GetPropertyAsBool("ENABLE_EXPORTS") &&
  1725. this->Makefile->PolicyOptionalWarningEnabled(
  1726. "CMAKE_POLICY_WARNING_CMP0065")) {
  1727. std::ostringstream w;
  1728. /* clang-format off */
  1729. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0065) << "\n"
  1730. "For compatibility with older versions of CMake, "
  1731. "additional flags may be added to export symbols on all "
  1732. "executables regardless of their ENABLE_EXPORTS property.";
  1733. /* clang-format on */
  1734. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  1735. }
  1736. CM_FALLTHROUGH;
  1737. case cmPolicies::OLD:
  1738. // OLD behavior is to always add the flags, except on AIX where
  1739. // we compute symbol exports if ENABLE_EXPORTS is on.
  1740. add_shlib_flags =
  1741. !(tgt.IsAIX() && tgt.GetPropertyAsBool("ENABLE_EXPORTS"));
  1742. break;
  1743. case cmPolicies::REQUIRED_IF_USED:
  1744. case cmPolicies::REQUIRED_ALWAYS:
  1745. this->IssueMessage(
  1746. MessageType::FATAL_ERROR,
  1747. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0065));
  1748. CM_FALLTHROUGH;
  1749. case cmPolicies::NEW:
  1750. // NEW behavior is to only add the flags if ENABLE_EXPORTS is on,
  1751. // except on AIX where we compute symbol exports.
  1752. add_shlib_flags =
  1753. !tgt.IsAIX() && tgt.GetPropertyAsBool("ENABLE_EXPORTS");
  1754. break;
  1755. }
  1756. if (add_shlib_flags) {
  1757. linkFlags = this->Makefile->GetSafeDefinition(
  1758. cmStrCat("CMAKE_SHARED_LIBRARY_LINK_", linkLanguage, "_FLAGS"));
  1759. }
  1760. }
  1761. return linkFlags;
  1762. }
  1763. bool cmLocalGenerator::AllAppleArchSysrootsAreTheSame(
  1764. const std::vector<std::string>& archs, cmValue sysroot)
  1765. {
  1766. if (!sysroot) {
  1767. return false;
  1768. }
  1769. return std::all_of(archs.begin(), archs.end(),
  1770. [this, sysroot](std::string const& arch) -> bool {
  1771. std::string const& archSysroot =
  1772. this->AppleArchSysroots[arch];
  1773. return cmIsOff(archSysroot) || *sysroot == archSysroot;
  1774. });
  1775. }
  1776. void cmLocalGenerator::AddArchitectureFlags(std::string& flags,
  1777. cmGeneratorTarget const* target,
  1778. const std::string& lang,
  1779. const std::string& config,
  1780. const std::string& filterArch)
  1781. {
  1782. // Only add Apple specific flags on Apple platforms
  1783. if (target->IsApple() && this->EmitUniversalBinaryFlags) {
  1784. std::vector<std::string> archs = target->GetAppleArchs(config, lang);
  1785. if (!archs.empty() &&
  1786. (lang == "C" || lang == "CXX" || lang == "OBJC" || lang == "OBJCXX" ||
  1787. lang == "ASM")) {
  1788. for (std::string const& arch : archs) {
  1789. if (filterArch.empty() || filterArch == arch) {
  1790. flags += " -arch ";
  1791. flags += arch;
  1792. }
  1793. }
  1794. }
  1795. cmValue sysroot = this->Makefile->GetDefinition("CMAKE_OSX_SYSROOT");
  1796. if (sysroot && *sysroot == "/") {
  1797. sysroot = nullptr;
  1798. }
  1799. std::string sysrootFlagVar = "CMAKE_" + lang + "_SYSROOT_FLAG";
  1800. cmValue sysrootFlag = this->Makefile->GetDefinition(sysrootFlagVar);
  1801. if (cmNonempty(sysrootFlag)) {
  1802. if (!this->AppleArchSysroots.empty() &&
  1803. !this->AllAppleArchSysrootsAreTheSame(archs, sysroot)) {
  1804. for (std::string const& arch : archs) {
  1805. std::string const& archSysroot = this->AppleArchSysroots[arch];
  1806. if (cmIsOff(archSysroot)) {
  1807. continue;
  1808. }
  1809. if (filterArch.empty() || filterArch == arch) {
  1810. flags += " -Xarch_" + arch + " ";
  1811. // Combine sysroot flag and path to work with -Xarch
  1812. std::string arch_sysroot = *sysrootFlag + archSysroot;
  1813. flags += this->ConvertToOutputFormat(arch_sysroot, SHELL);
  1814. }
  1815. }
  1816. } else if (cmNonempty(sysroot)) {
  1817. flags += " ";
  1818. flags += *sysrootFlag;
  1819. flags += " ";
  1820. flags += this->ConvertToOutputFormat(*sysroot, SHELL);
  1821. }
  1822. }
  1823. cmValue deploymentTarget =
  1824. this->Makefile->GetDefinition("CMAKE_OSX_DEPLOYMENT_TARGET");
  1825. if (cmNonempty(deploymentTarget)) {
  1826. std::string deploymentTargetFlagVar =
  1827. "CMAKE_" + lang + "_OSX_DEPLOYMENT_TARGET_FLAG";
  1828. cmValue deploymentTargetFlag =
  1829. this->Makefile->GetDefinition(deploymentTargetFlagVar);
  1830. if (cmNonempty(deploymentTargetFlag) &&
  1831. // CMAKE_<LANG>_COMPILER_TARGET overrides a --target= for
  1832. // CMAKE_OSX_DEPLOYMENT_TARGET, e.g., for visionOS.
  1833. (!cmHasLiteralPrefix(*deploymentTarget, "--target=") ||
  1834. this->Makefile
  1835. ->GetDefinition(cmStrCat("CMAKE_", lang, "_COMPILER_TARGET"))
  1836. .IsEmpty())) {
  1837. std::string flag = *deploymentTargetFlag;
  1838. // Add the deployment target architecture to the flag, if needed.
  1839. static const std::string kARCH = "<ARCH>";
  1840. std::string::size_type archPos = flag.find(kARCH);
  1841. if (archPos != std::string::npos) {
  1842. // This placeholder is meant for visionOS, so default to arm64
  1843. // unless only non-arm64 archs are given.
  1844. std::string const arch =
  1845. (archs.empty() || cm::contains(archs, "arm64")) ? "arm64"
  1846. : archs[0];
  1847. // Replace the placeholder with its value.
  1848. flag = cmStrCat(flag.substr(0, archPos), arch,
  1849. flag.substr(archPos + kARCH.size()));
  1850. }
  1851. // Add the deployment target version to the flag.
  1852. static const std::string kVERSION_MIN = "<VERSION_MIN>";
  1853. std::string::size_type verPos = flag.find(kVERSION_MIN);
  1854. if (verPos != std::string::npos) {
  1855. // Replace the placeholder with its value.
  1856. flag = cmStrCat(flag.substr(0, verPos), *deploymentTarget,
  1857. flag.substr(verPos + kVERSION_MIN.size()));
  1858. } else {
  1859. // There is no placeholder, so append the value.
  1860. flag = cmStrCat(flag, *deploymentTarget);
  1861. }
  1862. flags += " ";
  1863. flags += flag;
  1864. }
  1865. }
  1866. }
  1867. }
  1868. void cmLocalGenerator::AddLanguageFlags(std::string& flags,
  1869. cmGeneratorTarget const* target,
  1870. cmBuildStep compileOrLink,
  1871. const std::string& lang,
  1872. const std::string& config)
  1873. {
  1874. // Add language-specific flags.
  1875. this->AddConfigVariableFlags(flags, cmStrCat("CMAKE_", lang, "_FLAGS"),
  1876. config);
  1877. // Add the language standard flag for compiling, and sometimes linking.
  1878. if (compileOrLink == cmBuildStep::Compile ||
  1879. (compileOrLink == cmBuildStep::Link &&
  1880. // Some toolchains require use of the language standard flag
  1881. // when linking in order to use the matching standard library.
  1882. // FIXME: If CMake gains an abstraction for standard library
  1883. // selection, this will have to be reconciled with it.
  1884. this->Makefile->IsOn(
  1885. cmStrCat("CMAKE_", lang, "_LINK_WITH_STANDARD_COMPILE_OPTION")))) {
  1886. cmStandardLevelResolver standardResolver(this->Makefile);
  1887. std::string const& optionFlagDef =
  1888. standardResolver.GetCompileOptionDef(target, lang, config);
  1889. if (!optionFlagDef.empty()) {
  1890. cmValue opt =
  1891. target->Target->GetMakefile()->GetDefinition(optionFlagDef);
  1892. if (opt) {
  1893. cmList optList{ *opt };
  1894. for (std::string const& i : optList) {
  1895. this->AppendFlagEscape(flags, i);
  1896. }
  1897. }
  1898. }
  1899. }
  1900. std::string compiler = this->Makefile->GetSafeDefinition(
  1901. cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
  1902. std::string compilerSimulateId = this->Makefile->GetSafeDefinition(
  1903. cmStrCat("CMAKE_", lang, "_SIMULATE_ID"));
  1904. if (lang == "Swift") {
  1905. if (cmValue v = target->GetProperty("Swift_LANGUAGE_VERSION")) {
  1906. if (cmSystemTools::VersionCompare(
  1907. cmSystemTools::OP_GREATER_EQUAL,
  1908. this->Makefile->GetDefinition("CMAKE_Swift_COMPILER_VERSION"),
  1909. "4.2")) {
  1910. this->AppendFlags(flags, "-swift-version " + *v);
  1911. }
  1912. }
  1913. } else if (lang == "CUDA") {
  1914. target->AddCUDAArchitectureFlags(compileOrLink, config, flags);
  1915. target->AddCUDAToolkitFlags(flags);
  1916. } else if (lang == "ISPC") {
  1917. target->AddISPCTargetFlags(flags);
  1918. } else if (lang == "RC" &&
  1919. this->Makefile->GetSafeDefinition("CMAKE_RC_COMPILER")
  1920. .find("llvm-rc") != std::string::npos) {
  1921. compiler = this->Makefile->GetSafeDefinition("CMAKE_C_COMPILER_ID");
  1922. if (!compiler.empty()) {
  1923. compilerSimulateId =
  1924. this->Makefile->GetSafeDefinition("CMAKE_C_SIMULATE_ID");
  1925. } else {
  1926. compiler = this->Makefile->GetSafeDefinition("CMAKE_CXX_COMPILER_ID");
  1927. compilerSimulateId =
  1928. this->Makefile->GetSafeDefinition("CMAKE_CXX_SIMULATE_ID");
  1929. }
  1930. } else if (lang == "HIP") {
  1931. target->AddHIPArchitectureFlags(compileOrLink, config, flags);
  1932. }
  1933. // Add VFS Overlay for Clang compilers
  1934. if (compiler == "Clang") {
  1935. if (cmValue vfsOverlay =
  1936. this->Makefile->GetDefinition("CMAKE_CLANG_VFS_OVERLAY")) {
  1937. if (compilerSimulateId == "MSVC") {
  1938. this->AppendCompileOptions(
  1939. flags,
  1940. std::vector<std::string>{ "-Xclang", "-ivfsoverlay", "-Xclang",
  1941. *vfsOverlay });
  1942. } else {
  1943. this->AppendCompileOptions(
  1944. flags, std::vector<std::string>{ "-ivfsoverlay", *vfsOverlay });
  1945. }
  1946. }
  1947. }
  1948. // Add MSVC runtime library flags. This is activated by the presence
  1949. // of a default selection whether or not it is overridden by a property.
  1950. cmValue msvcRuntimeLibraryDefault =
  1951. this->Makefile->GetDefinition("CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT");
  1952. if (cmNonempty(msvcRuntimeLibraryDefault)) {
  1953. cmValue msvcRuntimeLibraryValue =
  1954. target->GetProperty("MSVC_RUNTIME_LIBRARY");
  1955. if (!msvcRuntimeLibraryValue) {
  1956. msvcRuntimeLibraryValue = msvcRuntimeLibraryDefault;
  1957. }
  1958. std::string const msvcRuntimeLibrary = cmGeneratorExpression::Evaluate(
  1959. *msvcRuntimeLibraryValue, this, config, target);
  1960. if (!msvcRuntimeLibrary.empty()) {
  1961. if (cmValue msvcRuntimeLibraryOptions = this->Makefile->GetDefinition(
  1962. "CMAKE_" + lang + "_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_" +
  1963. msvcRuntimeLibrary)) {
  1964. this->AppendCompileOptions(flags, *msvcRuntimeLibraryOptions);
  1965. } else if ((this->Makefile->GetSafeDefinition(
  1966. "CMAKE_" + lang + "_COMPILER_ID") == "MSVC" ||
  1967. this->Makefile->GetSafeDefinition(
  1968. "CMAKE_" + lang + "_SIMULATE_ID") == "MSVC") &&
  1969. !cmSystemTools::GetErrorOccurredFlag()) {
  1970. // The compiler uses the MSVC ABI so it needs a known runtime library.
  1971. this->IssueMessage(MessageType::FATAL_ERROR,
  1972. "MSVC_RUNTIME_LIBRARY value '" +
  1973. msvcRuntimeLibrary + "' not known for this " +
  1974. lang + " compiler.");
  1975. }
  1976. }
  1977. }
  1978. // Add Watcom runtime library flags. This is activated by the presence
  1979. // of a default selection whether or not it is overridden by a property.
  1980. cmValue watcomRuntimeLibraryDefault =
  1981. this->Makefile->GetDefinition("CMAKE_WATCOM_RUNTIME_LIBRARY_DEFAULT");
  1982. if (cmNonempty(watcomRuntimeLibraryDefault)) {
  1983. cmValue watcomRuntimeLibraryValue =
  1984. target->GetProperty("WATCOM_RUNTIME_LIBRARY");
  1985. if (!watcomRuntimeLibraryValue) {
  1986. watcomRuntimeLibraryValue = watcomRuntimeLibraryDefault;
  1987. }
  1988. std::string const watcomRuntimeLibrary = cmGeneratorExpression::Evaluate(
  1989. *watcomRuntimeLibraryValue, this, config, target);
  1990. if (!watcomRuntimeLibrary.empty()) {
  1991. if (cmValue watcomRuntimeLibraryOptions = this->Makefile->GetDefinition(
  1992. "CMAKE_" + lang + "_COMPILE_OPTIONS_WATCOM_RUNTIME_LIBRARY_" +
  1993. watcomRuntimeLibrary)) {
  1994. this->AppendCompileOptions(flags, *watcomRuntimeLibraryOptions);
  1995. } else if ((this->Makefile->GetSafeDefinition(
  1996. "CMAKE_" + lang + "_COMPILER_ID") == "OpenWatcom" ||
  1997. this->Makefile->GetSafeDefinition(
  1998. "CMAKE_" + lang + "_SIMULATE_ID") == "OpenWatcom") &&
  1999. !cmSystemTools::GetErrorOccurredFlag()) {
  2000. // The compiler uses the Watcom ABI so it needs a known runtime
  2001. // library.
  2002. this->IssueMessage(MessageType::FATAL_ERROR,
  2003. "WATCOM_RUNTIME_LIBRARY value '" +
  2004. watcomRuntimeLibrary + "' not known for this " +
  2005. lang + " compiler.");
  2006. }
  2007. }
  2008. }
  2009. // Add MSVC debug information format flags if CMP0141 is NEW.
  2010. if (cm::optional<std::string> msvcDebugInformationFormat =
  2011. this->GetMSVCDebugFormatName(config, target)) {
  2012. if (!msvcDebugInformationFormat->empty()) {
  2013. if (cmValue msvcDebugInformationFormatOptions =
  2014. this->Makefile->GetDefinition(
  2015. cmStrCat("CMAKE_", lang,
  2016. "_COMPILE_OPTIONS_MSVC_DEBUG_INFORMATION_FORMAT_",
  2017. *msvcDebugInformationFormat))) {
  2018. this->AppendCompileOptions(flags, *msvcDebugInformationFormatOptions);
  2019. } else if ((this->Makefile->GetSafeDefinition(
  2020. cmStrCat("CMAKE_", lang, "_COMPILER_ID")) == "MSVC"_s ||
  2021. this->Makefile->GetSafeDefinition(
  2022. cmStrCat("CMAKE_", lang, "_SIMULATE_ID")) == "MSVC"_s) &&
  2023. !cmSystemTools::GetErrorOccurredFlag()) {
  2024. // The compiler uses the MSVC ABI so it needs a known runtime library.
  2025. this->IssueMessage(MessageType::FATAL_ERROR,
  2026. cmStrCat("MSVC_DEBUG_INFORMATION_FORMAT value '",
  2027. *msvcDebugInformationFormat,
  2028. "' not known for this ", lang,
  2029. " compiler."));
  2030. }
  2031. }
  2032. }
  2033. }
  2034. void cmLocalGenerator::AddLanguageFlagsForLinking(
  2035. std::string& flags, cmGeneratorTarget const* target, const std::string& lang,
  2036. const std::string& config)
  2037. {
  2038. this->AddLanguageFlags(flags, target, cmBuildStep::Link, lang, config);
  2039. if (target->IsIPOEnabled(lang, config)) {
  2040. this->AppendFeatureOptions(flags, lang, "IPO");
  2041. }
  2042. }
  2043. cmGeneratorTarget* cmLocalGenerator::FindGeneratorTargetToUse(
  2044. const std::string& name) const
  2045. {
  2046. auto imported = this->ImportedGeneratorTargets.find(name);
  2047. if (imported != this->ImportedGeneratorTargets.end()) {
  2048. return imported->second;
  2049. }
  2050. // find local alias to imported target
  2051. auto aliased = this->AliasTargets.find(name);
  2052. if (aliased != this->AliasTargets.end()) {
  2053. imported = this->ImportedGeneratorTargets.find(aliased->second);
  2054. if (imported != this->ImportedGeneratorTargets.end()) {
  2055. return imported->second;
  2056. }
  2057. }
  2058. if (cmGeneratorTarget* t = this->FindLocalNonAliasGeneratorTarget(name)) {
  2059. return t;
  2060. }
  2061. return this->GetGlobalGenerator()->FindGeneratorTarget(name);
  2062. }
  2063. bool cmLocalGenerator::GetRealDependency(const std::string& inName,
  2064. const std::string& config,
  2065. std::string& dep)
  2066. {
  2067. // Older CMake code may specify the dependency using the target
  2068. // output file rather than the target name. Such code would have
  2069. // been written before there was support for target properties that
  2070. // modify the name so stripping down to just the file name should
  2071. // produce the target name in this case.
  2072. std::string name = cmSystemTools::GetFilenameName(inName);
  2073. // If the input name is the empty string, there is no real
  2074. // dependency. Short-circuit the other checks:
  2075. if (name.empty()) {
  2076. return false;
  2077. }
  2078. if (cmSystemTools::GetFilenameLastExtension(name) == ".exe") {
  2079. name = cmSystemTools::GetFilenameWithoutLastExtension(name);
  2080. }
  2081. // Look for a CMake target with the given name.
  2082. if (cmGeneratorTarget* target = this->FindGeneratorTargetToUse(name)) {
  2083. // make sure it is not just a coincidence that the target name
  2084. // found is part of the inName
  2085. if (cmSystemTools::FileIsFullPath(inName)) {
  2086. std::string tLocation;
  2087. if (target->GetType() >= cmStateEnums::EXECUTABLE &&
  2088. target->GetType() <= cmStateEnums::MODULE_LIBRARY) {
  2089. tLocation = target->GetLocation(config);
  2090. tLocation = cmSystemTools::GetFilenamePath(tLocation);
  2091. tLocation = cmSystemTools::CollapseFullPath(tLocation);
  2092. }
  2093. std::string depLocation =
  2094. cmSystemTools::GetFilenamePath(std::string(inName));
  2095. depLocation = cmSystemTools::CollapseFullPath(depLocation);
  2096. if (depLocation != tLocation) {
  2097. // it is a full path to a depend that has the same name
  2098. // as a target but is in a different location so do not use
  2099. // the target as the depend
  2100. dep = inName;
  2101. return true;
  2102. }
  2103. }
  2104. switch (target->GetType()) {
  2105. case cmStateEnums::EXECUTABLE:
  2106. case cmStateEnums::STATIC_LIBRARY:
  2107. case cmStateEnums::SHARED_LIBRARY:
  2108. case cmStateEnums::MODULE_LIBRARY:
  2109. case cmStateEnums::UNKNOWN_LIBRARY:
  2110. dep = target->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact,
  2111. /*realname=*/true);
  2112. return true;
  2113. case cmStateEnums::OBJECT_LIBRARY:
  2114. // An object library has no single file on which to depend.
  2115. // This was listed to get the target-level dependency.
  2116. case cmStateEnums::INTERFACE_LIBRARY:
  2117. // An interface library has no file on which to depend.
  2118. // This was listed to get the target-level dependency.
  2119. case cmStateEnums::UTILITY:
  2120. case cmStateEnums::GLOBAL_TARGET:
  2121. // A utility target has no file on which to depend. This was listed
  2122. // only to get the target-level dependency.
  2123. return false;
  2124. }
  2125. }
  2126. // The name was not that of a CMake target. It must name a file.
  2127. if (cmSystemTools::FileIsFullPath(inName)) {
  2128. // This is a full path. Return it as given.
  2129. dep = inName;
  2130. return true;
  2131. }
  2132. // Check for a source file in this directory that matches the
  2133. // dependency.
  2134. if (cmSourceFile* sf = this->Makefile->GetSource(inName)) {
  2135. dep = sf->ResolveFullPath();
  2136. return true;
  2137. }
  2138. // Treat the name as relative to the source directory in which it
  2139. // was given.
  2140. dep = cmStrCat(this->GetCurrentSourceDirectory(), '/', inName);
  2141. // If the in-source path does not exist, assume it instead lives in the
  2142. // binary directory.
  2143. if (!cmSystemTools::FileExists(dep)) {
  2144. dep = cmStrCat(this->GetCurrentBinaryDirectory(), '/', inName);
  2145. }
  2146. dep = cmSystemTools::CollapseFullPath(dep, this->GetBinaryDirectory());
  2147. return true;
  2148. }
  2149. void cmLocalGenerator::AddSharedFlags(std::string& flags,
  2150. const std::string& lang, bool shared)
  2151. {
  2152. std::string flagsVar;
  2153. // Add flags for dealing with shared libraries for this language.
  2154. if (shared) {
  2155. this->AppendFlags(flags,
  2156. this->Makefile->GetSafeDefinition(
  2157. cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS")));
  2158. }
  2159. }
  2160. static void AddVisibilityCompileOption(std::string& flags,
  2161. cmGeneratorTarget const* target,
  2162. cmLocalGenerator* lg,
  2163. const std::string& lang,
  2164. std::string* warnCMP0063)
  2165. {
  2166. std::string compileOption = "CMAKE_" + lang + "_COMPILE_OPTIONS_VISIBILITY";
  2167. cmValue opt = lg->GetMakefile()->GetDefinition(compileOption);
  2168. if (!opt) {
  2169. return;
  2170. }
  2171. std::string flagDefine = lang + "_VISIBILITY_PRESET";
  2172. cmValue prop = target->GetProperty(flagDefine);
  2173. if (!prop) {
  2174. return;
  2175. }
  2176. if (warnCMP0063) {
  2177. *warnCMP0063 += " " + flagDefine + "\n";
  2178. return;
  2179. }
  2180. if ((*prop != "hidden") && (*prop != "default") && (*prop != "protected") &&
  2181. (*prop != "internal")) {
  2182. std::ostringstream e;
  2183. e << "Target " << target->GetName() << " uses unsupported value \""
  2184. << *prop << "\" for " << flagDefine << "."
  2185. << " The supported values are: default, hidden, protected, and "
  2186. "internal.";
  2187. cmSystemTools::Error(e.str());
  2188. return;
  2189. }
  2190. std::string option = *opt + *prop;
  2191. lg->AppendFlags(flags, option);
  2192. }
  2193. static void AddInlineVisibilityCompileOption(std::string& flags,
  2194. cmGeneratorTarget const* target,
  2195. cmLocalGenerator* lg,
  2196. std::string* warnCMP0063,
  2197. const std::string& lang)
  2198. {
  2199. std::string compileOption =
  2200. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_VISIBILITY_INLINES_HIDDEN");
  2201. cmValue opt = lg->GetMakefile()->GetDefinition(compileOption);
  2202. if (!opt) {
  2203. return;
  2204. }
  2205. bool prop = target->GetPropertyAsBool("VISIBILITY_INLINES_HIDDEN");
  2206. if (!prop) {
  2207. return;
  2208. }
  2209. if (warnCMP0063) {
  2210. *warnCMP0063 += " VISIBILITY_INLINES_HIDDEN\n";
  2211. return;
  2212. }
  2213. lg->AppendFlags(flags, *opt);
  2214. }
  2215. void cmLocalGenerator::AddVisibilityPresetFlags(
  2216. std::string& flags, cmGeneratorTarget const* target, const std::string& lang)
  2217. {
  2218. if (lang.empty()) {
  2219. return;
  2220. }
  2221. std::string warnCMP0063;
  2222. std::string* pWarnCMP0063 = nullptr;
  2223. if (target->GetType() != cmStateEnums::SHARED_LIBRARY &&
  2224. target->GetType() != cmStateEnums::MODULE_LIBRARY &&
  2225. !target->IsExecutableWithExports()) {
  2226. switch (target->GetPolicyStatusCMP0063()) {
  2227. case cmPolicies::OLD:
  2228. return;
  2229. case cmPolicies::WARN:
  2230. pWarnCMP0063 = &warnCMP0063;
  2231. break;
  2232. default:
  2233. break;
  2234. }
  2235. }
  2236. AddVisibilityCompileOption(flags, target, this, lang, pWarnCMP0063);
  2237. if (lang == "CXX" || lang == "OBJCXX") {
  2238. AddInlineVisibilityCompileOption(flags, target, this, pWarnCMP0063, lang);
  2239. }
  2240. if (!warnCMP0063.empty() && this->WarnCMP0063.insert(target).second) {
  2241. std::ostringstream w;
  2242. /* clang-format off */
  2243. w <<
  2244. cmPolicies::GetPolicyWarning(cmPolicies::CMP0063) << "\n"
  2245. "Target \"" << target->GetName() << "\" of "
  2246. "type \"" << cmState::GetTargetTypeName(target->GetType()) << "\" "
  2247. "has the following visibility properties set for " << lang << ":\n" <<
  2248. warnCMP0063 <<
  2249. "For compatibility CMake is not honoring them for this target.";
  2250. /* clang-format on */
  2251. target->GetLocalGenerator()->GetCMakeInstance()->IssueMessage(
  2252. MessageType::AUTHOR_WARNING, w.str(), target->GetBacktrace());
  2253. }
  2254. }
  2255. void cmLocalGenerator::AddCMP0018Flags(std::string& flags,
  2256. cmGeneratorTarget const* target,
  2257. std::string const& lang,
  2258. const std::string& config)
  2259. {
  2260. int targetType = target->GetType();
  2261. bool shared = ((targetType == cmStateEnums::SHARED_LIBRARY) ||
  2262. (targetType == cmStateEnums::MODULE_LIBRARY));
  2263. if (this->GetShouldUseOldFlags(shared, lang)) {
  2264. this->AddSharedFlags(flags, lang, shared);
  2265. } else {
  2266. if (target->GetLinkInterfaceDependentBoolProperty(
  2267. "POSITION_INDEPENDENT_CODE", config)) {
  2268. this->AddPositionIndependentFlags(flags, lang, targetType);
  2269. }
  2270. if (shared) {
  2271. this->AppendFeatureOptions(flags, lang, "DLL");
  2272. }
  2273. }
  2274. }
  2275. bool cmLocalGenerator::GetShouldUseOldFlags(bool shared,
  2276. const std::string& lang) const
  2277. {
  2278. std::string originalFlags =
  2279. this->GlobalGenerator->GetSharedLibFlagsForLanguage(lang);
  2280. if (shared) {
  2281. std::string flagsVar = cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS");
  2282. std::string const& flags = this->Makefile->GetSafeDefinition(flagsVar);
  2283. if (flags != originalFlags) {
  2284. switch (this->GetPolicyStatus(cmPolicies::CMP0018)) {
  2285. case cmPolicies::WARN: {
  2286. std::ostringstream e;
  2287. e << "Variable " << flagsVar
  2288. << " has been modified. CMake "
  2289. "will ignore the POSITION_INDEPENDENT_CODE target property "
  2290. "for "
  2291. "shared libraries and will use the "
  2292. << flagsVar
  2293. << " variable "
  2294. "instead. This may cause errors if the original content of "
  2295. << flagsVar << " was removed.\n"
  2296. << cmPolicies::GetPolicyWarning(cmPolicies::CMP0018);
  2297. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  2298. CM_FALLTHROUGH;
  2299. }
  2300. case cmPolicies::OLD:
  2301. return true;
  2302. case cmPolicies::REQUIRED_IF_USED:
  2303. case cmPolicies::REQUIRED_ALWAYS:
  2304. case cmPolicies::NEW:
  2305. return false;
  2306. }
  2307. }
  2308. }
  2309. return false;
  2310. }
  2311. void cmLocalGenerator::AddPositionIndependentFlags(std::string& flags,
  2312. std::string const& lang,
  2313. int targetType)
  2314. {
  2315. std::string picFlags;
  2316. if (targetType == cmStateEnums::EXECUTABLE) {
  2317. picFlags = this->Makefile->GetSafeDefinition(
  2318. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIE"));
  2319. }
  2320. if (picFlags.empty()) {
  2321. picFlags = this->Makefile->GetSafeDefinition(
  2322. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIC"));
  2323. }
  2324. if (!picFlags.empty()) {
  2325. cmList options{ picFlags };
  2326. for (std::string const& o : options) {
  2327. this->AppendFlagEscape(flags, o);
  2328. }
  2329. }
  2330. }
  2331. void cmLocalGenerator::AddColorDiagnosticsFlags(std::string& flags,
  2332. const std::string& lang)
  2333. {
  2334. cmValue diag = this->Makefile->GetDefinition("CMAKE_COLOR_DIAGNOSTICS");
  2335. if (diag.IsSet()) {
  2336. std::string colorFlagName;
  2337. if (diag.IsOn()) {
  2338. colorFlagName =
  2339. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_COLOR_DIAGNOSTICS");
  2340. } else {
  2341. colorFlagName =
  2342. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_COLOR_DIAGNOSTICS_OFF");
  2343. }
  2344. cmList options{ this->Makefile->GetDefinition(colorFlagName) };
  2345. for (auto const& option : options) {
  2346. this->AppendFlagEscape(flags, option);
  2347. }
  2348. }
  2349. }
  2350. void cmLocalGenerator::AddConfigVariableFlags(std::string& flags,
  2351. const std::string& var,
  2352. const std::string& config)
  2353. {
  2354. // Add the flags from the variable itself.
  2355. this->AppendFlags(flags, this->Makefile->GetSafeDefinition(var));
  2356. // Add the flags from the build-type specific variable.
  2357. if (!config.empty()) {
  2358. const std::string flagsVar =
  2359. cmStrCat(var, '_', cmSystemTools::UpperCase(config));
  2360. this->AppendFlags(flags, this->Makefile->GetSafeDefinition(flagsVar));
  2361. }
  2362. }
  2363. void cmLocalGenerator::AppendFlags(std::string& flags,
  2364. const std::string& newFlags) const
  2365. {
  2366. bool allSpaces = std::all_of(newFlags.begin(), newFlags.end(), cmIsSpace);
  2367. if (!newFlags.empty() && !allSpaces) {
  2368. if (!flags.empty()) {
  2369. flags += " ";
  2370. }
  2371. flags += newFlags;
  2372. }
  2373. }
  2374. void cmLocalGenerator::AppendFlags(
  2375. std::string& flags, const std::vector<BT<std::string>>& newFlags) const
  2376. {
  2377. for (BT<std::string> const& flag : newFlags) {
  2378. this->AppendFlags(flags, flag.Value);
  2379. }
  2380. }
  2381. void cmLocalGenerator::AppendFlagEscape(std::string& flags,
  2382. const std::string& rawFlag) const
  2383. {
  2384. this->AppendFlags(
  2385. flags,
  2386. this->EscapeForShell(rawFlag, false, false, false, this->IsNinjaMulti()));
  2387. }
  2388. void cmLocalGenerator::AddISPCDependencies(cmGeneratorTarget* target)
  2389. {
  2390. std::vector<std::string> enabledLanguages =
  2391. this->GetState()->GetEnabledLanguages();
  2392. if (std::find(enabledLanguages.begin(), enabledLanguages.end(), "ISPC") ==
  2393. enabledLanguages.end()) {
  2394. return;
  2395. }
  2396. cmValue ispcHeaderSuffixProp = target->GetProperty("ISPC_HEADER_SUFFIX");
  2397. assert(ispcHeaderSuffixProp);
  2398. std::vector<std::string> ispcArchSuffixes =
  2399. detail::ComputeISPCObjectSuffixes(target);
  2400. const bool extra_objects = (ispcArchSuffixes.size() > 1);
  2401. std::vector<std::string> configsList =
  2402. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  2403. for (std::string const& config : configsList) {
  2404. std::string rootObjectDir = target->GetObjectDirectory(config);
  2405. std::string headerDir = rootObjectDir;
  2406. if (cmValue prop = target->GetProperty("ISPC_HEADER_DIRECTORY")) {
  2407. headerDir = cmSystemTools::CollapseFullPath(
  2408. cmStrCat(this->GetBinaryDirectory(), '/', *prop));
  2409. }
  2410. std::vector<cmSourceFile*> sources;
  2411. target->GetSourceFiles(sources, config);
  2412. // build up the list of ispc headers and extra objects that this target is
  2413. // generating
  2414. for (cmSourceFile const* sf : sources) {
  2415. // Generate this object file's rule file.
  2416. const std::string& lang = sf->GetLanguage();
  2417. if (lang == "ISPC") {
  2418. std::string const& objectName = target->GetObjectName(sf);
  2419. // Drop both ".obj" and the source file extension
  2420. std::string ispcSource =
  2421. cmSystemTools::GetFilenameWithoutLastExtension(objectName);
  2422. ispcSource =
  2423. cmSystemTools::GetFilenameWithoutLastExtension(ispcSource);
  2424. auto headerPath =
  2425. cmStrCat(headerDir, '/', ispcSource, *ispcHeaderSuffixProp);
  2426. target->AddISPCGeneratedHeader(headerPath, config);
  2427. if (extra_objects) {
  2428. std::vector<std::string> objs = detail::ComputeISPCExtraObjects(
  2429. objectName, rootObjectDir, ispcArchSuffixes);
  2430. target->AddISPCGeneratedObject(std::move(objs), config);
  2431. }
  2432. }
  2433. }
  2434. }
  2435. }
  2436. void cmLocalGenerator::AddPchDependencies(cmGeneratorTarget* target)
  2437. {
  2438. std::vector<std::string> configsList =
  2439. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  2440. for (std::string const& config : configsList) {
  2441. // FIXME: Refactor collection of sources to not evaluate object
  2442. // libraries.
  2443. std::vector<cmSourceFile*> sources;
  2444. target->GetSourceFiles(sources, config);
  2445. const std::string configUpper = cmSystemTools::UpperCase(config);
  2446. static const std::array<std::string, 4> langs = { { "C", "CXX", "OBJC",
  2447. "OBJCXX" } };
  2448. std::set<std::string> pchLangSet;
  2449. if (this->GetGlobalGenerator()->IsXcode()) {
  2450. for (const std::string& lang : langs) {
  2451. const std::string pchHeader = target->GetPchHeader(config, lang, "");
  2452. if (!pchHeader.empty()) {
  2453. pchLangSet.emplace(lang);
  2454. }
  2455. }
  2456. }
  2457. for (const std::string& lang : langs) {
  2458. auto langSources = std::count_if(
  2459. sources.begin(), sources.end(), [lang](cmSourceFile* sf) {
  2460. return lang == sf->GetLanguage() &&
  2461. !sf->GetProperty("SKIP_PRECOMPILE_HEADERS");
  2462. });
  2463. if (langSources == 0) {
  2464. continue;
  2465. }
  2466. std::vector<std::string> pchArchs = target->GetPchArchs(config, lang);
  2467. if (pchArchs.size() > 1) {
  2468. std::string useMultiArchPch;
  2469. for (const std::string& arch : pchArchs) {
  2470. const std::string pchHeader =
  2471. target->GetPchHeader(config, lang, arch);
  2472. if (!pchHeader.empty()) {
  2473. useMultiArchPch = cmStrCat(useMultiArchPch, ";-Xarch_", arch,
  2474. ";-include", pchHeader);
  2475. }
  2476. }
  2477. if (!useMultiArchPch.empty()) {
  2478. target->Target->AppendProperty(
  2479. cmStrCat(lang, "_COMPILE_OPTIONS_USE_PCH"),
  2480. cmStrCat("$<$<CONFIG:", config, ">:", useMultiArchPch, ">"));
  2481. }
  2482. }
  2483. for (const std::string& arch : pchArchs) {
  2484. const std::string pchSource = target->GetPchSource(config, lang, arch);
  2485. const std::string pchHeader = target->GetPchHeader(config, lang, arch);
  2486. if (pchSource.empty() || pchHeader.empty()) {
  2487. if (this->GetGlobalGenerator()->IsXcode() && !pchLangSet.empty()) {
  2488. for (auto* sf : sources) {
  2489. const auto sourceLanguage = sf->GetLanguage();
  2490. if (!sourceLanguage.empty() &&
  2491. pchLangSet.find(sourceLanguage) == pchLangSet.end()) {
  2492. sf->SetProperty("SKIP_PRECOMPILE_HEADERS", "ON");
  2493. }
  2494. }
  2495. }
  2496. continue;
  2497. }
  2498. cmValue pchExtension =
  2499. this->Makefile->GetDefinition("CMAKE_PCH_EXTENSION");
  2500. if (pchExtension.IsEmpty()) {
  2501. continue;
  2502. }
  2503. cmValue ReuseFrom =
  2504. target->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM");
  2505. auto* pch_sf = this->Makefile->GetOrCreateSource(
  2506. pchSource, false, cmSourceFileLocationKind::Known);
  2507. // PCH sources should never be scanned as they cannot contain C++
  2508. // module references.
  2509. pch_sf->SetProperty("CXX_SCAN_FOR_MODULES", "0");
  2510. if (!this->GetGlobalGenerator()->IsXcode()) {
  2511. if (!ReuseFrom) {
  2512. target->AddSource(pchSource, true);
  2513. }
  2514. const std::string pchFile = target->GetPchFile(config, lang, arch);
  2515. // Exclude the pch files from linking
  2516. if (this->Makefile->IsOn("CMAKE_LINK_PCH")) {
  2517. if (!ReuseFrom) {
  2518. pch_sf->AppendProperty(
  2519. "OBJECT_OUTPUTS",
  2520. cmStrCat("$<$<CONFIG:", config, ">:", pchFile, ">"));
  2521. } else {
  2522. auto* reuseTarget =
  2523. this->GlobalGenerator->FindGeneratorTarget(*ReuseFrom);
  2524. if (this->Makefile->IsOn("CMAKE_PCH_COPY_COMPILE_PDB")) {
  2525. const std::string compilerId =
  2526. this->Makefile->GetSafeDefinition(
  2527. cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
  2528. const std::string compilerVersion =
  2529. this->Makefile->GetSafeDefinition(
  2530. cmStrCat("CMAKE_", lang, "_COMPILER_VERSION"));
  2531. const std::string langFlags =
  2532. this->Makefile->GetSafeDefinition(
  2533. cmStrCat("CMAKE_", lang, "_FLAGS_", configUpper));
  2534. bool editAndContinueDebugInfo = false;
  2535. bool programDatabaseDebugInfo = false;
  2536. cm::optional<std::string> msvcDebugInformationFormat =
  2537. this->GetMSVCDebugFormatName(config, target);
  2538. if (msvcDebugInformationFormat &&
  2539. !msvcDebugInformationFormat->empty()) {
  2540. editAndContinueDebugInfo =
  2541. *msvcDebugInformationFormat == "EditAndContinue";
  2542. programDatabaseDebugInfo =
  2543. *msvcDebugInformationFormat == "ProgramDatabase";
  2544. } else {
  2545. editAndContinueDebugInfo =
  2546. langFlags.find("/ZI") != std::string::npos ||
  2547. langFlags.find("-ZI") != std::string::npos;
  2548. programDatabaseDebugInfo =
  2549. langFlags.find("/Zi") != std::string::npos ||
  2550. langFlags.find("-Zi") != std::string::npos;
  2551. }
  2552. // MSVC 2008 is producing both .pdb and .idb files with /Zi.
  2553. bool msvc2008OrLess =
  2554. cmSystemTools::VersionCompare(cmSystemTools::OP_LESS,
  2555. compilerVersion, "16.0") &&
  2556. compilerId == "MSVC";
  2557. // but not when used via toolset -Tv90
  2558. if (this->Makefile->GetSafeDefinition(
  2559. "CMAKE_VS_PLATFORM_TOOLSET") == "v90") {
  2560. msvc2008OrLess = false;
  2561. }
  2562. if (editAndContinueDebugInfo || msvc2008OrLess) {
  2563. this->CopyPchCompilePdb(config, lang, target, *ReuseFrom,
  2564. reuseTarget, { ".pdb", ".idb" });
  2565. } else if (programDatabaseDebugInfo) {
  2566. this->CopyPchCompilePdb(config, lang, target, *ReuseFrom,
  2567. reuseTarget, { ".pdb" });
  2568. }
  2569. }
  2570. // Link to the pch object file
  2571. std::string pchSourceObj =
  2572. reuseTarget->GetPchFileObject(config, lang, arch);
  2573. if (target->GetType() != cmStateEnums::OBJECT_LIBRARY) {
  2574. std::string linkerProperty = "LINK_FLAGS_";
  2575. if (target->GetType() == cmStateEnums::STATIC_LIBRARY) {
  2576. linkerProperty = "STATIC_LIBRARY_FLAGS_";
  2577. }
  2578. target->Target->AppendProperty(
  2579. cmStrCat(linkerProperty, configUpper),
  2580. cmStrCat(" ",
  2581. this->ConvertToOutputFormat(pchSourceObj, SHELL)),
  2582. cm::nullopt, true);
  2583. } else if (reuseTarget->GetType() ==
  2584. cmStateEnums::OBJECT_LIBRARY) {
  2585. target->Target->AppendProperty(
  2586. "INTERFACE_LINK_LIBRARIES",
  2587. cmStrCat("$<$<CONFIG:", config,
  2588. ">:$<LINK_ONLY:", pchSourceObj, ">>"));
  2589. }
  2590. }
  2591. } else {
  2592. pch_sf->SetProperty("PCH_EXTENSION", pchExtension);
  2593. }
  2594. // Add pchHeader to source files, which will
  2595. // be grouped as "Precompile Header File"
  2596. auto* pchHeader_sf = this->Makefile->GetOrCreateSource(
  2597. pchHeader, false, cmSourceFileLocationKind::Known);
  2598. std::string err;
  2599. pchHeader_sf->ResolveFullPath(&err);
  2600. if (!err.empty()) {
  2601. std::ostringstream msg;
  2602. msg << "Unable to resolve full path of PCH-header '" << pchHeader
  2603. << "' assigned to target " << target->GetName()
  2604. << ", although its path is supposed to be known!";
  2605. this->IssueMessage(MessageType::FATAL_ERROR, msg.str());
  2606. }
  2607. target->AddSource(pchHeader);
  2608. }
  2609. }
  2610. }
  2611. }
  2612. }
  2613. void cmLocalGenerator::CopyPchCompilePdb(
  2614. const std::string& config, const std::string& language,
  2615. cmGeneratorTarget* target, const std::string& ReuseFrom,
  2616. cmGeneratorTarget* reuseTarget, const std::vector<std::string>& extensions)
  2617. {
  2618. const std::string pdb_prefix =
  2619. this->GetGlobalGenerator()->IsMultiConfig() ? cmStrCat(config, "/") : "";
  2620. const std::string target_compile_pdb_dir =
  2621. cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/",
  2622. target->GetName(), ".dir/");
  2623. const std::string copy_script = cmStrCat(
  2624. target_compile_pdb_dir, "copy_idb_pdb_", config.c_str(), ".cmake");
  2625. cmGeneratedFileStream file(copy_script);
  2626. file << "# CMake generated file\n";
  2627. file << "# The compiler generated pdb file needs to be written to disk\n"
  2628. << "# by mspdbsrv. The foreach retry loop is needed to make sure\n"
  2629. << "# the pdb file is ready to be copied.\n\n";
  2630. for (auto const& extension : extensions) {
  2631. const std::string from_file =
  2632. cmStrCat(reuseTarget->GetLocalGenerator()->GetCurrentBinaryDirectory(),
  2633. "/", ReuseFrom, ".dir/${PDB_PREFIX}", ReuseFrom, extension);
  2634. const std::string to_dir =
  2635. cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/",
  2636. target->GetName(), ".dir/${PDB_PREFIX}");
  2637. const std::string to_file = cmStrCat(to_dir, ReuseFrom, extension);
  2638. std::string dest_file = to_file;
  2639. std::string const& prefix = target->GetSafeProperty("PREFIX");
  2640. if (!prefix.empty()) {
  2641. dest_file = cmStrCat(to_dir, prefix, ReuseFrom, extension);
  2642. }
  2643. file << "foreach(retry RANGE 1 30)\n";
  2644. file << " if (EXISTS \"" << from_file << "\" AND (NOT EXISTS \""
  2645. << dest_file << "\" OR NOT \"" << dest_file << " \" IS_NEWER_THAN \""
  2646. << from_file << "\"))\n";
  2647. file << " execute_process(COMMAND ${CMAKE_COMMAND} -E copy";
  2648. file << " \"" << from_file << "\""
  2649. << " \"" << to_dir << "\" RESULT_VARIABLE result "
  2650. << " ERROR_QUIET)\n";
  2651. file << " if (NOT result EQUAL 0)\n"
  2652. << " execute_process(COMMAND ${CMAKE_COMMAND}"
  2653. << " -E sleep 1)\n"
  2654. << " else()\n";
  2655. if (!prefix.empty()) {
  2656. file << " file(REMOVE \"" << dest_file << "\")\n";
  2657. file << " file(RENAME \"" << to_file << "\" \"" << dest_file << "\")\n";
  2658. }
  2659. file << " break()\n"
  2660. << " endif()\n";
  2661. file << " elseif(NOT EXISTS \"" << from_file << "\")\n"
  2662. << " execute_process(COMMAND ${CMAKE_COMMAND}"
  2663. << " -E sleep 1)\n"
  2664. << " endif()\n";
  2665. file << "endforeach()\n";
  2666. }
  2667. auto configGenex = [&](cm::string_view expr) -> std::string {
  2668. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2669. return cmStrCat("$<$<CONFIG:", config, ">:", expr, ">");
  2670. }
  2671. return std::string(expr);
  2672. };
  2673. cmCustomCommandLines commandLines = cmMakeSingleCommandLine(
  2674. { configGenex(cmSystemTools::GetCMakeCommand()),
  2675. configGenex(cmStrCat("-DPDB_PREFIX=", pdb_prefix)), configGenex("-P"),
  2676. configGenex(copy_script) });
  2677. const char* no_message = "";
  2678. std::vector<std::string> outputs;
  2679. outputs.push_back(configGenex(
  2680. cmStrCat(target_compile_pdb_dir, pdb_prefix, ReuseFrom, ".pdb")));
  2681. auto cc = cm::make_unique<cmCustomCommand>();
  2682. cc->SetCommandLines(commandLines);
  2683. cc->SetComment(no_message);
  2684. cc->SetStdPipesUTF8(true);
  2685. cc->AppendDepends({ reuseTarget->GetPchFile(config, language) });
  2686. if (this->GetGlobalGenerator()->IsVisualStudio()) {
  2687. cc->SetByproducts(outputs);
  2688. this->AddCustomCommandToTarget(
  2689. target->GetName(), cmCustomCommandType::PRE_BUILD, std::move(cc),
  2690. cmObjectLibraryCommands::Accept);
  2691. } else {
  2692. cc->SetOutputs(outputs);
  2693. cmSourceFile* copy_rule = this->AddCustomCommandToOutput(std::move(cc));
  2694. copy_rule->SetProperty("CXX_SCAN_FOR_MODULES", "0");
  2695. if (copy_rule) {
  2696. target->AddSource(copy_rule->ResolveFullPath());
  2697. }
  2698. }
  2699. target->Target->SetProperty("COMPILE_PDB_OUTPUT_DIRECTORY",
  2700. target_compile_pdb_dir);
  2701. }
  2702. cm::optional<std::string> cmLocalGenerator::GetMSVCDebugFormatName(
  2703. std::string const& config, cmGeneratorTarget const* target)
  2704. {
  2705. // MSVC debug information format selection is activated by the presence
  2706. // of a default whether or not it is overridden by a property.
  2707. cm::optional<std::string> msvcDebugInformationFormat;
  2708. cmValue msvcDebugInformationFormatDefault = this->Makefile->GetDefinition(
  2709. "CMAKE_MSVC_DEBUG_INFORMATION_FORMAT_DEFAULT");
  2710. if (cmNonempty(msvcDebugInformationFormatDefault)) {
  2711. cmValue msvcDebugInformationFormatValue =
  2712. target->GetProperty("MSVC_DEBUG_INFORMATION_FORMAT");
  2713. if (!msvcDebugInformationFormatValue) {
  2714. msvcDebugInformationFormatValue = msvcDebugInformationFormatDefault;
  2715. }
  2716. msvcDebugInformationFormat = cmGeneratorExpression::Evaluate(
  2717. *msvcDebugInformationFormatValue, this, config, target);
  2718. }
  2719. return msvcDebugInformationFormat;
  2720. }
  2721. cm::optional<cmSwiftCompileMode> cmLocalGenerator::GetSwiftCompileMode(
  2722. cmGeneratorTarget const* target, std::string const& config)
  2723. {
  2724. cmMakefile const* mf = this->GetMakefile();
  2725. cmValue const swiftCompileModeDefault =
  2726. mf->GetDefinition("CMAKE_Swift_COMPILATION_MODE_DEFAULT");
  2727. if (!cmNonempty(swiftCompileModeDefault)) {
  2728. return {};
  2729. }
  2730. cmValue swiftCompileMode = target->GetProperty("Swift_COMPILATION_MODE");
  2731. if (!swiftCompileMode) {
  2732. swiftCompileMode = swiftCompileModeDefault;
  2733. }
  2734. std::string const expandedCompileMode =
  2735. cmGeneratorExpression::Evaluate(*swiftCompileMode, this, config, target);
  2736. if (expandedCompileMode == "wholemodule") {
  2737. return cmSwiftCompileMode::Wholemodule;
  2738. }
  2739. if (expandedCompileMode == "singlefile") {
  2740. return cmSwiftCompileMode::Singlefile;
  2741. }
  2742. if (expandedCompileMode == "incremental") {
  2743. return cmSwiftCompileMode::Incremental;
  2744. }
  2745. return cmSwiftCompileMode::Unknown;
  2746. }
  2747. bool cmLocalGenerator::IsSplitSwiftBuild() const
  2748. {
  2749. return cmNonempty(this->GetMakefile()->GetDefinition(
  2750. "CMAKE_Swift_COMPILATION_MODE_DEFAULT"));
  2751. }
  2752. namespace {
  2753. inline void RegisterUnitySources(cmGeneratorTarget* target, cmSourceFile* sf,
  2754. std::string const& filename)
  2755. {
  2756. target->AddSourceFileToUnityBatch(sf->ResolveFullPath());
  2757. sf->SetProperty("UNITY_SOURCE_FILE", filename);
  2758. }
  2759. }
  2760. cmLocalGenerator::UnitySource cmLocalGenerator::WriteUnitySource(
  2761. cmGeneratorTarget* target, std::vector<std::string> const& configs,
  2762. cmRange<std::vector<UnityBatchedSource>::const_iterator> sources,
  2763. cmValue beforeInclude, cmValue afterInclude, std::string filename) const
  2764. {
  2765. cmValue uniqueIdName = target->GetProperty("UNITY_BUILD_UNIQUE_ID");
  2766. cmGeneratedFileStream file(
  2767. filename, false, target->GetGlobalGenerator()->GetMakefileEncoding());
  2768. file.SetCopyIfDifferent(true);
  2769. file << "/* generated by CMake */\n\n";
  2770. bool perConfig = false;
  2771. for (UnityBatchedSource const& ubs : sources) {
  2772. cm::optional<std::string> cond;
  2773. if (ubs.Configs.size() != configs.size()) {
  2774. perConfig = true;
  2775. cond = std::string();
  2776. cm::string_view sep;
  2777. for (size_t ci : ubs.Configs) {
  2778. cond = cmStrCat(*cond, sep, "defined(CMAKE_UNITY_CONFIG_",
  2779. cmSystemTools::UpperCase(configs[ci]), ")");
  2780. sep = " || "_s;
  2781. }
  2782. }
  2783. RegisterUnitySources(target, ubs.Source, filename);
  2784. WriteUnitySourceInclude(file, cond, ubs.Source->ResolveFullPath(),
  2785. beforeInclude, afterInclude, uniqueIdName);
  2786. }
  2787. return UnitySource(std::move(filename), perConfig);
  2788. }
  2789. void cmLocalGenerator::WriteUnitySourceInclude(
  2790. std::ostream& unity_file, cm::optional<std::string> const& cond,
  2791. std::string const& sf_full_path, cmValue beforeInclude, cmValue afterInclude,
  2792. cmValue uniqueIdName) const
  2793. {
  2794. if (cond) {
  2795. unity_file << "#if " << *cond << "\n";
  2796. }
  2797. if (cmNonempty(uniqueIdName)) {
  2798. std::string pathToHash;
  2799. auto PathEqOrSubDir = [](std::string const& a, std::string const& b) {
  2800. return (cmSystemTools::ComparePath(a, b) ||
  2801. cmSystemTools::IsSubDirectory(a, b));
  2802. };
  2803. const auto path = cmSystemTools::GetFilenamePath(sf_full_path);
  2804. if (PathEqOrSubDir(path, this->GetBinaryDirectory())) {
  2805. pathToHash = "BLD_" +
  2806. cmSystemTools::RelativePath(this->GetBinaryDirectory(), sf_full_path);
  2807. } else if (PathEqOrSubDir(path, this->GetSourceDirectory())) {
  2808. pathToHash = "SRC_" +
  2809. cmSystemTools::RelativePath(this->GetSourceDirectory(), sf_full_path);
  2810. } else {
  2811. pathToHash = "ABS_" + sf_full_path;
  2812. }
  2813. cmCryptoHash hasher(cmCryptoHash::AlgoMD5);
  2814. unity_file << "/* " << pathToHash << " */\n"
  2815. << "#undef " << *uniqueIdName << "\n"
  2816. << "#define " << *uniqueIdName << " unity_"
  2817. << hasher.HashString(pathToHash) << "\n";
  2818. }
  2819. if (beforeInclude) {
  2820. unity_file << *beforeInclude << "\n";
  2821. }
  2822. // clang-tidy-17 has new include checks that needs NOLINT too.
  2823. unity_file
  2824. << "/* NOLINTNEXTLINE(bugprone-suspicious-include,misc-include-cleaner) "
  2825. "*/\n";
  2826. unity_file << "#include \"" << sf_full_path << "\"\n";
  2827. if (afterInclude) {
  2828. unity_file << *afterInclude << "\n";
  2829. }
  2830. if (cond) {
  2831. unity_file << "#endif\n";
  2832. }
  2833. unity_file << "\n";
  2834. }
  2835. namespace {
  2836. std::string unity_file_extension(std::string const& lang)
  2837. {
  2838. std::string extension;
  2839. if (lang == "C") {
  2840. extension = "_c.c";
  2841. } else if (lang == "CXX") {
  2842. extension = "_cxx.cxx";
  2843. } else if (lang == "CUDA") {
  2844. extension = "_cu.cu";
  2845. } else if (lang == "OBJC") {
  2846. extension = "_m.m";
  2847. } else if (lang == "OBJCXX") {
  2848. extension = "_mm.mm";
  2849. }
  2850. return extension;
  2851. }
  2852. }
  2853. std::vector<cmLocalGenerator::UnitySource>
  2854. cmLocalGenerator::AddUnityFilesModeAuto(
  2855. cmGeneratorTarget* target, std::string const& lang,
  2856. std::vector<std::string> const& configs,
  2857. std::vector<UnityBatchedSource> const& filtered_sources,
  2858. cmValue beforeInclude, cmValue afterInclude,
  2859. std::string const& filename_base, size_t batchSize)
  2860. {
  2861. if (batchSize == 0) {
  2862. batchSize = filtered_sources.size();
  2863. }
  2864. std::vector<UnitySource> unity_files;
  2865. for (size_t itemsLeft = filtered_sources.size(), chunk, batch = 0;
  2866. itemsLeft > 0; itemsLeft -= chunk, ++batch) {
  2867. chunk = std::min(itemsLeft, batchSize);
  2868. std::string filename =
  2869. cmStrCat(filename_base, "unity_", batch, unity_file_extension(lang));
  2870. auto const begin = filtered_sources.begin() + batch * batchSize;
  2871. auto const end = begin + chunk;
  2872. unity_files.emplace_back(this->WriteUnitySource(
  2873. target, configs, cmMakeRange(begin, end), beforeInclude, afterInclude,
  2874. std::move(filename)));
  2875. }
  2876. return unity_files;
  2877. }
  2878. std::vector<cmLocalGenerator::UnitySource>
  2879. cmLocalGenerator::AddUnityFilesModeGroup(
  2880. cmGeneratorTarget* target, std::string const& lang,
  2881. std::vector<std::string> const& configs,
  2882. std::vector<UnityBatchedSource> const& filtered_sources,
  2883. cmValue beforeInclude, cmValue afterInclude,
  2884. std::string const& filename_base)
  2885. {
  2886. std::vector<UnitySource> unity_files;
  2887. // sources organized by group name. Drop any source
  2888. // without a group
  2889. std::unordered_map<std::string, std::vector<UnityBatchedSource>>
  2890. explicit_mapping;
  2891. for (UnityBatchedSource const& ubs : filtered_sources) {
  2892. if (cmValue value = ubs.Source->GetProperty("UNITY_GROUP")) {
  2893. auto i = explicit_mapping.find(*value);
  2894. if (i == explicit_mapping.end()) {
  2895. std::vector<UnityBatchedSource> sources{ ubs };
  2896. explicit_mapping.emplace(*value, std::move(sources));
  2897. } else {
  2898. i->second.emplace_back(ubs);
  2899. }
  2900. }
  2901. }
  2902. for (auto const& item : explicit_mapping) {
  2903. auto const& name = item.first;
  2904. std::string filename =
  2905. cmStrCat(filename_base, "unity_", name, unity_file_extension(lang));
  2906. unity_files.emplace_back(this->WriteUnitySource(
  2907. target, configs, cmMakeRange(item.second), beforeInclude, afterInclude,
  2908. std::move(filename)));
  2909. }
  2910. return unity_files;
  2911. }
  2912. void cmLocalGenerator::AddUnityBuild(cmGeneratorTarget* target)
  2913. {
  2914. if (!target->GetPropertyAsBool("UNITY_BUILD")) {
  2915. return;
  2916. }
  2917. std::vector<UnityBatchedSource> unitySources;
  2918. std::vector<std::string> configs =
  2919. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  2920. std::map<cmSourceFile const*, size_t> index;
  2921. for (size_t ci = 0; ci < configs.size(); ++ci) {
  2922. // FIXME: Refactor collection of sources to not evaluate object libraries.
  2923. // Their final set of object files might be transformed by unity builds.
  2924. std::vector<cmSourceFile*> sources;
  2925. target->GetSourceFiles(sources, configs[ci]);
  2926. for (cmSourceFile* sf : sources) {
  2927. // Files which need C++ scanning cannot participate in unity builds as
  2928. // there is a single place in TUs that may perform module-dependency bits
  2929. // and a unity source cannot `#include` them in-order and represent a
  2930. // valid TU.
  2931. if (sf->GetLanguage() == "CXX"_s &&
  2932. target->NeedDyndepForSource("CXX", configs[ci], sf)) {
  2933. continue;
  2934. }
  2935. auto mi = index.find(sf);
  2936. if (mi == index.end()) {
  2937. unitySources.emplace_back(sf);
  2938. std::map<cmSourceFile const*, size_t>::value_type entry(
  2939. sf, unitySources.size() - 1);
  2940. mi = index.insert(entry).first;
  2941. }
  2942. unitySources[mi->second].Configs.emplace_back(ci);
  2943. }
  2944. }
  2945. std::string filename_base =
  2946. cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles/",
  2947. target->GetName(), ".dir/Unity/");
  2948. cmValue batchSizeString = target->GetProperty("UNITY_BUILD_BATCH_SIZE");
  2949. const size_t unityBatchSize = batchSizeString
  2950. ? static_cast<size_t>(std::atoi(batchSizeString->c_str()))
  2951. : 0;
  2952. cmValue beforeInclude =
  2953. target->GetProperty("UNITY_BUILD_CODE_BEFORE_INCLUDE");
  2954. cmValue afterInclude = target->GetProperty("UNITY_BUILD_CODE_AFTER_INCLUDE");
  2955. cmValue unityMode = target->GetProperty("UNITY_BUILD_MODE");
  2956. for (std::string lang : { "C", "CXX", "OBJC", "OBJCXX", "CUDA" }) {
  2957. std::vector<UnityBatchedSource> filtered_sources;
  2958. std::copy_if(unitySources.begin(), unitySources.end(),
  2959. std::back_inserter(filtered_sources),
  2960. [&](UnityBatchedSource const& ubs) -> bool {
  2961. cmSourceFile* sf = ubs.Source;
  2962. return sf->GetLanguage() == lang &&
  2963. !sf->GetPropertyAsBool("SKIP_UNITY_BUILD_INCLUSION") &&
  2964. !sf->GetPropertyAsBool("HEADER_FILE_ONLY") &&
  2965. !sf->GetProperty("COMPILE_OPTIONS") &&
  2966. !sf->GetProperty("COMPILE_DEFINITIONS") &&
  2967. !sf->GetProperty("COMPILE_FLAGS") &&
  2968. !sf->GetProperty("INCLUDE_DIRECTORIES");
  2969. });
  2970. std::vector<UnitySource> unity_files;
  2971. if (!unityMode || *unityMode == "BATCH") {
  2972. unity_files = AddUnityFilesModeAuto(
  2973. target, lang, configs, filtered_sources, beforeInclude, afterInclude,
  2974. filename_base, unityBatchSize);
  2975. } else if (unityMode && *unityMode == "GROUP") {
  2976. unity_files =
  2977. AddUnityFilesModeGroup(target, lang, configs, filtered_sources,
  2978. beforeInclude, afterInclude, filename_base);
  2979. } else {
  2980. // unity mode is set to an unsupported value
  2981. std::string e("Invalid UNITY_BUILD_MODE value of " + *unityMode +
  2982. " assigned to target " + target->GetName() +
  2983. ". Acceptable values are BATCH and GROUP.");
  2984. this->IssueMessage(MessageType::FATAL_ERROR, e);
  2985. }
  2986. for (UnitySource const& file : unity_files) {
  2987. auto* unity = this->GetMakefile()->GetOrCreateSource(file.Path);
  2988. target->AddSource(file.Path, true);
  2989. unity->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "ON");
  2990. unity->SetProperty("UNITY_SOURCE_FILE", file.Path);
  2991. unity->SetProperty("CXX_SCAN_FOR_MODULES", "0");
  2992. if (file.PerConfig) {
  2993. unity->SetProperty("COMPILE_DEFINITIONS",
  2994. "CMAKE_UNITY_CONFIG_$<UPPER_CASE:$<CONFIG>>");
  2995. }
  2996. }
  2997. }
  2998. }
  2999. void cmLocalGenerator::AppendLinkerTypeFlags(std::string& flags,
  3000. cmGeneratorTarget* target,
  3001. const std::string& config,
  3002. const std::string& linkLanguage)
  3003. {
  3004. switch (target->GetType()) {
  3005. case cmStateEnums::EXECUTABLE:
  3006. case cmStateEnums::SHARED_LIBRARY:
  3007. case cmStateEnums::MODULE_LIBRARY:
  3008. break;
  3009. default:
  3010. return;
  3011. }
  3012. auto usingLinker =
  3013. cmStrCat("CMAKE_", linkLanguage, "_USING_",
  3014. target->IsDeviceLink() ? "DEVICE_" : "", "LINKER_");
  3015. auto format = this->Makefile->GetDefinition(cmStrCat(usingLinker, "MODE"));
  3016. if (format && format != "FLAG"_s) {
  3017. return;
  3018. }
  3019. auto linkerType = target->GetLinkerTypeProperty(linkLanguage, config);
  3020. if (linkerType.empty()) {
  3021. linkerType = "DEFAULT";
  3022. }
  3023. usingLinker = cmStrCat(usingLinker, linkerType);
  3024. auto linkerTypeFlags = this->Makefile->GetDefinition(usingLinker);
  3025. if (linkerTypeFlags) {
  3026. if (!linkerTypeFlags.IsEmpty()) {
  3027. auto linkerFlags = cmExpandListWithBacktrace(linkerTypeFlags);
  3028. target->ResolveLinkerWrapper(linkerFlags, linkLanguage);
  3029. this->AppendFlags(flags, linkerFlags);
  3030. }
  3031. } else if (linkerType != "DEFAULT"_s) {
  3032. auto isCMakeLinkerType = [](const std::string& type) -> bool {
  3033. return std::all_of(type.cbegin(), type.cend(),
  3034. [](char c) { return std::isupper(c); });
  3035. };
  3036. if (isCMakeLinkerType(linkerType)) {
  3037. this->IssueMessage(
  3038. MessageType::FATAL_ERROR,
  3039. cmStrCat("LINKER_TYPE '", linkerType,
  3040. "' is unknown or not supported by this toolchain."));
  3041. } else {
  3042. this->IssueMessage(
  3043. MessageType::FATAL_ERROR,
  3044. cmStrCat("LINKER_TYPE '", linkerType,
  3045. "' is unknown. Did you forget to define the '", usingLinker,
  3046. "' variable?"));
  3047. }
  3048. }
  3049. }
  3050. void cmLocalGenerator::AppendIPOLinkerFlags(std::string& flags,
  3051. cmGeneratorTarget* target,
  3052. const std::string& config,
  3053. const std::string& lang)
  3054. {
  3055. if (!target->IsIPOEnabled(lang, config)) {
  3056. return;
  3057. }
  3058. switch (target->GetType()) {
  3059. case cmStateEnums::EXECUTABLE:
  3060. case cmStateEnums::SHARED_LIBRARY:
  3061. case cmStateEnums::MODULE_LIBRARY:
  3062. break;
  3063. default:
  3064. return;
  3065. }
  3066. const std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_IPO";
  3067. cmValue rawFlagsList = this->Makefile->GetDefinition(name);
  3068. if (!rawFlagsList) {
  3069. return;
  3070. }
  3071. cmList flagsList{ *rawFlagsList };
  3072. for (std::string const& o : flagsList) {
  3073. this->AppendFlagEscape(flags, o);
  3074. }
  3075. }
  3076. void cmLocalGenerator::AppendPositionIndependentLinkerFlags(
  3077. std::string& flags, cmGeneratorTarget* target, const std::string& config,
  3078. const std::string& lang)
  3079. {
  3080. // For now, only EXECUTABLE is concerned
  3081. if (target->GetType() != cmStateEnums::EXECUTABLE) {
  3082. return;
  3083. }
  3084. const char* PICValue = target->GetLinkPIEProperty(config);
  3085. if (!PICValue) {
  3086. // POSITION_INDEPENDENT_CODE is not set
  3087. return;
  3088. }
  3089. const std::string mode = cmIsOn(PICValue) ? "PIE" : "NO_PIE";
  3090. std::string supported = "CMAKE_" + lang + "_LINK_" + mode + "_SUPPORTED";
  3091. if (this->Makefile->GetDefinition(supported).IsOff()) {
  3092. return;
  3093. }
  3094. std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_" + mode;
  3095. auto pieFlags = this->Makefile->GetSafeDefinition(name);
  3096. if (pieFlags.empty()) {
  3097. return;
  3098. }
  3099. cmList flagsList{ pieFlags };
  3100. for (const auto& flag : flagsList) {
  3101. this->AppendFlagEscape(flags, flag);
  3102. }
  3103. }
  3104. void cmLocalGenerator::AppendDependencyInfoLinkerFlags(
  3105. std::string& flags, cmGeneratorTarget* target, const std::string& config,
  3106. const std::string& linkLanguage)
  3107. {
  3108. if (!this->GetGlobalGenerator()->SupportsLinkerDependencyFile() ||
  3109. !target->HasLinkDependencyFile(config)) {
  3110. return;
  3111. }
  3112. auto depFlag = *this->Makefile->GetDefinition(
  3113. cmStrCat("CMAKE_", linkLanguage, "_LINKER_DEPFILE_FLAGS"));
  3114. if (depFlag.empty()) {
  3115. return;
  3116. }
  3117. auto depFile = this->ConvertToOutputFormat(
  3118. this->MaybeRelativeToWorkDir(this->GetLinkDependencyFile(target, config)),
  3119. cmOutputConverter::SHELL);
  3120. auto rulePlaceholderExpander = this->CreateRulePlaceholderExpander();
  3121. cmRulePlaceholderExpander::RuleVariables linkDepsVariables;
  3122. linkDepsVariables.DependencyFile = depFile.c_str();
  3123. rulePlaceholderExpander->ExpandRuleVariables(this, depFlag,
  3124. linkDepsVariables);
  3125. auto depFlags = cmExpandListWithBacktrace(depFlag);
  3126. target->ResolveLinkerWrapper(depFlags, linkLanguage);
  3127. this->AppendFlags(flags, depFlags);
  3128. }
  3129. std::string cmLocalGenerator::GetLinkDependencyFile(
  3130. cmGeneratorTarget* /*target*/, const std::string& /*config*/) const
  3131. {
  3132. return "link.d";
  3133. }
  3134. void cmLocalGenerator::AppendModuleDefinitionFlag(
  3135. std::string& flags, cmGeneratorTarget const* target,
  3136. cmLinkLineComputer* linkLineComputer, std::string const& config)
  3137. {
  3138. cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  3139. target->GetModuleDefinitionInfo(config);
  3140. if (!mdi || mdi->DefFile.empty()) {
  3141. return;
  3142. }
  3143. cmValue defFileFlag =
  3144. this->Makefile->GetDefinition("CMAKE_LINK_DEF_FILE_FLAG");
  3145. if (!defFileFlag) {
  3146. return;
  3147. }
  3148. // Append the flag and value. Use ConvertToLinkReference to help
  3149. // vs6's "cl -link" pass it to the linker.
  3150. std::string flag =
  3151. cmStrCat(*defFileFlag,
  3152. this->ConvertToOutputFormat(
  3153. linkLineComputer->ConvertToLinkReference(mdi->DefFile),
  3154. cmOutputConverter::SHELL));
  3155. this->AppendFlags(flags, flag);
  3156. }
  3157. bool cmLocalGenerator::AppendLWYUFlags(std::string& flags,
  3158. const cmGeneratorTarget* target,
  3159. const std::string& lang)
  3160. {
  3161. auto useLWYU = target->GetPropertyAsBool("LINK_WHAT_YOU_USE") &&
  3162. (target->GetType() == cmStateEnums::TargetType::EXECUTABLE ||
  3163. target->GetType() == cmStateEnums::TargetType::SHARED_LIBRARY ||
  3164. target->GetType() == cmStateEnums::TargetType::MODULE_LIBRARY);
  3165. if (useLWYU) {
  3166. const auto& lwyuFlag = this->GetMakefile()->GetSafeDefinition(
  3167. cmStrCat("CMAKE_", lang, "_LINK_WHAT_YOU_USE_FLAG"));
  3168. useLWYU = !lwyuFlag.empty();
  3169. if (useLWYU) {
  3170. std::vector<BT<std::string>> lwyuOpts;
  3171. lwyuOpts.emplace_back(lwyuFlag);
  3172. this->AppendFlags(flags, target->ResolveLinkerWrapper(lwyuOpts, lang));
  3173. }
  3174. }
  3175. return useLWYU;
  3176. }
  3177. void cmLocalGenerator::AppendCompileOptions(std::string& options,
  3178. std::string const& options_list,
  3179. const char* regex) const
  3180. {
  3181. // Short-circuit if there are no options.
  3182. if (options_list.empty()) {
  3183. return;
  3184. }
  3185. // Expand the list of options.
  3186. cmList options_vec{ options_list };
  3187. this->AppendCompileOptions(options, options_vec, regex);
  3188. }
  3189. void cmLocalGenerator::AppendCompileOptions(
  3190. std::string& options, const std::vector<std::string>& options_vec,
  3191. const char* regex) const
  3192. {
  3193. if (regex) {
  3194. // Filter flags upon specified reges.
  3195. cmsys::RegularExpression r(regex);
  3196. for (std::string const& opt : options_vec) {
  3197. if (r.find(opt)) {
  3198. this->AppendFlagEscape(options, opt);
  3199. }
  3200. }
  3201. } else {
  3202. for (std::string const& opt : options_vec) {
  3203. this->AppendFlagEscape(options, opt);
  3204. }
  3205. }
  3206. }
  3207. void cmLocalGenerator::AppendCompileOptions(
  3208. std::vector<BT<std::string>>& options,
  3209. const std::vector<BT<std::string>>& options_vec, const char* regex) const
  3210. {
  3211. if (regex) {
  3212. // Filter flags upon specified regular expressions.
  3213. cmsys::RegularExpression r(regex);
  3214. for (BT<std::string> const& opt : options_vec) {
  3215. if (r.find(opt.Value)) {
  3216. std::string flag;
  3217. this->AppendFlagEscape(flag, opt.Value);
  3218. options.emplace_back(std::move(flag), opt.Backtrace);
  3219. }
  3220. }
  3221. } else {
  3222. for (BT<std::string> const& opt : options_vec) {
  3223. std::string flag;
  3224. this->AppendFlagEscape(flag, opt.Value);
  3225. options.emplace_back(std::move(flag), opt.Backtrace);
  3226. }
  3227. }
  3228. }
  3229. void cmLocalGenerator::AppendIncludeDirectories(
  3230. std::vector<std::string>& includes, const std::string& includes_list,
  3231. const cmSourceFile& sourceFile) const
  3232. {
  3233. // Short-circuit if there are no includes.
  3234. if (includes_list.empty()) {
  3235. return;
  3236. }
  3237. // Expand the list of includes.
  3238. cmList includes_vec{ includes_list };
  3239. this->AppendIncludeDirectories(includes, includes_vec, sourceFile);
  3240. }
  3241. void cmLocalGenerator::AppendIncludeDirectories(
  3242. std::vector<std::string>& includes,
  3243. const std::vector<std::string>& includes_vec,
  3244. const cmSourceFile& sourceFile) const
  3245. {
  3246. std::unordered_set<std::string> uniqueIncludes;
  3247. for (const std::string& include : includes_vec) {
  3248. if (!cmSystemTools::FileIsFullPath(include)) {
  3249. std::ostringstream e;
  3250. e << "Found relative path while evaluating include directories of "
  3251. "\""
  3252. << sourceFile.GetLocation().GetName() << "\":\n \"" << include
  3253. << "\"\n";
  3254. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  3255. return;
  3256. }
  3257. std::string inc = include;
  3258. if (!cmIsOff(inc)) {
  3259. cmSystemTools::ConvertToUnixSlashes(inc);
  3260. }
  3261. if (uniqueIncludes.insert(inc).second) {
  3262. includes.push_back(std::move(inc));
  3263. }
  3264. }
  3265. }
  3266. void cmLocalGenerator::AppendDefines(std::set<std::string>& defines,
  3267. std::string const& defines_list) const
  3268. {
  3269. std::set<BT<std::string>> tmp;
  3270. this->AppendDefines(tmp, cmExpandListWithBacktrace(defines_list));
  3271. for (BT<std::string> const& i : tmp) {
  3272. defines.emplace(i.Value);
  3273. }
  3274. }
  3275. void cmLocalGenerator::AppendDefines(std::set<BT<std::string>>& defines,
  3276. std::string const& defines_list) const
  3277. {
  3278. // Short-circuit if there are no definitions.
  3279. if (defines_list.empty()) {
  3280. return;
  3281. }
  3282. // Expand the list of definitions.
  3283. this->AppendDefines(defines, cmExpandListWithBacktrace(defines_list));
  3284. }
  3285. void cmLocalGenerator::AppendDefines(
  3286. std::set<BT<std::string>>& defines,
  3287. const std::vector<BT<std::string>>& defines_vec) const
  3288. {
  3289. for (BT<std::string> const& d : defines_vec) {
  3290. // Skip unsupported definitions.
  3291. if (!this->CheckDefinition(d.Value)) {
  3292. continue;
  3293. }
  3294. // remove any leading -D
  3295. if (cmHasLiteralPrefix(d.Value, "-D")) {
  3296. defines.emplace(d.Value.substr(2), d.Backtrace);
  3297. } else {
  3298. defines.insert(d);
  3299. }
  3300. }
  3301. }
  3302. void cmLocalGenerator::JoinDefines(const std::set<std::string>& defines,
  3303. std::string& definesString,
  3304. const std::string& lang)
  3305. {
  3306. // Lookup the define flag for the current language.
  3307. std::string dflag = "-D";
  3308. if (!lang.empty()) {
  3309. cmValue df =
  3310. this->Makefile->GetDefinition(cmStrCat("CMAKE_", lang, "_DEFINE_FLAG"));
  3311. if (cmNonempty(df)) {
  3312. dflag = *df;
  3313. }
  3314. }
  3315. const char* itemSeparator = definesString.empty() ? "" : " ";
  3316. for (std::string const& define : defines) {
  3317. // Append the definition with proper escaping.
  3318. std::string def = dflag;
  3319. if (this->GetState()->UseWatcomWMake()) {
  3320. // The Watcom compiler does its own command line parsing instead
  3321. // of using the windows shell rules. Definitions are one of
  3322. // -DNAME
  3323. // -DNAME=<cpp-token>
  3324. // -DNAME="c-string with spaces and other characters(?@#$)"
  3325. //
  3326. // Watcom will properly parse each of these cases from the
  3327. // command line without any escapes. However we still have to
  3328. // get the '$' and '#' characters through WMake as '$$' and
  3329. // '$#'.
  3330. for (char c : define) {
  3331. if (c == '$' || c == '#') {
  3332. def += '$';
  3333. }
  3334. def += c;
  3335. }
  3336. } else {
  3337. // Make the definition appear properly on the command line. Use
  3338. // -DNAME="value" instead of -D"NAME=value" for historical reasons.
  3339. std::string::size_type eq = define.find('=');
  3340. def += define.substr(0, eq);
  3341. if (eq != std::string::npos) {
  3342. def += "=";
  3343. def += this->EscapeForShell(define.substr(eq + 1), true);
  3344. }
  3345. }
  3346. definesString += itemSeparator;
  3347. itemSeparator = " ";
  3348. definesString += def;
  3349. }
  3350. }
  3351. void cmLocalGenerator::AppendFeatureOptions(std::string& flags,
  3352. const std::string& lang,
  3353. const char* feature)
  3354. {
  3355. cmValue optionList = this->Makefile->GetDefinition(
  3356. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_", feature));
  3357. if (optionList) {
  3358. cmList options{ *optionList };
  3359. for (std::string const& o : options) {
  3360. this->AppendFlagEscape(flags, o);
  3361. }
  3362. }
  3363. }
  3364. cmValue cmLocalGenerator::GetFeature(const std::string& feature,
  3365. const std::string& config)
  3366. {
  3367. std::string featureName = feature;
  3368. // TODO: Define accumulation policy for features (prepend, append,
  3369. // replace). Currently we always replace.
  3370. if (!config.empty()) {
  3371. featureName += "_";
  3372. featureName += cmSystemTools::UpperCase(config);
  3373. }
  3374. cmStateSnapshot snp = this->StateSnapshot;
  3375. while (snp.IsValid()) {
  3376. if (cmValue value = snp.GetDirectory().GetProperty(featureName)) {
  3377. return value;
  3378. }
  3379. snp = snp.GetBuildsystemDirectoryParent();
  3380. }
  3381. return nullptr;
  3382. }
  3383. std::string cmLocalGenerator::GetProjectName() const
  3384. {
  3385. return this->StateSnapshot.GetProjectName();
  3386. }
  3387. std::string cmLocalGenerator::ConstructComment(
  3388. cmCustomCommandGenerator const& ccg, const char* default_comment) const
  3389. {
  3390. // Check for a comment provided with the command.
  3391. if (cm::optional<std::string> comment = ccg.GetComment()) {
  3392. return *comment;
  3393. }
  3394. // Construct a reasonable default comment if possible.
  3395. if (!ccg.GetOutputs().empty()) {
  3396. std::string comment;
  3397. comment = "Generating ";
  3398. const char* sep = "";
  3399. for (std::string const& o : ccg.GetOutputs()) {
  3400. comment += sep;
  3401. comment += this->MaybeRelativeToCurBinDir(o);
  3402. sep = ", ";
  3403. }
  3404. return comment;
  3405. }
  3406. // Otherwise use the provided default.
  3407. return default_comment;
  3408. }
  3409. class cmInstallTargetGeneratorLocal : public cmInstallTargetGenerator
  3410. {
  3411. public:
  3412. cmInstallTargetGeneratorLocal(cmLocalGenerator* lg, std::string const& t,
  3413. std::string const& dest, bool implib)
  3414. : cmInstallTargetGenerator(
  3415. t, dest, implib, "", std::vector<std::string>(), "Unspecified",
  3416. cmInstallGenerator::SelectMessageLevel(lg->GetMakefile()), false,
  3417. false)
  3418. {
  3419. this->Compute(lg);
  3420. }
  3421. };
  3422. void cmLocalGenerator::GenerateTargetInstallRules(
  3423. std::ostream& os, const std::string& config,
  3424. std::vector<std::string> const& configurationTypes)
  3425. {
  3426. // Convert the old-style install specification from each target to
  3427. // an install generator and run it.
  3428. const auto& tgts = this->GetGeneratorTargets();
  3429. for (const auto& l : tgts) {
  3430. if (l->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  3431. continue;
  3432. }
  3433. // Include the user-specified pre-install script for this target.
  3434. if (cmValue preinstall = l->GetProperty("PRE_INSTALL_SCRIPT")) {
  3435. cmInstallScriptGenerator g(*preinstall, false, "", false, false);
  3436. g.Generate(os, config, configurationTypes);
  3437. }
  3438. // Install this target if a destination is given.
  3439. if (!l->Target->GetInstallPath().empty()) {
  3440. // Compute the full install destination. Note that converting
  3441. // to unix slashes also removes any trailing slash.
  3442. // We also skip over the leading slash given by the user.
  3443. std::string destination = l->Target->GetInstallPath().substr(1);
  3444. cmSystemTools::ConvertToUnixSlashes(destination);
  3445. if (destination.empty()) {
  3446. destination = ".";
  3447. }
  3448. // Generate the proper install generator for this target type.
  3449. switch (l->GetType()) {
  3450. case cmStateEnums::EXECUTABLE:
  3451. case cmStateEnums::STATIC_LIBRARY:
  3452. case cmStateEnums::MODULE_LIBRARY: {
  3453. // Use a target install generator.
  3454. cmInstallTargetGeneratorLocal g(this, l->GetName(), destination,
  3455. false);
  3456. g.Generate(os, config, configurationTypes);
  3457. } break;
  3458. case cmStateEnums::SHARED_LIBRARY: {
  3459. #if defined(_WIN32) || defined(__CYGWIN__)
  3460. // Special code to handle DLL. Install the import library
  3461. // to the normal destination and the DLL to the runtime
  3462. // destination.
  3463. cmInstallTargetGeneratorLocal g1(this, l->GetName(), destination,
  3464. true);
  3465. g1.Generate(os, config, configurationTypes);
  3466. // We also skip over the leading slash given by the user.
  3467. destination = l->Target->GetRuntimeInstallPath().substr(1);
  3468. cmSystemTools::ConvertToUnixSlashes(destination);
  3469. cmInstallTargetGeneratorLocal g2(this, l->GetName(), destination,
  3470. false);
  3471. g2.Generate(os, config, configurationTypes);
  3472. #else
  3473. // Use a target install generator.
  3474. cmInstallTargetGeneratorLocal g(this, l->GetName(), destination,
  3475. false);
  3476. g.Generate(os, config, configurationTypes);
  3477. #endif
  3478. } break;
  3479. default:
  3480. break;
  3481. }
  3482. }
  3483. // Include the user-specified post-install script for this target.
  3484. if (cmValue postinstall = l->GetProperty("POST_INSTALL_SCRIPT")) {
  3485. cmInstallScriptGenerator g(*postinstall, false, "", false, false);
  3486. g.Generate(os, config, configurationTypes);
  3487. }
  3488. }
  3489. }
  3490. namespace {
  3491. bool cmLocalGeneratorShortenObjectName(std::string& objName,
  3492. std::string::size_type max_len)
  3493. {
  3494. // Check if the path can be shortened using an md5 sum replacement for
  3495. // a portion of the path.
  3496. std::string::size_type md5Len = 32;
  3497. std::string::size_type numExtraChars = objName.size() - max_len + md5Len;
  3498. std::string::size_type pos = objName.find('/', numExtraChars);
  3499. if (pos == std::string::npos) {
  3500. pos = objName.rfind('/', numExtraChars);
  3501. if (pos == std::string::npos || pos <= md5Len) {
  3502. return false;
  3503. }
  3504. }
  3505. // Replace the beginning of the path portion of the object name with
  3506. // its own md5 sum.
  3507. cmCryptoHash md5(cmCryptoHash::AlgoMD5);
  3508. std::string md5name = cmStrCat(md5.HashString(objName.substr(0, pos)),
  3509. cm::string_view(objName).substr(pos));
  3510. objName = md5name;
  3511. // The object name is now shorter, check if it is short enough.
  3512. return pos >= numExtraChars;
  3513. }
  3514. bool cmLocalGeneratorCheckObjectName(std::string& objName,
  3515. std::string::size_type dir_len,
  3516. std::string::size_type max_total_len)
  3517. {
  3518. // Enforce the maximum file name length if possible.
  3519. std::string::size_type max_obj_len = max_total_len;
  3520. if (dir_len < max_total_len) {
  3521. max_obj_len = max_total_len - dir_len;
  3522. if (objName.size() > max_obj_len) {
  3523. // The current object file name is too long. Try to shorten it.
  3524. return cmLocalGeneratorShortenObjectName(objName, max_obj_len);
  3525. }
  3526. // The object file name is short enough.
  3527. return true;
  3528. }
  3529. // The build directory in which the object will be stored is
  3530. // already too deep.
  3531. return false;
  3532. }
  3533. }
  3534. std::string& cmLocalGenerator::CreateSafeUniqueObjectFileName(
  3535. const std::string& sin, std::string const& dir_max)
  3536. {
  3537. // Look for an existing mapped name for this object file.
  3538. auto it = this->UniqueObjectNamesMap.find(sin);
  3539. // If no entry exists create one.
  3540. if (it == this->UniqueObjectNamesMap.end()) {
  3541. // Start with the original name.
  3542. std::string ssin = sin;
  3543. // Avoid full paths by removing leading slashes.
  3544. ssin.erase(0, ssin.find_first_not_of('/'));
  3545. // Avoid full paths by removing colons.
  3546. std::replace(ssin.begin(), ssin.end(), ':', '_');
  3547. // Avoid relative paths that go up the tree.
  3548. cmSystemTools::ReplaceString(ssin, "../", "__/");
  3549. // Avoid spaces.
  3550. std::replace(ssin.begin(), ssin.end(), ' ', '_');
  3551. // Mangle the name if necessary.
  3552. if (this->Makefile->IsOn("CMAKE_MANGLE_OBJECT_FILE_NAMES")) {
  3553. bool done;
  3554. int cc = 0;
  3555. char rpstr[100];
  3556. snprintf(rpstr, sizeof(rpstr), "_p_");
  3557. cmSystemTools::ReplaceString(ssin, "+", rpstr);
  3558. std::string sssin = sin;
  3559. do {
  3560. done = true;
  3561. for (it = this->UniqueObjectNamesMap.begin();
  3562. it != this->UniqueObjectNamesMap.end(); ++it) {
  3563. if (it->second == ssin) {
  3564. done = false;
  3565. }
  3566. }
  3567. if (done) {
  3568. break;
  3569. }
  3570. sssin = ssin;
  3571. cmSystemTools::ReplaceString(ssin, "_p_", rpstr);
  3572. snprintf(rpstr, sizeof(rpstr), "_p%d_", cc++);
  3573. } while (!done);
  3574. }
  3575. if (!cmLocalGeneratorCheckObjectName(ssin, dir_max.size(),
  3576. this->ObjectPathMax)) {
  3577. // Warn if this is the first time the path has been seen.
  3578. if (this->ObjectMaxPathViolations.insert(dir_max).second) {
  3579. std::ostringstream m;
  3580. /* clang-format off */
  3581. m << "The object file directory\n"
  3582. << " " << dir_max << "\n"
  3583. << "has " << dir_max.size() << " characters. "
  3584. << "The maximum full path to an object file is "
  3585. << this->ObjectPathMax << " characters "
  3586. << "(see CMAKE_OBJECT_PATH_MAX). "
  3587. << "Object file\n"
  3588. << " " << ssin << "\n"
  3589. << "cannot be safely placed under this directory. "
  3590. << "The build may not work correctly.";
  3591. /* clang-format on */
  3592. this->IssueMessage(MessageType::WARNING, m.str());
  3593. }
  3594. }
  3595. // Insert the newly mapped object file name.
  3596. std::map<std::string, std::string>::value_type e(sin, ssin);
  3597. it = this->UniqueObjectNamesMap.insert(e).first;
  3598. }
  3599. // Return the map entry.
  3600. return it->second;
  3601. }
  3602. void cmLocalGenerator::ComputeObjectFilenames(
  3603. std::map<cmSourceFile const*, std::string>& /*unused*/,
  3604. cmGeneratorTarget const* /*unused*/)
  3605. {
  3606. }
  3607. bool cmLocalGenerator::IsWindowsShell() const
  3608. {
  3609. return this->GetState()->UseWindowsShell();
  3610. }
  3611. bool cmLocalGenerator::IsWatcomWMake() const
  3612. {
  3613. return this->GetState()->UseWatcomWMake();
  3614. }
  3615. bool cmLocalGenerator::IsMinGWMake() const
  3616. {
  3617. return this->GetState()->UseMinGWMake();
  3618. }
  3619. bool cmLocalGenerator::IsNMake() const
  3620. {
  3621. return this->GetState()->UseNMake();
  3622. }
  3623. bool cmLocalGenerator::IsNinjaMulti() const
  3624. {
  3625. return this->GetState()->UseNinjaMulti();
  3626. }
  3627. namespace {
  3628. std::string relativeIfUnder(std::string const& top, std::string const& cur,
  3629. std::string const& path)
  3630. {
  3631. // Use a path relative to 'cur' if it can be expressed without
  3632. // a `../` sequence that leaves 'top'.
  3633. if (cmSystemTools::IsSubDirectory(path, cur) ||
  3634. (cmSystemTools::IsSubDirectory(cur, top) &&
  3635. cmSystemTools::IsSubDirectory(path, top))) {
  3636. return cmSystemTools::ForceToRelativePath(cur, path);
  3637. }
  3638. return path;
  3639. }
  3640. }
  3641. std::string cmLocalGenerator::GetObjectFileNameWithoutTarget(
  3642. const cmSourceFile& source, std::string const& dir_max,
  3643. bool* hasSourceExtension, char const* customOutputExtension)
  3644. {
  3645. // Construct the object file name using the full path to the source
  3646. // file which is its only unique identification.
  3647. std::string const& fullPath = source.GetFullPath();
  3648. // Try referencing the source relative to the source tree.
  3649. std::string relFromSource = relativeIfUnder(
  3650. this->GetSourceDirectory(), this->GetCurrentSourceDirectory(), fullPath);
  3651. assert(!relFromSource.empty());
  3652. bool relSource = !cmSystemTools::FileIsFullPath(relFromSource);
  3653. bool subSource = relSource && relFromSource[0] != '.';
  3654. // Try referencing the source relative to the binary tree.
  3655. std::string relFromBinary = relativeIfUnder(
  3656. this->GetBinaryDirectory(), this->GetCurrentBinaryDirectory(), fullPath);
  3657. assert(!relFromBinary.empty());
  3658. bool relBinary = !cmSystemTools::FileIsFullPath(relFromBinary);
  3659. bool subBinary = relBinary && relFromBinary[0] != '.';
  3660. // Select a nice-looking reference to the source file to construct
  3661. // the object file name.
  3662. std::string objectName;
  3663. // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
  3664. // NOLINTNEXTLINE(bugprone-branch-clone)
  3665. if ((relSource && !relBinary) || (subSource && !subBinary)) {
  3666. objectName = relFromSource;
  3667. } else if ((relBinary && !relSource) || (subBinary && !subSource) ||
  3668. relFromBinary.length() < relFromSource.length()) {
  3669. objectName = relFromBinary;
  3670. } else {
  3671. objectName = relFromSource;
  3672. }
  3673. // if it is still a full path check for the try compile case
  3674. // try compile never have in source sources, and should not
  3675. // have conflicting source file names in the same target
  3676. if (cmSystemTools::FileIsFullPath(objectName)) {
  3677. if (this->GetGlobalGenerator()->GetCMakeInstance()->GetIsInTryCompile()) {
  3678. objectName = cmSystemTools::GetFilenameName(source.GetFullPath());
  3679. }
  3680. }
  3681. // Ensure that for the CMakeFiles/<target>.dir/generated_source_file
  3682. // we don't end up having:
  3683. // CMakeFiles/<target>.dir/CMakeFiles/<target>.dir/generated_source_file.obj
  3684. cmValue unitySourceFile = source.GetProperty("UNITY_SOURCE_FILE");
  3685. cmValue pchExtension = source.GetProperty("PCH_EXTENSION");
  3686. const bool isPchObject = objectName.find("cmake_pch") != std::string::npos;
  3687. if (unitySourceFile || pchExtension || isPchObject) {
  3688. if (pchExtension) {
  3689. customOutputExtension = pchExtension->c_str();
  3690. }
  3691. cmsys::RegularExpression var("(CMakeFiles/[^/]+.dir/)");
  3692. if (var.find(objectName)) {
  3693. objectName.erase(var.start(), var.end() - var.start());
  3694. }
  3695. }
  3696. // Replace the original source file extension with the object file
  3697. // extension.
  3698. bool keptSourceExtension = true;
  3699. if (!source.GetPropertyAsBool("KEEP_EXTENSION")) {
  3700. // Decide whether this language wants to replace the source
  3701. // extension with the object extension. For CMake 2.4
  3702. // compatibility do this by default.
  3703. bool replaceExt = this->NeedBackwardsCompatibility_2_4();
  3704. if (!replaceExt) {
  3705. std::string lang = source.GetLanguage();
  3706. if (!lang.empty()) {
  3707. replaceExt = this->Makefile->IsOn(
  3708. cmStrCat("CMAKE_", lang, "_OUTPUT_EXTENSION_REPLACE"));
  3709. }
  3710. }
  3711. // Remove the source extension if it is to be replaced.
  3712. if (replaceExt || customOutputExtension) {
  3713. keptSourceExtension = false;
  3714. std::string::size_type dot_pos = objectName.rfind('.');
  3715. if (dot_pos != std::string::npos) {
  3716. objectName = objectName.substr(0, dot_pos);
  3717. }
  3718. }
  3719. // Store the new extension.
  3720. if (customOutputExtension) {
  3721. objectName += customOutputExtension;
  3722. } else {
  3723. objectName += this->GlobalGenerator->GetLanguageOutputExtension(source);
  3724. }
  3725. }
  3726. if (hasSourceExtension) {
  3727. *hasSourceExtension = keptSourceExtension;
  3728. }
  3729. // Convert to a safe name.
  3730. return this->CreateSafeUniqueObjectFileName(objectName, dir_max);
  3731. }
  3732. std::string cmLocalGenerator::GetSourceFileLanguage(const cmSourceFile& source)
  3733. {
  3734. return source.GetLanguage();
  3735. }
  3736. cmake* cmLocalGenerator::GetCMakeInstance() const
  3737. {
  3738. return this->GlobalGenerator->GetCMakeInstance();
  3739. }
  3740. std::string const& cmLocalGenerator::GetSourceDirectory() const
  3741. {
  3742. return this->GetCMakeInstance()->GetHomeDirectory();
  3743. }
  3744. std::string const& cmLocalGenerator::GetBinaryDirectory() const
  3745. {
  3746. return this->GetCMakeInstance()->GetHomeOutputDirectory();
  3747. }
  3748. std::string const& cmLocalGenerator::GetCurrentBinaryDirectory() const
  3749. {
  3750. return this->StateSnapshot.GetDirectory().GetCurrentBinary();
  3751. }
  3752. std::string const& cmLocalGenerator::GetCurrentSourceDirectory() const
  3753. {
  3754. return this->StateSnapshot.GetDirectory().GetCurrentSource();
  3755. }
  3756. std::string cmLocalGenerator::GetTargetDirectory(
  3757. const cmGeneratorTarget* /*unused*/) const
  3758. {
  3759. cmSystemTools::Error("GetTargetDirectory"
  3760. " called on cmLocalGenerator");
  3761. return "";
  3762. }
  3763. KWIML_INT_uint64_t cmLocalGenerator::GetBackwardsCompatibility()
  3764. {
  3765. // The computed version may change until the project is fully
  3766. // configured.
  3767. if (!this->BackwardsCompatibilityFinal) {
  3768. unsigned int major = 0;
  3769. unsigned int minor = 0;
  3770. unsigned int patch = 0;
  3771. if (cmValue value =
  3772. this->Makefile->GetDefinition("CMAKE_BACKWARDS_COMPATIBILITY")) {
  3773. switch (sscanf(value->c_str(), "%u.%u.%u", &major, &minor, &patch)) {
  3774. case 2:
  3775. patch = 0;
  3776. break;
  3777. case 1:
  3778. minor = 0;
  3779. patch = 0;
  3780. break;
  3781. default:
  3782. break;
  3783. }
  3784. }
  3785. this->BackwardsCompatibility = CMake_VERSION_ENCODE(major, minor, patch);
  3786. this->BackwardsCompatibilityFinal = true;
  3787. }
  3788. return this->BackwardsCompatibility;
  3789. }
  3790. bool cmLocalGenerator::NeedBackwardsCompatibility_2_4()
  3791. {
  3792. // Check the policy to decide whether to pay attention to this
  3793. // variable.
  3794. switch (this->GetPolicyStatus(cmPolicies::CMP0001)) {
  3795. case cmPolicies::WARN:
  3796. // WARN is just OLD without warning because user code does not
  3797. // always affect whether this check is done.
  3798. CM_FALLTHROUGH;
  3799. case cmPolicies::OLD:
  3800. // Old behavior is to check the variable.
  3801. break;
  3802. case cmPolicies::NEW:
  3803. // New behavior is to ignore the variable.
  3804. case cmPolicies::REQUIRED_IF_USED:
  3805. case cmPolicies::REQUIRED_ALWAYS:
  3806. // This will never be the case because the only way to require
  3807. // the setting is to require the user to specify version policy
  3808. // 2.6 or higher. Once we add that requirement then this whole
  3809. // method can be removed anyway.
  3810. return false;
  3811. }
  3812. // Compatibility is needed if CMAKE_BACKWARDS_COMPATIBILITY is set
  3813. // equal to or lower than the given version.
  3814. KWIML_INT_uint64_t actual_compat = this->GetBackwardsCompatibility();
  3815. return (actual_compat && actual_compat <= CMake_VERSION_ENCODE(2, 4, 255));
  3816. }
  3817. cmPolicies::PolicyStatus cmLocalGenerator::GetPolicyStatus(
  3818. cmPolicies::PolicyID id) const
  3819. {
  3820. return this->Makefile->GetPolicyStatus(id);
  3821. }
  3822. bool cmLocalGenerator::CheckDefinition(std::string const& define) const
  3823. {
  3824. // Many compilers do not support -DNAME(arg)=sdf so we disable it.
  3825. std::string::size_type pos = define.find_first_of("(=");
  3826. if (pos != std::string::npos) {
  3827. if (define[pos] == '(') {
  3828. std::ostringstream e;
  3829. /* clang-format off */
  3830. e << "WARNING: Function-style preprocessor definitions may not be "
  3831. << "passed on the compiler command line because many compilers "
  3832. << "do not support it.\n"
  3833. << "CMake is dropping a preprocessor definition: " << define << "\n"
  3834. << "Consider defining the macro in a (configured) header file.\n";
  3835. /* clang-format on */
  3836. cmSystemTools::Message(e.str());
  3837. return false;
  3838. }
  3839. }
  3840. // Many compilers do not support # in the value so we disable it.
  3841. if (define.find_first_of('#') != std::string::npos) {
  3842. std::ostringstream e;
  3843. /* clang-format off */
  3844. e << "WARNING: Preprocessor definitions containing '#' may not be "
  3845. << "passed on the compiler command line because many compilers "
  3846. << "do not support it.\n"
  3847. << "CMake is dropping a preprocessor definition: " << define << "\n"
  3848. << "Consider defining the macro in a (configured) header file.\n";
  3849. /* clang-format on */
  3850. cmSystemTools::Message(e.str());
  3851. return false;
  3852. }
  3853. // Assume it is supported.
  3854. return true;
  3855. }
  3856. static void cmLGInfoProp(cmMakefile* mf, cmGeneratorTarget* target,
  3857. const std::string& prop)
  3858. {
  3859. if (cmValue val = target->GetProperty(prop)) {
  3860. mf->AddDefinition(prop, *val);
  3861. }
  3862. }
  3863. void cmLocalGenerator::GenerateAppleInfoPList(cmGeneratorTarget* target,
  3864. const std::string& targetName,
  3865. const std::string& fname)
  3866. {
  3867. // Find the Info.plist template.
  3868. cmValue in = target->GetProperty("MACOSX_BUNDLE_INFO_PLIST");
  3869. std::string inFile = cmNonempty(in) ? *in : "MacOSXBundleInfo.plist.in";
  3870. if (!cmSystemTools::FileIsFullPath(inFile)) {
  3871. std::string inMod = this->Makefile->GetModulesFile(inFile);
  3872. if (!inMod.empty()) {
  3873. inFile = inMod;
  3874. }
  3875. }
  3876. if (!cmSystemTools::FileExists(inFile, true)) {
  3877. std::ostringstream e;
  3878. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  3879. << "\" could not be found.";
  3880. cmSystemTools::Error(e.str());
  3881. return;
  3882. }
  3883. // Convert target properties to variables in an isolated makefile
  3884. // scope to configure the file. If properties are set they will
  3885. // override user make variables. If not the configuration will fall
  3886. // back to the directory-level values set by the user.
  3887. cmMakefile* mf = this->Makefile;
  3888. cmMakefile::ScopePushPop varScope(mf);
  3889. mf->AddDefinition("MACOSX_BUNDLE_EXECUTABLE_NAME", targetName);
  3890. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_INFO_STRING");
  3891. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_ICON_FILE");
  3892. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_GUI_IDENTIFIER");
  3893. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_LONG_VERSION_STRING");
  3894. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_NAME");
  3895. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_SHORT_VERSION_STRING");
  3896. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_VERSION");
  3897. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_COPYRIGHT");
  3898. mf->ConfigureFile(inFile, fname, false, false, false);
  3899. }
  3900. void cmLocalGenerator::GenerateFrameworkInfoPList(
  3901. cmGeneratorTarget* target, const std::string& targetName,
  3902. const std::string& fname)
  3903. {
  3904. // Find the Info.plist template.
  3905. cmValue in = target->GetProperty("MACOSX_FRAMEWORK_INFO_PLIST");
  3906. std::string inFile = cmNonempty(in) ? *in : "MacOSXFrameworkInfo.plist.in";
  3907. if (!cmSystemTools::FileIsFullPath(inFile)) {
  3908. std::string inMod = this->Makefile->GetModulesFile(inFile);
  3909. if (!inMod.empty()) {
  3910. inFile = inMod;
  3911. }
  3912. }
  3913. if (!cmSystemTools::FileExists(inFile, true)) {
  3914. std::ostringstream e;
  3915. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  3916. << "\" could not be found.";
  3917. cmSystemTools::Error(e.str());
  3918. return;
  3919. }
  3920. // Convert target properties to variables in an isolated makefile
  3921. // scope to configure the file. If properties are set they will
  3922. // override user make variables. If not the configuration will fall
  3923. // back to the directory-level values set by the user.
  3924. cmMakefile* mf = this->Makefile;
  3925. cmMakefile::ScopePushPop varScope(mf);
  3926. mf->AddDefinition("MACOSX_FRAMEWORK_NAME", targetName);
  3927. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_ICON_FILE");
  3928. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_IDENTIFIER");
  3929. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_SHORT_VERSION_STRING");
  3930. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_BUNDLE_NAME");
  3931. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_BUNDLE_VERSION");
  3932. mf->ConfigureFile(inFile, fname, false, false, false);
  3933. }
  3934. namespace {
  3935. cm::string_view CustomOutputRoleKeyword(cmLocalGenerator::OutputRole role)
  3936. {
  3937. return (role == cmLocalGenerator::OutputRole::Primary ? "OUTPUT"_s
  3938. : "BYPRODUCTS"_s);
  3939. }
  3940. void CreateGeneratedSource(cmLocalGenerator& lg, const std::string& output,
  3941. cmLocalGenerator::OutputRole role,
  3942. cmCommandOrigin origin,
  3943. const cmListFileBacktrace& lfbt)
  3944. {
  3945. if (cmGeneratorExpression::Find(output) != std::string::npos) {
  3946. lg.GetCMakeInstance()->IssueMessage(
  3947. MessageType::FATAL_ERROR,
  3948. "Generator expressions in custom command outputs are not implemented!",
  3949. lfbt);
  3950. return;
  3951. }
  3952. // Make sure the file will not be generated into the source
  3953. // directory during an out of source build.
  3954. if (!lg.GetMakefile()->CanIWriteThisFile(output)) {
  3955. lg.GetCMakeInstance()->IssueMessage(
  3956. MessageType::FATAL_ERROR,
  3957. cmStrCat(CustomOutputRoleKeyword(role), " path\n ", output,
  3958. "\nin a source directory as an output of custom command."),
  3959. lfbt);
  3960. return;
  3961. }
  3962. // Make sure the output file name has no invalid characters.
  3963. const bool hashNotAllowed = lg.GetState()->UseBorlandMake();
  3964. std::string::size_type pos = output.find_first_of("<>");
  3965. if (pos == std::string::npos && hashNotAllowed) {
  3966. pos = output.find_first_of('#');
  3967. }
  3968. if (pos != std::string::npos) {
  3969. lg.GetCMakeInstance()->IssueMessage(
  3970. MessageType::FATAL_ERROR,
  3971. cmStrCat(CustomOutputRoleKeyword(role), " containing a \"", output[pos],
  3972. "\" is not allowed."),
  3973. lfbt);
  3974. return;
  3975. }
  3976. // Outputs without generator expressions from the project are already
  3977. // created and marked as generated. Do not mark them again, because
  3978. // other commands might have overwritten the property.
  3979. if (origin == cmCommandOrigin::Generator) {
  3980. lg.GetMakefile()->GetOrCreateGeneratedSource(output);
  3981. }
  3982. }
  3983. std::string ComputeCustomCommandRuleFileName(cmLocalGenerator& lg,
  3984. cmListFileBacktrace const& bt,
  3985. std::string const& output)
  3986. {
  3987. // If the output path has no generator expressions, use it directly.
  3988. if (cmGeneratorExpression::Find(output) == std::string::npos) {
  3989. return output;
  3990. }
  3991. // The output path contains a generator expression, but we must choose
  3992. // a single source file path to which to attach the custom command.
  3993. // Use some heuristics to provide a nice-looking name when possible.
  3994. // If the only genex is $<CONFIG>, replace that gracefully.
  3995. {
  3996. std::string simple = output;
  3997. cmSystemTools::ReplaceString(simple, "$<CONFIG>", "(CONFIG)");
  3998. if (cmGeneratorExpression::Find(simple) == std::string::npos) {
  3999. return simple;
  4000. }
  4001. }
  4002. // If the genex evaluates to the same value in all configurations, use that.
  4003. {
  4004. std::vector<std::string> allConfigOutputs =
  4005. lg.ExpandCustomCommandOutputGenex(output, bt);
  4006. if (allConfigOutputs.size() == 1) {
  4007. return allConfigOutputs.front();
  4008. }
  4009. }
  4010. // Fall back to a deterministic unique name.
  4011. cmCryptoHash h(cmCryptoHash::AlgoSHA256);
  4012. return cmStrCat(lg.GetCurrentBinaryDirectory(), "/CMakeFiles/",
  4013. h.HashString(output).substr(0, 16));
  4014. }
  4015. cmSourceFile* AddCustomCommand(cmLocalGenerator& lg, cmCommandOrigin origin,
  4016. std::unique_ptr<cmCustomCommand> cc,
  4017. bool replace)
  4018. {
  4019. cmMakefile* mf = lg.GetMakefile();
  4020. const auto& lfbt = cc->GetBacktrace();
  4021. const auto& outputs = cc->GetOutputs();
  4022. const auto& byproducts = cc->GetByproducts();
  4023. const auto& commandLines = cc->GetCommandLines();
  4024. // Choose a source file on which to store the custom command.
  4025. cmSourceFile* file = nullptr;
  4026. if (!commandLines.empty() && cc->HasMainDependency()) {
  4027. const auto& main_dependency = cc->GetMainDependency();
  4028. // The main dependency was specified. Use it unless a different
  4029. // custom command already used it.
  4030. file = mf->GetSource(main_dependency);
  4031. if (file && file->GetCustomCommand() && !replace) {
  4032. // The main dependency already has a custom command.
  4033. if (commandLines == file->GetCustomCommand()->GetCommandLines()) {
  4034. // The existing custom command is identical. Silently ignore
  4035. // the duplicate.
  4036. return file;
  4037. }
  4038. // The existing custom command is different. We need to
  4039. // generate a rule file for this new command.
  4040. file = nullptr;
  4041. } else if (!file) {
  4042. file = mf->CreateSource(main_dependency);
  4043. }
  4044. }
  4045. // Generate a rule file if the main dependency is not available.
  4046. if (!file) {
  4047. cmGlobalGenerator* gg = lg.GetGlobalGenerator();
  4048. // Construct a rule file associated with the first output produced.
  4049. std::string outName = gg->GenerateRuleFile(
  4050. ComputeCustomCommandRuleFileName(lg, lfbt, outputs[0]));
  4051. // Check if the rule file already exists.
  4052. file = mf->GetSource(outName, cmSourceFileLocationKind::Known);
  4053. if (file && file->GetCustomCommand() && !replace) {
  4054. // The rule file already exists.
  4055. if (commandLines != file->GetCustomCommand()->GetCommandLines()) {
  4056. lg.GetCMakeInstance()->IssueMessage(
  4057. MessageType::FATAL_ERROR,
  4058. cmStrCat("Attempt to add a custom rule to output\n ", outName,
  4059. "\nwhich already has a custom rule."),
  4060. lfbt);
  4061. }
  4062. return file;
  4063. }
  4064. // Create a cmSourceFile for the rule file.
  4065. if (!file) {
  4066. file = mf->CreateSource(outName, true, cmSourceFileLocationKind::Known);
  4067. }
  4068. file->SetProperty("__CMAKE_RULE", "1");
  4069. }
  4070. // Attach the custom command to the file.
  4071. if (file) {
  4072. cc->SetEscapeAllowMakeVars(true);
  4073. lg.AddSourceOutputs(file, outputs, cmLocalGenerator::OutputRole::Primary,
  4074. lfbt, origin);
  4075. lg.AddSourceOutputs(file, byproducts,
  4076. cmLocalGenerator::OutputRole::Byproduct, lfbt, origin);
  4077. file->SetCustomCommand(std::move(cc));
  4078. }
  4079. return file;
  4080. }
  4081. bool AnyOutputMatches(const std::string& name,
  4082. const std::vector<std::string>& outputs)
  4083. {
  4084. return std::any_of(outputs.begin(), outputs.end(),
  4085. [&name](std::string const& output) -> bool {
  4086. std::string::size_type pos = output.rfind(name);
  4087. // If the output matches exactly
  4088. return (pos != std::string::npos &&
  4089. pos == output.size() - name.size() &&
  4090. (pos == 0 || output[pos - 1] == '/'));
  4091. });
  4092. }
  4093. bool AnyTargetCommandOutputMatches(
  4094. const std::string& name, const std::vector<cmCustomCommand>& commands)
  4095. {
  4096. return std::any_of(commands.begin(), commands.end(),
  4097. [&name](cmCustomCommand const& command) -> bool {
  4098. return AnyOutputMatches(name, command.GetByproducts());
  4099. });
  4100. }
  4101. }
  4102. namespace detail {
  4103. void AddCustomCommandToTarget(cmLocalGenerator& lg, cmCommandOrigin origin,
  4104. cmTarget* target, cmCustomCommandType type,
  4105. std::unique_ptr<cmCustomCommand> cc)
  4106. {
  4107. // Add the command to the appropriate build step for the target.
  4108. cc->SetEscapeAllowMakeVars(true);
  4109. cc->SetTarget(target->GetName());
  4110. lg.AddTargetByproducts(target, cc->GetByproducts(), cc->GetBacktrace(),
  4111. origin);
  4112. switch (type) {
  4113. case cmCustomCommandType::PRE_BUILD:
  4114. target->AddPreBuildCommand(std::move(*cc));
  4115. break;
  4116. case cmCustomCommandType::PRE_LINK:
  4117. target->AddPreLinkCommand(std::move(*cc));
  4118. break;
  4119. case cmCustomCommandType::POST_BUILD:
  4120. target->AddPostBuildCommand(std::move(*cc));
  4121. break;
  4122. }
  4123. cc.reset();
  4124. }
  4125. cmSourceFile* AddCustomCommandToOutput(cmLocalGenerator& lg,
  4126. cmCommandOrigin origin,
  4127. std::unique_ptr<cmCustomCommand> cc,
  4128. bool replace)
  4129. {
  4130. return AddCustomCommand(lg, origin, std::move(cc), replace);
  4131. }
  4132. void AppendCustomCommandToOutput(cmLocalGenerator& lg,
  4133. const cmListFileBacktrace& lfbt,
  4134. const std::string& output,
  4135. const std::vector<std::string>& depends,
  4136. const cmImplicitDependsList& implicit_depends,
  4137. const cmCustomCommandLines& commandLines)
  4138. {
  4139. // Lookup an existing command.
  4140. cmSourceFile* sf = nullptr;
  4141. if (cmGeneratorExpression::Find(output) == std::string::npos) {
  4142. sf = lg.GetSourceFileWithOutput(output);
  4143. } else {
  4144. // This output path has a generator expression. Evaluate it to
  4145. // find the output for any configurations.
  4146. for (std::string const& out :
  4147. lg.ExpandCustomCommandOutputGenex(output, lfbt)) {
  4148. sf = lg.GetSourceFileWithOutput(out);
  4149. if (sf) {
  4150. break;
  4151. }
  4152. }
  4153. }
  4154. if (sf) {
  4155. if (cmCustomCommand* cc = sf->GetCustomCommand()) {
  4156. cc->AppendCommands(commandLines);
  4157. cc->AppendDepends(depends);
  4158. if (cc->GetCodegen() && !implicit_depends.empty()) {
  4159. lg.GetCMakeInstance()->IssueMessage(
  4160. MessageType::FATAL_ERROR,
  4161. "Cannot append IMPLICIT_DEPENDS to existing CODEGEN custom "
  4162. "command.");
  4163. }
  4164. cc->AppendImplicitDepends(implicit_depends);
  4165. return;
  4166. }
  4167. }
  4168. // No existing command found.
  4169. lg.GetCMakeInstance()->IssueMessage(
  4170. MessageType::FATAL_ERROR,
  4171. cmStrCat("Attempt to APPEND to custom command with output\n ", output,
  4172. "\nwhich is not already a custom command output."),
  4173. lfbt);
  4174. }
  4175. void AddUtilityCommand(cmLocalGenerator& lg, cmCommandOrigin origin,
  4176. cmTarget* target, std::unique_ptr<cmCustomCommand> cc)
  4177. {
  4178. // They might be moved away
  4179. auto byproducts = cc->GetByproducts();
  4180. auto lfbt = cc->GetBacktrace();
  4181. // Use an empty comment to avoid generation of default comment.
  4182. if (!cc->GetComment()) {
  4183. cc->SetComment("");
  4184. }
  4185. // Create the generated symbolic output name of the utility target.
  4186. std::string output =
  4187. lg.CreateUtilityOutput(target->GetName(), byproducts, lfbt);
  4188. cc->SetOutputs(output);
  4189. cmSourceFile* rule = AddCustomCommand(lg, origin, std::move(cc),
  4190. /*replace=*/false);
  4191. if (rule) {
  4192. lg.AddTargetByproducts(target, byproducts, lfbt, origin);
  4193. }
  4194. target->AddSource(output);
  4195. }
  4196. std::vector<std::string> ComputeISPCObjectSuffixes(cmGeneratorTarget* target)
  4197. {
  4198. const cmValue targetProperty = target->GetProperty("ISPC_INSTRUCTION_SETS");
  4199. cmList ispcTargets;
  4200. if (!targetProperty.IsOff()) {
  4201. ispcTargets.assign(targetProperty);
  4202. for (auto& ispcTarget : ispcTargets) {
  4203. // transform targets into the suffixes
  4204. auto pos = ispcTarget.find('-');
  4205. auto target_suffix = ispcTarget.substr(0, pos);
  4206. if (target_suffix ==
  4207. "avx1") { // when targeting avx1 ISPC uses the 'avx' output string
  4208. target_suffix = "avx";
  4209. }
  4210. ispcTarget = target_suffix;
  4211. }
  4212. }
  4213. return std::move(ispcTargets.data());
  4214. }
  4215. std::vector<std::string> ComputeISPCExtraObjects(
  4216. std::string const& objectName, std::string const& buildDirectory,
  4217. std::vector<std::string> const& ispcSuffixes)
  4218. {
  4219. auto normalizedDir = cmSystemTools::CollapseFullPath(buildDirectory);
  4220. std::vector<std::string> computedObjects;
  4221. computedObjects.reserve(ispcSuffixes.size());
  4222. auto extension = cmSystemTools::GetFilenameLastExtension(objectName);
  4223. // We can't use cmSystemTools::GetFilenameWithoutLastExtension as it
  4224. // drops any directories in objectName
  4225. auto objNameNoExt = objectName;
  4226. std::string::size_type dot_pos = objectName.rfind('.');
  4227. if (dot_pos != std::string::npos) {
  4228. objNameNoExt.resize(dot_pos);
  4229. }
  4230. for (const auto& ispcTarget : ispcSuffixes) {
  4231. computedObjects.emplace_back(
  4232. cmStrCat(normalizedDir, "/", objNameNoExt, "_", ispcTarget, extension));
  4233. }
  4234. return computedObjects;
  4235. }
  4236. }
  4237. cmSourcesWithOutput cmLocalGenerator::GetSourcesWithOutput(
  4238. const std::string& name) const
  4239. {
  4240. // Linear search? Also see GetSourceFileWithOutput for detail.
  4241. if (!cmSystemTools::FileIsFullPath(name)) {
  4242. cmSourcesWithOutput sources;
  4243. sources.Target = this->LinearGetTargetWithOutput(name);
  4244. sources.Source = this->LinearGetSourceFileWithOutput(
  4245. name, cmSourceOutputKind::OutputOrByproduct, sources.SourceIsByproduct);
  4246. return sources;
  4247. }
  4248. // Otherwise we use an efficient lookup map.
  4249. auto o = this->OutputToSource.find(name);
  4250. if (o != this->OutputToSource.end()) {
  4251. return o->second.Sources;
  4252. }
  4253. return {};
  4254. }
  4255. cmSourceFile* cmLocalGenerator::GetSourceFileWithOutput(
  4256. const std::string& name, cmSourceOutputKind kind) const
  4257. {
  4258. // If the queried path is not absolute we use the backward compatible
  4259. // linear-time search for an output with a matching suffix.
  4260. if (!cmSystemTools::FileIsFullPath(name)) {
  4261. bool byproduct = false;
  4262. return this->LinearGetSourceFileWithOutput(name, kind, byproduct);
  4263. }
  4264. // Otherwise we use an efficient lookup map.
  4265. auto o = this->OutputToSource.find(name);
  4266. if (o != this->OutputToSource.end() &&
  4267. (!o->second.Sources.SourceIsByproduct ||
  4268. kind == cmSourceOutputKind::OutputOrByproduct)) {
  4269. // Source file could also be null pointer for example if we found the
  4270. // byproduct of a utility target, a PRE_BUILD, PRE_LINK, or POST_BUILD
  4271. // command of a target, or a not yet created custom command.
  4272. return o->second.Sources.Source;
  4273. }
  4274. return nullptr;
  4275. }
  4276. std::string cmLocalGenerator::CreateUtilityOutput(
  4277. std::string const& targetName, std::vector<std::string> const&,
  4278. cmListFileBacktrace const&)
  4279. {
  4280. std::string force =
  4281. cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles/", targetName);
  4282. // The output is not actually created so mark it symbolic.
  4283. if (cmSourceFile* sf = this->Makefile->GetOrCreateGeneratedSource(force)) {
  4284. sf->SetProperty("SYMBOLIC", "1");
  4285. } else {
  4286. cmSystemTools::Error("Could not get source file entry for " + force);
  4287. }
  4288. return force;
  4289. }
  4290. std::vector<cmCustomCommandGenerator>
  4291. cmLocalGenerator::MakeCustomCommandGenerators(cmCustomCommand const& cc,
  4292. std::string const& config)
  4293. {
  4294. std::vector<cmCustomCommandGenerator> ccgs;
  4295. ccgs.emplace_back(cc, config, this);
  4296. return ccgs;
  4297. }
  4298. std::vector<std::string> cmLocalGenerator::ExpandCustomCommandOutputPaths(
  4299. cmCompiledGeneratorExpression const& cge, std::string const& config)
  4300. {
  4301. cmList paths{ cge.Evaluate(this, config) };
  4302. for (std::string& p : paths) {
  4303. p = cmSystemTools::CollapseFullPath(p, this->GetCurrentBinaryDirectory());
  4304. }
  4305. return std::move(paths.data());
  4306. }
  4307. std::vector<std::string> cmLocalGenerator::ExpandCustomCommandOutputGenex(
  4308. std::string const& o, cmListFileBacktrace const& bt)
  4309. {
  4310. std::vector<std::string> allConfigOutputs;
  4311. cmGeneratorExpression ge(*this->GetCMakeInstance(), bt);
  4312. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(o);
  4313. std::vector<std::string> configs =
  4314. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  4315. for (std::string const& config : configs) {
  4316. std::vector<std::string> configOutputs =
  4317. this->ExpandCustomCommandOutputPaths(*cge, config);
  4318. allConfigOutputs.reserve(allConfigOutputs.size() + configOutputs.size());
  4319. std::move(configOutputs.begin(), configOutputs.end(),
  4320. std::back_inserter(allConfigOutputs));
  4321. }
  4322. auto endUnique =
  4323. cmRemoveDuplicates(allConfigOutputs.begin(), allConfigOutputs.end());
  4324. allConfigOutputs.erase(endUnique, allConfigOutputs.end());
  4325. return allConfigOutputs;
  4326. }
  4327. void cmLocalGenerator::AddTargetByproducts(
  4328. cmTarget* target, const std::vector<std::string>& byproducts,
  4329. cmListFileBacktrace const& bt, cmCommandOrigin origin)
  4330. {
  4331. for (std::string const& o : byproducts) {
  4332. if (cmGeneratorExpression::Find(o) == std::string::npos) {
  4333. this->UpdateOutputToSourceMap(o, target, bt, origin);
  4334. continue;
  4335. }
  4336. // This byproduct path has a generator expression. Evaluate it to
  4337. // register the byproducts for all configurations.
  4338. for (std::string const& b : this->ExpandCustomCommandOutputGenex(o, bt)) {
  4339. this->UpdateOutputToSourceMap(b, target, bt, cmCommandOrigin::Generator);
  4340. }
  4341. }
  4342. }
  4343. void cmLocalGenerator::AddSourceOutputs(
  4344. cmSourceFile* source, const std::vector<std::string>& outputs,
  4345. OutputRole role, cmListFileBacktrace const& bt, cmCommandOrigin origin)
  4346. {
  4347. for (std::string const& o : outputs) {
  4348. if (cmGeneratorExpression::Find(o) == std::string::npos) {
  4349. this->UpdateOutputToSourceMap(o, source, role, bt, origin);
  4350. continue;
  4351. }
  4352. // This output path has a generator expression. Evaluate it to
  4353. // register the outputs for all configurations.
  4354. for (std::string const& out :
  4355. this->ExpandCustomCommandOutputGenex(o, bt)) {
  4356. this->UpdateOutputToSourceMap(out, source, role, bt,
  4357. cmCommandOrigin::Generator);
  4358. }
  4359. }
  4360. }
  4361. void cmLocalGenerator::UpdateOutputToSourceMap(std::string const& byproduct,
  4362. cmTarget* target,
  4363. cmListFileBacktrace const& bt,
  4364. cmCommandOrigin origin)
  4365. {
  4366. SourceEntry entry;
  4367. entry.Sources.Target = target;
  4368. auto pr = this->OutputToSource.emplace(byproduct, entry);
  4369. if (pr.second) {
  4370. CreateGeneratedSource(*this, byproduct, OutputRole::Byproduct, origin, bt);
  4371. } else {
  4372. SourceEntry& current = pr.first->second;
  4373. // Has the target already been set?
  4374. if (!current.Sources.Target) {
  4375. current.Sources.Target = target;
  4376. } else {
  4377. // Multiple custom commands/targets produce the same output (source file
  4378. // or target). See also comment in other UpdateOutputToSourceMap
  4379. // overload.
  4380. //
  4381. // TODO: Warn the user about this case.
  4382. }
  4383. }
  4384. }
  4385. void cmLocalGenerator::UpdateOutputToSourceMap(std::string const& output,
  4386. cmSourceFile* source,
  4387. OutputRole role,
  4388. cmListFileBacktrace const& bt,
  4389. cmCommandOrigin origin)
  4390. {
  4391. SourceEntry entry;
  4392. entry.Sources.Source = source;
  4393. entry.Sources.SourceIsByproduct = role == OutputRole::Byproduct;
  4394. auto pr = this->OutputToSource.emplace(output, entry);
  4395. if (pr.second) {
  4396. CreateGeneratedSource(*this, output, role, origin, bt);
  4397. } else {
  4398. SourceEntry& current = pr.first->second;
  4399. // Outputs take precedence over byproducts
  4400. if (!current.Sources.Source ||
  4401. (current.Sources.SourceIsByproduct && role == OutputRole::Primary)) {
  4402. current.Sources.Source = source;
  4403. current.Sources.SourceIsByproduct = false;
  4404. } else {
  4405. // Multiple custom commands produce the same output but may
  4406. // be attached to a different source file (MAIN_DEPENDENCY).
  4407. // LinearGetSourceFileWithOutput would return the first one,
  4408. // so keep the mapping for the first one.
  4409. //
  4410. // TODO: Warn the user about this case. However, the VS 8 generator
  4411. // triggers it for separate generate.stamp rules in ZERO_CHECK and
  4412. // individual targets.
  4413. }
  4414. }
  4415. }
  4416. cmTarget* cmLocalGenerator::LinearGetTargetWithOutput(
  4417. const std::string& name) const
  4418. {
  4419. // We go through the ordered vector of targets to get reproducible results
  4420. // should multiple names match.
  4421. for (cmTarget* t : this->Makefile->GetOrderedTargets()) {
  4422. // Does the output of any command match the source file name?
  4423. if (AnyTargetCommandOutputMatches(name, t->GetPreBuildCommands())) {
  4424. return t;
  4425. }
  4426. if (AnyTargetCommandOutputMatches(name, t->GetPreLinkCommands())) {
  4427. return t;
  4428. }
  4429. if (AnyTargetCommandOutputMatches(name, t->GetPostBuildCommands())) {
  4430. return t;
  4431. }
  4432. }
  4433. return nullptr;
  4434. }
  4435. cmSourceFile* cmLocalGenerator::LinearGetSourceFileWithOutput(
  4436. const std::string& name, cmSourceOutputKind kind, bool& byproduct) const
  4437. {
  4438. // Outputs take precedence over byproducts.
  4439. byproduct = false;
  4440. cmSourceFile* fallback = nullptr;
  4441. // Look through all the source files that have custom commands and see if the
  4442. // custom command has the passed source file as an output.
  4443. for (const auto& src : this->Makefile->GetSourceFiles()) {
  4444. // Does this source file have a custom command?
  4445. if (src->GetCustomCommand()) {
  4446. // Does the output of the custom command match the source file name?
  4447. if (AnyOutputMatches(name, src->GetCustomCommand()->GetOutputs())) {
  4448. // Return the first matching output.
  4449. return src.get();
  4450. }
  4451. if (kind == cmSourceOutputKind::OutputOrByproduct) {
  4452. if (AnyOutputMatches(name, src->GetCustomCommand()->GetByproducts())) {
  4453. // Do not return the source yet as there might be a matching output.
  4454. fallback = src.get();
  4455. }
  4456. }
  4457. }
  4458. }
  4459. // Did we find a byproduct?
  4460. byproduct = fallback != nullptr;
  4461. return fallback;
  4462. }