cmGlobalXCodeGenerator.cxx 126 KB

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