cmGlobalXCodeGenerator.cxx 199 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file LICENSE.rst or https://cmake.org/licensing for details. */
  3. #include "cmGlobalXCodeGenerator.h"
  4. #include <algorithm>
  5. #include <cassert>
  6. #include <cstdio>
  7. #include <cstring>
  8. #include <functional>
  9. #include <iomanip>
  10. #include <sstream>
  11. #include <unordered_set>
  12. #include <utility>
  13. #include <cm/memory>
  14. #include <cm/optional>
  15. #include <cm/string_view>
  16. #include <cmext/algorithm>
  17. #include <cmext/string_view>
  18. #include "cmsys/RegularExpression.hxx"
  19. #include "cmComputeLinkInformation.h"
  20. #include "cmCryptoHash.h"
  21. #include "cmCustomCommand.h"
  22. #include "cmCustomCommandGenerator.h"
  23. #include "cmCustomCommandLines.h"
  24. #include "cmCustomCommandTypes.h"
  25. #include "cmGeneratedFileStream.h"
  26. #include "cmGeneratorExpression.h"
  27. #include "cmGeneratorOptions.h"
  28. #include "cmGeneratorTarget.h"
  29. #include "cmGlobalGeneratorFactory.h"
  30. #include "cmLinkItem.h"
  31. #include "cmList.h"
  32. #include "cmListFileCache.h"
  33. #include "cmLocalGenerator.h"
  34. #include "cmLocalXCodeGenerator.h"
  35. #include "cmMakefile.h"
  36. #include "cmMessageType.h"
  37. #include "cmOutputConverter.h"
  38. #include "cmPolicies.h"
  39. #include "cmSourceFile.h"
  40. #include "cmSourceFileLocation.h"
  41. #include "cmSourceFileLocationKind.h"
  42. #include "cmSourceGroup.h"
  43. #include "cmState.h"
  44. #include "cmStateSnapshot.h"
  45. #include "cmStateTypes.h"
  46. #include "cmStringAlgorithms.h"
  47. #include "cmSystemTools.h"
  48. #include "cmTarget.h"
  49. #include "cmTargetDepend.h"
  50. #include "cmXCode21Object.h"
  51. #include "cmXCodeObject.h"
  52. #include "cmXCodeScheme.h"
  53. #include "cmXMLWriter.h"
  54. #include "cmXcFramework.h"
  55. #include "cmake.h"
  56. #if !defined(CMAKE_BOOTSTRAP) && defined(__APPLE__)
  57. # include <CoreFoundation/CFBundle.h>
  58. # include <CoreFoundation/CFString.h>
  59. # include <CoreFoundation/CFURL.h>
  60. # include <CoreFoundation/CFUUID.h>
  61. # if !TARGET_OS_IPHONE
  62. # define HAVE_APPLICATION_SERVICES
  63. # include <ApplicationServices/ApplicationServices.h>
  64. # endif
  65. #endif
  66. #if !defined(CMAKE_BOOTSTRAP)
  67. # include "cmXMLParser.h"
  68. // parse the xml file storing the installed version of Xcode on
  69. // the machine
  70. class cmXcodeVersionParser : public cmXMLParser
  71. {
  72. public:
  73. cmXcodeVersionParser()
  74. : Version("1.5")
  75. {
  76. }
  77. void StartElement(std::string const&, char const**) override
  78. {
  79. this->Data = "";
  80. }
  81. void EndElement(std::string const& name) override
  82. {
  83. if (name == "key"_s) {
  84. this->Key = this->Data;
  85. } else if (name == "string"_s) {
  86. if (this->Key == "CFBundleShortVersionString"_s) {
  87. this->Version = this->Data;
  88. }
  89. }
  90. }
  91. void CharacterDataHandler(char const* data, int length) override
  92. {
  93. this->Data.append(data, length);
  94. }
  95. std::string Version;
  96. std::string Key;
  97. std::string Data;
  98. };
  99. #endif
  100. // Builds either an object list or a space-separated string from the
  101. // given inputs.
  102. class cmGlobalXCodeGenerator::BuildObjectListOrString
  103. {
  104. cmGlobalXCodeGenerator* Generator;
  105. cmXCodeObject* Group = nullptr;
  106. bool Empty = true;
  107. std::string String;
  108. public:
  109. BuildObjectListOrString(cmGlobalXCodeGenerator* gen, bool buildObjectList)
  110. : Generator(gen)
  111. {
  112. if (buildObjectList) {
  113. this->Group = this->Generator->CreateObject(cmXCodeObject::OBJECT_LIST);
  114. }
  115. }
  116. bool IsEmpty() const { return this->Empty; }
  117. void Add(std::string const& newString)
  118. {
  119. this->Empty = false;
  120. if (this->Group) {
  121. this->Group->AddObject(this->Generator->CreateString(newString));
  122. } else {
  123. this->String += newString;
  124. this->String += ' ';
  125. }
  126. }
  127. std::string const& GetString() const { return this->String; }
  128. cmXCodeObject* CreateList()
  129. {
  130. if (this->Group) {
  131. return this->Group;
  132. }
  133. return this->Generator->CreateString(this->String);
  134. }
  135. };
  136. class cmGlobalXCodeGenerator::Factory : public cmGlobalGeneratorFactory
  137. {
  138. public:
  139. std::unique_ptr<cmGlobalGenerator> CreateGlobalGenerator(
  140. std::string const& name, cmake* cm) const override;
  141. cmDocumentationEntry GetDocumentation() const override
  142. {
  143. return cmGlobalXCodeGenerator::GetDocumentation();
  144. }
  145. std::vector<std::string> GetGeneratorNames() const override
  146. {
  147. std::vector<std::string> names;
  148. names.push_back(cmGlobalXCodeGenerator::GetActualName());
  149. return names;
  150. }
  151. bool SupportsToolset() const override { return true; }
  152. bool SupportsPlatform() const override { return false; }
  153. std::vector<std::string> GetKnownPlatforms() const override
  154. {
  155. return std::vector<std::string>();
  156. }
  157. std::string GetDefaultPlatformName() const override { return std::string(); }
  158. };
  159. cmGlobalXCodeGenerator::cmGlobalXCodeGenerator(
  160. cmake* cm, std::string const& version_string, unsigned int version_number)
  161. : cmGlobalGenerator(cm)
  162. {
  163. this->VersionString = version_string;
  164. this->XcodeVersion = version_number;
  165. if (this->XcodeVersion >= 120) {
  166. this->XcodeBuildSystem = BuildSystem::Twelve;
  167. } else {
  168. this->XcodeBuildSystem = BuildSystem::One;
  169. }
  170. this->RootObject = nullptr;
  171. this->MainGroupChildren = nullptr;
  172. this->FrameworkGroup = nullptr;
  173. this->CurrentMakefile = nullptr;
  174. this->CurrentLocalGenerator = nullptr;
  175. this->XcodeBuildCommandInitialized = false;
  176. this->ObjectDirArchDefault = "$(CURRENT_ARCH)";
  177. this->ObjectDirArch = this->ObjectDirArchDefault;
  178. cm->GetState()->SetIsGeneratorMultiConfig(true);
  179. }
  180. std::unique_ptr<cmGlobalGeneratorFactory> cmGlobalXCodeGenerator::NewFactory()
  181. {
  182. return std::unique_ptr<cmGlobalGeneratorFactory>(new Factory);
  183. }
  184. std::unique_ptr<cmGlobalGenerator>
  185. cmGlobalXCodeGenerator::Factory::CreateGlobalGenerator(std::string const& name,
  186. cmake* cm) const
  187. {
  188. if (name != GetActualName()) {
  189. return std::unique_ptr<cmGlobalGenerator>();
  190. }
  191. #if !defined(CMAKE_BOOTSTRAP)
  192. cmXcodeVersionParser parser;
  193. std::string versionFile;
  194. {
  195. std::string out;
  196. bool commandResult = cmSystemTools::RunSingleCommand(
  197. "xcode-select --print-path", &out, nullptr, nullptr, nullptr,
  198. cmSystemTools::OUTPUT_NONE);
  199. if (commandResult) {
  200. std::string::size_type pos = out.find(".app/");
  201. if (pos != std::string::npos) {
  202. versionFile =
  203. cmStrCat(out.substr(0, pos + 5), "Contents/version.plist");
  204. }
  205. }
  206. }
  207. if (!versionFile.empty() && cmSystemTools::FileExists(versionFile)) {
  208. parser.ParseFile(versionFile.c_str());
  209. } else if (cmSystemTools::FileExists(
  210. "/Applications/Xcode.app/Contents/version.plist")) {
  211. parser.ParseFile("/Applications/Xcode.app/Contents/version.plist");
  212. } else {
  213. parser.ParseFile(
  214. "/Developer/Applications/Xcode.app/Contents/version.plist");
  215. }
  216. std::string const& version_string = parser.Version;
  217. // Compute an integer form of the version number.
  218. unsigned int v[2] = { 0, 0 };
  219. sscanf(version_string.c_str(), "%u.%u", &v[0], &v[1]);
  220. unsigned int version_number = 10 * v[0] + v[1];
  221. if (version_number < 50) {
  222. cm->IssueMessage(MessageType::FATAL_ERROR,
  223. cmStrCat("Xcode ", version_string, " not supported."));
  224. return std::unique_ptr<cmGlobalGenerator>();
  225. }
  226. return std::unique_ptr<cmGlobalGenerator>(
  227. cm::make_unique<cmGlobalXCodeGenerator>(cm, version_string,
  228. version_number));
  229. #else
  230. std::cerr << "CMake should be built with cmake to use Xcode, "
  231. "default to Xcode 1.5\n";
  232. return std::unique_ptr<cmGlobalGenerator>(
  233. cm::make_unique<cmGlobalXCodeGenerator>(cm));
  234. #endif
  235. }
  236. namespace {
  237. std::string ConvertToMakefilePath(std::string const& path)
  238. {
  239. std::string result;
  240. result.reserve(path.size());
  241. for (char c : path) {
  242. switch (c) {
  243. case '\\':
  244. case ' ':
  245. case '#':
  246. result.push_back('\\');
  247. CM_FALLTHROUGH;
  248. default:
  249. result.push_back(c);
  250. break;
  251. }
  252. }
  253. return result;
  254. }
  255. }
  256. bool cmGlobalXCodeGenerator::FindMakeProgram(cmMakefile* mf)
  257. {
  258. // The Xcode generator knows how to lookup its build tool
  259. // directly instead of needing a helper module to do it, so we
  260. // do not actually need to put CMAKE_MAKE_PROGRAM into the cache.
  261. if (mf->GetDefinition("CMAKE_MAKE_PROGRAM").IsOff()) {
  262. mf->AddDefinition("CMAKE_MAKE_PROGRAM", this->GetXcodeBuildCommand());
  263. }
  264. return true;
  265. }
  266. std::string cmGlobalXCodeGenerator::GetAppleSpecificPlatformName()
  267. {
  268. std::string sdkRoot =
  269. this->GetCMakeInstance()->GetState()->GetCacheEntryValue(
  270. "CMAKE_OSX_SYSROOT");
  271. sdkRoot = cmSystemTools::LowerCase(sdkRoot);
  272. struct SdkDatabaseEntry
  273. {
  274. cm::string_view Name;
  275. cm::string_view AppleName;
  276. };
  277. std::array<SdkDatabaseEntry, 6> const sdkDatabase{ {
  278. { "appletvos"_s, "tvOS"_s },
  279. { "appletvsimulator"_s, "tvOS Simulator"_s },
  280. { "iphoneos"_s, "iOS"_s },
  281. { "iphonesimulator"_s, "iOS Simulator"_s },
  282. { "watchos"_s, "watchOS"_s },
  283. { "watchsimulator"_s, "watchOS Simulator"_s },
  284. } };
  285. cm::string_view platformName = "MacOS"_s;
  286. for (SdkDatabaseEntry const& entry : sdkDatabase) {
  287. if (cmHasPrefix(sdkRoot, entry.Name) ||
  288. sdkRoot.find(cmStrCat('/', entry.Name)) != std::string::npos) {
  289. platformName = entry.AppleName;
  290. break;
  291. }
  292. }
  293. return std::string(platformName);
  294. }
  295. std::string const& cmGlobalXCodeGenerator::GetXcodeBuildCommand()
  296. {
  297. if (!this->XcodeBuildCommandInitialized) {
  298. this->XcodeBuildCommandInitialized = true;
  299. this->XcodeBuildCommand = this->FindXcodeBuildCommand();
  300. }
  301. return this->XcodeBuildCommand;
  302. }
  303. std::string cmGlobalXCodeGenerator::FindXcodeBuildCommand()
  304. {
  305. std::string makeProgram = cmSystemTools::FindProgram("xcodebuild");
  306. if (makeProgram.empty()) {
  307. makeProgram = "xcodebuild";
  308. }
  309. return makeProgram;
  310. }
  311. bool cmGlobalXCodeGenerator::SetSystemName(std::string const& s,
  312. cmMakefile* mf)
  313. {
  314. this->SystemName = s;
  315. return this->cmGlobalGenerator::SetSystemName(s, mf);
  316. }
  317. namespace {
  318. cm::string_view cmXcodeBuildSystemString(cmGlobalXCodeGenerator::BuildSystem b)
  319. {
  320. switch (b) {
  321. case cmGlobalXCodeGenerator::BuildSystem::One:
  322. return "1"_s;
  323. case cmGlobalXCodeGenerator::BuildSystem::Twelve:
  324. return "12"_s;
  325. }
  326. return {};
  327. }
  328. }
  329. bool cmGlobalXCodeGenerator::SetGeneratorToolset(std::string const& ts,
  330. bool build, cmMakefile* mf)
  331. {
  332. if (!this->ParseGeneratorToolset(ts, mf)) {
  333. return false;
  334. }
  335. if (build) {
  336. return true;
  337. }
  338. if (!this->GeneratorToolset.empty()) {
  339. mf->AddDefinition("CMAKE_XCODE_PLATFORM_TOOLSET", this->GeneratorToolset);
  340. }
  341. mf->AddDefinition("CMAKE_XCODE_BUILD_SYSTEM",
  342. cmXcodeBuildSystemString(this->XcodeBuildSystem));
  343. return true;
  344. }
  345. bool cmGlobalXCodeGenerator::ParseGeneratorToolset(std::string const& ts,
  346. cmMakefile* mf)
  347. {
  348. std::vector<std::string> const fields =
  349. cmTokenize(ts, ',', cmTokenizerMode::New);
  350. if (fields.empty()) {
  351. return true;
  352. }
  353. auto fi = fields.cbegin();
  354. // The first field may be the Xcode GCC_VERSION.
  355. if (fi->find('=') == fi->npos) {
  356. this->GeneratorToolset = *fi;
  357. ++fi;
  358. }
  359. std::unordered_set<std::string> handled;
  360. // The rest of the fields must be key=value pairs.
  361. for (; fi != fields.cend(); ++fi) {
  362. std::string::size_type pos = fi->find('=');
  363. if (pos == fi->npos) {
  364. /* clang-format off */
  365. std::string const& e = cmStrCat(
  366. "Generator\n"
  367. " ", this->GetName(), "\n"
  368. "given toolset specification\n"
  369. " ", ts, "\n"
  370. "that contains a field after the first ',' with no '='."
  371. );
  372. /* clang-format on */
  373. mf->IssueMessage(MessageType::FATAL_ERROR, e);
  374. return false;
  375. }
  376. std::string const key = fi->substr(0, pos);
  377. std::string const value = fi->substr(pos + 1);
  378. if (!handled.insert(key).second) {
  379. /* clang-format off */
  380. std::string const& e = cmStrCat(
  381. "Generator\n"
  382. " ", this->GetName(), "\n"
  383. "given toolset specification\n"
  384. " ", ts, "\n"
  385. "that contains duplicate field key '", key, "'."
  386. );
  387. /* clang-format on */
  388. mf->IssueMessage(MessageType::FATAL_ERROR, e);
  389. return false;
  390. }
  391. if (!this->ProcessGeneratorToolsetField(key, value, mf)) {
  392. return false;
  393. }
  394. }
  395. return true;
  396. }
  397. bool cmGlobalXCodeGenerator::ProcessGeneratorToolsetField(
  398. std::string const& key, std::string const& value, cmMakefile* mf)
  399. {
  400. if (key == "buildsystem"_s) {
  401. if (value == "1"_s) {
  402. this->XcodeBuildSystem = BuildSystem::One;
  403. } else if (value == "12"_s) {
  404. this->XcodeBuildSystem = BuildSystem::Twelve;
  405. } else {
  406. /* clang-format off */
  407. std::string const& e = cmStrCat(
  408. "Generator\n"
  409. " ", this->GetName(), "\n"
  410. "toolset specification field\n"
  411. " buildsystem=", value, "\n"
  412. "value is unknown. It must be '1' or '12'."
  413. );
  414. /* clang-format on */
  415. mf->IssueMessage(MessageType::FATAL_ERROR, e);
  416. return false;
  417. }
  418. if ((this->XcodeBuildSystem == BuildSystem::Twelve &&
  419. this->XcodeVersion < 120) ||
  420. (this->XcodeBuildSystem == BuildSystem::One &&
  421. this->XcodeVersion >= 140)) {
  422. /* clang-format off */
  423. std::string const& e = cmStrCat(
  424. "Generator\n"
  425. " ", this->GetName(), "\n"
  426. "toolset specification field\n"
  427. " buildsystem=", value, "\n"
  428. "is not allowed with Xcode ", this->VersionString, '.'
  429. );
  430. /* clang-format on */
  431. mf->IssueMessage(MessageType::FATAL_ERROR, e);
  432. return false;
  433. }
  434. return true;
  435. }
  436. /* clang-format off */
  437. std::string const& e = cmStrCat(
  438. "Generator\n"
  439. " ", this->GetName(), "\n"
  440. "given toolset specification that contains invalid field '", key, "'."
  441. );
  442. /* clang-format on */
  443. mf->IssueMessage(MessageType::FATAL_ERROR, e);
  444. return false;
  445. }
  446. void cmGlobalXCodeGenerator::EnableLanguage(
  447. std::vector<std::string> const& lang, cmMakefile* mf, bool optional)
  448. {
  449. mf->AddDefinition("XCODE", "1");
  450. mf->AddDefinition("XCODE_VERSION", this->VersionString);
  451. mf->InitCMAKE_CONFIGURATION_TYPES("Debug;Release;MinSizeRel;RelWithDebInfo");
  452. mf->AddDefinition("CMAKE_GENERATOR_NO_COMPILER_ENV", "1");
  453. this->cmGlobalGenerator::EnableLanguage(lang, mf, optional);
  454. this->ComputeArchitectures(mf);
  455. }
  456. bool cmGlobalXCodeGenerator::Open(std::string const& bindir,
  457. std::string const& projectName, bool dryRun)
  458. {
  459. bool ret = false;
  460. #ifdef HAVE_APPLICATION_SERVICES
  461. // If an external tool created a workspace then open it instead.
  462. std::string url = cmStrCat(bindir, '/', projectName, ".xcworkspace");
  463. bool const isWorkspace = cmSystemTools::FileIsDirectory(url);
  464. if (!isWorkspace) {
  465. url = cmStrCat(bindir, '/', projectName, ".xcodeproj");
  466. }
  467. if (dryRun) {
  468. return cmSystemTools::FileIsDirectory(url);
  469. }
  470. CFStringRef cfStr = CFStringCreateWithCString(
  471. kCFAllocatorDefault, url.c_str(), kCFStringEncodingUTF8);
  472. if (cfStr) {
  473. CFURLRef cfUrl = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, cfStr,
  474. kCFURLPOSIXPathStyle, true);
  475. if (cfUrl) {
  476. OSStatus err = LSOpenCFURLRef(cfUrl, nullptr);
  477. ret = err == noErr;
  478. CFRelease(cfUrl);
  479. }
  480. CFRelease(cfStr);
  481. }
  482. #else
  483. (void)bindir;
  484. (void)projectName;
  485. (void)dryRun;
  486. #endif
  487. return ret;
  488. }
  489. std::vector<cmGlobalGenerator::GeneratedMakeCommand>
  490. cmGlobalXCodeGenerator::GenerateBuildCommand(
  491. std::string const& makeProgram, std::string const& projectName,
  492. std::string const& /*projectDir*/,
  493. std::vector<std::string> const& targetNames, std::string const& config,
  494. int jobs, bool /*verbose*/, cmBuildOptions /*buildOptions*/,
  495. std::vector<std::string> const& makeOptions)
  496. {
  497. std::string const xcodebuild =
  498. this->SelectMakeProgram(makeProgram, this->GetXcodeBuildCommand());
  499. // Note that projectName can be empty, such as from a command like this one:
  500. // ctest --build-and-test . build --build-generator Xcode
  501. // If projectName is empty, then isWorkspace set further below will always
  502. // be false because workspacePath will never point to a valid workspace file.
  503. // And if projectName is empty, we don't add any -workspace or -project
  504. // option to the xcodebuild command line because we don't know what to put
  505. // after either option. For that scenario, we rely on xcodebuild finding
  506. // exactly one .xcodeproj file in the working directory.
  507. std::string const workspacePath = cmStrCat(projectName, ".xcworkspace");
  508. std::string const projectPath = cmStrCat(projectName, ".xcodeproj");
  509. // If an external tool created a workspace then build it instead.
  510. bool const isWorkspace = cmSystemTools::FileIsDirectory(workspacePath);
  511. std::string const targetFlag = isWorkspace ? "-scheme" : "-target";
  512. std::vector<std::string> requiredArgs;
  513. if (isWorkspace) {
  514. requiredArgs.insert(requiredArgs.end(), { "-workspace", workspacePath });
  515. } else if (!projectName.empty()) {
  516. requiredArgs.insert(requiredArgs.end(), { "-project", projectPath });
  517. }
  518. bool const isCleanBuild = cm::contains(targetNames, "clean");
  519. bool const isTargetEmpty = targetNames.empty() ||
  520. ((targetNames.size() == 1) && targetNames.front().empty());
  521. if (isCleanBuild) {
  522. requiredArgs.push_back("clean");
  523. } else {
  524. requiredArgs.push_back("build");
  525. }
  526. requiredArgs.insert(requiredArgs.end(),
  527. { "-configuration", config.empty() ? "Debug" : config });
  528. if (isWorkspace) {
  529. requiredArgs.insert(
  530. requiredArgs.end(),
  531. { "-destination",
  532. cmStrCat("generic/platform=", this->GetAppleSpecificPlatformName()) });
  533. }
  534. if ((this->XcodeBuildSystem >= BuildSystem::Twelve) ||
  535. (jobs != cmake::NO_BUILD_PARALLEL_LEVEL)) {
  536. requiredArgs.push_back("-parallelizeTargets");
  537. }
  538. if ((jobs != cmake::NO_BUILD_PARALLEL_LEVEL) &&
  539. (jobs != cmake::DEFAULT_BUILD_PARALLEL_LEVEL)) {
  540. requiredArgs.insert(requiredArgs.end(), { "-jobs", std::to_string(jobs) });
  541. }
  542. if (this->XcodeVersion >= 70) {
  543. requiredArgs.push_back("-hideShellScriptEnvironment");
  544. }
  545. requiredArgs.insert(requiredArgs.end(), makeOptions.begin(),
  546. makeOptions.end());
  547. if (isWorkspace && !isCleanBuild && targetNames.size() > 1) {
  548. // For workspaces we need a separate command for each target,
  549. // because xcodebuild can pass only one -scheme arg
  550. std::vector<GeneratedMakeCommand> makeCommands;
  551. for (auto const& target : targetNames) {
  552. if (target.empty()) {
  553. continue;
  554. }
  555. GeneratedMakeCommand makeCommand;
  556. makeCommand.Add(xcodebuild);
  557. makeCommand.Add(requiredArgs.cbegin(), requiredArgs.cend());
  558. makeCommand.Add(targetFlag, target);
  559. makeCommands.emplace_back(std::move(makeCommand));
  560. }
  561. return makeCommands;
  562. }
  563. if (isTargetEmpty || isCleanBuild) {
  564. requiredArgs.insert(requiredArgs.end(), { targetFlag, "ALL_BUILD" });
  565. } else {
  566. for (auto const& target : targetNames) {
  567. if (target.empty()) {
  568. continue;
  569. }
  570. requiredArgs.insert(requiredArgs.end(), { targetFlag, target });
  571. }
  572. }
  573. GeneratedMakeCommand makeCommand;
  574. makeCommand.Add(xcodebuild);
  575. makeCommand.Add(requiredArgs.cbegin(), requiredArgs.cend());
  576. return { std::move(makeCommand) };
  577. }
  578. //! Create a local generator appropriate to this Global Generator
  579. std::unique_ptr<cmLocalGenerator> cmGlobalXCodeGenerator::CreateLocalGenerator(
  580. cmMakefile* mf)
  581. {
  582. std::unique_ptr<cmLocalGenerator> lg(
  583. cm::make_unique<cmLocalXCodeGenerator>(this, mf));
  584. if (this->XcodeBuildSystem >= BuildSystem::Twelve) {
  585. // For this build system variant we generate custom commands as
  586. // shell scripts directly rather than inside Makefiles.
  587. // FIXME: Rename or refactor this option for clarity.
  588. lg->SetLinkScriptShell(true);
  589. }
  590. return lg;
  591. }
  592. void cmGlobalXCodeGenerator::AddExtraIDETargets()
  593. {
  594. // make sure extra targets are added before calling
  595. // the parent generate which will call trace depends
  596. for (auto keyVal : this->ProjectMap) {
  597. cmLocalGenerator* root = keyVal.second[0];
  598. this->SetGenerationRoot(root);
  599. // add ALL_BUILD, INSTALL, etc
  600. this->AddExtraTargets(root, keyVal.second);
  601. }
  602. }
  603. void cmGlobalXCodeGenerator::Generate()
  604. {
  605. this->cmGlobalGenerator::Generate();
  606. if (cmSystemTools::GetErrorOccurredFlag()) {
  607. return;
  608. }
  609. for (auto keyVal : this->ProjectMap) {
  610. cmLocalGenerator* root = keyVal.second[0];
  611. bool generateTopLevelProjectOnly =
  612. root->GetMakefile()->IsOn("CMAKE_XCODE_GENERATE_TOP_LEVEL_PROJECT_ONLY");
  613. if (generateTopLevelProjectOnly) {
  614. cmStateSnapshot snp = root->GetStateSnapshot();
  615. if (snp.GetBuildsystemDirectoryParent().IsValid()) {
  616. continue;
  617. }
  618. }
  619. // cache the enabled languages for source file type queries
  620. this->GetEnabledLanguages(this->EnabledLangs);
  621. this->SetGenerationRoot(root);
  622. // now create the project
  623. this->OutputXCodeProject(root, keyVal.second);
  624. }
  625. }
  626. void cmGlobalXCodeGenerator::SetGenerationRoot(cmLocalGenerator* root)
  627. {
  628. this->CurrentProject = root->GetProjectName();
  629. this->SetCurrentLocalGenerator(root);
  630. this->CurrentRootGenerator = root;
  631. this->CurrentXCodeHackMakefile =
  632. cmStrCat(root->GetCurrentBinaryDirectory(), "/CMakeScripts");
  633. cmSystemTools::MakeDirectory(this->CurrentXCodeHackMakefile);
  634. this->CurrentXCodeHackMakefile += "/XCODE_DEPEND_HELPER.make";
  635. }
  636. std::string cmGlobalXCodeGenerator::PostBuildMakeTarget(
  637. std::string const& tName, std::string const& configName)
  638. {
  639. std::string target = tName;
  640. std::replace(target.begin(), target.end(), ' ', '_');
  641. std::string out = cmStrCat("PostBuild.", target, '.', configName);
  642. return out;
  643. }
  644. #define CMAKE_CHECK_BUILD_SYSTEM_TARGET "ZERO_CHECK"
  645. void cmGlobalXCodeGenerator::AddExtraTargets(
  646. cmLocalGenerator* root, std::vector<cmLocalGenerator*>& gens)
  647. {
  648. // Add ALL_BUILD
  649. auto cc = cm::make_unique<cmCustomCommand>();
  650. cc->SetCommandLines(
  651. cmMakeSingleCommandLine({ "echo", "Build all projects" }));
  652. cmTarget* allbuild =
  653. root->AddUtilityCommand("ALL_BUILD", true, std::move(cc));
  654. // Add xcconfig files to ALL_BUILD sources
  655. for (auto& config : this->CurrentConfigurationTypes) {
  656. auto xcconfig = cmGeneratorExpression::Evaluate(
  657. this->CurrentMakefile->GetSafeDefinition("CMAKE_XCODE_XCCONFIG"),
  658. this->CurrentLocalGenerator, config);
  659. if (!xcconfig.empty()) {
  660. auto* xcconfig_sf = allbuild->AddSource(xcconfig);
  661. xcconfig_sf->SetSpecialSourceType(
  662. cmSourceFile::SpecialSourceType::XcodeXCConfigFile);
  663. }
  664. }
  665. root->AddGeneratorTarget(cm::make_unique<cmGeneratorTarget>(allbuild, root));
  666. // Add XCODE depend helper
  667. std::string legacyDependHelperDir = root->GetCurrentBinaryDirectory();
  668. cmCustomCommandLines legacyDependHelperCommandLines;
  669. if (this->XcodeBuildSystem == BuildSystem::One) {
  670. legacyDependHelperCommandLines = cmMakeSingleCommandLine(
  671. { "make", "-C", legacyDependHelperDir, "-f",
  672. this->CurrentXCodeHackMakefile, "OBJDIR=$(OBJDIR)",
  673. /* placeholder, see below */ "" });
  674. }
  675. // Add ZERO_CHECK
  676. bool regenerate = !this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION");
  677. bool generateTopLevelProjectOnly =
  678. root->GetMakefile()->IsOn("CMAKE_XCODE_GENERATE_TOP_LEVEL_PROJECT_ONLY");
  679. bool isTopLevel =
  680. !root->GetStateSnapshot().GetBuildsystemDirectoryParent().IsValid();
  681. bool isGenerateProject = isTopLevel || !generateTopLevelProjectOnly;
  682. if (regenerate && isGenerateProject) {
  683. this->CreateReRunCMakeFile(root, gens);
  684. std::string file =
  685. cmSystemTools::ConvertToOutputPath(this->CurrentReRunCMakeMakefile);
  686. cmSystemTools::ReplaceString(file, "\\ ", " ");
  687. cc = cm::make_unique<cmCustomCommand>();
  688. cc->SetCommandLines(cmMakeSingleCommandLine({ "make", "-f", file }));
  689. cmTarget* check = root->AddUtilityCommand(CMAKE_CHECK_BUILD_SYSTEM_TARGET,
  690. true, std::move(cc));
  691. root->AddGeneratorTarget(cm::make_unique<cmGeneratorTarget>(check, root));
  692. }
  693. // now make the allbuild depend on all the non-utility targets
  694. // in the project
  695. for (auto& gen : gens) {
  696. for (auto const& target : gen->GetGeneratorTargets()) {
  697. if (target->GetType() == cmStateEnums::GLOBAL_TARGET) {
  698. continue;
  699. }
  700. if (regenerate &&
  701. (target->GetName() != CMAKE_CHECK_BUILD_SYSTEM_TARGET)) {
  702. target->Target->AddUtility(CMAKE_CHECK_BUILD_SYSTEM_TARGET, false);
  703. }
  704. // make all exe, shared libs and modules
  705. // run the depend check makefile as a post build rule
  706. // this will make sure that when the next target is built
  707. // things are up-to-date
  708. if (this->XcodeBuildSystem == BuildSystem::One && isGenerateProject &&
  709. target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  710. legacyDependHelperCommandLines.front().back() = // fill placeholder
  711. this->PostBuildMakeTarget(target->GetName(), "$(CONFIGURATION)");
  712. cc = cm::make_unique<cmCustomCommand>();
  713. cc->SetCommandLines(legacyDependHelperCommandLines);
  714. cc->SetComment("Depend check for xcode");
  715. cc->SetWorkingDirectory(legacyDependHelperDir.c_str());
  716. gen->AddCustomCommandToTarget(
  717. target->GetName(), cmCustomCommandType::POST_BUILD, std::move(cc),
  718. cmObjectLibraryCommands::Accept);
  719. }
  720. if (!this->IsExcluded(gens[0], target.get())) {
  721. allbuild->AddUtility(target->GetName(), false);
  722. }
  723. }
  724. }
  725. }
  726. void cmGlobalXCodeGenerator::CreateReRunCMakeFile(
  727. cmLocalGenerator* root, std::vector<cmLocalGenerator*> const& gens)
  728. {
  729. std::vector<std::string> lfiles;
  730. for (auto* gen : gens) {
  731. cm::append(lfiles, gen->GetMakefile()->GetListFiles());
  732. }
  733. // sort the array
  734. std::sort(lfiles.begin(), lfiles.end());
  735. lfiles.erase(std::unique(lfiles.begin(), lfiles.end()), lfiles.end());
  736. cmake* cm = this->GetCMakeInstance();
  737. if (cm->DoWriteGlobVerifyTarget()) {
  738. lfiles.emplace_back(cm->GetGlobVerifyStamp());
  739. }
  740. this->CurrentReRunCMakeMakefile =
  741. cmStrCat(root->GetCurrentBinaryDirectory(), "/CMakeScripts");
  742. cmSystemTools::MakeDirectory(this->CurrentReRunCMakeMakefile);
  743. this->CurrentReRunCMakeMakefile += "/ReRunCMake.make";
  744. cmGeneratedFileStream makefileStream(this->CurrentReRunCMakeMakefile);
  745. makefileStream.SetCopyIfDifferent(true);
  746. makefileStream << "# Generated by CMake, DO NOT EDIT\n\n"
  747. "TARGETS:= \n"
  748. "empty:= \n"
  749. "space:= $(empty) $(empty)\n"
  750. "spaceplus:= $(empty)\\ $(empty)\n\n";
  751. for (auto const& lfile : lfiles) {
  752. makefileStream << "TARGETS += $(subst $(space),$(spaceplus),$(wildcard "
  753. << ConvertToMakefilePath(lfile) << "))\n";
  754. }
  755. makefileStream << '\n';
  756. std::string checkCache =
  757. cmStrCat(root->GetBinaryDirectory(), "/CMakeFiles/cmake.check_cache");
  758. if (cm->DoWriteGlobVerifyTarget()) {
  759. makefileStream << ".NOTPARALLEL:\n\n"
  760. ".PHONY: all VERIFY_GLOBS\n\n"
  761. "all: VERIFY_GLOBS "
  762. << ConvertToMakefilePath(checkCache)
  763. << "\n\n"
  764. "VERIFY_GLOBS:\n"
  765. "\t"
  766. << ConvertToMakefilePath(cmSystemTools::GetCMakeCommand())
  767. << " -P "
  768. << ConvertToMakefilePath(cm->GetGlobVerifyScript())
  769. << "\n\n";
  770. }
  771. makefileStream << ConvertToMakefilePath(checkCache) << ": $(TARGETS)\n";
  772. makefileStream
  773. << '\t' << ConvertToMakefilePath(cmSystemTools::GetCMakeCommand()) << " -S"
  774. << ConvertToMakefilePath(root->GetSourceDirectory()) << " -B"
  775. << ConvertToMakefilePath(root->GetBinaryDirectory())
  776. << (cm->GetIgnoreCompileWarningAsError() ? " --compile-no-warning-as-error"
  777. : "")
  778. << (cm->GetIgnoreLinkWarningAsError() ? " --link-no-warning-as-error" : "")
  779. << '\n';
  780. }
  781. static bool objectIdLessThan(std::unique_ptr<cmXCodeObject> const& l,
  782. std::unique_ptr<cmXCodeObject> const& r)
  783. {
  784. return l->GetId() < r->GetId();
  785. }
  786. void cmGlobalXCodeGenerator::SortXCodeObjects()
  787. {
  788. std::sort(this->XCodeObjects.begin(), this->XCodeObjects.end(),
  789. objectIdLessThan);
  790. }
  791. void cmGlobalXCodeGenerator::ClearXCodeObjects()
  792. {
  793. this->TargetDoneSet.clear();
  794. this->XCodeObjects.clear();
  795. this->XCodeObjectIDs.clear();
  796. this->XCodeObjectMap.clear();
  797. this->GroupMap.clear();
  798. this->GroupNameMap.clear();
  799. this->TargetGroup.clear();
  800. this->FileRefs.clear();
  801. this->ExternalLibRefs.clear();
  802. this->FileRefToBuildFileMap.clear();
  803. this->FileRefToEmbedBuildFileMap.clear();
  804. this->CommandsVisited.clear();
  805. }
  806. void cmGlobalXCodeGenerator::addObject(std::unique_ptr<cmXCodeObject> obj)
  807. {
  808. if (obj->GetType() == cmXCodeObject::OBJECT) {
  809. std::string const& id = obj->GetId();
  810. // If this is a duplicate id, it's an error:
  811. //
  812. if (this->XCodeObjectIDs.count(id)) {
  813. cmSystemTools::Error(
  814. "Xcode generator: duplicate object ids not allowed");
  815. }
  816. this->XCodeObjectIDs.insert(id);
  817. }
  818. this->XCodeObjects.push_back(std::move(obj));
  819. }
  820. cmXCodeObject* cmGlobalXCodeGenerator::CreateObject(
  821. cmXCodeObject::PBXType ptype, cm::string_view key)
  822. {
  823. auto obj = cm::make_unique<cmXCode21Object>(ptype, cmXCodeObject::OBJECT,
  824. this->GetObjectId(ptype, key));
  825. auto* ptr = obj.get();
  826. this->addObject(std::move(obj));
  827. return ptr;
  828. }
  829. cmXCodeObject* cmGlobalXCodeGenerator::CreateObject(cmXCodeObject::Type type)
  830. {
  831. auto obj = cm::make_unique<cmXCodeObject>(
  832. cmXCodeObject::None, type,
  833. "Temporary cmake object, should not be referred to in Xcode file");
  834. auto* ptr = obj.get();
  835. this->addObject(std::move(obj));
  836. return ptr;
  837. }
  838. cmXCodeObject* cmGlobalXCodeGenerator::CreateString(cm::string_view s)
  839. {
  840. cmXCodeObject* obj = this->CreateObject(cmXCodeObject::STRING);
  841. obj->SetString(s);
  842. return obj;
  843. }
  844. cmXCodeObject* cmGlobalXCodeGenerator::CreateObjectReference(
  845. cmXCodeObject* ref)
  846. {
  847. cmXCodeObject* obj = this->CreateObject(cmXCodeObject::OBJECT_REF);
  848. obj->SetObject(ref);
  849. return obj;
  850. }
  851. cmXCodeObject* cmGlobalXCodeGenerator::CreateFlatClone(cmXCodeObject* orig)
  852. {
  853. cmXCodeObject* obj = this->CreateObject(orig->GetType());
  854. obj->CopyAttributes(orig);
  855. return obj;
  856. }
  857. static std::string GetGroupMapKeyFromPath(cmGeneratorTarget* target,
  858. std::string const& fullpath)
  859. {
  860. return cmStrCat(target->GetName(), '-', fullpath);
  861. }
  862. cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeBuildFileFromPath(
  863. std::string const& fullpath, cmGeneratorTarget* target,
  864. std::string const& lang, cmSourceFile* sf)
  865. {
  866. // Using a map and the full path guarantees that we will always get the same
  867. // fileRef object for any given full path. Same goes for the buildFile
  868. // object.
  869. cmXCodeObject* fileRef =
  870. this->CreateXCodeFileReferenceFromPath(fullpath, target, lang, sf);
  871. if (fileRef) {
  872. auto it = this->FileRefToBuildFileMap.find(fileRef);
  873. if (it == this->FileRefToBuildFileMap.end()) {
  874. cmXCodeObject* buildFile =
  875. this->CreateObject(cmXCodeObject::PBXBuildFile);
  876. buildFile->SetComment(fileRef->GetComment());
  877. buildFile->AddAttribute("fileRef", this->CreateObjectReference(fileRef));
  878. this->FileRefToBuildFileMap[fileRef] = buildFile;
  879. return buildFile;
  880. }
  881. return it->second;
  882. }
  883. return nullptr;
  884. }
  885. class XCodeGeneratorExpressionInterpreter
  886. : public cmGeneratorExpressionInterpreter
  887. {
  888. public:
  889. XCodeGeneratorExpressionInterpreter(cmSourceFile* sourceFile,
  890. cmLocalGenerator* localGenerator,
  891. cmGeneratorTarget* headTarget,
  892. std::string const& lang)
  893. : cmGeneratorExpressionInterpreter(
  894. localGenerator, "NO-PER-CONFIG-SUPPORT-IN-XCODE", headTarget, lang)
  895. , SourceFile(sourceFile)
  896. {
  897. }
  898. XCodeGeneratorExpressionInterpreter(
  899. XCodeGeneratorExpressionInterpreter const&) = delete;
  900. XCodeGeneratorExpressionInterpreter& operator=(
  901. XCodeGeneratorExpressionInterpreter const&) = delete;
  902. std::string const& Evaluate(char const* expression,
  903. std::string const& property)
  904. {
  905. return this->Evaluate(std::string(expression ? expression : ""), property);
  906. }
  907. std::string const& Evaluate(std::string const& expression,
  908. std::string const& property)
  909. {
  910. std::string const& processed =
  911. this->cmGeneratorExpressionInterpreter::Evaluate(expression, property);
  912. if (this->CompiledGeneratorExpression->GetHadContextSensitiveCondition()) {
  913. std::ostringstream e;
  914. /* clang-format off */
  915. e <<
  916. "Xcode does not support per-config per-source " << property << ":\n"
  917. " " << expression << "\n"
  918. "specified for source:\n"
  919. " " << this->SourceFile->ResolveFullPath() << '\n';
  920. /* clang-format on */
  921. this->LocalGenerator->IssueMessage(MessageType::FATAL_ERROR, e.str());
  922. }
  923. return processed;
  924. }
  925. private:
  926. cmSourceFile* SourceFile = nullptr;
  927. };
  928. cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeSourceFile(
  929. cmLocalGenerator* lg, cmSourceFile* sf, cmGeneratorTarget* gtgt)
  930. {
  931. std::string lang = this->CurrentLocalGenerator->GetSourceFileLanguage(*sf);
  932. XCodeGeneratorExpressionInterpreter genexInterpreter(sf, lg, gtgt, lang);
  933. // Add flags from target and source file properties.
  934. std::string flags;
  935. std::string const& srcfmt = sf->GetSafeProperty("Fortran_FORMAT");
  936. switch (cmOutputConverter::GetFortranFormat(srcfmt)) {
  937. case cmOutputConverter::FortranFormatFixed:
  938. flags = cmStrCat("-fixed ", flags);
  939. break;
  940. case cmOutputConverter::FortranFormatFree:
  941. flags = cmStrCat("-free ", flags);
  942. break;
  943. default:
  944. break;
  945. }
  946. // Explicitly add the explicit language flag before any other flag
  947. // so user flags can override it.
  948. gtgt->AddExplicitLanguageFlags(flags, *sf);
  949. std::string const COMPILE_FLAGS("COMPILE_FLAGS");
  950. if (cmValue cflags = sf->GetProperty(COMPILE_FLAGS)) {
  951. lg->AppendFlags(flags, genexInterpreter.Evaluate(*cflags, COMPILE_FLAGS));
  952. }
  953. std::string const COMPILE_OPTIONS("COMPILE_OPTIONS");
  954. if (cmValue coptions = sf->GetProperty(COMPILE_OPTIONS)) {
  955. lg->AppendCompileOptions(
  956. flags, genexInterpreter.Evaluate(*coptions, COMPILE_OPTIONS));
  957. }
  958. // Add per-source definitions.
  959. BuildObjectListOrString flagsBuild(this, false);
  960. std::string const COMPILE_DEFINITIONS("COMPILE_DEFINITIONS");
  961. if (cmValue compile_defs = sf->GetProperty(COMPILE_DEFINITIONS)) {
  962. this->AppendDefines(
  963. flagsBuild,
  964. genexInterpreter.Evaluate(*compile_defs, COMPILE_DEFINITIONS).c_str(),
  965. true);
  966. }
  967. if (sf->GetPropertyAsBool("SKIP_PRECOMPILE_HEADERS")) {
  968. this->AppendDefines(flagsBuild, "CMAKE_SKIP_PRECOMPILE_HEADERS", true);
  969. }
  970. if (!flagsBuild.IsEmpty()) {
  971. if (!flags.empty()) {
  972. flags += ' ';
  973. }
  974. flags += flagsBuild.GetString();
  975. }
  976. // Add per-source include directories.
  977. std::vector<std::string> includes;
  978. std::string const INCLUDE_DIRECTORIES("INCLUDE_DIRECTORIES");
  979. if (cmValue cincludes = sf->GetProperty(INCLUDE_DIRECTORIES)) {
  980. lg->AppendIncludeDirectories(
  981. includes, genexInterpreter.Evaluate(*cincludes, INCLUDE_DIRECTORIES),
  982. *sf);
  983. }
  984. lg->AppendFlags(flags,
  985. lg->GetIncludeFlags(includes, gtgt, lang, std::string()));
  986. cmXCodeObject* buildFile =
  987. this->CreateXCodeBuildFileFromPath(sf->ResolveFullPath(), gtgt, lang, sf);
  988. cmXCodeObject* settings = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  989. settings->AddAttributeIfNotEmpty("COMPILER_FLAGS",
  990. this->CreateString(flags));
  991. cmGeneratorTarget::SourceFileFlags tsFlags =
  992. gtgt->GetTargetSourceFileFlags(sf);
  993. cmXCodeObject* attrs = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  994. // Is this a "private" or "public" framework header file?
  995. // Set the ATTRIBUTES attribute appropriately...
  996. //
  997. if (gtgt->IsFrameworkOnApple()) {
  998. if (tsFlags.Type == cmGeneratorTarget::SourceFileTypePrivateHeader) {
  999. attrs->AddObject(this->CreateString("Private"));
  1000. } else if (tsFlags.Type == cmGeneratorTarget::SourceFileTypePublicHeader) {
  1001. attrs->AddObject(this->CreateString("Public"));
  1002. }
  1003. }
  1004. // Add user-specified file attributes.
  1005. cmValue extraFileAttributes = sf->GetProperty("XCODE_FILE_ATTRIBUTES");
  1006. if (extraFileAttributes) {
  1007. // Expand the list of attributes.
  1008. cmList attributes{ *extraFileAttributes };
  1009. // Store the attributes.
  1010. for (auto const& attribute : attributes) {
  1011. attrs->AddObject(this->CreateString(attribute));
  1012. }
  1013. }
  1014. settings->AddAttributeIfNotEmpty("ATTRIBUTES", attrs);
  1015. if (buildFile) {
  1016. buildFile->AddAttributeIfNotEmpty("settings", settings);
  1017. }
  1018. return buildFile;
  1019. }
  1020. void cmGlobalXCodeGenerator::AddXCodeProjBuildRule(
  1021. cmGeneratorTarget* target, std::vector<cmSourceFile*>& sources) const
  1022. {
  1023. std::string listfile = this->GetCMakeInstance()->GetCMakeListFile(
  1024. target->GetLocalGenerator()->GetCurrentSourceDirectory());
  1025. cmSourceFile* srcCMakeLists = target->Makefile->GetOrCreateSource(
  1026. listfile, false, cmSourceFileLocationKind::Known);
  1027. srcCMakeLists->SetSpecialSourceType(
  1028. cmSourceFile::SpecialSourceType::CMakeLists);
  1029. if (!cm::contains(sources, srcCMakeLists)) {
  1030. sources.push_back(srcCMakeLists);
  1031. }
  1032. }
  1033. namespace {
  1034. bool IsLinkPhaseLibraryExtension(std::string const& fileExt)
  1035. {
  1036. // Empty file extension is a special case for paths to framework's
  1037. // internal binary which could be MyFw.framework/Versions/*/MyFw
  1038. return (fileExt == ".framework"_s || fileExt == ".xcframework"_s ||
  1039. fileExt == ".a"_s || fileExt == ".o"_s || fileExt == ".dylib"_s ||
  1040. fileExt == ".tbd"_s || fileExt.empty());
  1041. }
  1042. bool IsLibraryType(std::string const& fileType)
  1043. {
  1044. return (fileType == "wrapper.framework"_s ||
  1045. fileType == "wrapper.xcframework"_s || fileType == "archive.ar"_s ||
  1046. fileType == "compiled.mach-o.objfile"_s ||
  1047. fileType == "compiled.mach-o.dylib"_s ||
  1048. fileType == "compiled.mach-o.executable"_s ||
  1049. fileType == "sourcecode.text-based-dylib-definition"_s);
  1050. }
  1051. std::string GetDirectoryValueFromFileExtension(std::string const& dirExt)
  1052. {
  1053. std::string ext = cmSystemTools::LowerCase(dirExt);
  1054. if (ext == "framework"_s) {
  1055. return "wrapper.framework";
  1056. }
  1057. if (ext == "xcframework"_s) {
  1058. return "wrapper.xcframework";
  1059. }
  1060. if (ext == "xcassets"_s) {
  1061. return "folder.assetcatalog";
  1062. }
  1063. if (ext == "icon"_s) {
  1064. return "folder.iconcomposer.icon";
  1065. }
  1066. return "folder";
  1067. }
  1068. std::string GetSourcecodeValueFromFileExtension(
  1069. std::string const& _ext, std::string const& lang,
  1070. bool& keepLastKnownFileType, std::vector<std::string> const& enabled_langs)
  1071. {
  1072. std::string ext = cmSystemTools::LowerCase(_ext);
  1073. std::string sourcecode = "default";
  1074. if (ext == "o"_s) {
  1075. keepLastKnownFileType = true;
  1076. sourcecode = "compiled.mach-o.objfile";
  1077. } else if (ext == "xctest"_s) {
  1078. sourcecode = "wrapper.cfbundle";
  1079. } else if (ext == "xib"_s) {
  1080. keepLastKnownFileType = true;
  1081. sourcecode = "file.xib";
  1082. } else if (ext == "storyboard"_s) {
  1083. keepLastKnownFileType = true;
  1084. sourcecode = "file.storyboard";
  1085. // NOLINTNEXTLINE(bugprone-branch-clone)
  1086. } else if (ext == "mm"_s && !cm::contains(enabled_langs, "OBJCXX")) {
  1087. sourcecode = "sourcecode.cpp.objcpp";
  1088. // NOLINTNEXTLINE(bugprone-branch-clone)
  1089. } else if (ext == "m"_s && !cm::contains(enabled_langs, "OBJC")) {
  1090. sourcecode = "sourcecode.c.objc";
  1091. } else if (ext == "swift"_s) {
  1092. sourcecode = "sourcecode.swift";
  1093. } else if (ext == "plist"_s) {
  1094. sourcecode = "sourcecode.text.plist";
  1095. } else if (ext == "h"_s) {
  1096. sourcecode = "sourcecode.c.h";
  1097. } else if (ext == "hxx"_s || ext == "hpp"_s || ext == "txx"_s ||
  1098. ext == "pch"_s || ext == "hh"_s || ext == "inl"_s) {
  1099. sourcecode = "sourcecode.cpp.h";
  1100. } else if (ext == "png"_s || ext == "gif"_s || ext == "jpg"_s) {
  1101. keepLastKnownFileType = true;
  1102. sourcecode = "image";
  1103. } else if (ext == "txt"_s) {
  1104. sourcecode = "sourcecode.text";
  1105. } else if (lang == "CXX"_s) {
  1106. sourcecode = "sourcecode.cpp.cpp";
  1107. } else if (lang == "C"_s) {
  1108. sourcecode = "sourcecode.c.c";
  1109. } else if (lang == "OBJCXX"_s) {
  1110. sourcecode = "sourcecode.cpp.objcpp";
  1111. } else if (lang == "OBJC"_s) {
  1112. sourcecode = "sourcecode.c.objc";
  1113. } else if (lang == "Fortran"_s) {
  1114. sourcecode = "sourcecode.fortran.f90";
  1115. } else if (lang == "ASM"_s) {
  1116. sourcecode = "sourcecode.asm";
  1117. } else if (ext == "metal"_s) {
  1118. sourcecode = "sourcecode.metal";
  1119. } else if (ext == "mig"_s) {
  1120. sourcecode = "sourcecode.mig";
  1121. } else if (ext == "tbd"_s) {
  1122. sourcecode = "sourcecode.text-based-dylib-definition";
  1123. } else if (ext == "a"_s) {
  1124. keepLastKnownFileType = true;
  1125. sourcecode = "archive.ar";
  1126. } else if (ext == "dylib"_s) {
  1127. keepLastKnownFileType = true;
  1128. sourcecode = "compiled.mach-o.dylib";
  1129. } else if (ext == "framework"_s) {
  1130. keepLastKnownFileType = true;
  1131. sourcecode = "wrapper.framework";
  1132. } else if (ext == "xcassets"_s) {
  1133. keepLastKnownFileType = true;
  1134. sourcecode = "folder.assetcatalog";
  1135. } else if (ext == "xcconfig"_s) {
  1136. keepLastKnownFileType = true;
  1137. sourcecode = "text.xcconfig";
  1138. } else if (ext == "icon"_s) {
  1139. keepLastKnownFileType = true;
  1140. sourcecode = "folder.iconcomposer.icon";
  1141. }
  1142. // else
  1143. // {
  1144. // // Already specialized above or we leave sourcecode == "sourcecode"
  1145. // // which is probably the most correct choice. Extensionless headers,
  1146. // // for example... Or file types unknown to Xcode that do not map to a
  1147. // // valid explicitFileType value.
  1148. // }
  1149. return sourcecode;
  1150. }
  1151. template <class T>
  1152. std::string GetTargetObjectDirArch(T const& target,
  1153. std::string const& defaultVal)
  1154. {
  1155. cmList archs{ target.GetSafeProperty("OSX_ARCHITECTURES") };
  1156. if (archs.size() > 1) {
  1157. return "$(CURRENT_ARCH)";
  1158. }
  1159. if (archs.size() == 1) {
  1160. return archs.front();
  1161. }
  1162. return defaultVal;
  1163. }
  1164. } // anonymous
  1165. // Extracts the framework directory, if path matches the framework syntax
  1166. // otherwise returns the path untouched
  1167. std::string cmGlobalXCodeGenerator::GetLibraryOrFrameworkPath(
  1168. std::string const& path) const
  1169. {
  1170. auto fwDescriptor = this->SplitFrameworkPath(path);
  1171. if (fwDescriptor) {
  1172. return fwDescriptor->GetFrameworkPath();
  1173. }
  1174. return path;
  1175. }
  1176. cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeFileReferenceFromPath(
  1177. std::string const& fullpath, cmGeneratorTarget* target,
  1178. std::string const& lang, cmSourceFile* sf)
  1179. {
  1180. bool useLastKnownFileType = false;
  1181. std::string fileType;
  1182. if (sf) {
  1183. if (cmValue e = sf->GetProperty("XCODE_EXPLICIT_FILE_TYPE")) {
  1184. fileType = *e;
  1185. } else if (cmValue l = sf->GetProperty("XCODE_LAST_KNOWN_FILE_TYPE")) {
  1186. useLastKnownFileType = true;
  1187. fileType = *l;
  1188. }
  1189. }
  1190. // Make a copy so that we can override it later
  1191. std::string path = cmSystemTools::CollapseFullPath(fullpath);
  1192. // Compute the extension without leading '.'.
  1193. std::string ext = cmSystemTools::GetFilenameLastExtension(path);
  1194. if (!ext.empty()) {
  1195. ext = ext.substr(1);
  1196. }
  1197. if (fileType.empty()) {
  1198. path = this->GetLibraryOrFrameworkPath(path);
  1199. ext = cmSystemTools::GetFilenameLastExtension(path);
  1200. if (!ext.empty()) {
  1201. ext = ext.substr(1);
  1202. }
  1203. // If fullpath references a directory, then we need to specify
  1204. // lastKnownFileType as folder in order for Xcode to be able to
  1205. // open the contents of the folder.
  1206. // (Xcode 4.6 does not like explicitFileType=folder).
  1207. if (cmSystemTools::FileIsDirectory(path)) {
  1208. fileType = GetDirectoryValueFromFileExtension(ext);
  1209. useLastKnownFileType = true;
  1210. } else {
  1211. if (ext.empty() && !sf) {
  1212. // Special case for executable or library without extension
  1213. // that is not a source file. We can't tell which without reading
  1214. // its Mach-O header, but the file might not exist yet, so we
  1215. // have to pick one here.
  1216. useLastKnownFileType = true;
  1217. fileType = "compiled.mach-o.executable";
  1218. } else {
  1219. fileType = GetSourcecodeValueFromFileExtension(
  1220. ext, lang, useLastKnownFileType, this->EnabledLangs);
  1221. }
  1222. }
  1223. }
  1224. std::string key = GetGroupMapKeyFromPath(target, path);
  1225. cmXCodeObject* fileRef = this->FileRefs[key];
  1226. if (!fileRef) {
  1227. fileRef = this->CreateObject(cmXCodeObject::PBXFileReference);
  1228. fileRef->SetComment(path);
  1229. this->FileRefs[key] = fileRef;
  1230. }
  1231. fileRef->AddAttribute("fileEncoding", this->CreateString("4"));
  1232. fileRef->AddAttribute(useLastKnownFileType ? "lastKnownFileType"
  1233. : "explicitFileType",
  1234. this->CreateString(fileType));
  1235. // Store the file path relative to the top of the source tree.
  1236. if (!IsLibraryType(fileType)) {
  1237. path = this->RelativeToSource(path);
  1238. }
  1239. std::string name = cmSystemTools::GetFilenameName(path);
  1240. char const* sourceTree =
  1241. cmSystemTools::FileIsFullPath(path) ? "<absolute>" : "SOURCE_ROOT";
  1242. fileRef->AddAttribute("name", this->CreateString(name));
  1243. fileRef->AddAttribute("path", this->CreateString(path));
  1244. fileRef->AddAttribute("sourceTree", this->CreateString(sourceTree));
  1245. cmXCodeObject* group = this->GroupMap[key];
  1246. if (!group) {
  1247. if (IsLibraryType(fileType)) {
  1248. group = this->FrameworkGroup;
  1249. } else if (fileType == "folder") {
  1250. group = this->ResourcesGroup;
  1251. }
  1252. if (group)
  1253. this->GroupMap[key] = group;
  1254. }
  1255. if (!group) {
  1256. cmSystemTools::Error(cmStrCat("Could not find a PBX group for ", key));
  1257. return nullptr;
  1258. }
  1259. cmXCodeObject* children = group->GetAttribute("children");
  1260. if (!children->HasObject(fileRef)) {
  1261. children->AddObject(fileRef);
  1262. }
  1263. return fileRef;
  1264. }
  1265. cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeFileReference(
  1266. cmSourceFile* sf, cmGeneratorTarget* target)
  1267. {
  1268. std::string lang = this->CurrentLocalGenerator->GetSourceFileLanguage(*sf);
  1269. return this->CreateXCodeFileReferenceFromPath(sf->ResolveFullPath(), target,
  1270. lang, sf);
  1271. }
  1272. bool cmGlobalXCodeGenerator::SpecialTargetEmitted(std::string const& tname)
  1273. {
  1274. if (tname == "ALL_BUILD"_s || tname == "install"_s || tname == "package"_s ||
  1275. tname == "RUN_TESTS"_s || tname == CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
  1276. if (this->TargetDoneSet.find(tname) != this->TargetDoneSet.end()) {
  1277. return true;
  1278. }
  1279. this->TargetDoneSet.insert(tname);
  1280. return false;
  1281. }
  1282. return false;
  1283. }
  1284. void cmGlobalXCodeGenerator::SetCurrentLocalGenerator(cmLocalGenerator* gen)
  1285. {
  1286. this->CurrentLocalGenerator = gen;
  1287. this->CurrentMakefile = gen->GetMakefile();
  1288. // Select the current set of configuration types.
  1289. this->CurrentConfigurationTypes =
  1290. this->CurrentMakefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  1291. }
  1292. struct cmSourceFilePathCompare
  1293. {
  1294. bool operator()(cmSourceFile* l, cmSourceFile* r)
  1295. {
  1296. return l->ResolveFullPath() < r->ResolveFullPath();
  1297. }
  1298. };
  1299. struct cmCompareTargets
  1300. {
  1301. bool operator()(cmXCodeObject* l, cmXCodeObject* r) const
  1302. {
  1303. std::string const& a = l->GetTarget()->GetName();
  1304. std::string const& b = r->GetTarget()->GetName();
  1305. if (a == b) {
  1306. return false;
  1307. }
  1308. if (a == "ALL_BUILD"_s) {
  1309. return true;
  1310. }
  1311. if (b == "ALL_BUILD"_s) {
  1312. return false;
  1313. }
  1314. std::string a_low = cmSystemTools::LowerCase(l->GetTarget()->GetName());
  1315. std::string b_low = cmSystemTools::LowerCase(r->GetTarget()->GetName());
  1316. if (a_low != b_low) {
  1317. return a_low < b_low;
  1318. }
  1319. return a < b;
  1320. }
  1321. };
  1322. bool cmGlobalXCodeGenerator::CreateXCodeTargets(
  1323. cmLocalGenerator* gen, std::vector<cmXCodeObject*>& targets)
  1324. {
  1325. this->SetCurrentLocalGenerator(gen);
  1326. std::vector<cmGeneratorTarget*> gts =
  1327. this->GetLocalGeneratorTargetsInOrder(gen);
  1328. for (auto* gtgt : gts) {
  1329. if (!this->CreateXCodeTarget(gtgt, targets)) {
  1330. return false;
  1331. }
  1332. }
  1333. std::sort(targets.begin(), targets.end(), cmCompareTargets());
  1334. return true;
  1335. }
  1336. bool cmGlobalXCodeGenerator::CreateXCodeTarget(
  1337. cmGeneratorTarget* gtgt, std::vector<cmXCodeObject*>& targets)
  1338. {
  1339. std::string targetName = gtgt->GetName();
  1340. // make sure ALL_BUILD, INSTALL, etc are only done once
  1341. if (this->SpecialTargetEmitted(targetName)) {
  1342. return true;
  1343. }
  1344. if (!gtgt->IsInBuildSystem()) {
  1345. return true;
  1346. }
  1347. for (std::string const& configName : this->CurrentConfigurationTypes) {
  1348. gtgt->CheckCxxModuleStatus(configName);
  1349. }
  1350. auto& gtgt_visited = this->CommandsVisited[gtgt];
  1351. auto const& deps = this->GetTargetDirectDepends(gtgt);
  1352. for (auto const& d : deps) {
  1353. // Take the union of visited source files of custom commands so far.
  1354. // ComputeTargetOrder ensures our dependencies already visited their
  1355. // custom commands and updated CommandsVisited.
  1356. auto& dep_visited = this->CommandsVisited[d];
  1357. gtgt_visited.insert(dep_visited.begin(), dep_visited.end());
  1358. }
  1359. if (gtgt->GetType() == cmStateEnums::UTILITY ||
  1360. gtgt->GetType() == cmStateEnums::INTERFACE_LIBRARY ||
  1361. gtgt->GetType() == cmStateEnums::GLOBAL_TARGET) {
  1362. cmXCodeObject* t = this->CreateUtilityTarget(gtgt);
  1363. if (!t) {
  1364. return false;
  1365. }
  1366. targets.push_back(t);
  1367. return true;
  1368. }
  1369. // organize the sources
  1370. std::vector<cmSourceFile*> commonSourceFiles;
  1371. if (!gtgt->GetConfigCommonSourceFilesForXcode(commonSourceFiles)) {
  1372. return false;
  1373. }
  1374. // Add CMakeLists.txt file for user convenience.
  1375. this->AddXCodeProjBuildRule(gtgt, commonSourceFiles);
  1376. // Add the Info.plist we are about to generate for an App Bundle.
  1377. if (gtgt->GetPropertyAsBool("MACOSX_BUNDLE")) {
  1378. std::string plist = this->ComputeInfoPListLocation(gtgt);
  1379. cmSourceFile* sf = gtgt->Makefile->GetOrCreateSource(
  1380. plist, true, cmSourceFileLocationKind::Known);
  1381. sf->SetSpecialSourceType(cmSourceFile::SpecialSourceType::BundleInfoPlist);
  1382. commonSourceFiles.push_back(sf);
  1383. }
  1384. std::sort(commonSourceFiles.begin(), commonSourceFiles.end(),
  1385. cmSourceFilePathCompare());
  1386. gtgt->ComputeObjectMapping();
  1387. std::vector<cmXCodeObject*> externalObjFiles;
  1388. std::vector<cmXCodeObject*> headerFiles;
  1389. std::vector<cmXCodeObject*> resourceFiles;
  1390. std::vector<cmXCodeObject*> sourceFiles;
  1391. for (auto* sourceFile : commonSourceFiles) {
  1392. cmXCodeObject* xsf = this->CreateXCodeSourceFile(
  1393. this->CurrentLocalGenerator, sourceFile, gtgt);
  1394. cmXCodeObject* fr = xsf->GetAttribute("fileRef");
  1395. cmXCodeObject* filetype =
  1396. fr->GetObject()->GetAttribute("explicitFileType");
  1397. if (!filetype) {
  1398. filetype = fr->GetObject()->GetAttribute("lastKnownFileType");
  1399. }
  1400. cmGeneratorTarget::SourceFileFlags tsFlags =
  1401. gtgt->GetTargetSourceFileFlags(sourceFile);
  1402. if (filetype && filetype->GetString() == "compiled.mach-o.objfile"_s) {
  1403. if (sourceFile->GetObjectLibrary().empty()) {
  1404. externalObjFiles.push_back(xsf);
  1405. }
  1406. } else if (this->IsHeaderFile(sourceFile) ||
  1407. (tsFlags.Type ==
  1408. cmGeneratorTarget::SourceFileTypePrivateHeader) ||
  1409. (tsFlags.Type ==
  1410. cmGeneratorTarget::SourceFileTypePublicHeader)) {
  1411. headerFiles.push_back(xsf);
  1412. } else if (tsFlags.Type == cmGeneratorTarget::SourceFileTypeResource) {
  1413. resourceFiles.push_back(xsf);
  1414. } else if (!sourceFile->GetPropertyAsBool("HEADER_FILE_ONLY") &&
  1415. !gtgt->IsSourceFilePartOfUnityBatch(
  1416. sourceFile->ResolveFullPath())) {
  1417. // Include this file in the build if it has a known language
  1418. // and has not been listed as an ignored extension for this
  1419. // generator.
  1420. if (!this->CurrentLocalGenerator->GetSourceFileLanguage(*sourceFile)
  1421. .empty() &&
  1422. !this->IgnoreFile(sourceFile->GetExtension().c_str())) {
  1423. sourceFiles.push_back(xsf);
  1424. }
  1425. }
  1426. }
  1427. // some build phases only apply to bundles and/or frameworks
  1428. bool isFrameworkTarget = gtgt->IsFrameworkOnApple();
  1429. bool isBundleTarget = gtgt->GetPropertyAsBool("MACOSX_BUNDLE");
  1430. bool isCFBundleTarget = gtgt->IsCFBundleOnApple();
  1431. cmXCodeObject* buildFiles = nullptr;
  1432. // create source build phase
  1433. cmXCodeObject* sourceBuildPhase = nullptr;
  1434. if (!sourceFiles.empty()) {
  1435. sourceBuildPhase = this->CreateObject(cmXCodeObject::PBXSourcesBuildPhase);
  1436. sourceBuildPhase->SetComment("Sources");
  1437. sourceBuildPhase->AddAttribute("buildActionMask",
  1438. this->CreateString("2147483647"));
  1439. buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1440. for (auto& sourceFile : sourceFiles) {
  1441. buildFiles->AddObject(sourceFile);
  1442. }
  1443. sourceBuildPhase->AddAttribute("files", buildFiles);
  1444. sourceBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1445. this->CreateString("0"));
  1446. }
  1447. // create header build phase - only for framework targets
  1448. cmXCodeObject* headerBuildPhase = nullptr;
  1449. if (!headerFiles.empty() && isFrameworkTarget) {
  1450. headerBuildPhase = this->CreateObject(cmXCodeObject::PBXHeadersBuildPhase);
  1451. headerBuildPhase->SetComment("Headers");
  1452. headerBuildPhase->AddAttribute("buildActionMask",
  1453. this->CreateString("2147483647"));
  1454. buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1455. for (auto& headerFile : headerFiles) {
  1456. buildFiles->AddObject(headerFile);
  1457. }
  1458. headerBuildPhase->AddAttribute("files", buildFiles);
  1459. headerBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1460. this->CreateString("0"));
  1461. }
  1462. // create resource build phase - only for framework or bundle targets
  1463. cmXCodeObject* resourceBuildPhase = nullptr;
  1464. if (!resourceFiles.empty() &&
  1465. (isFrameworkTarget || isBundleTarget || isCFBundleTarget)) {
  1466. resourceBuildPhase =
  1467. this->CreateObject(cmXCodeObject::PBXResourcesBuildPhase);
  1468. resourceBuildPhase->SetComment("Resources");
  1469. resourceBuildPhase->AddAttribute("buildActionMask",
  1470. this->CreateString("2147483647"));
  1471. buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1472. for (auto& resourceFile : resourceFiles) {
  1473. buildFiles->AddObject(resourceFile);
  1474. }
  1475. resourceBuildPhase->AddAttribute("files", buildFiles);
  1476. resourceBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1477. this->CreateString("0"));
  1478. }
  1479. // create vector of "non-resource content file" build phases - only for
  1480. // framework or bundle targets
  1481. std::vector<cmXCodeObject*> contentBuildPhases;
  1482. if (isFrameworkTarget || isBundleTarget || isCFBundleTarget) {
  1483. using mapOfVectorOfSourceFiles =
  1484. std::map<std::string, std::vector<cmSourceFile*>>;
  1485. mapOfVectorOfSourceFiles bundleFiles;
  1486. for (auto* sourceFile : commonSourceFiles) {
  1487. cmGeneratorTarget::SourceFileFlags tsFlags =
  1488. gtgt->GetTargetSourceFileFlags(sourceFile);
  1489. if (tsFlags.Type == cmGeneratorTarget::SourceFileTypeMacContent) {
  1490. bundleFiles[tsFlags.MacFolder].push_back(sourceFile);
  1491. }
  1492. }
  1493. for (auto const& keySources : bundleFiles) {
  1494. cmXCodeObject* copyFilesBuildPhase =
  1495. this->CreateObject(cmXCodeObject::PBXCopyFilesBuildPhase);
  1496. copyFilesBuildPhase->SetComment("Copy files");
  1497. copyFilesBuildPhase->AddAttribute("buildActionMask",
  1498. this->CreateString("2147483647"));
  1499. copyFilesBuildPhase->AddAttribute("dstSubfolderSpec",
  1500. this->CreateString("6"));
  1501. std::ostringstream ostr;
  1502. if (gtgt->IsFrameworkOnApple()) {
  1503. // dstPath in frameworks is relative to Versions/<version>
  1504. ostr << keySources.first;
  1505. } else if (keySources.first != "MacOS"_s) {
  1506. if (gtgt->Target->GetMakefile()->PlatformIsAppleEmbedded()) {
  1507. ostr << keySources.first;
  1508. } else {
  1509. // dstPath in bundles is relative to Contents/MacOS
  1510. ostr << "../" << keySources.first;
  1511. }
  1512. }
  1513. copyFilesBuildPhase->AddAttribute("dstPath",
  1514. this->CreateString(ostr.str()));
  1515. copyFilesBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1516. this->CreateString("0"));
  1517. buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1518. copyFilesBuildPhase->AddAttribute("files", buildFiles);
  1519. for (auto* sourceFile : keySources.second) {
  1520. cmXCodeObject* xsf = this->CreateXCodeSourceFile(
  1521. this->CurrentLocalGenerator, sourceFile, gtgt);
  1522. buildFiles->AddObject(xsf);
  1523. }
  1524. contentBuildPhases.push_back(copyFilesBuildPhase);
  1525. }
  1526. }
  1527. // create vector of "resource content file" build phases - only for
  1528. // framework or bundle targets
  1529. if (isFrameworkTarget || isBundleTarget || isCFBundleTarget) {
  1530. using mapOfVectorOfSourceFiles =
  1531. std::map<std::string, std::vector<cmSourceFile*>>;
  1532. mapOfVectorOfSourceFiles bundleFiles;
  1533. for (auto* sourceFile : commonSourceFiles) {
  1534. cmGeneratorTarget::SourceFileFlags tsFlags =
  1535. gtgt->GetTargetSourceFileFlags(sourceFile);
  1536. if (tsFlags.Type == cmGeneratorTarget::SourceFileTypeDeepResource) {
  1537. bundleFiles[tsFlags.MacFolder].push_back(sourceFile);
  1538. }
  1539. }
  1540. for (auto const& keySources : bundleFiles) {
  1541. cmXCodeObject* copyFilesBuildPhase =
  1542. this->CreateObject(cmXCodeObject::PBXCopyFilesBuildPhase);
  1543. copyFilesBuildPhase->SetComment("Copy files");
  1544. copyFilesBuildPhase->AddAttribute("buildActionMask",
  1545. this->CreateString("2147483647"));
  1546. copyFilesBuildPhase->AddAttribute("dstSubfolderSpec",
  1547. this->CreateString("7"));
  1548. copyFilesBuildPhase->AddAttribute("dstPath",
  1549. this->CreateString(keySources.first));
  1550. copyFilesBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1551. this->CreateString("0"));
  1552. buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1553. copyFilesBuildPhase->AddAttribute("files", buildFiles);
  1554. for (auto* sourceFile : keySources.second) {
  1555. cmXCodeObject* xsf = this->CreateXCodeSourceFile(
  1556. this->CurrentLocalGenerator, sourceFile, gtgt);
  1557. buildFiles->AddObject(xsf);
  1558. }
  1559. contentBuildPhases.push_back(copyFilesBuildPhase);
  1560. }
  1561. }
  1562. // Always create Link Binary With Libraries build phase
  1563. cmXCodeObject* frameworkBuildPhase = nullptr;
  1564. frameworkBuildPhase =
  1565. this->CreateObject(cmXCodeObject::PBXFrameworksBuildPhase);
  1566. frameworkBuildPhase->SetComment("Frameworks");
  1567. frameworkBuildPhase->AddAttribute("buildActionMask",
  1568. this->CreateString("2147483647"));
  1569. buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1570. frameworkBuildPhase->AddAttribute("files", buildFiles);
  1571. // Add all collected .o files to this build phase
  1572. for (auto& externalObjFile : externalObjFiles) {
  1573. buildFiles->AddObject(externalObjFile);
  1574. }
  1575. frameworkBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1576. this->CreateString("0"));
  1577. // create list of build phases and create the Xcode target
  1578. cmXCodeObject* buildPhases = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1579. this->CreateCustomCommands(buildPhases, sourceBuildPhase, headerBuildPhase,
  1580. resourceBuildPhase, contentBuildPhases,
  1581. frameworkBuildPhase, gtgt);
  1582. targets.push_back(this->CreateXCodeTarget(gtgt, buildPhases));
  1583. return true;
  1584. }
  1585. void cmGlobalXCodeGenerator::ForceLinkerLanguages()
  1586. {
  1587. for (auto const& localGenerator : this->LocalGenerators) {
  1588. // All targets depend on the build-system check target.
  1589. for (auto const& tgt : localGenerator->GetGeneratorTargets()) {
  1590. // This makes sure all targets link using the proper language.
  1591. this->ForceLinkerLanguage(tgt.get());
  1592. }
  1593. }
  1594. }
  1595. void cmGlobalXCodeGenerator::ForceLinkerLanguage(cmGeneratorTarget* gtgt)
  1596. {
  1597. // This matters only for targets that link.
  1598. if (gtgt->GetType() != cmStateEnums::EXECUTABLE &&
  1599. gtgt->GetType() != cmStateEnums::SHARED_LIBRARY &&
  1600. gtgt->GetType() != cmStateEnums::MODULE_LIBRARY) {
  1601. return;
  1602. }
  1603. std::string llang = gtgt->GetLinkerLanguage("NOCONFIG");
  1604. if (llang.empty()) {
  1605. return;
  1606. }
  1607. // If the language is compiled as a source trust Xcode to link with it.
  1608. for (auto const& Language :
  1609. gtgt->GetLinkImplementation("NOCONFIG", cmGeneratorTarget::UseTo::Link)
  1610. ->Languages) {
  1611. if (Language == llang) {
  1612. return;
  1613. }
  1614. }
  1615. // Allow empty source file list for iOS Sticker packs
  1616. cm::string_view productType = this->GetTargetProductType(gtgt);
  1617. if (productType ==
  1618. "com.apple.product-type.app-extension.messages-sticker-pack"_s) {
  1619. return;
  1620. }
  1621. // Add an empty source file to the target that compiles with the
  1622. // linker language. This should convince Xcode to choose the proper
  1623. // language.
  1624. cmMakefile* mf = gtgt->Target->GetMakefile();
  1625. std::string fname = cmStrCat(
  1626. gtgt->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/CMakeFiles/",
  1627. gtgt->GetName(), "-CMakeForceLinker.", cmSystemTools::LowerCase(llang));
  1628. {
  1629. cmGeneratedFileStream fout(fname);
  1630. fout << '\n';
  1631. }
  1632. if (cmSourceFile* sf = mf->GetOrCreateSource(fname)) {
  1633. sf->SetSpecialSourceType(
  1634. cmSourceFile::SpecialSourceType::XcodeForceLinkerSource);
  1635. sf->SetProperty("LANGUAGE", llang);
  1636. sf->SetProperty("CXX_SCAN_FOR_MODULES", "0");
  1637. gtgt->AddSource(fname);
  1638. }
  1639. }
  1640. bool cmGlobalXCodeGenerator::IsHeaderFile(cmSourceFile* sf)
  1641. {
  1642. return cm::contains(this->CMakeInstance->GetHeaderExtensions(),
  1643. sf->GetExtension());
  1644. }
  1645. cmXCodeObject* cmGlobalXCodeGenerator::CreateLegacyRunScriptBuildPhase(
  1646. char const* name, char const* name2, cmGeneratorTarget* target,
  1647. std::vector<cmCustomCommand> const& commands)
  1648. {
  1649. if (commands.empty() && strcmp(name, "CMake ReRun") != 0) {
  1650. return nullptr;
  1651. }
  1652. cmXCodeObject* buildPhase =
  1653. this->CreateObject(cmXCodeObject::PBXShellScriptBuildPhase);
  1654. buildPhase->AddAttribute("buildActionMask",
  1655. this->CreateString("2147483647"));
  1656. cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1657. buildPhase->AddAttribute("files", buildFiles);
  1658. buildPhase->AddAttribute("name", this->CreateString(name));
  1659. buildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1660. this->CreateString("0"));
  1661. buildPhase->AddAttribute("shellPath", this->CreateString("/bin/sh"));
  1662. this->AddCommandsToBuildPhase(buildPhase, target, commands, name2);
  1663. return buildPhase;
  1664. }
  1665. void cmGlobalXCodeGenerator::CreateCustomCommands(
  1666. cmXCodeObject* buildPhases, cmXCodeObject* sourceBuildPhase,
  1667. cmXCodeObject* headerBuildPhase, cmXCodeObject* resourceBuildPhase,
  1668. std::vector<cmXCodeObject*> const& contentBuildPhases,
  1669. cmXCodeObject* frameworkBuildPhase, cmGeneratorTarget* gtgt)
  1670. {
  1671. std::vector<cmCustomCommand> const& prebuild = gtgt->GetPreBuildCommands();
  1672. std::vector<cmCustomCommand> const& prelink = gtgt->GetPreLinkCommands();
  1673. std::vector<cmCustomCommand> postbuild = gtgt->GetPostBuildCommands();
  1674. if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY &&
  1675. !gtgt->IsFrameworkOnApple()) {
  1676. std::string str_file = cmStrCat("$<TARGET_FILE:", gtgt->GetName(), '>');
  1677. std::string str_so_file =
  1678. cmStrCat("$<TARGET_SONAME_FILE:", gtgt->GetName(), '>');
  1679. std::string str_link_file =
  1680. cmStrCat("$<TARGET_LINKER_LIBRARY_FILE:", gtgt->GetName(), '>');
  1681. cmCustomCommandLines cmd = cmMakeSingleCommandLine(
  1682. { cmSystemTools::GetCMakeCommand(), "-E", "cmake_symlink_library",
  1683. str_file, str_so_file, str_link_file });
  1684. cmCustomCommand command;
  1685. command.SetCommandLines(cmd);
  1686. command.SetComment("Creating symlinks");
  1687. command.SetWorkingDirectory("");
  1688. command.SetBacktrace(this->CurrentMakefile->GetBacktrace());
  1689. command.SetStdPipesUTF8(true);
  1690. postbuild.push_back(std::move(command));
  1691. }
  1692. if (gtgt->HasImportLibrary("") && !gtgt->IsFrameworkOnApple()) {
  1693. // create symbolic links for .tbd file
  1694. std::string file = cmStrCat("$<TARGET_IMPORT_FILE:", gtgt->GetName(), '>');
  1695. std::string soFile =
  1696. cmStrCat("$<TARGET_SONAME_IMPORT_FILE:", gtgt->GetName(), '>');
  1697. std::string linkFile =
  1698. cmStrCat("$<TARGET_LINKER_IMPORT_FILE:", gtgt->GetName(), '>');
  1699. cmCustomCommandLines symlink_command = cmMakeSingleCommandLine(
  1700. { cmSystemTools::GetCMakeCommand(), "-E", "cmake_symlink_library", file,
  1701. soFile, linkFile });
  1702. cmCustomCommand command;
  1703. command.SetCommandLines(symlink_command);
  1704. command.SetComment("Creating import symlinks");
  1705. command.SetWorkingDirectory("");
  1706. command.SetBacktrace(this->CurrentMakefile->GetBacktrace());
  1707. command.SetStdPipesUTF8(true);
  1708. postbuild.push_back(std::move(command));
  1709. }
  1710. cmXCodeObject* legacyCustomCommandsBuildPhase = nullptr;
  1711. cmXCodeObject* preBuildPhase = nullptr;
  1712. cmXCodeObject* preLinkPhase = nullptr;
  1713. cmXCodeObject* postBuildPhase = nullptr;
  1714. if (this->XcodeBuildSystem >= BuildSystem::Twelve) {
  1715. // create prebuild phase
  1716. preBuildPhase =
  1717. this->CreateRunScriptBuildPhase("CMake PreBuild Rules", gtgt, prebuild);
  1718. // create prelink phase
  1719. preLinkPhase =
  1720. this->CreateRunScriptBuildPhase("CMake PreLink Rules", gtgt, prelink);
  1721. std::vector<std::string> depends;
  1722. if (gtgt->IsBundleOnApple()) {
  1723. // In Xcode 16+ the POST_BUILD phase needs explicit dependencies to
  1724. // ensure it runs after certain bundle files are generated.
  1725. depends = {
  1726. "${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}/"
  1727. "Contents/Resources/DWARF/${PRODUCT_NAME}",
  1728. "${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}/"
  1729. "Contents/Info.plist",
  1730. "$(TARGET_BUILD_DIR)/$(EXECUTABLE_PATH)",
  1731. "$(TARGET_BUILD_DIR)/$(INFOPLIST_PATH)",
  1732. };
  1733. if (resourceBuildPhase) {
  1734. auto resourceFiles = resourceBuildPhase->GetAttribute("files");
  1735. for (auto xsf : resourceFiles->GetObjectList()) {
  1736. auto fileRef = xsf->GetAttribute("fileRef");
  1737. auto fileObj = fileRef->GetObject();
  1738. auto path = fileObj->GetAttribute("path");
  1739. auto fileName = cmSystemTools::GetFilenameName(path->GetString());
  1740. if (cmSystemTools::GetFilenameLastExtension(fileName) == ".plist") {
  1741. depends.push_back(
  1742. "$(TARGET_BUILD_DIR)/$(UNLOCALIZED_RESOURCES_FOLDER_PATH)/" +
  1743. fileName);
  1744. }
  1745. }
  1746. }
  1747. }
  1748. // create postbuild phase
  1749. postBuildPhase = this->CreateRunScriptBuildPhase("CMake PostBuild Rules",
  1750. gtgt, postbuild, depends);
  1751. } else {
  1752. std::vector<cmSourceFile*> classes;
  1753. if (!gtgt->GetConfigCommonSourceFilesForXcode(classes)) {
  1754. return;
  1755. }
  1756. // add all the sources
  1757. std::vector<cmCustomCommand> commands;
  1758. auto& visited = this->CommandsVisited[gtgt];
  1759. for (auto* sourceFile : classes) {
  1760. if (sourceFile->GetCustomCommand() &&
  1761. visited.insert(sourceFile).second) {
  1762. commands.push_back(*sourceFile->GetCustomCommand());
  1763. }
  1764. }
  1765. // create custom commands phase
  1766. legacyCustomCommandsBuildPhase = this->CreateLegacyRunScriptBuildPhase(
  1767. "CMake Rules", "cmakeRulesBuildPhase", gtgt, commands);
  1768. // create prebuild phase
  1769. preBuildPhase = this->CreateLegacyRunScriptBuildPhase(
  1770. "CMake PreBuild Rules", "preBuildCommands", gtgt, prebuild);
  1771. // create prelink phase
  1772. preLinkPhase = this->CreateLegacyRunScriptBuildPhase(
  1773. "CMake PreLink Rules", "preLinkCommands", gtgt, prelink);
  1774. // create postbuild phase
  1775. postBuildPhase = this->CreateLegacyRunScriptBuildPhase(
  1776. "CMake PostBuild Rules", "postBuildPhase", gtgt, postbuild);
  1777. }
  1778. // The order here is the order they will be built in.
  1779. // The order "headers, resources, sources" mimics a native project generated
  1780. // from an xcode template...
  1781. //
  1782. if (preBuildPhase) {
  1783. buildPhases->AddObject(preBuildPhase);
  1784. }
  1785. if (legacyCustomCommandsBuildPhase) {
  1786. buildPhases->AddObject(legacyCustomCommandsBuildPhase);
  1787. }
  1788. if (this->XcodeBuildSystem >= BuildSystem::Twelve) {
  1789. this->CreateRunScriptBuildPhases(buildPhases, gtgt);
  1790. }
  1791. if (headerBuildPhase) {
  1792. buildPhases->AddObject(headerBuildPhase);
  1793. }
  1794. if (resourceBuildPhase) {
  1795. buildPhases->AddObject(resourceBuildPhase);
  1796. }
  1797. for (auto* obj : contentBuildPhases) {
  1798. buildPhases->AddObject(obj);
  1799. }
  1800. if (sourceBuildPhase) {
  1801. buildPhases->AddObject(sourceBuildPhase);
  1802. }
  1803. if (preLinkPhase) {
  1804. buildPhases->AddObject(preLinkPhase);
  1805. }
  1806. if (frameworkBuildPhase) {
  1807. buildPhases->AddObject(frameworkBuildPhase);
  1808. }
  1809. // When this build phase is present, it must be last. More build phases may
  1810. // be added later for embedding things and they will insert themselves just
  1811. // before this last build phase.
  1812. if (postBuildPhase) {
  1813. buildPhases->AddObject(postBuildPhase);
  1814. }
  1815. }
  1816. void cmGlobalXCodeGenerator::CreateRunScriptBuildPhases(
  1817. cmXCodeObject* buildPhases, cmGeneratorTarget const* gt)
  1818. {
  1819. std::vector<cmSourceFile*> sources;
  1820. if (!gt->GetConfigCommonSourceFilesForXcode(sources)) {
  1821. return;
  1822. }
  1823. auto& visited = this->CommandsVisited[gt];
  1824. for (auto* sf : sources) {
  1825. this->CreateRunScriptBuildPhases(buildPhases, sf, gt, visited);
  1826. }
  1827. }
  1828. void cmGlobalXCodeGenerator::CreateRunScriptBuildPhases(
  1829. cmXCodeObject* buildPhases, cmSourceFile const* sf,
  1830. cmGeneratorTarget const* gt, std::set<cmSourceFile const*>& visited)
  1831. {
  1832. cmCustomCommand const* cc = sf->GetCustomCommand();
  1833. if (cc && visited.insert(sf).second) {
  1834. this->CustomCommandRoots[sf].insert(gt);
  1835. if (std::vector<cmSourceFile*> const* depends = gt->GetSourceDepends(sf)) {
  1836. for (cmSourceFile const* di : *depends) {
  1837. this->CreateRunScriptBuildPhases(buildPhases, di, gt, visited);
  1838. }
  1839. }
  1840. cmXCodeObject* buildPhase = this->CreateRunScriptBuildPhase(sf, gt, *cc);
  1841. buildPhases->AddObject(buildPhase);
  1842. }
  1843. }
  1844. cmXCodeObject* cmGlobalXCodeGenerator::CreateRunScriptBuildPhase(
  1845. cmSourceFile const* sf, cmGeneratorTarget const* gt,
  1846. cmCustomCommand const& cc)
  1847. {
  1848. std::set<std::string> allConfigInputs;
  1849. std::set<std::string> allConfigOutputs;
  1850. cmXCodeObject* buildPhase =
  1851. this->CreateObject(cmXCodeObject::PBXShellScriptBuildPhase,
  1852. cmStrCat(gt->GetName(), ':', sf->GetFullPath()));
  1853. auto depfilesDirectory = cmStrCat(
  1854. gt->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/CMakeFiles/d/");
  1855. auto depfilesPrefix = cmStrCat(depfilesDirectory, buildPhase->GetId(), '.');
  1856. std::string shellScript = "set -e\n";
  1857. for (std::string const& configName : this->CurrentConfigurationTypes) {
  1858. cmCustomCommandGenerator ccg(
  1859. cc, configName, this->CurrentLocalGenerator, true, {},
  1860. [&depfilesPrefix](std::string const& config, std::string const&)
  1861. -> std::string { return cmStrCat(depfilesPrefix, config, ".d"); });
  1862. std::vector<std::string> realDepends;
  1863. realDepends.reserve(ccg.GetDepends().size());
  1864. for (auto const& d : ccg.GetDepends()) {
  1865. std::string dep;
  1866. if (this->CurrentLocalGenerator->GetRealDependency(d, configName, dep)) {
  1867. realDepends.emplace_back(std::move(dep));
  1868. }
  1869. }
  1870. allConfigInputs.insert(realDepends.begin(), realDepends.end());
  1871. allConfigOutputs.insert(ccg.GetByproducts().begin(),
  1872. ccg.GetByproducts().end());
  1873. allConfigOutputs.insert(ccg.GetOutputs().begin(), ccg.GetOutputs().end());
  1874. shellScript =
  1875. cmStrCat(shellScript, R"(if test "$CONFIGURATION" = ")", configName,
  1876. "\"; then :\n", this->ConstructScript(ccg), "fi\n");
  1877. }
  1878. if (!cc.GetDepfile().empty()) {
  1879. buildPhase->AddAttribute(
  1880. "dependencyFile",
  1881. this->CreateString(cmStrCat(depfilesDirectory, buildPhase->GetId(),
  1882. ".$(CONFIGURATION).d")));
  1883. // to avoid spurious errors during first build, create empty dependency
  1884. // files
  1885. cmSystemTools::MakeDirectory(depfilesDirectory);
  1886. for (std::string const& configName : this->CurrentConfigurationTypes) {
  1887. auto file = cmStrCat(depfilesPrefix, configName, ".d");
  1888. if (!cmSystemTools::FileExists(file)) {
  1889. cmSystemTools::Touch(file, true);
  1890. }
  1891. }
  1892. }
  1893. buildPhase->AddAttribute("buildActionMask",
  1894. this->CreateString("2147483647"));
  1895. cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1896. buildPhase->AddAttribute("files", buildFiles);
  1897. {
  1898. std::string name;
  1899. if (!allConfigOutputs.empty()) {
  1900. name = cmStrCat("Generate ",
  1901. this->RelativeToBinary(*allConfigOutputs.begin()));
  1902. } else {
  1903. name = sf->GetLocation().GetName();
  1904. }
  1905. buildPhase->AddAttribute("name", this->CreateString(name));
  1906. }
  1907. buildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1908. this->CreateString("0"));
  1909. buildPhase->AddAttribute("shellPath", this->CreateString("/bin/sh"));
  1910. buildPhase->AddAttribute("shellScript", this->CreateString(shellScript));
  1911. buildPhase->AddAttribute("showEnvVarsInLog", this->CreateString("0"));
  1912. bool symbolic = false;
  1913. {
  1914. cmXCodeObject* inputPaths = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1915. for (std::string const& i : allConfigInputs) {
  1916. inputPaths->AddUniqueObject(this->CreateString(i));
  1917. if (!symbolic) {
  1918. if (cmSourceFile* isf =
  1919. gt->GetLocalGenerator()->GetMakefile()->GetSource(
  1920. i, cmSourceFileLocationKind::Known)) {
  1921. symbolic = isf->GetPropertyAsBool("SYMBOLIC");
  1922. }
  1923. }
  1924. }
  1925. buildPhase->AddAttribute("inputPaths", inputPaths);
  1926. }
  1927. {
  1928. cmXCodeObject* outputPaths =
  1929. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1930. for (std::string const& o : allConfigOutputs) {
  1931. outputPaths->AddUniqueObject(this->CreateString(o));
  1932. if (!symbolic) {
  1933. if (cmSourceFile* osf =
  1934. gt->GetLocalGenerator()->GetMakefile()->GetSource(
  1935. o, cmSourceFileLocationKind::Known)) {
  1936. symbolic = osf->GetPropertyAsBool("SYMBOLIC");
  1937. }
  1938. }
  1939. }
  1940. buildPhase->AddAttribute("outputPaths", outputPaths);
  1941. }
  1942. if (symbolic) {
  1943. buildPhase->AddAttribute("alwaysOutOfDate", this->CreateString("1"));
  1944. }
  1945. return buildPhase;
  1946. }
  1947. cmXCodeObject* cmGlobalXCodeGenerator::CreateRunScriptBuildPhase(
  1948. std::string const& name, cmGeneratorTarget const* gt,
  1949. std::vector<cmCustomCommand> const& commands,
  1950. std::vector<std::string> const& depends)
  1951. {
  1952. if (commands.empty()) {
  1953. return nullptr;
  1954. }
  1955. std::set<std::string> allConfigOutputs;
  1956. std::string shellScript = "set -e\n";
  1957. for (std::string const& configName : this->CurrentConfigurationTypes) {
  1958. shellScript = cmStrCat(shellScript, R"(if test "$CONFIGURATION" = ")",
  1959. configName, "\"; then :\n");
  1960. for (cmCustomCommand const& cc : commands) {
  1961. cmCustomCommandGenerator ccg(cc, configName,
  1962. this->CurrentLocalGenerator);
  1963. shellScript = cmStrCat(shellScript, this->ConstructScript(ccg));
  1964. allConfigOutputs.insert(ccg.GetByproducts().begin(),
  1965. ccg.GetByproducts().end());
  1966. }
  1967. shellScript = cmStrCat(shellScript, "fi\n");
  1968. }
  1969. cmXCodeObject* buildPhase =
  1970. this->CreateObject(cmXCodeObject::PBXShellScriptBuildPhase,
  1971. cmStrCat(gt->GetName(), ':', name));
  1972. buildPhase->AddAttribute("buildActionMask",
  1973. this->CreateString("2147483647"));
  1974. cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1975. buildPhase->AddAttribute("files", buildFiles);
  1976. buildPhase->AddAttribute("name", this->CreateString(name));
  1977. buildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1978. this->CreateString("0"));
  1979. buildPhase->AddAttribute("shellPath", this->CreateString("/bin/sh"));
  1980. buildPhase->AddAttribute("shellScript", this->CreateString(shellScript));
  1981. buildPhase->AddAttribute("showEnvVarsInLog", this->CreateString("0"));
  1982. {
  1983. cmXCodeObject* inputPaths = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1984. for (std::string const& s : depends) {
  1985. inputPaths->AddUniqueObject(this->CreateString(s));
  1986. }
  1987. buildPhase->AddAttribute("inputPaths", inputPaths);
  1988. }
  1989. {
  1990. cmXCodeObject* outputPaths =
  1991. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1992. for (std::string const& o : allConfigOutputs) {
  1993. outputPaths->AddUniqueObject(this->CreateString(o));
  1994. }
  1995. buildPhase->AddAttribute("outputPaths", outputPaths);
  1996. }
  1997. buildPhase->AddAttribute("alwaysOutOfDate", this->CreateString("1"));
  1998. return buildPhase;
  1999. }
  2000. namespace {
  2001. void ReplaceScriptVars(std::string& cmd)
  2002. {
  2003. cmSystemTools::ReplaceString(cmd, "$(CONFIGURATION)", "$CONFIGURATION");
  2004. cmSystemTools::ReplaceString(cmd, "$(EFFECTIVE_PLATFORM_NAME)",
  2005. "$EFFECTIVE_PLATFORM_NAME");
  2006. }
  2007. }
  2008. std::string cmGlobalXCodeGenerator::ConstructScript(
  2009. cmCustomCommandGenerator const& ccg)
  2010. {
  2011. std::string script;
  2012. cmLocalGenerator* lg = this->CurrentLocalGenerator;
  2013. std::string wd = ccg.GetWorkingDirectory();
  2014. if (wd.empty()) {
  2015. wd = lg->GetCurrentBinaryDirectory();
  2016. }
  2017. wd = lg->ConvertToOutputFormat(wd, cmOutputConverter::SHELL);
  2018. ReplaceScriptVars(wd);
  2019. script = cmStrCat(script, " cd ", wd, '\n');
  2020. for (unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) {
  2021. std::string cmd = ccg.GetCommand(c);
  2022. if (cmd.empty()) {
  2023. continue;
  2024. }
  2025. cmSystemTools::ReplaceString(cmd, "/./", "/");
  2026. cmd = lg->ConvertToOutputFormat(cmd, cmOutputConverter::SHELL);
  2027. ccg.AppendArguments(c, cmd);
  2028. ReplaceScriptVars(cmd);
  2029. script = cmStrCat(script, " ", cmd, '\n');
  2030. }
  2031. return script;
  2032. }
  2033. // This function removes each occurrence of the flag and returns the last one
  2034. // (i.e., the dominant flag in GCC)
  2035. std::string cmGlobalXCodeGenerator::ExtractFlag(char const* flag,
  2036. std::string& flags)
  2037. {
  2038. std::string retFlag;
  2039. std::string::size_type lastOccurrencePos = flags.rfind(flag);
  2040. bool saved = false;
  2041. while (lastOccurrencePos != std::string::npos) {
  2042. // increment pos, we use lastOccurrencePos to reduce search space on next
  2043. // inc
  2044. std::string::size_type pos = lastOccurrencePos;
  2045. if (pos == 0 || flags[pos - 1] == ' ') {
  2046. while (pos < flags.size() && flags[pos] != ' ') {
  2047. if (!saved) {
  2048. retFlag += flags[pos];
  2049. }
  2050. flags[pos] = ' ';
  2051. pos++;
  2052. }
  2053. saved = true;
  2054. }
  2055. // decrement lastOccurrencePos while making sure we don't loop around
  2056. // and become a very large positive number since size_type is unsigned
  2057. lastOccurrencePos = lastOccurrencePos == 0 ? 0 : lastOccurrencePos - 1;
  2058. lastOccurrencePos = flags.rfind(flag, lastOccurrencePos);
  2059. }
  2060. return retFlag;
  2061. }
  2062. // This function removes each matching occurrence of the expression and
  2063. // returns the last one (i.e., the dominant flag in GCC)
  2064. std::string cmGlobalXCodeGenerator::ExtractFlagRegex(char const* exp,
  2065. int matchIndex,
  2066. std::string& flags)
  2067. {
  2068. std::string retFlag;
  2069. cmsys::RegularExpression regex(exp);
  2070. assert(regex.is_valid());
  2071. if (!regex.is_valid()) {
  2072. return retFlag;
  2073. }
  2074. std::string::size_type offset = 0;
  2075. while (regex.find(&flags[offset])) {
  2076. std::string::size_type const startPos = offset + regex.start(matchIndex);
  2077. std::string::size_type const endPos = offset + regex.end(matchIndex);
  2078. std::string::size_type const size = endPos - startPos;
  2079. offset = startPos + 1;
  2080. retFlag.assign(flags, startPos, size);
  2081. flags.replace(startPos, size, size, ' ');
  2082. }
  2083. return retFlag;
  2084. }
  2085. //----------------------------------------------------------------------------
  2086. // This function strips off Xcode attributes that do not target the current
  2087. // configuration
  2088. void cmGlobalXCodeGenerator::FilterConfigurationAttribute(
  2089. std::string const& configName, std::string& attribute)
  2090. {
  2091. // Handle [variant=<config>] condition explicitly here.
  2092. std::string::size_type beginVariant = attribute.find("[variant=");
  2093. if (beginVariant == std::string::npos) {
  2094. // There is no variant in this attribute.
  2095. return;
  2096. }
  2097. std::string::size_type endVariant = attribute.find(']', beginVariant + 9);
  2098. if (endVariant == std::string::npos) {
  2099. // There is no terminating bracket.
  2100. return;
  2101. }
  2102. // Compare the variant to the configuration.
  2103. std::string variant =
  2104. attribute.substr(beginVariant + 9, endVariant - beginVariant - 9);
  2105. if (variant == configName) {
  2106. // The variant matches the configuration so use this
  2107. // attribute but drop the [variant=<config>] condition.
  2108. attribute.erase(beginVariant, endVariant - beginVariant + 1);
  2109. } else {
  2110. // The variant does not match the configuration so
  2111. // do not use this attribute.
  2112. attribute.clear();
  2113. }
  2114. }
  2115. void cmGlobalXCodeGenerator::AddCommandsToBuildPhase(
  2116. cmXCodeObject* buildphase, cmGeneratorTarget* target,
  2117. std::vector<cmCustomCommand> const& commands, char const* name)
  2118. {
  2119. std::string dir = cmStrCat(
  2120. this->CurrentLocalGenerator->GetCurrentBinaryDirectory(), "/CMakeScripts");
  2121. cmSystemTools::MakeDirectory(dir);
  2122. std::string makefile =
  2123. cmStrCat(dir, '/', target->GetName(), '_', name, ".make");
  2124. for (auto const& currentConfig : this->CurrentConfigurationTypes) {
  2125. this->CreateCustomRulesMakefile(makefile.c_str(), target, commands,
  2126. currentConfig);
  2127. }
  2128. std::string cdir = this->CurrentLocalGenerator->GetCurrentBinaryDirectory();
  2129. cdir = cmSystemTools::ConvertToOutputPath(cdir);
  2130. std::string makecmd = cmStrCat(
  2131. "make -C ", cdir, " -f ", cmSystemTools::ConvertToOutputPath(makefile),
  2132. "$CONFIGURATION OBJDIR=$(basename \"$OBJECT_FILE_DIR_normal\") all");
  2133. buildphase->AddAttribute("shellScript", this->CreateString(makecmd));
  2134. buildphase->AddAttribute("showEnvVarsInLog", this->CreateString("0"));
  2135. }
  2136. void cmGlobalXCodeGenerator::CreateCustomRulesMakefile(
  2137. char const* makefileBasename, cmGeneratorTarget* target,
  2138. std::vector<cmCustomCommand> const& commands, std::string const& configName)
  2139. {
  2140. std::string makefileName = cmStrCat(makefileBasename, configName);
  2141. cmGeneratedFileStream makefileStream(makefileName);
  2142. if (!makefileStream) {
  2143. return;
  2144. }
  2145. makefileStream.SetCopyIfDifferent(true);
  2146. makefileStream << "# Generated by CMake, DO NOT EDIT\n"
  2147. "# Custom rules for "
  2148. << target->GetName() << '\n';
  2149. // disable the implicit rules
  2150. makefileStream << ".SUFFIXES: "
  2151. "\n";
  2152. // have all depend on all outputs
  2153. makefileStream << "all: ";
  2154. std::map<cmCustomCommand const*, std::string> tname;
  2155. int count = 0;
  2156. for (auto const& command : commands) {
  2157. cmCustomCommandGenerator ccg(command, configName,
  2158. this->CurrentLocalGenerator);
  2159. if (ccg.GetNumberOfCommands() > 0) {
  2160. std::vector<std::string> const& outputs = ccg.GetOutputs();
  2161. if (!outputs.empty()) {
  2162. for (auto const& output : outputs) {
  2163. makefileStream << "\\\n\t" << ConvertToMakefilePath(output);
  2164. }
  2165. } else {
  2166. std::ostringstream str;
  2167. str << "_buildpart_" << count++;
  2168. tname[&ccg.GetCC()] = cmStrCat(target->GetName(), str.str());
  2169. makefileStream << "\\\n\t" << tname[&ccg.GetCC()];
  2170. }
  2171. }
  2172. }
  2173. makefileStream << "\n\n";
  2174. auto depfilesDirectory =
  2175. cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(),
  2176. "/CMakeFiles/d/");
  2177. for (auto const& command : commands) {
  2178. cmCustomCommandGenerator ccg(
  2179. command, configName, this->CurrentLocalGenerator, true, {},
  2180. [this, &depfilesDirectory](std::string const& config,
  2181. std::string const& file) -> std::string {
  2182. return cmStrCat(
  2183. depfilesDirectory,
  2184. this->GetObjectId(cmXCodeObject::PBXShellScriptBuildPhase, file),
  2185. '.', config, ".d");
  2186. });
  2187. auto depfile = ccg.GetInternalDepfile();
  2188. if (!depfile.empty()) {
  2189. makefileStream << "include "
  2190. << cmSystemTools::ConvertToOutputPath(depfile) << "\n\n";
  2191. cmSystemTools::MakeDirectory(depfilesDirectory);
  2192. if (!cmSystemTools::FileExists(depfile)) {
  2193. cmSystemTools::Touch(depfile, true);
  2194. }
  2195. }
  2196. std::vector<std::string> realDepends;
  2197. realDepends.reserve(ccg.GetDepends().size());
  2198. for (auto const& d : ccg.GetDepends()) {
  2199. std::string dep;
  2200. if (this->CurrentLocalGenerator->GetRealDependency(d, configName, dep)) {
  2201. realDepends.emplace_back(std::move(dep));
  2202. }
  2203. }
  2204. if (ccg.GetNumberOfCommands() > 0) {
  2205. makefileStream << '\n';
  2206. std::vector<std::string> const& outputs = ccg.GetOutputs();
  2207. if (!outputs.empty()) {
  2208. // There is at least one output, start the rule for it
  2209. char const* sep = "";
  2210. for (auto const& output : outputs) {
  2211. makefileStream << sep << ConvertToMakefilePath(output);
  2212. sep = " ";
  2213. }
  2214. makefileStream << ": ";
  2215. } else {
  2216. // There are no outputs. Use the generated force rule name.
  2217. makefileStream << tname[&ccg.GetCC()] << ": ";
  2218. }
  2219. for (auto const& dep : realDepends) {
  2220. makefileStream << "\\\n" << ConvertToMakefilePath(dep);
  2221. }
  2222. makefileStream << '\n';
  2223. if (cm::optional<std::string> comment = ccg.GetComment()) {
  2224. std::string echo_cmd =
  2225. cmStrCat("echo ",
  2226. (this->CurrentLocalGenerator->EscapeForShell(
  2227. *comment, ccg.GetCC().GetEscapeAllowMakeVars())));
  2228. makefileStream << '\t' << echo_cmd << '\n';
  2229. }
  2230. // Add each command line to the set of commands.
  2231. for (unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) {
  2232. // Build the command line in a single string.
  2233. std::string cmd2 = ccg.GetCommand(c);
  2234. cmSystemTools::ReplaceString(cmd2, "/./", "/");
  2235. cmd2 = ConvertToMakefilePath(cmd2);
  2236. std::string cmd;
  2237. std::string wd = ccg.GetWorkingDirectory();
  2238. if (!wd.empty()) {
  2239. cmd += "cd ";
  2240. cmd += ConvertToMakefilePath(wd);
  2241. cmd += " && ";
  2242. }
  2243. cmd += cmd2;
  2244. ccg.AppendArguments(c, cmd);
  2245. makefileStream << '\t' << cmd << '\n';
  2246. }
  2247. // Symbolic inputs are not expected to exist, so add dummy rules.
  2248. for (auto const& dep : realDepends) {
  2249. if (cmSourceFile* dsf =
  2250. target->GetLocalGenerator()->GetMakefile()->GetSource(
  2251. dep, cmSourceFileLocationKind::Known)) {
  2252. if (dsf->GetPropertyAsBool("SYMBOLIC")) {
  2253. makefileStream << ConvertToMakefilePath(dep) << ":\n";
  2254. }
  2255. }
  2256. }
  2257. }
  2258. }
  2259. }
  2260. void cmGlobalXCodeGenerator::AddPositionIndependentLinkAttribute(
  2261. cmGeneratorTarget* target, cmXCodeObject* buildSettings,
  2262. std::string const& configName)
  2263. {
  2264. // For now, only EXECUTABLE is concerned
  2265. if (target->GetType() != cmStateEnums::EXECUTABLE) {
  2266. return;
  2267. }
  2268. char const* PICValue = target->GetLinkPIEProperty(configName);
  2269. if (PICValue == nullptr) {
  2270. // POSITION_INDEPENDENT_CODE is not set
  2271. return;
  2272. }
  2273. buildSettings->AddAttribute(
  2274. "LD_NO_PIE", this->CreateString(cmIsOn(PICValue) ? "NO" : "YES"));
  2275. }
  2276. void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
  2277. cmXCodeObject* buildSettings,
  2278. std::string const& configName)
  2279. {
  2280. if (!gtgt->IsInBuildSystem()) {
  2281. return;
  2282. }
  2283. std::string defFlags;
  2284. bool shared = ((gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) ||
  2285. (gtgt->GetType() == cmStateEnums::MODULE_LIBRARY));
  2286. bool binary = ((gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY) ||
  2287. (gtgt->GetType() == cmStateEnums::STATIC_LIBRARY) ||
  2288. (gtgt->GetType() == cmStateEnums::EXECUTABLE) || shared);
  2289. // Compute the compilation flags for each language.
  2290. std::set<std::string> languages;
  2291. gtgt->GetLanguages(languages, configName);
  2292. std::map<std::string, std::string> cflags;
  2293. for (auto const& lang : languages) {
  2294. std::string& flags = cflags[lang];
  2295. // Add language-specific flags.
  2296. this->CurrentLocalGenerator->AddLanguageFlags(
  2297. flags, gtgt, cmBuildStep::Compile, lang, configName);
  2298. if (gtgt->IsIPOEnabled(lang, configName)) {
  2299. this->CurrentLocalGenerator->AppendFeatureOptions(flags, lang, "IPO");
  2300. }
  2301. this->CurrentLocalGenerator->AddFeatureFlags(flags, gtgt, lang,
  2302. configName);
  2303. this->CurrentLocalGenerator->AddVisibilityPresetFlags(flags, gtgt, lang);
  2304. this->CurrentLocalGenerator->AddCompileOptions(flags, gtgt, lang,
  2305. configName);
  2306. }
  2307. std::string llang = gtgt->GetLinkerLanguage(configName);
  2308. if (binary && llang.empty()) {
  2309. cmSystemTools::Error(
  2310. cmStrCat("CMake can not determine linker language for target: ",
  2311. gtgt->GetName()));
  2312. return;
  2313. }
  2314. // Choose a language to use for target-wide preprocessor definitions.
  2315. static char const* ppLangs[] = { "CXX", "C", "OBJCXX", "OBJC" };
  2316. std::string langForPreprocessorDefinitions;
  2317. if (cm::contains(ppLangs, llang)) {
  2318. langForPreprocessorDefinitions = llang;
  2319. } else {
  2320. for (char const* l : ppLangs) {
  2321. if (languages.count(l)) {
  2322. langForPreprocessorDefinitions = l;
  2323. break;
  2324. }
  2325. }
  2326. }
  2327. if (gtgt->IsIPOEnabled(llang, configName)) {
  2328. char const* ltoValue =
  2329. this->CurrentMakefile->IsOn("_CMAKE_LTO_THIN") ? "YES_THIN" : "YES";
  2330. buildSettings->AddAttribute("LLVM_LTO", this->CreateString(ltoValue));
  2331. }
  2332. // Handle PIE linker configuration
  2333. this->AddPositionIndependentLinkAttribute(gtgt, buildSettings, configName);
  2334. // Add define flags
  2335. this->CurrentLocalGenerator->AppendFlags(
  2336. defFlags, this->CurrentMakefile->GetDefineFlags());
  2337. // Add preprocessor definitions for this target and configuration.
  2338. BuildObjectListOrString ppDefs(this, true);
  2339. this->AppendDefines(
  2340. ppDefs, "CMAKE_INTDIR=\"$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)\"");
  2341. if (std::string const* exportMacro = gtgt->GetExportMacro()) {
  2342. // Add the export symbol definition for shared library objects.
  2343. this->AppendDefines(ppDefs, exportMacro->c_str());
  2344. }
  2345. for (auto const& sharedLibCompileDef :
  2346. gtgt->GetSharedLibraryCompileDefs(configName)) {
  2347. this->AppendDefines(ppDefs, sharedLibCompileDef.c_str());
  2348. }
  2349. std::vector<std::string> targetDefines;
  2350. if (!langForPreprocessorDefinitions.empty()) {
  2351. gtgt->GetCompileDefinitions(targetDefines, configName,
  2352. langForPreprocessorDefinitions);
  2353. }
  2354. this->AppendDefines(ppDefs, targetDefines);
  2355. buildSettings->AddAttribute("GCC_PREPROCESSOR_DEFINITIONS",
  2356. ppDefs.CreateList());
  2357. if (languages.count("Swift")) {
  2358. // Swift uses a separate attribute for definitions.
  2359. std::vector<std::string> targetSwiftDefines;
  2360. gtgt->GetCompileDefinitions(targetSwiftDefines, configName, "Swift");
  2361. // Remove the '=value' parts, as Swift does not support them.
  2362. std::for_each(targetSwiftDefines.begin(), targetSwiftDefines.end(),
  2363. [](std::string& def) {
  2364. std::string::size_type pos = def.find('=');
  2365. if (pos != std::string::npos) {
  2366. def.erase(pos);
  2367. }
  2368. });
  2369. if (this->XcodeVersion < 80) {
  2370. std::string defineString;
  2371. std::set<std::string> defines(targetSwiftDefines.begin(),
  2372. targetSwiftDefines.end());
  2373. this->CurrentLocalGenerator->JoinDefines(defines, defineString, "Swift");
  2374. cflags["Swift"] += cmStrCat(' ', defineString);
  2375. } else {
  2376. BuildObjectListOrString swiftDefs(this, true);
  2377. this->AppendDefines(swiftDefs, targetSwiftDefines);
  2378. buildSettings->AddAttribute("SWIFT_ACTIVE_COMPILATION_CONDITIONS",
  2379. swiftDefs.CreateList());
  2380. }
  2381. if (cm::optional<cmSwiftCompileMode> swiftCompileMode =
  2382. this->CurrentLocalGenerator->GetSwiftCompileMode(gtgt, configName)) {
  2383. switch (*swiftCompileMode) {
  2384. case cmSwiftCompileMode::Wholemodule:
  2385. buildSettings->AddAttribute("SWIFT_COMPILATION_MODE",
  2386. this->CreateString("wholemodule"));
  2387. break;
  2388. case cmSwiftCompileMode::Incremental:
  2389. case cmSwiftCompileMode::Singlefile:
  2390. break;
  2391. case cmSwiftCompileMode::Unknown:
  2392. this->CurrentLocalGenerator->IssueMessage(
  2393. MessageType::AUTHOR_WARNING,
  2394. cmStrCat("Unknown Swift_COMPILATION_MODE on target '",
  2395. gtgt->GetName(), '\''));
  2396. break;
  2397. }
  2398. }
  2399. }
  2400. std::string extraLinkOptionsVar;
  2401. std::string extraLinkOptions;
  2402. if (gtgt->GetType() == cmStateEnums::EXECUTABLE) {
  2403. extraLinkOptionsVar = "CMAKE_EXE_LINKER_FLAGS";
  2404. } else if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) {
  2405. extraLinkOptionsVar = "CMAKE_SHARED_LINKER_FLAGS";
  2406. } else if (gtgt->GetType() == cmStateEnums::MODULE_LIBRARY) {
  2407. extraLinkOptionsVar = "CMAKE_MODULE_LINKER_FLAGS";
  2408. }
  2409. if (!extraLinkOptionsVar.empty()) {
  2410. this->CurrentLocalGenerator->AddConfigVariableFlags(
  2411. extraLinkOptions, extraLinkOptionsVar, gtgt, cmBuildStep::Link, llang,
  2412. configName);
  2413. }
  2414. if (gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  2415. gtgt->GetType() == cmStateEnums::STATIC_LIBRARY) {
  2416. this->CurrentLocalGenerator->GetStaticLibraryFlags(
  2417. extraLinkOptions, configName, llang, gtgt);
  2418. } else {
  2419. this->CurrentLocalGenerator->AppendLinkerTypeFlags(extraLinkOptions, gtgt,
  2420. configName, llang);
  2421. this->CurrentLocalGenerator->AppendWarningAsErrorLinkerFlags(
  2422. extraLinkOptions, gtgt, llang);
  2423. cmValue targetLinkFlags = gtgt->GetProperty("LINK_FLAGS");
  2424. if (targetLinkFlags) {
  2425. this->CurrentLocalGenerator->AppendFlags(extraLinkOptions,
  2426. *targetLinkFlags);
  2427. }
  2428. if (!configName.empty()) {
  2429. std::string linkFlagsVar =
  2430. cmStrCat("LINK_FLAGS_", cmSystemTools::UpperCase(configName));
  2431. if (cmValue linkFlags = gtgt->GetProperty(linkFlagsVar)) {
  2432. this->CurrentLocalGenerator->AppendFlags(extraLinkOptions, *linkFlags);
  2433. }
  2434. }
  2435. std::vector<std::string> opts;
  2436. gtgt->GetLinkOptions(opts, configName, llang);
  2437. // LINK_OPTIONS are escaped.
  2438. this->CurrentLocalGenerator->AppendCompileOptions(extraLinkOptions, opts);
  2439. }
  2440. // Set target-specific architectures.
  2441. std::vector<std::string> archs =
  2442. gtgt->GetAppleArchs(configName, cm::nullopt);
  2443. if (!archs.empty()) {
  2444. // Enable ARCHS attribute.
  2445. buildSettings->AddAttribute("ONLY_ACTIVE_ARCH", this->CreateString("NO"));
  2446. // Store ARCHS value.
  2447. if (archs.size() == 1) {
  2448. buildSettings->AddAttribute("ARCHS", this->CreateString(archs[0]));
  2449. } else {
  2450. cmXCodeObject* archObjects =
  2451. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2452. for (auto& arch : archs) {
  2453. archObjects->AddObject(this->CreateString(arch));
  2454. }
  2455. buildSettings->AddAttribute("ARCHS", archObjects);
  2456. }
  2457. }
  2458. // Get the product name components.
  2459. cmGeneratorTarget::NameComponents const& components =
  2460. gtgt->GetFullNameComponents(configName);
  2461. cmValue version = gtgt->GetProperty("VERSION");
  2462. cmValue soversion = gtgt->GetProperty("SOVERSION");
  2463. if (!gtgt->HasSOName(configName) || gtgt->IsFrameworkOnApple()) {
  2464. version = nullptr;
  2465. soversion = nullptr;
  2466. }
  2467. if (version && !soversion) {
  2468. soversion = version;
  2469. }
  2470. if (!version && soversion) {
  2471. version = soversion;
  2472. }
  2473. std::string realName = components.base;
  2474. std::string soName = components.base;
  2475. if (version && soversion) {
  2476. realName += '.';
  2477. realName += *version;
  2478. soName += '.';
  2479. soName += *soversion;
  2480. }
  2481. if (gtgt->CanCompileSources()) {
  2482. std::string const tmpDir =
  2483. this->GetTargetTempDir(gtgt, this->GetCMakeCFGIntDir());
  2484. buildSettings->AddAttribute("TARGET_TEMP_DIR", this->CreateString(tmpDir));
  2485. std::string outDir;
  2486. if (gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  2487. // We cannot suppress the archive, so hide it with intermediate files.
  2488. outDir = tmpDir;
  2489. } else {
  2490. outDir = gtgt->GetDirectory(configName);
  2491. }
  2492. buildSettings->AddAttribute("CONFIGURATION_BUILD_DIR",
  2493. this->CreateString(outDir));
  2494. }
  2495. // Set attributes to specify the proper name for the target.
  2496. std::string pndir = this->CurrentLocalGenerator->GetCurrentBinaryDirectory();
  2497. if (gtgt->GetType() == cmStateEnums::STATIC_LIBRARY ||
  2498. gtgt->GetType() == cmStateEnums::SHARED_LIBRARY ||
  2499. gtgt->GetType() == cmStateEnums::MODULE_LIBRARY ||
  2500. gtgt->GetType() == cmStateEnums::EXECUTABLE) {
  2501. std::string prefix = components.prefix;
  2502. if (gtgt->IsFrameworkOnApple() || gtgt->IsCFBundleOnApple()) {
  2503. prefix = "";
  2504. }
  2505. buildSettings->AddAttribute("EXECUTABLE_PREFIX",
  2506. this->CreateString(prefix));
  2507. buildSettings->AddAttribute("EXECUTABLE_SUFFIX",
  2508. this->CreateString(components.suffix));
  2509. }
  2510. // Store the product name for all target types.
  2511. buildSettings->AddAttribute("PRODUCT_NAME", this->CreateString(realName));
  2512. // Handle settings for each target type.
  2513. switch (gtgt->GetType()) {
  2514. case cmStateEnums::STATIC_LIBRARY:
  2515. if (gtgt->GetPropertyAsBool("FRAMEWORK")) {
  2516. std::string fw_version = gtgt->GetFrameworkVersion();
  2517. buildSettings->AddAttribute("FRAMEWORK_VERSION",
  2518. this->CreateString(fw_version));
  2519. cmValue ext = gtgt->GetProperty("BUNDLE_EXTENSION");
  2520. if (ext) {
  2521. buildSettings->AddAttribute("WRAPPER_EXTENSION",
  2522. this->CreateString(*ext));
  2523. }
  2524. std::string plist = this->ComputeInfoPListLocation(gtgt);
  2525. // Xcode will create the final version of Info.plist at build time,
  2526. // so let it replace the framework name. This avoids creating
  2527. // a per-configuration Info.plist file.
  2528. this->CurrentLocalGenerator->GenerateFrameworkInfoPList(
  2529. gtgt, "$(EXECUTABLE_NAME)", plist);
  2530. buildSettings->AddAttribute("INFOPLIST_FILE",
  2531. this->CreateString(plist));
  2532. buildSettings->AddAttribute("MACH_O_TYPE",
  2533. this->CreateString("staticlib"));
  2534. } else {
  2535. buildSettings->AddAttribute("LIBRARY_STYLE",
  2536. this->CreateString("STATIC"));
  2537. }
  2538. break;
  2539. case cmStateEnums::OBJECT_LIBRARY: {
  2540. buildSettings->AddAttribute("LIBRARY_STYLE",
  2541. this->CreateString("STATIC"));
  2542. break;
  2543. }
  2544. case cmStateEnums::MODULE_LIBRARY: {
  2545. buildSettings->AddAttribute("LIBRARY_STYLE",
  2546. this->CreateString("BUNDLE"));
  2547. // Add the flags to create a module library (bundle).
  2548. std::string createFlags = this->LookupFlags(
  2549. "CMAKE_SHARED_MODULE_CREATE_", llang, "_FLAGS", gtgt);
  2550. if (this->GetTargetProductType(gtgt) !=
  2551. "com.apple.product-type.app-extension"_s) {
  2552. // Xcode passes -bundle automatically.
  2553. cmSystemTools::ReplaceString(createFlags, "-bundle", "");
  2554. }
  2555. createFlags = cmTrimWhitespace(createFlags);
  2556. if (!createFlags.empty()) {
  2557. extraLinkOptions += ' ';
  2558. extraLinkOptions += createFlags;
  2559. }
  2560. if (gtgt->IsCFBundleOnApple()) {
  2561. cmValue ext = gtgt->GetProperty("BUNDLE_EXTENSION");
  2562. if (ext) {
  2563. buildSettings->AddAttribute("WRAPPER_EXTENSION",
  2564. this->CreateString(*ext));
  2565. }
  2566. std::string plist = this->ComputeInfoPListLocation(gtgt);
  2567. // Xcode will create the final version of Info.plist at build time,
  2568. // so let it replace the cfbundle name. This avoids creating
  2569. // a per-configuration Info.plist file. The cfbundle plist
  2570. // is very similar to the application bundle plist
  2571. this->CurrentLocalGenerator->GenerateAppleInfoPList(
  2572. gtgt, "$(EXECUTABLE_NAME)", plist);
  2573. buildSettings->AddAttribute("INFOPLIST_FILE",
  2574. this->CreateString(plist));
  2575. } else {
  2576. buildSettings->AddAttribute("MACH_O_TYPE",
  2577. this->CreateString("mh_bundle"));
  2578. buildSettings->AddAttribute("GCC_DYNAMIC_NO_PIC",
  2579. this->CreateString("NO"));
  2580. }
  2581. break;
  2582. }
  2583. case cmStateEnums::SHARED_LIBRARY: {
  2584. if (gtgt->GetPropertyAsBool("FRAMEWORK")) {
  2585. std::string fw_version = gtgt->GetFrameworkVersion();
  2586. buildSettings->AddAttribute("FRAMEWORK_VERSION",
  2587. this->CreateString(fw_version));
  2588. cmValue ext = gtgt->GetProperty("BUNDLE_EXTENSION");
  2589. if (ext) {
  2590. buildSettings->AddAttribute("WRAPPER_EXTENSION",
  2591. this->CreateString(*ext));
  2592. }
  2593. std::string plist = this->ComputeInfoPListLocation(gtgt);
  2594. // Xcode will create the final version of Info.plist at build time,
  2595. // so let it replace the framework name. This avoids creating
  2596. // a per-configuration Info.plist file.
  2597. this->CurrentLocalGenerator->GenerateFrameworkInfoPList(
  2598. gtgt, "$(EXECUTABLE_NAME)", plist);
  2599. buildSettings->AddAttribute("INFOPLIST_FILE",
  2600. this->CreateString(plist));
  2601. } else {
  2602. // Add the flags to create a shared library.
  2603. std::string createFlags = this->LookupFlags(
  2604. "CMAKE_SHARED_LIBRARY_CREATE_", llang, "_FLAGS", gtgt);
  2605. // Xcode passes -dynamiclib automatically.
  2606. cmSystemTools::ReplaceString(createFlags, "-dynamiclib", "");
  2607. createFlags = cmTrimWhitespace(createFlags);
  2608. if (!createFlags.empty()) {
  2609. extraLinkOptions += ' ';
  2610. extraLinkOptions += createFlags;
  2611. }
  2612. }
  2613. buildSettings->AddAttribute("LIBRARY_STYLE",
  2614. this->CreateString("DYNAMIC"));
  2615. if (gtgt->HasImportLibrary(configName)) {
  2616. // Request .tbd file generation
  2617. buildSettings->AddAttribute("GENERATE_TEXT_BASED_STUBS",
  2618. this->CreateString("YES"));
  2619. }
  2620. break;
  2621. }
  2622. case cmStateEnums::EXECUTABLE: {
  2623. // Add the flags to create an executable.
  2624. std::string createFlags =
  2625. this->LookupFlags("CMAKE_", llang, "_LINK_FLAGS", gtgt);
  2626. if (!createFlags.empty()) {
  2627. extraLinkOptions += ' ';
  2628. extraLinkOptions += createFlags;
  2629. }
  2630. // Handle bundles and normal executables separately.
  2631. if (gtgt->GetPropertyAsBool("MACOSX_BUNDLE")) {
  2632. cmValue ext = gtgt->GetProperty("BUNDLE_EXTENSION");
  2633. if (ext) {
  2634. buildSettings->AddAttribute("WRAPPER_EXTENSION",
  2635. this->CreateString(*ext));
  2636. }
  2637. std::string plist = this->ComputeInfoPListLocation(gtgt);
  2638. // Xcode will create the final version of Info.plist at build time,
  2639. // so let it replace the executable name. This avoids creating
  2640. // a per-configuration Info.plist file.
  2641. this->CurrentLocalGenerator->GenerateAppleInfoPList(
  2642. gtgt, "$(EXECUTABLE_NAME)", plist);
  2643. buildSettings->AddAttribute("INFOPLIST_FILE",
  2644. this->CreateString(plist));
  2645. }
  2646. } break;
  2647. default:
  2648. break;
  2649. }
  2650. BuildObjectListOrString dirs(this, true);
  2651. BuildObjectListOrString fdirs(this, true);
  2652. BuildObjectListOrString sysdirs(this, true);
  2653. BuildObjectListOrString sysfdirs(this, true);
  2654. bool const emitSystemIncludes = this->XcodeVersion >= 83;
  2655. // Choose a language to use for target-wide include directories.
  2656. std::string const& langForIncludes = llang;
  2657. std::vector<std::string> includes;
  2658. if (!langForIncludes.empty()) {
  2659. this->CurrentLocalGenerator->GetIncludeDirectories(
  2660. includes, gtgt, langForIncludes, configName);
  2661. }
  2662. std::set<std::string> emitted;
  2663. emitted.insert("/System/Library/Frameworks");
  2664. for (auto& include : includes) {
  2665. if (this->NameResolvesToFramework(include)) {
  2666. std::string frameworkDir = cmStrCat(include, "/../");
  2667. frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
  2668. if (emitted.insert(frameworkDir).second) {
  2669. std::string incpath = this->XCodeEscapePath(frameworkDir);
  2670. if (emitSystemIncludes &&
  2671. gtgt->IsSystemIncludeDirectory(frameworkDir, configName,
  2672. langForIncludes)) {
  2673. sysfdirs.Add(incpath);
  2674. } else {
  2675. fdirs.Add(incpath);
  2676. }
  2677. }
  2678. } else {
  2679. std::string incpath = this->XCodeEscapePath(include);
  2680. if (emitSystemIncludes &&
  2681. gtgt->IsSystemIncludeDirectory(include, configName,
  2682. langForIncludes)) {
  2683. sysdirs.Add(incpath);
  2684. } else {
  2685. dirs.Add(incpath);
  2686. }
  2687. }
  2688. }
  2689. // Add framework search paths needed for linking.
  2690. if (cmComputeLinkInformation* cli = gtgt->GetLinkInformation(configName)) {
  2691. for (auto const& fwDir : cli->GetFrameworkPaths()) {
  2692. if (emitted.insert(fwDir).second) {
  2693. std::string incpath = this->XCodeEscapePath(fwDir);
  2694. if (emitSystemIncludes &&
  2695. gtgt->IsSystemIncludeDirectory(fwDir, configName,
  2696. langForIncludes)) {
  2697. sysfdirs.Add(incpath);
  2698. } else {
  2699. fdirs.Add(incpath);
  2700. }
  2701. }
  2702. }
  2703. }
  2704. if (!fdirs.IsEmpty()) {
  2705. buildSettings->AddAttribute("FRAMEWORK_SEARCH_PATHS", fdirs.CreateList());
  2706. }
  2707. if (!dirs.IsEmpty()) {
  2708. buildSettings->AddAttribute("HEADER_SEARCH_PATHS", dirs.CreateList());
  2709. if (languages.count("Swift")) {
  2710. buildSettings->AddAttribute("SWIFT_INCLUDE_PATHS", dirs.CreateList());
  2711. }
  2712. }
  2713. if (!sysfdirs.IsEmpty()) {
  2714. buildSettings->AddAttribute("SYSTEM_FRAMEWORK_SEARCH_PATHS",
  2715. sysfdirs.CreateList());
  2716. }
  2717. if (!sysdirs.IsEmpty()) {
  2718. buildSettings->AddAttribute("SYSTEM_HEADER_SEARCH_PATHS",
  2719. sysdirs.CreateList());
  2720. }
  2721. if (this->XcodeVersion >= 60 && !emitSystemIncludes) {
  2722. // Add those per-language flags in addition to HEADER_SEARCH_PATHS to gain
  2723. // system include directory awareness. We need to also keep on setting
  2724. // HEADER_SEARCH_PATHS to work around a missing compile options flag for
  2725. // GNU assembly files (#16449)
  2726. for (auto const& language : languages) {
  2727. std::string includeFlags = this->CurrentLocalGenerator->GetIncludeFlags(
  2728. includes, gtgt, language, configName);
  2729. if (!includeFlags.empty()) {
  2730. cflags[language] += cmStrCat(' ', includeFlags);
  2731. }
  2732. }
  2733. }
  2734. bool same_gflags = true;
  2735. std::map<std::string, std::string> gflags;
  2736. std::string const* last_gflag = nullptr;
  2737. std::string optLevel = "0";
  2738. // Minimal map of flags to build settings.
  2739. for (auto const& language : languages) {
  2740. std::string& flags = cflags[language];
  2741. std::string& gflag = gflags[language];
  2742. std::string oflag =
  2743. this->ExtractFlagRegex("(^| )(-Ofast|-Os|-O[0-9]*)( |$)", 2, flags);
  2744. if (oflag.size() == 2) {
  2745. optLevel = "1";
  2746. } else if (oflag.size() > 2) {
  2747. optLevel = oflag.substr(2);
  2748. }
  2749. gflag = this->ExtractFlag("-g", flags);
  2750. // put back gdwarf-2 if used since there is no way
  2751. // to represent it in the gui, but we still want debug yes
  2752. if (gflag == "-gdwarf-2"_s) {
  2753. flags += ' ';
  2754. flags += gflag;
  2755. }
  2756. if (last_gflag && *last_gflag != gflag) {
  2757. same_gflags = false;
  2758. }
  2759. last_gflag = &gflag;
  2760. }
  2761. char const* debugStr = "YES";
  2762. if (!same_gflags) {
  2763. // We can't set the Xcode flag differently depending on the language,
  2764. // so put them back in this case.
  2765. for (auto const& language : languages) {
  2766. cflags[language] += ' ';
  2767. cflags[language] += gflags[language];
  2768. }
  2769. debugStr = "NO";
  2770. } else if (last_gflag && (last_gflag->empty() || *last_gflag == "-g0"_s)) {
  2771. debugStr = "NO";
  2772. }
  2773. // extract C++ stdlib
  2774. for (auto const& language : languages) {
  2775. if (language != "CXX"_s && language != "OBJCXX"_s) {
  2776. continue;
  2777. }
  2778. std::string& flags = cflags[language];
  2779. auto stdlib =
  2780. this->ExtractFlagRegex("(^| )(-stdlib=[^ ]+)( |$)", 2, flags);
  2781. if (stdlib.size() > 8) {
  2782. auto const cxxLibrary = stdlib.substr(8);
  2783. if (language == "CXX"_s ||
  2784. !buildSettings->GetAttribute("CLANG_CXX_LIBRARY")) {
  2785. buildSettings->AddAttribute("CLANG_CXX_LIBRARY",
  2786. this->CreateString(cxxLibrary));
  2787. }
  2788. }
  2789. }
  2790. buildSettings->AddAttribute("COMBINE_HIDPI_IMAGES",
  2791. this->CreateString("YES"));
  2792. buildSettings->AddAttribute("GCC_GENERATE_DEBUGGING_SYMBOLS",
  2793. this->CreateString(debugStr));
  2794. buildSettings->AddAttribute("GCC_OPTIMIZATION_LEVEL",
  2795. this->CreateString(optLevel));
  2796. buildSettings->AddAttribute("GCC_SYMBOLS_PRIVATE_EXTERN",
  2797. this->CreateString("NO"));
  2798. buildSettings->AddAttribute("GCC_INLINES_ARE_PRIVATE_EXTERN",
  2799. this->CreateString("NO"));
  2800. for (auto const& language : languages) {
  2801. std::string flags = cmStrCat(cflags[language], ' ', defFlags);
  2802. if (language == "CXX"_s || language == "OBJCXX"_s) {
  2803. if (language == "CXX"_s ||
  2804. !buildSettings->GetAttribute("OTHER_CPLUSPLUSFLAGS")) {
  2805. buildSettings->AddAttribute("OTHER_CPLUSPLUSFLAGS",
  2806. this->CreateString(flags));
  2807. }
  2808. } else if (language == "Fortran"_s) {
  2809. buildSettings->AddAttribute("IFORT_OTHER_FLAGS",
  2810. this->CreateString(flags));
  2811. } else if (language == "C"_s || language == "OBJC"_s) {
  2812. if (language == "C"_s || !buildSettings->GetAttribute("OTHER_CFLAGS")) {
  2813. buildSettings->AddAttribute("OTHER_CFLAGS", this->CreateString(flags));
  2814. }
  2815. } else if (language == "Swift"_s) {
  2816. buildSettings->AddAttribute("OTHER_SWIFT_FLAGS",
  2817. this->CreateString(flags));
  2818. }
  2819. }
  2820. // Add Fortran source format attribute if property is set.
  2821. char const* format = nullptr;
  2822. std::string const& tgtfmt = gtgt->GetSafeProperty("Fortran_FORMAT");
  2823. switch (cmOutputConverter::GetFortranFormat(tgtfmt)) {
  2824. case cmOutputConverter::FortranFormatFixed:
  2825. format = "fixed";
  2826. break;
  2827. case cmOutputConverter::FortranFormatFree:
  2828. format = "free";
  2829. break;
  2830. default:
  2831. break;
  2832. }
  2833. if (format) {
  2834. buildSettings->AddAttribute("IFORT_LANG_SRCFMT",
  2835. this->CreateString(format));
  2836. }
  2837. // Create the INSTALL_PATH attribute.
  2838. std::string install_name_dir;
  2839. if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) {
  2840. // Get the install_name directory for the build tree.
  2841. install_name_dir = gtgt->GetInstallNameDirForBuildTree(configName);
  2842. // Xcode doesn't create the correct install_name in some cases.
  2843. // That is, if the INSTALL_PATH is empty, or if we have versioning
  2844. // of dylib libraries, we want to specify the install_name.
  2845. // This is done by adding a link flag to create an install_name
  2846. // with just the library soname.
  2847. std::string install_name;
  2848. if (!install_name_dir.empty()) {
  2849. // Convert to a path for the native build tool.
  2850. cmSystemTools::ConvertToUnixSlashes(install_name_dir);
  2851. install_name += install_name_dir;
  2852. install_name += '/';
  2853. }
  2854. install_name += gtgt->GetSOName(configName);
  2855. if ((realName != soName) || install_name_dir.empty()) {
  2856. install_name_dir = "";
  2857. extraLinkOptions += " -install_name ";
  2858. extraLinkOptions += XCodeEscapePath(install_name);
  2859. }
  2860. }
  2861. buildSettings->AddAttribute("INSTALL_PATH",
  2862. this->CreateString(install_name_dir));
  2863. // Create the LD_RUNPATH_SEARCH_PATHS
  2864. cmComputeLinkInformation* pcli = gtgt->GetLinkInformation(configName);
  2865. if (pcli) {
  2866. std::string search_paths;
  2867. std::vector<std::string> runtimeDirs;
  2868. pcli->GetRPath(runtimeDirs, false);
  2869. // runpath dirs needs to be unique to prevent corruption
  2870. std::set<std::string> unique_dirs;
  2871. for (auto runpath : runtimeDirs) {
  2872. runpath = this->ExpandCFGIntDir(runpath, configName);
  2873. if (unique_dirs.find(runpath) == unique_dirs.end()) {
  2874. unique_dirs.insert(runpath);
  2875. if (!search_paths.empty()) {
  2876. search_paths += ' ';
  2877. }
  2878. search_paths += this->XCodeEscapePath(runpath);
  2879. }
  2880. }
  2881. if (!search_paths.empty()) {
  2882. buildSettings->AddAttribute("LD_RUNPATH_SEARCH_PATHS",
  2883. this->CreateString(search_paths));
  2884. }
  2885. }
  2886. buildSettings->AddAttribute(this->GetTargetLinkFlagsVar(gtgt),
  2887. this->CreateString(extraLinkOptions));
  2888. buildSettings->AddAttribute("OTHER_REZFLAGS", this->CreateString(""));
  2889. buildSettings->AddAttribute("SECTORDER_FLAGS", this->CreateString(""));
  2890. buildSettings->AddAttribute("ALWAYS_SEARCH_USER_PATHS",
  2891. this->CreateString("NO"));
  2892. buildSettings->AddAttribute("USE_HEADERMAP", this->CreateString("NO"));
  2893. cmXCodeObject* group = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2894. group->AddObject(this->CreateString("$(inherited)"));
  2895. buildSettings->AddAttribute("WARNING_CFLAGS", group);
  2896. // Runtime version information.
  2897. if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) {
  2898. int major;
  2899. int minor;
  2900. int patch;
  2901. // MACHO_CURRENT_VERSION or VERSION -> current_version
  2902. gtgt->GetTargetVersionFallback("MACHO_CURRENT_VERSION", "VERSION", major,
  2903. minor, patch);
  2904. std::ostringstream v;
  2905. // Xcode always wants at least 1.0.0 or nothing
  2906. if (!(major == 0 && minor == 0 && patch == 0)) {
  2907. v << major << '.' << minor << '.' << patch;
  2908. }
  2909. buildSettings->AddAttribute("DYLIB_CURRENT_VERSION",
  2910. this->CreateString(v.str()));
  2911. // MACHO_COMPATIBILITY_VERSION or SOVERSION -> compatibility_version
  2912. gtgt->GetTargetVersionFallback("MACHO_COMPATIBILITY_VERSION", "SOVERSION",
  2913. major, minor, patch);
  2914. std::ostringstream vso;
  2915. // Xcode always wants at least 1.0.0 or nothing
  2916. if (!(major == 0 && minor == 0 && patch == 0)) {
  2917. vso << major << '.' << minor << '.' << patch;
  2918. }
  2919. buildSettings->AddAttribute("DYLIB_COMPATIBILITY_VERSION",
  2920. this->CreateString(vso.str()));
  2921. }
  2922. // Precompile Headers
  2923. std::string pchHeader =
  2924. gtgt->GetPchHeader(configName, langForPreprocessorDefinitions);
  2925. if (!pchHeader.empty()) {
  2926. buildSettings->AddAttribute("GCC_PREFIX_HEADER",
  2927. this->CreateString(pchHeader));
  2928. buildSettings->AddAttribute("GCC_PRECOMPILE_PREFIX_HEADER",
  2929. this->CreateString("YES"));
  2930. }
  2931. // put this last so it can override existing settings
  2932. // Convert "XCODE_ATTRIBUTE_*" properties directly.
  2933. {
  2934. for (auto const& prop : gtgt->GetPropertyKeys()) {
  2935. if (cmHasLiteralPrefix(prop, "XCODE_ATTRIBUTE_")) {
  2936. std::string attribute = prop.substr(16);
  2937. this->FilterConfigurationAttribute(configName, attribute);
  2938. if (!attribute.empty()) {
  2939. std::string const& pr = gtgt->GetSafeProperty(prop);
  2940. std::string processed = cmGeneratorExpression::Evaluate(
  2941. pr, this->CurrentLocalGenerator, configName);
  2942. buildSettings->AddAttribute(attribute,
  2943. this->CreateString(processed));
  2944. }
  2945. }
  2946. }
  2947. }
  2948. }
  2949. cmXCodeObject* cmGlobalXCodeGenerator::CreateUtilityTarget(
  2950. cmGeneratorTarget* gtgt)
  2951. {
  2952. cmXCodeObject* shellBuildPhase = this->CreateObject(
  2953. cmXCodeObject::PBXShellScriptBuildPhase, gtgt->GetName());
  2954. shellBuildPhase->AddAttribute("buildActionMask",
  2955. this->CreateString("2147483647"));
  2956. cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2957. shellBuildPhase->AddAttribute("files", buildFiles);
  2958. cmXCodeObject* inputPaths = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2959. shellBuildPhase->AddAttribute("inputPaths", inputPaths);
  2960. cmXCodeObject* outputPaths = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2961. shellBuildPhase->AddAttribute("outputPaths", outputPaths);
  2962. shellBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  2963. this->CreateString("0"));
  2964. shellBuildPhase->AddAttribute("shellPath", this->CreateString("/bin/sh"));
  2965. shellBuildPhase->AddAttribute(
  2966. "shellScript", this->CreateString("# shell script goes here\nexit 0"));
  2967. shellBuildPhase->AddAttribute("showEnvVarsInLog", this->CreateString("0"));
  2968. std::string targetBinaryPath = cmStrCat(
  2969. gtgt->Makefile->GetCurrentBinaryDirectory(), '/', gtgt->GetName());
  2970. cmXCodeObject* target = this->CreateObject(
  2971. cmXCodeObject::PBXAggregateTarget,
  2972. cmStrCat("PBXAggregateTarget:", gtgt->GetName(), ':', targetBinaryPath));
  2973. target->SetComment(gtgt->GetName());
  2974. cmXCodeObject* buildPhases = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2975. std::vector<cmXCodeObject*> emptyContentVector;
  2976. this->CreateCustomCommands(buildPhases, nullptr, nullptr, nullptr,
  2977. emptyContentVector, nullptr, gtgt);
  2978. target->AddAttribute("buildPhases", buildPhases);
  2979. this->AddConfigurations(target, gtgt);
  2980. cmXCodeObject* dependencies = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2981. target->AddAttribute("dependencies", dependencies);
  2982. target->AddAttribute("name", this->CreateString(gtgt->GetName()));
  2983. target->AddAttribute("productName", this->CreateString(gtgt->GetName()));
  2984. target->SetTarget(gtgt);
  2985. this->XCodeObjectMap[gtgt] = target;
  2986. // Add source files without build rules for editing convenience.
  2987. if (gtgt->GetType() != cmStateEnums::GLOBAL_TARGET &&
  2988. gtgt->GetName() != CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
  2989. std::vector<cmSourceFile*> sources;
  2990. if (!gtgt->GetConfigCommonSourceFilesForXcode(sources)) {
  2991. return nullptr;
  2992. }
  2993. // Add CMakeLists.txt file for user convenience.
  2994. this->AddXCodeProjBuildRule(gtgt, sources);
  2995. for (auto* sourceFile : sources) {
  2996. if (!sourceFile->GetIsGenerated()) {
  2997. this->CreateXCodeFileReference(sourceFile, gtgt);
  2998. }
  2999. }
  3000. }
  3001. target->SetId(this->GetOrCreateId(gtgt->GetName(), target->GetId()));
  3002. return target;
  3003. }
  3004. std::string cmGlobalXCodeGenerator::AddConfigurations(cmXCodeObject* target,
  3005. cmGeneratorTarget* gtgt)
  3006. {
  3007. cmList const configList{ this->CurrentMakefile->GetRequiredDefinition(
  3008. "CMAKE_CONFIGURATION_TYPES") };
  3009. cmXCodeObject* configlist =
  3010. this->CreateObject(cmXCodeObject::XCConfigurationList);
  3011. cmXCodeObject* buildConfigurations =
  3012. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3013. configlist->AddAttribute("buildConfigurations", buildConfigurations);
  3014. std::string comment = cmStrCat("Build configuration list for ",
  3015. cmXCodeObject::PBXTypeNames[target->GetIsA()],
  3016. " \"", gtgt->GetName(), '"');
  3017. configlist->SetComment(comment);
  3018. target->AddAttribute("buildConfigurationList",
  3019. this->CreateObjectReference(configlist));
  3020. for (auto const& i : configList) {
  3021. cmXCodeObject* config =
  3022. this->CreateObject(cmXCodeObject::XCBuildConfiguration);
  3023. buildConfigurations->AddObject(config);
  3024. cmXCodeObject* buildSettings =
  3025. this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  3026. this->CreateBuildSettings(gtgt, buildSettings, i);
  3027. config->AddAttribute("name", this->CreateString(i));
  3028. config->SetComment(i);
  3029. config->AddAttribute("buildSettings", buildSettings);
  3030. this->CreateTargetXCConfigSettings(gtgt, config, i);
  3031. }
  3032. if (!configList.empty()) {
  3033. configlist->AddAttribute("defaultConfigurationName",
  3034. this->CreateString(configList[0]));
  3035. configlist->AddAttribute("defaultConfigurationIsVisible",
  3036. this->CreateString("0"));
  3037. return configList[0];
  3038. }
  3039. return "";
  3040. }
  3041. void cmGlobalXCodeGenerator::CreateGlobalXCConfigSettings(
  3042. cmLocalGenerator* root, cmXCodeObject* config, std::string const& configName)
  3043. {
  3044. auto xcconfig = cmGeneratorExpression::Evaluate(
  3045. this->CurrentMakefile->GetSafeDefinition("CMAKE_XCODE_XCCONFIG"),
  3046. this->CurrentLocalGenerator, configName);
  3047. if (xcconfig.empty()) {
  3048. return;
  3049. }
  3050. auto* sf = this->CurrentMakefile->GetSource(xcconfig);
  3051. if (!sf) {
  3052. cmSystemTools::Error(
  3053. cmStrCat("sources for ALL_BUILD do not contain xcconfig file: '",
  3054. xcconfig, "' (configuration: ", configName, ')'));
  3055. return;
  3056. }
  3057. cmXCodeObject* fileRef = this->CreateXCodeFileReferenceFromPath(
  3058. sf->ResolveFullPath(), root->FindGeneratorTargetToUse("ALL_BUILD"), "",
  3059. sf);
  3060. if (!fileRef) {
  3061. // error is already reported by CreateXCodeFileReferenceFromPath
  3062. return;
  3063. }
  3064. config->AddAttribute("baseConfigurationReference",
  3065. this->CreateObjectReference(fileRef));
  3066. }
  3067. void cmGlobalXCodeGenerator::CreateTargetXCConfigSettings(
  3068. cmGeneratorTarget* target, cmXCodeObject* config,
  3069. std::string const& configName)
  3070. {
  3071. auto xcconfig =
  3072. cmGeneratorExpression::Evaluate(target->GetSafeProperty("XCODE_XCCONFIG"),
  3073. this->CurrentLocalGenerator, configName);
  3074. if (xcconfig.empty()) {
  3075. return;
  3076. }
  3077. auto* sf = target->Makefile->GetSource(xcconfig);
  3078. if (!sf) {
  3079. cmSystemTools::Error(cmStrCat("target sources for target ",
  3080. target->Target->GetName(),
  3081. " do not contain xcconfig file: '", xcconfig,
  3082. "' (configuration: ", configName, ')'));
  3083. return;
  3084. }
  3085. cmXCodeObject* fileRef = this->CreateXCodeFileReferenceFromPath(
  3086. sf->ResolveFullPath(), target, "", sf);
  3087. if (!fileRef) {
  3088. // error is already reported by CreateXCodeFileReferenceFromPath
  3089. return;
  3090. }
  3091. config->AddAttribute("baseConfigurationReference",
  3092. this->CreateObjectReference(fileRef));
  3093. }
  3094. char const* cmGlobalXCodeGenerator::GetTargetLinkFlagsVar(
  3095. cmGeneratorTarget const* target) const
  3096. {
  3097. if (this->XcodeVersion >= 60 &&
  3098. (target->GetType() == cmStateEnums::STATIC_LIBRARY ||
  3099. target->GetType() == cmStateEnums::OBJECT_LIBRARY)) {
  3100. return "OTHER_LIBTOOLFLAGS";
  3101. }
  3102. return "OTHER_LDFLAGS";
  3103. }
  3104. char const* cmGlobalXCodeGenerator::GetTargetFileType(
  3105. cmGeneratorTarget* target)
  3106. {
  3107. if (cmValue e = target->GetProperty("XCODE_EXPLICIT_FILE_TYPE")) {
  3108. return e->c_str();
  3109. }
  3110. switch (target->GetType()) {
  3111. case cmStateEnums::OBJECT_LIBRARY:
  3112. return "archive.ar";
  3113. case cmStateEnums::STATIC_LIBRARY:
  3114. return (target->GetPropertyAsBool("FRAMEWORK") ? "wrapper.framework"
  3115. : "archive.ar");
  3116. case cmStateEnums::MODULE_LIBRARY:
  3117. if (target->IsXCTestOnApple()) {
  3118. return "wrapper.cfbundle";
  3119. }
  3120. if (target->IsCFBundleOnApple()) {
  3121. return "wrapper.plug-in";
  3122. }
  3123. return "compiled.mach-o.executable";
  3124. case cmStateEnums::SHARED_LIBRARY:
  3125. return (target->GetPropertyAsBool("FRAMEWORK")
  3126. ? "wrapper.framework"
  3127. : "compiled.mach-o.dylib");
  3128. case cmStateEnums::EXECUTABLE:
  3129. return "compiled.mach-o.executable";
  3130. default:
  3131. break;
  3132. }
  3133. return nullptr;
  3134. }
  3135. cm::string_view cmGlobalXCodeGenerator::GetTargetProductType(
  3136. cmGeneratorTarget* target)
  3137. {
  3138. if (cmValue e = target->GetProperty("XCODE_PRODUCT_TYPE")) {
  3139. return cm::string_view(*e);
  3140. }
  3141. switch (target->GetType()) {
  3142. case cmStateEnums::OBJECT_LIBRARY:
  3143. return "com.apple.product-type.library.static"_s;
  3144. case cmStateEnums::STATIC_LIBRARY:
  3145. return target->GetPropertyAsBool("FRAMEWORK")
  3146. ? "com.apple.product-type.framework"_s
  3147. : "com.apple.product-type.library.static"_s;
  3148. case cmStateEnums::MODULE_LIBRARY:
  3149. if (target->IsXCTestOnApple()) {
  3150. return "com.apple.product-type.bundle.unit-test"_s;
  3151. } else if (target->IsCFBundleOnApple()) {
  3152. return "com.apple.product-type.bundle"_s;
  3153. } else {
  3154. return "com.apple.product-type.tool"_s;
  3155. }
  3156. case cmStateEnums::SHARED_LIBRARY:
  3157. return target->GetPropertyAsBool("FRAMEWORK")
  3158. ? "com.apple.product-type.framework"_s
  3159. : "com.apple.product-type.library.dynamic"_s;
  3160. case cmStateEnums::EXECUTABLE:
  3161. return target->GetPropertyAsBool("MACOSX_BUNDLE")
  3162. ? "com.apple.product-type.application"_s
  3163. : "com.apple.product-type.tool"_s;
  3164. default:
  3165. break;
  3166. }
  3167. return ""_s;
  3168. }
  3169. cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeTarget(
  3170. cmGeneratorTarget* gtgt, cmXCodeObject* buildPhases)
  3171. {
  3172. if (!gtgt->IsInBuildSystem()) {
  3173. return nullptr;
  3174. }
  3175. std::string targetBinaryPath = this->RelativeToRootBinary(cmStrCat(
  3176. gtgt->Makefile->GetCurrentBinaryDirectory(), '/', gtgt->GetName()));
  3177. cmXCodeObject* target = this->CreateObject(
  3178. cmXCodeObject::PBXNativeTarget,
  3179. cmStrCat("PBXNativeTarget:", gtgt->GetName(), ':', targetBinaryPath));
  3180. target->AddAttribute("buildPhases", buildPhases);
  3181. cmXCodeObject* buildRules = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3182. target->AddAttribute("buildRules", buildRules);
  3183. std::string defConfig;
  3184. defConfig = this->AddConfigurations(target, gtgt);
  3185. cmXCodeObject* dependencies = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3186. target->AddAttribute("dependencies", dependencies);
  3187. target->AddAttribute("name", this->CreateString(gtgt->GetName()));
  3188. target->AddAttribute("productName", this->CreateString(gtgt->GetName()));
  3189. cmXCodeObject* fileRef = this->CreateObject(cmXCodeObject::PBXFileReference);
  3190. if (char const* fileType = this->GetTargetFileType(gtgt)) {
  3191. fileRef->AddAttribute("explicitFileType", this->CreateString(fileType));
  3192. }
  3193. std::string fullName;
  3194. if (gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  3195. fullName = cmStrCat("lib", gtgt->GetName(), ".a");
  3196. } else {
  3197. fullName = gtgt->GetFullName(defConfig);
  3198. }
  3199. fileRef->AddAttribute("path", this->CreateString(fullName));
  3200. fileRef->AddAttribute("sourceTree",
  3201. this->CreateString("BUILT_PRODUCTS_DIR"));
  3202. fileRef->SetComment(gtgt->GetName());
  3203. target->AddAttribute("productReference",
  3204. this->CreateObjectReference(fileRef));
  3205. cm::string_view productType = this->GetTargetProductType(gtgt);
  3206. if (!productType.empty()) {
  3207. target->AddAttribute("productType", this->CreateString(productType));
  3208. }
  3209. target->SetTarget(gtgt);
  3210. this->XCodeObjectMap[gtgt] = target;
  3211. target->SetId(this->GetOrCreateId(gtgt->GetName(), target->GetId()));
  3212. return target;
  3213. }
  3214. cmXCodeObject* cmGlobalXCodeGenerator::FindXCodeTarget(
  3215. cmGeneratorTarget const* t)
  3216. {
  3217. if (!t) {
  3218. return nullptr;
  3219. }
  3220. auto const i = this->XCodeObjectMap.find(t);
  3221. if (i == this->XCodeObjectMap.end()) {
  3222. return nullptr;
  3223. }
  3224. return i->second;
  3225. }
  3226. std::string cmGlobalXCodeGenerator::GetObjectId(cmXCodeObject::PBXType ptype,
  3227. cm::string_view key)
  3228. {
  3229. std::string objectId;
  3230. if (!key.empty()) {
  3231. cmCryptoHash hash(cmCryptoHash::AlgoSHA256);
  3232. hash.Initialize();
  3233. hash.Append(&ptype, sizeof(ptype));
  3234. hash.Append(key);
  3235. objectId = cmSystemTools::UpperCase(hash.FinalizeHex().substr(0, 24));
  3236. } else {
  3237. char cUuid[40] = { 0 };
  3238. CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
  3239. CFStringRef s = CFUUIDCreateString(kCFAllocatorDefault, uuid);
  3240. CFStringGetCString(s, cUuid, sizeof(cUuid), kCFStringEncodingUTF8);
  3241. objectId = cUuid;
  3242. CFRelease(s);
  3243. CFRelease(uuid);
  3244. cmSystemTools::ReplaceString(objectId, "-", "");
  3245. if (objectId.size() > 24) {
  3246. objectId = objectId.substr(0, 24);
  3247. }
  3248. }
  3249. return objectId;
  3250. }
  3251. std::string cmGlobalXCodeGenerator::GetOrCreateId(std::string const& name,
  3252. std::string const& id)
  3253. {
  3254. std::string guidStoreName = cmStrCat(name, "_GUID_CMAKE");
  3255. cmValue storedGUID = this->CMakeInstance->GetCacheDefinition(guidStoreName);
  3256. if (storedGUID) {
  3257. return *storedGUID;
  3258. }
  3259. this->CMakeInstance->AddCacheEntry(
  3260. guidStoreName, id, "Stored Xcode object GUID", cmStateEnums::INTERNAL);
  3261. return id;
  3262. }
  3263. void cmGlobalXCodeGenerator::AddDependTarget(cmXCodeObject* target,
  3264. cmXCodeObject* dependTarget)
  3265. {
  3266. // This is called once for every edge in the target dependency graph.
  3267. cmXCodeObject* container =
  3268. this->CreateObject(cmXCodeObject::PBXContainerItemProxy);
  3269. container->SetComment("PBXContainerItemProxy");
  3270. container->AddAttribute("containerPortal",
  3271. this->CreateObjectReference(this->RootObject));
  3272. container->AddAttribute("proxyType", this->CreateString("1"));
  3273. container->AddAttribute("remoteGlobalIDString",
  3274. this->CreateObjectReference(dependTarget));
  3275. container->AddAttribute(
  3276. "remoteInfo", this->CreateString(dependTarget->GetTarget()->GetName()));
  3277. cmXCodeObject* targetdep =
  3278. this->CreateObject(cmXCodeObject::PBXTargetDependency);
  3279. targetdep->SetComment("PBXTargetDependency");
  3280. targetdep->AddAttribute("target", this->CreateObjectReference(dependTarget));
  3281. targetdep->AddAttribute("targetProxy",
  3282. this->CreateObjectReference(container));
  3283. cmXCodeObject* depends = target->GetAttribute("dependencies");
  3284. if (!depends) {
  3285. cmSystemTools::Error(
  3286. "target does not have dependencies attribute error..");
  3287. } else {
  3288. depends->AddUniqueObject(targetdep);
  3289. }
  3290. }
  3291. void cmGlobalXCodeGenerator::AppendOrAddBuildSetting(cmXCodeObject* settings,
  3292. char const* attribute,
  3293. cmXCodeObject* value)
  3294. {
  3295. if (settings) {
  3296. cmXCodeObject* attr = settings->GetAttribute(attribute);
  3297. if (!attr) {
  3298. settings->AddAttribute(attribute, value);
  3299. } else {
  3300. this->AppendBuildSettingAttribute(settings, attribute, attr, value);
  3301. }
  3302. }
  3303. }
  3304. void cmGlobalXCodeGenerator::AppendBuildSettingAttribute(
  3305. cmXCodeObject* settings, char const* attribute, cmXCodeObject* attr,
  3306. cmXCodeObject* value)
  3307. {
  3308. if (value->GetType() != cmXCodeObject::OBJECT_LIST &&
  3309. value->GetType() != cmXCodeObject::STRING) {
  3310. cmSystemTools::Error(
  3311. cmStrCat("Unsupported value type for appending: ", attribute));
  3312. return;
  3313. }
  3314. if (attr->GetType() == cmXCodeObject::OBJECT_LIST) {
  3315. if (value->GetType() == cmXCodeObject::OBJECT_LIST) {
  3316. for (auto* obj : value->GetObjectList()) {
  3317. attr->AddObject(obj);
  3318. }
  3319. } else {
  3320. attr->AddObject(value);
  3321. }
  3322. } else if (attr->GetType() == cmXCodeObject::STRING) {
  3323. if (value->GetType() == cmXCodeObject::OBJECT_LIST) {
  3324. // Add old value as a list item to new object list
  3325. // and replace the attribute with the new list
  3326. value->PrependObject(attr);
  3327. settings->AddAttribute(attribute, value);
  3328. } else {
  3329. std::string newValue =
  3330. cmStrCat(attr->GetString(), ' ', value->GetString());
  3331. attr->SetString(newValue);
  3332. }
  3333. } else {
  3334. cmSystemTools::Error(
  3335. cmStrCat("Unsupported attribute type for appending: ", attribute));
  3336. }
  3337. }
  3338. void cmGlobalXCodeGenerator::AppendBuildSettingAttribute(
  3339. cmXCodeObject* target, char const* attribute, cmXCodeObject* value,
  3340. std::string const& configName)
  3341. {
  3342. // There are multiple configurations. Add the setting to the
  3343. // buildSettings of the configuration name given.
  3344. cmXCodeObject* configurationList =
  3345. target->GetAttribute("buildConfigurationList")->GetObject();
  3346. cmXCodeObject* buildConfigs =
  3347. configurationList->GetAttribute("buildConfigurations");
  3348. for (auto* obj : buildConfigs->GetObjectList()) {
  3349. if (configName.empty() ||
  3350. obj->GetAttribute("name")->GetString() == configName) {
  3351. cmXCodeObject* settings = obj->GetAttribute("buildSettings");
  3352. this->AppendOrAddBuildSetting(settings, attribute, value);
  3353. }
  3354. }
  3355. }
  3356. void cmGlobalXCodeGenerator::InheritBuildSettingAttribute(
  3357. cmXCodeObject* target, char const* attribute)
  3358. {
  3359. cmXCodeObject* configurationList =
  3360. target->GetAttribute("buildConfigurationList")->GetObject();
  3361. cmXCodeObject* buildConfigs =
  3362. configurationList->GetAttribute("buildConfigurations");
  3363. for (auto* obj : buildConfigs->GetObjectList()) {
  3364. cmXCodeObject* settings = obj->GetAttribute("buildSettings");
  3365. if (cmXCodeObject* attr = settings->GetAttribute(attribute)) {
  3366. BuildObjectListOrString inherited(this, true);
  3367. inherited.Add("$(inherited)");
  3368. this->AppendBuildSettingAttribute(settings, attribute, attr,
  3369. inherited.CreateList());
  3370. }
  3371. }
  3372. }
  3373. void cmGlobalXCodeGenerator::AddDependAndLinkInformation(cmXCodeObject* target)
  3374. {
  3375. cmGeneratorTarget* gt = target->GetTarget();
  3376. if (!gt) {
  3377. cmSystemTools::Error("Error no target on xobject\n");
  3378. return;
  3379. }
  3380. if (!gt->IsInBuildSystem()) {
  3381. return;
  3382. }
  3383. // Add dependencies on other CMake targets.
  3384. for (auto const& dep : this->GetTargetDirectDepends(gt)) {
  3385. if (cmXCodeObject* dptarget = this->FindXCodeTarget(dep)) {
  3386. this->AddDependTarget(target, dptarget);
  3387. }
  3388. }
  3389. // Separate libraries into ones that can be linked using "Link Binary With
  3390. // Libraries" build phase and the ones that can't. Only targets that build
  3391. // Apple bundles (.app, .framework, .bundle), executables and dylibs can use
  3392. // this feature and only targets that represent actual libraries (object,
  3393. // static, dynamic or bundle, excluding executables) will be used. These are
  3394. // limitations imposed by CMake use-cases - otherwise a lot of things break.
  3395. // The rest will be linked using linker flags (OTHER_LDFLAGS setting in Xcode
  3396. // project).
  3397. std::map<std::string, std::vector<cmComputeLinkInformation::Item const*>>
  3398. configItemMap;
  3399. auto addToLinkerArguments =
  3400. [&configItemMap](std::string const& configName,
  3401. cmComputeLinkInformation::Item const* libItemPtr) {
  3402. auto& linkVector = configItemMap[configName];
  3403. if (std::find_if(linkVector.begin(), linkVector.end(),
  3404. [libItemPtr](cmComputeLinkInformation::Item const* p) {
  3405. return p == libItemPtr;
  3406. }) == linkVector.end()) {
  3407. linkVector.push_back(libItemPtr);
  3408. }
  3409. };
  3410. std::vector<cmComputeLinkInformation::Item const*> linkPhaseTargetVector;
  3411. std::map<std::string, std::vector<std::string>> targetConfigMap;
  3412. using ConfigItemPair =
  3413. std::pair<std::string, cmComputeLinkInformation::Item const*>;
  3414. std::map<std::string, std::vector<ConfigItemPair>> targetItemMap;
  3415. std::map<std::string, std::vector<std::string>> targetProductNameMap;
  3416. bool useLinkPhase = false;
  3417. bool forceLinkPhase = false;
  3418. cmValue prop =
  3419. target->GetTarget()->GetProperty("XCODE_LINK_BUILD_PHASE_MODE");
  3420. if (prop) {
  3421. if (*prop == "BUILT_ONLY"_s) {
  3422. useLinkPhase = true;
  3423. } else if (*prop == "KNOWN_LOCATION"_s) {
  3424. useLinkPhase = true;
  3425. forceLinkPhase = true;
  3426. } else if (*prop != "NONE"_s) {
  3427. cmSystemTools::Error(
  3428. cmStrCat("Invalid value for XCODE_LINK_BUILD_PHASE_MODE: ", *prop));
  3429. return;
  3430. }
  3431. }
  3432. for (auto const& configName : this->CurrentConfigurationTypes) {
  3433. cmComputeLinkInformation* cli = gt->GetLinkInformation(configName);
  3434. if (!cli) {
  3435. continue;
  3436. }
  3437. for (auto const& libItem : cli->GetItems()) {
  3438. // Explicitly ignore OBJECT libraries as Xcode emulates them as static
  3439. // libraries without an artifact. Avoid exposing this to the rest of
  3440. // CMake's compilation model.
  3441. if (libItem.Target &&
  3442. libItem.Target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  3443. continue;
  3444. }
  3445. // We want to put only static libraries, dynamic libraries, frameworks
  3446. // and bundles that are built from targets that are not imported in "Link
  3447. // Binary With Libraries" build phase. Except if the target property
  3448. // XCODE_LINK_BUILD_PHASE_MODE is KNOWN_LOCATION then all imported and
  3449. // non-target libraries will be added as well.
  3450. if (useLinkPhase &&
  3451. (gt->GetType() == cmStateEnums::EXECUTABLE ||
  3452. gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
  3453. gt->GetType() == cmStateEnums::MODULE_LIBRARY) &&
  3454. ((libItem.Target &&
  3455. (!libItem.Target->IsImported() || forceLinkPhase) &&
  3456. (libItem.Target->GetType() == cmStateEnums::STATIC_LIBRARY ||
  3457. libItem.Target->GetType() == cmStateEnums::SHARED_LIBRARY ||
  3458. libItem.Target->GetType() == cmStateEnums::MODULE_LIBRARY ||
  3459. libItem.Target->GetType() == cmStateEnums::UNKNOWN_LIBRARY)) ||
  3460. (!libItem.Target &&
  3461. libItem.IsPath == cmComputeLinkInformation::ItemIsPath::Yes &&
  3462. forceLinkPhase))) {
  3463. std::string libName;
  3464. bool canUseLinkPhase = !libItem.HasFeature() ||
  3465. libItem.GetFeatureName() == "__CMAKE_LINK_FRAMEWORK"_s ||
  3466. libItem.GetFeatureName() == "FRAMEWORK"_s ||
  3467. libItem.GetFeatureName() == "__CMAKE_LINK_XCFRAMEWORK"_s ||
  3468. libItem.GetFeatureName() == "XCFRAMEWORK"_s ||
  3469. libItem.GetFeatureName() == "WEAK_FRAMEWORK"_s ||
  3470. libItem.GetFeatureName() == "WEAK_LIBRARY"_s;
  3471. if (canUseLinkPhase) {
  3472. if (libItem.Target) {
  3473. if (libItem.Target->GetType() == cmStateEnums::UNKNOWN_LIBRARY) {
  3474. canUseLinkPhase = canUseLinkPhase && forceLinkPhase;
  3475. } else {
  3476. // If a library target uses custom build output directory Xcode
  3477. // won't pick it up so we have to resort back to linker flags,
  3478. // but that's OK as long as the custom output dir is absolute
  3479. // path.
  3480. for (auto const& libConfigName :
  3481. this->CurrentConfigurationTypes) {
  3482. canUseLinkPhase = canUseLinkPhase &&
  3483. libItem.Target->UsesDefaultOutputDir(
  3484. libConfigName, cmStateEnums::RuntimeBinaryArtifact);
  3485. }
  3486. }
  3487. libName = libItem.Target->GetName();
  3488. } else {
  3489. libName = cmSystemTools::GetFilenameName(libItem.Value.Value);
  3490. // We don't want all the possible files here, just standard
  3491. // libraries
  3492. auto const libExt = cmSystemTools::GetFilenameExtension(libName);
  3493. if (!IsLinkPhaseLibraryExtension(libExt)) {
  3494. canUseLinkPhase = false;
  3495. }
  3496. }
  3497. }
  3498. if (canUseLinkPhase) {
  3499. // Add unique configuration name to target-config map for later
  3500. // checks
  3501. auto& configVector = targetConfigMap[libName];
  3502. if (std::find(configVector.begin(), configVector.end(),
  3503. configName) == configVector.end()) {
  3504. configVector.push_back(configName);
  3505. }
  3506. // Add a pair of config and item to target-item map
  3507. auto& itemVector = targetItemMap[libName];
  3508. itemVector.emplace_back(configName, &libItem);
  3509. // Add product file-name to a lib-product map
  3510. auto productName =
  3511. cmSystemTools::GetFilenameName(libItem.Value.Value);
  3512. auto& productVector = targetProductNameMap[libName];
  3513. if (std::find(productVector.begin(), productVector.end(),
  3514. productName) == productVector.end()) {
  3515. productVector.push_back(productName);
  3516. }
  3517. continue;
  3518. }
  3519. }
  3520. // Add this library item to a regular linker flag list
  3521. addToLinkerArguments(configName, &libItem);
  3522. }
  3523. }
  3524. // Go through target library map and separate libraries that are linked
  3525. // in all configurations and produce only single product, from the rest.
  3526. // Only these will be linked through "Link Binary With Libraries" build
  3527. // phase.
  3528. for (auto const& targetLibConfigs : targetConfigMap) {
  3529. // Add this library to "Link Binary With Libraries" build phase if it's
  3530. // linked in all configurations and it has only one product name
  3531. auto& itemVector = targetItemMap[targetLibConfigs.first];
  3532. auto& productVector = targetProductNameMap[targetLibConfigs.first];
  3533. if (targetLibConfigs.second == this->CurrentConfigurationTypes &&
  3534. productVector.size() == 1) {
  3535. // Add this library to "Link Binary With Libraries" list
  3536. linkPhaseTargetVector.push_back(itemVector[0].second);
  3537. } else {
  3538. for (auto const& libItem : targetItemMap[targetLibConfigs.first]) {
  3539. // Add this library item to a regular linker flag list
  3540. addToLinkerArguments(libItem.first, libItem.second);
  3541. }
  3542. }
  3543. }
  3544. // Add libraries to "Link Binary With Libraries" build phase and collect
  3545. // their search paths. Xcode does not support per-configuration linking
  3546. // in this build phase so we don't have to do this for each configuration
  3547. // separately.
  3548. std::vector<std::string> linkSearchPaths;
  3549. std::vector<std::string> frameworkSearchPaths;
  3550. std::set<std::pair<cmXCodeObject*, std::string>> linkBuildFileSet;
  3551. for (auto const& libItem : linkPhaseTargetVector) {
  3552. // Add target output directory as a library search path
  3553. std::string linkDir;
  3554. if (libItem->Target) {
  3555. linkDir = libItem->Target->GetLocationForBuild();
  3556. } else {
  3557. linkDir = libItem->Value.Value;
  3558. }
  3559. if (cmHasSuffix(libItem->GetFeatureName(), "FRAMEWORK"_s)) {
  3560. auto fwDescriptor = this->SplitFrameworkPath(
  3561. linkDir, cmGlobalGenerator::FrameworkFormat::Extended);
  3562. if (fwDescriptor && !fwDescriptor->Directory.empty()) {
  3563. linkDir = fwDescriptor->Directory;
  3564. if (std::find(frameworkSearchPaths.begin(), frameworkSearchPaths.end(),
  3565. linkDir) == frameworkSearchPaths.end()) {
  3566. frameworkSearchPaths.push_back(linkDir);
  3567. }
  3568. }
  3569. } else {
  3570. linkDir = cmSystemTools::GetParentDirectory(linkDir);
  3571. if (std::find(linkSearchPaths.begin(), linkSearchPaths.end(), linkDir) ==
  3572. linkSearchPaths.end()) {
  3573. linkSearchPaths.push_back(linkDir);
  3574. }
  3575. }
  3576. if (libItem->Target && !libItem->Target->IsImported()) {
  3577. for (auto const& configName : this->CurrentConfigurationTypes) {
  3578. target->AddDependTarget(configName, libItem->Target->GetName());
  3579. }
  3580. }
  3581. // Get the library target
  3582. auto* libTarget = FindXCodeTarget(libItem->Target);
  3583. cmXCodeObject* buildFile;
  3584. if (!libTarget) {
  3585. if (libItem->IsPath == cmComputeLinkInformation::ItemIsPath::Yes) {
  3586. // Get or create a direct file ref in the root project
  3587. auto cleanPath = libItem->Value.Value;
  3588. if (cmSystemTools::FileIsFullPath(cleanPath)) {
  3589. // Some arguments are reported as paths, but they are actually not,
  3590. // so we can't collapse them, and neither can we collapse relative
  3591. // paths
  3592. cleanPath = cmSystemTools::CollapseFullPath(cleanPath);
  3593. }
  3594. auto it = this->ExternalLibRefs.find(cleanPath);
  3595. if (it == this->ExternalLibRefs.end()) {
  3596. buildFile = CreateXCodeBuildFileFromPath(cleanPath, gt, "", nullptr);
  3597. if (!buildFile) {
  3598. // Add this library item back to a regular linker flag list
  3599. for (auto const& conf : configItemMap) {
  3600. addToLinkerArguments(conf.first, libItem);
  3601. }
  3602. continue;
  3603. }
  3604. this->ExternalLibRefs.emplace(cleanPath, buildFile);
  3605. } else {
  3606. buildFile = it->second;
  3607. }
  3608. } else {
  3609. // Add this library item back to a regular linker flag list
  3610. for (auto const& conf : configItemMap) {
  3611. addToLinkerArguments(conf.first, libItem);
  3612. }
  3613. continue;
  3614. }
  3615. } else {
  3616. // Add the target output file as a build reference for other targets
  3617. // to link against
  3618. auto* fileRefObject = libTarget->GetAttribute("productReference");
  3619. if (!fileRefObject) {
  3620. // Add this library item back to a regular linker flag list
  3621. for (auto const& conf : configItemMap) {
  3622. addToLinkerArguments(conf.first, libItem);
  3623. }
  3624. continue;
  3625. }
  3626. auto it = FileRefToBuildFileMap.find(fileRefObject);
  3627. if (it == FileRefToBuildFileMap.end()) {
  3628. buildFile = this->CreateObject(cmXCodeObject::PBXBuildFile);
  3629. buildFile->AddAttribute("fileRef", fileRefObject);
  3630. FileRefToBuildFileMap[fileRefObject] = buildFile;
  3631. } else {
  3632. buildFile = it->second;
  3633. }
  3634. }
  3635. // Add this reference to current target
  3636. auto* buildPhases = target->GetAttribute("buildPhases");
  3637. if (!buildPhases) {
  3638. cmSystemTools::Error("Missing buildPhase of target");
  3639. continue;
  3640. }
  3641. auto* frameworkBuildPhase =
  3642. buildPhases->GetObject(cmXCodeObject::PBXFrameworksBuildPhase);
  3643. if (!frameworkBuildPhase) {
  3644. cmSystemTools::Error("Missing PBXFrameworksBuildPhase of buildPhase");
  3645. continue;
  3646. }
  3647. auto* buildFiles = frameworkBuildPhase->GetAttribute("files");
  3648. if (!buildFiles) {
  3649. cmSystemTools::Error("Missing files of PBXFrameworksBuildPhase");
  3650. continue;
  3651. }
  3652. if (buildFile) {
  3653. if (cmHasPrefix(libItem->GetFeatureName(), "WEAK_"_s)) {
  3654. auto key = std::make_pair(buildFile->GetAttribute("fileRef"),
  3655. libItem->GetFeatureName());
  3656. if (linkBuildFileSet.find(key) != linkBuildFileSet.end()) {
  3657. continue;
  3658. }
  3659. linkBuildFileSet.insert(key);
  3660. cmXCodeObject* buildObject =
  3661. this->CreateObject(cmXCodeObject::PBXBuildFile);
  3662. buildObject->AddAttribute("fileRef", key.first);
  3663. // Add settings, ATTRIBUTES, Weak flag
  3664. cmXCodeObject* settings =
  3665. this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  3666. cmXCodeObject* attrs = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3667. attrs->AddObject(this->CreateString("Weak"));
  3668. settings->AddAttribute("ATTRIBUTES", attrs);
  3669. buildObject->AddAttribute("settings", settings);
  3670. buildFile = buildObject;
  3671. }
  3672. if (!buildFiles->HasObject(buildFile)) {
  3673. buildFiles->AddObject(buildFile);
  3674. }
  3675. }
  3676. }
  3677. // Loop over configuration types and set per-configuration info.
  3678. for (auto const& configName : this->CurrentConfigurationTypes) {
  3679. {
  3680. // Add object library contents as link flags.
  3681. BuildObjectListOrString libSearchPaths(this, true);
  3682. std::vector<cmSourceFile const*> objs;
  3683. gt->GetExternalObjects(objs, configName);
  3684. for (auto const* sourceFile : objs) {
  3685. if (sourceFile->GetObjectLibrary().empty()) {
  3686. continue;
  3687. }
  3688. libSearchPaths.Add(this->XCodeEscapePath(sourceFile->GetFullPath()));
  3689. }
  3690. this->AppendBuildSettingAttribute(
  3691. target, this->GetTargetLinkFlagsVar(gt), libSearchPaths.CreateList(),
  3692. configName);
  3693. }
  3694. // Compute the link library and directory information.
  3695. cmComputeLinkInformation* cli = gt->GetLinkInformation(configName);
  3696. if (!cli) {
  3697. continue;
  3698. }
  3699. // add .xcframework include paths
  3700. {
  3701. // Keep track of framework search paths we've already added or that are
  3702. // part of the set of implicit search paths. We don't want to repeat
  3703. // them and we also need to avoid hard-coding any SDK-specific paths.
  3704. // This is essential for getting device-and-simulator builds to work,
  3705. // otherwise we end up hard-coding a path to the wrong SDK for
  3706. // SDK-provided frameworks that are added by their full path.
  3707. std::set<std::string> emitted(cli->GetFrameworkPathsEmitted());
  3708. BuildObjectListOrString includePaths(this, true);
  3709. BuildObjectListOrString fwSearchPaths(this, true);
  3710. for (auto const& libItem : configItemMap[configName]) {
  3711. auto const& libName = *libItem;
  3712. if (libName.IsPath == cmComputeLinkInformation::ItemIsPath::Yes) {
  3713. auto cleanPath = libName.Value.Value;
  3714. if (cmSystemTools::FileIsFullPath(cleanPath)) {
  3715. cleanPath = cmSystemTools::CollapseFullPath(cleanPath);
  3716. }
  3717. bool isXcFramework =
  3718. cmHasSuffix(libName.GetFeatureName(), "XCFRAMEWORK"_s);
  3719. if (isXcFramework) {
  3720. auto plist = cmParseXcFrameworkPlist(
  3721. cleanPath, *this->Makefiles.front(), libName.Value.Backtrace);
  3722. if (!plist) {
  3723. return;
  3724. }
  3725. if (auto const* library = plist->SelectSuitableLibrary(
  3726. *this->Makefiles.front(), libName.Value.Backtrace)) {
  3727. auto libraryPath =
  3728. cmStrCat(cleanPath, '/', library->LibraryIdentifier, '/',
  3729. library->LibraryPath);
  3730. if (auto const fwDescriptor = this->SplitFrameworkPath(
  3731. libraryPath,
  3732. cmGlobalGenerator::FrameworkFormat::Relaxed)) {
  3733. if (!fwDescriptor->Directory.empty() &&
  3734. emitted.insert(fwDescriptor->Directory).second) {
  3735. // This is a search path we had not added before and it
  3736. // isn't an implicit search path, so we need it
  3737. fwSearchPaths.Add(
  3738. this->XCodeEscapePath(fwDescriptor->Directory));
  3739. }
  3740. } else {
  3741. if (!library->HeadersPath.empty()) {
  3742. includePaths.Add(this->XCodeEscapePath(
  3743. cmStrCat(cleanPath, '/', library->LibraryIdentifier, '/',
  3744. library->HeadersPath)));
  3745. }
  3746. }
  3747. } else {
  3748. return;
  3749. }
  3750. }
  3751. }
  3752. }
  3753. if (!includePaths.IsEmpty()) {
  3754. this->AppendBuildSettingAttribute(target, "HEADER_SEARCH_PATHS",
  3755. includePaths.CreateList(),
  3756. configName);
  3757. }
  3758. if (!fwSearchPaths.IsEmpty()) {
  3759. this->AppendBuildSettingAttribute(target, "FRAMEWORK_SEARCH_PATHS",
  3760. fwSearchPaths.CreateList(),
  3761. configName);
  3762. }
  3763. }
  3764. // Skip link information for object libraries.
  3765. if (gt->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  3766. gt->GetType() == cmStateEnums::STATIC_LIBRARY) {
  3767. continue;
  3768. }
  3769. // Add dependencies directly on library files.
  3770. for (auto const& libDep : cli->GetDepends()) {
  3771. target->AddDependLibrary(configName, libDep);
  3772. }
  3773. // add the library search paths
  3774. {
  3775. BuildObjectListOrString libSearchPaths(this, true);
  3776. for (auto const& libDir : cli->GetDirectories()) {
  3777. if (!libDir.empty() && libDir != "/usr/lib"_s) {
  3778. cmPolicies::PolicyStatus cmp0142 =
  3779. target->GetTarget()->GetPolicyStatusCMP0142();
  3780. if (cmp0142 == cmPolicies::OLD || cmp0142 == cmPolicies::WARN) {
  3781. libSearchPaths.Add(this->XCodeEscapePath(cmStrCat(
  3782. libDir, "/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)")));
  3783. }
  3784. libSearchPaths.Add(this->XCodeEscapePath(libDir));
  3785. }
  3786. }
  3787. // Add previously collected paths where to look for libraries
  3788. // that were added to "Link Binary With Libraries"
  3789. for (auto& libDir : linkSearchPaths) {
  3790. libSearchPaths.Add(this->XCodeEscapePath(libDir));
  3791. }
  3792. // Add toolchain specified language link directories
  3793. std::string const& linkDirsString =
  3794. this->Makefiles.front()->GetSafeDefinition(cmStrCat(
  3795. "CMAKE_", cli->GetLinkLanguage(), "_STANDARD_LINK_DIRECTORIES"));
  3796. for (auto const& libDir : cmList(linkDirsString)) {
  3797. libSearchPaths.Add(this->XCodeEscapePath(libDir));
  3798. }
  3799. if (!libSearchPaths.IsEmpty()) {
  3800. this->AppendBuildSettingAttribute(target, "LIBRARY_SEARCH_PATHS",
  3801. libSearchPaths.CreateList(),
  3802. configName);
  3803. }
  3804. }
  3805. // add framework search paths
  3806. {
  3807. BuildObjectListOrString fwSearchPaths(this, true);
  3808. // Add previously collected paths where to look for frameworks
  3809. // that were added to "Link Binary With Libraries"
  3810. for (auto& fwDir : frameworkSearchPaths) {
  3811. fwSearchPaths.Add(this->XCodeEscapePath(fwDir));
  3812. }
  3813. if (!fwSearchPaths.IsEmpty()) {
  3814. this->AppendBuildSettingAttribute(target, "FRAMEWORK_SEARCH_PATHS",
  3815. fwSearchPaths.CreateList(),
  3816. configName);
  3817. }
  3818. }
  3819. // now add the left-over link libraries
  3820. {
  3821. // Keep track of framework search paths we've already added or that are
  3822. // part of the set of implicit search paths. We don't want to repeat
  3823. // them and we also need to avoid hard-coding any SDK-specific paths.
  3824. // This is essential for getting device-and-simulator builds to work,
  3825. // otherwise we end up hard-coding a path to the wrong SDK for
  3826. // SDK-provided frameworks that are added by their full path.
  3827. std::set<std::string> emitted(cli->GetFrameworkPathsEmitted());
  3828. BuildObjectListOrString libPaths(this, true);
  3829. BuildObjectListOrString fwSearchPaths(this, true);
  3830. for (auto const& libItem : configItemMap[configName]) {
  3831. auto const& libName = *libItem;
  3832. if (libName.IsPath == cmComputeLinkInformation::ItemIsPath::Yes) {
  3833. auto cleanPath = libName.Value.Value;
  3834. if (cmSystemTools::FileIsFullPath(cleanPath)) {
  3835. cleanPath = cmSystemTools::CollapseFullPath(cleanPath);
  3836. }
  3837. bool isXcFramework =
  3838. cmHasSuffix(libName.GetFeatureName(), "XCFRAMEWORK"_s);
  3839. bool isFramework = !isXcFramework &&
  3840. cmHasSuffix(libName.GetFeatureName(), "FRAMEWORK"_s);
  3841. if (isFramework) {
  3842. auto const fwDescriptor = this->SplitFrameworkPath(
  3843. cleanPath, cmGlobalGenerator::FrameworkFormat::Extended);
  3844. if (isFramework && !fwDescriptor->Directory.empty() &&
  3845. emitted.insert(fwDescriptor->Directory).second) {
  3846. // This is a search path we had not added before and it isn't
  3847. // an implicit search path, so we need it
  3848. fwSearchPaths.Add(
  3849. this->XCodeEscapePath(fwDescriptor->Directory));
  3850. }
  3851. if (libName.GetFeatureName() == "__CMAKE_LINK_FRAMEWORK"_s) {
  3852. // use the full path
  3853. libPaths.Add(
  3854. libName.GetFormattedItem(this->XCodeEscapePath(cleanPath))
  3855. .Value);
  3856. } else {
  3857. libPaths.Add(libName
  3858. .GetFormattedItem(this->XCodeEscapePath(
  3859. fwDescriptor->GetLinkName()))
  3860. .Value);
  3861. }
  3862. } else if (isXcFramework) {
  3863. auto plist = cmParseXcFrameworkPlist(
  3864. cleanPath, *this->Makefiles.front(), libName.Value.Backtrace);
  3865. if (!plist) {
  3866. return;
  3867. }
  3868. if (auto const* library = plist->SelectSuitableLibrary(
  3869. *this->Makefiles.front(), libName.Value.Backtrace)) {
  3870. auto libraryPath =
  3871. cmStrCat(cleanPath, '/', library->LibraryIdentifier, '/',
  3872. library->LibraryPath);
  3873. if (auto const fwDescriptor = this->SplitFrameworkPath(
  3874. libraryPath,
  3875. cmGlobalGenerator::FrameworkFormat::Relaxed)) {
  3876. libPaths.Add(cmStrCat(
  3877. "-framework ",
  3878. this->XCodeEscapePath(fwDescriptor->GetLinkName())));
  3879. } else {
  3880. libPaths.Add(
  3881. libName.GetFormattedItem(this->XCodeEscapePath(libraryPath))
  3882. .Value);
  3883. }
  3884. } else {
  3885. return;
  3886. }
  3887. } else {
  3888. libPaths.Add(
  3889. libName.GetFormattedItem(this->XCodeEscapePath(cleanPath))
  3890. .Value);
  3891. }
  3892. if ((!libName.Target || libName.Target->IsImported()) &&
  3893. (isFramework || isXcFramework ||
  3894. IsLinkPhaseLibraryExtension(cleanPath))) {
  3895. // Create file reference for embedding
  3896. auto it = this->ExternalLibRefs.find(cleanPath);
  3897. if (it == this->ExternalLibRefs.end()) {
  3898. auto* buildFile =
  3899. this->CreateXCodeBuildFileFromPath(cleanPath, gt, "", nullptr);
  3900. if (buildFile) {
  3901. this->ExternalLibRefs.emplace(cleanPath, buildFile);
  3902. }
  3903. }
  3904. }
  3905. } else if (!libName.Target ||
  3906. libName.Target->GetType() !=
  3907. cmStateEnums::INTERFACE_LIBRARY) {
  3908. libPaths.Add(libName.Value.Value);
  3909. }
  3910. if (libName.Target && !libName.Target->IsImported()) {
  3911. target->AddDependTarget(configName, libName.Target->GetName());
  3912. }
  3913. }
  3914. if (!libPaths.IsEmpty()) {
  3915. this->AppendBuildSettingAttribute(target,
  3916. this->GetTargetLinkFlagsVar(gt),
  3917. libPaths.CreateList(), configName);
  3918. }
  3919. if (!fwSearchPaths.IsEmpty()) {
  3920. this->AppendBuildSettingAttribute(target, "FRAMEWORK_SEARCH_PATHS",
  3921. fwSearchPaths.CreateList(),
  3922. configName);
  3923. }
  3924. }
  3925. }
  3926. }
  3927. void cmGlobalXCodeGenerator::AddEmbeddedObjects(
  3928. cmXCodeObject* target, std::string const& copyFilesBuildPhaseName,
  3929. std::string const& embedPropertyName, std::string const& dstSubfolderSpec,
  3930. int actionsOnByDefault, std::string const& defaultDstPath)
  3931. {
  3932. cmGeneratorTarget* gt = target->GetTarget();
  3933. if (!gt) {
  3934. cmSystemTools::Error("Error no target on xobject\n");
  3935. return;
  3936. }
  3937. if (!gt->IsInBuildSystem()) {
  3938. return;
  3939. }
  3940. bool isFrameworkTarget = gt->IsFrameworkOnApple();
  3941. bool isBundleTarget = gt->GetPropertyAsBool("MACOSX_BUNDLE");
  3942. bool isCFBundleTarget = gt->IsCFBundleOnApple();
  3943. if (!(isFrameworkTarget || isBundleTarget || isCFBundleTarget)) {
  3944. return;
  3945. }
  3946. cmValue files = gt->GetProperty(embedPropertyName);
  3947. if (!files) {
  3948. return;
  3949. }
  3950. // Create an "Embedded Frameworks" build phase
  3951. auto* copyFilesBuildPhase =
  3952. this->CreateObject(cmXCodeObject::PBXCopyFilesBuildPhase);
  3953. copyFilesBuildPhase->SetComment(copyFilesBuildPhaseName);
  3954. copyFilesBuildPhase->AddAttribute("buildActionMask",
  3955. this->CreateString("2147483647"));
  3956. copyFilesBuildPhase->AddAttribute("dstSubfolderSpec",
  3957. this->CreateString(dstSubfolderSpec));
  3958. copyFilesBuildPhase->AddAttribute(
  3959. "name", this->CreateString(copyFilesBuildPhaseName));
  3960. if (cmValue fwEmbedPath =
  3961. gt->GetProperty(cmStrCat(embedPropertyName, "_PATH"))) {
  3962. copyFilesBuildPhase->AddAttribute("dstPath",
  3963. this->CreateString(*fwEmbedPath));
  3964. } else {
  3965. copyFilesBuildPhase->AddAttribute("dstPath",
  3966. this->CreateString(defaultDstPath));
  3967. }
  3968. copyFilesBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  3969. this->CreateString("0"));
  3970. cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3971. // Collect all embedded frameworks and dylibs and add them to build phase
  3972. cmList relFiles{ *files };
  3973. for (std::string const& relFile : relFiles) {
  3974. cmXCodeObject* buildFile{ nullptr };
  3975. std::string filePath = relFile;
  3976. auto* genTarget = this->FindGeneratorTarget(relFile);
  3977. if (genTarget) {
  3978. // This is a target - get it's product path reference
  3979. auto* xcTarget = this->FindXCodeTarget(genTarget);
  3980. if (!xcTarget) {
  3981. cmSystemTools::Error(
  3982. cmStrCat("Can not find a target for ", genTarget->GetName()));
  3983. continue;
  3984. }
  3985. // Add the target output file as a build reference for other targets
  3986. // to link against
  3987. auto* fileRefObject = xcTarget->GetAttribute("productReference");
  3988. if (!fileRefObject) {
  3989. cmSystemTools::Error(cmStrCat("Target ", genTarget->GetName(),
  3990. " is missing product reference"));
  3991. continue;
  3992. }
  3993. auto it = this->FileRefToEmbedBuildFileMap.find(fileRefObject);
  3994. if (it == this->FileRefToEmbedBuildFileMap.end()) {
  3995. buildFile = this->CreateObject(cmXCodeObject::PBXBuildFile);
  3996. buildFile->AddAttribute("fileRef", fileRefObject);
  3997. this->FileRefToEmbedBuildFileMap[fileRefObject] = buildFile;
  3998. } else {
  3999. buildFile = it->second;
  4000. }
  4001. } else if (cmSystemTools::IsPathToFramework(relFile) ||
  4002. cmSystemTools::IsPathToMacOSSharedLibrary(relFile) ||
  4003. cmSystemTools::FileIsDirectory(filePath)) {
  4004. // This is a regular string path - create file reference
  4005. cmXCodeObject* fileRef =
  4006. this->CreateXCodeFileReferenceFromPath(relFile, gt, "", nullptr);
  4007. if (fileRef) {
  4008. buildFile = this->CreateObject(cmXCodeObject::PBXBuildFile);
  4009. buildFile->SetComment(fileRef->GetComment());
  4010. buildFile->AddAttribute("fileRef",
  4011. this->CreateObjectReference(fileRef));
  4012. }
  4013. if (!buildFile) {
  4014. cmSystemTools::Error(
  4015. cmStrCat("Can't create build file for ", relFile));
  4016. continue;
  4017. }
  4018. }
  4019. if (!buildFile) {
  4020. cmSystemTools::Error(cmStrCat("Can't find a build file for ", relFile));
  4021. continue;
  4022. }
  4023. // Set build file configuration
  4024. cmXCodeObject* settings =
  4025. this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  4026. cmXCodeObject* attrs = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4027. bool removeHeaders = actionsOnByDefault & RemoveHeadersOnCopyByDefault;
  4028. if (cmValue prop = gt->GetProperty(
  4029. cmStrCat(embedPropertyName, "_REMOVE_HEADERS_ON_COPY"))) {
  4030. removeHeaders = prop.IsOn();
  4031. }
  4032. if (removeHeaders) {
  4033. attrs->AddObject(this->CreateString("RemoveHeadersOnCopy"));
  4034. }
  4035. bool codeSign = actionsOnByDefault & CodeSignOnCopyByDefault;
  4036. if (cmValue prop =
  4037. gt->GetProperty(cmStrCat(embedPropertyName, "_CODE_SIGN_ON_COPY"))) {
  4038. codeSign = prop.IsOn();
  4039. }
  4040. if (codeSign) {
  4041. attrs->AddObject(this->CreateString("CodeSignOnCopy"));
  4042. }
  4043. settings->AddAttributeIfNotEmpty("ATTRIBUTES", attrs);
  4044. buildFile->AddAttributeIfNotEmpty("settings", settings);
  4045. if (!buildFiles->HasObject(buildFile)) {
  4046. buildFiles->AddObject(buildFile);
  4047. }
  4048. }
  4049. copyFilesBuildPhase->AddAttribute("files", buildFiles);
  4050. auto* buildPhases = target->GetAttribute("buildPhases");
  4051. // Embed-something build phases must be inserted before the post-build
  4052. // command because that command is expected to be last
  4053. buildPhases->InsertObject(buildPhases->GetObjectCount() - 1,
  4054. copyFilesBuildPhase);
  4055. }
  4056. void cmGlobalXCodeGenerator::AddEmbeddedFrameworks(cmXCodeObject* target)
  4057. {
  4058. static auto const* const dstSubfolderSpec = "10";
  4059. // Despite the name, by default Xcode uses "Embed Frameworks" build phase
  4060. // for both frameworks and dynamic libraries
  4061. this->AddEmbeddedObjects(target, "Embed Frameworks",
  4062. "XCODE_EMBED_FRAMEWORKS", dstSubfolderSpec,
  4063. NoActionOnCopyByDefault);
  4064. }
  4065. void cmGlobalXCodeGenerator::AddEmbeddedPlugIns(cmXCodeObject* target)
  4066. {
  4067. static auto const* const dstSubfolderSpec = "13";
  4068. this->AddEmbeddedObjects(target, "Embed PlugIns", "XCODE_EMBED_PLUGINS",
  4069. dstSubfolderSpec, NoActionOnCopyByDefault);
  4070. }
  4071. void cmGlobalXCodeGenerator::AddEmbeddedAppExtensions(cmXCodeObject* target)
  4072. {
  4073. static auto const* const dstSubfolderSpec = "13";
  4074. this->AddEmbeddedObjects(target, "Embed App Extensions",
  4075. "XCODE_EMBED_APP_EXTENSIONS", dstSubfolderSpec,
  4076. RemoveHeadersOnCopyByDefault);
  4077. }
  4078. void cmGlobalXCodeGenerator::AddEmbeddedExtensionKitExtensions(
  4079. cmXCodeObject* target)
  4080. {
  4081. static auto const* const dstSubfolderSpec = "16";
  4082. this->AddEmbeddedObjects(target, "Embed App Extensions",
  4083. "XCODE_EMBED_EXTENSIONKIT_EXTENSIONS",
  4084. dstSubfolderSpec, RemoveHeadersOnCopyByDefault,
  4085. "$(EXTENSIONS_FOLDER_PATH)");
  4086. }
  4087. void cmGlobalXCodeGenerator::AddEmbeddedResources(cmXCodeObject* target)
  4088. {
  4089. static auto const dstSubfolderSpec = "7";
  4090. this->AddEmbeddedObjects(target, "Embed Resources", "XCODE_EMBED_RESOURCES",
  4091. dstSubfolderSpec, NoActionOnCopyByDefault);
  4092. }
  4093. void cmGlobalXCodeGenerator::AddEmbeddedXPCServices(cmXCodeObject* target)
  4094. {
  4095. static auto const dstSubfolderSpec = "16";
  4096. this->AddEmbeddedObjects(
  4097. target, "Embed XPC Services", "XCODE_EMBED_XPC_SERVICES", dstSubfolderSpec,
  4098. NoActionOnCopyByDefault, "$(CONTENTS_FOLDER_PATH)/XPCServices");
  4099. }
  4100. bool cmGlobalXCodeGenerator::CreateGroups(
  4101. std::vector<cmLocalGenerator*>& generators)
  4102. {
  4103. for (auto& generator : generators) {
  4104. cmMakefile* mf = generator->GetMakefile();
  4105. std::vector<cmSourceGroup> sourceGroups = mf->GetSourceGroups();
  4106. for (auto const& gtgt : generator->GetGeneratorTargets()) {
  4107. // Same skipping logic here as in CreateXCodeTargets so that we do not
  4108. // end up with (empty anyhow) ZERO_CHECK, install, or test source
  4109. // groups:
  4110. //
  4111. if (!gtgt->IsInBuildSystem() ||
  4112. gtgt->GetType() == cmStateEnums::GLOBAL_TARGET ||
  4113. gtgt->GetName() == CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
  4114. continue;
  4115. }
  4116. auto addSourceToGroup = [this, mf, &gtgt,
  4117. &sourceGroups](std::string const& source) {
  4118. cmSourceGroup* sourceGroup = mf->FindSourceGroup(source, sourceGroups);
  4119. cmXCodeObject* pbxgroup =
  4120. this->CreateOrGetPBXGroup(gtgt.get(), sourceGroup);
  4121. std::string key = GetGroupMapKeyFromPath(gtgt.get(), source);
  4122. this->GroupMap[key] = pbxgroup;
  4123. };
  4124. // Put cmSourceFile instances in proper groups:
  4125. for (auto const& si : gtgt->GetAllConfigSources()) {
  4126. cmSourceFile const* sf = si.Source;
  4127. if (!sf->GetObjectLibrary().empty()) {
  4128. // Object library files go on the link line instead.
  4129. continue;
  4130. }
  4131. addSourceToGroup(sf->GetFullPath());
  4132. }
  4133. // Add CMakeLists.txt file for user convenience.
  4134. {
  4135. std::string listfile = this->GetCMakeInstance()->GetCMakeListFile(
  4136. gtgt->GetLocalGenerator()->GetCurrentSourceDirectory());
  4137. cmSourceFile* sf = gtgt->Makefile->GetOrCreateSource(
  4138. listfile, false, cmSourceFileLocationKind::Known);
  4139. sf->SetSpecialSourceType(cmSourceFile::SpecialSourceType::CMakeLists);
  4140. addSourceToGroup(sf->ResolveFullPath());
  4141. }
  4142. // Add the Info.plist we are about to generate for an App Bundle.
  4143. if (gtgt->GetPropertyAsBool("MACOSX_BUNDLE")) {
  4144. std::string plist = this->ComputeInfoPListLocation(gtgt.get());
  4145. cmSourceFile* sf = gtgt->Makefile->GetOrCreateSource(
  4146. plist, true, cmSourceFileLocationKind::Known);
  4147. sf->SetSpecialSourceType(
  4148. cmSourceFile::SpecialSourceType::BundleInfoPlist);
  4149. addSourceToGroup(sf->ResolveFullPath());
  4150. }
  4151. }
  4152. }
  4153. return true;
  4154. }
  4155. cmXCodeObject* cmGlobalXCodeGenerator::CreatePBXGroup(cmXCodeObject* parent,
  4156. std::string const& name)
  4157. {
  4158. cmXCodeObject* parentChildren = nullptr;
  4159. if (parent) {
  4160. parentChildren = parent->GetAttribute("children");
  4161. }
  4162. cmXCodeObject* group = this->CreateObject(cmXCodeObject::PBXGroup);
  4163. cmXCodeObject* groupChildren =
  4164. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4165. group->AddAttribute("name", this->CreateString(name));
  4166. group->AddAttribute("children", groupChildren);
  4167. group->AddAttribute("sourceTree", this->CreateString("<group>"));
  4168. if (parentChildren) {
  4169. parentChildren->AddObject(group);
  4170. }
  4171. return group;
  4172. }
  4173. cmXCodeObject* cmGlobalXCodeGenerator::CreateOrGetPBXGroup(
  4174. cmGeneratorTarget* gtgt, cmSourceGroup* sg)
  4175. {
  4176. std::string s;
  4177. std::string target;
  4178. std::string const targetFolder = gtgt->GetEffectiveFolderName();
  4179. if (!targetFolder.empty()) {
  4180. target = cmStrCat(targetFolder, '/');
  4181. }
  4182. target += gtgt->GetName();
  4183. s = cmStrCat(target, '/', sg->GetFullName());
  4184. auto it = this->GroupNameMap.find(s);
  4185. if (it != this->GroupNameMap.end()) {
  4186. return it->second;
  4187. }
  4188. it = this->TargetGroup.find(target);
  4189. cmXCodeObject* tgroup = nullptr;
  4190. if (it != this->TargetGroup.end()) {
  4191. tgroup = it->second;
  4192. } else {
  4193. std::vector<std::string> const tgt_folders = cmTokenize(target, '/');
  4194. std::string curr_tgt_folder;
  4195. for (std::vector<std::string>::size_type i = 0; i < tgt_folders.size();
  4196. i++) {
  4197. if (i != 0) {
  4198. curr_tgt_folder += '/';
  4199. }
  4200. curr_tgt_folder += tgt_folders[i];
  4201. it = this->TargetGroup.find(curr_tgt_folder);
  4202. if (it != this->TargetGroup.end()) {
  4203. tgroup = it->second;
  4204. continue;
  4205. }
  4206. tgroup = this->CreatePBXGroup(tgroup, tgt_folders[i]);
  4207. this->TargetGroup[curr_tgt_folder] = tgroup;
  4208. if (i == 0) {
  4209. this->MainGroupChildren->AddObject(tgroup);
  4210. }
  4211. }
  4212. }
  4213. this->TargetGroup[target] = tgroup;
  4214. // If it's the default source group (empty name) then put the source file
  4215. // directly in the tgroup...
  4216. //
  4217. if (sg->GetFullName().empty()) {
  4218. this->GroupNameMap[s] = tgroup;
  4219. return tgroup;
  4220. }
  4221. // It's a recursive folder structure, let's find the real parent group
  4222. if (sg->GetFullName() != sg->GetName()) {
  4223. std::string curr_folder = cmStrCat(target, '/');
  4224. for (auto const& folder : cmTokenize(sg->GetFullName(), '\\')) {
  4225. curr_folder += folder;
  4226. auto const i_folder = this->GroupNameMap.find(curr_folder);
  4227. // Create new folder
  4228. if (i_folder == this->GroupNameMap.end()) {
  4229. cmXCodeObject* group = this->CreatePBXGroup(tgroup, folder);
  4230. this->GroupNameMap[curr_folder] = group;
  4231. tgroup = group;
  4232. } else {
  4233. tgroup = i_folder->second;
  4234. }
  4235. curr_folder += '\\';
  4236. }
  4237. return tgroup;
  4238. }
  4239. cmXCodeObject* group = this->CreatePBXGroup(tgroup, sg->GetName());
  4240. this->GroupNameMap[s] = group;
  4241. return group;
  4242. }
  4243. bool cmGlobalXCodeGenerator::CreateXCodeObjects(
  4244. cmLocalGenerator* root, std::vector<cmLocalGenerator*>& generators)
  4245. {
  4246. this->ClearXCodeObjects();
  4247. this->RootObject = nullptr;
  4248. this->MainGroupChildren = nullptr;
  4249. this->FrameworkGroup = nullptr;
  4250. cmXCodeObject* group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  4251. group->AddAttribute("COPY_PHASE_STRIP", this->CreateString("NO"));
  4252. cmXCodeObject* listObjs = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4253. for (std::string const& CurrentConfigurationType :
  4254. this->CurrentConfigurationTypes) {
  4255. cmXCodeObject* buildStyle =
  4256. this->CreateObject(cmXCodeObject::PBXBuildStyle);
  4257. std::string const& name = CurrentConfigurationType;
  4258. buildStyle->AddAttribute("name", this->CreateString(name));
  4259. buildStyle->SetComment(name);
  4260. cmXCodeObject* sgroup = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  4261. sgroup->AddAttribute("COPY_PHASE_STRIP", this->CreateString("NO"));
  4262. buildStyle->AddAttribute("buildSettings", sgroup);
  4263. listObjs->AddObject(buildStyle);
  4264. }
  4265. cmXCodeObject* mainGroup = this->CreateObject(cmXCodeObject::PBXGroup);
  4266. this->MainGroupChildren = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4267. mainGroup->AddAttribute("children", this->MainGroupChildren);
  4268. mainGroup->AddAttribute("sourceTree", this->CreateString("<group>"));
  4269. // now create the cmake groups
  4270. if (!this->CreateGroups(generators)) {
  4271. return false;
  4272. }
  4273. cmXCodeObject* productGroup = this->CreateObject(cmXCodeObject::PBXGroup);
  4274. productGroup->AddAttribute("name", this->CreateString("Products"));
  4275. productGroup->AddAttribute("sourceTree", this->CreateString("<group>"));
  4276. cmXCodeObject* productGroupChildren =
  4277. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4278. productGroup->AddAttribute("children", productGroupChildren);
  4279. this->MainGroupChildren->AddObject(productGroup);
  4280. this->FrameworkGroup = this->CreateObject(cmXCodeObject::PBXGroup);
  4281. this->FrameworkGroup->AddAttribute("name", this->CreateString("Frameworks"));
  4282. this->FrameworkGroup->AddAttribute("sourceTree",
  4283. this->CreateString("<group>"));
  4284. cmXCodeObject* frameworkGroupChildren =
  4285. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4286. this->FrameworkGroup->AddAttribute("children", frameworkGroupChildren);
  4287. this->MainGroupChildren->AddObject(this->FrameworkGroup);
  4288. this->ResourcesGroup = this->CreateObject(cmXCodeObject::PBXGroup);
  4289. this->ResourcesGroup->AddAttribute("name", this->CreateString("Resources"));
  4290. this->ResourcesGroup->AddAttribute("sourceTree",
  4291. this->CreateString("<group>"));
  4292. cmXCodeObject* ResourcesGroupChildren =
  4293. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4294. this->ResourcesGroup->AddAttribute("children", ResourcesGroupChildren);
  4295. this->MainGroupChildren->AddObject(this->ResourcesGroup);
  4296. this->RootObject = this->CreateObject(cmXCodeObject::PBXProject);
  4297. this->RootObject->SetComment("Project object");
  4298. std::string project_id = cmStrCat("PROJECT_", root->GetProjectName());
  4299. this->RootObject->SetId(
  4300. this->GetOrCreateId(project_id, this->RootObject->GetId()));
  4301. group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  4302. this->RootObject->AddAttribute("mainGroup",
  4303. this->CreateObjectReference(mainGroup));
  4304. this->RootObject->AddAttribute("buildSettings", group);
  4305. this->RootObject->AddAttribute("buildStyles", listObjs);
  4306. this->RootObject->AddAttribute("hasScannedForEncodings",
  4307. this->CreateString("0"));
  4308. group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  4309. group->AddAttribute("BuildIndependentTargetsInParallel",
  4310. this->CreateString("YES"));
  4311. std::ostringstream v;
  4312. v << std::setfill('0') << std::setw(4) << XcodeVersion * 10;
  4313. group->AddAttribute("LastUpgradeCheck", this->CreateString(v.str()));
  4314. this->RootObject->AddAttribute("attributes", group);
  4315. this->RootObject->AddAttribute("compatibilityVersion",
  4316. this->CreateString("Xcode 3.2"));
  4317. // Point Xcode at the top of the source tree.
  4318. {
  4319. std::string pdir =
  4320. this->RelativeToBinary(root->GetCurrentSourceDirectory());
  4321. this->RootObject->AddAttribute("projectDirPath", this->CreateString(pdir));
  4322. this->RootObject->AddAttribute("projectRoot", this->CreateString(""));
  4323. }
  4324. cmXCodeObject* configlist =
  4325. this->CreateObject(cmXCodeObject::XCConfigurationList);
  4326. cmXCodeObject* buildConfigurations =
  4327. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4328. using Configs = std::vector<std::pair<std::string, cmXCodeObject*>>;
  4329. Configs configs;
  4330. std::string defaultConfigName;
  4331. for (auto const& name : this->CurrentConfigurationTypes) {
  4332. if (defaultConfigName.empty()) {
  4333. defaultConfigName = name;
  4334. }
  4335. cmXCodeObject* config =
  4336. this->CreateObject(cmXCodeObject::XCBuildConfiguration);
  4337. config->AddAttribute("name", this->CreateString(name));
  4338. configs.emplace_back(name, config);
  4339. }
  4340. if (defaultConfigName.empty()) {
  4341. defaultConfigName = "Debug";
  4342. }
  4343. for (auto& config : configs) {
  4344. buildConfigurations->AddObject(config.second);
  4345. }
  4346. configlist->AddAttribute("buildConfigurations", buildConfigurations);
  4347. std::string comment = cmStrCat("Build configuration list for PBXProject \"",
  4348. this->CurrentProject, '"');
  4349. configlist->SetComment(comment);
  4350. configlist->AddAttribute("defaultConfigurationIsVisible",
  4351. this->CreateString("0"));
  4352. configlist->AddAttribute("defaultConfigurationName",
  4353. this->CreateString(defaultConfigName));
  4354. cmXCodeObject* buildSettings =
  4355. this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  4356. cmValue sysroot = this->CurrentMakefile->GetDefinition("CMAKE_OSX_SYSROOT");
  4357. cmValue deploymentTarget =
  4358. this->CurrentMakefile->GetDefinition("CMAKE_OSX_DEPLOYMENT_TARGET");
  4359. if (sysroot) {
  4360. buildSettings->AddAttribute("SDKROOT", this->CreateString(*sysroot));
  4361. }
  4362. // recompute this as it may have been changed since enable language
  4363. this->ComputeArchitectures(this->CurrentMakefile);
  4364. std::string const archs = cmJoin(this->Architectures, " ");
  4365. if (archs.empty()) {
  4366. // Tell Xcode to use NATIVE_ARCH instead of ARCHS.
  4367. buildSettings->AddAttribute("ONLY_ACTIVE_ARCH", this->CreateString("YES"));
  4368. // When targeting macOS, use only the host architecture.
  4369. if (this->SystemName == "Darwin"_s &&
  4370. (!cmNonempty(sysroot) ||
  4371. cmSystemTools::LowerCase(*sysroot).find("macos") !=
  4372. std::string::npos)) {
  4373. buildSettings->AddAttribute("ARCHS",
  4374. this->CreateString("$(NATIVE_ARCH_ACTUAL)"));
  4375. }
  4376. } else {
  4377. // Tell Xcode to use ARCHS (ONLY_ACTIVE_ARCH defaults to NO).
  4378. buildSettings->AddAttribute("ARCHS", this->CreateString(archs));
  4379. }
  4380. if (cmNonempty(deploymentTarget)) {
  4381. buildSettings->AddAttribute(GetDeploymentPlatform(root->GetMakefile()),
  4382. this->CreateString(*deploymentTarget));
  4383. }
  4384. if (!this->GeneratorToolset.empty()) {
  4385. buildSettings->AddAttribute("GCC_VERSION",
  4386. this->CreateString(this->GeneratorToolset));
  4387. }
  4388. if (this->GetLanguageEnabled("Swift")) {
  4389. std::string swiftVersion;
  4390. if (cmValue vers = this->CurrentMakefile->GetDefinition(
  4391. "CMAKE_Swift_LANGUAGE_VERSION")) {
  4392. swiftVersion = *vers;
  4393. } else if (this->XcodeVersion >= 102) {
  4394. swiftVersion = "4.0";
  4395. } else if (this->XcodeVersion >= 83) {
  4396. swiftVersion = "3.0";
  4397. } else {
  4398. swiftVersion = "2.3";
  4399. }
  4400. buildSettings->AddAttribute("SWIFT_VERSION",
  4401. this->CreateString(swiftVersion));
  4402. }
  4403. std::string const symroot = this->GetSymrootDir();
  4404. buildSettings->AddAttribute("SYMROOT", this->CreateString(symroot));
  4405. // Inside a try_compile project, do not require signing on any platform.
  4406. if (this->CMakeInstance->GetIsInTryCompile()) {
  4407. buildSettings->AddAttribute("CODE_SIGNING_ALLOWED",
  4408. this->CreateString("NO"));
  4409. }
  4410. // This code supports the OLD behavior of CMP0157. We should be able to
  4411. // remove computing the debug configuration set once the old behavior is
  4412. // removed.
  4413. auto debugConfigs = this->GetCMakeInstance()->GetDebugConfigs();
  4414. std::set<std::string> debugConfigSet(debugConfigs.begin(),
  4415. debugConfigs.end());
  4416. for (auto& config : configs) {
  4417. CreateGlobalXCConfigSettings(root, config.second, config.first);
  4418. cmXCodeObject* buildSettingsForCfg = this->CreateFlatClone(buildSettings);
  4419. // Supports the OLD behavior of CMP0157. CMP0157 OLD behavior globally set
  4420. // wholemodule compilation for all non-debug configurations, for all
  4421. // targets.
  4422. if (this->CurrentMakefile
  4423. ->GetDefinition("CMAKE_Swift_COMPILATION_MODE_DEFAULT")
  4424. .IsEmpty()) {
  4425. if (debugConfigSet.count(cmSystemTools::UpperCase(config.first)) == 0) {
  4426. buildSettingsForCfg->AddAttribute("SWIFT_COMPILATION_MODE",
  4427. this->CreateString("wholemodule"));
  4428. }
  4429. }
  4430. // Put this last so it can override existing settings
  4431. // Convert "CMAKE_XCODE_ATTRIBUTE_*" variables directly.
  4432. for (auto const& var : this->CurrentMakefile->GetDefinitions()) {
  4433. if (cmHasLiteralPrefix(var, "CMAKE_XCODE_ATTRIBUTE_")) {
  4434. std::string attribute = var.substr(22);
  4435. this->FilterConfigurationAttribute(config.first, attribute);
  4436. if (!attribute.empty()) {
  4437. std::string processed = cmGeneratorExpression::Evaluate(
  4438. this->CurrentMakefile->GetSafeDefinition(var),
  4439. this->CurrentLocalGenerator, config.first);
  4440. buildSettingsForCfg->AddAttribute(attribute,
  4441. this->CreateString(processed));
  4442. }
  4443. }
  4444. }
  4445. // store per-config buildSettings into configuration object
  4446. config.second->AddAttribute("buildSettings", buildSettingsForCfg);
  4447. }
  4448. this->RootObject->AddAttribute("buildConfigurationList",
  4449. this->CreateObjectReference(configlist));
  4450. std::vector<cmXCodeObject*> targets;
  4451. for (auto& generator : generators) {
  4452. if (!this->CreateXCodeTargets(generator, targets)) {
  4453. return false;
  4454. }
  4455. for (auto const& ccRoot : this->CustomCommandRoots) {
  4456. if (ccRoot.second.size() > 1) {
  4457. std::string e = "The custom command ";
  4458. std::vector<std::string> const& outputs =
  4459. ccRoot.first->GetCustomCommand()->GetOutputs();
  4460. if (!outputs.empty()) {
  4461. e = cmStrCat(e, "generating\n ", outputs[0]);
  4462. } else {
  4463. e = cmStrCat(e, "driven by\n ", ccRoot.first->GetFullPath());
  4464. }
  4465. e = cmStrCat(e, "\nis attached to multiple targets:");
  4466. for (cmGeneratorTarget const* gt : ccRoot.second) {
  4467. e = cmStrCat(e, "\n ", gt->GetName());
  4468. }
  4469. e = cmStrCat(
  4470. e,
  4471. "\nbut none of these is a common dependency of the other(s). "
  4472. "This is not allowed by the Xcode \"new build system\".");
  4473. generator->IssueMessage(MessageType::FATAL_ERROR, e);
  4474. return false;
  4475. }
  4476. }
  4477. this->CustomCommandRoots.clear();
  4478. }
  4479. // loop over all targets and add link and depend info
  4480. for (auto* t : targets) {
  4481. this->AddDependAndLinkInformation(t);
  4482. this->AddEmbeddedFrameworks(t);
  4483. this->AddEmbeddedPlugIns(t);
  4484. this->AddEmbeddedAppExtensions(t);
  4485. this->AddEmbeddedExtensionKitExtensions(t);
  4486. this->AddEmbeddedResources(t);
  4487. this->AddEmbeddedXPCServices(t);
  4488. // Inherit project-wide values for any target-specific search paths.
  4489. this->InheritBuildSettingAttribute(t, "HEADER_SEARCH_PATHS");
  4490. this->InheritBuildSettingAttribute(t, "SYSTEM_HEADER_SEARCH_PATHS");
  4491. this->InheritBuildSettingAttribute(t, "FRAMEWORK_SEARCH_PATHS");
  4492. this->InheritBuildSettingAttribute(t, "SYSTEM_FRAMEWORK_SEARCH_PATHS");
  4493. this->InheritBuildSettingAttribute(t, "LIBRARY_SEARCH_PATHS");
  4494. this->InheritBuildSettingAttribute(t, "LD_RUNPATH_SEARCH_PATHS");
  4495. this->InheritBuildSettingAttribute(t, "GCC_PREPROCESSOR_DEFINITIONS");
  4496. this->InheritBuildSettingAttribute(t, "OTHER_CFLAGS");
  4497. this->InheritBuildSettingAttribute(t, "OTHER_LDFLAGS");
  4498. this->InheritBuildSettingAttribute(t, "OTHER_SWIFT_FLAGS");
  4499. this->InheritBuildSettingAttribute(t,
  4500. "SWIFT_ACTIVE_COMPILATION_CONDITIONS");
  4501. }
  4502. if (this->XcodeBuildSystem == BuildSystem::One) {
  4503. this->CreateXCodeDependHackMakefile(targets);
  4504. }
  4505. // now add all targets to the root object
  4506. cmXCodeObject* allTargets = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4507. for (auto* t : targets) {
  4508. allTargets->AddObject(t);
  4509. cmXCodeObject* productRef = t->GetAttribute("productReference");
  4510. if (productRef) {
  4511. productGroupChildren->AddObject(productRef->GetObject());
  4512. }
  4513. }
  4514. this->RootObject->AddAttribute("targets", allTargets);
  4515. return true;
  4516. }
  4517. std::string cmGlobalXCodeGenerator::GetSymrootDir() const
  4518. {
  4519. return cmStrCat(this->CMakeInstance->GetHomeOutputDirectory(), "/build");
  4520. }
  4521. std::string cmGlobalXCodeGenerator::GetTargetTempDir(
  4522. cmGeneratorTarget const* gt, std::string const& configName) const
  4523. {
  4524. // Use a path inside the SYMROOT.
  4525. return cmStrCat(this->GetSymrootDir(), '/', gt->GetName(), ".build/",
  4526. configName);
  4527. }
  4528. void cmGlobalXCodeGenerator::ComputeArchitectures(cmMakefile* mf)
  4529. {
  4530. this->Architectures.clear();
  4531. cmList::append(this->Architectures,
  4532. mf->GetDefinition("CMAKE_OSX_ARCHITECTURES"));
  4533. if (this->Architectures.empty()) {
  4534. cmList::append(this->Architectures,
  4535. mf->GetDefinition("_CMAKE_APPLE_ARCHS_DEFAULT"));
  4536. }
  4537. if (this->Architectures.empty()) {
  4538. // With no ARCHS we use ONLY_ACTIVE_ARCH and possibly a
  4539. // platform-specific default ARCHS placeholder value.
  4540. // Look up the arch that Xcode chooses in this case.
  4541. if (cmValue arch = mf->GetDefinition("CMAKE_XCODE_ARCHS")) {
  4542. this->ObjectDirArchDefault = *arch;
  4543. // We expect only one arch but choose the first just in case.
  4544. std::string::size_type pos = this->ObjectDirArchDefault.find(';');
  4545. if (pos != std::string::npos) {
  4546. this->ObjectDirArchDefault = this->ObjectDirArchDefault.substr(0, pos);
  4547. }
  4548. }
  4549. }
  4550. this->ComputeObjectDirArch(mf);
  4551. }
  4552. void cmGlobalXCodeGenerator::ComputeObjectDirArch(cmMakefile* mf)
  4553. {
  4554. if (this->Architectures.size() > 1 || this->UseEffectivePlatformName(mf)) {
  4555. this->ObjectDirArch = "$(CURRENT_ARCH)";
  4556. } else if (!this->Architectures.empty()) {
  4557. this->ObjectDirArch = this->Architectures[0];
  4558. } else {
  4559. this->ObjectDirArch = this->ObjectDirArchDefault;
  4560. }
  4561. }
  4562. void cmGlobalXCodeGenerator::CreateXCodeDependHackMakefile(
  4563. std::vector<cmXCodeObject*>& targets)
  4564. {
  4565. cmGeneratedFileStream makefileStream(this->CurrentXCodeHackMakefile);
  4566. if (!makefileStream) {
  4567. cmSystemTools::Error(
  4568. cmStrCat("Could not create ", this->CurrentXCodeHackMakefile));
  4569. return;
  4570. }
  4571. makefileStream.SetCopyIfDifferent(true);
  4572. // one more pass for external depend information not handled
  4573. // correctly by xcode
  4574. /* clang-format off */
  4575. makefileStream << "# DO NOT EDIT\n"
  4576. "# This makefile makes sure all linkable targets are\n"
  4577. "# up-to-date with anything they link to\n"
  4578. "default:\n"
  4579. "\techo \"Do not invoke directly\"\n"
  4580. "\n";
  4581. /* clang-format on */
  4582. std::set<std::string> dummyRules;
  4583. // Write rules to help Xcode relink things at the right time.
  4584. /* clang-format off */
  4585. makefileStream <<
  4586. "# Rules to remove targets that are older than anything to which they\n"
  4587. "# link. This forces Xcode to relink the targets from scratch. It\n"
  4588. "# does not seem to check these dependencies itself.\n";
  4589. /* clang-format on */
  4590. for (auto const& configName : this->CurrentConfigurationTypes) {
  4591. for (auto* target : targets) {
  4592. cmGeneratorTarget* gt = target->GetTarget();
  4593. if (gt->GetType() == cmStateEnums::EXECUTABLE ||
  4594. gt->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  4595. gt->GetType() == cmStateEnums::STATIC_LIBRARY ||
  4596. gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4597. gt->GetType() == cmStateEnums::MODULE_LIBRARY) {
  4598. // Declare an entry point for the target post-build phase.
  4599. makefileStream << this->PostBuildMakeTarget(gt->GetName(), configName)
  4600. << ":\n";
  4601. }
  4602. if (gt->GetType() == cmStateEnums::EXECUTABLE ||
  4603. gt->GetType() == cmStateEnums::STATIC_LIBRARY ||
  4604. gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4605. gt->GetType() == cmStateEnums::MODULE_LIBRARY) {
  4606. std::string tfull = gt->GetFullPath(configName);
  4607. std::string trel = ConvertToMakefilePath(tfull);
  4608. // Add this target to the post-build phases of its dependencies.
  4609. auto const y = target->GetDependTargets().find(configName);
  4610. if (y != target->GetDependTargets().end()) {
  4611. for (auto const& deptgt : y->second) {
  4612. makefileStream << this->PostBuildMakeTarget(deptgt, configName)
  4613. << ": " << trel << '\n';
  4614. }
  4615. }
  4616. std::vector<BT<cmGeneratorTarget*>> objlibs;
  4617. gt->GetObjectLibrariesInSources(objlibs);
  4618. for (auto const& objLib : objlibs) {
  4619. makefileStream << this->PostBuildMakeTarget(objLib.Value->GetName(),
  4620. configName)
  4621. << ": " << trel << '\n';
  4622. }
  4623. // Create a rule for this target.
  4624. makefileStream << trel << ':';
  4625. // List dependencies if any exist.
  4626. auto const x = target->GetDependLibraries().find(configName);
  4627. if (x != target->GetDependLibraries().end()) {
  4628. for (auto const& deplib : x->second) {
  4629. std::string file = ConvertToMakefilePath(deplib);
  4630. makefileStream << "\\\n\t" << file;
  4631. dummyRules.insert(file);
  4632. }
  4633. }
  4634. for (auto const& objLib : objlibs) {
  4635. std::string const& objLibName = objLib.Value->GetName();
  4636. std::string d = cmStrCat(this->GetTargetTempDir(gt, configName),
  4637. "/lib", objLibName, ".a");
  4638. std::string dependency = ConvertToMakefilePath(d);
  4639. makefileStream << "\\\n\t" << dependency;
  4640. dummyRules.insert(dependency);
  4641. }
  4642. // Write the action to remove the target if it is out of date.
  4643. makefileStream << "\n"
  4644. "\t/bin/rm -f "
  4645. << ConvertToMakefilePath(tfull) << '\n';
  4646. // if building for more than one architecture
  4647. // then remove those executables as well
  4648. if (this->Architectures.size() > 1) {
  4649. std::string universal =
  4650. cmStrCat(this->GetTargetTempDir(gt, configName), "/$(OBJDIR)/");
  4651. for (auto const& architecture : this->Architectures) {
  4652. std::string universalFile = cmStrCat(universal, architecture, '/',
  4653. gt->GetFullName(configName));
  4654. makefileStream << "\t/bin/rm -f "
  4655. << ConvertToMakefilePath(universalFile) << '\n';
  4656. }
  4657. }
  4658. makefileStream << "\n\n";
  4659. }
  4660. }
  4661. }
  4662. makefileStream << "\n\n"
  4663. "# For each target create a dummy rule"
  4664. "so the target does not have to exist\n";
  4665. for (auto const& dummyRule : dummyRules) {
  4666. makefileStream << dummyRule << ":\n";
  4667. }
  4668. }
  4669. void cmGlobalXCodeGenerator::OutputXCodeProject(
  4670. cmLocalGenerator* root, std::vector<cmLocalGenerator*>& generators)
  4671. {
  4672. if (generators.empty()) {
  4673. return;
  4674. }
  4675. if (!this->CreateXCodeObjects(root, generators)) {
  4676. return;
  4677. }
  4678. std::string xcodeDir = cmStrCat(root->GetCurrentBinaryDirectory(), '/',
  4679. root->GetProjectName(), ".xcodeproj");
  4680. cmSystemTools::MakeDirectory(xcodeDir);
  4681. std::string xcodeProjFile = cmStrCat(xcodeDir, "/project.pbxproj");
  4682. cmGeneratedFileStream fout(xcodeProjFile);
  4683. fout.SetCopyIfDifferent(true);
  4684. if (!fout) {
  4685. return;
  4686. }
  4687. this->WriteXCodePBXProj(fout, root, generators);
  4688. bool hasGeneratedSchemes = this->OutputXCodeSharedSchemes(xcodeDir, root);
  4689. this->OutputXCodeWorkspaceSettings(xcodeDir, hasGeneratedSchemes);
  4690. this->ClearXCodeObjects();
  4691. // Since this call may have created new cache entries, save the cache:
  4692. //
  4693. root->GetMakefile()->GetCMakeInstance()->SaveCache(
  4694. root->GetBinaryDirectory());
  4695. }
  4696. bool cmGlobalXCodeGenerator::OutputXCodeSharedSchemes(
  4697. std::string const& xcProjDir, cmLocalGenerator* root)
  4698. {
  4699. // collect all tests for the targets
  4700. std::map<std::string, cmXCodeScheme::TestObjects> testables;
  4701. for (auto const& obj : this->XCodeObjects) {
  4702. if (obj->GetType() != cmXCodeObject::OBJECT ||
  4703. obj->GetIsA() != cmXCodeObject::PBXNativeTarget) {
  4704. continue;
  4705. }
  4706. if (!obj->GetTarget()->IsXCTestOnApple()) {
  4707. continue;
  4708. }
  4709. cmValue testee = obj->GetTarget()->GetProperty("XCTEST_TESTEE");
  4710. if (!testee) {
  4711. continue;
  4712. }
  4713. testables[*testee].push_back(obj.get());
  4714. }
  4715. // generate scheme
  4716. bool ret = false;
  4717. // Since the lowest available Xcode version for testing was 6.4,
  4718. // I'm setting this as a limit then
  4719. if (this->XcodeVersion >= 64) {
  4720. for (auto const& obj : this->XCodeObjects) {
  4721. if (obj->GetType() == cmXCodeObject::OBJECT &&
  4722. (obj->GetIsA() == cmXCodeObject::PBXNativeTarget ||
  4723. obj->GetIsA() == cmXCodeObject::PBXAggregateTarget) &&
  4724. (root->GetMakefile()->GetCMakeInstance()->GetIsInTryCompile() ||
  4725. obj->GetTarget()->GetPropertyAsBool("XCODE_GENERATE_SCHEME"))) {
  4726. std::string const& targetName = obj->GetTarget()->GetName();
  4727. cmXCodeScheme schm(root, obj.get(), testables[targetName],
  4728. this->CurrentConfigurationTypes,
  4729. this->XcodeVersion);
  4730. schm.WriteXCodeSharedScheme(xcProjDir,
  4731. this->RelativeToSource(xcProjDir));
  4732. ret = true;
  4733. }
  4734. }
  4735. }
  4736. return ret;
  4737. }
  4738. void cmGlobalXCodeGenerator::OutputXCodeWorkspaceSettings(
  4739. std::string const& xcProjDir, bool hasGeneratedSchemes)
  4740. {
  4741. std::string xcodeSharedDataDir =
  4742. cmStrCat(xcProjDir, "/project.xcworkspace/xcshareddata");
  4743. cmSystemTools::MakeDirectory(xcodeSharedDataDir);
  4744. std::string workspaceSettingsFile =
  4745. cmStrCat(xcodeSharedDataDir, "/WorkspaceSettings.xcsettings");
  4746. cmGeneratedFileStream fout(workspaceSettingsFile);
  4747. fout.SetCopyIfDifferent(true);
  4748. if (!fout) {
  4749. return;
  4750. }
  4751. cmXMLWriter xout(fout);
  4752. xout.StartDocument();
  4753. xout.Doctype("plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\""
  4754. "\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"");
  4755. xout.StartElement("plist");
  4756. xout.Attribute("version", "1.0");
  4757. xout.StartElement("dict");
  4758. if (this->XcodeVersion >= 100) {
  4759. xout.Element("key", "BuildSystemType");
  4760. switch (this->XcodeBuildSystem) {
  4761. case BuildSystem::One:
  4762. xout.Element("string", "Original");
  4763. if (this->XcodeVersion >= 130) {
  4764. xout.Element("key", "DisableBuildSystemDeprecationDiagnostic");
  4765. } else {
  4766. xout.Element("key", "DisableBuildSystemDeprecationWarning");
  4767. }
  4768. xout.Element("true");
  4769. break;
  4770. case BuildSystem::Twelve:
  4771. xout.Element("string", "Latest");
  4772. break;
  4773. }
  4774. }
  4775. if (hasGeneratedSchemes) {
  4776. xout.Element("key",
  4777. "IDEWorkspaceSharedSettings_AutocreateContextsIfNeeded");
  4778. xout.Element("false");
  4779. }
  4780. xout.EndElement(); // dict
  4781. xout.EndElement(); // plist
  4782. xout.EndDocument();
  4783. }
  4784. void cmGlobalXCodeGenerator::WriteXCodePBXProj(std::ostream& fout,
  4785. cmLocalGenerator*,
  4786. std::vector<cmLocalGenerator*>&)
  4787. {
  4788. SortXCodeObjects();
  4789. fout << "// !$*UTF8*$!\n"
  4790. "{\n";
  4791. cmXCodeObject::Indent(1, fout);
  4792. fout << "archiveVersion = 1;\n";
  4793. cmXCodeObject::Indent(1, fout);
  4794. fout << "classes = {\n";
  4795. cmXCodeObject::Indent(1, fout);
  4796. fout << "};\n";
  4797. cmXCodeObject::Indent(1, fout);
  4798. fout << "objectVersion = 46;\n";
  4799. cmXCode21Object::PrintList(this->XCodeObjects, fout);
  4800. cmXCodeObject::Indent(1, fout);
  4801. fout << "rootObject = " << this->RootObject->GetId()
  4802. << " /* Project object */;\n"
  4803. "}\n";
  4804. }
  4805. char const* cmGlobalXCodeGenerator::GetCMakeCFGIntDir() const
  4806. {
  4807. return "$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)";
  4808. }
  4809. std::string cmGlobalXCodeGenerator::ExpandCFGIntDir(
  4810. std::string const& str, std::string const& config) const
  4811. {
  4812. std::string replace1 = "$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)";
  4813. std::string replace2 = "$(CONFIGURATION)";
  4814. std::string tmp = str;
  4815. for (std::string::size_type i = tmp.find(replace1); i != std::string::npos;
  4816. i = tmp.find(replace1, i)) {
  4817. tmp.replace(i, replace1.size(), config);
  4818. i += config.size();
  4819. }
  4820. for (std::string::size_type i = tmp.find(replace2); i != std::string::npos;
  4821. i = tmp.find(replace2, i)) {
  4822. tmp.replace(i, replace2.size(), config);
  4823. i += config.size();
  4824. }
  4825. return tmp;
  4826. }
  4827. cmDocumentationEntry cmGlobalXCodeGenerator::GetDocumentation()
  4828. {
  4829. return { cmGlobalXCodeGenerator::GetActualName(),
  4830. "Generate Xcode project files." };
  4831. }
  4832. std::string cmGlobalXCodeGenerator::RelativeToSource(std::string const& p)
  4833. {
  4834. std::string const& rootSrc =
  4835. this->CurrentRootGenerator->GetCurrentSourceDirectory();
  4836. if (cmSystemTools::IsSubDirectory(p, rootSrc)) {
  4837. return cmSystemTools::ForceToRelativePath(rootSrc, p);
  4838. }
  4839. return p;
  4840. }
  4841. std::string cmGlobalXCodeGenerator::RelativeToRootBinary(std::string const& p)
  4842. {
  4843. std::string binaryDirectory =
  4844. this->CurrentRootGenerator->GetCurrentBinaryDirectory();
  4845. if (cmSystemTools::IsSubDirectory(p, binaryDirectory)) {
  4846. binaryDirectory = cmSystemTools::ForceToRelativePath(binaryDirectory, p);
  4847. }
  4848. return binaryDirectory;
  4849. }
  4850. std::string cmGlobalXCodeGenerator::RelativeToBinary(std::string const& p)
  4851. {
  4852. return this->CurrentRootGenerator->MaybeRelativeToCurBinDir(p);
  4853. }
  4854. std::string cmGlobalXCodeGenerator::XCodeEscapePath(std::string const& p)
  4855. {
  4856. if (p.find_first_of(" []") != std::string::npos) {
  4857. std::string t = cmStrCat('"', p, '"');
  4858. return t;
  4859. }
  4860. return p;
  4861. }
  4862. void cmGlobalXCodeGenerator::AppendDirectoryForConfig(
  4863. std::string const& prefix, std::string const& config,
  4864. std::string const& suffix, std::string& dir)
  4865. {
  4866. if (!config.empty()) {
  4867. dir += prefix;
  4868. dir += config;
  4869. dir += suffix;
  4870. }
  4871. }
  4872. std::string cmGlobalXCodeGenerator::LookupFlags(
  4873. std::string const& varNamePrefix, std::string const& varNameLang,
  4874. std::string const& varNameSuffix, cmGeneratorTarget const* gt)
  4875. {
  4876. std::string flags;
  4877. if (!varNameLang.empty()) {
  4878. std::string varName = cmStrCat(varNamePrefix, varNameLang, varNameSuffix);
  4879. if (cmValue varValue = this->CurrentMakefile->GetDefinition(varName)) {
  4880. if (!varValue->empty()) {
  4881. this->CurrentLocalGenerator->AppendFlags(
  4882. flags, *varValue, varName, gt, cmBuildStep::Link, varNameLang);
  4883. }
  4884. }
  4885. }
  4886. return flags;
  4887. }
  4888. void cmGlobalXCodeGenerator::AppendDefines(BuildObjectListOrString& defs,
  4889. char const* defines_list,
  4890. bool dflag)
  4891. {
  4892. // Skip this if there are no definitions.
  4893. if (!defines_list) {
  4894. return;
  4895. }
  4896. // Expand the list of definitions.
  4897. cmList defines{ defines_list };
  4898. // Store the definitions in the string.
  4899. this->AppendDefines(defs, defines, dflag);
  4900. }
  4901. void cmGlobalXCodeGenerator::AppendDefines(
  4902. BuildObjectListOrString& defs, std::vector<std::string> const& defines,
  4903. bool dflag)
  4904. {
  4905. // GCC_PREPROCESSOR_DEFINITIONS is a space-separated list of definitions.
  4906. std::string def;
  4907. for (auto const& define : defines) {
  4908. // Start with -D if requested.
  4909. if (dflag && !cmHasLiteralPrefix(define, "-D")) {
  4910. def = cmStrCat("-D", define);
  4911. } else if (!dflag && cmHasLiteralPrefix(define, "-D")) {
  4912. def = define.substr(2);
  4913. } else {
  4914. def = define;
  4915. }
  4916. // Append the flag with needed escapes.
  4917. std::string tmp;
  4918. this->AppendFlag(tmp, def);
  4919. defs.Add(tmp);
  4920. }
  4921. }
  4922. void cmGlobalXCodeGenerator::AppendFlag(std::string& flags,
  4923. std::string const& flag) const
  4924. {
  4925. // Short-circuit for an empty flag.
  4926. if (flag.empty()) {
  4927. return;
  4928. }
  4929. // Separate from previous flags.
  4930. if (!flags.empty()) {
  4931. flags += ' ';
  4932. }
  4933. // Check if the flag needs quoting.
  4934. bool quoteFlag =
  4935. flag.find_first_of("`~!@#$%^&*()+={}[]|:;\"'<>,.? ") != std::string::npos;
  4936. // We escape a flag as follows:
  4937. // - Place each flag in single quotes ''
  4938. // - Escape a single quote as \'
  4939. // - Escape a backslash as \\ since it itself is an escape
  4940. // Note that in the code below we need one more level of escapes for
  4941. // C string syntax in this source file.
  4942. //
  4943. // The final level of escaping is done when the string is stored
  4944. // into the project file by cmXCodeObject::PrintString.
  4945. if (quoteFlag) {
  4946. // Open single quote.
  4947. flags += '\'';
  4948. }
  4949. // Flag value with escaped quotes and backslashes.
  4950. for (auto c : flag) {
  4951. if (c == '\'') {
  4952. flags += "'\\''";
  4953. } else if (c == '\\') {
  4954. flags += "\\\\";
  4955. } else {
  4956. flags += c;
  4957. }
  4958. }
  4959. if (quoteFlag) {
  4960. // Close single quote.
  4961. flags += '\'';
  4962. }
  4963. }
  4964. std::string cmGlobalXCodeGenerator::ComputeInfoPListLocation(
  4965. cmGeneratorTarget* target)
  4966. {
  4967. std::string plist = cmStrCat(target->GetSupportDirectory(), "/Info.plist");
  4968. return plist;
  4969. }
  4970. // Return true if the generated build tree may contain multiple builds.
  4971. // i.e. "Can I build Debug and Release in the same tree?"
  4972. bool cmGlobalXCodeGenerator::IsMultiConfig() const
  4973. {
  4974. // Newer Xcode versions are multi config:
  4975. return true;
  4976. }
  4977. bool cmGlobalXCodeGenerator::HasKnownObjectFileLocation(
  4978. cmTarget const& target, std::string* reason) const
  4979. {
  4980. auto objectDirArch = GetTargetObjectDirArch(target, this->ObjectDirArch);
  4981. if (objectDirArch.find('$') != std::string::npos) {
  4982. if (reason != nullptr) {
  4983. *reason = " under Xcode with multiple architectures";
  4984. }
  4985. return false;
  4986. }
  4987. return true;
  4988. }
  4989. bool cmGlobalXCodeGenerator::UseEffectivePlatformName(cmMakefile* mf) const
  4990. {
  4991. cmValue epnValue = this->GetCMakeInstance()->GetState()->GetGlobalProperty(
  4992. "XCODE_EMIT_EFFECTIVE_PLATFORM_NAME");
  4993. if (!epnValue) {
  4994. return mf->PlatformIsAppleEmbedded();
  4995. }
  4996. return epnValue.IsOn();
  4997. }
  4998. bool cmGlobalXCodeGenerator::ShouldStripResourcePath(cmMakefile*) const
  4999. {
  5000. // Xcode determines Resource location itself
  5001. return true;
  5002. }
  5003. void cmGlobalXCodeGenerator::ComputeTargetObjectDirectory(
  5004. cmGeneratorTarget* gt) const
  5005. {
  5006. auto objectDirArch = GetTargetObjectDirArch(*gt, this->ObjectDirArch);
  5007. gt->ObjectDirectory =
  5008. cmStrCat(this->GetTargetTempDir(gt, this->GetCMakeCFGIntDir()),
  5009. "/$(OBJECT_FILE_DIR_normal:base)/", objectDirArch, '/');
  5010. }
  5011. std::string cmGlobalXCodeGenerator::GetDeploymentPlatform(cmMakefile const* mf)
  5012. {
  5013. switch (mf->GetAppleSDKType()) {
  5014. case cmMakefile::AppleSDK::AppleTVOS:
  5015. case cmMakefile::AppleSDK::AppleTVSimulator:
  5016. return "TVOS_DEPLOYMENT_TARGET";
  5017. case cmMakefile::AppleSDK::IPhoneOS:
  5018. case cmMakefile::AppleSDK::IPhoneSimulator:
  5019. return "IPHONEOS_DEPLOYMENT_TARGET";
  5020. case cmMakefile::AppleSDK::WatchOS:
  5021. case cmMakefile::AppleSDK::WatchSimulator:
  5022. return "WATCHOS_DEPLOYMENT_TARGET";
  5023. case cmMakefile::AppleSDK::XROS:
  5024. case cmMakefile::AppleSDK::XRSimulator:
  5025. return "XROS_DEPLOYMENT_TARGET";
  5026. case cmMakefile::AppleSDK::MacOS:
  5027. default:
  5028. return "MACOSX_DEPLOYMENT_TARGET";
  5029. }
  5030. }
  5031. cmValue cmGlobalXCodeGenerator::GetDebuggerWorkingDirectory(
  5032. cmGeneratorTarget* gt) const
  5033. {
  5034. if (cmValue ret = gt->GetProperty("XCODE_SCHEME_WORKING_DIRECTORY")) {
  5035. return ret;
  5036. }
  5037. return cmGlobalGenerator::GetDebuggerWorkingDirectory(gt);
  5038. }