cmGlobalXCodeGenerator.cxx 170 KB

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