cmGlobalXCodeGenerator.cxx 193 KB

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