cmGlobalXCodeGenerator.cxx 163 KB

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