cmGlobalXCodeGenerator.cxx 138 KB

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