cmGlobalXCodeGenerator.cxx 130 KB

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