cmGlobalXCodeGenerator.cxx 130 KB

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