cmGlobalXCodeGenerator.cxx 130 KB

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