cmGlobalXCodeGenerator.cxx 169 KB

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