cmGlobalXCodeGenerator.cxx 195 KB

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