cmGlobalXCodeGenerator.cxx 130 KB

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