cmGlobalXCodeGenerator.cxx 142 KB

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