cmGlobalXCodeGenerator.cxx 200 KB

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