cmGlobalXCodeGenerator.cxx 194 KB

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