cmGlobalXCodeGenerator.cxx 189 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255
  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. if (gtgt->HaveCxx20ModuleSources()) {
  1239. gtgt->Makefile->IssueMessage(
  1240. MessageType::FATAL_ERROR,
  1241. cmStrCat("The target named \"", gtgt->GetName(),
  1242. "\" contains C++ sources that export modules which is not "
  1243. "supported by the generator"));
  1244. }
  1245. auto& gtgt_visited = this->CommandsVisited[gtgt];
  1246. auto const& deps = this->GetTargetDirectDepends(gtgt);
  1247. for (auto const& d : deps) {
  1248. // Take the union of visited source files of custom commands so far.
  1249. // ComputeTargetOrder ensures our dependencies already visited their
  1250. // custom commands and updated CommandsVisited.
  1251. auto& dep_visited = this->CommandsVisited[d];
  1252. gtgt_visited.insert(dep_visited.begin(), dep_visited.end());
  1253. }
  1254. if (gtgt->GetType() == cmStateEnums::UTILITY ||
  1255. gtgt->GetType() == cmStateEnums::INTERFACE_LIBRARY ||
  1256. gtgt->GetType() == cmStateEnums::GLOBAL_TARGET) {
  1257. cmXCodeObject* t = this->CreateUtilityTarget(gtgt);
  1258. if (!t) {
  1259. return false;
  1260. }
  1261. targets.push_back(t);
  1262. return true;
  1263. }
  1264. // organize the sources
  1265. std::vector<cmSourceFile*> commonSourceFiles;
  1266. if (!gtgt->GetConfigCommonSourceFilesForXcode(commonSourceFiles)) {
  1267. return false;
  1268. }
  1269. // Add CMakeLists.txt file for user convenience.
  1270. this->AddXCodeProjBuildRule(gtgt, commonSourceFiles);
  1271. // Add the Info.plist we are about to generate for an App Bundle.
  1272. if (gtgt->GetPropertyAsBool("MACOSX_BUNDLE")) {
  1273. std::string plist = this->ComputeInfoPListLocation(gtgt);
  1274. cmSourceFile* sf = gtgt->Makefile->GetOrCreateSource(
  1275. plist, true, cmSourceFileLocationKind::Known);
  1276. commonSourceFiles.push_back(sf);
  1277. }
  1278. std::sort(commonSourceFiles.begin(), commonSourceFiles.end(),
  1279. cmSourceFilePathCompare());
  1280. gtgt->ComputeObjectMapping();
  1281. std::vector<cmXCodeObject*> externalObjFiles;
  1282. std::vector<cmXCodeObject*> headerFiles;
  1283. std::vector<cmXCodeObject*> resourceFiles;
  1284. std::vector<cmXCodeObject*> sourceFiles;
  1285. for (auto* sourceFile : commonSourceFiles) {
  1286. cmXCodeObject* xsf = this->CreateXCodeSourceFile(
  1287. this->CurrentLocalGenerator, sourceFile, gtgt);
  1288. cmXCodeObject* fr = xsf->GetAttribute("fileRef");
  1289. cmXCodeObject* filetype =
  1290. fr->GetObject()->GetAttribute("explicitFileType");
  1291. if (!filetype) {
  1292. filetype = fr->GetObject()->GetAttribute("lastKnownFileType");
  1293. }
  1294. cmGeneratorTarget::SourceFileFlags tsFlags =
  1295. gtgt->GetTargetSourceFileFlags(sourceFile);
  1296. if (filetype && filetype->GetString() == "compiled.mach-o.objfile"_s) {
  1297. if (sourceFile->GetObjectLibrary().empty()) {
  1298. externalObjFiles.push_back(xsf);
  1299. }
  1300. } else if (this->IsHeaderFile(sourceFile) ||
  1301. (tsFlags.Type ==
  1302. cmGeneratorTarget::SourceFileTypePrivateHeader) ||
  1303. (tsFlags.Type ==
  1304. cmGeneratorTarget::SourceFileTypePublicHeader)) {
  1305. headerFiles.push_back(xsf);
  1306. } else if (tsFlags.Type == cmGeneratorTarget::SourceFileTypeResource) {
  1307. resourceFiles.push_back(xsf);
  1308. } else if (!sourceFile->GetPropertyAsBool("HEADER_FILE_ONLY") &&
  1309. !gtgt->IsSourceFilePartOfUnityBatch(
  1310. sourceFile->ResolveFullPath())) {
  1311. // Include this file in the build if it has a known language
  1312. // and has not been listed as an ignored extension for this
  1313. // generator.
  1314. if (!this->CurrentLocalGenerator->GetSourceFileLanguage(*sourceFile)
  1315. .empty() &&
  1316. !this->IgnoreFile(sourceFile->GetExtension().c_str())) {
  1317. sourceFiles.push_back(xsf);
  1318. }
  1319. }
  1320. }
  1321. // some build phases only apply to bundles and/or frameworks
  1322. bool isFrameworkTarget = gtgt->IsFrameworkOnApple();
  1323. bool isBundleTarget = gtgt->GetPropertyAsBool("MACOSX_BUNDLE");
  1324. bool isCFBundleTarget = gtgt->IsCFBundleOnApple();
  1325. cmXCodeObject* buildFiles = nullptr;
  1326. // create source build phase
  1327. cmXCodeObject* sourceBuildPhase = nullptr;
  1328. if (!sourceFiles.empty()) {
  1329. sourceBuildPhase = this->CreateObject(cmXCodeObject::PBXSourcesBuildPhase);
  1330. sourceBuildPhase->SetComment("Sources");
  1331. sourceBuildPhase->AddAttribute("buildActionMask",
  1332. this->CreateString("2147483647"));
  1333. buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1334. for (auto& sourceFile : sourceFiles) {
  1335. buildFiles->AddObject(sourceFile);
  1336. }
  1337. sourceBuildPhase->AddAttribute("files", buildFiles);
  1338. sourceBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1339. this->CreateString("0"));
  1340. }
  1341. // create header build phase - only for framework targets
  1342. cmXCodeObject* headerBuildPhase = nullptr;
  1343. if (!headerFiles.empty() && isFrameworkTarget) {
  1344. headerBuildPhase = this->CreateObject(cmXCodeObject::PBXHeadersBuildPhase);
  1345. headerBuildPhase->SetComment("Headers");
  1346. headerBuildPhase->AddAttribute("buildActionMask",
  1347. this->CreateString("2147483647"));
  1348. buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1349. for (auto& headerFile : headerFiles) {
  1350. buildFiles->AddObject(headerFile);
  1351. }
  1352. headerBuildPhase->AddAttribute("files", buildFiles);
  1353. headerBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1354. this->CreateString("0"));
  1355. }
  1356. // create resource build phase - only for framework or bundle targets
  1357. cmXCodeObject* resourceBuildPhase = nullptr;
  1358. if (!resourceFiles.empty() &&
  1359. (isFrameworkTarget || isBundleTarget || isCFBundleTarget)) {
  1360. resourceBuildPhase =
  1361. this->CreateObject(cmXCodeObject::PBXResourcesBuildPhase);
  1362. resourceBuildPhase->SetComment("Resources");
  1363. resourceBuildPhase->AddAttribute("buildActionMask",
  1364. this->CreateString("2147483647"));
  1365. buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1366. for (auto& resourceFile : resourceFiles) {
  1367. buildFiles->AddObject(resourceFile);
  1368. }
  1369. resourceBuildPhase->AddAttribute("files", buildFiles);
  1370. resourceBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1371. this->CreateString("0"));
  1372. }
  1373. // create vector of "non-resource content file" build phases - only for
  1374. // framework or bundle targets
  1375. std::vector<cmXCodeObject*> contentBuildPhases;
  1376. if (isFrameworkTarget || isBundleTarget || isCFBundleTarget) {
  1377. using mapOfVectorOfSourceFiles =
  1378. std::map<std::string, std::vector<cmSourceFile*>>;
  1379. mapOfVectorOfSourceFiles bundleFiles;
  1380. for (auto* sourceFile : commonSourceFiles) {
  1381. cmGeneratorTarget::SourceFileFlags tsFlags =
  1382. gtgt->GetTargetSourceFileFlags(sourceFile);
  1383. if (tsFlags.Type == cmGeneratorTarget::SourceFileTypeMacContent) {
  1384. bundleFiles[tsFlags.MacFolder].push_back(sourceFile);
  1385. }
  1386. }
  1387. for (auto const& keySources : bundleFiles) {
  1388. cmXCodeObject* copyFilesBuildPhase =
  1389. this->CreateObject(cmXCodeObject::PBXCopyFilesBuildPhase);
  1390. copyFilesBuildPhase->SetComment("Copy files");
  1391. copyFilesBuildPhase->AddAttribute("buildActionMask",
  1392. this->CreateString("2147483647"));
  1393. copyFilesBuildPhase->AddAttribute("dstSubfolderSpec",
  1394. this->CreateString("6"));
  1395. std::ostringstream ostr;
  1396. if (gtgt->IsFrameworkOnApple()) {
  1397. // dstPath in frameworks is relative to Versions/<version>
  1398. ostr << keySources.first;
  1399. } else if (keySources.first != "MacOS"_s) {
  1400. if (gtgt->Target->GetMakefile()->PlatformIsAppleEmbedded()) {
  1401. ostr << keySources.first;
  1402. } else {
  1403. // dstPath in bundles is relative to Contents/MacOS
  1404. ostr << "../" << keySources.first;
  1405. }
  1406. }
  1407. copyFilesBuildPhase->AddAttribute("dstPath",
  1408. this->CreateString(ostr.str()));
  1409. copyFilesBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1410. this->CreateString("0"));
  1411. buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1412. copyFilesBuildPhase->AddAttribute("files", buildFiles);
  1413. for (auto* sourceFile : keySources.second) {
  1414. cmXCodeObject* xsf = this->CreateXCodeSourceFile(
  1415. this->CurrentLocalGenerator, sourceFile, gtgt);
  1416. buildFiles->AddObject(xsf);
  1417. }
  1418. contentBuildPhases.push_back(copyFilesBuildPhase);
  1419. }
  1420. }
  1421. // create vector of "resource content file" build phases - only for
  1422. // framework or bundle targets
  1423. if (isFrameworkTarget || isBundleTarget || isCFBundleTarget) {
  1424. using mapOfVectorOfSourceFiles =
  1425. std::map<std::string, std::vector<cmSourceFile*>>;
  1426. mapOfVectorOfSourceFiles bundleFiles;
  1427. for (auto* sourceFile : commonSourceFiles) {
  1428. cmGeneratorTarget::SourceFileFlags tsFlags =
  1429. gtgt->GetTargetSourceFileFlags(sourceFile);
  1430. if (tsFlags.Type == cmGeneratorTarget::SourceFileTypeDeepResource) {
  1431. bundleFiles[tsFlags.MacFolder].push_back(sourceFile);
  1432. }
  1433. }
  1434. for (auto const& keySources : bundleFiles) {
  1435. cmXCodeObject* copyFilesBuildPhase =
  1436. this->CreateObject(cmXCodeObject::PBXCopyFilesBuildPhase);
  1437. copyFilesBuildPhase->SetComment("Copy files");
  1438. copyFilesBuildPhase->AddAttribute("buildActionMask",
  1439. this->CreateString("2147483647"));
  1440. copyFilesBuildPhase->AddAttribute("dstSubfolderSpec",
  1441. this->CreateString("7"));
  1442. copyFilesBuildPhase->AddAttribute("dstPath",
  1443. this->CreateString(keySources.first));
  1444. copyFilesBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1445. this->CreateString("0"));
  1446. buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1447. copyFilesBuildPhase->AddAttribute("files", buildFiles);
  1448. for (auto* sourceFile : keySources.second) {
  1449. cmXCodeObject* xsf = this->CreateXCodeSourceFile(
  1450. this->CurrentLocalGenerator, sourceFile, gtgt);
  1451. buildFiles->AddObject(xsf);
  1452. }
  1453. contentBuildPhases.push_back(copyFilesBuildPhase);
  1454. }
  1455. }
  1456. // Always create Link Binary With Libraries build phase
  1457. cmXCodeObject* frameworkBuildPhase = nullptr;
  1458. frameworkBuildPhase =
  1459. this->CreateObject(cmXCodeObject::PBXFrameworksBuildPhase);
  1460. frameworkBuildPhase->SetComment("Frameworks");
  1461. frameworkBuildPhase->AddAttribute("buildActionMask",
  1462. this->CreateString("2147483647"));
  1463. buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1464. frameworkBuildPhase->AddAttribute("files", buildFiles);
  1465. // Add all collected .o files to this build phase
  1466. for (auto& externalObjFile : externalObjFiles) {
  1467. buildFiles->AddObject(externalObjFile);
  1468. }
  1469. frameworkBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1470. this->CreateString("0"));
  1471. // create list of build phases and create the Xcode target
  1472. cmXCodeObject* buildPhases = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1473. this->CreateCustomCommands(buildPhases, sourceBuildPhase, headerBuildPhase,
  1474. resourceBuildPhase, contentBuildPhases,
  1475. frameworkBuildPhase, gtgt);
  1476. targets.push_back(this->CreateXCodeTarget(gtgt, buildPhases));
  1477. return true;
  1478. }
  1479. void cmGlobalXCodeGenerator::ForceLinkerLanguages()
  1480. {
  1481. for (const auto& localGenerator : this->LocalGenerators) {
  1482. // All targets depend on the build-system check target.
  1483. for (const auto& tgt : localGenerator->GetGeneratorTargets()) {
  1484. // This makes sure all targets link using the proper language.
  1485. this->ForceLinkerLanguage(tgt.get());
  1486. }
  1487. }
  1488. }
  1489. void cmGlobalXCodeGenerator::ForceLinkerLanguage(cmGeneratorTarget* gtgt)
  1490. {
  1491. // This matters only for targets that link.
  1492. if (gtgt->GetType() != cmStateEnums::EXECUTABLE &&
  1493. gtgt->GetType() != cmStateEnums::SHARED_LIBRARY &&
  1494. gtgt->GetType() != cmStateEnums::MODULE_LIBRARY) {
  1495. return;
  1496. }
  1497. std::string llang = gtgt->GetLinkerLanguage("NOCONFIG");
  1498. if (llang.empty()) {
  1499. return;
  1500. }
  1501. // If the language is compiled as a source trust Xcode to link with it.
  1502. for (auto const& Language :
  1503. gtgt
  1504. ->GetLinkImplementation("NOCONFIG",
  1505. cmGeneratorTarget::LinkInterfaceFor::Link)
  1506. ->Languages) {
  1507. if (Language == llang) {
  1508. return;
  1509. }
  1510. }
  1511. // Allow empty source file list for iOS Sticker packs
  1512. if (const char* productType = GetTargetProductType(gtgt)) {
  1513. if (strcmp(productType,
  1514. "com.apple.product-type.app-extension.messages-sticker-pack") ==
  1515. 0) {
  1516. return;
  1517. }
  1518. }
  1519. // Add an empty source file to the target that compiles with the
  1520. // linker language. This should convince Xcode to choose the proper
  1521. // language.
  1522. cmMakefile* mf = gtgt->Target->GetMakefile();
  1523. std::string fname = cmStrCat(
  1524. gtgt->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/CMakeFiles/",
  1525. gtgt->GetName(), "-CMakeForceLinker.", cmSystemTools::LowerCase(llang));
  1526. {
  1527. cmGeneratedFileStream fout(fname);
  1528. fout << '\n';
  1529. }
  1530. if (cmSourceFile* sf = mf->GetOrCreateSource(fname)) {
  1531. sf->SetProperty("LANGUAGE", llang);
  1532. gtgt->AddSource(fname);
  1533. }
  1534. }
  1535. bool cmGlobalXCodeGenerator::IsHeaderFile(cmSourceFile* sf)
  1536. {
  1537. return cm::contains(this->CMakeInstance->GetHeaderExtensions(),
  1538. sf->GetExtension());
  1539. }
  1540. cmXCodeObject* cmGlobalXCodeGenerator::CreateLegacyRunScriptBuildPhase(
  1541. const char* name, const char* name2, cmGeneratorTarget* target,
  1542. const std::vector<cmCustomCommand>& commands)
  1543. {
  1544. if (commands.empty() && strcmp(name, "CMake ReRun") != 0) {
  1545. return nullptr;
  1546. }
  1547. cmXCodeObject* buildPhase =
  1548. this->CreateObject(cmXCodeObject::PBXShellScriptBuildPhase);
  1549. buildPhase->AddAttribute("buildActionMask",
  1550. this->CreateString("2147483647"));
  1551. cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1552. buildPhase->AddAttribute("files", buildFiles);
  1553. buildPhase->AddAttribute("name", this->CreateString(name));
  1554. buildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1555. this->CreateString("0"));
  1556. buildPhase->AddAttribute("shellPath", this->CreateString("/bin/sh"));
  1557. this->AddCommandsToBuildPhase(buildPhase, target, commands, name2);
  1558. return buildPhase;
  1559. }
  1560. void cmGlobalXCodeGenerator::CreateCustomCommands(
  1561. cmXCodeObject* buildPhases, cmXCodeObject* sourceBuildPhase,
  1562. cmXCodeObject* headerBuildPhase, cmXCodeObject* resourceBuildPhase,
  1563. std::vector<cmXCodeObject*> const& contentBuildPhases,
  1564. cmXCodeObject* frameworkBuildPhase, cmGeneratorTarget* gtgt)
  1565. {
  1566. std::vector<cmCustomCommand> const& prebuild = gtgt->GetPreBuildCommands();
  1567. std::vector<cmCustomCommand> const& prelink = gtgt->GetPreLinkCommands();
  1568. std::vector<cmCustomCommand> postbuild = gtgt->GetPostBuildCommands();
  1569. if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY &&
  1570. !gtgt->IsFrameworkOnApple()) {
  1571. std::string str_file = cmStrCat("$<TARGET_FILE:", gtgt->GetName(), '>');
  1572. std::string str_so_file =
  1573. cmStrCat("$<TARGET_SONAME_FILE:", gtgt->GetName(), '>');
  1574. std::string str_link_file =
  1575. cmStrCat("$<TARGET_LINKER_LIBRARY_FILE:", gtgt->GetName(), '>');
  1576. cmCustomCommandLines cmd = cmMakeSingleCommandLine(
  1577. { cmSystemTools::GetCMakeCommand(), "-E", "cmake_symlink_library",
  1578. str_file, str_so_file, str_link_file });
  1579. cmCustomCommand command;
  1580. command.SetCommandLines(cmd);
  1581. command.SetComment("Creating symlinks");
  1582. command.SetWorkingDirectory("");
  1583. command.SetBacktrace(this->CurrentMakefile->GetBacktrace());
  1584. command.SetStdPipesUTF8(true);
  1585. postbuild.push_back(std::move(command));
  1586. }
  1587. if (gtgt->HasImportLibrary("") && !gtgt->IsFrameworkOnApple()) {
  1588. // create symbolic links for .tbd file
  1589. std::string file = cmStrCat("$<TARGET_IMPORT_FILE:", gtgt->GetName(), '>');
  1590. std::string soFile =
  1591. cmStrCat("$<TARGET_SONAME_IMPORT_FILE:", gtgt->GetName(), '>');
  1592. std::string linkFile =
  1593. cmStrCat("$<TARGET_LINKER_IMPORT_FILE:", gtgt->GetName(), '>');
  1594. cmCustomCommandLines symlink_command = cmMakeSingleCommandLine(
  1595. { cmSystemTools::GetCMakeCommand(), "-E", "cmake_symlink_library", file,
  1596. soFile, linkFile });
  1597. cmCustomCommand command;
  1598. command.SetCommandLines(symlink_command);
  1599. command.SetComment("Creating import symlinks");
  1600. command.SetWorkingDirectory("");
  1601. command.SetBacktrace(this->CurrentMakefile->GetBacktrace());
  1602. command.SetStdPipesUTF8(true);
  1603. postbuild.push_back(std::move(command));
  1604. }
  1605. cmXCodeObject* legacyCustomCommandsBuildPhase = nullptr;
  1606. cmXCodeObject* preBuildPhase = nullptr;
  1607. cmXCodeObject* preLinkPhase = nullptr;
  1608. cmXCodeObject* postBuildPhase = nullptr;
  1609. if (this->XcodeBuildSystem >= BuildSystem::Twelve) {
  1610. // create prebuild phase
  1611. preBuildPhase =
  1612. this->CreateRunScriptBuildPhase("CMake PreBuild Rules", gtgt, prebuild);
  1613. // create prelink phase
  1614. preLinkPhase =
  1615. this->CreateRunScriptBuildPhase("CMake PreLink Rules", gtgt, prelink);
  1616. // create postbuild phase
  1617. postBuildPhase = this->CreateRunScriptBuildPhase("CMake PostBuild Rules",
  1618. gtgt, postbuild);
  1619. } else {
  1620. std::vector<cmSourceFile*> classes;
  1621. if (!gtgt->GetConfigCommonSourceFilesForXcode(classes)) {
  1622. return;
  1623. }
  1624. // add all the sources
  1625. std::vector<cmCustomCommand> commands;
  1626. auto& visited = this->CommandsVisited[gtgt];
  1627. for (auto* sourceFile : classes) {
  1628. if (sourceFile->GetCustomCommand() &&
  1629. visited.insert(sourceFile).second) {
  1630. commands.push_back(*sourceFile->GetCustomCommand());
  1631. }
  1632. }
  1633. // create custom commands phase
  1634. legacyCustomCommandsBuildPhase = this->CreateLegacyRunScriptBuildPhase(
  1635. "CMake Rules", "cmakeRulesBuildPhase", gtgt, commands);
  1636. // create prebuild phase
  1637. preBuildPhase = this->CreateLegacyRunScriptBuildPhase(
  1638. "CMake PreBuild Rules", "preBuildCommands", gtgt, prebuild);
  1639. // create prelink phase
  1640. preLinkPhase = this->CreateLegacyRunScriptBuildPhase(
  1641. "CMake PreLink Rules", "preLinkCommands", gtgt, prelink);
  1642. // create postbuild phase
  1643. postBuildPhase = this->CreateLegacyRunScriptBuildPhase(
  1644. "CMake PostBuild Rules", "postBuildPhase", gtgt, postbuild);
  1645. }
  1646. // The order here is the order they will be built in.
  1647. // The order "headers, resources, sources" mimics a native project generated
  1648. // from an xcode template...
  1649. //
  1650. if (preBuildPhase) {
  1651. buildPhases->AddObject(preBuildPhase);
  1652. }
  1653. if (legacyCustomCommandsBuildPhase) {
  1654. buildPhases->AddObject(legacyCustomCommandsBuildPhase);
  1655. }
  1656. if (this->XcodeBuildSystem >= BuildSystem::Twelve) {
  1657. this->CreateRunScriptBuildPhases(buildPhases, gtgt);
  1658. }
  1659. if (headerBuildPhase) {
  1660. buildPhases->AddObject(headerBuildPhase);
  1661. }
  1662. if (resourceBuildPhase) {
  1663. buildPhases->AddObject(resourceBuildPhase);
  1664. }
  1665. for (auto* obj : contentBuildPhases) {
  1666. buildPhases->AddObject(obj);
  1667. }
  1668. if (sourceBuildPhase) {
  1669. buildPhases->AddObject(sourceBuildPhase);
  1670. }
  1671. if (preLinkPhase) {
  1672. buildPhases->AddObject(preLinkPhase);
  1673. }
  1674. if (frameworkBuildPhase) {
  1675. buildPhases->AddObject(frameworkBuildPhase);
  1676. }
  1677. // When this build phase is present, it must be last. More build phases may
  1678. // be added later for embedding things and they will insert themselves just
  1679. // before this last build phase.
  1680. if (postBuildPhase) {
  1681. buildPhases->AddObject(postBuildPhase);
  1682. }
  1683. }
  1684. void cmGlobalXCodeGenerator::CreateRunScriptBuildPhases(
  1685. cmXCodeObject* buildPhases, cmGeneratorTarget const* gt)
  1686. {
  1687. std::vector<cmSourceFile*> sources;
  1688. if (!gt->GetConfigCommonSourceFilesForXcode(sources)) {
  1689. return;
  1690. }
  1691. auto& visited = this->CommandsVisited[gt];
  1692. for (auto* sf : sources) {
  1693. this->CreateRunScriptBuildPhases(buildPhases, sf, gt, visited);
  1694. }
  1695. }
  1696. void cmGlobalXCodeGenerator::CreateRunScriptBuildPhases(
  1697. cmXCodeObject* buildPhases, cmSourceFile const* sf,
  1698. cmGeneratorTarget const* gt, std::set<cmSourceFile const*>& visited)
  1699. {
  1700. cmCustomCommand const* cc = sf->GetCustomCommand();
  1701. if (cc && visited.insert(sf).second) {
  1702. this->CustomCommandRoots[sf].insert(gt);
  1703. if (std::vector<cmSourceFile*> const* depends = gt->GetSourceDepends(sf)) {
  1704. for (cmSourceFile const* di : *depends) {
  1705. this->CreateRunScriptBuildPhases(buildPhases, di, gt, visited);
  1706. }
  1707. }
  1708. cmXCodeObject* buildPhase = this->CreateRunScriptBuildPhase(sf, gt, *cc);
  1709. buildPhases->AddObject(buildPhase);
  1710. }
  1711. }
  1712. cmXCodeObject* cmGlobalXCodeGenerator::CreateRunScriptBuildPhase(
  1713. cmSourceFile const* sf, cmGeneratorTarget const* gt,
  1714. cmCustomCommand const& cc)
  1715. {
  1716. std::set<std::string> allConfigInputs;
  1717. std::set<std::string> allConfigOutputs;
  1718. cmXCodeObject* buildPhase =
  1719. this->CreateObject(cmXCodeObject::PBXShellScriptBuildPhase,
  1720. cmStrCat(gt->GetName(), ':', sf->GetFullPath()));
  1721. auto depfilesDirectory = cmStrCat(
  1722. gt->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/CMakeFiles/d/");
  1723. auto depfilesPrefix = cmStrCat(depfilesDirectory, buildPhase->GetId(), '.');
  1724. std::string shellScript = "set -e\n";
  1725. for (std::string const& configName : this->CurrentConfigurationTypes) {
  1726. cmCustomCommandGenerator ccg(
  1727. cc, configName, this->CurrentLocalGenerator, true, {},
  1728. [&depfilesPrefix](const std::string& config, const std::string&)
  1729. -> std::string { return cmStrCat(depfilesPrefix, config, ".d"); });
  1730. std::vector<std::string> realDepends;
  1731. realDepends.reserve(ccg.GetDepends().size());
  1732. for (auto const& d : ccg.GetDepends()) {
  1733. std::string dep;
  1734. if (this->CurrentLocalGenerator->GetRealDependency(d, configName, dep)) {
  1735. realDepends.emplace_back(std::move(dep));
  1736. }
  1737. }
  1738. allConfigInputs.insert(realDepends.begin(), realDepends.end());
  1739. allConfigOutputs.insert(ccg.GetByproducts().begin(),
  1740. ccg.GetByproducts().end());
  1741. allConfigOutputs.insert(ccg.GetOutputs().begin(), ccg.GetOutputs().end());
  1742. shellScript =
  1743. cmStrCat(shellScript, R"(if test "$CONFIGURATION" = ")", configName,
  1744. "\"; then :\n", this->ConstructScript(ccg), "fi\n");
  1745. }
  1746. if (!cc.GetDepfile().empty()) {
  1747. buildPhase->AddAttribute(
  1748. "dependencyFile",
  1749. this->CreateString(cmStrCat(depfilesDirectory, buildPhase->GetId(),
  1750. ".$(CONFIGURATION).d")));
  1751. // to avoid spurious errors during first build, create empty dependency
  1752. // files
  1753. cmSystemTools::MakeDirectory(depfilesDirectory);
  1754. for (std::string const& configName : this->CurrentConfigurationTypes) {
  1755. auto file = cmStrCat(depfilesPrefix, configName, ".d");
  1756. if (!cmSystemTools::FileExists(file)) {
  1757. cmSystemTools::Touch(file, true);
  1758. }
  1759. }
  1760. }
  1761. buildPhase->AddAttribute("buildActionMask",
  1762. this->CreateString("2147483647"));
  1763. cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1764. buildPhase->AddAttribute("files", buildFiles);
  1765. {
  1766. std::string name;
  1767. if (!allConfigOutputs.empty()) {
  1768. name = cmStrCat("Generate ",
  1769. this->RelativeToBinary(*allConfigOutputs.begin()));
  1770. } else {
  1771. name = sf->GetLocation().GetName();
  1772. }
  1773. buildPhase->AddAttribute("name", this->CreateString(name));
  1774. }
  1775. buildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1776. this->CreateString("0"));
  1777. buildPhase->AddAttribute("shellPath", this->CreateString("/bin/sh"));
  1778. buildPhase->AddAttribute("shellScript", this->CreateString(shellScript));
  1779. buildPhase->AddAttribute("showEnvVarsInLog", this->CreateString("0"));
  1780. bool symbolic = false;
  1781. {
  1782. cmXCodeObject* inputPaths = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1783. for (std::string const& i : allConfigInputs) {
  1784. inputPaths->AddUniqueObject(this->CreateString(i));
  1785. if (!symbolic) {
  1786. if (cmSourceFile* isf =
  1787. gt->GetLocalGenerator()->GetMakefile()->GetSource(
  1788. i, cmSourceFileLocationKind::Known)) {
  1789. symbolic = isf->GetPropertyAsBool("SYMBOLIC");
  1790. }
  1791. }
  1792. }
  1793. buildPhase->AddAttribute("inputPaths", inputPaths);
  1794. }
  1795. {
  1796. cmXCodeObject* outputPaths =
  1797. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1798. for (std::string const& o : allConfigOutputs) {
  1799. outputPaths->AddUniqueObject(this->CreateString(o));
  1800. if (!symbolic) {
  1801. if (cmSourceFile* osf =
  1802. gt->GetLocalGenerator()->GetMakefile()->GetSource(
  1803. o, cmSourceFileLocationKind::Known)) {
  1804. symbolic = osf->GetPropertyAsBool("SYMBOLIC");
  1805. }
  1806. }
  1807. }
  1808. buildPhase->AddAttribute("outputPaths", outputPaths);
  1809. }
  1810. if (symbolic) {
  1811. buildPhase->AddAttribute("alwaysOutOfDate", this->CreateString("1"));
  1812. }
  1813. return buildPhase;
  1814. }
  1815. cmXCodeObject* cmGlobalXCodeGenerator::CreateRunScriptBuildPhase(
  1816. std::string const& name, cmGeneratorTarget const* gt,
  1817. std::vector<cmCustomCommand> const& commands)
  1818. {
  1819. if (commands.empty()) {
  1820. return nullptr;
  1821. }
  1822. std::set<std::string> allConfigOutputs;
  1823. std::string shellScript = "set -e\n";
  1824. for (std::string const& configName : this->CurrentConfigurationTypes) {
  1825. shellScript = cmStrCat(shellScript, R"(if test "$CONFIGURATION" = ")",
  1826. configName, "\"; then :\n");
  1827. for (cmCustomCommand const& cc : commands) {
  1828. cmCustomCommandGenerator ccg(cc, configName,
  1829. this->CurrentLocalGenerator);
  1830. shellScript = cmStrCat(shellScript, this->ConstructScript(ccg));
  1831. allConfigOutputs.insert(ccg.GetByproducts().begin(),
  1832. ccg.GetByproducts().end());
  1833. }
  1834. shellScript = cmStrCat(shellScript, "fi\n");
  1835. }
  1836. cmXCodeObject* buildPhase =
  1837. this->CreateObject(cmXCodeObject::PBXShellScriptBuildPhase,
  1838. cmStrCat(gt->GetName(), ':', name));
  1839. buildPhase->AddAttribute("buildActionMask",
  1840. this->CreateString("2147483647"));
  1841. cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1842. buildPhase->AddAttribute("files", buildFiles);
  1843. buildPhase->AddAttribute("name", this->CreateString(name));
  1844. buildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1845. this->CreateString("0"));
  1846. buildPhase->AddAttribute("shellPath", this->CreateString("/bin/sh"));
  1847. buildPhase->AddAttribute("shellScript", this->CreateString(shellScript));
  1848. buildPhase->AddAttribute("showEnvVarsInLog", this->CreateString("0"));
  1849. {
  1850. cmXCodeObject* outputPaths =
  1851. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1852. for (std::string const& o : allConfigOutputs) {
  1853. outputPaths->AddUniqueObject(this->CreateString(o));
  1854. }
  1855. buildPhase->AddAttribute("outputPaths", outputPaths);
  1856. }
  1857. buildPhase->AddAttribute("alwaysOutOfDate", this->CreateString("1"));
  1858. return buildPhase;
  1859. }
  1860. namespace {
  1861. void ReplaceScriptVars(std::string& cmd)
  1862. {
  1863. cmSystemTools::ReplaceString(cmd, "$(CONFIGURATION)", "$CONFIGURATION");
  1864. cmSystemTools::ReplaceString(cmd, "$(EFFECTIVE_PLATFORM_NAME)",
  1865. "$EFFECTIVE_PLATFORM_NAME");
  1866. }
  1867. }
  1868. std::string cmGlobalXCodeGenerator::ConstructScript(
  1869. cmCustomCommandGenerator const& ccg)
  1870. {
  1871. std::string script;
  1872. cmLocalGenerator* lg = this->CurrentLocalGenerator;
  1873. std::string wd = ccg.GetWorkingDirectory();
  1874. if (wd.empty()) {
  1875. wd = lg->GetCurrentBinaryDirectory();
  1876. }
  1877. wd = lg->ConvertToOutputFormat(wd, cmOutputConverter::SHELL);
  1878. ReplaceScriptVars(wd);
  1879. script = cmStrCat(script, " cd ", wd, '\n');
  1880. for (unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) {
  1881. std::string cmd = ccg.GetCommand(c);
  1882. if (cmd.empty()) {
  1883. continue;
  1884. }
  1885. cmSystemTools::ReplaceString(cmd, "/./", "/");
  1886. cmd = lg->ConvertToOutputFormat(cmd, cmOutputConverter::SHELL);
  1887. ccg.AppendArguments(c, cmd);
  1888. ReplaceScriptVars(cmd);
  1889. script = cmStrCat(script, " ", cmd, '\n');
  1890. }
  1891. return script;
  1892. }
  1893. // This function removes each occurrence of the flag and returns the last one
  1894. // (i.e., the dominant flag in GCC)
  1895. std::string cmGlobalXCodeGenerator::ExtractFlag(const char* flag,
  1896. std::string& flags)
  1897. {
  1898. std::string retFlag;
  1899. std::string::size_type lastOccurancePos = flags.rfind(flag);
  1900. bool saved = false;
  1901. while (lastOccurancePos != std::string::npos) {
  1902. // increment pos, we use lastOccurancePos to reduce search space on next
  1903. // inc
  1904. std::string::size_type pos = lastOccurancePos;
  1905. if (pos == 0 || flags[pos - 1] == ' ') {
  1906. while (pos < flags.size() && flags[pos] != ' ') {
  1907. if (!saved) {
  1908. retFlag += flags[pos];
  1909. }
  1910. flags[pos] = ' ';
  1911. pos++;
  1912. }
  1913. saved = true;
  1914. }
  1915. // decrement lastOccurancePos while making sure we don't loop around
  1916. // and become a very large positive number since size_type is unsigned
  1917. lastOccurancePos = lastOccurancePos == 0 ? 0 : lastOccurancePos - 1;
  1918. lastOccurancePos = flags.rfind(flag, lastOccurancePos);
  1919. }
  1920. return retFlag;
  1921. }
  1922. // This function removes each matching occurrence of the expression and
  1923. // returns the last one (i.e., the dominant flag in GCC)
  1924. std::string cmGlobalXCodeGenerator::ExtractFlagRegex(const char* exp,
  1925. int matchIndex,
  1926. std::string& flags)
  1927. {
  1928. std::string retFlag;
  1929. cmsys::RegularExpression regex(exp);
  1930. assert(regex.is_valid());
  1931. if (!regex.is_valid()) {
  1932. return retFlag;
  1933. }
  1934. std::string::size_type offset = 0;
  1935. while (regex.find(&flags[offset])) {
  1936. const std::string::size_type startPos = offset + regex.start(matchIndex);
  1937. const std::string::size_type endPos = offset + regex.end(matchIndex);
  1938. const std::string::size_type size = endPos - startPos;
  1939. offset = startPos + 1;
  1940. retFlag.assign(flags, startPos, size);
  1941. flags.replace(startPos, size, size, ' ');
  1942. }
  1943. return retFlag;
  1944. }
  1945. //----------------------------------------------------------------------------
  1946. // This function strips off Xcode attributes that do not target the current
  1947. // configuration
  1948. void cmGlobalXCodeGenerator::FilterConfigurationAttribute(
  1949. std::string const& configName, std::string& attribute)
  1950. {
  1951. // Handle [variant=<config>] condition explicitly here.
  1952. std::string::size_type beginVariant = attribute.find("[variant=");
  1953. if (beginVariant == std::string::npos) {
  1954. // There is no variant in this attribute.
  1955. return;
  1956. }
  1957. std::string::size_type endVariant = attribute.find(']', beginVariant + 9);
  1958. if (endVariant == std::string::npos) {
  1959. // There is no terminating bracket.
  1960. return;
  1961. }
  1962. // Compare the variant to the configuration.
  1963. std::string variant =
  1964. attribute.substr(beginVariant + 9, endVariant - beginVariant - 9);
  1965. if (variant == configName) {
  1966. // The variant matches the configuration so use this
  1967. // attribute but drop the [variant=<config>] condition.
  1968. attribute.erase(beginVariant, endVariant - beginVariant + 1);
  1969. } else {
  1970. // The variant does not match the configuration so
  1971. // do not use this attribute.
  1972. attribute.clear();
  1973. }
  1974. }
  1975. void cmGlobalXCodeGenerator::AddCommandsToBuildPhase(
  1976. cmXCodeObject* buildphase, cmGeneratorTarget* target,
  1977. std::vector<cmCustomCommand> const& commands, const char* name)
  1978. {
  1979. std::string dir = cmStrCat(
  1980. this->CurrentLocalGenerator->GetCurrentBinaryDirectory(), "/CMakeScripts");
  1981. cmSystemTools::MakeDirectory(dir);
  1982. std::string makefile =
  1983. cmStrCat(dir, '/', target->GetName(), '_', name, ".make");
  1984. for (const auto& currentConfig : this->CurrentConfigurationTypes) {
  1985. this->CreateCustomRulesMakefile(makefile.c_str(), target, commands,
  1986. currentConfig);
  1987. }
  1988. std::string cdir = this->CurrentLocalGenerator->GetCurrentBinaryDirectory();
  1989. cdir = this->ConvertToRelativeForMake(cdir);
  1990. std::string makecmd = cmStrCat(
  1991. "make -C ", cdir, " -f ",
  1992. this->ConvertToRelativeForMake(cmStrCat(makefile, "$CONFIGURATION")),
  1993. " OBJDIR=$(basename \"$OBJECT_FILE_DIR_normal\") all");
  1994. buildphase->AddAttribute("shellScript", this->CreateString(makecmd));
  1995. buildphase->AddAttribute("showEnvVarsInLog", this->CreateString("0"));
  1996. }
  1997. void cmGlobalXCodeGenerator::CreateCustomRulesMakefile(
  1998. const char* makefileBasename, cmGeneratorTarget* target,
  1999. std::vector<cmCustomCommand> const& commands, const std::string& configName)
  2000. {
  2001. std::string makefileName = cmStrCat(makefileBasename, configName);
  2002. cmGeneratedFileStream makefileStream(makefileName);
  2003. if (!makefileStream) {
  2004. return;
  2005. }
  2006. makefileStream.SetCopyIfDifferent(true);
  2007. makefileStream << "# Generated by CMake, DO NOT EDIT\n"
  2008. "# Custom rules for "
  2009. << target->GetName() << '\n';
  2010. // disable the implicit rules
  2011. makefileStream << ".SUFFIXES: "
  2012. "\n";
  2013. // have all depend on all outputs
  2014. makefileStream << "all: ";
  2015. std::map<const cmCustomCommand*, std::string> tname;
  2016. int count = 0;
  2017. for (auto const& command : commands) {
  2018. cmCustomCommandGenerator ccg(command, configName,
  2019. this->CurrentLocalGenerator);
  2020. if (ccg.GetNumberOfCommands() > 0) {
  2021. const std::vector<std::string>& outputs = ccg.GetOutputs();
  2022. if (!outputs.empty()) {
  2023. for (auto const& output : outputs) {
  2024. makefileStream << "\\\n\t" << this->ConvertToRelativeForMake(output);
  2025. }
  2026. } else {
  2027. std::ostringstream str;
  2028. str << "_buildpart_" << count++;
  2029. tname[&ccg.GetCC()] = cmStrCat(target->GetName(), str.str());
  2030. makefileStream << "\\\n\t" << tname[&ccg.GetCC()];
  2031. }
  2032. }
  2033. }
  2034. makefileStream << "\n\n";
  2035. auto depfilesDirectory =
  2036. cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(),
  2037. "/CMakeFiles/d/");
  2038. for (auto const& command : commands) {
  2039. cmCustomCommandGenerator ccg(
  2040. command, configName, this->CurrentLocalGenerator, true, {},
  2041. [this, &depfilesDirectory](const std::string& config,
  2042. const std::string& file) -> std::string {
  2043. return cmStrCat(
  2044. depfilesDirectory,
  2045. this->GetObjectId(cmXCodeObject::PBXShellScriptBuildPhase, file),
  2046. '.', config, ".d");
  2047. });
  2048. auto depfile = ccg.GetInternalDepfile();
  2049. if (!depfile.empty()) {
  2050. makefileStream << "include "
  2051. << cmSystemTools::ConvertToOutputPath(depfile) << "\n\n";
  2052. cmSystemTools::MakeDirectory(depfilesDirectory);
  2053. if (!cmSystemTools::FileExists(depfile)) {
  2054. cmSystemTools::Touch(depfile, true);
  2055. }
  2056. }
  2057. std::vector<std::string> realDepends;
  2058. realDepends.reserve(ccg.GetDepends().size());
  2059. for (auto const& d : ccg.GetDepends()) {
  2060. std::string dep;
  2061. if (this->CurrentLocalGenerator->GetRealDependency(d, configName, dep)) {
  2062. realDepends.emplace_back(std::move(dep));
  2063. }
  2064. }
  2065. if (ccg.GetNumberOfCommands() > 0) {
  2066. makefileStream << '\n';
  2067. const std::vector<std::string>& outputs = ccg.GetOutputs();
  2068. if (!outputs.empty()) {
  2069. // There is at least one output, start the rule for it
  2070. const char* sep = "";
  2071. for (auto const& output : outputs) {
  2072. makefileStream << sep << this->ConvertToRelativeForMake(output);
  2073. sep = " ";
  2074. }
  2075. makefileStream << ": ";
  2076. } else {
  2077. // There are no outputs. Use the generated force rule name.
  2078. makefileStream << tname[&ccg.GetCC()] << ": ";
  2079. }
  2080. for (auto const& dep : realDepends) {
  2081. makefileStream << "\\\n" << this->ConvertToRelativeForMake(dep);
  2082. }
  2083. makefileStream << '\n';
  2084. if (cm::optional<std::string> comment = ccg.GetComment()) {
  2085. std::string echo_cmd =
  2086. cmStrCat("echo ",
  2087. (this->CurrentLocalGenerator->EscapeForShell(
  2088. *comment, ccg.GetCC().GetEscapeAllowMakeVars())));
  2089. makefileStream << '\t' << echo_cmd << '\n';
  2090. }
  2091. // Add each command line to the set of commands.
  2092. for (unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) {
  2093. // Build the command line in a single string.
  2094. std::string cmd2 = ccg.GetCommand(c);
  2095. cmSystemTools::ReplaceString(cmd2, "/./", "/");
  2096. cmd2 = this->ConvertToRelativeForMake(cmd2);
  2097. std::string cmd;
  2098. std::string wd = ccg.GetWorkingDirectory();
  2099. if (!wd.empty()) {
  2100. cmd += "cd ";
  2101. cmd += this->ConvertToRelativeForMake(wd);
  2102. cmd += " && ";
  2103. }
  2104. cmd += cmd2;
  2105. ccg.AppendArguments(c, cmd);
  2106. makefileStream << '\t' << cmd << '\n';
  2107. }
  2108. // Symbolic inputs are not expected to exist, so add dummy rules.
  2109. for (auto const& dep : realDepends) {
  2110. if (cmSourceFile* dsf =
  2111. target->GetLocalGenerator()->GetMakefile()->GetSource(
  2112. dep, cmSourceFileLocationKind::Known)) {
  2113. if (dsf->GetPropertyAsBool("SYMBOLIC")) {
  2114. makefileStream << this->ConvertToRelativeForMake(dep) << ":\n";
  2115. }
  2116. }
  2117. }
  2118. }
  2119. }
  2120. }
  2121. void cmGlobalXCodeGenerator::AddPositionIndependentLinkAttribute(
  2122. cmGeneratorTarget* target, cmXCodeObject* buildSettings,
  2123. const std::string& configName)
  2124. {
  2125. // For now, only EXECUTABLE is concerned
  2126. if (target->GetType() != cmStateEnums::EXECUTABLE) {
  2127. return;
  2128. }
  2129. const char* PICValue = target->GetLinkPIEProperty(configName);
  2130. if (PICValue == nullptr) {
  2131. // POSITION_INDEPENDENT_CODE is not set
  2132. return;
  2133. }
  2134. buildSettings->AddAttribute(
  2135. "LD_NO_PIE", this->CreateString(cmIsOn(PICValue) ? "NO" : "YES"));
  2136. }
  2137. void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
  2138. cmXCodeObject* buildSettings,
  2139. const std::string& configName)
  2140. {
  2141. if (!gtgt->IsInBuildSystem()) {
  2142. return;
  2143. }
  2144. std::string defFlags;
  2145. bool shared = ((gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) ||
  2146. (gtgt->GetType() == cmStateEnums::MODULE_LIBRARY));
  2147. bool binary = ((gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY) ||
  2148. (gtgt->GetType() == cmStateEnums::STATIC_LIBRARY) ||
  2149. (gtgt->GetType() == cmStateEnums::EXECUTABLE) || shared);
  2150. // Compute the compilation flags for each language.
  2151. std::set<std::string> languages;
  2152. gtgt->GetLanguages(languages, configName);
  2153. std::map<std::string, std::string> cflags;
  2154. for (auto const& lang : languages) {
  2155. std::string& flags = cflags[lang];
  2156. // Add language-specific flags.
  2157. this->CurrentLocalGenerator->AddLanguageFlags(
  2158. flags, gtgt, cmBuildStep::Compile, lang, configName);
  2159. if (gtgt->IsIPOEnabled(lang, configName)) {
  2160. this->CurrentLocalGenerator->AppendFeatureOptions(flags, lang, "IPO");
  2161. }
  2162. // Add shared-library flags if needed.
  2163. this->CurrentLocalGenerator->AddCMP0018Flags(flags, gtgt, lang,
  2164. configName);
  2165. this->CurrentLocalGenerator->AddVisibilityPresetFlags(flags, gtgt, lang);
  2166. this->CurrentLocalGenerator->AddCompileOptions(flags, gtgt, lang,
  2167. configName);
  2168. }
  2169. std::string llang = gtgt->GetLinkerLanguage(configName);
  2170. if (binary && llang.empty()) {
  2171. cmSystemTools::Error(
  2172. cmStrCat("CMake can not determine linker language for target: ",
  2173. gtgt->GetName()));
  2174. return;
  2175. }
  2176. // Choose a language to use for target-wide preprocessor definitions.
  2177. static const char* ppLangs[] = { "CXX", "C", "OBJCXX", "OBJC" };
  2178. std::string langForPreprocessorDefinitions;
  2179. if (cm::contains(ppLangs, llang)) {
  2180. langForPreprocessorDefinitions = llang;
  2181. } else {
  2182. for (const char* l : ppLangs) {
  2183. if (languages.count(l)) {
  2184. langForPreprocessorDefinitions = l;
  2185. break;
  2186. }
  2187. }
  2188. }
  2189. if (gtgt->IsIPOEnabled(llang, configName)) {
  2190. const char* ltoValue =
  2191. this->CurrentMakefile->IsOn("_CMAKE_LTO_THIN") ? "YES_THIN" : "YES";
  2192. buildSettings->AddAttribute("LLVM_LTO", this->CreateString(ltoValue));
  2193. }
  2194. // Handle PIE linker configuration
  2195. this->AddPositionIndependentLinkAttribute(gtgt, buildSettings, configName);
  2196. // Add define flags
  2197. this->CurrentLocalGenerator->AppendFlags(
  2198. defFlags, this->CurrentMakefile->GetDefineFlags());
  2199. // Add preprocessor definitions for this target and configuration.
  2200. BuildObjectListOrString ppDefs(this, true);
  2201. this->AppendDefines(
  2202. ppDefs, "CMAKE_INTDIR=\"$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)\"");
  2203. if (const std::string* exportMacro = gtgt->GetExportMacro()) {
  2204. // Add the export symbol definition for shared library objects.
  2205. this->AppendDefines(ppDefs, exportMacro->c_str());
  2206. }
  2207. std::vector<std::string> targetDefines;
  2208. if (!langForPreprocessorDefinitions.empty()) {
  2209. gtgt->GetCompileDefinitions(targetDefines, configName,
  2210. langForPreprocessorDefinitions);
  2211. }
  2212. this->AppendDefines(ppDefs, targetDefines);
  2213. buildSettings->AddAttribute("GCC_PREPROCESSOR_DEFINITIONS",
  2214. ppDefs.CreateList());
  2215. if (languages.count("Swift")) {
  2216. // Swift uses a separate attribute for definitions.
  2217. std::vector<std::string> targetSwiftDefines;
  2218. gtgt->GetCompileDefinitions(targetSwiftDefines, configName, "Swift");
  2219. // Remove the '=value' parts, as Swift does not support them.
  2220. std::for_each(targetSwiftDefines.begin(), targetSwiftDefines.end(),
  2221. [](std::string& def) {
  2222. std::string::size_type pos = def.find('=');
  2223. if (pos != std::string::npos) {
  2224. def.erase(pos);
  2225. }
  2226. });
  2227. if (this->XcodeVersion < 80) {
  2228. std::string defineString;
  2229. std::set<std::string> defines(targetSwiftDefines.begin(),
  2230. targetSwiftDefines.end());
  2231. this->CurrentLocalGenerator->JoinDefines(defines, defineString, "Swift");
  2232. cflags["Swift"] += cmStrCat(' ', defineString);
  2233. } else {
  2234. BuildObjectListOrString swiftDefs(this, true);
  2235. this->AppendDefines(swiftDefs, targetSwiftDefines);
  2236. buildSettings->AddAttribute("SWIFT_ACTIVE_COMPILATION_CONDITIONS",
  2237. swiftDefs.CreateList());
  2238. }
  2239. }
  2240. std::string extraLinkOptionsVar;
  2241. std::string extraLinkOptions;
  2242. if (gtgt->GetType() == cmStateEnums::EXECUTABLE) {
  2243. extraLinkOptionsVar = "CMAKE_EXE_LINKER_FLAGS";
  2244. } else if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) {
  2245. extraLinkOptionsVar = "CMAKE_SHARED_LINKER_FLAGS";
  2246. } else if (gtgt->GetType() == cmStateEnums::MODULE_LIBRARY) {
  2247. extraLinkOptionsVar = "CMAKE_MODULE_LINKER_FLAGS";
  2248. }
  2249. if (!extraLinkOptionsVar.empty()) {
  2250. this->CurrentLocalGenerator->AddConfigVariableFlags(
  2251. extraLinkOptions, extraLinkOptionsVar, configName);
  2252. }
  2253. if (gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  2254. gtgt->GetType() == cmStateEnums::STATIC_LIBRARY) {
  2255. this->CurrentLocalGenerator->GetStaticLibraryFlags(
  2256. extraLinkOptions, configName, llang, gtgt);
  2257. } else {
  2258. cmValue targetLinkFlags = gtgt->GetProperty("LINK_FLAGS");
  2259. if (targetLinkFlags) {
  2260. this->CurrentLocalGenerator->AppendFlags(extraLinkOptions,
  2261. *targetLinkFlags);
  2262. }
  2263. if (!configName.empty()) {
  2264. std::string linkFlagsVar =
  2265. cmStrCat("LINK_FLAGS_", cmSystemTools::UpperCase(configName));
  2266. if (cmValue linkFlags = gtgt->GetProperty(linkFlagsVar)) {
  2267. this->CurrentLocalGenerator->AppendFlags(extraLinkOptions, *linkFlags);
  2268. }
  2269. }
  2270. std::vector<std::string> opts;
  2271. gtgt->GetLinkOptions(opts, configName, llang);
  2272. // LINK_OPTIONS are escaped.
  2273. this->CurrentLocalGenerator->AppendCompileOptions(extraLinkOptions, opts);
  2274. }
  2275. // Set target-specific architectures.
  2276. std::vector<std::string> archs =
  2277. gtgt->GetAppleArchs(configName, cm::nullopt);
  2278. if (!archs.empty()) {
  2279. // Enable ARCHS attribute.
  2280. buildSettings->AddAttribute("ONLY_ACTIVE_ARCH", this->CreateString("NO"));
  2281. // Store ARCHS value.
  2282. if (archs.size() == 1) {
  2283. buildSettings->AddAttribute("ARCHS", this->CreateString(archs[0]));
  2284. } else {
  2285. cmXCodeObject* archObjects =
  2286. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2287. for (auto& arch : archs) {
  2288. archObjects->AddObject(this->CreateString(arch));
  2289. }
  2290. buildSettings->AddAttribute("ARCHS", archObjects);
  2291. }
  2292. }
  2293. // Get the product name components.
  2294. cmGeneratorTarget::NameComponents const& components =
  2295. gtgt->GetFullNameComponents(configName);
  2296. cmValue version = gtgt->GetProperty("VERSION");
  2297. cmValue soversion = gtgt->GetProperty("SOVERSION");
  2298. if (!gtgt->HasSOName(configName) || gtgt->IsFrameworkOnApple()) {
  2299. version = nullptr;
  2300. soversion = nullptr;
  2301. }
  2302. if (version && !soversion) {
  2303. soversion = version;
  2304. }
  2305. if (!version && soversion) {
  2306. version = soversion;
  2307. }
  2308. std::string realName = components.base;
  2309. std::string soName = components.base;
  2310. if (version && soversion) {
  2311. realName += '.';
  2312. realName += *version;
  2313. soName += '.';
  2314. soName += *soversion;
  2315. }
  2316. if (gtgt->CanCompileSources()) {
  2317. std::string const tmpDir =
  2318. this->GetTargetTempDir(gtgt, this->GetCMakeCFGIntDir());
  2319. buildSettings->AddAttribute("TARGET_TEMP_DIR", this->CreateString(tmpDir));
  2320. std::string outDir;
  2321. if (gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  2322. // We cannot suppress the archive, so hide it with intermediate files.
  2323. outDir = tmpDir;
  2324. } else {
  2325. outDir = gtgt->GetDirectory(configName);
  2326. }
  2327. buildSettings->AddAttribute("CONFIGURATION_BUILD_DIR",
  2328. this->CreateString(outDir));
  2329. }
  2330. // Set attributes to specify the proper name for the target.
  2331. std::string pndir = this->CurrentLocalGenerator->GetCurrentBinaryDirectory();
  2332. if (gtgt->GetType() == cmStateEnums::STATIC_LIBRARY ||
  2333. gtgt->GetType() == cmStateEnums::SHARED_LIBRARY ||
  2334. gtgt->GetType() == cmStateEnums::MODULE_LIBRARY ||
  2335. gtgt->GetType() == cmStateEnums::EXECUTABLE) {
  2336. std::string prefix = components.prefix;
  2337. if (gtgt->IsFrameworkOnApple() || gtgt->IsCFBundleOnApple()) {
  2338. prefix = "";
  2339. }
  2340. buildSettings->AddAttribute("EXECUTABLE_PREFIX",
  2341. this->CreateString(prefix));
  2342. buildSettings->AddAttribute("EXECUTABLE_SUFFIX",
  2343. this->CreateString(components.suffix));
  2344. }
  2345. // Store the product name for all target types.
  2346. buildSettings->AddAttribute("PRODUCT_NAME", this->CreateString(realName));
  2347. // Handle settings for each target type.
  2348. switch (gtgt->GetType()) {
  2349. case cmStateEnums::STATIC_LIBRARY:
  2350. if (gtgt->GetPropertyAsBool("FRAMEWORK")) {
  2351. std::string fw_version = gtgt->GetFrameworkVersion();
  2352. buildSettings->AddAttribute("FRAMEWORK_VERSION",
  2353. this->CreateString(fw_version));
  2354. cmValue ext = gtgt->GetProperty("BUNDLE_EXTENSION");
  2355. if (ext) {
  2356. buildSettings->AddAttribute("WRAPPER_EXTENSION",
  2357. this->CreateString(*ext));
  2358. }
  2359. std::string plist = this->ComputeInfoPListLocation(gtgt);
  2360. // Xcode will create the final version of Info.plist at build time,
  2361. // so let it replace the framework name. This avoids creating
  2362. // a per-configuration Info.plist file.
  2363. this->CurrentLocalGenerator->GenerateFrameworkInfoPList(
  2364. gtgt, "$(EXECUTABLE_NAME)", plist);
  2365. buildSettings->AddAttribute("INFOPLIST_FILE",
  2366. this->CreateString(plist));
  2367. buildSettings->AddAttribute("MACH_O_TYPE",
  2368. this->CreateString("staticlib"));
  2369. } else {
  2370. buildSettings->AddAttribute("LIBRARY_STYLE",
  2371. this->CreateString("STATIC"));
  2372. }
  2373. break;
  2374. case cmStateEnums::OBJECT_LIBRARY: {
  2375. buildSettings->AddAttribute("LIBRARY_STYLE",
  2376. this->CreateString("STATIC"));
  2377. break;
  2378. }
  2379. case cmStateEnums::MODULE_LIBRARY: {
  2380. buildSettings->AddAttribute("LIBRARY_STYLE",
  2381. this->CreateString("BUNDLE"));
  2382. if (gtgt->IsCFBundleOnApple()) {
  2383. // It turns out that a BUNDLE is basically the same
  2384. // in many ways as an application bundle, as far as
  2385. // link flags go
  2386. std::string createFlags = this->LookupFlags(
  2387. "CMAKE_SHARED_MODULE_CREATE_", llang, "_FLAGS", "-bundle");
  2388. if (!createFlags.empty()) {
  2389. extraLinkOptions += ' ';
  2390. extraLinkOptions += createFlags;
  2391. }
  2392. cmValue ext = gtgt->GetProperty("BUNDLE_EXTENSION");
  2393. if (ext) {
  2394. buildSettings->AddAttribute("WRAPPER_EXTENSION",
  2395. this->CreateString(*ext));
  2396. }
  2397. std::string plist = this->ComputeInfoPListLocation(gtgt);
  2398. // Xcode will create the final version of Info.plist at build time,
  2399. // so let it replace the cfbundle name. This avoids creating
  2400. // a per-configuration Info.plist file. The cfbundle plist
  2401. // is very similar to the application bundle plist
  2402. this->CurrentLocalGenerator->GenerateAppleInfoPList(
  2403. gtgt, "$(EXECUTABLE_NAME)", plist);
  2404. buildSettings->AddAttribute("INFOPLIST_FILE",
  2405. this->CreateString(plist));
  2406. } else {
  2407. buildSettings->AddAttribute("MACH_O_TYPE",
  2408. this->CreateString("mh_bundle"));
  2409. buildSettings->AddAttribute("GCC_DYNAMIC_NO_PIC",
  2410. this->CreateString("NO"));
  2411. // Add the flags to create an executable.
  2412. std::string createFlags =
  2413. this->LookupFlags("CMAKE_", llang, "_LINK_FLAGS", "");
  2414. if (!createFlags.empty()) {
  2415. extraLinkOptions += ' ';
  2416. extraLinkOptions += createFlags;
  2417. }
  2418. }
  2419. break;
  2420. }
  2421. case cmStateEnums::SHARED_LIBRARY: {
  2422. if (gtgt->GetPropertyAsBool("FRAMEWORK")) {
  2423. std::string fw_version = gtgt->GetFrameworkVersion();
  2424. buildSettings->AddAttribute("FRAMEWORK_VERSION",
  2425. this->CreateString(fw_version));
  2426. cmValue ext = gtgt->GetProperty("BUNDLE_EXTENSION");
  2427. if (ext) {
  2428. buildSettings->AddAttribute("WRAPPER_EXTENSION",
  2429. this->CreateString(*ext));
  2430. }
  2431. std::string plist = this->ComputeInfoPListLocation(gtgt);
  2432. // Xcode will create the final version of Info.plist at build time,
  2433. // so let it replace the framework name. This avoids creating
  2434. // a per-configuration Info.plist file.
  2435. this->CurrentLocalGenerator->GenerateFrameworkInfoPList(
  2436. gtgt, "$(EXECUTABLE_NAME)", plist);
  2437. buildSettings->AddAttribute("INFOPLIST_FILE",
  2438. this->CreateString(plist));
  2439. } else {
  2440. // Add the flags to create a shared library.
  2441. std::string createFlags = this->LookupFlags(
  2442. "CMAKE_SHARED_LIBRARY_CREATE_", llang, "_FLAGS", "-dynamiclib");
  2443. if (!createFlags.empty()) {
  2444. extraLinkOptions += ' ';
  2445. extraLinkOptions += createFlags;
  2446. }
  2447. }
  2448. buildSettings->AddAttribute("LIBRARY_STYLE",
  2449. this->CreateString("DYNAMIC"));
  2450. if (gtgt->HasImportLibrary(configName)) {
  2451. // Request .tbd file generation
  2452. buildSettings->AddAttribute("GENERATE_TEXT_BASED_STUBS",
  2453. this->CreateString("YES"));
  2454. }
  2455. break;
  2456. }
  2457. case cmStateEnums::EXECUTABLE: {
  2458. // Add the flags to create an executable.
  2459. std::string createFlags =
  2460. this->LookupFlags("CMAKE_", llang, "_LINK_FLAGS", "");
  2461. if (!createFlags.empty()) {
  2462. extraLinkOptions += ' ';
  2463. extraLinkOptions += createFlags;
  2464. }
  2465. // Handle bundles and normal executables separately.
  2466. if (gtgt->GetPropertyAsBool("MACOSX_BUNDLE")) {
  2467. cmValue ext = gtgt->GetProperty("BUNDLE_EXTENSION");
  2468. if (ext) {
  2469. buildSettings->AddAttribute("WRAPPER_EXTENSION",
  2470. this->CreateString(*ext));
  2471. }
  2472. std::string plist = this->ComputeInfoPListLocation(gtgt);
  2473. // Xcode will create the final version of Info.plist at build time,
  2474. // so let it replace the executable name. This avoids creating
  2475. // a per-configuration Info.plist file.
  2476. this->CurrentLocalGenerator->GenerateAppleInfoPList(
  2477. gtgt, "$(EXECUTABLE_NAME)", plist);
  2478. buildSettings->AddAttribute("INFOPLIST_FILE",
  2479. this->CreateString(plist));
  2480. }
  2481. } break;
  2482. default:
  2483. break;
  2484. }
  2485. BuildObjectListOrString dirs(this, true);
  2486. BuildObjectListOrString fdirs(this, true);
  2487. BuildObjectListOrString sysdirs(this, true);
  2488. BuildObjectListOrString sysfdirs(this, true);
  2489. const bool emitSystemIncludes = this->XcodeVersion >= 83;
  2490. // Choose a language to use for target-wide include directories.
  2491. std::string const& langForIncludes = llang;
  2492. std::vector<std::string> includes;
  2493. if (!langForIncludes.empty()) {
  2494. this->CurrentLocalGenerator->GetIncludeDirectories(
  2495. includes, gtgt, langForIncludes, configName);
  2496. }
  2497. std::set<std::string> emitted;
  2498. emitted.insert("/System/Library/Frameworks");
  2499. for (auto& include : includes) {
  2500. if (this->NameResolvesToFramework(include)) {
  2501. std::string frameworkDir = cmStrCat(include, "/../");
  2502. frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
  2503. if (emitted.insert(frameworkDir).second) {
  2504. std::string incpath = this->XCodeEscapePath(frameworkDir);
  2505. if (emitSystemIncludes &&
  2506. gtgt->IsSystemIncludeDirectory(frameworkDir, configName,
  2507. langForIncludes)) {
  2508. sysfdirs.Add(incpath);
  2509. } else {
  2510. fdirs.Add(incpath);
  2511. }
  2512. }
  2513. } else {
  2514. std::string incpath = this->XCodeEscapePath(include);
  2515. if (emitSystemIncludes &&
  2516. gtgt->IsSystemIncludeDirectory(include, configName,
  2517. langForIncludes)) {
  2518. sysdirs.Add(incpath);
  2519. } else {
  2520. dirs.Add(incpath);
  2521. }
  2522. }
  2523. }
  2524. // Add framework search paths needed for linking.
  2525. if (cmComputeLinkInformation* cli = gtgt->GetLinkInformation(configName)) {
  2526. for (auto const& fwDir : cli->GetFrameworkPaths()) {
  2527. if (emitted.insert(fwDir).second) {
  2528. std::string incpath = this->XCodeEscapePath(fwDir);
  2529. if (emitSystemIncludes &&
  2530. gtgt->IsSystemIncludeDirectory(fwDir, configName,
  2531. langForIncludes)) {
  2532. sysfdirs.Add(incpath);
  2533. } else {
  2534. fdirs.Add(incpath);
  2535. }
  2536. }
  2537. }
  2538. }
  2539. if (!fdirs.IsEmpty()) {
  2540. buildSettings->AddAttribute("FRAMEWORK_SEARCH_PATHS", fdirs.CreateList());
  2541. }
  2542. if (!dirs.IsEmpty()) {
  2543. buildSettings->AddAttribute("HEADER_SEARCH_PATHS", dirs.CreateList());
  2544. if (languages.count("Swift")) {
  2545. buildSettings->AddAttribute("SWIFT_INCLUDE_PATHS", dirs.CreateList());
  2546. }
  2547. }
  2548. if (!sysfdirs.IsEmpty()) {
  2549. buildSettings->AddAttribute("SYSTEM_FRAMEWORK_SEARCH_PATHS",
  2550. sysfdirs.CreateList());
  2551. }
  2552. if (!sysdirs.IsEmpty()) {
  2553. buildSettings->AddAttribute("SYSTEM_HEADER_SEARCH_PATHS",
  2554. sysdirs.CreateList());
  2555. }
  2556. if (this->XcodeVersion >= 60 && !emitSystemIncludes) {
  2557. // Add those per-language flags in addition to HEADER_SEARCH_PATHS to gain
  2558. // system include directory awareness. We need to also keep on setting
  2559. // HEADER_SEARCH_PATHS to work around a missing compile options flag for
  2560. // GNU assembly files (#16449)
  2561. for (auto const& language : languages) {
  2562. std::string includeFlags = this->CurrentLocalGenerator->GetIncludeFlags(
  2563. includes, gtgt, language, configName);
  2564. if (!includeFlags.empty()) {
  2565. cflags[language] += cmStrCat(' ', includeFlags);
  2566. }
  2567. }
  2568. }
  2569. bool same_gflags = true;
  2570. std::map<std::string, std::string> gflags;
  2571. std::string const* last_gflag = nullptr;
  2572. std::string optLevel = "0";
  2573. // Minimal map of flags to build settings.
  2574. for (auto const& language : languages) {
  2575. std::string& flags = cflags[language];
  2576. std::string& gflag = gflags[language];
  2577. std::string oflag =
  2578. this->ExtractFlagRegex("(^| )(-Ofast|-Os|-O[0-9]*)( |$)", 2, flags);
  2579. if (oflag.size() == 2) {
  2580. optLevel = "1";
  2581. } else if (oflag.size() > 2) {
  2582. optLevel = oflag.substr(2);
  2583. }
  2584. gflag = this->ExtractFlag("-g", flags);
  2585. // put back gdwarf-2 if used since there is no way
  2586. // to represent it in the gui, but we still want debug yes
  2587. if (gflag == "-gdwarf-2"_s) {
  2588. flags += ' ';
  2589. flags += gflag;
  2590. }
  2591. if (last_gflag && *last_gflag != gflag) {
  2592. same_gflags = false;
  2593. }
  2594. last_gflag = &gflag;
  2595. }
  2596. const char* debugStr = "YES";
  2597. if (!same_gflags) {
  2598. // We can't set the Xcode flag differently depending on the language,
  2599. // so put them back in this case.
  2600. for (auto const& language : languages) {
  2601. cflags[language] += ' ';
  2602. cflags[language] += gflags[language];
  2603. }
  2604. debugStr = "NO";
  2605. } else if (last_gflag && (last_gflag->empty() || *last_gflag == "-g0"_s)) {
  2606. debugStr = "NO";
  2607. }
  2608. // extract C++ stdlib
  2609. for (auto const& language : languages) {
  2610. if (language != "CXX"_s && language != "OBJCXX"_s) {
  2611. continue;
  2612. }
  2613. std::string& flags = cflags[language];
  2614. auto stdlib =
  2615. this->ExtractFlagRegex("(^| )(-stdlib=[^ ]+)( |$)", 2, flags);
  2616. if (stdlib.size() > 8) {
  2617. const auto cxxLibrary = stdlib.substr(8);
  2618. if (language == "CXX"_s ||
  2619. !buildSettings->GetAttribute("CLANG_CXX_LIBRARY")) {
  2620. buildSettings->AddAttribute("CLANG_CXX_LIBRARY",
  2621. this->CreateString(cxxLibrary));
  2622. }
  2623. }
  2624. }
  2625. buildSettings->AddAttribute("COMBINE_HIDPI_IMAGES",
  2626. this->CreateString("YES"));
  2627. buildSettings->AddAttribute("GCC_GENERATE_DEBUGGING_SYMBOLS",
  2628. this->CreateString(debugStr));
  2629. buildSettings->AddAttribute("GCC_OPTIMIZATION_LEVEL",
  2630. this->CreateString(optLevel));
  2631. buildSettings->AddAttribute("GCC_SYMBOLS_PRIVATE_EXTERN",
  2632. this->CreateString("NO"));
  2633. buildSettings->AddAttribute("GCC_INLINES_ARE_PRIVATE_EXTERN",
  2634. this->CreateString("NO"));
  2635. for (auto const& language : languages) {
  2636. std::string flags = cmStrCat(cflags[language], ' ', defFlags);
  2637. if (language == "CXX"_s || language == "OBJCXX"_s) {
  2638. if (language == "CXX"_s ||
  2639. !buildSettings->GetAttribute("OTHER_CPLUSPLUSFLAGS")) {
  2640. buildSettings->AddAttribute("OTHER_CPLUSPLUSFLAGS",
  2641. this->CreateString(flags));
  2642. }
  2643. } else if (language == "Fortran"_s) {
  2644. buildSettings->AddAttribute("IFORT_OTHER_FLAGS",
  2645. this->CreateString(flags));
  2646. } else if (language == "C"_s || language == "OBJC"_s) {
  2647. if (language == "C"_s || !buildSettings->GetAttribute("OTHER_CFLAGS")) {
  2648. buildSettings->AddAttribute("OTHER_CFLAGS", this->CreateString(flags));
  2649. }
  2650. } else if (language == "Swift"_s) {
  2651. buildSettings->AddAttribute("OTHER_SWIFT_FLAGS",
  2652. this->CreateString(flags));
  2653. }
  2654. }
  2655. // Add Fortran source format attribute if property is set.
  2656. const char* format = nullptr;
  2657. std::string const& tgtfmt = gtgt->GetSafeProperty("Fortran_FORMAT");
  2658. switch (cmOutputConverter::GetFortranFormat(tgtfmt)) {
  2659. case cmOutputConverter::FortranFormatFixed:
  2660. format = "fixed";
  2661. break;
  2662. case cmOutputConverter::FortranFormatFree:
  2663. format = "free";
  2664. break;
  2665. default:
  2666. break;
  2667. }
  2668. if (format) {
  2669. buildSettings->AddAttribute("IFORT_LANG_SRCFMT",
  2670. this->CreateString(format));
  2671. }
  2672. // Create the INSTALL_PATH attribute.
  2673. std::string install_name_dir;
  2674. if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) {
  2675. // Get the install_name directory for the build tree.
  2676. install_name_dir = gtgt->GetInstallNameDirForBuildTree(configName);
  2677. // Xcode doesn't create the correct install_name in some cases.
  2678. // That is, if the INSTALL_PATH is empty, or if we have versioning
  2679. // of dylib libraries, we want to specify the install_name.
  2680. // This is done by adding a link flag to create an install_name
  2681. // with just the library soname.
  2682. std::string install_name;
  2683. if (!install_name_dir.empty()) {
  2684. // Convert to a path for the native build tool.
  2685. cmSystemTools::ConvertToUnixSlashes(install_name_dir);
  2686. install_name += install_name_dir;
  2687. install_name += '/';
  2688. }
  2689. install_name += gtgt->GetSOName(configName);
  2690. if ((realName != soName) || install_name_dir.empty()) {
  2691. install_name_dir = "";
  2692. extraLinkOptions += " -install_name ";
  2693. extraLinkOptions += XCodeEscapePath(install_name);
  2694. }
  2695. }
  2696. buildSettings->AddAttribute("INSTALL_PATH",
  2697. this->CreateString(install_name_dir));
  2698. // Create the LD_RUNPATH_SEARCH_PATHS
  2699. cmComputeLinkInformation* pcli = gtgt->GetLinkInformation(configName);
  2700. if (pcli) {
  2701. std::string search_paths;
  2702. std::vector<std::string> runtimeDirs;
  2703. pcli->GetRPath(runtimeDirs, false);
  2704. // runpath dirs needs to be unique to prevent corruption
  2705. std::set<std::string> unique_dirs;
  2706. for (auto runpath : runtimeDirs) {
  2707. runpath = this->ExpandCFGIntDir(runpath, configName);
  2708. if (unique_dirs.find(runpath) == unique_dirs.end()) {
  2709. unique_dirs.insert(runpath);
  2710. if (!search_paths.empty()) {
  2711. search_paths += ' ';
  2712. }
  2713. search_paths += this->XCodeEscapePath(runpath);
  2714. }
  2715. }
  2716. if (!search_paths.empty()) {
  2717. buildSettings->AddAttribute("LD_RUNPATH_SEARCH_PATHS",
  2718. this->CreateString(search_paths));
  2719. }
  2720. }
  2721. buildSettings->AddAttribute(this->GetTargetLinkFlagsVar(gtgt),
  2722. this->CreateString(extraLinkOptions));
  2723. buildSettings->AddAttribute("OTHER_REZFLAGS", this->CreateString(""));
  2724. buildSettings->AddAttribute("SECTORDER_FLAGS", this->CreateString(""));
  2725. buildSettings->AddAttribute("ALWAYS_SEARCH_USER_PATHS",
  2726. this->CreateString("NO"));
  2727. buildSettings->AddAttribute("USE_HEADERMAP", this->CreateString("NO"));
  2728. cmXCodeObject* group = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2729. group->AddObject(this->CreateString("$(inherited)"));
  2730. buildSettings->AddAttribute("WARNING_CFLAGS", group);
  2731. // Runtime version information.
  2732. if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) {
  2733. int major;
  2734. int minor;
  2735. int patch;
  2736. // MACHO_CURRENT_VERSION or VERSION -> current_version
  2737. gtgt->GetTargetVersionFallback("MACHO_CURRENT_VERSION", "VERSION", major,
  2738. minor, patch);
  2739. std::ostringstream v;
  2740. // Xcode always wants at least 1.0.0 or nothing
  2741. if (!(major == 0 && minor == 0 && patch == 0)) {
  2742. v << major << '.' << minor << '.' << patch;
  2743. }
  2744. buildSettings->AddAttribute("DYLIB_CURRENT_VERSION",
  2745. this->CreateString(v.str()));
  2746. // MACHO_COMPATIBILITY_VERSION or SOVERSION -> compatibility_version
  2747. gtgt->GetTargetVersionFallback("MACHO_COMPATIBILITY_VERSION", "SOVERSION",
  2748. major, minor, patch);
  2749. std::ostringstream vso;
  2750. // Xcode always wants at least 1.0.0 or nothing
  2751. if (!(major == 0 && minor == 0 && patch == 0)) {
  2752. vso << major << '.' << minor << '.' << patch;
  2753. }
  2754. buildSettings->AddAttribute("DYLIB_COMPATIBILITY_VERSION",
  2755. this->CreateString(vso.str()));
  2756. }
  2757. // Precompile Headers
  2758. std::string pchHeader = gtgt->GetPchHeader(configName, llang);
  2759. if (!pchHeader.empty()) {
  2760. buildSettings->AddAttribute("GCC_PREFIX_HEADER",
  2761. this->CreateString(pchHeader));
  2762. buildSettings->AddAttribute("GCC_PRECOMPILE_PREFIX_HEADER",
  2763. this->CreateString("YES"));
  2764. }
  2765. // put this last so it can override existing settings
  2766. // Convert "XCODE_ATTRIBUTE_*" properties directly.
  2767. {
  2768. for (auto const& prop : gtgt->GetPropertyKeys()) {
  2769. if (cmHasLiteralPrefix(prop, "XCODE_ATTRIBUTE_")) {
  2770. std::string attribute = prop.substr(16);
  2771. this->FilterConfigurationAttribute(configName, attribute);
  2772. if (!attribute.empty()) {
  2773. std::string const& pr = gtgt->GetSafeProperty(prop);
  2774. std::string processed = cmGeneratorExpression::Evaluate(
  2775. pr, this->CurrentLocalGenerator, configName);
  2776. buildSettings->AddAttribute(attribute,
  2777. this->CreateString(processed));
  2778. }
  2779. }
  2780. }
  2781. }
  2782. }
  2783. cmXCodeObject* cmGlobalXCodeGenerator::CreateUtilityTarget(
  2784. cmGeneratorTarget* gtgt)
  2785. {
  2786. cmXCodeObject* shellBuildPhase = this->CreateObject(
  2787. cmXCodeObject::PBXShellScriptBuildPhase, gtgt->GetName());
  2788. shellBuildPhase->AddAttribute("buildActionMask",
  2789. this->CreateString("2147483647"));
  2790. cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2791. shellBuildPhase->AddAttribute("files", buildFiles);
  2792. cmXCodeObject* inputPaths = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2793. shellBuildPhase->AddAttribute("inputPaths", inputPaths);
  2794. cmXCodeObject* outputPaths = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2795. shellBuildPhase->AddAttribute("outputPaths", outputPaths);
  2796. shellBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  2797. this->CreateString("0"));
  2798. shellBuildPhase->AddAttribute("shellPath", this->CreateString("/bin/sh"));
  2799. shellBuildPhase->AddAttribute(
  2800. "shellScript", this->CreateString("# shell script goes here\nexit 0"));
  2801. shellBuildPhase->AddAttribute("showEnvVarsInLog", this->CreateString("0"));
  2802. cmXCodeObject* target =
  2803. this->CreateObject(cmXCodeObject::PBXAggregateTarget);
  2804. target->SetComment(gtgt->GetName());
  2805. cmXCodeObject* buildPhases = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2806. std::vector<cmXCodeObject*> emptyContentVector;
  2807. this->CreateCustomCommands(buildPhases, nullptr, nullptr, nullptr,
  2808. emptyContentVector, nullptr, gtgt);
  2809. target->AddAttribute("buildPhases", buildPhases);
  2810. this->AddConfigurations(target, gtgt);
  2811. cmXCodeObject* dependencies = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2812. target->AddAttribute("dependencies", dependencies);
  2813. target->AddAttribute("name", this->CreateString(gtgt->GetName()));
  2814. target->AddAttribute("productName", this->CreateString(gtgt->GetName()));
  2815. target->SetTarget(gtgt);
  2816. this->XCodeObjectMap[gtgt] = target;
  2817. // Add source files without build rules for editing convenience.
  2818. if (gtgt->GetType() != cmStateEnums::GLOBAL_TARGET &&
  2819. gtgt->GetName() != CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
  2820. std::vector<cmSourceFile*> sources;
  2821. if (!gtgt->GetConfigCommonSourceFilesForXcode(sources)) {
  2822. return nullptr;
  2823. }
  2824. // Add CMakeLists.txt file for user convenience.
  2825. this->AddXCodeProjBuildRule(gtgt, sources);
  2826. for (auto* sourceFile : sources) {
  2827. if (!sourceFile->GetIsGenerated()) {
  2828. this->CreateXCodeFileReference(sourceFile, gtgt);
  2829. }
  2830. }
  2831. }
  2832. target->SetId(this->GetOrCreateId(gtgt->GetName(), target->GetId()));
  2833. return target;
  2834. }
  2835. std::string cmGlobalXCodeGenerator::AddConfigurations(cmXCodeObject* target,
  2836. cmGeneratorTarget* gtgt)
  2837. {
  2838. cmList const configList{ this->CurrentMakefile->GetRequiredDefinition(
  2839. "CMAKE_CONFIGURATION_TYPES") };
  2840. cmXCodeObject* configlist =
  2841. this->CreateObject(cmXCodeObject::XCConfigurationList);
  2842. cmXCodeObject* buildConfigurations =
  2843. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2844. configlist->AddAttribute("buildConfigurations", buildConfigurations);
  2845. std::string comment = cmStrCat("Build configuration list for ",
  2846. cmXCodeObject::PBXTypeNames[target->GetIsA()],
  2847. " \"", gtgt->GetName(), '"');
  2848. configlist->SetComment(comment);
  2849. target->AddAttribute("buildConfigurationList",
  2850. this->CreateObjectReference(configlist));
  2851. for (auto const& i : configList) {
  2852. cmXCodeObject* config =
  2853. this->CreateObject(cmXCodeObject::XCBuildConfiguration);
  2854. buildConfigurations->AddObject(config);
  2855. cmXCodeObject* buildSettings =
  2856. this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  2857. this->CreateBuildSettings(gtgt, buildSettings, i);
  2858. config->AddAttribute("name", this->CreateString(i));
  2859. config->SetComment(i);
  2860. config->AddAttribute("buildSettings", buildSettings);
  2861. this->CreateTargetXCConfigSettings(gtgt, config, i);
  2862. }
  2863. if (!configList.empty()) {
  2864. configlist->AddAttribute("defaultConfigurationName",
  2865. this->CreateString(configList[0]));
  2866. configlist->AddAttribute("defaultConfigurationIsVisible",
  2867. this->CreateString("0"));
  2868. return configList[0];
  2869. }
  2870. return "";
  2871. }
  2872. void cmGlobalXCodeGenerator::CreateGlobalXCConfigSettings(
  2873. cmLocalGenerator* root, cmXCodeObject* config, const std::string& configName)
  2874. {
  2875. auto xcconfig = cmGeneratorExpression::Evaluate(
  2876. this->CurrentMakefile->GetSafeDefinition("CMAKE_XCODE_XCCONFIG"),
  2877. this->CurrentLocalGenerator, configName);
  2878. if (xcconfig.empty()) {
  2879. return;
  2880. }
  2881. auto* sf = this->CurrentMakefile->GetSource(xcconfig);
  2882. if (!sf) {
  2883. cmSystemTools::Error(
  2884. cmStrCat("sources for ALL_BUILD do not contain xcconfig file: '",
  2885. xcconfig, "' (configuration: ", configName, ')'));
  2886. return;
  2887. }
  2888. cmXCodeObject* fileRef = this->CreateXCodeFileReferenceFromPath(
  2889. sf->ResolveFullPath(), root->FindGeneratorTargetToUse("ALL_BUILD"), "",
  2890. sf);
  2891. if (!fileRef) {
  2892. // error is already reported by CreateXCodeFileReferenceFromPath
  2893. return;
  2894. }
  2895. config->AddAttribute("baseConfigurationReference",
  2896. this->CreateObjectReference(fileRef));
  2897. }
  2898. void cmGlobalXCodeGenerator::CreateTargetXCConfigSettings(
  2899. cmGeneratorTarget* target, cmXCodeObject* config,
  2900. const std::string& configName)
  2901. {
  2902. auto xcconfig =
  2903. cmGeneratorExpression::Evaluate(target->GetSafeProperty("XCODE_XCCONFIG"),
  2904. this->CurrentLocalGenerator, configName);
  2905. if (xcconfig.empty()) {
  2906. return;
  2907. }
  2908. auto* sf = target->Makefile->GetSource(xcconfig);
  2909. if (!sf) {
  2910. cmSystemTools::Error(cmStrCat("target sources for target ",
  2911. target->Target->GetName(),
  2912. " do not contain xcconfig file: '", xcconfig,
  2913. "' (configuration: ", configName, ')'));
  2914. return;
  2915. }
  2916. cmXCodeObject* fileRef = this->CreateXCodeFileReferenceFromPath(
  2917. sf->ResolveFullPath(), target, "", sf);
  2918. if (!fileRef) {
  2919. // error is already reported by CreateXCodeFileReferenceFromPath
  2920. return;
  2921. }
  2922. config->AddAttribute("baseConfigurationReference",
  2923. this->CreateObjectReference(fileRef));
  2924. }
  2925. const char* cmGlobalXCodeGenerator::GetTargetLinkFlagsVar(
  2926. cmGeneratorTarget const* target) const
  2927. {
  2928. if (this->XcodeVersion >= 60 &&
  2929. (target->GetType() == cmStateEnums::STATIC_LIBRARY ||
  2930. target->GetType() == cmStateEnums::OBJECT_LIBRARY)) {
  2931. return "OTHER_LIBTOOLFLAGS";
  2932. }
  2933. return "OTHER_LDFLAGS";
  2934. }
  2935. const char* cmGlobalXCodeGenerator::GetTargetFileType(
  2936. cmGeneratorTarget* target)
  2937. {
  2938. if (cmValue e = target->GetProperty("XCODE_EXPLICIT_FILE_TYPE")) {
  2939. return e->c_str();
  2940. }
  2941. switch (target->GetType()) {
  2942. case cmStateEnums::OBJECT_LIBRARY:
  2943. return "archive.ar";
  2944. case cmStateEnums::STATIC_LIBRARY:
  2945. return (target->GetPropertyAsBool("FRAMEWORK") ? "wrapper.framework"
  2946. : "archive.ar");
  2947. case cmStateEnums::MODULE_LIBRARY:
  2948. if (target->IsXCTestOnApple()) {
  2949. return "wrapper.cfbundle";
  2950. }
  2951. if (target->IsCFBundleOnApple()) {
  2952. return "wrapper.plug-in";
  2953. }
  2954. return "compiled.mach-o.executable";
  2955. case cmStateEnums::SHARED_LIBRARY:
  2956. return (target->GetPropertyAsBool("FRAMEWORK")
  2957. ? "wrapper.framework"
  2958. : "compiled.mach-o.dylib");
  2959. case cmStateEnums::EXECUTABLE:
  2960. return "compiled.mach-o.executable";
  2961. default:
  2962. break;
  2963. }
  2964. return nullptr;
  2965. }
  2966. const char* cmGlobalXCodeGenerator::GetTargetProductType(
  2967. cmGeneratorTarget* target)
  2968. {
  2969. if (cmValue e = target->GetProperty("XCODE_PRODUCT_TYPE")) {
  2970. return e->c_str();
  2971. }
  2972. switch (target->GetType()) {
  2973. case cmStateEnums::OBJECT_LIBRARY:
  2974. return "com.apple.product-type.library.static";
  2975. case cmStateEnums::STATIC_LIBRARY:
  2976. return (target->GetPropertyAsBool("FRAMEWORK")
  2977. ? "com.apple.product-type.framework"
  2978. : "com.apple.product-type.library.static");
  2979. case cmStateEnums::MODULE_LIBRARY:
  2980. if (target->IsXCTestOnApple()) {
  2981. return "com.apple.product-type.bundle.unit-test";
  2982. } else if (target->IsCFBundleOnApple()) {
  2983. return "com.apple.product-type.bundle";
  2984. } else {
  2985. return "com.apple.product-type.tool";
  2986. }
  2987. case cmStateEnums::SHARED_LIBRARY:
  2988. return (target->GetPropertyAsBool("FRAMEWORK")
  2989. ? "com.apple.product-type.framework"
  2990. : "com.apple.product-type.library.dynamic");
  2991. case cmStateEnums::EXECUTABLE:
  2992. return (target->GetPropertyAsBool("MACOSX_BUNDLE")
  2993. ? "com.apple.product-type.application"
  2994. : "com.apple.product-type.tool");
  2995. default:
  2996. break;
  2997. }
  2998. return nullptr;
  2999. }
  3000. cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeTarget(
  3001. cmGeneratorTarget* gtgt, cmXCodeObject* buildPhases)
  3002. {
  3003. if (!gtgt->IsInBuildSystem()) {
  3004. return nullptr;
  3005. }
  3006. cmXCodeObject* target = this->CreateObject(cmXCodeObject::PBXNativeTarget);
  3007. target->AddAttribute("buildPhases", buildPhases);
  3008. cmXCodeObject* buildRules = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3009. target->AddAttribute("buildRules", buildRules);
  3010. std::string defConfig;
  3011. defConfig = this->AddConfigurations(target, gtgt);
  3012. cmXCodeObject* dependencies = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3013. target->AddAttribute("dependencies", dependencies);
  3014. target->AddAttribute("name", this->CreateString(gtgt->GetName()));
  3015. target->AddAttribute("productName", this->CreateString(gtgt->GetName()));
  3016. cmXCodeObject* fileRef = this->CreateObject(cmXCodeObject::PBXFileReference);
  3017. if (const char* fileType = this->GetTargetFileType(gtgt)) {
  3018. fileRef->AddAttribute("explicitFileType", this->CreateString(fileType));
  3019. }
  3020. std::string fullName;
  3021. if (gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  3022. fullName = cmStrCat("lib", gtgt->GetName(), ".a");
  3023. } else {
  3024. fullName = gtgt->GetFullName(defConfig);
  3025. }
  3026. fileRef->AddAttribute("path", this->CreateString(fullName));
  3027. fileRef->AddAttribute("sourceTree",
  3028. this->CreateString("BUILT_PRODUCTS_DIR"));
  3029. fileRef->SetComment(gtgt->GetName());
  3030. target->AddAttribute("productReference",
  3031. this->CreateObjectReference(fileRef));
  3032. if (const char* productType = this->GetTargetProductType(gtgt)) {
  3033. target->AddAttribute("productType", this->CreateString(productType));
  3034. }
  3035. target->SetTarget(gtgt);
  3036. this->XCodeObjectMap[gtgt] = target;
  3037. target->SetId(this->GetOrCreateId(gtgt->GetName(), target->GetId()));
  3038. return target;
  3039. }
  3040. cmXCodeObject* cmGlobalXCodeGenerator::FindXCodeTarget(
  3041. cmGeneratorTarget const* t)
  3042. {
  3043. if (!t) {
  3044. return nullptr;
  3045. }
  3046. auto const i = this->XCodeObjectMap.find(t);
  3047. if (i == this->XCodeObjectMap.end()) {
  3048. return nullptr;
  3049. }
  3050. return i->second;
  3051. }
  3052. std::string cmGlobalXCodeGenerator::GetObjectId(cmXCodeObject::PBXType ptype,
  3053. cm::string_view key)
  3054. {
  3055. std::string objectId;
  3056. if (!key.empty()) {
  3057. cmCryptoHash hash(cmCryptoHash::AlgoSHA256);
  3058. hash.Initialize();
  3059. hash.Append(&ptype, sizeof(ptype));
  3060. hash.Append(key);
  3061. objectId = cmSystemTools::UpperCase(hash.FinalizeHex().substr(0, 24));
  3062. } else {
  3063. char cUuid[40] = { 0 };
  3064. CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
  3065. CFStringRef s = CFUUIDCreateString(kCFAllocatorDefault, uuid);
  3066. CFStringGetCString(s, cUuid, sizeof(cUuid), kCFStringEncodingUTF8);
  3067. objectId = cUuid;
  3068. CFRelease(s);
  3069. CFRelease(uuid);
  3070. cmSystemTools::ReplaceString(objectId, "-", "");
  3071. if (objectId.size() > 24) {
  3072. objectId = objectId.substr(0, 24);
  3073. }
  3074. }
  3075. return objectId;
  3076. }
  3077. std::string cmGlobalXCodeGenerator::GetOrCreateId(const std::string& name,
  3078. const std::string& id)
  3079. {
  3080. std::string guidStoreName = cmStrCat(name, "_GUID_CMAKE");
  3081. cmValue storedGUID = this->CMakeInstance->GetCacheDefinition(guidStoreName);
  3082. if (storedGUID) {
  3083. return *storedGUID;
  3084. }
  3085. this->CMakeInstance->AddCacheEntry(
  3086. guidStoreName, id, "Stored Xcode object GUID", cmStateEnums::INTERNAL);
  3087. return id;
  3088. }
  3089. void cmGlobalXCodeGenerator::AddDependTarget(cmXCodeObject* target,
  3090. cmXCodeObject* dependTarget)
  3091. {
  3092. // This is called once for every edge in the target dependency graph.
  3093. cmXCodeObject* container =
  3094. this->CreateObject(cmXCodeObject::PBXContainerItemProxy);
  3095. container->SetComment("PBXContainerItemProxy");
  3096. container->AddAttribute("containerPortal",
  3097. this->CreateObjectReference(this->RootObject));
  3098. container->AddAttribute("proxyType", this->CreateString("1"));
  3099. container->AddAttribute("remoteGlobalIDString",
  3100. this->CreateObjectReference(dependTarget));
  3101. container->AddAttribute(
  3102. "remoteInfo", this->CreateString(dependTarget->GetTarget()->GetName()));
  3103. cmXCodeObject* targetdep =
  3104. this->CreateObject(cmXCodeObject::PBXTargetDependency);
  3105. targetdep->SetComment("PBXTargetDependency");
  3106. targetdep->AddAttribute("target", this->CreateObjectReference(dependTarget));
  3107. targetdep->AddAttribute("targetProxy",
  3108. this->CreateObjectReference(container));
  3109. cmXCodeObject* depends = target->GetAttribute("dependencies");
  3110. if (!depends) {
  3111. cmSystemTools::Error(
  3112. "target does not have dependencies attribute error..");
  3113. } else {
  3114. depends->AddUniqueObject(targetdep);
  3115. }
  3116. }
  3117. void cmGlobalXCodeGenerator::AppendOrAddBuildSetting(cmXCodeObject* settings,
  3118. const char* attribute,
  3119. cmXCodeObject* value)
  3120. {
  3121. if (settings) {
  3122. cmXCodeObject* attr = settings->GetAttribute(attribute);
  3123. if (!attr) {
  3124. settings->AddAttribute(attribute, value);
  3125. } else {
  3126. this->AppendBuildSettingAttribute(settings, attribute, attr, value);
  3127. }
  3128. }
  3129. }
  3130. void cmGlobalXCodeGenerator::AppendBuildSettingAttribute(
  3131. cmXCodeObject* settings, const char* attribute, cmXCodeObject* attr,
  3132. cmXCodeObject* value)
  3133. {
  3134. if (value->GetType() != cmXCodeObject::OBJECT_LIST &&
  3135. value->GetType() != cmXCodeObject::STRING) {
  3136. cmSystemTools::Error(
  3137. cmStrCat("Unsupported value type for appending: ", attribute));
  3138. return;
  3139. }
  3140. if (attr->GetType() == cmXCodeObject::OBJECT_LIST) {
  3141. if (value->GetType() == cmXCodeObject::OBJECT_LIST) {
  3142. for (auto* obj : value->GetObjectList()) {
  3143. attr->AddObject(obj);
  3144. }
  3145. } else {
  3146. attr->AddObject(value);
  3147. }
  3148. } else if (attr->GetType() == cmXCodeObject::STRING) {
  3149. if (value->GetType() == cmXCodeObject::OBJECT_LIST) {
  3150. // Add old value as a list item to new object list
  3151. // and replace the attribute with the new list
  3152. value->PrependObject(attr);
  3153. settings->AddAttribute(attribute, value);
  3154. } else {
  3155. std::string newValue =
  3156. cmStrCat(attr->GetString(), ' ', value->GetString());
  3157. attr->SetString(newValue);
  3158. }
  3159. } else {
  3160. cmSystemTools::Error(
  3161. cmStrCat("Unsupported attribute type for appending: ", attribute));
  3162. }
  3163. }
  3164. void cmGlobalXCodeGenerator::AppendBuildSettingAttribute(
  3165. cmXCodeObject* target, const char* attribute, cmXCodeObject* value,
  3166. const std::string& configName)
  3167. {
  3168. // There are multiple configurations. Add the setting to the
  3169. // buildSettings of the configuration name given.
  3170. cmXCodeObject* configurationList =
  3171. target->GetAttribute("buildConfigurationList")->GetObject();
  3172. cmXCodeObject* buildConfigs =
  3173. configurationList->GetAttribute("buildConfigurations");
  3174. for (auto* obj : buildConfigs->GetObjectList()) {
  3175. if (configName.empty() ||
  3176. obj->GetAttribute("name")->GetString() == configName) {
  3177. cmXCodeObject* settings = obj->GetAttribute("buildSettings");
  3178. this->AppendOrAddBuildSetting(settings, attribute, value);
  3179. }
  3180. }
  3181. }
  3182. void cmGlobalXCodeGenerator::InheritBuildSettingAttribute(
  3183. cmXCodeObject* target, const char* attribute)
  3184. {
  3185. cmXCodeObject* configurationList =
  3186. target->GetAttribute("buildConfigurationList")->GetObject();
  3187. cmXCodeObject* buildConfigs =
  3188. configurationList->GetAttribute("buildConfigurations");
  3189. for (auto* obj : buildConfigs->GetObjectList()) {
  3190. cmXCodeObject* settings = obj->GetAttribute("buildSettings");
  3191. if (cmXCodeObject* attr = settings->GetAttribute(attribute)) {
  3192. BuildObjectListOrString inherited(this, true);
  3193. inherited.Add("$(inherited)");
  3194. this->AppendBuildSettingAttribute(settings, attribute, attr,
  3195. inherited.CreateList());
  3196. }
  3197. }
  3198. }
  3199. void cmGlobalXCodeGenerator::AddDependAndLinkInformation(cmXCodeObject* target)
  3200. {
  3201. cmGeneratorTarget* gt = target->GetTarget();
  3202. if (!gt) {
  3203. cmSystemTools::Error("Error no target on xobject\n");
  3204. return;
  3205. }
  3206. if (!gt->IsInBuildSystem()) {
  3207. return;
  3208. }
  3209. // Add dependencies on other CMake targets.
  3210. for (const auto& dep : this->GetTargetDirectDepends(gt)) {
  3211. if (cmXCodeObject* dptarget = this->FindXCodeTarget(dep)) {
  3212. this->AddDependTarget(target, dptarget);
  3213. }
  3214. }
  3215. // Separate libraries into ones that can be linked using "Link Binary With
  3216. // Libraries" build phase and the ones that can't. Only targets that build
  3217. // Apple bundles (.app, .framework, .bundle), executables and dylibs can use
  3218. // this feature and only targets that represent actual libraries (object,
  3219. // static, dynamic or bundle, excluding executables) will be used. These are
  3220. // limitations imposed by CMake use-cases - otherwise a lot of things break.
  3221. // The rest will be linked using linker flags (OTHER_LDFLAGS setting in Xcode
  3222. // project).
  3223. std::map<std::string, std::vector<cmComputeLinkInformation::Item const*>>
  3224. configItemMap;
  3225. auto addToLinkerArguments =
  3226. [&configItemMap](const std::string& configName,
  3227. cmComputeLinkInformation::Item const* libItemPtr) {
  3228. auto& linkVector = configItemMap[configName];
  3229. if (std::find_if(linkVector.begin(), linkVector.end(),
  3230. [libItemPtr](cmComputeLinkInformation::Item const* p) {
  3231. return p == libItemPtr;
  3232. }) == linkVector.end()) {
  3233. linkVector.push_back(libItemPtr);
  3234. }
  3235. };
  3236. std::vector<cmComputeLinkInformation::Item const*> linkPhaseTargetVector;
  3237. std::map<std::string, std::vector<std::string>> targetConfigMap;
  3238. using ConfigItemPair =
  3239. std::pair<std::string, cmComputeLinkInformation::Item const*>;
  3240. std::map<std::string, std::vector<ConfigItemPair>> targetItemMap;
  3241. std::map<std::string, std::vector<std::string>> targetProductNameMap;
  3242. bool useLinkPhase = false;
  3243. bool forceLinkPhase = false;
  3244. cmValue prop =
  3245. target->GetTarget()->GetProperty("XCODE_LINK_BUILD_PHASE_MODE");
  3246. if (prop) {
  3247. if (*prop == "BUILT_ONLY"_s) {
  3248. useLinkPhase = true;
  3249. } else if (*prop == "KNOWN_LOCATION"_s) {
  3250. useLinkPhase = true;
  3251. forceLinkPhase = true;
  3252. } else if (*prop != "NONE"_s) {
  3253. cmSystemTools::Error(
  3254. cmStrCat("Invalid value for XCODE_LINK_BUILD_PHASE_MODE: ", *prop));
  3255. return;
  3256. }
  3257. }
  3258. for (auto const& configName : this->CurrentConfigurationTypes) {
  3259. cmComputeLinkInformation* cli = gt->GetLinkInformation(configName);
  3260. if (!cli) {
  3261. continue;
  3262. }
  3263. for (auto const& libItem : cli->GetItems()) {
  3264. // Explicitly ignore OBJECT libraries as Xcode emulates them as static
  3265. // libraries without an artifact. Avoid exposing this to the rest of
  3266. // CMake's compilation model.
  3267. if (libItem.Target &&
  3268. libItem.Target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  3269. continue;
  3270. }
  3271. // We want to put only static libraries, dynamic libraries, frameworks
  3272. // and bundles that are built from targets that are not imported in "Link
  3273. // Binary With Libraries" build phase. Except if the target property
  3274. // XCODE_LINK_BUILD_PHASE_MODE is KNOWN_LOCATION then all imported and
  3275. // non-target libraries will be added as well.
  3276. if (useLinkPhase &&
  3277. (gt->GetType() == cmStateEnums::EXECUTABLE ||
  3278. gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
  3279. gt->GetType() == cmStateEnums::MODULE_LIBRARY) &&
  3280. ((libItem.Target &&
  3281. (!libItem.Target->IsImported() || forceLinkPhase) &&
  3282. (libItem.Target->GetType() == cmStateEnums::STATIC_LIBRARY ||
  3283. libItem.Target->GetType() == cmStateEnums::SHARED_LIBRARY ||
  3284. libItem.Target->GetType() == cmStateEnums::MODULE_LIBRARY ||
  3285. libItem.Target->GetType() == cmStateEnums::UNKNOWN_LIBRARY)) ||
  3286. (!libItem.Target &&
  3287. libItem.IsPath == cmComputeLinkInformation::ItemIsPath::Yes &&
  3288. forceLinkPhase))) {
  3289. std::string libName;
  3290. bool canUseLinkPhase = !libItem.HasFeature() ||
  3291. libItem.GetFeatureName() == "__CMAKE_LINK_FRAMEWORK"_s ||
  3292. libItem.GetFeatureName() == "FRAMEWORK"_s ||
  3293. libItem.GetFeatureName() == "__CMAKE_LINK_XCFRAMEWORK"_s ||
  3294. libItem.GetFeatureName() == "XCFRAMEWORK"_s ||
  3295. libItem.GetFeatureName() == "WEAK_FRAMEWORK"_s ||
  3296. libItem.GetFeatureName() == "WEAK_LIBRARY"_s;
  3297. if (canUseLinkPhase) {
  3298. if (libItem.Target) {
  3299. if (libItem.Target->GetType() == cmStateEnums::UNKNOWN_LIBRARY) {
  3300. canUseLinkPhase = canUseLinkPhase && forceLinkPhase;
  3301. } else {
  3302. // If a library target uses custom build output directory Xcode
  3303. // won't pick it up so we have to resort back to linker flags,
  3304. // but that's OK as long as the custom output dir is absolute
  3305. // path.
  3306. for (auto const& libConfigName :
  3307. this->CurrentConfigurationTypes) {
  3308. canUseLinkPhase = canUseLinkPhase &&
  3309. libItem.Target->UsesDefaultOutputDir(
  3310. libConfigName, cmStateEnums::RuntimeBinaryArtifact);
  3311. }
  3312. }
  3313. libName = libItem.Target->GetName();
  3314. } else {
  3315. libName = cmSystemTools::GetFilenameName(libItem.Value.Value);
  3316. // We don't want all the possible files here, just standard
  3317. // libraries
  3318. const auto libExt = cmSystemTools::GetFilenameExtension(libName);
  3319. if (!IsLinkPhaseLibraryExtension(libExt)) {
  3320. canUseLinkPhase = false;
  3321. }
  3322. }
  3323. }
  3324. if (canUseLinkPhase) {
  3325. // Add unique configuration name to target-config map for later
  3326. // checks
  3327. auto& configVector = targetConfigMap[libName];
  3328. if (std::find(configVector.begin(), configVector.end(),
  3329. configName) == configVector.end()) {
  3330. configVector.push_back(configName);
  3331. }
  3332. // Add a pair of config and item to target-item map
  3333. auto& itemVector = targetItemMap[libName];
  3334. itemVector.emplace_back(configName, &libItem);
  3335. // Add product file-name to a lib-product map
  3336. auto productName =
  3337. cmSystemTools::GetFilenameName(libItem.Value.Value);
  3338. auto& productVector = targetProductNameMap[libName];
  3339. if (std::find(productVector.begin(), productVector.end(),
  3340. productName) == productVector.end()) {
  3341. productVector.push_back(productName);
  3342. }
  3343. continue;
  3344. }
  3345. }
  3346. // Add this library item to a regular linker flag list
  3347. addToLinkerArguments(configName, &libItem);
  3348. }
  3349. }
  3350. // Go through target library map and separate libraries that are linked
  3351. // in all configurations and produce only single product, from the rest.
  3352. // Only these will be linked through "Link Binary With Libraries" build
  3353. // phase.
  3354. for (auto const& targetLibConfigs : targetConfigMap) {
  3355. // Add this library to "Link Binary With Libraries" build phase if it's
  3356. // linked in all configurations and it has only one product name
  3357. auto& itemVector = targetItemMap[targetLibConfigs.first];
  3358. auto& productVector = targetProductNameMap[targetLibConfigs.first];
  3359. if (targetLibConfigs.second == this->CurrentConfigurationTypes &&
  3360. productVector.size() == 1) {
  3361. // Add this library to "Link Binary With Libraries" list
  3362. linkPhaseTargetVector.push_back(itemVector[0].second);
  3363. } else {
  3364. for (auto const& libItem : targetItemMap[targetLibConfigs.first]) {
  3365. // Add this library item to a regular linker flag list
  3366. addToLinkerArguments(libItem.first, libItem.second);
  3367. }
  3368. }
  3369. }
  3370. // Add libraries to "Link Binary With Libraries" build phase and collect
  3371. // their search paths. Xcode does not support per-configuration linking
  3372. // in this build phase so we don't have to do this for each configuration
  3373. // separately.
  3374. std::vector<std::string> linkSearchPaths;
  3375. std::vector<std::string> frameworkSearchPaths;
  3376. std::set<std::pair<cmXCodeObject*, std::string>> linkBuildFileSet;
  3377. for (auto const& libItem : linkPhaseTargetVector) {
  3378. // Add target output directory as a library search path
  3379. std::string linkDir;
  3380. if (libItem->Target) {
  3381. linkDir = libItem->Target->GetLocationForBuild();
  3382. } else {
  3383. linkDir = libItem->Value.Value;
  3384. }
  3385. if (cmHasSuffix(libItem->GetFeatureName(), "FRAMEWORK"_s)) {
  3386. auto fwDescriptor = this->SplitFrameworkPath(
  3387. linkDir, cmGlobalGenerator::FrameworkFormat::Extended);
  3388. if (fwDescriptor && !fwDescriptor->Directory.empty()) {
  3389. linkDir = fwDescriptor->Directory;
  3390. if (std::find(frameworkSearchPaths.begin(), frameworkSearchPaths.end(),
  3391. linkDir) == frameworkSearchPaths.end()) {
  3392. frameworkSearchPaths.push_back(linkDir);
  3393. }
  3394. }
  3395. } else {
  3396. linkDir = cmSystemTools::GetParentDirectory(linkDir);
  3397. if (std::find(linkSearchPaths.begin(), linkSearchPaths.end(), linkDir) ==
  3398. linkSearchPaths.end()) {
  3399. linkSearchPaths.push_back(linkDir);
  3400. }
  3401. }
  3402. if (libItem->Target && !libItem->Target->IsImported()) {
  3403. for (auto const& configName : this->CurrentConfigurationTypes) {
  3404. target->AddDependTarget(configName, libItem->Target->GetName());
  3405. }
  3406. }
  3407. // Get the library target
  3408. auto* libTarget = FindXCodeTarget(libItem->Target);
  3409. cmXCodeObject* buildFile;
  3410. if (!libTarget) {
  3411. if (libItem->IsPath == cmComputeLinkInformation::ItemIsPath::Yes) {
  3412. // Get or create a direct file ref in the root project
  3413. auto cleanPath = libItem->Value.Value;
  3414. if (cmSystemTools::FileIsFullPath(cleanPath)) {
  3415. // Some arguments are reported as paths, but they are actually not,
  3416. // so we can't collapse them, and neither can we collapse relative
  3417. // paths
  3418. cleanPath = cmSystemTools::CollapseFullPath(cleanPath);
  3419. }
  3420. auto it = this->ExternalLibRefs.find(cleanPath);
  3421. if (it == this->ExternalLibRefs.end()) {
  3422. buildFile = CreateXCodeBuildFileFromPath(cleanPath, gt, "", nullptr);
  3423. if (!buildFile) {
  3424. // Add this library item back to a regular linker flag list
  3425. for (const auto& conf : configItemMap) {
  3426. addToLinkerArguments(conf.first, libItem);
  3427. }
  3428. continue;
  3429. }
  3430. this->ExternalLibRefs.emplace(cleanPath, buildFile);
  3431. } else {
  3432. buildFile = it->second;
  3433. }
  3434. } else {
  3435. // Add this library item back to a regular linker flag list
  3436. for (const auto& conf : configItemMap) {
  3437. addToLinkerArguments(conf.first, libItem);
  3438. }
  3439. continue;
  3440. }
  3441. } else {
  3442. // Add the target output file as a build reference for other targets
  3443. // to link against
  3444. auto* fileRefObject = libTarget->GetAttribute("productReference");
  3445. if (!fileRefObject) {
  3446. // Add this library item back to a regular linker flag list
  3447. for (const auto& conf : configItemMap) {
  3448. addToLinkerArguments(conf.first, libItem);
  3449. }
  3450. continue;
  3451. }
  3452. auto it = FileRefToBuildFileMap.find(fileRefObject);
  3453. if (it == FileRefToBuildFileMap.end()) {
  3454. buildFile = this->CreateObject(cmXCodeObject::PBXBuildFile);
  3455. buildFile->AddAttribute("fileRef", fileRefObject);
  3456. FileRefToBuildFileMap[fileRefObject] = buildFile;
  3457. } else {
  3458. buildFile = it->second;
  3459. }
  3460. }
  3461. // Add this reference to current target
  3462. auto* buildPhases = target->GetAttribute("buildPhases");
  3463. if (!buildPhases) {
  3464. cmSystemTools::Error("Missing buildPhase of target");
  3465. continue;
  3466. }
  3467. auto* frameworkBuildPhase =
  3468. buildPhases->GetObject(cmXCodeObject::PBXFrameworksBuildPhase);
  3469. if (!frameworkBuildPhase) {
  3470. cmSystemTools::Error("Missing PBXFrameworksBuildPhase of buildPhase");
  3471. continue;
  3472. }
  3473. auto* buildFiles = frameworkBuildPhase->GetAttribute("files");
  3474. if (!buildFiles) {
  3475. cmSystemTools::Error("Missing files of PBXFrameworksBuildPhase");
  3476. continue;
  3477. }
  3478. if (buildFile) {
  3479. if (cmHasPrefix(libItem->GetFeatureName(), "WEAK_"_s)) {
  3480. auto key = std::make_pair(buildFile->GetAttribute("fileRef"),
  3481. libItem->GetFeatureName());
  3482. if (linkBuildFileSet.find(key) != linkBuildFileSet.end()) {
  3483. continue;
  3484. }
  3485. linkBuildFileSet.insert(key);
  3486. cmXCodeObject* buildObject =
  3487. this->CreateObject(cmXCodeObject::PBXBuildFile);
  3488. buildObject->AddAttribute("fileRef", key.first);
  3489. // Add settings, ATTRIBUTES, Weak flag
  3490. cmXCodeObject* settings =
  3491. this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  3492. cmXCodeObject* attrs = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3493. attrs->AddObject(this->CreateString("Weak"));
  3494. settings->AddAttribute("ATTRIBUTES", attrs);
  3495. buildObject->AddAttribute("settings", settings);
  3496. buildFile = buildObject;
  3497. }
  3498. if (!buildFiles->HasObject(buildFile)) {
  3499. buildFiles->AddObject(buildFile);
  3500. }
  3501. }
  3502. }
  3503. // Loop over configuration types and set per-configuration info.
  3504. for (auto const& configName : this->CurrentConfigurationTypes) {
  3505. {
  3506. // Add object library contents as link flags.
  3507. BuildObjectListOrString libSearchPaths(this, true);
  3508. std::vector<cmSourceFile const*> objs;
  3509. gt->GetExternalObjects(objs, configName);
  3510. for (auto const* sourceFile : objs) {
  3511. if (sourceFile->GetObjectLibrary().empty()) {
  3512. continue;
  3513. }
  3514. libSearchPaths.Add(this->XCodeEscapePath(sourceFile->GetFullPath()));
  3515. }
  3516. this->AppendBuildSettingAttribute(
  3517. target, this->GetTargetLinkFlagsVar(gt), libSearchPaths.CreateList(),
  3518. configName);
  3519. }
  3520. // Skip link information for object libraries.
  3521. if (gt->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  3522. gt->GetType() == cmStateEnums::STATIC_LIBRARY) {
  3523. continue;
  3524. }
  3525. // Compute the link library and directory information.
  3526. cmComputeLinkInformation* cli = gt->GetLinkInformation(configName);
  3527. if (!cli) {
  3528. continue;
  3529. }
  3530. // Add dependencies directly on library files.
  3531. for (auto const& libDep : cli->GetDepends()) {
  3532. target->AddDependLibrary(configName, libDep);
  3533. }
  3534. // add the library search paths
  3535. {
  3536. BuildObjectListOrString libSearchPaths(this, true);
  3537. std::string linkDirs;
  3538. for (auto const& libDir : cli->GetDirectories()) {
  3539. if (!libDir.empty() && libDir != "/usr/lib"_s) {
  3540. cmPolicies::PolicyStatus cmp0142 =
  3541. target->GetTarget()->GetPolicyStatusCMP0142();
  3542. if (cmp0142 == cmPolicies::OLD || cmp0142 == cmPolicies::WARN) {
  3543. libSearchPaths.Add(this->XCodeEscapePath(cmStrCat(
  3544. libDir, "/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)")));
  3545. }
  3546. libSearchPaths.Add(this->XCodeEscapePath(libDir));
  3547. }
  3548. }
  3549. // Add previously collected paths where to look for libraries
  3550. // that were added to "Link Binary With Libraries"
  3551. for (auto& libDir : linkSearchPaths) {
  3552. libSearchPaths.Add(this->XCodeEscapePath(libDir));
  3553. }
  3554. if (!libSearchPaths.IsEmpty()) {
  3555. this->AppendBuildSettingAttribute(target, "LIBRARY_SEARCH_PATHS",
  3556. libSearchPaths.CreateList(),
  3557. configName);
  3558. }
  3559. }
  3560. // add framework search paths
  3561. {
  3562. BuildObjectListOrString fwSearchPaths(this, true);
  3563. // Add previously collected paths where to look for frameworks
  3564. // that were added to "Link Binary With Libraries"
  3565. for (auto& fwDir : frameworkSearchPaths) {
  3566. fwSearchPaths.Add(this->XCodeEscapePath(fwDir));
  3567. }
  3568. if (!fwSearchPaths.IsEmpty()) {
  3569. this->AppendBuildSettingAttribute(target, "FRAMEWORK_SEARCH_PATHS",
  3570. fwSearchPaths.CreateList(),
  3571. configName);
  3572. }
  3573. }
  3574. // now add the left-over link libraries
  3575. {
  3576. // Keep track of framework search paths we've already added or that are
  3577. // part of the set of implicit search paths. We don't want to repeat
  3578. // them and we also need to avoid hard-coding any SDK-specific paths.
  3579. // This is essential for getting device-and-simulator builds to work,
  3580. // otherwise we end up hard-coding a path to the wrong SDK for
  3581. // SDK-provided frameworks that are added by their full path.
  3582. std::set<std::string> emitted(cli->GetFrameworkPathsEmitted());
  3583. BuildObjectListOrString libPaths(this, true);
  3584. BuildObjectListOrString fwSearchPaths(this, true);
  3585. for (auto const& libItem : configItemMap[configName]) {
  3586. auto const& libName = *libItem;
  3587. if (libName.IsPath == cmComputeLinkInformation::ItemIsPath::Yes) {
  3588. auto cleanPath = libName.Value.Value;
  3589. if (cmSystemTools::FileIsFullPath(cleanPath)) {
  3590. cleanPath = cmSystemTools::CollapseFullPath(cleanPath);
  3591. }
  3592. bool isXcFramework =
  3593. cmHasSuffix(libName.GetFeatureName(), "XCFRAMEWORK"_s);
  3594. bool isFramework = !isXcFramework &&
  3595. cmHasSuffix(libName.GetFeatureName(), "FRAMEWORK"_s);
  3596. if (isFramework) {
  3597. const auto fwDescriptor = this->SplitFrameworkPath(
  3598. cleanPath, cmGlobalGenerator::FrameworkFormat::Extended);
  3599. if (isFramework && !fwDescriptor->Directory.empty() &&
  3600. emitted.insert(fwDescriptor->Directory).second) {
  3601. // This is a search path we had not added before and it isn't
  3602. // an implicit search path, so we need it
  3603. fwSearchPaths.Add(
  3604. this->XCodeEscapePath(fwDescriptor->Directory));
  3605. }
  3606. if (libName.GetFeatureName() == "__CMAKE_LINK_FRAMEWORK"_s) {
  3607. // use the full path
  3608. libPaths.Add(
  3609. libName.GetFormattedItem(this->XCodeEscapePath(cleanPath))
  3610. .Value);
  3611. } else {
  3612. libPaths.Add(libName
  3613. .GetFormattedItem(this->XCodeEscapePath(
  3614. fwDescriptor->GetLinkName()))
  3615. .Value);
  3616. }
  3617. } else if (isXcFramework) {
  3618. auto plist = cmParseXcFrameworkPlist(
  3619. cleanPath, *this->Makefiles.front(), libName.Value.Backtrace);
  3620. if (!plist) {
  3621. return;
  3622. }
  3623. if (auto const* library = plist->SelectSuitableLibrary(
  3624. *this->Makefiles.front(), libName.Value.Backtrace)) {
  3625. auto libraryPath =
  3626. cmStrCat(cleanPath, '/', library->LibraryIdentifier, '/',
  3627. library->LibraryPath);
  3628. if (auto const fwDescriptor = this->SplitFrameworkPath(
  3629. libraryPath,
  3630. cmGlobalGenerator::FrameworkFormat::Relaxed)) {
  3631. if (!fwDescriptor->Directory.empty() &&
  3632. emitted.insert(fwDescriptor->Directory).second) {
  3633. // This is a search path we had not added before and it
  3634. // isn't an implicit search path, so we need it
  3635. fwSearchPaths.Add(
  3636. this->XCodeEscapePath(fwDescriptor->Directory));
  3637. }
  3638. libPaths.Add(cmStrCat(
  3639. "-framework ",
  3640. this->XCodeEscapePath(fwDescriptor->GetLinkName())));
  3641. } else {
  3642. libPaths.Add(
  3643. libName.GetFormattedItem(this->XCodeEscapePath(libraryPath))
  3644. .Value);
  3645. if (!library->HeadersPath.empty()) {
  3646. this->AppendBuildSettingAttribute(
  3647. target, "HEADER_SEARCH_PATHS",
  3648. this->CreateString(this->XCodeEscapePath(
  3649. cmStrCat(cleanPath, '/', library->LibraryIdentifier, '/',
  3650. library->HeadersPath))),
  3651. configName);
  3652. }
  3653. }
  3654. } else {
  3655. return;
  3656. }
  3657. } else {
  3658. libPaths.Add(
  3659. libName.GetFormattedItem(this->XCodeEscapePath(cleanPath))
  3660. .Value);
  3661. }
  3662. if ((!libName.Target || libName.Target->IsImported()) &&
  3663. (isFramework || isXcFramework ||
  3664. IsLinkPhaseLibraryExtension(cleanPath))) {
  3665. // Create file reference for embedding
  3666. auto it = this->ExternalLibRefs.find(cleanPath);
  3667. if (it == this->ExternalLibRefs.end()) {
  3668. auto* buildFile =
  3669. this->CreateXCodeBuildFileFromPath(cleanPath, gt, "", nullptr);
  3670. if (buildFile) {
  3671. this->ExternalLibRefs.emplace(cleanPath, buildFile);
  3672. }
  3673. }
  3674. }
  3675. } else if (!libName.Target ||
  3676. libName.Target->GetType() !=
  3677. cmStateEnums::INTERFACE_LIBRARY) {
  3678. libPaths.Add(libName.Value.Value);
  3679. }
  3680. if (libName.Target && !libName.Target->IsImported()) {
  3681. target->AddDependTarget(configName, libName.Target->GetName());
  3682. }
  3683. }
  3684. if (!libPaths.IsEmpty()) {
  3685. this->AppendBuildSettingAttribute(target,
  3686. this->GetTargetLinkFlagsVar(gt),
  3687. libPaths.CreateList(), configName);
  3688. }
  3689. if (!fwSearchPaths.IsEmpty()) {
  3690. this->AppendBuildSettingAttribute(target, "FRAMEWORK_SEARCH_PATHS",
  3691. fwSearchPaths.CreateList(),
  3692. configName);
  3693. }
  3694. }
  3695. }
  3696. }
  3697. void cmGlobalXCodeGenerator::AddEmbeddedObjects(
  3698. cmXCodeObject* target, const std::string& copyFilesBuildPhaseName,
  3699. const std::string& embedPropertyName, const std::string& dstSubfolderSpec,
  3700. int actionsOnByDefault, const std::string& defaultDstPath)
  3701. {
  3702. cmGeneratorTarget* gt = target->GetTarget();
  3703. if (!gt) {
  3704. cmSystemTools::Error("Error no target on xobject\n");
  3705. return;
  3706. }
  3707. if (!gt->IsInBuildSystem()) {
  3708. return;
  3709. }
  3710. bool isFrameworkTarget = gt->IsFrameworkOnApple();
  3711. bool isBundleTarget = gt->GetPropertyAsBool("MACOSX_BUNDLE");
  3712. bool isCFBundleTarget = gt->IsCFBundleOnApple();
  3713. if (!(isFrameworkTarget || isBundleTarget || isCFBundleTarget)) {
  3714. return;
  3715. }
  3716. cmValue files = gt->GetProperty(embedPropertyName);
  3717. if (!files) {
  3718. return;
  3719. }
  3720. // Create an "Embedded Frameworks" build phase
  3721. auto* copyFilesBuildPhase =
  3722. this->CreateObject(cmXCodeObject::PBXCopyFilesBuildPhase);
  3723. copyFilesBuildPhase->SetComment(copyFilesBuildPhaseName);
  3724. copyFilesBuildPhase->AddAttribute("buildActionMask",
  3725. this->CreateString("2147483647"));
  3726. copyFilesBuildPhase->AddAttribute("dstSubfolderSpec",
  3727. this->CreateString(dstSubfolderSpec));
  3728. copyFilesBuildPhase->AddAttribute(
  3729. "name", this->CreateString(copyFilesBuildPhaseName));
  3730. if (cmValue fwEmbedPath =
  3731. gt->GetProperty(cmStrCat(embedPropertyName, "_PATH"))) {
  3732. copyFilesBuildPhase->AddAttribute("dstPath",
  3733. this->CreateString(*fwEmbedPath));
  3734. } else {
  3735. copyFilesBuildPhase->AddAttribute("dstPath",
  3736. this->CreateString(defaultDstPath));
  3737. }
  3738. copyFilesBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  3739. this->CreateString("0"));
  3740. cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3741. // Collect all embedded frameworks and dylibs and add them to build phase
  3742. cmList relFiles{ *files };
  3743. for (std::string const& relFile : relFiles) {
  3744. cmXCodeObject* buildFile{ nullptr };
  3745. std::string filePath = relFile;
  3746. auto* genTarget = this->FindGeneratorTarget(relFile);
  3747. if (genTarget) {
  3748. // This is a target - get it's product path reference
  3749. auto* xcTarget = this->FindXCodeTarget(genTarget);
  3750. if (!xcTarget) {
  3751. cmSystemTools::Error(
  3752. cmStrCat("Can not find a target for ", genTarget->GetName()));
  3753. continue;
  3754. }
  3755. // Add the target output file as a build reference for other targets
  3756. // to link against
  3757. auto* fileRefObject = xcTarget->GetAttribute("productReference");
  3758. if (!fileRefObject) {
  3759. cmSystemTools::Error(cmStrCat("Target ", genTarget->GetName(),
  3760. " is missing product reference"));
  3761. continue;
  3762. }
  3763. auto it = this->FileRefToEmbedBuildFileMap.find(fileRefObject);
  3764. if (it == this->FileRefToEmbedBuildFileMap.end()) {
  3765. buildFile = this->CreateObject(cmXCodeObject::PBXBuildFile);
  3766. buildFile->AddAttribute("fileRef", fileRefObject);
  3767. this->FileRefToEmbedBuildFileMap[fileRefObject] = buildFile;
  3768. } else {
  3769. buildFile = it->second;
  3770. }
  3771. } else if (cmSystemTools::IsPathToFramework(relFile) ||
  3772. cmSystemTools::IsPathToMacOSSharedLibrary(relFile) ||
  3773. cmSystemTools::FileIsDirectory(filePath)) {
  3774. // This is a regular string path - create file reference
  3775. auto it = this->EmbeddedLibRefs.find(relFile);
  3776. if (it == this->EmbeddedLibRefs.end()) {
  3777. cmXCodeObject* fileRef =
  3778. this->CreateXCodeFileReferenceFromPath(relFile, gt, "", nullptr);
  3779. if (fileRef) {
  3780. buildFile = this->CreateObject(cmXCodeObject::PBXBuildFile);
  3781. buildFile->SetComment(fileRef->GetComment());
  3782. buildFile->AddAttribute("fileRef",
  3783. this->CreateObjectReference(fileRef));
  3784. }
  3785. if (!buildFile) {
  3786. cmSystemTools::Error(
  3787. cmStrCat("Can't create build file for ", relFile));
  3788. continue;
  3789. }
  3790. this->EmbeddedLibRefs.emplace(filePath, buildFile);
  3791. } else {
  3792. buildFile = it->second;
  3793. }
  3794. }
  3795. if (!buildFile) {
  3796. cmSystemTools::Error(cmStrCat("Can't find a build file for ", relFile));
  3797. continue;
  3798. }
  3799. // Set build file configuration
  3800. cmXCodeObject* settings =
  3801. this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  3802. cmXCodeObject* attrs = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3803. bool removeHeaders = actionsOnByDefault & RemoveHeadersOnCopyByDefault;
  3804. if (auto prop = gt->GetProperty(
  3805. cmStrCat(embedPropertyName, "_REMOVE_HEADERS_ON_COPY"))) {
  3806. removeHeaders = cmIsOn(*prop);
  3807. }
  3808. if (removeHeaders) {
  3809. attrs->AddObject(this->CreateString("RemoveHeadersOnCopy"));
  3810. }
  3811. bool codeSign = actionsOnByDefault & CodeSignOnCopyByDefault;
  3812. if (auto prop =
  3813. gt->GetProperty(cmStrCat(embedPropertyName, "_CODE_SIGN_ON_COPY"))) {
  3814. codeSign = cmIsOn(*prop);
  3815. }
  3816. if (codeSign) {
  3817. attrs->AddObject(this->CreateString("CodeSignOnCopy"));
  3818. }
  3819. settings->AddAttributeIfNotEmpty("ATTRIBUTES", attrs);
  3820. buildFile->AddAttributeIfNotEmpty("settings", settings);
  3821. if (!buildFiles->HasObject(buildFile)) {
  3822. buildFiles->AddObject(buildFile);
  3823. }
  3824. }
  3825. copyFilesBuildPhase->AddAttribute("files", buildFiles);
  3826. auto* buildPhases = target->GetAttribute("buildPhases");
  3827. // Embed-something build phases must be inserted before the post-build
  3828. // command because that command is expected to be last
  3829. buildPhases->InsertObject(buildPhases->GetObjectCount() - 1,
  3830. copyFilesBuildPhase);
  3831. }
  3832. void cmGlobalXCodeGenerator::AddEmbeddedFrameworks(cmXCodeObject* target)
  3833. {
  3834. static auto const* const dstSubfolderSpec = "10";
  3835. // Despite the name, by default Xcode uses "Embed Frameworks" build phase
  3836. // for both frameworks and dynamic libraries
  3837. this->AddEmbeddedObjects(target, "Embed Frameworks",
  3838. "XCODE_EMBED_FRAMEWORKS", dstSubfolderSpec,
  3839. NoActionOnCopyByDefault);
  3840. }
  3841. void cmGlobalXCodeGenerator::AddEmbeddedPlugIns(cmXCodeObject* target)
  3842. {
  3843. static auto const* const dstSubfolderSpec = "13";
  3844. this->AddEmbeddedObjects(target, "Embed PlugIns", "XCODE_EMBED_PLUGINS",
  3845. dstSubfolderSpec, NoActionOnCopyByDefault);
  3846. }
  3847. void cmGlobalXCodeGenerator::AddEmbeddedAppExtensions(cmXCodeObject* target)
  3848. {
  3849. static auto const* const dstSubfolderSpec = "13";
  3850. this->AddEmbeddedObjects(target, "Embed App Extensions",
  3851. "XCODE_EMBED_APP_EXTENSIONS", dstSubfolderSpec,
  3852. RemoveHeadersOnCopyByDefault);
  3853. }
  3854. void cmGlobalXCodeGenerator::AddEmbeddedExtensionKitExtensions(
  3855. cmXCodeObject* target)
  3856. {
  3857. static auto const* const dstSubfolderSpec = "16";
  3858. this->AddEmbeddedObjects(target, "Embed App Extensions",
  3859. "XCODE_EMBED_EXTENSIONKIT_EXTENSIONS",
  3860. dstSubfolderSpec, RemoveHeadersOnCopyByDefault,
  3861. "$(EXTENSIONS_FOLDER_PATH)");
  3862. }
  3863. void cmGlobalXCodeGenerator::AddEmbeddedResources(cmXCodeObject* target)
  3864. {
  3865. static const auto dstSubfolderSpec = "7";
  3866. this->AddEmbeddedObjects(target, "Embed Resources",
  3867. "XCODE_EMBED_RESOURCES_PATH", dstSubfolderSpec,
  3868. NoActionOnCopyByDefault);
  3869. }
  3870. bool cmGlobalXCodeGenerator::CreateGroups(
  3871. std::vector<cmLocalGenerator*>& generators)
  3872. {
  3873. for (auto& generator : generators) {
  3874. cmMakefile* mf = generator->GetMakefile();
  3875. std::vector<cmSourceGroup> sourceGroups = mf->GetSourceGroups();
  3876. for (const auto& gtgt : generator->GetGeneratorTargets()) {
  3877. // Same skipping logic here as in CreateXCodeTargets so that we do not
  3878. // end up with (empty anyhow) ZERO_CHECK, install, or test source
  3879. // groups:
  3880. //
  3881. if (!gtgt->IsInBuildSystem() ||
  3882. gtgt->GetType() == cmStateEnums::GLOBAL_TARGET ||
  3883. gtgt->GetName() == CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
  3884. continue;
  3885. }
  3886. auto addSourceToGroup = [this, mf, &gtgt,
  3887. &sourceGroups](std::string const& source) {
  3888. cmSourceGroup* sourceGroup = mf->FindSourceGroup(source, sourceGroups);
  3889. cmXCodeObject* pbxgroup =
  3890. this->CreateOrGetPBXGroup(gtgt.get(), sourceGroup);
  3891. std::string key = GetGroupMapKeyFromPath(gtgt.get(), source);
  3892. this->GroupMap[key] = pbxgroup;
  3893. };
  3894. // Put cmSourceFile instances in proper groups:
  3895. for (auto const& si : gtgt->GetAllConfigSources()) {
  3896. cmSourceFile const* sf = si.Source;
  3897. if (!sf->GetObjectLibrary().empty()) {
  3898. // Object library files go on the link line instead.
  3899. continue;
  3900. }
  3901. addSourceToGroup(sf->GetFullPath());
  3902. }
  3903. // Add CMakeLists.txt file for user convenience.
  3904. {
  3905. std::string listfile =
  3906. cmStrCat(gtgt->GetLocalGenerator()->GetCurrentSourceDirectory(),
  3907. "/CMakeLists.txt");
  3908. cmSourceFile* sf = gtgt->Makefile->GetOrCreateSource(
  3909. listfile, false, cmSourceFileLocationKind::Known);
  3910. addSourceToGroup(sf->ResolveFullPath());
  3911. }
  3912. // Add the Info.plist we are about to generate for an App Bundle.
  3913. if (gtgt->GetPropertyAsBool("MACOSX_BUNDLE")) {
  3914. std::string plist = this->ComputeInfoPListLocation(gtgt.get());
  3915. cmSourceFile* sf = gtgt->Makefile->GetOrCreateSource(
  3916. plist, true, cmSourceFileLocationKind::Known);
  3917. addSourceToGroup(sf->ResolveFullPath());
  3918. }
  3919. }
  3920. }
  3921. return true;
  3922. }
  3923. cmXCodeObject* cmGlobalXCodeGenerator::CreatePBXGroup(cmXCodeObject* parent,
  3924. const std::string& name)
  3925. {
  3926. cmXCodeObject* parentChildren = nullptr;
  3927. if (parent) {
  3928. parentChildren = parent->GetAttribute("children");
  3929. }
  3930. cmXCodeObject* group = this->CreateObject(cmXCodeObject::PBXGroup);
  3931. cmXCodeObject* groupChildren =
  3932. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3933. group->AddAttribute("name", this->CreateString(name));
  3934. group->AddAttribute("children", groupChildren);
  3935. group->AddAttribute("sourceTree", this->CreateString("<group>"));
  3936. if (parentChildren) {
  3937. parentChildren->AddObject(group);
  3938. }
  3939. return group;
  3940. }
  3941. cmXCodeObject* cmGlobalXCodeGenerator::CreateOrGetPBXGroup(
  3942. cmGeneratorTarget* gtgt, cmSourceGroup* sg)
  3943. {
  3944. std::string s;
  3945. std::string target;
  3946. const std::string targetFolder = gtgt->GetEffectiveFolderName();
  3947. if (!targetFolder.empty()) {
  3948. target = cmStrCat(targetFolder, '/');
  3949. }
  3950. target += gtgt->GetName();
  3951. s = cmStrCat(target, '/', sg->GetFullName());
  3952. auto it = this->GroupNameMap.find(s);
  3953. if (it != this->GroupNameMap.end()) {
  3954. return it->second;
  3955. }
  3956. it = this->TargetGroup.find(target);
  3957. cmXCodeObject* tgroup = nullptr;
  3958. if (it != this->TargetGroup.end()) {
  3959. tgroup = it->second;
  3960. } else {
  3961. std::vector<std::string> tgt_folders = cmTokenize(target, "/");
  3962. std::string curr_tgt_folder;
  3963. for (std::vector<std::string>::size_type i = 0; i < tgt_folders.size();
  3964. i++) {
  3965. if (i != 0) {
  3966. curr_tgt_folder += '/';
  3967. }
  3968. curr_tgt_folder += tgt_folders[i];
  3969. it = this->TargetGroup.find(curr_tgt_folder);
  3970. if (it != this->TargetGroup.end()) {
  3971. tgroup = it->second;
  3972. continue;
  3973. }
  3974. tgroup = this->CreatePBXGroup(tgroup, tgt_folders[i]);
  3975. this->TargetGroup[curr_tgt_folder] = tgroup;
  3976. if (i == 0) {
  3977. this->MainGroupChildren->AddObject(tgroup);
  3978. }
  3979. }
  3980. }
  3981. this->TargetGroup[target] = tgroup;
  3982. // If it's the default source group (empty name) then put the source file
  3983. // directly in the tgroup...
  3984. //
  3985. if (sg->GetFullName().empty()) {
  3986. this->GroupNameMap[s] = tgroup;
  3987. return tgroup;
  3988. }
  3989. // It's a recursive folder structure, let's find the real parent group
  3990. if (sg->GetFullName() != sg->GetName()) {
  3991. std::string curr_folder = cmStrCat(target, '/');
  3992. for (auto const& folder : cmTokenize(sg->GetFullName(), "\\")) {
  3993. curr_folder += folder;
  3994. auto const i_folder = this->GroupNameMap.find(curr_folder);
  3995. // Create new folder
  3996. if (i_folder == this->GroupNameMap.end()) {
  3997. cmXCodeObject* group = this->CreatePBXGroup(tgroup, folder);
  3998. this->GroupNameMap[curr_folder] = group;
  3999. tgroup = group;
  4000. } else {
  4001. tgroup = i_folder->second;
  4002. }
  4003. curr_folder += '\\';
  4004. }
  4005. return tgroup;
  4006. }
  4007. cmXCodeObject* group = this->CreatePBXGroup(tgroup, sg->GetName());
  4008. this->GroupNameMap[s] = group;
  4009. return group;
  4010. }
  4011. bool cmGlobalXCodeGenerator::CreateXCodeObjects(
  4012. cmLocalGenerator* root, std::vector<cmLocalGenerator*>& generators)
  4013. {
  4014. this->ClearXCodeObjects();
  4015. this->RootObject = nullptr;
  4016. this->MainGroupChildren = nullptr;
  4017. this->FrameworkGroup = nullptr;
  4018. cmXCodeObject* group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  4019. group->AddAttribute("COPY_PHASE_STRIP", this->CreateString("NO"));
  4020. cmXCodeObject* listObjs = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4021. for (const std::string& CurrentConfigurationType :
  4022. this->CurrentConfigurationTypes) {
  4023. cmXCodeObject* buildStyle =
  4024. this->CreateObject(cmXCodeObject::PBXBuildStyle);
  4025. const std::string& name = CurrentConfigurationType;
  4026. buildStyle->AddAttribute("name", this->CreateString(name));
  4027. buildStyle->SetComment(name);
  4028. cmXCodeObject* sgroup = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  4029. sgroup->AddAttribute("COPY_PHASE_STRIP", this->CreateString("NO"));
  4030. buildStyle->AddAttribute("buildSettings", sgroup);
  4031. listObjs->AddObject(buildStyle);
  4032. }
  4033. cmXCodeObject* mainGroup = this->CreateObject(cmXCodeObject::PBXGroup);
  4034. this->MainGroupChildren = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4035. mainGroup->AddAttribute("children", this->MainGroupChildren);
  4036. mainGroup->AddAttribute("sourceTree", this->CreateString("<group>"));
  4037. // now create the cmake groups
  4038. if (!this->CreateGroups(generators)) {
  4039. return false;
  4040. }
  4041. cmXCodeObject* productGroup = this->CreateObject(cmXCodeObject::PBXGroup);
  4042. productGroup->AddAttribute("name", this->CreateString("Products"));
  4043. productGroup->AddAttribute("sourceTree", this->CreateString("<group>"));
  4044. cmXCodeObject* productGroupChildren =
  4045. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4046. productGroup->AddAttribute("children", productGroupChildren);
  4047. this->MainGroupChildren->AddObject(productGroup);
  4048. this->FrameworkGroup = this->CreateObject(cmXCodeObject::PBXGroup);
  4049. this->FrameworkGroup->AddAttribute("name", this->CreateString("Frameworks"));
  4050. this->FrameworkGroup->AddAttribute("sourceTree",
  4051. this->CreateString("<group>"));
  4052. cmXCodeObject* frameworkGroupChildren =
  4053. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4054. this->FrameworkGroup->AddAttribute("children", frameworkGroupChildren);
  4055. this->MainGroupChildren->AddObject(this->FrameworkGroup);
  4056. this->ResourcesGroup = this->CreateObject(cmXCodeObject::PBXGroup);
  4057. this->ResourcesGroup->AddAttribute("name", this->CreateString("Resources"));
  4058. this->ResourcesGroup->AddAttribute("sourceTree",
  4059. this->CreateString("<group>"));
  4060. cmXCodeObject* ResourcesGroupChildren =
  4061. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4062. this->ResourcesGroup->AddAttribute("children", ResourcesGroupChildren);
  4063. this->MainGroupChildren->AddObject(this->ResourcesGroup);
  4064. this->RootObject = this->CreateObject(cmXCodeObject::PBXProject);
  4065. this->RootObject->SetComment("Project object");
  4066. std::string project_id = cmStrCat("PROJECT_", root->GetProjectName());
  4067. this->RootObject->SetId(
  4068. this->GetOrCreateId(project_id, this->RootObject->GetId()));
  4069. group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  4070. this->RootObject->AddAttribute("mainGroup",
  4071. this->CreateObjectReference(mainGroup));
  4072. this->RootObject->AddAttribute("buildSettings", group);
  4073. this->RootObject->AddAttribute("buildStyles", listObjs);
  4074. this->RootObject->AddAttribute("hasScannedForEncodings",
  4075. this->CreateString("0"));
  4076. group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  4077. group->AddAttribute("BuildIndependentTargetsInParallel",
  4078. this->CreateString("YES"));
  4079. std::ostringstream v;
  4080. v << std::setfill('0') << std::setw(4) << XcodeVersion * 10;
  4081. group->AddAttribute("LastUpgradeCheck", this->CreateString(v.str()));
  4082. this->RootObject->AddAttribute("attributes", group);
  4083. this->RootObject->AddAttribute("compatibilityVersion",
  4084. this->CreateString("Xcode 3.2"));
  4085. // Point Xcode at the top of the source tree.
  4086. {
  4087. std::string pdir =
  4088. this->RelativeToBinary(root->GetCurrentSourceDirectory());
  4089. this->RootObject->AddAttribute("projectDirPath", this->CreateString(pdir));
  4090. this->RootObject->AddAttribute("projectRoot", this->CreateString(""));
  4091. }
  4092. cmXCodeObject* configlist =
  4093. this->CreateObject(cmXCodeObject::XCConfigurationList);
  4094. cmXCodeObject* buildConfigurations =
  4095. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4096. using Configs = std::vector<std::pair<std::string, cmXCodeObject*>>;
  4097. Configs configs;
  4098. std::string defaultConfigName;
  4099. for (const auto& name : this->CurrentConfigurationTypes) {
  4100. if (defaultConfigName.empty()) {
  4101. defaultConfigName = name;
  4102. }
  4103. cmXCodeObject* config =
  4104. this->CreateObject(cmXCodeObject::XCBuildConfiguration);
  4105. config->AddAttribute("name", this->CreateString(name));
  4106. configs.emplace_back(name, config);
  4107. }
  4108. if (defaultConfigName.empty()) {
  4109. defaultConfigName = "Debug";
  4110. }
  4111. for (auto& config : configs) {
  4112. buildConfigurations->AddObject(config.second);
  4113. }
  4114. configlist->AddAttribute("buildConfigurations", buildConfigurations);
  4115. std::string comment = cmStrCat("Build configuration list for PBXProject \"",
  4116. this->CurrentProject, '"');
  4117. configlist->SetComment(comment);
  4118. configlist->AddAttribute("defaultConfigurationIsVisible",
  4119. this->CreateString("0"));
  4120. configlist->AddAttribute("defaultConfigurationName",
  4121. this->CreateString(defaultConfigName));
  4122. cmXCodeObject* buildSettings =
  4123. this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  4124. cmValue sysroot = this->CurrentMakefile->GetDefinition("CMAKE_OSX_SYSROOT");
  4125. cmValue deploymentTarget =
  4126. this->CurrentMakefile->GetDefinition("CMAKE_OSX_DEPLOYMENT_TARGET");
  4127. if (sysroot) {
  4128. buildSettings->AddAttribute("SDKROOT", this->CreateString(*sysroot));
  4129. }
  4130. // recompute this as it may have been changed since enable language
  4131. this->ComputeArchitectures(this->CurrentMakefile);
  4132. std::string const archs = cmJoin(this->Architectures, " ");
  4133. if (archs.empty()) {
  4134. // Tell Xcode to use NATIVE_ARCH instead of ARCHS.
  4135. buildSettings->AddAttribute("ONLY_ACTIVE_ARCH", this->CreateString("YES"));
  4136. // When targeting macOS, use only the host architecture.
  4137. if (this->SystemName == "Darwin"_s &&
  4138. (!cmNonempty(sysroot) ||
  4139. cmSystemTools::LowerCase(*sysroot).find("macos") !=
  4140. std::string::npos)) {
  4141. buildSettings->AddAttribute("ARCHS",
  4142. this->CreateString("$(NATIVE_ARCH_ACTUAL)"));
  4143. }
  4144. } else {
  4145. // Tell Xcode to use ARCHS (ONLY_ACTIVE_ARCH defaults to NO).
  4146. buildSettings->AddAttribute("ARCHS", this->CreateString(archs));
  4147. }
  4148. if (cmNonempty(deploymentTarget)) {
  4149. buildSettings->AddAttribute(GetDeploymentPlatform(root->GetMakefile()),
  4150. this->CreateString(*deploymentTarget));
  4151. }
  4152. if (!this->GeneratorToolset.empty()) {
  4153. buildSettings->AddAttribute("GCC_VERSION",
  4154. this->CreateString(this->GeneratorToolset));
  4155. }
  4156. if (this->GetLanguageEnabled("Swift")) {
  4157. std::string swiftVersion;
  4158. if (cmValue vers = this->CurrentMakefile->GetDefinition(
  4159. "CMAKE_Swift_LANGUAGE_VERSION")) {
  4160. swiftVersion = *vers;
  4161. } else if (this->XcodeVersion >= 102) {
  4162. swiftVersion = "4.0";
  4163. } else if (this->XcodeVersion >= 83) {
  4164. swiftVersion = "3.0";
  4165. } else {
  4166. swiftVersion = "2.3";
  4167. }
  4168. buildSettings->AddAttribute("SWIFT_VERSION",
  4169. this->CreateString(swiftVersion));
  4170. }
  4171. std::string const symroot = this->GetSymrootDir();
  4172. buildSettings->AddAttribute("SYMROOT", this->CreateString(symroot));
  4173. // Inside a try_compile project, do not require signing on any platform.
  4174. if (this->CMakeInstance->GetIsInTryCompile()) {
  4175. buildSettings->AddAttribute("CODE_SIGNING_ALLOWED",
  4176. this->CreateString("NO"));
  4177. }
  4178. auto debugConfigs = this->GetCMakeInstance()->GetDebugConfigs();
  4179. std::set<std::string> debugConfigSet(debugConfigs.begin(),
  4180. debugConfigs.end());
  4181. for (auto& config : configs) {
  4182. CreateGlobalXCConfigSettings(root, config.second, config.first);
  4183. cmXCodeObject* buildSettingsForCfg = this->CreateFlatClone(buildSettings);
  4184. if (debugConfigSet.count(cmSystemTools::UpperCase(config.first)) == 0) {
  4185. buildSettingsForCfg->AddAttribute("SWIFT_COMPILATION_MODE",
  4186. this->CreateString("wholemodule"));
  4187. }
  4188. // Put this last so it can override existing settings
  4189. // Convert "CMAKE_XCODE_ATTRIBUTE_*" variables directly.
  4190. for (const auto& var : this->CurrentMakefile->GetDefinitions()) {
  4191. if (cmHasLiteralPrefix(var, "CMAKE_XCODE_ATTRIBUTE_")) {
  4192. std::string attribute = var.substr(22);
  4193. this->FilterConfigurationAttribute(config.first, attribute);
  4194. if (!attribute.empty()) {
  4195. std::string processed = cmGeneratorExpression::Evaluate(
  4196. this->CurrentMakefile->GetSafeDefinition(var),
  4197. this->CurrentLocalGenerator, config.first);
  4198. buildSettingsForCfg->AddAttribute(attribute,
  4199. this->CreateString(processed));
  4200. }
  4201. }
  4202. }
  4203. // store per-config buildSettings into configuration object
  4204. config.second->AddAttribute("buildSettings", buildSettingsForCfg);
  4205. }
  4206. this->RootObject->AddAttribute("buildConfigurationList",
  4207. this->CreateObjectReference(configlist));
  4208. std::vector<cmXCodeObject*> targets;
  4209. for (auto& generator : generators) {
  4210. if (!this->CreateXCodeTargets(generator, targets)) {
  4211. return false;
  4212. }
  4213. for (auto const& ccRoot : this->CustomCommandRoots) {
  4214. if (ccRoot.second.size() > 1) {
  4215. std::string e = "The custom command ";
  4216. std::vector<std::string> const& outputs =
  4217. ccRoot.first->GetCustomCommand()->GetOutputs();
  4218. if (!outputs.empty()) {
  4219. e = cmStrCat(e, "generating\n ", outputs[0]);
  4220. } else {
  4221. e = cmStrCat(e, "driven by\n ", ccRoot.first->GetFullPath());
  4222. }
  4223. e = cmStrCat(e, "\nis attached to multiple targets:");
  4224. for (cmGeneratorTarget const* gt : ccRoot.second) {
  4225. e = cmStrCat(e, "\n ", gt->GetName());
  4226. }
  4227. e = cmStrCat(
  4228. e,
  4229. "\nbut none of these is a common dependency of the other(s). "
  4230. "This is not allowed by the Xcode \"new build system\".");
  4231. generator->IssueMessage(MessageType::FATAL_ERROR, e);
  4232. return false;
  4233. }
  4234. }
  4235. this->CustomCommandRoots.clear();
  4236. }
  4237. // loop over all targets and add link and depend info
  4238. for (auto* t : targets) {
  4239. this->AddDependAndLinkInformation(t);
  4240. this->AddEmbeddedFrameworks(t);
  4241. this->AddEmbeddedPlugIns(t);
  4242. this->AddEmbeddedAppExtensions(t);
  4243. this->AddEmbeddedExtensionKitExtensions(t);
  4244. this->AddEmbeddedResources(t);
  4245. // Inherit project-wide values for any target-specific search paths.
  4246. this->InheritBuildSettingAttribute(t, "HEADER_SEARCH_PATHS");
  4247. this->InheritBuildSettingAttribute(t, "SYSTEM_HEADER_SEARCH_PATHS");
  4248. this->InheritBuildSettingAttribute(t, "FRAMEWORK_SEARCH_PATHS");
  4249. this->InheritBuildSettingAttribute(t, "SYSTEM_FRAMEWORK_SEARCH_PATHS");
  4250. this->InheritBuildSettingAttribute(t, "LIBRARY_SEARCH_PATHS");
  4251. this->InheritBuildSettingAttribute(t, "LD_RUNPATH_SEARCH_PATHS");
  4252. this->InheritBuildSettingAttribute(t, "GCC_PREPROCESSOR_DEFINITIONS");
  4253. this->InheritBuildSettingAttribute(t, "OTHER_CFLAGS");
  4254. this->InheritBuildSettingAttribute(t, "OTHER_LDFLAGS");
  4255. this->InheritBuildSettingAttribute(t, "OTHER_SWIFT_FLAGS");
  4256. this->InheritBuildSettingAttribute(t,
  4257. "SWIFT_ACTIVE_COMPILATION_CONDITIONS");
  4258. }
  4259. if (this->XcodeBuildSystem == BuildSystem::One) {
  4260. this->CreateXCodeDependHackMakefile(targets);
  4261. }
  4262. // now add all targets to the root object
  4263. cmXCodeObject* allTargets = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  4264. for (auto* t : targets) {
  4265. allTargets->AddObject(t);
  4266. cmXCodeObject* productRef = t->GetAttribute("productReference");
  4267. if (productRef) {
  4268. productGroupChildren->AddObject(productRef->GetObject());
  4269. }
  4270. }
  4271. this->RootObject->AddAttribute("targets", allTargets);
  4272. return true;
  4273. }
  4274. std::string cmGlobalXCodeGenerator::GetSymrootDir() const
  4275. {
  4276. return cmStrCat(this->CMakeInstance->GetHomeOutputDirectory(), "/build");
  4277. }
  4278. std::string cmGlobalXCodeGenerator::GetTargetTempDir(
  4279. cmGeneratorTarget const* gt, std::string const& configName) const
  4280. {
  4281. // Use a path inside the SYMROOT.
  4282. return cmStrCat(this->GetSymrootDir(), '/', gt->GetName(), ".build/",
  4283. configName);
  4284. }
  4285. void cmGlobalXCodeGenerator::ComputeArchitectures(cmMakefile* mf)
  4286. {
  4287. this->Architectures.clear();
  4288. cmList::append(this->Architectures,
  4289. mf->GetDefinition("CMAKE_OSX_ARCHITECTURES"));
  4290. if (this->Architectures.empty()) {
  4291. cmList::append(this->Architectures,
  4292. mf->GetDefinition("_CMAKE_APPLE_ARCHS_DEFAULT"));
  4293. }
  4294. if (this->Architectures.empty()) {
  4295. // With no ARCHS we use ONLY_ACTIVE_ARCH and possibly a
  4296. // platform-specific default ARCHS placeholder value.
  4297. // Look up the arch that Xcode chooses in this case.
  4298. if (cmValue arch = mf->GetDefinition("CMAKE_XCODE_ARCHS")) {
  4299. this->ObjectDirArchDefault = *arch;
  4300. // We expect only one arch but choose the first just in case.
  4301. std::string::size_type pos = this->ObjectDirArchDefault.find(';');
  4302. if (pos != std::string::npos) {
  4303. this->ObjectDirArchDefault = this->ObjectDirArchDefault.substr(0, pos);
  4304. }
  4305. }
  4306. }
  4307. this->ComputeObjectDirArch(mf);
  4308. }
  4309. void cmGlobalXCodeGenerator::ComputeObjectDirArch(cmMakefile* mf)
  4310. {
  4311. if (this->Architectures.size() > 1 || this->UseEffectivePlatformName(mf)) {
  4312. this->ObjectDirArch = "$(CURRENT_ARCH)";
  4313. } else if (!this->Architectures.empty()) {
  4314. this->ObjectDirArch = this->Architectures[0];
  4315. } else {
  4316. this->ObjectDirArch = this->ObjectDirArchDefault;
  4317. }
  4318. }
  4319. void cmGlobalXCodeGenerator::CreateXCodeDependHackMakefile(
  4320. std::vector<cmXCodeObject*>& targets)
  4321. {
  4322. cmGeneratedFileStream makefileStream(this->CurrentXCodeHackMakefile);
  4323. if (!makefileStream) {
  4324. cmSystemTools::Error(
  4325. cmStrCat("Could not create ", this->CurrentXCodeHackMakefile));
  4326. return;
  4327. }
  4328. makefileStream.SetCopyIfDifferent(true);
  4329. // one more pass for external depend information not handled
  4330. // correctly by xcode
  4331. /* clang-format off */
  4332. makefileStream << "# DO NOT EDIT\n"
  4333. "# This makefile makes sure all linkable targets are\n"
  4334. "# up-to-date with anything they link to\n"
  4335. "default:\n"
  4336. "\techo \"Do not invoke directly\"\n"
  4337. "\n";
  4338. /* clang-format on */
  4339. std::set<std::string> dummyRules;
  4340. // Write rules to help Xcode relink things at the right time.
  4341. /* clang-format off */
  4342. makefileStream <<
  4343. "# Rules to remove targets that are older than anything to which they\n"
  4344. "# link. This forces Xcode to relink the targets from scratch. It\n"
  4345. "# does not seem to check these dependencies itself.\n";
  4346. /* clang-format on */
  4347. for (const auto& configName : this->CurrentConfigurationTypes) {
  4348. for (auto* target : targets) {
  4349. cmGeneratorTarget* gt = target->GetTarget();
  4350. if (gt->GetType() == cmStateEnums::EXECUTABLE ||
  4351. gt->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  4352. gt->GetType() == cmStateEnums::STATIC_LIBRARY ||
  4353. gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4354. gt->GetType() == cmStateEnums::MODULE_LIBRARY) {
  4355. // Declare an entry point for the target post-build phase.
  4356. makefileStream << this->PostBuildMakeTarget(gt->GetName(), configName)
  4357. << ":\n";
  4358. }
  4359. if (gt->GetType() == cmStateEnums::EXECUTABLE ||
  4360. gt->GetType() == cmStateEnums::STATIC_LIBRARY ||
  4361. gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4362. gt->GetType() == cmStateEnums::MODULE_LIBRARY) {
  4363. std::string tfull = gt->GetFullPath(configName);
  4364. std::string trel = this->ConvertToRelativeForMake(tfull);
  4365. // Add this target to the post-build phases of its dependencies.
  4366. auto const y = target->GetDependTargets().find(configName);
  4367. if (y != target->GetDependTargets().end()) {
  4368. for (auto const& deptgt : y->second) {
  4369. makefileStream << this->PostBuildMakeTarget(deptgt, configName)
  4370. << ": " << trel << '\n';
  4371. }
  4372. }
  4373. std::vector<cmGeneratorTarget*> objlibs;
  4374. gt->GetObjectLibrariesCMP0026(objlibs);
  4375. for (auto* objLib : objlibs) {
  4376. makefileStream << this->PostBuildMakeTarget(objLib->GetName(),
  4377. configName)
  4378. << ": " << trel << '\n';
  4379. }
  4380. // Create a rule for this target.
  4381. makefileStream << trel << ':';
  4382. // List dependencies if any exist.
  4383. auto const x = target->GetDependLibraries().find(configName);
  4384. if (x != target->GetDependLibraries().end()) {
  4385. for (auto const& deplib : x->second) {
  4386. std::string file = this->ConvertToRelativeForMake(deplib);
  4387. makefileStream << "\\\n\t" << file;
  4388. dummyRules.insert(file);
  4389. }
  4390. }
  4391. for (auto* objLib : objlibs) {
  4392. const std::string objLibName = objLib->GetName();
  4393. std::string d = cmStrCat(this->GetTargetTempDir(gt, configName),
  4394. "/lib", objLibName, ".a");
  4395. std::string dependency = this->ConvertToRelativeForMake(d);
  4396. makefileStream << "\\\n\t" << dependency;
  4397. dummyRules.insert(dependency);
  4398. }
  4399. // Write the action to remove the target if it is out of date.
  4400. makefileStream << "\n"
  4401. "\t/bin/rm -f "
  4402. << this->ConvertToRelativeForMake(tfull) << '\n';
  4403. // if building for more than one architecture
  4404. // then remove those executables as well
  4405. if (this->Architectures.size() > 1) {
  4406. std::string universal =
  4407. cmStrCat(this->GetTargetTempDir(gt, configName), "/$(OBJDIR)/");
  4408. for (const auto& architecture : this->Architectures) {
  4409. std::string universalFile = cmStrCat(universal, architecture, '/',
  4410. gt->GetFullName(configName));
  4411. makefileStream << "\t/bin/rm -f "
  4412. << this->ConvertToRelativeForMake(universalFile)
  4413. << '\n';
  4414. }
  4415. }
  4416. makefileStream << "\n\n";
  4417. }
  4418. }
  4419. }
  4420. makefileStream << "\n\n"
  4421. "# For each target create a dummy rule"
  4422. "so the target does not have to exist\n";
  4423. for (auto const& dummyRule : dummyRules) {
  4424. makefileStream << dummyRule << ":\n";
  4425. }
  4426. }
  4427. void cmGlobalXCodeGenerator::OutputXCodeProject(
  4428. cmLocalGenerator* root, std::vector<cmLocalGenerator*>& generators)
  4429. {
  4430. if (generators.empty()) {
  4431. return;
  4432. }
  4433. if (!this->CreateXCodeObjects(root, generators)) {
  4434. return;
  4435. }
  4436. std::string xcodeDir = cmStrCat(root->GetCurrentBinaryDirectory(), '/',
  4437. root->GetProjectName(), ".xcodeproj");
  4438. cmSystemTools::MakeDirectory(xcodeDir);
  4439. std::string xcodeProjFile = cmStrCat(xcodeDir, "/project.pbxproj");
  4440. cmGeneratedFileStream fout(xcodeProjFile);
  4441. fout.SetCopyIfDifferent(true);
  4442. if (!fout) {
  4443. return;
  4444. }
  4445. this->WriteXCodePBXProj(fout, root, generators);
  4446. bool hasGeneratedSchemes = this->OutputXCodeSharedSchemes(xcodeDir, root);
  4447. this->OutputXCodeWorkspaceSettings(xcodeDir, hasGeneratedSchemes);
  4448. this->ClearXCodeObjects();
  4449. // Since this call may have created new cache entries, save the cache:
  4450. //
  4451. root->GetMakefile()->GetCMakeInstance()->SaveCache(
  4452. root->GetBinaryDirectory());
  4453. }
  4454. bool cmGlobalXCodeGenerator::OutputXCodeSharedSchemes(
  4455. const std::string& xcProjDir, cmLocalGenerator* root)
  4456. {
  4457. // collect all tests for the targets
  4458. std::map<std::string, cmXCodeScheme::TestObjects> testables;
  4459. for (const auto& obj : this->XCodeObjects) {
  4460. if (obj->GetType() != cmXCodeObject::OBJECT ||
  4461. obj->GetIsA() != cmXCodeObject::PBXNativeTarget) {
  4462. continue;
  4463. }
  4464. if (!obj->GetTarget()->IsXCTestOnApple()) {
  4465. continue;
  4466. }
  4467. cmValue testee = obj->GetTarget()->GetProperty("XCTEST_TESTEE");
  4468. if (!testee) {
  4469. continue;
  4470. }
  4471. testables[*testee].push_back(obj.get());
  4472. }
  4473. // generate scheme
  4474. bool ret = false;
  4475. // Since the lowest available Xcode version for testing was 6.4,
  4476. // I'm setting this as a limit then
  4477. if (this->XcodeVersion >= 64) {
  4478. for (const auto& obj : this->XCodeObjects) {
  4479. if (obj->GetType() == cmXCodeObject::OBJECT &&
  4480. (obj->GetIsA() == cmXCodeObject::PBXNativeTarget ||
  4481. obj->GetIsA() == cmXCodeObject::PBXAggregateTarget) &&
  4482. (root->GetMakefile()->GetCMakeInstance()->GetIsInTryCompile() ||
  4483. obj->GetTarget()->GetPropertyAsBool("XCODE_GENERATE_SCHEME"))) {
  4484. const std::string& targetName = obj->GetTarget()->GetName();
  4485. cmXCodeScheme schm(root, obj.get(), testables[targetName],
  4486. this->CurrentConfigurationTypes,
  4487. this->XcodeVersion);
  4488. schm.WriteXCodeSharedScheme(xcProjDir,
  4489. this->RelativeToSource(xcProjDir));
  4490. ret = true;
  4491. }
  4492. }
  4493. }
  4494. return ret;
  4495. }
  4496. void cmGlobalXCodeGenerator::OutputXCodeWorkspaceSettings(
  4497. const std::string& xcProjDir, bool hasGeneratedSchemes)
  4498. {
  4499. std::string xcodeSharedDataDir =
  4500. cmStrCat(xcProjDir, "/project.xcworkspace/xcshareddata");
  4501. cmSystemTools::MakeDirectory(xcodeSharedDataDir);
  4502. std::string workspaceSettingsFile =
  4503. cmStrCat(xcodeSharedDataDir, "/WorkspaceSettings.xcsettings");
  4504. cmGeneratedFileStream fout(workspaceSettingsFile);
  4505. fout.SetCopyIfDifferent(true);
  4506. if (!fout) {
  4507. return;
  4508. }
  4509. cmXMLWriter xout(fout);
  4510. xout.StartDocument();
  4511. xout.Doctype("plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\""
  4512. "\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"");
  4513. xout.StartElement("plist");
  4514. xout.Attribute("version", "1.0");
  4515. xout.StartElement("dict");
  4516. if (this->XcodeVersion >= 100) {
  4517. xout.Element("key", "BuildSystemType");
  4518. switch (this->XcodeBuildSystem) {
  4519. case BuildSystem::One:
  4520. xout.Element("string", "Original");
  4521. if (this->XcodeVersion >= 130) {
  4522. xout.Element("key", "DisableBuildSystemDeprecationDiagnostic");
  4523. } else {
  4524. xout.Element("key", "DisableBuildSystemDeprecationWarning");
  4525. }
  4526. xout.Element("true");
  4527. break;
  4528. case BuildSystem::Twelve:
  4529. xout.Element("string", "Latest");
  4530. break;
  4531. }
  4532. }
  4533. if (hasGeneratedSchemes) {
  4534. xout.Element("key",
  4535. "IDEWorkspaceSharedSettings_AutocreateContextsIfNeeded");
  4536. xout.Element("false");
  4537. }
  4538. xout.EndElement(); // dict
  4539. xout.EndElement(); // plist
  4540. xout.EndDocument();
  4541. }
  4542. void cmGlobalXCodeGenerator::WriteXCodePBXProj(std::ostream& fout,
  4543. cmLocalGenerator*,
  4544. std::vector<cmLocalGenerator*>&)
  4545. {
  4546. SortXCodeObjects();
  4547. fout << "// !$*UTF8*$!\n"
  4548. "{\n";
  4549. cmXCodeObject::Indent(1, fout);
  4550. fout << "archiveVersion = 1;\n";
  4551. cmXCodeObject::Indent(1, fout);
  4552. fout << "classes = {\n";
  4553. cmXCodeObject::Indent(1, fout);
  4554. fout << "};\n";
  4555. cmXCodeObject::Indent(1, fout);
  4556. fout << "objectVersion = 46;\n";
  4557. cmXCode21Object::PrintList(this->XCodeObjects, fout);
  4558. cmXCodeObject::Indent(1, fout);
  4559. fout << "rootObject = " << this->RootObject->GetId()
  4560. << " /* Project object */;\n"
  4561. "}\n";
  4562. }
  4563. const char* cmGlobalXCodeGenerator::GetCMakeCFGIntDir() const
  4564. {
  4565. return "$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)";
  4566. }
  4567. std::string cmGlobalXCodeGenerator::ExpandCFGIntDir(
  4568. const std::string& str, const std::string& config) const
  4569. {
  4570. std::string replace1 = "$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)";
  4571. std::string replace2 = "$(CONFIGURATION)";
  4572. std::string tmp = str;
  4573. for (std::string::size_type i = tmp.find(replace1); i != std::string::npos;
  4574. i = tmp.find(replace1, i)) {
  4575. tmp.replace(i, replace1.size(), config);
  4576. i += config.size();
  4577. }
  4578. for (std::string::size_type i = tmp.find(replace2); i != std::string::npos;
  4579. i = tmp.find(replace2, i)) {
  4580. tmp.replace(i, replace2.size(), config);
  4581. i += config.size();
  4582. }
  4583. return tmp;
  4584. }
  4585. cmDocumentationEntry cmGlobalXCodeGenerator::GetDocumentation()
  4586. {
  4587. return { cmGlobalXCodeGenerator::GetActualName(),
  4588. "Generate Xcode project files." };
  4589. }
  4590. std::string cmGlobalXCodeGenerator::ConvertToRelativeForMake(
  4591. std::string const& p)
  4592. {
  4593. return cmSystemTools::ConvertToOutputPath(p);
  4594. }
  4595. std::string cmGlobalXCodeGenerator::RelativeToSource(const std::string& p)
  4596. {
  4597. std::string const& rootSrc =
  4598. this->CurrentRootGenerator->GetCurrentSourceDirectory();
  4599. if (cmSystemTools::IsSubDirectory(p, rootSrc)) {
  4600. return cmSystemTools::ForceToRelativePath(rootSrc, p);
  4601. }
  4602. return p;
  4603. }
  4604. std::string cmGlobalXCodeGenerator::RelativeToBinary(const std::string& p)
  4605. {
  4606. return this->CurrentRootGenerator->MaybeRelativeToCurBinDir(p);
  4607. }
  4608. std::string cmGlobalXCodeGenerator::XCodeEscapePath(const std::string& p)
  4609. {
  4610. if (p.find_first_of(" []") != std::string::npos) {
  4611. std::string t = cmStrCat('"', p, '"');
  4612. return t;
  4613. }
  4614. return p;
  4615. }
  4616. void cmGlobalXCodeGenerator::AppendDirectoryForConfig(
  4617. const std::string& prefix, const std::string& config,
  4618. const std::string& suffix, std::string& dir)
  4619. {
  4620. if (!config.empty()) {
  4621. dir += prefix;
  4622. dir += config;
  4623. dir += suffix;
  4624. }
  4625. }
  4626. std::string cmGlobalXCodeGenerator::LookupFlags(
  4627. const std::string& varNamePrefix, const std::string& varNameLang,
  4628. const std::string& varNameSuffix, const std::string& default_flags)
  4629. {
  4630. if (!varNameLang.empty()) {
  4631. std::string varName = cmStrCat(varNamePrefix, varNameLang, varNameSuffix);
  4632. if (cmValue varValue = this->CurrentMakefile->GetDefinition(varName)) {
  4633. if (!varValue->empty()) {
  4634. return *varValue;
  4635. }
  4636. }
  4637. }
  4638. return default_flags;
  4639. }
  4640. void cmGlobalXCodeGenerator::AppendDefines(BuildObjectListOrString& defs,
  4641. const char* defines_list,
  4642. bool dflag)
  4643. {
  4644. // Skip this if there are no definitions.
  4645. if (!defines_list) {
  4646. return;
  4647. }
  4648. // Expand the list of definitions.
  4649. cmList defines{ defines_list };
  4650. // Store the definitions in the string.
  4651. this->AppendDefines(defs, defines, dflag);
  4652. }
  4653. void cmGlobalXCodeGenerator::AppendDefines(
  4654. BuildObjectListOrString& defs, std::vector<std::string> const& defines,
  4655. bool dflag)
  4656. {
  4657. // GCC_PREPROCESSOR_DEFINITIONS is a space-separated list of definitions.
  4658. std::string def;
  4659. for (auto const& define : defines) {
  4660. // Start with -D if requested.
  4661. if (dflag && !cmHasLiteralPrefix(define, "-D")) {
  4662. def = cmStrCat("-D", define);
  4663. } else if (!dflag && cmHasLiteralPrefix(define, "-D")) {
  4664. def = define.substr(2);
  4665. } else {
  4666. def = define;
  4667. }
  4668. // Append the flag with needed escapes.
  4669. std::string tmp;
  4670. this->AppendFlag(tmp, def);
  4671. defs.Add(tmp);
  4672. }
  4673. }
  4674. void cmGlobalXCodeGenerator::AppendFlag(std::string& flags,
  4675. std::string const& flag) const
  4676. {
  4677. // Short-circuit for an empty flag.
  4678. if (flag.empty()) {
  4679. return;
  4680. }
  4681. // Separate from previous flags.
  4682. if (!flags.empty()) {
  4683. flags += ' ';
  4684. }
  4685. // Check if the flag needs quoting.
  4686. bool quoteFlag =
  4687. flag.find_first_of("`~!@#$%^&*()+={}[]|:;\"'<>,.? ") != std::string::npos;
  4688. // We escape a flag as follows:
  4689. // - Place each flag in single quotes ''
  4690. // - Escape a single quote as \'
  4691. // - Escape a backslash as \\ since it itself is an escape
  4692. // Note that in the code below we need one more level of escapes for
  4693. // C string syntax in this source file.
  4694. //
  4695. // The final level of escaping is done when the string is stored
  4696. // into the project file by cmXCodeObject::PrintString.
  4697. if (quoteFlag) {
  4698. // Open single quote.
  4699. flags += '\'';
  4700. }
  4701. // Flag value with escaped quotes and backslashes.
  4702. for (auto c : flag) {
  4703. if (c == '\'') {
  4704. flags += "'\\''";
  4705. } else if (c == '\\') {
  4706. flags += "\\\\";
  4707. } else {
  4708. flags += c;
  4709. }
  4710. }
  4711. if (quoteFlag) {
  4712. // Close single quote.
  4713. flags += '\'';
  4714. }
  4715. }
  4716. std::string cmGlobalXCodeGenerator::ComputeInfoPListLocation(
  4717. cmGeneratorTarget* target)
  4718. {
  4719. std::string plist =
  4720. cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(),
  4721. "/CMakeFiles/", target->GetName(), ".dir/Info.plist");
  4722. return plist;
  4723. }
  4724. // Return true if the generated build tree may contain multiple builds.
  4725. // i.e. "Can I build Debug and Release in the same tree?"
  4726. bool cmGlobalXCodeGenerator::IsMultiConfig() const
  4727. {
  4728. // Newer Xcode versions are multi config:
  4729. return true;
  4730. }
  4731. bool cmGlobalXCodeGenerator::HasKnownObjectFileLocation(
  4732. cmTarget const& target, std::string* reason) const
  4733. {
  4734. auto objectDirArch = GetTargetObjectDirArch(target, this->ObjectDirArch);
  4735. if (objectDirArch.find('$') != std::string::npos) {
  4736. if (reason != nullptr) {
  4737. *reason = " under Xcode with multiple architectures";
  4738. }
  4739. return false;
  4740. }
  4741. return true;
  4742. }
  4743. bool cmGlobalXCodeGenerator::UseEffectivePlatformName(cmMakefile* mf) const
  4744. {
  4745. cmValue epnValue = this->GetCMakeInstance()->GetState()->GetGlobalProperty(
  4746. "XCODE_EMIT_EFFECTIVE_PLATFORM_NAME");
  4747. if (!epnValue) {
  4748. return mf->PlatformIsAppleEmbedded();
  4749. }
  4750. return cmIsOn(*epnValue);
  4751. }
  4752. bool cmGlobalXCodeGenerator::ShouldStripResourcePath(cmMakefile*) const
  4753. {
  4754. // Xcode determines Resource location itself
  4755. return true;
  4756. }
  4757. void cmGlobalXCodeGenerator::ComputeTargetObjectDirectory(
  4758. cmGeneratorTarget* gt) const
  4759. {
  4760. auto objectDirArch = GetTargetObjectDirArch(*gt, this->ObjectDirArch);
  4761. gt->ObjectDirectory =
  4762. cmStrCat(this->GetTargetTempDir(gt, this->GetCMakeCFGIntDir()),
  4763. "/$(OBJECT_FILE_DIR_normal:base)/", objectDirArch, '/');
  4764. }
  4765. std::string cmGlobalXCodeGenerator::GetDeploymentPlatform(const cmMakefile* mf)
  4766. {
  4767. switch (mf->GetAppleSDKType()) {
  4768. case cmMakefile::AppleSDK::AppleTVOS:
  4769. case cmMakefile::AppleSDK::AppleTVSimulator:
  4770. return "TVOS_DEPLOYMENT_TARGET";
  4771. case cmMakefile::AppleSDK::IPhoneOS:
  4772. case cmMakefile::AppleSDK::IPhoneSimulator:
  4773. return "IPHONEOS_DEPLOYMENT_TARGET";
  4774. case cmMakefile::AppleSDK::WatchOS:
  4775. case cmMakefile::AppleSDK::WatchSimulator:
  4776. return "WATCHOS_DEPLOYMENT_TARGET";
  4777. case cmMakefile::AppleSDK::XROS:
  4778. case cmMakefile::AppleSDK::XRSimulator:
  4779. return "XROS_DEPLOYMENT_TARGET";
  4780. case cmMakefile::AppleSDK::MacOS:
  4781. default:
  4782. return "MACOSX_DEPLOYMENT_TARGET";
  4783. }
  4784. }