cmGlobalXCodeGenerator.cxx 194 KB

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