cmGlobalXCodeGenerator.cxx 181 KB

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