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