cmGlobalXCodeGenerator.cxx 164 KB

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