cmGlobalXCodeGenerator.cxx 162 KB

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