cmGlobalXCodeGenerator.cxx 176 KB

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