cmGlobalXCodeGenerator.cxx 130 KB

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