cmGlobalXCodeGenerator.cxx 150 KB

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