cmGlobalXCodeGenerator.cxx 176 KB

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