cmGlobalXCodeGenerator.cxx 131 KB

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