cmGlobalXCodeGenerator.cxx 151 KB

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