cmGlobalXCodeGenerator.cxx 176 KB

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