cmGlobalXCodeGenerator.cxx 178 KB

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