cmGlobalXCodeGenerator.cxx 194 KB

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