1
0

cmGlobalXCodeGenerator.cxx 127 KB

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