cmGlobalXCodeGenerator.cxx 131 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmGlobalXCodeGenerator.h"
  4. #include "cmsys/RegularExpression.hxx"
  5. #include <assert.h>
  6. #include <iomanip>
  7. #include <memory> // IWYU pragma: keep
  8. #include <sstream>
  9. #include <stdio.h>
  10. #include <string.h>
  11. #include "cmAlgorithms.h"
  12. #include "cmComputeLinkInformation.h"
  13. #include "cmCustomCommandGenerator.h"
  14. #include "cmDocumentationEntry.h"
  15. #include "cmGeneratedFileStream.h"
  16. #include "cmGeneratorExpression.h"
  17. #include "cmGeneratorTarget.h"
  18. #include "cmGlobalGeneratorFactory.h"
  19. #include "cmLocalGenerator.h"
  20. #include "cmLocalXCodeGenerator.h"
  21. #include "cmMakefile.h"
  22. #include "cmMessageType.h"
  23. #include "cmOutputConverter.h"
  24. #include "cmSourceFile.h"
  25. #include "cmSourceGroup.h"
  26. #include "cmState.h"
  27. #include "cmStateTypes.h"
  28. #include "cmSystemTools.h"
  29. #include "cmTarget.h"
  30. #include "cmXCode21Object.h"
  31. #include "cmXCodeObject.h"
  32. #include "cmXCodeScheme.h"
  33. #include "cmake.h"
  34. struct cmLinkImplementation;
  35. #if defined(CMAKE_BUILD_WITH_CMAKE) && defined(__APPLE__)
  36. # define HAVE_APPLICATION_SERVICES
  37. # include <ApplicationServices/ApplicationServices.h>
  38. #endif
  39. #if defined(CMAKE_BUILD_WITH_CMAKE)
  40. # include "cmXMLParser.h"
  41. // parse the xml file storing the installed version of Xcode on
  42. // the machine
  43. class cmXcodeVersionParser : public cmXMLParser
  44. {
  45. public:
  46. cmXcodeVersionParser()
  47. : Version("1.5")
  48. {
  49. }
  50. void StartElement(const std::string&, const char**) override
  51. {
  52. this->Data = "";
  53. }
  54. void EndElement(const std::string& name) override
  55. {
  56. if (name == "key") {
  57. this->Key = this->Data;
  58. } else if (name == "string") {
  59. if (this->Key == "CFBundleShortVersionString") {
  60. this->Version = this->Data;
  61. }
  62. }
  63. }
  64. void CharacterDataHandler(const char* data, int length) override
  65. {
  66. this->Data.append(data, length);
  67. }
  68. std::string Version;
  69. std::string Key;
  70. std::string Data;
  71. };
  72. #endif
  73. // Builds either an object list or a space-separated string from the
  74. // given inputs.
  75. class cmGlobalXCodeGenerator::BuildObjectListOrString
  76. {
  77. cmGlobalXCodeGenerator* Generator;
  78. cmXCodeObject* Group;
  79. bool Empty;
  80. std::string String;
  81. public:
  82. BuildObjectListOrString(cmGlobalXCodeGenerator* gen, bool buildObjectList)
  83. : Generator(gen)
  84. , Group(nullptr)
  85. , Empty(true)
  86. {
  87. if (buildObjectList) {
  88. this->Group = this->Generator->CreateObject(cmXCodeObject::OBJECT_LIST);
  89. }
  90. }
  91. bool IsEmpty() const { return this->Empty; }
  92. void Add(const std::string& newString)
  93. {
  94. this->Empty = false;
  95. if (this->Group) {
  96. this->Group->AddObject(this->Generator->CreateString(newString));
  97. } else {
  98. this->String += newString;
  99. this->String += ' ';
  100. }
  101. }
  102. const std::string& GetString() const { return this->String; }
  103. cmXCodeObject* CreateList()
  104. {
  105. if (this->Group) {
  106. return this->Group;
  107. }
  108. return this->Generator->CreateString(this->String);
  109. }
  110. };
  111. class cmGlobalXCodeGenerator::Factory : public cmGlobalGeneratorFactory
  112. {
  113. public:
  114. cmGlobalGenerator* CreateGlobalGenerator(const std::string& name,
  115. cmake* cm) const override;
  116. void GetDocumentation(cmDocumentationEntry& entry) const override
  117. {
  118. cmGlobalXCodeGenerator::GetDocumentation(entry);
  119. }
  120. void GetGenerators(std::vector<std::string>& names) const override
  121. {
  122. names.push_back(cmGlobalXCodeGenerator::GetActualName());
  123. }
  124. bool SupportsToolset() const override { return true; }
  125. bool SupportsPlatform() const override { return false; }
  126. };
  127. cmGlobalXCodeGenerator::cmGlobalXCodeGenerator(
  128. cmake* cm, std::string const& version_string, unsigned int version_number)
  129. : cmGlobalGenerator(cm)
  130. {
  131. this->VersionString = version_string;
  132. this->XcodeVersion = version_number;
  133. this->RootObject = nullptr;
  134. this->MainGroupChildren = nullptr;
  135. this->CurrentMakefile = nullptr;
  136. this->CurrentLocalGenerator = nullptr;
  137. this->XcodeBuildCommandInitialized = false;
  138. this->ObjectDirArchDefault = "$(CURRENT_ARCH)";
  139. this->ObjectDirArch = this->ObjectDirArchDefault;
  140. cm->GetState()->SetIsGeneratorMultiConfig(true);
  141. }
  142. cmGlobalGeneratorFactory* cmGlobalXCodeGenerator::NewFactory()
  143. {
  144. return new Factory;
  145. }
  146. cmGlobalGenerator* cmGlobalXCodeGenerator::Factory::CreateGlobalGenerator(
  147. const std::string& name, cmake* cm) const
  148. {
  149. if (name != GetActualName()) {
  150. return nullptr;
  151. }
  152. #if defined(CMAKE_BUILD_WITH_CMAKE)
  153. cmXcodeVersionParser parser;
  154. std::string versionFile;
  155. {
  156. std::string out;
  157. std::string::size_type pos = 0;
  158. if (cmSystemTools::RunSingleCommand("xcode-select --print-path", &out,
  159. nullptr, nullptr, nullptr,
  160. cmSystemTools::OUTPUT_NONE) &&
  161. (pos = out.find(".app/"), pos != std::string::npos)) {
  162. versionFile = out.substr(0, pos + 5) + "Contents/version.plist";
  163. }
  164. }
  165. if (!versionFile.empty() && cmSystemTools::FileExists(versionFile.c_str())) {
  166. parser.ParseFile(versionFile.c_str());
  167. } else if (cmSystemTools::FileExists(
  168. "/Applications/Xcode.app/Contents/version.plist")) {
  169. parser.ParseFile("/Applications/Xcode.app/Contents/version.plist");
  170. } else {
  171. parser.ParseFile(
  172. "/Developer/Applications/Xcode.app/Contents/version.plist");
  173. }
  174. std::string const& version_string = parser.Version;
  175. // Compute an integer form of the version number.
  176. unsigned int v[2] = { 0, 0 };
  177. sscanf(version_string.c_str(), "%u.%u", &v[0], &v[1]);
  178. unsigned int version_number = 10 * v[0] + v[1];
  179. if (version_number < 30) {
  180. cm->IssueMessage(MessageType::FATAL_ERROR,
  181. "Xcode " + version_string + " not supported.");
  182. return nullptr;
  183. }
  184. auto gg = cm::make_unique<cmGlobalXCodeGenerator>(cm, version_string,
  185. version_number);
  186. return gg.release();
  187. #else
  188. std::cerr << "CMake should be built with cmake to use Xcode, "
  189. "default to Xcode 1.5\n";
  190. return new cmGlobalXCodeGenerator(cm);
  191. #endif
  192. }
  193. bool cmGlobalXCodeGenerator::FindMakeProgram(cmMakefile* mf)
  194. {
  195. // The Xcode generator knows how to lookup its build tool
  196. // directly instead of needing a helper module to do it, so we
  197. // do not actually need to put CMAKE_MAKE_PROGRAM into the cache.
  198. if (cmSystemTools::IsOff(mf->GetDefinition("CMAKE_MAKE_PROGRAM"))) {
  199. mf->AddDefinition("CMAKE_MAKE_PROGRAM",
  200. this->GetXcodeBuildCommand().c_str());
  201. }
  202. return true;
  203. }
  204. std::string const& cmGlobalXCodeGenerator::GetXcodeBuildCommand()
  205. {
  206. if (!this->XcodeBuildCommandInitialized) {
  207. this->XcodeBuildCommandInitialized = true;
  208. this->XcodeBuildCommand = this->FindXcodeBuildCommand();
  209. }
  210. return this->XcodeBuildCommand;
  211. }
  212. std::string cmGlobalXCodeGenerator::FindXcodeBuildCommand()
  213. {
  214. if (this->XcodeVersion >= 40) {
  215. std::string makeProgram = cmSystemTools::FindProgram("xcodebuild");
  216. if (makeProgram.empty()) {
  217. makeProgram = "xcodebuild";
  218. }
  219. return makeProgram;
  220. }
  221. // Use cmakexbuild wrapper to suppress environment dump from output.
  222. return cmSystemTools::GetCMakeCommand() + "xbuild";
  223. }
  224. bool cmGlobalXCodeGenerator::SetGeneratorToolset(std::string const& ts,
  225. cmMakefile* mf)
  226. {
  227. if (ts.find_first_of(",=") != std::string::npos) {
  228. std::ostringstream e;
  229. /* clang-format off */
  230. e <<
  231. "Generator\n"
  232. " " << this->GetName() << "\n"
  233. "does not recognize the toolset\n"
  234. " " << ts << "\n"
  235. "that was specified.";
  236. /* clang-format on */
  237. mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
  238. return false;
  239. }
  240. this->GeneratorToolset = ts;
  241. if (!this->GeneratorToolset.empty()) {
  242. mf->AddDefinition("CMAKE_XCODE_PLATFORM_TOOLSET",
  243. this->GeneratorToolset.c_str());
  244. }
  245. return true;
  246. }
  247. void cmGlobalXCodeGenerator::EnableLanguage(
  248. std::vector<std::string> const& lang, cmMakefile* mf, bool optional)
  249. {
  250. mf->AddDefinition("XCODE", "1");
  251. mf->AddDefinition("XCODE_VERSION", this->VersionString.c_str());
  252. if (!mf->GetDefinition("CMAKE_CONFIGURATION_TYPES")) {
  253. mf->AddCacheDefinition(
  254. "CMAKE_CONFIGURATION_TYPES", "Debug;Release;MinSizeRel;RelWithDebInfo",
  255. "Semicolon separated list of supported configuration types, "
  256. "only supports Debug, Release, MinSizeRel, and RelWithDebInfo, "
  257. "anything else will be ignored.",
  258. cmStateEnums::STRING);
  259. }
  260. mf->AddDefinition("CMAKE_GENERATOR_NO_COMPILER_ENV", "1");
  261. this->cmGlobalGenerator::EnableLanguage(lang, mf, optional);
  262. this->ComputeArchitectures(mf);
  263. }
  264. bool cmGlobalXCodeGenerator::Open(const std::string& bindir,
  265. const std::string& projectName, bool dryRun)
  266. {
  267. bool ret = false;
  268. #ifdef HAVE_APPLICATION_SERVICES
  269. std::string url = bindir + "/" + projectName + ".xcodeproj";
  270. if (dryRun) {
  271. return cmSystemTools::FileExists(url, false);
  272. }
  273. CFStringRef cfStr = CFStringCreateWithCString(
  274. kCFAllocatorDefault, url.c_str(), kCFStringEncodingUTF8);
  275. if (cfStr) {
  276. CFURLRef cfUrl = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, cfStr,
  277. kCFURLPOSIXPathStyle, true);
  278. if (cfUrl) {
  279. OSStatus err = LSOpenCFURLRef(cfUrl, nullptr);
  280. ret = err == noErr;
  281. CFRelease(cfUrl);
  282. }
  283. CFRelease(cfStr);
  284. }
  285. #endif
  286. return ret;
  287. }
  288. void cmGlobalXCodeGenerator::GenerateBuildCommand(
  289. std::vector<std::string>& makeCommand, const std::string& makeProgram,
  290. const std::string& projectName, const std::string& /*projectDir*/,
  291. const std::string& targetName, const std::string& config, bool /*fast*/,
  292. int jobs, bool /*verbose*/, std::vector<std::string> const& makeOptions)
  293. {
  294. // now build the test
  295. makeCommand.emplace_back(
  296. this->SelectMakeProgram(makeProgram, this->GetXcodeBuildCommand()));
  297. makeCommand.emplace_back("-project");
  298. std::string projectArg = projectName;
  299. projectArg += ".xcode";
  300. projectArg += "proj";
  301. makeCommand.emplace_back(projectArg);
  302. bool clean = false;
  303. std::string realTarget = targetName;
  304. if (realTarget == "clean") {
  305. clean = true;
  306. realTarget = "ALL_BUILD";
  307. }
  308. if (clean) {
  309. makeCommand.emplace_back("clean");
  310. } else {
  311. makeCommand.emplace_back("build");
  312. }
  313. makeCommand.emplace_back("-target");
  314. if (!realTarget.empty()) {
  315. makeCommand.emplace_back(realTarget);
  316. } else {
  317. makeCommand.emplace_back("ALL_BUILD");
  318. }
  319. makeCommand.emplace_back("-configuration");
  320. makeCommand.emplace_back(!config.empty() ? config : "Debug");
  321. if (jobs != cmake::NO_BUILD_PARALLEL_LEVEL) {
  322. makeCommand.emplace_back("-jobs");
  323. if (jobs != cmake::DEFAULT_BUILD_PARALLEL_LEVEL) {
  324. makeCommand.emplace_back(std::to_string(jobs));
  325. }
  326. }
  327. makeCommand.insert(makeCommand.end(), makeOptions.begin(),
  328. makeOptions.end());
  329. }
  330. ///! Create a local generator appropriate to this Global Generator
  331. cmLocalGenerator* cmGlobalXCodeGenerator::CreateLocalGenerator(cmMakefile* mf)
  332. {
  333. return new cmLocalXCodeGenerator(this, mf);
  334. }
  335. void cmGlobalXCodeGenerator::AddExtraIDETargets()
  336. {
  337. // make sure extra targets are added before calling
  338. // the parent generate which will call trace depends
  339. for (auto keyVal : this->ProjectMap) {
  340. cmLocalGenerator* root = keyVal.second[0];
  341. this->SetGenerationRoot(root);
  342. // add ALL_BUILD, INSTALL, etc
  343. this->AddExtraTargets(root, keyVal.second);
  344. }
  345. }
  346. void cmGlobalXCodeGenerator::ComputeTargetOrder()
  347. {
  348. size_t index = 0;
  349. auto const& lgens = this->GetLocalGenerators();
  350. for (cmLocalGenerator* lgen : lgens) {
  351. auto const& targets = lgen->GetGeneratorTargets();
  352. for (cmGeneratorTarget const* gt : targets) {
  353. this->ComputeTargetOrder(gt, index);
  354. }
  355. }
  356. assert(index == this->TargetOrderIndex.size());
  357. }
  358. void cmGlobalXCodeGenerator::ComputeTargetOrder(cmGeneratorTarget const* gt,
  359. size_t& index)
  360. {
  361. std::map<cmGeneratorTarget const*, size_t>::value_type value(gt, 0);
  362. auto insertion = this->TargetOrderIndex.insert(value);
  363. if (!insertion.second) {
  364. return;
  365. }
  366. auto entry = insertion.first;
  367. auto& deps = this->GetTargetDirectDepends(gt);
  368. for (auto& d : deps) {
  369. this->ComputeTargetOrder(d, index);
  370. }
  371. entry->second = index++;
  372. }
  373. void cmGlobalXCodeGenerator::Generate()
  374. {
  375. this->cmGlobalGenerator::Generate();
  376. if (cmSystemTools::GetErrorOccuredFlag()) {
  377. return;
  378. }
  379. this->ComputeTargetOrder();
  380. for (auto keyVal : this->ProjectMap) {
  381. cmLocalGenerator* root = keyVal.second[0];
  382. bool generateTopLevelProjectOnly =
  383. root->GetMakefile()->IsOn("CMAKE_XCODE_GENERATE_TOP_LEVEL_PROJECT_ONLY");
  384. if (generateTopLevelProjectOnly) {
  385. cmStateSnapshot snp = root->GetStateSnapshot();
  386. if (snp.GetBuildsystemDirectoryParent().IsValid()) {
  387. continue;
  388. }
  389. }
  390. this->SetGenerationRoot(root);
  391. // now create the project
  392. this->OutputXCodeProject(root, keyVal.second);
  393. }
  394. }
  395. void cmGlobalXCodeGenerator::SetGenerationRoot(cmLocalGenerator* root)
  396. {
  397. this->CurrentProject = root->GetProjectName();
  398. this->SetCurrentLocalGenerator(root);
  399. cmSystemTools::SplitPath(
  400. this->CurrentLocalGenerator->GetCurrentSourceDirectory(),
  401. this->ProjectSourceDirectoryComponents);
  402. cmSystemTools::SplitPath(
  403. this->CurrentLocalGenerator->GetCurrentBinaryDirectory(),
  404. this->ProjectOutputDirectoryComponents);
  405. this->CurrentXCodeHackMakefile = root->GetCurrentBinaryDirectory();
  406. this->CurrentXCodeHackMakefile += "/CMakeScripts";
  407. cmSystemTools::MakeDirectory(this->CurrentXCodeHackMakefile.c_str());
  408. this->CurrentXCodeHackMakefile += "/XCODE_DEPEND_HELPER.make";
  409. }
  410. std::string cmGlobalXCodeGenerator::PostBuildMakeTarget(
  411. std::string const& tName, std::string const& configName)
  412. {
  413. std::string target = tName;
  414. std::replace(target.begin(), target.end(), ' ', '_');
  415. std::string out = "PostBuild." + target;
  416. out += "." + configName;
  417. return out;
  418. }
  419. #define CMAKE_CHECK_BUILD_SYSTEM_TARGET "ZERO_CHECK"
  420. void cmGlobalXCodeGenerator::AddExtraTargets(
  421. cmLocalGenerator* root, std::vector<cmLocalGenerator*>& gens)
  422. {
  423. cmMakefile* mf = root->GetMakefile();
  424. // Add ALL_BUILD
  425. const char* no_working_directory = nullptr;
  426. std::vector<std::string> no_depends;
  427. cmTarget* allbuild = mf->AddUtilityCommand(
  428. "ALL_BUILD", cmMakefile::TargetOrigin::Generator, true, no_depends,
  429. no_working_directory, "echo", "Build all projects");
  430. cmGeneratorTarget* allBuildGt = new cmGeneratorTarget(allbuild, root);
  431. root->AddGeneratorTarget(allBuildGt);
  432. // Add XCODE depend helper
  433. std::string dir = root->GetCurrentBinaryDirectory();
  434. cmCustomCommandLine makeHelper;
  435. makeHelper.push_back("make");
  436. makeHelper.push_back("-C");
  437. makeHelper.push_back(dir);
  438. makeHelper.push_back("-f");
  439. makeHelper.push_back(this->CurrentXCodeHackMakefile);
  440. makeHelper.push_back(""); // placeholder, see below
  441. // Add ZERO_CHECK
  442. bool regenerate = !this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION");
  443. bool generateTopLevelProjectOnly =
  444. mf->IsOn("CMAKE_XCODE_GENERATE_TOP_LEVEL_PROJECT_ONLY");
  445. bool isTopLevel =
  446. !root->GetStateSnapshot().GetBuildsystemDirectoryParent().IsValid();
  447. if (regenerate && (isTopLevel || !generateTopLevelProjectOnly)) {
  448. this->CreateReRunCMakeFile(root, gens);
  449. std::string file =
  450. this->ConvertToRelativeForMake(this->CurrentReRunCMakeMakefile);
  451. cmSystemTools::ReplaceString(file, "\\ ", " ");
  452. cmTarget* check = mf->AddUtilityCommand(
  453. CMAKE_CHECK_BUILD_SYSTEM_TARGET, cmMakefile::TargetOrigin::Generator,
  454. true, no_depends, no_working_directory, "make", "-f", file.c_str());
  455. cmGeneratorTarget* checkGt = new cmGeneratorTarget(check, root);
  456. root->AddGeneratorTarget(checkGt);
  457. }
  458. // now make the allbuild depend on all the non-utility targets
  459. // in the project
  460. for (auto& gen : gens) {
  461. if (this->IsExcluded(root, gen)) {
  462. continue;
  463. }
  464. for (auto target : gen->GetGeneratorTargets()) {
  465. if (target->GetType() == cmStateEnums::GLOBAL_TARGET) {
  466. continue;
  467. }
  468. std::string targetName = target->GetName();
  469. if (regenerate && (targetName != CMAKE_CHECK_BUILD_SYSTEM_TARGET)) {
  470. target->Target->AddUtility(CMAKE_CHECK_BUILD_SYSTEM_TARGET);
  471. }
  472. // make all exe, shared libs and modules
  473. // run the depend check makefile as a post build rule
  474. // this will make sure that when the next target is built
  475. // things are up-to-date
  476. if (target->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  477. (this->XcodeVersion < 50 &&
  478. (target->GetType() == cmStateEnums::EXECUTABLE ||
  479. target->GetType() == cmStateEnums::STATIC_LIBRARY ||
  480. target->GetType() == cmStateEnums::SHARED_LIBRARY ||
  481. target->GetType() == cmStateEnums::MODULE_LIBRARY))) {
  482. makeHelper.back() = // fill placeholder
  483. this->PostBuildMakeTarget(target->GetName(), "$(CONFIGURATION)");
  484. cmCustomCommandLines commandLines;
  485. commandLines.push_back(makeHelper);
  486. std::vector<std::string> no_byproducts;
  487. gen->GetMakefile()->AddCustomCommandToTarget(
  488. target->GetName(), no_byproducts, no_depends, commandLines,
  489. cmTarget::POST_BUILD, "Depend check for xcode", dir.c_str(), true,
  490. false, "", false, cmMakefile::AcceptObjectLibraryCommands);
  491. }
  492. if (target->GetType() != cmStateEnums::INTERFACE_LIBRARY &&
  493. !target->GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
  494. allbuild->AddUtility(target->GetName());
  495. }
  496. }
  497. }
  498. }
  499. void cmGlobalXCodeGenerator::CreateReRunCMakeFile(
  500. cmLocalGenerator* root, std::vector<cmLocalGenerator*> const& gens)
  501. {
  502. std::vector<std::string> lfiles;
  503. for (auto gen : gens) {
  504. std::vector<std::string> const& lf = gen->GetMakefile()->GetListFiles();
  505. lfiles.insert(lfiles.end(), lf.begin(), lf.end());
  506. }
  507. // sort the array
  508. std::sort(lfiles.begin(), lfiles.end(), std::less<std::string>());
  509. std::vector<std::string>::iterator new_end =
  510. std::unique(lfiles.begin(), lfiles.end());
  511. lfiles.erase(new_end, lfiles.end());
  512. cmake* cm = this->GetCMakeInstance();
  513. if (cm->DoWriteGlobVerifyTarget()) {
  514. lfiles.emplace_back(cm->GetGlobVerifyStamp());
  515. }
  516. this->CurrentReRunCMakeMakefile = root->GetCurrentBinaryDirectory();
  517. this->CurrentReRunCMakeMakefile += "/CMakeScripts";
  518. cmSystemTools::MakeDirectory(this->CurrentReRunCMakeMakefile.c_str());
  519. this->CurrentReRunCMakeMakefile += "/ReRunCMake.make";
  520. cmGeneratedFileStream makefileStream(this->CurrentReRunCMakeMakefile);
  521. makefileStream.SetCopyIfDifferent(true);
  522. makefileStream << "# Generated by CMake, DO NOT EDIT\n\n";
  523. makefileStream << "TARGETS:= \n";
  524. makefileStream << "empty:= \n";
  525. makefileStream << "space:= $(empty) $(empty)\n";
  526. makefileStream << "spaceplus:= $(empty)\\ $(empty)\n\n";
  527. for (const auto& lfile : lfiles) {
  528. makefileStream << "TARGETS += $(subst $(space),$(spaceplus),$(wildcard "
  529. << this->ConvertToRelativeForMake(lfile) << "))\n";
  530. }
  531. makefileStream << "\n";
  532. std::string checkCache = 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* headTarget,
  659. const std::string& lang)
  660. : cmGeneratorExpressionInterpreter(
  661. localGenerator, "NO-PER-CONFIG-SUPPORT-IN-XCODE", headTarget, lang)
  662. , SourceFile(sourceFile)
  663. {
  664. }
  665. using cmGeneratorExpressionInterpreter::Evaluate;
  666. const std::string& Evaluate(const char* expression,
  667. const std::string& property)
  668. {
  669. const std::string& processed =
  670. this->cmGeneratorExpressionInterpreter::Evaluate(expression, property);
  671. if (this->CompiledGeneratorExpression->GetHadContextSensitiveCondition()) {
  672. std::ostringstream e;
  673. /* clang-format off */
  674. e <<
  675. "Xcode does not support per-config per-source " << property << ":\n"
  676. " " << expression << "\n"
  677. "specified for source:\n"
  678. " " << this->SourceFile->GetFullPath() << "\n";
  679. /* clang-format on */
  680. this->LocalGenerator->IssueMessage(MessageType::FATAL_ERROR, e.str());
  681. }
  682. return processed;
  683. }
  684. private:
  685. cmSourceFile* SourceFile = nullptr;
  686. };
  687. cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeSourceFile(
  688. cmLocalGenerator* lg, cmSourceFile* sf, cmGeneratorTarget* gtgt)
  689. {
  690. std::string lang = this->CurrentLocalGenerator->GetSourceFileLanguage(*sf);
  691. XCodeGeneratorExpressionInterpreter genexInterpreter(sf, lg, gtgt, lang);
  692. // Add flags from target and source file properties.
  693. std::string flags;
  694. const char* srcfmt = sf->GetProperty("Fortran_FORMAT");
  695. switch (cmOutputConverter::GetFortranFormat(srcfmt)) {
  696. case cmOutputConverter::FortranFormatFixed:
  697. flags = "-fixed " + flags;
  698. break;
  699. case cmOutputConverter::FortranFormatFree:
  700. flags = "-free " + flags;
  701. break;
  702. default:
  703. break;
  704. }
  705. const std::string COMPILE_FLAGS("COMPILE_FLAGS");
  706. if (const char* cflags = sf->GetProperty(COMPILE_FLAGS)) {
  707. lg->AppendFlags(flags, genexInterpreter.Evaluate(cflags, COMPILE_FLAGS));
  708. }
  709. const std::string COMPILE_OPTIONS("COMPILE_OPTIONS");
  710. if (const char* coptions = sf->GetProperty(COMPILE_OPTIONS)) {
  711. lg->AppendCompileOptions(
  712. flags, genexInterpreter.Evaluate(coptions, COMPILE_OPTIONS));
  713. }
  714. // Add per-source definitions.
  715. BuildObjectListOrString flagsBuild(this, false);
  716. const std::string COMPILE_DEFINITIONS("COMPILE_DEFINITIONS");
  717. if (const char* compile_defs = sf->GetProperty(COMPILE_DEFINITIONS)) {
  718. this->AppendDefines(
  719. flagsBuild,
  720. genexInterpreter.Evaluate(compile_defs, COMPILE_DEFINITIONS).c_str(),
  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.emplace_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);
  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);
  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::AddPositionIndependentLinkAttribute(
  1572. cmGeneratorTarget* target, cmXCodeObject* buildSettings,
  1573. const std::string& configName)
  1574. {
  1575. // For now, only EXECUTABLE is concerned
  1576. if (target->GetType() != cmStateEnums::EXECUTABLE) {
  1577. return;
  1578. }
  1579. const char* PICValue = target->GetLinkPIEProperty(configName);
  1580. if (PICValue == nullptr) {
  1581. // POSITION_INDEPENDENT_CODE is not set
  1582. return;
  1583. }
  1584. buildSettings->AddAttribute(
  1585. "LD_NO_PIE",
  1586. this->CreateString(cmSystemTools::IsOn(PICValue) ? "NO" : "YES"));
  1587. }
  1588. void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
  1589. cmXCodeObject* buildSettings,
  1590. const std::string& configName)
  1591. {
  1592. if (gtgt->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  1593. return;
  1594. }
  1595. std::string defFlags;
  1596. bool shared = ((gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) ||
  1597. (gtgt->GetType() == cmStateEnums::MODULE_LIBRARY));
  1598. bool binary = ((gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY) ||
  1599. (gtgt->GetType() == cmStateEnums::STATIC_LIBRARY) ||
  1600. (gtgt->GetType() == cmStateEnums::EXECUTABLE) || shared);
  1601. // Compute the compilation flags for each language.
  1602. std::set<std::string> languages;
  1603. gtgt->GetLanguages(languages, configName);
  1604. std::map<std::string, std::string> cflags;
  1605. for (auto const& lang : languages) {
  1606. std::string& flags = cflags[lang];
  1607. // Add language-specific flags.
  1608. this->CurrentLocalGenerator->AddLanguageFlags(flags, gtgt, lang,
  1609. configName);
  1610. // Add shared-library flags if needed.
  1611. this->CurrentLocalGenerator->AddCMP0018Flags(flags, gtgt, lang,
  1612. configName);
  1613. this->CurrentLocalGenerator->AddVisibilityPresetFlags(flags, gtgt, lang);
  1614. this->CurrentLocalGenerator->AddCompileOptions(flags, gtgt, lang,
  1615. configName);
  1616. }
  1617. std::string llang = gtgt->GetLinkerLanguage(configName);
  1618. if (binary && llang.empty()) {
  1619. cmSystemTools::Error(
  1620. "CMake can not determine linker language for target: ",
  1621. gtgt->GetName().c_str());
  1622. return;
  1623. }
  1624. std::string const& langForPreprocessor = llang;
  1625. if (gtgt->IsIPOEnabled(llang, configName)) {
  1626. const char* ltoValue =
  1627. this->CurrentMakefile->IsOn("_CMAKE_LTO_THIN") ? "YES_THIN" : "YES";
  1628. buildSettings->AddAttribute("LLVM_LTO", this->CreateString(ltoValue));
  1629. }
  1630. // Handle PIE linker configuration
  1631. this->AddPositionIndependentLinkAttribute(gtgt, buildSettings, configName);
  1632. // Add define flags
  1633. this->CurrentLocalGenerator->AppendFlags(
  1634. defFlags, this->CurrentMakefile->GetDefineFlags());
  1635. // Add preprocessor definitions for this target and configuration.
  1636. BuildObjectListOrString ppDefs(this, true);
  1637. this->AppendDefines(
  1638. ppDefs, "CMAKE_INTDIR=\"$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)\"");
  1639. if (const std::string* exportMacro = gtgt->GetExportMacro()) {
  1640. // Add the export symbol definition for shared library objects.
  1641. this->AppendDefines(ppDefs, exportMacro->c_str());
  1642. }
  1643. std::vector<std::string> targetDefines;
  1644. if (!langForPreprocessor.empty()) {
  1645. gtgt->GetCompileDefinitions(targetDefines, configName,
  1646. langForPreprocessor);
  1647. }
  1648. this->AppendDefines(ppDefs, targetDefines);
  1649. buildSettings->AddAttribute("GCC_PREPROCESSOR_DEFINITIONS",
  1650. ppDefs.CreateList());
  1651. std::string extraLinkOptionsVar;
  1652. std::string extraLinkOptions;
  1653. if (gtgt->GetType() == cmStateEnums::EXECUTABLE) {
  1654. extraLinkOptionsVar = "CMAKE_EXE_LINKER_FLAGS";
  1655. } else if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) {
  1656. extraLinkOptionsVar = "CMAKE_SHARED_LINKER_FLAGS";
  1657. } else if (gtgt->GetType() == cmStateEnums::MODULE_LIBRARY) {
  1658. extraLinkOptionsVar = "CMAKE_MODULE_LINKER_FLAGS";
  1659. }
  1660. if (!extraLinkOptionsVar.empty()) {
  1661. this->CurrentLocalGenerator->AddConfigVariableFlags(
  1662. extraLinkOptions, extraLinkOptionsVar, configName);
  1663. }
  1664. if (gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  1665. gtgt->GetType() == cmStateEnums::STATIC_LIBRARY) {
  1666. this->CurrentLocalGenerator->GetStaticLibraryFlags(
  1667. extraLinkOptions, cmSystemTools::UpperCase(configName), llang, gtgt);
  1668. } else {
  1669. const char* targetLinkFlags = gtgt->GetProperty("LINK_FLAGS");
  1670. if (targetLinkFlags) {
  1671. this->CurrentLocalGenerator->AppendFlags(extraLinkOptions,
  1672. targetLinkFlags);
  1673. }
  1674. if (!configName.empty()) {
  1675. std::string linkFlagsVar = "LINK_FLAGS_";
  1676. linkFlagsVar += cmSystemTools::UpperCase(configName);
  1677. if (const char* linkFlags = gtgt->GetProperty(linkFlagsVar)) {
  1678. this->CurrentLocalGenerator->AppendFlags(extraLinkOptions, linkFlags);
  1679. }
  1680. }
  1681. std::vector<std::string> opts;
  1682. gtgt->GetLinkOptions(opts, configName, llang);
  1683. // LINK_OPTIONS are escaped.
  1684. this->CurrentLocalGenerator->AppendCompileOptions(extraLinkOptions, opts);
  1685. }
  1686. // Set target-specific architectures.
  1687. std::vector<std::string> archs;
  1688. gtgt->GetAppleArchs(configName, archs);
  1689. if (!archs.empty()) {
  1690. // Enable ARCHS attribute.
  1691. buildSettings->AddAttribute("ONLY_ACTIVE_ARCH", this->CreateString("NO"));
  1692. // Store ARCHS value.
  1693. if (archs.size() == 1) {
  1694. buildSettings->AddAttribute("ARCHS", this->CreateString(archs[0]));
  1695. } else {
  1696. cmXCodeObject* archObjects =
  1697. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1698. for (auto& arch : archs) {
  1699. archObjects->AddObject(this->CreateString(arch));
  1700. }
  1701. buildSettings->AddAttribute("ARCHS", archObjects);
  1702. }
  1703. }
  1704. // Get the product name components.
  1705. std::string pnprefix;
  1706. std::string pnbase;
  1707. std::string pnsuffix;
  1708. gtgt->GetFullNameComponents(pnprefix, pnbase, pnsuffix, configName);
  1709. const char* version = gtgt->GetProperty("VERSION");
  1710. const char* soversion = gtgt->GetProperty("SOVERSION");
  1711. if (!gtgt->HasSOName(configName) || gtgt->IsFrameworkOnApple()) {
  1712. version = nullptr;
  1713. soversion = nullptr;
  1714. }
  1715. if (version && !soversion) {
  1716. soversion = version;
  1717. }
  1718. if (!version && soversion) {
  1719. version = soversion;
  1720. }
  1721. std::string realName = pnbase;
  1722. std::string soName = pnbase;
  1723. if (version && soversion) {
  1724. realName += ".";
  1725. realName += version;
  1726. soName += ".";
  1727. soName += soversion;
  1728. }
  1729. // Set attributes to specify the proper name for the target.
  1730. std::string pndir = this->CurrentLocalGenerator->GetCurrentBinaryDirectory();
  1731. if (gtgt->GetType() == cmStateEnums::STATIC_LIBRARY ||
  1732. gtgt->GetType() == cmStateEnums::SHARED_LIBRARY ||
  1733. gtgt->GetType() == cmStateEnums::MODULE_LIBRARY ||
  1734. gtgt->GetType() == cmStateEnums::EXECUTABLE) {
  1735. if (!gtgt->UsesDefaultOutputDir(configName,
  1736. cmStateEnums::RuntimeBinaryArtifact)) {
  1737. std::string pncdir = gtgt->GetDirectory(configName);
  1738. buildSettings->AddAttribute("CONFIGURATION_BUILD_DIR",
  1739. this->CreateString(pncdir));
  1740. }
  1741. if (gtgt->IsFrameworkOnApple() || gtgt->IsCFBundleOnApple()) {
  1742. pnprefix = "";
  1743. }
  1744. buildSettings->AddAttribute("EXECUTABLE_PREFIX",
  1745. this->CreateString(pnprefix));
  1746. buildSettings->AddAttribute("EXECUTABLE_SUFFIX",
  1747. this->CreateString(pnsuffix));
  1748. } else if (gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  1749. pnprefix = "lib";
  1750. pnbase = gtgt->GetName();
  1751. pnsuffix = ".a";
  1752. std::string pncdir =
  1753. this->GetObjectsNormalDirectory(this->CurrentProject, configName, gtgt);
  1754. buildSettings->AddAttribute("CONFIGURATION_BUILD_DIR",
  1755. this->CreateString(pncdir));
  1756. }
  1757. // Store the product name for all target types.
  1758. buildSettings->AddAttribute("PRODUCT_NAME", this->CreateString(realName));
  1759. buildSettings->AddAttribute("SYMROOT", this->CreateString(pndir));
  1760. // Handle settings for each target type.
  1761. switch (gtgt->GetType()) {
  1762. case cmStateEnums::STATIC_LIBRARY:
  1763. if (gtgt->GetPropertyAsBool("FRAMEWORK")) {
  1764. std::string fw_version = gtgt->GetFrameworkVersion();
  1765. buildSettings->AddAttribute("FRAMEWORK_VERSION",
  1766. this->CreateString(fw_version));
  1767. const char* ext = gtgt->GetProperty("BUNDLE_EXTENSION");
  1768. if (ext) {
  1769. buildSettings->AddAttribute("WRAPPER_EXTENSION",
  1770. this->CreateString(ext));
  1771. }
  1772. std::string plist = this->ComputeInfoPListLocation(gtgt);
  1773. // Xcode will create the final version of Info.plist at build time,
  1774. // so let it replace the framework name. This avoids creating
  1775. // a per-configuration Info.plist file.
  1776. this->CurrentLocalGenerator->GenerateFrameworkInfoPList(
  1777. gtgt, "$(EXECUTABLE_NAME)", plist.c_str());
  1778. buildSettings->AddAttribute("INFOPLIST_FILE",
  1779. this->CreateString(plist));
  1780. buildSettings->AddAttribute("MACH_O_TYPE",
  1781. this->CreateString("staticlib"));
  1782. } else {
  1783. buildSettings->AddAttribute("LIBRARY_STYLE",
  1784. this->CreateString("STATIC"));
  1785. }
  1786. break;
  1787. case cmStateEnums::OBJECT_LIBRARY: {
  1788. buildSettings->AddAttribute("LIBRARY_STYLE",
  1789. this->CreateString("STATIC"));
  1790. break;
  1791. }
  1792. case cmStateEnums::MODULE_LIBRARY: {
  1793. buildSettings->AddAttribute("LIBRARY_STYLE",
  1794. this->CreateString("BUNDLE"));
  1795. if (gtgt->IsCFBundleOnApple()) {
  1796. // It turns out that a BUNDLE is basically the same
  1797. // in many ways as an application bundle, as far as
  1798. // link flags go
  1799. std::string createFlags = this->LookupFlags(
  1800. "CMAKE_SHARED_MODULE_CREATE_", llang, "_FLAGS", "-bundle");
  1801. if (!createFlags.empty()) {
  1802. extraLinkOptions += " ";
  1803. extraLinkOptions += createFlags;
  1804. }
  1805. const char* ext = gtgt->GetProperty("BUNDLE_EXTENSION");
  1806. if (ext) {
  1807. buildSettings->AddAttribute("WRAPPER_EXTENSION",
  1808. this->CreateString(ext));
  1809. }
  1810. std::string plist = this->ComputeInfoPListLocation(gtgt);
  1811. // Xcode will create the final version of Info.plist at build time,
  1812. // so let it replace the cfbundle name. This avoids creating
  1813. // a per-configuration Info.plist file. The cfbundle plist
  1814. // is very similar to the application bundle plist
  1815. this->CurrentLocalGenerator->GenerateAppleInfoPList(
  1816. gtgt, "$(EXECUTABLE_NAME)", plist.c_str());
  1817. buildSettings->AddAttribute("INFOPLIST_FILE",
  1818. this->CreateString(plist));
  1819. } else {
  1820. buildSettings->AddAttribute("MACH_O_TYPE",
  1821. this->CreateString("mh_bundle"));
  1822. buildSettings->AddAttribute("GCC_DYNAMIC_NO_PIC",
  1823. this->CreateString("NO"));
  1824. // Add the flags to create an executable.
  1825. std::string createFlags =
  1826. this->LookupFlags("CMAKE_", llang, "_LINK_FLAGS", "");
  1827. if (!createFlags.empty()) {
  1828. extraLinkOptions += " ";
  1829. extraLinkOptions += createFlags;
  1830. }
  1831. }
  1832. break;
  1833. }
  1834. case cmStateEnums::SHARED_LIBRARY: {
  1835. if (gtgt->GetPropertyAsBool("FRAMEWORK")) {
  1836. std::string fw_version = gtgt->GetFrameworkVersion();
  1837. buildSettings->AddAttribute("FRAMEWORK_VERSION",
  1838. this->CreateString(fw_version));
  1839. const char* ext = gtgt->GetProperty("BUNDLE_EXTENSION");
  1840. if (ext) {
  1841. buildSettings->AddAttribute("WRAPPER_EXTENSION",
  1842. this->CreateString(ext));
  1843. }
  1844. std::string plist = this->ComputeInfoPListLocation(gtgt);
  1845. // Xcode will create the final version of Info.plist at build time,
  1846. // so let it replace the framework name. This avoids creating
  1847. // a per-configuration Info.plist file.
  1848. this->CurrentLocalGenerator->GenerateFrameworkInfoPList(
  1849. gtgt, "$(EXECUTABLE_NAME)", plist.c_str());
  1850. buildSettings->AddAttribute("INFOPLIST_FILE",
  1851. this->CreateString(plist));
  1852. } else {
  1853. // Add the flags to create a shared library.
  1854. std::string createFlags = this->LookupFlags(
  1855. "CMAKE_SHARED_LIBRARY_CREATE_", llang, "_FLAGS", "-dynamiclib");
  1856. if (!createFlags.empty()) {
  1857. extraLinkOptions += " ";
  1858. extraLinkOptions += createFlags;
  1859. }
  1860. }
  1861. buildSettings->AddAttribute("LIBRARY_STYLE",
  1862. this->CreateString("DYNAMIC"));
  1863. break;
  1864. }
  1865. case cmStateEnums::EXECUTABLE: {
  1866. // Add the flags to create an executable.
  1867. std::string createFlags =
  1868. this->LookupFlags("CMAKE_", llang, "_LINK_FLAGS", "");
  1869. if (!createFlags.empty()) {
  1870. extraLinkOptions += " ";
  1871. extraLinkOptions += createFlags;
  1872. }
  1873. // Handle bundles and normal executables separately.
  1874. if (gtgt->GetPropertyAsBool("MACOSX_BUNDLE")) {
  1875. const char* ext = gtgt->GetProperty("BUNDLE_EXTENSION");
  1876. if (ext) {
  1877. buildSettings->AddAttribute("WRAPPER_EXTENSION",
  1878. this->CreateString(ext));
  1879. }
  1880. std::string plist = this->ComputeInfoPListLocation(gtgt);
  1881. // Xcode will create the final version of Info.plist at build time,
  1882. // so let it replace the executable name. This avoids creating
  1883. // a per-configuration Info.plist file.
  1884. this->CurrentLocalGenerator->GenerateAppleInfoPList(
  1885. gtgt, "$(EXECUTABLE_NAME)", plist.c_str());
  1886. buildSettings->AddAttribute("INFOPLIST_FILE",
  1887. this->CreateString(plist));
  1888. }
  1889. } break;
  1890. default:
  1891. break;
  1892. }
  1893. if (this->XcodeVersion < 40) {
  1894. buildSettings->AddAttribute("PREBINDING", this->CreateString("NO"));
  1895. }
  1896. BuildObjectListOrString dirs(this, true);
  1897. BuildObjectListOrString fdirs(this, true);
  1898. BuildObjectListOrString sysdirs(this, true);
  1899. BuildObjectListOrString sysfdirs(this, true);
  1900. const bool emitSystemIncludes = this->XcodeVersion >= 83;
  1901. std::vector<std::string> includes;
  1902. if (!langForPreprocessor.empty()) {
  1903. this->CurrentLocalGenerator->GetIncludeDirectories(
  1904. includes, gtgt, langForPreprocessor, configName);
  1905. }
  1906. std::set<std::string> emitted;
  1907. emitted.insert("/System/Library/Frameworks");
  1908. for (auto& include : includes) {
  1909. if (this->NameResolvesToFramework(include)) {
  1910. std::string frameworkDir = include;
  1911. frameworkDir += "/../";
  1912. frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
  1913. if (emitted.insert(frameworkDir).second) {
  1914. std::string incpath = this->XCodeEscapePath(frameworkDir);
  1915. if (emitSystemIncludes &&
  1916. gtgt->IsSystemIncludeDirectory(frameworkDir, configName,
  1917. langForPreprocessor)) {
  1918. sysfdirs.Add(incpath);
  1919. } else {
  1920. fdirs.Add(incpath);
  1921. }
  1922. }
  1923. } else {
  1924. std::string incpath = this->XCodeEscapePath(include);
  1925. if (emitSystemIncludes &&
  1926. gtgt->IsSystemIncludeDirectory(include, configName,
  1927. langForPreprocessor)) {
  1928. sysdirs.Add(incpath);
  1929. } else {
  1930. dirs.Add(incpath);
  1931. }
  1932. }
  1933. }
  1934. // Add framework search paths needed for linking.
  1935. if (cmComputeLinkInformation* cli = gtgt->GetLinkInformation(configName)) {
  1936. for (auto const& fwDir : cli->GetFrameworkPaths()) {
  1937. if (emitted.insert(fwDir).second) {
  1938. std::string incpath = this->XCodeEscapePath(fwDir);
  1939. if (emitSystemIncludes &&
  1940. gtgt->IsSystemIncludeDirectory(fwDir, configName,
  1941. langForPreprocessor)) {
  1942. sysfdirs.Add(incpath);
  1943. } else {
  1944. fdirs.Add(incpath);
  1945. }
  1946. }
  1947. }
  1948. }
  1949. if (!fdirs.IsEmpty()) {
  1950. buildSettings->AddAttribute("FRAMEWORK_SEARCH_PATHS", fdirs.CreateList());
  1951. }
  1952. if (!dirs.IsEmpty()) {
  1953. buildSettings->AddAttribute("HEADER_SEARCH_PATHS", dirs.CreateList());
  1954. }
  1955. if (!sysfdirs.IsEmpty()) {
  1956. buildSettings->AddAttribute("SYSTEM_FRAMEWORK_SEARCH_PATHS",
  1957. sysfdirs.CreateList());
  1958. }
  1959. if (!sysdirs.IsEmpty()) {
  1960. buildSettings->AddAttribute("SYSTEM_HEADER_SEARCH_PATHS",
  1961. sysdirs.CreateList());
  1962. }
  1963. if (this->XcodeVersion >= 60 && !emitSystemIncludes) {
  1964. // Add those per-language flags in addition to HEADER_SEARCH_PATHS to gain
  1965. // system include directory awareness. We need to also keep on setting
  1966. // HEADER_SEARCH_PATHS to work around a missing compile options flag for
  1967. // GNU assembly files (#16449)
  1968. for (auto const& language : languages) {
  1969. std::string includeFlags = this->CurrentLocalGenerator->GetIncludeFlags(
  1970. includes, gtgt, language, true, false, configName);
  1971. if (!includeFlags.empty()) {
  1972. cflags[language] += " " + includeFlags;
  1973. }
  1974. }
  1975. }
  1976. bool same_gflags = true;
  1977. std::map<std::string, std::string> gflags;
  1978. std::string const* last_gflag = nullptr;
  1979. std::string optLevel = "0";
  1980. // Minimal map of flags to build settings.
  1981. for (auto const& language : languages) {
  1982. std::string& flags = cflags[language];
  1983. std::string& gflag = gflags[language];
  1984. std::string oflag =
  1985. this->ExtractFlagRegex("(^| )(-Ofast|-Os|-O[0-9]*)( |$)", 2, flags);
  1986. if (oflag.size() == 2) {
  1987. optLevel = "1";
  1988. } else if (oflag.size() > 2) {
  1989. optLevel = oflag.substr(2);
  1990. }
  1991. gflag = this->ExtractFlag("-g", flags);
  1992. // put back gdwarf-2 if used since there is no way
  1993. // to represent it in the gui, but we still want debug yes
  1994. if (gflag == "-gdwarf-2") {
  1995. flags += " ";
  1996. flags += gflag;
  1997. }
  1998. if (last_gflag && *last_gflag != gflag) {
  1999. same_gflags = false;
  2000. }
  2001. last_gflag = &gflag;
  2002. }
  2003. const char* debugStr = "YES";
  2004. if (!same_gflags) {
  2005. // We can't set the Xcode flag differently depending on the language,
  2006. // so put them back in this case.
  2007. for (auto const& language : languages) {
  2008. cflags[language] += " ";
  2009. cflags[language] += gflags[language];
  2010. }
  2011. debugStr = "NO";
  2012. } else if (last_gflag && (last_gflag->empty() || *last_gflag == "-g0")) {
  2013. debugStr = "NO";
  2014. }
  2015. buildSettings->AddAttribute("COMBINE_HIDPI_IMAGES",
  2016. this->CreateString("YES"));
  2017. buildSettings->AddAttribute("GCC_GENERATE_DEBUGGING_SYMBOLS",
  2018. this->CreateString(debugStr));
  2019. buildSettings->AddAttribute("GCC_OPTIMIZATION_LEVEL",
  2020. this->CreateString(optLevel));
  2021. buildSettings->AddAttribute("GCC_SYMBOLS_PRIVATE_EXTERN",
  2022. this->CreateString("NO"));
  2023. buildSettings->AddAttribute("GCC_INLINES_ARE_PRIVATE_EXTERN",
  2024. this->CreateString("NO"));
  2025. for (auto const& language : languages) {
  2026. std::string flags = cflags[language] + " " + defFlags;
  2027. if (language == "CXX") {
  2028. buildSettings->AddAttribute("OTHER_CPLUSPLUSFLAGS",
  2029. this->CreateString(flags));
  2030. } else if (language == "Fortran") {
  2031. buildSettings->AddAttribute("IFORT_OTHER_FLAGS",
  2032. this->CreateString(flags));
  2033. } else if (language == "C") {
  2034. buildSettings->AddAttribute("OTHER_CFLAGS", this->CreateString(flags));
  2035. } else if (language == "Swift") {
  2036. buildSettings->AddAttribute("OTHER_SWIFT_FLAGS",
  2037. this->CreateString(flags));
  2038. }
  2039. }
  2040. // Add Fortran source format attribute if property is set.
  2041. const char* format = nullptr;
  2042. const char* tgtfmt = gtgt->GetProperty("Fortran_FORMAT");
  2043. switch (cmOutputConverter::GetFortranFormat(tgtfmt)) {
  2044. case cmOutputConverter::FortranFormatFixed:
  2045. format = "fixed";
  2046. break;
  2047. case cmOutputConverter::FortranFormatFree:
  2048. format = "free";
  2049. break;
  2050. default:
  2051. break;
  2052. }
  2053. if (format) {
  2054. buildSettings->AddAttribute("IFORT_LANG_SRCFMT",
  2055. this->CreateString(format));
  2056. }
  2057. // Create the INSTALL_PATH attribute.
  2058. std::string install_name_dir;
  2059. if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) {
  2060. // Get the install_name directory for the build tree.
  2061. install_name_dir = gtgt->GetInstallNameDirForBuildTree(configName);
  2062. // Xcode doesn't create the correct install_name in some cases.
  2063. // That is, if the INSTALL_PATH is empty, or if we have versioning
  2064. // of dylib libraries, we want to specify the install_name.
  2065. // This is done by adding a link flag to create an install_name
  2066. // with just the library soname.
  2067. std::string install_name;
  2068. if (!install_name_dir.empty()) {
  2069. // Convert to a path for the native build tool.
  2070. cmSystemTools::ConvertToUnixSlashes(install_name_dir);
  2071. install_name += install_name_dir;
  2072. install_name += "/";
  2073. }
  2074. install_name += gtgt->GetSOName(configName);
  2075. if ((realName != soName) || install_name_dir.empty()) {
  2076. install_name_dir = "";
  2077. extraLinkOptions += " -install_name ";
  2078. extraLinkOptions += XCodeEscapePath(install_name);
  2079. }
  2080. }
  2081. buildSettings->AddAttribute("INSTALL_PATH",
  2082. this->CreateString(install_name_dir));
  2083. // Create the LD_RUNPATH_SEARCH_PATHS
  2084. cmComputeLinkInformation* pcli = gtgt->GetLinkInformation(configName);
  2085. if (pcli) {
  2086. std::string search_paths;
  2087. std::vector<std::string> runtimeDirs;
  2088. pcli->GetRPath(runtimeDirs, false);
  2089. // runpath dirs needs to be unique to prevent corruption
  2090. std::set<std::string> unique_dirs;
  2091. for (auto runpath : runtimeDirs) {
  2092. runpath = this->ExpandCFGIntDir(runpath, configName);
  2093. if (unique_dirs.find(runpath) == unique_dirs.end()) {
  2094. unique_dirs.insert(runpath);
  2095. if (!search_paths.empty()) {
  2096. search_paths += " ";
  2097. }
  2098. search_paths += this->XCodeEscapePath(runpath);
  2099. }
  2100. }
  2101. if (!search_paths.empty()) {
  2102. buildSettings->AddAttribute("LD_RUNPATH_SEARCH_PATHS",
  2103. this->CreateString(search_paths));
  2104. }
  2105. }
  2106. buildSettings->AddAttribute(this->GetTargetLinkFlagsVar(gtgt),
  2107. this->CreateString(extraLinkOptions));
  2108. buildSettings->AddAttribute("OTHER_REZFLAGS", this->CreateString(""));
  2109. buildSettings->AddAttribute("SECTORDER_FLAGS", this->CreateString(""));
  2110. buildSettings->AddAttribute("USE_HEADERMAP", this->CreateString("NO"));
  2111. cmXCodeObject* group = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2112. group->AddObject(this->CreateString("-Wmost"));
  2113. group->AddObject(this->CreateString("-Wno-four-char-constants"));
  2114. group->AddObject(this->CreateString("-Wno-unknown-pragmas"));
  2115. group->AddObject(this->CreateString("$(inherited)"));
  2116. buildSettings->AddAttribute("WARNING_CFLAGS", group);
  2117. // Runtime version information.
  2118. if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) {
  2119. int major;
  2120. int minor;
  2121. int patch;
  2122. // VERSION -> current_version
  2123. gtgt->GetTargetVersion(false, major, minor, patch);
  2124. std::ostringstream v;
  2125. // Xcode always wants at least 1.0.0 or nothing
  2126. if (!(major == 0 && minor == 0 && patch == 0)) {
  2127. v << major << "." << minor << "." << patch;
  2128. }
  2129. buildSettings->AddAttribute("DYLIB_CURRENT_VERSION",
  2130. this->CreateString(v.str()));
  2131. // SOVERSION -> compatibility_version
  2132. gtgt->GetTargetVersion(true, major, minor, patch);
  2133. std::ostringstream vso;
  2134. // Xcode always wants at least 1.0.0 or nothing
  2135. if (!(major == 0 && minor == 0 && patch == 0)) {
  2136. vso << major << "." << minor << "." << patch;
  2137. }
  2138. buildSettings->AddAttribute("DYLIB_COMPATIBILITY_VERSION",
  2139. this->CreateString(vso.str()));
  2140. }
  2141. // put this last so it can override existing settings
  2142. // Convert "XCODE_ATTRIBUTE_*" properties directly.
  2143. {
  2144. for (auto const& prop : gtgt->GetPropertyKeys()) {
  2145. if (prop.find("XCODE_ATTRIBUTE_") == 0) {
  2146. std::string attribute = prop.substr(16);
  2147. this->FilterConfigurationAttribute(configName, attribute);
  2148. if (!attribute.empty()) {
  2149. cmGeneratorExpression ge;
  2150. std::string processed =
  2151. ge.Parse(gtgt->GetProperty(prop))
  2152. ->Evaluate(this->CurrentLocalGenerator, configName);
  2153. buildSettings->AddAttribute(attribute,
  2154. this->CreateString(processed));
  2155. }
  2156. }
  2157. }
  2158. }
  2159. }
  2160. cmXCodeObject* cmGlobalXCodeGenerator::CreateUtilityTarget(
  2161. cmGeneratorTarget* gtgt)
  2162. {
  2163. cmXCodeObject* shellBuildPhase =
  2164. this->CreateObject(cmXCodeObject::PBXShellScriptBuildPhase);
  2165. shellBuildPhase->AddAttribute("buildActionMask",
  2166. this->CreateString("2147483647"));
  2167. cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2168. shellBuildPhase->AddAttribute("files", buildFiles);
  2169. cmXCodeObject* inputPaths = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2170. shellBuildPhase->AddAttribute("inputPaths", inputPaths);
  2171. cmXCodeObject* outputPaths = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2172. shellBuildPhase->AddAttribute("outputPaths", outputPaths);
  2173. shellBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  2174. this->CreateString("0"));
  2175. shellBuildPhase->AddAttribute("shellPath", this->CreateString("/bin/sh"));
  2176. shellBuildPhase->AddAttribute(
  2177. "shellScript", this->CreateString("# shell script goes here\nexit 0"));
  2178. shellBuildPhase->AddAttribute("showEnvVarsInLog", this->CreateString("0"));
  2179. cmXCodeObject* target =
  2180. this->CreateObject(cmXCodeObject::PBXAggregateTarget);
  2181. target->SetComment(gtgt->GetName());
  2182. cmXCodeObject* buildPhases = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2183. std::vector<cmXCodeObject*> emptyContentVector;
  2184. this->CreateCustomCommands(buildPhases, nullptr, nullptr, nullptr,
  2185. emptyContentVector, nullptr, gtgt);
  2186. target->AddAttribute("buildPhases", buildPhases);
  2187. this->AddConfigurations(target, gtgt);
  2188. cmXCodeObject* dependencies = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2189. target->AddAttribute("dependencies", dependencies);
  2190. target->AddAttribute("name", this->CreateString(gtgt->GetName()));
  2191. target->AddAttribute("productName", this->CreateString(gtgt->GetName()));
  2192. target->SetTarget(gtgt);
  2193. this->XCodeObjectMap[gtgt] = target;
  2194. // Add source files without build rules for editing convenience.
  2195. if (gtgt->GetType() == cmStateEnums::UTILITY &&
  2196. gtgt->GetName() != CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
  2197. std::vector<cmSourceFile*> sources;
  2198. if (!gtgt->GetConfigCommonSourceFiles(sources)) {
  2199. return nullptr;
  2200. }
  2201. // Add CMakeLists.txt file for user convenience.
  2202. this->AddXCodeProjBuildRule(gtgt, sources);
  2203. for (auto sourceFile : sources) {
  2204. if (!sourceFile->GetPropertyAsBool("GENERATED")) {
  2205. this->CreateXCodeFileReference(sourceFile, gtgt);
  2206. }
  2207. }
  2208. }
  2209. target->SetId(this->GetOrCreateId(gtgt->GetName(), target->GetId()));
  2210. return target;
  2211. }
  2212. std::string cmGlobalXCodeGenerator::AddConfigurations(cmXCodeObject* target,
  2213. cmGeneratorTarget* gtgt)
  2214. {
  2215. std::string configTypes =
  2216. this->CurrentMakefile->GetRequiredDefinition("CMAKE_CONFIGURATION_TYPES");
  2217. std::vector<std::string> configVectorIn;
  2218. std::vector<std::string> configVector;
  2219. configVectorIn.push_back(configTypes);
  2220. cmSystemTools::ExpandList(configVectorIn, configVector);
  2221. cmXCodeObject* configlist =
  2222. this->CreateObject(cmXCodeObject::XCConfigurationList);
  2223. cmXCodeObject* buildConfigurations =
  2224. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2225. configlist->AddAttribute("buildConfigurations", buildConfigurations);
  2226. std::string comment = "Build configuration list for ";
  2227. comment += cmXCodeObject::PBXTypeNames[target->GetIsA()];
  2228. comment += " \"";
  2229. comment += gtgt->GetName();
  2230. comment += "\"";
  2231. configlist->SetComment(comment);
  2232. target->AddAttribute("buildConfigurationList",
  2233. this->CreateObjectReference(configlist));
  2234. for (auto const& i : configVector) {
  2235. cmXCodeObject* config =
  2236. this->CreateObject(cmXCodeObject::XCBuildConfiguration);
  2237. buildConfigurations->AddObject(config);
  2238. cmXCodeObject* buildSettings =
  2239. this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  2240. this->CreateBuildSettings(gtgt, buildSettings, i);
  2241. config->AddAttribute("name", this->CreateString(i));
  2242. config->SetComment(i);
  2243. config->AddAttribute("buildSettings", buildSettings);
  2244. }
  2245. if (!configVector.empty()) {
  2246. configlist->AddAttribute("defaultConfigurationName",
  2247. this->CreateString(configVector[0]));
  2248. configlist->AddAttribute("defaultConfigurationIsVisible",
  2249. this->CreateString("0"));
  2250. return configVector[0];
  2251. }
  2252. return "";
  2253. }
  2254. const char* cmGlobalXCodeGenerator::GetTargetLinkFlagsVar(
  2255. cmGeneratorTarget const* target) const
  2256. {
  2257. if (this->XcodeVersion >= 60 &&
  2258. (target->GetType() == cmStateEnums::STATIC_LIBRARY ||
  2259. target->GetType() == cmStateEnums::OBJECT_LIBRARY)) {
  2260. return "OTHER_LIBTOOLFLAGS";
  2261. }
  2262. return "OTHER_LDFLAGS";
  2263. }
  2264. const char* cmGlobalXCodeGenerator::GetTargetFileType(
  2265. cmGeneratorTarget* target)
  2266. {
  2267. if (const char* e = target->GetProperty("XCODE_EXPLICIT_FILE_TYPE")) {
  2268. return e;
  2269. }
  2270. switch (target->GetType()) {
  2271. case cmStateEnums::OBJECT_LIBRARY:
  2272. return "archive.ar";
  2273. case cmStateEnums::STATIC_LIBRARY:
  2274. return (target->GetPropertyAsBool("FRAMEWORK") ? "wrapper.framework"
  2275. : "archive.ar");
  2276. case cmStateEnums::MODULE_LIBRARY:
  2277. if (target->IsXCTestOnApple()) {
  2278. return "wrapper.cfbundle";
  2279. }
  2280. if (target->IsCFBundleOnApple()) {
  2281. return "wrapper.plug-in";
  2282. }
  2283. return "compiled.mach-o.executable";
  2284. case cmStateEnums::SHARED_LIBRARY:
  2285. return (target->GetPropertyAsBool("FRAMEWORK")
  2286. ? "wrapper.framework"
  2287. : "compiled.mach-o.dylib");
  2288. case cmStateEnums::EXECUTABLE:
  2289. return "compiled.mach-o.executable";
  2290. default:
  2291. break;
  2292. }
  2293. return nullptr;
  2294. }
  2295. const char* cmGlobalXCodeGenerator::GetTargetProductType(
  2296. cmGeneratorTarget* target)
  2297. {
  2298. if (const char* e = target->GetProperty("XCODE_PRODUCT_TYPE")) {
  2299. return e;
  2300. }
  2301. switch (target->GetType()) {
  2302. case cmStateEnums::OBJECT_LIBRARY:
  2303. return "com.apple.product-type.library.static";
  2304. case cmStateEnums::STATIC_LIBRARY:
  2305. return (target->GetPropertyAsBool("FRAMEWORK")
  2306. ? "com.apple.product-type.framework"
  2307. : "com.apple.product-type.library.static");
  2308. case cmStateEnums::MODULE_LIBRARY:
  2309. if (target->IsXCTestOnApple()) {
  2310. return "com.apple.product-type.bundle.unit-test";
  2311. } else if (target->IsCFBundleOnApple()) {
  2312. return "com.apple.product-type.bundle";
  2313. } else {
  2314. return "com.apple.product-type.tool";
  2315. }
  2316. case cmStateEnums::SHARED_LIBRARY:
  2317. return (target->GetPropertyAsBool("FRAMEWORK")
  2318. ? "com.apple.product-type.framework"
  2319. : "com.apple.product-type.library.dynamic");
  2320. case cmStateEnums::EXECUTABLE:
  2321. return (target->GetPropertyAsBool("MACOSX_BUNDLE")
  2322. ? "com.apple.product-type.application"
  2323. : "com.apple.product-type.tool");
  2324. default:
  2325. break;
  2326. }
  2327. return nullptr;
  2328. }
  2329. cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeTarget(
  2330. cmGeneratorTarget* gtgt, cmXCodeObject* buildPhases)
  2331. {
  2332. if (gtgt->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  2333. return nullptr;
  2334. }
  2335. cmXCodeObject* target = this->CreateObject(cmXCodeObject::PBXNativeTarget);
  2336. target->AddAttribute("buildPhases", buildPhases);
  2337. cmXCodeObject* buildRules = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2338. target->AddAttribute("buildRules", buildRules);
  2339. std::string defConfig;
  2340. defConfig = this->AddConfigurations(target, gtgt);
  2341. cmXCodeObject* dependencies = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2342. target->AddAttribute("dependencies", dependencies);
  2343. target->AddAttribute("name", this->CreateString(gtgt->GetName()));
  2344. target->AddAttribute("productName", this->CreateString(gtgt->GetName()));
  2345. cmXCodeObject* fileRef = this->CreateObject(cmXCodeObject::PBXFileReference);
  2346. if (const char* fileType = this->GetTargetFileType(gtgt)) {
  2347. fileRef->AddAttribute("explicitFileType", this->CreateString(fileType));
  2348. }
  2349. std::string fullName;
  2350. if (gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  2351. fullName = "lib";
  2352. fullName += gtgt->GetName();
  2353. fullName += ".a";
  2354. } else {
  2355. fullName = gtgt->GetFullName(defConfig);
  2356. }
  2357. fileRef->AddAttribute("path", this->CreateString(fullName));
  2358. fileRef->AddAttribute("sourceTree",
  2359. this->CreateString("BUILT_PRODUCTS_DIR"));
  2360. fileRef->SetComment(gtgt->GetName());
  2361. target->AddAttribute("productReference",
  2362. this->CreateObjectReference(fileRef));
  2363. if (const char* productType = this->GetTargetProductType(gtgt)) {
  2364. target->AddAttribute("productType", this->CreateString(productType));
  2365. }
  2366. target->SetTarget(gtgt);
  2367. this->XCodeObjectMap[gtgt] = target;
  2368. target->SetId(this->GetOrCreateId(gtgt->GetName(), target->GetId()));
  2369. return target;
  2370. }
  2371. cmXCodeObject* cmGlobalXCodeGenerator::FindXCodeTarget(
  2372. cmGeneratorTarget const* t)
  2373. {
  2374. if (!t) {
  2375. return nullptr;
  2376. }
  2377. std::map<cmGeneratorTarget const*, cmXCodeObject*>::const_iterator const i =
  2378. this->XCodeObjectMap.find(t);
  2379. if (i == this->XCodeObjectMap.end()) {
  2380. return nullptr;
  2381. }
  2382. return i->second;
  2383. }
  2384. std::string cmGlobalXCodeGenerator::GetOrCreateId(const std::string& name,
  2385. const std::string& id)
  2386. {
  2387. std::string guidStoreName = name;
  2388. guidStoreName += "_GUID_CMAKE";
  2389. const char* storedGUID =
  2390. this->CMakeInstance->GetCacheDefinition(guidStoreName);
  2391. if (storedGUID) {
  2392. return storedGUID;
  2393. }
  2394. this->CMakeInstance->AddCacheEntry(guidStoreName, id.c_str(),
  2395. "Stored Xcode object GUID",
  2396. cmStateEnums::INTERNAL);
  2397. return id;
  2398. }
  2399. void cmGlobalXCodeGenerator::AddDependTarget(cmXCodeObject* target,
  2400. cmXCodeObject* dependTarget)
  2401. {
  2402. // This is called once for every edge in the target dependency graph.
  2403. cmXCodeObject* container =
  2404. this->CreateObject(cmXCodeObject::PBXContainerItemProxy);
  2405. container->SetComment("PBXContainerItemProxy");
  2406. container->AddAttribute("containerPortal",
  2407. this->CreateObjectReference(this->RootObject));
  2408. container->AddAttribute("proxyType", this->CreateString("1"));
  2409. container->AddAttribute("remoteGlobalIDString",
  2410. this->CreateObjectReference(dependTarget));
  2411. container->AddAttribute(
  2412. "remoteInfo", this->CreateString(dependTarget->GetTarget()->GetName()));
  2413. cmXCodeObject* targetdep =
  2414. this->CreateObject(cmXCodeObject::PBXTargetDependency);
  2415. targetdep->SetComment("PBXTargetDependency");
  2416. targetdep->AddAttribute("target", this->CreateObjectReference(dependTarget));
  2417. targetdep->AddAttribute("targetProxy",
  2418. this->CreateObjectReference(container));
  2419. cmXCodeObject* depends = target->GetObject("dependencies");
  2420. if (!depends) {
  2421. cmSystemTools::Error(
  2422. "target does not have dependencies attribute error..");
  2423. } else {
  2424. depends->AddUniqueObject(targetdep);
  2425. }
  2426. }
  2427. void cmGlobalXCodeGenerator::AppendOrAddBuildSetting(cmXCodeObject* settings,
  2428. const char* attribute,
  2429. const char* value)
  2430. {
  2431. if (settings) {
  2432. cmXCodeObject* attr = settings->GetObject(attribute);
  2433. if (!attr) {
  2434. settings->AddAttribute(attribute, this->CreateString(value));
  2435. } else {
  2436. std::string oldValue = attr->GetString();
  2437. oldValue += " ";
  2438. oldValue += value;
  2439. attr->SetString(oldValue);
  2440. }
  2441. }
  2442. }
  2443. void cmGlobalXCodeGenerator::AppendBuildSettingAttribute(
  2444. cmXCodeObject* target, const char* attribute, const char* value,
  2445. const std::string& configName)
  2446. {
  2447. // There are multiple configurations. Add the setting to the
  2448. // buildSettings of the configuration name given.
  2449. cmXCodeObject* configurationList =
  2450. target->GetObject("buildConfigurationList")->GetObject();
  2451. cmXCodeObject* buildConfigs =
  2452. configurationList->GetObject("buildConfigurations");
  2453. for (auto obj : buildConfigs->GetObjectList()) {
  2454. if (configName.empty() ||
  2455. obj->GetObject("name")->GetString() == configName) {
  2456. cmXCodeObject* settings = obj->GetObject("buildSettings");
  2457. this->AppendOrAddBuildSetting(settings, attribute, value);
  2458. }
  2459. }
  2460. }
  2461. void cmGlobalXCodeGenerator::AddDependAndLinkInformation(cmXCodeObject* target)
  2462. {
  2463. cmGeneratorTarget* gt = target->GetTarget();
  2464. if (!gt) {
  2465. cmSystemTools::Error("Error no target on xobject\n");
  2466. return;
  2467. }
  2468. if (gt->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  2469. return;
  2470. }
  2471. // Add dependencies on other CMake targets.
  2472. for (const auto& dep : this->GetTargetDirectDepends(gt)) {
  2473. if (cmXCodeObject* dptarget = this->FindXCodeTarget(dep)) {
  2474. this->AddDependTarget(target, dptarget);
  2475. }
  2476. }
  2477. // Loop over configuration types and set per-configuration info.
  2478. for (auto const& configName : this->CurrentConfigurationTypes) {
  2479. // Get the current configuration name.
  2480. if (this->XcodeVersion >= 50) {
  2481. // Add object library contents as link flags.
  2482. std::string linkObjs;
  2483. const char* sep = "";
  2484. std::vector<cmSourceFile const*> objs;
  2485. gt->GetExternalObjects(objs, configName);
  2486. for (auto sourceFile : objs) {
  2487. if (sourceFile->GetObjectLibrary().empty()) {
  2488. continue;
  2489. }
  2490. linkObjs += sep;
  2491. sep = " ";
  2492. linkObjs += this->XCodeEscapePath(sourceFile->GetFullPath());
  2493. }
  2494. this->AppendBuildSettingAttribute(
  2495. target, this->GetTargetLinkFlagsVar(gt), linkObjs.c_str(), configName);
  2496. }
  2497. // Skip link information for object libraries.
  2498. if (gt->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  2499. gt->GetType() == cmStateEnums::STATIC_LIBRARY) {
  2500. continue;
  2501. }
  2502. // Compute the link library and directory information.
  2503. cmComputeLinkInformation* pcli = gt->GetLinkInformation(configName);
  2504. if (!pcli) {
  2505. continue;
  2506. }
  2507. cmComputeLinkInformation& cli = *pcli;
  2508. // Add dependencies directly on library files.
  2509. for (auto const& libDep : cli.GetDepends()) {
  2510. target->AddDependLibrary(configName, libDep);
  2511. }
  2512. // add the library search paths
  2513. {
  2514. std::string linkDirs;
  2515. for (auto const& libDir : cli.GetDirectories()) {
  2516. if (!libDir.empty() && libDir != "/usr/lib") {
  2517. // Now add the same one but append
  2518. // $(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) to it:
  2519. linkDirs += " ";
  2520. linkDirs += this->XCodeEscapePath(
  2521. libDir + "/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)");
  2522. linkDirs += " ";
  2523. linkDirs += this->XCodeEscapePath(libDir);
  2524. }
  2525. }
  2526. this->AppendBuildSettingAttribute(target, "LIBRARY_SEARCH_PATHS",
  2527. linkDirs.c_str(), configName);
  2528. }
  2529. // now add the link libraries
  2530. {
  2531. std::string linkLibs;
  2532. const char* sep = "";
  2533. for (auto const& libName : cli.GetItems()) {
  2534. linkLibs += sep;
  2535. sep = " ";
  2536. if (libName.IsPath) {
  2537. linkLibs += this->XCodeEscapePath(libName.Value);
  2538. } else if (!libName.Target ||
  2539. libName.Target->GetType() !=
  2540. cmStateEnums::INTERFACE_LIBRARY) {
  2541. linkLibs += libName.Value;
  2542. }
  2543. if (libName.Target && !libName.Target->IsImported()) {
  2544. target->AddDependTarget(configName, libName.Target->GetName());
  2545. }
  2546. }
  2547. this->AppendBuildSettingAttribute(
  2548. target, this->GetTargetLinkFlagsVar(gt), linkLibs.c_str(), configName);
  2549. }
  2550. }
  2551. }
  2552. bool cmGlobalXCodeGenerator::CreateGroups(
  2553. std::vector<cmLocalGenerator*>& generators)
  2554. {
  2555. for (auto& generator : generators) {
  2556. cmMakefile* mf = generator->GetMakefile();
  2557. std::vector<cmSourceGroup> sourceGroups = mf->GetSourceGroups();
  2558. for (auto gtgt : generator->GetGeneratorTargets()) {
  2559. // Same skipping logic here as in CreateXCodeTargets so that we do not
  2560. // end up with (empty anyhow) ZERO_CHECK, install, or test source
  2561. // groups:
  2562. //
  2563. if (gtgt->GetType() == cmStateEnums::GLOBAL_TARGET) {
  2564. continue;
  2565. }
  2566. if (gtgt->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  2567. continue;
  2568. }
  2569. if (gtgt->GetName() == CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
  2570. continue;
  2571. }
  2572. // add the soon to be generated Info.plist file as a source for a
  2573. // MACOSX_BUNDLE file
  2574. if (gtgt->GetPropertyAsBool("MACOSX_BUNDLE")) {
  2575. std::string plist = this->ComputeInfoPListLocation(gtgt);
  2576. mf->GetOrCreateSource(plist, true);
  2577. gtgt->AddSource(plist);
  2578. }
  2579. // Put cmSourceFile instances in proper groups:
  2580. for (auto const& si : gtgt->GetAllConfigSources()) {
  2581. cmSourceFile const* sf = si.Source;
  2582. if (this->XcodeVersion >= 50 && !sf->GetObjectLibrary().empty()) {
  2583. // Object library files go on the link line instead.
  2584. continue;
  2585. }
  2586. // Add the file to the list of sources.
  2587. std::string const& source = sf->GetFullPath();
  2588. cmSourceGroup* sourceGroup = mf->FindSourceGroup(source, sourceGroups);
  2589. cmXCodeObject* pbxgroup = this->CreateOrGetPBXGroup(gtgt, sourceGroup);
  2590. std::string key = GetGroupMapKeyFromPath(gtgt, source);
  2591. this->GroupMap[key] = pbxgroup;
  2592. }
  2593. // Add CMakeLists.txt file for user convenience.
  2594. {
  2595. std::string listfile =
  2596. gtgt->GetLocalGenerator()->GetCurrentSourceDirectory();
  2597. listfile += "/CMakeLists.txt";
  2598. cmSourceFile* sf = gtgt->Makefile->GetOrCreateSource(listfile);
  2599. std::string const& source = sf->GetFullPath();
  2600. cmSourceGroup* sourceGroup = mf->FindSourceGroup(source, sourceGroups);
  2601. cmXCodeObject* pbxgroup = this->CreateOrGetPBXGroup(gtgt, sourceGroup);
  2602. std::string key = GetGroupMapKeyFromPath(gtgt, source);
  2603. this->GroupMap[key] = pbxgroup;
  2604. }
  2605. }
  2606. }
  2607. return true;
  2608. }
  2609. cmXCodeObject* cmGlobalXCodeGenerator::CreatePBXGroup(cmXCodeObject* parent,
  2610. const std::string& name)
  2611. {
  2612. cmXCodeObject* parentChildren = nullptr;
  2613. if (parent) {
  2614. parentChildren = parent->GetObject("children");
  2615. }
  2616. cmXCodeObject* group = this->CreateObject(cmXCodeObject::PBXGroup);
  2617. cmXCodeObject* groupChildren =
  2618. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2619. group->AddAttribute("name", this->CreateString(name));
  2620. group->AddAttribute("children", groupChildren);
  2621. group->AddAttribute("sourceTree", this->CreateString("<group>"));
  2622. if (parentChildren) {
  2623. parentChildren->AddObject(group);
  2624. }
  2625. return group;
  2626. }
  2627. cmXCodeObject* cmGlobalXCodeGenerator::CreateOrGetPBXGroup(
  2628. cmGeneratorTarget* gtgt, cmSourceGroup* sg)
  2629. {
  2630. std::string s;
  2631. std::string target;
  2632. const std::string targetFolder = gtgt->GetEffectiveFolderName();
  2633. if (!targetFolder.empty()) {
  2634. target = targetFolder;
  2635. target += "/";
  2636. }
  2637. target += gtgt->GetName();
  2638. s = target + "/";
  2639. s += sg->GetFullName();
  2640. std::map<std::string, cmXCodeObject*>::iterator it =
  2641. this->GroupNameMap.find(s);
  2642. if (it != this->GroupNameMap.end()) {
  2643. return it->second;
  2644. }
  2645. it = this->TargetGroup.find(target);
  2646. cmXCodeObject* tgroup = nullptr;
  2647. if (it != this->TargetGroup.end()) {
  2648. tgroup = it->second;
  2649. } else {
  2650. std::vector<std::string> tgt_folders =
  2651. cmSystemTools::tokenize(target, "/");
  2652. std::string curr_tgt_folder;
  2653. for (std::vector<std::string>::size_type i = 0; i < tgt_folders.size();
  2654. i++) {
  2655. if (i != 0) {
  2656. curr_tgt_folder += "/";
  2657. }
  2658. curr_tgt_folder += tgt_folders[i];
  2659. it = this->TargetGroup.find(curr_tgt_folder);
  2660. if (it != this->TargetGroup.end()) {
  2661. tgroup = it->second;
  2662. continue;
  2663. }
  2664. tgroup = this->CreatePBXGroup(tgroup, tgt_folders[i]);
  2665. this->TargetGroup[curr_tgt_folder] = tgroup;
  2666. if (i == 0) {
  2667. this->MainGroupChildren->AddObject(tgroup);
  2668. }
  2669. }
  2670. }
  2671. this->TargetGroup[target] = tgroup;
  2672. // If it's the default source group (empty name) then put the source file
  2673. // directly in the tgroup...
  2674. //
  2675. if (sg->GetFullName().empty()) {
  2676. this->GroupNameMap[s] = tgroup;
  2677. return tgroup;
  2678. }
  2679. // It's a recursive folder structure, let's find the real parent group
  2680. if (sg->GetFullName() != sg->GetName()) {
  2681. std::string curr_folder = target;
  2682. curr_folder += "/";
  2683. for (auto const& folder :
  2684. cmSystemTools::tokenize(sg->GetFullName(), "\\")) {
  2685. curr_folder += folder;
  2686. std::map<std::string, cmXCodeObject*>::iterator i_folder =
  2687. this->GroupNameMap.find(curr_folder);
  2688. // Create new folder
  2689. if (i_folder == this->GroupNameMap.end()) {
  2690. cmXCodeObject* group = this->CreatePBXGroup(tgroup, folder);
  2691. this->GroupNameMap[curr_folder] = group;
  2692. tgroup = group;
  2693. } else {
  2694. tgroup = i_folder->second;
  2695. }
  2696. curr_folder = curr_folder + "\\";
  2697. }
  2698. return tgroup;
  2699. }
  2700. cmXCodeObject* group = this->CreatePBXGroup(tgroup, sg->GetName());
  2701. this->GroupNameMap[s] = group;
  2702. return group;
  2703. }
  2704. bool cmGlobalXCodeGenerator::CreateXCodeObjects(
  2705. cmLocalGenerator* root, std::vector<cmLocalGenerator*>& generators)
  2706. {
  2707. this->ClearXCodeObjects();
  2708. this->RootObject = nullptr;
  2709. this->MainGroupChildren = nullptr;
  2710. cmXCodeObject* group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  2711. group->AddAttribute("COPY_PHASE_STRIP", this->CreateString("NO"));
  2712. cmXCodeObject* listObjs = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2713. for (auto& CurrentConfigurationType : this->CurrentConfigurationTypes) {
  2714. cmXCodeObject* buildStyle =
  2715. this->CreateObject(cmXCodeObject::PBXBuildStyle);
  2716. const char* name = CurrentConfigurationType.c_str();
  2717. buildStyle->AddAttribute("name", this->CreateString(name));
  2718. buildStyle->SetComment(name);
  2719. cmXCodeObject* sgroup = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  2720. sgroup->AddAttribute("COPY_PHASE_STRIP", this->CreateString("NO"));
  2721. buildStyle->AddAttribute("buildSettings", sgroup);
  2722. listObjs->AddObject(buildStyle);
  2723. }
  2724. cmXCodeObject* mainGroup = this->CreateObject(cmXCodeObject::PBXGroup);
  2725. this->MainGroupChildren = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2726. mainGroup->AddAttribute("children", this->MainGroupChildren);
  2727. mainGroup->AddAttribute("sourceTree", this->CreateString("<group>"));
  2728. // now create the cmake groups
  2729. if (!this->CreateGroups(generators)) {
  2730. return false;
  2731. }
  2732. cmXCodeObject* productGroup = this->CreateObject(cmXCodeObject::PBXGroup);
  2733. productGroup->AddAttribute("name", this->CreateString("Products"));
  2734. productGroup->AddAttribute("sourceTree", this->CreateString("<group>"));
  2735. cmXCodeObject* productGroupChildren =
  2736. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2737. productGroup->AddAttribute("children", productGroupChildren);
  2738. this->MainGroupChildren->AddObject(productGroup);
  2739. this->RootObject = this->CreateObject(cmXCodeObject::PBXProject);
  2740. this->RootObject->SetComment("Project object");
  2741. std::string project_id = "PROJECT_";
  2742. project_id += root->GetProjectName();
  2743. this->RootObject->SetId(
  2744. this->GetOrCreateId(project_id, this->RootObject->GetId()));
  2745. group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  2746. this->RootObject->AddAttribute("mainGroup",
  2747. this->CreateObjectReference(mainGroup));
  2748. this->RootObject->AddAttribute("buildSettings", group);
  2749. this->RootObject->AddAttribute("buildStyles", listObjs);
  2750. this->RootObject->AddAttribute("hasScannedForEncodings",
  2751. this->CreateString("0"));
  2752. group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  2753. group->AddAttribute("BuildIndependentTargetsInParallel",
  2754. this->CreateString("YES"));
  2755. std::ostringstream v;
  2756. v << std::setfill('0') << std::setw(4) << XcodeVersion * 10;
  2757. group->AddAttribute("LastUpgradeCheck", this->CreateString(v.str()));
  2758. this->RootObject->AddAttribute("attributes", group);
  2759. if (this->XcodeVersion >= 32) {
  2760. this->RootObject->AddAttribute("compatibilityVersion",
  2761. this->CreateString("Xcode 3.2"));
  2762. } else if (this->XcodeVersion >= 31) {
  2763. this->RootObject->AddAttribute("compatibilityVersion",
  2764. this->CreateString("Xcode 3.1"));
  2765. } else {
  2766. this->RootObject->AddAttribute("compatibilityVersion",
  2767. this->CreateString("Xcode 3.0"));
  2768. }
  2769. // Point Xcode at the top of the source tree.
  2770. {
  2771. std::string pdir =
  2772. this->RelativeToBinary(root->GetCurrentSourceDirectory().c_str());
  2773. this->RootObject->AddAttribute("projectDirPath", this->CreateString(pdir));
  2774. this->RootObject->AddAttribute("projectRoot", this->CreateString(""));
  2775. }
  2776. cmXCodeObject* configlist =
  2777. this->CreateObject(cmXCodeObject::XCConfigurationList);
  2778. cmXCodeObject* buildConfigurations =
  2779. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2780. typedef std::vector<std::pair<std::string, cmXCodeObject*>> Configs;
  2781. Configs configs;
  2782. std::string defaultConfigName;
  2783. for (const auto& name : this->CurrentConfigurationTypes) {
  2784. if (defaultConfigName.empty()) {
  2785. defaultConfigName = name;
  2786. }
  2787. cmXCodeObject* config =
  2788. this->CreateObject(cmXCodeObject::XCBuildConfiguration);
  2789. config->AddAttribute("name", this->CreateString(name));
  2790. configs.push_back(std::make_pair(name, config));
  2791. }
  2792. if (defaultConfigName.empty()) {
  2793. defaultConfigName = "Debug";
  2794. }
  2795. for (auto& config : configs) {
  2796. buildConfigurations->AddObject(config.second);
  2797. }
  2798. configlist->AddAttribute("buildConfigurations", buildConfigurations);
  2799. std::string comment = "Build configuration list for PBXProject";
  2800. comment += " \"";
  2801. comment += this->CurrentProject;
  2802. comment += "\"";
  2803. configlist->SetComment(comment);
  2804. configlist->AddAttribute("defaultConfigurationIsVisible",
  2805. this->CreateString("0"));
  2806. configlist->AddAttribute("defaultConfigurationName",
  2807. this->CreateString(defaultConfigName));
  2808. cmXCodeObject* buildSettings =
  2809. this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  2810. const char* sysroot =
  2811. this->CurrentMakefile->GetDefinition("CMAKE_OSX_SYSROOT");
  2812. const char* deploymentTarget =
  2813. this->CurrentMakefile->GetDefinition("CMAKE_OSX_DEPLOYMENT_TARGET");
  2814. if (sysroot) {
  2815. buildSettings->AddAttribute("SDKROOT", this->CreateString(sysroot));
  2816. }
  2817. // recompute this as it may have been changed since enable language
  2818. this->ComputeArchitectures(this->CurrentMakefile);
  2819. std::string const archs = cmJoin(this->Architectures, " ");
  2820. if (archs.empty()) {
  2821. // Tell Xcode to use NATIVE_ARCH instead of ARCHS.
  2822. buildSettings->AddAttribute("ONLY_ACTIVE_ARCH", this->CreateString("YES"));
  2823. } else {
  2824. // Tell Xcode to use ARCHS (ONLY_ACTIVE_ARCH defaults to NO).
  2825. buildSettings->AddAttribute("ARCHS", this->CreateString(archs));
  2826. }
  2827. if (deploymentTarget && *deploymentTarget) {
  2828. buildSettings->AddAttribute(GetDeploymentPlatform(root->GetMakefile()),
  2829. this->CreateString(deploymentTarget));
  2830. }
  2831. if (!this->GeneratorToolset.empty()) {
  2832. buildSettings->AddAttribute("GCC_VERSION",
  2833. this->CreateString(this->GeneratorToolset));
  2834. }
  2835. if (this->GetLanguageEnabled("Swift")) {
  2836. std::string swiftVersion;
  2837. if (const char* vers = this->CurrentMakefile->GetDefinition(
  2838. "CMAKE_Swift_LANGUAGE_VERSION")) {
  2839. swiftVersion = vers;
  2840. } else if (this->XcodeVersion >= 83) {
  2841. swiftVersion = "3.0";
  2842. } else {
  2843. swiftVersion = "2.3";
  2844. }
  2845. buildSettings->AddAttribute("SWIFT_VERSION",
  2846. this->CreateString(swiftVersion));
  2847. }
  2848. std::string symroot = root->GetCurrentBinaryDirectory();
  2849. symroot += "/build";
  2850. buildSettings->AddAttribute("SYMROOT", this->CreateString(symroot));
  2851. for (auto& config : configs) {
  2852. cmXCodeObject* buildSettingsForCfg = this->CreateFlatClone(buildSettings);
  2853. // Put this last so it can override existing settings
  2854. // Convert "CMAKE_XCODE_ATTRIBUTE_*" variables directly.
  2855. for (const auto& var : this->CurrentMakefile->GetDefinitions()) {
  2856. if (var.find("CMAKE_XCODE_ATTRIBUTE_") == 0) {
  2857. std::string attribute = var.substr(22);
  2858. this->FilterConfigurationAttribute(config.first, attribute);
  2859. if (!attribute.empty()) {
  2860. cmGeneratorExpression ge;
  2861. std::string processed =
  2862. ge.Parse(this->CurrentMakefile->GetDefinition(var))
  2863. ->Evaluate(this->CurrentLocalGenerator, config.first);
  2864. buildSettingsForCfg->AddAttribute(attribute,
  2865. this->CreateString(processed));
  2866. }
  2867. }
  2868. }
  2869. // store per-config buildSettings into configuration object
  2870. config.second->AddAttribute("buildSettings", buildSettingsForCfg);
  2871. }
  2872. this->RootObject->AddAttribute("buildConfigurationList",
  2873. this->CreateObjectReference(configlist));
  2874. std::vector<cmXCodeObject*> targets;
  2875. for (auto& generator : generators) {
  2876. if (!this->CreateXCodeTargets(generator, targets)) {
  2877. return false;
  2878. }
  2879. }
  2880. // loop over all targets and add link and depend info
  2881. for (auto t : targets) {
  2882. this->AddDependAndLinkInformation(t);
  2883. }
  2884. this->CreateXCodeDependHackTarget(targets);
  2885. // now add all targets to the root object
  2886. cmXCodeObject* allTargets = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2887. for (auto t : targets) {
  2888. allTargets->AddObject(t);
  2889. cmXCodeObject* productRef = t->GetObject("productReference");
  2890. if (productRef) {
  2891. productGroupChildren->AddObject(productRef->GetObject());
  2892. }
  2893. }
  2894. this->RootObject->AddAttribute("targets", allTargets);
  2895. return true;
  2896. }
  2897. std::string cmGlobalXCodeGenerator::GetObjectsNormalDirectory(
  2898. const std::string& projName, const std::string& configName,
  2899. const cmGeneratorTarget* t) const
  2900. {
  2901. std::string dir = t->GetLocalGenerator()->GetCurrentBinaryDirectory();
  2902. dir += "/";
  2903. dir += projName;
  2904. dir += ".build/";
  2905. dir += configName;
  2906. dir += "/";
  2907. dir += t->GetName();
  2908. dir += ".build/Objects-normal/";
  2909. return dir;
  2910. }
  2911. void cmGlobalXCodeGenerator::ComputeArchitectures(cmMakefile* mf)
  2912. {
  2913. this->Architectures.clear();
  2914. const char* osxArch = mf->GetDefinition("CMAKE_OSX_ARCHITECTURES");
  2915. const char* sysroot = mf->GetDefinition("CMAKE_OSX_SYSROOT");
  2916. if (osxArch && sysroot) {
  2917. cmSystemTools::ExpandListArgument(std::string(osxArch),
  2918. this->Architectures);
  2919. }
  2920. if (this->Architectures.empty()) {
  2921. // With no ARCHS we use ONLY_ACTIVE_ARCH.
  2922. // Look up the arch that Xcode chooses in this case.
  2923. if (const char* arch = mf->GetDefinition("CMAKE_XCODE_ARCHS")) {
  2924. this->ObjectDirArchDefault = arch;
  2925. // We expect only one arch but choose the first just in case.
  2926. std::string::size_type pos = this->ObjectDirArchDefault.find(';');
  2927. if (pos != std::string::npos) {
  2928. this->ObjectDirArchDefault = this->ObjectDirArchDefault.substr(0, pos);
  2929. }
  2930. }
  2931. }
  2932. this->ComputeObjectDirArch(mf);
  2933. }
  2934. void cmGlobalXCodeGenerator::ComputeObjectDirArch(cmMakefile* mf)
  2935. {
  2936. if (this->Architectures.size() > 1 || this->UseEffectivePlatformName(mf)) {
  2937. this->ObjectDirArch = "$(CURRENT_ARCH)";
  2938. } else if (!this->Architectures.empty()) {
  2939. this->ObjectDirArch = this->Architectures[0];
  2940. } else {
  2941. this->ObjectDirArch = this->ObjectDirArchDefault;
  2942. }
  2943. }
  2944. void cmGlobalXCodeGenerator::CreateXCodeDependHackTarget(
  2945. std::vector<cmXCodeObject*>& targets)
  2946. {
  2947. cmGeneratedFileStream makefileStream(this->CurrentXCodeHackMakefile);
  2948. if (!makefileStream) {
  2949. cmSystemTools::Error("Could not create",
  2950. this->CurrentXCodeHackMakefile.c_str());
  2951. return;
  2952. }
  2953. makefileStream.SetCopyIfDifferent(true);
  2954. // one more pass for external depend information not handled
  2955. // correctly by xcode
  2956. /* clang-format off */
  2957. makefileStream << "# DO NOT EDIT\n";
  2958. makefileStream << "# This makefile makes sure all linkable targets are\n";
  2959. makefileStream << "# up-to-date with anything they link to\n"
  2960. "default:\n"
  2961. "\techo \"Do not invoke directly\"\n"
  2962. "\n";
  2963. /* clang-format on */
  2964. std::set<std::string> dummyRules;
  2965. // Write rules to help Xcode relink things at the right time.
  2966. /* clang-format off */
  2967. makefileStream <<
  2968. "# Rules to remove targets that are older than anything to which they\n"
  2969. "# link. This forces Xcode to relink the targets from scratch. It\n"
  2970. "# does not seem to check these dependencies itself.\n";
  2971. /* clang-format on */
  2972. for (const auto& configName : this->CurrentConfigurationTypes) {
  2973. for (auto target : targets) {
  2974. cmGeneratorTarget* gt = target->GetTarget();
  2975. if (gt->GetType() == cmStateEnums::EXECUTABLE ||
  2976. gt->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  2977. gt->GetType() == cmStateEnums::STATIC_LIBRARY ||
  2978. gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
  2979. gt->GetType() == cmStateEnums::MODULE_LIBRARY) {
  2980. // Declare an entry point for the target post-build phase.
  2981. makefileStream << this->PostBuildMakeTarget(gt->GetName(), configName)
  2982. << ":\n";
  2983. }
  2984. if (gt->GetType() == cmStateEnums::EXECUTABLE ||
  2985. gt->GetType() == cmStateEnums::STATIC_LIBRARY ||
  2986. gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
  2987. gt->GetType() == cmStateEnums::MODULE_LIBRARY) {
  2988. std::string tfull = gt->GetFullPath(configName);
  2989. std::string trel = this->ConvertToRelativeForMake(tfull);
  2990. // Add this target to the post-build phases of its dependencies.
  2991. std::map<std::string, cmXCodeObject::StringVec>::const_iterator y =
  2992. target->GetDependTargets().find(configName);
  2993. if (y != target->GetDependTargets().end()) {
  2994. for (auto const& deptgt : y->second) {
  2995. makefileStream << this->PostBuildMakeTarget(deptgt, configName)
  2996. << ": " << trel << "\n";
  2997. }
  2998. }
  2999. std::vector<cmGeneratorTarget*> objlibs;
  3000. gt->GetObjectLibrariesCMP0026(objlibs);
  3001. for (auto objLib : objlibs) {
  3002. makefileStream << this->PostBuildMakeTarget(objLib->GetName(),
  3003. configName)
  3004. << ": " << trel << "\n";
  3005. }
  3006. // Create a rule for this target.
  3007. makefileStream << trel << ":";
  3008. // List dependencies if any exist.
  3009. std::map<std::string, cmXCodeObject::StringVec>::const_iterator x =
  3010. target->GetDependLibraries().find(configName);
  3011. if (x != target->GetDependLibraries().end()) {
  3012. for (auto const& deplib : x->second) {
  3013. std::string file = this->ConvertToRelativeForMake(deplib);
  3014. makefileStream << "\\\n\t" << file;
  3015. dummyRules.insert(file);
  3016. }
  3017. }
  3018. for (auto objLib : objlibs) {
  3019. const std::string objLibName = objLib->GetName();
  3020. std::string d = this->GetObjectsNormalDirectory(this->CurrentProject,
  3021. configName, objLib);
  3022. d += "lib";
  3023. d += objLibName;
  3024. d += ".a";
  3025. std::string dependency = this->ConvertToRelativeForMake(d);
  3026. makefileStream << "\\\n\t" << dependency;
  3027. dummyRules.insert(dependency);
  3028. }
  3029. // Write the action to remove the target if it is out of date.
  3030. makefileStream << "\n";
  3031. makefileStream << "\t/bin/rm -f "
  3032. << this->ConvertToRelativeForMake(tfull) << "\n";
  3033. // if building for more than one architecture
  3034. // then remove those executables as well
  3035. if (this->Architectures.size() > 1) {
  3036. std::string universal = this->GetObjectsNormalDirectory(
  3037. this->CurrentProject, configName, gt);
  3038. for (const auto& architecture : this->Architectures) {
  3039. std::string universalFile = universal;
  3040. universalFile += architecture;
  3041. universalFile += "/";
  3042. universalFile += gt->GetFullName(configName);
  3043. makefileStream << "\t/bin/rm -f "
  3044. << this->ConvertToRelativeForMake(universalFile)
  3045. << "\n";
  3046. }
  3047. }
  3048. makefileStream << "\n\n";
  3049. }
  3050. }
  3051. }
  3052. makefileStream << "\n\n"
  3053. << "# For each target create a dummy rule"
  3054. << "so the target does not have to exist\n";
  3055. for (auto const& dummyRule : dummyRules) {
  3056. makefileStream << dummyRule << ":\n";
  3057. }
  3058. }
  3059. void cmGlobalXCodeGenerator::OutputXCodeProject(
  3060. cmLocalGenerator* root, std::vector<cmLocalGenerator*>& generators)
  3061. {
  3062. if (generators.empty()) {
  3063. return;
  3064. }
  3065. if (!this->CreateXCodeObjects(root, generators)) {
  3066. return;
  3067. }
  3068. std::string xcodeDir = root->GetCurrentBinaryDirectory();
  3069. xcodeDir += "/";
  3070. xcodeDir += root->GetProjectName();
  3071. xcodeDir += ".xcodeproj";
  3072. cmSystemTools::MakeDirectory(xcodeDir.c_str());
  3073. std::string xcodeProjFile = xcodeDir + "/project.pbxproj";
  3074. cmGeneratedFileStream fout(xcodeProjFile);
  3075. fout.SetCopyIfDifferent(true);
  3076. if (!fout) {
  3077. return;
  3078. }
  3079. this->WriteXCodePBXProj(fout, root, generators);
  3080. if (this->IsGeneratingScheme(root)) {
  3081. this->OutputXCodeSharedSchemes(xcodeDir);
  3082. }
  3083. this->OutputXCodeWorkspaceSettings(xcodeDir, root);
  3084. this->ClearXCodeObjects();
  3085. // Since this call may have created new cache entries, save the cache:
  3086. //
  3087. root->GetMakefile()->GetCMakeInstance()->SaveCache(
  3088. root->GetBinaryDirectory());
  3089. }
  3090. bool cmGlobalXCodeGenerator::IsGeneratingScheme(cmLocalGenerator* root) const
  3091. {
  3092. // Since the lowest available Xcode version for testing was 6.4,
  3093. // I'm setting this as a limit then
  3094. return this->XcodeVersion >= 64 &&
  3095. (root->GetMakefile()->GetCMakeInstance()->GetIsInTryCompile() ||
  3096. root->GetMakefile()->IsOn("CMAKE_XCODE_GENERATE_SCHEME"));
  3097. }
  3098. void cmGlobalXCodeGenerator::OutputXCodeSharedSchemes(
  3099. const std::string& xcProjDir)
  3100. {
  3101. // collect all tests for the targets
  3102. std::map<std::string, cmXCodeScheme::TestObjects> testables;
  3103. for (auto obj : this->XCodeObjects) {
  3104. if (obj->GetType() != cmXCodeObject::OBJECT ||
  3105. obj->GetIsA() != cmXCodeObject::PBXNativeTarget) {
  3106. continue;
  3107. }
  3108. if (!obj->GetTarget()->IsXCTestOnApple()) {
  3109. continue;
  3110. }
  3111. const char* testee = obj->GetTarget()->GetProperty("XCTEST_TESTEE");
  3112. if (!testee) {
  3113. continue;
  3114. }
  3115. testables[testee].push_back(obj);
  3116. }
  3117. // generate scheme
  3118. for (auto obj : this->XCodeObjects) {
  3119. if (obj->GetType() == cmXCodeObject::OBJECT &&
  3120. (obj->GetIsA() == cmXCodeObject::PBXNativeTarget ||
  3121. obj->GetIsA() == cmXCodeObject::PBXAggregateTarget)) {
  3122. const std::string& targetName = obj->GetTarget()->GetName();
  3123. cmXCodeScheme schm(obj, testables[targetName],
  3124. this->CurrentConfigurationTypes, this->XcodeVersion);
  3125. schm.WriteXCodeSharedScheme(xcProjDir,
  3126. this->RelativeToSource(xcProjDir.c_str()));
  3127. }
  3128. }
  3129. }
  3130. void cmGlobalXCodeGenerator::OutputXCodeWorkspaceSettings(
  3131. const std::string& xcProjDir, cmLocalGenerator* root)
  3132. {
  3133. std::string xcodeSharedDataDir = xcProjDir;
  3134. xcodeSharedDataDir += "/project.xcworkspace/xcshareddata";
  3135. cmSystemTools::MakeDirectory(xcodeSharedDataDir);
  3136. std::string workspaceSettingsFile = xcodeSharedDataDir;
  3137. workspaceSettingsFile += "/WorkspaceSettings.xcsettings";
  3138. cmGeneratedFileStream fout(workspaceSettingsFile);
  3139. fout.SetCopyIfDifferent(true);
  3140. if (!fout) {
  3141. return;
  3142. }
  3143. cmXMLWriter xout(fout);
  3144. xout.StartDocument();
  3145. xout.Doctype("plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\""
  3146. "\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"");
  3147. xout.StartElement("plist");
  3148. xout.Attribute("version", "1.0");
  3149. xout.StartElement("dict");
  3150. if (this->XcodeVersion >= 100) {
  3151. xout.Element("key", "BuildSystemType");
  3152. xout.Element("string", "Original");
  3153. }
  3154. if (this->IsGeneratingScheme(root)) {
  3155. xout.Element("key",
  3156. "IDEWorkspaceSharedSettings_AutocreateContextsIfNeeded");
  3157. xout.Element("false");
  3158. }
  3159. xout.EndElement(); // dict
  3160. xout.EndElement(); // plist
  3161. xout.EndDocument();
  3162. }
  3163. void cmGlobalXCodeGenerator::WriteXCodePBXProj(std::ostream& fout,
  3164. cmLocalGenerator*,
  3165. std::vector<cmLocalGenerator*>&)
  3166. {
  3167. SortXCodeObjects();
  3168. fout << "// !$*UTF8*$!\n";
  3169. fout << "{\n";
  3170. cmXCodeObject::Indent(1, fout);
  3171. fout << "archiveVersion = 1;\n";
  3172. cmXCodeObject::Indent(1, fout);
  3173. fout << "classes = {\n";
  3174. cmXCodeObject::Indent(1, fout);
  3175. fout << "};\n";
  3176. cmXCodeObject::Indent(1, fout);
  3177. if (this->XcodeVersion >= 32) {
  3178. fout << "objectVersion = 46;\n";
  3179. } else if (this->XcodeVersion >= 31) {
  3180. fout << "objectVersion = 45;\n";
  3181. } else {
  3182. fout << "objectVersion = 44;\n";
  3183. }
  3184. cmXCode21Object::PrintList(this->XCodeObjects, fout);
  3185. cmXCodeObject::Indent(1, fout);
  3186. fout << "rootObject = " << this->RootObject->GetId()
  3187. << " /* Project object */;\n";
  3188. fout << "}\n";
  3189. }
  3190. const char* cmGlobalXCodeGenerator::GetCMakeCFGIntDir() const
  3191. {
  3192. return "$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)";
  3193. }
  3194. std::string cmGlobalXCodeGenerator::ExpandCFGIntDir(
  3195. const std::string& str, const std::string& config) const
  3196. {
  3197. std::string replace1 = "$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)";
  3198. std::string replace2 = "$(CONFIGURATION)";
  3199. std::string tmp = str;
  3200. for (std::string::size_type i = tmp.find(replace1); i != std::string::npos;
  3201. i = tmp.find(replace1, i)) {
  3202. tmp.replace(i, replace1.size(), config);
  3203. i += config.size();
  3204. }
  3205. for (std::string::size_type i = tmp.find(replace2); i != std::string::npos;
  3206. i = tmp.find(replace2, i)) {
  3207. tmp.replace(i, replace2.size(), config);
  3208. i += config.size();
  3209. }
  3210. return tmp;
  3211. }
  3212. void cmGlobalXCodeGenerator::GetDocumentation(cmDocumentationEntry& entry)
  3213. {
  3214. entry.Name = cmGlobalXCodeGenerator::GetActualName();
  3215. entry.Brief = "Generate Xcode project files.";
  3216. }
  3217. std::string cmGlobalXCodeGenerator::ConvertToRelativeForMake(
  3218. std::string const& p)
  3219. {
  3220. return cmSystemTools::ConvertToOutputPath(p);
  3221. }
  3222. std::string cmGlobalXCodeGenerator::RelativeToSource(const char* p)
  3223. {
  3224. // We force conversion because Xcode breakpoints do not work unless
  3225. // they are in a file named relative to the source tree.
  3226. return cmSystemTools::ForceToRelativePath(
  3227. cmSystemTools::JoinPath(this->ProjectSourceDirectoryComponents), p);
  3228. }
  3229. std::string cmGlobalXCodeGenerator::RelativeToBinary(const char* p)
  3230. {
  3231. return this->CurrentLocalGenerator->ConvertToRelativePath(
  3232. cmSystemTools::JoinPath(this->ProjectOutputDirectoryComponents), p);
  3233. }
  3234. std::string cmGlobalXCodeGenerator::XCodeEscapePath(const std::string& p)
  3235. {
  3236. if (p.find(' ') != std::string::npos) {
  3237. std::string t = "\"";
  3238. t += p;
  3239. t += "\"";
  3240. return t;
  3241. }
  3242. return p;
  3243. }
  3244. void cmGlobalXCodeGenerator::AppendDirectoryForConfig(
  3245. const std::string& prefix, const std::string& config,
  3246. const std::string& suffix, std::string& dir)
  3247. {
  3248. if (!config.empty()) {
  3249. dir += prefix;
  3250. dir += config;
  3251. dir += suffix;
  3252. }
  3253. }
  3254. std::string cmGlobalXCodeGenerator::LookupFlags(
  3255. const std::string& varNamePrefix, const std::string& varNameLang,
  3256. const std::string& varNameSuffix, const std::string& default_flags)
  3257. {
  3258. if (!varNameLang.empty()) {
  3259. std::string varName = varNamePrefix;
  3260. varName += varNameLang;
  3261. varName += varNameSuffix;
  3262. if (const char* varValue = this->CurrentMakefile->GetDefinition(varName)) {
  3263. if (*varValue) {
  3264. return varValue;
  3265. }
  3266. }
  3267. }
  3268. return default_flags;
  3269. }
  3270. void cmGlobalXCodeGenerator::AppendDefines(BuildObjectListOrString& defs,
  3271. const char* defines_list,
  3272. bool dflag)
  3273. {
  3274. // Skip this if there are no definitions.
  3275. if (!defines_list) {
  3276. return;
  3277. }
  3278. // Expand the list of definitions.
  3279. std::vector<std::string> defines;
  3280. cmSystemTools::ExpandListArgument(defines_list, defines);
  3281. // Store the definitions in the string.
  3282. this->AppendDefines(defs, defines, dflag);
  3283. }
  3284. void cmGlobalXCodeGenerator::AppendDefines(
  3285. BuildObjectListOrString& defs, std::vector<std::string> const& defines,
  3286. bool dflag)
  3287. {
  3288. // GCC_PREPROCESSOR_DEFINITIONS is a space-separated list of definitions.
  3289. std::string def;
  3290. for (auto const& define : defines) {
  3291. // Start with -D if requested.
  3292. def = dflag ? "-D" : "";
  3293. def += define;
  3294. // Append the flag with needed escapes.
  3295. std::string tmp;
  3296. this->AppendFlag(tmp, def);
  3297. defs.Add(tmp);
  3298. }
  3299. }
  3300. void cmGlobalXCodeGenerator::AppendFlag(std::string& flags,
  3301. std::string const& flag) const
  3302. {
  3303. // Short-circuit for an empty flag.
  3304. if (flag.empty()) {
  3305. return;
  3306. }
  3307. // Separate from previous flags.
  3308. if (!flags.empty()) {
  3309. flags += " ";
  3310. }
  3311. // Check if the flag needs quoting.
  3312. bool quoteFlag =
  3313. flag.find_first_of("`~!@#$%^&*()+={}[]|:;\"'<>,.? ") != std::string::npos;
  3314. // We escape a flag as follows:
  3315. // - Place each flag in single quotes ''
  3316. // - Escape a single quote as \'
  3317. // - Escape a backslash as \\ since it itself is an escape
  3318. // Note that in the code below we need one more level of escapes for
  3319. // C string syntax in this source file.
  3320. //
  3321. // The final level of escaping is done when the string is stored
  3322. // into the project file by cmXCodeObject::PrintString.
  3323. if (quoteFlag) {
  3324. // Open single quote.
  3325. flags += "'";
  3326. }
  3327. // Flag value with escaped quotes and backslashes.
  3328. for (auto c : flag) {
  3329. if (c == '\'') {
  3330. if (this->XcodeVersion >= 40) {
  3331. flags += "'\\''";
  3332. } else {
  3333. flags += "\\'";
  3334. }
  3335. } else if (c == '\\') {
  3336. flags += "\\\\";
  3337. } else {
  3338. flags += c;
  3339. }
  3340. }
  3341. if (quoteFlag) {
  3342. // Close single quote.
  3343. flags += "'";
  3344. }
  3345. }
  3346. std::string cmGlobalXCodeGenerator::ComputeInfoPListLocation(
  3347. cmGeneratorTarget* target)
  3348. {
  3349. std::string plist = target->GetLocalGenerator()->GetCurrentBinaryDirectory();
  3350. plist += cmake::GetCMakeFilesDirectory();
  3351. plist += "/";
  3352. plist += target->GetName();
  3353. plist += ".dir/Info.plist";
  3354. return plist;
  3355. }
  3356. // Return true if the generated build tree may contain multiple builds.
  3357. // i.e. "Can I build Debug and Release in the same tree?"
  3358. bool cmGlobalXCodeGenerator::IsMultiConfig() const
  3359. {
  3360. // Newer Xcode versions are multi config:
  3361. return true;
  3362. }
  3363. bool cmGlobalXCodeGenerator::HasKnownObjectFileLocation(
  3364. std::string* reason) const
  3365. {
  3366. if (this->ObjectDirArch.find('$') != std::string::npos) {
  3367. if (reason != nullptr) {
  3368. *reason = " under Xcode with multiple architectures";
  3369. }
  3370. return false;
  3371. }
  3372. return true;
  3373. }
  3374. bool cmGlobalXCodeGenerator::UseEffectivePlatformName(cmMakefile* mf) const
  3375. {
  3376. const char* epnValue =
  3377. this->GetCMakeInstance()->GetState()->GetGlobalProperty(
  3378. "XCODE_EMIT_EFFECTIVE_PLATFORM_NAME");
  3379. if (!epnValue) {
  3380. return mf->PlatformIsAppleEmbedded();
  3381. }
  3382. return cmSystemTools::IsOn(epnValue);
  3383. }
  3384. bool cmGlobalXCodeGenerator::ShouldStripResourcePath(cmMakefile*) const
  3385. {
  3386. // Xcode determines Resource location itself
  3387. return true;
  3388. }
  3389. void cmGlobalXCodeGenerator::ComputeTargetObjectDirectory(
  3390. cmGeneratorTarget* gt) const
  3391. {
  3392. std::string configName = this->GetCMakeCFGIntDir();
  3393. std::string dir =
  3394. this->GetObjectsNormalDirectory("$(PROJECT_NAME)", configName, gt);
  3395. dir += this->ObjectDirArch;
  3396. dir += "/";
  3397. gt->ObjectDirectory = dir;
  3398. }
  3399. std::string cmGlobalXCodeGenerator::GetDeploymentPlatform(const cmMakefile* mf)
  3400. {
  3401. switch (mf->GetAppleSDKType()) {
  3402. case cmMakefile::AppleSDK::AppleTVOS:
  3403. case cmMakefile::AppleSDK::AppleTVSimulator:
  3404. return "TVOS_DEPLOYMENT_TARGET";
  3405. case cmMakefile::AppleSDK::IPhoneOS:
  3406. case cmMakefile::AppleSDK::IPhoneSimulator:
  3407. return "IPHONEOS_DEPLOYMENT_TARGET";
  3408. case cmMakefile::AppleSDK::WatchOS:
  3409. case cmMakefile::AppleSDK::WatchSimulator:
  3410. return "WATCHOS_DEPLOYMENT_TARGET";
  3411. case cmMakefile::AppleSDK::MacOS:
  3412. default:
  3413. return "MACOSX_DEPLOYMENT_TARGET";
  3414. }
  3415. }