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