cmGlobalXCodeGenerator.cxx 165 KB

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