cmGlobalXCodeGenerator.cxx 199 KB

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