cmGlobalXCodeGenerator.cxx 131 KB

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