cmGlobalXCodeGenerator.cxx 130 KB

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