cmGlobalXCodeGenerator.cxx 192 KB

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