cmGlobalXCodeGenerator.cxx 130 KB

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