cmGlobalXCodeGenerator.cxx 130 KB

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