cmGlobalXCodeGenerator.cxx 176 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902
  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 <iomanip>
  9. #include <sstream>
  10. #include <unordered_set>
  11. #include <utility>
  12. #include <cm/memory>
  13. #include <cmext/algorithm>
  14. #include <cmext/string_view>
  15. #include "cmsys/RegularExpression.hxx"
  16. #include "cmCMakePath.h"
  17. #include "cmComputeLinkInformation.h"
  18. #include "cmCryptoHash.h"
  19. #include "cmCustomCommand.h"
  20. #include "cmCustomCommandGenerator.h"
  21. #include "cmCustomCommandLines.h"
  22. #include "cmDocumentationEntry.h"
  23. #include "cmGeneratedFileStream.h"
  24. #include "cmGeneratorExpression.h"
  25. #include "cmGeneratorTarget.h"
  26. #include "cmGlobalGeneratorFactory.h"
  27. #include "cmLocalGenerator.h"
  28. #include "cmLocalXCodeGenerator.h"
  29. #include "cmMakefile.h"
  30. #include "cmMessageType.h"
  31. #include "cmOutputConverter.h"
  32. #include "cmSourceFile.h"
  33. #include "cmSourceGroup.h"
  34. #include "cmState.h"
  35. #include "cmStateTypes.h"
  36. #include "cmStringAlgorithms.h"
  37. #include "cmSystemTools.h"
  38. #include "cmTarget.h"
  39. #include "cmXCode21Object.h"
  40. #include "cmXCodeObject.h"
  41. #include "cmXCodeScheme.h"
  42. #include "cmake.h"
  43. struct cmLinkImplementation;
  44. #if !defined(CMAKE_BOOTSTRAP) && defined(__APPLE__)
  45. # include <CoreFoundation/CoreFoundation.h>
  46. # if !TARGET_OS_IPHONE
  47. # define HAVE_APPLICATION_SERVICES
  48. # include <ApplicationServices/ApplicationServices.h>
  49. # endif
  50. #endif
  51. #if !defined(CMAKE_BOOTSTRAP)
  52. # include "cmXMLParser.h"
  53. // parse the xml file storing the installed version of Xcode on
  54. // the machine
  55. class cmXcodeVersionParser : public cmXMLParser
  56. {
  57. public:
  58. cmXcodeVersionParser()
  59. : Version("1.5")
  60. {
  61. }
  62. void StartElement(const std::string&, const char**) override
  63. {
  64. this->Data = "";
  65. }
  66. void EndElement(const std::string& name) override
  67. {
  68. if (name == "key") {
  69. this->Key = this->Data;
  70. } else if (name == "string") {
  71. if (this->Key == "CFBundleShortVersionString") {
  72. this->Version = this->Data;
  73. }
  74. }
  75. }
  76. void CharacterDataHandler(const char* data, int length) override
  77. {
  78. this->Data.append(data, length);
  79. }
  80. std::string Version;
  81. std::string Key;
  82. std::string Data;
  83. };
  84. #endif
  85. // Builds either an object list or a space-separated string from the
  86. // given inputs.
  87. class cmGlobalXCodeGenerator::BuildObjectListOrString
  88. {
  89. cmGlobalXCodeGenerator* Generator;
  90. cmXCodeObject* Group;
  91. bool Empty;
  92. std::string String;
  93. public:
  94. BuildObjectListOrString(cmGlobalXCodeGenerator* gen, bool buildObjectList)
  95. : Generator(gen)
  96. , Group(nullptr)
  97. , Empty(true)
  98. {
  99. if (buildObjectList) {
  100. this->Group = this->Generator->CreateObject(cmXCodeObject::OBJECT_LIST);
  101. }
  102. }
  103. bool IsEmpty() const { return this->Empty; }
  104. void Add(const std::string& newString)
  105. {
  106. this->Empty = false;
  107. if (this->Group) {
  108. this->Group->AddObject(this->Generator->CreateString(newString));
  109. } else {
  110. this->String += newString;
  111. this->String += ' ';
  112. }
  113. }
  114. const std::string& GetString() const { return this->String; }
  115. cmXCodeObject* CreateList()
  116. {
  117. if (this->Group) {
  118. return this->Group;
  119. }
  120. return this->Generator->CreateString(this->String);
  121. }
  122. };
  123. class cmGlobalXCodeGenerator::Factory : public cmGlobalGeneratorFactory
  124. {
  125. public:
  126. std::unique_ptr<cmGlobalGenerator> CreateGlobalGenerator(
  127. const std::string& name, bool allowArch, cmake* cm) const override;
  128. void GetDocumentation(cmDocumentationEntry& entry) const override
  129. {
  130. cmGlobalXCodeGenerator::GetDocumentation(entry);
  131. }
  132. std::vector<std::string> GetGeneratorNames() const override
  133. {
  134. std::vector<std::string> names;
  135. names.push_back(cmGlobalXCodeGenerator::GetActualName());
  136. return names;
  137. }
  138. std::vector<std::string> GetGeneratorNamesWithPlatform() const override
  139. {
  140. return std::vector<std::string>();
  141. }
  142. bool SupportsToolset() const override { return true; }
  143. bool SupportsPlatform() const override { return false; }
  144. std::vector<std::string> GetKnownPlatforms() const override
  145. {
  146. return std::vector<std::string>();
  147. }
  148. std::string GetDefaultPlatformName() const override { return std::string(); }
  149. };
  150. cmGlobalXCodeGenerator::cmGlobalXCodeGenerator(
  151. cmake* cm, std::string const& version_string, unsigned int version_number)
  152. : cmGlobalGenerator(cm)
  153. {
  154. this->VersionString = version_string;
  155. this->XcodeVersion = version_number;
  156. if (this->XcodeVersion >= 120) {
  157. this->XcodeBuildSystem = BuildSystem::Twelve;
  158. } else {
  159. this->XcodeBuildSystem = BuildSystem::One;
  160. }
  161. this->RootObject = nullptr;
  162. this->MainGroupChildren = nullptr;
  163. this->FrameworkGroup = nullptr;
  164. this->CurrentMakefile = nullptr;
  165. this->CurrentLocalGenerator = nullptr;
  166. this->XcodeBuildCommandInitialized = false;
  167. this->ObjectDirArchDefault = "$(CURRENT_ARCH)";
  168. this->ObjectDirArch = this->ObjectDirArchDefault;
  169. cm->GetState()->SetIsGeneratorMultiConfig(true);
  170. }
  171. std::unique_ptr<cmGlobalGeneratorFactory> cmGlobalXCodeGenerator::NewFactory()
  172. {
  173. return std::unique_ptr<cmGlobalGeneratorFactory>(new Factory);
  174. }
  175. std::unique_ptr<cmGlobalGenerator>
  176. cmGlobalXCodeGenerator::Factory::CreateGlobalGenerator(const std::string& name,
  177. bool /*allowArch*/,
  178. cmake* cm) const
  179. {
  180. if (name != GetActualName()) {
  181. return std::unique_ptr<cmGlobalGenerator>();
  182. }
  183. #if !defined(CMAKE_BOOTSTRAP)
  184. cmXcodeVersionParser parser;
  185. std::string versionFile;
  186. {
  187. std::string out;
  188. bool commandResult = cmSystemTools::RunSingleCommand(
  189. "xcode-select --print-path", &out, nullptr, nullptr, nullptr,
  190. cmSystemTools::OUTPUT_NONE);
  191. if (commandResult) {
  192. std::string::size_type pos = out.find(".app/");
  193. if (pos != std::string::npos) {
  194. versionFile = out.substr(0, pos + 5) + "Contents/version.plist";
  195. }
  196. }
  197. }
  198. if (!versionFile.empty() && cmSystemTools::FileExists(versionFile)) {
  199. parser.ParseFile(versionFile.c_str());
  200. } else if (cmSystemTools::FileExists(
  201. "/Applications/Xcode.app/Contents/version.plist")) {
  202. parser.ParseFile("/Applications/Xcode.app/Contents/version.plist");
  203. } else {
  204. parser.ParseFile(
  205. "/Developer/Applications/Xcode.app/Contents/version.plist");
  206. }
  207. std::string const& version_string = parser.Version;
  208. // Compute an integer form of the version number.
  209. unsigned int v[2] = { 0, 0 };
  210. sscanf(version_string.c_str(), "%u.%u", &v[0], &v[1]);
  211. unsigned int version_number = 10 * v[0] + v[1];
  212. if (version_number < 50) {
  213. cm->IssueMessage(MessageType::FATAL_ERROR,
  214. "Xcode " + version_string + " not supported.");
  215. return std::unique_ptr<cmGlobalGenerator>();
  216. }
  217. return std::unique_ptr<cmGlobalGenerator>(
  218. cm::make_unique<cmGlobalXCodeGenerator>(cm, version_string,
  219. version_number));
  220. #else
  221. std::cerr << "CMake should be built with cmake to use Xcode, "
  222. "default to Xcode 1.5\n";
  223. return std::unique_ptr<cmGlobalGenerator>(
  224. cm::make_unique<cmGlobalXCodeGenerator>(cm));
  225. #endif
  226. }
  227. bool cmGlobalXCodeGenerator::FindMakeProgram(cmMakefile* mf)
  228. {
  229. // The Xcode generator knows how to lookup its build tool
  230. // directly instead of needing a helper module to do it, so we
  231. // do not actually need to put CMAKE_MAKE_PROGRAM into the cache.
  232. if (cmIsOff(mf->GetDefinition("CMAKE_MAKE_PROGRAM"))) {
  233. mf->AddDefinition("CMAKE_MAKE_PROGRAM", this->GetXcodeBuildCommand());
  234. }
  235. return true;
  236. }
  237. std::string const& cmGlobalXCodeGenerator::GetXcodeBuildCommand()
  238. {
  239. if (!this->XcodeBuildCommandInitialized) {
  240. this->XcodeBuildCommandInitialized = true;
  241. this->XcodeBuildCommand = this->FindXcodeBuildCommand();
  242. }
  243. return this->XcodeBuildCommand;
  244. }
  245. std::string cmGlobalXCodeGenerator::FindXcodeBuildCommand()
  246. {
  247. std::string makeProgram = cmSystemTools::FindProgram("xcodebuild");
  248. if (makeProgram.empty()) {
  249. makeProgram = "xcodebuild";
  250. }
  251. return makeProgram;
  252. }
  253. bool cmGlobalXCodeGenerator::SetSystemName(std::string const& s,
  254. cmMakefile* mf)
  255. {
  256. this->SystemName = s;
  257. return this->cmGlobalGenerator::SetSystemName(s, mf);
  258. }
  259. namespace {
  260. cm::string_view cmXcodeBuildSystemString(cmGlobalXCodeGenerator::BuildSystem b)
  261. {
  262. switch (b) {
  263. case cmGlobalXCodeGenerator::BuildSystem::One:
  264. return "1"_s;
  265. case cmGlobalXCodeGenerator::BuildSystem::Twelve:
  266. return "12"_s;
  267. }
  268. return {};
  269. }
  270. }
  271. bool cmGlobalXCodeGenerator::SetGeneratorToolset(std::string const& ts,
  272. bool build, cmMakefile* mf)
  273. {
  274. if (!this->ParseGeneratorToolset(ts, mf)) {
  275. return false;
  276. }
  277. if (build) {
  278. return true;
  279. }
  280. if (!this->GeneratorToolset.empty()) {
  281. mf->AddDefinition("CMAKE_XCODE_PLATFORM_TOOLSET", this->GeneratorToolset);
  282. }
  283. mf->AddDefinition("CMAKE_XCODE_BUILD_SYSTEM",
  284. cmXcodeBuildSystemString(this->XcodeBuildSystem));
  285. return true;
  286. }
  287. bool cmGlobalXCodeGenerator::ParseGeneratorToolset(std::string const& ts,
  288. cmMakefile* mf)
  289. {
  290. std::vector<std::string> const fields = cmTokenize(ts, ",");
  291. auto fi = fields.cbegin();
  292. if (fi == fields.cend()) {
  293. return true;
  294. }
  295. // The first field may be the Xcode GCC_VERSION.
  296. if (fi->find('=') == fi->npos) {
  297. this->GeneratorToolset = *fi;
  298. ++fi;
  299. }
  300. std::unordered_set<std::string> handled;
  301. // The rest of the fields must be key=value pairs.
  302. for (; fi != fields.cend(); ++fi) {
  303. std::string::size_type pos = fi->find('=');
  304. if (pos == fi->npos) {
  305. /* clang-format off */
  306. std::string const& e = cmStrCat(
  307. "Generator\n"
  308. " ", this->GetName(), "\n"
  309. "given toolset specification\n"
  310. " ", ts, "\n"
  311. "that contains a field after the first ',' with no '='."
  312. );
  313. /* clang-format on */
  314. mf->IssueMessage(MessageType::FATAL_ERROR, e);
  315. return false;
  316. }
  317. std::string const key = fi->substr(0, pos);
  318. std::string const value = fi->substr(pos + 1);
  319. if (!handled.insert(key).second) {
  320. /* clang-format off */
  321. std::string const& e = cmStrCat(
  322. "Generator\n"
  323. " ", this->GetName(), "\n"
  324. "given toolset specification\n"
  325. " ", ts, "\n"
  326. "that contains duplicate field key '", key, "'."
  327. );
  328. /* clang-format on */
  329. mf->IssueMessage(MessageType::FATAL_ERROR, e);
  330. return false;
  331. }
  332. if (!this->ProcessGeneratorToolsetField(key, value, mf)) {
  333. return false;
  334. }
  335. }
  336. return true;
  337. }
  338. bool cmGlobalXCodeGenerator::ProcessGeneratorToolsetField(
  339. std::string const& key, std::string const& value, cmMakefile* mf)
  340. {
  341. if (key == "buildsystem") {
  342. if (value == "1"_s) {
  343. this->XcodeBuildSystem = BuildSystem::One;
  344. } else if (value == "12"_s) {
  345. this->XcodeBuildSystem = BuildSystem::Twelve;
  346. } else {
  347. /* clang-format off */
  348. std::string const& e = cmStrCat(
  349. "Generator\n"
  350. " ", this->GetName(), "\n"
  351. "toolset specification field\n"
  352. " buildsystem=", value, "\n"
  353. "value is unknown. It must be '1' or '12'."
  354. );
  355. /* clang-format on */
  356. mf->IssueMessage(MessageType::FATAL_ERROR, e);
  357. return false;
  358. }
  359. if (this->XcodeBuildSystem == BuildSystem::Twelve &&
  360. this->XcodeVersion < 120) {
  361. /* clang-format off */
  362. std::string const& e = cmStrCat(
  363. "Generator\n"
  364. " ", this->GetName(), "\n"
  365. "toolset specification field\n"
  366. " buildsystem=", value, "\n"
  367. "is not allowed with Xcode ", this->VersionString, '.'
  368. );
  369. /* clang-format on */
  370. mf->IssueMessage(MessageType::FATAL_ERROR, e);
  371. return false;
  372. }
  373. return true;
  374. }
  375. /* clang-format off */
  376. std::string const& e = cmStrCat(
  377. "Generator\n"
  378. " ", this->GetName(), "\n"
  379. "given toolset specification that contains invalid field '", key, "'."
  380. );
  381. /* clang-format on */
  382. mf->IssueMessage(MessageType::FATAL_ERROR, e);
  383. return false;
  384. }
  385. void cmGlobalXCodeGenerator::EnableLanguage(
  386. std::vector<std::string> const& lang, cmMakefile* mf, bool optional)
  387. {
  388. mf->AddDefinition("XCODE", "1");
  389. mf->AddDefinition("XCODE_VERSION", this->VersionString);
  390. mf->InitCMAKE_CONFIGURATION_TYPES("Debug;Release;MinSizeRel;RelWithDebInfo");
  391. mf->AddDefinition("CMAKE_GENERATOR_NO_COMPILER_ENV", "1");
  392. this->cmGlobalGenerator::EnableLanguage(lang, mf, optional);
  393. this->ComputeArchitectures(mf);
  394. }
  395. bool cmGlobalXCodeGenerator::Open(const std::string& bindir,
  396. const std::string& projectName, bool dryRun)
  397. {
  398. bool ret = false;
  399. #ifdef HAVE_APPLICATION_SERVICES
  400. std::string url = bindir + "/" + projectName + ".xcodeproj";
  401. if (dryRun) {
  402. return cmSystemTools::FileExists(url, false);
  403. }
  404. CFStringRef cfStr = CFStringCreateWithCString(
  405. kCFAllocatorDefault, url.c_str(), kCFStringEncodingUTF8);
  406. if (cfStr) {
  407. CFURLRef cfUrl = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, cfStr,
  408. kCFURLPOSIXPathStyle, true);
  409. if (cfUrl) {
  410. OSStatus err = LSOpenCFURLRef(cfUrl, nullptr);
  411. ret = err == noErr;
  412. CFRelease(cfUrl);
  413. }
  414. CFRelease(cfStr);
  415. }
  416. #endif
  417. return ret;
  418. }
  419. std::vector<cmGlobalGenerator::GeneratedMakeCommand>
  420. cmGlobalXCodeGenerator::GenerateBuildCommand(
  421. const std::string& makeProgram, const std::string& projectName,
  422. const std::string& /*projectDir*/,
  423. std::vector<std::string> const& targetNames, const std::string& config,
  424. bool /*fast*/, int jobs, bool /*verbose*/,
  425. std::vector<std::string> const& makeOptions)
  426. {
  427. GeneratedMakeCommand makeCommand;
  428. // now build the test
  429. makeCommand.Add(
  430. this->SelectMakeProgram(makeProgram, this->GetXcodeBuildCommand()));
  431. if (!projectName.empty()) {
  432. makeCommand.Add("-project");
  433. std::string projectArg = cmStrCat(projectName, ".xcodeproj");
  434. makeCommand.Add(projectArg);
  435. }
  436. if (cm::contains(targetNames, "clean")) {
  437. makeCommand.Add("clean");
  438. makeCommand.Add("-target", "ALL_BUILD");
  439. } else {
  440. makeCommand.Add("build");
  441. if (targetNames.empty() ||
  442. ((targetNames.size() == 1) && targetNames.front().empty())) {
  443. makeCommand.Add("-target", "ALL_BUILD");
  444. } else {
  445. for (const auto& tname : targetNames) {
  446. if (!tname.empty()) {
  447. makeCommand.Add("-target", tname);
  448. }
  449. }
  450. }
  451. }
  452. if ((this->XcodeBuildSystem >= BuildSystem::Twelve) ||
  453. (jobs != cmake::NO_BUILD_PARALLEL_LEVEL)) {
  454. makeCommand.Add("-parallelizeTargets");
  455. }
  456. makeCommand.Add("-configuration", (config.empty() ? "Debug" : config));
  457. if ((jobs != cmake::NO_BUILD_PARALLEL_LEVEL) &&
  458. (jobs != cmake::DEFAULT_BUILD_PARALLEL_LEVEL)) {
  459. makeCommand.Add("-jobs", std::to_string(jobs));
  460. }
  461. if (this->XcodeVersion >= 70) {
  462. makeCommand.Add("-hideShellScriptEnvironment");
  463. }
  464. makeCommand.Add(makeOptions.begin(), makeOptions.end());
  465. return { std::move(makeCommand) };
  466. }
  467. //! Create a local generator appropriate to this Global Generator
  468. std::unique_ptr<cmLocalGenerator> cmGlobalXCodeGenerator::CreateLocalGenerator(
  469. cmMakefile* mf)
  470. {
  471. std::unique_ptr<cmLocalGenerator> lg(
  472. cm::make_unique<cmLocalXCodeGenerator>(this, mf));
  473. if (this->XcodeBuildSystem >= BuildSystem::Twelve) {
  474. // For this build system variant we generate custom commands as
  475. // shell scripts directly rather than inside Makefiles.
  476. // FIXME: Rename or refactor this option for clarity.
  477. lg->SetLinkScriptShell(true);
  478. }
  479. return lg;
  480. }
  481. void cmGlobalXCodeGenerator::AddExtraIDETargets()
  482. {
  483. // make sure extra targets are added before calling
  484. // the parent generate which will call trace depends
  485. for (auto keyVal : this->ProjectMap) {
  486. cmLocalGenerator* root = keyVal.second[0];
  487. this->SetGenerationRoot(root);
  488. // add ALL_BUILD, INSTALL, etc
  489. this->AddExtraTargets(root, keyVal.second);
  490. }
  491. }
  492. void cmGlobalXCodeGenerator::Generate()
  493. {
  494. this->cmGlobalGenerator::Generate();
  495. if (cmSystemTools::GetErrorOccuredFlag()) {
  496. return;
  497. }
  498. for (auto keyVal : this->ProjectMap) {
  499. cmLocalGenerator* root = keyVal.second[0];
  500. bool generateTopLevelProjectOnly =
  501. root->GetMakefile()->IsOn("CMAKE_XCODE_GENERATE_TOP_LEVEL_PROJECT_ONLY");
  502. if (generateTopLevelProjectOnly) {
  503. cmStateSnapshot snp = root->GetStateSnapshot();
  504. if (snp.GetBuildsystemDirectoryParent().IsValid()) {
  505. continue;
  506. }
  507. }
  508. // cache the enabled languages for source file type queries
  509. this->GetEnabledLanguages(this->EnabledLangs);
  510. this->SetGenerationRoot(root);
  511. // now create the project
  512. this->OutputXCodeProject(root, keyVal.second);
  513. }
  514. }
  515. void cmGlobalXCodeGenerator::SetGenerationRoot(cmLocalGenerator* root)
  516. {
  517. this->CurrentProject = root->GetProjectName();
  518. this->SetCurrentLocalGenerator(root);
  519. this->CurrentRootGenerator = root;
  520. this->CurrentXCodeHackMakefile =
  521. cmStrCat(root->GetCurrentBinaryDirectory(), "/CMakeScripts");
  522. cmSystemTools::MakeDirectory(this->CurrentXCodeHackMakefile);
  523. this->CurrentXCodeHackMakefile += "/XCODE_DEPEND_HELPER.make";
  524. }
  525. std::string cmGlobalXCodeGenerator::PostBuildMakeTarget(
  526. std::string const& tName, std::string const& configName)
  527. {
  528. std::string target = tName;
  529. std::replace(target.begin(), target.end(), ' ', '_');
  530. std::string out = cmStrCat("PostBuild.", target, '.', configName);
  531. return out;
  532. }
  533. #define CMAKE_CHECK_BUILD_SYSTEM_TARGET "ZERO_CHECK"
  534. #define OBJECT_LIBRARY_ARTIFACT_DIR std::string()
  535. void cmGlobalXCodeGenerator::AddExtraTargets(
  536. cmLocalGenerator* root, std::vector<cmLocalGenerator*>& gens)
  537. {
  538. const char* no_working_directory = nullptr;
  539. std::vector<std::string> no_byproducts;
  540. std::vector<std::string> no_depends;
  541. // Add ALL_BUILD
  542. cmTarget* allbuild = root->AddUtilityCommand(
  543. "ALL_BUILD", true, no_working_directory, no_byproducts, no_depends,
  544. cmMakeSingleCommandLine({ "echo", "Build all projects" }),
  545. cmPolicies::NEW);
  546. root->AddGeneratorTarget(cm::make_unique<cmGeneratorTarget>(allbuild, root));
  547. // Add XCODE depend helper
  548. std::string legacyDependHelperDir = root->GetCurrentBinaryDirectory();
  549. cmCustomCommandLines legacyDependHelperCommandLines;
  550. if (this->XcodeBuildSystem == BuildSystem::One) {
  551. legacyDependHelperCommandLines = cmMakeSingleCommandLine(
  552. { "make", "-C", legacyDependHelperDir, "-f",
  553. this->CurrentXCodeHackMakefile, "OBJDIR=$(OBJDIR)",
  554. /* placeholder, see below */ "" });
  555. }
  556. // Add ZERO_CHECK
  557. bool regenerate = !this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION");
  558. bool generateTopLevelProjectOnly =
  559. root->GetMakefile()->IsOn("CMAKE_XCODE_GENERATE_TOP_LEVEL_PROJECT_ONLY");
  560. bool isTopLevel =
  561. !root->GetStateSnapshot().GetBuildsystemDirectoryParent().IsValid();
  562. bool isGenerateProject = isTopLevel || !generateTopLevelProjectOnly;
  563. if (regenerate && isGenerateProject) {
  564. this->CreateReRunCMakeFile(root, gens);
  565. std::string file =
  566. this->ConvertToRelativeForMake(this->CurrentReRunCMakeMakefile);
  567. cmSystemTools::ReplaceString(file, "\\ ", " ");
  568. cmTarget* check = root->AddUtilityCommand(
  569. CMAKE_CHECK_BUILD_SYSTEM_TARGET, true, no_working_directory,
  570. no_byproducts, no_depends,
  571. cmMakeSingleCommandLine({ "make", "-f", file }), cmPolicies::NEW);
  572. root->AddGeneratorTarget(cm::make_unique<cmGeneratorTarget>(check, root));
  573. }
  574. // now make the allbuild depend on all the non-utility targets
  575. // in the project
  576. for (auto& gen : gens) {
  577. for (const auto& target : gen->GetGeneratorTargets()) {
  578. if (target->GetType() == cmStateEnums::GLOBAL_TARGET) {
  579. continue;
  580. }
  581. if (regenerate &&
  582. (target->GetName() != CMAKE_CHECK_BUILD_SYSTEM_TARGET)) {
  583. target->Target->AddUtility(CMAKE_CHECK_BUILD_SYSTEM_TARGET, false);
  584. }
  585. // make all exe, shared libs and modules
  586. // run the depend check makefile as a post build rule
  587. // this will make sure that when the next target is built
  588. // things are up-to-date
  589. if (this->XcodeBuildSystem == BuildSystem::One && isGenerateProject &&
  590. target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  591. legacyDependHelperCommandLines.front().back() = // fill placeholder
  592. this->PostBuildMakeTarget(target->GetName(), "$(CONFIGURATION)");
  593. gen->AddCustomCommandToTarget(
  594. target->GetName(), no_byproducts, no_depends,
  595. legacyDependHelperCommandLines, cmCustomCommandType::POST_BUILD,
  596. "Depend check for xcode", legacyDependHelperDir.c_str(),
  597. cmPolicies::NEW, true, false, "", "", false,
  598. cmObjectLibraryCommands::Accept);
  599. }
  600. if (!this->IsExcluded(gens[0], target.get())) {
  601. allbuild->AddUtility(target->GetName(), false);
  602. }
  603. }
  604. }
  605. }
  606. void cmGlobalXCodeGenerator::CreateReRunCMakeFile(
  607. cmLocalGenerator* root, std::vector<cmLocalGenerator*> const& gens)
  608. {
  609. std::vector<std::string> lfiles;
  610. for (auto gen : gens) {
  611. cm::append(lfiles, gen->GetMakefile()->GetListFiles());
  612. }
  613. // sort the array
  614. std::sort(lfiles.begin(), lfiles.end());
  615. lfiles.erase(std::unique(lfiles.begin(), lfiles.end()), lfiles.end());
  616. cmake* cm = this->GetCMakeInstance();
  617. if (cm->DoWriteGlobVerifyTarget()) {
  618. lfiles.emplace_back(cm->GetGlobVerifyStamp());
  619. }
  620. this->CurrentReRunCMakeMakefile =
  621. cmStrCat(root->GetCurrentBinaryDirectory(), "/CMakeScripts");
  622. cmSystemTools::MakeDirectory(this->CurrentReRunCMakeMakefile);
  623. this->CurrentReRunCMakeMakefile += "/ReRunCMake.make";
  624. cmGeneratedFileStream makefileStream(this->CurrentReRunCMakeMakefile);
  625. makefileStream.SetCopyIfDifferent(true);
  626. makefileStream << "# Generated by CMake, DO NOT EDIT\n\n";
  627. makefileStream << "TARGETS:= \n";
  628. makefileStream << "empty:= \n";
  629. makefileStream << "space:= $(empty) $(empty)\n";
  630. makefileStream << "spaceplus:= $(empty)\\ $(empty)\n\n";
  631. for (const auto& lfile : lfiles) {
  632. makefileStream << "TARGETS += $(subst $(space),$(spaceplus),$(wildcard "
  633. << this->ConvertToRelativeForMake(lfile) << "))\n";
  634. }
  635. makefileStream << "\n";
  636. std::string checkCache =
  637. cmStrCat(root->GetBinaryDirectory(), "/CMakeFiles/cmake.check_cache");
  638. if (cm->DoWriteGlobVerifyTarget()) {
  639. makefileStream << ".NOTPARALLEL:\n\n";
  640. makefileStream << ".PHONY: all VERIFY_GLOBS\n\n";
  641. makefileStream << "all: VERIFY_GLOBS "
  642. << this->ConvertToRelativeForMake(checkCache) << "\n\n";
  643. makefileStream << "VERIFY_GLOBS:\n";
  644. makefileStream << "\t"
  645. << this->ConvertToRelativeForMake(
  646. cmSystemTools::GetCMakeCommand())
  647. << " -P "
  648. << this->ConvertToRelativeForMake(cm->GetGlobVerifyScript())
  649. << "\n\n";
  650. }
  651. makefileStream << this->ConvertToRelativeForMake(checkCache)
  652. << ": $(TARGETS)\n";
  653. makefileStream << "\t"
  654. << this->ConvertToRelativeForMake(
  655. cmSystemTools::GetCMakeCommand())
  656. << " -H"
  657. << this->ConvertToRelativeForMake(root->GetSourceDirectory())
  658. << " -B"
  659. << this->ConvertToRelativeForMake(root->GetBinaryDirectory())
  660. << "\n";
  661. }
  662. static bool objectIdLessThan(const std::unique_ptr<cmXCodeObject>& l,
  663. const std::unique_ptr<cmXCodeObject>& r)
  664. {
  665. return l->GetId() < r->GetId();
  666. }
  667. void cmGlobalXCodeGenerator::SortXCodeObjects()
  668. {
  669. std::sort(this->XCodeObjects.begin(), this->XCodeObjects.end(),
  670. objectIdLessThan);
  671. }
  672. void cmGlobalXCodeGenerator::ClearXCodeObjects()
  673. {
  674. this->TargetDoneSet.clear();
  675. this->XCodeObjects.clear();
  676. this->XCodeObjectIDs.clear();
  677. this->XCodeObjectMap.clear();
  678. this->GroupMap.clear();
  679. this->GroupNameMap.clear();
  680. this->TargetGroup.clear();
  681. this->FileRefs.clear();
  682. this->ExternalLibRefs.clear();
  683. this->EmbeddedLibRefs.clear();
  684. this->FileRefToBuildFileMap.clear();
  685. this->FileRefToEmbedBuildFileMap.clear();
  686. this->CommandsVisited.clear();
  687. }
  688. void cmGlobalXCodeGenerator::addObject(std::unique_ptr<cmXCodeObject> obj)
  689. {
  690. if (obj->GetType() == cmXCodeObject::OBJECT) {
  691. const std::string& id = obj->GetId();
  692. // If this is a duplicate id, it's an error:
  693. //
  694. if (this->XCodeObjectIDs.count(id)) {
  695. cmSystemTools::Error(
  696. "Xcode generator: duplicate object ids not allowed");
  697. }
  698. this->XCodeObjectIDs.insert(id);
  699. }
  700. this->XCodeObjects.push_back(std::move(obj));
  701. }
  702. cmXCodeObject* cmGlobalXCodeGenerator::CreateObject(
  703. cmXCodeObject::PBXType ptype, cm::string_view key)
  704. {
  705. auto obj = cm::make_unique<cmXCode21Object>(ptype, cmXCodeObject::OBJECT,
  706. this->GetObjectId(ptype, key));
  707. auto ptr = obj.get();
  708. this->addObject(std::move(obj));
  709. return ptr;
  710. }
  711. cmXCodeObject* cmGlobalXCodeGenerator::CreateObject(cmXCodeObject::Type type)
  712. {
  713. auto obj = cm::make_unique<cmXCodeObject>(
  714. cmXCodeObject::None, type,
  715. "Temporary cmake object, should not be referred to in Xcode file");
  716. auto ptr = obj.get();
  717. this->addObject(std::move(obj));
  718. return ptr;
  719. }
  720. cmXCodeObject* cmGlobalXCodeGenerator::CreateString(const std::string& s)
  721. {
  722. cmXCodeObject* obj = this->CreateObject(cmXCodeObject::STRING);
  723. obj->SetString(s);
  724. return obj;
  725. }
  726. cmXCodeObject* cmGlobalXCodeGenerator::CreateObjectReference(
  727. cmXCodeObject* ref)
  728. {
  729. cmXCodeObject* obj = this->CreateObject(cmXCodeObject::OBJECT_REF);
  730. obj->SetObject(ref);
  731. return obj;
  732. }
  733. cmXCodeObject* cmGlobalXCodeGenerator::CreateFlatClone(cmXCodeObject* orig)
  734. {
  735. cmXCodeObject* obj = this->CreateObject(orig->GetType());
  736. obj->CopyAttributes(orig);
  737. return obj;
  738. }
  739. std::string GetGroupMapKeyFromPath(cmGeneratorTarget* target,
  740. const std::string& fullpath)
  741. {
  742. std::string key(target->GetName());
  743. key += "-";
  744. key += fullpath;
  745. return key;
  746. }
  747. cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeBuildFileFromPath(
  748. const std::string& fullpath, cmGeneratorTarget* target,
  749. const std::string& lang, cmSourceFile* sf)
  750. {
  751. // Using a map and the full path guarantees that we will always get the same
  752. // fileRef object for any given full path. Same goes for the buildFile
  753. // object.
  754. cmXCodeObject* fileRef =
  755. this->CreateXCodeFileReferenceFromPath(fullpath, target, lang, sf);
  756. if (fileRef) {
  757. auto it = this->FileRefToBuildFileMap.find(fileRef);
  758. if (it == this->FileRefToBuildFileMap.end()) {
  759. cmXCodeObject* buildFile =
  760. this->CreateObject(cmXCodeObject::PBXBuildFile);
  761. buildFile->SetComment(fileRef->GetComment());
  762. buildFile->AddAttribute("fileRef", this->CreateObjectReference(fileRef));
  763. this->FileRefToBuildFileMap[fileRef] = buildFile;
  764. return buildFile;
  765. }
  766. return it->second;
  767. }
  768. return nullptr;
  769. }
  770. class XCodeGeneratorExpressionInterpreter
  771. : public cmGeneratorExpressionInterpreter
  772. {
  773. public:
  774. XCodeGeneratorExpressionInterpreter(cmSourceFile* sourceFile,
  775. cmLocalGenerator* localGenerator,
  776. cmGeneratorTarget* headTarget,
  777. const std::string& lang)
  778. : cmGeneratorExpressionInterpreter(
  779. localGenerator, "NO-PER-CONFIG-SUPPORT-IN-XCODE", headTarget, lang)
  780. , SourceFile(sourceFile)
  781. {
  782. }
  783. XCodeGeneratorExpressionInterpreter(
  784. XCodeGeneratorExpressionInterpreter const&) = delete;
  785. XCodeGeneratorExpressionInterpreter& operator=(
  786. XCodeGeneratorExpressionInterpreter const&) = delete;
  787. const std::string& Evaluate(const char* expression,
  788. const std::string& property)
  789. {
  790. return this->Evaluate(std::string(expression ? expression : ""), property);
  791. }
  792. const std::string& Evaluate(const std::string& expression,
  793. const std::string& property)
  794. {
  795. const std::string& processed =
  796. this->cmGeneratorExpressionInterpreter::Evaluate(expression, property);
  797. if (this->CompiledGeneratorExpression->GetHadContextSensitiveCondition()) {
  798. std::ostringstream e;
  799. /* clang-format off */
  800. e <<
  801. "Xcode does not support per-config per-source " << property << ":\n"
  802. " " << expression << "\n"
  803. "specified for source:\n"
  804. " " << this->SourceFile->ResolveFullPath() << "\n";
  805. /* clang-format on */
  806. this->LocalGenerator->IssueMessage(MessageType::FATAL_ERROR, e.str());
  807. }
  808. return processed;
  809. }
  810. private:
  811. cmSourceFile* SourceFile = nullptr;
  812. };
  813. cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeSourceFile(
  814. cmLocalGenerator* lg, cmSourceFile* sf, cmGeneratorTarget* gtgt)
  815. {
  816. std::string lang = this->CurrentLocalGenerator->GetSourceFileLanguage(*sf);
  817. XCodeGeneratorExpressionInterpreter genexInterpreter(sf, lg, gtgt, lang);
  818. // Add flags from target and source file properties.
  819. std::string flags;
  820. std::string const& srcfmt = sf->GetSafeProperty("Fortran_FORMAT");
  821. switch (cmOutputConverter::GetFortranFormat(srcfmt)) {
  822. case cmOutputConverter::FortranFormatFixed:
  823. flags = "-fixed " + flags;
  824. break;
  825. case cmOutputConverter::FortranFormatFree:
  826. flags = "-free " + flags;
  827. break;
  828. default:
  829. break;
  830. }
  831. // Explicitly add the explicit language flag before any other flag
  832. // so user flags can override it.
  833. gtgt->AddExplicitLanguageFlags(flags, *sf);
  834. const std::string COMPILE_FLAGS("COMPILE_FLAGS");
  835. if (cmProp cflags = sf->GetProperty(COMPILE_FLAGS)) {
  836. lg->AppendFlags(flags, genexInterpreter.Evaluate(*cflags, COMPILE_FLAGS));
  837. }
  838. const std::string COMPILE_OPTIONS("COMPILE_OPTIONS");
  839. if (cmProp coptions = sf->GetProperty(COMPILE_OPTIONS)) {
  840. lg->AppendCompileOptions(
  841. flags, genexInterpreter.Evaluate(*coptions, COMPILE_OPTIONS));
  842. }
  843. // Add per-source definitions.
  844. BuildObjectListOrString flagsBuild(this, false);
  845. const std::string COMPILE_DEFINITIONS("COMPILE_DEFINITIONS");
  846. if (cmProp compile_defs = sf->GetProperty(COMPILE_DEFINITIONS)) {
  847. this->AppendDefines(
  848. flagsBuild,
  849. genexInterpreter.Evaluate(*compile_defs, COMPILE_DEFINITIONS).c_str(),
  850. true);
  851. }
  852. if (sf->GetPropertyAsBool("SKIP_PRECOMPILE_HEADERS")) {
  853. this->AppendDefines(flagsBuild, "CMAKE_SKIP_PRECOMPILE_HEADERS", true);
  854. }
  855. if (!flagsBuild.IsEmpty()) {
  856. if (!flags.empty()) {
  857. flags += ' ';
  858. }
  859. flags += flagsBuild.GetString();
  860. }
  861. // Add per-source include directories.
  862. std::vector<std::string> includes;
  863. const std::string INCLUDE_DIRECTORIES("INCLUDE_DIRECTORIES");
  864. if (cmProp cincludes = sf->GetProperty(INCLUDE_DIRECTORIES)) {
  865. lg->AppendIncludeDirectories(
  866. includes, genexInterpreter.Evaluate(*cincludes, INCLUDE_DIRECTORIES),
  867. *sf);
  868. }
  869. lg->AppendFlags(flags,
  870. lg->GetIncludeFlags(includes, gtgt, lang, std::string()));
  871. cmXCodeObject* buildFile =
  872. this->CreateXCodeBuildFileFromPath(sf->ResolveFullPath(), gtgt, lang, sf);
  873. cmXCodeObject* settings = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  874. settings->AddAttributeIfNotEmpty("COMPILER_FLAGS",
  875. this->CreateString(flags));
  876. cmGeneratorTarget::SourceFileFlags tsFlags =
  877. gtgt->GetTargetSourceFileFlags(sf);
  878. cmXCodeObject* attrs = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  879. // Is this a "private" or "public" framework header file?
  880. // Set the ATTRIBUTES attribute appropriately...
  881. //
  882. if (gtgt->IsFrameworkOnApple()) {
  883. if (tsFlags.Type == cmGeneratorTarget::SourceFileTypePrivateHeader) {
  884. attrs->AddObject(this->CreateString("Private"));
  885. } else if (tsFlags.Type == cmGeneratorTarget::SourceFileTypePublicHeader) {
  886. attrs->AddObject(this->CreateString("Public"));
  887. }
  888. }
  889. // Add user-specified file attributes.
  890. cmProp extraFileAttributes = sf->GetProperty("XCODE_FILE_ATTRIBUTES");
  891. if (extraFileAttributes) {
  892. // Expand the list of attributes.
  893. std::vector<std::string> attributes = cmExpandedList(*extraFileAttributes);
  894. // Store the attributes.
  895. for (const auto& attribute : attributes) {
  896. attrs->AddObject(this->CreateString(attribute));
  897. }
  898. }
  899. settings->AddAttributeIfNotEmpty("ATTRIBUTES", attrs);
  900. if (buildFile) {
  901. buildFile->AddAttributeIfNotEmpty("settings", settings);
  902. }
  903. return buildFile;
  904. }
  905. void cmGlobalXCodeGenerator::AddXCodeProjBuildRule(
  906. cmGeneratorTarget* target, std::vector<cmSourceFile*>& sources) const
  907. {
  908. std::string listfile =
  909. cmStrCat(target->GetLocalGenerator()->GetCurrentSourceDirectory(),
  910. "/CMakeLists.txt");
  911. cmSourceFile* srcCMakeLists = target->Makefile->GetOrCreateSource(
  912. listfile, false, cmSourceFileLocationKind::Known);
  913. if (!cm::contains(sources, srcCMakeLists)) {
  914. sources.push_back(srcCMakeLists);
  915. }
  916. }
  917. namespace {
  918. bool IsLinkPhaseLibraryExtension(const std::string& fileExt)
  919. {
  920. // Empty file extension is a special case for paths to framework's
  921. // internal binary which could be MyFw.framework/Versions/*/MyFw
  922. return (fileExt == ".framework" || fileExt == ".a" || fileExt == ".o" ||
  923. fileExt == ".dylib" || fileExt == ".tbd" || fileExt.empty());
  924. }
  925. bool IsLibraryType(const std::string& fileType)
  926. {
  927. return (fileType == "wrapper.framework" || fileType == "archive.ar" ||
  928. fileType == "compiled.mach-o.objfile" ||
  929. fileType == "compiled.mach-o.dylib" ||
  930. fileType == "compiled.mach-o.executable" ||
  931. fileType == "sourcecode.text-based-dylib-definition");
  932. }
  933. std::string GetDirectoryValueFromFileExtension(const std::string& dirExt)
  934. {
  935. std::string ext = cmSystemTools::LowerCase(dirExt);
  936. if (ext == "framework") {
  937. return "wrapper.framework";
  938. }
  939. if (ext == "xcassets") {
  940. return "folder.assetcatalog";
  941. }
  942. return "folder";
  943. }
  944. std::string GetSourcecodeValueFromFileExtension(
  945. const std::string& _ext, const std::string& lang,
  946. bool& keepLastKnownFileType, const std::vector<std::string>& enabled_langs)
  947. {
  948. std::string ext = cmSystemTools::LowerCase(_ext);
  949. std::string sourcecode = "sourcecode";
  950. if (ext == "o") {
  951. keepLastKnownFileType = true;
  952. sourcecode = "compiled.mach-o.objfile";
  953. } else if (ext == "xctest") {
  954. sourcecode = "wrapper.cfbundle";
  955. } else if (ext == "xib") {
  956. keepLastKnownFileType = true;
  957. sourcecode = "file.xib";
  958. } else if (ext == "storyboard") {
  959. keepLastKnownFileType = true;
  960. sourcecode = "file.storyboard";
  961. } else if (ext == "mm" && !cm::contains(enabled_langs, "OBJCXX")) {
  962. sourcecode += ".cpp.objcpp";
  963. } else if (ext == "m" && !cm::contains(enabled_langs, "OBJC")) {
  964. sourcecode += ".c.objc";
  965. } else if (ext == "swift") {
  966. sourcecode += ".swift";
  967. } else if (ext == "plist") {
  968. sourcecode += ".text.plist";
  969. } else if (ext == "h") {
  970. sourcecode += ".c.h";
  971. } else if (ext == "hxx" || ext == "hpp" || ext == "txx" || ext == "pch" ||
  972. ext == "hh") {
  973. sourcecode += ".cpp.h";
  974. } else if (ext == "png" || ext == "gif" || ext == "jpg") {
  975. keepLastKnownFileType = true;
  976. sourcecode = "image";
  977. } else if (ext == "txt") {
  978. sourcecode += ".text";
  979. } else if (lang == "CXX") {
  980. sourcecode += ".cpp.cpp";
  981. } else if (lang == "C") {
  982. sourcecode += ".c.c";
  983. } else if (lang == "OBJCXX") {
  984. sourcecode += ".cpp.objcpp";
  985. } else if (lang == "OBJC") {
  986. sourcecode += ".c.objc";
  987. } else if (lang == "Fortran") {
  988. sourcecode += ".fortran.f90";
  989. } else if (lang == "ASM") {
  990. sourcecode += ".asm";
  991. } else if (ext == "metal") {
  992. sourcecode += ".metal";
  993. } else if (ext == "mig") {
  994. sourcecode += ".mig";
  995. } else if (ext == "tbd") {
  996. sourcecode += ".text-based-dylib-definition";
  997. } else if (ext == "a") {
  998. keepLastKnownFileType = true;
  999. sourcecode = "archive.ar";
  1000. } else if (ext == "dylib") {
  1001. keepLastKnownFileType = true;
  1002. sourcecode = "compiled.mach-o.dylib";
  1003. } else if (ext == "framework") {
  1004. keepLastKnownFileType = true;
  1005. sourcecode = "wrapper.framework";
  1006. } else if (ext == "xcassets") {
  1007. keepLastKnownFileType = true;
  1008. sourcecode = "folder.assetcatalog";
  1009. }
  1010. // else
  1011. // {
  1012. // // Already specialized above or we leave sourcecode == "sourcecode"
  1013. // // which is probably the most correct choice. Extensionless headers,
  1014. // // for example... Or file types unknown to Xcode that do not map to a
  1015. // // valid explicitFileType value.
  1016. // }
  1017. return sourcecode;
  1018. }
  1019. // If the file has no extension it's either a raw executable or might
  1020. // be a direct reference to a binary within a framework (bad practice!).
  1021. // This is where we change the path to point to the framework directory.
  1022. // .tbd files also can be located in SDK frameworks (they are
  1023. // placeholders for actual libraries shipped with the OS)
  1024. std::string GetLibraryOrFrameworkPath(const std::string& path)
  1025. {
  1026. auto ext = cmSystemTools::GetFilenameLastExtension(path);
  1027. if (ext.empty() || ext == ".tbd") {
  1028. auto name = cmSystemTools::GetFilenameWithoutExtension(path);
  1029. // Check for iOS framework structure:
  1030. // FwName.framework/FwName (and also on macOS where FwName lib is a
  1031. // symlink)
  1032. auto parentDir = cmSystemTools::GetParentDirectory(path);
  1033. auto parentName = cmSystemTools::GetFilenameWithoutExtension(parentDir);
  1034. ext = cmSystemTools::GetFilenameLastExtension(parentDir);
  1035. if (ext == ".framework" && name == parentName) {
  1036. return parentDir;
  1037. }
  1038. // Check for macOS framework structure:
  1039. // FwName.framework/Versions/*/FwName
  1040. std::vector<std::string> components;
  1041. cmSystemTools::SplitPath(path, components);
  1042. if (components.size() > 3 &&
  1043. components[components.size() - 3] == "Versions") {
  1044. ext = cmSystemTools::GetFilenameLastExtension(
  1045. components[components.size() - 4]);
  1046. parentName = cmSystemTools::GetFilenameWithoutExtension(
  1047. components[components.size() - 4]);
  1048. if (ext == ".framework" && name == parentName) {
  1049. components.erase(components.begin() + components.size() - 3,
  1050. components.end());
  1051. return cmSystemTools::JoinPath(components);
  1052. }
  1053. }
  1054. }
  1055. return path;
  1056. }
  1057. } // anonymous
  1058. cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeFileReferenceFromPath(
  1059. const std::string& fullpath, cmGeneratorTarget* target,
  1060. const std::string& lang, cmSourceFile* sf)
  1061. {
  1062. bool useLastKnownFileType = false;
  1063. std::string fileType;
  1064. if (sf) {
  1065. if (cmProp e = sf->GetProperty("XCODE_EXPLICIT_FILE_TYPE")) {
  1066. fileType = *e;
  1067. } else if (cmProp l = sf->GetProperty("XCODE_LAST_KNOWN_FILE_TYPE")) {
  1068. useLastKnownFileType = true;
  1069. fileType = *l;
  1070. }
  1071. }
  1072. // Make a copy so that we can override it later
  1073. std::string path = cmSystemTools::CollapseFullPath(fullpath);
  1074. // Compute the extension without leading '.'.
  1075. std::string ext = cmSystemTools::GetFilenameLastExtension(path);
  1076. if (!ext.empty()) {
  1077. ext = ext.substr(1);
  1078. }
  1079. if (fileType.empty()) {
  1080. path = GetLibraryOrFrameworkPath(path);
  1081. ext = cmSystemTools::GetFilenameLastExtension(path);
  1082. if (!ext.empty()) {
  1083. ext = ext.substr(1);
  1084. }
  1085. // If fullpath references a directory, then we need to specify
  1086. // lastKnownFileType as folder in order for Xcode to be able to
  1087. // open the contents of the folder.
  1088. // (Xcode 4.6 does not like explicitFileType=folder).
  1089. if (cmSystemTools::FileIsDirectory(path)) {
  1090. fileType = GetDirectoryValueFromFileExtension(ext);
  1091. useLastKnownFileType = true;
  1092. } else {
  1093. if (ext.empty() && !sf) {
  1094. // Special case for executable or library without extension
  1095. // that is not a source file. We can't tell which without reading
  1096. // its Mach-O header, but the file might not exist yet, so we
  1097. // have to pick one here.
  1098. useLastKnownFileType = true;
  1099. fileType = "compiled.mach-o.executable";
  1100. } else {
  1101. fileType = GetSourcecodeValueFromFileExtension(
  1102. ext, lang, useLastKnownFileType, this->EnabledLangs);
  1103. }
  1104. }
  1105. }
  1106. std::string key = GetGroupMapKeyFromPath(target, path);
  1107. cmXCodeObject* fileRef = this->FileRefs[key];
  1108. if (!fileRef) {
  1109. fileRef = this->CreateObject(cmXCodeObject::PBXFileReference);
  1110. fileRef->SetComment(path);
  1111. this->FileRefs[key] = fileRef;
  1112. }
  1113. fileRef->AddAttribute("fileEncoding", this->CreateString("4"));
  1114. fileRef->AddAttribute(useLastKnownFileType ? "lastKnownFileType"
  1115. : "explicitFileType",
  1116. this->CreateString(fileType));
  1117. // Store the file path relative to the top of the source tree.
  1118. if (!IsLibraryType(fileType)) {
  1119. path = this->RelativeToSource(path);
  1120. }
  1121. std::string name = cmSystemTools::GetFilenameName(path);
  1122. const char* sourceTree =
  1123. cmSystemTools::FileIsFullPath(path) ? "<absolute>" : "SOURCE_ROOT";
  1124. fileRef->AddAttribute("name", this->CreateString(name));
  1125. fileRef->AddAttribute("path", this->CreateString(path));
  1126. fileRef->AddAttribute("sourceTree", this->CreateString(sourceTree));
  1127. cmXCodeObject* group = this->GroupMap[key];
  1128. if (!group && IsLibraryType(fileType)) {
  1129. group = this->FrameworkGroup;
  1130. this->GroupMap[key] = group;
  1131. }
  1132. if (!group) {
  1133. cmSystemTools::Error("Could not find a PBX group for " + key);
  1134. return nullptr;
  1135. }
  1136. cmXCodeObject* children = group->GetAttribute("children");
  1137. if (!children->HasObject(fileRef)) {
  1138. children->AddObject(fileRef);
  1139. }
  1140. return fileRef;
  1141. }
  1142. cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeFileReference(
  1143. cmSourceFile* sf, cmGeneratorTarget* target)
  1144. {
  1145. std::string lang = this->CurrentLocalGenerator->GetSourceFileLanguage(*sf);
  1146. return this->CreateXCodeFileReferenceFromPath(sf->ResolveFullPath(), target,
  1147. lang, sf);
  1148. }
  1149. bool cmGlobalXCodeGenerator::SpecialTargetEmitted(std::string const& tname)
  1150. {
  1151. if (tname == "ALL_BUILD" || tname == "install" || tname == "package" ||
  1152. tname == "RUN_TESTS" || tname == CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
  1153. if (this->TargetDoneSet.find(tname) != this->TargetDoneSet.end()) {
  1154. return true;
  1155. }
  1156. this->TargetDoneSet.insert(tname);
  1157. return false;
  1158. }
  1159. return false;
  1160. }
  1161. void cmGlobalXCodeGenerator::SetCurrentLocalGenerator(cmLocalGenerator* gen)
  1162. {
  1163. this->CurrentLocalGenerator = gen;
  1164. this->CurrentMakefile = gen->GetMakefile();
  1165. // Select the current set of configuration types.
  1166. this->CurrentConfigurationTypes =
  1167. this->CurrentMakefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  1168. }
  1169. struct cmSourceFilePathCompare
  1170. {
  1171. bool operator()(cmSourceFile* l, cmSourceFile* r)
  1172. {
  1173. return l->ResolveFullPath() < r->ResolveFullPath();
  1174. }
  1175. };
  1176. struct cmCompareTargets
  1177. {
  1178. bool operator()(cmXCodeObject* l, cmXCodeObject* r) const
  1179. {
  1180. std::string const& a = l->GetTarget()->GetName();
  1181. std::string const& b = r->GetTarget()->GetName();
  1182. if (a == "ALL_BUILD") {
  1183. return true;
  1184. }
  1185. if (b == "ALL_BUILD") {
  1186. return false;
  1187. }
  1188. return a < b;
  1189. }
  1190. };
  1191. bool cmGlobalXCodeGenerator::CreateXCodeTargets(
  1192. cmLocalGenerator* gen, std::vector<cmXCodeObject*>& targets)
  1193. {
  1194. this->SetCurrentLocalGenerator(gen);
  1195. std::vector<cmGeneratorTarget*> gts =
  1196. this->GetLocalGeneratorTargetsInOrder(gen);
  1197. for (auto gtgt : gts) {
  1198. if (!this->CreateXCodeTarget(gtgt, targets)) {
  1199. return false;
  1200. }
  1201. }
  1202. std::sort(targets.begin(), targets.end(), cmCompareTargets());
  1203. return true;
  1204. }
  1205. bool cmGlobalXCodeGenerator::CreateXCodeTarget(
  1206. cmGeneratorTarget* gtgt, std::vector<cmXCodeObject*>& targets)
  1207. {
  1208. std::string targetName = gtgt->GetName();
  1209. // make sure ALL_BUILD, INSTALL, etc are only done once
  1210. if (this->SpecialTargetEmitted(targetName)) {
  1211. return true;
  1212. }
  1213. if (!gtgt->IsInBuildSystem()) {
  1214. return true;
  1215. }
  1216. auto& gtgt_visited = this->CommandsVisited[gtgt];
  1217. auto& deps = this->GetTargetDirectDepends(gtgt);
  1218. for (auto& d : deps) {
  1219. // Take the union of visited source files of custom commands so far.
  1220. // ComputeTargetOrder ensures our dependencies already visited their
  1221. // custom commands and updated CommandsVisited.
  1222. auto& dep_visited = this->CommandsVisited[d];
  1223. gtgt_visited.insert(dep_visited.begin(), dep_visited.end());
  1224. }
  1225. if (gtgt->GetType() == cmStateEnums::UTILITY ||
  1226. gtgt->GetType() == cmStateEnums::INTERFACE_LIBRARY ||
  1227. gtgt->GetType() == cmStateEnums::GLOBAL_TARGET) {
  1228. cmXCodeObject* t = this->CreateUtilityTarget(gtgt);
  1229. if (!t) {
  1230. return false;
  1231. }
  1232. targets.push_back(t);
  1233. return true;
  1234. }
  1235. // organize the sources
  1236. std::vector<cmSourceFile*> commonSourceFiles;
  1237. if (!gtgt->GetConfigCommonSourceFilesForXcode(commonSourceFiles)) {
  1238. return false;
  1239. }
  1240. // Add CMakeLists.txt file for user convenience.
  1241. this->AddXCodeProjBuildRule(gtgt, commonSourceFiles);
  1242. // Add the Info.plist we are about to generate for an App Bundle.
  1243. if (gtgt->GetPropertyAsBool("MACOSX_BUNDLE")) {
  1244. std::string plist = this->ComputeInfoPListLocation(gtgt);
  1245. cmSourceFile* sf = gtgt->Makefile->GetOrCreateSource(
  1246. plist, true, cmSourceFileLocationKind::Known);
  1247. commonSourceFiles.push_back(sf);
  1248. }
  1249. std::sort(commonSourceFiles.begin(), commonSourceFiles.end(),
  1250. cmSourceFilePathCompare());
  1251. gtgt->ComputeObjectMapping();
  1252. std::vector<cmXCodeObject*> externalObjFiles;
  1253. std::vector<cmXCodeObject*> headerFiles;
  1254. std::vector<cmXCodeObject*> resourceFiles;
  1255. std::vector<cmXCodeObject*> sourceFiles;
  1256. for (auto sourceFile : commonSourceFiles) {
  1257. cmXCodeObject* xsf = this->CreateXCodeSourceFile(
  1258. this->CurrentLocalGenerator, sourceFile, gtgt);
  1259. cmXCodeObject* fr = xsf->GetAttribute("fileRef");
  1260. cmXCodeObject* filetype =
  1261. fr->GetObject()->GetAttribute("explicitFileType");
  1262. if (!filetype) {
  1263. filetype = fr->GetObject()->GetAttribute("lastKnownFileType");
  1264. }
  1265. cmGeneratorTarget::SourceFileFlags tsFlags =
  1266. gtgt->GetTargetSourceFileFlags(sourceFile);
  1267. if (filetype && filetype->GetString() == "compiled.mach-o.objfile") {
  1268. if (sourceFile->GetObjectLibrary().empty()) {
  1269. externalObjFiles.push_back(xsf);
  1270. }
  1271. } else if (this->IsHeaderFile(sourceFile) ||
  1272. (tsFlags.Type ==
  1273. cmGeneratorTarget::SourceFileTypePrivateHeader) ||
  1274. (tsFlags.Type ==
  1275. cmGeneratorTarget::SourceFileTypePublicHeader)) {
  1276. headerFiles.push_back(xsf);
  1277. } else if (tsFlags.Type == cmGeneratorTarget::SourceFileTypeResource) {
  1278. resourceFiles.push_back(xsf);
  1279. } else if (!sourceFile->GetPropertyAsBool("HEADER_FILE_ONLY") &&
  1280. !gtgt->IsSourceFilePartOfUnityBatch(
  1281. sourceFile->ResolveFullPath())) {
  1282. // Include this file in the build if it has a known language
  1283. // and has not been listed as an ignored extension for this
  1284. // generator.
  1285. if (!this->CurrentLocalGenerator->GetSourceFileLanguage(*sourceFile)
  1286. .empty() &&
  1287. !this->IgnoreFile(sourceFile->GetExtension().c_str())) {
  1288. sourceFiles.push_back(xsf);
  1289. }
  1290. }
  1291. }
  1292. // some build phases only apply to bundles and/or frameworks
  1293. bool isFrameworkTarget = gtgt->IsFrameworkOnApple();
  1294. bool isBundleTarget = gtgt->GetPropertyAsBool("MACOSX_BUNDLE");
  1295. bool isCFBundleTarget = gtgt->IsCFBundleOnApple();
  1296. cmXCodeObject* buildFiles = nullptr;
  1297. // create source build phase
  1298. cmXCodeObject* sourceBuildPhase = nullptr;
  1299. if (!sourceFiles.empty()) {
  1300. sourceBuildPhase = this->CreateObject(cmXCodeObject::PBXSourcesBuildPhase);
  1301. sourceBuildPhase->SetComment("Sources");
  1302. sourceBuildPhase->AddAttribute("buildActionMask",
  1303. this->CreateString("2147483647"));
  1304. buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1305. for (auto& sourceFile : sourceFiles) {
  1306. buildFiles->AddObject(sourceFile);
  1307. }
  1308. sourceBuildPhase->AddAttribute("files", buildFiles);
  1309. sourceBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1310. this->CreateString("0"));
  1311. }
  1312. // create header build phase - only for framework targets
  1313. cmXCodeObject* headerBuildPhase = nullptr;
  1314. if (!headerFiles.empty() && isFrameworkTarget) {
  1315. headerBuildPhase = this->CreateObject(cmXCodeObject::PBXHeadersBuildPhase);
  1316. headerBuildPhase->SetComment("Headers");
  1317. headerBuildPhase->AddAttribute("buildActionMask",
  1318. this->CreateString("2147483647"));
  1319. buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1320. for (auto& headerFile : headerFiles) {
  1321. buildFiles->AddObject(headerFile);
  1322. }
  1323. headerBuildPhase->AddAttribute("files", buildFiles);
  1324. headerBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1325. this->CreateString("0"));
  1326. }
  1327. // create resource build phase - only for framework or bundle targets
  1328. cmXCodeObject* resourceBuildPhase = nullptr;
  1329. if (!resourceFiles.empty() &&
  1330. (isFrameworkTarget || isBundleTarget || isCFBundleTarget)) {
  1331. resourceBuildPhase =
  1332. this->CreateObject(cmXCodeObject::PBXResourcesBuildPhase);
  1333. resourceBuildPhase->SetComment("Resources");
  1334. resourceBuildPhase->AddAttribute("buildActionMask",
  1335. this->CreateString("2147483647"));
  1336. buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1337. for (auto& resourceFile : resourceFiles) {
  1338. buildFiles->AddObject(resourceFile);
  1339. }
  1340. resourceBuildPhase->AddAttribute("files", buildFiles);
  1341. resourceBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1342. this->CreateString("0"));
  1343. }
  1344. // create vector of "non-resource content file" build phases - only for
  1345. // framework or bundle targets
  1346. std::vector<cmXCodeObject*> contentBuildPhases;
  1347. if (isFrameworkTarget || isBundleTarget || isCFBundleTarget) {
  1348. using mapOfVectorOfSourceFiles =
  1349. std::map<std::string, std::vector<cmSourceFile*>>;
  1350. mapOfVectorOfSourceFiles bundleFiles;
  1351. for (auto sourceFile : commonSourceFiles) {
  1352. cmGeneratorTarget::SourceFileFlags tsFlags =
  1353. gtgt->GetTargetSourceFileFlags(sourceFile);
  1354. if (tsFlags.Type == cmGeneratorTarget::SourceFileTypeMacContent) {
  1355. bundleFiles[tsFlags.MacFolder].push_back(sourceFile);
  1356. }
  1357. }
  1358. for (auto const& keySources : bundleFiles) {
  1359. cmXCodeObject* copyFilesBuildPhase =
  1360. this->CreateObject(cmXCodeObject::PBXCopyFilesBuildPhase);
  1361. copyFilesBuildPhase->SetComment("Copy files");
  1362. copyFilesBuildPhase->AddAttribute("buildActionMask",
  1363. this->CreateString("2147483647"));
  1364. copyFilesBuildPhase->AddAttribute("dstSubfolderSpec",
  1365. this->CreateString("6"));
  1366. std::ostringstream ostr;
  1367. if (gtgt->IsFrameworkOnApple()) {
  1368. // dstPath in frameworks is relative to Versions/<version>
  1369. ostr << keySources.first;
  1370. } else if (keySources.first != "MacOS") {
  1371. if (gtgt->Target->GetMakefile()->PlatformIsAppleEmbedded()) {
  1372. ostr << keySources.first;
  1373. } else {
  1374. // dstPath in bundles is relative to Contents/MacOS
  1375. ostr << "../" << keySources.first;
  1376. }
  1377. }
  1378. copyFilesBuildPhase->AddAttribute("dstPath",
  1379. this->CreateString(ostr.str()));
  1380. copyFilesBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1381. this->CreateString("0"));
  1382. buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1383. copyFilesBuildPhase->AddAttribute("files", buildFiles);
  1384. for (auto sourceFile : keySources.second) {
  1385. cmXCodeObject* xsf = this->CreateXCodeSourceFile(
  1386. this->CurrentLocalGenerator, sourceFile, gtgt);
  1387. buildFiles->AddObject(xsf);
  1388. }
  1389. contentBuildPhases.push_back(copyFilesBuildPhase);
  1390. }
  1391. }
  1392. // create vector of "resource content file" build phases - only for
  1393. // framework or bundle targets
  1394. if (isFrameworkTarget || isBundleTarget || isCFBundleTarget) {
  1395. using mapOfVectorOfSourceFiles =
  1396. std::map<std::string, std::vector<cmSourceFile*>>;
  1397. mapOfVectorOfSourceFiles bundleFiles;
  1398. for (auto sourceFile : commonSourceFiles) {
  1399. cmGeneratorTarget::SourceFileFlags tsFlags =
  1400. gtgt->GetTargetSourceFileFlags(sourceFile);
  1401. if (tsFlags.Type == cmGeneratorTarget::SourceFileTypeDeepResource) {
  1402. bundleFiles[tsFlags.MacFolder].push_back(sourceFile);
  1403. }
  1404. }
  1405. for (auto const& keySources : bundleFiles) {
  1406. cmXCodeObject* copyFilesBuildPhase =
  1407. this->CreateObject(cmXCodeObject::PBXCopyFilesBuildPhase);
  1408. copyFilesBuildPhase->SetComment("Copy files");
  1409. copyFilesBuildPhase->AddAttribute("buildActionMask",
  1410. this->CreateString("2147483647"));
  1411. copyFilesBuildPhase->AddAttribute("dstSubfolderSpec",
  1412. this->CreateString("7"));
  1413. copyFilesBuildPhase->AddAttribute("dstPath",
  1414. this->CreateString(keySources.first));
  1415. copyFilesBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1416. this->CreateString("0"));
  1417. buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1418. copyFilesBuildPhase->AddAttribute("files", buildFiles);
  1419. for (auto sourceFile : keySources.second) {
  1420. cmXCodeObject* xsf = this->CreateXCodeSourceFile(
  1421. this->CurrentLocalGenerator, sourceFile, gtgt);
  1422. buildFiles->AddObject(xsf);
  1423. }
  1424. contentBuildPhases.push_back(copyFilesBuildPhase);
  1425. }
  1426. }
  1427. // Always create Link Binary With Libraries build phase
  1428. cmXCodeObject* frameworkBuildPhase = nullptr;
  1429. frameworkBuildPhase =
  1430. this->CreateObject(cmXCodeObject::PBXFrameworksBuildPhase);
  1431. frameworkBuildPhase->SetComment("Frameworks");
  1432. frameworkBuildPhase->AddAttribute("buildActionMask",
  1433. this->CreateString("2147483647"));
  1434. buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1435. frameworkBuildPhase->AddAttribute("files", buildFiles);
  1436. // Add all collected .o files to this build phase
  1437. for (auto& externalObjFile : externalObjFiles) {
  1438. buildFiles->AddObject(externalObjFile);
  1439. }
  1440. frameworkBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1441. this->CreateString("0"));
  1442. // create list of build phases and create the Xcode target
  1443. cmXCodeObject* buildPhases = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1444. this->CreateCustomCommands(buildPhases, sourceBuildPhase, headerBuildPhase,
  1445. resourceBuildPhase, contentBuildPhases,
  1446. frameworkBuildPhase, gtgt);
  1447. targets.push_back(this->CreateXCodeTarget(gtgt, buildPhases));
  1448. return true;
  1449. }
  1450. void cmGlobalXCodeGenerator::ForceLinkerLanguages()
  1451. {
  1452. for (const auto& localGenerator : this->LocalGenerators) {
  1453. // All targets depend on the build-system check target.
  1454. for (const auto& tgt : localGenerator->GetGeneratorTargets()) {
  1455. // This makes sure all targets link using the proper language.
  1456. this->ForceLinkerLanguage(tgt.get());
  1457. }
  1458. }
  1459. }
  1460. void cmGlobalXCodeGenerator::ForceLinkerLanguage(cmGeneratorTarget* gtgt)
  1461. {
  1462. // This matters only for targets that link.
  1463. if (gtgt->GetType() != cmStateEnums::EXECUTABLE &&
  1464. gtgt->GetType() != cmStateEnums::SHARED_LIBRARY &&
  1465. gtgt->GetType() != cmStateEnums::MODULE_LIBRARY) {
  1466. return;
  1467. }
  1468. std::string llang = gtgt->GetLinkerLanguage("NOCONFIG");
  1469. if (llang.empty()) {
  1470. return;
  1471. }
  1472. // If the language is compiled as a source trust Xcode to link with it.
  1473. for (auto const& Language :
  1474. gtgt->GetLinkImplementation("NOCONFIG")->Languages) {
  1475. if (Language == llang) {
  1476. return;
  1477. }
  1478. }
  1479. // Allow empty source file list for iOS Sticker packs
  1480. if (const char* productType = GetTargetProductType(gtgt)) {
  1481. if (strcmp(productType,
  1482. "com.apple.product-type.app-extension.messages-sticker-pack") ==
  1483. 0)
  1484. return;
  1485. }
  1486. // Add an empty source file to the target that compiles with the
  1487. // linker language. This should convince Xcode to choose the proper
  1488. // language.
  1489. cmMakefile* mf = gtgt->Target->GetMakefile();
  1490. std::string fname = cmStrCat(
  1491. gtgt->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/CMakeFiles/",
  1492. gtgt->GetName(), "-CMakeForceLinker.", cmSystemTools::LowerCase(llang));
  1493. {
  1494. cmGeneratedFileStream fout(fname);
  1495. fout << "\n";
  1496. }
  1497. if (cmSourceFile* sf = mf->GetOrCreateSource(fname)) {
  1498. sf->SetProperty("LANGUAGE", llang);
  1499. gtgt->AddSource(fname);
  1500. }
  1501. }
  1502. bool cmGlobalXCodeGenerator::IsHeaderFile(cmSourceFile* sf)
  1503. {
  1504. return cm::contains(this->CMakeInstance->GetHeaderExtensions(),
  1505. sf->GetExtension());
  1506. }
  1507. cmXCodeObject* cmGlobalXCodeGenerator::CreateLegacyRunScriptBuildPhase(
  1508. const char* name, const char* name2, cmGeneratorTarget* target,
  1509. const std::vector<cmCustomCommand>& commands)
  1510. {
  1511. if (commands.empty() && strcmp(name, "CMake ReRun") != 0) {
  1512. return nullptr;
  1513. }
  1514. cmXCodeObject* buildPhase =
  1515. this->CreateObject(cmXCodeObject::PBXShellScriptBuildPhase);
  1516. buildPhase->AddAttribute("buildActionMask",
  1517. this->CreateString("2147483647"));
  1518. cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1519. buildPhase->AddAttribute("files", buildFiles);
  1520. buildPhase->AddAttribute("name", this->CreateString(name));
  1521. buildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1522. this->CreateString("0"));
  1523. buildPhase->AddAttribute("shellPath", this->CreateString("/bin/sh"));
  1524. this->AddCommandsToBuildPhase(buildPhase, target, commands, name2);
  1525. return buildPhase;
  1526. }
  1527. void cmGlobalXCodeGenerator::CreateCustomCommands(
  1528. cmXCodeObject* buildPhases, cmXCodeObject* sourceBuildPhase,
  1529. cmXCodeObject* headerBuildPhase, cmXCodeObject* resourceBuildPhase,
  1530. std::vector<cmXCodeObject*> const& contentBuildPhases,
  1531. cmXCodeObject* frameworkBuildPhase, cmGeneratorTarget* gtgt)
  1532. {
  1533. std::vector<cmCustomCommand> const& prebuild = gtgt->GetPreBuildCommands();
  1534. std::vector<cmCustomCommand> const& prelink = gtgt->GetPreLinkCommands();
  1535. std::vector<cmCustomCommand> postbuild = gtgt->GetPostBuildCommands();
  1536. if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY &&
  1537. !gtgt->IsFrameworkOnApple()) {
  1538. std::string str_file = cmStrCat("$<TARGET_FILE:", gtgt->GetName(), '>');
  1539. std::string str_so_file =
  1540. cmStrCat("$<TARGET_SONAME_FILE:", gtgt->GetName(), '>');
  1541. std::string str_link_file =
  1542. cmStrCat("$<TARGET_LINKER_FILE:", gtgt->GetName(), '>');
  1543. bool stdPipesUTF8 = true;
  1544. cmCustomCommandLines cmd = cmMakeSingleCommandLine(
  1545. { cmSystemTools::GetCMakeCommand(), "-E", "cmake_symlink_library",
  1546. str_file, str_so_file, str_link_file });
  1547. cmCustomCommand command(
  1548. std::vector<std::string>(), std::vector<std::string>(),
  1549. std::vector<std::string>(), cmd, this->CurrentMakefile->GetBacktrace(),
  1550. "Creating symlinks", "", stdPipesUTF8);
  1551. postbuild.push_back(std::move(command));
  1552. }
  1553. cmXCodeObject* legacyCustomCommandsBuildPhase = nullptr;
  1554. cmXCodeObject* preBuildPhase = nullptr;
  1555. cmXCodeObject* preLinkPhase = nullptr;
  1556. cmXCodeObject* postBuildPhase = nullptr;
  1557. if (this->XcodeBuildSystem >= BuildSystem::Twelve) {
  1558. // create prebuild phase
  1559. preBuildPhase =
  1560. this->CreateRunScriptBuildPhase("CMake PreBuild Rules", gtgt, prebuild);
  1561. // create prelink phase
  1562. preLinkPhase =
  1563. this->CreateRunScriptBuildPhase("CMake PreLink Rules", gtgt, prelink);
  1564. // create postbuild phase
  1565. postBuildPhase = this->CreateRunScriptBuildPhase("CMake PostBuild Rules",
  1566. gtgt, postbuild);
  1567. } else {
  1568. std::vector<cmSourceFile*> classes;
  1569. if (!gtgt->GetConfigCommonSourceFilesForXcode(classes)) {
  1570. return;
  1571. }
  1572. // add all the sources
  1573. std::vector<cmCustomCommand> commands;
  1574. auto& visited = this->CommandsVisited[gtgt];
  1575. for (auto sourceFile : classes) {
  1576. if (sourceFile->GetCustomCommand() &&
  1577. visited.insert(sourceFile).second) {
  1578. commands.push_back(*sourceFile->GetCustomCommand());
  1579. if (this->XcodeBuildSystem >= BuildSystem::Twelve) {
  1580. this->CustomCommandRoots[sourceFile].insert(gtgt);
  1581. }
  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. cmProp 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 (cmProp 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. cmProp version = gtgt->GetProperty("VERSION");
  2212. cmProp 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. cmProp 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. cmProp 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. cmProp 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. cmProp 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(frameworkDir, 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. }
  2765. if (!configVector.empty()) {
  2766. configlist->AddAttribute("defaultConfigurationName",
  2767. this->CreateString(configVector[0]));
  2768. configlist->AddAttribute("defaultConfigurationIsVisible",
  2769. this->CreateString("0"));
  2770. return configVector[0];
  2771. }
  2772. return "";
  2773. }
  2774. const char* cmGlobalXCodeGenerator::GetTargetLinkFlagsVar(
  2775. cmGeneratorTarget const* target) const
  2776. {
  2777. if (this->XcodeVersion >= 60 &&
  2778. (target->GetType() == cmStateEnums::STATIC_LIBRARY ||
  2779. target->GetType() == cmStateEnums::OBJECT_LIBRARY)) {
  2780. return "OTHER_LIBTOOLFLAGS";
  2781. }
  2782. return "OTHER_LDFLAGS";
  2783. }
  2784. const char* cmGlobalXCodeGenerator::GetTargetFileType(
  2785. cmGeneratorTarget* target)
  2786. {
  2787. if (cmProp e = target->GetProperty("XCODE_EXPLICIT_FILE_TYPE")) {
  2788. return e->c_str();
  2789. }
  2790. switch (target->GetType()) {
  2791. case cmStateEnums::OBJECT_LIBRARY:
  2792. return "archive.ar";
  2793. case cmStateEnums::STATIC_LIBRARY:
  2794. return (target->GetPropertyAsBool("FRAMEWORK") ? "wrapper.framework"
  2795. : "archive.ar");
  2796. case cmStateEnums::MODULE_LIBRARY:
  2797. if (target->IsXCTestOnApple()) {
  2798. return "wrapper.cfbundle";
  2799. }
  2800. if (target->IsCFBundleOnApple()) {
  2801. return "wrapper.plug-in";
  2802. }
  2803. return "compiled.mach-o.executable";
  2804. case cmStateEnums::SHARED_LIBRARY:
  2805. return (target->GetPropertyAsBool("FRAMEWORK")
  2806. ? "wrapper.framework"
  2807. : "compiled.mach-o.dylib");
  2808. case cmStateEnums::EXECUTABLE:
  2809. return "compiled.mach-o.executable";
  2810. default:
  2811. break;
  2812. }
  2813. return nullptr;
  2814. }
  2815. const char* cmGlobalXCodeGenerator::GetTargetProductType(
  2816. cmGeneratorTarget* target)
  2817. {
  2818. if (cmProp e = target->GetProperty("XCODE_PRODUCT_TYPE")) {
  2819. return e->c_str();
  2820. }
  2821. switch (target->GetType()) {
  2822. case cmStateEnums::OBJECT_LIBRARY:
  2823. return "com.apple.product-type.library.static";
  2824. case cmStateEnums::STATIC_LIBRARY:
  2825. return (target->GetPropertyAsBool("FRAMEWORK")
  2826. ? "com.apple.product-type.framework"
  2827. : "com.apple.product-type.library.static");
  2828. case cmStateEnums::MODULE_LIBRARY:
  2829. if (target->IsXCTestOnApple()) {
  2830. return "com.apple.product-type.bundle.unit-test";
  2831. } else if (target->IsCFBundleOnApple()) {
  2832. return "com.apple.product-type.bundle";
  2833. } else {
  2834. return "com.apple.product-type.tool";
  2835. }
  2836. case cmStateEnums::SHARED_LIBRARY:
  2837. return (target->GetPropertyAsBool("FRAMEWORK")
  2838. ? "com.apple.product-type.framework"
  2839. : "com.apple.product-type.library.dynamic");
  2840. case cmStateEnums::EXECUTABLE:
  2841. return (target->GetPropertyAsBool("MACOSX_BUNDLE")
  2842. ? "com.apple.product-type.application"
  2843. : "com.apple.product-type.tool");
  2844. default:
  2845. break;
  2846. }
  2847. return nullptr;
  2848. }
  2849. cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeTarget(
  2850. cmGeneratorTarget* gtgt, cmXCodeObject* buildPhases)
  2851. {
  2852. if (!gtgt->IsInBuildSystem()) {
  2853. return nullptr;
  2854. }
  2855. cmXCodeObject* target = this->CreateObject(cmXCodeObject::PBXNativeTarget);
  2856. target->AddAttribute("buildPhases", buildPhases);
  2857. cmXCodeObject* buildRules = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2858. target->AddAttribute("buildRules", buildRules);
  2859. std::string defConfig;
  2860. defConfig = this->AddConfigurations(target, gtgt);
  2861. cmXCodeObject* dependencies = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2862. target->AddAttribute("dependencies", dependencies);
  2863. target->AddAttribute("name", this->CreateString(gtgt->GetName()));
  2864. target->AddAttribute("productName", this->CreateString(gtgt->GetName()));
  2865. cmXCodeObject* fileRef = this->CreateObject(cmXCodeObject::PBXFileReference);
  2866. if (const char* fileType = this->GetTargetFileType(gtgt)) {
  2867. fileRef->AddAttribute("explicitFileType", this->CreateString(fileType));
  2868. }
  2869. std::string fullName;
  2870. if (gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  2871. fullName = cmStrCat("lib", gtgt->GetName(), ".a");
  2872. } else {
  2873. fullName = gtgt->GetFullName(defConfig);
  2874. }
  2875. fileRef->AddAttribute("path", this->CreateString(fullName));
  2876. fileRef->AddAttribute("sourceTree",
  2877. this->CreateString("BUILT_PRODUCTS_DIR"));
  2878. fileRef->SetComment(gtgt->GetName());
  2879. target->AddAttribute("productReference",
  2880. this->CreateObjectReference(fileRef));
  2881. if (const char* productType = this->GetTargetProductType(gtgt)) {
  2882. target->AddAttribute("productType", this->CreateString(productType));
  2883. }
  2884. target->SetTarget(gtgt);
  2885. this->XCodeObjectMap[gtgt] = target;
  2886. target->SetId(this->GetOrCreateId(gtgt->GetName(), target->GetId()));
  2887. return target;
  2888. }
  2889. cmXCodeObject* cmGlobalXCodeGenerator::FindXCodeTarget(
  2890. cmGeneratorTarget const* t)
  2891. {
  2892. if (!t) {
  2893. return nullptr;
  2894. }
  2895. auto const i = this->XCodeObjectMap.find(t);
  2896. if (i == this->XCodeObjectMap.end()) {
  2897. return nullptr;
  2898. }
  2899. return i->second;
  2900. }
  2901. std::string cmGlobalXCodeGenerator::GetObjectId(cmXCodeObject::PBXType ptype,
  2902. cm::string_view key)
  2903. {
  2904. std::string objectId;
  2905. if (!key.empty()) {
  2906. cmCryptoHash hash(cmCryptoHash::AlgoSHA256);
  2907. hash.Initialize();
  2908. hash.Append(&ptype, sizeof(ptype));
  2909. hash.Append(key);
  2910. objectId = cmSystemTools::UpperCase(hash.FinalizeHex().substr(0, 24));
  2911. } else {
  2912. char cUuid[40] = { 0 };
  2913. CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
  2914. CFStringRef s = CFUUIDCreateString(kCFAllocatorDefault, uuid);
  2915. CFStringGetCString(s, cUuid, sizeof(cUuid), kCFStringEncodingUTF8);
  2916. objectId = cUuid;
  2917. CFRelease(s);
  2918. CFRelease(uuid);
  2919. cmSystemTools::ReplaceString(objectId, "-", "");
  2920. if (objectId.size() > 24) {
  2921. objectId = objectId.substr(0, 24);
  2922. }
  2923. }
  2924. return objectId;
  2925. }
  2926. std::string cmGlobalXCodeGenerator::GetOrCreateId(const std::string& name,
  2927. const std::string& id)
  2928. {
  2929. std::string guidStoreName = cmStrCat(name, "_GUID_CMAKE");
  2930. cmProp storedGUID = this->CMakeInstance->GetCacheDefinition(guidStoreName);
  2931. if (storedGUID) {
  2932. return *storedGUID;
  2933. }
  2934. this->CMakeInstance->AddCacheEntry(guidStoreName, id.c_str(),
  2935. "Stored Xcode object GUID",
  2936. cmStateEnums::INTERNAL);
  2937. return id;
  2938. }
  2939. void cmGlobalXCodeGenerator::AddDependTarget(cmXCodeObject* target,
  2940. cmXCodeObject* dependTarget)
  2941. {
  2942. // This is called once for every edge in the target dependency graph.
  2943. cmXCodeObject* container =
  2944. this->CreateObject(cmXCodeObject::PBXContainerItemProxy);
  2945. container->SetComment("PBXContainerItemProxy");
  2946. container->AddAttribute("containerPortal",
  2947. this->CreateObjectReference(this->RootObject));
  2948. container->AddAttribute("proxyType", this->CreateString("1"));
  2949. container->AddAttribute("remoteGlobalIDString",
  2950. this->CreateObjectReference(dependTarget));
  2951. container->AddAttribute(
  2952. "remoteInfo", this->CreateString(dependTarget->GetTarget()->GetName()));
  2953. cmXCodeObject* targetdep =
  2954. this->CreateObject(cmXCodeObject::PBXTargetDependency);
  2955. targetdep->SetComment("PBXTargetDependency");
  2956. targetdep->AddAttribute("target", this->CreateObjectReference(dependTarget));
  2957. targetdep->AddAttribute("targetProxy",
  2958. this->CreateObjectReference(container));
  2959. cmXCodeObject* depends = target->GetAttribute("dependencies");
  2960. if (!depends) {
  2961. cmSystemTools::Error(
  2962. "target does not have dependencies attribute error..");
  2963. } else {
  2964. depends->AddUniqueObject(targetdep);
  2965. }
  2966. }
  2967. void cmGlobalXCodeGenerator::AppendOrAddBuildSetting(cmXCodeObject* settings,
  2968. const char* attribute,
  2969. cmXCodeObject* value)
  2970. {
  2971. if (settings) {
  2972. cmXCodeObject* attr = settings->GetAttribute(attribute);
  2973. if (!attr) {
  2974. settings->AddAttribute(attribute, value);
  2975. } else {
  2976. this->AppendBuildSettingAttribute(settings, attribute, attr, value);
  2977. }
  2978. }
  2979. }
  2980. void cmGlobalXCodeGenerator::AppendBuildSettingAttribute(
  2981. cmXCodeObject* settings, const char* attribute, cmXCodeObject* attr,
  2982. cmXCodeObject* value)
  2983. {
  2984. if (value->GetType() != cmXCodeObject::OBJECT_LIST &&
  2985. value->GetType() != cmXCodeObject::STRING) {
  2986. cmSystemTools::Error("Unsupported value type for appending: " +
  2987. std::string(attribute));
  2988. return;
  2989. }
  2990. if (attr->GetType() == cmXCodeObject::OBJECT_LIST) {
  2991. if (value->GetType() == cmXCodeObject::OBJECT_LIST) {
  2992. for (auto* obj : value->GetObjectList()) {
  2993. attr->AddObject(obj);
  2994. }
  2995. } else {
  2996. attr->AddObject(value);
  2997. }
  2998. } else if (attr->GetType() == cmXCodeObject::STRING) {
  2999. if (value->GetType() == cmXCodeObject::OBJECT_LIST) {
  3000. // Add old value as a list item to new object list
  3001. // and replace the attribute with the new list
  3002. value->PrependObject(attr);
  3003. settings->AddAttribute(attribute, value);
  3004. } else {
  3005. std::string newValue =
  3006. cmStrCat(attr->GetString(), ' ', value->GetString());
  3007. attr->SetString(newValue);
  3008. }
  3009. } else {
  3010. cmSystemTools::Error("Unsupported attribute type for appending: " +
  3011. std::string(attribute));
  3012. }
  3013. }
  3014. void cmGlobalXCodeGenerator::AppendBuildSettingAttribute(
  3015. cmXCodeObject* target, const char* attribute, cmXCodeObject* value,
  3016. const std::string& configName)
  3017. {
  3018. // There are multiple configurations. Add the setting to the
  3019. // buildSettings of the configuration name given.
  3020. cmXCodeObject* configurationList =
  3021. target->GetAttribute("buildConfigurationList")->GetObject();
  3022. cmXCodeObject* buildConfigs =
  3023. configurationList->GetAttribute("buildConfigurations");
  3024. for (auto obj : buildConfigs->GetObjectList()) {
  3025. if (configName.empty() ||
  3026. obj->GetAttribute("name")->GetString() == configName) {
  3027. cmXCodeObject* settings = obj->GetAttribute("buildSettings");
  3028. this->AppendOrAddBuildSetting(settings, attribute, value);
  3029. }
  3030. }
  3031. }
  3032. void cmGlobalXCodeGenerator::InheritBuildSettingAttribute(
  3033. cmXCodeObject* target, const char* attribute)
  3034. {
  3035. cmXCodeObject* configurationList =
  3036. target->GetAttribute("buildConfigurationList")->GetObject();
  3037. cmXCodeObject* buildConfigs =
  3038. configurationList->GetAttribute("buildConfigurations");
  3039. for (auto obj : buildConfigs->GetObjectList()) {
  3040. cmXCodeObject* settings = obj->GetAttribute("buildSettings");
  3041. if (cmXCodeObject* attr = settings->GetAttribute(attribute)) {
  3042. BuildObjectListOrString inherited(this, true);
  3043. inherited.Add("$(inherited)");
  3044. this->AppendBuildSettingAttribute(settings, attribute, attr,
  3045. inherited.CreateList());
  3046. }
  3047. }
  3048. }
  3049. void cmGlobalXCodeGenerator::AddDependAndLinkInformation(cmXCodeObject* target)
  3050. {
  3051. cmGeneratorTarget* gt = target->GetTarget();
  3052. if (!gt) {
  3053. cmSystemTools::Error("Error no target on xobject\n");
  3054. return;
  3055. }
  3056. if (!gt->IsInBuildSystem()) {
  3057. return;
  3058. }
  3059. // Add dependencies on other CMake targets.
  3060. for (const auto& dep : this->GetTargetDirectDepends(gt)) {
  3061. if (cmXCodeObject* dptarget = this->FindXCodeTarget(dep)) {
  3062. this->AddDependTarget(target, dptarget);
  3063. }
  3064. }
  3065. // Separate libraries into ones that can be linked using "Link Binary With
  3066. // Libraries" build phase and the ones that can't. Only targets that build
  3067. // Apple bundles (.app, .framework, .bundle), executables and dylibs can use
  3068. // this feature and only targets that represent actual libraries (object,
  3069. // static, dynamic or bundle, excluding executables) will be used. These are
  3070. // limitations imposed by CMake use-cases - otherwise a lot of things break.
  3071. // The rest will be linked using linker flags (OTHER_LDFLAGS setting in Xcode
  3072. // project).
  3073. std::map<std::string, std::vector<cmComputeLinkInformation::Item const*>>
  3074. configItemMap;
  3075. auto addToLinkerArguments =
  3076. [&configItemMap](const std::string& configName,
  3077. cmComputeLinkInformation::Item const* libItemPtr) {
  3078. auto& linkVector = configItemMap[configName];
  3079. if (std::find_if(linkVector.begin(), linkVector.end(),
  3080. [libItemPtr](cmComputeLinkInformation::Item const* p) {
  3081. return p == libItemPtr;
  3082. }) == linkVector.end()) {
  3083. linkVector.push_back(libItemPtr);
  3084. }
  3085. };
  3086. std::vector<cmComputeLinkInformation::Item const*> linkPhaseTargetVector;
  3087. std::map<std::string, std::vector<std::string>> targetConfigMap;
  3088. using ConfigItemPair =
  3089. std::pair<std::string, cmComputeLinkInformation::Item const*>;
  3090. std::map<std::string, std::vector<ConfigItemPair>> targetItemMap;
  3091. std::map<std::string, std::vector<std::string>> targetProductNameMap;
  3092. bool useLinkPhase = false;
  3093. bool forceLinkPhase = false;
  3094. cmProp prop =
  3095. target->GetTarget()->GetProperty("XCODE_LINK_BUILD_PHASE_MODE");
  3096. if (prop) {
  3097. if (*prop == "BUILT_ONLY") {
  3098. useLinkPhase = true;
  3099. } else if (*prop == "KNOWN_LOCATION") {
  3100. useLinkPhase = true;
  3101. forceLinkPhase = true;
  3102. } else if (*prop != "NONE") {
  3103. cmSystemTools::Error("Invalid value for XCODE_LINK_BUILD_PHASE_MODE: " +
  3104. *prop);
  3105. return;
  3106. }
  3107. }
  3108. for (auto const& configName : this->CurrentConfigurationTypes) {
  3109. cmComputeLinkInformation* cli = gt->GetLinkInformation(configName);
  3110. if (!cli) {
  3111. continue;
  3112. }
  3113. for (auto const& libItem : cli->GetItems()) {
  3114. // We want to put only static libraries, dynamic libraries, frameworks
  3115. // and bundles that are built from targets that are not imported in "Link
  3116. // Binary With Libraries" build phase. Except if the target property
  3117. // XCODE_LINK_BUILD_PHASE_MODE is KNOWN_LOCATION then all imported and
  3118. // non-target libraries will be added as well.
  3119. if (useLinkPhase &&
  3120. (gt->GetType() == cmStateEnums::EXECUTABLE ||
  3121. gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
  3122. gt->GetType() == cmStateEnums::MODULE_LIBRARY) &&
  3123. ((libItem.Target &&
  3124. (!libItem.Target->IsImported() || forceLinkPhase) &&
  3125. (libItem.Target->GetType() == cmStateEnums::STATIC_LIBRARY ||
  3126. libItem.Target->GetType() == cmStateEnums::SHARED_LIBRARY ||
  3127. libItem.Target->GetType() == cmStateEnums::MODULE_LIBRARY ||
  3128. libItem.Target->GetType() == cmStateEnums::UNKNOWN_LIBRARY)) ||
  3129. (!libItem.Target &&
  3130. libItem.IsPath == cmComputeLinkInformation::ItemIsPath::Yes &&
  3131. forceLinkPhase))) {
  3132. std::string libName;
  3133. bool canUseLinkPhase = true;
  3134. if (libItem.Target) {
  3135. if (libItem.Target->GetType() == cmStateEnums::UNKNOWN_LIBRARY) {
  3136. canUseLinkPhase = canUseLinkPhase && forceLinkPhase;
  3137. } else {
  3138. // If a library target uses custom build output directory Xcode
  3139. // won't pick it up so we have to resort back to linker flags, but
  3140. // that's OK as long as the custom output dir is absolute path.
  3141. for (auto const& libConfigName : this->CurrentConfigurationTypes) {
  3142. canUseLinkPhase = canUseLinkPhase &&
  3143. libItem.Target->UsesDefaultOutputDir(
  3144. libConfigName, cmStateEnums::RuntimeBinaryArtifact);
  3145. }
  3146. }
  3147. libName = libItem.Target->GetName();
  3148. } else {
  3149. libName = cmSystemTools::GetFilenameName(libItem.Value.Value);
  3150. // We don't want all the possible files here, just standard libraries
  3151. const auto libExt = cmSystemTools::GetFilenameExtension(libName);
  3152. if (!IsLinkPhaseLibraryExtension(libExt)) {
  3153. canUseLinkPhase = false;
  3154. }
  3155. }
  3156. if (canUseLinkPhase) {
  3157. // Add unique configuration name to target-config map for later
  3158. // checks
  3159. auto& configVector = targetConfigMap[libName];
  3160. if (std::find(configVector.begin(), configVector.end(),
  3161. configName) == configVector.end()) {
  3162. configVector.push_back(configName);
  3163. }
  3164. // Add a pair of config and item to target-item map
  3165. auto& itemVector = targetItemMap[libName];
  3166. itemVector.emplace_back(ConfigItemPair(configName, &libItem));
  3167. // Add product file-name to a lib-product map
  3168. auto productName =
  3169. cmSystemTools::GetFilenameName(libItem.Value.Value);
  3170. auto& productVector = targetProductNameMap[libName];
  3171. if (std::find(productVector.begin(), productVector.end(),
  3172. productName) == productVector.end()) {
  3173. productVector.push_back(productName);
  3174. }
  3175. continue;
  3176. }
  3177. }
  3178. // Add this library item to a regular linker flag list
  3179. addToLinkerArguments(configName, &libItem);
  3180. }
  3181. }
  3182. // Go through target library map and separate libraries that are linked
  3183. // in all configurations and produce only single product, from the rest.
  3184. // Only these will be linked through "Link Binary With Libraries" build
  3185. // phase.
  3186. for (auto const& targetLibConfigs : targetConfigMap) {
  3187. // Add this library to "Link Binary With Libraries" build phase if it's
  3188. // linked in all configurations and it has only one product name
  3189. auto& itemVector = targetItemMap[targetLibConfigs.first];
  3190. auto& productVector = targetProductNameMap[targetLibConfigs.first];
  3191. if (targetLibConfigs.second == this->CurrentConfigurationTypes &&
  3192. productVector.size() == 1) {
  3193. // Add this library to "Link Binary With Libraries" list
  3194. linkPhaseTargetVector.push_back(itemVector[0].second);
  3195. } else {
  3196. for (auto const& libItem : targetItemMap[targetLibConfigs.first]) {
  3197. // Add this library item to a regular linker flag list
  3198. addToLinkerArguments(libItem.first, libItem.second);
  3199. }
  3200. }
  3201. }
  3202. // Add libraries to "Link Binary With Libraries" build phase and collect
  3203. // their search paths. Xcode does not support per-configuration linking
  3204. // in this build phase so we don't have to do this for each configuration
  3205. // separately.
  3206. std::vector<std::string> linkSearchPaths;
  3207. std::vector<std::string> frameworkSearchPaths;
  3208. for (auto const& libItem : linkPhaseTargetVector) {
  3209. // Add target output directory as a library search path
  3210. std::string linkDir;
  3211. if (libItem->Target) {
  3212. linkDir = libItem->Target->GetLocationForBuild();
  3213. } else {
  3214. linkDir = libItem->Value.Value;
  3215. }
  3216. linkDir = GetLibraryOrFrameworkPath(linkDir);
  3217. bool isFramework = cmSystemTools::IsPathToFramework(linkDir);
  3218. linkDir = cmSystemTools::GetParentDirectory(linkDir);
  3219. if (isFramework) {
  3220. if (std::find(frameworkSearchPaths.begin(), frameworkSearchPaths.end(),
  3221. linkDir) == frameworkSearchPaths.end()) {
  3222. frameworkSearchPaths.push_back(linkDir);
  3223. }
  3224. } else {
  3225. if (std::find(linkSearchPaths.begin(), linkSearchPaths.end(), linkDir) ==
  3226. linkSearchPaths.end()) {
  3227. linkSearchPaths.push_back(linkDir);
  3228. }
  3229. }
  3230. // Add target dependency
  3231. if (libItem->Target && !libItem->Target->IsImported()) {
  3232. for (auto const& configName : this->CurrentConfigurationTypes) {
  3233. target->AddDependTarget(configName, libItem->Target->GetName());
  3234. }
  3235. }
  3236. // Get the library target
  3237. auto* libTarget = FindXCodeTarget(libItem->Target);
  3238. cmXCodeObject* buildFile;
  3239. if (!libTarget) {
  3240. if (libItem->IsPath == cmComputeLinkInformation::ItemIsPath::Yes) {
  3241. // Get or create a direct file ref in the root project
  3242. auto cleanPath = libItem->Value.Value;
  3243. if (cmSystemTools::FileIsFullPath(cleanPath)) {
  3244. // Some arguments are reported as paths, but they are actually not,
  3245. // so we can't collapse them, and neither can we collapse relative
  3246. // paths
  3247. cleanPath = cmSystemTools::CollapseFullPath(cleanPath);
  3248. }
  3249. auto it = this->ExternalLibRefs.find(cleanPath);
  3250. if (it == this->ExternalLibRefs.end()) {
  3251. buildFile = CreateXCodeBuildFileFromPath(cleanPath, gt, "", nullptr);
  3252. if (!buildFile) {
  3253. // Add this library item back to a regular linker flag list
  3254. for (const auto& conf : configItemMap) {
  3255. addToLinkerArguments(conf.first, libItem);
  3256. }
  3257. continue;
  3258. }
  3259. this->ExternalLibRefs.emplace(cleanPath, buildFile);
  3260. } else {
  3261. buildFile = it->second;
  3262. }
  3263. } else {
  3264. // Add this library item back to a regular linker flag list
  3265. for (const auto& conf : configItemMap) {
  3266. addToLinkerArguments(conf.first, libItem);
  3267. }
  3268. continue;
  3269. }
  3270. } else {
  3271. // Add the target output file as a build reference for other targets
  3272. // to link against
  3273. auto* fileRefObject = libTarget->GetAttribute("productReference");
  3274. if (!fileRefObject) {
  3275. // Add this library item back to a regular linker flag list
  3276. for (const auto& conf : configItemMap) {
  3277. addToLinkerArguments(conf.first, libItem);
  3278. }
  3279. continue;
  3280. }
  3281. auto it = FileRefToBuildFileMap.find(fileRefObject);
  3282. if (it == FileRefToBuildFileMap.end()) {
  3283. buildFile = this->CreateObject(cmXCodeObject::PBXBuildFile);
  3284. buildFile->AddAttribute("fileRef", fileRefObject);
  3285. FileRefToBuildFileMap[fileRefObject] = buildFile;
  3286. } else {
  3287. buildFile = it->second;
  3288. }
  3289. }
  3290. // Add this reference to current target
  3291. auto* buildPhases = target->GetAttribute("buildPhases");
  3292. if (!buildPhases) {
  3293. cmSystemTools::Error("Missing buildPhase of target");
  3294. continue;
  3295. }
  3296. auto* frameworkBuildPhase =
  3297. buildPhases->GetObject(cmXCodeObject::PBXFrameworksBuildPhase);
  3298. if (!frameworkBuildPhase) {
  3299. cmSystemTools::Error("Missing PBXFrameworksBuildPhase of buildPhase");
  3300. continue;
  3301. }
  3302. auto* buildFiles = frameworkBuildPhase->GetAttribute("files");
  3303. if (!buildFiles) {
  3304. cmSystemTools::Error("Missing files of PBXFrameworksBuildPhase");
  3305. continue;
  3306. }
  3307. if (buildFile && !buildFiles->HasObject(buildFile)) {
  3308. buildFiles->AddObject(buildFile);
  3309. }
  3310. }
  3311. // Loop over configuration types and set per-configuration info.
  3312. for (auto const& configName : this->CurrentConfigurationTypes) {
  3313. {
  3314. // Add object library contents as link flags.
  3315. BuildObjectListOrString libSearchPaths(this, true);
  3316. std::vector<cmSourceFile const*> objs;
  3317. gt->GetExternalObjects(objs, configName);
  3318. for (auto sourceFile : objs) {
  3319. if (sourceFile->GetObjectLibrary().empty()) {
  3320. continue;
  3321. }
  3322. libSearchPaths.Add(this->XCodeEscapePath(sourceFile->GetFullPath()));
  3323. }
  3324. this->AppendBuildSettingAttribute(
  3325. target, this->GetTargetLinkFlagsVar(gt), libSearchPaths.CreateList(),
  3326. configName);
  3327. }
  3328. // Skip link information for object libraries.
  3329. if (gt->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  3330. gt->GetType() == cmStateEnums::STATIC_LIBRARY) {
  3331. continue;
  3332. }
  3333. // Compute the link library and directory information.
  3334. cmComputeLinkInformation* cli = gt->GetLinkInformation(configName);
  3335. if (!cli) {
  3336. continue;
  3337. }
  3338. // Add dependencies directly on library files.
  3339. for (auto const& libDep : cli->GetDepends()) {
  3340. target->AddDependLibrary(configName, libDep);
  3341. }
  3342. // add the library search paths
  3343. {
  3344. BuildObjectListOrString libSearchPaths(this, true);
  3345. std::string linkDirs;
  3346. for (auto const& libDir : cli->GetDirectories()) {
  3347. if (!libDir.empty() && libDir != "/usr/lib") {
  3348. libSearchPaths.Add(this->XCodeEscapePath(
  3349. libDir + "/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)"));
  3350. libSearchPaths.Add(this->XCodeEscapePath(libDir));
  3351. }
  3352. }
  3353. // Add previously collected paths where to look for libraries
  3354. // that were added to "Link Binary With Libraries"
  3355. for (auto& libDir : linkSearchPaths) {
  3356. libSearchPaths.Add(this->XCodeEscapePath(libDir));
  3357. }
  3358. if (!libSearchPaths.IsEmpty()) {
  3359. this->AppendBuildSettingAttribute(target, "LIBRARY_SEARCH_PATHS",
  3360. libSearchPaths.CreateList(),
  3361. configName);
  3362. }
  3363. }
  3364. // add framework search paths
  3365. {
  3366. BuildObjectListOrString fwSearchPaths(this, true);
  3367. // Add previously collected paths where to look for frameworks
  3368. // that were added to "Link Binary With Libraries"
  3369. for (auto& fwDir : frameworkSearchPaths) {
  3370. fwSearchPaths.Add(this->XCodeEscapePath(fwDir));
  3371. }
  3372. if (!fwSearchPaths.IsEmpty()) {
  3373. this->AppendBuildSettingAttribute(target, "FRAMEWORK_SEARCH_PATHS",
  3374. fwSearchPaths.CreateList(),
  3375. configName);
  3376. }
  3377. }
  3378. // now add the left-over link libraries
  3379. {
  3380. // Keep track of framework search paths we've already added or that are
  3381. // part of the set of implicit search paths. We don't want to repeat
  3382. // them and we also need to avoid hard-coding any SDK-specific paths.
  3383. // This is essential for getting device-and-simulator builds to work,
  3384. // otherwise we end up hard-coding a path to the wrong SDK for
  3385. // SDK-provided frameworks that are added by their full path.
  3386. std::set<std::string> emitted(cli->GetFrameworkPathsEmitted());
  3387. const auto& fwPaths = cli->GetFrameworkPaths();
  3388. emitted.insert(fwPaths.begin(), fwPaths.end());
  3389. BuildObjectListOrString libPaths(this, true);
  3390. for (auto const& libItem : configItemMap[configName]) {
  3391. auto const& libName = *libItem;
  3392. if (libName.IsPath == cmComputeLinkInformation::ItemIsPath::Yes) {
  3393. auto cleanPath = libName.Value.Value;
  3394. if (cmSystemTools::FileIsFullPath(cleanPath)) {
  3395. cleanPath = cmSystemTools::CollapseFullPath(cleanPath);
  3396. }
  3397. const auto libPath = GetLibraryOrFrameworkPath(cleanPath);
  3398. if (cmSystemTools::StringEndsWith(libPath.c_str(), ".framework")) {
  3399. const auto fwName =
  3400. cmSystemTools::GetFilenameWithoutExtension(libPath);
  3401. const auto fwDir = cmSystemTools::GetParentDirectory(libPath);
  3402. if (emitted.insert(fwDir).second) {
  3403. // This is a search path we had not added before and it isn't an
  3404. // implicit search path, so we need it
  3405. libPaths.Add("-F " + this->XCodeEscapePath(fwDir));
  3406. }
  3407. libPaths.Add("-framework " + this->XCodeEscapePath(fwName));
  3408. } else {
  3409. libPaths.Add(this->XCodeEscapePath(cleanPath));
  3410. }
  3411. if ((!libName.Target || libName.Target->IsImported()) &&
  3412. IsLinkPhaseLibraryExtension(libPath)) {
  3413. // Create file reference for embedding
  3414. auto it = this->ExternalLibRefs.find(cleanPath);
  3415. if (it == this->ExternalLibRefs.end()) {
  3416. auto* buildFile =
  3417. this->CreateXCodeBuildFileFromPath(cleanPath, gt, "", nullptr);
  3418. if (buildFile) {
  3419. this->ExternalLibRefs.emplace(cleanPath, buildFile);
  3420. }
  3421. }
  3422. }
  3423. } else if (!libName.Target ||
  3424. libName.Target->GetType() !=
  3425. cmStateEnums::INTERFACE_LIBRARY) {
  3426. libPaths.Add(libName.Value.Value);
  3427. }
  3428. if (libName.Target && !libName.Target->IsImported()) {
  3429. target->AddDependTarget(configName, libName.Target->GetName());
  3430. }
  3431. }
  3432. this->AppendBuildSettingAttribute(target,
  3433. this->GetTargetLinkFlagsVar(gt),
  3434. libPaths.CreateList(), configName);
  3435. }
  3436. }
  3437. }
  3438. void cmGlobalXCodeGenerator::AddEmbeddedObjects(
  3439. cmXCodeObject* target, const std::string& copyFilesBuildPhaseName,
  3440. const std::string& embedPropertyName, const std::string& dstSubfolderSpec,
  3441. int actionsOnByDefault)
  3442. {
  3443. cmGeneratorTarget* gt = target->GetTarget();
  3444. if (!gt) {
  3445. cmSystemTools::Error("Error no target on xobject\n");
  3446. return;
  3447. }
  3448. if (!gt->IsInBuildSystem()) {
  3449. return;
  3450. }
  3451. bool isFrameworkTarget = gt->IsFrameworkOnApple();
  3452. bool isBundleTarget = gt->GetPropertyAsBool("MACOSX_BUNDLE");
  3453. bool isCFBundleTarget = gt->IsCFBundleOnApple();
  3454. if (!(isFrameworkTarget || isBundleTarget || isCFBundleTarget)) {
  3455. return;
  3456. }
  3457. cmProp files = gt->GetProperty(embedPropertyName);
  3458. if (!files) {
  3459. return;
  3460. }
  3461. // Create an "Embedded Frameworks" build phase
  3462. auto* copyFilesBuildPhase =
  3463. this->CreateObject(cmXCodeObject::PBXCopyFilesBuildPhase);
  3464. copyFilesBuildPhase->SetComment(copyFilesBuildPhaseName);
  3465. copyFilesBuildPhase->AddAttribute("buildActionMask",
  3466. this->CreateString("2147483647"));
  3467. copyFilesBuildPhase->AddAttribute("dstSubfolderSpec",
  3468. this->CreateString(dstSubfolderSpec));
  3469. copyFilesBuildPhase->AddAttribute(
  3470. "name", this->CreateString(copyFilesBuildPhaseName));
  3471. if (cmProp fwEmbedPath =
  3472. gt->GetProperty(cmStrCat(embedPropertyName, "_PATH"))) {
  3473. copyFilesBuildPhase->AddAttribute("dstPath",
  3474. this->CreateString(*fwEmbedPath));
  3475. } else {
  3476. copyFilesBuildPhase->AddAttribute("dstPath", this->CreateString(""));
  3477. }
  3478. copyFilesBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  3479. this->CreateString("0"));
  3480. cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3481. // Collect all embedded frameworks and add them to build phase
  3482. std::vector<std::string> relFiles = cmExpandedList(*files);
  3483. for (std::string const& relFile : relFiles) {
  3484. cmXCodeObject* buildFile{ nullptr };
  3485. std::string filePath = relFile;
  3486. auto* genTarget = this->FindGeneratorTarget(relFile);
  3487. if (genTarget) {
  3488. // This is a target - get it's product path reference
  3489. auto* xcTarget = this->FindXCodeTarget(genTarget);
  3490. if (!xcTarget) {
  3491. cmSystemTools::Error("Can not find a target for " +
  3492. genTarget->GetName());
  3493. continue;
  3494. }
  3495. // Add the target output file as a build reference for other targets
  3496. // to link against
  3497. auto* fileRefObject = xcTarget->GetAttribute("productReference");
  3498. if (!fileRefObject) {
  3499. cmSystemTools::Error("Target " + genTarget->GetName() +
  3500. " is missing product reference");
  3501. continue;
  3502. }
  3503. auto it = this->FileRefToEmbedBuildFileMap.find(fileRefObject);
  3504. if (it == this->FileRefToEmbedBuildFileMap.end()) {
  3505. buildFile = this->CreateObject(cmXCodeObject::PBXBuildFile);
  3506. buildFile->AddAttribute("fileRef", fileRefObject);
  3507. this->FileRefToEmbedBuildFileMap[fileRefObject] = buildFile;
  3508. } else {
  3509. buildFile = it->second;
  3510. }
  3511. } else if (cmSystemTools::IsPathToFramework(relFile)) {
  3512. // This is a regular string path - create file reference
  3513. auto it = this->EmbeddedLibRefs.find(relFile);
  3514. if (it == this->EmbeddedLibRefs.end()) {
  3515. cmXCodeObject* fileRef =
  3516. this->CreateXCodeFileReferenceFromPath(relFile, gt, "", nullptr);
  3517. if (fileRef) {
  3518. buildFile = this->CreateObject(cmXCodeObject::PBXBuildFile);
  3519. buildFile->SetComment(fileRef->GetComment());
  3520. buildFile->AddAttribute("fileRef",
  3521. this->CreateObjectReference(fileRef));
  3522. }
  3523. if (!buildFile) {
  3524. cmSystemTools::Error("Can't create build file for " + relFile);
  3525. continue;
  3526. }
  3527. this->EmbeddedLibRefs.emplace(filePath, buildFile);
  3528. } else {
  3529. buildFile = it->second;
  3530. }
  3531. }
  3532. if (!buildFile) {
  3533. cmSystemTools::Error("Can't find a build file for " + relFile);
  3534. continue;
  3535. }
  3536. // Set build file configuration
  3537. cmXCodeObject* settings =
  3538. this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  3539. cmXCodeObject* attrs = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3540. bool removeHeaders = actionsOnByDefault & RemoveHeadersOnCopyByDefault;
  3541. if (auto prop = gt->GetProperty(
  3542. cmStrCat(embedPropertyName, "_REMOVE_HEADERS_ON_COPY"))) {
  3543. removeHeaders = cmIsOn(*prop);
  3544. }
  3545. if (removeHeaders) {
  3546. attrs->AddObject(this->CreateString("RemoveHeadersOnCopy"));
  3547. }
  3548. bool codeSign = actionsOnByDefault & CodeSignOnCopyByDefault;
  3549. if (auto prop =
  3550. gt->GetProperty(cmStrCat(embedPropertyName, "_CODE_SIGN_ON_COPY"))) {
  3551. codeSign = cmIsOn(*prop);
  3552. }
  3553. if (codeSign) {
  3554. attrs->AddObject(this->CreateString("CodeSignOnCopy"));
  3555. }
  3556. settings->AddAttributeIfNotEmpty("ATTRIBUTES", attrs);
  3557. buildFile->AddAttributeIfNotEmpty("settings", settings);
  3558. if (!buildFiles->HasObject(buildFile)) {
  3559. buildFiles->AddObject(buildFile);
  3560. }
  3561. }
  3562. copyFilesBuildPhase->AddAttribute("files", buildFiles);
  3563. auto* buildPhases = target->GetAttribute("buildPhases");
  3564. // Embed-something build phases must be inserted before the post-build
  3565. // command because that command is expected to be last
  3566. buildPhases->InsertObject(buildPhases->GetObjectCount() - 1,
  3567. copyFilesBuildPhase);
  3568. }
  3569. void cmGlobalXCodeGenerator::AddEmbeddedFrameworks(cmXCodeObject* target)
  3570. {
  3571. static const auto dstSubfolderSpec = "10";
  3572. this->AddEmbeddedObjects(target, "Embed Frameworks",
  3573. "XCODE_EMBED_FRAMEWORKS", dstSubfolderSpec,
  3574. NoActionOnCopyByDefault);
  3575. }
  3576. void cmGlobalXCodeGenerator::AddEmbeddedAppExtensions(cmXCodeObject* target)
  3577. {
  3578. static const auto dstSubfolderSpec = "13";
  3579. this->AddEmbeddedObjects(target, "Embed App Extensions",
  3580. "XCODE_EMBED_APP_EXTENSIONS", dstSubfolderSpec,
  3581. RemoveHeadersOnCopyByDefault);
  3582. }
  3583. bool cmGlobalXCodeGenerator::CreateGroups(
  3584. std::vector<cmLocalGenerator*>& generators)
  3585. {
  3586. for (auto& generator : generators) {
  3587. cmMakefile* mf = generator->GetMakefile();
  3588. std::vector<cmSourceGroup> sourceGroups = mf->GetSourceGroups();
  3589. for (const auto& gtgt : generator->GetGeneratorTargets()) {
  3590. // Same skipping logic here as in CreateXCodeTargets so that we do not
  3591. // end up with (empty anyhow) ZERO_CHECK, install, or test source
  3592. // groups:
  3593. //
  3594. if (!gtgt->IsInBuildSystem() ||
  3595. gtgt->GetType() == cmStateEnums::GLOBAL_TARGET ||
  3596. gtgt->GetName() == CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
  3597. continue;
  3598. }
  3599. auto addSourceToGroup = [this, mf, &gtgt,
  3600. &sourceGroups](std::string const& source) {
  3601. cmSourceGroup* sourceGroup = mf->FindSourceGroup(source, sourceGroups);
  3602. cmXCodeObject* pbxgroup =
  3603. this->CreateOrGetPBXGroup(gtgt.get(), sourceGroup);
  3604. std::string key = GetGroupMapKeyFromPath(gtgt.get(), source);
  3605. this->GroupMap[key] = pbxgroup;
  3606. };
  3607. // Put cmSourceFile instances in proper groups:
  3608. for (auto const& si : gtgt->GetAllConfigSources()) {
  3609. cmSourceFile const* sf = si.Source;
  3610. if (!sf->GetObjectLibrary().empty()) {
  3611. // Object library files go on the link line instead.
  3612. continue;
  3613. }
  3614. addSourceToGroup(sf->GetFullPath());
  3615. }
  3616. // Add CMakeLists.txt file for user convenience.
  3617. {
  3618. std::string listfile =
  3619. cmStrCat(gtgt->GetLocalGenerator()->GetCurrentSourceDirectory(),
  3620. "/CMakeLists.txt");
  3621. cmSourceFile* sf = gtgt->Makefile->GetOrCreateSource(
  3622. listfile, false, cmSourceFileLocationKind::Known);
  3623. addSourceToGroup(sf->ResolveFullPath());
  3624. }
  3625. // Add the Info.plist we are about to generate for an App Bundle.
  3626. if (gtgt->GetPropertyAsBool("MACOSX_BUNDLE")) {
  3627. std::string plist = this->ComputeInfoPListLocation(gtgt.get());
  3628. cmSourceFile* sf = gtgt->Makefile->GetOrCreateSource(
  3629. plist, true, cmSourceFileLocationKind::Known);
  3630. addSourceToGroup(sf->ResolveFullPath());
  3631. }
  3632. }
  3633. }
  3634. return true;
  3635. }
  3636. cmXCodeObject* cmGlobalXCodeGenerator::CreatePBXGroup(cmXCodeObject* parent,
  3637. const std::string& name)
  3638. {
  3639. cmXCodeObject* parentChildren = nullptr;
  3640. if (parent) {
  3641. parentChildren = parent->GetAttribute("children");
  3642. }
  3643. cmXCodeObject* group = this->CreateObject(cmXCodeObject::PBXGroup);
  3644. cmXCodeObject* groupChildren =
  3645. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3646. group->AddAttribute("name", this->CreateString(name));
  3647. group->AddAttribute("children", groupChildren);
  3648. group->AddAttribute("sourceTree", this->CreateString("<group>"));
  3649. if (parentChildren) {
  3650. parentChildren->AddObject(group);
  3651. }
  3652. return group;
  3653. }
  3654. cmXCodeObject* cmGlobalXCodeGenerator::CreateOrGetPBXGroup(
  3655. cmGeneratorTarget* gtgt, cmSourceGroup* sg)
  3656. {
  3657. std::string s;
  3658. std::string target;
  3659. const std::string targetFolder = gtgt->GetEffectiveFolderName();
  3660. if (!targetFolder.empty()) {
  3661. target = cmStrCat(targetFolder, '/');
  3662. }
  3663. target += gtgt->GetName();
  3664. s = cmStrCat(target, '/', sg->GetFullName());
  3665. auto it = this->GroupNameMap.find(s);
  3666. if (it != this->GroupNameMap.end()) {
  3667. return it->second;
  3668. }
  3669. it = this->TargetGroup.find(target);
  3670. cmXCodeObject* tgroup = nullptr;
  3671. if (it != this->TargetGroup.end()) {
  3672. tgroup = it->second;
  3673. } else {
  3674. std::vector<std::string> tgt_folders = cmTokenize(target, "/");
  3675. std::string curr_tgt_folder;
  3676. for (std::vector<std::string>::size_type i = 0; i < tgt_folders.size();
  3677. i++) {
  3678. if (i != 0) {
  3679. curr_tgt_folder += "/";
  3680. }
  3681. curr_tgt_folder += tgt_folders[i];
  3682. it = this->TargetGroup.find(curr_tgt_folder);
  3683. if (it != this->TargetGroup.end()) {
  3684. tgroup = it->second;
  3685. continue;
  3686. }
  3687. tgroup = this->CreatePBXGroup(tgroup, tgt_folders[i]);
  3688. this->TargetGroup[curr_tgt_folder] = tgroup;
  3689. if (i == 0) {
  3690. this->MainGroupChildren->AddObject(tgroup);
  3691. }
  3692. }
  3693. }
  3694. this->TargetGroup[target] = tgroup;
  3695. // If it's the default source group (empty name) then put the source file
  3696. // directly in the tgroup...
  3697. //
  3698. if (sg->GetFullName().empty()) {
  3699. this->GroupNameMap[s] = tgroup;
  3700. return tgroup;
  3701. }
  3702. // It's a recursive folder structure, let's find the real parent group
  3703. if (sg->GetFullName() != sg->GetName()) {
  3704. std::string curr_folder = cmStrCat(target, '/');
  3705. for (auto const& folder : cmTokenize(sg->GetFullName(), "\\")) {
  3706. curr_folder += folder;
  3707. auto const i_folder = this->GroupNameMap.find(curr_folder);
  3708. // Create new folder
  3709. if (i_folder == this->GroupNameMap.end()) {
  3710. cmXCodeObject* group = this->CreatePBXGroup(tgroup, folder);
  3711. this->GroupNameMap[curr_folder] = group;
  3712. tgroup = group;
  3713. } else {
  3714. tgroup = i_folder->second;
  3715. }
  3716. curr_folder += "\\";
  3717. }
  3718. return tgroup;
  3719. }
  3720. cmXCodeObject* group = this->CreatePBXGroup(tgroup, sg->GetName());
  3721. this->GroupNameMap[s] = group;
  3722. return group;
  3723. }
  3724. bool cmGlobalXCodeGenerator::CreateXCodeObjects(
  3725. cmLocalGenerator* root, std::vector<cmLocalGenerator*>& generators)
  3726. {
  3727. this->ClearXCodeObjects();
  3728. this->RootObject = nullptr;
  3729. this->MainGroupChildren = nullptr;
  3730. this->FrameworkGroup = nullptr;
  3731. cmXCodeObject* group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  3732. group->AddAttribute("COPY_PHASE_STRIP", this->CreateString("NO"));
  3733. cmXCodeObject* listObjs = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3734. for (const std::string& CurrentConfigurationType :
  3735. this->CurrentConfigurationTypes) {
  3736. cmXCodeObject* buildStyle =
  3737. this->CreateObject(cmXCodeObject::PBXBuildStyle);
  3738. const std::string& name = CurrentConfigurationType;
  3739. buildStyle->AddAttribute("name", this->CreateString(name));
  3740. buildStyle->SetComment(name);
  3741. cmXCodeObject* sgroup = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  3742. sgroup->AddAttribute("COPY_PHASE_STRIP", this->CreateString("NO"));
  3743. buildStyle->AddAttribute("buildSettings", sgroup);
  3744. listObjs->AddObject(buildStyle);
  3745. }
  3746. cmXCodeObject* mainGroup = this->CreateObject(cmXCodeObject::PBXGroup);
  3747. this->MainGroupChildren = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3748. mainGroup->AddAttribute("children", this->MainGroupChildren);
  3749. mainGroup->AddAttribute("sourceTree", this->CreateString("<group>"));
  3750. // now create the cmake groups
  3751. if (!this->CreateGroups(generators)) {
  3752. return false;
  3753. }
  3754. cmXCodeObject* productGroup = this->CreateObject(cmXCodeObject::PBXGroup);
  3755. productGroup->AddAttribute("name", this->CreateString("Products"));
  3756. productGroup->AddAttribute("sourceTree", this->CreateString("<group>"));
  3757. cmXCodeObject* productGroupChildren =
  3758. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3759. productGroup->AddAttribute("children", productGroupChildren);
  3760. this->MainGroupChildren->AddObject(productGroup);
  3761. this->FrameworkGroup = this->CreateObject(cmXCodeObject::PBXGroup);
  3762. this->FrameworkGroup->AddAttribute("name", this->CreateString("Frameworks"));
  3763. this->FrameworkGroup->AddAttribute("sourceTree",
  3764. this->CreateString("<group>"));
  3765. cmXCodeObject* frameworkGroupChildren =
  3766. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3767. this->FrameworkGroup->AddAttribute("children", frameworkGroupChildren);
  3768. this->MainGroupChildren->AddObject(this->FrameworkGroup);
  3769. this->RootObject = this->CreateObject(cmXCodeObject::PBXProject);
  3770. this->RootObject->SetComment("Project object");
  3771. std::string project_id = cmStrCat("PROJECT_", root->GetProjectName());
  3772. this->RootObject->SetId(
  3773. this->GetOrCreateId(project_id, this->RootObject->GetId()));
  3774. group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  3775. this->RootObject->AddAttribute("mainGroup",
  3776. this->CreateObjectReference(mainGroup));
  3777. this->RootObject->AddAttribute("buildSettings", group);
  3778. this->RootObject->AddAttribute("buildStyles", listObjs);
  3779. this->RootObject->AddAttribute("hasScannedForEncodings",
  3780. this->CreateString("0"));
  3781. group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  3782. group->AddAttribute("BuildIndependentTargetsInParallel",
  3783. this->CreateString("YES"));
  3784. std::ostringstream v;
  3785. v << std::setfill('0') << std::setw(4) << XcodeVersion * 10;
  3786. group->AddAttribute("LastUpgradeCheck", this->CreateString(v.str()));
  3787. this->RootObject->AddAttribute("attributes", group);
  3788. this->RootObject->AddAttribute("compatibilityVersion",
  3789. this->CreateString("Xcode 3.2"));
  3790. // Point Xcode at the top of the source tree.
  3791. {
  3792. std::string pdir =
  3793. this->RelativeToBinary(root->GetCurrentSourceDirectory());
  3794. this->RootObject->AddAttribute("projectDirPath", this->CreateString(pdir));
  3795. this->RootObject->AddAttribute("projectRoot", this->CreateString(""));
  3796. }
  3797. cmXCodeObject* configlist =
  3798. this->CreateObject(cmXCodeObject::XCConfigurationList);
  3799. cmXCodeObject* buildConfigurations =
  3800. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3801. using Configs = std::vector<std::pair<std::string, cmXCodeObject*>>;
  3802. Configs configs;
  3803. std::string defaultConfigName;
  3804. for (const auto& name : this->CurrentConfigurationTypes) {
  3805. if (defaultConfigName.empty()) {
  3806. defaultConfigName = name;
  3807. }
  3808. cmXCodeObject* config =
  3809. this->CreateObject(cmXCodeObject::XCBuildConfiguration);
  3810. config->AddAttribute("name", this->CreateString(name));
  3811. configs.push_back(std::make_pair(name, config));
  3812. }
  3813. if (defaultConfigName.empty()) {
  3814. defaultConfigName = "Debug";
  3815. }
  3816. for (auto& config : configs) {
  3817. buildConfigurations->AddObject(config.second);
  3818. }
  3819. configlist->AddAttribute("buildConfigurations", buildConfigurations);
  3820. std::string comment = cmStrCat("Build configuration list for PBXProject \"",
  3821. this->CurrentProject, '"');
  3822. configlist->SetComment(comment);
  3823. configlist->AddAttribute("defaultConfigurationIsVisible",
  3824. this->CreateString("0"));
  3825. configlist->AddAttribute("defaultConfigurationName",
  3826. this->CreateString(defaultConfigName));
  3827. cmXCodeObject* buildSettings =
  3828. this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  3829. cmProp sysroot = this->CurrentMakefile->GetDefinition("CMAKE_OSX_SYSROOT");
  3830. cmProp deploymentTarget =
  3831. this->CurrentMakefile->GetDefinition("CMAKE_OSX_DEPLOYMENT_TARGET");
  3832. if (sysroot) {
  3833. buildSettings->AddAttribute("SDKROOT", this->CreateString(*sysroot));
  3834. }
  3835. // recompute this as it may have been changed since enable language
  3836. this->ComputeArchitectures(this->CurrentMakefile);
  3837. std::string const archs = cmJoin(this->Architectures, " ");
  3838. if (archs.empty()) {
  3839. // Tell Xcode to use NATIVE_ARCH instead of ARCHS.
  3840. buildSettings->AddAttribute("ONLY_ACTIVE_ARCH", this->CreateString("YES"));
  3841. // When targeting macOS, use only the host architecture.
  3842. if (this->SystemName == "Darwin"_s &&
  3843. (!cmNonempty(sysroot) ||
  3844. cmSystemTools::LowerCase(*sysroot).find("macos") !=
  3845. std::string::npos)) {
  3846. buildSettings->AddAttribute("ARCHS",
  3847. this->CreateString("$(NATIVE_ARCH_ACTUAL)"));
  3848. }
  3849. } else {
  3850. // Tell Xcode to use ARCHS (ONLY_ACTIVE_ARCH defaults to NO).
  3851. buildSettings->AddAttribute("ARCHS", this->CreateString(archs));
  3852. }
  3853. if (cmNonempty(deploymentTarget)) {
  3854. buildSettings->AddAttribute(GetDeploymentPlatform(root->GetMakefile()),
  3855. this->CreateString(*deploymentTarget));
  3856. }
  3857. if (!this->GeneratorToolset.empty()) {
  3858. buildSettings->AddAttribute("GCC_VERSION",
  3859. this->CreateString(this->GeneratorToolset));
  3860. }
  3861. if (this->GetLanguageEnabled("Swift")) {
  3862. std::string swiftVersion;
  3863. if (cmProp vers = this->CurrentMakefile->GetDefinition(
  3864. "CMAKE_Swift_LANGUAGE_VERSION")) {
  3865. swiftVersion = *vers;
  3866. } else if (this->XcodeVersion >= 102) {
  3867. swiftVersion = "4.0";
  3868. } else if (this->XcodeVersion >= 83) {
  3869. swiftVersion = "3.0";
  3870. } else {
  3871. swiftVersion = "2.3";
  3872. }
  3873. buildSettings->AddAttribute("SWIFT_VERSION",
  3874. this->CreateString(swiftVersion));
  3875. }
  3876. std::string symroot = cmStrCat(root->GetCurrentBinaryDirectory(), "/build");
  3877. buildSettings->AddAttribute("SYMROOT", this->CreateString(symroot));
  3878. // Inside a try_compile project, do not require signing on any platform.
  3879. if (this->CMakeInstance->GetIsInTryCompile()) {
  3880. buildSettings->AddAttribute("CODE_SIGNING_ALLOWED",
  3881. this->CreateString("NO"));
  3882. }
  3883. for (auto& config : configs) {
  3884. cmXCodeObject* buildSettingsForCfg = this->CreateFlatClone(buildSettings);
  3885. // Put this last so it can override existing settings
  3886. // Convert "CMAKE_XCODE_ATTRIBUTE_*" variables directly.
  3887. for (const auto& var : this->CurrentMakefile->GetDefinitions()) {
  3888. if (cmHasLiteralPrefix(var, "CMAKE_XCODE_ATTRIBUTE_")) {
  3889. std::string attribute = var.substr(22);
  3890. this->FilterConfigurationAttribute(config.first, attribute);
  3891. if (!attribute.empty()) {
  3892. std::string processed = cmGeneratorExpression::Evaluate(
  3893. this->CurrentMakefile->GetSafeDefinition(var),
  3894. this->CurrentLocalGenerator, config.first);
  3895. buildSettingsForCfg->AddAttribute(attribute,
  3896. this->CreateString(processed));
  3897. }
  3898. }
  3899. }
  3900. // store per-config buildSettings into configuration object
  3901. config.second->AddAttribute("buildSettings", buildSettingsForCfg);
  3902. }
  3903. this->RootObject->AddAttribute("buildConfigurationList",
  3904. this->CreateObjectReference(configlist));
  3905. std::vector<cmXCodeObject*> targets;
  3906. for (auto& generator : generators) {
  3907. if (!this->CreateXCodeTargets(generator, targets)) {
  3908. return false;
  3909. }
  3910. for (auto const& ccRoot : this->CustomCommandRoots) {
  3911. if (ccRoot.second.size() > 1) {
  3912. std::string e = "The custom command ";
  3913. std::vector<std::string> const& outputs =
  3914. ccRoot.first->GetCustomCommand()->GetOutputs();
  3915. if (!outputs.empty()) {
  3916. e = cmStrCat(e, "generating\n ", outputs[0]);
  3917. } else {
  3918. e = cmStrCat(e, "driven by\n ", ccRoot.first->GetFullPath());
  3919. }
  3920. e = cmStrCat(e, "\nis attached to multiple targets:");
  3921. for (cmGeneratorTarget const* gt : ccRoot.second) {
  3922. e = cmStrCat(e, "\n ", gt->GetName());
  3923. }
  3924. e = cmStrCat(
  3925. e,
  3926. "\nbut none of these is a common dependency of the other(s). "
  3927. "This is not allowed by the Xcode \"new build system\".");
  3928. generator->IssueMessage(MessageType::FATAL_ERROR, e);
  3929. return false;
  3930. }
  3931. }
  3932. this->CustomCommandRoots.clear();
  3933. }
  3934. // loop over all targets and add link and depend info
  3935. for (auto t : targets) {
  3936. this->AddDependAndLinkInformation(t);
  3937. this->AddEmbeddedFrameworks(t);
  3938. this->AddEmbeddedAppExtensions(t);
  3939. // Inherit project-wide values for any target-specific search paths.
  3940. this->InheritBuildSettingAttribute(t, "HEADER_SEARCH_PATHS");
  3941. this->InheritBuildSettingAttribute(t, "SYSTEM_HEADER_SEARCH_PATHS");
  3942. this->InheritBuildSettingAttribute(t, "FRAMEWORK_SEARCH_PATHS");
  3943. this->InheritBuildSettingAttribute(t, "SYSTEM_FRAMEWORK_SEARCH_PATHS");
  3944. this->InheritBuildSettingAttribute(t, "LIBRARY_SEARCH_PATHS");
  3945. this->InheritBuildSettingAttribute(t, "LD_RUNPATH_SEARCH_PATHS");
  3946. this->InheritBuildSettingAttribute(t, "GCC_PREPROCESSOR_DEFINITIONS");
  3947. this->InheritBuildSettingAttribute(t, "OTHER_CFLAGS");
  3948. this->InheritBuildSettingAttribute(t, "OTHER_LDFLAGS");
  3949. }
  3950. if (this->XcodeBuildSystem == BuildSystem::One) {
  3951. this->CreateXCodeDependHackMakefile(targets);
  3952. }
  3953. // now add all targets to the root object
  3954. cmXCodeObject* allTargets = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3955. for (auto t : targets) {
  3956. allTargets->AddObject(t);
  3957. cmXCodeObject* productRef = t->GetAttribute("productReference");
  3958. if (productRef) {
  3959. productGroupChildren->AddObject(productRef->GetObject());
  3960. }
  3961. }
  3962. this->RootObject->AddAttribute("targets", allTargets);
  3963. return true;
  3964. }
  3965. std::string cmGlobalXCodeGenerator::GetObjectsDirectory(
  3966. const std::string& projName, const std::string& configName,
  3967. const cmGeneratorTarget* t, const std::string& variant) const
  3968. {
  3969. std::string dir = cmStrCat(
  3970. t->GetLocalGenerator()->GetCurrentBinaryDirectory(), '/', projName,
  3971. ".build/", configName, '/', t->GetName(), ".build/", variant);
  3972. return dir;
  3973. }
  3974. void cmGlobalXCodeGenerator::ComputeArchitectures(cmMakefile* mf)
  3975. {
  3976. this->Architectures.clear();
  3977. cmProp sysroot = mf->GetDefinition("CMAKE_OSX_SYSROOT");
  3978. if (sysroot) {
  3979. mf->GetDefExpandList("CMAKE_OSX_ARCHITECTURES", this->Architectures);
  3980. }
  3981. if (this->Architectures.empty()) {
  3982. mf->GetDefExpandList("_CMAKE_APPLE_ARCHS_DEFAULT", this->Architectures);
  3983. }
  3984. if (this->Architectures.empty()) {
  3985. // With no ARCHS we use ONLY_ACTIVE_ARCH and possibly a
  3986. // platform-specific default ARCHS placeholder value.
  3987. // Look up the arch that Xcode chooses in this case.
  3988. if (cmProp arch = mf->GetDefinition("CMAKE_XCODE_ARCHS")) {
  3989. this->ObjectDirArchDefault = *arch;
  3990. // We expect only one arch but choose the first just in case.
  3991. std::string::size_type pos = this->ObjectDirArchDefault.find(';');
  3992. if (pos != std::string::npos) {
  3993. this->ObjectDirArchDefault = this->ObjectDirArchDefault.substr(0, pos);
  3994. }
  3995. }
  3996. }
  3997. this->ComputeObjectDirArch(mf);
  3998. }
  3999. void cmGlobalXCodeGenerator::ComputeObjectDirArch(cmMakefile* mf)
  4000. {
  4001. if (this->Architectures.size() > 1 || this->UseEffectivePlatformName(mf)) {
  4002. this->ObjectDirArch = "$(CURRENT_ARCH)";
  4003. } else if (!this->Architectures.empty()) {
  4004. this->ObjectDirArch = this->Architectures[0];
  4005. } else {
  4006. this->ObjectDirArch = this->ObjectDirArchDefault;
  4007. }
  4008. }
  4009. void cmGlobalXCodeGenerator::CreateXCodeDependHackMakefile(
  4010. std::vector<cmXCodeObject*>& targets)
  4011. {
  4012. cmGeneratedFileStream makefileStream(this->CurrentXCodeHackMakefile);
  4013. if (!makefileStream) {
  4014. cmSystemTools::Error("Could not create " + this->CurrentXCodeHackMakefile);
  4015. return;
  4016. }
  4017. makefileStream.SetCopyIfDifferent(true);
  4018. // one more pass for external depend information not handled
  4019. // correctly by xcode
  4020. /* clang-format off */
  4021. makefileStream << "# DO NOT EDIT\n";
  4022. makefileStream << "# This makefile makes sure all linkable targets are\n";
  4023. makefileStream << "# up-to-date with anything they link to\n"
  4024. "default:\n"
  4025. "\techo \"Do not invoke directly\"\n"
  4026. "\n";
  4027. /* clang-format on */
  4028. std::set<std::string> dummyRules;
  4029. // Write rules to help Xcode relink things at the right time.
  4030. /* clang-format off */
  4031. makefileStream <<
  4032. "# Rules to remove targets that are older than anything to which they\n"
  4033. "# link. This forces Xcode to relink the targets from scratch. It\n"
  4034. "# does not seem to check these dependencies itself.\n";
  4035. /* clang-format on */
  4036. for (const auto& configName : this->CurrentConfigurationTypes) {
  4037. for (auto target : targets) {
  4038. cmGeneratorTarget* gt = target->GetTarget();
  4039. if (gt->GetType() == cmStateEnums::EXECUTABLE ||
  4040. gt->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  4041. gt->GetType() == cmStateEnums::STATIC_LIBRARY ||
  4042. gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4043. gt->GetType() == cmStateEnums::MODULE_LIBRARY) {
  4044. // Declare an entry point for the target post-build phase.
  4045. makefileStream << this->PostBuildMakeTarget(gt->GetName(), configName)
  4046. << ":\n";
  4047. }
  4048. if (gt->GetType() == cmStateEnums::EXECUTABLE ||
  4049. gt->GetType() == cmStateEnums::STATIC_LIBRARY ||
  4050. gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4051. gt->GetType() == cmStateEnums::MODULE_LIBRARY) {
  4052. std::string tfull = gt->GetFullPath(configName);
  4053. std::string trel = this->ConvertToRelativeForMake(tfull);
  4054. // Add this target to the post-build phases of its dependencies.
  4055. auto const y = target->GetDependTargets().find(configName);
  4056. if (y != target->GetDependTargets().end()) {
  4057. for (auto const& deptgt : y->second) {
  4058. makefileStream << this->PostBuildMakeTarget(deptgt, configName)
  4059. << ": " << trel << "\n";
  4060. }
  4061. }
  4062. std::vector<cmGeneratorTarget*> objlibs;
  4063. gt->GetObjectLibrariesCMP0026(objlibs);
  4064. for (auto objLib : objlibs) {
  4065. makefileStream << this->PostBuildMakeTarget(objLib->GetName(),
  4066. configName)
  4067. << ": " << trel << "\n";
  4068. }
  4069. // Create a rule for this target.
  4070. makefileStream << trel << ":";
  4071. // List dependencies if any exist.
  4072. auto const x = target->GetDependLibraries().find(configName);
  4073. if (x != target->GetDependLibraries().end()) {
  4074. for (auto const& deplib : x->second) {
  4075. std::string file = this->ConvertToRelativeForMake(deplib);
  4076. makefileStream << "\\\n\t" << file;
  4077. dummyRules.insert(file);
  4078. }
  4079. }
  4080. for (auto objLib : objlibs) {
  4081. const std::string objLibName = objLib->GetName();
  4082. std::string d = cmStrCat(
  4083. this->GetObjectsDirectory(this->CurrentProject, configName, objLib,
  4084. OBJECT_LIBRARY_ARTIFACT_DIR),
  4085. "lib", objLibName, ".a");
  4086. std::string dependency = this->ConvertToRelativeForMake(d);
  4087. makefileStream << "\\\n\t" << dependency;
  4088. dummyRules.insert(dependency);
  4089. }
  4090. // Write the action to remove the target if it is out of date.
  4091. makefileStream << "\n";
  4092. makefileStream << "\t/bin/rm -f "
  4093. << this->ConvertToRelativeForMake(tfull) << "\n";
  4094. // if building for more than one architecture
  4095. // then remove those executables as well
  4096. if (this->Architectures.size() > 1) {
  4097. std::string universal = this->GetObjectsDirectory(
  4098. this->CurrentProject, configName, gt, "$(OBJDIR)/");
  4099. for (const auto& architecture : this->Architectures) {
  4100. std::string universalFile = cmStrCat(universal, architecture, '/',
  4101. gt->GetFullName(configName));
  4102. makefileStream << "\t/bin/rm -f "
  4103. << this->ConvertToRelativeForMake(universalFile)
  4104. << "\n";
  4105. }
  4106. }
  4107. makefileStream << "\n\n";
  4108. }
  4109. }
  4110. }
  4111. makefileStream << "\n\n"
  4112. << "# For each target create a dummy rule"
  4113. << "so the target does not have to exist\n";
  4114. for (auto const& dummyRule : dummyRules) {
  4115. makefileStream << dummyRule << ":\n";
  4116. }
  4117. }
  4118. void cmGlobalXCodeGenerator::OutputXCodeProject(
  4119. cmLocalGenerator* root, std::vector<cmLocalGenerator*>& generators)
  4120. {
  4121. if (generators.empty()) {
  4122. return;
  4123. }
  4124. if (!this->CreateXCodeObjects(root, generators)) {
  4125. return;
  4126. }
  4127. std::string xcodeDir = cmStrCat(root->GetCurrentBinaryDirectory(), '/',
  4128. root->GetProjectName(), ".xcodeproj");
  4129. cmSystemTools::MakeDirectory(xcodeDir);
  4130. std::string xcodeProjFile = xcodeDir + "/project.pbxproj";
  4131. cmGeneratedFileStream fout(xcodeProjFile);
  4132. fout.SetCopyIfDifferent(true);
  4133. if (!fout) {
  4134. return;
  4135. }
  4136. this->WriteXCodePBXProj(fout, root, generators);
  4137. bool hasGeneratedSchemes = this->OutputXCodeSharedSchemes(xcodeDir, root);
  4138. this->OutputXCodeWorkspaceSettings(xcodeDir, hasGeneratedSchemes);
  4139. this->ClearXCodeObjects();
  4140. // Since this call may have created new cache entries, save the cache:
  4141. //
  4142. root->GetMakefile()->GetCMakeInstance()->SaveCache(
  4143. root->GetBinaryDirectory());
  4144. }
  4145. bool cmGlobalXCodeGenerator::OutputXCodeSharedSchemes(
  4146. const std::string& xcProjDir, cmLocalGenerator* root)
  4147. {
  4148. // collect all tests for the targets
  4149. std::map<std::string, cmXCodeScheme::TestObjects> testables;
  4150. for (const auto& obj : this->XCodeObjects) {
  4151. if (obj->GetType() != cmXCodeObject::OBJECT ||
  4152. obj->GetIsA() != cmXCodeObject::PBXNativeTarget) {
  4153. continue;
  4154. }
  4155. if (!obj->GetTarget()->IsXCTestOnApple()) {
  4156. continue;
  4157. }
  4158. cmProp testee = obj->GetTarget()->GetProperty("XCTEST_TESTEE");
  4159. if (!testee) {
  4160. continue;
  4161. }
  4162. testables[*testee].push_back(obj.get());
  4163. }
  4164. // generate scheme
  4165. bool ret = false;
  4166. // Since the lowest available Xcode version for testing was 6.4,
  4167. // I'm setting this as a limit then
  4168. if (this->XcodeVersion >= 64) {
  4169. for (const auto& obj : this->XCodeObjects) {
  4170. if (obj->GetType() == cmXCodeObject::OBJECT &&
  4171. (obj->GetIsA() == cmXCodeObject::PBXNativeTarget ||
  4172. obj->GetIsA() == cmXCodeObject::PBXAggregateTarget) &&
  4173. (root->GetMakefile()->GetCMakeInstance()->GetIsInTryCompile() ||
  4174. obj->GetTarget()->GetPropertyAsBool("XCODE_GENERATE_SCHEME"))) {
  4175. const std::string& targetName = obj->GetTarget()->GetName();
  4176. cmXCodeScheme schm(root, obj.get(), testables[targetName],
  4177. this->CurrentConfigurationTypes,
  4178. this->XcodeVersion);
  4179. schm.WriteXCodeSharedScheme(xcProjDir,
  4180. this->RelativeToSource(xcProjDir));
  4181. ret = true;
  4182. }
  4183. }
  4184. }
  4185. return ret;
  4186. }
  4187. void cmGlobalXCodeGenerator::OutputXCodeWorkspaceSettings(
  4188. const std::string& xcProjDir, bool hasGeneratedSchemes)
  4189. {
  4190. std::string xcodeSharedDataDir =
  4191. cmStrCat(xcProjDir, "/project.xcworkspace/xcshareddata");
  4192. cmSystemTools::MakeDirectory(xcodeSharedDataDir);
  4193. std::string workspaceSettingsFile =
  4194. cmStrCat(xcodeSharedDataDir, "/WorkspaceSettings.xcsettings");
  4195. cmGeneratedFileStream fout(workspaceSettingsFile);
  4196. fout.SetCopyIfDifferent(true);
  4197. if (!fout) {
  4198. return;
  4199. }
  4200. cmXMLWriter xout(fout);
  4201. xout.StartDocument();
  4202. xout.Doctype("plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\""
  4203. "\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"");
  4204. xout.StartElement("plist");
  4205. xout.Attribute("version", "1.0");
  4206. xout.StartElement("dict");
  4207. if (this->XcodeVersion >= 100) {
  4208. xout.Element("key", "BuildSystemType");
  4209. switch (this->XcodeBuildSystem) {
  4210. case BuildSystem::One:
  4211. xout.Element("string", "Original");
  4212. if (this->XcodeVersion >= 130) {
  4213. xout.Element("key", "DisableBuildSystemDeprecationDiagnostic");
  4214. } else {
  4215. xout.Element("key", "DisableBuildSystemDeprecationWarning");
  4216. }
  4217. xout.Element("true");
  4218. break;
  4219. case BuildSystem::Twelve:
  4220. xout.Element("string", "Latest");
  4221. break;
  4222. }
  4223. }
  4224. if (hasGeneratedSchemes) {
  4225. xout.Element("key",
  4226. "IDEWorkspaceSharedSettings_AutocreateContextsIfNeeded");
  4227. xout.Element("false");
  4228. }
  4229. xout.EndElement(); // dict
  4230. xout.EndElement(); // plist
  4231. xout.EndDocument();
  4232. }
  4233. void cmGlobalXCodeGenerator::WriteXCodePBXProj(std::ostream& fout,
  4234. cmLocalGenerator*,
  4235. std::vector<cmLocalGenerator*>&)
  4236. {
  4237. SortXCodeObjects();
  4238. fout << "// !$*UTF8*$!\n";
  4239. fout << "{\n";
  4240. cmXCodeObject::Indent(1, fout);
  4241. fout << "archiveVersion = 1;\n";
  4242. cmXCodeObject::Indent(1, fout);
  4243. fout << "classes = {\n";
  4244. cmXCodeObject::Indent(1, fout);
  4245. fout << "};\n";
  4246. cmXCodeObject::Indent(1, fout);
  4247. fout << "objectVersion = 46;\n";
  4248. cmXCode21Object::PrintList(this->XCodeObjects, fout);
  4249. cmXCodeObject::Indent(1, fout);
  4250. fout << "rootObject = " << this->RootObject->GetId()
  4251. << " /* Project object */;\n";
  4252. fout << "}\n";
  4253. }
  4254. const char* cmGlobalXCodeGenerator::GetCMakeCFGIntDir() const
  4255. {
  4256. return "$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)";
  4257. }
  4258. std::string cmGlobalXCodeGenerator::ExpandCFGIntDir(
  4259. const std::string& str, const std::string& config) const
  4260. {
  4261. std::string replace1 = "$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)";
  4262. std::string replace2 = "$(CONFIGURATION)";
  4263. std::string tmp = str;
  4264. for (std::string::size_type i = tmp.find(replace1); i != std::string::npos;
  4265. i = tmp.find(replace1, i)) {
  4266. tmp.replace(i, replace1.size(), config);
  4267. i += config.size();
  4268. }
  4269. for (std::string::size_type i = tmp.find(replace2); i != std::string::npos;
  4270. i = tmp.find(replace2, i)) {
  4271. tmp.replace(i, replace2.size(), config);
  4272. i += config.size();
  4273. }
  4274. return tmp;
  4275. }
  4276. void cmGlobalXCodeGenerator::GetDocumentation(cmDocumentationEntry& entry)
  4277. {
  4278. entry.Name = cmGlobalXCodeGenerator::GetActualName();
  4279. entry.Brief = "Generate Xcode project files.";
  4280. }
  4281. std::string cmGlobalXCodeGenerator::ConvertToRelativeForMake(
  4282. std::string const& p)
  4283. {
  4284. return cmSystemTools::ConvertToOutputPath(p);
  4285. }
  4286. std::string cmGlobalXCodeGenerator::RelativeToSource(const std::string& p)
  4287. {
  4288. // We force conversion because Xcode breakpoints do not work unless
  4289. // they are in a file named relative to the source tree.
  4290. return cmSystemTools::ForceToRelativePath(
  4291. this->CurrentRootGenerator->GetCurrentSourceDirectory(), p);
  4292. }
  4293. std::string cmGlobalXCodeGenerator::RelativeToBinary(const std::string& p)
  4294. {
  4295. return this->CurrentRootGenerator->MaybeRelativeToCurBinDir(p);
  4296. }
  4297. std::string cmGlobalXCodeGenerator::XCodeEscapePath(const std::string& p)
  4298. {
  4299. if (p.find_first_of(" []") != std::string::npos) {
  4300. std::string t = cmStrCat('"', p, '"');
  4301. return t;
  4302. }
  4303. return p;
  4304. }
  4305. void cmGlobalXCodeGenerator::AppendDirectoryForConfig(
  4306. const std::string& prefix, const std::string& config,
  4307. const std::string& suffix, std::string& dir)
  4308. {
  4309. if (!config.empty()) {
  4310. dir += prefix;
  4311. dir += config;
  4312. dir += suffix;
  4313. }
  4314. }
  4315. std::string cmGlobalXCodeGenerator::LookupFlags(
  4316. const std::string& varNamePrefix, const std::string& varNameLang,
  4317. const std::string& varNameSuffix, const std::string& default_flags)
  4318. {
  4319. if (!varNameLang.empty()) {
  4320. std::string varName = cmStrCat(varNamePrefix, varNameLang, varNameSuffix);
  4321. if (cmProp varValue = this->CurrentMakefile->GetDefinition(varName)) {
  4322. if (!varValue->empty()) {
  4323. return *varValue;
  4324. }
  4325. }
  4326. }
  4327. return default_flags;
  4328. }
  4329. void cmGlobalXCodeGenerator::AppendDefines(BuildObjectListOrString& defs,
  4330. const char* defines_list,
  4331. bool dflag)
  4332. {
  4333. // Skip this if there are no definitions.
  4334. if (!defines_list) {
  4335. return;
  4336. }
  4337. // Expand the list of definitions.
  4338. std::vector<std::string> defines = cmExpandedList(defines_list);
  4339. // Store the definitions in the string.
  4340. this->AppendDefines(defs, defines, dflag);
  4341. }
  4342. void cmGlobalXCodeGenerator::AppendDefines(
  4343. BuildObjectListOrString& defs, std::vector<std::string> const& defines,
  4344. bool dflag)
  4345. {
  4346. // GCC_PREPROCESSOR_DEFINITIONS is a space-separated list of definitions.
  4347. std::string def;
  4348. for (auto const& define : defines) {
  4349. // Start with -D if requested.
  4350. def = cmStrCat(dflag ? "-D" : "", define);
  4351. // Append the flag with needed escapes.
  4352. std::string tmp;
  4353. this->AppendFlag(tmp, def);
  4354. defs.Add(tmp);
  4355. }
  4356. }
  4357. void cmGlobalXCodeGenerator::AppendFlag(std::string& flags,
  4358. std::string const& flag) const
  4359. {
  4360. // Short-circuit for an empty flag.
  4361. if (flag.empty()) {
  4362. return;
  4363. }
  4364. // Separate from previous flags.
  4365. if (!flags.empty()) {
  4366. flags += " ";
  4367. }
  4368. // Check if the flag needs quoting.
  4369. bool quoteFlag =
  4370. flag.find_first_of("`~!@#$%^&*()+={}[]|:;\"'<>,.? ") != std::string::npos;
  4371. // We escape a flag as follows:
  4372. // - Place each flag in single quotes ''
  4373. // - Escape a single quote as \'
  4374. // - Escape a backslash as \\ since it itself is an escape
  4375. // Note that in the code below we need one more level of escapes for
  4376. // C string syntax in this source file.
  4377. //
  4378. // The final level of escaping is done when the string is stored
  4379. // into the project file by cmXCodeObject::PrintString.
  4380. if (quoteFlag) {
  4381. // Open single quote.
  4382. flags += "'";
  4383. }
  4384. // Flag value with escaped quotes and backslashes.
  4385. for (auto c : flag) {
  4386. if (c == '\'') {
  4387. flags += "'\\''";
  4388. } else if (c == '\\') {
  4389. flags += "\\\\";
  4390. } else {
  4391. flags += c;
  4392. }
  4393. }
  4394. if (quoteFlag) {
  4395. // Close single quote.
  4396. flags += "'";
  4397. }
  4398. }
  4399. std::string cmGlobalXCodeGenerator::ComputeInfoPListLocation(
  4400. cmGeneratorTarget* target)
  4401. {
  4402. std::string plist =
  4403. cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(),
  4404. "/CMakeFiles/", target->GetName(), ".dir/Info.plist");
  4405. return plist;
  4406. }
  4407. // Return true if the generated build tree may contain multiple builds.
  4408. // i.e. "Can I build Debug and Release in the same tree?"
  4409. bool cmGlobalXCodeGenerator::IsMultiConfig() const
  4410. {
  4411. // Newer Xcode versions are multi config:
  4412. return true;
  4413. }
  4414. bool cmGlobalXCodeGenerator::HasKnownObjectFileLocation(
  4415. std::string* reason) const
  4416. {
  4417. if (this->ObjectDirArch.find('$') != std::string::npos) {
  4418. if (reason != nullptr) {
  4419. *reason = " under Xcode with multiple architectures";
  4420. }
  4421. return false;
  4422. }
  4423. return true;
  4424. }
  4425. bool cmGlobalXCodeGenerator::UseEffectivePlatformName(cmMakefile* mf) const
  4426. {
  4427. cmProp epnValue = this->GetCMakeInstance()->GetState()->GetGlobalProperty(
  4428. "XCODE_EMIT_EFFECTIVE_PLATFORM_NAME");
  4429. if (!epnValue) {
  4430. return mf->PlatformIsAppleEmbedded();
  4431. }
  4432. return cmIsOn(*epnValue);
  4433. }
  4434. bool cmGlobalXCodeGenerator::ShouldStripResourcePath(cmMakefile*) const
  4435. {
  4436. // Xcode determines Resource location itself
  4437. return true;
  4438. }
  4439. void cmGlobalXCodeGenerator::ComputeTargetObjectDirectory(
  4440. cmGeneratorTarget* gt) const
  4441. {
  4442. std::string configName = this->GetCMakeCFGIntDir();
  4443. std::string dir =
  4444. cmStrCat(this->GetObjectsDirectory("$(PROJECT_NAME)", configName, gt,
  4445. "$(OBJECT_FILE_DIR_normal:base)/"),
  4446. this->ObjectDirArch, '/');
  4447. gt->ObjectDirectory = dir;
  4448. }
  4449. std::string cmGlobalXCodeGenerator::GetDeploymentPlatform(const cmMakefile* mf)
  4450. {
  4451. switch (mf->GetAppleSDKType()) {
  4452. case cmMakefile::AppleSDK::AppleTVOS:
  4453. case cmMakefile::AppleSDK::AppleTVSimulator:
  4454. return "TVOS_DEPLOYMENT_TARGET";
  4455. case cmMakefile::AppleSDK::IPhoneOS:
  4456. case cmMakefile::AppleSDK::IPhoneSimulator:
  4457. return "IPHONEOS_DEPLOYMENT_TARGET";
  4458. case cmMakefile::AppleSDK::WatchOS:
  4459. case cmMakefile::AppleSDK::WatchSimulator:
  4460. return "WATCHOS_DEPLOYMENT_TARGET";
  4461. case cmMakefile::AppleSDK::MacOS:
  4462. default:
  4463. return "MACOSX_DEPLOYMENT_TARGET";
  4464. }
  4465. }