cmGlobalXCodeGenerator.cxx 187 KB

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