cmGlobalXCodeGenerator.cxx 188 KB

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