cmGlobalXCodeGenerator.cxx 162 KB

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