cmGlobalXCodeGenerator.cxx 191 KB

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