cmGlobalXCodeGenerator.cxx 127 KB

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