cmGlobalXCodeGenerator.cxx 164 KB

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