cmGlobalXCodeGenerator.cxx 188 KB

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