cmGlobalXCodeGenerator.cxx 131 KB

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