cmGlobalXCodeGenerator.cxx 130 KB

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