cmGlobalXCodeGenerator.cxx 175 KB

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