cmGlobalXCodeGenerator.cxx 163 KB

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