cmGlobalXCodeGenerator.cxx 131 KB

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