cmGlobalXCodeGenerator.cxx 138 KB

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