cmGlobalXCodeGenerator.cxx 130 KB

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