cmLocalGenerator.cxx 103 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015
  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 "cmLocalGenerator.h"
  4. #include "cmAlgorithms.h"
  5. #include "cmComputeLinkInformation.h"
  6. #include "cmCustomCommandGenerator.h"
  7. #include "cmGeneratedFileStream.h"
  8. #include "cmGeneratorExpression.h"
  9. #include "cmGeneratorExpressionEvaluationFile.h"
  10. #include "cmGeneratorTarget.h"
  11. #include "cmGlobalGenerator.h"
  12. #include "cmInstallGenerator.h"
  13. #include "cmInstallScriptGenerator.h"
  14. #include "cmInstallTargetGenerator.h"
  15. #include "cmLinkLineComputer.h"
  16. #include "cmMakefile.h"
  17. #include "cmRulePlaceholderExpander.h"
  18. #include "cmSourceFile.h"
  19. #include "cmSourceFileLocation.h"
  20. #include "cmState.h"
  21. #include "cmStateDirectory.h"
  22. #include "cmStateTypes.h"
  23. #include "cmSystemTools.h"
  24. #include "cmTarget.h"
  25. #include "cmTestGenerator.h"
  26. #include "cmVersion.h"
  27. #include "cmake.h"
  28. #include "cmsys/RegularExpression.hxx"
  29. #if defined(CMAKE_BUILD_WITH_CMAKE)
  30. # define CM_LG_ENCODE_OBJECT_NAMES
  31. # include "cmCryptoHash.h"
  32. #endif
  33. #include <algorithm>
  34. #include <assert.h>
  35. #include <initializer_list>
  36. #include <iterator>
  37. #include <memory>
  38. #include <sstream>
  39. #include <stdio.h>
  40. #include <string.h>
  41. #include <unordered_set>
  42. #include <utility>
  43. #include <vector>
  44. #if defined(__HAIKU__)
  45. # include <FindDirectory.h>
  46. # include <StorageDefs.h>
  47. #endif
  48. // List of variables that are replaced when
  49. // rules are expanced. These variables are
  50. // replaced in the form <var> with GetSafeDefinition(var).
  51. // ${LANG} is replaced in the variable first with all enabled
  52. // languages.
  53. static auto ruleReplaceVars = { "CMAKE_${LANG}_COMPILER",
  54. "CMAKE_SHARED_LIBRARY_CREATE_${LANG}_FLAGS",
  55. "CMAKE_SHARED_MODULE_CREATE_${LANG}_FLAGS",
  56. "CMAKE_SHARED_MODULE_${LANG}_FLAGS",
  57. "CMAKE_SHARED_LIBRARY_${LANG}_FLAGS",
  58. "CMAKE_${LANG}_LINK_FLAGS",
  59. "CMAKE_SHARED_LIBRARY_SONAME_${LANG}_FLAG",
  60. "CMAKE_${LANG}_ARCHIVE",
  61. "CMAKE_AR",
  62. "CMAKE_CURRENT_SOURCE_DIR",
  63. "CMAKE_CURRENT_BINARY_DIR",
  64. "CMAKE_RANLIB",
  65. "CMAKE_LINKER",
  66. "CMAKE_MT",
  67. "CMAKE_CUDA_HOST_COMPILER",
  68. "CMAKE_CUDA_HOST_LINK_LAUNCHER",
  69. "CMAKE_CL_SHOWINCLUDES_PREFIX" };
  70. cmLocalGenerator::cmLocalGenerator(cmGlobalGenerator* gg, cmMakefile* makefile)
  71. : cmOutputConverter(makefile->GetStateSnapshot())
  72. , StateSnapshot(makefile->GetStateSnapshot())
  73. , DirectoryBacktrace(makefile->GetBacktrace())
  74. {
  75. this->GlobalGenerator = gg;
  76. this->Makefile = makefile;
  77. this->AliasTargets = makefile->GetAliasTargets();
  78. this->EmitUniversalBinaryFlags = true;
  79. this->BackwardsCompatibility = 0;
  80. this->BackwardsCompatibilityFinal = false;
  81. this->ComputeObjectMaxPath();
  82. // Canonicalize entries of the CPATH environment variable the same
  83. // way detection of CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES does.
  84. {
  85. std::vector<std::string> cpath;
  86. cmSystemTools::GetPath(cpath, "CPATH");
  87. for (std::string& cp : cpath) {
  88. if (cmSystemTools::FileIsFullPath(cp)) {
  89. cp = cmSystemTools::CollapseFullPath(cp);
  90. this->EnvCPATH.emplace(std::move(cp));
  91. }
  92. }
  93. }
  94. std::vector<std::string> enabledLanguages =
  95. this->GetState()->GetEnabledLanguages();
  96. if (const char* sysrootCompile =
  97. this->Makefile->GetDefinition("CMAKE_SYSROOT_COMPILE")) {
  98. this->CompilerSysroot = sysrootCompile;
  99. } else {
  100. this->CompilerSysroot = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
  101. }
  102. if (const char* sysrootLink =
  103. this->Makefile->GetDefinition("CMAKE_SYSROOT_LINK")) {
  104. this->LinkerSysroot = sysrootLink;
  105. } else {
  106. this->LinkerSysroot = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
  107. }
  108. for (std::string const& lang : enabledLanguages) {
  109. if (lang == "NONE") {
  110. continue;
  111. }
  112. this->Compilers["CMAKE_" + lang + "_COMPILER"] = lang;
  113. this->VariableMappings["CMAKE_" + lang + "_COMPILER"] =
  114. this->Makefile->GetSafeDefinition("CMAKE_" + lang + "_COMPILER");
  115. std::string const& compilerArg1 = "CMAKE_" + lang + "_COMPILER_ARG1";
  116. std::string const& compilerTarget = "CMAKE_" + lang + "_COMPILER_TARGET";
  117. std::string const& compilerOptionTarget =
  118. "CMAKE_" + lang + "_COMPILE_OPTIONS_TARGET";
  119. std::string const& compilerExternalToolchain =
  120. "CMAKE_" + lang + "_COMPILER_EXTERNAL_TOOLCHAIN";
  121. std::string const& compilerOptionExternalToolchain =
  122. "CMAKE_" + lang + "_COMPILE_OPTIONS_EXTERNAL_TOOLCHAIN";
  123. std::string const& compilerOptionSysroot =
  124. "CMAKE_" + lang + "_COMPILE_OPTIONS_SYSROOT";
  125. this->VariableMappings[compilerArg1] =
  126. this->Makefile->GetSafeDefinition(compilerArg1);
  127. this->VariableMappings[compilerTarget] =
  128. this->Makefile->GetSafeDefinition(compilerTarget);
  129. this->VariableMappings[compilerOptionTarget] =
  130. this->Makefile->GetSafeDefinition(compilerOptionTarget);
  131. this->VariableMappings[compilerExternalToolchain] =
  132. this->Makefile->GetSafeDefinition(compilerExternalToolchain);
  133. this->VariableMappings[compilerOptionExternalToolchain] =
  134. this->Makefile->GetSafeDefinition(compilerOptionExternalToolchain);
  135. this->VariableMappings[compilerOptionSysroot] =
  136. this->Makefile->GetSafeDefinition(compilerOptionSysroot);
  137. for (std::string replaceVar : ruleReplaceVars) {
  138. if (replaceVar.find("${LANG}") != std::string::npos) {
  139. cmSystemTools::ReplaceString(replaceVar, "${LANG}", lang);
  140. }
  141. this->VariableMappings[replaceVar] =
  142. this->Makefile->GetSafeDefinition(replaceVar);
  143. }
  144. }
  145. }
  146. cmRulePlaceholderExpander* cmLocalGenerator::CreateRulePlaceholderExpander()
  147. const
  148. {
  149. return new cmRulePlaceholderExpander(this->Compilers, this->VariableMappings,
  150. this->CompilerSysroot,
  151. this->LinkerSysroot);
  152. }
  153. cmLocalGenerator::~cmLocalGenerator()
  154. {
  155. cmDeleteAll(this->GeneratorTargets);
  156. cmDeleteAll(this->OwnedImportedGeneratorTargets);
  157. }
  158. void cmLocalGenerator::IssueMessage(MessageType t,
  159. std::string const& text) const
  160. {
  161. this->GetCMakeInstance()->IssueMessage(t, text, this->DirectoryBacktrace);
  162. }
  163. void cmLocalGenerator::ComputeObjectMaxPath()
  164. {
  165. // Choose a maximum object file name length.
  166. #if defined(_WIN32) || defined(__CYGWIN__)
  167. this->ObjectPathMax = 250;
  168. #else
  169. this->ObjectPathMax = 1000;
  170. #endif
  171. const char* plen = this->Makefile->GetDefinition("CMAKE_OBJECT_PATH_MAX");
  172. if (plen && *plen) {
  173. unsigned int pmax;
  174. if (sscanf(plen, "%u", &pmax) == 1) {
  175. if (pmax >= 128) {
  176. this->ObjectPathMax = pmax;
  177. } else {
  178. std::ostringstream w;
  179. w << "CMAKE_OBJECT_PATH_MAX is set to " << pmax
  180. << ", which is less than the minimum of 128. "
  181. << "The value will be ignored.";
  182. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  183. }
  184. } else {
  185. std::ostringstream w;
  186. w << "CMAKE_OBJECT_PATH_MAX is set to \"" << plen
  187. << "\", which fails to parse as a positive integer. "
  188. << "The value will be ignored.";
  189. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  190. }
  191. }
  192. this->ObjectMaxPathViolations.clear();
  193. }
  194. static void MoveSystemIncludesToEnd(std::vector<std::string>& includeDirs,
  195. const std::string& config,
  196. const std::string& lang,
  197. const cmGeneratorTarget* target)
  198. {
  199. if (!target) {
  200. return;
  201. }
  202. std::stable_sort(
  203. includeDirs.begin(), includeDirs.end(),
  204. [&target, &config, &lang](std::string const& a, std::string const& b) {
  205. return !target->IsSystemIncludeDirectory(a, config, lang) &&
  206. target->IsSystemIncludeDirectory(b, config, lang);
  207. });
  208. }
  209. static void MoveSystemIncludesToEnd(std::vector<BT<std::string>>& includeDirs,
  210. const std::string& config,
  211. const std::string& lang,
  212. const cmGeneratorTarget* target)
  213. {
  214. if (!target) {
  215. return;
  216. }
  217. std::stable_sort(includeDirs.begin(), includeDirs.end(),
  218. [target, &config, &lang](BT<std::string> const& a,
  219. BT<std::string> const& b) {
  220. return !target->IsSystemIncludeDirectory(a.Value, config,
  221. lang) &&
  222. target->IsSystemIncludeDirectory(b.Value, config, lang);
  223. });
  224. }
  225. void cmLocalGenerator::TraceDependencies()
  226. {
  227. std::vector<std::string> configs;
  228. this->Makefile->GetConfigurations(configs);
  229. if (configs.empty()) {
  230. configs.emplace_back();
  231. }
  232. for (std::string const& c : configs) {
  233. this->GlobalGenerator->CreateEvaluationSourceFiles(c);
  234. }
  235. // Generate the rule files for each target.
  236. const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
  237. for (cmGeneratorTarget* target : targets) {
  238. if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  239. continue;
  240. }
  241. target->TraceDependencies();
  242. }
  243. }
  244. void cmLocalGenerator::GenerateTestFiles()
  245. {
  246. if (!this->Makefile->IsOn("CMAKE_TESTING_ENABLED")) {
  247. return;
  248. }
  249. // Compute the set of configurations.
  250. std::vector<std::string> configurationTypes;
  251. const std::string& config =
  252. this->Makefile->GetConfigurations(configurationTypes, false);
  253. std::string file = this->StateSnapshot.GetDirectory().GetCurrentBinary();
  254. file += "/";
  255. file += "CTestTestfile.cmake";
  256. cmGeneratedFileStream fout(file);
  257. fout.SetCopyIfDifferent(true);
  258. fout << "# CMake generated Testfile for " << std::endl
  259. << "# Source directory: "
  260. << this->StateSnapshot.GetDirectory().GetCurrentSource() << std::endl
  261. << "# Build directory: "
  262. << this->StateSnapshot.GetDirectory().GetCurrentBinary() << std::endl
  263. << "# " << std::endl
  264. << "# This file includes the relevant testing commands "
  265. << "required for " << std::endl
  266. << "# testing this directory and lists subdirectories to "
  267. << "be tested as well." << std::endl;
  268. const char* testIncludeFile =
  269. this->Makefile->GetProperty("TEST_INCLUDE_FILE");
  270. if (testIncludeFile) {
  271. fout << "include(\"" << testIncludeFile << "\")" << std::endl;
  272. }
  273. const char* testIncludeFiles =
  274. this->Makefile->GetProperty("TEST_INCLUDE_FILES");
  275. if (testIncludeFiles) {
  276. std::vector<std::string> includesList;
  277. cmSystemTools::ExpandListArgument(testIncludeFiles, includesList);
  278. for (std::string const& i : includesList) {
  279. fout << "include(\"" << i << "\")" << std::endl;
  280. }
  281. }
  282. // Ask each test generator to write its code.
  283. std::vector<cmTestGenerator*> const& testers =
  284. this->Makefile->GetTestGenerators();
  285. for (cmTestGenerator* tester : testers) {
  286. tester->Compute(this);
  287. tester->Generate(fout, config, configurationTypes);
  288. }
  289. typedef std::vector<cmStateSnapshot> vec_t;
  290. vec_t const& children = this->Makefile->GetStateSnapshot().GetChildren();
  291. std::string parentBinDir = this->GetCurrentBinaryDirectory();
  292. for (cmStateSnapshot const& i : children) {
  293. // TODO: Use add_subdirectory instead?
  294. std::string outP = i.GetDirectory().GetCurrentBinary();
  295. outP = this->MaybeConvertToRelativePath(parentBinDir, outP);
  296. outP = cmOutputConverter::EscapeForCMake(outP);
  297. fout << "subdirs(" << outP << ")" << std::endl;
  298. }
  299. // Add directory labels property
  300. const char* directoryLabels =
  301. this->Makefile->GetDefinition("CMAKE_DIRECTORY_LABELS");
  302. const char* labels = this->Makefile->GetProperty("LABELS");
  303. if (labels || directoryLabels) {
  304. fout << "set_directory_properties(PROPERTIES LABELS ";
  305. if (labels) {
  306. fout << cmOutputConverter::EscapeForCMake(labels);
  307. }
  308. if (labels && directoryLabels) {
  309. fout << ";";
  310. }
  311. if (directoryLabels) {
  312. fout << cmOutputConverter::EscapeForCMake(directoryLabels);
  313. }
  314. fout << ")" << std::endl;
  315. }
  316. }
  317. void cmLocalGenerator::CreateEvaluationFileOutputs(std::string const& config)
  318. {
  319. std::vector<cmGeneratorExpressionEvaluationFile*> ef =
  320. this->Makefile->GetEvaluationFiles();
  321. for (cmGeneratorExpressionEvaluationFile* geef : ef) {
  322. geef->CreateOutputFile(this, config);
  323. }
  324. }
  325. void cmLocalGenerator::ProcessEvaluationFiles(
  326. std::vector<std::string>& generatedFiles)
  327. {
  328. for (cmGeneratorExpressionEvaluationFile* geef :
  329. this->Makefile->GetEvaluationFiles()) {
  330. geef->Generate(this);
  331. if (cmSystemTools::GetFatalErrorOccured()) {
  332. return;
  333. }
  334. std::vector<std::string> files = geef->GetFiles();
  335. std::sort(files.begin(), files.end());
  336. std::vector<std::string> intersection;
  337. std::set_intersection(files.begin(), files.end(), generatedFiles.begin(),
  338. generatedFiles.end(),
  339. std::back_inserter(intersection));
  340. if (!intersection.empty()) {
  341. cmSystemTools::Error("Files to be generated by multiple different "
  342. "commands: " +
  343. cmWrap('"', intersection, '"', " "));
  344. return;
  345. }
  346. cmAppend(generatedFiles, files);
  347. std::inplace_merge(generatedFiles.begin(),
  348. generatedFiles.end() - files.size(),
  349. generatedFiles.end());
  350. }
  351. }
  352. void cmLocalGenerator::GenerateInstallRules()
  353. {
  354. // Compute the install prefix.
  355. const char* prefix = this->Makefile->GetDefinition("CMAKE_INSTALL_PREFIX");
  356. #if defined(_WIN32) && !defined(__CYGWIN__)
  357. std::string prefix_win32;
  358. if (!prefix) {
  359. if (!cmSystemTools::GetEnv("SystemDrive", prefix_win32)) {
  360. prefix_win32 = "C:";
  361. }
  362. const char* project_name = this->Makefile->GetDefinition("PROJECT_NAME");
  363. if (project_name && project_name[0]) {
  364. prefix_win32 += "/Program Files/";
  365. prefix_win32 += project_name;
  366. } else {
  367. prefix_win32 += "/InstalledCMakeProject";
  368. }
  369. prefix = prefix_win32.c_str();
  370. }
  371. #elif defined(__HAIKU__)
  372. char dir[B_PATH_NAME_LENGTH];
  373. if (!prefix) {
  374. if (find_directory(B_SYSTEM_DIRECTORY, -1, false, dir, sizeof(dir)) ==
  375. B_OK) {
  376. prefix = dir;
  377. } else {
  378. prefix = "/boot/system";
  379. }
  380. }
  381. #else
  382. if (!prefix) {
  383. prefix = "/usr/local";
  384. }
  385. #endif
  386. if (const char* stagingPrefix =
  387. this->Makefile->GetDefinition("CMAKE_STAGING_PREFIX")) {
  388. prefix = stagingPrefix;
  389. }
  390. // Compute the set of configurations.
  391. std::vector<std::string> configurationTypes;
  392. const std::string& config =
  393. this->Makefile->GetConfigurations(configurationTypes, false);
  394. // Choose a default install configuration.
  395. std::string default_config = config;
  396. const char* default_order[] = { "RELEASE", "MINSIZEREL", "RELWITHDEBINFO",
  397. "DEBUG", nullptr };
  398. for (const char** c = default_order; *c && default_config.empty(); ++c) {
  399. for (std::string const& configurationType : configurationTypes) {
  400. if (cmSystemTools::UpperCase(configurationType) == *c) {
  401. default_config = configurationType;
  402. }
  403. }
  404. }
  405. if (default_config.empty() && !configurationTypes.empty()) {
  406. default_config = configurationTypes[0];
  407. }
  408. // Create the install script file.
  409. std::string file = this->StateSnapshot.GetDirectory().GetCurrentBinary();
  410. std::string homedir = this->GetState()->GetBinaryDirectory();
  411. int toplevel_install = 0;
  412. if (file == homedir) {
  413. toplevel_install = 1;
  414. }
  415. file += "/cmake_install.cmake";
  416. cmGeneratedFileStream fout(file);
  417. fout.SetCopyIfDifferent(true);
  418. // Write the header.
  419. fout << "# Install script for directory: "
  420. << this->StateSnapshot.GetDirectory().GetCurrentSource() << std::endl
  421. << std::endl;
  422. fout << "# Set the install prefix" << std::endl
  423. << "if(NOT DEFINED CMAKE_INSTALL_PREFIX)" << std::endl
  424. << " set(CMAKE_INSTALL_PREFIX \"" << prefix << "\")" << std::endl
  425. << "endif()" << std::endl
  426. << R"(string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX )"
  427. << "\"${CMAKE_INSTALL_PREFIX}\")" << std::endl
  428. << std::endl;
  429. // Write support code for generating per-configuration install rules.
  430. /* clang-format off */
  431. fout <<
  432. "# Set the install configuration name.\n"
  433. "if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)\n"
  434. " if(BUILD_TYPE)\n"
  435. " string(REGEX REPLACE \"^[^A-Za-z0-9_]+\" \"\"\n"
  436. " CMAKE_INSTALL_CONFIG_NAME \"${BUILD_TYPE}\")\n"
  437. " else()\n"
  438. " set(CMAKE_INSTALL_CONFIG_NAME \"" << default_config << "\")\n"
  439. " endif()\n"
  440. " message(STATUS \"Install configuration: "
  441. "\\\"${CMAKE_INSTALL_CONFIG_NAME}\\\"\")\n"
  442. "endif()\n"
  443. "\n";
  444. /* clang-format on */
  445. // Write support code for dealing with component-specific installs.
  446. /* clang-format off */
  447. fout <<
  448. "# Set the component getting installed.\n"
  449. "if(NOT CMAKE_INSTALL_COMPONENT)\n"
  450. " if(COMPONENT)\n"
  451. " message(STATUS \"Install component: \\\"${COMPONENT}\\\"\")\n"
  452. " set(CMAKE_INSTALL_COMPONENT \"${COMPONENT}\")\n"
  453. " else()\n"
  454. " set(CMAKE_INSTALL_COMPONENT)\n"
  455. " endif()\n"
  456. "endif()\n"
  457. "\n";
  458. /* clang-format on */
  459. // Copy user-specified install options to the install code.
  460. if (const char* so_no_exe =
  461. this->Makefile->GetDefinition("CMAKE_INSTALL_SO_NO_EXE")) {
  462. /* clang-format off */
  463. fout <<
  464. "# Install shared libraries without execute permission?\n"
  465. "if(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE)\n"
  466. " set(CMAKE_INSTALL_SO_NO_EXE \"" << so_no_exe << "\")\n"
  467. "endif()\n"
  468. "\n";
  469. /* clang-format on */
  470. }
  471. // Copy cmake cross compile state to install code.
  472. if (const char* crosscompiling =
  473. this->Makefile->GetDefinition("CMAKE_CROSSCOMPILING")) {
  474. /* clang-format off */
  475. fout <<
  476. "# Is this installation the result of a crosscompile?\n"
  477. "if(NOT DEFINED CMAKE_CROSSCOMPILING)\n"
  478. " set(CMAKE_CROSSCOMPILING \"" << crosscompiling << "\")\n"
  479. "endif()\n"
  480. "\n";
  481. /* clang-format on */
  482. }
  483. // Write default directory permissions.
  484. if (const char* defaultDirPermissions = this->Makefile->GetDefinition(
  485. "CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS")) {
  486. /* clang-format off */
  487. fout <<
  488. "# Set default install directory permissions.\n"
  489. "if(NOT DEFINED CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS)\n"
  490. " set(CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS \""
  491. << defaultDirPermissions << "\")\n"
  492. "endif()\n"
  493. "\n";
  494. /* clang-format on */
  495. }
  496. // Ask each install generator to write its code.
  497. cmPolicies::PolicyStatus status = this->GetPolicyStatus(cmPolicies::CMP0082);
  498. std::vector<cmInstallGenerator*> const& installers =
  499. this->Makefile->GetInstallGenerators();
  500. bool haveSubdirectoryInstall = false;
  501. bool haveInstallAfterSubdirectory = false;
  502. if (status == cmPolicies::WARN) {
  503. for (cmInstallGenerator* installer : installers) {
  504. installer->CheckCMP0082(haveSubdirectoryInstall,
  505. haveInstallAfterSubdirectory);
  506. installer->Generate(fout, config, configurationTypes);
  507. }
  508. } else {
  509. for (cmInstallGenerator* installer : installers) {
  510. installer->Generate(fout, config, configurationTypes);
  511. }
  512. }
  513. // Write rules from old-style specification stored in targets.
  514. this->GenerateTargetInstallRules(fout, config, configurationTypes);
  515. // Include install scripts from subdirectories.
  516. switch (status) {
  517. case cmPolicies::WARN:
  518. if (haveInstallAfterSubdirectory &&
  519. this->Makefile->PolicyOptionalWarningEnabled(
  520. "CMAKE_POLICY_WARNING_CMP0082")) {
  521. std::ostringstream e;
  522. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0082) << "\n";
  523. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  524. }
  525. CM_FALLTHROUGH;
  526. case cmPolicies::OLD: {
  527. std::vector<cmStateSnapshot> children =
  528. this->Makefile->GetStateSnapshot().GetChildren();
  529. if (!children.empty()) {
  530. fout << "if(NOT CMAKE_INSTALL_LOCAL_ONLY)\n";
  531. fout << " # Include the install script for each subdirectory.\n";
  532. for (cmStateSnapshot const& c : children) {
  533. if (!c.GetDirectory().GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
  534. std::string odir = c.GetDirectory().GetCurrentBinary();
  535. cmSystemTools::ConvertToUnixSlashes(odir);
  536. fout << " include(\"" << odir << "/cmake_install.cmake\")"
  537. << std::endl;
  538. }
  539. }
  540. fout << "\n";
  541. fout << "endif()\n\n";
  542. }
  543. } break;
  544. case cmPolicies::REQUIRED_IF_USED:
  545. case cmPolicies::REQUIRED_ALWAYS:
  546. case cmPolicies::NEW:
  547. // NEW behavior is handled in
  548. // cmInstallSubdirectoryGenerator::GenerateScript()
  549. break;
  550. }
  551. // Record the install manifest.
  552. if (toplevel_install) {
  553. /* clang-format off */
  554. fout <<
  555. "if(CMAKE_INSTALL_COMPONENT)\n"
  556. " set(CMAKE_INSTALL_MANIFEST \"install_manifest_"
  557. "${CMAKE_INSTALL_COMPONENT}.txt\")\n"
  558. "else()\n"
  559. " set(CMAKE_INSTALL_MANIFEST \"install_manifest.txt\")\n"
  560. "endif()\n"
  561. "\n"
  562. "string(REPLACE \";\" \"\\n\" CMAKE_INSTALL_MANIFEST_CONTENT\n"
  563. " \"${CMAKE_INSTALL_MANIFEST_FILES}\")\n"
  564. "file(WRITE \"" << homedir << "/${CMAKE_INSTALL_MANIFEST}\"\n"
  565. " \"${CMAKE_INSTALL_MANIFEST_CONTENT}\")\n";
  566. /* clang-format on */
  567. }
  568. }
  569. void cmLocalGenerator::AddGeneratorTarget(cmGeneratorTarget* gt)
  570. {
  571. this->GeneratorTargets.push_back(gt);
  572. this->GeneratorTargetSearchIndex.emplace(gt->GetName(), gt);
  573. this->GlobalGenerator->IndexGeneratorTarget(gt);
  574. }
  575. void cmLocalGenerator::AddImportedGeneratorTarget(cmGeneratorTarget* gt)
  576. {
  577. this->ImportedGeneratorTargets.emplace(gt->GetName(), gt);
  578. this->GlobalGenerator->IndexGeneratorTarget(gt);
  579. }
  580. void cmLocalGenerator::AddOwnedImportedGeneratorTarget(cmGeneratorTarget* gt)
  581. {
  582. this->OwnedImportedGeneratorTargets.push_back(gt);
  583. }
  584. cmGeneratorTarget* cmLocalGenerator::FindLocalNonAliasGeneratorTarget(
  585. const std::string& name) const
  586. {
  587. GeneratorTargetMap::const_iterator ti =
  588. this->GeneratorTargetSearchIndex.find(name);
  589. if (ti != this->GeneratorTargetSearchIndex.end()) {
  590. return ti->second;
  591. }
  592. return nullptr;
  593. }
  594. void cmLocalGenerator::ComputeTargetManifest()
  595. {
  596. // Collect the set of configuration types.
  597. std::vector<std::string> configNames;
  598. this->Makefile->GetConfigurations(configNames);
  599. if (configNames.empty()) {
  600. configNames.emplace_back();
  601. }
  602. // Add our targets to the manifest for each configuration.
  603. const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
  604. for (cmGeneratorTarget* target : targets) {
  605. if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  606. continue;
  607. }
  608. for (std::string const& c : configNames) {
  609. target->ComputeTargetManifest(c);
  610. }
  611. }
  612. }
  613. bool cmLocalGenerator::ComputeTargetCompileFeatures()
  614. {
  615. // Collect the set of configuration types.
  616. std::vector<std::string> configNames;
  617. this->Makefile->GetConfigurations(configNames);
  618. if (configNames.empty()) {
  619. configNames.emplace_back();
  620. }
  621. // Process compile features of all targets.
  622. const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
  623. for (cmGeneratorTarget* target : targets) {
  624. for (std::string const& c : configNames) {
  625. if (!target->ComputeCompileFeatures(c)) {
  626. return false;
  627. }
  628. }
  629. }
  630. return true;
  631. }
  632. bool cmLocalGenerator::IsRootMakefile() const
  633. {
  634. return !this->StateSnapshot.GetBuildsystemDirectoryParent().IsValid();
  635. }
  636. cmState* cmLocalGenerator::GetState() const
  637. {
  638. return this->GlobalGenerator->GetCMakeInstance()->GetState();
  639. }
  640. cmStateSnapshot cmLocalGenerator::GetStateSnapshot() const
  641. {
  642. return this->Makefile->GetStateSnapshot();
  643. }
  644. const char* cmLocalGenerator::GetRuleLauncher(cmGeneratorTarget* target,
  645. const std::string& prop)
  646. {
  647. if (target) {
  648. return target->GetProperty(prop);
  649. }
  650. return this->Makefile->GetProperty(prop);
  651. }
  652. std::string cmLocalGenerator::ConvertToIncludeReference(
  653. std::string const& path, OutputFormat format, bool forceFullPaths)
  654. {
  655. static_cast<void>(forceFullPaths);
  656. return this->ConvertToOutputForExisting(path, format);
  657. }
  658. std::string cmLocalGenerator::GetIncludeFlags(
  659. const std::vector<std::string>& includeDirs, cmGeneratorTarget* target,
  660. const std::string& lang, bool forceFullPaths, bool forResponseFile,
  661. const std::string& config)
  662. {
  663. if (lang.empty()) {
  664. return "";
  665. }
  666. std::vector<std::string> includes = includeDirs;
  667. MoveSystemIncludesToEnd(includes, config, lang, target);
  668. OutputFormat shellFormat = forResponseFile ? RESPONSE : SHELL;
  669. std::ostringstream includeFlags;
  670. std::string flagVar = "CMAKE_INCLUDE_FLAG_";
  671. flagVar += lang;
  672. std::string const& includeFlag = this->Makefile->GetSafeDefinition(flagVar);
  673. flagVar = "CMAKE_INCLUDE_FLAG_SEP_";
  674. flagVar += lang;
  675. const char* sep = this->Makefile->GetDefinition(flagVar);
  676. bool quotePaths = false;
  677. if (this->Makefile->GetDefinition("CMAKE_QUOTE_INCLUDE_PATHS")) {
  678. quotePaths = true;
  679. }
  680. bool repeatFlag = true;
  681. // should the include flag be repeated like ie. -IA -IB
  682. if (!sep) {
  683. sep = " ";
  684. } else {
  685. // if there is a separator then the flag is not repeated but is only
  686. // given once i.e. -classpath a:b:c
  687. repeatFlag = false;
  688. }
  689. // Support special system include flag if it is available and the
  690. // normal flag is repeated for each directory.
  691. std::string sysFlagVar = "CMAKE_INCLUDE_SYSTEM_FLAG_";
  692. sysFlagVar += lang;
  693. const char* sysIncludeFlag = nullptr;
  694. if (repeatFlag) {
  695. sysIncludeFlag = this->Makefile->GetDefinition(sysFlagVar);
  696. }
  697. std::string fwSearchFlagVar = "CMAKE_";
  698. fwSearchFlagVar += lang;
  699. fwSearchFlagVar += "_FRAMEWORK_SEARCH_FLAG";
  700. const char* fwSearchFlag = this->Makefile->GetDefinition(fwSearchFlagVar);
  701. std::string sysFwSearchFlagVar = "CMAKE_";
  702. sysFwSearchFlagVar += lang;
  703. sysFwSearchFlagVar += "_SYSTEM_FRAMEWORK_SEARCH_FLAG";
  704. const char* sysFwSearchFlag =
  705. this->Makefile->GetDefinition(sysFwSearchFlagVar);
  706. bool flagUsed = false;
  707. std::set<std::string> emitted;
  708. #ifdef __APPLE__
  709. emitted.insert("/System/Library/Frameworks");
  710. #endif
  711. for (std::string const& i : includes) {
  712. if (fwSearchFlag && *fwSearchFlag && this->Makefile->IsOn("APPLE") &&
  713. cmSystemTools::IsPathToFramework(i)) {
  714. std::string frameworkDir = i;
  715. frameworkDir += "/../";
  716. frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
  717. if (emitted.insert(frameworkDir).second) {
  718. if (sysFwSearchFlag && target &&
  719. target->IsSystemIncludeDirectory(i, config, lang)) {
  720. includeFlags << sysFwSearchFlag;
  721. } else {
  722. includeFlags << fwSearchFlag;
  723. }
  724. includeFlags << this->ConvertToOutputFormat(frameworkDir, shellFormat)
  725. << " ";
  726. }
  727. continue;
  728. }
  729. if (!flagUsed || repeatFlag) {
  730. if (sysIncludeFlag && target &&
  731. target->IsSystemIncludeDirectory(i, config, lang)) {
  732. includeFlags << sysIncludeFlag;
  733. } else {
  734. includeFlags << includeFlag;
  735. }
  736. flagUsed = true;
  737. }
  738. std::string includePath =
  739. this->ConvertToIncludeReference(i, shellFormat, forceFullPaths);
  740. if (quotePaths && !includePath.empty() && includePath.front() != '\"') {
  741. includeFlags << "\"";
  742. }
  743. includeFlags << includePath;
  744. if (quotePaths && !includePath.empty() && includePath.front() != '\"') {
  745. includeFlags << "\"";
  746. }
  747. includeFlags << sep;
  748. }
  749. std::string flags = includeFlags.str();
  750. // remove trailing separators
  751. if ((sep[0] != ' ') && !flags.empty() && flags.back() == sep[0]) {
  752. flags.back() = ' ';
  753. }
  754. return flags;
  755. }
  756. void cmLocalGenerator::AddCompileOptions(std::string& flags,
  757. cmGeneratorTarget* target,
  758. const std::string& lang,
  759. const std::string& config)
  760. {
  761. std::string langFlagRegexVar = std::string("CMAKE_") + lang + "_FLAG_REGEX";
  762. if (const char* langFlagRegexStr =
  763. this->Makefile->GetDefinition(langFlagRegexVar)) {
  764. // Filter flags acceptable to this language.
  765. std::vector<std::string> opts;
  766. if (const char* targetFlags = target->GetProperty("COMPILE_FLAGS")) {
  767. cmSystemTools::ParseWindowsCommandLine(targetFlags, opts);
  768. }
  769. target->GetCompileOptions(opts, config, lang);
  770. // (Re-)Escape these flags. COMPILE_FLAGS were already parsed
  771. // as a command line above, and COMPILE_OPTIONS are escaped.
  772. this->AppendCompileOptions(flags, opts, langFlagRegexStr);
  773. } else {
  774. // Use all flags.
  775. if (const char* targetFlags = target->GetProperty("COMPILE_FLAGS")) {
  776. // COMPILE_FLAGS are not escaped for historical reasons.
  777. this->AppendFlags(flags, targetFlags);
  778. }
  779. std::vector<std::string> opts;
  780. target->GetCompileOptions(opts, config, lang);
  781. // COMPILE_OPTIONS are escaped.
  782. this->AppendCompileOptions(flags, opts);
  783. }
  784. for (auto const& it : target->GetMaxLanguageStandards()) {
  785. const char* standard = target->GetProperty(it.first + "_STANDARD");
  786. if (!standard) {
  787. continue;
  788. }
  789. if (this->Makefile->IsLaterStandard(it.first, standard, it.second)) {
  790. std::ostringstream e;
  791. e << "The COMPILE_FEATURES property of target \"" << target->GetName()
  792. << "\" was evaluated when computing the link "
  793. "implementation, and the \""
  794. << it.first << "_STANDARD\" was \"" << it.second
  795. << "\" for that computation. Computing the "
  796. "COMPILE_FEATURES based on the link implementation resulted in a "
  797. "higher \""
  798. << it.first << "_STANDARD\" \"" << standard
  799. << "\". "
  800. "This is not permitted. The COMPILE_FEATURES may not both depend "
  801. "on "
  802. "and be depended on by the link implementation."
  803. << std::endl;
  804. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  805. return;
  806. }
  807. }
  808. this->AddCompilerRequirementFlag(flags, target, lang);
  809. // Add compile flag for the MSVC compiler only.
  810. cmMakefile* mf = this->GetMakefile();
  811. if (const char* jmc =
  812. mf->GetDefinition("CMAKE_" + lang + "_COMPILE_OPTIONS_JMC")) {
  813. // Handle Just My Code debugging flags, /JMC.
  814. // If the target is a Managed C++ one, /JMC is not compatible.
  815. if (target->GetManagedType(config) !=
  816. cmGeneratorTarget::ManagedType::Managed) {
  817. // add /JMC flags if target property VS_JUST_MY_CODE_DEBUGGING is set
  818. // to ON
  819. if (char const* jmcExprGen =
  820. target->GetProperty("VS_JUST_MY_CODE_DEBUGGING")) {
  821. cmGeneratorExpression ge;
  822. std::unique_ptr<cmCompiledGeneratorExpression> cge =
  823. ge.Parse(jmcExprGen);
  824. std::string isJMCEnabled = cge->Evaluate(this, config);
  825. if (cmSystemTools::IsOn(isJMCEnabled)) {
  826. std::vector<std::string> optVec;
  827. cmSystemTools::ExpandListArgument(jmc, optVec);
  828. this->AppendCompileOptions(flags, optVec);
  829. }
  830. }
  831. }
  832. }
  833. }
  834. std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectoriesImplicit(
  835. cmGeneratorTarget const* target, std::string const& lang,
  836. std::string const& config, bool stripImplicitDirs,
  837. bool appendAllImplicitDirs) const
  838. {
  839. std::vector<BT<std::string>> result;
  840. // Do not repeat an include path.
  841. std::set<std::string> emitted;
  842. auto emitDir = [&result, &emitted](std::string const& dir) {
  843. if (emitted.insert(dir).second) {
  844. result.emplace_back(dir);
  845. }
  846. };
  847. auto emitBT = [&result, &emitted](BT<std::string> const& dir) {
  848. if (emitted.insert(dir.Value).second) {
  849. result.emplace_back(dir);
  850. }
  851. };
  852. // When automatic include directories are requested for a build then
  853. // include the source and binary directories at the beginning of the
  854. // include path to approximate include file behavior for an
  855. // in-source build. This does not account for the case of a source
  856. // file in a subdirectory of the current source directory but we
  857. // cannot fix this because not all native build tools support
  858. // per-source-file include paths.
  859. if (this->Makefile->IsOn("CMAKE_INCLUDE_CURRENT_DIR")) {
  860. // Current binary directory
  861. emitDir(this->StateSnapshot.GetDirectory().GetCurrentBinary());
  862. // Current source directory
  863. emitDir(this->StateSnapshot.GetDirectory().GetCurrentSource());
  864. }
  865. if (!target) {
  866. return result;
  867. }
  868. // Standard include directories to be added unconditionally at the end.
  869. // These are intended to simulate additional implicit include directories.
  870. std::vector<std::string> userStandardDirs;
  871. {
  872. std::string key = "CMAKE_";
  873. key += lang;
  874. key += "_STANDARD_INCLUDE_DIRECTORIES";
  875. std::string const value = this->Makefile->GetSafeDefinition(key);
  876. cmSystemTools::ExpandListArgument(value, userStandardDirs);
  877. for (std::string& usd : userStandardDirs) {
  878. cmSystemTools::ConvertToUnixSlashes(usd);
  879. }
  880. }
  881. // Implicit include directories
  882. std::vector<std::string> implicitDirs;
  883. std::set<std::string> implicitSet;
  884. // Include directories to be excluded as if they were implicit.
  885. std::set<std::string> implicitExclude;
  886. {
  887. // Raw list of implicit include directories
  888. // Start with "standard" directories that we unconditionally add below.
  889. std::vector<std::string> impDirVec = userStandardDirs;
  890. // Load implicit include directories for this language.
  891. // We ignore this for Fortran because:
  892. // * There are no standard library headers to avoid overriding.
  893. // * Compilers like gfortran do not search their own implicit include
  894. // directories for modules ('.mod' files).
  895. if (lang != "Fortran") {
  896. std::string key = "CMAKE_";
  897. key += lang;
  898. key += "_IMPLICIT_INCLUDE_DIRECTORIES";
  899. if (const char* value = this->Makefile->GetDefinition(key)) {
  900. size_t const impDirVecOldSize = impDirVec.size();
  901. cmSystemTools::ExpandListArgument(value, impDirVec);
  902. // FIXME: Use cmRange with 'advance()' when it supports non-const.
  903. for (size_t i = impDirVecOldSize; i < impDirVec.size(); ++i) {
  904. cmSystemTools::ConvertToUnixSlashes(impDirVec[i]);
  905. }
  906. }
  907. }
  908. // The Platform/UnixPaths module used to hard-code /usr/include for C, CXX,
  909. // and CUDA in CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES, but those
  910. // variables are now computed. On macOS the /usr/include directory is
  911. // inside the platform SDK so the computed value does not contain it
  912. // directly. In this case adding -I/usr/include can hide SDK headers so we
  913. // must still exclude it.
  914. if ((lang == "C" || lang == "CXX" || lang == "CUDA") &&
  915. std::find(impDirVec.begin(), impDirVec.end(), "/usr/include") ==
  916. impDirVec.end() &&
  917. std::find_if(impDirVec.begin(), impDirVec.end(),
  918. [](std::string const& d) {
  919. return cmHasLiteralSuffix(d, "/usr/include");
  920. }) != impDirVec.end()) {
  921. // Only exclude this hard coded path for backwards compatibility.
  922. implicitExclude.emplace("/usr/include");
  923. }
  924. for (std::string const& i : impDirVec) {
  925. if (implicitSet.insert(cmSystemTools::GetRealPath(i)).second) {
  926. implicitDirs.emplace_back(i);
  927. }
  928. }
  929. }
  930. // Checks if this is not an excluded (implicit) include directory.
  931. auto notExcluded = [this, &implicitSet, &implicitExclude,
  932. &lang](std::string const& dir) {
  933. return (
  934. // Do not exclude directories that are not in an excluded set.
  935. ((implicitSet.find(cmSystemTools::GetRealPath(dir)) ==
  936. implicitSet.end()) &&
  937. (implicitExclude.find(dir) == implicitExclude.end()))
  938. // Do not exclude entries of the CPATH environment variable even though
  939. // they are implicitly searched by the compiler. They are meant to be
  940. // user-specified directories that can be re-ordered or converted to
  941. // -isystem without breaking real compiler builtin headers.
  942. || ((lang == "C" || lang == "CXX") &&
  943. (this->EnvCPATH.find(dir) != this->EnvCPATH.end())));
  944. };
  945. // Get the target-specific include directories.
  946. std::vector<BT<std::string>> userDirs =
  947. target->GetIncludeDirectories(config, lang);
  948. // Support putting all the in-project include directories first if
  949. // it is requested by the project.
  950. if (this->Makefile->IsOn("CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE")) {
  951. std::string const &topSourceDir = this->GetState()->GetSourceDirectory(),
  952. &topBinaryDir = this->GetState()->GetBinaryDirectory();
  953. for (BT<std::string> const& udr : userDirs) {
  954. // Emit this directory only if it is a subdirectory of the
  955. // top-level source or binary tree.
  956. if (cmSystemTools::ComparePath(udr.Value, topSourceDir) ||
  957. cmSystemTools::ComparePath(udr.Value, topBinaryDir) ||
  958. cmSystemTools::IsSubDirectory(udr.Value, topSourceDir) ||
  959. cmSystemTools::IsSubDirectory(udr.Value, topBinaryDir)) {
  960. if (notExcluded(udr.Value)) {
  961. emitBT(udr);
  962. }
  963. }
  964. }
  965. }
  966. // Emit remaining non implicit user direcories.
  967. for (BT<std::string> const& udr : userDirs) {
  968. if (notExcluded(udr.Value)) {
  969. emitBT(udr);
  970. }
  971. }
  972. // Sort result
  973. MoveSystemIncludesToEnd(result, config, lang, target);
  974. // Append standard include directories for this language.
  975. userDirs.reserve(userDirs.size() + userStandardDirs.size());
  976. for (std::string& usd : userStandardDirs) {
  977. emitDir(usd);
  978. userDirs.emplace_back(std::move(usd));
  979. }
  980. // Append compiler implicit include directories
  981. if (!stripImplicitDirs) {
  982. // Append implicit directories that were requested by the user only
  983. for (BT<std::string> const& udr : userDirs) {
  984. if (implicitSet.find(cmSystemTools::GetRealPath(udr.Value)) !=
  985. implicitSet.end()) {
  986. emitBT(udr);
  987. }
  988. }
  989. // Append remaining implicit directories (on demand)
  990. if (appendAllImplicitDirs) {
  991. for (std::string& imd : implicitDirs) {
  992. emitDir(imd);
  993. }
  994. }
  995. }
  996. return result;
  997. }
  998. void cmLocalGenerator::GetIncludeDirectoriesImplicit(
  999. std::vector<std::string>& dirs, cmGeneratorTarget const* target,
  1000. const std::string& lang, const std::string& config, bool stripImplicitDirs,
  1001. bool appendAllImplicitDirs) const
  1002. {
  1003. std::vector<BT<std::string>> tmp = this->GetIncludeDirectoriesImplicit(
  1004. target, lang, config, stripImplicitDirs, appendAllImplicitDirs);
  1005. dirs.reserve(dirs.size() + tmp.size());
  1006. for (BT<std::string>& v : tmp) {
  1007. dirs.emplace_back(std::move(v.Value));
  1008. }
  1009. }
  1010. std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectories(
  1011. cmGeneratorTarget const* target, std::string const& lang,
  1012. std::string const& config) const
  1013. {
  1014. return this->GetIncludeDirectoriesImplicit(target, lang, config);
  1015. }
  1016. void cmLocalGenerator::GetIncludeDirectories(std::vector<std::string>& dirs,
  1017. cmGeneratorTarget const* target,
  1018. const std::string& lang,
  1019. const std::string& config) const
  1020. {
  1021. this->GetIncludeDirectoriesImplicit(dirs, target, lang, config);
  1022. }
  1023. void cmLocalGenerator::GetStaticLibraryFlags(std::string& flags,
  1024. std::string const& config,
  1025. std::string const& linkLanguage,
  1026. cmGeneratorTarget* target)
  1027. {
  1028. this->AppendFlags(
  1029. flags, this->Makefile->GetSafeDefinition("CMAKE_STATIC_LINKER_FLAGS"));
  1030. if (!config.empty()) {
  1031. std::string name = "CMAKE_STATIC_LINKER_FLAGS_" + config;
  1032. this->AppendFlags(flags, this->Makefile->GetSafeDefinition(name));
  1033. }
  1034. this->AppendFlags(flags, target->GetProperty("STATIC_LIBRARY_FLAGS"));
  1035. if (!config.empty()) {
  1036. std::string name = "STATIC_LIBRARY_FLAGS_" + config;
  1037. this->AppendFlags(flags, target->GetProperty(name));
  1038. }
  1039. std::vector<std::string> options;
  1040. target->GetStaticLibraryLinkOptions(options, config, linkLanguage);
  1041. // STATIC_LIBRARY_OPTIONS are escaped.
  1042. this->AppendCompileOptions(flags, options);
  1043. }
  1044. void cmLocalGenerator::GetTargetFlags(
  1045. cmLinkLineComputer* linkLineComputer, const std::string& config,
  1046. std::string& linkLibs, std::string& flags, std::string& linkFlags,
  1047. std::string& frameworkPath, std::string& linkPath, cmGeneratorTarget* target)
  1048. {
  1049. const std::string buildType = cmSystemTools::UpperCase(config);
  1050. cmComputeLinkInformation* pcli = target->GetLinkInformation(config);
  1051. const char* libraryLinkVariable =
  1052. "CMAKE_SHARED_LINKER_FLAGS"; // default to shared library
  1053. const std::string linkLanguage =
  1054. linkLineComputer->GetLinkerLanguage(target, buildType);
  1055. switch (target->GetType()) {
  1056. case cmStateEnums::STATIC_LIBRARY:
  1057. this->GetStaticLibraryFlags(linkFlags, buildType, linkLanguage, target);
  1058. break;
  1059. case cmStateEnums::MODULE_LIBRARY:
  1060. libraryLinkVariable = "CMAKE_MODULE_LINKER_FLAGS";
  1061. CM_FALLTHROUGH;
  1062. case cmStateEnums::SHARED_LIBRARY: {
  1063. if (linkLanguage != "Swift") {
  1064. linkFlags = this->Makefile->GetSafeDefinition(libraryLinkVariable);
  1065. linkFlags += " ";
  1066. if (!buildType.empty()) {
  1067. std::string build = libraryLinkVariable;
  1068. build += "_";
  1069. build += buildType;
  1070. linkFlags += this->Makefile->GetSafeDefinition(build);
  1071. linkFlags += " ";
  1072. }
  1073. if (this->Makefile->IsOn("WIN32") &&
  1074. !(this->Makefile->IsOn("CYGWIN") ||
  1075. this->Makefile->IsOn("MINGW"))) {
  1076. std::vector<cmSourceFile*> sources;
  1077. target->GetSourceFiles(sources, buildType);
  1078. std::string defFlag =
  1079. this->Makefile->GetSafeDefinition("CMAKE_LINK_DEF_FILE_FLAG");
  1080. for (cmSourceFile* sf : sources) {
  1081. if (sf->GetExtension() == "def") {
  1082. linkFlags += defFlag;
  1083. linkFlags += this->ConvertToOutputFormat(
  1084. cmSystemTools::CollapseFullPath(sf->GetFullPath()), SHELL);
  1085. linkFlags += " ";
  1086. }
  1087. }
  1088. }
  1089. }
  1090. const char* targetLinkFlags = target->GetProperty("LINK_FLAGS");
  1091. if (targetLinkFlags) {
  1092. linkFlags += targetLinkFlags;
  1093. linkFlags += " ";
  1094. }
  1095. if (!buildType.empty()) {
  1096. std::string configLinkFlags = "LINK_FLAGS_";
  1097. configLinkFlags += buildType;
  1098. targetLinkFlags = target->GetProperty(configLinkFlags);
  1099. if (targetLinkFlags) {
  1100. linkFlags += targetLinkFlags;
  1101. linkFlags += " ";
  1102. }
  1103. }
  1104. std::vector<std::string> opts;
  1105. target->GetLinkOptions(opts, config, linkLanguage);
  1106. // LINK_OPTIONS are escaped.
  1107. this->AppendCompileOptions(linkFlags, opts);
  1108. if (pcli) {
  1109. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1110. frameworkPath, linkPath);
  1111. }
  1112. } break;
  1113. case cmStateEnums::EXECUTABLE: {
  1114. if (linkLanguage != "Swift") {
  1115. linkFlags +=
  1116. this->Makefile->GetSafeDefinition("CMAKE_EXE_LINKER_FLAGS");
  1117. linkFlags += " ";
  1118. if (!buildType.empty()) {
  1119. std::string build = "CMAKE_EXE_LINKER_FLAGS_";
  1120. build += buildType;
  1121. linkFlags += this->Makefile->GetSafeDefinition(build);
  1122. linkFlags += " ";
  1123. }
  1124. if (linkLanguage.empty()) {
  1125. cmSystemTools::Error(
  1126. "CMake can not determine linker language for target: " +
  1127. target->GetName());
  1128. return;
  1129. }
  1130. if (target->GetPropertyAsBool("WIN32_EXECUTABLE")) {
  1131. linkFlags +=
  1132. this->Makefile->GetSafeDefinition("CMAKE_CREATE_WIN32_EXE");
  1133. linkFlags += " ";
  1134. } else {
  1135. linkFlags +=
  1136. this->Makefile->GetSafeDefinition("CMAKE_CREATE_CONSOLE_EXE");
  1137. linkFlags += " ";
  1138. }
  1139. if (target->IsExecutableWithExports()) {
  1140. std::string exportFlagVar = "CMAKE_EXE_EXPORTS_";
  1141. exportFlagVar += linkLanguage;
  1142. exportFlagVar += "_FLAG";
  1143. linkFlags += this->Makefile->GetSafeDefinition(exportFlagVar);
  1144. linkFlags += " ";
  1145. }
  1146. }
  1147. this->AddLanguageFlagsForLinking(flags, target, linkLanguage, buildType);
  1148. if (pcli) {
  1149. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1150. frameworkPath, linkPath);
  1151. }
  1152. if (cmSystemTools::IsOn(
  1153. this->Makefile->GetDefinition("BUILD_SHARED_LIBS"))) {
  1154. std::string sFlagVar = std::string("CMAKE_SHARED_BUILD_") +
  1155. linkLanguage + std::string("_FLAGS");
  1156. linkFlags += this->Makefile->GetSafeDefinition(sFlagVar);
  1157. linkFlags += " ";
  1158. }
  1159. std::string cmp0065Flags =
  1160. this->GetLinkLibsCMP0065(linkLanguage, *target);
  1161. if (!cmp0065Flags.empty()) {
  1162. linkFlags += cmp0065Flags;
  1163. linkFlags += " ";
  1164. }
  1165. const char* targetLinkFlags = target->GetProperty("LINK_FLAGS");
  1166. if (targetLinkFlags) {
  1167. linkFlags += targetLinkFlags;
  1168. linkFlags += " ";
  1169. }
  1170. if (!buildType.empty()) {
  1171. std::string configLinkFlags = "LINK_FLAGS_";
  1172. configLinkFlags += buildType;
  1173. targetLinkFlags = target->GetProperty(configLinkFlags);
  1174. if (targetLinkFlags) {
  1175. linkFlags += targetLinkFlags;
  1176. linkFlags += " ";
  1177. }
  1178. }
  1179. std::vector<std::string> opts;
  1180. target->GetLinkOptions(opts, config, linkLanguage);
  1181. // LINK_OPTIONS are escaped.
  1182. this->AppendCompileOptions(linkFlags, opts);
  1183. } break;
  1184. default:
  1185. break;
  1186. }
  1187. this->AppendPositionIndependentLinkerFlags(linkFlags, target, config,
  1188. linkLanguage);
  1189. this->AppendIPOLinkerFlags(linkFlags, target, config, linkLanguage);
  1190. }
  1191. void cmLocalGenerator::GetTargetCompileFlags(cmGeneratorTarget* target,
  1192. std::string const& config,
  1193. std::string const& lang,
  1194. std::string& flags)
  1195. {
  1196. cmMakefile* mf = this->GetMakefile();
  1197. // Add language-specific flags.
  1198. this->AddLanguageFlags(flags, target, lang, config);
  1199. if (target->IsIPOEnabled(lang, config)) {
  1200. this->AppendFeatureOptions(flags, lang, "IPO");
  1201. }
  1202. this->AddArchitectureFlags(flags, target, lang, config);
  1203. if (lang == "Fortran") {
  1204. this->AppendFlags(flags, this->GetTargetFortranFlags(target, config));
  1205. }
  1206. this->AddCMP0018Flags(flags, target, lang, config);
  1207. this->AddVisibilityPresetFlags(flags, target, lang);
  1208. this->AppendFlags(flags, mf->GetDefineFlags());
  1209. this->AppendFlags(flags, this->GetFrameworkFlags(lang, config, target));
  1210. this->AddCompileOptions(flags, target, lang, config);
  1211. }
  1212. static std::string GetFrameworkFlags(const std::string& lang,
  1213. const std::string& config,
  1214. cmGeneratorTarget* target)
  1215. {
  1216. cmLocalGenerator* lg = target->GetLocalGenerator();
  1217. cmMakefile* mf = lg->GetMakefile();
  1218. if (!mf->IsOn("APPLE")) {
  1219. return std::string();
  1220. }
  1221. std::string fwSearchFlagVar = "CMAKE_" + lang + "_FRAMEWORK_SEARCH_FLAG";
  1222. const char* fwSearchFlag = mf->GetDefinition(fwSearchFlagVar);
  1223. if (!(fwSearchFlag && *fwSearchFlag)) {
  1224. return std::string();
  1225. }
  1226. std::set<std::string> emitted;
  1227. #ifdef __APPLE__ /* don't insert this when crosscompiling e.g. to iphone */
  1228. emitted.insert("/System/Library/Frameworks");
  1229. #endif
  1230. std::vector<std::string> includes;
  1231. lg->GetIncludeDirectories(includes, target, "C", config);
  1232. // check all include directories for frameworks as this
  1233. // will already have added a -F for the framework
  1234. for (std::string const& include : includes) {
  1235. if (lg->GetGlobalGenerator()->NameResolvesToFramework(include)) {
  1236. std::string frameworkDir = include;
  1237. frameworkDir += "/../";
  1238. frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
  1239. emitted.insert(frameworkDir);
  1240. }
  1241. }
  1242. std::string flags;
  1243. if (cmComputeLinkInformation* cli = target->GetLinkInformation(config)) {
  1244. std::vector<std::string> const& frameworks = cli->GetFrameworkPaths();
  1245. for (std::string const& framework : frameworks) {
  1246. if (emitted.insert(framework).second) {
  1247. flags += fwSearchFlag;
  1248. flags +=
  1249. lg->ConvertToOutputFormat(framework, cmOutputConverter::SHELL);
  1250. flags += " ";
  1251. }
  1252. }
  1253. }
  1254. return flags;
  1255. }
  1256. std::string cmLocalGenerator::GetFrameworkFlags(std::string const& l,
  1257. std::string const& config,
  1258. cmGeneratorTarget* target)
  1259. {
  1260. return ::GetFrameworkFlags(l, config, target);
  1261. }
  1262. void cmLocalGenerator::GetTargetDefines(cmGeneratorTarget const* target,
  1263. std::string const& config,
  1264. std::string const& lang,
  1265. std::set<std::string>& defines) const
  1266. {
  1267. std::set<BT<std::string>> tmp = this->GetTargetDefines(target, config, lang);
  1268. for (BT<std::string> const& v : tmp) {
  1269. defines.emplace(v.Value);
  1270. }
  1271. }
  1272. std::set<BT<std::string>> cmLocalGenerator::GetTargetDefines(
  1273. cmGeneratorTarget const* target, std::string const& config,
  1274. std::string const& lang) const
  1275. {
  1276. std::set<BT<std::string>> defines;
  1277. // Add the export symbol definition for shared library objects.
  1278. if (const std::string* exportMacro = target->GetExportMacro()) {
  1279. this->AppendDefines(defines, *exportMacro);
  1280. }
  1281. // Add preprocessor definitions for this target and configuration.
  1282. std::vector<BT<std::string>> targetDefines =
  1283. target->GetCompileDefinitions(config, lang);
  1284. this->AppendDefines(defines, targetDefines);
  1285. return defines;
  1286. }
  1287. std::string cmLocalGenerator::GetTargetFortranFlags(
  1288. cmGeneratorTarget const* /*unused*/, std::string const& /*unused*/)
  1289. {
  1290. // Implemented by specific generators that override this.
  1291. return std::string();
  1292. }
  1293. /**
  1294. * Output the linking rules on a command line. For executables,
  1295. * targetLibrary should be a NULL pointer. For libraries, it should point
  1296. * to the name of the library. This will not link a library against itself.
  1297. */
  1298. void cmLocalGenerator::OutputLinkLibraries(
  1299. cmComputeLinkInformation* pcli, cmLinkLineComputer* linkLineComputer,
  1300. std::string& linkLibraries, std::string& frameworkPath,
  1301. std::string& linkPath)
  1302. {
  1303. cmComputeLinkInformation& cli = *pcli;
  1304. std::string linkLanguage = cli.GetLinkLanguage();
  1305. std::string libPathFlag;
  1306. if (const char* value = this->Makefile->GetDefinition(
  1307. "CMAKE_" + cli.GetLinkLanguage() + "_LIBRARY_PATH_FLAG")) {
  1308. libPathFlag = value;
  1309. } else {
  1310. libPathFlag =
  1311. this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_FLAG");
  1312. }
  1313. std::string libPathTerminator;
  1314. if (const char* value = this->Makefile->GetDefinition(
  1315. "CMAKE_" + cli.GetLinkLanguage() + "_LIBRARY_PATH_TERMINATOR")) {
  1316. libPathTerminator = value;
  1317. } else {
  1318. libPathTerminator =
  1319. this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_TERMINATOR");
  1320. }
  1321. // Add standard libraries for this language.
  1322. std::string standardLibsVar = "CMAKE_";
  1323. standardLibsVar += cli.GetLinkLanguage();
  1324. standardLibsVar += "_STANDARD_LIBRARIES";
  1325. std::string stdLibString;
  1326. if (const char* stdLibs = this->Makefile->GetDefinition(standardLibsVar)) {
  1327. stdLibString = stdLibs;
  1328. }
  1329. // Append the framework search path flags.
  1330. std::string fwSearchFlagVar = "CMAKE_";
  1331. fwSearchFlagVar += linkLanguage;
  1332. fwSearchFlagVar += "_FRAMEWORK_SEARCH_FLAG";
  1333. std::string fwSearchFlag =
  1334. this->Makefile->GetSafeDefinition(fwSearchFlagVar);
  1335. frameworkPath = linkLineComputer->ComputeFrameworkPath(cli, fwSearchFlag);
  1336. linkPath =
  1337. linkLineComputer->ComputeLinkPath(cli, libPathFlag, libPathTerminator);
  1338. linkLibraries = linkLineComputer->ComputeLinkLibraries(cli, stdLibString);
  1339. }
  1340. std::string cmLocalGenerator::GetLinkLibsCMP0065(
  1341. std::string const& linkLanguage, cmGeneratorTarget& tgt) const
  1342. {
  1343. std::string linkFlags;
  1344. // Flags to link an executable to shared libraries.
  1345. if (tgt.GetType() == cmStateEnums::EXECUTABLE &&
  1346. this->StateSnapshot.GetState()->GetGlobalPropertyAsBool(
  1347. "TARGET_SUPPORTS_SHARED_LIBS")) {
  1348. bool add_shlib_flags = false;
  1349. switch (tgt.GetPolicyStatusCMP0065()) {
  1350. case cmPolicies::WARN:
  1351. if (!tgt.GetPropertyAsBool("ENABLE_EXPORTS") &&
  1352. this->Makefile->PolicyOptionalWarningEnabled(
  1353. "CMAKE_POLICY_WARNING_CMP0065")) {
  1354. std::ostringstream w;
  1355. /* clang-format off */
  1356. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0065) << "\n"
  1357. "For compatibility with older versions of CMake, "
  1358. "additional flags may be added to export symbols on all "
  1359. "executables regardless of their ENABLE_EXPORTS property.";
  1360. /* clang-format on */
  1361. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  1362. }
  1363. CM_FALLTHROUGH;
  1364. case cmPolicies::OLD:
  1365. // OLD behavior is to always add the flags
  1366. add_shlib_flags = true;
  1367. break;
  1368. case cmPolicies::REQUIRED_IF_USED:
  1369. case cmPolicies::REQUIRED_ALWAYS:
  1370. this->IssueMessage(
  1371. MessageType::FATAL_ERROR,
  1372. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0065));
  1373. CM_FALLTHROUGH;
  1374. case cmPolicies::NEW:
  1375. // NEW behavior is to only add the flags if ENABLE_EXPORTS is on
  1376. add_shlib_flags = tgt.GetPropertyAsBool("ENABLE_EXPORTS");
  1377. break;
  1378. }
  1379. if (add_shlib_flags) {
  1380. std::string linkFlagsVar = "CMAKE_SHARED_LIBRARY_LINK_";
  1381. linkFlagsVar += linkLanguage;
  1382. linkFlagsVar += "_FLAGS";
  1383. linkFlags = this->Makefile->GetSafeDefinition(linkFlagsVar);
  1384. }
  1385. }
  1386. return linkFlags;
  1387. }
  1388. void cmLocalGenerator::AddArchitectureFlags(std::string& flags,
  1389. cmGeneratorTarget const* target,
  1390. const std::string& lang,
  1391. const std::string& config)
  1392. {
  1393. // Only add macOS specific flags on Darwin platforms (macOS and iOS):
  1394. if (this->Makefile->IsOn("APPLE") && this->EmitUniversalBinaryFlags) {
  1395. std::vector<std::string> archs;
  1396. target->GetAppleArchs(config, archs);
  1397. const char* sysroot = this->Makefile->GetDefinition("CMAKE_OSX_SYSROOT");
  1398. if (sysroot && sysroot[0] == '/' && !sysroot[1]) {
  1399. sysroot = nullptr;
  1400. }
  1401. std::string sysrootFlagVar =
  1402. std::string("CMAKE_") + lang + "_SYSROOT_FLAG";
  1403. const char* sysrootFlag = this->Makefile->GetDefinition(sysrootFlagVar);
  1404. const char* deploymentTarget =
  1405. this->Makefile->GetDefinition("CMAKE_OSX_DEPLOYMENT_TARGET");
  1406. std::string deploymentTargetFlagVar =
  1407. std::string("CMAKE_") + lang + "_OSX_DEPLOYMENT_TARGET_FLAG";
  1408. const char* deploymentTargetFlag =
  1409. this->Makefile->GetDefinition(deploymentTargetFlagVar);
  1410. if (!archs.empty() && !lang.empty() &&
  1411. (lang[0] == 'C' || lang[0] == 'F')) {
  1412. for (std::string const& arch : archs) {
  1413. flags += " -arch ";
  1414. flags += arch;
  1415. }
  1416. }
  1417. if (sysrootFlag && *sysrootFlag && sysroot && *sysroot) {
  1418. flags += " ";
  1419. flags += sysrootFlag;
  1420. flags += " ";
  1421. flags += this->ConvertToOutputFormat(sysroot, SHELL);
  1422. }
  1423. if (deploymentTargetFlag && *deploymentTargetFlag && deploymentTarget &&
  1424. *deploymentTarget) {
  1425. flags += " ";
  1426. flags += deploymentTargetFlag;
  1427. flags += deploymentTarget;
  1428. }
  1429. }
  1430. }
  1431. void cmLocalGenerator::AddLanguageFlags(std::string& flags,
  1432. cmGeneratorTarget const* target,
  1433. const std::string& lang,
  1434. const std::string& config)
  1435. {
  1436. // Add language-specific flags.
  1437. std::string flagsVar = "CMAKE_";
  1438. flagsVar += lang;
  1439. flagsVar += "_FLAGS";
  1440. this->AddConfigVariableFlags(flags, flagsVar, config);
  1441. // Add MSVC runtime library flags. This is activated by the presence
  1442. // of a default selection whether or not it is overridden by a property.
  1443. const char* msvcRuntimeLibraryDefault =
  1444. this->Makefile->GetDefinition("CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT");
  1445. if (msvcRuntimeLibraryDefault && *msvcRuntimeLibraryDefault) {
  1446. const char* msvcRuntimeLibraryValue =
  1447. target->GetProperty("MSVC_RUNTIME_LIBRARY");
  1448. if (!msvcRuntimeLibraryValue) {
  1449. msvcRuntimeLibraryValue = msvcRuntimeLibraryDefault;
  1450. }
  1451. cmGeneratorExpression ge;
  1452. std::unique_ptr<cmCompiledGeneratorExpression> cge =
  1453. ge.Parse(msvcRuntimeLibraryValue);
  1454. std::string const msvcRuntimeLibrary =
  1455. cge->Evaluate(this, config, false, target);
  1456. if (!msvcRuntimeLibrary.empty()) {
  1457. if (const char* msvcRuntimeLibraryOptions =
  1458. this->Makefile->GetDefinition(
  1459. "CMAKE_" + lang + "_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_" +
  1460. msvcRuntimeLibrary)) {
  1461. this->AppendCompileOptions(flags, msvcRuntimeLibraryOptions);
  1462. } else if ((this->Makefile->GetSafeDefinition(
  1463. "CMAKE_" + lang + "_COMPILER_ID") == "MSVC" ||
  1464. this->Makefile->GetSafeDefinition(
  1465. "CMAKE_" + lang + "_SIMULATE_ID") == "MSVC") &&
  1466. !cmSystemTools::GetErrorOccuredFlag()) {
  1467. // The compiler uses the MSVC ABI so it needs a known runtime library.
  1468. this->IssueMessage(MessageType::FATAL_ERROR,
  1469. "MSVC_RUNTIME_LIBRARY value '" +
  1470. msvcRuntimeLibrary + "' not known for this " +
  1471. lang + " compiler.");
  1472. }
  1473. }
  1474. }
  1475. }
  1476. void cmLocalGenerator::AddLanguageFlagsForLinking(
  1477. std::string& flags, cmGeneratorTarget const* target, const std::string& lang,
  1478. const std::string& config)
  1479. {
  1480. if (this->Makefile->IsOn("CMAKE_" + lang +
  1481. "_LINK_WITH_STANDARD_COMPILE_OPTION")) {
  1482. // This toolchain requires use of the language standard flag
  1483. // when linking in order to use the matching standard library.
  1484. // FIXME: If CMake gains an abstraction for standard library
  1485. // selection, this will have to be reconciled with it.
  1486. this->AddCompilerRequirementFlag(flags, target, lang);
  1487. }
  1488. this->AddLanguageFlags(flags, target, lang, config);
  1489. if (target->IsIPOEnabled(lang, config)) {
  1490. this->AppendFeatureOptions(flags, lang, "IPO");
  1491. }
  1492. }
  1493. cmGeneratorTarget* cmLocalGenerator::FindGeneratorTargetToUse(
  1494. const std::string& name) const
  1495. {
  1496. GeneratorTargetMap::const_iterator imported =
  1497. this->ImportedGeneratorTargets.find(name);
  1498. if (imported != this->ImportedGeneratorTargets.end()) {
  1499. return imported->second;
  1500. }
  1501. if (cmGeneratorTarget* t = this->FindLocalNonAliasGeneratorTarget(name)) {
  1502. return t;
  1503. }
  1504. return this->GetGlobalGenerator()->FindGeneratorTarget(name);
  1505. }
  1506. bool cmLocalGenerator::GetRealDependency(const std::string& inName,
  1507. const std::string& config,
  1508. std::string& dep)
  1509. {
  1510. // Older CMake code may specify the dependency using the target
  1511. // output file rather than the target name. Such code would have
  1512. // been written before there was support for target properties that
  1513. // modify the name so stripping down to just the file name should
  1514. // produce the target name in this case.
  1515. std::string name = cmSystemTools::GetFilenameName(inName);
  1516. // If the input name is the empty string, there is no real
  1517. // dependency. Short-circuit the other checks:
  1518. if (name.empty()) {
  1519. return false;
  1520. }
  1521. if (cmSystemTools::GetFilenameLastExtension(name) == ".exe") {
  1522. name = cmSystemTools::GetFilenameWithoutLastExtension(name);
  1523. }
  1524. // Look for a CMake target with the given name.
  1525. if (cmGeneratorTarget* target = this->FindGeneratorTargetToUse(name)) {
  1526. // make sure it is not just a coincidence that the target name
  1527. // found is part of the inName
  1528. if (cmSystemTools::FileIsFullPath(inName)) {
  1529. std::string tLocation;
  1530. if (target->GetType() >= cmStateEnums::EXECUTABLE &&
  1531. target->GetType() <= cmStateEnums::MODULE_LIBRARY) {
  1532. tLocation = target->GetLocation(config);
  1533. tLocation = cmSystemTools::GetFilenamePath(tLocation);
  1534. tLocation = cmSystemTools::CollapseFullPath(tLocation);
  1535. }
  1536. std::string depLocation =
  1537. cmSystemTools::GetFilenamePath(std::string(inName));
  1538. depLocation = cmSystemTools::CollapseFullPath(depLocation);
  1539. if (depLocation != tLocation) {
  1540. // it is a full path to a depend that has the same name
  1541. // as a target but is in a different location so do not use
  1542. // the target as the depend
  1543. dep = inName;
  1544. return true;
  1545. }
  1546. }
  1547. switch (target->GetType()) {
  1548. case cmStateEnums::EXECUTABLE:
  1549. case cmStateEnums::STATIC_LIBRARY:
  1550. case cmStateEnums::SHARED_LIBRARY:
  1551. case cmStateEnums::MODULE_LIBRARY:
  1552. case cmStateEnums::UNKNOWN_LIBRARY:
  1553. dep = target->GetLocation(config);
  1554. return true;
  1555. case cmStateEnums::OBJECT_LIBRARY:
  1556. // An object library has no single file on which to depend.
  1557. // This was listed to get the target-level dependency.
  1558. return false;
  1559. case cmStateEnums::INTERFACE_LIBRARY:
  1560. // An interface library has no file on which to depend.
  1561. // This was listed to get the target-level dependency.
  1562. return false;
  1563. case cmStateEnums::UTILITY:
  1564. case cmStateEnums::GLOBAL_TARGET:
  1565. // A utility target has no file on which to depend. This was listed
  1566. // only to get the target-level dependency.
  1567. return false;
  1568. }
  1569. }
  1570. // The name was not that of a CMake target. It must name a file.
  1571. if (cmSystemTools::FileIsFullPath(inName)) {
  1572. // This is a full path. Return it as given.
  1573. dep = inName;
  1574. return true;
  1575. }
  1576. // Check for a source file in this directory that matches the
  1577. // dependency.
  1578. if (cmSourceFile* sf = this->Makefile->GetSource(inName)) {
  1579. dep = sf->GetFullPath();
  1580. return true;
  1581. }
  1582. // Treat the name as relative to the source directory in which it
  1583. // was given.
  1584. dep = this->StateSnapshot.GetDirectory().GetCurrentSource();
  1585. dep += "/";
  1586. dep += inName;
  1587. return true;
  1588. }
  1589. void cmLocalGenerator::AddSharedFlags(std::string& flags,
  1590. const std::string& lang, bool shared)
  1591. {
  1592. std::string flagsVar;
  1593. // Add flags for dealing with shared libraries for this language.
  1594. if (shared) {
  1595. flagsVar = "CMAKE_SHARED_LIBRARY_";
  1596. flagsVar += lang;
  1597. flagsVar += "_FLAGS";
  1598. this->AppendFlags(flags, this->Makefile->GetDefinition(flagsVar));
  1599. }
  1600. }
  1601. void cmLocalGenerator::AddCompilerRequirementFlag(
  1602. std::string& flags, cmGeneratorTarget const* target, const std::string& lang)
  1603. {
  1604. if (lang.empty()) {
  1605. return;
  1606. }
  1607. const char* defaultStd =
  1608. this->Makefile->GetDefinition("CMAKE_" + lang + "_STANDARD_DEFAULT");
  1609. if (!defaultStd || !*defaultStd) {
  1610. // This compiler has no notion of language standard levels.
  1611. return;
  1612. }
  1613. std::string extProp = lang + "_EXTENSIONS";
  1614. bool ext = true;
  1615. if (const char* extPropValue = target->GetProperty(extProp)) {
  1616. if (cmSystemTools::IsOff(extPropValue)) {
  1617. ext = false;
  1618. }
  1619. }
  1620. std::string stdProp = lang + "_STANDARD";
  1621. const char* standardProp = target->GetProperty(stdProp);
  1622. if (!standardProp) {
  1623. if (ext) {
  1624. // No language standard is specified and extensions are not disabled.
  1625. // Check if this compiler needs a flag to enable extensions.
  1626. std::string const option_flag =
  1627. "CMAKE_" + lang + "_EXTENSION_COMPILE_OPTION";
  1628. if (const char* opt =
  1629. target->Target->GetMakefile()->GetDefinition(option_flag)) {
  1630. std::vector<std::string> optVec;
  1631. cmSystemTools::ExpandListArgument(opt, optVec);
  1632. for (std::string const& i : optVec) {
  1633. this->AppendFlagEscape(flags, i);
  1634. }
  1635. }
  1636. }
  1637. return;
  1638. }
  1639. std::string const type = ext ? "EXTENSION" : "STANDARD";
  1640. if (target->GetPropertyAsBool(lang + "_STANDARD_REQUIRED")) {
  1641. std::string option_flag =
  1642. "CMAKE_" + lang + standardProp + "_" + type + "_COMPILE_OPTION";
  1643. const char* opt =
  1644. target->Target->GetMakefile()->GetDefinition(option_flag);
  1645. if (!opt) {
  1646. std::ostringstream e;
  1647. e << "Target \"" << target->GetName()
  1648. << "\" requires the language "
  1649. "dialect \""
  1650. << lang << standardProp << "\" "
  1651. << (ext ? "(with compiler extensions)" : "")
  1652. << ", but CMake "
  1653. "does not know the compile flags to use to enable it.";
  1654. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  1655. } else {
  1656. std::vector<std::string> optVec;
  1657. cmSystemTools::ExpandListArgument(opt, optVec);
  1658. for (std::string const& i : optVec) {
  1659. this->AppendFlagEscape(flags, i);
  1660. }
  1661. }
  1662. return;
  1663. }
  1664. static std::map<std::string, std::vector<std::string>> langStdMap;
  1665. if (langStdMap.empty()) {
  1666. // Maintain sorted order, most recent first.
  1667. langStdMap["CXX"].emplace_back("20");
  1668. langStdMap["CXX"].emplace_back("17");
  1669. langStdMap["CXX"].emplace_back("14");
  1670. langStdMap["CXX"].emplace_back("11");
  1671. langStdMap["CXX"].emplace_back("98");
  1672. langStdMap["C"].emplace_back("11");
  1673. langStdMap["C"].emplace_back("99");
  1674. langStdMap["C"].emplace_back("90");
  1675. langStdMap["CUDA"].emplace_back("14");
  1676. langStdMap["CUDA"].emplace_back("11");
  1677. langStdMap["CUDA"].emplace_back("98");
  1678. }
  1679. std::string standard(standardProp);
  1680. std::vector<std::string>& stds = langStdMap[lang];
  1681. std::vector<std::string>::const_iterator stdIt =
  1682. std::find(stds.begin(), stds.end(), standard);
  1683. if (stdIt == stds.end()) {
  1684. std::string e =
  1685. lang + "_STANDARD is set to invalid value '" + standard + "'";
  1686. this->GetGlobalGenerator()->GetCMakeInstance()->IssueMessage(
  1687. MessageType::FATAL_ERROR, e, target->GetBacktrace());
  1688. return;
  1689. }
  1690. std::vector<std::string>::const_iterator defaultStdIt =
  1691. std::find(stds.begin(), stds.end(), defaultStd);
  1692. if (defaultStdIt == stds.end()) {
  1693. std::string e = "CMAKE_" + lang +
  1694. "_STANDARD_DEFAULT is set to invalid value '" + std::string(defaultStd) +
  1695. "'";
  1696. this->IssueMessage(MessageType::INTERNAL_ERROR, e);
  1697. return;
  1698. }
  1699. // If the standard requested is older than the compiler's default
  1700. // then we need to use a flag to change it. The comparison is
  1701. // greater-or-equal because the standards are stored in backward
  1702. // chronological order.
  1703. if (stdIt >= defaultStdIt) {
  1704. std::string option_flag =
  1705. "CMAKE_" + lang + *stdIt + "_" + type + "_COMPILE_OPTION";
  1706. std::string const& opt =
  1707. target->Target->GetMakefile()->GetRequiredDefinition(option_flag);
  1708. std::vector<std::string> optVec;
  1709. cmSystemTools::ExpandListArgument(opt, optVec);
  1710. for (std::string const& i : optVec) {
  1711. this->AppendFlagEscape(flags, i);
  1712. }
  1713. return;
  1714. }
  1715. // The standard requested is at least as new as the compiler's default,
  1716. // and the standard request is not required. Decay to the newest standard
  1717. // for which a flag is defined.
  1718. for (; stdIt < defaultStdIt; ++stdIt) {
  1719. std::string option_flag =
  1720. "CMAKE_" + lang + *stdIt + "_" + type + "_COMPILE_OPTION";
  1721. if (const char* opt =
  1722. target->Target->GetMakefile()->GetDefinition(option_flag)) {
  1723. std::vector<std::string> optVec;
  1724. cmSystemTools::ExpandListArgument(opt, optVec);
  1725. for (std::string const& i : optVec) {
  1726. this->AppendFlagEscape(flags, i);
  1727. }
  1728. return;
  1729. }
  1730. }
  1731. }
  1732. static void AddVisibilityCompileOption(std::string& flags,
  1733. cmGeneratorTarget const* target,
  1734. cmLocalGenerator* lg,
  1735. const std::string& lang,
  1736. std::string* warnCMP0063)
  1737. {
  1738. std::string compileOption = "CMAKE_" + lang + "_COMPILE_OPTIONS_VISIBILITY";
  1739. const char* opt = lg->GetMakefile()->GetDefinition(compileOption);
  1740. if (!opt) {
  1741. return;
  1742. }
  1743. std::string flagDefine = lang + "_VISIBILITY_PRESET";
  1744. const char* prop = target->GetProperty(flagDefine);
  1745. if (!prop) {
  1746. return;
  1747. }
  1748. if (warnCMP0063) {
  1749. *warnCMP0063 += " " + flagDefine + "\n";
  1750. return;
  1751. }
  1752. if (strcmp(prop, "hidden") != 0 && strcmp(prop, "default") != 0 &&
  1753. strcmp(prop, "protected") != 0 && strcmp(prop, "internal") != 0) {
  1754. std::ostringstream e;
  1755. e << "Target " << target->GetName() << " uses unsupported value \"" << prop
  1756. << "\" for " << flagDefine << "."
  1757. << " The supported values are: default, hidden, protected, and "
  1758. "internal.";
  1759. cmSystemTools::Error(e.str());
  1760. return;
  1761. }
  1762. std::string option = std::string(opt) + prop;
  1763. lg->AppendFlags(flags, option);
  1764. }
  1765. static void AddInlineVisibilityCompileOption(std::string& flags,
  1766. cmGeneratorTarget const* target,
  1767. cmLocalGenerator* lg,
  1768. std::string* warnCMP0063)
  1769. {
  1770. std::string compileOption =
  1771. "CMAKE_CXX_COMPILE_OPTIONS_VISIBILITY_INLINES_HIDDEN";
  1772. const char* opt = lg->GetMakefile()->GetDefinition(compileOption);
  1773. if (!opt) {
  1774. return;
  1775. }
  1776. bool prop = target->GetPropertyAsBool("VISIBILITY_INLINES_HIDDEN");
  1777. if (!prop) {
  1778. return;
  1779. }
  1780. if (warnCMP0063) {
  1781. *warnCMP0063 += " VISIBILITY_INLINES_HIDDEN\n";
  1782. return;
  1783. }
  1784. lg->AppendFlags(flags, opt);
  1785. }
  1786. void cmLocalGenerator::AddVisibilityPresetFlags(
  1787. std::string& flags, cmGeneratorTarget const* target, const std::string& lang)
  1788. {
  1789. if (lang.empty()) {
  1790. return;
  1791. }
  1792. std::string warnCMP0063;
  1793. std::string* pWarnCMP0063 = nullptr;
  1794. if (target->GetType() != cmStateEnums::SHARED_LIBRARY &&
  1795. target->GetType() != cmStateEnums::MODULE_LIBRARY &&
  1796. !target->IsExecutableWithExports()) {
  1797. switch (target->GetPolicyStatusCMP0063()) {
  1798. case cmPolicies::OLD:
  1799. return;
  1800. case cmPolicies::WARN:
  1801. pWarnCMP0063 = &warnCMP0063;
  1802. break;
  1803. default:
  1804. break;
  1805. }
  1806. }
  1807. AddVisibilityCompileOption(flags, target, this, lang, pWarnCMP0063);
  1808. if (lang == "CXX") {
  1809. AddInlineVisibilityCompileOption(flags, target, this, pWarnCMP0063);
  1810. }
  1811. if (!warnCMP0063.empty() && this->WarnCMP0063.insert(target).second) {
  1812. std::ostringstream w;
  1813. /* clang-format off */
  1814. w <<
  1815. cmPolicies::GetPolicyWarning(cmPolicies::CMP0063) << "\n"
  1816. "Target \"" << target->GetName() << "\" of "
  1817. "type \"" << cmState::GetTargetTypeName(target->GetType()) << "\" "
  1818. "has the following visibility properties set for " << lang << ":\n" <<
  1819. warnCMP0063 <<
  1820. "For compatibility CMake is not honoring them for this target.";
  1821. /* clang-format on */
  1822. target->GetLocalGenerator()->GetCMakeInstance()->IssueMessage(
  1823. MessageType::AUTHOR_WARNING, w.str(), target->GetBacktrace());
  1824. }
  1825. }
  1826. void cmLocalGenerator::AddCMP0018Flags(std::string& flags,
  1827. cmGeneratorTarget const* target,
  1828. std::string const& lang,
  1829. const std::string& config)
  1830. {
  1831. int targetType = target->GetType();
  1832. bool shared = ((targetType == cmStateEnums::SHARED_LIBRARY) ||
  1833. (targetType == cmStateEnums::MODULE_LIBRARY));
  1834. if (this->GetShouldUseOldFlags(shared, lang)) {
  1835. this->AddSharedFlags(flags, lang, shared);
  1836. } else {
  1837. if (target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  1838. if (target->GetPropertyAsBool("POSITION_INDEPENDENT_CODE")) {
  1839. this->AddPositionIndependentFlags(flags, lang, targetType);
  1840. }
  1841. return;
  1842. }
  1843. if (target->GetLinkInterfaceDependentBoolProperty(
  1844. "POSITION_INDEPENDENT_CODE", config)) {
  1845. this->AddPositionIndependentFlags(flags, lang, targetType);
  1846. }
  1847. if (shared) {
  1848. this->AppendFeatureOptions(flags, lang, "DLL");
  1849. }
  1850. }
  1851. }
  1852. bool cmLocalGenerator::GetShouldUseOldFlags(bool shared,
  1853. const std::string& lang) const
  1854. {
  1855. std::string originalFlags =
  1856. this->GlobalGenerator->GetSharedLibFlagsForLanguage(lang);
  1857. if (shared) {
  1858. std::string flagsVar = "CMAKE_SHARED_LIBRARY_";
  1859. flagsVar += lang;
  1860. flagsVar += "_FLAGS";
  1861. std::string const& flags = this->Makefile->GetSafeDefinition(flagsVar);
  1862. if (flags != originalFlags) {
  1863. switch (this->GetPolicyStatus(cmPolicies::CMP0018)) {
  1864. case cmPolicies::WARN: {
  1865. std::ostringstream e;
  1866. e << "Variable " << flagsVar
  1867. << " has been modified. CMake "
  1868. "will ignore the POSITION_INDEPENDENT_CODE target property for "
  1869. "shared libraries and will use the "
  1870. << flagsVar
  1871. << " variable "
  1872. "instead. This may cause errors if the original content of "
  1873. << flagsVar << " was removed.\n"
  1874. << cmPolicies::GetPolicyWarning(cmPolicies::CMP0018);
  1875. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  1876. CM_FALLTHROUGH;
  1877. }
  1878. case cmPolicies::OLD:
  1879. return true;
  1880. case cmPolicies::REQUIRED_IF_USED:
  1881. case cmPolicies::REQUIRED_ALWAYS:
  1882. case cmPolicies::NEW:
  1883. return false;
  1884. }
  1885. }
  1886. }
  1887. return false;
  1888. }
  1889. void cmLocalGenerator::AddPositionIndependentFlags(std::string& flags,
  1890. std::string const& lang,
  1891. int targetType)
  1892. {
  1893. std::string picFlags;
  1894. if (targetType == cmStateEnums::EXECUTABLE) {
  1895. std::string flagsVar = "CMAKE_";
  1896. flagsVar += lang;
  1897. flagsVar += "_COMPILE_OPTIONS_PIE";
  1898. picFlags = this->Makefile->GetSafeDefinition(flagsVar);
  1899. }
  1900. if (picFlags.empty()) {
  1901. std::string flagsVar = "CMAKE_";
  1902. flagsVar += lang;
  1903. flagsVar += "_COMPILE_OPTIONS_PIC";
  1904. picFlags = this->Makefile->GetSafeDefinition(flagsVar);
  1905. }
  1906. if (!picFlags.empty()) {
  1907. std::vector<std::string> options;
  1908. cmSystemTools::ExpandListArgument(picFlags, options);
  1909. for (std::string const& o : options) {
  1910. this->AppendFlagEscape(flags, o);
  1911. }
  1912. }
  1913. }
  1914. void cmLocalGenerator::AddConfigVariableFlags(std::string& flags,
  1915. const std::string& var,
  1916. const std::string& config)
  1917. {
  1918. // Add the flags from the variable itself.
  1919. std::string flagsVar = var;
  1920. this->AppendFlags(flags, this->Makefile->GetDefinition(flagsVar));
  1921. // Add the flags from the build-type specific variable.
  1922. if (!config.empty()) {
  1923. flagsVar += "_";
  1924. flagsVar += cmSystemTools::UpperCase(config);
  1925. this->AppendFlags(flags, this->Makefile->GetDefinition(flagsVar));
  1926. }
  1927. }
  1928. void cmLocalGenerator::AppendFlags(std::string& flags,
  1929. const std::string& newFlags) const
  1930. {
  1931. if (!newFlags.empty()) {
  1932. if (!flags.empty()) {
  1933. flags += " ";
  1934. }
  1935. flags += newFlags;
  1936. }
  1937. }
  1938. void cmLocalGenerator::AppendFlags(std::string& flags,
  1939. const char* newFlags) const
  1940. {
  1941. if (newFlags && *newFlags) {
  1942. this->AppendFlags(flags, std::string(newFlags));
  1943. }
  1944. }
  1945. void cmLocalGenerator::AppendFlagEscape(std::string& flags,
  1946. const std::string& rawFlag) const
  1947. {
  1948. this->AppendFlags(flags, this->EscapeForShell(rawFlag));
  1949. }
  1950. void cmLocalGenerator::AppendIPOLinkerFlags(std::string& flags,
  1951. cmGeneratorTarget* target,
  1952. const std::string& config,
  1953. const std::string& lang)
  1954. {
  1955. if (!target->IsIPOEnabled(lang, config)) {
  1956. return;
  1957. }
  1958. switch (target->GetType()) {
  1959. case cmStateEnums::EXECUTABLE:
  1960. case cmStateEnums::SHARED_LIBRARY:
  1961. case cmStateEnums::MODULE_LIBRARY:
  1962. break;
  1963. default:
  1964. return;
  1965. }
  1966. const std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_IPO";
  1967. const char* rawFlagsList = this->Makefile->GetDefinition(name);
  1968. if (rawFlagsList == nullptr) {
  1969. return;
  1970. }
  1971. std::vector<std::string> flagsList;
  1972. cmSystemTools::ExpandListArgument(rawFlagsList, flagsList);
  1973. for (std::string const& o : flagsList) {
  1974. this->AppendFlagEscape(flags, o);
  1975. }
  1976. }
  1977. void cmLocalGenerator::AppendPositionIndependentLinkerFlags(
  1978. std::string& flags, cmGeneratorTarget* target, const std::string& config,
  1979. const std::string& lang)
  1980. {
  1981. // For now, only EXECUTABLE is concerned
  1982. if (target->GetType() != cmStateEnums::EXECUTABLE) {
  1983. return;
  1984. }
  1985. const char* PICValue = target->GetLinkPIEProperty(config);
  1986. if (PICValue == nullptr) {
  1987. // POSITION_INDEPENDENT_CODE is not set
  1988. return;
  1989. }
  1990. const std::string mode = cmSystemTools::IsOn(PICValue) ? "PIE" : "NO_PIE";
  1991. std::string supported = "CMAKE_" + lang + "_LINK_" + mode + "_SUPPORTED";
  1992. if (cmSystemTools::IsOff(this->Makefile->GetDefinition(supported))) {
  1993. return;
  1994. }
  1995. std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_" + mode;
  1996. auto pieFlags = this->Makefile->GetSafeDefinition(name);
  1997. if (pieFlags.empty()) {
  1998. return;
  1999. }
  2000. std::vector<std::string> flagsList;
  2001. cmSystemTools::ExpandListArgument(pieFlags, flagsList);
  2002. for (const auto& flag : flagsList) {
  2003. this->AppendFlagEscape(flags, flag);
  2004. }
  2005. }
  2006. void cmLocalGenerator::AppendCompileOptions(std::string& options,
  2007. const char* options_list,
  2008. const char* regex) const
  2009. {
  2010. // Short-circuit if there are no options.
  2011. if (!options_list) {
  2012. return;
  2013. }
  2014. // Expand the list of options.
  2015. std::vector<std::string> options_vec;
  2016. cmSystemTools::ExpandListArgument(options_list, options_vec);
  2017. this->AppendCompileOptions(options, options_vec, regex);
  2018. }
  2019. void cmLocalGenerator::AppendCompileOptions(
  2020. std::string& options, const std::vector<std::string>& options_vec,
  2021. const char* regex) const
  2022. {
  2023. if (regex != nullptr) {
  2024. // Filter flags upon specified reges.
  2025. cmsys::RegularExpression r(regex);
  2026. for (std::string const& opt : options_vec) {
  2027. if (r.find(opt)) {
  2028. this->AppendFlagEscape(options, opt);
  2029. }
  2030. }
  2031. } else {
  2032. for (std::string const& opt : options_vec) {
  2033. this->AppendFlagEscape(options, opt);
  2034. }
  2035. }
  2036. }
  2037. void cmLocalGenerator::AppendIncludeDirectories(
  2038. std::vector<std::string>& includes, const char* includes_list,
  2039. const cmSourceFile& sourceFile) const
  2040. {
  2041. // Short-circuit if there are no includes.
  2042. if (!includes_list) {
  2043. return;
  2044. }
  2045. // Expand the list of includes.
  2046. std::vector<std::string> includes_vec;
  2047. cmSystemTools::ExpandListArgument(includes_list, includes_vec);
  2048. this->AppendIncludeDirectories(includes, includes_vec, sourceFile);
  2049. }
  2050. void cmLocalGenerator::AppendIncludeDirectories(
  2051. std::vector<std::string>& includes,
  2052. const std::vector<std::string>& includes_vec,
  2053. const cmSourceFile& sourceFile) const
  2054. {
  2055. std::unordered_set<std::string> uniqueIncludes;
  2056. for (const std::string& include : includes_vec) {
  2057. if (!cmSystemTools::FileIsFullPath(include)) {
  2058. std::ostringstream e;
  2059. e << "Found relative path while evaluating include directories of "
  2060. "\""
  2061. << sourceFile.GetLocation().GetName() << "\":\n \"" << include
  2062. << "\"\n";
  2063. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2064. return;
  2065. }
  2066. std::string inc = include;
  2067. if (!cmSystemTools::IsOff(inc)) {
  2068. cmSystemTools::ConvertToUnixSlashes(inc);
  2069. }
  2070. if (uniqueIncludes.insert(inc).second) {
  2071. includes.push_back(std::move(inc));
  2072. }
  2073. }
  2074. }
  2075. void cmLocalGenerator::AppendDefines(std::set<std::string>& defines,
  2076. std::string const& defines_list) const
  2077. {
  2078. std::set<BT<std::string>> tmp;
  2079. this->AppendDefines(tmp, ExpandListWithBacktrace(defines_list));
  2080. for (BT<std::string> const& i : tmp) {
  2081. defines.emplace(i.Value);
  2082. }
  2083. }
  2084. void cmLocalGenerator::AppendDefines(std::set<BT<std::string>>& defines,
  2085. std::string const& defines_list) const
  2086. {
  2087. // Short-circuit if there are no definitions.
  2088. if (defines_list.empty()) {
  2089. return;
  2090. }
  2091. // Expand the list of definitions.
  2092. this->AppendDefines(defines, ExpandListWithBacktrace(defines_list));
  2093. }
  2094. void cmLocalGenerator::AppendDefines(
  2095. std::set<BT<std::string>>& defines,
  2096. const std::vector<BT<std::string>>& defines_vec) const
  2097. {
  2098. for (BT<std::string> const& d : defines_vec) {
  2099. // Skip unsupported definitions.
  2100. if (!this->CheckDefinition(d.Value)) {
  2101. continue;
  2102. }
  2103. defines.insert(d);
  2104. }
  2105. }
  2106. void cmLocalGenerator::JoinDefines(const std::set<std::string>& defines,
  2107. std::string& definesString,
  2108. const std::string& lang)
  2109. {
  2110. // Lookup the define flag for the current language.
  2111. std::string dflag = "-D";
  2112. if (!lang.empty()) {
  2113. std::string defineFlagVar = "CMAKE_";
  2114. defineFlagVar += lang;
  2115. defineFlagVar += "_DEFINE_FLAG";
  2116. const char* df = this->Makefile->GetDefinition(defineFlagVar);
  2117. if (df && *df) {
  2118. dflag = df;
  2119. }
  2120. }
  2121. const char* itemSeparator = definesString.empty() ? "" : " ";
  2122. for (std::string const& define : defines) {
  2123. // Append the definition with proper escaping.
  2124. std::string def = dflag;
  2125. if (this->GetState()->UseWatcomWMake()) {
  2126. // The Watcom compiler does its own command line parsing instead
  2127. // of using the windows shell rules. Definitions are one of
  2128. // -DNAME
  2129. // -DNAME=<cpp-token>
  2130. // -DNAME="c-string with spaces and other characters(?@#$)"
  2131. //
  2132. // Watcom will properly parse each of these cases from the
  2133. // command line without any escapes. However we still have to
  2134. // get the '$' and '#' characters through WMake as '$$' and
  2135. // '$#'.
  2136. for (const char* c = define.c_str(); *c; ++c) {
  2137. if (*c == '$' || *c == '#') {
  2138. def += '$';
  2139. }
  2140. def += *c;
  2141. }
  2142. } else {
  2143. // Make the definition appear properly on the command line. Use
  2144. // -DNAME="value" instead of -D"NAME=value" for historical reasons.
  2145. std::string::size_type eq = define.find('=');
  2146. def += define.substr(0, eq);
  2147. if (eq != std::string::npos) {
  2148. def += "=";
  2149. def += this->EscapeForShell(define.substr(eq + 1), true);
  2150. }
  2151. }
  2152. definesString += itemSeparator;
  2153. itemSeparator = " ";
  2154. definesString += def;
  2155. }
  2156. }
  2157. void cmLocalGenerator::AppendFeatureOptions(std::string& flags,
  2158. const std::string& lang,
  2159. const char* feature)
  2160. {
  2161. std::string optVar = "CMAKE_";
  2162. optVar += lang;
  2163. optVar += "_COMPILE_OPTIONS_";
  2164. optVar += feature;
  2165. if (const char* optionList = this->Makefile->GetDefinition(optVar)) {
  2166. std::vector<std::string> options;
  2167. cmSystemTools::ExpandListArgument(optionList, options);
  2168. for (std::string const& o : options) {
  2169. this->AppendFlagEscape(flags, o);
  2170. }
  2171. }
  2172. }
  2173. const char* cmLocalGenerator::GetFeature(const std::string& feature,
  2174. const std::string& config)
  2175. {
  2176. std::string featureName = feature;
  2177. // TODO: Define accumulation policy for features (prepend, append, replace).
  2178. // Currently we always replace.
  2179. if (!config.empty()) {
  2180. featureName += "_";
  2181. featureName += cmSystemTools::UpperCase(config);
  2182. }
  2183. cmStateSnapshot snp = this->StateSnapshot;
  2184. while (snp.IsValid()) {
  2185. if (const char* value = snp.GetDirectory().GetProperty(featureName)) {
  2186. return value;
  2187. }
  2188. snp = snp.GetBuildsystemDirectoryParent();
  2189. }
  2190. return nullptr;
  2191. }
  2192. std::string cmLocalGenerator::GetProjectName() const
  2193. {
  2194. return this->StateSnapshot.GetProjectName();
  2195. }
  2196. std::string cmLocalGenerator::ConstructComment(
  2197. cmCustomCommandGenerator const& ccg, const char* default_comment)
  2198. {
  2199. // Check for a comment provided with the command.
  2200. if (ccg.GetComment()) {
  2201. return ccg.GetComment();
  2202. }
  2203. // Construct a reasonable default comment if possible.
  2204. if (!ccg.GetOutputs().empty()) {
  2205. std::string comment;
  2206. comment = "Generating ";
  2207. const char* sep = "";
  2208. std::string currentBinaryDir = this->GetCurrentBinaryDirectory();
  2209. for (std::string const& o : ccg.GetOutputs()) {
  2210. comment += sep;
  2211. comment += this->MaybeConvertToRelativePath(currentBinaryDir, o);
  2212. sep = ", ";
  2213. }
  2214. return comment;
  2215. }
  2216. // Otherwise use the provided default.
  2217. return default_comment;
  2218. }
  2219. class cmInstallTargetGeneratorLocal : public cmInstallTargetGenerator
  2220. {
  2221. public:
  2222. cmInstallTargetGeneratorLocal(cmLocalGenerator* lg, std::string const& t,
  2223. const char* dest, bool implib)
  2224. : cmInstallTargetGenerator(
  2225. t, dest, implib, "", std::vector<std::string>(), "Unspecified",
  2226. cmInstallGenerator::SelectMessageLevel(lg->GetMakefile()), false,
  2227. false)
  2228. {
  2229. this->Compute(lg);
  2230. }
  2231. };
  2232. void cmLocalGenerator::GenerateTargetInstallRules(
  2233. std::ostream& os, const std::string& config,
  2234. std::vector<std::string> const& configurationTypes)
  2235. {
  2236. // Convert the old-style install specification from each target to
  2237. // an install generator and run it.
  2238. const std::vector<cmGeneratorTarget*>& tgts = this->GetGeneratorTargets();
  2239. for (cmGeneratorTarget* l : tgts) {
  2240. if (l->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  2241. continue;
  2242. }
  2243. // Include the user-specified pre-install script for this target.
  2244. if (const char* preinstall = l->GetProperty("PRE_INSTALL_SCRIPT")) {
  2245. cmInstallScriptGenerator g(preinstall, false, nullptr, false);
  2246. g.Generate(os, config, configurationTypes);
  2247. }
  2248. // Install this target if a destination is given.
  2249. if (!l->Target->GetInstallPath().empty()) {
  2250. // Compute the full install destination. Note that converting
  2251. // to unix slashes also removes any trailing slash.
  2252. // We also skip over the leading slash given by the user.
  2253. std::string destination = l->Target->GetInstallPath().substr(1);
  2254. cmSystemTools::ConvertToUnixSlashes(destination);
  2255. if (destination.empty()) {
  2256. destination = ".";
  2257. }
  2258. // Generate the proper install generator for this target type.
  2259. switch (l->GetType()) {
  2260. case cmStateEnums::EXECUTABLE:
  2261. case cmStateEnums::STATIC_LIBRARY:
  2262. case cmStateEnums::MODULE_LIBRARY: {
  2263. // Use a target install generator.
  2264. cmInstallTargetGeneratorLocal g(this, l->GetName(),
  2265. destination.c_str(), false);
  2266. g.Generate(os, config, configurationTypes);
  2267. } break;
  2268. case cmStateEnums::SHARED_LIBRARY: {
  2269. #if defined(_WIN32) || defined(__CYGWIN__)
  2270. // Special code to handle DLL. Install the import library
  2271. // to the normal destination and the DLL to the runtime
  2272. // destination.
  2273. cmInstallTargetGeneratorLocal g1(this, l->GetName(),
  2274. destination.c_str(), true);
  2275. g1.Generate(os, config, configurationTypes);
  2276. // We also skip over the leading slash given by the user.
  2277. destination = l->Target->GetRuntimeInstallPath().substr(1);
  2278. cmSystemTools::ConvertToUnixSlashes(destination);
  2279. cmInstallTargetGeneratorLocal g2(this, l->GetName(),
  2280. destination.c_str(), false);
  2281. g2.Generate(os, config, configurationTypes);
  2282. #else
  2283. // Use a target install generator.
  2284. cmInstallTargetGeneratorLocal g(this, l->GetName(),
  2285. destination.c_str(), false);
  2286. g.Generate(os, config, configurationTypes);
  2287. #endif
  2288. } break;
  2289. default:
  2290. break;
  2291. }
  2292. }
  2293. // Include the user-specified post-install script for this target.
  2294. if (const char* postinstall = l->GetProperty("POST_INSTALL_SCRIPT")) {
  2295. cmInstallScriptGenerator g(postinstall, false, nullptr, false);
  2296. g.Generate(os, config, configurationTypes);
  2297. }
  2298. }
  2299. }
  2300. #if defined(CM_LG_ENCODE_OBJECT_NAMES)
  2301. static bool cmLocalGeneratorShortenObjectName(std::string& objName,
  2302. std::string::size_type max_len)
  2303. {
  2304. // Replace the beginning of the path portion of the object name with
  2305. // its own md5 sum.
  2306. std::string::size_type pos =
  2307. objName.find('/', objName.size() - max_len + 32);
  2308. if (pos != std::string::npos) {
  2309. cmCryptoHash md5(cmCryptoHash::AlgoMD5);
  2310. std::string md5name = md5.HashString(objName.substr(0, pos));
  2311. md5name += objName.substr(pos);
  2312. objName = md5name;
  2313. // The object name is now short enough.
  2314. return true;
  2315. }
  2316. // The object name could not be shortened enough.
  2317. return false;
  2318. }
  2319. bool cmLocalGeneratorCheckObjectName(std::string& objName,
  2320. std::string::size_type dir_len,
  2321. std::string::size_type max_total_len)
  2322. {
  2323. // Enforce the maximum file name length if possible.
  2324. std::string::size_type max_obj_len = max_total_len;
  2325. if (dir_len < max_total_len) {
  2326. max_obj_len = max_total_len - dir_len;
  2327. if (objName.size() > max_obj_len) {
  2328. // The current object file name is too long. Try to shorten it.
  2329. return cmLocalGeneratorShortenObjectName(objName, max_obj_len);
  2330. }
  2331. // The object file name is short enough.
  2332. return true;
  2333. }
  2334. // The build directory in which the object will be stored is
  2335. // already too deep.
  2336. return false;
  2337. }
  2338. #endif
  2339. std::string& cmLocalGenerator::CreateSafeUniqueObjectFileName(
  2340. const std::string& sin, std::string const& dir_max)
  2341. {
  2342. // Look for an existing mapped name for this object file.
  2343. std::map<std::string, std::string>::iterator it =
  2344. this->UniqueObjectNamesMap.find(sin);
  2345. // If no entry exists create one.
  2346. if (it == this->UniqueObjectNamesMap.end()) {
  2347. // Start with the original name.
  2348. std::string ssin = sin;
  2349. // Avoid full paths by removing leading slashes.
  2350. ssin.erase(0, ssin.find_first_not_of('/'));
  2351. // Avoid full paths by removing colons.
  2352. std::replace(ssin.begin(), ssin.end(), ':', '_');
  2353. // Avoid relative paths that go up the tree.
  2354. cmSystemTools::ReplaceString(ssin, "../", "__/");
  2355. // Avoid spaces.
  2356. std::replace(ssin.begin(), ssin.end(), ' ', '_');
  2357. // Mangle the name if necessary.
  2358. if (this->Makefile->IsOn("CMAKE_MANGLE_OBJECT_FILE_NAMES")) {
  2359. bool done;
  2360. int cc = 0;
  2361. char rpstr[100];
  2362. sprintf(rpstr, "_p_");
  2363. cmSystemTools::ReplaceString(ssin, "+", rpstr);
  2364. std::string sssin = sin;
  2365. do {
  2366. done = true;
  2367. for (it = this->UniqueObjectNamesMap.begin();
  2368. it != this->UniqueObjectNamesMap.end(); ++it) {
  2369. if (it->second == ssin) {
  2370. done = false;
  2371. }
  2372. }
  2373. if (done) {
  2374. break;
  2375. }
  2376. sssin = ssin;
  2377. cmSystemTools::ReplaceString(ssin, "_p_", rpstr);
  2378. sprintf(rpstr, "_p%d_", cc++);
  2379. } while (!done);
  2380. }
  2381. #if defined(CM_LG_ENCODE_OBJECT_NAMES)
  2382. if (!cmLocalGeneratorCheckObjectName(ssin, dir_max.size(),
  2383. this->ObjectPathMax)) {
  2384. // Warn if this is the first time the path has been seen.
  2385. if (this->ObjectMaxPathViolations.insert(dir_max).second) {
  2386. std::ostringstream m;
  2387. /* clang-format off */
  2388. m << "The object file directory\n"
  2389. << " " << dir_max << "\n"
  2390. << "has " << dir_max.size() << " characters. "
  2391. << "The maximum full path to an object file is "
  2392. << this->ObjectPathMax << " characters "
  2393. << "(see CMAKE_OBJECT_PATH_MAX). "
  2394. << "Object file\n"
  2395. << " " << ssin << "\n"
  2396. << "cannot be safely placed under this directory. "
  2397. << "The build may not work correctly.";
  2398. /* clang-format on */
  2399. this->IssueMessage(MessageType::WARNING, m.str());
  2400. }
  2401. }
  2402. #else
  2403. (void)dir_max;
  2404. #endif
  2405. // Insert the newly mapped object file name.
  2406. std::map<std::string, std::string>::value_type e(sin, ssin);
  2407. it = this->UniqueObjectNamesMap.insert(e).first;
  2408. }
  2409. // Return the map entry.
  2410. return it->second;
  2411. }
  2412. void cmLocalGenerator::ComputeObjectFilenames(
  2413. std::map<cmSourceFile const*, std::string>& /*unused*/,
  2414. cmGeneratorTarget const* /*unused*/)
  2415. {
  2416. }
  2417. bool cmLocalGenerator::IsWindowsShell() const
  2418. {
  2419. return this->GetState()->UseWindowsShell();
  2420. }
  2421. bool cmLocalGenerator::IsWatcomWMake() const
  2422. {
  2423. return this->GetState()->UseWatcomWMake();
  2424. }
  2425. bool cmLocalGenerator::IsMinGWMake() const
  2426. {
  2427. return this->GetState()->UseMinGWMake();
  2428. }
  2429. bool cmLocalGenerator::IsNMake() const
  2430. {
  2431. return this->GetState()->UseNMake();
  2432. }
  2433. std::string cmLocalGenerator::GetObjectFileNameWithoutTarget(
  2434. const cmSourceFile& source, std::string const& dir_max,
  2435. bool* hasSourceExtension, char const* customOutputExtension)
  2436. {
  2437. // Construct the object file name using the full path to the source
  2438. // file which is its only unique identification.
  2439. std::string const& fullPath = source.GetFullPath();
  2440. // Try referencing the source relative to the source tree.
  2441. std::string relFromSource = this->MaybeConvertToRelativePath(
  2442. this->GetCurrentSourceDirectory(), fullPath);
  2443. assert(!relFromSource.empty());
  2444. bool relSource = !cmSystemTools::FileIsFullPath(relFromSource);
  2445. bool subSource = relSource && relFromSource[0] != '.';
  2446. // Try referencing the source relative to the binary tree.
  2447. std::string relFromBinary = this->MaybeConvertToRelativePath(
  2448. this->GetCurrentBinaryDirectory(), fullPath);
  2449. assert(!relFromBinary.empty());
  2450. bool relBinary = !cmSystemTools::FileIsFullPath(relFromBinary);
  2451. bool subBinary = relBinary && relFromBinary[0] != '.';
  2452. // Select a nice-looking reference to the source file to construct
  2453. // the object file name.
  2454. std::string objectName;
  2455. if ((relSource && !relBinary) || (subSource && !subBinary)) {
  2456. objectName = relFromSource;
  2457. } else if ((relBinary && !relSource) || (subBinary && !subSource)) {
  2458. objectName = relFromBinary;
  2459. } else if (relFromBinary.length() < relFromSource.length()) {
  2460. objectName = relFromBinary;
  2461. } else {
  2462. objectName = relFromSource;
  2463. }
  2464. // if it is still a full path check for the try compile case
  2465. // try compile never have in source sources, and should not
  2466. // have conflicting source file names in the same target
  2467. if (cmSystemTools::FileIsFullPath(objectName)) {
  2468. if (this->GetGlobalGenerator()->GetCMakeInstance()->GetIsInTryCompile()) {
  2469. objectName = cmSystemTools::GetFilenameName(source.GetFullPath());
  2470. }
  2471. }
  2472. // Replace the original source file extension with the object file
  2473. // extension.
  2474. bool keptSourceExtension = true;
  2475. if (!source.GetPropertyAsBool("KEEP_EXTENSION")) {
  2476. // Decide whether this language wants to replace the source
  2477. // extension with the object extension. For CMake 2.4
  2478. // compatibility do this by default.
  2479. bool replaceExt = this->NeedBackwardsCompatibility_2_4();
  2480. if (!replaceExt) {
  2481. std::string lang = source.GetLanguage();
  2482. if (!lang.empty()) {
  2483. std::string repVar = "CMAKE_";
  2484. repVar += lang;
  2485. repVar += "_OUTPUT_EXTENSION_REPLACE";
  2486. replaceExt = this->Makefile->IsOn(repVar);
  2487. }
  2488. }
  2489. // Remove the source extension if it is to be replaced.
  2490. if (replaceExt || customOutputExtension) {
  2491. keptSourceExtension = false;
  2492. std::string::size_type dot_pos = objectName.rfind('.');
  2493. if (dot_pos != std::string::npos) {
  2494. objectName = objectName.substr(0, dot_pos);
  2495. }
  2496. }
  2497. // Store the new extension.
  2498. if (customOutputExtension) {
  2499. objectName += customOutputExtension;
  2500. } else {
  2501. objectName += this->GlobalGenerator->GetLanguageOutputExtension(source);
  2502. }
  2503. }
  2504. if (hasSourceExtension) {
  2505. *hasSourceExtension = keptSourceExtension;
  2506. }
  2507. // Convert to a safe name.
  2508. return this->CreateSafeUniqueObjectFileName(objectName, dir_max);
  2509. }
  2510. std::string cmLocalGenerator::GetSourceFileLanguage(const cmSourceFile& source)
  2511. {
  2512. return source.GetLanguage();
  2513. }
  2514. cmake* cmLocalGenerator::GetCMakeInstance() const
  2515. {
  2516. return this->GlobalGenerator->GetCMakeInstance();
  2517. }
  2518. std::string const& cmLocalGenerator::GetSourceDirectory() const
  2519. {
  2520. return this->GetCMakeInstance()->GetHomeDirectory();
  2521. }
  2522. std::string const& cmLocalGenerator::GetBinaryDirectory() const
  2523. {
  2524. return this->GetCMakeInstance()->GetHomeOutputDirectory();
  2525. }
  2526. std::string const& cmLocalGenerator::GetCurrentBinaryDirectory() const
  2527. {
  2528. return this->StateSnapshot.GetDirectory().GetCurrentBinary();
  2529. }
  2530. std::string const& cmLocalGenerator::GetCurrentSourceDirectory() const
  2531. {
  2532. return this->StateSnapshot.GetDirectory().GetCurrentSource();
  2533. }
  2534. std::string cmLocalGenerator::MaybeConvertToRelativePath(
  2535. std::string const& local_path, std::string const& remote_path) const
  2536. {
  2537. return this->StateSnapshot.GetDirectory().ConvertToRelPathIfNotContained(
  2538. local_path, remote_path);
  2539. }
  2540. std::string cmLocalGenerator::GetTargetDirectory(
  2541. const cmGeneratorTarget* /*unused*/) const
  2542. {
  2543. cmSystemTools::Error("GetTargetDirectory"
  2544. " called on cmLocalGenerator");
  2545. return "";
  2546. }
  2547. KWIML_INT_uint64_t cmLocalGenerator::GetBackwardsCompatibility()
  2548. {
  2549. // The computed version may change until the project is fully
  2550. // configured.
  2551. if (!this->BackwardsCompatibilityFinal) {
  2552. unsigned int major = 0;
  2553. unsigned int minor = 0;
  2554. unsigned int patch = 0;
  2555. if (const char* value =
  2556. this->Makefile->GetDefinition("CMAKE_BACKWARDS_COMPATIBILITY")) {
  2557. switch (sscanf(value, "%u.%u.%u", &major, &minor, &patch)) {
  2558. case 2:
  2559. patch = 0;
  2560. break;
  2561. case 1:
  2562. minor = 0;
  2563. patch = 0;
  2564. break;
  2565. default:
  2566. break;
  2567. }
  2568. }
  2569. this->BackwardsCompatibility = CMake_VERSION_ENCODE(major, minor, patch);
  2570. this->BackwardsCompatibilityFinal = true;
  2571. }
  2572. return this->BackwardsCompatibility;
  2573. }
  2574. bool cmLocalGenerator::NeedBackwardsCompatibility_2_4()
  2575. {
  2576. // Check the policy to decide whether to pay attention to this
  2577. // variable.
  2578. switch (this->GetPolicyStatus(cmPolicies::CMP0001)) {
  2579. case cmPolicies::WARN:
  2580. // WARN is just OLD without warning because user code does not
  2581. // always affect whether this check is done.
  2582. case cmPolicies::OLD:
  2583. // Old behavior is to check the variable.
  2584. break;
  2585. case cmPolicies::NEW:
  2586. // New behavior is to ignore the variable.
  2587. return false;
  2588. case cmPolicies::REQUIRED_IF_USED:
  2589. case cmPolicies::REQUIRED_ALWAYS:
  2590. // This will never be the case because the only way to require
  2591. // the setting is to require the user to specify version policy
  2592. // 2.6 or higher. Once we add that requirement then this whole
  2593. // method can be removed anyway.
  2594. return false;
  2595. }
  2596. // Compatibility is needed if CMAKE_BACKWARDS_COMPATIBILITY is set
  2597. // equal to or lower than the given version.
  2598. KWIML_INT_uint64_t actual_compat = this->GetBackwardsCompatibility();
  2599. return (actual_compat && actual_compat <= CMake_VERSION_ENCODE(2, 4, 255));
  2600. }
  2601. cmPolicies::PolicyStatus cmLocalGenerator::GetPolicyStatus(
  2602. cmPolicies::PolicyID id) const
  2603. {
  2604. return this->Makefile->GetPolicyStatus(id);
  2605. }
  2606. bool cmLocalGenerator::CheckDefinition(std::string const& define) const
  2607. {
  2608. // Many compilers do not support -DNAME(arg)=sdf so we disable it.
  2609. std::string::size_type pos = define.find_first_of("(=");
  2610. if (pos != std::string::npos) {
  2611. if (define[pos] == '(') {
  2612. std::ostringstream e;
  2613. /* clang-format off */
  2614. e << "WARNING: Function-style preprocessor definitions may not be "
  2615. << "passed on the compiler command line because many compilers "
  2616. << "do not support it.\n"
  2617. << "CMake is dropping a preprocessor definition: " << define << "\n"
  2618. << "Consider defining the macro in a (configured) header file.\n";
  2619. /* clang-format on */
  2620. cmSystemTools::Message(e.str());
  2621. return false;
  2622. }
  2623. }
  2624. // Many compilers do not support # in the value so we disable it.
  2625. if (define.find_first_of('#') != std::string::npos) {
  2626. std::ostringstream e;
  2627. /* clang-format off */
  2628. e << "WARNING: Preprocessor definitions containing '#' may not be "
  2629. << "passed on the compiler command line because many compilers "
  2630. << "do not support it.\n"
  2631. << "CMake is dropping a preprocessor definition: " << define << "\n"
  2632. << "Consider defining the macro in a (configured) header file.\n";
  2633. /* clang-format on */
  2634. cmSystemTools::Message(e.str());
  2635. return false;
  2636. }
  2637. // Assume it is supported.
  2638. return true;
  2639. }
  2640. static void cmLGInfoProp(cmMakefile* mf, cmGeneratorTarget* target,
  2641. const std::string& prop)
  2642. {
  2643. if (const char* val = target->GetProperty(prop)) {
  2644. mf->AddDefinition(prop, val);
  2645. }
  2646. }
  2647. void cmLocalGenerator::GenerateAppleInfoPList(cmGeneratorTarget* target,
  2648. const std::string& targetName,
  2649. const std::string& fname)
  2650. {
  2651. // Find the Info.plist template.
  2652. const char* in = target->GetProperty("MACOSX_BUNDLE_INFO_PLIST");
  2653. std::string inFile = (in && *in) ? in : "MacOSXBundleInfo.plist.in";
  2654. if (!cmSystemTools::FileIsFullPath(inFile)) {
  2655. std::string inMod = this->Makefile->GetModulesFile(inFile);
  2656. if (!inMod.empty()) {
  2657. inFile = inMod;
  2658. }
  2659. }
  2660. if (!cmSystemTools::FileExists(inFile, true)) {
  2661. std::ostringstream e;
  2662. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  2663. << "\" could not be found.";
  2664. cmSystemTools::Error(e.str());
  2665. return;
  2666. }
  2667. // Convert target properties to variables in an isolated makefile
  2668. // scope to configure the file. If properties are set they will
  2669. // override user make variables. If not the configuration will fall
  2670. // back to the directory-level values set by the user.
  2671. cmMakefile* mf = this->Makefile;
  2672. cmMakefile::ScopePushPop varScope(mf);
  2673. mf->AddDefinition("MACOSX_BUNDLE_EXECUTABLE_NAME", targetName.c_str());
  2674. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_INFO_STRING");
  2675. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_ICON_FILE");
  2676. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_GUI_IDENTIFIER");
  2677. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_LONG_VERSION_STRING");
  2678. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_NAME");
  2679. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_SHORT_VERSION_STRING");
  2680. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_VERSION");
  2681. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_COPYRIGHT");
  2682. mf->ConfigureFile(inFile, fname, false, false, false);
  2683. }
  2684. void cmLocalGenerator::GenerateFrameworkInfoPList(
  2685. cmGeneratorTarget* target, const std::string& targetName,
  2686. const std::string& fname)
  2687. {
  2688. // Find the Info.plist template.
  2689. const char* in = target->GetProperty("MACOSX_FRAMEWORK_INFO_PLIST");
  2690. std::string inFile = (in && *in) ? in : "MacOSXFrameworkInfo.plist.in";
  2691. if (!cmSystemTools::FileIsFullPath(inFile)) {
  2692. std::string inMod = this->Makefile->GetModulesFile(inFile);
  2693. if (!inMod.empty()) {
  2694. inFile = inMod;
  2695. }
  2696. }
  2697. if (!cmSystemTools::FileExists(inFile, true)) {
  2698. std::ostringstream e;
  2699. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  2700. << "\" could not be found.";
  2701. cmSystemTools::Error(e.str());
  2702. return;
  2703. }
  2704. // Convert target properties to variables in an isolated makefile
  2705. // scope to configure the file. If properties are set they will
  2706. // override user make variables. If not the configuration will fall
  2707. // back to the directory-level values set by the user.
  2708. cmMakefile* mf = this->Makefile;
  2709. cmMakefile::ScopePushPop varScope(mf);
  2710. mf->AddDefinition("MACOSX_FRAMEWORK_NAME", targetName.c_str());
  2711. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_ICON_FILE");
  2712. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_IDENTIFIER");
  2713. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_SHORT_VERSION_STRING");
  2714. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_BUNDLE_VERSION");
  2715. mf->ConfigureFile(inFile, fname, false, false, false);
  2716. }