cmGlobalXCodeGenerator.cxx 130 KB

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