cmGlobalXCodeGenerator.cxx 173 KB

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