cmGlobalXCodeGenerator.cxx 194 KB

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