cmGlobalXCodeGenerator.cxx 132 KB

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