cmGlobalXCodeGenerator.cxx 131 KB

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