cmGlobalXCodeGenerator.cxx 126 KB

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