cmGlobalXCodeGenerator.cxx 125 KB

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