cmGlobalXCodeGenerator.cxx 130 KB

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