cmGlobalXCodeGenerator.cxx 130 KB

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