cmGlobalXCodeGenerator.cxx 137 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908
  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 =
  946. this->CurrentMakefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  947. }
  948. struct cmSourceFilePathCompare
  949. {
  950. bool operator()(cmSourceFile* l, cmSourceFile* r)
  951. {
  952. return l->ResolveFullPath() < r->ResolveFullPath();
  953. }
  954. };
  955. struct cmCompareTargets
  956. {
  957. bool operator()(cmXCodeObject* l, cmXCodeObject* r) const
  958. {
  959. std::string const& a = l->GetTarget()->GetName();
  960. std::string const& b = r->GetTarget()->GetName();
  961. if (a == "ALL_BUILD") {
  962. return true;
  963. }
  964. if (b == "ALL_BUILD") {
  965. return false;
  966. }
  967. return a < b;
  968. }
  969. };
  970. bool cmGlobalXCodeGenerator::CreateXCodeTargets(
  971. cmLocalGenerator* gen, std::vector<cmXCodeObject*>& targets)
  972. {
  973. this->SetCurrentLocalGenerator(gen);
  974. std::vector<cmGeneratorTarget*> gts;
  975. cm::append(gts, this->CurrentLocalGenerator->GetGeneratorTargets());
  976. std::sort(gts.begin(), gts.end(),
  977. [this](cmGeneratorTarget const* l, cmGeneratorTarget const* r) {
  978. return this->TargetOrderIndex[l] < this->TargetOrderIndex[r];
  979. });
  980. for (auto gtgt : gts) {
  981. if (!this->CreateXCodeTarget(gtgt, targets)) {
  982. return false;
  983. }
  984. }
  985. std::sort(targets.begin(), targets.end(), cmCompareTargets());
  986. return true;
  987. }
  988. bool cmGlobalXCodeGenerator::CreateXCodeTarget(
  989. cmGeneratorTarget* gtgt, std::vector<cmXCodeObject*>& targets)
  990. {
  991. std::string targetName = gtgt->GetName();
  992. // make sure ALL_BUILD, INSTALL, etc are only done once
  993. if (this->SpecialTargetEmitted(targetName)) {
  994. return true;
  995. }
  996. if (gtgt->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  997. return true;
  998. }
  999. if (gtgt->GetType() == cmStateEnums::UTILITY ||
  1000. gtgt->GetType() == cmStateEnums::GLOBAL_TARGET) {
  1001. cmXCodeObject* t = this->CreateUtilityTarget(gtgt);
  1002. if (!t) {
  1003. return false;
  1004. }
  1005. targets.push_back(t);
  1006. return true;
  1007. }
  1008. // organize the sources
  1009. std::vector<cmSourceFile*> commonSourceFiles;
  1010. if (!gtgt->GetConfigCommonSourceFiles(commonSourceFiles)) {
  1011. return false;
  1012. }
  1013. // Add CMakeLists.txt file for user convenience.
  1014. this->AddXCodeProjBuildRule(gtgt, commonSourceFiles);
  1015. // Add the Info.plist we are about to generate for an App Bundle.
  1016. if (gtgt->GetPropertyAsBool("MACOSX_BUNDLE")) {
  1017. std::string plist = this->ComputeInfoPListLocation(gtgt);
  1018. cmSourceFile* sf = gtgt->Makefile->GetOrCreateSource(
  1019. plist, true, cmSourceFileLocationKind::Known);
  1020. commonSourceFiles.push_back(sf);
  1021. }
  1022. std::sort(commonSourceFiles.begin(), commonSourceFiles.end(),
  1023. cmSourceFilePathCompare());
  1024. gtgt->ComputeObjectMapping();
  1025. std::vector<cmXCodeObject*> externalObjFiles;
  1026. std::vector<cmXCodeObject*> headerFiles;
  1027. std::vector<cmXCodeObject*> resourceFiles;
  1028. std::vector<cmXCodeObject*> sourceFiles;
  1029. for (auto sourceFile : commonSourceFiles) {
  1030. cmXCodeObject* xsf = this->CreateXCodeSourceFile(
  1031. this->CurrentLocalGenerator, sourceFile, gtgt);
  1032. cmXCodeObject* fr = xsf->GetObject("fileRef");
  1033. cmXCodeObject* filetype = fr->GetObject()->GetObject("explicitFileType");
  1034. cmGeneratorTarget::SourceFileFlags tsFlags =
  1035. gtgt->GetTargetSourceFileFlags(sourceFile);
  1036. if (filetype && filetype->GetString() == "compiled.mach-o.objfile") {
  1037. if (sourceFile->GetObjectLibrary().empty()) {
  1038. externalObjFiles.push_back(xsf);
  1039. }
  1040. } else if (this->IsHeaderFile(sourceFile) ||
  1041. (tsFlags.Type ==
  1042. cmGeneratorTarget::SourceFileTypePrivateHeader) ||
  1043. (tsFlags.Type ==
  1044. cmGeneratorTarget::SourceFileTypePublicHeader)) {
  1045. headerFiles.push_back(xsf);
  1046. } else if (tsFlags.Type == cmGeneratorTarget::SourceFileTypeResource) {
  1047. resourceFiles.push_back(xsf);
  1048. } else if (!sourceFile->GetPropertyAsBool("HEADER_FILE_ONLY") &&
  1049. !gtgt->IsSourceFilePartOfUnityBatch(
  1050. sourceFile->ResolveFullPath())) {
  1051. // Include this file in the build if it has a known language
  1052. // and has not been listed as an ignored extension for this
  1053. // generator.
  1054. if (!this->CurrentLocalGenerator->GetSourceFileLanguage(*sourceFile)
  1055. .empty() &&
  1056. !this->IgnoreFile(sourceFile->GetExtension().c_str())) {
  1057. sourceFiles.push_back(xsf);
  1058. }
  1059. }
  1060. }
  1061. // some build phases only apply to bundles and/or frameworks
  1062. bool isFrameworkTarget = gtgt->IsFrameworkOnApple();
  1063. bool isBundleTarget = gtgt->GetPropertyAsBool("MACOSX_BUNDLE");
  1064. bool isCFBundleTarget = gtgt->IsCFBundleOnApple();
  1065. cmXCodeObject* buildFiles = nullptr;
  1066. // create source build phase
  1067. cmXCodeObject* sourceBuildPhase = nullptr;
  1068. if (!sourceFiles.empty()) {
  1069. sourceBuildPhase = this->CreateObject(cmXCodeObject::PBXSourcesBuildPhase);
  1070. sourceBuildPhase->SetComment("Sources");
  1071. sourceBuildPhase->AddAttribute("buildActionMask",
  1072. this->CreateString("2147483647"));
  1073. buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1074. for (auto& sourceFile : sourceFiles) {
  1075. buildFiles->AddObject(sourceFile);
  1076. }
  1077. sourceBuildPhase->AddAttribute("files", buildFiles);
  1078. sourceBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1079. this->CreateString("0"));
  1080. }
  1081. // create header build phase - only for framework targets
  1082. cmXCodeObject* headerBuildPhase = nullptr;
  1083. if (!headerFiles.empty() && isFrameworkTarget) {
  1084. headerBuildPhase = this->CreateObject(cmXCodeObject::PBXHeadersBuildPhase);
  1085. headerBuildPhase->SetComment("Headers");
  1086. headerBuildPhase->AddAttribute("buildActionMask",
  1087. this->CreateString("2147483647"));
  1088. buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1089. for (auto& headerFile : headerFiles) {
  1090. buildFiles->AddObject(headerFile);
  1091. }
  1092. headerBuildPhase->AddAttribute("files", buildFiles);
  1093. headerBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1094. this->CreateString("0"));
  1095. }
  1096. // create resource build phase - only for framework or bundle targets
  1097. cmXCodeObject* resourceBuildPhase = nullptr;
  1098. if (!resourceFiles.empty() &&
  1099. (isFrameworkTarget || isBundleTarget || isCFBundleTarget)) {
  1100. resourceBuildPhase =
  1101. this->CreateObject(cmXCodeObject::PBXResourcesBuildPhase);
  1102. resourceBuildPhase->SetComment("Resources");
  1103. resourceBuildPhase->AddAttribute("buildActionMask",
  1104. this->CreateString("2147483647"));
  1105. buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1106. for (auto& resourceFile : resourceFiles) {
  1107. buildFiles->AddObject(resourceFile);
  1108. }
  1109. resourceBuildPhase->AddAttribute("files", buildFiles);
  1110. resourceBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1111. this->CreateString("0"));
  1112. }
  1113. // create vector of "non-resource content file" build phases - only for
  1114. // framework or bundle targets
  1115. std::vector<cmXCodeObject*> contentBuildPhases;
  1116. if (isFrameworkTarget || isBundleTarget || isCFBundleTarget) {
  1117. using mapOfVectorOfSourceFiles =
  1118. std::map<std::string, std::vector<cmSourceFile*>>;
  1119. mapOfVectorOfSourceFiles bundleFiles;
  1120. for (auto sourceFile : commonSourceFiles) {
  1121. cmGeneratorTarget::SourceFileFlags tsFlags =
  1122. gtgt->GetTargetSourceFileFlags(sourceFile);
  1123. if (tsFlags.Type == cmGeneratorTarget::SourceFileTypeMacContent) {
  1124. bundleFiles[tsFlags.MacFolder].push_back(sourceFile);
  1125. }
  1126. }
  1127. for (auto const& keySources : bundleFiles) {
  1128. cmXCodeObject* copyFilesBuildPhase =
  1129. this->CreateObject(cmXCodeObject::PBXCopyFilesBuildPhase);
  1130. copyFilesBuildPhase->SetComment("Copy files");
  1131. copyFilesBuildPhase->AddAttribute("buildActionMask",
  1132. this->CreateString("2147483647"));
  1133. copyFilesBuildPhase->AddAttribute("dstSubfolderSpec",
  1134. this->CreateString("6"));
  1135. std::ostringstream ostr;
  1136. if (gtgt->IsFrameworkOnApple()) {
  1137. // dstPath in frameworks is relative to Versions/<version>
  1138. ostr << keySources.first;
  1139. } else if (keySources.first != "MacOS") {
  1140. if (gtgt->Target->GetMakefile()->PlatformIsAppleEmbedded()) {
  1141. ostr << keySources.first;
  1142. } else {
  1143. // dstPath in bundles is relative to Contents/MacOS
  1144. ostr << "../" << keySources.first;
  1145. }
  1146. }
  1147. copyFilesBuildPhase->AddAttribute("dstPath",
  1148. this->CreateString(ostr.str()));
  1149. copyFilesBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1150. this->CreateString("0"));
  1151. buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1152. copyFilesBuildPhase->AddAttribute("files", buildFiles);
  1153. for (auto sourceFile : keySources.second) {
  1154. cmXCodeObject* xsf = this->CreateXCodeSourceFile(
  1155. this->CurrentLocalGenerator, sourceFile, gtgt);
  1156. buildFiles->AddObject(xsf);
  1157. }
  1158. contentBuildPhases.push_back(copyFilesBuildPhase);
  1159. }
  1160. }
  1161. // create vector of "resource content file" build phases - only for
  1162. // framework or bundle targets
  1163. if (isFrameworkTarget || isBundleTarget || isCFBundleTarget) {
  1164. using mapOfVectorOfSourceFiles =
  1165. std::map<std::string, std::vector<cmSourceFile*>>;
  1166. mapOfVectorOfSourceFiles bundleFiles;
  1167. for (auto sourceFile : commonSourceFiles) {
  1168. cmGeneratorTarget::SourceFileFlags tsFlags =
  1169. gtgt->GetTargetSourceFileFlags(sourceFile);
  1170. if (tsFlags.Type == cmGeneratorTarget::SourceFileTypeDeepResource) {
  1171. bundleFiles[tsFlags.MacFolder].push_back(sourceFile);
  1172. }
  1173. }
  1174. for (auto const& keySources : bundleFiles) {
  1175. cmXCodeObject* copyFilesBuildPhase =
  1176. this->CreateObject(cmXCodeObject::PBXCopyFilesBuildPhase);
  1177. copyFilesBuildPhase->SetComment("Copy files");
  1178. copyFilesBuildPhase->AddAttribute("buildActionMask",
  1179. this->CreateString("2147483647"));
  1180. copyFilesBuildPhase->AddAttribute("dstSubfolderSpec",
  1181. this->CreateString("7"));
  1182. copyFilesBuildPhase->AddAttribute("dstPath",
  1183. this->CreateString(keySources.first));
  1184. copyFilesBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1185. this->CreateString("0"));
  1186. buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1187. copyFilesBuildPhase->AddAttribute("files", buildFiles);
  1188. for (auto sourceFile : keySources.second) {
  1189. cmXCodeObject* xsf = this->CreateXCodeSourceFile(
  1190. this->CurrentLocalGenerator, sourceFile, gtgt);
  1191. buildFiles->AddObject(xsf);
  1192. }
  1193. contentBuildPhases.push_back(copyFilesBuildPhase);
  1194. }
  1195. }
  1196. // always create framework build phase
  1197. cmXCodeObject* frameworkBuildPhase = nullptr;
  1198. frameworkBuildPhase =
  1199. this->CreateObject(cmXCodeObject::PBXFrameworksBuildPhase);
  1200. frameworkBuildPhase->SetComment("Frameworks");
  1201. frameworkBuildPhase->AddAttribute("buildActionMask",
  1202. this->CreateString("2147483647"));
  1203. buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1204. frameworkBuildPhase->AddAttribute("files", buildFiles);
  1205. for (auto& externalObjFile : externalObjFiles) {
  1206. buildFiles->AddObject(externalObjFile);
  1207. }
  1208. frameworkBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1209. this->CreateString("0"));
  1210. // create list of build phases and create the Xcode target
  1211. cmXCodeObject* buildPhases = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1212. this->CreateCustomCommands(buildPhases, sourceBuildPhase, headerBuildPhase,
  1213. resourceBuildPhase, contentBuildPhases,
  1214. frameworkBuildPhase, gtgt);
  1215. targets.push_back(this->CreateXCodeTarget(gtgt, buildPhases));
  1216. return true;
  1217. }
  1218. void cmGlobalXCodeGenerator::ForceLinkerLanguages()
  1219. {
  1220. for (const auto& localGenerator : this->LocalGenerators) {
  1221. // All targets depend on the build-system check target.
  1222. for (const auto& tgt : localGenerator->GetGeneratorTargets()) {
  1223. // This makes sure all targets link using the proper language.
  1224. this->ForceLinkerLanguage(tgt.get());
  1225. }
  1226. }
  1227. }
  1228. void cmGlobalXCodeGenerator::ForceLinkerLanguage(cmGeneratorTarget* gtgt)
  1229. {
  1230. // This matters only for targets that link.
  1231. if (gtgt->GetType() != cmStateEnums::EXECUTABLE &&
  1232. gtgt->GetType() != cmStateEnums::SHARED_LIBRARY &&
  1233. gtgt->GetType() != cmStateEnums::MODULE_LIBRARY) {
  1234. return;
  1235. }
  1236. std::string llang = gtgt->GetLinkerLanguage("NOCONFIG");
  1237. if (llang.empty()) {
  1238. return;
  1239. }
  1240. // If the language is compiled as a source trust Xcode to link with it.
  1241. for (auto const& Language :
  1242. gtgt->GetLinkImplementation("NOCONFIG")->Languages) {
  1243. if (Language == llang) {
  1244. return;
  1245. }
  1246. }
  1247. // Add an empty source file to the target that compiles with the
  1248. // linker language. This should convince Xcode to choose the proper
  1249. // language.
  1250. cmMakefile* mf = gtgt->Target->GetMakefile();
  1251. std::string fname = cmStrCat(
  1252. gtgt->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/CMakeFiles/",
  1253. gtgt->GetName(), "-CMakeForceLinker.", cmSystemTools::LowerCase(llang));
  1254. {
  1255. cmGeneratedFileStream fout(fname);
  1256. fout << "\n";
  1257. }
  1258. if (cmSourceFile* sf = mf->GetOrCreateSource(fname)) {
  1259. sf->SetProperty("LANGUAGE", llang.c_str());
  1260. gtgt->AddSource(fname);
  1261. }
  1262. }
  1263. bool cmGlobalXCodeGenerator::IsHeaderFile(cmSourceFile* sf)
  1264. {
  1265. return cm::contains(this->CMakeInstance->GetHeaderExtensions(),
  1266. sf->GetExtension());
  1267. }
  1268. cmXCodeObject* cmGlobalXCodeGenerator::CreateBuildPhase(
  1269. const char* name, const char* name2, cmGeneratorTarget* target,
  1270. const std::vector<cmCustomCommand>& commands)
  1271. {
  1272. if (commands.empty() && strcmp(name, "CMake ReRun") != 0) {
  1273. return nullptr;
  1274. }
  1275. cmXCodeObject* buildPhase =
  1276. this->CreateObject(cmXCodeObject::PBXShellScriptBuildPhase);
  1277. buildPhase->AddAttribute("buildActionMask",
  1278. this->CreateString("2147483647"));
  1279. cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1280. buildPhase->AddAttribute("files", buildFiles);
  1281. buildPhase->AddAttribute("name", this->CreateString(name));
  1282. buildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  1283. this->CreateString("0"));
  1284. buildPhase->AddAttribute("shellPath", this->CreateString("/bin/sh"));
  1285. this->AddCommandsToBuildPhase(buildPhase, target, commands, name2);
  1286. return buildPhase;
  1287. }
  1288. void cmGlobalXCodeGenerator::CreateCustomCommands(
  1289. cmXCodeObject* buildPhases, cmXCodeObject* sourceBuildPhase,
  1290. cmXCodeObject* headerBuildPhase, cmXCodeObject* resourceBuildPhase,
  1291. std::vector<cmXCodeObject*> const& contentBuildPhases,
  1292. cmXCodeObject* frameworkBuildPhase, cmGeneratorTarget* gtgt)
  1293. {
  1294. std::vector<cmCustomCommand> const& prebuild = gtgt->GetPreBuildCommands();
  1295. std::vector<cmCustomCommand> const& prelink = gtgt->GetPreLinkCommands();
  1296. std::vector<cmCustomCommand> postbuild = gtgt->GetPostBuildCommands();
  1297. if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY &&
  1298. !gtgt->IsFrameworkOnApple()) {
  1299. std::string str_file = cmStrCat("$<TARGET_FILE:", gtgt->GetName(), '>');
  1300. std::string str_so_file =
  1301. cmStrCat("$<TARGET_SONAME_FILE:", gtgt->GetName(), '>');
  1302. std::string str_link_file =
  1303. cmStrCat("$<TARGET_LINKER_FILE:", gtgt->GetName(), '>');
  1304. bool stdPipesUTF8 = true;
  1305. cmCustomCommandLines cmd = cmMakeSingleCommandLine(
  1306. { cmSystemTools::GetCMakeCommand(), "-E", "cmake_symlink_library",
  1307. str_file, str_so_file, str_link_file });
  1308. cmCustomCommand command(
  1309. std::vector<std::string>(), std::vector<std::string>(),
  1310. std::vector<std::string>(), cmd, this->CurrentMakefile->GetBacktrace(),
  1311. "Creating symlinks", "", stdPipesUTF8);
  1312. postbuild.push_back(std::move(command));
  1313. }
  1314. std::vector<cmSourceFile*> classes;
  1315. if (!gtgt->GetConfigCommonSourceFiles(classes)) {
  1316. return;
  1317. }
  1318. // add all the sources
  1319. std::vector<cmCustomCommand> commands;
  1320. for (auto sourceFile : classes) {
  1321. if (sourceFile->GetCustomCommand()) {
  1322. commands.push_back(*sourceFile->GetCustomCommand());
  1323. }
  1324. }
  1325. // create prebuild phase
  1326. cmXCodeObject* cmakeRulesBuildPhase = this->CreateBuildPhase(
  1327. "CMake Rules", "cmakeRulesBuildPhase", gtgt, commands);
  1328. // create prebuild phase
  1329. cmXCodeObject* preBuildPhase = this->CreateBuildPhase(
  1330. "CMake PreBuild Rules", "preBuildCommands", gtgt, prebuild);
  1331. // create prelink phase
  1332. cmXCodeObject* preLinkPhase = this->CreateBuildPhase(
  1333. "CMake PreLink Rules", "preLinkCommands", gtgt, prelink);
  1334. // create postbuild phase
  1335. cmXCodeObject* postBuildPhase = this->CreateBuildPhase(
  1336. "CMake PostBuild Rules", "postBuildPhase", gtgt, postbuild);
  1337. // The order here is the order they will be built in.
  1338. // The order "headers, resources, sources" mimics a native project generated
  1339. // from an xcode template...
  1340. //
  1341. if (preBuildPhase) {
  1342. buildPhases->AddObject(preBuildPhase);
  1343. }
  1344. if (cmakeRulesBuildPhase) {
  1345. buildPhases->AddObject(cmakeRulesBuildPhase);
  1346. }
  1347. if (headerBuildPhase) {
  1348. buildPhases->AddObject(headerBuildPhase);
  1349. }
  1350. if (resourceBuildPhase) {
  1351. buildPhases->AddObject(resourceBuildPhase);
  1352. }
  1353. for (auto obj : contentBuildPhases) {
  1354. buildPhases->AddObject(obj);
  1355. }
  1356. if (sourceBuildPhase) {
  1357. buildPhases->AddObject(sourceBuildPhase);
  1358. }
  1359. if (preLinkPhase) {
  1360. buildPhases->AddObject(preLinkPhase);
  1361. }
  1362. if (frameworkBuildPhase) {
  1363. buildPhases->AddObject(frameworkBuildPhase);
  1364. }
  1365. if (postBuildPhase) {
  1366. buildPhases->AddObject(postBuildPhase);
  1367. }
  1368. }
  1369. // This function removes each occurrence of the flag and returns the last one
  1370. // (i.e., the dominant flag in GCC)
  1371. std::string cmGlobalXCodeGenerator::ExtractFlag(const char* flag,
  1372. std::string& flags)
  1373. {
  1374. std::string retFlag;
  1375. std::string::size_type lastOccurancePos = flags.rfind(flag);
  1376. bool saved = false;
  1377. while (lastOccurancePos != std::string::npos) {
  1378. // increment pos, we use lastOccurancePos to reduce search space on next
  1379. // inc
  1380. std::string::size_type pos = lastOccurancePos;
  1381. if (pos == 0 || flags[pos - 1] == ' ') {
  1382. while (pos < flags.size() && flags[pos] != ' ') {
  1383. if (!saved) {
  1384. retFlag += flags[pos];
  1385. }
  1386. flags[pos] = ' ';
  1387. pos++;
  1388. }
  1389. saved = true;
  1390. }
  1391. // decrement lastOccurancePos while making sure we don't loop around
  1392. // and become a very large positive number since size_type is unsigned
  1393. lastOccurancePos = lastOccurancePos == 0 ? 0 : lastOccurancePos - 1;
  1394. lastOccurancePos = flags.rfind(flag, lastOccurancePos);
  1395. }
  1396. return retFlag;
  1397. }
  1398. // This function removes each matching occurrence of the expression and
  1399. // returns the last one (i.e., the dominant flag in GCC)
  1400. std::string cmGlobalXCodeGenerator::ExtractFlagRegex(const char* exp,
  1401. int matchIndex,
  1402. std::string& flags)
  1403. {
  1404. std::string retFlag;
  1405. cmsys::RegularExpression regex(exp);
  1406. assert(regex.is_valid());
  1407. if (!regex.is_valid()) {
  1408. return retFlag;
  1409. }
  1410. std::string::size_type offset = 0;
  1411. while (regex.find(&flags[offset])) {
  1412. const std::string::size_type startPos = offset + regex.start(matchIndex);
  1413. const std::string::size_type endPos = offset + regex.end(matchIndex);
  1414. const std::string::size_type size = endPos - startPos;
  1415. offset = startPos + 1;
  1416. retFlag.assign(flags, startPos, size);
  1417. flags.replace(startPos, size, size, ' ');
  1418. }
  1419. return retFlag;
  1420. }
  1421. //----------------------------------------------------------------------------
  1422. // This function strips off Xcode attributes that do not target the current
  1423. // configuration
  1424. void cmGlobalXCodeGenerator::FilterConfigurationAttribute(
  1425. std::string const& configName, std::string& attribute)
  1426. {
  1427. // Handle [variant=<config>] condition explicitly here.
  1428. std::string::size_type beginVariant = attribute.find("[variant=");
  1429. if (beginVariant == std::string::npos) {
  1430. // There is no variant in this attribute.
  1431. return;
  1432. }
  1433. std::string::size_type endVariant = attribute.find(']', beginVariant + 9);
  1434. if (endVariant == std::string::npos) {
  1435. // There is no terminating bracket.
  1436. return;
  1437. }
  1438. // Compare the variant to the configuration.
  1439. std::string variant =
  1440. attribute.substr(beginVariant + 9, endVariant - beginVariant - 9);
  1441. if (variant == configName) {
  1442. // The variant matches the configuration so use this
  1443. // attribute but drop the [variant=<config>] condition.
  1444. attribute.erase(beginVariant, endVariant - beginVariant + 1);
  1445. } else {
  1446. // The variant does not match the configuration so
  1447. // do not use this attribute.
  1448. attribute.clear();
  1449. }
  1450. }
  1451. void cmGlobalXCodeGenerator::AddCommandsToBuildPhase(
  1452. cmXCodeObject* buildphase, cmGeneratorTarget* target,
  1453. std::vector<cmCustomCommand> const& commands, const char* name)
  1454. {
  1455. std::string dir = cmStrCat(
  1456. this->CurrentLocalGenerator->GetCurrentBinaryDirectory(), "/CMakeScripts");
  1457. cmSystemTools::MakeDirectory(dir);
  1458. std::string makefile =
  1459. cmStrCat(dir, '/', target->GetName(), '_', name, ".make");
  1460. for (const auto& currentConfig : this->CurrentConfigurationTypes) {
  1461. this->CreateCustomRulesMakefile(makefile.c_str(), target, commands,
  1462. currentConfig);
  1463. }
  1464. std::string cdir = this->CurrentLocalGenerator->GetCurrentBinaryDirectory();
  1465. cdir = this->ConvertToRelativeForMake(cdir);
  1466. std::string makecmd =
  1467. cmStrCat("make -C ", cdir, " -f ",
  1468. this->ConvertToRelativeForMake((makefile + "$CONFIGURATION")),
  1469. " OBJDIR=$(basename \"$OBJECT_FILE_DIR_normal\") all");
  1470. buildphase->AddAttribute("shellScript", this->CreateString(makecmd));
  1471. buildphase->AddAttribute("showEnvVarsInLog", this->CreateString("0"));
  1472. }
  1473. void cmGlobalXCodeGenerator::CreateCustomRulesMakefile(
  1474. const char* makefileBasename, cmGeneratorTarget* target,
  1475. std::vector<cmCustomCommand> const& commands, const std::string& configName)
  1476. {
  1477. std::string makefileName = cmStrCat(makefileBasename, configName);
  1478. cmGeneratedFileStream makefileStream(makefileName);
  1479. if (!makefileStream) {
  1480. return;
  1481. }
  1482. makefileStream.SetCopyIfDifferent(true);
  1483. makefileStream << "# Generated by CMake, DO NOT EDIT\n";
  1484. makefileStream << "# Custom rules for " << target->GetName() << "\n";
  1485. // disable the implicit rules
  1486. makefileStream << ".SUFFIXES: "
  1487. << "\n";
  1488. // have all depend on all outputs
  1489. makefileStream << "all: ";
  1490. std::map<const cmCustomCommand*, std::string> tname;
  1491. int count = 0;
  1492. for (auto const& command : commands) {
  1493. cmCustomCommandGenerator ccg(command, configName,
  1494. this->CurrentLocalGenerator);
  1495. if (ccg.GetNumberOfCommands() > 0) {
  1496. const std::vector<std::string>& outputs = ccg.GetOutputs();
  1497. if (!outputs.empty()) {
  1498. for (auto const& output : outputs) {
  1499. makefileStream << "\\\n\t" << this->ConvertToRelativeForMake(output);
  1500. }
  1501. } else {
  1502. std::ostringstream str;
  1503. str << "_buildpart_" << count++;
  1504. tname[&ccg.GetCC()] = target->GetName() + str.str();
  1505. makefileStream << "\\\n\t" << tname[&ccg.GetCC()];
  1506. }
  1507. }
  1508. }
  1509. makefileStream << "\n\n";
  1510. for (auto const& command : commands) {
  1511. cmCustomCommandGenerator ccg(command, configName,
  1512. this->CurrentLocalGenerator);
  1513. if (ccg.GetNumberOfCommands() > 0) {
  1514. makefileStream << "\n";
  1515. const std::vector<std::string>& outputs = ccg.GetOutputs();
  1516. if (!outputs.empty()) {
  1517. // There is at least one output, start the rule for it
  1518. const char* sep = "";
  1519. for (auto const& output : outputs) {
  1520. makefileStream << sep << this->ConvertToRelativeForMake(output);
  1521. sep = " ";
  1522. }
  1523. makefileStream << ": ";
  1524. } else {
  1525. // There are no outputs. Use the generated force rule name.
  1526. makefileStream << tname[&ccg.GetCC()] << ": ";
  1527. }
  1528. for (auto const& d : ccg.GetDepends()) {
  1529. std::string dep;
  1530. if (this->CurrentLocalGenerator->GetRealDependency(d, configName,
  1531. dep)) {
  1532. makefileStream << "\\\n" << this->ConvertToRelativeForMake(dep);
  1533. }
  1534. }
  1535. makefileStream << "\n";
  1536. if (const char* comment = ccg.GetComment()) {
  1537. std::string echo_cmd =
  1538. cmStrCat("echo ",
  1539. (this->CurrentLocalGenerator->EscapeForShell(
  1540. comment, ccg.GetCC().GetEscapeAllowMakeVars())));
  1541. makefileStream << "\t" << echo_cmd << "\n";
  1542. }
  1543. // Add each command line to the set of commands.
  1544. for (unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) {
  1545. // Build the command line in a single string.
  1546. std::string cmd2 = ccg.GetCommand(c);
  1547. cmSystemTools::ReplaceString(cmd2, "/./", "/");
  1548. cmd2 = this->ConvertToRelativeForMake(cmd2);
  1549. std::string cmd;
  1550. std::string wd = ccg.GetWorkingDirectory();
  1551. if (!wd.empty()) {
  1552. cmd += "cd ";
  1553. cmd += this->ConvertToRelativeForMake(wd);
  1554. cmd += " && ";
  1555. }
  1556. cmd += cmd2;
  1557. ccg.AppendArguments(c, cmd);
  1558. makefileStream << "\t" << cmd << "\n";
  1559. }
  1560. }
  1561. }
  1562. }
  1563. void cmGlobalXCodeGenerator::AddPositionIndependentLinkAttribute(
  1564. cmGeneratorTarget* target, cmXCodeObject* buildSettings,
  1565. const std::string& configName)
  1566. {
  1567. // For now, only EXECUTABLE is concerned
  1568. if (target->GetType() != cmStateEnums::EXECUTABLE) {
  1569. return;
  1570. }
  1571. const char* PICValue = target->GetLinkPIEProperty(configName);
  1572. if (PICValue == nullptr) {
  1573. // POSITION_INDEPENDENT_CODE is not set
  1574. return;
  1575. }
  1576. buildSettings->AddAttribute(
  1577. "LD_NO_PIE", this->CreateString(cmIsOn(PICValue) ? "NO" : "YES"));
  1578. }
  1579. void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
  1580. cmXCodeObject* buildSettings,
  1581. const std::string& configName)
  1582. {
  1583. if (gtgt->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  1584. return;
  1585. }
  1586. std::string defFlags;
  1587. bool shared = ((gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) ||
  1588. (gtgt->GetType() == cmStateEnums::MODULE_LIBRARY));
  1589. bool binary = ((gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY) ||
  1590. (gtgt->GetType() == cmStateEnums::STATIC_LIBRARY) ||
  1591. (gtgt->GetType() == cmStateEnums::EXECUTABLE) || shared);
  1592. // Compute the compilation flags for each language.
  1593. std::set<std::string> languages;
  1594. gtgt->GetLanguages(languages, configName);
  1595. std::map<std::string, std::string> cflags;
  1596. for (auto const& lang : languages) {
  1597. std::string& flags = cflags[lang];
  1598. // Add language-specific flags.
  1599. this->CurrentLocalGenerator->AddLanguageFlags(flags, gtgt, lang,
  1600. configName);
  1601. if (gtgt->IsIPOEnabled(lang, configName)) {
  1602. this->CurrentLocalGenerator->AppendFeatureOptions(flags, lang, "IPO");
  1603. }
  1604. // Add shared-library flags if needed.
  1605. this->CurrentLocalGenerator->AddCMP0018Flags(flags, gtgt, lang,
  1606. configName);
  1607. this->CurrentLocalGenerator->AddVisibilityPresetFlags(flags, gtgt, lang);
  1608. this->CurrentLocalGenerator->AddCompileOptions(flags, gtgt, lang,
  1609. configName);
  1610. }
  1611. std::string llang = gtgt->GetLinkerLanguage(configName);
  1612. if (binary && llang.empty()) {
  1613. cmSystemTools::Error(
  1614. "CMake can not determine linker language for target: " +
  1615. gtgt->GetName());
  1616. return;
  1617. }
  1618. std::string const& langForPreprocessor = llang;
  1619. if (gtgt->IsIPOEnabled(llang, configName)) {
  1620. const char* ltoValue =
  1621. this->CurrentMakefile->IsOn("_CMAKE_LTO_THIN") ? "YES_THIN" : "YES";
  1622. buildSettings->AddAttribute("LLVM_LTO", this->CreateString(ltoValue));
  1623. }
  1624. // Handle PIE linker configuration
  1625. this->AddPositionIndependentLinkAttribute(gtgt, buildSettings, configName);
  1626. // Add define flags
  1627. this->CurrentLocalGenerator->AppendFlags(
  1628. defFlags, this->CurrentMakefile->GetDefineFlags());
  1629. // Add preprocessor definitions for this target and configuration.
  1630. BuildObjectListOrString ppDefs(this, true);
  1631. this->AppendDefines(
  1632. ppDefs, "CMAKE_INTDIR=\"$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)\"");
  1633. if (const std::string* exportMacro = gtgt->GetExportMacro()) {
  1634. // Add the export symbol definition for shared library objects.
  1635. this->AppendDefines(ppDefs, exportMacro->c_str());
  1636. }
  1637. std::vector<std::string> targetDefines;
  1638. if (!langForPreprocessor.empty()) {
  1639. gtgt->GetCompileDefinitions(targetDefines, configName,
  1640. langForPreprocessor);
  1641. }
  1642. this->AppendDefines(ppDefs, targetDefines);
  1643. buildSettings->AddAttribute("GCC_PREPROCESSOR_DEFINITIONS",
  1644. ppDefs.CreateList());
  1645. std::string extraLinkOptionsVar;
  1646. std::string extraLinkOptions;
  1647. if (gtgt->GetType() == cmStateEnums::EXECUTABLE) {
  1648. extraLinkOptionsVar = "CMAKE_EXE_LINKER_FLAGS";
  1649. } else if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) {
  1650. extraLinkOptionsVar = "CMAKE_SHARED_LINKER_FLAGS";
  1651. } else if (gtgt->GetType() == cmStateEnums::MODULE_LIBRARY) {
  1652. extraLinkOptionsVar = "CMAKE_MODULE_LINKER_FLAGS";
  1653. }
  1654. if (!extraLinkOptionsVar.empty()) {
  1655. this->CurrentLocalGenerator->AddConfigVariableFlags(
  1656. extraLinkOptions, extraLinkOptionsVar, configName);
  1657. }
  1658. if (gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  1659. gtgt->GetType() == cmStateEnums::STATIC_LIBRARY) {
  1660. this->CurrentLocalGenerator->GetStaticLibraryFlags(
  1661. extraLinkOptions, configName, llang, gtgt);
  1662. } else {
  1663. cmProp targetLinkFlags = gtgt->GetProperty("LINK_FLAGS");
  1664. if (targetLinkFlags) {
  1665. this->CurrentLocalGenerator->AppendFlags(extraLinkOptions,
  1666. *targetLinkFlags);
  1667. }
  1668. if (!configName.empty()) {
  1669. std::string linkFlagsVar =
  1670. cmStrCat("LINK_FLAGS_", cmSystemTools::UpperCase(configName));
  1671. if (cmProp linkFlags = gtgt->GetProperty(linkFlagsVar)) {
  1672. this->CurrentLocalGenerator->AppendFlags(extraLinkOptions, *linkFlags);
  1673. }
  1674. }
  1675. std::vector<std::string> opts;
  1676. gtgt->GetLinkOptions(opts, configName, llang);
  1677. // LINK_OPTIONS are escaped.
  1678. this->CurrentLocalGenerator->AppendCompileOptions(extraLinkOptions, opts);
  1679. }
  1680. // Set target-specific architectures.
  1681. std::vector<std::string> archs;
  1682. gtgt->GetAppleArchs(configName, archs);
  1683. if (!archs.empty()) {
  1684. // Enable ARCHS attribute.
  1685. buildSettings->AddAttribute("ONLY_ACTIVE_ARCH", this->CreateString("NO"));
  1686. // Store ARCHS value.
  1687. if (archs.size() == 1) {
  1688. buildSettings->AddAttribute("ARCHS", this->CreateString(archs[0]));
  1689. } else {
  1690. cmXCodeObject* archObjects =
  1691. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  1692. for (auto& arch : archs) {
  1693. archObjects->AddObject(this->CreateString(arch));
  1694. }
  1695. buildSettings->AddAttribute("ARCHS", archObjects);
  1696. }
  1697. }
  1698. // Get the product name components.
  1699. std::string pnprefix;
  1700. std::string pnbase;
  1701. std::string pnsuffix;
  1702. gtgt->GetFullNameComponents(pnprefix, pnbase, pnsuffix, configName);
  1703. cmProp version = gtgt->GetProperty("VERSION");
  1704. cmProp soversion = gtgt->GetProperty("SOVERSION");
  1705. if (!gtgt->HasSOName(configName) || gtgt->IsFrameworkOnApple()) {
  1706. version = nullptr;
  1707. soversion = nullptr;
  1708. }
  1709. if (version && !soversion) {
  1710. soversion = version;
  1711. }
  1712. if (!version && soversion) {
  1713. version = soversion;
  1714. }
  1715. std::string realName = pnbase;
  1716. std::string soName = pnbase;
  1717. if (version && soversion) {
  1718. realName += ".";
  1719. realName += *version;
  1720. soName += ".";
  1721. soName += *soversion;
  1722. }
  1723. // Set attributes to specify the proper name for the target.
  1724. std::string pndir = this->CurrentLocalGenerator->GetCurrentBinaryDirectory();
  1725. if (gtgt->GetType() == cmStateEnums::STATIC_LIBRARY ||
  1726. gtgt->GetType() == cmStateEnums::SHARED_LIBRARY ||
  1727. gtgt->GetType() == cmStateEnums::MODULE_LIBRARY ||
  1728. gtgt->GetType() == cmStateEnums::EXECUTABLE) {
  1729. if (!gtgt->UsesDefaultOutputDir(configName,
  1730. cmStateEnums::RuntimeBinaryArtifact)) {
  1731. std::string pncdir = gtgt->GetDirectory(configName);
  1732. buildSettings->AddAttribute("CONFIGURATION_BUILD_DIR",
  1733. this->CreateString(pncdir));
  1734. }
  1735. if (gtgt->IsFrameworkOnApple() || gtgt->IsCFBundleOnApple()) {
  1736. pnprefix = "";
  1737. }
  1738. buildSettings->AddAttribute("EXECUTABLE_PREFIX",
  1739. this->CreateString(pnprefix));
  1740. buildSettings->AddAttribute("EXECUTABLE_SUFFIX",
  1741. this->CreateString(pnsuffix));
  1742. } else if (gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  1743. pnprefix = "lib";
  1744. pnbase = gtgt->GetName();
  1745. pnsuffix = ".a";
  1746. std::string pncdir = this->GetObjectsDirectory(
  1747. this->CurrentProject, configName, gtgt, OBJECT_LIBRARY_ARTIFACT_DIR);
  1748. buildSettings->AddAttribute("CONFIGURATION_BUILD_DIR",
  1749. this->CreateString(pncdir));
  1750. }
  1751. // Store the product name for all target types.
  1752. buildSettings->AddAttribute("PRODUCT_NAME", this->CreateString(realName));
  1753. buildSettings->AddAttribute("SYMROOT", this->CreateString(pndir));
  1754. // Handle settings for each target type.
  1755. switch (gtgt->GetType()) {
  1756. case cmStateEnums::STATIC_LIBRARY:
  1757. if (gtgt->GetPropertyAsBool("FRAMEWORK")) {
  1758. std::string fw_version = gtgt->GetFrameworkVersion();
  1759. buildSettings->AddAttribute("FRAMEWORK_VERSION",
  1760. this->CreateString(fw_version));
  1761. cmProp ext = gtgt->GetProperty("BUNDLE_EXTENSION");
  1762. if (ext) {
  1763. buildSettings->AddAttribute("WRAPPER_EXTENSION",
  1764. this->CreateString(*ext));
  1765. }
  1766. std::string plist = this->ComputeInfoPListLocation(gtgt);
  1767. // Xcode will create the final version of Info.plist at build time,
  1768. // so let it replace the framework name. This avoids creating
  1769. // a per-configuration Info.plist file.
  1770. this->CurrentLocalGenerator->GenerateFrameworkInfoPList(
  1771. gtgt, "$(EXECUTABLE_NAME)", plist);
  1772. buildSettings->AddAttribute("INFOPLIST_FILE",
  1773. this->CreateString(plist));
  1774. buildSettings->AddAttribute("MACH_O_TYPE",
  1775. this->CreateString("staticlib"));
  1776. } else {
  1777. buildSettings->AddAttribute("LIBRARY_STYLE",
  1778. this->CreateString("STATIC"));
  1779. }
  1780. break;
  1781. case cmStateEnums::OBJECT_LIBRARY: {
  1782. buildSettings->AddAttribute("LIBRARY_STYLE",
  1783. this->CreateString("STATIC"));
  1784. break;
  1785. }
  1786. case cmStateEnums::MODULE_LIBRARY: {
  1787. buildSettings->AddAttribute("LIBRARY_STYLE",
  1788. this->CreateString("BUNDLE"));
  1789. if (gtgt->IsCFBundleOnApple()) {
  1790. // It turns out that a BUNDLE is basically the same
  1791. // in many ways as an application bundle, as far as
  1792. // link flags go
  1793. std::string createFlags = this->LookupFlags(
  1794. "CMAKE_SHARED_MODULE_CREATE_", llang, "_FLAGS", "-bundle");
  1795. if (!createFlags.empty()) {
  1796. extraLinkOptions += " ";
  1797. extraLinkOptions += createFlags;
  1798. }
  1799. cmProp ext = gtgt->GetProperty("BUNDLE_EXTENSION");
  1800. if (ext) {
  1801. buildSettings->AddAttribute("WRAPPER_EXTENSION",
  1802. this->CreateString(*ext));
  1803. }
  1804. std::string plist = this->ComputeInfoPListLocation(gtgt);
  1805. // Xcode will create the final version of Info.plist at build time,
  1806. // so let it replace the cfbundle name. This avoids creating
  1807. // a per-configuration Info.plist file. The cfbundle plist
  1808. // is very similar to the application bundle plist
  1809. this->CurrentLocalGenerator->GenerateAppleInfoPList(
  1810. gtgt, "$(EXECUTABLE_NAME)", plist);
  1811. buildSettings->AddAttribute("INFOPLIST_FILE",
  1812. this->CreateString(plist));
  1813. } else {
  1814. buildSettings->AddAttribute("MACH_O_TYPE",
  1815. this->CreateString("mh_bundle"));
  1816. buildSettings->AddAttribute("GCC_DYNAMIC_NO_PIC",
  1817. this->CreateString("NO"));
  1818. // Add the flags to create an executable.
  1819. std::string createFlags =
  1820. this->LookupFlags("CMAKE_", llang, "_LINK_FLAGS", "");
  1821. if (!createFlags.empty()) {
  1822. extraLinkOptions += " ";
  1823. extraLinkOptions += createFlags;
  1824. }
  1825. }
  1826. break;
  1827. }
  1828. case cmStateEnums::SHARED_LIBRARY: {
  1829. if (gtgt->GetPropertyAsBool("FRAMEWORK")) {
  1830. std::string fw_version = gtgt->GetFrameworkVersion();
  1831. buildSettings->AddAttribute("FRAMEWORK_VERSION",
  1832. this->CreateString(fw_version));
  1833. cmProp ext = gtgt->GetProperty("BUNDLE_EXTENSION");
  1834. if (ext) {
  1835. buildSettings->AddAttribute("WRAPPER_EXTENSION",
  1836. this->CreateString(*ext));
  1837. }
  1838. std::string plist = this->ComputeInfoPListLocation(gtgt);
  1839. // Xcode will create the final version of Info.plist at build time,
  1840. // so let it replace the framework name. This avoids creating
  1841. // a per-configuration Info.plist file.
  1842. this->CurrentLocalGenerator->GenerateFrameworkInfoPList(
  1843. gtgt, "$(EXECUTABLE_NAME)", plist);
  1844. buildSettings->AddAttribute("INFOPLIST_FILE",
  1845. this->CreateString(plist));
  1846. } else {
  1847. // Add the flags to create a shared library.
  1848. std::string createFlags = this->LookupFlags(
  1849. "CMAKE_SHARED_LIBRARY_CREATE_", llang, "_FLAGS", "-dynamiclib");
  1850. if (!createFlags.empty()) {
  1851. extraLinkOptions += " ";
  1852. extraLinkOptions += createFlags;
  1853. }
  1854. }
  1855. buildSettings->AddAttribute("LIBRARY_STYLE",
  1856. this->CreateString("DYNAMIC"));
  1857. break;
  1858. }
  1859. case cmStateEnums::EXECUTABLE: {
  1860. // Add the flags to create an executable.
  1861. std::string createFlags =
  1862. this->LookupFlags("CMAKE_", llang, "_LINK_FLAGS", "");
  1863. if (!createFlags.empty()) {
  1864. extraLinkOptions += " ";
  1865. extraLinkOptions += createFlags;
  1866. }
  1867. // Handle bundles and normal executables separately.
  1868. if (gtgt->GetPropertyAsBool("MACOSX_BUNDLE")) {
  1869. cmProp ext = gtgt->GetProperty("BUNDLE_EXTENSION");
  1870. if (ext) {
  1871. buildSettings->AddAttribute("WRAPPER_EXTENSION",
  1872. this->CreateString(*ext));
  1873. }
  1874. std::string plist = this->ComputeInfoPListLocation(gtgt);
  1875. // Xcode will create the final version of Info.plist at build time,
  1876. // so let it replace the executable name. This avoids creating
  1877. // a per-configuration Info.plist file.
  1878. this->CurrentLocalGenerator->GenerateAppleInfoPList(
  1879. gtgt, "$(EXECUTABLE_NAME)", plist);
  1880. buildSettings->AddAttribute("INFOPLIST_FILE",
  1881. this->CreateString(plist));
  1882. }
  1883. } break;
  1884. default:
  1885. break;
  1886. }
  1887. BuildObjectListOrString dirs(this, true);
  1888. BuildObjectListOrString fdirs(this, true);
  1889. BuildObjectListOrString sysdirs(this, true);
  1890. BuildObjectListOrString sysfdirs(this, true);
  1891. const bool emitSystemIncludes = this->XcodeVersion >= 83;
  1892. std::vector<std::string> includes;
  1893. if (!langForPreprocessor.empty()) {
  1894. this->CurrentLocalGenerator->GetIncludeDirectories(
  1895. includes, gtgt, langForPreprocessor, configName);
  1896. }
  1897. std::set<std::string> emitted;
  1898. emitted.insert("/System/Library/Frameworks");
  1899. for (auto& include : includes) {
  1900. if (this->NameResolvesToFramework(include)) {
  1901. std::string frameworkDir = cmStrCat(include, "/../");
  1902. frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
  1903. if (emitted.insert(frameworkDir).second) {
  1904. std::string incpath = this->XCodeEscapePath(frameworkDir);
  1905. if (emitSystemIncludes &&
  1906. gtgt->IsSystemIncludeDirectory(frameworkDir, configName,
  1907. langForPreprocessor)) {
  1908. sysfdirs.Add(incpath);
  1909. } else {
  1910. fdirs.Add(incpath);
  1911. }
  1912. }
  1913. } else {
  1914. std::string incpath = this->XCodeEscapePath(include);
  1915. if (emitSystemIncludes &&
  1916. gtgt->IsSystemIncludeDirectory(include, configName,
  1917. langForPreprocessor)) {
  1918. sysdirs.Add(incpath);
  1919. } else {
  1920. dirs.Add(incpath);
  1921. }
  1922. }
  1923. }
  1924. // Add framework search paths needed for linking.
  1925. if (cmComputeLinkInformation* cli = gtgt->GetLinkInformation(configName)) {
  1926. for (auto const& fwDir : cli->GetFrameworkPaths()) {
  1927. if (emitted.insert(fwDir).second) {
  1928. std::string incpath = this->XCodeEscapePath(fwDir);
  1929. if (emitSystemIncludes &&
  1930. gtgt->IsSystemIncludeDirectory(fwDir, configName,
  1931. langForPreprocessor)) {
  1932. sysfdirs.Add(incpath);
  1933. } else {
  1934. fdirs.Add(incpath);
  1935. }
  1936. }
  1937. }
  1938. }
  1939. if (!fdirs.IsEmpty()) {
  1940. buildSettings->AddAttribute("FRAMEWORK_SEARCH_PATHS", fdirs.CreateList());
  1941. }
  1942. if (!dirs.IsEmpty()) {
  1943. buildSettings->AddAttribute("HEADER_SEARCH_PATHS", dirs.CreateList());
  1944. }
  1945. if (!sysfdirs.IsEmpty()) {
  1946. buildSettings->AddAttribute("SYSTEM_FRAMEWORK_SEARCH_PATHS",
  1947. sysfdirs.CreateList());
  1948. }
  1949. if (!sysdirs.IsEmpty()) {
  1950. buildSettings->AddAttribute("SYSTEM_HEADER_SEARCH_PATHS",
  1951. sysdirs.CreateList());
  1952. }
  1953. if (this->XcodeVersion >= 60 && !emitSystemIncludes) {
  1954. // Add those per-language flags in addition to HEADER_SEARCH_PATHS to gain
  1955. // system include directory awareness. We need to also keep on setting
  1956. // HEADER_SEARCH_PATHS to work around a missing compile options flag for
  1957. // GNU assembly files (#16449)
  1958. for (auto const& language : languages) {
  1959. std::string includeFlags = this->CurrentLocalGenerator->GetIncludeFlags(
  1960. includes, gtgt, language, true, false, configName);
  1961. if (!includeFlags.empty()) {
  1962. cflags[language] += " " + includeFlags;
  1963. }
  1964. }
  1965. }
  1966. bool same_gflags = true;
  1967. std::map<std::string, std::string> gflags;
  1968. std::string const* last_gflag = nullptr;
  1969. std::string optLevel = "0";
  1970. // Minimal map of flags to build settings.
  1971. for (auto const& language : languages) {
  1972. std::string& flags = cflags[language];
  1973. std::string& gflag = gflags[language];
  1974. std::string oflag =
  1975. this->ExtractFlagRegex("(^| )(-Ofast|-Os|-O[0-9]*)( |$)", 2, flags);
  1976. if (oflag.size() == 2) {
  1977. optLevel = "1";
  1978. } else if (oflag.size() > 2) {
  1979. optLevel = oflag.substr(2);
  1980. }
  1981. gflag = this->ExtractFlag("-g", flags);
  1982. // put back gdwarf-2 if used since there is no way
  1983. // to represent it in the gui, but we still want debug yes
  1984. if (gflag == "-gdwarf-2") {
  1985. flags += " ";
  1986. flags += gflag;
  1987. }
  1988. if (last_gflag && *last_gflag != gflag) {
  1989. same_gflags = false;
  1990. }
  1991. last_gflag = &gflag;
  1992. }
  1993. const char* debugStr = "YES";
  1994. if (!same_gflags) {
  1995. // We can't set the Xcode flag differently depending on the language,
  1996. // so put them back in this case.
  1997. for (auto const& language : languages) {
  1998. cflags[language] += " ";
  1999. cflags[language] += gflags[language];
  2000. }
  2001. debugStr = "NO";
  2002. } else if (last_gflag && (last_gflag->empty() || *last_gflag == "-g0")) {
  2003. debugStr = "NO";
  2004. }
  2005. // extract C++ stdlib
  2006. for (auto const& language : languages) {
  2007. if (language != "CXX" && language != "OBJCXX") {
  2008. continue;
  2009. }
  2010. std::string& flags = cflags[language];
  2011. auto stdlib =
  2012. this->ExtractFlagRegex("(^| )(-stdlib=[^ ]+)( |$)", 2, flags);
  2013. if (stdlib.size() > 8) {
  2014. const auto cxxLibrary = stdlib.substr(8);
  2015. if (language == "CXX" ||
  2016. !buildSettings->GetObject("CLANG_CXX_LIBRARY")) {
  2017. buildSettings->AddAttribute("CLANG_CXX_LIBRARY",
  2018. this->CreateString(cxxLibrary));
  2019. }
  2020. }
  2021. }
  2022. buildSettings->AddAttribute("COMBINE_HIDPI_IMAGES",
  2023. this->CreateString("YES"));
  2024. buildSettings->AddAttribute("GCC_GENERATE_DEBUGGING_SYMBOLS",
  2025. this->CreateString(debugStr));
  2026. buildSettings->AddAttribute("GCC_OPTIMIZATION_LEVEL",
  2027. this->CreateString(optLevel));
  2028. buildSettings->AddAttribute("GCC_SYMBOLS_PRIVATE_EXTERN",
  2029. this->CreateString("NO"));
  2030. buildSettings->AddAttribute("GCC_INLINES_ARE_PRIVATE_EXTERN",
  2031. this->CreateString("NO"));
  2032. for (auto const& language : languages) {
  2033. std::string flags = cflags[language] + " " + defFlags;
  2034. if (language == "CXX" || language == "OBJCXX") {
  2035. if (language == "CXX" ||
  2036. !buildSettings->GetObject("OTHER_CPLUSPLUSFLAGS")) {
  2037. buildSettings->AddAttribute("OTHER_CPLUSPLUSFLAGS",
  2038. this->CreateString(flags));
  2039. }
  2040. } else if (language == "Fortran") {
  2041. buildSettings->AddAttribute("IFORT_OTHER_FLAGS",
  2042. this->CreateString(flags));
  2043. } else if (language == "C" || language == "OBJC") {
  2044. if (language == "C" || !buildSettings->GetObject("OTHER_CFLAGS")) {
  2045. buildSettings->AddAttribute("OTHER_CFLAGS", this->CreateString(flags));
  2046. }
  2047. } else if (language == "Swift") {
  2048. buildSettings->AddAttribute("OTHER_SWIFT_FLAGS",
  2049. this->CreateString(flags));
  2050. }
  2051. }
  2052. // Add Fortran source format attribute if property is set.
  2053. const char* format = nullptr;
  2054. std::string const& tgtfmt = gtgt->GetSafeProperty("Fortran_FORMAT");
  2055. switch (cmOutputConverter::GetFortranFormat(tgtfmt)) {
  2056. case cmOutputConverter::FortranFormatFixed:
  2057. format = "fixed";
  2058. break;
  2059. case cmOutputConverter::FortranFormatFree:
  2060. format = "free";
  2061. break;
  2062. default:
  2063. break;
  2064. }
  2065. if (format) {
  2066. buildSettings->AddAttribute("IFORT_LANG_SRCFMT",
  2067. this->CreateString(format));
  2068. }
  2069. // Create the INSTALL_PATH attribute.
  2070. std::string install_name_dir;
  2071. if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) {
  2072. // Get the install_name directory for the build tree.
  2073. install_name_dir = gtgt->GetInstallNameDirForBuildTree(configName);
  2074. // Xcode doesn't create the correct install_name in some cases.
  2075. // That is, if the INSTALL_PATH is empty, or if we have versioning
  2076. // of dylib libraries, we want to specify the install_name.
  2077. // This is done by adding a link flag to create an install_name
  2078. // with just the library soname.
  2079. std::string install_name;
  2080. if (!install_name_dir.empty()) {
  2081. // Convert to a path for the native build tool.
  2082. cmSystemTools::ConvertToUnixSlashes(install_name_dir);
  2083. install_name += install_name_dir;
  2084. install_name += "/";
  2085. }
  2086. install_name += gtgt->GetSOName(configName);
  2087. if ((realName != soName) || install_name_dir.empty()) {
  2088. install_name_dir = "";
  2089. extraLinkOptions += " -install_name ";
  2090. extraLinkOptions += XCodeEscapePath(install_name);
  2091. }
  2092. }
  2093. buildSettings->AddAttribute("INSTALL_PATH",
  2094. this->CreateString(install_name_dir));
  2095. // Create the LD_RUNPATH_SEARCH_PATHS
  2096. cmComputeLinkInformation* pcli = gtgt->GetLinkInformation(configName);
  2097. if (pcli) {
  2098. std::string search_paths;
  2099. std::vector<std::string> runtimeDirs;
  2100. pcli->GetRPath(runtimeDirs, false);
  2101. // runpath dirs needs to be unique to prevent corruption
  2102. std::set<std::string> unique_dirs;
  2103. for (auto runpath : runtimeDirs) {
  2104. runpath = this->ExpandCFGIntDir(runpath, configName);
  2105. if (unique_dirs.find(runpath) == unique_dirs.end()) {
  2106. unique_dirs.insert(runpath);
  2107. if (!search_paths.empty()) {
  2108. search_paths += " ";
  2109. }
  2110. search_paths += this->XCodeEscapePath(runpath);
  2111. }
  2112. }
  2113. if (!search_paths.empty()) {
  2114. buildSettings->AddAttribute("LD_RUNPATH_SEARCH_PATHS",
  2115. this->CreateString(search_paths));
  2116. }
  2117. }
  2118. buildSettings->AddAttribute(this->GetTargetLinkFlagsVar(gtgt),
  2119. this->CreateString(extraLinkOptions));
  2120. buildSettings->AddAttribute("OTHER_REZFLAGS", this->CreateString(""));
  2121. buildSettings->AddAttribute("SECTORDER_FLAGS", this->CreateString(""));
  2122. buildSettings->AddAttribute("USE_HEADERMAP", this->CreateString("NO"));
  2123. cmXCodeObject* group = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2124. group->AddObject(this->CreateString("$(inherited)"));
  2125. buildSettings->AddAttribute("WARNING_CFLAGS", group);
  2126. // Runtime version information.
  2127. if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) {
  2128. int major;
  2129. int minor;
  2130. int patch;
  2131. // MACHO_CURRENT_VERSION or VERSION -> current_version
  2132. gtgt->GetTargetVersionFallback("MACHO_CURRENT_VERSION", "VERSION", major,
  2133. minor, patch);
  2134. std::ostringstream v;
  2135. // Xcode always wants at least 1.0.0 or nothing
  2136. if (!(major == 0 && minor == 0 && patch == 0)) {
  2137. v << major << "." << minor << "." << patch;
  2138. }
  2139. buildSettings->AddAttribute("DYLIB_CURRENT_VERSION",
  2140. this->CreateString(v.str()));
  2141. // MACHO_COMPATIBILITY_VERSION or SOVERSION -> compatibility_version
  2142. gtgt->GetTargetVersionFallback("MACHO_COMPATIBILITY_VERSION", "SOVERSION",
  2143. major, minor, patch);
  2144. std::ostringstream vso;
  2145. // Xcode always wants at least 1.0.0 or nothing
  2146. if (!(major == 0 && minor == 0 && patch == 0)) {
  2147. vso << major << "." << minor << "." << patch;
  2148. }
  2149. buildSettings->AddAttribute("DYLIB_COMPATIBILITY_VERSION",
  2150. this->CreateString(vso.str()));
  2151. }
  2152. // Precompile Headers
  2153. std::string pchHeader = gtgt->GetPchHeader(configName, llang);
  2154. if (!pchHeader.empty()) {
  2155. buildSettings->AddAttribute("GCC_PREFIX_HEADER",
  2156. this->CreateString(pchHeader));
  2157. buildSettings->AddAttribute("GCC_PRECOMPILE_PREFIX_HEADER",
  2158. this->CreateString("YES"));
  2159. }
  2160. // put this last so it can override existing settings
  2161. // Convert "XCODE_ATTRIBUTE_*" properties directly.
  2162. {
  2163. for (auto const& prop : gtgt->GetPropertyKeys()) {
  2164. if (cmHasLiteralPrefix(prop, "XCODE_ATTRIBUTE_")) {
  2165. std::string attribute = prop.substr(16);
  2166. this->FilterConfigurationAttribute(configName, attribute);
  2167. if (!attribute.empty()) {
  2168. std::string const& pr = gtgt->GetSafeProperty(prop);
  2169. std::string processed = cmGeneratorExpression::Evaluate(
  2170. pr, this->CurrentLocalGenerator, configName);
  2171. buildSettings->AddAttribute(attribute,
  2172. this->CreateString(processed));
  2173. }
  2174. }
  2175. }
  2176. }
  2177. }
  2178. cmXCodeObject* cmGlobalXCodeGenerator::CreateUtilityTarget(
  2179. cmGeneratorTarget* gtgt)
  2180. {
  2181. cmXCodeObject* shellBuildPhase =
  2182. this->CreateObject(cmXCodeObject::PBXShellScriptBuildPhase);
  2183. shellBuildPhase->AddAttribute("buildActionMask",
  2184. this->CreateString("2147483647"));
  2185. cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2186. shellBuildPhase->AddAttribute("files", buildFiles);
  2187. cmXCodeObject* inputPaths = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2188. shellBuildPhase->AddAttribute("inputPaths", inputPaths);
  2189. cmXCodeObject* outputPaths = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2190. shellBuildPhase->AddAttribute("outputPaths", outputPaths);
  2191. shellBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
  2192. this->CreateString("0"));
  2193. shellBuildPhase->AddAttribute("shellPath", this->CreateString("/bin/sh"));
  2194. shellBuildPhase->AddAttribute(
  2195. "shellScript", this->CreateString("# shell script goes here\nexit 0"));
  2196. shellBuildPhase->AddAttribute("showEnvVarsInLog", this->CreateString("0"));
  2197. cmXCodeObject* target =
  2198. this->CreateObject(cmXCodeObject::PBXAggregateTarget);
  2199. target->SetComment(gtgt->GetName());
  2200. cmXCodeObject* buildPhases = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2201. std::vector<cmXCodeObject*> emptyContentVector;
  2202. this->CreateCustomCommands(buildPhases, nullptr, nullptr, nullptr,
  2203. emptyContentVector, nullptr, gtgt);
  2204. target->AddAttribute("buildPhases", buildPhases);
  2205. this->AddConfigurations(target, gtgt);
  2206. cmXCodeObject* dependencies = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2207. target->AddAttribute("dependencies", dependencies);
  2208. target->AddAttribute("name", this->CreateString(gtgt->GetName()));
  2209. target->AddAttribute("productName", this->CreateString(gtgt->GetName()));
  2210. target->SetTarget(gtgt);
  2211. this->XCodeObjectMap[gtgt] = target;
  2212. // Add source files without build rules for editing convenience.
  2213. if (gtgt->GetType() == cmStateEnums::UTILITY &&
  2214. gtgt->GetName() != CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
  2215. std::vector<cmSourceFile*> sources;
  2216. if (!gtgt->GetConfigCommonSourceFiles(sources)) {
  2217. return nullptr;
  2218. }
  2219. // Add CMakeLists.txt file for user convenience.
  2220. this->AddXCodeProjBuildRule(gtgt, sources);
  2221. for (auto sourceFile : sources) {
  2222. if (!sourceFile->GetIsGenerated()) {
  2223. this->CreateXCodeFileReference(sourceFile, gtgt);
  2224. }
  2225. }
  2226. }
  2227. target->SetId(this->GetOrCreateId(gtgt->GetName(), target->GetId()));
  2228. return target;
  2229. }
  2230. std::string cmGlobalXCodeGenerator::AddConfigurations(cmXCodeObject* target,
  2231. cmGeneratorTarget* gtgt)
  2232. {
  2233. std::vector<std::string> const configVector = cmExpandedList(
  2234. this->CurrentMakefile->GetRequiredDefinition("CMAKE_CONFIGURATION_TYPES"));
  2235. cmXCodeObject* configlist =
  2236. this->CreateObject(cmXCodeObject::XCConfigurationList);
  2237. cmXCodeObject* buildConfigurations =
  2238. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2239. configlist->AddAttribute("buildConfigurations", buildConfigurations);
  2240. std::string comment = cmStrCat("Build configuration list for ",
  2241. cmXCodeObject::PBXTypeNames[target->GetIsA()],
  2242. " \"", gtgt->GetName(), '"');
  2243. configlist->SetComment(comment);
  2244. target->AddAttribute("buildConfigurationList",
  2245. this->CreateObjectReference(configlist));
  2246. for (auto const& i : configVector) {
  2247. cmXCodeObject* config =
  2248. this->CreateObject(cmXCodeObject::XCBuildConfiguration);
  2249. buildConfigurations->AddObject(config);
  2250. cmXCodeObject* buildSettings =
  2251. this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  2252. this->CreateBuildSettings(gtgt, buildSettings, i);
  2253. config->AddAttribute("name", this->CreateString(i));
  2254. config->SetComment(i);
  2255. config->AddAttribute("buildSettings", buildSettings);
  2256. }
  2257. if (!configVector.empty()) {
  2258. configlist->AddAttribute("defaultConfigurationName",
  2259. this->CreateString(configVector[0]));
  2260. configlist->AddAttribute("defaultConfigurationIsVisible",
  2261. this->CreateString("0"));
  2262. return configVector[0];
  2263. }
  2264. return "";
  2265. }
  2266. const char* cmGlobalXCodeGenerator::GetTargetLinkFlagsVar(
  2267. cmGeneratorTarget const* target) const
  2268. {
  2269. if (this->XcodeVersion >= 60 &&
  2270. (target->GetType() == cmStateEnums::STATIC_LIBRARY ||
  2271. target->GetType() == cmStateEnums::OBJECT_LIBRARY)) {
  2272. return "OTHER_LIBTOOLFLAGS";
  2273. }
  2274. return "OTHER_LDFLAGS";
  2275. }
  2276. const char* cmGlobalXCodeGenerator::GetTargetFileType(
  2277. cmGeneratorTarget* target)
  2278. {
  2279. if (cmProp e = target->GetProperty("XCODE_EXPLICIT_FILE_TYPE")) {
  2280. return e->c_str();
  2281. }
  2282. switch (target->GetType()) {
  2283. case cmStateEnums::OBJECT_LIBRARY:
  2284. return "archive.ar";
  2285. case cmStateEnums::STATIC_LIBRARY:
  2286. return (target->GetPropertyAsBool("FRAMEWORK") ? "wrapper.framework"
  2287. : "archive.ar");
  2288. case cmStateEnums::MODULE_LIBRARY:
  2289. if (target->IsXCTestOnApple()) {
  2290. return "wrapper.cfbundle";
  2291. }
  2292. if (target->IsCFBundleOnApple()) {
  2293. return "wrapper.plug-in";
  2294. }
  2295. return "compiled.mach-o.executable";
  2296. case cmStateEnums::SHARED_LIBRARY:
  2297. return (target->GetPropertyAsBool("FRAMEWORK")
  2298. ? "wrapper.framework"
  2299. : "compiled.mach-o.dylib");
  2300. case cmStateEnums::EXECUTABLE:
  2301. return "compiled.mach-o.executable";
  2302. default:
  2303. break;
  2304. }
  2305. return nullptr;
  2306. }
  2307. const char* cmGlobalXCodeGenerator::GetTargetProductType(
  2308. cmGeneratorTarget* target)
  2309. {
  2310. if (cmProp e = target->GetProperty("XCODE_PRODUCT_TYPE")) {
  2311. return e->c_str();
  2312. }
  2313. switch (target->GetType()) {
  2314. case cmStateEnums::OBJECT_LIBRARY:
  2315. return "com.apple.product-type.library.static";
  2316. case cmStateEnums::STATIC_LIBRARY:
  2317. return (target->GetPropertyAsBool("FRAMEWORK")
  2318. ? "com.apple.product-type.framework"
  2319. : "com.apple.product-type.library.static");
  2320. case cmStateEnums::MODULE_LIBRARY:
  2321. if (target->IsXCTestOnApple()) {
  2322. return "com.apple.product-type.bundle.unit-test";
  2323. } else if (target->IsCFBundleOnApple()) {
  2324. return "com.apple.product-type.bundle";
  2325. } else {
  2326. return "com.apple.product-type.tool";
  2327. }
  2328. case cmStateEnums::SHARED_LIBRARY:
  2329. return (target->GetPropertyAsBool("FRAMEWORK")
  2330. ? "com.apple.product-type.framework"
  2331. : "com.apple.product-type.library.dynamic");
  2332. case cmStateEnums::EXECUTABLE:
  2333. return (target->GetPropertyAsBool("MACOSX_BUNDLE")
  2334. ? "com.apple.product-type.application"
  2335. : "com.apple.product-type.tool");
  2336. default:
  2337. break;
  2338. }
  2339. return nullptr;
  2340. }
  2341. cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeTarget(
  2342. cmGeneratorTarget* gtgt, cmXCodeObject* buildPhases)
  2343. {
  2344. if (gtgt->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  2345. return nullptr;
  2346. }
  2347. cmXCodeObject* target = this->CreateObject(cmXCodeObject::PBXNativeTarget);
  2348. target->AddAttribute("buildPhases", buildPhases);
  2349. cmXCodeObject* buildRules = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2350. target->AddAttribute("buildRules", buildRules);
  2351. std::string defConfig;
  2352. defConfig = this->AddConfigurations(target, gtgt);
  2353. cmXCodeObject* dependencies = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2354. target->AddAttribute("dependencies", dependencies);
  2355. target->AddAttribute("name", this->CreateString(gtgt->GetName()));
  2356. target->AddAttribute("productName", this->CreateString(gtgt->GetName()));
  2357. cmXCodeObject* fileRef = this->CreateObject(cmXCodeObject::PBXFileReference);
  2358. if (const char* fileType = this->GetTargetFileType(gtgt)) {
  2359. fileRef->AddAttribute("explicitFileType", this->CreateString(fileType));
  2360. }
  2361. std::string fullName;
  2362. if (gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  2363. fullName = cmStrCat("lib", gtgt->GetName(), ".a");
  2364. } else {
  2365. fullName = gtgt->GetFullName(defConfig);
  2366. }
  2367. fileRef->AddAttribute("path", this->CreateString(fullName));
  2368. fileRef->AddAttribute("sourceTree",
  2369. this->CreateString("BUILT_PRODUCTS_DIR"));
  2370. fileRef->SetComment(gtgt->GetName());
  2371. target->AddAttribute("productReference",
  2372. this->CreateObjectReference(fileRef));
  2373. if (const char* productType = this->GetTargetProductType(gtgt)) {
  2374. target->AddAttribute("productType", this->CreateString(productType));
  2375. }
  2376. target->SetTarget(gtgt);
  2377. this->XCodeObjectMap[gtgt] = target;
  2378. target->SetId(this->GetOrCreateId(gtgt->GetName(), target->GetId()));
  2379. return target;
  2380. }
  2381. cmXCodeObject* cmGlobalXCodeGenerator::FindXCodeTarget(
  2382. cmGeneratorTarget const* t)
  2383. {
  2384. if (!t) {
  2385. return nullptr;
  2386. }
  2387. auto const i = this->XCodeObjectMap.find(t);
  2388. if (i == this->XCodeObjectMap.end()) {
  2389. return nullptr;
  2390. }
  2391. return i->second;
  2392. }
  2393. std::string cmGlobalXCodeGenerator::GetOrCreateId(const std::string& name,
  2394. const std::string& id)
  2395. {
  2396. std::string guidStoreName = cmStrCat(name, "_GUID_CMAKE");
  2397. const char* storedGUID =
  2398. this->CMakeInstance->GetCacheDefinition(guidStoreName);
  2399. if (storedGUID) {
  2400. return storedGUID;
  2401. }
  2402. this->CMakeInstance->AddCacheEntry(guidStoreName, id.c_str(),
  2403. "Stored Xcode object GUID",
  2404. cmStateEnums::INTERNAL);
  2405. return id;
  2406. }
  2407. void cmGlobalXCodeGenerator::AddDependTarget(cmXCodeObject* target,
  2408. cmXCodeObject* dependTarget)
  2409. {
  2410. // This is called once for every edge in the target dependency graph.
  2411. cmXCodeObject* container =
  2412. this->CreateObject(cmXCodeObject::PBXContainerItemProxy);
  2413. container->SetComment("PBXContainerItemProxy");
  2414. container->AddAttribute("containerPortal",
  2415. this->CreateObjectReference(this->RootObject));
  2416. container->AddAttribute("proxyType", this->CreateString("1"));
  2417. container->AddAttribute("remoteGlobalIDString",
  2418. this->CreateObjectReference(dependTarget));
  2419. container->AddAttribute(
  2420. "remoteInfo", this->CreateString(dependTarget->GetTarget()->GetName()));
  2421. cmXCodeObject* targetdep =
  2422. this->CreateObject(cmXCodeObject::PBXTargetDependency);
  2423. targetdep->SetComment("PBXTargetDependency");
  2424. targetdep->AddAttribute("target", this->CreateObjectReference(dependTarget));
  2425. targetdep->AddAttribute("targetProxy",
  2426. this->CreateObjectReference(container));
  2427. cmXCodeObject* depends = target->GetObject("dependencies");
  2428. if (!depends) {
  2429. cmSystemTools::Error(
  2430. "target does not have dependencies attribute error..");
  2431. } else {
  2432. depends->AddUniqueObject(targetdep);
  2433. }
  2434. }
  2435. void cmGlobalXCodeGenerator::AppendOrAddBuildSetting(cmXCodeObject* settings,
  2436. const char* attribute,
  2437. const char* value)
  2438. {
  2439. if (settings) {
  2440. cmXCodeObject* attr = settings->GetObject(attribute);
  2441. if (!attr) {
  2442. settings->AddAttribute(attribute, this->CreateString(value));
  2443. } else {
  2444. std::string oldValue = cmStrCat(attr->GetString(), ' ', value);
  2445. attr->SetString(oldValue);
  2446. }
  2447. }
  2448. }
  2449. void cmGlobalXCodeGenerator::AppendBuildSettingAttribute(
  2450. cmXCodeObject* target, const char* attribute, const char* value,
  2451. const std::string& configName)
  2452. {
  2453. // There are multiple configurations. Add the setting to the
  2454. // buildSettings of the configuration name given.
  2455. cmXCodeObject* configurationList =
  2456. target->GetObject("buildConfigurationList")->GetObject();
  2457. cmXCodeObject* buildConfigs =
  2458. configurationList->GetObject("buildConfigurations");
  2459. for (auto obj : buildConfigs->GetObjectList()) {
  2460. if (configName.empty() ||
  2461. obj->GetObject("name")->GetString() == configName) {
  2462. cmXCodeObject* settings = obj->GetObject("buildSettings");
  2463. this->AppendOrAddBuildSetting(settings, attribute, value);
  2464. }
  2465. }
  2466. }
  2467. void cmGlobalXCodeGenerator::AddDependAndLinkInformation(cmXCodeObject* target)
  2468. {
  2469. cmGeneratorTarget* gt = target->GetTarget();
  2470. if (!gt) {
  2471. cmSystemTools::Error("Error no target on xobject\n");
  2472. return;
  2473. }
  2474. if (gt->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  2475. return;
  2476. }
  2477. // Add dependencies on other CMake targets.
  2478. for (const auto& dep : this->GetTargetDirectDepends(gt)) {
  2479. if (cmXCodeObject* dptarget = this->FindXCodeTarget(dep)) {
  2480. this->AddDependTarget(target, dptarget);
  2481. }
  2482. }
  2483. // Separate libraries into ones that can be linked using "Link Binary With
  2484. // Libraries" build phase and the ones that can't. Only targets that build
  2485. // Apple bundles (.app, .framework, .bundle) can use this feature and only
  2486. // targets that represent actual libraries (static or dynamic, local or
  2487. // imported) not objects and not executables will be used. These are
  2488. // limitations imposed by CMake use-cases - otherwise a lot of things break.
  2489. // The rest will be linked using linker flags (OTHER_LDFLAGS setting in Xcode
  2490. // project).
  2491. std::map<std::string, std::vector<cmComputeLinkInformation::Item const*>>
  2492. configItemMap;
  2493. auto addToLinkerArguments =
  2494. [&configItemMap](const std::string& configName,
  2495. cmComputeLinkInformation::Item const* libItemPtr) {
  2496. auto& linkVector = configItemMap[configName];
  2497. if (std::find_if(linkVector.begin(), linkVector.end(),
  2498. [libItemPtr](cmComputeLinkInformation::Item const* p) {
  2499. return p == libItemPtr;
  2500. }) == linkVector.end()) {
  2501. linkVector.push_back(libItemPtr);
  2502. }
  2503. };
  2504. std::vector<cmComputeLinkInformation::Item const*> linkPhaseTargetVector;
  2505. std::map<std::string, std::vector<std::string>> targetConfigMap;
  2506. using ConfigItemPair =
  2507. std::pair<std::string, cmComputeLinkInformation::Item const*>;
  2508. std::map<std::string, std::vector<ConfigItemPair>> targetItemMap;
  2509. std::map<std::string, std::vector<std::string>> targetProductNameMap;
  2510. for (auto const& configName : this->CurrentConfigurationTypes) {
  2511. cmComputeLinkInformation* cli = gt->GetLinkInformation(configName);
  2512. if (!cli) {
  2513. continue;
  2514. }
  2515. for (auto const& libItem : cli->GetItems()) {
  2516. // TODO: Drop this check once we have option to add outside libraries to
  2517. // Xcode project
  2518. auto* libTarget = FindXCodeTarget(libItem.Target);
  2519. if (gt->IsBundleOnApple() &&
  2520. (gt->GetType() == cmStateEnums::EXECUTABLE ||
  2521. gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
  2522. gt->GetType() == cmStateEnums::MODULE_LIBRARY ||
  2523. gt->GetType() == cmStateEnums::UNKNOWN_LIBRARY) &&
  2524. (libTarget && libItem.Target &&
  2525. (libItem.Target->GetType() == cmStateEnums::STATIC_LIBRARY ||
  2526. libItem.Target->GetType() == cmStateEnums::SHARED_LIBRARY ||
  2527. libItem.Target->GetType() == cmStateEnums::MODULE_LIBRARY))) {
  2528. // Add unique configuration name to target-config map for later
  2529. // checks
  2530. std::string libName = libItem.Target->GetName();
  2531. auto& configVector = targetConfigMap[libName];
  2532. if (std::find(configVector.begin(), configVector.end(), configName) ==
  2533. configVector.end()) {
  2534. configVector.push_back(configName);
  2535. }
  2536. // Add a pair of config and item to target-item map
  2537. auto& itemVector = targetItemMap[libName];
  2538. itemVector.emplace_back(ConfigItemPair(configName, &libItem));
  2539. // Add product file-name to a lib-product map
  2540. auto productName = cmSystemTools::GetFilenameName(libItem.Value.Value);
  2541. auto& productVector = targetProductNameMap[libName];
  2542. if (std::find(productVector.begin(), productVector.end(),
  2543. productName) == productVector.end()) {
  2544. productVector.push_back(productName);
  2545. }
  2546. } else {
  2547. // Add this library item to a regular linker flag list
  2548. addToLinkerArguments(configName, &libItem);
  2549. }
  2550. }
  2551. }
  2552. // Go through target library map and separate libraries that are linked
  2553. // in all configurations and produce only single product, from the rest.
  2554. // Only these will be linked through "Link Binary With Libraries" build
  2555. // phase.
  2556. for (auto const& targetLibConfigs : targetConfigMap) {
  2557. // Add this library to "Link Binary With Libraries" build phase if it's
  2558. // linked in all configurations and it has only one product name
  2559. auto& itemVector = targetItemMap[targetLibConfigs.first];
  2560. auto& productVector = targetProductNameMap[targetLibConfigs.first];
  2561. if (targetLibConfigs.second == this->CurrentConfigurationTypes &&
  2562. productVector.size() == 1) {
  2563. // Add this library to "Link Binary With Libraries" list
  2564. linkPhaseTargetVector.push_back(itemVector[0].second);
  2565. } else {
  2566. for (auto const& libItem : targetItemMap[targetLibConfigs.first]) {
  2567. // Add this library item to a regular linker flag list
  2568. addToLinkerArguments(libItem.first, libItem.second);
  2569. }
  2570. }
  2571. }
  2572. // Add libraries to "Link Binary With Libraries" build phase and collect
  2573. // their search paths. Xcode does not support per-configuration linking
  2574. // in this build phase so we don't have to do this for each configuration
  2575. // separately.
  2576. std::vector<std::string> linkSearchPaths;
  2577. for (auto const& libItem : linkPhaseTargetVector) {
  2578. // Add target output directory as a library search path
  2579. std::string linkDir = cmSystemTools::GetParentDirectory(
  2580. libItem->Target->GetLocationForBuild());
  2581. if (std::find(linkSearchPaths.begin(), linkSearchPaths.end(), linkDir) ==
  2582. linkSearchPaths.end()) {
  2583. linkSearchPaths.push_back(linkDir);
  2584. }
  2585. // Add target dependency
  2586. auto const& libName = *libItem;
  2587. if (!libName.Target->IsImported()) {
  2588. for (auto const& configName : this->CurrentConfigurationTypes) {
  2589. target->AddDependTarget(configName, libName.Target->GetName());
  2590. }
  2591. }
  2592. // Get the library target
  2593. auto* libTarget = FindXCodeTarget(libItem->Target);
  2594. if (!libTarget) {
  2595. continue;
  2596. }
  2597. // Add the target output file as a build reference for other targets
  2598. // to link against
  2599. auto* fileRefObject = libTarget->GetObject("productReference");
  2600. if (!fileRefObject) {
  2601. continue;
  2602. }
  2603. cmXCodeObject* buildFile;
  2604. auto it = FileRefToBuildFileMap.find(fileRefObject);
  2605. if (it == FileRefToBuildFileMap.end()) {
  2606. buildFile = this->CreateObject(cmXCodeObject::PBXBuildFile);
  2607. buildFile->AddAttribute("fileRef", fileRefObject);
  2608. FileRefToBuildFileMap[fileRefObject] = buildFile;
  2609. } else {
  2610. buildFile = it->second;
  2611. }
  2612. // Add this reference to current target
  2613. auto* buildPhases = target->GetObject("buildPhases");
  2614. if (!buildPhases) {
  2615. continue;
  2616. }
  2617. auto* frameworkBuildPhase =
  2618. buildPhases->GetObject(cmXCodeObject::PBXFrameworksBuildPhase);
  2619. if (!frameworkBuildPhase) {
  2620. continue;
  2621. }
  2622. auto* buildFiles = frameworkBuildPhase->GetObject("files");
  2623. if (!buildFiles) {
  2624. continue;
  2625. }
  2626. if (!buildFiles->HasObject(buildFile)) {
  2627. buildFiles->AddObject(buildFile);
  2628. }
  2629. }
  2630. // Loop over configuration types and set per-configuration info.
  2631. for (auto const& configName : this->CurrentConfigurationTypes) {
  2632. {
  2633. // Add object library contents as link flags.
  2634. std::string linkObjs;
  2635. const char* sep = "";
  2636. std::vector<cmSourceFile const*> objs;
  2637. gt->GetExternalObjects(objs, configName);
  2638. for (auto sourceFile : objs) {
  2639. if (sourceFile->GetObjectLibrary().empty()) {
  2640. continue;
  2641. }
  2642. linkObjs += sep;
  2643. sep = " ";
  2644. linkObjs += this->XCodeEscapePath(sourceFile->GetFullPath());
  2645. }
  2646. this->AppendBuildSettingAttribute(
  2647. target, this->GetTargetLinkFlagsVar(gt), linkObjs.c_str(), configName);
  2648. }
  2649. // Skip link information for object libraries.
  2650. if (gt->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  2651. gt->GetType() == cmStateEnums::STATIC_LIBRARY) {
  2652. continue;
  2653. }
  2654. // Compute the link library and directory information.
  2655. cmComputeLinkInformation* cli = gt->GetLinkInformation(configName);
  2656. if (!cli) {
  2657. continue;
  2658. }
  2659. // Add dependencies directly on library files.
  2660. for (auto const& libDep : cli->GetDepends()) {
  2661. target->AddDependLibrary(configName, libDep);
  2662. }
  2663. // add the library search paths
  2664. {
  2665. std::string linkDirs;
  2666. for (auto const& libDir : cli->GetDirectories()) {
  2667. if (!libDir.empty() && libDir != "/usr/lib") {
  2668. // Now add the same one but append
  2669. // $(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) to it:
  2670. linkDirs += " ";
  2671. linkDirs += this->XCodeEscapePath(
  2672. libDir + "/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)");
  2673. linkDirs += " ";
  2674. linkDirs += this->XCodeEscapePath(libDir);
  2675. }
  2676. }
  2677. // Add previously collected paths where to look for libraries
  2678. // that were added to "Link Binary With Libraries"
  2679. for (auto& linkDir : linkSearchPaths) {
  2680. linkDirs += " ";
  2681. linkDirs += this->XCodeEscapePath(linkDir);
  2682. }
  2683. this->AppendBuildSettingAttribute(target, "LIBRARY_SEARCH_PATHS",
  2684. linkDirs.c_str(), configName);
  2685. }
  2686. // now add the left-over link libraries
  2687. {
  2688. std::string linkLibs;
  2689. const char* sep = "";
  2690. for (auto const& libItem : configItemMap[configName]) {
  2691. auto const& libName = *libItem;
  2692. linkLibs += sep;
  2693. sep = " ";
  2694. if (libName.IsPath) {
  2695. linkLibs += this->XCodeEscapePath(libName.Value.Value);
  2696. } else if (!libName.Target ||
  2697. libName.Target->GetType() !=
  2698. cmStateEnums::INTERFACE_LIBRARY) {
  2699. linkLibs += libName.Value.Value;
  2700. }
  2701. if (libName.Target && !libName.Target->IsImported()) {
  2702. target->AddDependTarget(configName, libName.Target->GetName());
  2703. }
  2704. }
  2705. this->AppendBuildSettingAttribute(
  2706. target, this->GetTargetLinkFlagsVar(gt), linkLibs.c_str(), configName);
  2707. }
  2708. }
  2709. }
  2710. bool cmGlobalXCodeGenerator::CreateGroups(
  2711. std::vector<cmLocalGenerator*>& generators)
  2712. {
  2713. for (auto& generator : generators) {
  2714. cmMakefile* mf = generator->GetMakefile();
  2715. std::vector<cmSourceGroup> sourceGroups = mf->GetSourceGroups();
  2716. for (const auto& gtgt : generator->GetGeneratorTargets()) {
  2717. // Same skipping logic here as in CreateXCodeTargets so that we do not
  2718. // end up with (empty anyhow) ZERO_CHECK, install, or test source
  2719. // groups:
  2720. //
  2721. if (gtgt->GetType() == cmStateEnums::GLOBAL_TARGET) {
  2722. continue;
  2723. }
  2724. if (gtgt->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  2725. continue;
  2726. }
  2727. if (gtgt->GetName() == CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
  2728. continue;
  2729. }
  2730. auto addSourceToGroup = [this, mf, &gtgt,
  2731. &sourceGroups](std::string const& source) {
  2732. cmSourceGroup* sourceGroup = mf->FindSourceGroup(source, sourceGroups);
  2733. cmXCodeObject* pbxgroup =
  2734. this->CreateOrGetPBXGroup(gtgt.get(), sourceGroup);
  2735. std::string key = GetGroupMapKeyFromPath(gtgt.get(), source);
  2736. this->GroupMap[key] = pbxgroup;
  2737. };
  2738. // Put cmSourceFile instances in proper groups:
  2739. for (auto const& si : gtgt->GetAllConfigSources()) {
  2740. cmSourceFile const* sf = si.Source;
  2741. if (!sf->GetObjectLibrary().empty()) {
  2742. // Object library files go on the link line instead.
  2743. continue;
  2744. }
  2745. addSourceToGroup(sf->GetFullPath());
  2746. }
  2747. // Add CMakeLists.txt file for user convenience.
  2748. {
  2749. std::string listfile =
  2750. cmStrCat(gtgt->GetLocalGenerator()->GetCurrentSourceDirectory(),
  2751. "/CMakeLists.txt");
  2752. cmSourceFile* sf = gtgt->Makefile->GetOrCreateSource(
  2753. listfile, false, cmSourceFileLocationKind::Known);
  2754. addSourceToGroup(sf->ResolveFullPath());
  2755. }
  2756. // Add the Info.plist we are about to generate for an App Bundle.
  2757. if (gtgt->GetPropertyAsBool("MACOSX_BUNDLE")) {
  2758. std::string plist = this->ComputeInfoPListLocation(gtgt.get());
  2759. cmSourceFile* sf = gtgt->Makefile->GetOrCreateSource(
  2760. plist, true, cmSourceFileLocationKind::Known);
  2761. addSourceToGroup(sf->ResolveFullPath());
  2762. }
  2763. }
  2764. }
  2765. return true;
  2766. }
  2767. cmXCodeObject* cmGlobalXCodeGenerator::CreatePBXGroup(cmXCodeObject* parent,
  2768. const std::string& name)
  2769. {
  2770. cmXCodeObject* parentChildren = nullptr;
  2771. if (parent) {
  2772. parentChildren = parent->GetObject("children");
  2773. }
  2774. cmXCodeObject* group = this->CreateObject(cmXCodeObject::PBXGroup);
  2775. cmXCodeObject* groupChildren =
  2776. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2777. group->AddAttribute("name", this->CreateString(name));
  2778. group->AddAttribute("children", groupChildren);
  2779. group->AddAttribute("sourceTree", this->CreateString("<group>"));
  2780. if (parentChildren) {
  2781. parentChildren->AddObject(group);
  2782. }
  2783. return group;
  2784. }
  2785. cmXCodeObject* cmGlobalXCodeGenerator::CreateOrGetPBXGroup(
  2786. cmGeneratorTarget* gtgt, cmSourceGroup* sg)
  2787. {
  2788. std::string s;
  2789. std::string target;
  2790. const std::string targetFolder = gtgt->GetEffectiveFolderName();
  2791. if (!targetFolder.empty()) {
  2792. target = cmStrCat(targetFolder, '/');
  2793. }
  2794. target += gtgt->GetName();
  2795. s = cmStrCat(target, '/', sg->GetFullName());
  2796. auto it = this->GroupNameMap.find(s);
  2797. if (it != this->GroupNameMap.end()) {
  2798. return it->second;
  2799. }
  2800. it = this->TargetGroup.find(target);
  2801. cmXCodeObject* tgroup = nullptr;
  2802. if (it != this->TargetGroup.end()) {
  2803. tgroup = it->second;
  2804. } else {
  2805. std::vector<std::string> tgt_folders = cmTokenize(target, "/");
  2806. std::string curr_tgt_folder;
  2807. for (std::vector<std::string>::size_type i = 0; i < tgt_folders.size();
  2808. i++) {
  2809. if (i != 0) {
  2810. curr_tgt_folder += "/";
  2811. }
  2812. curr_tgt_folder += tgt_folders[i];
  2813. it = this->TargetGroup.find(curr_tgt_folder);
  2814. if (it != this->TargetGroup.end()) {
  2815. tgroup = it->second;
  2816. continue;
  2817. }
  2818. tgroup = this->CreatePBXGroup(tgroup, tgt_folders[i]);
  2819. this->TargetGroup[curr_tgt_folder] = tgroup;
  2820. if (i == 0) {
  2821. this->MainGroupChildren->AddObject(tgroup);
  2822. }
  2823. }
  2824. }
  2825. this->TargetGroup[target] = tgroup;
  2826. // If it's the default source group (empty name) then put the source file
  2827. // directly in the tgroup...
  2828. //
  2829. if (sg->GetFullName().empty()) {
  2830. this->GroupNameMap[s] = tgroup;
  2831. return tgroup;
  2832. }
  2833. // It's a recursive folder structure, let's find the real parent group
  2834. if (sg->GetFullName() != sg->GetName()) {
  2835. std::string curr_folder = cmStrCat(target, '/');
  2836. for (auto const& folder : cmTokenize(sg->GetFullName(), "\\")) {
  2837. curr_folder += folder;
  2838. auto const i_folder = this->GroupNameMap.find(curr_folder);
  2839. // Create new folder
  2840. if (i_folder == this->GroupNameMap.end()) {
  2841. cmXCodeObject* group = this->CreatePBXGroup(tgroup, folder);
  2842. this->GroupNameMap[curr_folder] = group;
  2843. tgroup = group;
  2844. } else {
  2845. tgroup = i_folder->second;
  2846. }
  2847. curr_folder += "\\";
  2848. }
  2849. return tgroup;
  2850. }
  2851. cmXCodeObject* group = this->CreatePBXGroup(tgroup, sg->GetName());
  2852. this->GroupNameMap[s] = group;
  2853. return group;
  2854. }
  2855. bool cmGlobalXCodeGenerator::CreateXCodeObjects(
  2856. cmLocalGenerator* root, std::vector<cmLocalGenerator*>& generators)
  2857. {
  2858. this->ClearXCodeObjects();
  2859. this->RootObject = nullptr;
  2860. this->MainGroupChildren = nullptr;
  2861. cmXCodeObject* group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  2862. group->AddAttribute("COPY_PHASE_STRIP", this->CreateString("NO"));
  2863. cmXCodeObject* listObjs = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2864. for (const std::string& CurrentConfigurationType :
  2865. this->CurrentConfigurationTypes) {
  2866. cmXCodeObject* buildStyle =
  2867. this->CreateObject(cmXCodeObject::PBXBuildStyle);
  2868. const std::string& name = CurrentConfigurationType;
  2869. buildStyle->AddAttribute("name", this->CreateString(name));
  2870. buildStyle->SetComment(name);
  2871. cmXCodeObject* sgroup = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  2872. sgroup->AddAttribute("COPY_PHASE_STRIP", this->CreateString("NO"));
  2873. buildStyle->AddAttribute("buildSettings", sgroup);
  2874. listObjs->AddObject(buildStyle);
  2875. }
  2876. cmXCodeObject* mainGroup = this->CreateObject(cmXCodeObject::PBXGroup);
  2877. this->MainGroupChildren = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2878. mainGroup->AddAttribute("children", this->MainGroupChildren);
  2879. mainGroup->AddAttribute("sourceTree", this->CreateString("<group>"));
  2880. // now create the cmake groups
  2881. if (!this->CreateGroups(generators)) {
  2882. return false;
  2883. }
  2884. cmXCodeObject* productGroup = this->CreateObject(cmXCodeObject::PBXGroup);
  2885. productGroup->AddAttribute("name", this->CreateString("Products"));
  2886. productGroup->AddAttribute("sourceTree", this->CreateString("<group>"));
  2887. cmXCodeObject* productGroupChildren =
  2888. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2889. productGroup->AddAttribute("children", productGroupChildren);
  2890. this->MainGroupChildren->AddObject(productGroup);
  2891. this->RootObject = this->CreateObject(cmXCodeObject::PBXProject);
  2892. this->RootObject->SetComment("Project object");
  2893. std::string project_id = cmStrCat("PROJECT_", root->GetProjectName());
  2894. this->RootObject->SetId(
  2895. this->GetOrCreateId(project_id, this->RootObject->GetId()));
  2896. group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  2897. this->RootObject->AddAttribute("mainGroup",
  2898. this->CreateObjectReference(mainGroup));
  2899. this->RootObject->AddAttribute("buildSettings", group);
  2900. this->RootObject->AddAttribute("buildStyles", listObjs);
  2901. this->RootObject->AddAttribute("hasScannedForEncodings",
  2902. this->CreateString("0"));
  2903. group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  2904. group->AddAttribute("BuildIndependentTargetsInParallel",
  2905. this->CreateString("YES"));
  2906. std::ostringstream v;
  2907. v << std::setfill('0') << std::setw(4) << XcodeVersion * 10;
  2908. group->AddAttribute("LastUpgradeCheck", this->CreateString(v.str()));
  2909. this->RootObject->AddAttribute("attributes", group);
  2910. this->RootObject->AddAttribute("compatibilityVersion",
  2911. this->CreateString("Xcode 3.2"));
  2912. // Point Xcode at the top of the source tree.
  2913. {
  2914. std::string pdir =
  2915. this->RelativeToBinary(root->GetCurrentSourceDirectory());
  2916. this->RootObject->AddAttribute("projectDirPath", this->CreateString(pdir));
  2917. this->RootObject->AddAttribute("projectRoot", this->CreateString(""));
  2918. }
  2919. cmXCodeObject* configlist =
  2920. this->CreateObject(cmXCodeObject::XCConfigurationList);
  2921. cmXCodeObject* buildConfigurations =
  2922. this->CreateObject(cmXCodeObject::OBJECT_LIST);
  2923. using Configs = std::vector<std::pair<std::string, cmXCodeObject*>>;
  2924. Configs configs;
  2925. std::string defaultConfigName;
  2926. for (const auto& name : this->CurrentConfigurationTypes) {
  2927. if (defaultConfigName.empty()) {
  2928. defaultConfigName = name;
  2929. }
  2930. cmXCodeObject* config =
  2931. this->CreateObject(cmXCodeObject::XCBuildConfiguration);
  2932. config->AddAttribute("name", this->CreateString(name));
  2933. configs.push_back(std::make_pair(name, config));
  2934. }
  2935. if (defaultConfigName.empty()) {
  2936. defaultConfigName = "Debug";
  2937. }
  2938. for (auto& config : configs) {
  2939. buildConfigurations->AddObject(config.second);
  2940. }
  2941. configlist->AddAttribute("buildConfigurations", buildConfigurations);
  2942. std::string comment = cmStrCat("Build configuration list for PBXProject \"",
  2943. this->CurrentProject, '"');
  2944. configlist->SetComment(comment);
  2945. configlist->AddAttribute("defaultConfigurationIsVisible",
  2946. this->CreateString("0"));
  2947. configlist->AddAttribute("defaultConfigurationName",
  2948. this->CreateString(defaultConfigName));
  2949. cmXCodeObject* buildSettings =
  2950. this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
  2951. const char* sysroot =
  2952. this->CurrentMakefile->GetDefinition("CMAKE_OSX_SYSROOT");
  2953. const char* deploymentTarget =
  2954. this->CurrentMakefile->GetDefinition("CMAKE_OSX_DEPLOYMENT_TARGET");
  2955. if (sysroot) {
  2956. buildSettings->AddAttribute("SDKROOT", this->CreateString(sysroot));
  2957. }
  2958. // recompute this as it may have been changed since enable language
  2959. this->ComputeArchitectures(this->CurrentMakefile);
  2960. std::string const archs = cmJoin(this->Architectures, " ");
  2961. if (archs.empty()) {
  2962. // Tell Xcode to use NATIVE_ARCH instead of ARCHS.
  2963. buildSettings->AddAttribute("ONLY_ACTIVE_ARCH", this->CreateString("YES"));
  2964. } else {
  2965. // Tell Xcode to use ARCHS (ONLY_ACTIVE_ARCH defaults to NO).
  2966. buildSettings->AddAttribute("ARCHS", this->CreateString(archs));
  2967. }
  2968. if (deploymentTarget && *deploymentTarget) {
  2969. buildSettings->AddAttribute(GetDeploymentPlatform(root->GetMakefile()),
  2970. this->CreateString(deploymentTarget));
  2971. }
  2972. if (!this->GeneratorToolset.empty()) {
  2973. buildSettings->AddAttribute("GCC_VERSION",
  2974. this->CreateString(this->GeneratorToolset));
  2975. }
  2976. if (this->GetLanguageEnabled("Swift")) {
  2977. std::string swiftVersion;
  2978. if (const char* vers = this->CurrentMakefile->GetDefinition(
  2979. "CMAKE_Swift_LANGUAGE_VERSION")) {
  2980. swiftVersion = vers;
  2981. } else if (this->XcodeVersion >= 102) {
  2982. swiftVersion = "4.0";
  2983. } else if (this->XcodeVersion >= 83) {
  2984. swiftVersion = "3.0";
  2985. } else {
  2986. swiftVersion = "2.3";
  2987. }
  2988. buildSettings->AddAttribute("SWIFT_VERSION",
  2989. this->CreateString(swiftVersion));
  2990. }
  2991. std::string symroot = cmStrCat(root->GetCurrentBinaryDirectory(), "/build");
  2992. buildSettings->AddAttribute("SYMROOT", this->CreateString(symroot));
  2993. for (auto& config : configs) {
  2994. cmXCodeObject* buildSettingsForCfg = this->CreateFlatClone(buildSettings);
  2995. // Put this last so it can override existing settings
  2996. // Convert "CMAKE_XCODE_ATTRIBUTE_*" variables directly.
  2997. for (const auto& var : this->CurrentMakefile->GetDefinitions()) {
  2998. if (cmHasLiteralPrefix(var, "CMAKE_XCODE_ATTRIBUTE_")) {
  2999. std::string attribute = var.substr(22);
  3000. this->FilterConfigurationAttribute(config.first, attribute);
  3001. if (!attribute.empty()) {
  3002. std::string processed = cmGeneratorExpression::Evaluate(
  3003. this->CurrentMakefile->GetSafeDefinition(var),
  3004. this->CurrentLocalGenerator, config.first);
  3005. buildSettingsForCfg->AddAttribute(attribute,
  3006. this->CreateString(processed));
  3007. }
  3008. }
  3009. }
  3010. // store per-config buildSettings into configuration object
  3011. config.second->AddAttribute("buildSettings", buildSettingsForCfg);
  3012. }
  3013. this->RootObject->AddAttribute("buildConfigurationList",
  3014. this->CreateObjectReference(configlist));
  3015. std::vector<cmXCodeObject*> targets;
  3016. for (auto& generator : generators) {
  3017. if (!this->CreateXCodeTargets(generator, targets)) {
  3018. return false;
  3019. }
  3020. }
  3021. // loop over all targets and add link and depend info
  3022. for (auto t : targets) {
  3023. this->AddDependAndLinkInformation(t);
  3024. }
  3025. this->CreateXCodeDependHackTarget(targets);
  3026. // now add all targets to the root object
  3027. cmXCodeObject* allTargets = this->CreateObject(cmXCodeObject::OBJECT_LIST);
  3028. for (auto t : targets) {
  3029. allTargets->AddObject(t);
  3030. cmXCodeObject* productRef = t->GetObject("productReference");
  3031. if (productRef) {
  3032. productGroupChildren->AddObject(productRef->GetObject());
  3033. }
  3034. }
  3035. this->RootObject->AddAttribute("targets", allTargets);
  3036. return true;
  3037. }
  3038. std::string cmGlobalXCodeGenerator::GetObjectsDirectory(
  3039. const std::string& projName, const std::string& configName,
  3040. const cmGeneratorTarget* t, const std::string& variant) const
  3041. {
  3042. std::string dir = cmStrCat(
  3043. t->GetLocalGenerator()->GetCurrentBinaryDirectory(), '/', projName,
  3044. ".build/", configName, '/', t->GetName(), ".build/", variant);
  3045. return dir;
  3046. }
  3047. void cmGlobalXCodeGenerator::ComputeArchitectures(cmMakefile* mf)
  3048. {
  3049. this->Architectures.clear();
  3050. const char* sysroot = mf->GetDefinition("CMAKE_OSX_SYSROOT");
  3051. if (sysroot) {
  3052. mf->GetDefExpandList("CMAKE_OSX_ARCHITECTURES", this->Architectures);
  3053. }
  3054. if (this->Architectures.empty()) {
  3055. // With no ARCHS we use ONLY_ACTIVE_ARCH.
  3056. // Look up the arch that Xcode chooses in this case.
  3057. if (const char* arch = mf->GetDefinition("CMAKE_XCODE_ARCHS")) {
  3058. this->ObjectDirArchDefault = arch;
  3059. // We expect only one arch but choose the first just in case.
  3060. std::string::size_type pos = this->ObjectDirArchDefault.find(';');
  3061. if (pos != std::string::npos) {
  3062. this->ObjectDirArchDefault = this->ObjectDirArchDefault.substr(0, pos);
  3063. }
  3064. }
  3065. }
  3066. this->ComputeObjectDirArch(mf);
  3067. }
  3068. void cmGlobalXCodeGenerator::ComputeObjectDirArch(cmMakefile* mf)
  3069. {
  3070. if (this->Architectures.size() > 1 || this->UseEffectivePlatformName(mf)) {
  3071. this->ObjectDirArch = "$(CURRENT_ARCH)";
  3072. } else if (!this->Architectures.empty()) {
  3073. this->ObjectDirArch = this->Architectures[0];
  3074. } else {
  3075. this->ObjectDirArch = this->ObjectDirArchDefault;
  3076. }
  3077. }
  3078. void cmGlobalXCodeGenerator::CreateXCodeDependHackTarget(
  3079. std::vector<cmXCodeObject*>& targets)
  3080. {
  3081. cmGeneratedFileStream makefileStream(this->CurrentXCodeHackMakefile);
  3082. if (!makefileStream) {
  3083. cmSystemTools::Error("Could not create " + this->CurrentXCodeHackMakefile);
  3084. return;
  3085. }
  3086. makefileStream.SetCopyIfDifferent(true);
  3087. // one more pass for external depend information not handled
  3088. // correctly by xcode
  3089. /* clang-format off */
  3090. makefileStream << "# DO NOT EDIT\n";
  3091. makefileStream << "# This makefile makes sure all linkable targets are\n";
  3092. makefileStream << "# up-to-date with anything they link to\n"
  3093. "default:\n"
  3094. "\techo \"Do not invoke directly\"\n"
  3095. "\n";
  3096. /* clang-format on */
  3097. std::set<std::string> dummyRules;
  3098. // Write rules to help Xcode relink things at the right time.
  3099. /* clang-format off */
  3100. makefileStream <<
  3101. "# Rules to remove targets that are older than anything to which they\n"
  3102. "# link. This forces Xcode to relink the targets from scratch. It\n"
  3103. "# does not seem to check these dependencies itself.\n";
  3104. /* clang-format on */
  3105. for (const auto& configName : this->CurrentConfigurationTypes) {
  3106. for (auto target : targets) {
  3107. cmGeneratorTarget* gt = target->GetTarget();
  3108. if (gt->GetType() == cmStateEnums::EXECUTABLE ||
  3109. gt->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  3110. gt->GetType() == cmStateEnums::STATIC_LIBRARY ||
  3111. gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
  3112. gt->GetType() == cmStateEnums::MODULE_LIBRARY) {
  3113. // Declare an entry point for the target post-build phase.
  3114. makefileStream << this->PostBuildMakeTarget(gt->GetName(), configName)
  3115. << ":\n";
  3116. }
  3117. if (gt->GetType() == cmStateEnums::EXECUTABLE ||
  3118. gt->GetType() == cmStateEnums::STATIC_LIBRARY ||
  3119. gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
  3120. gt->GetType() == cmStateEnums::MODULE_LIBRARY) {
  3121. std::string tfull = gt->GetFullPath(configName);
  3122. std::string trel = this->ConvertToRelativeForMake(tfull);
  3123. // Add this target to the post-build phases of its dependencies.
  3124. auto const y = target->GetDependTargets().find(configName);
  3125. if (y != target->GetDependTargets().end()) {
  3126. for (auto const& deptgt : y->second) {
  3127. makefileStream << this->PostBuildMakeTarget(deptgt, configName)
  3128. << ": " << trel << "\n";
  3129. }
  3130. }
  3131. std::vector<cmGeneratorTarget*> objlibs;
  3132. gt->GetObjectLibrariesCMP0026(objlibs);
  3133. for (auto objLib : objlibs) {
  3134. makefileStream << this->PostBuildMakeTarget(objLib->GetName(),
  3135. configName)
  3136. << ": " << trel << "\n";
  3137. }
  3138. // Create a rule for this target.
  3139. makefileStream << trel << ":";
  3140. // List dependencies if any exist.
  3141. auto const x = target->GetDependLibraries().find(configName);
  3142. if (x != target->GetDependLibraries().end()) {
  3143. for (auto const& deplib : x->second) {
  3144. std::string file = this->ConvertToRelativeForMake(deplib);
  3145. makefileStream << "\\\n\t" << file;
  3146. dummyRules.insert(file);
  3147. }
  3148. }
  3149. for (auto objLib : objlibs) {
  3150. const std::string objLibName = objLib->GetName();
  3151. std::string d = cmStrCat(
  3152. this->GetObjectsDirectory(this->CurrentProject, configName, objLib,
  3153. OBJECT_LIBRARY_ARTIFACT_DIR),
  3154. "lib", objLibName, ".a");
  3155. std::string dependency = this->ConvertToRelativeForMake(d);
  3156. makefileStream << "\\\n\t" << dependency;
  3157. dummyRules.insert(dependency);
  3158. }
  3159. // Write the action to remove the target if it is out of date.
  3160. makefileStream << "\n";
  3161. makefileStream << "\t/bin/rm -f "
  3162. << this->ConvertToRelativeForMake(tfull) << "\n";
  3163. // if building for more than one architecture
  3164. // then remove those executables as well
  3165. if (this->Architectures.size() > 1) {
  3166. std::string universal = this->GetObjectsDirectory(
  3167. this->CurrentProject, configName, gt, "$(OBJDIR)/");
  3168. for (const auto& architecture : this->Architectures) {
  3169. std::string universalFile = cmStrCat(universal, architecture, '/',
  3170. gt->GetFullName(configName));
  3171. makefileStream << "\t/bin/rm -f "
  3172. << this->ConvertToRelativeForMake(universalFile)
  3173. << "\n";
  3174. }
  3175. }
  3176. makefileStream << "\n\n";
  3177. }
  3178. }
  3179. }
  3180. makefileStream << "\n\n"
  3181. << "# For each target create a dummy rule"
  3182. << "so the target does not have to exist\n";
  3183. for (auto const& dummyRule : dummyRules) {
  3184. makefileStream << dummyRule << ":\n";
  3185. }
  3186. }
  3187. void cmGlobalXCodeGenerator::OutputXCodeProject(
  3188. cmLocalGenerator* root, std::vector<cmLocalGenerator*>& generators)
  3189. {
  3190. if (generators.empty()) {
  3191. return;
  3192. }
  3193. if (!this->CreateXCodeObjects(root, generators)) {
  3194. return;
  3195. }
  3196. std::string xcodeDir = cmStrCat(root->GetCurrentBinaryDirectory(), '/',
  3197. root->GetProjectName(), ".xcodeproj");
  3198. cmSystemTools::MakeDirectory(xcodeDir);
  3199. std::string xcodeProjFile = xcodeDir + "/project.pbxproj";
  3200. cmGeneratedFileStream fout(xcodeProjFile);
  3201. fout.SetCopyIfDifferent(true);
  3202. if (!fout) {
  3203. return;
  3204. }
  3205. this->WriteXCodePBXProj(fout, root, generators);
  3206. bool hasGeneratedSchemes = this->OutputXCodeSharedSchemes(xcodeDir, root);
  3207. this->OutputXCodeWorkspaceSettings(xcodeDir, hasGeneratedSchemes);
  3208. this->ClearXCodeObjects();
  3209. // Since this call may have created new cache entries, save the cache:
  3210. //
  3211. root->GetMakefile()->GetCMakeInstance()->SaveCache(
  3212. root->GetBinaryDirectory());
  3213. }
  3214. bool cmGlobalXCodeGenerator::OutputXCodeSharedSchemes(
  3215. const std::string& xcProjDir, cmLocalGenerator* root)
  3216. {
  3217. // collect all tests for the targets
  3218. std::map<std::string, cmXCodeScheme::TestObjects> testables;
  3219. for (const auto& obj : this->XCodeObjects) {
  3220. if (obj->GetType() != cmXCodeObject::OBJECT ||
  3221. obj->GetIsA() != cmXCodeObject::PBXNativeTarget) {
  3222. continue;
  3223. }
  3224. if (!obj->GetTarget()->IsXCTestOnApple()) {
  3225. continue;
  3226. }
  3227. cmProp testee = obj->GetTarget()->GetProperty("XCTEST_TESTEE");
  3228. if (!testee) {
  3229. continue;
  3230. }
  3231. testables[*testee].push_back(obj.get());
  3232. }
  3233. // generate scheme
  3234. bool ret = false;
  3235. // Since the lowest available Xcode version for testing was 6.4,
  3236. // I'm setting this as a limit then
  3237. if (this->XcodeVersion >= 64) {
  3238. for (const auto& obj : this->XCodeObjects) {
  3239. if (obj->GetType() == cmXCodeObject::OBJECT &&
  3240. (obj->GetIsA() == cmXCodeObject::PBXNativeTarget ||
  3241. obj->GetIsA() == cmXCodeObject::PBXAggregateTarget) &&
  3242. (root->GetMakefile()->GetCMakeInstance()->GetIsInTryCompile() ||
  3243. obj->GetTarget()->GetPropertyAsBool("XCODE_GENERATE_SCHEME"))) {
  3244. const std::string& targetName = obj->GetTarget()->GetName();
  3245. cmXCodeScheme schm(root, obj.get(), testables[targetName],
  3246. this->CurrentConfigurationTypes,
  3247. this->XcodeVersion);
  3248. schm.WriteXCodeSharedScheme(xcProjDir,
  3249. this->RelativeToSource(xcProjDir));
  3250. ret = true;
  3251. }
  3252. }
  3253. }
  3254. return ret;
  3255. }
  3256. void cmGlobalXCodeGenerator::OutputXCodeWorkspaceSettings(
  3257. const std::string& xcProjDir, bool hasGeneratedSchemes)
  3258. {
  3259. std::string xcodeSharedDataDir =
  3260. cmStrCat(xcProjDir, "/project.xcworkspace/xcshareddata");
  3261. cmSystemTools::MakeDirectory(xcodeSharedDataDir);
  3262. std::string workspaceSettingsFile =
  3263. cmStrCat(xcodeSharedDataDir, "/WorkspaceSettings.xcsettings");
  3264. cmGeneratedFileStream fout(workspaceSettingsFile);
  3265. fout.SetCopyIfDifferent(true);
  3266. if (!fout) {
  3267. return;
  3268. }
  3269. cmXMLWriter xout(fout);
  3270. xout.StartDocument();
  3271. xout.Doctype("plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\""
  3272. "\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"");
  3273. xout.StartElement("plist");
  3274. xout.Attribute("version", "1.0");
  3275. xout.StartElement("dict");
  3276. if (this->XcodeVersion >= 100) {
  3277. xout.Element("key", "BuildSystemType");
  3278. xout.Element("string", "Original");
  3279. }
  3280. if (hasGeneratedSchemes) {
  3281. xout.Element("key",
  3282. "IDEWorkspaceSharedSettings_AutocreateContextsIfNeeded");
  3283. xout.Element("false");
  3284. }
  3285. xout.EndElement(); // dict
  3286. xout.EndElement(); // plist
  3287. xout.EndDocument();
  3288. }
  3289. void cmGlobalXCodeGenerator::WriteXCodePBXProj(std::ostream& fout,
  3290. cmLocalGenerator*,
  3291. std::vector<cmLocalGenerator*>&)
  3292. {
  3293. SortXCodeObjects();
  3294. fout << "// !$*UTF8*$!\n";
  3295. fout << "{\n";
  3296. cmXCodeObject::Indent(1, fout);
  3297. fout << "archiveVersion = 1;\n";
  3298. cmXCodeObject::Indent(1, fout);
  3299. fout << "classes = {\n";
  3300. cmXCodeObject::Indent(1, fout);
  3301. fout << "};\n";
  3302. cmXCodeObject::Indent(1, fout);
  3303. fout << "objectVersion = 46;\n";
  3304. cmXCode21Object::PrintList(this->XCodeObjects, fout);
  3305. cmXCodeObject::Indent(1, fout);
  3306. fout << "rootObject = " << this->RootObject->GetId()
  3307. << " /* Project object */;\n";
  3308. fout << "}\n";
  3309. }
  3310. const char* cmGlobalXCodeGenerator::GetCMakeCFGIntDir() const
  3311. {
  3312. return "$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)";
  3313. }
  3314. std::string cmGlobalXCodeGenerator::ExpandCFGIntDir(
  3315. const std::string& str, const std::string& config) const
  3316. {
  3317. std::string replace1 = "$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)";
  3318. std::string replace2 = "$(CONFIGURATION)";
  3319. std::string tmp = str;
  3320. for (std::string::size_type i = tmp.find(replace1); i != std::string::npos;
  3321. i = tmp.find(replace1, i)) {
  3322. tmp.replace(i, replace1.size(), config);
  3323. i += config.size();
  3324. }
  3325. for (std::string::size_type i = tmp.find(replace2); i != std::string::npos;
  3326. i = tmp.find(replace2, i)) {
  3327. tmp.replace(i, replace2.size(), config);
  3328. i += config.size();
  3329. }
  3330. return tmp;
  3331. }
  3332. void cmGlobalXCodeGenerator::GetDocumentation(cmDocumentationEntry& entry)
  3333. {
  3334. entry.Name = cmGlobalXCodeGenerator::GetActualName();
  3335. entry.Brief = "Generate Xcode project files.";
  3336. }
  3337. std::string cmGlobalXCodeGenerator::ConvertToRelativeForMake(
  3338. std::string const& p)
  3339. {
  3340. return cmSystemTools::ConvertToOutputPath(p);
  3341. }
  3342. std::string cmGlobalXCodeGenerator::RelativeToSource(const std::string& p)
  3343. {
  3344. // We force conversion because Xcode breakpoints do not work unless
  3345. // they are in a file named relative to the source tree.
  3346. return cmSystemTools::ForceToRelativePath(
  3347. cmSystemTools::JoinPath(this->ProjectSourceDirectoryComponents), p);
  3348. }
  3349. std::string cmGlobalXCodeGenerator::RelativeToBinary(const std::string& p)
  3350. {
  3351. return this->CurrentLocalGenerator->MaybeConvertToRelativePath(
  3352. cmSystemTools::JoinPath(this->ProjectOutputDirectoryComponents), p);
  3353. }
  3354. std::string cmGlobalXCodeGenerator::XCodeEscapePath(const std::string& p)
  3355. {
  3356. if (p.find_first_of(" []") != std::string::npos) {
  3357. std::string t = cmStrCat('"', p, '"');
  3358. return t;
  3359. }
  3360. return p;
  3361. }
  3362. void cmGlobalXCodeGenerator::AppendDirectoryForConfig(
  3363. const std::string& prefix, const std::string& config,
  3364. const std::string& suffix, std::string& dir)
  3365. {
  3366. if (!config.empty()) {
  3367. dir += prefix;
  3368. dir += config;
  3369. dir += suffix;
  3370. }
  3371. }
  3372. std::string cmGlobalXCodeGenerator::LookupFlags(
  3373. const std::string& varNamePrefix, const std::string& varNameLang,
  3374. const std::string& varNameSuffix, const std::string& default_flags)
  3375. {
  3376. if (!varNameLang.empty()) {
  3377. std::string varName = cmStrCat(varNamePrefix, varNameLang, varNameSuffix);
  3378. if (const char* varValue = this->CurrentMakefile->GetDefinition(varName)) {
  3379. if (*varValue) {
  3380. return varValue;
  3381. }
  3382. }
  3383. }
  3384. return default_flags;
  3385. }
  3386. void cmGlobalXCodeGenerator::AppendDefines(BuildObjectListOrString& defs,
  3387. const char* defines_list,
  3388. bool dflag)
  3389. {
  3390. // Skip this if there are no definitions.
  3391. if (!defines_list) {
  3392. return;
  3393. }
  3394. // Expand the list of definitions.
  3395. std::vector<std::string> defines = cmExpandedList(defines_list);
  3396. // Store the definitions in the string.
  3397. this->AppendDefines(defs, defines, dflag);
  3398. }
  3399. void cmGlobalXCodeGenerator::AppendDefines(
  3400. BuildObjectListOrString& defs, std::vector<std::string> const& defines,
  3401. bool dflag)
  3402. {
  3403. // GCC_PREPROCESSOR_DEFINITIONS is a space-separated list of definitions.
  3404. std::string def;
  3405. for (auto const& define : defines) {
  3406. // Start with -D if requested.
  3407. def = cmStrCat(dflag ? "-D" : "", define);
  3408. // Append the flag with needed escapes.
  3409. std::string tmp;
  3410. this->AppendFlag(tmp, def);
  3411. defs.Add(tmp);
  3412. }
  3413. }
  3414. void cmGlobalXCodeGenerator::AppendFlag(std::string& flags,
  3415. std::string const& flag) const
  3416. {
  3417. // Short-circuit for an empty flag.
  3418. if (flag.empty()) {
  3419. return;
  3420. }
  3421. // Separate from previous flags.
  3422. if (!flags.empty()) {
  3423. flags += " ";
  3424. }
  3425. // Check if the flag needs quoting.
  3426. bool quoteFlag =
  3427. flag.find_first_of("`~!@#$%^&*()+={}[]|:;\"'<>,.? ") != std::string::npos;
  3428. // We escape a flag as follows:
  3429. // - Place each flag in single quotes ''
  3430. // - Escape a single quote as \'
  3431. // - Escape a backslash as \\ since it itself is an escape
  3432. // Note that in the code below we need one more level of escapes for
  3433. // C string syntax in this source file.
  3434. //
  3435. // The final level of escaping is done when the string is stored
  3436. // into the project file by cmXCodeObject::PrintString.
  3437. if (quoteFlag) {
  3438. // Open single quote.
  3439. flags += "'";
  3440. }
  3441. // Flag value with escaped quotes and backslashes.
  3442. for (auto c : flag) {
  3443. if (c == '\'') {
  3444. flags += "'\\''";
  3445. } else if (c == '\\') {
  3446. flags += "\\\\";
  3447. } else {
  3448. flags += c;
  3449. }
  3450. }
  3451. if (quoteFlag) {
  3452. // Close single quote.
  3453. flags += "'";
  3454. }
  3455. }
  3456. std::string cmGlobalXCodeGenerator::ComputeInfoPListLocation(
  3457. cmGeneratorTarget* target)
  3458. {
  3459. std::string plist =
  3460. cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(),
  3461. "/CMakeFiles/", target->GetName(), ".dir/Info.plist");
  3462. return plist;
  3463. }
  3464. // Return true if the generated build tree may contain multiple builds.
  3465. // i.e. "Can I build Debug and Release in the same tree?"
  3466. bool cmGlobalXCodeGenerator::IsMultiConfig() const
  3467. {
  3468. // Newer Xcode versions are multi config:
  3469. return true;
  3470. }
  3471. bool cmGlobalXCodeGenerator::HasKnownObjectFileLocation(
  3472. std::string* reason) const
  3473. {
  3474. if (this->ObjectDirArch.find('$') != std::string::npos) {
  3475. if (reason != nullptr) {
  3476. *reason = " under Xcode with multiple architectures";
  3477. }
  3478. return false;
  3479. }
  3480. return true;
  3481. }
  3482. bool cmGlobalXCodeGenerator::UseEffectivePlatformName(cmMakefile* mf) const
  3483. {
  3484. cmProp epnValue = this->GetCMakeInstance()->GetState()->GetGlobalProperty(
  3485. "XCODE_EMIT_EFFECTIVE_PLATFORM_NAME");
  3486. if (!epnValue) {
  3487. return mf->PlatformIsAppleEmbedded();
  3488. }
  3489. return cmIsOn(*epnValue);
  3490. }
  3491. bool cmGlobalXCodeGenerator::ShouldStripResourcePath(cmMakefile*) const
  3492. {
  3493. // Xcode determines Resource location itself
  3494. return true;
  3495. }
  3496. void cmGlobalXCodeGenerator::ComputeTargetObjectDirectory(
  3497. cmGeneratorTarget* gt) const
  3498. {
  3499. std::string configName = this->GetCMakeCFGIntDir();
  3500. std::string dir =
  3501. cmStrCat(this->GetObjectsDirectory("$(PROJECT_NAME)", configName, gt,
  3502. "$(OBJECT_FILE_DIR_normal:base)/"),
  3503. this->ObjectDirArch, '/');
  3504. gt->ObjectDirectory = dir;
  3505. }
  3506. std::string cmGlobalXCodeGenerator::GetDeploymentPlatform(const cmMakefile* mf)
  3507. {
  3508. switch (mf->GetAppleSDKType()) {
  3509. case cmMakefile::AppleSDK::AppleTVOS:
  3510. case cmMakefile::AppleSDK::AppleTVSimulator:
  3511. return "TVOS_DEPLOYMENT_TARGET";
  3512. case cmMakefile::AppleSDK::IPhoneOS:
  3513. case cmMakefile::AppleSDK::IPhoneSimulator:
  3514. return "IPHONEOS_DEPLOYMENT_TARGET";
  3515. case cmMakefile::AppleSDK::WatchOS:
  3516. case cmMakefile::AppleSDK::WatchSimulator:
  3517. return "WATCHOS_DEPLOYMENT_TARGET";
  3518. case cmMakefile::AppleSDK::MacOS:
  3519. default:
  3520. return "MACOSX_DEPLOYMENT_TARGET";
  3521. }
  3522. }