cmGlobalXCodeGenerator.cxx 150 KB

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