cmGlobalXCodeGenerator.cxx 179 KB

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