cmGlobalXCodeGenerator.cxx 180 KB

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