cmGlobalXCodeGenerator.cxx 195 KB

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