cmLocalGenerator.cxx 166 KB

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