cmGlobalXCodeGenerator.cxx 126 KB

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