cmGlobalXCodeGenerator.cxx 143 KB

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