cmGlobalXCodeGenerator.cxx 194 KB

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