cmGlobalXCodeGenerator.cxx 164 KB

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