cmGlobalXCodeGenerator.cxx 126 KB

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