cmGlobalXCodeGenerator.cxx 174 KB

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