cmGlobalXCodeGenerator.cxx 163 KB

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