cmGlobalXCodeGenerator.cxx 130 KB

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