cmGlobalXCodeGenerator.cxx 176 KB

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