cmGlobalXCodeGenerator.cxx 173 KB

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