cmGlobalXCodeGenerator.cxx 193 KB

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