cmGlobalXCodeGenerator.cxx 130 KB

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