cmGlobalXCodeGenerator.cxx 172 KB

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