cmGlobalXCodeGenerator.cxx 181 KB

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