cmGlobalXCodeGenerator.cxx 138 KB

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