cmGlobalXCodeGenerator.cxx 190 KB

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