cmGlobalXCodeGenerator.cxx 192 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340
  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. gtgt->AddSource(fname);
  1526. }
  1527. }
  1528. bool cmGlobalXCodeGenerator::IsHeaderFile(cmSourceFile* sf)
  1529. {
  1530. return cm::contains(this->CMakeInstance->GetHeaderExtensions(),
  1531. sf->GetExtension());
  1532. }
  1533. cmXCodeObject* cmGlobalXCodeGenerator::CreateLegacyRunScriptBuildPhase(
  1534. const char* name, const char* name2, cmGeneratorTarget* target,
  1535. const std::vector<cmCustomCommand>& commands)
  1536. {
  1537. if (commands.empty() && strcmp(name, "CMake ReRun") != 0) {
  1538. return nullptr;
  1539. }
  1540. cmXCodeObject* buildPhase =
  1541. this->CreateObject(cmXCodeObject::PBXShellScriptBuildPhase);
  1542. buildPhase->AddAttribute("buildActionMask",
  1543. this->CreateString("2147483647"));
  1544. cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1545. buildPhase->AddAttribute("files", buildFiles);
  1546. buildPhase->AddAttribute("name", this->CreateString(name));
  1547. buildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1548. this->CreateString("0"));
  1549. buildPhase->AddAttribute("shellPath", this->CreateString("/bin/sh"));
  1550. this->AddCommandsToBuildPhase(buildPhase, target, commands, name2);
  1551. return buildPhase;
  1552. }
  1553. void cmGlobalXCodeGenerator::CreateCustomCommands(
  1554. cmXCodeObject* buildPhases, cmXCodeObject* sourceBuildPhase,
  1555. cmXCodeObject* headerBuildPhase, cmXCodeObject* resourceBuildPhase,
  1556. std::vector<cmXCodeObject*> const& contentBuildPhases,
  1557. cmXCodeObject* frameworkBuildPhase, cmGeneratorTarget* gtgt)
  1558. {
  1559. std::vector<cmCustomCommand> const& prebuild = gtgt->GetPreBuildCommands();
  1560. std::vector<cmCustomCommand> const& prelink = gtgt->GetPreLinkCommands();
  1561. std::vector<cmCustomCommand> postbuild = gtgt->GetPostBuildCommands();
  1562. if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY &&
  1563. !gtgt->IsFrameworkOnApple()) {
  1564. std::string str_file = cmStrCat("$<TARGET_FILE:", gtgt->GetName(), '>');
  1565. std::string str_so_file =
  1566. cmStrCat("$<TARGET_SONAME_FILE:", gtgt->GetName(), '>');
  1567. std::string str_link_file =
  1568. cmStrCat("$<TARGET_LINKER_LIBRARY_FILE:", gtgt->GetName(), '>');
  1569. cmCustomCommandLines cmd = cmMakeSingleCommandLine(
  1570. { cmSystemTools::GetCMakeCommand(), "-E", "cmake_symlink_library",
  1571. str_file, str_so_file, str_link_file });
  1572. cmCustomCommand command;
  1573. command.SetCommandLines(cmd);
  1574. command.SetComment("Creating symlinks");
  1575. command.SetWorkingDirectory("");
  1576. command.SetBacktrace(this->CurrentMakefile->GetBacktrace());
  1577. command.SetStdPipesUTF8(true);
  1578. postbuild.push_back(std::move(command));
  1579. }
  1580. if (gtgt->HasImportLibrary("") && !gtgt->IsFrameworkOnApple()) {
  1581. // create symbolic links for .tbd file
  1582. std::string file = cmStrCat("$<TARGET_IMPORT_FILE:", gtgt->GetName(), '>');
  1583. std::string soFile =
  1584. cmStrCat("$<TARGET_SONAME_IMPORT_FILE:", gtgt->GetName(), '>');
  1585. std::string linkFile =
  1586. cmStrCat("$<TARGET_LINKER_IMPORT_FILE:", gtgt->GetName(), '>');
  1587. cmCustomCommandLines symlink_command = cmMakeSingleCommandLine(
  1588. { cmSystemTools::GetCMakeCommand(), "-E", "cmake_symlink_library", file,
  1589. soFile, linkFile });
  1590. cmCustomCommand command;
  1591. command.SetCommandLines(symlink_command);
  1592. command.SetComment("Creating import symlinks");
  1593. command.SetWorkingDirectory("");
  1594. command.SetBacktrace(this->CurrentMakefile->GetBacktrace());
  1595. command.SetStdPipesUTF8(true);
  1596. postbuild.push_back(std::move(command));
  1597. }
  1598. cmXCodeObject* legacyCustomCommandsBuildPhase = nullptr;
  1599. cmXCodeObject* preBuildPhase = nullptr;
  1600. cmXCodeObject* preLinkPhase = nullptr;
  1601. cmXCodeObject* postBuildPhase = nullptr;
  1602. if (this->XcodeBuildSystem >= BuildSystem::Twelve) {
  1603. // create prebuild phase
  1604. preBuildPhase =
  1605. this->CreateRunScriptBuildPhase("CMake PreBuild Rules", gtgt, prebuild);
  1606. // create prelink phase
  1607. preLinkPhase =
  1608. this->CreateRunScriptBuildPhase("CMake PreLink Rules", gtgt, prelink);
  1609. // create postbuild phase
  1610. postBuildPhase = this->CreateRunScriptBuildPhase("CMake PostBuild Rules",
  1611. gtgt, postbuild);
  1612. } else {
  1613. std::vector<cmSourceFile*> classes;
  1614. if (!gtgt->GetConfigCommonSourceFilesForXcode(classes)) {
  1615. return;
  1616. }
  1617. // add all the sources
  1618. std::vector<cmCustomCommand> commands;
  1619. auto& visited = this->CommandsVisited[gtgt];
  1620. for (auto* sourceFile : classes) {
  1621. if (sourceFile->GetCustomCommand() &&
  1622. visited.insert(sourceFile).second) {
  1623. commands.push_back(*sourceFile->GetCustomCommand());
  1624. }
  1625. }
  1626. // create custom commands phase
  1627. legacyCustomCommandsBuildPhase = this->CreateLegacyRunScriptBuildPhase(
  1628. "CMake Rules", "cmakeRulesBuildPhase", gtgt, commands);
  1629. // create prebuild phase
  1630. preBuildPhase = this->CreateLegacyRunScriptBuildPhase(
  1631. "CMake PreBuild Rules", "preBuildCommands", gtgt, prebuild);
  1632. // create prelink phase
  1633. preLinkPhase = this->CreateLegacyRunScriptBuildPhase(
  1634. "CMake PreLink Rules", "preLinkCommands", gtgt, prelink);
  1635. // create postbuild phase
  1636. postBuildPhase = this->CreateLegacyRunScriptBuildPhase(
  1637. "CMake PostBuild Rules", "postBuildPhase", gtgt, postbuild);
  1638. }
  1639. // The order here is the order they will be built in.
  1640. // The order "headers, resources, sources" mimics a native project generated
  1641. // from an xcode template...
  1642. //
  1643. if (preBuildPhase) {
  1644. buildPhases->AddObject(preBuildPhase);
  1645. }
  1646. if (legacyCustomCommandsBuildPhase) {
  1647. buildPhases->AddObject(legacyCustomCommandsBuildPhase);
  1648. }
  1649. if (this->XcodeBuildSystem >= BuildSystem::Twelve) {
  1650. this->CreateRunScriptBuildPhases(buildPhases, gtgt);
  1651. }
  1652. if (headerBuildPhase) {
  1653. buildPhases->AddObject(headerBuildPhase);
  1654. }
  1655. if (resourceBuildPhase) {
  1656. buildPhases->AddObject(resourceBuildPhase);
  1657. }
  1658. for (auto* obj : contentBuildPhases) {
  1659. buildPhases->AddObject(obj);
  1660. }
  1661. if (sourceBuildPhase) {
  1662. buildPhases->AddObject(sourceBuildPhase);
  1663. }
  1664. if (preLinkPhase) {
  1665. buildPhases->AddObject(preLinkPhase);
  1666. }
  1667. if (frameworkBuildPhase) {
  1668. buildPhases->AddObject(frameworkBuildPhase);
  1669. }
  1670. // When this build phase is present, it must be last. More build phases may
  1671. // be added later for embedding things and they will insert themselves just
  1672. // before this last build phase.
  1673. if (postBuildPhase) {
  1674. buildPhases->AddObject(postBuildPhase);
  1675. }
  1676. }
  1677. void cmGlobalXCodeGenerator::CreateRunScriptBuildPhases(
  1678. cmXCodeObject* buildPhases, cmGeneratorTarget const* gt)
  1679. {
  1680. std::vector<cmSourceFile*> sources;
  1681. if (!gt->GetConfigCommonSourceFilesForXcode(sources)) {
  1682. return;
  1683. }
  1684. auto& visited = this->CommandsVisited[gt];
  1685. for (auto* sf : sources) {
  1686. this->CreateRunScriptBuildPhases(buildPhases, sf, gt, visited);
  1687. }
  1688. }
  1689. void cmGlobalXCodeGenerator::CreateRunScriptBuildPhases(
  1690. cmXCodeObject* buildPhases, cmSourceFile const* sf,
  1691. cmGeneratorTarget const* gt, std::set<cmSourceFile const*>& visited)
  1692. {
  1693. cmCustomCommand const* cc = sf->GetCustomCommand();
  1694. if (cc && visited.insert(sf).second) {
  1695. this->CustomCommandRoots[sf].insert(gt);
  1696. if (std::vector<cmSourceFile*> const* depends = gt->GetSourceDepends(sf)) {
  1697. for (cmSourceFile const* di : *depends) {
  1698. this->CreateRunScriptBuildPhases(buildPhases, di, gt, visited);
  1699. }
  1700. }
  1701. cmXCodeObject* buildPhase = this->CreateRunScriptBuildPhase(sf, gt, *cc);
  1702. buildPhases->AddObject(buildPhase);
  1703. }
  1704. }
  1705. cmXCodeObject* cmGlobalXCodeGenerator::CreateRunScriptBuildPhase(
  1706. cmSourceFile const* sf, cmGeneratorTarget const* gt,
  1707. cmCustomCommand const& cc)
  1708. {
  1709. std::set<std::string> allConfigInputs;
  1710. std::set<std::string> allConfigOutputs;
  1711. cmXCodeObject* buildPhase =
  1712. this->CreateObject(cmXCodeObject::PBXShellScriptBuildPhase,
  1713. cmStrCat(gt->GetName(), ':', sf->GetFullPath()));
  1714. auto depfilesDirectory = cmStrCat(
  1715. gt->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/CMakeFiles/d/");
  1716. auto depfilesPrefix = cmStrCat(depfilesDirectory, buildPhase->GetId(), '.');
  1717. std::string shellScript = "set -e\n";
  1718. for (std::string const& configName : this->CurrentConfigurationTypes) {
  1719. cmCustomCommandGenerator ccg(
  1720. cc, configName, this->CurrentLocalGenerator, true, {},
  1721. [&depfilesPrefix](const std::string& config, const std::string&)
  1722. -> std::string { return cmStrCat(depfilesPrefix, config, ".d"); });
  1723. std::vector<std::string> realDepends;
  1724. realDepends.reserve(ccg.GetDepends().size());
  1725. for (auto const& d : ccg.GetDepends()) {
  1726. std::string dep;
  1727. if (this->CurrentLocalGenerator->GetRealDependency(d, configName, dep)) {
  1728. realDepends.emplace_back(std::move(dep));
  1729. }
  1730. }
  1731. allConfigInputs.insert(realDepends.begin(), realDepends.end());
  1732. allConfigOutputs.insert(ccg.GetByproducts().begin(),
  1733. ccg.GetByproducts().end());
  1734. allConfigOutputs.insert(ccg.GetOutputs().begin(), ccg.GetOutputs().end());
  1735. shellScript =
  1736. cmStrCat(shellScript, R"(if test "$CONFIGURATION" = ")", configName,
  1737. "\"; then :\n", this->ConstructScript(ccg), "fi\n");
  1738. }
  1739. if (!cc.GetDepfile().empty()) {
  1740. buildPhase->AddAttribute(
  1741. "dependencyFile",
  1742. this->CreateString(cmStrCat(depfilesDirectory, buildPhase->GetId(),
  1743. ".$(CONFIGURATION).d")));
  1744. // to avoid spurious errors during first build, create empty dependency
  1745. // files
  1746. cmSystemTools::MakeDirectory(depfilesDirectory);
  1747. for (std::string const& configName : this->CurrentConfigurationTypes) {
  1748. auto file = cmStrCat(depfilesPrefix, configName, ".d");
  1749. if (!cmSystemTools::FileExists(file)) {
  1750. cmSystemTools::Touch(file, true);
  1751. }
  1752. }
  1753. }
  1754. buildPhase->AddAttribute("buildActionMask",
  1755. this->CreateString("2147483647"));
  1756. cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1757. buildPhase->AddAttribute("files", buildFiles);
  1758. {
  1759. std::string name;
  1760. if (!allConfigOutputs.empty()) {
  1761. name = cmStrCat("Generate ",
  1762. this->RelativeToBinary(*allConfigOutputs.begin()));
  1763. } else {
  1764. name = sf->GetLocation().GetName();
  1765. }
  1766. buildPhase->AddAttribute("name", this->CreateString(name));
  1767. }
  1768. buildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1769. this->CreateString("0"));
  1770. buildPhase->AddAttribute("shellPath", this->CreateString("/bin/sh"));
  1771. buildPhase->AddAttribute("shellScript", this->CreateString(shellScript));
  1772. buildPhase->AddAttribute("showEnvVarsInLog", this->CreateString("0"));
  1773. bool symbolic = false;
  1774. {
  1775. cmXCodeObject* inputPaths = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1776. for (std::string const& i : allConfigInputs) {
  1777. inputPaths->AddUniqueObject(this->CreateString(i));
  1778. if (!symbolic) {
  1779. if (cmSourceFile* isf =
  1780. gt->GetLocalGenerator()->GetMakefile()->GetSource(
  1781. i, cmSourceFileLocationKind::Known)) {
  1782. symbolic = isf->GetPropertyAsBool("SYMBOLIC");
  1783. }
  1784. }
  1785. }
  1786. buildPhase->AddAttribute("inputPaths", inputPaths);
  1787. }
  1788. {
  1789. cmXCodeObject* outputPaths =
  1790. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1791. for (std::string const& o : allConfigOutputs) {
  1792. outputPaths->AddUniqueObject(this->CreateString(o));
  1793. if (!symbolic) {
  1794. if (cmSourceFile* osf =
  1795. gt->GetLocalGenerator()->GetMakefile()->GetSource(
  1796. o, cmSourceFileLocationKind::Known)) {
  1797. symbolic = osf->GetPropertyAsBool("SYMBOLIC");
  1798. }
  1799. }
  1800. }
  1801. buildPhase->AddAttribute("outputPaths", outputPaths);
  1802. }
  1803. if (symbolic) {
  1804. buildPhase->AddAttribute("alwaysOutOfDate", this->CreateString("1"));
  1805. }
  1806. return buildPhase;
  1807. }
  1808. cmXCodeObject* cmGlobalXCodeGenerator::CreateRunScriptBuildPhase(
  1809. std::string const& name, cmGeneratorTarget const* gt,
  1810. std::vector<cmCustomCommand> const& commands)
  1811. {
  1812. if (commands.empty()) {
  1813. return nullptr;
  1814. }
  1815. std::set<std::string> allConfigOutputs;
  1816. std::string shellScript = "set -e\n";
  1817. for (std::string const& configName : this->CurrentConfigurationTypes) {
  1818. shellScript = cmStrCat(shellScript, R"(if test "$CONFIGURATION" = ")",
  1819. configName, "\"; then :\n");
  1820. for (cmCustomCommand const& cc : commands) {
  1821. cmCustomCommandGenerator ccg(cc, configName,
  1822. this->CurrentLocalGenerator);
  1823. shellScript = cmStrCat(shellScript, this->ConstructScript(ccg));
  1824. allConfigOutputs.insert(ccg.GetByproducts().begin(),
  1825. ccg.GetByproducts().end());
  1826. }
  1827. shellScript = cmStrCat(shellScript, "fi\n");
  1828. }
  1829. cmXCodeObject* buildPhase =
  1830. this->CreateObject(cmXCodeObject::PBXShellScriptBuildPhase,
  1831. cmStrCat(gt->GetName(), ':', name));
  1832. buildPhase->AddAttribute("buildActionMask",
  1833. this->CreateString("2147483647"));
  1834. cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1835. buildPhase->AddAttribute("files", buildFiles);
  1836. buildPhase->AddAttribute("name", this->CreateString(name));
  1837. buildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1838. this->CreateString("0"));
  1839. buildPhase->AddAttribute("shellPath", this->CreateString("/bin/sh"));
  1840. buildPhase->AddAttribute("shellScript", this->CreateString(shellScript));
  1841. buildPhase->AddAttribute("showEnvVarsInLog", this->CreateString("0"));
  1842. {
  1843. cmXCodeObject* outputPaths =
  1844. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1845. for (std::string const& o : allConfigOutputs) {
  1846. outputPaths->AddUniqueObject(this->CreateString(o));
  1847. }
  1848. buildPhase->AddAttribute("outputPaths", outputPaths);
  1849. }
  1850. buildPhase->AddAttribute("alwaysOutOfDate", this->CreateString("1"));
  1851. return buildPhase;
  1852. }
  1853. namespace {
  1854. void ReplaceScriptVars(std::string& cmd)
  1855. {
  1856. cmSystemTools::ReplaceString(cmd, "$(CONFIGURATION)", "$CONFIGURATION");
  1857. cmSystemTools::ReplaceString(cmd, "$(EFFECTIVE_PLATFORM_NAME)",
  1858. "$EFFECTIVE_PLATFORM_NAME");
  1859. }
  1860. }
  1861. std::string cmGlobalXCodeGenerator::ConstructScript(
  1862. cmCustomCommandGenerator const& ccg)
  1863. {
  1864. std::string script;
  1865. cmLocalGenerator* lg = this->CurrentLocalGenerator;
  1866. std::string wd = ccg.GetWorkingDirectory();
  1867. if (wd.empty()) {
  1868. wd = lg->GetCurrentBinaryDirectory();
  1869. }
  1870. wd = lg->ConvertToOutputFormat(wd, cmOutputConverter::SHELL);
  1871. ReplaceScriptVars(wd);
  1872. script = cmStrCat(script, " cd ", wd, '\n');
  1873. for (unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) {
  1874. std::string cmd = ccg.GetCommand(c);
  1875. if (cmd.empty()) {
  1876. continue;
  1877. }
  1878. cmSystemTools::ReplaceString(cmd, "/./", "/");
  1879. cmd = lg->ConvertToOutputFormat(cmd, cmOutputConverter::SHELL);
  1880. ccg.AppendArguments(c, cmd);
  1881. ReplaceScriptVars(cmd);
  1882. script = cmStrCat(script, " ", cmd, '\n');
  1883. }
  1884. return script;
  1885. }
  1886. // This function removes each occurrence of the flag and returns the last one
  1887. // (i.e., the dominant flag in GCC)
  1888. std::string cmGlobalXCodeGenerator::ExtractFlag(const char* flag,
  1889. std::string& flags)
  1890. {
  1891. std::string retFlag;
  1892. std::string::size_type lastOccurancePos = flags.rfind(flag);
  1893. bool saved = false;
  1894. while (lastOccurancePos != std::string::npos) {
  1895. // increment pos, we use lastOccurancePos to reduce search space on next
  1896. // inc
  1897. std::string::size_type pos = lastOccurancePos;
  1898. if (pos == 0 || flags[pos - 1] == ' ') {
  1899. while (pos < flags.size() && flags[pos] != ' ') {
  1900. if (!saved) {
  1901. retFlag += flags[pos];
  1902. }
  1903. flags[pos] = ' ';
  1904. pos++;
  1905. }
  1906. saved = true;
  1907. }
  1908. // decrement lastOccurancePos while making sure we don't loop around
  1909. // and become a very large positive number since size_type is unsigned
  1910. lastOccurancePos = lastOccurancePos == 0 ? 0 : lastOccurancePos - 1;
  1911. lastOccurancePos = flags.rfind(flag, lastOccurancePos);
  1912. }
  1913. return retFlag;
  1914. }
  1915. // This function removes each matching occurrence of the expression and
  1916. // returns the last one (i.e., the dominant flag in GCC)
  1917. std::string cmGlobalXCodeGenerator::ExtractFlagRegex(const char* exp,
  1918. int matchIndex,
  1919. std::string& flags)
  1920. {
  1921. std::string retFlag;
  1922. cmsys::RegularExpression regex(exp);
  1923. assert(regex.is_valid());
  1924. if (!regex.is_valid()) {
  1925. return retFlag;
  1926. }
  1927. std::string::size_type offset = 0;
  1928. while (regex.find(&flags[offset])) {
  1929. const std::string::size_type startPos = offset + regex.start(matchIndex);
  1930. const std::string::size_type endPos = offset + regex.end(matchIndex);
  1931. const std::string::size_type size = endPos - startPos;
  1932. offset = startPos + 1;
  1933. retFlag.assign(flags, startPos, size);
  1934. flags.replace(startPos, size, size, ' ');
  1935. }
  1936. return retFlag;
  1937. }
  1938. //----------------------------------------------------------------------------
  1939. // This function strips off Xcode attributes that do not target the current
  1940. // configuration
  1941. void cmGlobalXCodeGenerator::FilterConfigurationAttribute(
  1942. std::string const& configName, std::string& attribute)
  1943. {
  1944. // Handle [variant=<config>] condition explicitly here.
  1945. std::string::size_type beginVariant = attribute.find("[variant=");
  1946. if (beginVariant == std::string::npos) {
  1947. // There is no variant in this attribute.
  1948. return;
  1949. }
  1950. std::string::size_type endVariant = attribute.find(']', beginVariant + 9);
  1951. if (endVariant == std::string::npos) {
  1952. // There is no terminating bracket.
  1953. return;
  1954. }
  1955. // Compare the variant to the configuration.
  1956. std::string variant =
  1957. attribute.substr(beginVariant + 9, endVariant - beginVariant - 9);
  1958. if (variant == configName) {
  1959. // The variant matches the configuration so use this
  1960. // attribute but drop the [variant=<config>] condition.
  1961. attribute.erase(beginVariant, endVariant - beginVariant + 1);
  1962. } else {
  1963. // The variant does not match the configuration so
  1964. // do not use this attribute.
  1965. attribute.clear();
  1966. }
  1967. }
  1968. void cmGlobalXCodeGenerator::AddCommandsToBuildPhase(
  1969. cmXCodeObject* buildphase, cmGeneratorTarget* target,
  1970. std::vector<cmCustomCommand> const& commands, const char* name)
  1971. {
  1972. std::string dir = cmStrCat(
  1973. this->CurrentLocalGenerator->GetCurrentBinaryDirectory(), "/CMakeScripts");
  1974. cmSystemTools::MakeDirectory(dir);
  1975. std::string makefile =
  1976. cmStrCat(dir, '/', target->GetName(), '_', name, ".make");
  1977. for (const auto& currentConfig : this->CurrentConfigurationTypes) {
  1978. this->CreateCustomRulesMakefile(makefile.c_str(), target, commands,
  1979. currentConfig);
  1980. }
  1981. std::string cdir = this->CurrentLocalGenerator->GetCurrentBinaryDirectory();
  1982. cdir = this->ConvertToRelativeForMake(cdir);
  1983. std::string makecmd = cmStrCat(
  1984. "make -C ", cdir, " -f ",
  1985. this->ConvertToRelativeForMake(cmStrCat(makefile, "$CONFIGURATION")),
  1986. " OBJDIR=$(basename \"$OBJECT_FILE_DIR_normal\") all");
  1987. buildphase->AddAttribute("shellScript", this->CreateString(makecmd));
  1988. buildphase->AddAttribute("showEnvVarsInLog", this->CreateString("0"));
  1989. }
  1990. void cmGlobalXCodeGenerator::CreateCustomRulesMakefile(
  1991. const char* makefileBasename, cmGeneratorTarget* target,
  1992. std::vector<cmCustomCommand> const& commands, const std::string& configName)
  1993. {
  1994. std::string makefileName = cmStrCat(makefileBasename, configName);
  1995. cmGeneratedFileStream makefileStream(makefileName);
  1996. if (!makefileStream) {
  1997. return;
  1998. }
  1999. makefileStream.SetCopyIfDifferent(true);
  2000. makefileStream << "# Generated by CMake, DO NOT EDIT\n"
  2001. "# Custom rules for "
  2002. << target->GetName() << '\n';
  2003. // disable the implicit rules
  2004. makefileStream << ".SUFFIXES: "
  2005. "\n";
  2006. // have all depend on all outputs
  2007. makefileStream << "all: ";
  2008. std::map<const cmCustomCommand*, std::string> tname;
  2009. int count = 0;
  2010. for (auto const& command : commands) {
  2011. cmCustomCommandGenerator ccg(command, configName,
  2012. this->CurrentLocalGenerator);
  2013. if (ccg.GetNumberOfCommands() > 0) {
  2014. const std::vector<std::string>& outputs = ccg.GetOutputs();
  2015. if (!outputs.empty()) {
  2016. for (auto const& output : outputs) {
  2017. makefileStream << "\\\n\t" << this->ConvertToRelativeForMake(output);
  2018. }
  2019. } else {
  2020. std::ostringstream str;
  2021. str << "_buildpart_" << count++;
  2022. tname[&ccg.GetCC()] = cmStrCat(target->GetName(), str.str());
  2023. makefileStream << "\\\n\t" << tname[&ccg.GetCC()];
  2024. }
  2025. }
  2026. }
  2027. makefileStream << "\n\n";
  2028. auto depfilesDirectory =
  2029. cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(),
  2030. "/CMakeFiles/d/");
  2031. for (auto const& command : commands) {
  2032. cmCustomCommandGenerator ccg(
  2033. command, configName, this->CurrentLocalGenerator, true, {},
  2034. [this, &depfilesDirectory](const std::string& config,
  2035. const std::string& file) -> std::string {
  2036. return cmStrCat(
  2037. depfilesDirectory,
  2038. this->GetObjectId(cmXCodeObject::PBXShellScriptBuildPhase, file),
  2039. '.', config, ".d");
  2040. });
  2041. auto depfile = ccg.GetInternalDepfile();
  2042. if (!depfile.empty()) {
  2043. makefileStream << "include "
  2044. << cmSystemTools::ConvertToOutputPath(depfile) << "\n\n";
  2045. cmSystemTools::MakeDirectory(depfilesDirectory);
  2046. if (!cmSystemTools::FileExists(depfile)) {
  2047. cmSystemTools::Touch(depfile, true);
  2048. }
  2049. }
  2050. std::vector<std::string> realDepends;
  2051. realDepends.reserve(ccg.GetDepends().size());
  2052. for (auto const& d : ccg.GetDepends()) {
  2053. std::string dep;
  2054. if (this->CurrentLocalGenerator->GetRealDependency(d, configName, dep)) {
  2055. realDepends.emplace_back(std::move(dep));
  2056. }
  2057. }
  2058. if (ccg.GetNumberOfCommands() > 0) {
  2059. makefileStream << '\n';
  2060. const std::vector<std::string>& outputs = ccg.GetOutputs();
  2061. if (!outputs.empty()) {
  2062. // There is at least one output, start the rule for it
  2063. const char* sep = "";
  2064. for (auto const& output : outputs) {
  2065. makefileStream << sep << this->ConvertToRelativeForMake(output);
  2066. sep = " ";
  2067. }
  2068. makefileStream << ": ";
  2069. } else {
  2070. // There are no outputs. Use the generated force rule name.
  2071. makefileStream << tname[&ccg.GetCC()] << ": ";
  2072. }
  2073. for (auto const& dep : realDepends) {
  2074. makefileStream << "\\\n" << this->ConvertToRelativeForMake(dep);
  2075. }
  2076. makefileStream << '\n';
  2077. if (cm::optional<std::string> comment = ccg.GetComment()) {
  2078. std::string echo_cmd =
  2079. cmStrCat("echo ",
  2080. (this->CurrentLocalGenerator->EscapeForShell(
  2081. *comment, ccg.GetCC().GetEscapeAllowMakeVars())));
  2082. makefileStream << '\t' << echo_cmd << '\n';
  2083. }
  2084. // Add each command line to the set of commands.
  2085. for (unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) {
  2086. // Build the command line in a single string.
  2087. std::string cmd2 = ccg.GetCommand(c);
  2088. cmSystemTools::ReplaceString(cmd2, "/./", "/");
  2089. cmd2 = this->ConvertToRelativeForMake(cmd2);
  2090. std::string cmd;
  2091. std::string wd = ccg.GetWorkingDirectory();
  2092. if (!wd.empty()) {
  2093. cmd += "cd ";
  2094. cmd += this->ConvertToRelativeForMake(wd);
  2095. cmd += " && ";
  2096. }
  2097. cmd += cmd2;
  2098. ccg.AppendArguments(c, cmd);
  2099. makefileStream << '\t' << cmd << '\n';
  2100. }
  2101. // Symbolic inputs are not expected to exist, so add dummy rules.
  2102. for (auto const& dep : realDepends) {
  2103. if (cmSourceFile* dsf =
  2104. target->GetLocalGenerator()->GetMakefile()->GetSource(
  2105. dep, cmSourceFileLocationKind::Known)) {
  2106. if (dsf->GetPropertyAsBool("SYMBOLIC")) {
  2107. makefileStream << this->ConvertToRelativeForMake(dep) << ":\n";
  2108. }
  2109. }
  2110. }
  2111. }
  2112. }
  2113. }
  2114. void cmGlobalXCodeGenerator::AddPositionIndependentLinkAttribute(
  2115. cmGeneratorTarget* target, cmXCodeObject* buildSettings,
  2116. const std::string& configName)
  2117. {
  2118. // For now, only EXECUTABLE is concerned
  2119. if (target->GetType() != cmStateEnums::EXECUTABLE) {
  2120. return;
  2121. }
  2122. const char* PICValue = target->GetLinkPIEProperty(configName);
  2123. if (PICValue == nullptr) {
  2124. // POSITION_INDEPENDENT_CODE is not set
  2125. return;
  2126. }
  2127. buildSettings->AddAttribute(
  2128. "LD_NO_PIE", this->CreateString(cmIsOn(PICValue) ? "NO" : "YES"));
  2129. }
  2130. void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
  2131. cmXCodeObject* buildSettings,
  2132. const std::string& configName)
  2133. {
  2134. if (!gtgt->IsInBuildSystem()) {
  2135. return;
  2136. }
  2137. std::string defFlags;
  2138. bool shared = ((gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) ||
  2139. (gtgt->GetType() == cmStateEnums::MODULE_LIBRARY));
  2140. bool binary = ((gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY) ||
  2141. (gtgt->GetType() == cmStateEnums::STATIC_LIBRARY) ||
  2142. (gtgt->GetType() == cmStateEnums::EXECUTABLE) || shared);
  2143. // Compute the compilation flags for each language.
  2144. std::set<std::string> languages;
  2145. gtgt->GetLanguages(languages, configName);
  2146. std::map<std::string, std::string> cflags;
  2147. for (auto const& lang : languages) {
  2148. std::string& flags = cflags[lang];
  2149. // Add language-specific flags.
  2150. this->CurrentLocalGenerator->AddLanguageFlags(
  2151. flags, gtgt, cmBuildStep::Compile, lang, configName);
  2152. if (gtgt->IsIPOEnabled(lang, configName)) {
  2153. this->CurrentLocalGenerator->AppendFeatureOptions(flags, lang, "IPO");
  2154. }
  2155. // Add shared-library flags if needed.
  2156. this->CurrentLocalGenerator->AddCMP0018Flags(flags, gtgt, lang,
  2157. configName);
  2158. this->CurrentLocalGenerator->AddVisibilityPresetFlags(flags, gtgt, lang);
  2159. this->CurrentLocalGenerator->AddCompileOptions(flags, gtgt, lang,
  2160. configName);
  2161. }
  2162. std::string llang = gtgt->GetLinkerLanguage(configName);
  2163. if (binary && llang.empty()) {
  2164. cmSystemTools::Error(
  2165. cmStrCat("CMake can not determine linker language for target: ",
  2166. gtgt->GetName()));
  2167. return;
  2168. }
  2169. // Choose a language to use for target-wide preprocessor definitions.
  2170. static const char* ppLangs[] = { "CXX", "C", "OBJCXX", "OBJC" };
  2171. std::string langForPreprocessorDefinitions;
  2172. if (cm::contains(ppLangs, llang)) {
  2173. langForPreprocessorDefinitions = llang;
  2174. } else {
  2175. for (const char* l : ppLangs) {
  2176. if (languages.count(l)) {
  2177. langForPreprocessorDefinitions = l;
  2178. break;
  2179. }
  2180. }
  2181. }
  2182. if (gtgt->IsIPOEnabled(llang, configName)) {
  2183. const char* ltoValue =
  2184. this->CurrentMakefile->IsOn("_CMAKE_LTO_THIN") ? "YES_THIN" : "YES";
  2185. buildSettings->AddAttribute("LLVM_LTO", this->CreateString(ltoValue));
  2186. }
  2187. // Handle PIE linker configuration
  2188. this->AddPositionIndependentLinkAttribute(gtgt, buildSettings, configName);
  2189. // Add define flags
  2190. this->CurrentLocalGenerator->AppendFlags(
  2191. defFlags, this->CurrentMakefile->GetDefineFlags());
  2192. // Add preprocessor definitions for this target and configuration.
  2193. BuildObjectListOrString ppDefs(this, true);
  2194. this->AppendDefines(
  2195. ppDefs, "CMAKE_INTDIR=\"$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)\"");
  2196. if (const std::string* exportMacro = gtgt->GetExportMacro()) {
  2197. // Add the export symbol definition for shared library objects.
  2198. this->AppendDefines(ppDefs, exportMacro->c_str());
  2199. }
  2200. std::vector<std::string> targetDefines;
  2201. if (!langForPreprocessorDefinitions.empty()) {
  2202. gtgt->GetCompileDefinitions(targetDefines, configName,
  2203. langForPreprocessorDefinitions);
  2204. }
  2205. this->AppendDefines(ppDefs, targetDefines);
  2206. buildSettings->AddAttribute("GCC_PREPROCESSOR_DEFINITIONS",
  2207. ppDefs.CreateList());
  2208. if (languages.count("Swift")) {
  2209. // Swift uses a separate attribute for definitions.
  2210. std::vector<std::string> targetSwiftDefines;
  2211. gtgt->GetCompileDefinitions(targetSwiftDefines, configName, "Swift");
  2212. // Remove the '=value' parts, as Swift does not support them.
  2213. std::for_each(targetSwiftDefines.begin(), targetSwiftDefines.end(),
  2214. [](std::string& def) {
  2215. std::string::size_type pos = def.find('=');
  2216. if (pos != std::string::npos) {
  2217. def.erase(pos);
  2218. }
  2219. });
  2220. if (this->XcodeVersion < 80) {
  2221. std::string defineString;
  2222. std::set<std::string> defines(targetSwiftDefines.begin(),
  2223. targetSwiftDefines.end());
  2224. this->CurrentLocalGenerator->JoinDefines(defines, defineString, "Swift");
  2225. cflags["Swift"] += cmStrCat(' ', defineString);
  2226. } else {
  2227. BuildObjectListOrString swiftDefs(this, true);
  2228. this->AppendDefines(swiftDefs, targetSwiftDefines);
  2229. buildSettings->AddAttribute("SWIFT_ACTIVE_COMPILATION_CONDITIONS",
  2230. swiftDefs.CreateList());
  2231. }
  2232. if (cm::optional<cmSwiftCompileMode> swiftCompileMode =
  2233. this->CurrentLocalGenerator->GetSwiftCompileMode(gtgt, configName)) {
  2234. switch (*swiftCompileMode) {
  2235. case cmSwiftCompileMode::Wholemodule:
  2236. buildSettings->AddAttribute("SWIFT_COMPILATION_MODE",
  2237. this->CreateString("wholemodule"));
  2238. break;
  2239. case cmSwiftCompileMode::Incremental:
  2240. case cmSwiftCompileMode::Singlefile:
  2241. break;
  2242. case cmSwiftCompileMode::Unknown:
  2243. this->CurrentLocalGenerator->IssueMessage(
  2244. MessageType::AUTHOR_WARNING,
  2245. cmStrCat("Unknown Swift_COMPILATION_MODE on target '",
  2246. gtgt->GetName(), "'"));
  2247. break;
  2248. }
  2249. }
  2250. }
  2251. std::string extraLinkOptionsVar;
  2252. std::string extraLinkOptions;
  2253. if (gtgt->GetType() == cmStateEnums::EXECUTABLE) {
  2254. extraLinkOptionsVar = "CMAKE_EXE_LINKER_FLAGS";
  2255. } else if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) {
  2256. extraLinkOptionsVar = "CMAKE_SHARED_LINKER_FLAGS";
  2257. } else if (gtgt->GetType() == cmStateEnums::MODULE_LIBRARY) {
  2258. extraLinkOptionsVar = "CMAKE_MODULE_LINKER_FLAGS";
  2259. }
  2260. if (!extraLinkOptionsVar.empty()) {
  2261. this->CurrentLocalGenerator->AddConfigVariableFlags(
  2262. extraLinkOptions, extraLinkOptionsVar, configName);
  2263. }
  2264. if (gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  2265. gtgt->GetType() == cmStateEnums::STATIC_LIBRARY) {
  2266. this->CurrentLocalGenerator->GetStaticLibraryFlags(
  2267. extraLinkOptions, configName, llang, gtgt);
  2268. } else {
  2269. this->CurrentLocalGenerator->AppendLinkerTypeFlags(extraLinkOptions, gtgt,
  2270. configName, llang);
  2271. cmValue targetLinkFlags = gtgt->GetProperty("LINK_FLAGS");
  2272. if (targetLinkFlags) {
  2273. this->CurrentLocalGenerator->AppendFlags(extraLinkOptions,
  2274. *targetLinkFlags);
  2275. }
  2276. if (!configName.empty()) {
  2277. std::string linkFlagsVar =
  2278. cmStrCat("LINK_FLAGS_", cmSystemTools::UpperCase(configName));
  2279. if (cmValue linkFlags = gtgt->GetProperty(linkFlagsVar)) {
  2280. this->CurrentLocalGenerator->AppendFlags(extraLinkOptions, *linkFlags);
  2281. }
  2282. }
  2283. std::vector<std::string> opts;
  2284. gtgt->GetLinkOptions(opts, configName, llang);
  2285. // LINK_OPTIONS are escaped.
  2286. this->CurrentLocalGenerator->AppendCompileOptions(extraLinkOptions, opts);
  2287. }
  2288. // Set target-specific architectures.
  2289. std::vector<std::string> archs =
  2290. gtgt->GetAppleArchs(configName, cm::nullopt);
  2291. if (!archs.empty()) {
  2292. // Enable ARCHS attribute.
  2293. buildSettings->AddAttribute("ONLY_ACTIVE_ARCH", this->CreateString("NO"));
  2294. // Store ARCHS value.
  2295. if (archs.size() == 1) {
  2296. buildSettings->AddAttribute("ARCHS", this->CreateString(archs[0]));
  2297. } else {
  2298. cmXCodeObject* archObjects =
  2299. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2300. for (auto& arch : archs) {
  2301. archObjects->AddObject(this->CreateString(arch));
  2302. }
  2303. buildSettings->AddAttribute("ARCHS", archObjects);
  2304. }
  2305. }
  2306. // Get the product name components.
  2307. cmGeneratorTarget::NameComponents const& components =
  2308. gtgt->GetFullNameComponents(configName);
  2309. cmValue version = gtgt->GetProperty("VERSION");
  2310. cmValue soversion = gtgt->GetProperty("SOVERSION");
  2311. if (!gtgt->HasSOName(configName) || gtgt->IsFrameworkOnApple()) {
  2312. version = nullptr;
  2313. soversion = nullptr;
  2314. }
  2315. if (version && !soversion) {
  2316. soversion = version;
  2317. }
  2318. if (!version && soversion) {
  2319. version = soversion;
  2320. }
  2321. std::string realName = components.base;
  2322. std::string soName = components.base;
  2323. if (version && soversion) {
  2324. realName += '.';
  2325. realName += *version;
  2326. soName += '.';
  2327. soName += *soversion;
  2328. }
  2329. if (gtgt->CanCompileSources()) {
  2330. std::string const tmpDir =
  2331. this->GetTargetTempDir(gtgt, this->GetCMakeCFGIntDir());
  2332. buildSettings->AddAttribute("TARGET_TEMP_DIR", this->CreateString(tmpDir));
  2333. std::string outDir;
  2334. if (gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  2335. // We cannot suppress the archive, so hide it with intermediate files.
  2336. outDir = tmpDir;
  2337. } else {
  2338. outDir = gtgt->GetDirectory(configName);
  2339. }
  2340. buildSettings->AddAttribute("CONFIGURATION_BUILD_DIR",
  2341. this->CreateString(outDir));
  2342. }
  2343. // Set attributes to specify the proper name for the target.
  2344. std::string pndir = this->CurrentLocalGenerator->GetCurrentBinaryDirectory();
  2345. if (gtgt->GetType() == cmStateEnums::STATIC_LIBRARY ||
  2346. gtgt->GetType() == cmStateEnums::SHARED_LIBRARY ||
  2347. gtgt->GetType() == cmStateEnums::MODULE_LIBRARY ||
  2348. gtgt->GetType() == cmStateEnums::EXECUTABLE) {
  2349. std::string prefix = components.prefix;
  2350. if (gtgt->IsFrameworkOnApple() || gtgt->IsCFBundleOnApple()) {
  2351. prefix = "";
  2352. }
  2353. buildSettings->AddAttribute("EXECUTABLE_PREFIX",
  2354. this->CreateString(prefix));
  2355. buildSettings->AddAttribute("EXECUTABLE_SUFFIX",
  2356. this->CreateString(components.suffix));
  2357. }
  2358. // Store the product name for all target types.
  2359. buildSettings->AddAttribute("PRODUCT_NAME", this->CreateString(realName));
  2360. // Handle settings for each target type.
  2361. switch (gtgt->GetType()) {
  2362. case cmStateEnums::STATIC_LIBRARY:
  2363. if (gtgt->GetPropertyAsBool("FRAMEWORK")) {
  2364. std::string fw_version = gtgt->GetFrameworkVersion();
  2365. buildSettings->AddAttribute("FRAMEWORK_VERSION",
  2366. this->CreateString(fw_version));
  2367. cmValue ext = gtgt->GetProperty("BUNDLE_EXTENSION");
  2368. if (ext) {
  2369. buildSettings->AddAttribute("WRAPPER_EXTENSION",
  2370. this->CreateString(*ext));
  2371. }
  2372. std::string plist = this->ComputeInfoPListLocation(gtgt);
  2373. // Xcode will create the final version of Info.plist at build time,
  2374. // so let it replace the framework name. This avoids creating
  2375. // a per-configuration Info.plist file.
  2376. this->CurrentLocalGenerator->GenerateFrameworkInfoPList(
  2377. gtgt, "$(EXECUTABLE_NAME)", plist);
  2378. buildSettings->AddAttribute("INFOPLIST_FILE",
  2379. this->CreateString(plist));
  2380. buildSettings->AddAttribute("MACH_O_TYPE",
  2381. this->CreateString("staticlib"));
  2382. } else {
  2383. buildSettings->AddAttribute("LIBRARY_STYLE",
  2384. this->CreateString("STATIC"));
  2385. }
  2386. break;
  2387. case cmStateEnums::OBJECT_LIBRARY: {
  2388. buildSettings->AddAttribute("LIBRARY_STYLE",
  2389. this->CreateString("STATIC"));
  2390. break;
  2391. }
  2392. case cmStateEnums::MODULE_LIBRARY: {
  2393. buildSettings->AddAttribute("LIBRARY_STYLE",
  2394. this->CreateString("BUNDLE"));
  2395. if (gtgt->IsCFBundleOnApple()) {
  2396. // It turns out that a BUNDLE is basically the same
  2397. // in many ways as an application bundle, as far as
  2398. // link flags go
  2399. std::string createFlags = this->LookupFlags(
  2400. "CMAKE_SHARED_MODULE_CREATE_", llang, "_FLAGS", "-bundle");
  2401. if (!createFlags.empty()) {
  2402. extraLinkOptions += ' ';
  2403. extraLinkOptions += createFlags;
  2404. }
  2405. cmValue ext = gtgt->GetProperty("BUNDLE_EXTENSION");
  2406. if (ext) {
  2407. buildSettings->AddAttribute("WRAPPER_EXTENSION",
  2408. this->CreateString(*ext));
  2409. }
  2410. std::string plist = this->ComputeInfoPListLocation(gtgt);
  2411. // Xcode will create the final version of Info.plist at build time,
  2412. // so let it replace the cfbundle name. This avoids creating
  2413. // a per-configuration Info.plist file. The cfbundle plist
  2414. // is very similar to the application bundle plist
  2415. this->CurrentLocalGenerator->GenerateAppleInfoPList(
  2416. gtgt, "$(EXECUTABLE_NAME)", plist);
  2417. buildSettings->AddAttribute("INFOPLIST_FILE",
  2418. this->CreateString(plist));
  2419. } else {
  2420. buildSettings->AddAttribute("MACH_O_TYPE",
  2421. this->CreateString("mh_bundle"));
  2422. buildSettings->AddAttribute("GCC_DYNAMIC_NO_PIC",
  2423. this->CreateString("NO"));
  2424. // Add the flags to create an executable.
  2425. std::string createFlags =
  2426. this->LookupFlags("CMAKE_", llang, "_LINK_FLAGS", "");
  2427. if (!createFlags.empty()) {
  2428. extraLinkOptions += ' ';
  2429. extraLinkOptions += createFlags;
  2430. }
  2431. }
  2432. break;
  2433. }
  2434. case cmStateEnums::SHARED_LIBRARY: {
  2435. if (gtgt->GetPropertyAsBool("FRAMEWORK")) {
  2436. std::string fw_version = gtgt->GetFrameworkVersion();
  2437. buildSettings->AddAttribute("FRAMEWORK_VERSION",
  2438. this->CreateString(fw_version));
  2439. cmValue ext = gtgt->GetProperty("BUNDLE_EXTENSION");
  2440. if (ext) {
  2441. buildSettings->AddAttribute("WRAPPER_EXTENSION",
  2442. this->CreateString(*ext));
  2443. }
  2444. std::string plist = this->ComputeInfoPListLocation(gtgt);
  2445. // Xcode will create the final version of Info.plist at build time,
  2446. // so let it replace the framework name. This avoids creating
  2447. // a per-configuration Info.plist file.
  2448. this->CurrentLocalGenerator->GenerateFrameworkInfoPList(
  2449. gtgt, "$(EXECUTABLE_NAME)", plist);
  2450. buildSettings->AddAttribute("INFOPLIST_FILE",
  2451. this->CreateString(plist));
  2452. } else {
  2453. // Add the flags to create a shared library.
  2454. std::string createFlags = this->LookupFlags(
  2455. "CMAKE_SHARED_LIBRARY_CREATE_", llang, "_FLAGS", "-dynamiclib");
  2456. if (!createFlags.empty()) {
  2457. extraLinkOptions += ' ';
  2458. extraLinkOptions += createFlags;
  2459. }
  2460. }
  2461. buildSettings->AddAttribute("LIBRARY_STYLE",
  2462. this->CreateString("DYNAMIC"));
  2463. if (gtgt->HasImportLibrary(configName)) {
  2464. // Request .tbd file generation
  2465. buildSettings->AddAttribute("GENERATE_TEXT_BASED_STUBS",
  2466. this->CreateString("YES"));
  2467. }
  2468. break;
  2469. }
  2470. case cmStateEnums::EXECUTABLE: {
  2471. // Add the flags to create an executable.
  2472. std::string createFlags =
  2473. this->LookupFlags("CMAKE_", llang, "_LINK_FLAGS", "");
  2474. if (!createFlags.empty()) {
  2475. extraLinkOptions += ' ';
  2476. extraLinkOptions += createFlags;
  2477. }
  2478. // Handle bundles and normal executables separately.
  2479. if (gtgt->GetPropertyAsBool("MACOSX_BUNDLE")) {
  2480. cmValue ext = gtgt->GetProperty("BUNDLE_EXTENSION");
  2481. if (ext) {
  2482. buildSettings->AddAttribute("WRAPPER_EXTENSION",
  2483. this->CreateString(*ext));
  2484. }
  2485. std::string plist = this->ComputeInfoPListLocation(gtgt);
  2486. // Xcode will create the final version of Info.plist at build time,
  2487. // so let it replace the executable name. This avoids creating
  2488. // a per-configuration Info.plist file.
  2489. this->CurrentLocalGenerator->GenerateAppleInfoPList(
  2490. gtgt, "$(EXECUTABLE_NAME)", plist);
  2491. buildSettings->AddAttribute("INFOPLIST_FILE",
  2492. this->CreateString(plist));
  2493. }
  2494. } break;
  2495. default:
  2496. break;
  2497. }
  2498. BuildObjectListOrString dirs(this, true);
  2499. BuildObjectListOrString fdirs(this, true);
  2500. BuildObjectListOrString sysdirs(this, true);
  2501. BuildObjectListOrString sysfdirs(this, true);
  2502. const bool emitSystemIncludes = this->XcodeVersion >= 83;
  2503. // Choose a language to use for target-wide include directories.
  2504. std::string const& langForIncludes = llang;
  2505. std::vector<std::string> includes;
  2506. if (!langForIncludes.empty()) {
  2507. this->CurrentLocalGenerator->GetIncludeDirectories(
  2508. includes, gtgt, langForIncludes, configName);
  2509. }
  2510. std::set<std::string> emitted;
  2511. emitted.insert("/System/Library/Frameworks");
  2512. for (auto& include : includes) {
  2513. if (this->NameResolvesToFramework(include)) {
  2514. std::string frameworkDir = cmStrCat(include, "/../");
  2515. frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
  2516. if (emitted.insert(frameworkDir).second) {
  2517. std::string incpath = this->XCodeEscapePath(frameworkDir);
  2518. if (emitSystemIncludes &&
  2519. gtgt->IsSystemIncludeDirectory(frameworkDir, configName,
  2520. langForIncludes)) {
  2521. sysfdirs.Add(incpath);
  2522. } else {
  2523. fdirs.Add(incpath);
  2524. }
  2525. }
  2526. } else {
  2527. std::string incpath = this->XCodeEscapePath(include);
  2528. if (emitSystemIncludes &&
  2529. gtgt->IsSystemIncludeDirectory(include, configName,
  2530. langForIncludes)) {
  2531. sysdirs.Add(incpath);
  2532. } else {
  2533. dirs.Add(incpath);
  2534. }
  2535. }
  2536. }
  2537. // Add framework search paths needed for linking.
  2538. if (cmComputeLinkInformation* cli = gtgt->GetLinkInformation(configName)) {
  2539. for (auto const& fwDir : cli->GetFrameworkPaths()) {
  2540. if (emitted.insert(fwDir).second) {
  2541. std::string incpath = this->XCodeEscapePath(fwDir);
  2542. if (emitSystemIncludes &&
  2543. gtgt->IsSystemIncludeDirectory(fwDir, configName,
  2544. langForIncludes)) {
  2545. sysfdirs.Add(incpath);
  2546. } else {
  2547. fdirs.Add(incpath);
  2548. }
  2549. }
  2550. }
  2551. }
  2552. if (!fdirs.IsEmpty()) {
  2553. buildSettings->AddAttribute("FRAMEWORK_SEARCH_PATHS", fdirs.CreateList());
  2554. }
  2555. if (!dirs.IsEmpty()) {
  2556. buildSettings->AddAttribute("HEADER_SEARCH_PATHS", dirs.CreateList());
  2557. if (languages.count("Swift")) {
  2558. buildSettings->AddAttribute("SWIFT_INCLUDE_PATHS", dirs.CreateList());
  2559. }
  2560. }
  2561. if (!sysfdirs.IsEmpty()) {
  2562. buildSettings->AddAttribute("SYSTEM_FRAMEWORK_SEARCH_PATHS",
  2563. sysfdirs.CreateList());
  2564. }
  2565. if (!sysdirs.IsEmpty()) {
  2566. buildSettings->AddAttribute("SYSTEM_HEADER_SEARCH_PATHS",
  2567. sysdirs.CreateList());
  2568. }
  2569. if (this->XcodeVersion >= 60 && !emitSystemIncludes) {
  2570. // Add those per-language flags in addition to HEADER_SEARCH_PATHS to gain
  2571. // system include directory awareness. We need to also keep on setting
  2572. // HEADER_SEARCH_PATHS to work around a missing compile options flag for
  2573. // GNU assembly files (#16449)
  2574. for (auto const& language : languages) {
  2575. std::string includeFlags = this->CurrentLocalGenerator->GetIncludeFlags(
  2576. includes, gtgt, language, configName);
  2577. if (!includeFlags.empty()) {
  2578. cflags[language] += cmStrCat(' ', includeFlags);
  2579. }
  2580. }
  2581. }
  2582. bool same_gflags = true;
  2583. std::map<std::string, std::string> gflags;
  2584. std::string const* last_gflag = nullptr;
  2585. std::string optLevel = "0";
  2586. // Minimal map of flags to build settings.
  2587. for (auto const& language : languages) {
  2588. std::string& flags = cflags[language];
  2589. std::string& gflag = gflags[language];
  2590. std::string oflag =
  2591. this->ExtractFlagRegex("(^| )(-Ofast|-Os|-O[0-9]*)( |$)", 2, flags);
  2592. if (oflag.size() == 2) {
  2593. optLevel = "1";
  2594. } else if (oflag.size() > 2) {
  2595. optLevel = oflag.substr(2);
  2596. }
  2597. gflag = this->ExtractFlag("-g", flags);
  2598. // put back gdwarf-2 if used since there is no way
  2599. // to represent it in the gui, but we still want debug yes
  2600. if (gflag == "-gdwarf-2"_s) {
  2601. flags += ' ';
  2602. flags += gflag;
  2603. }
  2604. if (last_gflag && *last_gflag != gflag) {
  2605. same_gflags = false;
  2606. }
  2607. last_gflag = &gflag;
  2608. }
  2609. const char* debugStr = "YES";
  2610. if (!same_gflags) {
  2611. // We can't set the Xcode flag differently depending on the language,
  2612. // so put them back in this case.
  2613. for (auto const& language : languages) {
  2614. cflags[language] += ' ';
  2615. cflags[language] += gflags[language];
  2616. }
  2617. debugStr = "NO";
  2618. } else if (last_gflag && (last_gflag->empty() || *last_gflag == "-g0"_s)) {
  2619. debugStr = "NO";
  2620. }
  2621. // extract C++ stdlib
  2622. for (auto const& language : languages) {
  2623. if (language != "CXX"_s && language != "OBJCXX"_s) {
  2624. continue;
  2625. }
  2626. std::string& flags = cflags[language];
  2627. auto stdlib =
  2628. this->ExtractFlagRegex("(^| )(-stdlib=[^ ]+)( |$)", 2, flags);
  2629. if (stdlib.size() > 8) {
  2630. const auto cxxLibrary = stdlib.substr(8);
  2631. if (language == "CXX"_s ||
  2632. !buildSettings->GetAttribute("CLANG_CXX_LIBRARY")) {
  2633. buildSettings->AddAttribute("CLANG_CXX_LIBRARY",
  2634. this->CreateString(cxxLibrary));
  2635. }
  2636. }
  2637. }
  2638. buildSettings->AddAttribute("COMBINE_HIDPI_IMAGES",
  2639. this->CreateString("YES"));
  2640. buildSettings->AddAttribute("GCC_GENERATE_DEBUGGING_SYMBOLS",
  2641. this->CreateString(debugStr));
  2642. buildSettings->AddAttribute("GCC_OPTIMIZATION_LEVEL",
  2643. this->CreateString(optLevel));
  2644. buildSettings->AddAttribute("GCC_SYMBOLS_PRIVATE_EXTERN",
  2645. this->CreateString("NO"));
  2646. buildSettings->AddAttribute("GCC_INLINES_ARE_PRIVATE_EXTERN",
  2647. this->CreateString("NO"));
  2648. for (auto const& language : languages) {
  2649. std::string flags = cmStrCat(cflags[language], ' ', defFlags);
  2650. if (language == "CXX"_s || language == "OBJCXX"_s) {
  2651. if (language == "CXX"_s ||
  2652. !buildSettings->GetAttribute("OTHER_CPLUSPLUSFLAGS")) {
  2653. buildSettings->AddAttribute("OTHER_CPLUSPLUSFLAGS",
  2654. this->CreateString(flags));
  2655. }
  2656. } else if (language == "Fortran"_s) {
  2657. buildSettings->AddAttribute("IFORT_OTHER_FLAGS",
  2658. this->CreateString(flags));
  2659. } else if (language == "C"_s || language == "OBJC"_s) {
  2660. if (language == "C"_s || !buildSettings->GetAttribute("OTHER_CFLAGS")) {
  2661. buildSettings->AddAttribute("OTHER_CFLAGS", this->CreateString(flags));
  2662. }
  2663. } else if (language == "Swift"_s) {
  2664. buildSettings->AddAttribute("OTHER_SWIFT_FLAGS",
  2665. this->CreateString(flags));
  2666. }
  2667. }
  2668. // Add Fortran source format attribute if property is set.
  2669. const char* format = nullptr;
  2670. std::string const& tgtfmt = gtgt->GetSafeProperty("Fortran_FORMAT");
  2671. switch (cmOutputConverter::GetFortranFormat(tgtfmt)) {
  2672. case cmOutputConverter::FortranFormatFixed:
  2673. format = "fixed";
  2674. break;
  2675. case cmOutputConverter::FortranFormatFree:
  2676. format = "free";
  2677. break;
  2678. default:
  2679. break;
  2680. }
  2681. if (format) {
  2682. buildSettings->AddAttribute("IFORT_LANG_SRCFMT",
  2683. this->CreateString(format));
  2684. }
  2685. // Create the INSTALL_PATH attribute.
  2686. std::string install_name_dir;
  2687. if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) {
  2688. // Get the install_name directory for the build tree.
  2689. install_name_dir = gtgt->GetInstallNameDirForBuildTree(configName);
  2690. // Xcode doesn't create the correct install_name in some cases.
  2691. // That is, if the INSTALL_PATH is empty, or if we have versioning
  2692. // of dylib libraries, we want to specify the install_name.
  2693. // This is done by adding a link flag to create an install_name
  2694. // with just the library soname.
  2695. std::string install_name;
  2696. if (!install_name_dir.empty()) {
  2697. // Convert to a path for the native build tool.
  2698. cmSystemTools::ConvertToUnixSlashes(install_name_dir);
  2699. install_name += install_name_dir;
  2700. install_name += '/';
  2701. }
  2702. install_name += gtgt->GetSOName(configName);
  2703. if ((realName != soName) || install_name_dir.empty()) {
  2704. install_name_dir = "";
  2705. extraLinkOptions += " -install_name ";
  2706. extraLinkOptions += XCodeEscapePath(install_name);
  2707. }
  2708. }
  2709. buildSettings->AddAttribute("INSTALL_PATH",
  2710. this->CreateString(install_name_dir));
  2711. // Create the LD_RUNPATH_SEARCH_PATHS
  2712. cmComputeLinkInformation* pcli = gtgt->GetLinkInformation(configName);
  2713. if (pcli) {
  2714. std::string search_paths;
  2715. std::vector<std::string> runtimeDirs;
  2716. pcli->GetRPath(runtimeDirs, false);
  2717. // runpath dirs needs to be unique to prevent corruption
  2718. std::set<std::string> unique_dirs;
  2719. for (auto runpath : runtimeDirs) {
  2720. runpath = this->ExpandCFGIntDir(runpath, configName);
  2721. if (unique_dirs.find(runpath) == unique_dirs.end()) {
  2722. unique_dirs.insert(runpath);
  2723. if (!search_paths.empty()) {
  2724. search_paths += ' ';
  2725. }
  2726. search_paths += this->XCodeEscapePath(runpath);
  2727. }
  2728. }
  2729. if (!search_paths.empty()) {
  2730. buildSettings->AddAttribute("LD_RUNPATH_SEARCH_PATHS",
  2731. this->CreateString(search_paths));
  2732. }
  2733. }
  2734. buildSettings->AddAttribute(this->GetTargetLinkFlagsVar(gtgt),
  2735. this->CreateString(extraLinkOptions));
  2736. buildSettings->AddAttribute("OTHER_REZFLAGS", this->CreateString(""));
  2737. buildSettings->AddAttribute("SECTORDER_FLAGS", this->CreateString(""));
  2738. buildSettings->AddAttribute("ALWAYS_SEARCH_USER_PATHS",
  2739. this->CreateString("NO"));
  2740. buildSettings->AddAttribute("USE_HEADERMAP", this->CreateString("NO"));
  2741. cmXCodeObject* group = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2742. group->AddObject(this->CreateString("$(inherited)"));
  2743. buildSettings->AddAttribute("WARNING_CFLAGS", group);
  2744. // Runtime version information.
  2745. if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) {
  2746. int major;
  2747. int minor;
  2748. int patch;
  2749. // MACHO_CURRENT_VERSION or VERSION -> current_version
  2750. gtgt->GetTargetVersionFallback("MACHO_CURRENT_VERSION", "VERSION", major,
  2751. minor, patch);
  2752. std::ostringstream v;
  2753. // Xcode always wants at least 1.0.0 or nothing
  2754. if (!(major == 0 && minor == 0 && patch == 0)) {
  2755. v << major << '.' << minor << '.' << patch;
  2756. }
  2757. buildSettings->AddAttribute("DYLIB_CURRENT_VERSION",
  2758. this->CreateString(v.str()));
  2759. // MACHO_COMPATIBILITY_VERSION or SOVERSION -> compatibility_version
  2760. gtgt->GetTargetVersionFallback("MACHO_COMPATIBILITY_VERSION", "SOVERSION",
  2761. major, minor, patch);
  2762. std::ostringstream vso;
  2763. // Xcode always wants at least 1.0.0 or nothing
  2764. if (!(major == 0 && minor == 0 && patch == 0)) {
  2765. vso << major << '.' << minor << '.' << patch;
  2766. }
  2767. buildSettings->AddAttribute("DYLIB_COMPATIBILITY_VERSION",
  2768. this->CreateString(vso.str()));
  2769. }
  2770. // Precompile Headers
  2771. std::string pchHeader = gtgt->GetPchHeader(configName, llang);
  2772. if (!pchHeader.empty()) {
  2773. buildSettings->AddAttribute("GCC_PREFIX_HEADER",
  2774. this->CreateString(pchHeader));
  2775. buildSettings->AddAttribute("GCC_PRECOMPILE_PREFIX_HEADER",
  2776. this->CreateString("YES"));
  2777. }
  2778. // put this last so it can override existing settings
  2779. // Convert "XCODE_ATTRIBUTE_*" properties directly.
  2780. {
  2781. for (auto const& prop : gtgt->GetPropertyKeys()) {
  2782. if (cmHasLiteralPrefix(prop, "XCODE_ATTRIBUTE_")) {
  2783. std::string attribute = prop.substr(16);
  2784. this->FilterConfigurationAttribute(configName, attribute);
  2785. if (!attribute.empty()) {
  2786. std::string const& pr = gtgt->GetSafeProperty(prop);
  2787. std::string processed = cmGeneratorExpression::Evaluate(
  2788. pr, this->CurrentLocalGenerator, configName);
  2789. buildSettings->AddAttribute(attribute,
  2790. this->CreateString(processed));
  2791. }
  2792. }
  2793. }
  2794. }
  2795. }
  2796. cmXCodeObject* cmGlobalXCodeGenerator::CreateUtilityTarget(
  2797. cmGeneratorTarget* gtgt)
  2798. {
  2799. cmXCodeObject* shellBuildPhase = this->CreateObject(
  2800. cmXCodeObject::PBXShellScriptBuildPhase, gtgt->GetName());
  2801. shellBuildPhase->AddAttribute("buildActionMask",
  2802. this->CreateString("2147483647"));
  2803. cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2804. shellBuildPhase->AddAttribute("files", buildFiles);
  2805. cmXCodeObject* inputPaths = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2806. shellBuildPhase->AddAttribute("inputPaths", inputPaths);
  2807. cmXCodeObject* outputPaths = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2808. shellBuildPhase->AddAttribute("outputPaths", outputPaths);
  2809. shellBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  2810. this->CreateString("0"));
  2811. shellBuildPhase->AddAttribute("shellPath", this->CreateString("/bin/sh"));
  2812. shellBuildPhase->AddAttribute(
  2813. "shellScript", this->CreateString("# shell script goes here\nexit 0"));
  2814. shellBuildPhase->AddAttribute("showEnvVarsInLog", this->CreateString("0"));
  2815. cmXCodeObject* target =
  2816. this->CreateObject(cmXCodeObject::PBXAggregateTarget);
  2817. target->SetComment(gtgt->GetName());
  2818. cmXCodeObject* buildPhases = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2819. std::vector<cmXCodeObject*> emptyContentVector;
  2820. this->CreateCustomCommands(buildPhases, nullptr, nullptr, nullptr,
  2821. emptyContentVector, nullptr, gtgt);
  2822. target->AddAttribute("buildPhases", buildPhases);
  2823. this->AddConfigurations(target, gtgt);
  2824. cmXCodeObject* dependencies = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2825. target->AddAttribute("dependencies", dependencies);
  2826. target->AddAttribute("name", this->CreateString(gtgt->GetName()));
  2827. target->AddAttribute("productName", this->CreateString(gtgt->GetName()));
  2828. target->SetTarget(gtgt);
  2829. this->XCodeObjectMap[gtgt] = target;
  2830. // Add source files without build rules for editing convenience.
  2831. if (gtgt->GetType() != cmStateEnums::GLOBAL_TARGET &&
  2832. gtgt->GetName() != CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
  2833. std::vector<cmSourceFile*> sources;
  2834. if (!gtgt->GetConfigCommonSourceFilesForXcode(sources)) {
  2835. return nullptr;
  2836. }
  2837. // Add CMakeLists.txt file for user convenience.
  2838. this->AddXCodeProjBuildRule(gtgt, sources);
  2839. for (auto* sourceFile : sources) {
  2840. if (!sourceFile->GetIsGenerated()) {
  2841. this->CreateXCodeFileReference(sourceFile, gtgt);
  2842. }
  2843. }
  2844. }
  2845. target->SetId(this->GetOrCreateId(gtgt->GetName(), target->GetId()));
  2846. return target;
  2847. }
  2848. std::string cmGlobalXCodeGenerator::AddConfigurations(cmXCodeObject* target,
  2849. cmGeneratorTarget* gtgt)
  2850. {
  2851. cmList const configList{ this->CurrentMakefile->GetRequiredDefinition(
  2852. "CMAKE_CONFIGURATION_TYPES") };
  2853. cmXCodeObject* configlist =
  2854. this->CreateObject(cmXCodeObject::XCConfigurationList);
  2855. cmXCodeObject* buildConfigurations =
  2856. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2857. configlist->AddAttribute("buildConfigurations", buildConfigurations);
  2858. std::string comment = cmStrCat("Build configuration list for ",
  2859. cmXCodeObject::PBXTypeNames[target->GetIsA()],
  2860. " \"", gtgt->GetName(), '"');
  2861. configlist->SetComment(comment);
  2862. target->AddAttribute("buildConfigurationList",
  2863. this->CreateObjectReference(configlist));
  2864. for (auto const& i : configList) {
  2865. cmXCodeObject* config =
  2866. this->CreateObject(cmXCodeObject::XCBuildConfiguration);
  2867. buildConfigurations->AddObject(config);
  2868. cmXCodeObject* buildSettings =
  2869. this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  2870. this->CreateBuildSettings(gtgt, buildSettings, i);
  2871. config->AddAttribute("name", this->CreateString(i));
  2872. config->SetComment(i);
  2873. config->AddAttribute("buildSettings", buildSettings);
  2874. this->CreateTargetXCConfigSettings(gtgt, config, i);
  2875. }
  2876. if (!configList.empty()) {
  2877. configlist->AddAttribute("defaultConfigurationName",
  2878. this->CreateString(configList[0]));
  2879. configlist->AddAttribute("defaultConfigurationIsVisible",
  2880. this->CreateString("0"));
  2881. return configList[0];
  2882. }
  2883. return "";
  2884. }
  2885. void cmGlobalXCodeGenerator::CreateGlobalXCConfigSettings(
  2886. cmLocalGenerator* root, cmXCodeObject* config, const std::string& configName)
  2887. {
  2888. auto xcconfig = cmGeneratorExpression::Evaluate(
  2889. this->CurrentMakefile->GetSafeDefinition("CMAKE_XCODE_XCCONFIG"),
  2890. this->CurrentLocalGenerator, configName);
  2891. if (xcconfig.empty()) {
  2892. return;
  2893. }
  2894. auto* sf = this->CurrentMakefile->GetSource(xcconfig);
  2895. if (!sf) {
  2896. cmSystemTools::Error(
  2897. cmStrCat("sources for ALL_BUILD do not contain xcconfig file: '",
  2898. xcconfig, "' (configuration: ", configName, ')'));
  2899. return;
  2900. }
  2901. cmXCodeObject* fileRef = this->CreateXCodeFileReferenceFromPath(
  2902. sf->ResolveFullPath(), root->FindGeneratorTargetToUse("ALL_BUILD"), "",
  2903. sf);
  2904. if (!fileRef) {
  2905. // error is already reported by CreateXCodeFileReferenceFromPath
  2906. return;
  2907. }
  2908. config->AddAttribute("baseConfigurationReference",
  2909. this->CreateObjectReference(fileRef));
  2910. }
  2911. void cmGlobalXCodeGenerator::CreateTargetXCConfigSettings(
  2912. cmGeneratorTarget* target, cmXCodeObject* config,
  2913. const std::string& configName)
  2914. {
  2915. auto xcconfig =
  2916. cmGeneratorExpression::Evaluate(target->GetSafeProperty("XCODE_XCCONFIG"),
  2917. this->CurrentLocalGenerator, configName);
  2918. if (xcconfig.empty()) {
  2919. return;
  2920. }
  2921. auto* sf = target->Makefile->GetSource(xcconfig);
  2922. if (!sf) {
  2923. cmSystemTools::Error(cmStrCat("target sources for target ",
  2924. target->Target->GetName(),
  2925. " do not contain xcconfig file: '", xcconfig,
  2926. "' (configuration: ", configName, ')'));
  2927. return;
  2928. }
  2929. cmXCodeObject* fileRef = this->CreateXCodeFileReferenceFromPath(
  2930. sf->ResolveFullPath(), target, "", sf);
  2931. if (!fileRef) {
  2932. // error is already reported by CreateXCodeFileReferenceFromPath
  2933. return;
  2934. }
  2935. config->AddAttribute("baseConfigurationReference",
  2936. this->CreateObjectReference(fileRef));
  2937. }
  2938. const char* cmGlobalXCodeGenerator::GetTargetLinkFlagsVar(
  2939. cmGeneratorTarget const* target) const
  2940. {
  2941. if (this->XcodeVersion >= 60 &&
  2942. (target->GetType() == cmStateEnums::STATIC_LIBRARY ||
  2943. target->GetType() == cmStateEnums::OBJECT_LIBRARY)) {
  2944. return "OTHER_LIBTOOLFLAGS";
  2945. }
  2946. return "OTHER_LDFLAGS";
  2947. }
  2948. const char* cmGlobalXCodeGenerator::GetTargetFileType(
  2949. cmGeneratorTarget* target)
  2950. {
  2951. if (cmValue e = target->GetProperty("XCODE_EXPLICIT_FILE_TYPE")) {
  2952. return e->c_str();
  2953. }
  2954. switch (target->GetType()) {
  2955. case cmStateEnums::OBJECT_LIBRARY:
  2956. return "archive.ar";
  2957. case cmStateEnums::STATIC_LIBRARY:
  2958. return (target->GetPropertyAsBool("FRAMEWORK") ? "wrapper.framework"
  2959. : "archive.ar");
  2960. case cmStateEnums::MODULE_LIBRARY:
  2961. if (target->IsXCTestOnApple()) {
  2962. return "wrapper.cfbundle";
  2963. }
  2964. if (target->IsCFBundleOnApple()) {
  2965. return "wrapper.plug-in";
  2966. }
  2967. return "compiled.mach-o.executable";
  2968. case cmStateEnums::SHARED_LIBRARY:
  2969. return (target->GetPropertyAsBool("FRAMEWORK")
  2970. ? "wrapper.framework"
  2971. : "compiled.mach-o.dylib");
  2972. case cmStateEnums::EXECUTABLE:
  2973. return "compiled.mach-o.executable";
  2974. default:
  2975. break;
  2976. }
  2977. return nullptr;
  2978. }
  2979. const char* cmGlobalXCodeGenerator::GetTargetProductType(
  2980. cmGeneratorTarget* target)
  2981. {
  2982. if (cmValue e = target->GetProperty("XCODE_PRODUCT_TYPE")) {
  2983. return e->c_str();
  2984. }
  2985. switch (target->GetType()) {
  2986. case cmStateEnums::OBJECT_LIBRARY:
  2987. return "com.apple.product-type.library.static";
  2988. case cmStateEnums::STATIC_LIBRARY:
  2989. return (target->GetPropertyAsBool("FRAMEWORK")
  2990. ? "com.apple.product-type.framework"
  2991. : "com.apple.product-type.library.static");
  2992. case cmStateEnums::MODULE_LIBRARY:
  2993. if (target->IsXCTestOnApple()) {
  2994. return "com.apple.product-type.bundle.unit-test";
  2995. } else if (target->IsCFBundleOnApple()) {
  2996. return "com.apple.product-type.bundle";
  2997. } else {
  2998. return "com.apple.product-type.tool";
  2999. }
  3000. case cmStateEnums::SHARED_LIBRARY:
  3001. return (target->GetPropertyAsBool("FRAMEWORK")
  3002. ? "com.apple.product-type.framework"
  3003. : "com.apple.product-type.library.dynamic");
  3004. case cmStateEnums::EXECUTABLE:
  3005. return (target->GetPropertyAsBool("MACOSX_BUNDLE")
  3006. ? "com.apple.product-type.application"
  3007. : "com.apple.product-type.tool");
  3008. default:
  3009. break;
  3010. }
  3011. return nullptr;
  3012. }
  3013. cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeTarget(
  3014. cmGeneratorTarget* gtgt, cmXCodeObject* buildPhases)
  3015. {
  3016. if (!gtgt->IsInBuildSystem()) {
  3017. return nullptr;
  3018. }
  3019. cmXCodeObject* target = this->CreateObject(cmXCodeObject::PBXNativeTarget);
  3020. target->AddAttribute("buildPhases", buildPhases);
  3021. cmXCodeObject* buildRules = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3022. target->AddAttribute("buildRules", buildRules);
  3023. std::string defConfig;
  3024. defConfig = this->AddConfigurations(target, gtgt);
  3025. cmXCodeObject* dependencies = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3026. target->AddAttribute("dependencies", dependencies);
  3027. target->AddAttribute("name", this->CreateString(gtgt->GetName()));
  3028. target->AddAttribute("productName", this->CreateString(gtgt->GetName()));
  3029. cmXCodeObject* fileRef = this->CreateObject(cmXCodeObject::PBXFileReference);
  3030. if (const char* fileType = this->GetTargetFileType(gtgt)) {
  3031. fileRef->AddAttribute("explicitFileType", this->CreateString(fileType));
  3032. }
  3033. std::string fullName;
  3034. if (gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  3035. fullName = cmStrCat("lib", gtgt->GetName(), ".a");
  3036. } else {
  3037. fullName = gtgt->GetFullName(defConfig);
  3038. }
  3039. fileRef->AddAttribute("path", this->CreateString(fullName));
  3040. fileRef->AddAttribute("sourceTree",
  3041. this->CreateString("BUILT_PRODUCTS_DIR"));
  3042. fileRef->SetComment(gtgt->GetName());
  3043. target->AddAttribute("productReference",
  3044. this->CreateObjectReference(fileRef));
  3045. if (const char* productType = this->GetTargetProductType(gtgt)) {
  3046. target->AddAttribute("productType", this->CreateString(productType));
  3047. }
  3048. target->SetTarget(gtgt);
  3049. this->XCodeObjectMap[gtgt] = target;
  3050. target->SetId(this->GetOrCreateId(gtgt->GetName(), target->GetId()));
  3051. return target;
  3052. }
  3053. cmXCodeObject* cmGlobalXCodeGenerator::FindXCodeTarget(
  3054. cmGeneratorTarget const* t)
  3055. {
  3056. if (!t) {
  3057. return nullptr;
  3058. }
  3059. auto const i = this->XCodeObjectMap.find(t);
  3060. if (i == this->XCodeObjectMap.end()) {
  3061. return nullptr;
  3062. }
  3063. return i->second;
  3064. }
  3065. std::string cmGlobalXCodeGenerator::GetObjectId(cmXCodeObject::PBXType ptype,
  3066. cm::string_view key)
  3067. {
  3068. std::string objectId;
  3069. if (!key.empty()) {
  3070. cmCryptoHash hash(cmCryptoHash::AlgoSHA256);
  3071. hash.Initialize();
  3072. hash.Append(&ptype, sizeof(ptype));
  3073. hash.Append(key);
  3074. objectId = cmSystemTools::UpperCase(hash.FinalizeHex().substr(0, 24));
  3075. } else {
  3076. char cUuid[40] = { 0 };
  3077. CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
  3078. CFStringRef s = CFUUIDCreateString(kCFAllocatorDefault, uuid);
  3079. CFStringGetCString(s, cUuid, sizeof(cUuid), kCFStringEncodingUTF8);
  3080. objectId = cUuid;
  3081. CFRelease(s);
  3082. CFRelease(uuid);
  3083. cmSystemTools::ReplaceString(objectId, "-", "");
  3084. if (objectId.size() > 24) {
  3085. objectId = objectId.substr(0, 24);
  3086. }
  3087. }
  3088. return objectId;
  3089. }
  3090. std::string cmGlobalXCodeGenerator::GetOrCreateId(const std::string& name,
  3091. const std::string& id)
  3092. {
  3093. std::string guidStoreName = cmStrCat(name, "_GUID_CMAKE");
  3094. cmValue storedGUID = this->CMakeInstance->GetCacheDefinition(guidStoreName);
  3095. if (storedGUID) {
  3096. return *storedGUID;
  3097. }
  3098. this->CMakeInstance->AddCacheEntry(
  3099. guidStoreName, id, "Stored Xcode object GUID", cmStateEnums::INTERNAL);
  3100. return id;
  3101. }
  3102. void cmGlobalXCodeGenerator::AddDependTarget(cmXCodeObject* target,
  3103. cmXCodeObject* dependTarget)
  3104. {
  3105. // This is called once for every edge in the target dependency graph.
  3106. cmXCodeObject* container =
  3107. this->CreateObject(cmXCodeObject::PBXContainerItemProxy);
  3108. container->SetComment("PBXContainerItemProxy");
  3109. container->AddAttribute("containerPortal",
  3110. this->CreateObjectReference(this->RootObject));
  3111. container->AddAttribute("proxyType", this->CreateString("1"));
  3112. container->AddAttribute("remoteGlobalIDString",
  3113. this->CreateObjectReference(dependTarget));
  3114. container->AddAttribute(
  3115. "remoteInfo", this->CreateString(dependTarget->GetTarget()->GetName()));
  3116. cmXCodeObject* targetdep =
  3117. this->CreateObject(cmXCodeObject::PBXTargetDependency);
  3118. targetdep->SetComment("PBXTargetDependency");
  3119. targetdep->AddAttribute("target", this->CreateObjectReference(dependTarget));
  3120. targetdep->AddAttribute("targetProxy",
  3121. this->CreateObjectReference(container));
  3122. cmXCodeObject* depends = target->GetAttribute("dependencies");
  3123. if (!depends) {
  3124. cmSystemTools::Error(
  3125. "target does not have dependencies attribute error..");
  3126. } else {
  3127. depends->AddUniqueObject(targetdep);
  3128. }
  3129. }
  3130. void cmGlobalXCodeGenerator::AppendOrAddBuildSetting(cmXCodeObject* settings,
  3131. const char* attribute,
  3132. cmXCodeObject* value)
  3133. {
  3134. if (settings) {
  3135. cmXCodeObject* attr = settings->GetAttribute(attribute);
  3136. if (!attr) {
  3137. settings->AddAttribute(attribute, value);
  3138. } else {
  3139. this->AppendBuildSettingAttribute(settings, attribute, attr, value);
  3140. }
  3141. }
  3142. }
  3143. void cmGlobalXCodeGenerator::AppendBuildSettingAttribute(
  3144. cmXCodeObject* settings, const char* attribute, cmXCodeObject* attr,
  3145. cmXCodeObject* value)
  3146. {
  3147. if (value->GetType() != cmXCodeObject::OBJECT_LIST &&
  3148. value->GetType() != cmXCodeObject::STRING) {
  3149. cmSystemTools::Error(
  3150. cmStrCat("Unsupported value type for appending: ", attribute));
  3151. return;
  3152. }
  3153. if (attr->GetType() == cmXCodeObject::OBJECT_LIST) {
  3154. if (value->GetType() == cmXCodeObject::OBJECT_LIST) {
  3155. for (auto* obj : value->GetObjectList()) {
  3156. attr->AddObject(obj);
  3157. }
  3158. } else {
  3159. attr->AddObject(value);
  3160. }
  3161. } else if (attr->GetType() == cmXCodeObject::STRING) {
  3162. if (value->GetType() == cmXCodeObject::OBJECT_LIST) {
  3163. // Add old value as a list item to new object list
  3164. // and replace the attribute with the new list
  3165. value->PrependObject(attr);
  3166. settings->AddAttribute(attribute, value);
  3167. } else {
  3168. std::string newValue =
  3169. cmStrCat(attr->GetString(), ' ', value->GetString());
  3170. attr->SetString(newValue);
  3171. }
  3172. } else {
  3173. cmSystemTools::Error(
  3174. cmStrCat("Unsupported attribute type for appending: ", attribute));
  3175. }
  3176. }
  3177. void cmGlobalXCodeGenerator::AppendBuildSettingAttribute(
  3178. cmXCodeObject* target, const char* attribute, cmXCodeObject* value,
  3179. const std::string& configName)
  3180. {
  3181. // There are multiple configurations. Add the setting to the
  3182. // buildSettings of the configuration name given.
  3183. cmXCodeObject* configurationList =
  3184. target->GetAttribute("buildConfigurationList")->GetObject();
  3185. cmXCodeObject* buildConfigs =
  3186. configurationList->GetAttribute("buildConfigurations");
  3187. for (auto* obj : buildConfigs->GetObjectList()) {
  3188. if (configName.empty() ||
  3189. obj->GetAttribute("name")->GetString() == configName) {
  3190. cmXCodeObject* settings = obj->GetAttribute("buildSettings");
  3191. this->AppendOrAddBuildSetting(settings, attribute, value);
  3192. }
  3193. }
  3194. }
  3195. void cmGlobalXCodeGenerator::InheritBuildSettingAttribute(
  3196. cmXCodeObject* target, const char* attribute)
  3197. {
  3198. cmXCodeObject* configurationList =
  3199. target->GetAttribute("buildConfigurationList")->GetObject();
  3200. cmXCodeObject* buildConfigs =
  3201. configurationList->GetAttribute("buildConfigurations");
  3202. for (auto* obj : buildConfigs->GetObjectList()) {
  3203. cmXCodeObject* settings = obj->GetAttribute("buildSettings");
  3204. if (cmXCodeObject* attr = settings->GetAttribute(attribute)) {
  3205. BuildObjectListOrString inherited(this, true);
  3206. inherited.Add("$(inherited)");
  3207. this->AppendBuildSettingAttribute(settings, attribute, attr,
  3208. inherited.CreateList());
  3209. }
  3210. }
  3211. }
  3212. void cmGlobalXCodeGenerator::AddDependAndLinkInformation(cmXCodeObject* target)
  3213. {
  3214. cmGeneratorTarget* gt = target->GetTarget();
  3215. if (!gt) {
  3216. cmSystemTools::Error("Error no target on xobject\n");
  3217. return;
  3218. }
  3219. if (!gt->IsInBuildSystem()) {
  3220. return;
  3221. }
  3222. // Add dependencies on other CMake targets.
  3223. for (const auto& dep : this->GetTargetDirectDepends(gt)) {
  3224. if (cmXCodeObject* dptarget = this->FindXCodeTarget(dep)) {
  3225. this->AddDependTarget(target, dptarget);
  3226. }
  3227. }
  3228. // Separate libraries into ones that can be linked using "Link Binary With
  3229. // Libraries" build phase and the ones that can't. Only targets that build
  3230. // Apple bundles (.app, .framework, .bundle), executables and dylibs can use
  3231. // this feature and only targets that represent actual libraries (object,
  3232. // static, dynamic or bundle, excluding executables) will be used. These are
  3233. // limitations imposed by CMake use-cases - otherwise a lot of things break.
  3234. // The rest will be linked using linker flags (OTHER_LDFLAGS setting in Xcode
  3235. // project).
  3236. std::map<std::string, std::vector<cmComputeLinkInformation::Item const*>>
  3237. configItemMap;
  3238. auto addToLinkerArguments =
  3239. [&configItemMap](const std::string& configName,
  3240. cmComputeLinkInformation::Item const* libItemPtr) {
  3241. auto& linkVector = configItemMap[configName];
  3242. if (std::find_if(linkVector.begin(), linkVector.end(),
  3243. [libItemPtr](cmComputeLinkInformation::Item const* p) {
  3244. return p == libItemPtr;
  3245. }) == linkVector.end()) {
  3246. linkVector.push_back(libItemPtr);
  3247. }
  3248. };
  3249. std::vector<cmComputeLinkInformation::Item const*> linkPhaseTargetVector;
  3250. std::map<std::string, std::vector<std::string>> targetConfigMap;
  3251. using ConfigItemPair =
  3252. std::pair<std::string, cmComputeLinkInformation::Item const*>;
  3253. std::map<std::string, std::vector<ConfigItemPair>> targetItemMap;
  3254. std::map<std::string, std::vector<std::string>> targetProductNameMap;
  3255. bool useLinkPhase = false;
  3256. bool forceLinkPhase = false;
  3257. cmValue prop =
  3258. target->GetTarget()->GetProperty("XCODE_LINK_BUILD_PHASE_MODE");
  3259. if (prop) {
  3260. if (*prop == "BUILT_ONLY"_s) {
  3261. useLinkPhase = true;
  3262. } else if (*prop == "KNOWN_LOCATION"_s) {
  3263. useLinkPhase = true;
  3264. forceLinkPhase = true;
  3265. } else if (*prop != "NONE"_s) {
  3266. cmSystemTools::Error(
  3267. cmStrCat("Invalid value for XCODE_LINK_BUILD_PHASE_MODE: ", *prop));
  3268. return;
  3269. }
  3270. }
  3271. for (auto const& configName : this->CurrentConfigurationTypes) {
  3272. cmComputeLinkInformation* cli = gt->GetLinkInformation(configName);
  3273. if (!cli) {
  3274. continue;
  3275. }
  3276. for (auto const& libItem : cli->GetItems()) {
  3277. // Explicitly ignore OBJECT libraries as Xcode emulates them as static
  3278. // libraries without an artifact. Avoid exposing this to the rest of
  3279. // CMake's compilation model.
  3280. if (libItem.Target &&
  3281. libItem.Target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  3282. continue;
  3283. }
  3284. // We want to put only static libraries, dynamic libraries, frameworks
  3285. // and bundles that are built from targets that are not imported in "Link
  3286. // Binary With Libraries" build phase. Except if the target property
  3287. // XCODE_LINK_BUILD_PHASE_MODE is KNOWN_LOCATION then all imported and
  3288. // non-target libraries will be added as well.
  3289. if (useLinkPhase &&
  3290. (gt->GetType() == cmStateEnums::EXECUTABLE ||
  3291. gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
  3292. gt->GetType() == cmStateEnums::MODULE_LIBRARY) &&
  3293. ((libItem.Target &&
  3294. (!libItem.Target->IsImported() || forceLinkPhase) &&
  3295. (libItem.Target->GetType() == cmStateEnums::STATIC_LIBRARY ||
  3296. libItem.Target->GetType() == cmStateEnums::SHARED_LIBRARY ||
  3297. libItem.Target->GetType() == cmStateEnums::MODULE_LIBRARY ||
  3298. libItem.Target->GetType() == cmStateEnums::UNKNOWN_LIBRARY)) ||
  3299. (!libItem.Target &&
  3300. libItem.IsPath == cmComputeLinkInformation::ItemIsPath::Yes &&
  3301. forceLinkPhase))) {
  3302. std::string libName;
  3303. bool canUseLinkPhase = !libItem.HasFeature() ||
  3304. libItem.GetFeatureName() == "__CMAKE_LINK_FRAMEWORK"_s ||
  3305. libItem.GetFeatureName() == "FRAMEWORK"_s ||
  3306. libItem.GetFeatureName() == "__CMAKE_LINK_XCFRAMEWORK"_s ||
  3307. libItem.GetFeatureName() == "XCFRAMEWORK"_s ||
  3308. libItem.GetFeatureName() == "WEAK_FRAMEWORK"_s ||
  3309. libItem.GetFeatureName() == "WEAK_LIBRARY"_s;
  3310. if (canUseLinkPhase) {
  3311. if (libItem.Target) {
  3312. if (libItem.Target->GetType() == cmStateEnums::UNKNOWN_LIBRARY) {
  3313. canUseLinkPhase = canUseLinkPhase && forceLinkPhase;
  3314. } else {
  3315. // If a library target uses custom build output directory Xcode
  3316. // won't pick it up so we have to resort back to linker flags,
  3317. // but that's OK as long as the custom output dir is absolute
  3318. // path.
  3319. for (auto const& libConfigName :
  3320. this->CurrentConfigurationTypes) {
  3321. canUseLinkPhase = canUseLinkPhase &&
  3322. libItem.Target->UsesDefaultOutputDir(
  3323. libConfigName, cmStateEnums::RuntimeBinaryArtifact);
  3324. }
  3325. }
  3326. libName = libItem.Target->GetName();
  3327. } else {
  3328. libName = cmSystemTools::GetFilenameName(libItem.Value.Value);
  3329. // We don't want all the possible files here, just standard
  3330. // libraries
  3331. const auto libExt = cmSystemTools::GetFilenameExtension(libName);
  3332. if (!IsLinkPhaseLibraryExtension(libExt)) {
  3333. canUseLinkPhase = false;
  3334. }
  3335. }
  3336. }
  3337. if (canUseLinkPhase) {
  3338. // Add unique configuration name to target-config map for later
  3339. // checks
  3340. auto& configVector = targetConfigMap[libName];
  3341. if (std::find(configVector.begin(), configVector.end(),
  3342. configName) == configVector.end()) {
  3343. configVector.push_back(configName);
  3344. }
  3345. // Add a pair of config and item to target-item map
  3346. auto& itemVector = targetItemMap[libName];
  3347. itemVector.emplace_back(configName, &libItem);
  3348. // Add product file-name to a lib-product map
  3349. auto productName =
  3350. cmSystemTools::GetFilenameName(libItem.Value.Value);
  3351. auto& productVector = targetProductNameMap[libName];
  3352. if (std::find(productVector.begin(), productVector.end(),
  3353. productName) == productVector.end()) {
  3354. productVector.push_back(productName);
  3355. }
  3356. continue;
  3357. }
  3358. }
  3359. // Add this library item to a regular linker flag list
  3360. addToLinkerArguments(configName, &libItem);
  3361. }
  3362. }
  3363. // Go through target library map and separate libraries that are linked
  3364. // in all configurations and produce only single product, from the rest.
  3365. // Only these will be linked through "Link Binary With Libraries" build
  3366. // phase.
  3367. for (auto const& targetLibConfigs : targetConfigMap) {
  3368. // Add this library to "Link Binary With Libraries" build phase if it's
  3369. // linked in all configurations and it has only one product name
  3370. auto& itemVector = targetItemMap[targetLibConfigs.first];
  3371. auto& productVector = targetProductNameMap[targetLibConfigs.first];
  3372. if (targetLibConfigs.second == this->CurrentConfigurationTypes &&
  3373. productVector.size() == 1) {
  3374. // Add this library to "Link Binary With Libraries" list
  3375. linkPhaseTargetVector.push_back(itemVector[0].second);
  3376. } else {
  3377. for (auto const& libItem : targetItemMap[targetLibConfigs.first]) {
  3378. // Add this library item to a regular linker flag list
  3379. addToLinkerArguments(libItem.first, libItem.second);
  3380. }
  3381. }
  3382. }
  3383. // Add libraries to "Link Binary With Libraries" build phase and collect
  3384. // their search paths. Xcode does not support per-configuration linking
  3385. // in this build phase so we don't have to do this for each configuration
  3386. // separately.
  3387. std::vector<std::string> linkSearchPaths;
  3388. std::vector<std::string> frameworkSearchPaths;
  3389. std::set<std::pair<cmXCodeObject*, std::string>> linkBuildFileSet;
  3390. for (auto const& libItem : linkPhaseTargetVector) {
  3391. // Add target output directory as a library search path
  3392. std::string linkDir;
  3393. if (libItem->Target) {
  3394. linkDir = libItem->Target->GetLocationForBuild();
  3395. } else {
  3396. linkDir = libItem->Value.Value;
  3397. }
  3398. if (cmHasSuffix(libItem->GetFeatureName(), "FRAMEWORK"_s)) {
  3399. auto fwDescriptor = this->SplitFrameworkPath(
  3400. linkDir, cmGlobalGenerator::FrameworkFormat::Extended);
  3401. if (fwDescriptor && !fwDescriptor->Directory.empty()) {
  3402. linkDir = fwDescriptor->Directory;
  3403. if (std::find(frameworkSearchPaths.begin(), frameworkSearchPaths.end(),
  3404. linkDir) == frameworkSearchPaths.end()) {
  3405. frameworkSearchPaths.push_back(linkDir);
  3406. }
  3407. }
  3408. } else {
  3409. linkDir = cmSystemTools::GetParentDirectory(linkDir);
  3410. if (std::find(linkSearchPaths.begin(), linkSearchPaths.end(), linkDir) ==
  3411. linkSearchPaths.end()) {
  3412. linkSearchPaths.push_back(linkDir);
  3413. }
  3414. }
  3415. if (libItem->Target && !libItem->Target->IsImported()) {
  3416. for (auto const& configName : this->CurrentConfigurationTypes) {
  3417. target->AddDependTarget(configName, libItem->Target->GetName());
  3418. }
  3419. }
  3420. // Get the library target
  3421. auto* libTarget = FindXCodeTarget(libItem->Target);
  3422. cmXCodeObject* buildFile;
  3423. if (!libTarget) {
  3424. if (libItem->IsPath == cmComputeLinkInformation::ItemIsPath::Yes) {
  3425. // Get or create a direct file ref in the root project
  3426. auto cleanPath = libItem->Value.Value;
  3427. if (cmSystemTools::FileIsFullPath(cleanPath)) {
  3428. // Some arguments are reported as paths, but they are actually not,
  3429. // so we can't collapse them, and neither can we collapse relative
  3430. // paths
  3431. cleanPath = cmSystemTools::CollapseFullPath(cleanPath);
  3432. }
  3433. auto it = this->ExternalLibRefs.find(cleanPath);
  3434. if (it == this->ExternalLibRefs.end()) {
  3435. buildFile = CreateXCodeBuildFileFromPath(cleanPath, gt, "", nullptr);
  3436. if (!buildFile) {
  3437. // Add this library item back to a regular linker flag list
  3438. for (const auto& conf : configItemMap) {
  3439. addToLinkerArguments(conf.first, libItem);
  3440. }
  3441. continue;
  3442. }
  3443. this->ExternalLibRefs.emplace(cleanPath, buildFile);
  3444. } else {
  3445. buildFile = it->second;
  3446. }
  3447. } else {
  3448. // Add this library item back to a regular linker flag list
  3449. for (const auto& conf : configItemMap) {
  3450. addToLinkerArguments(conf.first, libItem);
  3451. }
  3452. continue;
  3453. }
  3454. } else {
  3455. // Add the target output file as a build reference for other targets
  3456. // to link against
  3457. auto* fileRefObject = libTarget->GetAttribute("productReference");
  3458. if (!fileRefObject) {
  3459. // Add this library item back to a regular linker flag list
  3460. for (const auto& conf : configItemMap) {
  3461. addToLinkerArguments(conf.first, libItem);
  3462. }
  3463. continue;
  3464. }
  3465. auto it = FileRefToBuildFileMap.find(fileRefObject);
  3466. if (it == FileRefToBuildFileMap.end()) {
  3467. buildFile = this->CreateObject(cmXCodeObject::PBXBuildFile);
  3468. buildFile->AddAttribute("fileRef", fileRefObject);
  3469. FileRefToBuildFileMap[fileRefObject] = buildFile;
  3470. } else {
  3471. buildFile = it->second;
  3472. }
  3473. }
  3474. // Add this reference to current target
  3475. auto* buildPhases = target->GetAttribute("buildPhases");
  3476. if (!buildPhases) {
  3477. cmSystemTools::Error("Missing buildPhase of target");
  3478. continue;
  3479. }
  3480. auto* frameworkBuildPhase =
  3481. buildPhases->GetObject(cmXCodeObject::PBXFrameworksBuildPhase);
  3482. if (!frameworkBuildPhase) {
  3483. cmSystemTools::Error("Missing PBXFrameworksBuildPhase of buildPhase");
  3484. continue;
  3485. }
  3486. auto* buildFiles = frameworkBuildPhase->GetAttribute("files");
  3487. if (!buildFiles) {
  3488. cmSystemTools::Error("Missing files of PBXFrameworksBuildPhase");
  3489. continue;
  3490. }
  3491. if (buildFile) {
  3492. if (cmHasPrefix(libItem->GetFeatureName(), "WEAK_"_s)) {
  3493. auto key = std::make_pair(buildFile->GetAttribute("fileRef"),
  3494. libItem->GetFeatureName());
  3495. if (linkBuildFileSet.find(key) != linkBuildFileSet.end()) {
  3496. continue;
  3497. }
  3498. linkBuildFileSet.insert(key);
  3499. cmXCodeObject* buildObject =
  3500. this->CreateObject(cmXCodeObject::PBXBuildFile);
  3501. buildObject->AddAttribute("fileRef", key.first);
  3502. // Add settings, ATTRIBUTES, Weak flag
  3503. cmXCodeObject* settings =
  3504. this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  3505. cmXCodeObject* attrs = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3506. attrs->AddObject(this->CreateString("Weak"));
  3507. settings->AddAttribute("ATTRIBUTES", attrs);
  3508. buildObject->AddAttribute("settings", settings);
  3509. buildFile = buildObject;
  3510. }
  3511. if (!buildFiles->HasObject(buildFile)) {
  3512. buildFiles->AddObject(buildFile);
  3513. }
  3514. }
  3515. }
  3516. // Loop over configuration types and set per-configuration info.
  3517. for (auto const& configName : this->CurrentConfigurationTypes) {
  3518. {
  3519. // Add object library contents as link flags.
  3520. BuildObjectListOrString libSearchPaths(this, true);
  3521. std::vector<cmSourceFile const*> objs;
  3522. gt->GetExternalObjects(objs, configName);
  3523. for (auto const* sourceFile : objs) {
  3524. if (sourceFile->GetObjectLibrary().empty()) {
  3525. continue;
  3526. }
  3527. libSearchPaths.Add(this->XCodeEscapePath(sourceFile->GetFullPath()));
  3528. }
  3529. this->AppendBuildSettingAttribute(
  3530. target, this->GetTargetLinkFlagsVar(gt), libSearchPaths.CreateList(),
  3531. configName);
  3532. }
  3533. // Compute the link library and directory information.
  3534. cmComputeLinkInformation* cli = gt->GetLinkInformation(configName);
  3535. if (!cli) {
  3536. continue;
  3537. }
  3538. // add .xcframework include paths
  3539. {
  3540. // Keep track of framework search paths we've already added or that are
  3541. // part of the set of implicit search paths. We don't want to repeat
  3542. // them and we also need to avoid hard-coding any SDK-specific paths.
  3543. // This is essential for getting device-and-simulator builds to work,
  3544. // otherwise we end up hard-coding a path to the wrong SDK for
  3545. // SDK-provided frameworks that are added by their full path.
  3546. std::set<std::string> emitted(cli->GetFrameworkPathsEmitted());
  3547. BuildObjectListOrString includePaths(this, true);
  3548. BuildObjectListOrString fwSearchPaths(this, true);
  3549. for (auto const& libItem : configItemMap[configName]) {
  3550. auto const& libName = *libItem;
  3551. if (libName.IsPath == cmComputeLinkInformation::ItemIsPath::Yes) {
  3552. auto cleanPath = libName.Value.Value;
  3553. if (cmSystemTools::FileIsFullPath(cleanPath)) {
  3554. cleanPath = cmSystemTools::CollapseFullPath(cleanPath);
  3555. }
  3556. bool isXcFramework =
  3557. cmHasSuffix(libName.GetFeatureName(), "XCFRAMEWORK"_s);
  3558. if (isXcFramework) {
  3559. auto plist = cmParseXcFrameworkPlist(
  3560. cleanPath, *this->Makefiles.front(), libName.Value.Backtrace);
  3561. if (!plist) {
  3562. return;
  3563. }
  3564. if (auto const* library = plist->SelectSuitableLibrary(
  3565. *this->Makefiles.front(), libName.Value.Backtrace)) {
  3566. auto libraryPath =
  3567. cmStrCat(cleanPath, '/', library->LibraryIdentifier, '/',
  3568. library->LibraryPath);
  3569. if (auto const fwDescriptor = this->SplitFrameworkPath(
  3570. libraryPath,
  3571. cmGlobalGenerator::FrameworkFormat::Relaxed)) {
  3572. if (!fwDescriptor->Directory.empty() &&
  3573. emitted.insert(fwDescriptor->Directory).second) {
  3574. // This is a search path we had not added before and it
  3575. // isn't an implicit search path, so we need it
  3576. fwSearchPaths.Add(
  3577. this->XCodeEscapePath(fwDescriptor->Directory));
  3578. }
  3579. } else {
  3580. if (!library->HeadersPath.empty()) {
  3581. includePaths.Add(this->XCodeEscapePath(
  3582. cmStrCat(cleanPath, '/', library->LibraryIdentifier, '/',
  3583. library->HeadersPath)));
  3584. }
  3585. }
  3586. } else {
  3587. return;
  3588. }
  3589. }
  3590. }
  3591. }
  3592. if (!includePaths.IsEmpty()) {
  3593. this->AppendBuildSettingAttribute(target, "HEADER_SEARCH_PATHS",
  3594. includePaths.CreateList(),
  3595. configName);
  3596. }
  3597. if (!fwSearchPaths.IsEmpty()) {
  3598. this->AppendBuildSettingAttribute(target, "FRAMEWORK_SEARCH_PATHS",
  3599. fwSearchPaths.CreateList(),
  3600. configName);
  3601. }
  3602. }
  3603. // Skip link information for object libraries.
  3604. if (gt->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  3605. gt->GetType() == cmStateEnums::STATIC_LIBRARY) {
  3606. continue;
  3607. }
  3608. // Add dependencies directly on library files.
  3609. for (auto const& libDep : cli->GetDepends()) {
  3610. target->AddDependLibrary(configName, libDep);
  3611. }
  3612. // add the library search paths
  3613. {
  3614. BuildObjectListOrString libSearchPaths(this, true);
  3615. std::string linkDirs;
  3616. for (auto const& libDir : cli->GetDirectories()) {
  3617. if (!libDir.empty() && libDir != "/usr/lib"_s) {
  3618. cmPolicies::PolicyStatus cmp0142 =
  3619. target->GetTarget()->GetPolicyStatusCMP0142();
  3620. if (cmp0142 == cmPolicies::OLD || cmp0142 == cmPolicies::WARN) {
  3621. libSearchPaths.Add(this->XCodeEscapePath(cmStrCat(
  3622. libDir, "/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)")));
  3623. }
  3624. libSearchPaths.Add(this->XCodeEscapePath(libDir));
  3625. }
  3626. }
  3627. // Add previously collected paths where to look for libraries
  3628. // that were added to "Link Binary With Libraries"
  3629. for (auto& libDir : linkSearchPaths) {
  3630. libSearchPaths.Add(this->XCodeEscapePath(libDir));
  3631. }
  3632. if (!libSearchPaths.IsEmpty()) {
  3633. this->AppendBuildSettingAttribute(target, "LIBRARY_SEARCH_PATHS",
  3634. libSearchPaths.CreateList(),
  3635. configName);
  3636. }
  3637. }
  3638. // add framework search paths
  3639. {
  3640. BuildObjectListOrString fwSearchPaths(this, true);
  3641. // Add previously collected paths where to look for frameworks
  3642. // that were added to "Link Binary With Libraries"
  3643. for (auto& fwDir : frameworkSearchPaths) {
  3644. fwSearchPaths.Add(this->XCodeEscapePath(fwDir));
  3645. }
  3646. if (!fwSearchPaths.IsEmpty()) {
  3647. this->AppendBuildSettingAttribute(target, "FRAMEWORK_SEARCH_PATHS",
  3648. fwSearchPaths.CreateList(),
  3649. configName);
  3650. }
  3651. }
  3652. // now add the left-over link libraries
  3653. {
  3654. // Keep track of framework search paths we've already added or that are
  3655. // part of the set of implicit search paths. We don't want to repeat
  3656. // them and we also need to avoid hard-coding any SDK-specific paths.
  3657. // This is essential for getting device-and-simulator builds to work,
  3658. // otherwise we end up hard-coding a path to the wrong SDK for
  3659. // SDK-provided frameworks that are added by their full path.
  3660. std::set<std::string> emitted(cli->GetFrameworkPathsEmitted());
  3661. BuildObjectListOrString libPaths(this, true);
  3662. BuildObjectListOrString fwSearchPaths(this, true);
  3663. for (auto const& libItem : configItemMap[configName]) {
  3664. auto const& libName = *libItem;
  3665. if (libName.IsPath == cmComputeLinkInformation::ItemIsPath::Yes) {
  3666. auto cleanPath = libName.Value.Value;
  3667. if (cmSystemTools::FileIsFullPath(cleanPath)) {
  3668. cleanPath = cmSystemTools::CollapseFullPath(cleanPath);
  3669. }
  3670. bool isXcFramework =
  3671. cmHasSuffix(libName.GetFeatureName(), "XCFRAMEWORK"_s);
  3672. bool isFramework = !isXcFramework &&
  3673. cmHasSuffix(libName.GetFeatureName(), "FRAMEWORK"_s);
  3674. if (isFramework) {
  3675. const auto fwDescriptor = this->SplitFrameworkPath(
  3676. cleanPath, cmGlobalGenerator::FrameworkFormat::Extended);
  3677. if (isFramework && !fwDescriptor->Directory.empty() &&
  3678. emitted.insert(fwDescriptor->Directory).second) {
  3679. // This is a search path we had not added before and it isn't
  3680. // an implicit search path, so we need it
  3681. fwSearchPaths.Add(
  3682. this->XCodeEscapePath(fwDescriptor->Directory));
  3683. }
  3684. if (libName.GetFeatureName() == "__CMAKE_LINK_FRAMEWORK"_s) {
  3685. // use the full path
  3686. libPaths.Add(
  3687. libName.GetFormattedItem(this->XCodeEscapePath(cleanPath))
  3688. .Value);
  3689. } else {
  3690. libPaths.Add(libName
  3691. .GetFormattedItem(this->XCodeEscapePath(
  3692. fwDescriptor->GetLinkName()))
  3693. .Value);
  3694. }
  3695. } else if (isXcFramework) {
  3696. auto plist = cmParseXcFrameworkPlist(
  3697. cleanPath, *this->Makefiles.front(), libName.Value.Backtrace);
  3698. if (!plist) {
  3699. return;
  3700. }
  3701. if (auto const* library = plist->SelectSuitableLibrary(
  3702. *this->Makefiles.front(), libName.Value.Backtrace)) {
  3703. auto libraryPath =
  3704. cmStrCat(cleanPath, '/', library->LibraryIdentifier, '/',
  3705. library->LibraryPath);
  3706. if (auto const fwDescriptor = this->SplitFrameworkPath(
  3707. libraryPath,
  3708. cmGlobalGenerator::FrameworkFormat::Relaxed)) {
  3709. libPaths.Add(cmStrCat(
  3710. "-framework ",
  3711. this->XCodeEscapePath(fwDescriptor->GetLinkName())));
  3712. } else {
  3713. libPaths.Add(
  3714. libName.GetFormattedItem(this->XCodeEscapePath(libraryPath))
  3715. .Value);
  3716. }
  3717. } else {
  3718. return;
  3719. }
  3720. } else {
  3721. libPaths.Add(
  3722. libName.GetFormattedItem(this->XCodeEscapePath(cleanPath))
  3723. .Value);
  3724. }
  3725. if ((!libName.Target || libName.Target->IsImported()) &&
  3726. (isFramework || isXcFramework ||
  3727. IsLinkPhaseLibraryExtension(cleanPath))) {
  3728. // Create file reference for embedding
  3729. auto it = this->ExternalLibRefs.find(cleanPath);
  3730. if (it == this->ExternalLibRefs.end()) {
  3731. auto* buildFile =
  3732. this->CreateXCodeBuildFileFromPath(cleanPath, gt, "", nullptr);
  3733. if (buildFile) {
  3734. this->ExternalLibRefs.emplace(cleanPath, buildFile);
  3735. }
  3736. }
  3737. }
  3738. } else if (!libName.Target ||
  3739. libName.Target->GetType() !=
  3740. cmStateEnums::INTERFACE_LIBRARY) {
  3741. libPaths.Add(libName.Value.Value);
  3742. }
  3743. if (libName.Target && !libName.Target->IsImported()) {
  3744. target->AddDependTarget(configName, libName.Target->GetName());
  3745. }
  3746. }
  3747. if (!libPaths.IsEmpty()) {
  3748. this->AppendBuildSettingAttribute(target,
  3749. this->GetTargetLinkFlagsVar(gt),
  3750. libPaths.CreateList(), configName);
  3751. }
  3752. if (!fwSearchPaths.IsEmpty()) {
  3753. this->AppendBuildSettingAttribute(target, "FRAMEWORK_SEARCH_PATHS",
  3754. fwSearchPaths.CreateList(),
  3755. configName);
  3756. }
  3757. }
  3758. }
  3759. }
  3760. void cmGlobalXCodeGenerator::AddEmbeddedObjects(
  3761. cmXCodeObject* target, const std::string& copyFilesBuildPhaseName,
  3762. const std::string& embedPropertyName, const std::string& dstSubfolderSpec,
  3763. int actionsOnByDefault, const std::string& defaultDstPath)
  3764. {
  3765. cmGeneratorTarget* gt = target->GetTarget();
  3766. if (!gt) {
  3767. cmSystemTools::Error("Error no target on xobject\n");
  3768. return;
  3769. }
  3770. if (!gt->IsInBuildSystem()) {
  3771. return;
  3772. }
  3773. bool isFrameworkTarget = gt->IsFrameworkOnApple();
  3774. bool isBundleTarget = gt->GetPropertyAsBool("MACOSX_BUNDLE");
  3775. bool isCFBundleTarget = gt->IsCFBundleOnApple();
  3776. if (!(isFrameworkTarget || isBundleTarget || isCFBundleTarget)) {
  3777. return;
  3778. }
  3779. cmValue files = gt->GetProperty(embedPropertyName);
  3780. if (!files) {
  3781. return;
  3782. }
  3783. // Create an "Embedded Frameworks" build phase
  3784. auto* copyFilesBuildPhase =
  3785. this->CreateObject(cmXCodeObject::PBXCopyFilesBuildPhase);
  3786. copyFilesBuildPhase->SetComment(copyFilesBuildPhaseName);
  3787. copyFilesBuildPhase->AddAttribute("buildActionMask",
  3788. this->CreateString("2147483647"));
  3789. copyFilesBuildPhase->AddAttribute("dstSubfolderSpec",
  3790. this->CreateString(dstSubfolderSpec));
  3791. copyFilesBuildPhase->AddAttribute(
  3792. "name", this->CreateString(copyFilesBuildPhaseName));
  3793. if (cmValue fwEmbedPath =
  3794. gt->GetProperty(cmStrCat(embedPropertyName, "_PATH"))) {
  3795. copyFilesBuildPhase->AddAttribute("dstPath",
  3796. this->CreateString(*fwEmbedPath));
  3797. } else {
  3798. copyFilesBuildPhase->AddAttribute("dstPath",
  3799. this->CreateString(defaultDstPath));
  3800. }
  3801. copyFilesBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  3802. this->CreateString("0"));
  3803. cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3804. // Collect all embedded frameworks and dylibs and add them to build phase
  3805. cmList relFiles{ *files };
  3806. for (std::string const& relFile : relFiles) {
  3807. cmXCodeObject* buildFile{ nullptr };
  3808. std::string filePath = relFile;
  3809. auto* genTarget = this->FindGeneratorTarget(relFile);
  3810. if (genTarget) {
  3811. // This is a target - get it's product path reference
  3812. auto* xcTarget = this->FindXCodeTarget(genTarget);
  3813. if (!xcTarget) {
  3814. cmSystemTools::Error(
  3815. cmStrCat("Can not find a target for ", genTarget->GetName()));
  3816. continue;
  3817. }
  3818. // Add the target output file as a build reference for other targets
  3819. // to link against
  3820. auto* fileRefObject = xcTarget->GetAttribute("productReference");
  3821. if (!fileRefObject) {
  3822. cmSystemTools::Error(cmStrCat("Target ", genTarget->GetName(),
  3823. " is missing product reference"));
  3824. continue;
  3825. }
  3826. auto it = this->FileRefToEmbedBuildFileMap.find(fileRefObject);
  3827. if (it == this->FileRefToEmbedBuildFileMap.end()) {
  3828. buildFile = this->CreateObject(cmXCodeObject::PBXBuildFile);
  3829. buildFile->AddAttribute("fileRef", fileRefObject);
  3830. this->FileRefToEmbedBuildFileMap[fileRefObject] = buildFile;
  3831. } else {
  3832. buildFile = it->second;
  3833. }
  3834. } else if (cmSystemTools::IsPathToFramework(relFile) ||
  3835. cmSystemTools::IsPathToMacOSSharedLibrary(relFile) ||
  3836. cmSystemTools::FileIsDirectory(filePath)) {
  3837. // This is a regular string path - create file reference
  3838. auto it = this->EmbeddedLibRefs.find(relFile);
  3839. if (it == this->EmbeddedLibRefs.end()) {
  3840. cmXCodeObject* fileRef =
  3841. this->CreateXCodeFileReferenceFromPath(relFile, gt, "", nullptr);
  3842. if (fileRef) {
  3843. buildFile = this->CreateObject(cmXCodeObject::PBXBuildFile);
  3844. buildFile->SetComment(fileRef->GetComment());
  3845. buildFile->AddAttribute("fileRef",
  3846. this->CreateObjectReference(fileRef));
  3847. }
  3848. if (!buildFile) {
  3849. cmSystemTools::Error(
  3850. cmStrCat("Can't create build file for ", relFile));
  3851. continue;
  3852. }
  3853. this->EmbeddedLibRefs.emplace(filePath, buildFile);
  3854. } else {
  3855. buildFile = it->second;
  3856. }
  3857. }
  3858. if (!buildFile) {
  3859. cmSystemTools::Error(cmStrCat("Can't find a build file for ", relFile));
  3860. continue;
  3861. }
  3862. // Set build file configuration
  3863. cmXCodeObject* settings =
  3864. this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  3865. cmXCodeObject* attrs = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3866. bool removeHeaders = actionsOnByDefault & RemoveHeadersOnCopyByDefault;
  3867. if (auto prop = gt->GetProperty(
  3868. cmStrCat(embedPropertyName, "_REMOVE_HEADERS_ON_COPY"))) {
  3869. removeHeaders = cmIsOn(*prop);
  3870. }
  3871. if (removeHeaders) {
  3872. attrs->AddObject(this->CreateString("RemoveHeadersOnCopy"));
  3873. }
  3874. bool codeSign = actionsOnByDefault & CodeSignOnCopyByDefault;
  3875. if (auto prop =
  3876. gt->GetProperty(cmStrCat(embedPropertyName, "_CODE_SIGN_ON_COPY"))) {
  3877. codeSign = cmIsOn(*prop);
  3878. }
  3879. if (codeSign) {
  3880. attrs->AddObject(this->CreateString("CodeSignOnCopy"));
  3881. }
  3882. settings->AddAttributeIfNotEmpty("ATTRIBUTES", attrs);
  3883. buildFile->AddAttributeIfNotEmpty("settings", settings);
  3884. if (!buildFiles->HasObject(buildFile)) {
  3885. buildFiles->AddObject(buildFile);
  3886. }
  3887. }
  3888. copyFilesBuildPhase->AddAttribute("files", buildFiles);
  3889. auto* buildPhases = target->GetAttribute("buildPhases");
  3890. // Embed-something build phases must be inserted before the post-build
  3891. // command because that command is expected to be last
  3892. buildPhases->InsertObject(buildPhases->GetObjectCount() - 1,
  3893. copyFilesBuildPhase);
  3894. }
  3895. void cmGlobalXCodeGenerator::AddEmbeddedFrameworks(cmXCodeObject* target)
  3896. {
  3897. static auto const* const dstSubfolderSpec = "10";
  3898. // Despite the name, by default Xcode uses "Embed Frameworks" build phase
  3899. // for both frameworks and dynamic libraries
  3900. this->AddEmbeddedObjects(target, "Embed Frameworks",
  3901. "XCODE_EMBED_FRAMEWORKS", dstSubfolderSpec,
  3902. NoActionOnCopyByDefault);
  3903. }
  3904. void cmGlobalXCodeGenerator::AddEmbeddedPlugIns(cmXCodeObject* target)
  3905. {
  3906. static auto const* const dstSubfolderSpec = "13";
  3907. this->AddEmbeddedObjects(target, "Embed PlugIns", "XCODE_EMBED_PLUGINS",
  3908. dstSubfolderSpec, NoActionOnCopyByDefault);
  3909. }
  3910. void cmGlobalXCodeGenerator::AddEmbeddedAppExtensions(cmXCodeObject* target)
  3911. {
  3912. static auto const* const dstSubfolderSpec = "13";
  3913. this->AddEmbeddedObjects(target, "Embed App Extensions",
  3914. "XCODE_EMBED_APP_EXTENSIONS", dstSubfolderSpec,
  3915. RemoveHeadersOnCopyByDefault);
  3916. }
  3917. void cmGlobalXCodeGenerator::AddEmbeddedExtensionKitExtensions(
  3918. cmXCodeObject* target)
  3919. {
  3920. static auto const* const dstSubfolderSpec = "16";
  3921. this->AddEmbeddedObjects(target, "Embed App Extensions",
  3922. "XCODE_EMBED_EXTENSIONKIT_EXTENSIONS",
  3923. dstSubfolderSpec, RemoveHeadersOnCopyByDefault,
  3924. "$(EXTENSIONS_FOLDER_PATH)");
  3925. }
  3926. void cmGlobalXCodeGenerator::AddEmbeddedResources(cmXCodeObject* target)
  3927. {
  3928. static const auto dstSubfolderSpec = "7";
  3929. this->AddEmbeddedObjects(target, "Embed Resources", "XCODE_EMBED_RESOURCES",
  3930. dstSubfolderSpec, NoActionOnCopyByDefault);
  3931. }
  3932. void cmGlobalXCodeGenerator::AddEmbeddedXPCServices(cmXCodeObject* target)
  3933. {
  3934. static const auto dstSubfolderSpec = "16";
  3935. this->AddEmbeddedObjects(
  3936. target, "Embed XPC Services", "XCODE_EMBED_XPC_SERVICES", dstSubfolderSpec,
  3937. NoActionOnCopyByDefault, "$(CONTENTS_FOLDER_PATH)/XPCServices");
  3938. }
  3939. bool cmGlobalXCodeGenerator::CreateGroups(
  3940. std::vector<cmLocalGenerator*>& generators)
  3941. {
  3942. for (auto& generator : generators) {
  3943. cmMakefile* mf = generator->GetMakefile();
  3944. std::vector<cmSourceGroup> sourceGroups = mf->GetSourceGroups();
  3945. for (const auto& gtgt : generator->GetGeneratorTargets()) {
  3946. // Same skipping logic here as in CreateXCodeTargets so that we do not
  3947. // end up with (empty anyhow) ZERO_CHECK, install, or test source
  3948. // groups:
  3949. //
  3950. if (!gtgt->IsInBuildSystem() ||
  3951. gtgt->GetType() == cmStateEnums::GLOBAL_TARGET ||
  3952. gtgt->GetName() == CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
  3953. continue;
  3954. }
  3955. auto addSourceToGroup = [this, mf, &gtgt,
  3956. &sourceGroups](std::string const& source) {
  3957. cmSourceGroup* sourceGroup = mf->FindSourceGroup(source, sourceGroups);
  3958. cmXCodeObject* pbxgroup =
  3959. this->CreateOrGetPBXGroup(gtgt.get(), sourceGroup);
  3960. std::string key = GetGroupMapKeyFromPath(gtgt.get(), source);
  3961. this->GroupMap[key] = pbxgroup;
  3962. };
  3963. // Put cmSourceFile instances in proper groups:
  3964. for (auto const& si : gtgt->GetAllConfigSources()) {
  3965. cmSourceFile const* sf = si.Source;
  3966. if (!sf->GetObjectLibrary().empty()) {
  3967. // Object library files go on the link line instead.
  3968. continue;
  3969. }
  3970. addSourceToGroup(sf->GetFullPath());
  3971. }
  3972. // Add CMakeLists.txt file for user convenience.
  3973. {
  3974. std::string listfile =
  3975. cmStrCat(gtgt->GetLocalGenerator()->GetCurrentSourceDirectory(),
  3976. "/CMakeLists.txt");
  3977. cmSourceFile* sf = gtgt->Makefile->GetOrCreateSource(
  3978. listfile, false, cmSourceFileLocationKind::Known);
  3979. addSourceToGroup(sf->ResolveFullPath());
  3980. }
  3981. // Add the Info.plist we are about to generate for an App Bundle.
  3982. if (gtgt->GetPropertyAsBool("MACOSX_BUNDLE")) {
  3983. std::string plist = this->ComputeInfoPListLocation(gtgt.get());
  3984. cmSourceFile* sf = gtgt->Makefile->GetOrCreateSource(
  3985. plist, true, cmSourceFileLocationKind::Known);
  3986. addSourceToGroup(sf->ResolveFullPath());
  3987. }
  3988. }
  3989. }
  3990. return true;
  3991. }
  3992. cmXCodeObject* cmGlobalXCodeGenerator::CreatePBXGroup(cmXCodeObject* parent,
  3993. const std::string& name)
  3994. {
  3995. cmXCodeObject* parentChildren = nullptr;
  3996. if (parent) {
  3997. parentChildren = parent->GetAttribute("children");
  3998. }
  3999. cmXCodeObject* group = this->CreateObject(cmXCodeObject::PBXGroup);
  4000. cmXCodeObject* groupChildren =
  4001. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4002. group->AddAttribute("name", this->CreateString(name));
  4003. group->AddAttribute("children", groupChildren);
  4004. group->AddAttribute("sourceTree", this->CreateString("<group>"));
  4005. if (parentChildren) {
  4006. parentChildren->AddObject(group);
  4007. }
  4008. return group;
  4009. }
  4010. cmXCodeObject* cmGlobalXCodeGenerator::CreateOrGetPBXGroup(
  4011. cmGeneratorTarget* gtgt, cmSourceGroup* sg)
  4012. {
  4013. std::string s;
  4014. std::string target;
  4015. const std::string targetFolder = gtgt->GetEffectiveFolderName();
  4016. if (!targetFolder.empty()) {
  4017. target = cmStrCat(targetFolder, '/');
  4018. }
  4019. target += gtgt->GetName();
  4020. s = cmStrCat(target, '/', sg->GetFullName());
  4021. auto it = this->GroupNameMap.find(s);
  4022. if (it != this->GroupNameMap.end()) {
  4023. return it->second;
  4024. }
  4025. it = this->TargetGroup.find(target);
  4026. cmXCodeObject* tgroup = nullptr;
  4027. if (it != this->TargetGroup.end()) {
  4028. tgroup = it->second;
  4029. } else {
  4030. std::vector<std::string> tgt_folders = cmTokenize(target, "/");
  4031. std::string curr_tgt_folder;
  4032. for (std::vector<std::string>::size_type i = 0; i < tgt_folders.size();
  4033. i++) {
  4034. if (i != 0) {
  4035. curr_tgt_folder += '/';
  4036. }
  4037. curr_tgt_folder += tgt_folders[i];
  4038. it = this->TargetGroup.find(curr_tgt_folder);
  4039. if (it != this->TargetGroup.end()) {
  4040. tgroup = it->second;
  4041. continue;
  4042. }
  4043. tgroup = this->CreatePBXGroup(tgroup, tgt_folders[i]);
  4044. this->TargetGroup[curr_tgt_folder] = tgroup;
  4045. if (i == 0) {
  4046. this->MainGroupChildren->AddObject(tgroup);
  4047. }
  4048. }
  4049. }
  4050. this->TargetGroup[target] = tgroup;
  4051. // If it's the default source group (empty name) then put the source file
  4052. // directly in the tgroup...
  4053. //
  4054. if (sg->GetFullName().empty()) {
  4055. this->GroupNameMap[s] = tgroup;
  4056. return tgroup;
  4057. }
  4058. // It's a recursive folder structure, let's find the real parent group
  4059. if (sg->GetFullName() != sg->GetName()) {
  4060. std::string curr_folder = cmStrCat(target, '/');
  4061. for (auto const& folder : cmTokenize(sg->GetFullName(), "\\")) {
  4062. curr_folder += folder;
  4063. auto const i_folder = this->GroupNameMap.find(curr_folder);
  4064. // Create new folder
  4065. if (i_folder == this->GroupNameMap.end()) {
  4066. cmXCodeObject* group = this->CreatePBXGroup(tgroup, folder);
  4067. this->GroupNameMap[curr_folder] = group;
  4068. tgroup = group;
  4069. } else {
  4070. tgroup = i_folder->second;
  4071. }
  4072. curr_folder += '\\';
  4073. }
  4074. return tgroup;
  4075. }
  4076. cmXCodeObject* group = this->CreatePBXGroup(tgroup, sg->GetName());
  4077. this->GroupNameMap[s] = group;
  4078. return group;
  4079. }
  4080. bool cmGlobalXCodeGenerator::CreateXCodeObjects(
  4081. cmLocalGenerator* root, std::vector<cmLocalGenerator*>& generators)
  4082. {
  4083. this->ClearXCodeObjects();
  4084. this->RootObject = nullptr;
  4085. this->MainGroupChildren = nullptr;
  4086. this->FrameworkGroup = nullptr;
  4087. cmXCodeObject* group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  4088. group->AddAttribute("COPY_PHASE_STRIP", this->CreateString("NO"));
  4089. cmXCodeObject* listObjs = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4090. for (const std::string& CurrentConfigurationType :
  4091. this->CurrentConfigurationTypes) {
  4092. cmXCodeObject* buildStyle =
  4093. this->CreateObject(cmXCodeObject::PBXBuildStyle);
  4094. const std::string& name = CurrentConfigurationType;
  4095. buildStyle->AddAttribute("name", this->CreateString(name));
  4096. buildStyle->SetComment(name);
  4097. cmXCodeObject* sgroup = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  4098. sgroup->AddAttribute("COPY_PHASE_STRIP", this->CreateString("NO"));
  4099. buildStyle->AddAttribute("buildSettings", sgroup);
  4100. listObjs->AddObject(buildStyle);
  4101. }
  4102. cmXCodeObject* mainGroup = this->CreateObject(cmXCodeObject::PBXGroup);
  4103. this->MainGroupChildren = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4104. mainGroup->AddAttribute("children", this->MainGroupChildren);
  4105. mainGroup->AddAttribute("sourceTree", this->CreateString("<group>"));
  4106. // now create the cmake groups
  4107. if (!this->CreateGroups(generators)) {
  4108. return false;
  4109. }
  4110. cmXCodeObject* productGroup = this->CreateObject(cmXCodeObject::PBXGroup);
  4111. productGroup->AddAttribute("name", this->CreateString("Products"));
  4112. productGroup->AddAttribute("sourceTree", this->CreateString("<group>"));
  4113. cmXCodeObject* productGroupChildren =
  4114. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4115. productGroup->AddAttribute("children", productGroupChildren);
  4116. this->MainGroupChildren->AddObject(productGroup);
  4117. this->FrameworkGroup = this->CreateObject(cmXCodeObject::PBXGroup);
  4118. this->FrameworkGroup->AddAttribute("name", this->CreateString("Frameworks"));
  4119. this->FrameworkGroup->AddAttribute("sourceTree",
  4120. this->CreateString("<group>"));
  4121. cmXCodeObject* frameworkGroupChildren =
  4122. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4123. this->FrameworkGroup->AddAttribute("children", frameworkGroupChildren);
  4124. this->MainGroupChildren->AddObject(this->FrameworkGroup);
  4125. this->ResourcesGroup = this->CreateObject(cmXCodeObject::PBXGroup);
  4126. this->ResourcesGroup->AddAttribute("name", this->CreateString("Resources"));
  4127. this->ResourcesGroup->AddAttribute("sourceTree",
  4128. this->CreateString("<group>"));
  4129. cmXCodeObject* ResourcesGroupChildren =
  4130. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4131. this->ResourcesGroup->AddAttribute("children", ResourcesGroupChildren);
  4132. this->MainGroupChildren->AddObject(this->ResourcesGroup);
  4133. this->RootObject = this->CreateObject(cmXCodeObject::PBXProject);
  4134. this->RootObject->SetComment("Project object");
  4135. std::string project_id = cmStrCat("PROJECT_", root->GetProjectName());
  4136. this->RootObject->SetId(
  4137. this->GetOrCreateId(project_id, this->RootObject->GetId()));
  4138. group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  4139. this->RootObject->AddAttribute("mainGroup",
  4140. this->CreateObjectReference(mainGroup));
  4141. this->RootObject->AddAttribute("buildSettings", group);
  4142. this->RootObject->AddAttribute("buildStyles", listObjs);
  4143. this->RootObject->AddAttribute("hasScannedForEncodings",
  4144. this->CreateString("0"));
  4145. group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  4146. group->AddAttribute("BuildIndependentTargetsInParallel",
  4147. this->CreateString("YES"));
  4148. std::ostringstream v;
  4149. v << std::setfill('0') << std::setw(4) << XcodeVersion * 10;
  4150. group->AddAttribute("LastUpgradeCheck", this->CreateString(v.str()));
  4151. this->RootObject->AddAttribute("attributes", group);
  4152. this->RootObject->AddAttribute("compatibilityVersion",
  4153. this->CreateString("Xcode 3.2"));
  4154. // Point Xcode at the top of the source tree.
  4155. {
  4156. std::string pdir =
  4157. this->RelativeToBinary(root->GetCurrentSourceDirectory());
  4158. this->RootObject->AddAttribute("projectDirPath", this->CreateString(pdir));
  4159. this->RootObject->AddAttribute("projectRoot", this->CreateString(""));
  4160. }
  4161. cmXCodeObject* configlist =
  4162. this->CreateObject(cmXCodeObject::XCConfigurationList);
  4163. cmXCodeObject* buildConfigurations =
  4164. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4165. using Configs = std::vector<std::pair<std::string, cmXCodeObject*>>;
  4166. Configs configs;
  4167. std::string defaultConfigName;
  4168. for (const auto& name : this->CurrentConfigurationTypes) {
  4169. if (defaultConfigName.empty()) {
  4170. defaultConfigName = name;
  4171. }
  4172. cmXCodeObject* config =
  4173. this->CreateObject(cmXCodeObject::XCBuildConfiguration);
  4174. config->AddAttribute("name", this->CreateString(name));
  4175. configs.emplace_back(name, config);
  4176. }
  4177. if (defaultConfigName.empty()) {
  4178. defaultConfigName = "Debug";
  4179. }
  4180. for (auto& config : configs) {
  4181. buildConfigurations->AddObject(config.second);
  4182. }
  4183. configlist->AddAttribute("buildConfigurations", buildConfigurations);
  4184. std::string comment = cmStrCat("Build configuration list for PBXProject \"",
  4185. this->CurrentProject, '"');
  4186. configlist->SetComment(comment);
  4187. configlist->AddAttribute("defaultConfigurationIsVisible",
  4188. this->CreateString("0"));
  4189. configlist->AddAttribute("defaultConfigurationName",
  4190. this->CreateString(defaultConfigName));
  4191. cmXCodeObject* buildSettings =
  4192. this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  4193. cmValue sysroot = this->CurrentMakefile->GetDefinition("CMAKE_OSX_SYSROOT");
  4194. cmValue deploymentTarget =
  4195. this->CurrentMakefile->GetDefinition("CMAKE_OSX_DEPLOYMENT_TARGET");
  4196. if (sysroot) {
  4197. buildSettings->AddAttribute("SDKROOT", this->CreateString(*sysroot));
  4198. }
  4199. // recompute this as it may have been changed since enable language
  4200. this->ComputeArchitectures(this->CurrentMakefile);
  4201. std::string const archs = cmJoin(this->Architectures, " ");
  4202. if (archs.empty()) {
  4203. // Tell Xcode to use NATIVE_ARCH instead of ARCHS.
  4204. buildSettings->AddAttribute("ONLY_ACTIVE_ARCH", this->CreateString("YES"));
  4205. // When targeting macOS, use only the host architecture.
  4206. if (this->SystemName == "Darwin"_s &&
  4207. (!cmNonempty(sysroot) ||
  4208. cmSystemTools::LowerCase(*sysroot).find("macos") !=
  4209. std::string::npos)) {
  4210. buildSettings->AddAttribute("ARCHS",
  4211. this->CreateString("$(NATIVE_ARCH_ACTUAL)"));
  4212. }
  4213. } else {
  4214. // Tell Xcode to use ARCHS (ONLY_ACTIVE_ARCH defaults to NO).
  4215. buildSettings->AddAttribute("ARCHS", this->CreateString(archs));
  4216. }
  4217. if (cmNonempty(deploymentTarget)) {
  4218. buildSettings->AddAttribute(GetDeploymentPlatform(root->GetMakefile()),
  4219. this->CreateString(*deploymentTarget));
  4220. }
  4221. if (!this->GeneratorToolset.empty()) {
  4222. buildSettings->AddAttribute("GCC_VERSION",
  4223. this->CreateString(this->GeneratorToolset));
  4224. }
  4225. if (this->GetLanguageEnabled("Swift")) {
  4226. std::string swiftVersion;
  4227. if (cmValue vers = this->CurrentMakefile->GetDefinition(
  4228. "CMAKE_Swift_LANGUAGE_VERSION")) {
  4229. swiftVersion = *vers;
  4230. } else if (this->XcodeVersion >= 102) {
  4231. swiftVersion = "4.0";
  4232. } else if (this->XcodeVersion >= 83) {
  4233. swiftVersion = "3.0";
  4234. } else {
  4235. swiftVersion = "2.3";
  4236. }
  4237. buildSettings->AddAttribute("SWIFT_VERSION",
  4238. this->CreateString(swiftVersion));
  4239. }
  4240. std::string const symroot = this->GetSymrootDir();
  4241. buildSettings->AddAttribute("SYMROOT", this->CreateString(symroot));
  4242. // Inside a try_compile project, do not require signing on any platform.
  4243. if (this->CMakeInstance->GetIsInTryCompile()) {
  4244. buildSettings->AddAttribute("CODE_SIGNING_ALLOWED",
  4245. this->CreateString("NO"));
  4246. }
  4247. // This code supports the OLD behavior of CMP0157. We should be able to
  4248. // remove computing the debug configuration set once the old behavior is
  4249. // removed.
  4250. auto debugConfigs = this->GetCMakeInstance()->GetDebugConfigs();
  4251. std::set<std::string> debugConfigSet(debugConfigs.begin(),
  4252. debugConfigs.end());
  4253. for (auto& config : configs) {
  4254. CreateGlobalXCConfigSettings(root, config.second, config.first);
  4255. cmXCodeObject* buildSettingsForCfg = this->CreateFlatClone(buildSettings);
  4256. // Supports the OLD behavior of CMP0157. CMP0157 OLD behavior globally set
  4257. // wholemodule compilation for all non-debug configurations, for all
  4258. // targets.
  4259. if (this->CurrentMakefile
  4260. ->GetDefinition("CMAKE_Swift_COMPILATION_MODE_DEFAULT")
  4261. .IsEmpty()) {
  4262. if (debugConfigSet.count(cmSystemTools::UpperCase(config.first)) == 0) {
  4263. buildSettingsForCfg->AddAttribute("SWIFT_COMPILATION_MODE",
  4264. this->CreateString("wholemodule"));
  4265. }
  4266. }
  4267. // Put this last so it can override existing settings
  4268. // Convert "CMAKE_XCODE_ATTRIBUTE_*" variables directly.
  4269. for (const auto& var : this->CurrentMakefile->GetDefinitions()) {
  4270. if (cmHasLiteralPrefix(var, "CMAKE_XCODE_ATTRIBUTE_")) {
  4271. std::string attribute = var.substr(22);
  4272. this->FilterConfigurationAttribute(config.first, attribute);
  4273. if (!attribute.empty()) {
  4274. std::string processed = cmGeneratorExpression::Evaluate(
  4275. this->CurrentMakefile->GetSafeDefinition(var),
  4276. this->CurrentLocalGenerator, config.first);
  4277. buildSettingsForCfg->AddAttribute(attribute,
  4278. this->CreateString(processed));
  4279. }
  4280. }
  4281. }
  4282. // store per-config buildSettings into configuration object
  4283. config.second->AddAttribute("buildSettings", buildSettingsForCfg);
  4284. }
  4285. this->RootObject->AddAttribute("buildConfigurationList",
  4286. this->CreateObjectReference(configlist));
  4287. std::vector<cmXCodeObject*> targets;
  4288. for (auto& generator : generators) {
  4289. if (!this->CreateXCodeTargets(generator, targets)) {
  4290. return false;
  4291. }
  4292. for (auto const& ccRoot : this->CustomCommandRoots) {
  4293. if (ccRoot.second.size() > 1) {
  4294. std::string e = "The custom command ";
  4295. std::vector<std::string> const& outputs =
  4296. ccRoot.first->GetCustomCommand()->GetOutputs();
  4297. if (!outputs.empty()) {
  4298. e = cmStrCat(e, "generating\n ", outputs[0]);
  4299. } else {
  4300. e = cmStrCat(e, "driven by\n ", ccRoot.first->GetFullPath());
  4301. }
  4302. e = cmStrCat(e, "\nis attached to multiple targets:");
  4303. for (cmGeneratorTarget const* gt : ccRoot.second) {
  4304. e = cmStrCat(e, "\n ", gt->GetName());
  4305. }
  4306. e = cmStrCat(
  4307. e,
  4308. "\nbut none of these is a common dependency of the other(s). "
  4309. "This is not allowed by the Xcode \"new build system\".");
  4310. generator->IssueMessage(MessageType::FATAL_ERROR, e);
  4311. return false;
  4312. }
  4313. }
  4314. this->CustomCommandRoots.clear();
  4315. }
  4316. // loop over all targets and add link and depend info
  4317. for (auto* t : targets) {
  4318. this->AddDependAndLinkInformation(t);
  4319. this->AddEmbeddedFrameworks(t);
  4320. this->AddEmbeddedPlugIns(t);
  4321. this->AddEmbeddedAppExtensions(t);
  4322. this->AddEmbeddedExtensionKitExtensions(t);
  4323. this->AddEmbeddedResources(t);
  4324. this->AddEmbeddedXPCServices(t);
  4325. // Inherit project-wide values for any target-specific search paths.
  4326. this->InheritBuildSettingAttribute(t, "HEADER_SEARCH_PATHS");
  4327. this->InheritBuildSettingAttribute(t, "SYSTEM_HEADER_SEARCH_PATHS");
  4328. this->InheritBuildSettingAttribute(t, "FRAMEWORK_SEARCH_PATHS");
  4329. this->InheritBuildSettingAttribute(t, "SYSTEM_FRAMEWORK_SEARCH_PATHS");
  4330. this->InheritBuildSettingAttribute(t, "LIBRARY_SEARCH_PATHS");
  4331. this->InheritBuildSettingAttribute(t, "LD_RUNPATH_SEARCH_PATHS");
  4332. this->InheritBuildSettingAttribute(t, "GCC_PREPROCESSOR_DEFINITIONS");
  4333. this->InheritBuildSettingAttribute(t, "OTHER_CFLAGS");
  4334. this->InheritBuildSettingAttribute(t, "OTHER_LDFLAGS");
  4335. this->InheritBuildSettingAttribute(t, "OTHER_SWIFT_FLAGS");
  4336. this->InheritBuildSettingAttribute(t,
  4337. "SWIFT_ACTIVE_COMPILATION_CONDITIONS");
  4338. }
  4339. if (this->XcodeBuildSystem == BuildSystem::One) {
  4340. this->CreateXCodeDependHackMakefile(targets);
  4341. }
  4342. // now add all targets to the root object
  4343. cmXCodeObject* allTargets = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4344. for (auto* t : targets) {
  4345. allTargets->AddObject(t);
  4346. cmXCodeObject* productRef = t->GetAttribute("productReference");
  4347. if (productRef) {
  4348. productGroupChildren->AddObject(productRef->GetObject());
  4349. }
  4350. }
  4351. this->RootObject->AddAttribute("targets", allTargets);
  4352. return true;
  4353. }
  4354. std::string cmGlobalXCodeGenerator::GetSymrootDir() const
  4355. {
  4356. return cmStrCat(this->CMakeInstance->GetHomeOutputDirectory(), "/build");
  4357. }
  4358. std::string cmGlobalXCodeGenerator::GetTargetTempDir(
  4359. cmGeneratorTarget const* gt, std::string const& configName) const
  4360. {
  4361. // Use a path inside the SYMROOT.
  4362. return cmStrCat(this->GetSymrootDir(), '/', gt->GetName(), ".build/",
  4363. configName);
  4364. }
  4365. void cmGlobalXCodeGenerator::ComputeArchitectures(cmMakefile* mf)
  4366. {
  4367. this->Architectures.clear();
  4368. cmList::append(this->Architectures,
  4369. mf->GetDefinition("CMAKE_OSX_ARCHITECTURES"));
  4370. if (this->Architectures.empty()) {
  4371. cmList::append(this->Architectures,
  4372. mf->GetDefinition("_CMAKE_APPLE_ARCHS_DEFAULT"));
  4373. }
  4374. if (this->Architectures.empty()) {
  4375. // With no ARCHS we use ONLY_ACTIVE_ARCH and possibly a
  4376. // platform-specific default ARCHS placeholder value.
  4377. // Look up the arch that Xcode chooses in this case.
  4378. if (cmValue arch = mf->GetDefinition("CMAKE_XCODE_ARCHS")) {
  4379. this->ObjectDirArchDefault = *arch;
  4380. // We expect only one arch but choose the first just in case.
  4381. std::string::size_type pos = this->ObjectDirArchDefault.find(';');
  4382. if (pos != std::string::npos) {
  4383. this->ObjectDirArchDefault = this->ObjectDirArchDefault.substr(0, pos);
  4384. }
  4385. }
  4386. }
  4387. this->ComputeObjectDirArch(mf);
  4388. }
  4389. void cmGlobalXCodeGenerator::ComputeObjectDirArch(cmMakefile* mf)
  4390. {
  4391. if (this->Architectures.size() > 1 || this->UseEffectivePlatformName(mf)) {
  4392. this->ObjectDirArch = "$(CURRENT_ARCH)";
  4393. } else if (!this->Architectures.empty()) {
  4394. this->ObjectDirArch = this->Architectures[0];
  4395. } else {
  4396. this->ObjectDirArch = this->ObjectDirArchDefault;
  4397. }
  4398. }
  4399. void cmGlobalXCodeGenerator::CreateXCodeDependHackMakefile(
  4400. std::vector<cmXCodeObject*>& targets)
  4401. {
  4402. cmGeneratedFileStream makefileStream(this->CurrentXCodeHackMakefile);
  4403. if (!makefileStream) {
  4404. cmSystemTools::Error(
  4405. cmStrCat("Could not create ", this->CurrentXCodeHackMakefile));
  4406. return;
  4407. }
  4408. makefileStream.SetCopyIfDifferent(true);
  4409. // one more pass for external depend information not handled
  4410. // correctly by xcode
  4411. /* clang-format off */
  4412. makefileStream << "# DO NOT EDIT\n"
  4413. "# This makefile makes sure all linkable targets are\n"
  4414. "# up-to-date with anything they link to\n"
  4415. "default:\n"
  4416. "\techo \"Do not invoke directly\"\n"
  4417. "\n";
  4418. /* clang-format on */
  4419. std::set<std::string> dummyRules;
  4420. // Write rules to help Xcode relink things at the right time.
  4421. /* clang-format off */
  4422. makefileStream <<
  4423. "# Rules to remove targets that are older than anything to which they\n"
  4424. "# link. This forces Xcode to relink the targets from scratch. It\n"
  4425. "# does not seem to check these dependencies itself.\n";
  4426. /* clang-format on */
  4427. for (const auto& configName : this->CurrentConfigurationTypes) {
  4428. for (auto* target : targets) {
  4429. cmGeneratorTarget* gt = target->GetTarget();
  4430. if (gt->GetType() == cmStateEnums::EXECUTABLE ||
  4431. gt->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  4432. gt->GetType() == cmStateEnums::STATIC_LIBRARY ||
  4433. gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4434. gt->GetType() == cmStateEnums::MODULE_LIBRARY) {
  4435. // Declare an entry point for the target post-build phase.
  4436. makefileStream << this->PostBuildMakeTarget(gt->GetName(), configName)
  4437. << ":\n";
  4438. }
  4439. if (gt->GetType() == cmStateEnums::EXECUTABLE ||
  4440. gt->GetType() == cmStateEnums::STATIC_LIBRARY ||
  4441. gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4442. gt->GetType() == cmStateEnums::MODULE_LIBRARY) {
  4443. std::string tfull = gt->GetFullPath(configName);
  4444. std::string trel = this->ConvertToRelativeForMake(tfull);
  4445. // Add this target to the post-build phases of its dependencies.
  4446. auto const y = target->GetDependTargets().find(configName);
  4447. if (y != target->GetDependTargets().end()) {
  4448. for (auto const& deptgt : y->second) {
  4449. makefileStream << this->PostBuildMakeTarget(deptgt, configName)
  4450. << ": " << trel << '\n';
  4451. }
  4452. }
  4453. std::vector<cmGeneratorTarget*> objlibs;
  4454. gt->GetObjectLibrariesCMP0026(objlibs);
  4455. for (auto* objLib : objlibs) {
  4456. makefileStream << this->PostBuildMakeTarget(objLib->GetName(),
  4457. configName)
  4458. << ": " << trel << '\n';
  4459. }
  4460. // Create a rule for this target.
  4461. makefileStream << trel << ':';
  4462. // List dependencies if any exist.
  4463. auto const x = target->GetDependLibraries().find(configName);
  4464. if (x != target->GetDependLibraries().end()) {
  4465. for (auto const& deplib : x->second) {
  4466. std::string file = this->ConvertToRelativeForMake(deplib);
  4467. makefileStream << "\\\n\t" << file;
  4468. dummyRules.insert(file);
  4469. }
  4470. }
  4471. for (auto* objLib : objlibs) {
  4472. const std::string objLibName = objLib->GetName();
  4473. std::string d = cmStrCat(this->GetTargetTempDir(gt, configName),
  4474. "/lib", objLibName, ".a");
  4475. std::string dependency = this->ConvertToRelativeForMake(d);
  4476. makefileStream << "\\\n\t" << dependency;
  4477. dummyRules.insert(dependency);
  4478. }
  4479. // Write the action to remove the target if it is out of date.
  4480. makefileStream << "\n"
  4481. "\t/bin/rm -f "
  4482. << this->ConvertToRelativeForMake(tfull) << '\n';
  4483. // if building for more than one architecture
  4484. // then remove those executables as well
  4485. if (this->Architectures.size() > 1) {
  4486. std::string universal =
  4487. cmStrCat(this->GetTargetTempDir(gt, configName), "/$(OBJDIR)/");
  4488. for (const auto& architecture : this->Architectures) {
  4489. std::string universalFile = cmStrCat(universal, architecture, '/',
  4490. gt->GetFullName(configName));
  4491. makefileStream << "\t/bin/rm -f "
  4492. << this->ConvertToRelativeForMake(universalFile)
  4493. << '\n';
  4494. }
  4495. }
  4496. makefileStream << "\n\n";
  4497. }
  4498. }
  4499. }
  4500. makefileStream << "\n\n"
  4501. "# For each target create a dummy rule"
  4502. "so the target does not have to exist\n";
  4503. for (auto const& dummyRule : dummyRules) {
  4504. makefileStream << dummyRule << ":\n";
  4505. }
  4506. }
  4507. void cmGlobalXCodeGenerator::OutputXCodeProject(
  4508. cmLocalGenerator* root, std::vector<cmLocalGenerator*>& generators)
  4509. {
  4510. if (generators.empty()) {
  4511. return;
  4512. }
  4513. if (!this->CreateXCodeObjects(root, generators)) {
  4514. return;
  4515. }
  4516. std::string xcodeDir = cmStrCat(root->GetCurrentBinaryDirectory(), '/',
  4517. root->GetProjectName(), ".xcodeproj");
  4518. cmSystemTools::MakeDirectory(xcodeDir);
  4519. std::string xcodeProjFile = cmStrCat(xcodeDir, "/project.pbxproj");
  4520. cmGeneratedFileStream fout(xcodeProjFile);
  4521. fout.SetCopyIfDifferent(true);
  4522. if (!fout) {
  4523. return;
  4524. }
  4525. this->WriteXCodePBXProj(fout, root, generators);
  4526. bool hasGeneratedSchemes = this->OutputXCodeSharedSchemes(xcodeDir, root);
  4527. this->OutputXCodeWorkspaceSettings(xcodeDir, hasGeneratedSchemes);
  4528. this->ClearXCodeObjects();
  4529. // Since this call may have created new cache entries, save the cache:
  4530. //
  4531. root->GetMakefile()->GetCMakeInstance()->SaveCache(
  4532. root->GetBinaryDirectory());
  4533. }
  4534. bool cmGlobalXCodeGenerator::OutputXCodeSharedSchemes(
  4535. const std::string& xcProjDir, cmLocalGenerator* root)
  4536. {
  4537. // collect all tests for the targets
  4538. std::map<std::string, cmXCodeScheme::TestObjects> testables;
  4539. for (const auto& obj : this->XCodeObjects) {
  4540. if (obj->GetType() != cmXCodeObject::OBJECT ||
  4541. obj->GetIsA() != cmXCodeObject::PBXNativeTarget) {
  4542. continue;
  4543. }
  4544. if (!obj->GetTarget()->IsXCTestOnApple()) {
  4545. continue;
  4546. }
  4547. cmValue testee = obj->GetTarget()->GetProperty("XCTEST_TESTEE");
  4548. if (!testee) {
  4549. continue;
  4550. }
  4551. testables[*testee].push_back(obj.get());
  4552. }
  4553. // generate scheme
  4554. bool ret = false;
  4555. // Since the lowest available Xcode version for testing was 6.4,
  4556. // I'm setting this as a limit then
  4557. if (this->XcodeVersion >= 64) {
  4558. for (const auto& obj : this->XCodeObjects) {
  4559. if (obj->GetType() == cmXCodeObject::OBJECT &&
  4560. (obj->GetIsA() == cmXCodeObject::PBXNativeTarget ||
  4561. obj->GetIsA() == cmXCodeObject::PBXAggregateTarget) &&
  4562. (root->GetMakefile()->GetCMakeInstance()->GetIsInTryCompile() ||
  4563. obj->GetTarget()->GetPropertyAsBool("XCODE_GENERATE_SCHEME"))) {
  4564. const std::string& targetName = obj->GetTarget()->GetName();
  4565. cmXCodeScheme schm(root, obj.get(), testables[targetName],
  4566. this->CurrentConfigurationTypes,
  4567. this->XcodeVersion);
  4568. schm.WriteXCodeSharedScheme(xcProjDir,
  4569. this->RelativeToSource(xcProjDir));
  4570. ret = true;
  4571. }
  4572. }
  4573. }
  4574. return ret;
  4575. }
  4576. void cmGlobalXCodeGenerator::OutputXCodeWorkspaceSettings(
  4577. const std::string& xcProjDir, bool hasGeneratedSchemes)
  4578. {
  4579. std::string xcodeSharedDataDir =
  4580. cmStrCat(xcProjDir, "/project.xcworkspace/xcshareddata");
  4581. cmSystemTools::MakeDirectory(xcodeSharedDataDir);
  4582. std::string workspaceSettingsFile =
  4583. cmStrCat(xcodeSharedDataDir, "/WorkspaceSettings.xcsettings");
  4584. cmGeneratedFileStream fout(workspaceSettingsFile);
  4585. fout.SetCopyIfDifferent(true);
  4586. if (!fout) {
  4587. return;
  4588. }
  4589. cmXMLWriter xout(fout);
  4590. xout.StartDocument();
  4591. xout.Doctype("plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\""
  4592. "\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"");
  4593. xout.StartElement("plist");
  4594. xout.Attribute("version", "1.0");
  4595. xout.StartElement("dict");
  4596. if (this->XcodeVersion >= 100) {
  4597. xout.Element("key", "BuildSystemType");
  4598. switch (this->XcodeBuildSystem) {
  4599. case BuildSystem::One:
  4600. xout.Element("string", "Original");
  4601. if (this->XcodeVersion >= 130) {
  4602. xout.Element("key", "DisableBuildSystemDeprecationDiagnostic");
  4603. } else {
  4604. xout.Element("key", "DisableBuildSystemDeprecationWarning");
  4605. }
  4606. xout.Element("true");
  4607. break;
  4608. case BuildSystem::Twelve:
  4609. xout.Element("string", "Latest");
  4610. break;
  4611. }
  4612. }
  4613. if (hasGeneratedSchemes) {
  4614. xout.Element("key",
  4615. "IDEWorkspaceSharedSettings_AutocreateContextsIfNeeded");
  4616. xout.Element("false");
  4617. }
  4618. xout.EndElement(); // dict
  4619. xout.EndElement(); // plist
  4620. xout.EndDocument();
  4621. }
  4622. void cmGlobalXCodeGenerator::WriteXCodePBXProj(std::ostream& fout,
  4623. cmLocalGenerator*,
  4624. std::vector<cmLocalGenerator*>&)
  4625. {
  4626. SortXCodeObjects();
  4627. fout << "// !$*UTF8*$!\n"
  4628. "{\n";
  4629. cmXCodeObject::Indent(1, fout);
  4630. fout << "archiveVersion = 1;\n";
  4631. cmXCodeObject::Indent(1, fout);
  4632. fout << "classes = {\n";
  4633. cmXCodeObject::Indent(1, fout);
  4634. fout << "};\n";
  4635. cmXCodeObject::Indent(1, fout);
  4636. fout << "objectVersion = 46;\n";
  4637. cmXCode21Object::PrintList(this->XCodeObjects, fout);
  4638. cmXCodeObject::Indent(1, fout);
  4639. fout << "rootObject = " << this->RootObject->GetId()
  4640. << " /* Project object */;\n"
  4641. "}\n";
  4642. }
  4643. const char* cmGlobalXCodeGenerator::GetCMakeCFGIntDir() const
  4644. {
  4645. return "$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)";
  4646. }
  4647. std::string cmGlobalXCodeGenerator::ExpandCFGIntDir(
  4648. const std::string& str, const std::string& config) const
  4649. {
  4650. std::string replace1 = "$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)";
  4651. std::string replace2 = "$(CONFIGURATION)";
  4652. std::string tmp = str;
  4653. for (std::string::size_type i = tmp.find(replace1); i != std::string::npos;
  4654. i = tmp.find(replace1, i)) {
  4655. tmp.replace(i, replace1.size(), config);
  4656. i += config.size();
  4657. }
  4658. for (std::string::size_type i = tmp.find(replace2); i != std::string::npos;
  4659. i = tmp.find(replace2, i)) {
  4660. tmp.replace(i, replace2.size(), config);
  4661. i += config.size();
  4662. }
  4663. return tmp;
  4664. }
  4665. cmDocumentationEntry cmGlobalXCodeGenerator::GetDocumentation()
  4666. {
  4667. return { cmGlobalXCodeGenerator::GetActualName(),
  4668. "Generate Xcode project files." };
  4669. }
  4670. std::string cmGlobalXCodeGenerator::ConvertToRelativeForMake(
  4671. std::string const& p)
  4672. {
  4673. return cmSystemTools::ConvertToOutputPath(p);
  4674. }
  4675. std::string cmGlobalXCodeGenerator::RelativeToSource(const std::string& p)
  4676. {
  4677. std::string const& rootSrc =
  4678. this->CurrentRootGenerator->GetCurrentSourceDirectory();
  4679. if (cmSystemTools::IsSubDirectory(p, rootSrc)) {
  4680. return cmSystemTools::ForceToRelativePath(rootSrc, p);
  4681. }
  4682. return p;
  4683. }
  4684. std::string cmGlobalXCodeGenerator::RelativeToBinary(const std::string& p)
  4685. {
  4686. return this->CurrentRootGenerator->MaybeRelativeToCurBinDir(p);
  4687. }
  4688. std::string cmGlobalXCodeGenerator::XCodeEscapePath(const std::string& p)
  4689. {
  4690. if (p.find_first_of(" []") != std::string::npos) {
  4691. std::string t = cmStrCat('"', p, '"');
  4692. return t;
  4693. }
  4694. return p;
  4695. }
  4696. void cmGlobalXCodeGenerator::AppendDirectoryForConfig(
  4697. const std::string& prefix, const std::string& config,
  4698. const std::string& suffix, std::string& dir)
  4699. {
  4700. if (!config.empty()) {
  4701. dir += prefix;
  4702. dir += config;
  4703. dir += suffix;
  4704. }
  4705. }
  4706. std::string cmGlobalXCodeGenerator::LookupFlags(
  4707. const std::string& varNamePrefix, const std::string& varNameLang,
  4708. const std::string& varNameSuffix, const std::string& default_flags)
  4709. {
  4710. if (!varNameLang.empty()) {
  4711. std::string varName = cmStrCat(varNamePrefix, varNameLang, varNameSuffix);
  4712. if (cmValue varValue = this->CurrentMakefile->GetDefinition(varName)) {
  4713. if (!varValue->empty()) {
  4714. return *varValue;
  4715. }
  4716. }
  4717. }
  4718. return default_flags;
  4719. }
  4720. void cmGlobalXCodeGenerator::AppendDefines(BuildObjectListOrString& defs,
  4721. const char* defines_list,
  4722. bool dflag)
  4723. {
  4724. // Skip this if there are no definitions.
  4725. if (!defines_list) {
  4726. return;
  4727. }
  4728. // Expand the list of definitions.
  4729. cmList defines{ defines_list };
  4730. // Store the definitions in the string.
  4731. this->AppendDefines(defs, defines, dflag);
  4732. }
  4733. void cmGlobalXCodeGenerator::AppendDefines(
  4734. BuildObjectListOrString& defs, std::vector<std::string> const& defines,
  4735. bool dflag)
  4736. {
  4737. // GCC_PREPROCESSOR_DEFINITIONS is a space-separated list of definitions.
  4738. std::string def;
  4739. for (auto const& define : defines) {
  4740. // Start with -D if requested.
  4741. if (dflag && !cmHasLiteralPrefix(define, "-D")) {
  4742. def = cmStrCat("-D", define);
  4743. } else if (!dflag && cmHasLiteralPrefix(define, "-D")) {
  4744. def = define.substr(2);
  4745. } else {
  4746. def = define;
  4747. }
  4748. // Append the flag with needed escapes.
  4749. std::string tmp;
  4750. this->AppendFlag(tmp, def);
  4751. defs.Add(tmp);
  4752. }
  4753. }
  4754. void cmGlobalXCodeGenerator::AppendFlag(std::string& flags,
  4755. std::string const& flag) const
  4756. {
  4757. // Short-circuit for an empty flag.
  4758. if (flag.empty()) {
  4759. return;
  4760. }
  4761. // Separate from previous flags.
  4762. if (!flags.empty()) {
  4763. flags += ' ';
  4764. }
  4765. // Check if the flag needs quoting.
  4766. bool quoteFlag =
  4767. flag.find_first_of("`~!@#$%^&*()+={}[]|:;\"'<>,.? ") != std::string::npos;
  4768. // We escape a flag as follows:
  4769. // - Place each flag in single quotes ''
  4770. // - Escape a single quote as \'
  4771. // - Escape a backslash as \\ since it itself is an escape
  4772. // Note that in the code below we need one more level of escapes for
  4773. // C string syntax in this source file.
  4774. //
  4775. // The final level of escaping is done when the string is stored
  4776. // into the project file by cmXCodeObject::PrintString.
  4777. if (quoteFlag) {
  4778. // Open single quote.
  4779. flags += '\'';
  4780. }
  4781. // Flag value with escaped quotes and backslashes.
  4782. for (auto c : flag) {
  4783. if (c == '\'') {
  4784. flags += "'\\''";
  4785. } else if (c == '\\') {
  4786. flags += "\\\\";
  4787. } else {
  4788. flags += c;
  4789. }
  4790. }
  4791. if (quoteFlag) {
  4792. // Close single quote.
  4793. flags += '\'';
  4794. }
  4795. }
  4796. std::string cmGlobalXCodeGenerator::ComputeInfoPListLocation(
  4797. cmGeneratorTarget* target)
  4798. {
  4799. std::string plist =
  4800. cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(),
  4801. "/CMakeFiles/", target->GetName(), ".dir/Info.plist");
  4802. return plist;
  4803. }
  4804. // Return true if the generated build tree may contain multiple builds.
  4805. // i.e. "Can I build Debug and Release in the same tree?"
  4806. bool cmGlobalXCodeGenerator::IsMultiConfig() const
  4807. {
  4808. // Newer Xcode versions are multi config:
  4809. return true;
  4810. }
  4811. bool cmGlobalXCodeGenerator::HasKnownObjectFileLocation(
  4812. cmTarget const& target, std::string* reason) const
  4813. {
  4814. auto objectDirArch = GetTargetObjectDirArch(target, this->ObjectDirArch);
  4815. if (objectDirArch.find('$') != std::string::npos) {
  4816. if (reason != nullptr) {
  4817. *reason = " under Xcode with multiple architectures";
  4818. }
  4819. return false;
  4820. }
  4821. return true;
  4822. }
  4823. bool cmGlobalXCodeGenerator::UseEffectivePlatformName(cmMakefile* mf) const
  4824. {
  4825. cmValue epnValue = this->GetCMakeInstance()->GetState()->GetGlobalProperty(
  4826. "XCODE_EMIT_EFFECTIVE_PLATFORM_NAME");
  4827. if (!epnValue) {
  4828. return mf->PlatformIsAppleEmbedded();
  4829. }
  4830. return cmIsOn(*epnValue);
  4831. }
  4832. bool cmGlobalXCodeGenerator::ShouldStripResourcePath(cmMakefile*) const
  4833. {
  4834. // Xcode determines Resource location itself
  4835. return true;
  4836. }
  4837. void cmGlobalXCodeGenerator::ComputeTargetObjectDirectory(
  4838. cmGeneratorTarget* gt) const
  4839. {
  4840. auto objectDirArch = GetTargetObjectDirArch(*gt, this->ObjectDirArch);
  4841. gt->ObjectDirectory =
  4842. cmStrCat(this->GetTargetTempDir(gt, this->GetCMakeCFGIntDir()),
  4843. "/$(OBJECT_FILE_DIR_normal:base)/", objectDirArch, '/');
  4844. }
  4845. std::string cmGlobalXCodeGenerator::GetDeploymentPlatform(const cmMakefile* mf)
  4846. {
  4847. switch (mf->GetAppleSDKType()) {
  4848. case cmMakefile::AppleSDK::AppleTVOS:
  4849. case cmMakefile::AppleSDK::AppleTVSimulator:
  4850. return "TVOS_DEPLOYMENT_TARGET";
  4851. case cmMakefile::AppleSDK::IPhoneOS:
  4852. case cmMakefile::AppleSDK::IPhoneSimulator:
  4853. return "IPHONEOS_DEPLOYMENT_TARGET";
  4854. case cmMakefile::AppleSDK::WatchOS:
  4855. case cmMakefile::AppleSDK::WatchSimulator:
  4856. return "WATCHOS_DEPLOYMENT_TARGET";
  4857. case cmMakefile::AppleSDK::XROS:
  4858. case cmMakefile::AppleSDK::XRSimulator:
  4859. return "XROS_DEPLOYMENT_TARGET";
  4860. case cmMakefile::AppleSDK::MacOS:
  4861. default:
  4862. return "MACOSX_DEPLOYMENT_TARGET";
  4863. }
  4864. }