cmGlobalXCodeGenerator.cxx 198 KB

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