cmGlobalXCodeGenerator.cxx 199 KB

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