cmGlobalXCodeGenerator.cxx 131 KB

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