cmGlobalXCodeGenerator.cxx 131 KB

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