cmGlobalXCodeGenerator.cxx 130 KB

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