cmGlobalXCodeGenerator.cxx 195 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434
  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(std::string const& 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. if (char const* productType = GetTargetProductType(gtgt)) {
  1530. if (strcmp(productType,
  1531. "com.apple.product-type.app-extension.messages-sticker-pack") ==
  1532. 0) {
  1533. return;
  1534. }
  1535. }
  1536. // Add an empty source file to the target that compiles with the
  1537. // linker language. This should convince Xcode to choose the proper
  1538. // language.
  1539. cmMakefile* mf = gtgt->Target->GetMakefile();
  1540. std::string fname = cmStrCat(
  1541. gtgt->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/CMakeFiles/",
  1542. gtgt->GetName(), "-CMakeForceLinker.", cmSystemTools::LowerCase(llang));
  1543. {
  1544. cmGeneratedFileStream fout(fname);
  1545. fout << '\n';
  1546. }
  1547. if (cmSourceFile* sf = mf->GetOrCreateSource(fname)) {
  1548. sf->SetProperty("LANGUAGE", llang);
  1549. sf->SetProperty("CXX_SCAN_FOR_MODULES", "0");
  1550. gtgt->AddSource(fname);
  1551. }
  1552. }
  1553. bool cmGlobalXCodeGenerator::IsHeaderFile(cmSourceFile* sf)
  1554. {
  1555. return cm::contains(this->CMakeInstance->GetHeaderExtensions(),
  1556. sf->GetExtension());
  1557. }
  1558. cmXCodeObject* cmGlobalXCodeGenerator::CreateLegacyRunScriptBuildPhase(
  1559. char const* name, char const* name2, cmGeneratorTarget* target,
  1560. std::vector<cmCustomCommand> const& commands)
  1561. {
  1562. if (commands.empty() && strcmp(name, "CMake ReRun") != 0) {
  1563. return nullptr;
  1564. }
  1565. cmXCodeObject* buildPhase =
  1566. this->CreateObject(cmXCodeObject::PBXShellScriptBuildPhase);
  1567. buildPhase->AddAttribute("buildActionMask",
  1568. this->CreateString("2147483647"));
  1569. cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1570. buildPhase->AddAttribute("files", buildFiles);
  1571. buildPhase->AddAttribute("name", this->CreateString(name));
  1572. buildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1573. this->CreateString("0"));
  1574. buildPhase->AddAttribute("shellPath", this->CreateString("/bin/sh"));
  1575. this->AddCommandsToBuildPhase(buildPhase, target, commands, name2);
  1576. return buildPhase;
  1577. }
  1578. void cmGlobalXCodeGenerator::CreateCustomCommands(
  1579. cmXCodeObject* buildPhases, cmXCodeObject* sourceBuildPhase,
  1580. cmXCodeObject* headerBuildPhase, cmXCodeObject* resourceBuildPhase,
  1581. std::vector<cmXCodeObject*> const& contentBuildPhases,
  1582. cmXCodeObject* frameworkBuildPhase, cmGeneratorTarget* gtgt)
  1583. {
  1584. std::vector<cmCustomCommand> const& prebuild = gtgt->GetPreBuildCommands();
  1585. std::vector<cmCustomCommand> const& prelink = gtgt->GetPreLinkCommands();
  1586. std::vector<cmCustomCommand> postbuild = gtgt->GetPostBuildCommands();
  1587. if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY &&
  1588. !gtgt->IsFrameworkOnApple()) {
  1589. std::string str_file = cmStrCat("$<TARGET_FILE:", gtgt->GetName(), '>');
  1590. std::string str_so_file =
  1591. cmStrCat("$<TARGET_SONAME_FILE:", gtgt->GetName(), '>');
  1592. std::string str_link_file =
  1593. cmStrCat("$<TARGET_LINKER_LIBRARY_FILE:", gtgt->GetName(), '>');
  1594. cmCustomCommandLines cmd = cmMakeSingleCommandLine(
  1595. { cmSystemTools::GetCMakeCommand(), "-E", "cmake_symlink_library",
  1596. str_file, str_so_file, str_link_file });
  1597. cmCustomCommand command;
  1598. command.SetCommandLines(cmd);
  1599. command.SetComment("Creating symlinks");
  1600. command.SetWorkingDirectory("");
  1601. command.SetBacktrace(this->CurrentMakefile->GetBacktrace());
  1602. command.SetStdPipesUTF8(true);
  1603. postbuild.push_back(std::move(command));
  1604. }
  1605. if (gtgt->HasImportLibrary("") && !gtgt->IsFrameworkOnApple()) {
  1606. // create symbolic links for .tbd file
  1607. std::string file = cmStrCat("$<TARGET_IMPORT_FILE:", gtgt->GetName(), '>');
  1608. std::string soFile =
  1609. cmStrCat("$<TARGET_SONAME_IMPORT_FILE:", gtgt->GetName(), '>');
  1610. std::string linkFile =
  1611. cmStrCat("$<TARGET_LINKER_IMPORT_FILE:", gtgt->GetName(), '>');
  1612. cmCustomCommandLines symlink_command = cmMakeSingleCommandLine(
  1613. { cmSystemTools::GetCMakeCommand(), "-E", "cmake_symlink_library", file,
  1614. soFile, linkFile });
  1615. cmCustomCommand command;
  1616. command.SetCommandLines(symlink_command);
  1617. command.SetComment("Creating import symlinks");
  1618. command.SetWorkingDirectory("");
  1619. command.SetBacktrace(this->CurrentMakefile->GetBacktrace());
  1620. command.SetStdPipesUTF8(true);
  1621. postbuild.push_back(std::move(command));
  1622. }
  1623. cmXCodeObject* legacyCustomCommandsBuildPhase = nullptr;
  1624. cmXCodeObject* preBuildPhase = nullptr;
  1625. cmXCodeObject* preLinkPhase = nullptr;
  1626. cmXCodeObject* postBuildPhase = nullptr;
  1627. if (this->XcodeBuildSystem >= BuildSystem::Twelve) {
  1628. // create prebuild phase
  1629. preBuildPhase =
  1630. this->CreateRunScriptBuildPhase("CMake PreBuild Rules", gtgt, prebuild);
  1631. // create prelink phase
  1632. preLinkPhase =
  1633. this->CreateRunScriptBuildPhase("CMake PreLink Rules", gtgt, prelink);
  1634. std::vector<std::string> depends;
  1635. if (gtgt->IsBundleOnApple()) {
  1636. // In Xcode 16+ the POST_BUILD phase needs explicit dependencies to
  1637. // ensure it runs after certain bundle files are generated.
  1638. depends = {
  1639. "${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}/"
  1640. "Contents/Resources/DWARF/${PRODUCT_NAME}",
  1641. "${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}/"
  1642. "Contents/Info.plist",
  1643. "$(TARGET_BUILD_DIR)/$(EXECUTABLE_PATH)",
  1644. "$(TARGET_BUILD_DIR)/$(INFOPLIST_PATH)",
  1645. };
  1646. if (resourceBuildPhase) {
  1647. auto resourceFiles = resourceBuildPhase->GetAttribute("files");
  1648. for (auto xsf : resourceFiles->GetObjectList()) {
  1649. auto fileRef = xsf->GetAttribute("fileRef");
  1650. auto fileObj = fileRef->GetObject();
  1651. auto path = fileObj->GetAttribute("path");
  1652. auto fileName = cmSystemTools::GetFilenameName(path->GetString());
  1653. if (cmSystemTools::GetFilenameLastExtension(fileName) == ".plist") {
  1654. depends.push_back(
  1655. "$(TARGET_BUILD_DIR)/$(UNLOCALIZED_RESOURCES_FOLDER_PATH)/" +
  1656. fileName);
  1657. }
  1658. }
  1659. }
  1660. }
  1661. // create postbuild phase
  1662. postBuildPhase = this->CreateRunScriptBuildPhase("CMake PostBuild Rules",
  1663. gtgt, postbuild, depends);
  1664. } else {
  1665. std::vector<cmSourceFile*> classes;
  1666. if (!gtgt->GetConfigCommonSourceFilesForXcode(classes)) {
  1667. return;
  1668. }
  1669. // add all the sources
  1670. std::vector<cmCustomCommand> commands;
  1671. auto& visited = this->CommandsVisited[gtgt];
  1672. for (auto* sourceFile : classes) {
  1673. if (sourceFile->GetCustomCommand() &&
  1674. visited.insert(sourceFile).second) {
  1675. commands.push_back(*sourceFile->GetCustomCommand());
  1676. }
  1677. }
  1678. // create custom commands phase
  1679. legacyCustomCommandsBuildPhase = this->CreateLegacyRunScriptBuildPhase(
  1680. "CMake Rules", "cmakeRulesBuildPhase", gtgt, commands);
  1681. // create prebuild phase
  1682. preBuildPhase = this->CreateLegacyRunScriptBuildPhase(
  1683. "CMake PreBuild Rules", "preBuildCommands", gtgt, prebuild);
  1684. // create prelink phase
  1685. preLinkPhase = this->CreateLegacyRunScriptBuildPhase(
  1686. "CMake PreLink Rules", "preLinkCommands", gtgt, prelink);
  1687. // create postbuild phase
  1688. postBuildPhase = this->CreateLegacyRunScriptBuildPhase(
  1689. "CMake PostBuild Rules", "postBuildPhase", gtgt, postbuild);
  1690. }
  1691. // The order here is the order they will be built in.
  1692. // The order "headers, resources, sources" mimics a native project generated
  1693. // from an xcode template...
  1694. //
  1695. if (preBuildPhase) {
  1696. buildPhases->AddObject(preBuildPhase);
  1697. }
  1698. if (legacyCustomCommandsBuildPhase) {
  1699. buildPhases->AddObject(legacyCustomCommandsBuildPhase);
  1700. }
  1701. if (this->XcodeBuildSystem >= BuildSystem::Twelve) {
  1702. this->CreateRunScriptBuildPhases(buildPhases, gtgt);
  1703. }
  1704. if (headerBuildPhase) {
  1705. buildPhases->AddObject(headerBuildPhase);
  1706. }
  1707. if (resourceBuildPhase) {
  1708. buildPhases->AddObject(resourceBuildPhase);
  1709. }
  1710. for (auto* obj : contentBuildPhases) {
  1711. buildPhases->AddObject(obj);
  1712. }
  1713. if (sourceBuildPhase) {
  1714. buildPhases->AddObject(sourceBuildPhase);
  1715. }
  1716. if (preLinkPhase) {
  1717. buildPhases->AddObject(preLinkPhase);
  1718. }
  1719. if (frameworkBuildPhase) {
  1720. buildPhases->AddObject(frameworkBuildPhase);
  1721. }
  1722. // When this build phase is present, it must be last. More build phases may
  1723. // be added later for embedding things and they will insert themselves just
  1724. // before this last build phase.
  1725. if (postBuildPhase) {
  1726. buildPhases->AddObject(postBuildPhase);
  1727. }
  1728. }
  1729. void cmGlobalXCodeGenerator::CreateRunScriptBuildPhases(
  1730. cmXCodeObject* buildPhases, cmGeneratorTarget const* gt)
  1731. {
  1732. std::vector<cmSourceFile*> sources;
  1733. if (!gt->GetConfigCommonSourceFilesForXcode(sources)) {
  1734. return;
  1735. }
  1736. auto& visited = this->CommandsVisited[gt];
  1737. for (auto* sf : sources) {
  1738. this->CreateRunScriptBuildPhases(buildPhases, sf, gt, visited);
  1739. }
  1740. }
  1741. void cmGlobalXCodeGenerator::CreateRunScriptBuildPhases(
  1742. cmXCodeObject* buildPhases, cmSourceFile const* sf,
  1743. cmGeneratorTarget const* gt, std::set<cmSourceFile const*>& visited)
  1744. {
  1745. cmCustomCommand const* cc = sf->GetCustomCommand();
  1746. if (cc && visited.insert(sf).second) {
  1747. this->CustomCommandRoots[sf].insert(gt);
  1748. if (std::vector<cmSourceFile*> const* depends = gt->GetSourceDepends(sf)) {
  1749. for (cmSourceFile const* di : *depends) {
  1750. this->CreateRunScriptBuildPhases(buildPhases, di, gt, visited);
  1751. }
  1752. }
  1753. cmXCodeObject* buildPhase = this->CreateRunScriptBuildPhase(sf, gt, *cc);
  1754. buildPhases->AddObject(buildPhase);
  1755. }
  1756. }
  1757. cmXCodeObject* cmGlobalXCodeGenerator::CreateRunScriptBuildPhase(
  1758. cmSourceFile const* sf, cmGeneratorTarget const* gt,
  1759. cmCustomCommand const& cc)
  1760. {
  1761. std::set<std::string> allConfigInputs;
  1762. std::set<std::string> allConfigOutputs;
  1763. cmXCodeObject* buildPhase =
  1764. this->CreateObject(cmXCodeObject::PBXShellScriptBuildPhase,
  1765. cmStrCat(gt->GetName(), ':', sf->GetFullPath()));
  1766. auto depfilesDirectory = cmStrCat(
  1767. gt->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/CMakeFiles/d/");
  1768. auto depfilesPrefix = cmStrCat(depfilesDirectory, buildPhase->GetId(), '.');
  1769. std::string shellScript = "set -e\n";
  1770. for (std::string const& configName : this->CurrentConfigurationTypes) {
  1771. cmCustomCommandGenerator ccg(
  1772. cc, configName, this->CurrentLocalGenerator, true, {},
  1773. [&depfilesPrefix](std::string const& config, std::string const&)
  1774. -> std::string { return cmStrCat(depfilesPrefix, config, ".d"); });
  1775. std::vector<std::string> realDepends;
  1776. realDepends.reserve(ccg.GetDepends().size());
  1777. for (auto const& d : ccg.GetDepends()) {
  1778. std::string dep;
  1779. if (this->CurrentLocalGenerator->GetRealDependency(d, configName, dep)) {
  1780. realDepends.emplace_back(std::move(dep));
  1781. }
  1782. }
  1783. allConfigInputs.insert(realDepends.begin(), realDepends.end());
  1784. allConfigOutputs.insert(ccg.GetByproducts().begin(),
  1785. ccg.GetByproducts().end());
  1786. allConfigOutputs.insert(ccg.GetOutputs().begin(), ccg.GetOutputs().end());
  1787. shellScript =
  1788. cmStrCat(shellScript, R"(if test "$CONFIGURATION" = ")", configName,
  1789. "\"; then :\n", this->ConstructScript(ccg), "fi\n");
  1790. }
  1791. if (!cc.GetDepfile().empty()) {
  1792. buildPhase->AddAttribute(
  1793. "dependencyFile",
  1794. this->CreateString(cmStrCat(depfilesDirectory, buildPhase->GetId(),
  1795. ".$(CONFIGURATION).d")));
  1796. // to avoid spurious errors during first build, create empty dependency
  1797. // files
  1798. cmSystemTools::MakeDirectory(depfilesDirectory);
  1799. for (std::string const& configName : this->CurrentConfigurationTypes) {
  1800. auto file = cmStrCat(depfilesPrefix, configName, ".d");
  1801. if (!cmSystemTools::FileExists(file)) {
  1802. cmSystemTools::Touch(file, true);
  1803. }
  1804. }
  1805. }
  1806. buildPhase->AddAttribute("buildActionMask",
  1807. this->CreateString("2147483647"));
  1808. cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1809. buildPhase->AddAttribute("files", buildFiles);
  1810. {
  1811. std::string name;
  1812. if (!allConfigOutputs.empty()) {
  1813. name = cmStrCat("Generate ",
  1814. this->RelativeToBinary(*allConfigOutputs.begin()));
  1815. } else {
  1816. name = sf->GetLocation().GetName();
  1817. }
  1818. buildPhase->AddAttribute("name", this->CreateString(name));
  1819. }
  1820. buildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1821. this->CreateString("0"));
  1822. buildPhase->AddAttribute("shellPath", this->CreateString("/bin/sh"));
  1823. buildPhase->AddAttribute("shellScript", this->CreateString(shellScript));
  1824. buildPhase->AddAttribute("showEnvVarsInLog", this->CreateString("0"));
  1825. bool symbolic = false;
  1826. {
  1827. cmXCodeObject* inputPaths = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1828. for (std::string const& i : allConfigInputs) {
  1829. inputPaths->AddUniqueObject(this->CreateString(i));
  1830. if (!symbolic) {
  1831. if (cmSourceFile* isf =
  1832. gt->GetLocalGenerator()->GetMakefile()->GetSource(
  1833. i, cmSourceFileLocationKind::Known)) {
  1834. symbolic = isf->GetPropertyAsBool("SYMBOLIC");
  1835. }
  1836. }
  1837. }
  1838. buildPhase->AddAttribute("inputPaths", inputPaths);
  1839. }
  1840. {
  1841. cmXCodeObject* outputPaths =
  1842. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1843. for (std::string const& o : allConfigOutputs) {
  1844. outputPaths->AddUniqueObject(this->CreateString(o));
  1845. if (!symbolic) {
  1846. if (cmSourceFile* osf =
  1847. gt->GetLocalGenerator()->GetMakefile()->GetSource(
  1848. o, cmSourceFileLocationKind::Known)) {
  1849. symbolic = osf->GetPropertyAsBool("SYMBOLIC");
  1850. }
  1851. }
  1852. }
  1853. buildPhase->AddAttribute("outputPaths", outputPaths);
  1854. }
  1855. if (symbolic) {
  1856. buildPhase->AddAttribute("alwaysOutOfDate", this->CreateString("1"));
  1857. }
  1858. return buildPhase;
  1859. }
  1860. cmXCodeObject* cmGlobalXCodeGenerator::CreateRunScriptBuildPhase(
  1861. std::string const& name, cmGeneratorTarget const* gt,
  1862. std::vector<cmCustomCommand> const& commands,
  1863. std::vector<std::string> const& depends)
  1864. {
  1865. if (commands.empty()) {
  1866. return nullptr;
  1867. }
  1868. std::set<std::string> allConfigOutputs;
  1869. std::string shellScript = "set -e\n";
  1870. for (std::string const& configName : this->CurrentConfigurationTypes) {
  1871. shellScript = cmStrCat(shellScript, R"(if test "$CONFIGURATION" = ")",
  1872. configName, "\"; then :\n");
  1873. for (cmCustomCommand const& cc : commands) {
  1874. cmCustomCommandGenerator ccg(cc, configName,
  1875. this->CurrentLocalGenerator);
  1876. shellScript = cmStrCat(shellScript, this->ConstructScript(ccg));
  1877. allConfigOutputs.insert(ccg.GetByproducts().begin(),
  1878. ccg.GetByproducts().end());
  1879. }
  1880. shellScript = cmStrCat(shellScript, "fi\n");
  1881. }
  1882. cmXCodeObject* buildPhase =
  1883. this->CreateObject(cmXCodeObject::PBXShellScriptBuildPhase,
  1884. cmStrCat(gt->GetName(), ':', name));
  1885. buildPhase->AddAttribute("buildActionMask",
  1886. this->CreateString("2147483647"));
  1887. cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1888. buildPhase->AddAttribute("files", buildFiles);
  1889. buildPhase->AddAttribute("name", this->CreateString(name));
  1890. buildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1891. this->CreateString("0"));
  1892. buildPhase->AddAttribute("shellPath", this->CreateString("/bin/sh"));
  1893. buildPhase->AddAttribute("shellScript", this->CreateString(shellScript));
  1894. buildPhase->AddAttribute("showEnvVarsInLog", this->CreateString("0"));
  1895. {
  1896. cmXCodeObject* inputPaths = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1897. for (std::string const& s : depends) {
  1898. inputPaths->AddUniqueObject(this->CreateString(s));
  1899. }
  1900. buildPhase->AddAttribute("inputPaths", inputPaths);
  1901. }
  1902. {
  1903. cmXCodeObject* outputPaths =
  1904. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1905. for (std::string const& o : allConfigOutputs) {
  1906. outputPaths->AddUniqueObject(this->CreateString(o));
  1907. }
  1908. buildPhase->AddAttribute("outputPaths", outputPaths);
  1909. }
  1910. buildPhase->AddAttribute("alwaysOutOfDate", this->CreateString("1"));
  1911. return buildPhase;
  1912. }
  1913. namespace {
  1914. void ReplaceScriptVars(std::string& cmd)
  1915. {
  1916. cmSystemTools::ReplaceString(cmd, "$(CONFIGURATION)", "$CONFIGURATION");
  1917. cmSystemTools::ReplaceString(cmd, "$(EFFECTIVE_PLATFORM_NAME)",
  1918. "$EFFECTIVE_PLATFORM_NAME");
  1919. }
  1920. }
  1921. std::string cmGlobalXCodeGenerator::ConstructScript(
  1922. cmCustomCommandGenerator const& ccg)
  1923. {
  1924. std::string script;
  1925. cmLocalGenerator* lg = this->CurrentLocalGenerator;
  1926. std::string wd = ccg.GetWorkingDirectory();
  1927. if (wd.empty()) {
  1928. wd = lg->GetCurrentBinaryDirectory();
  1929. }
  1930. wd = lg->ConvertToOutputFormat(wd, cmOutputConverter::SHELL);
  1931. ReplaceScriptVars(wd);
  1932. script = cmStrCat(script, " cd ", wd, '\n');
  1933. for (unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) {
  1934. std::string cmd = ccg.GetCommand(c);
  1935. if (cmd.empty()) {
  1936. continue;
  1937. }
  1938. cmSystemTools::ReplaceString(cmd, "/./", "/");
  1939. cmd = lg->ConvertToOutputFormat(cmd, cmOutputConverter::SHELL);
  1940. ccg.AppendArguments(c, cmd);
  1941. ReplaceScriptVars(cmd);
  1942. script = cmStrCat(script, " ", cmd, '\n');
  1943. }
  1944. return script;
  1945. }
  1946. // This function removes each occurrence of the flag and returns the last one
  1947. // (i.e., the dominant flag in GCC)
  1948. std::string cmGlobalXCodeGenerator::ExtractFlag(char const* flag,
  1949. std::string& flags)
  1950. {
  1951. std::string retFlag;
  1952. std::string::size_type lastOccurrencePos = flags.rfind(flag);
  1953. bool saved = false;
  1954. while (lastOccurrencePos != std::string::npos) {
  1955. // increment pos, we use lastOccurrencePos to reduce search space on next
  1956. // inc
  1957. std::string::size_type pos = lastOccurrencePos;
  1958. if (pos == 0 || flags[pos - 1] == ' ') {
  1959. while (pos < flags.size() && flags[pos] != ' ') {
  1960. if (!saved) {
  1961. retFlag += flags[pos];
  1962. }
  1963. flags[pos] = ' ';
  1964. pos++;
  1965. }
  1966. saved = true;
  1967. }
  1968. // decrement lastOccurrencePos while making sure we don't loop around
  1969. // and become a very large positive number since size_type is unsigned
  1970. lastOccurrencePos = lastOccurrencePos == 0 ? 0 : lastOccurrencePos - 1;
  1971. lastOccurrencePos = flags.rfind(flag, lastOccurrencePos);
  1972. }
  1973. return retFlag;
  1974. }
  1975. // This function removes each matching occurrence of the expression and
  1976. // returns the last one (i.e., the dominant flag in GCC)
  1977. std::string cmGlobalXCodeGenerator::ExtractFlagRegex(char const* exp,
  1978. int matchIndex,
  1979. std::string& flags)
  1980. {
  1981. std::string retFlag;
  1982. cmsys::RegularExpression regex(exp);
  1983. assert(regex.is_valid());
  1984. if (!regex.is_valid()) {
  1985. return retFlag;
  1986. }
  1987. std::string::size_type offset = 0;
  1988. while (regex.find(&flags[offset])) {
  1989. std::string::size_type const startPos = offset + regex.start(matchIndex);
  1990. std::string::size_type const endPos = offset + regex.end(matchIndex);
  1991. std::string::size_type const size = endPos - startPos;
  1992. offset = startPos + 1;
  1993. retFlag.assign(flags, startPos, size);
  1994. flags.replace(startPos, size, size, ' ');
  1995. }
  1996. return retFlag;
  1997. }
  1998. //----------------------------------------------------------------------------
  1999. // This function strips off Xcode attributes that do not target the current
  2000. // configuration
  2001. void cmGlobalXCodeGenerator::FilterConfigurationAttribute(
  2002. std::string const& configName, std::string& attribute)
  2003. {
  2004. // Handle [variant=<config>] condition explicitly here.
  2005. std::string::size_type beginVariant = attribute.find("[variant=");
  2006. if (beginVariant == std::string::npos) {
  2007. // There is no variant in this attribute.
  2008. return;
  2009. }
  2010. std::string::size_type endVariant = attribute.find(']', beginVariant + 9);
  2011. if (endVariant == std::string::npos) {
  2012. // There is no terminating bracket.
  2013. return;
  2014. }
  2015. // Compare the variant to the configuration.
  2016. std::string variant =
  2017. attribute.substr(beginVariant + 9, endVariant - beginVariant - 9);
  2018. if (variant == configName) {
  2019. // The variant matches the configuration so use this
  2020. // attribute but drop the [variant=<config>] condition.
  2021. attribute.erase(beginVariant, endVariant - beginVariant + 1);
  2022. } else {
  2023. // The variant does not match the configuration so
  2024. // do not use this attribute.
  2025. attribute.clear();
  2026. }
  2027. }
  2028. void cmGlobalXCodeGenerator::AddCommandsToBuildPhase(
  2029. cmXCodeObject* buildphase, cmGeneratorTarget* target,
  2030. std::vector<cmCustomCommand> const& commands, char const* name)
  2031. {
  2032. std::string dir = cmStrCat(
  2033. this->CurrentLocalGenerator->GetCurrentBinaryDirectory(), "/CMakeScripts");
  2034. cmSystemTools::MakeDirectory(dir);
  2035. std::string makefile =
  2036. cmStrCat(dir, '/', target->GetName(), '_', name, ".make");
  2037. for (auto const& currentConfig : this->CurrentConfigurationTypes) {
  2038. this->CreateCustomRulesMakefile(makefile.c_str(), target, commands,
  2039. currentConfig);
  2040. }
  2041. std::string cdir = this->CurrentLocalGenerator->GetCurrentBinaryDirectory();
  2042. cdir = cmSystemTools::ConvertToOutputPath(cdir);
  2043. std::string makecmd = cmStrCat(
  2044. "make -C ", cdir, " -f ", cmSystemTools::ConvertToOutputPath(makefile),
  2045. "$CONFIGURATION", " OBJDIR=$(basename \"$OBJECT_FILE_DIR_normal\") all");
  2046. buildphase->AddAttribute("shellScript", this->CreateString(makecmd));
  2047. buildphase->AddAttribute("showEnvVarsInLog", this->CreateString("0"));
  2048. }
  2049. void cmGlobalXCodeGenerator::CreateCustomRulesMakefile(
  2050. char const* makefileBasename, cmGeneratorTarget* target,
  2051. std::vector<cmCustomCommand> const& commands, std::string const& configName)
  2052. {
  2053. std::string makefileName = cmStrCat(makefileBasename, configName);
  2054. cmGeneratedFileStream makefileStream(makefileName);
  2055. if (!makefileStream) {
  2056. return;
  2057. }
  2058. makefileStream.SetCopyIfDifferent(true);
  2059. makefileStream << "# Generated by CMake, DO NOT EDIT\n"
  2060. "# Custom rules for "
  2061. << target->GetName() << '\n';
  2062. // disable the implicit rules
  2063. makefileStream << ".SUFFIXES: "
  2064. "\n";
  2065. // have all depend on all outputs
  2066. makefileStream << "all: ";
  2067. std::map<cmCustomCommand const*, std::string> tname;
  2068. int count = 0;
  2069. for (auto const& command : commands) {
  2070. cmCustomCommandGenerator ccg(command, configName,
  2071. this->CurrentLocalGenerator);
  2072. if (ccg.GetNumberOfCommands() > 0) {
  2073. std::vector<std::string> const& outputs = ccg.GetOutputs();
  2074. if (!outputs.empty()) {
  2075. for (auto const& output : outputs) {
  2076. makefileStream << "\\\n\t" << ConvertToMakefilePath(output);
  2077. }
  2078. } else {
  2079. std::ostringstream str;
  2080. str << "_buildpart_" << count++;
  2081. tname[&ccg.GetCC()] = cmStrCat(target->GetName(), str.str());
  2082. makefileStream << "\\\n\t" << tname[&ccg.GetCC()];
  2083. }
  2084. }
  2085. }
  2086. makefileStream << "\n\n";
  2087. auto depfilesDirectory =
  2088. cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(),
  2089. "/CMakeFiles/d/");
  2090. for (auto const& command : commands) {
  2091. cmCustomCommandGenerator ccg(
  2092. command, configName, this->CurrentLocalGenerator, true, {},
  2093. [this, &depfilesDirectory](std::string const& config,
  2094. std::string const& file) -> std::string {
  2095. return cmStrCat(
  2096. depfilesDirectory,
  2097. this->GetObjectId(cmXCodeObject::PBXShellScriptBuildPhase, file),
  2098. '.', config, ".d");
  2099. });
  2100. auto depfile = ccg.GetInternalDepfile();
  2101. if (!depfile.empty()) {
  2102. makefileStream << "include "
  2103. << cmSystemTools::ConvertToOutputPath(depfile) << "\n\n";
  2104. cmSystemTools::MakeDirectory(depfilesDirectory);
  2105. if (!cmSystemTools::FileExists(depfile)) {
  2106. cmSystemTools::Touch(depfile, true);
  2107. }
  2108. }
  2109. std::vector<std::string> realDepends;
  2110. realDepends.reserve(ccg.GetDepends().size());
  2111. for (auto const& d : ccg.GetDepends()) {
  2112. std::string dep;
  2113. if (this->CurrentLocalGenerator->GetRealDependency(d, configName, dep)) {
  2114. realDepends.emplace_back(std::move(dep));
  2115. }
  2116. }
  2117. if (ccg.GetNumberOfCommands() > 0) {
  2118. makefileStream << '\n';
  2119. std::vector<std::string> const& outputs = ccg.GetOutputs();
  2120. if (!outputs.empty()) {
  2121. // There is at least one output, start the rule for it
  2122. char const* sep = "";
  2123. for (auto const& output : outputs) {
  2124. makefileStream << sep << ConvertToMakefilePath(output);
  2125. sep = " ";
  2126. }
  2127. makefileStream << ": ";
  2128. } else {
  2129. // There are no outputs. Use the generated force rule name.
  2130. makefileStream << tname[&ccg.GetCC()] << ": ";
  2131. }
  2132. for (auto const& dep : realDepends) {
  2133. makefileStream << "\\\n" << ConvertToMakefilePath(dep);
  2134. }
  2135. makefileStream << '\n';
  2136. if (cm::optional<std::string> comment = ccg.GetComment()) {
  2137. std::string echo_cmd =
  2138. cmStrCat("echo ",
  2139. (this->CurrentLocalGenerator->EscapeForShell(
  2140. *comment, ccg.GetCC().GetEscapeAllowMakeVars())));
  2141. makefileStream << '\t' << echo_cmd << '\n';
  2142. }
  2143. // Add each command line to the set of commands.
  2144. for (unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) {
  2145. // Build the command line in a single string.
  2146. std::string cmd2 = ccg.GetCommand(c);
  2147. cmSystemTools::ReplaceString(cmd2, "/./", "/");
  2148. cmd2 = ConvertToMakefilePath(cmd2);
  2149. std::string cmd;
  2150. std::string wd = ccg.GetWorkingDirectory();
  2151. if (!wd.empty()) {
  2152. cmd += "cd ";
  2153. cmd += ConvertToMakefilePath(wd);
  2154. cmd += " && ";
  2155. }
  2156. cmd += cmd2;
  2157. ccg.AppendArguments(c, cmd);
  2158. makefileStream << '\t' << cmd << '\n';
  2159. }
  2160. // Symbolic inputs are not expected to exist, so add dummy rules.
  2161. for (auto const& dep : realDepends) {
  2162. if (cmSourceFile* dsf =
  2163. target->GetLocalGenerator()->GetMakefile()->GetSource(
  2164. dep, cmSourceFileLocationKind::Known)) {
  2165. if (dsf->GetPropertyAsBool("SYMBOLIC")) {
  2166. makefileStream << ConvertToMakefilePath(dep) << ":\n";
  2167. }
  2168. }
  2169. }
  2170. }
  2171. }
  2172. }
  2173. void cmGlobalXCodeGenerator::AddPositionIndependentLinkAttribute(
  2174. cmGeneratorTarget* target, cmXCodeObject* buildSettings,
  2175. std::string const& configName)
  2176. {
  2177. // For now, only EXECUTABLE is concerned
  2178. if (target->GetType() != cmStateEnums::EXECUTABLE) {
  2179. return;
  2180. }
  2181. char const* PICValue = target->GetLinkPIEProperty(configName);
  2182. if (PICValue == nullptr) {
  2183. // POSITION_INDEPENDENT_CODE is not set
  2184. return;
  2185. }
  2186. buildSettings->AddAttribute(
  2187. "LD_NO_PIE", this->CreateString(cmIsOn(PICValue) ? "NO" : "YES"));
  2188. }
  2189. void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
  2190. cmXCodeObject* buildSettings,
  2191. std::string const& configName)
  2192. {
  2193. if (!gtgt->IsInBuildSystem()) {
  2194. return;
  2195. }
  2196. std::string defFlags;
  2197. bool shared = ((gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) ||
  2198. (gtgt->GetType() == cmStateEnums::MODULE_LIBRARY));
  2199. bool binary = ((gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY) ||
  2200. (gtgt->GetType() == cmStateEnums::STATIC_LIBRARY) ||
  2201. (gtgt->GetType() == cmStateEnums::EXECUTABLE) || shared);
  2202. // Compute the compilation flags for each language.
  2203. std::set<std::string> languages;
  2204. gtgt->GetLanguages(languages, configName);
  2205. std::map<std::string, std::string> cflags;
  2206. for (auto const& lang : languages) {
  2207. std::string& flags = cflags[lang];
  2208. // Add language-specific flags.
  2209. this->CurrentLocalGenerator->AddLanguageFlags(
  2210. flags, gtgt, cmBuildStep::Compile, lang, configName);
  2211. if (gtgt->IsIPOEnabled(lang, configName)) {
  2212. this->CurrentLocalGenerator->AppendFeatureOptions(flags, lang, "IPO");
  2213. }
  2214. this->CurrentLocalGenerator->AddFeatureFlags(flags, gtgt, lang,
  2215. configName);
  2216. this->CurrentLocalGenerator->AddVisibilityPresetFlags(flags, gtgt, lang);
  2217. this->CurrentLocalGenerator->AddCompileOptions(flags, gtgt, lang,
  2218. configName);
  2219. }
  2220. std::string llang = gtgt->GetLinkerLanguage(configName);
  2221. if (binary && llang.empty()) {
  2222. cmSystemTools::Error(
  2223. cmStrCat("CMake can not determine linker language for target: ",
  2224. gtgt->GetName()));
  2225. return;
  2226. }
  2227. // Choose a language to use for target-wide preprocessor definitions.
  2228. static char const* ppLangs[] = { "CXX", "C", "OBJCXX", "OBJC" };
  2229. std::string langForPreprocessorDefinitions;
  2230. if (cm::contains(ppLangs, llang)) {
  2231. langForPreprocessorDefinitions = llang;
  2232. } else {
  2233. for (char const* l : ppLangs) {
  2234. if (languages.count(l)) {
  2235. langForPreprocessorDefinitions = l;
  2236. break;
  2237. }
  2238. }
  2239. }
  2240. if (gtgt->IsIPOEnabled(llang, configName)) {
  2241. char const* ltoValue =
  2242. this->CurrentMakefile->IsOn("_CMAKE_LTO_THIN") ? "YES_THIN" : "YES";
  2243. buildSettings->AddAttribute("LLVM_LTO", this->CreateString(ltoValue));
  2244. }
  2245. // Handle PIE linker configuration
  2246. this->AddPositionIndependentLinkAttribute(gtgt, buildSettings, configName);
  2247. // Add define flags
  2248. this->CurrentLocalGenerator->AppendFlags(
  2249. defFlags, this->CurrentMakefile->GetDefineFlags());
  2250. // Add preprocessor definitions for this target and configuration.
  2251. BuildObjectListOrString ppDefs(this, true);
  2252. this->AppendDefines(
  2253. ppDefs, "CMAKE_INTDIR=\"$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)\"");
  2254. if (std::string const* exportMacro = gtgt->GetExportMacro()) {
  2255. // Add the export symbol definition for shared library objects.
  2256. this->AppendDefines(ppDefs, exportMacro->c_str());
  2257. }
  2258. std::vector<std::string> targetDefines;
  2259. if (!langForPreprocessorDefinitions.empty()) {
  2260. gtgt->GetCompileDefinitions(targetDefines, configName,
  2261. langForPreprocessorDefinitions);
  2262. }
  2263. this->AppendDefines(ppDefs, targetDefines);
  2264. buildSettings->AddAttribute("GCC_PREPROCESSOR_DEFINITIONS",
  2265. ppDefs.CreateList());
  2266. if (languages.count("Swift")) {
  2267. // Swift uses a separate attribute for definitions.
  2268. std::vector<std::string> targetSwiftDefines;
  2269. gtgt->GetCompileDefinitions(targetSwiftDefines, configName, "Swift");
  2270. // Remove the '=value' parts, as Swift does not support them.
  2271. std::for_each(targetSwiftDefines.begin(), targetSwiftDefines.end(),
  2272. [](std::string& def) {
  2273. std::string::size_type pos = def.find('=');
  2274. if (pos != std::string::npos) {
  2275. def.erase(pos);
  2276. }
  2277. });
  2278. if (this->XcodeVersion < 80) {
  2279. std::string defineString;
  2280. std::set<std::string> defines(targetSwiftDefines.begin(),
  2281. targetSwiftDefines.end());
  2282. this->CurrentLocalGenerator->JoinDefines(defines, defineString, "Swift");
  2283. cflags["Swift"] += cmStrCat(' ', defineString);
  2284. } else {
  2285. BuildObjectListOrString swiftDefs(this, true);
  2286. this->AppendDefines(swiftDefs, targetSwiftDefines);
  2287. buildSettings->AddAttribute("SWIFT_ACTIVE_COMPILATION_CONDITIONS",
  2288. swiftDefs.CreateList());
  2289. }
  2290. if (cm::optional<cmSwiftCompileMode> swiftCompileMode =
  2291. this->CurrentLocalGenerator->GetSwiftCompileMode(gtgt, configName)) {
  2292. switch (*swiftCompileMode) {
  2293. case cmSwiftCompileMode::Wholemodule:
  2294. buildSettings->AddAttribute("SWIFT_COMPILATION_MODE",
  2295. this->CreateString("wholemodule"));
  2296. break;
  2297. case cmSwiftCompileMode::Incremental:
  2298. case cmSwiftCompileMode::Singlefile:
  2299. break;
  2300. case cmSwiftCompileMode::Unknown:
  2301. this->CurrentLocalGenerator->IssueMessage(
  2302. MessageType::AUTHOR_WARNING,
  2303. cmStrCat("Unknown Swift_COMPILATION_MODE on target '",
  2304. gtgt->GetName(), "'"));
  2305. break;
  2306. }
  2307. }
  2308. }
  2309. std::string extraLinkOptionsVar;
  2310. std::string extraLinkOptions;
  2311. if (gtgt->GetType() == cmStateEnums::EXECUTABLE) {
  2312. extraLinkOptionsVar = "CMAKE_EXE_LINKER_FLAGS";
  2313. } else if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) {
  2314. extraLinkOptionsVar = "CMAKE_SHARED_LINKER_FLAGS";
  2315. } else if (gtgt->GetType() == cmStateEnums::MODULE_LIBRARY) {
  2316. extraLinkOptionsVar = "CMAKE_MODULE_LINKER_FLAGS";
  2317. }
  2318. if (!extraLinkOptionsVar.empty()) {
  2319. this->CurrentLocalGenerator->AddConfigVariableFlags(
  2320. extraLinkOptions, extraLinkOptionsVar, gtgt, cmBuildStep::Link, llang,
  2321. configName);
  2322. }
  2323. if (gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  2324. gtgt->GetType() == cmStateEnums::STATIC_LIBRARY) {
  2325. this->CurrentLocalGenerator->GetStaticLibraryFlags(
  2326. extraLinkOptions, configName, llang, gtgt);
  2327. } else {
  2328. this->CurrentLocalGenerator->AppendLinkerTypeFlags(extraLinkOptions, gtgt,
  2329. configName, llang);
  2330. this->CurrentLocalGenerator->AppendWarningAsErrorLinkerFlags(
  2331. extraLinkOptions, gtgt, llang);
  2332. cmValue targetLinkFlags = gtgt->GetProperty("LINK_FLAGS");
  2333. if (targetLinkFlags) {
  2334. this->CurrentLocalGenerator->AppendFlags(extraLinkOptions,
  2335. *targetLinkFlags);
  2336. }
  2337. if (!configName.empty()) {
  2338. std::string linkFlagsVar =
  2339. cmStrCat("LINK_FLAGS_", cmSystemTools::UpperCase(configName));
  2340. if (cmValue linkFlags = gtgt->GetProperty(linkFlagsVar)) {
  2341. this->CurrentLocalGenerator->AppendFlags(extraLinkOptions, *linkFlags);
  2342. }
  2343. }
  2344. std::vector<std::string> opts;
  2345. gtgt->GetLinkOptions(opts, configName, llang);
  2346. // LINK_OPTIONS are escaped.
  2347. this->CurrentLocalGenerator->AppendCompileOptions(extraLinkOptions, opts);
  2348. }
  2349. // Set target-specific architectures.
  2350. std::vector<std::string> archs =
  2351. gtgt->GetAppleArchs(configName, cm::nullopt);
  2352. if (!archs.empty()) {
  2353. // Enable ARCHS attribute.
  2354. buildSettings->AddAttribute("ONLY_ACTIVE_ARCH", this->CreateString("NO"));
  2355. // Store ARCHS value.
  2356. if (archs.size() == 1) {
  2357. buildSettings->AddAttribute("ARCHS", this->CreateString(archs[0]));
  2358. } else {
  2359. cmXCodeObject* archObjects =
  2360. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2361. for (auto& arch : archs) {
  2362. archObjects->AddObject(this->CreateString(arch));
  2363. }
  2364. buildSettings->AddAttribute("ARCHS", archObjects);
  2365. }
  2366. }
  2367. // Get the product name components.
  2368. cmGeneratorTarget::NameComponents const& components =
  2369. gtgt->GetFullNameComponents(configName);
  2370. cmValue version = gtgt->GetProperty("VERSION");
  2371. cmValue soversion = gtgt->GetProperty("SOVERSION");
  2372. if (!gtgt->HasSOName(configName) || gtgt->IsFrameworkOnApple()) {
  2373. version = nullptr;
  2374. soversion = nullptr;
  2375. }
  2376. if (version && !soversion) {
  2377. soversion = version;
  2378. }
  2379. if (!version && soversion) {
  2380. version = soversion;
  2381. }
  2382. std::string realName = components.base;
  2383. std::string soName = components.base;
  2384. if (version && soversion) {
  2385. realName += '.';
  2386. realName += *version;
  2387. soName += '.';
  2388. soName += *soversion;
  2389. }
  2390. if (gtgt->CanCompileSources()) {
  2391. std::string const tmpDir =
  2392. this->GetTargetTempDir(gtgt, this->GetCMakeCFGIntDir());
  2393. buildSettings->AddAttribute("TARGET_TEMP_DIR", this->CreateString(tmpDir));
  2394. std::string outDir;
  2395. if (gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  2396. // We cannot suppress the archive, so hide it with intermediate files.
  2397. outDir = tmpDir;
  2398. } else {
  2399. outDir = gtgt->GetDirectory(configName);
  2400. }
  2401. buildSettings->AddAttribute("CONFIGURATION_BUILD_DIR",
  2402. this->CreateString(outDir));
  2403. }
  2404. // Set attributes to specify the proper name for the target.
  2405. std::string pndir = this->CurrentLocalGenerator->GetCurrentBinaryDirectory();
  2406. if (gtgt->GetType() == cmStateEnums::STATIC_LIBRARY ||
  2407. gtgt->GetType() == cmStateEnums::SHARED_LIBRARY ||
  2408. gtgt->GetType() == cmStateEnums::MODULE_LIBRARY ||
  2409. gtgt->GetType() == cmStateEnums::EXECUTABLE) {
  2410. std::string prefix = components.prefix;
  2411. if (gtgt->IsFrameworkOnApple() || gtgt->IsCFBundleOnApple()) {
  2412. prefix = "";
  2413. }
  2414. buildSettings->AddAttribute("EXECUTABLE_PREFIX",
  2415. this->CreateString(prefix));
  2416. buildSettings->AddAttribute("EXECUTABLE_SUFFIX",
  2417. this->CreateString(components.suffix));
  2418. }
  2419. // Store the product name for all target types.
  2420. buildSettings->AddAttribute("PRODUCT_NAME", this->CreateString(realName));
  2421. // Handle settings for each target type.
  2422. switch (gtgt->GetType()) {
  2423. case cmStateEnums::STATIC_LIBRARY:
  2424. if (gtgt->GetPropertyAsBool("FRAMEWORK")) {
  2425. std::string fw_version = gtgt->GetFrameworkVersion();
  2426. buildSettings->AddAttribute("FRAMEWORK_VERSION",
  2427. this->CreateString(fw_version));
  2428. cmValue ext = gtgt->GetProperty("BUNDLE_EXTENSION");
  2429. if (ext) {
  2430. buildSettings->AddAttribute("WRAPPER_EXTENSION",
  2431. this->CreateString(*ext));
  2432. }
  2433. std::string plist = this->ComputeInfoPListLocation(gtgt);
  2434. // Xcode will create the final version of Info.plist at build time,
  2435. // so let it replace the framework name. This avoids creating
  2436. // a per-configuration Info.plist file.
  2437. this->CurrentLocalGenerator->GenerateFrameworkInfoPList(
  2438. gtgt, "$(EXECUTABLE_NAME)", plist);
  2439. buildSettings->AddAttribute("INFOPLIST_FILE",
  2440. this->CreateString(plist));
  2441. buildSettings->AddAttribute("MACH_O_TYPE",
  2442. this->CreateString("staticlib"));
  2443. } else {
  2444. buildSettings->AddAttribute("LIBRARY_STYLE",
  2445. this->CreateString("STATIC"));
  2446. }
  2447. break;
  2448. case cmStateEnums::OBJECT_LIBRARY: {
  2449. buildSettings->AddAttribute("LIBRARY_STYLE",
  2450. this->CreateString("STATIC"));
  2451. break;
  2452. }
  2453. case cmStateEnums::MODULE_LIBRARY: {
  2454. buildSettings->AddAttribute("LIBRARY_STYLE",
  2455. this->CreateString("BUNDLE"));
  2456. if (gtgt->IsCFBundleOnApple()) {
  2457. // It turns out that a BUNDLE is basically the same
  2458. // in many ways as an application bundle, as far as
  2459. // link flags go
  2460. std::string createFlags = this->LookupFlags(
  2461. "CMAKE_SHARED_MODULE_CREATE_", llang, "_FLAGS", gtgt, "-bundle");
  2462. if (!createFlags.empty()) {
  2463. extraLinkOptions += ' ';
  2464. extraLinkOptions += createFlags;
  2465. }
  2466. cmValue ext = gtgt->GetProperty("BUNDLE_EXTENSION");
  2467. if (ext) {
  2468. buildSettings->AddAttribute("WRAPPER_EXTENSION",
  2469. this->CreateString(*ext));
  2470. }
  2471. std::string plist = this->ComputeInfoPListLocation(gtgt);
  2472. // Xcode will create the final version of Info.plist at build time,
  2473. // so let it replace the cfbundle name. This avoids creating
  2474. // a per-configuration Info.plist file. The cfbundle plist
  2475. // is very similar to the application bundle plist
  2476. this->CurrentLocalGenerator->GenerateAppleInfoPList(
  2477. gtgt, "$(EXECUTABLE_NAME)", plist);
  2478. buildSettings->AddAttribute("INFOPLIST_FILE",
  2479. this->CreateString(plist));
  2480. } else {
  2481. buildSettings->AddAttribute("MACH_O_TYPE",
  2482. this->CreateString("mh_bundle"));
  2483. buildSettings->AddAttribute("GCC_DYNAMIC_NO_PIC",
  2484. this->CreateString("NO"));
  2485. // Add the flags to create an executable.
  2486. std::string createFlags =
  2487. this->LookupFlags("CMAKE_", llang, "_LINK_FLAGS", gtgt, "");
  2488. if (!createFlags.empty()) {
  2489. extraLinkOptions += ' ';
  2490. extraLinkOptions += createFlags;
  2491. }
  2492. }
  2493. break;
  2494. }
  2495. case cmStateEnums::SHARED_LIBRARY: {
  2496. if (gtgt->GetPropertyAsBool("FRAMEWORK")) {
  2497. std::string fw_version = gtgt->GetFrameworkVersion();
  2498. buildSettings->AddAttribute("FRAMEWORK_VERSION",
  2499. this->CreateString(fw_version));
  2500. cmValue ext = gtgt->GetProperty("BUNDLE_EXTENSION");
  2501. if (ext) {
  2502. buildSettings->AddAttribute("WRAPPER_EXTENSION",
  2503. this->CreateString(*ext));
  2504. }
  2505. std::string plist = this->ComputeInfoPListLocation(gtgt);
  2506. // Xcode will create the final version of Info.plist at build time,
  2507. // so let it replace the framework name. This avoids creating
  2508. // a per-configuration Info.plist file.
  2509. this->CurrentLocalGenerator->GenerateFrameworkInfoPList(
  2510. gtgt, "$(EXECUTABLE_NAME)", plist);
  2511. buildSettings->AddAttribute("INFOPLIST_FILE",
  2512. this->CreateString(plist));
  2513. } else {
  2514. // Add the flags to create a shared library.
  2515. std::string createFlags =
  2516. this->LookupFlags("CMAKE_SHARED_LIBRARY_CREATE_", llang, "_FLAGS",
  2517. gtgt, "-dynamiclib");
  2518. if (!createFlags.empty()) {
  2519. extraLinkOptions += ' ';
  2520. extraLinkOptions += createFlags;
  2521. }
  2522. }
  2523. buildSettings->AddAttribute("LIBRARY_STYLE",
  2524. this->CreateString("DYNAMIC"));
  2525. if (gtgt->HasImportLibrary(configName)) {
  2526. // Request .tbd file generation
  2527. buildSettings->AddAttribute("GENERATE_TEXT_BASED_STUBS",
  2528. this->CreateString("YES"));
  2529. }
  2530. break;
  2531. }
  2532. case cmStateEnums::EXECUTABLE: {
  2533. // Add the flags to create an executable.
  2534. std::string createFlags =
  2535. this->LookupFlags("CMAKE_", llang, "_LINK_FLAGS", gtgt, "");
  2536. if (!createFlags.empty()) {
  2537. extraLinkOptions += ' ';
  2538. extraLinkOptions += createFlags;
  2539. }
  2540. // Handle bundles and normal executables separately.
  2541. if (gtgt->GetPropertyAsBool("MACOSX_BUNDLE")) {
  2542. cmValue ext = gtgt->GetProperty("BUNDLE_EXTENSION");
  2543. if (ext) {
  2544. buildSettings->AddAttribute("WRAPPER_EXTENSION",
  2545. this->CreateString(*ext));
  2546. }
  2547. std::string plist = this->ComputeInfoPListLocation(gtgt);
  2548. // Xcode will create the final version of Info.plist at build time,
  2549. // so let it replace the executable name. This avoids creating
  2550. // a per-configuration Info.plist file.
  2551. this->CurrentLocalGenerator->GenerateAppleInfoPList(
  2552. gtgt, "$(EXECUTABLE_NAME)", plist);
  2553. buildSettings->AddAttribute("INFOPLIST_FILE",
  2554. this->CreateString(plist));
  2555. }
  2556. } break;
  2557. default:
  2558. break;
  2559. }
  2560. BuildObjectListOrString dirs(this, true);
  2561. BuildObjectListOrString fdirs(this, true);
  2562. BuildObjectListOrString sysdirs(this, true);
  2563. BuildObjectListOrString sysfdirs(this, true);
  2564. bool const emitSystemIncludes = this->XcodeVersion >= 83;
  2565. // Choose a language to use for target-wide include directories.
  2566. std::string const& langForIncludes = llang;
  2567. std::vector<std::string> includes;
  2568. if (!langForIncludes.empty()) {
  2569. this->CurrentLocalGenerator->GetIncludeDirectories(
  2570. includes, gtgt, langForIncludes, configName);
  2571. }
  2572. std::set<std::string> emitted;
  2573. emitted.insert("/System/Library/Frameworks");
  2574. for (auto& include : includes) {
  2575. if (this->NameResolvesToFramework(include)) {
  2576. std::string frameworkDir = cmStrCat(include, "/../");
  2577. frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
  2578. if (emitted.insert(frameworkDir).second) {
  2579. std::string incpath = this->XCodeEscapePath(frameworkDir);
  2580. if (emitSystemIncludes &&
  2581. gtgt->IsSystemIncludeDirectory(frameworkDir, configName,
  2582. langForIncludes)) {
  2583. sysfdirs.Add(incpath);
  2584. } else {
  2585. fdirs.Add(incpath);
  2586. }
  2587. }
  2588. } else {
  2589. std::string incpath = this->XCodeEscapePath(include);
  2590. if (emitSystemIncludes &&
  2591. gtgt->IsSystemIncludeDirectory(include, configName,
  2592. langForIncludes)) {
  2593. sysdirs.Add(incpath);
  2594. } else {
  2595. dirs.Add(incpath);
  2596. }
  2597. }
  2598. }
  2599. // Add framework search paths needed for linking.
  2600. if (cmComputeLinkInformation* cli = gtgt->GetLinkInformation(configName)) {
  2601. for (auto const& fwDir : cli->GetFrameworkPaths()) {
  2602. if (emitted.insert(fwDir).second) {
  2603. std::string incpath = this->XCodeEscapePath(fwDir);
  2604. if (emitSystemIncludes &&
  2605. gtgt->IsSystemIncludeDirectory(fwDir, configName,
  2606. langForIncludes)) {
  2607. sysfdirs.Add(incpath);
  2608. } else {
  2609. fdirs.Add(incpath);
  2610. }
  2611. }
  2612. }
  2613. }
  2614. if (!fdirs.IsEmpty()) {
  2615. buildSettings->AddAttribute("FRAMEWORK_SEARCH_PATHS", fdirs.CreateList());
  2616. }
  2617. if (!dirs.IsEmpty()) {
  2618. buildSettings->AddAttribute("HEADER_SEARCH_PATHS", dirs.CreateList());
  2619. if (languages.count("Swift")) {
  2620. buildSettings->AddAttribute("SWIFT_INCLUDE_PATHS", dirs.CreateList());
  2621. }
  2622. }
  2623. if (!sysfdirs.IsEmpty()) {
  2624. buildSettings->AddAttribute("SYSTEM_FRAMEWORK_SEARCH_PATHS",
  2625. sysfdirs.CreateList());
  2626. }
  2627. if (!sysdirs.IsEmpty()) {
  2628. buildSettings->AddAttribute("SYSTEM_HEADER_SEARCH_PATHS",
  2629. sysdirs.CreateList());
  2630. }
  2631. if (this->XcodeVersion >= 60 && !emitSystemIncludes) {
  2632. // Add those per-language flags in addition to HEADER_SEARCH_PATHS to gain
  2633. // system include directory awareness. We need to also keep on setting
  2634. // HEADER_SEARCH_PATHS to work around a missing compile options flag for
  2635. // GNU assembly files (#16449)
  2636. for (auto const& language : languages) {
  2637. std::string includeFlags = this->CurrentLocalGenerator->GetIncludeFlags(
  2638. includes, gtgt, language, configName);
  2639. if (!includeFlags.empty()) {
  2640. cflags[language] += cmStrCat(' ', includeFlags);
  2641. }
  2642. }
  2643. }
  2644. bool same_gflags = true;
  2645. std::map<std::string, std::string> gflags;
  2646. std::string const* last_gflag = nullptr;
  2647. std::string optLevel = "0";
  2648. // Minimal map of flags to build settings.
  2649. for (auto const& language : languages) {
  2650. std::string& flags = cflags[language];
  2651. std::string& gflag = gflags[language];
  2652. std::string oflag =
  2653. this->ExtractFlagRegex("(^| )(-Ofast|-Os|-O[0-9]*)( |$)", 2, flags);
  2654. if (oflag.size() == 2) {
  2655. optLevel = "1";
  2656. } else if (oflag.size() > 2) {
  2657. optLevel = oflag.substr(2);
  2658. }
  2659. gflag = this->ExtractFlag("-g", flags);
  2660. // put back gdwarf-2 if used since there is no way
  2661. // to represent it in the gui, but we still want debug yes
  2662. if (gflag == "-gdwarf-2"_s) {
  2663. flags += ' ';
  2664. flags += gflag;
  2665. }
  2666. if (last_gflag && *last_gflag != gflag) {
  2667. same_gflags = false;
  2668. }
  2669. last_gflag = &gflag;
  2670. }
  2671. char const* debugStr = "YES";
  2672. if (!same_gflags) {
  2673. // We can't set the Xcode flag differently depending on the language,
  2674. // so put them back in this case.
  2675. for (auto const& language : languages) {
  2676. cflags[language] += ' ';
  2677. cflags[language] += gflags[language];
  2678. }
  2679. debugStr = "NO";
  2680. } else if (last_gflag && (last_gflag->empty() || *last_gflag == "-g0"_s)) {
  2681. debugStr = "NO";
  2682. }
  2683. // extract C++ stdlib
  2684. for (auto const& language : languages) {
  2685. if (language != "CXX"_s && language != "OBJCXX"_s) {
  2686. continue;
  2687. }
  2688. std::string& flags = cflags[language];
  2689. auto stdlib =
  2690. this->ExtractFlagRegex("(^| )(-stdlib=[^ ]+)( |$)", 2, flags);
  2691. if (stdlib.size() > 8) {
  2692. auto const cxxLibrary = stdlib.substr(8);
  2693. if (language == "CXX"_s ||
  2694. !buildSettings->GetAttribute("CLANG_CXX_LIBRARY")) {
  2695. buildSettings->AddAttribute("CLANG_CXX_LIBRARY",
  2696. this->CreateString(cxxLibrary));
  2697. }
  2698. }
  2699. }
  2700. buildSettings->AddAttribute("COMBINE_HIDPI_IMAGES",
  2701. this->CreateString("YES"));
  2702. buildSettings->AddAttribute("GCC_GENERATE_DEBUGGING_SYMBOLS",
  2703. this->CreateString(debugStr));
  2704. buildSettings->AddAttribute("GCC_OPTIMIZATION_LEVEL",
  2705. this->CreateString(optLevel));
  2706. buildSettings->AddAttribute("GCC_SYMBOLS_PRIVATE_EXTERN",
  2707. this->CreateString("NO"));
  2708. buildSettings->AddAttribute("GCC_INLINES_ARE_PRIVATE_EXTERN",
  2709. this->CreateString("NO"));
  2710. for (auto const& language : languages) {
  2711. std::string flags = cmStrCat(cflags[language], ' ', defFlags);
  2712. if (language == "CXX"_s || language == "OBJCXX"_s) {
  2713. if (language == "CXX"_s ||
  2714. !buildSettings->GetAttribute("OTHER_CPLUSPLUSFLAGS")) {
  2715. buildSettings->AddAttribute("OTHER_CPLUSPLUSFLAGS",
  2716. this->CreateString(flags));
  2717. }
  2718. } else if (language == "Fortran"_s) {
  2719. buildSettings->AddAttribute("IFORT_OTHER_FLAGS",
  2720. this->CreateString(flags));
  2721. } else if (language == "C"_s || language == "OBJC"_s) {
  2722. if (language == "C"_s || !buildSettings->GetAttribute("OTHER_CFLAGS")) {
  2723. buildSettings->AddAttribute("OTHER_CFLAGS", this->CreateString(flags));
  2724. }
  2725. } else if (language == "Swift"_s) {
  2726. buildSettings->AddAttribute("OTHER_SWIFT_FLAGS",
  2727. this->CreateString(flags));
  2728. }
  2729. }
  2730. // Add Fortran source format attribute if property is set.
  2731. char const* format = nullptr;
  2732. std::string const& tgtfmt = gtgt->GetSafeProperty("Fortran_FORMAT");
  2733. switch (cmOutputConverter::GetFortranFormat(tgtfmt)) {
  2734. case cmOutputConverter::FortranFormatFixed:
  2735. format = "fixed";
  2736. break;
  2737. case cmOutputConverter::FortranFormatFree:
  2738. format = "free";
  2739. break;
  2740. default:
  2741. break;
  2742. }
  2743. if (format) {
  2744. buildSettings->AddAttribute("IFORT_LANG_SRCFMT",
  2745. this->CreateString(format));
  2746. }
  2747. // Create the INSTALL_PATH attribute.
  2748. std::string install_name_dir;
  2749. if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) {
  2750. // Get the install_name directory for the build tree.
  2751. install_name_dir = gtgt->GetInstallNameDirForBuildTree(configName);
  2752. // Xcode doesn't create the correct install_name in some cases.
  2753. // That is, if the INSTALL_PATH is empty, or if we have versioning
  2754. // of dylib libraries, we want to specify the install_name.
  2755. // This is done by adding a link flag to create an install_name
  2756. // with just the library soname.
  2757. std::string install_name;
  2758. if (!install_name_dir.empty()) {
  2759. // Convert to a path for the native build tool.
  2760. cmSystemTools::ConvertToUnixSlashes(install_name_dir);
  2761. install_name += install_name_dir;
  2762. install_name += '/';
  2763. }
  2764. install_name += gtgt->GetSOName(configName);
  2765. if ((realName != soName) || install_name_dir.empty()) {
  2766. install_name_dir = "";
  2767. extraLinkOptions += " -install_name ";
  2768. extraLinkOptions += XCodeEscapePath(install_name);
  2769. }
  2770. }
  2771. buildSettings->AddAttribute("INSTALL_PATH",
  2772. this->CreateString(install_name_dir));
  2773. // Create the LD_RUNPATH_SEARCH_PATHS
  2774. cmComputeLinkInformation* pcli = gtgt->GetLinkInformation(configName);
  2775. if (pcli) {
  2776. std::string search_paths;
  2777. std::vector<std::string> runtimeDirs;
  2778. pcli->GetRPath(runtimeDirs, false);
  2779. // runpath dirs needs to be unique to prevent corruption
  2780. std::set<std::string> unique_dirs;
  2781. for (auto runpath : runtimeDirs) {
  2782. runpath = this->ExpandCFGIntDir(runpath, configName);
  2783. if (unique_dirs.find(runpath) == unique_dirs.end()) {
  2784. unique_dirs.insert(runpath);
  2785. if (!search_paths.empty()) {
  2786. search_paths += ' ';
  2787. }
  2788. search_paths += this->XCodeEscapePath(runpath);
  2789. }
  2790. }
  2791. if (!search_paths.empty()) {
  2792. buildSettings->AddAttribute("LD_RUNPATH_SEARCH_PATHS",
  2793. this->CreateString(search_paths));
  2794. }
  2795. }
  2796. buildSettings->AddAttribute(this->GetTargetLinkFlagsVar(gtgt),
  2797. this->CreateString(extraLinkOptions));
  2798. buildSettings->AddAttribute("OTHER_REZFLAGS", this->CreateString(""));
  2799. buildSettings->AddAttribute("SECTORDER_FLAGS", this->CreateString(""));
  2800. buildSettings->AddAttribute("ALWAYS_SEARCH_USER_PATHS",
  2801. this->CreateString("NO"));
  2802. buildSettings->AddAttribute("USE_HEADERMAP", this->CreateString("NO"));
  2803. cmXCodeObject* group = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2804. group->AddObject(this->CreateString("$(inherited)"));
  2805. buildSettings->AddAttribute("WARNING_CFLAGS", group);
  2806. // Runtime version information.
  2807. if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) {
  2808. int major;
  2809. int minor;
  2810. int patch;
  2811. // MACHO_CURRENT_VERSION or VERSION -> current_version
  2812. gtgt->GetTargetVersionFallback("MACHO_CURRENT_VERSION", "VERSION", major,
  2813. minor, patch);
  2814. std::ostringstream v;
  2815. // Xcode always wants at least 1.0.0 or nothing
  2816. if (!(major == 0 && minor == 0 && patch == 0)) {
  2817. v << major << '.' << minor << '.' << patch;
  2818. }
  2819. buildSettings->AddAttribute("DYLIB_CURRENT_VERSION",
  2820. this->CreateString(v.str()));
  2821. // MACHO_COMPATIBILITY_VERSION or SOVERSION -> compatibility_version
  2822. gtgt->GetTargetVersionFallback("MACHO_COMPATIBILITY_VERSION", "SOVERSION",
  2823. major, minor, patch);
  2824. std::ostringstream vso;
  2825. // Xcode always wants at least 1.0.0 or nothing
  2826. if (!(major == 0 && minor == 0 && patch == 0)) {
  2827. vso << major << '.' << minor << '.' << patch;
  2828. }
  2829. buildSettings->AddAttribute("DYLIB_COMPATIBILITY_VERSION",
  2830. this->CreateString(vso.str()));
  2831. }
  2832. // Precompile Headers
  2833. std::string pchHeader =
  2834. gtgt->GetPchHeader(configName, langForPreprocessorDefinitions);
  2835. if (!pchHeader.empty()) {
  2836. buildSettings->AddAttribute("GCC_PREFIX_HEADER",
  2837. this->CreateString(pchHeader));
  2838. buildSettings->AddAttribute("GCC_PRECOMPILE_PREFIX_HEADER",
  2839. this->CreateString("YES"));
  2840. }
  2841. // put this last so it can override existing settings
  2842. // Convert "XCODE_ATTRIBUTE_*" properties directly.
  2843. {
  2844. for (auto const& prop : gtgt->GetPropertyKeys()) {
  2845. if (cmHasLiteralPrefix(prop, "XCODE_ATTRIBUTE_")) {
  2846. std::string attribute = prop.substr(16);
  2847. this->FilterConfigurationAttribute(configName, attribute);
  2848. if (!attribute.empty()) {
  2849. std::string const& pr = gtgt->GetSafeProperty(prop);
  2850. std::string processed = cmGeneratorExpression::Evaluate(
  2851. pr, this->CurrentLocalGenerator, configName);
  2852. buildSettings->AddAttribute(attribute,
  2853. this->CreateString(processed));
  2854. }
  2855. }
  2856. }
  2857. }
  2858. }
  2859. cmXCodeObject* cmGlobalXCodeGenerator::CreateUtilityTarget(
  2860. cmGeneratorTarget* gtgt)
  2861. {
  2862. cmXCodeObject* shellBuildPhase = this->CreateObject(
  2863. cmXCodeObject::PBXShellScriptBuildPhase, gtgt->GetName());
  2864. shellBuildPhase->AddAttribute("buildActionMask",
  2865. this->CreateString("2147483647"));
  2866. cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2867. shellBuildPhase->AddAttribute("files", buildFiles);
  2868. cmXCodeObject* inputPaths = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2869. shellBuildPhase->AddAttribute("inputPaths", inputPaths);
  2870. cmXCodeObject* outputPaths = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2871. shellBuildPhase->AddAttribute("outputPaths", outputPaths);
  2872. shellBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  2873. this->CreateString("0"));
  2874. shellBuildPhase->AddAttribute("shellPath", this->CreateString("/bin/sh"));
  2875. shellBuildPhase->AddAttribute(
  2876. "shellScript", this->CreateString("# shell script goes here\nexit 0"));
  2877. shellBuildPhase->AddAttribute("showEnvVarsInLog", this->CreateString("0"));
  2878. std::string targetBinaryPath = cmStrCat(
  2879. gtgt->Makefile->GetCurrentBinaryDirectory(), '/', gtgt->GetName());
  2880. cmXCodeObject* target = this->CreateObject(
  2881. cmXCodeObject::PBXAggregateTarget,
  2882. cmStrCat("PBXAggregateTarget:", gtgt->GetName(), ":", targetBinaryPath));
  2883. target->SetComment(gtgt->GetName());
  2884. cmXCodeObject* buildPhases = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2885. std::vector<cmXCodeObject*> emptyContentVector;
  2886. this->CreateCustomCommands(buildPhases, nullptr, nullptr, nullptr,
  2887. emptyContentVector, nullptr, gtgt);
  2888. target->AddAttribute("buildPhases", buildPhases);
  2889. this->AddConfigurations(target, gtgt);
  2890. cmXCodeObject* dependencies = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2891. target->AddAttribute("dependencies", dependencies);
  2892. target->AddAttribute("name", this->CreateString(gtgt->GetName()));
  2893. target->AddAttribute("productName", this->CreateString(gtgt->GetName()));
  2894. target->SetTarget(gtgt);
  2895. this->XCodeObjectMap[gtgt] = target;
  2896. // Add source files without build rules for editing convenience.
  2897. if (gtgt->GetType() != cmStateEnums::GLOBAL_TARGET &&
  2898. gtgt->GetName() != CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
  2899. std::vector<cmSourceFile*> sources;
  2900. if (!gtgt->GetConfigCommonSourceFilesForXcode(sources)) {
  2901. return nullptr;
  2902. }
  2903. // Add CMakeLists.txt file for user convenience.
  2904. this->AddXCodeProjBuildRule(gtgt, sources);
  2905. for (auto* sourceFile : sources) {
  2906. if (!sourceFile->GetIsGenerated()) {
  2907. this->CreateXCodeFileReference(sourceFile, gtgt);
  2908. }
  2909. }
  2910. }
  2911. target->SetId(this->GetOrCreateId(gtgt->GetName(), target->GetId()));
  2912. return target;
  2913. }
  2914. std::string cmGlobalXCodeGenerator::AddConfigurations(cmXCodeObject* target,
  2915. cmGeneratorTarget* gtgt)
  2916. {
  2917. cmList const configList{ this->CurrentMakefile->GetRequiredDefinition(
  2918. "CMAKE_CONFIGURATION_TYPES") };
  2919. cmXCodeObject* configlist =
  2920. this->CreateObject(cmXCodeObject::XCConfigurationList);
  2921. cmXCodeObject* buildConfigurations =
  2922. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2923. configlist->AddAttribute("buildConfigurations", buildConfigurations);
  2924. std::string comment = cmStrCat("Build configuration list for ",
  2925. cmXCodeObject::PBXTypeNames[target->GetIsA()],
  2926. " \"", gtgt->GetName(), '"');
  2927. configlist->SetComment(comment);
  2928. target->AddAttribute("buildConfigurationList",
  2929. this->CreateObjectReference(configlist));
  2930. for (auto const& i : configList) {
  2931. cmXCodeObject* config =
  2932. this->CreateObject(cmXCodeObject::XCBuildConfiguration);
  2933. buildConfigurations->AddObject(config);
  2934. cmXCodeObject* buildSettings =
  2935. this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  2936. this->CreateBuildSettings(gtgt, buildSettings, i);
  2937. config->AddAttribute("name", this->CreateString(i));
  2938. config->SetComment(i);
  2939. config->AddAttribute("buildSettings", buildSettings);
  2940. this->CreateTargetXCConfigSettings(gtgt, config, i);
  2941. }
  2942. if (!configList.empty()) {
  2943. configlist->AddAttribute("defaultConfigurationName",
  2944. this->CreateString(configList[0]));
  2945. configlist->AddAttribute("defaultConfigurationIsVisible",
  2946. this->CreateString("0"));
  2947. return configList[0];
  2948. }
  2949. return "";
  2950. }
  2951. void cmGlobalXCodeGenerator::CreateGlobalXCConfigSettings(
  2952. cmLocalGenerator* root, cmXCodeObject* config, std::string const& configName)
  2953. {
  2954. auto xcconfig = cmGeneratorExpression::Evaluate(
  2955. this->CurrentMakefile->GetSafeDefinition("CMAKE_XCODE_XCCONFIG"),
  2956. this->CurrentLocalGenerator, configName);
  2957. if (xcconfig.empty()) {
  2958. return;
  2959. }
  2960. auto* sf = this->CurrentMakefile->GetSource(xcconfig);
  2961. if (!sf) {
  2962. cmSystemTools::Error(
  2963. cmStrCat("sources for ALL_BUILD do not contain xcconfig file: '",
  2964. xcconfig, "' (configuration: ", configName, ')'));
  2965. return;
  2966. }
  2967. cmXCodeObject* fileRef = this->CreateXCodeFileReferenceFromPath(
  2968. sf->ResolveFullPath(), root->FindGeneratorTargetToUse("ALL_BUILD"), "",
  2969. sf);
  2970. if (!fileRef) {
  2971. // error is already reported by CreateXCodeFileReferenceFromPath
  2972. return;
  2973. }
  2974. config->AddAttribute("baseConfigurationReference",
  2975. this->CreateObjectReference(fileRef));
  2976. }
  2977. void cmGlobalXCodeGenerator::CreateTargetXCConfigSettings(
  2978. cmGeneratorTarget* target, cmXCodeObject* config,
  2979. std::string const& configName)
  2980. {
  2981. auto xcconfig =
  2982. cmGeneratorExpression::Evaluate(target->GetSafeProperty("XCODE_XCCONFIG"),
  2983. this->CurrentLocalGenerator, configName);
  2984. if (xcconfig.empty()) {
  2985. return;
  2986. }
  2987. auto* sf = target->Makefile->GetSource(xcconfig);
  2988. if (!sf) {
  2989. cmSystemTools::Error(cmStrCat("target sources for target ",
  2990. target->Target->GetName(),
  2991. " do not contain xcconfig file: '", xcconfig,
  2992. "' (configuration: ", configName, ')'));
  2993. return;
  2994. }
  2995. cmXCodeObject* fileRef = this->CreateXCodeFileReferenceFromPath(
  2996. sf->ResolveFullPath(), target, "", sf);
  2997. if (!fileRef) {
  2998. // error is already reported by CreateXCodeFileReferenceFromPath
  2999. return;
  3000. }
  3001. config->AddAttribute("baseConfigurationReference",
  3002. this->CreateObjectReference(fileRef));
  3003. }
  3004. char const* cmGlobalXCodeGenerator::GetTargetLinkFlagsVar(
  3005. cmGeneratorTarget const* target) const
  3006. {
  3007. if (this->XcodeVersion >= 60 &&
  3008. (target->GetType() == cmStateEnums::STATIC_LIBRARY ||
  3009. target->GetType() == cmStateEnums::OBJECT_LIBRARY)) {
  3010. return "OTHER_LIBTOOLFLAGS";
  3011. }
  3012. return "OTHER_LDFLAGS";
  3013. }
  3014. char const* cmGlobalXCodeGenerator::GetTargetFileType(
  3015. cmGeneratorTarget* target)
  3016. {
  3017. if (cmValue e = target->GetProperty("XCODE_EXPLICIT_FILE_TYPE")) {
  3018. return e->c_str();
  3019. }
  3020. switch (target->GetType()) {
  3021. case cmStateEnums::OBJECT_LIBRARY:
  3022. return "archive.ar";
  3023. case cmStateEnums::STATIC_LIBRARY:
  3024. return (target->GetPropertyAsBool("FRAMEWORK") ? "wrapper.framework"
  3025. : "archive.ar");
  3026. case cmStateEnums::MODULE_LIBRARY:
  3027. if (target->IsXCTestOnApple()) {
  3028. return "wrapper.cfbundle";
  3029. }
  3030. if (target->IsCFBundleOnApple()) {
  3031. return "wrapper.plug-in";
  3032. }
  3033. return "compiled.mach-o.executable";
  3034. case cmStateEnums::SHARED_LIBRARY:
  3035. return (target->GetPropertyAsBool("FRAMEWORK")
  3036. ? "wrapper.framework"
  3037. : "compiled.mach-o.dylib");
  3038. case cmStateEnums::EXECUTABLE:
  3039. return "compiled.mach-o.executable";
  3040. default:
  3041. break;
  3042. }
  3043. return nullptr;
  3044. }
  3045. char const* cmGlobalXCodeGenerator::GetTargetProductType(
  3046. cmGeneratorTarget* target)
  3047. {
  3048. if (cmValue e = target->GetProperty("XCODE_PRODUCT_TYPE")) {
  3049. return e->c_str();
  3050. }
  3051. switch (target->GetType()) {
  3052. case cmStateEnums::OBJECT_LIBRARY:
  3053. return "com.apple.product-type.library.static";
  3054. case cmStateEnums::STATIC_LIBRARY:
  3055. return (target->GetPropertyAsBool("FRAMEWORK")
  3056. ? "com.apple.product-type.framework"
  3057. : "com.apple.product-type.library.static");
  3058. case cmStateEnums::MODULE_LIBRARY:
  3059. if (target->IsXCTestOnApple()) {
  3060. return "com.apple.product-type.bundle.unit-test";
  3061. } else if (target->IsCFBundleOnApple()) {
  3062. return "com.apple.product-type.bundle";
  3063. } else {
  3064. return "com.apple.product-type.tool";
  3065. }
  3066. case cmStateEnums::SHARED_LIBRARY:
  3067. return (target->GetPropertyAsBool("FRAMEWORK")
  3068. ? "com.apple.product-type.framework"
  3069. : "com.apple.product-type.library.dynamic");
  3070. case cmStateEnums::EXECUTABLE:
  3071. return (target->GetPropertyAsBool("MACOSX_BUNDLE")
  3072. ? "com.apple.product-type.application"
  3073. : "com.apple.product-type.tool");
  3074. default:
  3075. break;
  3076. }
  3077. return nullptr;
  3078. }
  3079. cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeTarget(
  3080. cmGeneratorTarget* gtgt, cmXCodeObject* buildPhases)
  3081. {
  3082. if (!gtgt->IsInBuildSystem()) {
  3083. return nullptr;
  3084. }
  3085. std::string targetBinaryPath = this->RelativeToRootBinary(cmStrCat(
  3086. gtgt->Makefile->GetCurrentBinaryDirectory(), '/', gtgt->GetName()));
  3087. cmXCodeObject* target = this->CreateObject(
  3088. cmXCodeObject::PBXNativeTarget,
  3089. cmStrCat("PBXNativeTarget:", gtgt->GetName(), ":", targetBinaryPath));
  3090. target->AddAttribute("buildPhases", buildPhases);
  3091. cmXCodeObject* buildRules = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3092. target->AddAttribute("buildRules", buildRules);
  3093. std::string defConfig;
  3094. defConfig = this->AddConfigurations(target, gtgt);
  3095. cmXCodeObject* dependencies = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3096. target->AddAttribute("dependencies", dependencies);
  3097. target->AddAttribute("name", this->CreateString(gtgt->GetName()));
  3098. target->AddAttribute("productName", this->CreateString(gtgt->GetName()));
  3099. cmXCodeObject* fileRef = this->CreateObject(cmXCodeObject::PBXFileReference);
  3100. if (char const* fileType = this->GetTargetFileType(gtgt)) {
  3101. fileRef->AddAttribute("explicitFileType", this->CreateString(fileType));
  3102. }
  3103. std::string fullName;
  3104. if (gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  3105. fullName = cmStrCat("lib", gtgt->GetName(), ".a");
  3106. } else {
  3107. fullName = gtgt->GetFullName(defConfig);
  3108. }
  3109. fileRef->AddAttribute("path", this->CreateString(fullName));
  3110. fileRef->AddAttribute("sourceTree",
  3111. this->CreateString("BUILT_PRODUCTS_DIR"));
  3112. fileRef->SetComment(gtgt->GetName());
  3113. target->AddAttribute("productReference",
  3114. this->CreateObjectReference(fileRef));
  3115. if (char const* productType = this->GetTargetProductType(gtgt)) {
  3116. target->AddAttribute("productType", this->CreateString(productType));
  3117. }
  3118. target->SetTarget(gtgt);
  3119. this->XCodeObjectMap[gtgt] = target;
  3120. target->SetId(this->GetOrCreateId(gtgt->GetName(), target->GetId()));
  3121. return target;
  3122. }
  3123. cmXCodeObject* cmGlobalXCodeGenerator::FindXCodeTarget(
  3124. cmGeneratorTarget const* t)
  3125. {
  3126. if (!t) {
  3127. return nullptr;
  3128. }
  3129. auto const i = this->XCodeObjectMap.find(t);
  3130. if (i == this->XCodeObjectMap.end()) {
  3131. return nullptr;
  3132. }
  3133. return i->second;
  3134. }
  3135. std::string cmGlobalXCodeGenerator::GetObjectId(cmXCodeObject::PBXType ptype,
  3136. cm::string_view key)
  3137. {
  3138. std::string objectId;
  3139. if (!key.empty()) {
  3140. cmCryptoHash hash(cmCryptoHash::AlgoSHA256);
  3141. hash.Initialize();
  3142. hash.Append(&ptype, sizeof(ptype));
  3143. hash.Append(key);
  3144. objectId = cmSystemTools::UpperCase(hash.FinalizeHex().substr(0, 24));
  3145. } else {
  3146. char cUuid[40] = { 0 };
  3147. CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
  3148. CFStringRef s = CFUUIDCreateString(kCFAllocatorDefault, uuid);
  3149. CFStringGetCString(s, cUuid, sizeof(cUuid), kCFStringEncodingUTF8);
  3150. objectId = cUuid;
  3151. CFRelease(s);
  3152. CFRelease(uuid);
  3153. cmSystemTools::ReplaceString(objectId, "-", "");
  3154. if (objectId.size() > 24) {
  3155. objectId = objectId.substr(0, 24);
  3156. }
  3157. }
  3158. return objectId;
  3159. }
  3160. std::string cmGlobalXCodeGenerator::GetOrCreateId(std::string const& name,
  3161. std::string const& id)
  3162. {
  3163. std::string guidStoreName = cmStrCat(name, "_GUID_CMAKE");
  3164. cmValue storedGUID = this->CMakeInstance->GetCacheDefinition(guidStoreName);
  3165. if (storedGUID) {
  3166. return *storedGUID;
  3167. }
  3168. this->CMakeInstance->AddCacheEntry(
  3169. guidStoreName, id, "Stored Xcode object GUID", cmStateEnums::INTERNAL);
  3170. return id;
  3171. }
  3172. void cmGlobalXCodeGenerator::AddDependTarget(cmXCodeObject* target,
  3173. cmXCodeObject* dependTarget)
  3174. {
  3175. // This is called once for every edge in the target dependency graph.
  3176. cmXCodeObject* container =
  3177. this->CreateObject(cmXCodeObject::PBXContainerItemProxy);
  3178. container->SetComment("PBXContainerItemProxy");
  3179. container->AddAttribute("containerPortal",
  3180. this->CreateObjectReference(this->RootObject));
  3181. container->AddAttribute("proxyType", this->CreateString("1"));
  3182. container->AddAttribute("remoteGlobalIDString",
  3183. this->CreateObjectReference(dependTarget));
  3184. container->AddAttribute(
  3185. "remoteInfo", this->CreateString(dependTarget->GetTarget()->GetName()));
  3186. cmXCodeObject* targetdep =
  3187. this->CreateObject(cmXCodeObject::PBXTargetDependency);
  3188. targetdep->SetComment("PBXTargetDependency");
  3189. targetdep->AddAttribute("target", this->CreateObjectReference(dependTarget));
  3190. targetdep->AddAttribute("targetProxy",
  3191. this->CreateObjectReference(container));
  3192. cmXCodeObject* depends = target->GetAttribute("dependencies");
  3193. if (!depends) {
  3194. cmSystemTools::Error(
  3195. "target does not have dependencies attribute error..");
  3196. } else {
  3197. depends->AddUniqueObject(targetdep);
  3198. }
  3199. }
  3200. void cmGlobalXCodeGenerator::AppendOrAddBuildSetting(cmXCodeObject* settings,
  3201. char const* attribute,
  3202. cmXCodeObject* value)
  3203. {
  3204. if (settings) {
  3205. cmXCodeObject* attr = settings->GetAttribute(attribute);
  3206. if (!attr) {
  3207. settings->AddAttribute(attribute, value);
  3208. } else {
  3209. this->AppendBuildSettingAttribute(settings, attribute, attr, value);
  3210. }
  3211. }
  3212. }
  3213. void cmGlobalXCodeGenerator::AppendBuildSettingAttribute(
  3214. cmXCodeObject* settings, char const* attribute, cmXCodeObject* attr,
  3215. cmXCodeObject* value)
  3216. {
  3217. if (value->GetType() != cmXCodeObject::OBJECT_LIST &&
  3218. value->GetType() != cmXCodeObject::STRING) {
  3219. cmSystemTools::Error(
  3220. cmStrCat("Unsupported value type for appending: ", attribute));
  3221. return;
  3222. }
  3223. if (attr->GetType() == cmXCodeObject::OBJECT_LIST) {
  3224. if (value->GetType() == cmXCodeObject::OBJECT_LIST) {
  3225. for (auto* obj : value->GetObjectList()) {
  3226. attr->AddObject(obj);
  3227. }
  3228. } else {
  3229. attr->AddObject(value);
  3230. }
  3231. } else if (attr->GetType() == cmXCodeObject::STRING) {
  3232. if (value->GetType() == cmXCodeObject::OBJECT_LIST) {
  3233. // Add old value as a list item to new object list
  3234. // and replace the attribute with the new list
  3235. value->PrependObject(attr);
  3236. settings->AddAttribute(attribute, value);
  3237. } else {
  3238. std::string newValue =
  3239. cmStrCat(attr->GetString(), ' ', value->GetString());
  3240. attr->SetString(newValue);
  3241. }
  3242. } else {
  3243. cmSystemTools::Error(
  3244. cmStrCat("Unsupported attribute type for appending: ", attribute));
  3245. }
  3246. }
  3247. void cmGlobalXCodeGenerator::AppendBuildSettingAttribute(
  3248. cmXCodeObject* target, char const* attribute, cmXCodeObject* value,
  3249. std::string const& configName)
  3250. {
  3251. // There are multiple configurations. Add the setting to the
  3252. // buildSettings of the configuration name given.
  3253. cmXCodeObject* configurationList =
  3254. target->GetAttribute("buildConfigurationList")->GetObject();
  3255. cmXCodeObject* buildConfigs =
  3256. configurationList->GetAttribute("buildConfigurations");
  3257. for (auto* obj : buildConfigs->GetObjectList()) {
  3258. if (configName.empty() ||
  3259. obj->GetAttribute("name")->GetString() == configName) {
  3260. cmXCodeObject* settings = obj->GetAttribute("buildSettings");
  3261. this->AppendOrAddBuildSetting(settings, attribute, value);
  3262. }
  3263. }
  3264. }
  3265. void cmGlobalXCodeGenerator::InheritBuildSettingAttribute(
  3266. cmXCodeObject* target, char const* attribute)
  3267. {
  3268. cmXCodeObject* configurationList =
  3269. target->GetAttribute("buildConfigurationList")->GetObject();
  3270. cmXCodeObject* buildConfigs =
  3271. configurationList->GetAttribute("buildConfigurations");
  3272. for (auto* obj : buildConfigs->GetObjectList()) {
  3273. cmXCodeObject* settings = obj->GetAttribute("buildSettings");
  3274. if (cmXCodeObject* attr = settings->GetAttribute(attribute)) {
  3275. BuildObjectListOrString inherited(this, true);
  3276. inherited.Add("$(inherited)");
  3277. this->AppendBuildSettingAttribute(settings, attribute, attr,
  3278. inherited.CreateList());
  3279. }
  3280. }
  3281. }
  3282. void cmGlobalXCodeGenerator::AddDependAndLinkInformation(cmXCodeObject* target)
  3283. {
  3284. cmGeneratorTarget* gt = target->GetTarget();
  3285. if (!gt) {
  3286. cmSystemTools::Error("Error no target on xobject\n");
  3287. return;
  3288. }
  3289. if (!gt->IsInBuildSystem()) {
  3290. return;
  3291. }
  3292. // Add dependencies on other CMake targets.
  3293. for (auto const& dep : this->GetTargetDirectDepends(gt)) {
  3294. if (cmXCodeObject* dptarget = this->FindXCodeTarget(dep)) {
  3295. this->AddDependTarget(target, dptarget);
  3296. }
  3297. }
  3298. // Separate libraries into ones that can be linked using "Link Binary With
  3299. // Libraries" build phase and the ones that can't. Only targets that build
  3300. // Apple bundles (.app, .framework, .bundle), executables and dylibs can use
  3301. // this feature and only targets that represent actual libraries (object,
  3302. // static, dynamic or bundle, excluding executables) will be used. These are
  3303. // limitations imposed by CMake use-cases - otherwise a lot of things break.
  3304. // The rest will be linked using linker flags (OTHER_LDFLAGS setting in Xcode
  3305. // project).
  3306. std::map<std::string, std::vector<cmComputeLinkInformation::Item const*>>
  3307. configItemMap;
  3308. auto addToLinkerArguments =
  3309. [&configItemMap](std::string const& configName,
  3310. cmComputeLinkInformation::Item const* libItemPtr) {
  3311. auto& linkVector = configItemMap[configName];
  3312. if (std::find_if(linkVector.begin(), linkVector.end(),
  3313. [libItemPtr](cmComputeLinkInformation::Item const* p) {
  3314. return p == libItemPtr;
  3315. }) == linkVector.end()) {
  3316. linkVector.push_back(libItemPtr);
  3317. }
  3318. };
  3319. std::vector<cmComputeLinkInformation::Item const*> linkPhaseTargetVector;
  3320. std::map<std::string, std::vector<std::string>> targetConfigMap;
  3321. using ConfigItemPair =
  3322. std::pair<std::string, cmComputeLinkInformation::Item const*>;
  3323. std::map<std::string, std::vector<ConfigItemPair>> targetItemMap;
  3324. std::map<std::string, std::vector<std::string>> targetProductNameMap;
  3325. bool useLinkPhase = false;
  3326. bool forceLinkPhase = false;
  3327. cmValue prop =
  3328. target->GetTarget()->GetProperty("XCODE_LINK_BUILD_PHASE_MODE");
  3329. if (prop) {
  3330. if (*prop == "BUILT_ONLY"_s) {
  3331. useLinkPhase = true;
  3332. } else if (*prop == "KNOWN_LOCATION"_s) {
  3333. useLinkPhase = true;
  3334. forceLinkPhase = true;
  3335. } else if (*prop != "NONE"_s) {
  3336. cmSystemTools::Error(
  3337. cmStrCat("Invalid value for XCODE_LINK_BUILD_PHASE_MODE: ", *prop));
  3338. return;
  3339. }
  3340. }
  3341. for (auto const& configName : this->CurrentConfigurationTypes) {
  3342. cmComputeLinkInformation* cli = gt->GetLinkInformation(configName);
  3343. if (!cli) {
  3344. continue;
  3345. }
  3346. for (auto const& libItem : cli->GetItems()) {
  3347. // Explicitly ignore OBJECT libraries as Xcode emulates them as static
  3348. // libraries without an artifact. Avoid exposing this to the rest of
  3349. // CMake's compilation model.
  3350. if (libItem.Target &&
  3351. libItem.Target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  3352. continue;
  3353. }
  3354. // We want to put only static libraries, dynamic libraries, frameworks
  3355. // and bundles that are built from targets that are not imported in "Link
  3356. // Binary With Libraries" build phase. Except if the target property
  3357. // XCODE_LINK_BUILD_PHASE_MODE is KNOWN_LOCATION then all imported and
  3358. // non-target libraries will be added as well.
  3359. if (useLinkPhase &&
  3360. (gt->GetType() == cmStateEnums::EXECUTABLE ||
  3361. gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
  3362. gt->GetType() == cmStateEnums::MODULE_LIBRARY) &&
  3363. ((libItem.Target &&
  3364. (!libItem.Target->IsImported() || forceLinkPhase) &&
  3365. (libItem.Target->GetType() == cmStateEnums::STATIC_LIBRARY ||
  3366. libItem.Target->GetType() == cmStateEnums::SHARED_LIBRARY ||
  3367. libItem.Target->GetType() == cmStateEnums::MODULE_LIBRARY ||
  3368. libItem.Target->GetType() == cmStateEnums::UNKNOWN_LIBRARY)) ||
  3369. (!libItem.Target &&
  3370. libItem.IsPath == cmComputeLinkInformation::ItemIsPath::Yes &&
  3371. forceLinkPhase))) {
  3372. std::string libName;
  3373. bool canUseLinkPhase = !libItem.HasFeature() ||
  3374. libItem.GetFeatureName() == "__CMAKE_LINK_FRAMEWORK"_s ||
  3375. libItem.GetFeatureName() == "FRAMEWORK"_s ||
  3376. libItem.GetFeatureName() == "__CMAKE_LINK_XCFRAMEWORK"_s ||
  3377. libItem.GetFeatureName() == "XCFRAMEWORK"_s ||
  3378. libItem.GetFeatureName() == "WEAK_FRAMEWORK"_s ||
  3379. libItem.GetFeatureName() == "WEAK_LIBRARY"_s;
  3380. if (canUseLinkPhase) {
  3381. if (libItem.Target) {
  3382. if (libItem.Target->GetType() == cmStateEnums::UNKNOWN_LIBRARY) {
  3383. canUseLinkPhase = canUseLinkPhase && forceLinkPhase;
  3384. } else {
  3385. // If a library target uses custom build output directory Xcode
  3386. // won't pick it up so we have to resort back to linker flags,
  3387. // but that's OK as long as the custom output dir is absolute
  3388. // path.
  3389. for (auto const& libConfigName :
  3390. this->CurrentConfigurationTypes) {
  3391. canUseLinkPhase = canUseLinkPhase &&
  3392. libItem.Target->UsesDefaultOutputDir(
  3393. libConfigName, cmStateEnums::RuntimeBinaryArtifact);
  3394. }
  3395. }
  3396. libName = libItem.Target->GetName();
  3397. } else {
  3398. libName = cmSystemTools::GetFilenameName(libItem.Value.Value);
  3399. // We don't want all the possible files here, just standard
  3400. // libraries
  3401. auto const libExt = cmSystemTools::GetFilenameExtension(libName);
  3402. if (!IsLinkPhaseLibraryExtension(libExt)) {
  3403. canUseLinkPhase = false;
  3404. }
  3405. }
  3406. }
  3407. if (canUseLinkPhase) {
  3408. // Add unique configuration name to target-config map for later
  3409. // checks
  3410. auto& configVector = targetConfigMap[libName];
  3411. if (std::find(configVector.begin(), configVector.end(),
  3412. configName) == configVector.end()) {
  3413. configVector.push_back(configName);
  3414. }
  3415. // Add a pair of config and item to target-item map
  3416. auto& itemVector = targetItemMap[libName];
  3417. itemVector.emplace_back(configName, &libItem);
  3418. // Add product file-name to a lib-product map
  3419. auto productName =
  3420. cmSystemTools::GetFilenameName(libItem.Value.Value);
  3421. auto& productVector = targetProductNameMap[libName];
  3422. if (std::find(productVector.begin(), productVector.end(),
  3423. productName) == productVector.end()) {
  3424. productVector.push_back(productName);
  3425. }
  3426. continue;
  3427. }
  3428. }
  3429. // Add this library item to a regular linker flag list
  3430. addToLinkerArguments(configName, &libItem);
  3431. }
  3432. }
  3433. // Go through target library map and separate libraries that are linked
  3434. // in all configurations and produce only single product, from the rest.
  3435. // Only these will be linked through "Link Binary With Libraries" build
  3436. // phase.
  3437. for (auto const& targetLibConfigs : targetConfigMap) {
  3438. // Add this library to "Link Binary With Libraries" build phase if it's
  3439. // linked in all configurations and it has only one product name
  3440. auto& itemVector = targetItemMap[targetLibConfigs.first];
  3441. auto& productVector = targetProductNameMap[targetLibConfigs.first];
  3442. if (targetLibConfigs.second == this->CurrentConfigurationTypes &&
  3443. productVector.size() == 1) {
  3444. // Add this library to "Link Binary With Libraries" list
  3445. linkPhaseTargetVector.push_back(itemVector[0].second);
  3446. } else {
  3447. for (auto const& libItem : targetItemMap[targetLibConfigs.first]) {
  3448. // Add this library item to a regular linker flag list
  3449. addToLinkerArguments(libItem.first, libItem.second);
  3450. }
  3451. }
  3452. }
  3453. // Add libraries to "Link Binary With Libraries" build phase and collect
  3454. // their search paths. Xcode does not support per-configuration linking
  3455. // in this build phase so we don't have to do this for each configuration
  3456. // separately.
  3457. std::vector<std::string> linkSearchPaths;
  3458. std::vector<std::string> frameworkSearchPaths;
  3459. std::set<std::pair<cmXCodeObject*, std::string>> linkBuildFileSet;
  3460. for (auto const& libItem : linkPhaseTargetVector) {
  3461. // Add target output directory as a library search path
  3462. std::string linkDir;
  3463. if (libItem->Target) {
  3464. linkDir = libItem->Target->GetLocationForBuild();
  3465. } else {
  3466. linkDir = libItem->Value.Value;
  3467. }
  3468. if (cmHasSuffix(libItem->GetFeatureName(), "FRAMEWORK"_s)) {
  3469. auto fwDescriptor = this->SplitFrameworkPath(
  3470. linkDir, cmGlobalGenerator::FrameworkFormat::Extended);
  3471. if (fwDescriptor && !fwDescriptor->Directory.empty()) {
  3472. linkDir = fwDescriptor->Directory;
  3473. if (std::find(frameworkSearchPaths.begin(), frameworkSearchPaths.end(),
  3474. linkDir) == frameworkSearchPaths.end()) {
  3475. frameworkSearchPaths.push_back(linkDir);
  3476. }
  3477. }
  3478. } else {
  3479. linkDir = cmSystemTools::GetParentDirectory(linkDir);
  3480. if (std::find(linkSearchPaths.begin(), linkSearchPaths.end(), linkDir) ==
  3481. linkSearchPaths.end()) {
  3482. linkSearchPaths.push_back(linkDir);
  3483. }
  3484. }
  3485. if (libItem->Target && !libItem->Target->IsImported()) {
  3486. for (auto const& configName : this->CurrentConfigurationTypes) {
  3487. target->AddDependTarget(configName, libItem->Target->GetName());
  3488. }
  3489. }
  3490. // Get the library target
  3491. auto* libTarget = FindXCodeTarget(libItem->Target);
  3492. cmXCodeObject* buildFile;
  3493. if (!libTarget) {
  3494. if (libItem->IsPath == cmComputeLinkInformation::ItemIsPath::Yes) {
  3495. // Get or create a direct file ref in the root project
  3496. auto cleanPath = libItem->Value.Value;
  3497. if (cmSystemTools::FileIsFullPath(cleanPath)) {
  3498. // Some arguments are reported as paths, but they are actually not,
  3499. // so we can't collapse them, and neither can we collapse relative
  3500. // paths
  3501. cleanPath = cmSystemTools::CollapseFullPath(cleanPath);
  3502. }
  3503. auto it = this->ExternalLibRefs.find(cleanPath);
  3504. if (it == this->ExternalLibRefs.end()) {
  3505. buildFile = CreateXCodeBuildFileFromPath(cleanPath, gt, "", nullptr);
  3506. if (!buildFile) {
  3507. // Add this library item back to a regular linker flag list
  3508. for (auto const& conf : configItemMap) {
  3509. addToLinkerArguments(conf.first, libItem);
  3510. }
  3511. continue;
  3512. }
  3513. this->ExternalLibRefs.emplace(cleanPath, buildFile);
  3514. } else {
  3515. buildFile = it->second;
  3516. }
  3517. } else {
  3518. // Add this library item back to a regular linker flag list
  3519. for (auto const& conf : configItemMap) {
  3520. addToLinkerArguments(conf.first, libItem);
  3521. }
  3522. continue;
  3523. }
  3524. } else {
  3525. // Add the target output file as a build reference for other targets
  3526. // to link against
  3527. auto* fileRefObject = libTarget->GetAttribute("productReference");
  3528. if (!fileRefObject) {
  3529. // Add this library item back to a regular linker flag list
  3530. for (auto const& conf : configItemMap) {
  3531. addToLinkerArguments(conf.first, libItem);
  3532. }
  3533. continue;
  3534. }
  3535. auto it = FileRefToBuildFileMap.find(fileRefObject);
  3536. if (it == FileRefToBuildFileMap.end()) {
  3537. buildFile = this->CreateObject(cmXCodeObject::PBXBuildFile);
  3538. buildFile->AddAttribute("fileRef", fileRefObject);
  3539. FileRefToBuildFileMap[fileRefObject] = buildFile;
  3540. } else {
  3541. buildFile = it->second;
  3542. }
  3543. }
  3544. // Add this reference to current target
  3545. auto* buildPhases = target->GetAttribute("buildPhases");
  3546. if (!buildPhases) {
  3547. cmSystemTools::Error("Missing buildPhase of target");
  3548. continue;
  3549. }
  3550. auto* frameworkBuildPhase =
  3551. buildPhases->GetObject(cmXCodeObject::PBXFrameworksBuildPhase);
  3552. if (!frameworkBuildPhase) {
  3553. cmSystemTools::Error("Missing PBXFrameworksBuildPhase of buildPhase");
  3554. continue;
  3555. }
  3556. auto* buildFiles = frameworkBuildPhase->GetAttribute("files");
  3557. if (!buildFiles) {
  3558. cmSystemTools::Error("Missing files of PBXFrameworksBuildPhase");
  3559. continue;
  3560. }
  3561. if (buildFile) {
  3562. if (cmHasPrefix(libItem->GetFeatureName(), "WEAK_"_s)) {
  3563. auto key = std::make_pair(buildFile->GetAttribute("fileRef"),
  3564. libItem->GetFeatureName());
  3565. if (linkBuildFileSet.find(key) != linkBuildFileSet.end()) {
  3566. continue;
  3567. }
  3568. linkBuildFileSet.insert(key);
  3569. cmXCodeObject* buildObject =
  3570. this->CreateObject(cmXCodeObject::PBXBuildFile);
  3571. buildObject->AddAttribute("fileRef", key.first);
  3572. // Add settings, ATTRIBUTES, Weak flag
  3573. cmXCodeObject* settings =
  3574. this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  3575. cmXCodeObject* attrs = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3576. attrs->AddObject(this->CreateString("Weak"));
  3577. settings->AddAttribute("ATTRIBUTES", attrs);
  3578. buildObject->AddAttribute("settings", settings);
  3579. buildFile = buildObject;
  3580. }
  3581. if (!buildFiles->HasObject(buildFile)) {
  3582. buildFiles->AddObject(buildFile);
  3583. }
  3584. }
  3585. }
  3586. // Loop over configuration types and set per-configuration info.
  3587. for (auto const& configName : this->CurrentConfigurationTypes) {
  3588. {
  3589. // Add object library contents as link flags.
  3590. BuildObjectListOrString libSearchPaths(this, true);
  3591. std::vector<cmSourceFile const*> objs;
  3592. gt->GetExternalObjects(objs, configName);
  3593. for (auto const* sourceFile : objs) {
  3594. if (sourceFile->GetObjectLibrary().empty()) {
  3595. continue;
  3596. }
  3597. libSearchPaths.Add(this->XCodeEscapePath(sourceFile->GetFullPath()));
  3598. }
  3599. this->AppendBuildSettingAttribute(
  3600. target, this->GetTargetLinkFlagsVar(gt), libSearchPaths.CreateList(),
  3601. configName);
  3602. }
  3603. // Compute the link library and directory information.
  3604. cmComputeLinkInformation* cli = gt->GetLinkInformation(configName);
  3605. if (!cli) {
  3606. continue;
  3607. }
  3608. // add .xcframework include paths
  3609. {
  3610. // Keep track of framework search paths we've already added or that are
  3611. // part of the set of implicit search paths. We don't want to repeat
  3612. // them and we also need to avoid hard-coding any SDK-specific paths.
  3613. // This is essential for getting device-and-simulator builds to work,
  3614. // otherwise we end up hard-coding a path to the wrong SDK for
  3615. // SDK-provided frameworks that are added by their full path.
  3616. std::set<std::string> emitted(cli->GetFrameworkPathsEmitted());
  3617. BuildObjectListOrString includePaths(this, true);
  3618. BuildObjectListOrString fwSearchPaths(this, true);
  3619. for (auto const& libItem : configItemMap[configName]) {
  3620. auto const& libName = *libItem;
  3621. if (libName.IsPath == cmComputeLinkInformation::ItemIsPath::Yes) {
  3622. auto cleanPath = libName.Value.Value;
  3623. if (cmSystemTools::FileIsFullPath(cleanPath)) {
  3624. cleanPath = cmSystemTools::CollapseFullPath(cleanPath);
  3625. }
  3626. bool isXcFramework =
  3627. cmHasSuffix(libName.GetFeatureName(), "XCFRAMEWORK"_s);
  3628. if (isXcFramework) {
  3629. auto plist = cmParseXcFrameworkPlist(
  3630. cleanPath, *this->Makefiles.front(), libName.Value.Backtrace);
  3631. if (!plist) {
  3632. return;
  3633. }
  3634. if (auto const* library = plist->SelectSuitableLibrary(
  3635. *this->Makefiles.front(), libName.Value.Backtrace)) {
  3636. auto libraryPath =
  3637. cmStrCat(cleanPath, '/', library->LibraryIdentifier, '/',
  3638. library->LibraryPath);
  3639. if (auto const fwDescriptor = this->SplitFrameworkPath(
  3640. libraryPath,
  3641. cmGlobalGenerator::FrameworkFormat::Relaxed)) {
  3642. if (!fwDescriptor->Directory.empty() &&
  3643. emitted.insert(fwDescriptor->Directory).second) {
  3644. // This is a search path we had not added before and it
  3645. // isn't an implicit search path, so we need it
  3646. fwSearchPaths.Add(
  3647. this->XCodeEscapePath(fwDescriptor->Directory));
  3648. }
  3649. } else {
  3650. if (!library->HeadersPath.empty()) {
  3651. includePaths.Add(this->XCodeEscapePath(
  3652. cmStrCat(cleanPath, '/', library->LibraryIdentifier, '/',
  3653. library->HeadersPath)));
  3654. }
  3655. }
  3656. } else {
  3657. return;
  3658. }
  3659. }
  3660. }
  3661. }
  3662. if (!includePaths.IsEmpty()) {
  3663. this->AppendBuildSettingAttribute(target, "HEADER_SEARCH_PATHS",
  3664. includePaths.CreateList(),
  3665. configName);
  3666. }
  3667. if (!fwSearchPaths.IsEmpty()) {
  3668. this->AppendBuildSettingAttribute(target, "FRAMEWORK_SEARCH_PATHS",
  3669. fwSearchPaths.CreateList(),
  3670. configName);
  3671. }
  3672. }
  3673. // Skip link information for object libraries.
  3674. if (gt->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  3675. gt->GetType() == cmStateEnums::STATIC_LIBRARY) {
  3676. continue;
  3677. }
  3678. // Add dependencies directly on library files.
  3679. for (auto const& libDep : cli->GetDepends()) {
  3680. target->AddDependLibrary(configName, libDep);
  3681. }
  3682. // add the library search paths
  3683. {
  3684. BuildObjectListOrString libSearchPaths(this, true);
  3685. for (auto const& libDir : cli->GetDirectories()) {
  3686. if (!libDir.empty() && libDir != "/usr/lib"_s) {
  3687. cmPolicies::PolicyStatus cmp0142 =
  3688. target->GetTarget()->GetPolicyStatusCMP0142();
  3689. if (cmp0142 == cmPolicies::OLD || cmp0142 == cmPolicies::WARN) {
  3690. libSearchPaths.Add(this->XCodeEscapePath(cmStrCat(
  3691. libDir, "/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)")));
  3692. }
  3693. libSearchPaths.Add(this->XCodeEscapePath(libDir));
  3694. }
  3695. }
  3696. // Add previously collected paths where to look for libraries
  3697. // that were added to "Link Binary With Libraries"
  3698. for (auto& libDir : linkSearchPaths) {
  3699. libSearchPaths.Add(this->XCodeEscapePath(libDir));
  3700. }
  3701. // Add toolchain specified language link directories
  3702. std::string const& linkDirsString =
  3703. this->Makefiles.front()->GetSafeDefinition(cmStrCat(
  3704. "CMAKE_", cli->GetLinkLanguage(), "_STANDARD_LINK_DIRECTORIES"));
  3705. for (auto const& libDir : cmList(linkDirsString)) {
  3706. libSearchPaths.Add(this->XCodeEscapePath(libDir));
  3707. }
  3708. if (!libSearchPaths.IsEmpty()) {
  3709. this->AppendBuildSettingAttribute(target, "LIBRARY_SEARCH_PATHS",
  3710. libSearchPaths.CreateList(),
  3711. configName);
  3712. }
  3713. }
  3714. // add framework search paths
  3715. {
  3716. BuildObjectListOrString fwSearchPaths(this, true);
  3717. // Add previously collected paths where to look for frameworks
  3718. // that were added to "Link Binary With Libraries"
  3719. for (auto& fwDir : frameworkSearchPaths) {
  3720. fwSearchPaths.Add(this->XCodeEscapePath(fwDir));
  3721. }
  3722. if (!fwSearchPaths.IsEmpty()) {
  3723. this->AppendBuildSettingAttribute(target, "FRAMEWORK_SEARCH_PATHS",
  3724. fwSearchPaths.CreateList(),
  3725. configName);
  3726. }
  3727. }
  3728. // now add the left-over link libraries
  3729. {
  3730. // Keep track of framework search paths we've already added or that are
  3731. // part of the set of implicit search paths. We don't want to repeat
  3732. // them and we also need to avoid hard-coding any SDK-specific paths.
  3733. // This is essential for getting device-and-simulator builds to work,
  3734. // otherwise we end up hard-coding a path to the wrong SDK for
  3735. // SDK-provided frameworks that are added by their full path.
  3736. std::set<std::string> emitted(cli->GetFrameworkPathsEmitted());
  3737. BuildObjectListOrString libPaths(this, true);
  3738. BuildObjectListOrString fwSearchPaths(this, true);
  3739. for (auto const& libItem : configItemMap[configName]) {
  3740. auto const& libName = *libItem;
  3741. if (libName.IsPath == cmComputeLinkInformation::ItemIsPath::Yes) {
  3742. auto cleanPath = libName.Value.Value;
  3743. if (cmSystemTools::FileIsFullPath(cleanPath)) {
  3744. cleanPath = cmSystemTools::CollapseFullPath(cleanPath);
  3745. }
  3746. bool isXcFramework =
  3747. cmHasSuffix(libName.GetFeatureName(), "XCFRAMEWORK"_s);
  3748. bool isFramework = !isXcFramework &&
  3749. cmHasSuffix(libName.GetFeatureName(), "FRAMEWORK"_s);
  3750. if (isFramework) {
  3751. auto const fwDescriptor = this->SplitFrameworkPath(
  3752. cleanPath, cmGlobalGenerator::FrameworkFormat::Extended);
  3753. if (isFramework && !fwDescriptor->Directory.empty() &&
  3754. emitted.insert(fwDescriptor->Directory).second) {
  3755. // This is a search path we had not added before and it isn't
  3756. // an implicit search path, so we need it
  3757. fwSearchPaths.Add(
  3758. this->XCodeEscapePath(fwDescriptor->Directory));
  3759. }
  3760. if (libName.GetFeatureName() == "__CMAKE_LINK_FRAMEWORK"_s) {
  3761. // use the full path
  3762. libPaths.Add(
  3763. libName.GetFormattedItem(this->XCodeEscapePath(cleanPath))
  3764. .Value);
  3765. } else {
  3766. libPaths.Add(libName
  3767. .GetFormattedItem(this->XCodeEscapePath(
  3768. fwDescriptor->GetLinkName()))
  3769. .Value);
  3770. }
  3771. } else if (isXcFramework) {
  3772. auto plist = cmParseXcFrameworkPlist(
  3773. cleanPath, *this->Makefiles.front(), libName.Value.Backtrace);
  3774. if (!plist) {
  3775. return;
  3776. }
  3777. if (auto const* library = plist->SelectSuitableLibrary(
  3778. *this->Makefiles.front(), libName.Value.Backtrace)) {
  3779. auto libraryPath =
  3780. cmStrCat(cleanPath, '/', library->LibraryIdentifier, '/',
  3781. library->LibraryPath);
  3782. if (auto const fwDescriptor = this->SplitFrameworkPath(
  3783. libraryPath,
  3784. cmGlobalGenerator::FrameworkFormat::Relaxed)) {
  3785. libPaths.Add(cmStrCat(
  3786. "-framework ",
  3787. this->XCodeEscapePath(fwDescriptor->GetLinkName())));
  3788. } else {
  3789. libPaths.Add(
  3790. libName.GetFormattedItem(this->XCodeEscapePath(libraryPath))
  3791. .Value);
  3792. }
  3793. } else {
  3794. return;
  3795. }
  3796. } else {
  3797. libPaths.Add(
  3798. libName.GetFormattedItem(this->XCodeEscapePath(cleanPath))
  3799. .Value);
  3800. }
  3801. if ((!libName.Target || libName.Target->IsImported()) &&
  3802. (isFramework || isXcFramework ||
  3803. IsLinkPhaseLibraryExtension(cleanPath))) {
  3804. // Create file reference for embedding
  3805. auto it = this->ExternalLibRefs.find(cleanPath);
  3806. if (it == this->ExternalLibRefs.end()) {
  3807. auto* buildFile =
  3808. this->CreateXCodeBuildFileFromPath(cleanPath, gt, "", nullptr);
  3809. if (buildFile) {
  3810. this->ExternalLibRefs.emplace(cleanPath, buildFile);
  3811. }
  3812. }
  3813. }
  3814. } else if (!libName.Target ||
  3815. libName.Target->GetType() !=
  3816. cmStateEnums::INTERFACE_LIBRARY) {
  3817. libPaths.Add(libName.Value.Value);
  3818. }
  3819. if (libName.Target && !libName.Target->IsImported()) {
  3820. target->AddDependTarget(configName, libName.Target->GetName());
  3821. }
  3822. }
  3823. if (!libPaths.IsEmpty()) {
  3824. this->AppendBuildSettingAttribute(target,
  3825. this->GetTargetLinkFlagsVar(gt),
  3826. libPaths.CreateList(), configName);
  3827. }
  3828. if (!fwSearchPaths.IsEmpty()) {
  3829. this->AppendBuildSettingAttribute(target, "FRAMEWORK_SEARCH_PATHS",
  3830. fwSearchPaths.CreateList(),
  3831. configName);
  3832. }
  3833. }
  3834. }
  3835. }
  3836. void cmGlobalXCodeGenerator::AddEmbeddedObjects(
  3837. cmXCodeObject* target, std::string const& copyFilesBuildPhaseName,
  3838. std::string const& embedPropertyName, std::string const& dstSubfolderSpec,
  3839. int actionsOnByDefault, std::string const& defaultDstPath)
  3840. {
  3841. cmGeneratorTarget* gt = target->GetTarget();
  3842. if (!gt) {
  3843. cmSystemTools::Error("Error no target on xobject\n");
  3844. return;
  3845. }
  3846. if (!gt->IsInBuildSystem()) {
  3847. return;
  3848. }
  3849. bool isFrameworkTarget = gt->IsFrameworkOnApple();
  3850. bool isBundleTarget = gt->GetPropertyAsBool("MACOSX_BUNDLE");
  3851. bool isCFBundleTarget = gt->IsCFBundleOnApple();
  3852. if (!(isFrameworkTarget || isBundleTarget || isCFBundleTarget)) {
  3853. return;
  3854. }
  3855. cmValue files = gt->GetProperty(embedPropertyName);
  3856. if (!files) {
  3857. return;
  3858. }
  3859. // Create an "Embedded Frameworks" build phase
  3860. auto* copyFilesBuildPhase =
  3861. this->CreateObject(cmXCodeObject::PBXCopyFilesBuildPhase);
  3862. copyFilesBuildPhase->SetComment(copyFilesBuildPhaseName);
  3863. copyFilesBuildPhase->AddAttribute("buildActionMask",
  3864. this->CreateString("2147483647"));
  3865. copyFilesBuildPhase->AddAttribute("dstSubfolderSpec",
  3866. this->CreateString(dstSubfolderSpec));
  3867. copyFilesBuildPhase->AddAttribute(
  3868. "name", this->CreateString(copyFilesBuildPhaseName));
  3869. if (cmValue fwEmbedPath =
  3870. gt->GetProperty(cmStrCat(embedPropertyName, "_PATH"))) {
  3871. copyFilesBuildPhase->AddAttribute("dstPath",
  3872. this->CreateString(*fwEmbedPath));
  3873. } else {
  3874. copyFilesBuildPhase->AddAttribute("dstPath",
  3875. this->CreateString(defaultDstPath));
  3876. }
  3877. copyFilesBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  3878. this->CreateString("0"));
  3879. cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3880. // Collect all embedded frameworks and dylibs and add them to build phase
  3881. cmList relFiles{ *files };
  3882. for (std::string const& relFile : relFiles) {
  3883. cmXCodeObject* buildFile{ nullptr };
  3884. std::string filePath = relFile;
  3885. auto* genTarget = this->FindGeneratorTarget(relFile);
  3886. if (genTarget) {
  3887. // This is a target - get it's product path reference
  3888. auto* xcTarget = this->FindXCodeTarget(genTarget);
  3889. if (!xcTarget) {
  3890. cmSystemTools::Error(
  3891. cmStrCat("Can not find a target for ", genTarget->GetName()));
  3892. continue;
  3893. }
  3894. // Add the target output file as a build reference for other targets
  3895. // to link against
  3896. auto* fileRefObject = xcTarget->GetAttribute("productReference");
  3897. if (!fileRefObject) {
  3898. cmSystemTools::Error(cmStrCat("Target ", genTarget->GetName(),
  3899. " is missing product reference"));
  3900. continue;
  3901. }
  3902. auto it = this->FileRefToEmbedBuildFileMap.find(fileRefObject);
  3903. if (it == this->FileRefToEmbedBuildFileMap.end()) {
  3904. buildFile = this->CreateObject(cmXCodeObject::PBXBuildFile);
  3905. buildFile->AddAttribute("fileRef", fileRefObject);
  3906. this->FileRefToEmbedBuildFileMap[fileRefObject] = buildFile;
  3907. } else {
  3908. buildFile = it->second;
  3909. }
  3910. } else if (cmSystemTools::IsPathToFramework(relFile) ||
  3911. cmSystemTools::IsPathToMacOSSharedLibrary(relFile) ||
  3912. cmSystemTools::FileIsDirectory(filePath)) {
  3913. // This is a regular string path - create file reference
  3914. cmXCodeObject* fileRef =
  3915. this->CreateXCodeFileReferenceFromPath(relFile, gt, "", nullptr);
  3916. if (fileRef) {
  3917. buildFile = this->CreateObject(cmXCodeObject::PBXBuildFile);
  3918. buildFile->SetComment(fileRef->GetComment());
  3919. buildFile->AddAttribute("fileRef",
  3920. this->CreateObjectReference(fileRef));
  3921. }
  3922. if (!buildFile) {
  3923. cmSystemTools::Error(
  3924. cmStrCat("Can't create build file for ", relFile));
  3925. continue;
  3926. }
  3927. }
  3928. if (!buildFile) {
  3929. cmSystemTools::Error(cmStrCat("Can't find a build file for ", relFile));
  3930. continue;
  3931. }
  3932. // Set build file configuration
  3933. cmXCodeObject* settings =
  3934. this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  3935. cmXCodeObject* attrs = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3936. bool removeHeaders = actionsOnByDefault & RemoveHeadersOnCopyByDefault;
  3937. if (cmValue prop = gt->GetProperty(
  3938. cmStrCat(embedPropertyName, "_REMOVE_HEADERS_ON_COPY"))) {
  3939. removeHeaders = prop.IsOn();
  3940. }
  3941. if (removeHeaders) {
  3942. attrs->AddObject(this->CreateString("RemoveHeadersOnCopy"));
  3943. }
  3944. bool codeSign = actionsOnByDefault & CodeSignOnCopyByDefault;
  3945. if (cmValue prop =
  3946. gt->GetProperty(cmStrCat(embedPropertyName, "_CODE_SIGN_ON_COPY"))) {
  3947. codeSign = prop.IsOn();
  3948. }
  3949. if (codeSign) {
  3950. attrs->AddObject(this->CreateString("CodeSignOnCopy"));
  3951. }
  3952. settings->AddAttributeIfNotEmpty("ATTRIBUTES", attrs);
  3953. buildFile->AddAttributeIfNotEmpty("settings", settings);
  3954. if (!buildFiles->HasObject(buildFile)) {
  3955. buildFiles->AddObject(buildFile);
  3956. }
  3957. }
  3958. copyFilesBuildPhase->AddAttribute("files", buildFiles);
  3959. auto* buildPhases = target->GetAttribute("buildPhases");
  3960. // Embed-something build phases must be inserted before the post-build
  3961. // command because that command is expected to be last
  3962. buildPhases->InsertObject(buildPhases->GetObjectCount() - 1,
  3963. copyFilesBuildPhase);
  3964. }
  3965. void cmGlobalXCodeGenerator::AddEmbeddedFrameworks(cmXCodeObject* target)
  3966. {
  3967. static auto const* const dstSubfolderSpec = "10";
  3968. // Despite the name, by default Xcode uses "Embed Frameworks" build phase
  3969. // for both frameworks and dynamic libraries
  3970. this->AddEmbeddedObjects(target, "Embed Frameworks",
  3971. "XCODE_EMBED_FRAMEWORKS", dstSubfolderSpec,
  3972. NoActionOnCopyByDefault);
  3973. }
  3974. void cmGlobalXCodeGenerator::AddEmbeddedPlugIns(cmXCodeObject* target)
  3975. {
  3976. static auto const* const dstSubfolderSpec = "13";
  3977. this->AddEmbeddedObjects(target, "Embed PlugIns", "XCODE_EMBED_PLUGINS",
  3978. dstSubfolderSpec, NoActionOnCopyByDefault);
  3979. }
  3980. void cmGlobalXCodeGenerator::AddEmbeddedAppExtensions(cmXCodeObject* target)
  3981. {
  3982. static auto const* const dstSubfolderSpec = "13";
  3983. this->AddEmbeddedObjects(target, "Embed App Extensions",
  3984. "XCODE_EMBED_APP_EXTENSIONS", dstSubfolderSpec,
  3985. RemoveHeadersOnCopyByDefault);
  3986. }
  3987. void cmGlobalXCodeGenerator::AddEmbeddedExtensionKitExtensions(
  3988. cmXCodeObject* target)
  3989. {
  3990. static auto const* const dstSubfolderSpec = "16";
  3991. this->AddEmbeddedObjects(target, "Embed App Extensions",
  3992. "XCODE_EMBED_EXTENSIONKIT_EXTENSIONS",
  3993. dstSubfolderSpec, RemoveHeadersOnCopyByDefault,
  3994. "$(EXTENSIONS_FOLDER_PATH)");
  3995. }
  3996. void cmGlobalXCodeGenerator::AddEmbeddedResources(cmXCodeObject* target)
  3997. {
  3998. static auto const dstSubfolderSpec = "7";
  3999. this->AddEmbeddedObjects(target, "Embed Resources", "XCODE_EMBED_RESOURCES",
  4000. dstSubfolderSpec, NoActionOnCopyByDefault);
  4001. }
  4002. void cmGlobalXCodeGenerator::AddEmbeddedXPCServices(cmXCodeObject* target)
  4003. {
  4004. static auto const dstSubfolderSpec = "16";
  4005. this->AddEmbeddedObjects(
  4006. target, "Embed XPC Services", "XCODE_EMBED_XPC_SERVICES", dstSubfolderSpec,
  4007. NoActionOnCopyByDefault, "$(CONTENTS_FOLDER_PATH)/XPCServices");
  4008. }
  4009. bool cmGlobalXCodeGenerator::CreateGroups(
  4010. std::vector<cmLocalGenerator*>& generators)
  4011. {
  4012. for (auto& generator : generators) {
  4013. cmMakefile* mf = generator->GetMakefile();
  4014. std::vector<cmSourceGroup> sourceGroups = mf->GetSourceGroups();
  4015. for (auto const& gtgt : generator->GetGeneratorTargets()) {
  4016. // Same skipping logic here as in CreateXCodeTargets so that we do not
  4017. // end up with (empty anyhow) ZERO_CHECK, install, or test source
  4018. // groups:
  4019. //
  4020. if (!gtgt->IsInBuildSystem() ||
  4021. gtgt->GetType() == cmStateEnums::GLOBAL_TARGET ||
  4022. gtgt->GetName() == CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
  4023. continue;
  4024. }
  4025. auto addSourceToGroup = [this, mf, &gtgt,
  4026. &sourceGroups](std::string const& source) {
  4027. cmSourceGroup* sourceGroup = mf->FindSourceGroup(source, sourceGroups);
  4028. cmXCodeObject* pbxgroup =
  4029. this->CreateOrGetPBXGroup(gtgt.get(), sourceGroup);
  4030. std::string key = GetGroupMapKeyFromPath(gtgt.get(), source);
  4031. this->GroupMap[key] = pbxgroup;
  4032. };
  4033. // Put cmSourceFile instances in proper groups:
  4034. for (auto const& si : gtgt->GetAllConfigSources()) {
  4035. cmSourceFile const* sf = si.Source;
  4036. if (!sf->GetObjectLibrary().empty()) {
  4037. // Object library files go on the link line instead.
  4038. continue;
  4039. }
  4040. addSourceToGroup(sf->GetFullPath());
  4041. }
  4042. // Add CMakeLists.txt file for user convenience.
  4043. {
  4044. std::string listfile = this->GetCMakeInstance()->GetCMakeListFile(
  4045. gtgt->GetLocalGenerator()->GetCurrentSourceDirectory());
  4046. cmSourceFile* sf = gtgt->Makefile->GetOrCreateSource(
  4047. listfile, false, cmSourceFileLocationKind::Known);
  4048. addSourceToGroup(sf->ResolveFullPath());
  4049. }
  4050. // Add the Info.plist we are about to generate for an App Bundle.
  4051. if (gtgt->GetPropertyAsBool("MACOSX_BUNDLE")) {
  4052. std::string plist = this->ComputeInfoPListLocation(gtgt.get());
  4053. cmSourceFile* sf = gtgt->Makefile->GetOrCreateSource(
  4054. plist, true, cmSourceFileLocationKind::Known);
  4055. addSourceToGroup(sf->ResolveFullPath());
  4056. }
  4057. }
  4058. }
  4059. return true;
  4060. }
  4061. cmXCodeObject* cmGlobalXCodeGenerator::CreatePBXGroup(cmXCodeObject* parent,
  4062. std::string const& name)
  4063. {
  4064. cmXCodeObject* parentChildren = nullptr;
  4065. if (parent) {
  4066. parentChildren = parent->GetAttribute("children");
  4067. }
  4068. cmXCodeObject* group = this->CreateObject(cmXCodeObject::PBXGroup);
  4069. cmXCodeObject* groupChildren =
  4070. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4071. group->AddAttribute("name", this->CreateString(name));
  4072. group->AddAttribute("children", groupChildren);
  4073. group->AddAttribute("sourceTree", this->CreateString("<group>"));
  4074. if (parentChildren) {
  4075. parentChildren->AddObject(group);
  4076. }
  4077. return group;
  4078. }
  4079. cmXCodeObject* cmGlobalXCodeGenerator::CreateOrGetPBXGroup(
  4080. cmGeneratorTarget* gtgt, cmSourceGroup* sg)
  4081. {
  4082. std::string s;
  4083. std::string target;
  4084. std::string const targetFolder = gtgt->GetEffectiveFolderName();
  4085. if (!targetFolder.empty()) {
  4086. target = cmStrCat(targetFolder, '/');
  4087. }
  4088. target += gtgt->GetName();
  4089. s = cmStrCat(target, '/', sg->GetFullName());
  4090. auto it = this->GroupNameMap.find(s);
  4091. if (it != this->GroupNameMap.end()) {
  4092. return it->second;
  4093. }
  4094. it = this->TargetGroup.find(target);
  4095. cmXCodeObject* tgroup = nullptr;
  4096. if (it != this->TargetGroup.end()) {
  4097. tgroup = it->second;
  4098. } else {
  4099. std::vector<std::string> const tgt_folders = cmTokenize(target, '/');
  4100. std::string curr_tgt_folder;
  4101. for (std::vector<std::string>::size_type i = 0; i < tgt_folders.size();
  4102. i++) {
  4103. if (i != 0) {
  4104. curr_tgt_folder += '/';
  4105. }
  4106. curr_tgt_folder += tgt_folders[i];
  4107. it = this->TargetGroup.find(curr_tgt_folder);
  4108. if (it != this->TargetGroup.end()) {
  4109. tgroup = it->second;
  4110. continue;
  4111. }
  4112. tgroup = this->CreatePBXGroup(tgroup, tgt_folders[i]);
  4113. this->TargetGroup[curr_tgt_folder] = tgroup;
  4114. if (i == 0) {
  4115. this->MainGroupChildren->AddObject(tgroup);
  4116. }
  4117. }
  4118. }
  4119. this->TargetGroup[target] = tgroup;
  4120. // If it's the default source group (empty name) then put the source file
  4121. // directly in the tgroup...
  4122. //
  4123. if (sg->GetFullName().empty()) {
  4124. this->GroupNameMap[s] = tgroup;
  4125. return tgroup;
  4126. }
  4127. // It's a recursive folder structure, let's find the real parent group
  4128. if (sg->GetFullName() != sg->GetName()) {
  4129. std::string curr_folder = cmStrCat(target, '/');
  4130. for (auto const& folder : cmTokenize(sg->GetFullName(), '\\')) {
  4131. curr_folder += folder;
  4132. auto const i_folder = this->GroupNameMap.find(curr_folder);
  4133. // Create new folder
  4134. if (i_folder == this->GroupNameMap.end()) {
  4135. cmXCodeObject* group = this->CreatePBXGroup(tgroup, folder);
  4136. this->GroupNameMap[curr_folder] = group;
  4137. tgroup = group;
  4138. } else {
  4139. tgroup = i_folder->second;
  4140. }
  4141. curr_folder += '\\';
  4142. }
  4143. return tgroup;
  4144. }
  4145. cmXCodeObject* group = this->CreatePBXGroup(tgroup, sg->GetName());
  4146. this->GroupNameMap[s] = group;
  4147. return group;
  4148. }
  4149. bool cmGlobalXCodeGenerator::CreateXCodeObjects(
  4150. cmLocalGenerator* root, std::vector<cmLocalGenerator*>& generators)
  4151. {
  4152. this->ClearXCodeObjects();
  4153. this->RootObject = nullptr;
  4154. this->MainGroupChildren = nullptr;
  4155. this->FrameworkGroup = nullptr;
  4156. cmXCodeObject* group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  4157. group->AddAttribute("COPY_PHASE_STRIP", this->CreateString("NO"));
  4158. cmXCodeObject* listObjs = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4159. for (std::string const& CurrentConfigurationType :
  4160. this->CurrentConfigurationTypes) {
  4161. cmXCodeObject* buildStyle =
  4162. this->CreateObject(cmXCodeObject::PBXBuildStyle);
  4163. std::string const& name = CurrentConfigurationType;
  4164. buildStyle->AddAttribute("name", this->CreateString(name));
  4165. buildStyle->SetComment(name);
  4166. cmXCodeObject* sgroup = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  4167. sgroup->AddAttribute("COPY_PHASE_STRIP", this->CreateString("NO"));
  4168. buildStyle->AddAttribute("buildSettings", sgroup);
  4169. listObjs->AddObject(buildStyle);
  4170. }
  4171. cmXCodeObject* mainGroup = this->CreateObject(cmXCodeObject::PBXGroup);
  4172. this->MainGroupChildren = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4173. mainGroup->AddAttribute("children", this->MainGroupChildren);
  4174. mainGroup->AddAttribute("sourceTree", this->CreateString("<group>"));
  4175. // now create the cmake groups
  4176. if (!this->CreateGroups(generators)) {
  4177. return false;
  4178. }
  4179. cmXCodeObject* productGroup = this->CreateObject(cmXCodeObject::PBXGroup);
  4180. productGroup->AddAttribute("name", this->CreateString("Products"));
  4181. productGroup->AddAttribute("sourceTree", this->CreateString("<group>"));
  4182. cmXCodeObject* productGroupChildren =
  4183. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4184. productGroup->AddAttribute("children", productGroupChildren);
  4185. this->MainGroupChildren->AddObject(productGroup);
  4186. this->FrameworkGroup = this->CreateObject(cmXCodeObject::PBXGroup);
  4187. this->FrameworkGroup->AddAttribute("name", this->CreateString("Frameworks"));
  4188. this->FrameworkGroup->AddAttribute("sourceTree",
  4189. this->CreateString("<group>"));
  4190. cmXCodeObject* frameworkGroupChildren =
  4191. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4192. this->FrameworkGroup->AddAttribute("children", frameworkGroupChildren);
  4193. this->MainGroupChildren->AddObject(this->FrameworkGroup);
  4194. this->ResourcesGroup = this->CreateObject(cmXCodeObject::PBXGroup);
  4195. this->ResourcesGroup->AddAttribute("name", this->CreateString("Resources"));
  4196. this->ResourcesGroup->AddAttribute("sourceTree",
  4197. this->CreateString("<group>"));
  4198. cmXCodeObject* ResourcesGroupChildren =
  4199. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4200. this->ResourcesGroup->AddAttribute("children", ResourcesGroupChildren);
  4201. this->MainGroupChildren->AddObject(this->ResourcesGroup);
  4202. this->RootObject = this->CreateObject(cmXCodeObject::PBXProject);
  4203. this->RootObject->SetComment("Project object");
  4204. std::string project_id = cmStrCat("PROJECT_", root->GetProjectName());
  4205. this->RootObject->SetId(
  4206. this->GetOrCreateId(project_id, this->RootObject->GetId()));
  4207. group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  4208. this->RootObject->AddAttribute("mainGroup",
  4209. this->CreateObjectReference(mainGroup));
  4210. this->RootObject->AddAttribute("buildSettings", group);
  4211. this->RootObject->AddAttribute("buildStyles", listObjs);
  4212. this->RootObject->AddAttribute("hasScannedForEncodings",
  4213. this->CreateString("0"));
  4214. group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  4215. group->AddAttribute("BuildIndependentTargetsInParallel",
  4216. this->CreateString("YES"));
  4217. std::ostringstream v;
  4218. v << std::setfill('0') << std::setw(4) << XcodeVersion * 10;
  4219. group->AddAttribute("LastUpgradeCheck", this->CreateString(v.str()));
  4220. this->RootObject->AddAttribute("attributes", group);
  4221. this->RootObject->AddAttribute("compatibilityVersion",
  4222. this->CreateString("Xcode 3.2"));
  4223. // Point Xcode at the top of the source tree.
  4224. {
  4225. std::string pdir =
  4226. this->RelativeToBinary(root->GetCurrentSourceDirectory());
  4227. this->RootObject->AddAttribute("projectDirPath", this->CreateString(pdir));
  4228. this->RootObject->AddAttribute("projectRoot", this->CreateString(""));
  4229. }
  4230. cmXCodeObject* configlist =
  4231. this->CreateObject(cmXCodeObject::XCConfigurationList);
  4232. cmXCodeObject* buildConfigurations =
  4233. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4234. using Configs = std::vector<std::pair<std::string, cmXCodeObject*>>;
  4235. Configs configs;
  4236. std::string defaultConfigName;
  4237. for (auto const& name : this->CurrentConfigurationTypes) {
  4238. if (defaultConfigName.empty()) {
  4239. defaultConfigName = name;
  4240. }
  4241. cmXCodeObject* config =
  4242. this->CreateObject(cmXCodeObject::XCBuildConfiguration);
  4243. config->AddAttribute("name", this->CreateString(name));
  4244. configs.emplace_back(name, config);
  4245. }
  4246. if (defaultConfigName.empty()) {
  4247. defaultConfigName = "Debug";
  4248. }
  4249. for (auto& config : configs) {
  4250. buildConfigurations->AddObject(config.second);
  4251. }
  4252. configlist->AddAttribute("buildConfigurations", buildConfigurations);
  4253. std::string comment = cmStrCat("Build configuration list for PBXProject \"",
  4254. this->CurrentProject, '"');
  4255. configlist->SetComment(comment);
  4256. configlist->AddAttribute("defaultConfigurationIsVisible",
  4257. this->CreateString("0"));
  4258. configlist->AddAttribute("defaultConfigurationName",
  4259. this->CreateString(defaultConfigName));
  4260. cmXCodeObject* buildSettings =
  4261. this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  4262. cmValue sysroot = this->CurrentMakefile->GetDefinition("CMAKE_OSX_SYSROOT");
  4263. cmValue deploymentTarget =
  4264. this->CurrentMakefile->GetDefinition("CMAKE_OSX_DEPLOYMENT_TARGET");
  4265. if (sysroot) {
  4266. buildSettings->AddAttribute("SDKROOT", this->CreateString(*sysroot));
  4267. }
  4268. // recompute this as it may have been changed since enable language
  4269. this->ComputeArchitectures(this->CurrentMakefile);
  4270. std::string const archs = cmJoin(this->Architectures, " ");
  4271. if (archs.empty()) {
  4272. // Tell Xcode to use NATIVE_ARCH instead of ARCHS.
  4273. buildSettings->AddAttribute("ONLY_ACTIVE_ARCH", this->CreateString("YES"));
  4274. // When targeting macOS, use only the host architecture.
  4275. if (this->SystemName == "Darwin"_s &&
  4276. (!cmNonempty(sysroot) ||
  4277. cmSystemTools::LowerCase(*sysroot).find("macos") !=
  4278. std::string::npos)) {
  4279. buildSettings->AddAttribute("ARCHS",
  4280. this->CreateString("$(NATIVE_ARCH_ACTUAL)"));
  4281. }
  4282. } else {
  4283. // Tell Xcode to use ARCHS (ONLY_ACTIVE_ARCH defaults to NO).
  4284. buildSettings->AddAttribute("ARCHS", this->CreateString(archs));
  4285. }
  4286. if (cmNonempty(deploymentTarget)) {
  4287. buildSettings->AddAttribute(GetDeploymentPlatform(root->GetMakefile()),
  4288. this->CreateString(*deploymentTarget));
  4289. }
  4290. if (!this->GeneratorToolset.empty()) {
  4291. buildSettings->AddAttribute("GCC_VERSION",
  4292. this->CreateString(this->GeneratorToolset));
  4293. }
  4294. if (this->GetLanguageEnabled("Swift")) {
  4295. std::string swiftVersion;
  4296. if (cmValue vers = this->CurrentMakefile->GetDefinition(
  4297. "CMAKE_Swift_LANGUAGE_VERSION")) {
  4298. swiftVersion = *vers;
  4299. } else if (this->XcodeVersion >= 102) {
  4300. swiftVersion = "4.0";
  4301. } else if (this->XcodeVersion >= 83) {
  4302. swiftVersion = "3.0";
  4303. } else {
  4304. swiftVersion = "2.3";
  4305. }
  4306. buildSettings->AddAttribute("SWIFT_VERSION",
  4307. this->CreateString(swiftVersion));
  4308. }
  4309. std::string const symroot = this->GetSymrootDir();
  4310. buildSettings->AddAttribute("SYMROOT", this->CreateString(symroot));
  4311. // Inside a try_compile project, do not require signing on any platform.
  4312. if (this->CMakeInstance->GetIsInTryCompile()) {
  4313. buildSettings->AddAttribute("CODE_SIGNING_ALLOWED",
  4314. this->CreateString("NO"));
  4315. }
  4316. // This code supports the OLD behavior of CMP0157. We should be able to
  4317. // remove computing the debug configuration set once the old behavior is
  4318. // removed.
  4319. auto debugConfigs = this->GetCMakeInstance()->GetDebugConfigs();
  4320. std::set<std::string> debugConfigSet(debugConfigs.begin(),
  4321. debugConfigs.end());
  4322. for (auto& config : configs) {
  4323. CreateGlobalXCConfigSettings(root, config.second, config.first);
  4324. cmXCodeObject* buildSettingsForCfg = this->CreateFlatClone(buildSettings);
  4325. // Supports the OLD behavior of CMP0157. CMP0157 OLD behavior globally set
  4326. // wholemodule compilation for all non-debug configurations, for all
  4327. // targets.
  4328. if (this->CurrentMakefile
  4329. ->GetDefinition("CMAKE_Swift_COMPILATION_MODE_DEFAULT")
  4330. .IsEmpty()) {
  4331. if (debugConfigSet.count(cmSystemTools::UpperCase(config.first)) == 0) {
  4332. buildSettingsForCfg->AddAttribute("SWIFT_COMPILATION_MODE",
  4333. this->CreateString("wholemodule"));
  4334. }
  4335. }
  4336. // Put this last so it can override existing settings
  4337. // Convert "CMAKE_XCODE_ATTRIBUTE_*" variables directly.
  4338. for (auto const& var : this->CurrentMakefile->GetDefinitions()) {
  4339. if (cmHasLiteralPrefix(var, "CMAKE_XCODE_ATTRIBUTE_")) {
  4340. std::string attribute = var.substr(22);
  4341. this->FilterConfigurationAttribute(config.first, attribute);
  4342. if (!attribute.empty()) {
  4343. std::string processed = cmGeneratorExpression::Evaluate(
  4344. this->CurrentMakefile->GetSafeDefinition(var),
  4345. this->CurrentLocalGenerator, config.first);
  4346. buildSettingsForCfg->AddAttribute(attribute,
  4347. this->CreateString(processed));
  4348. }
  4349. }
  4350. }
  4351. // store per-config buildSettings into configuration object
  4352. config.second->AddAttribute("buildSettings", buildSettingsForCfg);
  4353. }
  4354. this->RootObject->AddAttribute("buildConfigurationList",
  4355. this->CreateObjectReference(configlist));
  4356. std::vector<cmXCodeObject*> targets;
  4357. for (auto& generator : generators) {
  4358. if (!this->CreateXCodeTargets(generator, targets)) {
  4359. return false;
  4360. }
  4361. for (auto const& ccRoot : this->CustomCommandRoots) {
  4362. if (ccRoot.second.size() > 1) {
  4363. std::string e = "The custom command ";
  4364. std::vector<std::string> const& outputs =
  4365. ccRoot.first->GetCustomCommand()->GetOutputs();
  4366. if (!outputs.empty()) {
  4367. e = cmStrCat(e, "generating\n ", outputs[0]);
  4368. } else {
  4369. e = cmStrCat(e, "driven by\n ", ccRoot.first->GetFullPath());
  4370. }
  4371. e = cmStrCat(e, "\nis attached to multiple targets:");
  4372. for (cmGeneratorTarget const* gt : ccRoot.second) {
  4373. e = cmStrCat(e, "\n ", gt->GetName());
  4374. }
  4375. e = cmStrCat(
  4376. e,
  4377. "\nbut none of these is a common dependency of the other(s). "
  4378. "This is not allowed by the Xcode \"new build system\".");
  4379. generator->IssueMessage(MessageType::FATAL_ERROR, e);
  4380. return false;
  4381. }
  4382. }
  4383. this->CustomCommandRoots.clear();
  4384. }
  4385. // loop over all targets and add link and depend info
  4386. for (auto* t : targets) {
  4387. this->AddDependAndLinkInformation(t);
  4388. this->AddEmbeddedFrameworks(t);
  4389. this->AddEmbeddedPlugIns(t);
  4390. this->AddEmbeddedAppExtensions(t);
  4391. this->AddEmbeddedExtensionKitExtensions(t);
  4392. this->AddEmbeddedResources(t);
  4393. this->AddEmbeddedXPCServices(t);
  4394. // Inherit project-wide values for any target-specific search paths.
  4395. this->InheritBuildSettingAttribute(t, "HEADER_SEARCH_PATHS");
  4396. this->InheritBuildSettingAttribute(t, "SYSTEM_HEADER_SEARCH_PATHS");
  4397. this->InheritBuildSettingAttribute(t, "FRAMEWORK_SEARCH_PATHS");
  4398. this->InheritBuildSettingAttribute(t, "SYSTEM_FRAMEWORK_SEARCH_PATHS");
  4399. this->InheritBuildSettingAttribute(t, "LIBRARY_SEARCH_PATHS");
  4400. this->InheritBuildSettingAttribute(t, "LD_RUNPATH_SEARCH_PATHS");
  4401. this->InheritBuildSettingAttribute(t, "GCC_PREPROCESSOR_DEFINITIONS");
  4402. this->InheritBuildSettingAttribute(t, "OTHER_CFLAGS");
  4403. this->InheritBuildSettingAttribute(t, "OTHER_LDFLAGS");
  4404. this->InheritBuildSettingAttribute(t, "OTHER_SWIFT_FLAGS");
  4405. this->InheritBuildSettingAttribute(t,
  4406. "SWIFT_ACTIVE_COMPILATION_CONDITIONS");
  4407. }
  4408. if (this->XcodeBuildSystem == BuildSystem::One) {
  4409. this->CreateXCodeDependHackMakefile(targets);
  4410. }
  4411. // now add all targets to the root object
  4412. cmXCodeObject* allTargets = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4413. for (auto* t : targets) {
  4414. allTargets->AddObject(t);
  4415. cmXCodeObject* productRef = t->GetAttribute("productReference");
  4416. if (productRef) {
  4417. productGroupChildren->AddObject(productRef->GetObject());
  4418. }
  4419. }
  4420. this->RootObject->AddAttribute("targets", allTargets);
  4421. return true;
  4422. }
  4423. std::string cmGlobalXCodeGenerator::GetSymrootDir() const
  4424. {
  4425. return cmStrCat(this->CMakeInstance->GetHomeOutputDirectory(), "/build");
  4426. }
  4427. std::string cmGlobalXCodeGenerator::GetTargetTempDir(
  4428. cmGeneratorTarget const* gt, std::string const& configName) const
  4429. {
  4430. // Use a path inside the SYMROOT.
  4431. return cmStrCat(this->GetSymrootDir(), '/', gt->GetName(), ".build/",
  4432. configName);
  4433. }
  4434. void cmGlobalXCodeGenerator::ComputeArchitectures(cmMakefile* mf)
  4435. {
  4436. this->Architectures.clear();
  4437. cmList::append(this->Architectures,
  4438. mf->GetDefinition("CMAKE_OSX_ARCHITECTURES"));
  4439. if (this->Architectures.empty()) {
  4440. cmList::append(this->Architectures,
  4441. mf->GetDefinition("_CMAKE_APPLE_ARCHS_DEFAULT"));
  4442. }
  4443. if (this->Architectures.empty()) {
  4444. // With no ARCHS we use ONLY_ACTIVE_ARCH and possibly a
  4445. // platform-specific default ARCHS placeholder value.
  4446. // Look up the arch that Xcode chooses in this case.
  4447. if (cmValue arch = mf->GetDefinition("CMAKE_XCODE_ARCHS")) {
  4448. this->ObjectDirArchDefault = *arch;
  4449. // We expect only one arch but choose the first just in case.
  4450. std::string::size_type pos = this->ObjectDirArchDefault.find(';');
  4451. if (pos != std::string::npos) {
  4452. this->ObjectDirArchDefault = this->ObjectDirArchDefault.substr(0, pos);
  4453. }
  4454. }
  4455. }
  4456. this->ComputeObjectDirArch(mf);
  4457. }
  4458. void cmGlobalXCodeGenerator::ComputeObjectDirArch(cmMakefile* mf)
  4459. {
  4460. if (this->Architectures.size() > 1 || this->UseEffectivePlatformName(mf)) {
  4461. this->ObjectDirArch = "$(CURRENT_ARCH)";
  4462. } else if (!this->Architectures.empty()) {
  4463. this->ObjectDirArch = this->Architectures[0];
  4464. } else {
  4465. this->ObjectDirArch = this->ObjectDirArchDefault;
  4466. }
  4467. }
  4468. void cmGlobalXCodeGenerator::CreateXCodeDependHackMakefile(
  4469. std::vector<cmXCodeObject*>& targets)
  4470. {
  4471. cmGeneratedFileStream makefileStream(this->CurrentXCodeHackMakefile);
  4472. if (!makefileStream) {
  4473. cmSystemTools::Error(
  4474. cmStrCat("Could not create ", this->CurrentXCodeHackMakefile));
  4475. return;
  4476. }
  4477. makefileStream.SetCopyIfDifferent(true);
  4478. // one more pass for external depend information not handled
  4479. // correctly by xcode
  4480. /* clang-format off */
  4481. makefileStream << "# DO NOT EDIT\n"
  4482. "# This makefile makes sure all linkable targets are\n"
  4483. "# up-to-date with anything they link to\n"
  4484. "default:\n"
  4485. "\techo \"Do not invoke directly\"\n"
  4486. "\n";
  4487. /* clang-format on */
  4488. std::set<std::string> dummyRules;
  4489. // Write rules to help Xcode relink things at the right time.
  4490. /* clang-format off */
  4491. makefileStream <<
  4492. "# Rules to remove targets that are older than anything to which they\n"
  4493. "# link. This forces Xcode to relink the targets from scratch. It\n"
  4494. "# does not seem to check these dependencies itself.\n";
  4495. /* clang-format on */
  4496. for (auto const& configName : this->CurrentConfigurationTypes) {
  4497. for (auto* target : targets) {
  4498. cmGeneratorTarget* gt = target->GetTarget();
  4499. if (gt->GetType() == cmStateEnums::EXECUTABLE ||
  4500. gt->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  4501. gt->GetType() == cmStateEnums::STATIC_LIBRARY ||
  4502. gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4503. gt->GetType() == cmStateEnums::MODULE_LIBRARY) {
  4504. // Declare an entry point for the target post-build phase.
  4505. makefileStream << this->PostBuildMakeTarget(gt->GetName(), configName)
  4506. << ":\n";
  4507. }
  4508. if (gt->GetType() == cmStateEnums::EXECUTABLE ||
  4509. gt->GetType() == cmStateEnums::STATIC_LIBRARY ||
  4510. gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4511. gt->GetType() == cmStateEnums::MODULE_LIBRARY) {
  4512. std::string tfull = gt->GetFullPath(configName);
  4513. std::string trel = ConvertToMakefilePath(tfull);
  4514. // Add this target to the post-build phases of its dependencies.
  4515. auto const y = target->GetDependTargets().find(configName);
  4516. if (y != target->GetDependTargets().end()) {
  4517. for (auto const& deptgt : y->second) {
  4518. makefileStream << this->PostBuildMakeTarget(deptgt, configName)
  4519. << ": " << trel << '\n';
  4520. }
  4521. }
  4522. std::vector<cmGeneratorTarget*> objlibs;
  4523. gt->GetObjectLibrariesInSources(objlibs);
  4524. for (auto* objLib : objlibs) {
  4525. makefileStream << this->PostBuildMakeTarget(objLib->GetName(),
  4526. configName)
  4527. << ": " << trel << '\n';
  4528. }
  4529. // Create a rule for this target.
  4530. makefileStream << trel << ':';
  4531. // List dependencies if any exist.
  4532. auto const x = target->GetDependLibraries().find(configName);
  4533. if (x != target->GetDependLibraries().end()) {
  4534. for (auto const& deplib : x->second) {
  4535. std::string file = ConvertToMakefilePath(deplib);
  4536. makefileStream << "\\\n\t" << file;
  4537. dummyRules.insert(file);
  4538. }
  4539. }
  4540. for (auto* objLib : objlibs) {
  4541. std::string const objLibName = objLib->GetName();
  4542. std::string d = cmStrCat(this->GetTargetTempDir(gt, configName),
  4543. "/lib", objLibName, ".a");
  4544. std::string dependency = ConvertToMakefilePath(d);
  4545. makefileStream << "\\\n\t" << dependency;
  4546. dummyRules.insert(dependency);
  4547. }
  4548. // Write the action to remove the target if it is out of date.
  4549. makefileStream << "\n"
  4550. "\t/bin/rm -f "
  4551. << ConvertToMakefilePath(tfull) << '\n';
  4552. // if building for more than one architecture
  4553. // then remove those executables as well
  4554. if (this->Architectures.size() > 1) {
  4555. std::string universal =
  4556. cmStrCat(this->GetTargetTempDir(gt, configName), "/$(OBJDIR)/");
  4557. for (auto const& architecture : this->Architectures) {
  4558. std::string universalFile = cmStrCat(universal, architecture, '/',
  4559. gt->GetFullName(configName));
  4560. makefileStream << "\t/bin/rm -f "
  4561. << ConvertToMakefilePath(universalFile) << '\n';
  4562. }
  4563. }
  4564. makefileStream << "\n\n";
  4565. }
  4566. }
  4567. }
  4568. makefileStream << "\n\n"
  4569. "# For each target create a dummy rule"
  4570. "so the target does not have to exist\n";
  4571. for (auto const& dummyRule : dummyRules) {
  4572. makefileStream << dummyRule << ":\n";
  4573. }
  4574. }
  4575. void cmGlobalXCodeGenerator::OutputXCodeProject(
  4576. cmLocalGenerator* root, std::vector<cmLocalGenerator*>& generators)
  4577. {
  4578. if (generators.empty()) {
  4579. return;
  4580. }
  4581. if (!this->CreateXCodeObjects(root, generators)) {
  4582. return;
  4583. }
  4584. std::string xcodeDir = cmStrCat(root->GetCurrentBinaryDirectory(), '/',
  4585. root->GetProjectName(), ".xcodeproj");
  4586. cmSystemTools::MakeDirectory(xcodeDir);
  4587. std::string xcodeProjFile = cmStrCat(xcodeDir, "/project.pbxproj");
  4588. cmGeneratedFileStream fout(xcodeProjFile);
  4589. fout.SetCopyIfDifferent(true);
  4590. if (!fout) {
  4591. return;
  4592. }
  4593. this->WriteXCodePBXProj(fout, root, generators);
  4594. bool hasGeneratedSchemes = this->OutputXCodeSharedSchemes(xcodeDir, root);
  4595. this->OutputXCodeWorkspaceSettings(xcodeDir, hasGeneratedSchemes);
  4596. this->ClearXCodeObjects();
  4597. // Since this call may have created new cache entries, save the cache:
  4598. //
  4599. root->GetMakefile()->GetCMakeInstance()->SaveCache(
  4600. root->GetBinaryDirectory());
  4601. }
  4602. bool cmGlobalXCodeGenerator::OutputXCodeSharedSchemes(
  4603. std::string const& xcProjDir, cmLocalGenerator* root)
  4604. {
  4605. // collect all tests for the targets
  4606. std::map<std::string, cmXCodeScheme::TestObjects> testables;
  4607. for (auto const& obj : this->XCodeObjects) {
  4608. if (obj->GetType() != cmXCodeObject::OBJECT ||
  4609. obj->GetIsA() != cmXCodeObject::PBXNativeTarget) {
  4610. continue;
  4611. }
  4612. if (!obj->GetTarget()->IsXCTestOnApple()) {
  4613. continue;
  4614. }
  4615. cmValue testee = obj->GetTarget()->GetProperty("XCTEST_TESTEE");
  4616. if (!testee) {
  4617. continue;
  4618. }
  4619. testables[*testee].push_back(obj.get());
  4620. }
  4621. // generate scheme
  4622. bool ret = false;
  4623. // Since the lowest available Xcode version for testing was 6.4,
  4624. // I'm setting this as a limit then
  4625. if (this->XcodeVersion >= 64) {
  4626. for (auto const& obj : this->XCodeObjects) {
  4627. if (obj->GetType() == cmXCodeObject::OBJECT &&
  4628. (obj->GetIsA() == cmXCodeObject::PBXNativeTarget ||
  4629. obj->GetIsA() == cmXCodeObject::PBXAggregateTarget) &&
  4630. (root->GetMakefile()->GetCMakeInstance()->GetIsInTryCompile() ||
  4631. obj->GetTarget()->GetPropertyAsBool("XCODE_GENERATE_SCHEME"))) {
  4632. std::string const& targetName = obj->GetTarget()->GetName();
  4633. cmXCodeScheme schm(root, obj.get(), testables[targetName],
  4634. this->CurrentConfigurationTypes,
  4635. this->XcodeVersion);
  4636. schm.WriteXCodeSharedScheme(xcProjDir,
  4637. this->RelativeToSource(xcProjDir));
  4638. ret = true;
  4639. }
  4640. }
  4641. }
  4642. return ret;
  4643. }
  4644. void cmGlobalXCodeGenerator::OutputXCodeWorkspaceSettings(
  4645. std::string const& xcProjDir, bool hasGeneratedSchemes)
  4646. {
  4647. std::string xcodeSharedDataDir =
  4648. cmStrCat(xcProjDir, "/project.xcworkspace/xcshareddata");
  4649. cmSystemTools::MakeDirectory(xcodeSharedDataDir);
  4650. std::string workspaceSettingsFile =
  4651. cmStrCat(xcodeSharedDataDir, "/WorkspaceSettings.xcsettings");
  4652. cmGeneratedFileStream fout(workspaceSettingsFile);
  4653. fout.SetCopyIfDifferent(true);
  4654. if (!fout) {
  4655. return;
  4656. }
  4657. cmXMLWriter xout(fout);
  4658. xout.StartDocument();
  4659. xout.Doctype("plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\""
  4660. "\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"");
  4661. xout.StartElement("plist");
  4662. xout.Attribute("version", "1.0");
  4663. xout.StartElement("dict");
  4664. if (this->XcodeVersion >= 100) {
  4665. xout.Element("key", "BuildSystemType");
  4666. switch (this->XcodeBuildSystem) {
  4667. case BuildSystem::One:
  4668. xout.Element("string", "Original");
  4669. if (this->XcodeVersion >= 130) {
  4670. xout.Element("key", "DisableBuildSystemDeprecationDiagnostic");
  4671. } else {
  4672. xout.Element("key", "DisableBuildSystemDeprecationWarning");
  4673. }
  4674. xout.Element("true");
  4675. break;
  4676. case BuildSystem::Twelve:
  4677. xout.Element("string", "Latest");
  4678. break;
  4679. }
  4680. }
  4681. if (hasGeneratedSchemes) {
  4682. xout.Element("key",
  4683. "IDEWorkspaceSharedSettings_AutocreateContextsIfNeeded");
  4684. xout.Element("false");
  4685. }
  4686. xout.EndElement(); // dict
  4687. xout.EndElement(); // plist
  4688. xout.EndDocument();
  4689. }
  4690. void cmGlobalXCodeGenerator::WriteXCodePBXProj(std::ostream& fout,
  4691. cmLocalGenerator*,
  4692. std::vector<cmLocalGenerator*>&)
  4693. {
  4694. SortXCodeObjects();
  4695. fout << "// !$*UTF8*$!\n"
  4696. "{\n";
  4697. cmXCodeObject::Indent(1, fout);
  4698. fout << "archiveVersion = 1;\n";
  4699. cmXCodeObject::Indent(1, fout);
  4700. fout << "classes = {\n";
  4701. cmXCodeObject::Indent(1, fout);
  4702. fout << "};\n";
  4703. cmXCodeObject::Indent(1, fout);
  4704. fout << "objectVersion = 46;\n";
  4705. cmXCode21Object::PrintList(this->XCodeObjects, fout);
  4706. cmXCodeObject::Indent(1, fout);
  4707. fout << "rootObject = " << this->RootObject->GetId()
  4708. << " /* Project object */;\n"
  4709. "}\n";
  4710. }
  4711. char const* cmGlobalXCodeGenerator::GetCMakeCFGIntDir() const
  4712. {
  4713. return "$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)";
  4714. }
  4715. std::string cmGlobalXCodeGenerator::ExpandCFGIntDir(
  4716. std::string const& str, std::string const& config) const
  4717. {
  4718. std::string replace1 = "$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)";
  4719. std::string replace2 = "$(CONFIGURATION)";
  4720. std::string tmp = str;
  4721. for (std::string::size_type i = tmp.find(replace1); i != std::string::npos;
  4722. i = tmp.find(replace1, i)) {
  4723. tmp.replace(i, replace1.size(), config);
  4724. i += config.size();
  4725. }
  4726. for (std::string::size_type i = tmp.find(replace2); i != std::string::npos;
  4727. i = tmp.find(replace2, i)) {
  4728. tmp.replace(i, replace2.size(), config);
  4729. i += config.size();
  4730. }
  4731. return tmp;
  4732. }
  4733. cmDocumentationEntry cmGlobalXCodeGenerator::GetDocumentation()
  4734. {
  4735. return { cmGlobalXCodeGenerator::GetActualName(),
  4736. "Generate Xcode project files." };
  4737. }
  4738. std::string cmGlobalXCodeGenerator::RelativeToSource(std::string const& p)
  4739. {
  4740. std::string const& rootSrc =
  4741. this->CurrentRootGenerator->GetCurrentSourceDirectory();
  4742. if (cmSystemTools::IsSubDirectory(p, rootSrc)) {
  4743. return cmSystemTools::ForceToRelativePath(rootSrc, p);
  4744. }
  4745. return p;
  4746. }
  4747. std::string cmGlobalXCodeGenerator::RelativeToRootBinary(std::string const& p)
  4748. {
  4749. std::string binaryDirectory =
  4750. this->CurrentRootGenerator->GetCurrentBinaryDirectory();
  4751. if (cmSystemTools::IsSubDirectory(p, binaryDirectory)) {
  4752. binaryDirectory = cmSystemTools::ForceToRelativePath(binaryDirectory, p);
  4753. }
  4754. return binaryDirectory;
  4755. }
  4756. std::string cmGlobalXCodeGenerator::RelativeToBinary(std::string const& p)
  4757. {
  4758. return this->CurrentRootGenerator->MaybeRelativeToCurBinDir(p);
  4759. }
  4760. std::string cmGlobalXCodeGenerator::XCodeEscapePath(std::string const& p)
  4761. {
  4762. if (p.find_first_of(" []") != std::string::npos) {
  4763. std::string t = cmStrCat('"', p, '"');
  4764. return t;
  4765. }
  4766. return p;
  4767. }
  4768. void cmGlobalXCodeGenerator::AppendDirectoryForConfig(
  4769. std::string const& prefix, std::string const& config,
  4770. std::string const& suffix, std::string& dir)
  4771. {
  4772. if (!config.empty()) {
  4773. dir += prefix;
  4774. dir += config;
  4775. dir += suffix;
  4776. }
  4777. }
  4778. std::string cmGlobalXCodeGenerator::LookupFlags(
  4779. std::string const& varNamePrefix, std::string const& varNameLang,
  4780. std::string const& varNameSuffix, cmGeneratorTarget const* gt,
  4781. std::string const& default_flags)
  4782. {
  4783. if (!varNameLang.empty()) {
  4784. std::string varName = cmStrCat(varNamePrefix, varNameLang, varNameSuffix);
  4785. if (cmValue varValue = this->CurrentMakefile->GetDefinition(varName)) {
  4786. if (!varValue->empty()) {
  4787. std::string flags;
  4788. this->CurrentLocalGenerator->AppendFlags(
  4789. flags, *varValue, varName, gt, cmBuildStep::Link, varNameLang);
  4790. return flags;
  4791. }
  4792. }
  4793. }
  4794. return default_flags;
  4795. }
  4796. void cmGlobalXCodeGenerator::AppendDefines(BuildObjectListOrString& defs,
  4797. char const* defines_list,
  4798. bool dflag)
  4799. {
  4800. // Skip this if there are no definitions.
  4801. if (!defines_list) {
  4802. return;
  4803. }
  4804. // Expand the list of definitions.
  4805. cmList defines{ defines_list };
  4806. // Store the definitions in the string.
  4807. this->AppendDefines(defs, defines, dflag);
  4808. }
  4809. void cmGlobalXCodeGenerator::AppendDefines(
  4810. BuildObjectListOrString& defs, std::vector<std::string> const& defines,
  4811. bool dflag)
  4812. {
  4813. // GCC_PREPROCESSOR_DEFINITIONS is a space-separated list of definitions.
  4814. std::string def;
  4815. for (auto const& define : defines) {
  4816. // Start with -D if requested.
  4817. if (dflag && !cmHasLiteralPrefix(define, "-D")) {
  4818. def = cmStrCat("-D", define);
  4819. } else if (!dflag && cmHasLiteralPrefix(define, "-D")) {
  4820. def = define.substr(2);
  4821. } else {
  4822. def = define;
  4823. }
  4824. // Append the flag with needed escapes.
  4825. std::string tmp;
  4826. this->AppendFlag(tmp, def);
  4827. defs.Add(tmp);
  4828. }
  4829. }
  4830. void cmGlobalXCodeGenerator::AppendFlag(std::string& flags,
  4831. std::string const& flag) const
  4832. {
  4833. // Short-circuit for an empty flag.
  4834. if (flag.empty()) {
  4835. return;
  4836. }
  4837. // Separate from previous flags.
  4838. if (!flags.empty()) {
  4839. flags += ' ';
  4840. }
  4841. // Check if the flag needs quoting.
  4842. bool quoteFlag =
  4843. flag.find_first_of("`~!@#$%^&*()+={}[]|:;\"'<>,.? ") != std::string::npos;
  4844. // We escape a flag as follows:
  4845. // - Place each flag in single quotes ''
  4846. // - Escape a single quote as \'
  4847. // - Escape a backslash as \\ since it itself is an escape
  4848. // Note that in the code below we need one more level of escapes for
  4849. // C string syntax in this source file.
  4850. //
  4851. // The final level of escaping is done when the string is stored
  4852. // into the project file by cmXCodeObject::PrintString.
  4853. if (quoteFlag) {
  4854. // Open single quote.
  4855. flags += '\'';
  4856. }
  4857. // Flag value with escaped quotes and backslashes.
  4858. for (auto c : flag) {
  4859. if (c == '\'') {
  4860. flags += "'\\''";
  4861. } else if (c == '\\') {
  4862. flags += "\\\\";
  4863. } else {
  4864. flags += c;
  4865. }
  4866. }
  4867. if (quoteFlag) {
  4868. // Close single quote.
  4869. flags += '\'';
  4870. }
  4871. }
  4872. std::string cmGlobalXCodeGenerator::ComputeInfoPListLocation(
  4873. cmGeneratorTarget* target)
  4874. {
  4875. std::string plist =
  4876. cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(),
  4877. "/CMakeFiles/", target->GetName(), ".dir/Info.plist");
  4878. return plist;
  4879. }
  4880. // Return true if the generated build tree may contain multiple builds.
  4881. // i.e. "Can I build Debug and Release in the same tree?"
  4882. bool cmGlobalXCodeGenerator::IsMultiConfig() const
  4883. {
  4884. // Newer Xcode versions are multi config:
  4885. return true;
  4886. }
  4887. bool cmGlobalXCodeGenerator::HasKnownObjectFileLocation(
  4888. cmTarget const& target, std::string* reason) const
  4889. {
  4890. auto objectDirArch = GetTargetObjectDirArch(target, this->ObjectDirArch);
  4891. if (objectDirArch.find('$') != std::string::npos) {
  4892. if (reason != nullptr) {
  4893. *reason = " under Xcode with multiple architectures";
  4894. }
  4895. return false;
  4896. }
  4897. return true;
  4898. }
  4899. bool cmGlobalXCodeGenerator::UseEffectivePlatformName(cmMakefile* mf) const
  4900. {
  4901. cmValue epnValue = this->GetCMakeInstance()->GetState()->GetGlobalProperty(
  4902. "XCODE_EMIT_EFFECTIVE_PLATFORM_NAME");
  4903. if (!epnValue) {
  4904. return mf->PlatformIsAppleEmbedded();
  4905. }
  4906. return epnValue.IsOn();
  4907. }
  4908. bool cmGlobalXCodeGenerator::ShouldStripResourcePath(cmMakefile*) const
  4909. {
  4910. // Xcode determines Resource location itself
  4911. return true;
  4912. }
  4913. void cmGlobalXCodeGenerator::ComputeTargetObjectDirectory(
  4914. cmGeneratorTarget* gt) const
  4915. {
  4916. auto objectDirArch = GetTargetObjectDirArch(*gt, this->ObjectDirArch);
  4917. gt->ObjectDirectory =
  4918. cmStrCat(this->GetTargetTempDir(gt, this->GetCMakeCFGIntDir()),
  4919. "/$(OBJECT_FILE_DIR_normal:base)/", objectDirArch, '/');
  4920. }
  4921. std::string cmGlobalXCodeGenerator::GetDeploymentPlatform(cmMakefile const* mf)
  4922. {
  4923. switch (mf->GetAppleSDKType()) {
  4924. case cmMakefile::AppleSDK::AppleTVOS:
  4925. case cmMakefile::AppleSDK::AppleTVSimulator:
  4926. return "TVOS_DEPLOYMENT_TARGET";
  4927. case cmMakefile::AppleSDK::IPhoneOS:
  4928. case cmMakefile::AppleSDK::IPhoneSimulator:
  4929. return "IPHONEOS_DEPLOYMENT_TARGET";
  4930. case cmMakefile::AppleSDK::WatchOS:
  4931. case cmMakefile::AppleSDK::WatchSimulator:
  4932. return "WATCHOS_DEPLOYMENT_TARGET";
  4933. case cmMakefile::AppleSDK::XROS:
  4934. case cmMakefile::AppleSDK::XRSimulator:
  4935. return "XROS_DEPLOYMENT_TARGET";
  4936. case cmMakefile::AppleSDK::MacOS:
  4937. default:
  4938. return "MACOSX_DEPLOYMENT_TARGET";
  4939. }
  4940. }
  4941. cmValue cmGlobalXCodeGenerator::GetDebuggerWorkingDirectory(
  4942. cmGeneratorTarget* gt) const
  4943. {
  4944. if (cmValue ret = gt->GetProperty("XCODE_SCHEME_WORKING_DIRECTORY")) {
  4945. return ret;
  4946. }
  4947. return cmGlobalGenerator::GetDebuggerWorkingDirectory(gt);
  4948. }