cmGlobalXCodeGenerator.cxx 130 KB

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