cmGlobalXCodeGenerator.cxx 127 KB

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