cmGlobalXCodeGenerator.cxx 130 KB

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