cmGlobalXCodeGenerator.cxx 175 KB

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