cmGlobalXCodeGenerator.cxx 131 KB

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