cmGlobalXCodeGenerator.cxx 185 KB

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