cmLocalGenerator.cxx 103 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021
  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. if (linkLanguage != "Swift") {
  1029. this->AppendFlags(
  1030. flags, this->Makefile->GetSafeDefinition("CMAKE_STATIC_LINKER_FLAGS"));
  1031. if (!config.empty()) {
  1032. std::string name = "CMAKE_STATIC_LINKER_FLAGS_" + config;
  1033. this->AppendFlags(flags, this->Makefile->GetSafeDefinition(name));
  1034. }
  1035. }
  1036. this->AppendFlags(flags, target->GetProperty("STATIC_LIBRARY_FLAGS"));
  1037. if (!config.empty()) {
  1038. std::string name = "STATIC_LIBRARY_FLAGS_" + config;
  1039. this->AppendFlags(flags, target->GetProperty(name));
  1040. }
  1041. std::vector<std::string> options;
  1042. target->GetStaticLibraryLinkOptions(options, config, linkLanguage);
  1043. // STATIC_LIBRARY_OPTIONS are escaped.
  1044. this->AppendCompileOptions(flags, options);
  1045. }
  1046. void cmLocalGenerator::GetTargetFlags(
  1047. cmLinkLineComputer* linkLineComputer, const std::string& config,
  1048. std::string& linkLibs, std::string& flags, std::string& linkFlags,
  1049. std::string& frameworkPath, std::string& linkPath, cmGeneratorTarget* target)
  1050. {
  1051. const std::string buildType = cmSystemTools::UpperCase(config);
  1052. cmComputeLinkInformation* pcli = target->GetLinkInformation(config);
  1053. const char* libraryLinkVariable =
  1054. "CMAKE_SHARED_LINKER_FLAGS"; // default to shared library
  1055. const std::string linkLanguage =
  1056. linkLineComputer->GetLinkerLanguage(target, buildType);
  1057. switch (target->GetType()) {
  1058. case cmStateEnums::STATIC_LIBRARY:
  1059. this->GetStaticLibraryFlags(linkFlags, buildType, linkLanguage, target);
  1060. break;
  1061. case cmStateEnums::MODULE_LIBRARY:
  1062. libraryLinkVariable = "CMAKE_MODULE_LINKER_FLAGS";
  1063. CM_FALLTHROUGH;
  1064. case cmStateEnums::SHARED_LIBRARY: {
  1065. if (linkLanguage != "Swift") {
  1066. linkFlags = this->Makefile->GetSafeDefinition(libraryLinkVariable);
  1067. linkFlags += " ";
  1068. if (!buildType.empty()) {
  1069. std::string build = libraryLinkVariable;
  1070. build += "_";
  1071. build += buildType;
  1072. linkFlags += this->Makefile->GetSafeDefinition(build);
  1073. linkFlags += " ";
  1074. }
  1075. if (this->Makefile->IsOn("WIN32") &&
  1076. !(this->Makefile->IsOn("CYGWIN") ||
  1077. this->Makefile->IsOn("MINGW"))) {
  1078. std::vector<cmSourceFile*> sources;
  1079. target->GetSourceFiles(sources, buildType);
  1080. std::string defFlag =
  1081. this->Makefile->GetSafeDefinition("CMAKE_LINK_DEF_FILE_FLAG");
  1082. for (cmSourceFile* sf : sources) {
  1083. if (sf->GetExtension() == "def") {
  1084. linkFlags += defFlag;
  1085. linkFlags += this->ConvertToOutputFormat(
  1086. cmSystemTools::CollapseFullPath(sf->GetFullPath()), SHELL);
  1087. linkFlags += " ";
  1088. }
  1089. }
  1090. }
  1091. }
  1092. const char* targetLinkFlags = target->GetProperty("LINK_FLAGS");
  1093. if (targetLinkFlags) {
  1094. linkFlags += targetLinkFlags;
  1095. linkFlags += " ";
  1096. }
  1097. if (!buildType.empty()) {
  1098. std::string configLinkFlags = "LINK_FLAGS_";
  1099. configLinkFlags += buildType;
  1100. targetLinkFlags = target->GetProperty(configLinkFlags);
  1101. if (targetLinkFlags) {
  1102. linkFlags += targetLinkFlags;
  1103. linkFlags += " ";
  1104. }
  1105. }
  1106. std::vector<std::string> opts;
  1107. target->GetLinkOptions(opts, config, linkLanguage);
  1108. // LINK_OPTIONS are escaped.
  1109. this->AppendCompileOptions(linkFlags, opts);
  1110. if (pcli) {
  1111. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1112. frameworkPath, linkPath);
  1113. }
  1114. } break;
  1115. case cmStateEnums::EXECUTABLE: {
  1116. if (linkLanguage != "Swift") {
  1117. linkFlags +=
  1118. this->Makefile->GetSafeDefinition("CMAKE_EXE_LINKER_FLAGS");
  1119. linkFlags += " ";
  1120. if (!buildType.empty()) {
  1121. std::string build = "CMAKE_EXE_LINKER_FLAGS_";
  1122. build += buildType;
  1123. linkFlags += this->Makefile->GetSafeDefinition(build);
  1124. linkFlags += " ";
  1125. }
  1126. if (linkLanguage.empty()) {
  1127. cmSystemTools::Error(
  1128. "CMake can not determine linker language for target: " +
  1129. target->GetName());
  1130. return;
  1131. }
  1132. if (target->GetPropertyAsBool("WIN32_EXECUTABLE")) {
  1133. linkFlags +=
  1134. this->Makefile->GetSafeDefinition("CMAKE_CREATE_WIN32_EXE");
  1135. linkFlags += " ";
  1136. } else {
  1137. linkFlags +=
  1138. this->Makefile->GetSafeDefinition("CMAKE_CREATE_CONSOLE_EXE");
  1139. linkFlags += " ";
  1140. }
  1141. if (target->IsExecutableWithExports()) {
  1142. std::string exportFlagVar = "CMAKE_EXE_EXPORTS_";
  1143. exportFlagVar += linkLanguage;
  1144. exportFlagVar += "_FLAG";
  1145. linkFlags += this->Makefile->GetSafeDefinition(exportFlagVar);
  1146. linkFlags += " ";
  1147. }
  1148. }
  1149. this->AddLanguageFlagsForLinking(flags, target, linkLanguage, buildType);
  1150. if (pcli) {
  1151. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1152. frameworkPath, linkPath);
  1153. }
  1154. if (cmSystemTools::IsOn(
  1155. this->Makefile->GetDefinition("BUILD_SHARED_LIBS"))) {
  1156. std::string sFlagVar = std::string("CMAKE_SHARED_BUILD_") +
  1157. linkLanguage + std::string("_FLAGS");
  1158. linkFlags += this->Makefile->GetSafeDefinition(sFlagVar);
  1159. linkFlags += " ";
  1160. }
  1161. std::string cmp0065Flags =
  1162. this->GetLinkLibsCMP0065(linkLanguage, *target);
  1163. if (!cmp0065Flags.empty()) {
  1164. linkFlags += cmp0065Flags;
  1165. linkFlags += " ";
  1166. }
  1167. const char* targetLinkFlags = target->GetProperty("LINK_FLAGS");
  1168. if (targetLinkFlags) {
  1169. linkFlags += targetLinkFlags;
  1170. linkFlags += " ";
  1171. }
  1172. if (!buildType.empty()) {
  1173. std::string configLinkFlags = "LINK_FLAGS_";
  1174. configLinkFlags += buildType;
  1175. targetLinkFlags = target->GetProperty(configLinkFlags);
  1176. if (targetLinkFlags) {
  1177. linkFlags += targetLinkFlags;
  1178. linkFlags += " ";
  1179. }
  1180. }
  1181. std::vector<std::string> opts;
  1182. target->GetLinkOptions(opts, config, linkLanguage);
  1183. // LINK_OPTIONS are escaped.
  1184. this->AppendCompileOptions(linkFlags, opts);
  1185. } break;
  1186. default:
  1187. break;
  1188. }
  1189. this->AppendPositionIndependentLinkerFlags(linkFlags, target, config,
  1190. linkLanguage);
  1191. this->AppendIPOLinkerFlags(linkFlags, target, config, linkLanguage);
  1192. }
  1193. void cmLocalGenerator::GetTargetCompileFlags(cmGeneratorTarget* target,
  1194. std::string const& config,
  1195. std::string const& lang,
  1196. std::string& flags)
  1197. {
  1198. cmMakefile* mf = this->GetMakefile();
  1199. // Add language-specific flags.
  1200. this->AddLanguageFlags(flags, target, lang, config);
  1201. if (target->IsIPOEnabled(lang, config)) {
  1202. this->AppendFeatureOptions(flags, lang, "IPO");
  1203. }
  1204. this->AddArchitectureFlags(flags, target, lang, config);
  1205. if (lang == "Fortran") {
  1206. this->AppendFlags(flags, this->GetTargetFortranFlags(target, config));
  1207. }
  1208. this->AddCMP0018Flags(flags, target, lang, config);
  1209. this->AddVisibilityPresetFlags(flags, target, lang);
  1210. this->AppendFlags(flags, mf->GetDefineFlags());
  1211. this->AppendFlags(flags, this->GetFrameworkFlags(lang, config, target));
  1212. this->AddCompileOptions(flags, target, lang, config);
  1213. }
  1214. static std::string GetFrameworkFlags(const std::string& lang,
  1215. const std::string& config,
  1216. cmGeneratorTarget* target)
  1217. {
  1218. cmLocalGenerator* lg = target->GetLocalGenerator();
  1219. cmMakefile* mf = lg->GetMakefile();
  1220. if (!mf->IsOn("APPLE")) {
  1221. return std::string();
  1222. }
  1223. std::string fwSearchFlagVar = "CMAKE_" + lang + "_FRAMEWORK_SEARCH_FLAG";
  1224. const char* fwSearchFlag = mf->GetDefinition(fwSearchFlagVar);
  1225. if (!(fwSearchFlag && *fwSearchFlag)) {
  1226. return std::string();
  1227. }
  1228. std::set<std::string> emitted;
  1229. #ifdef __APPLE__ /* don't insert this when crosscompiling e.g. to iphone */
  1230. emitted.insert("/System/Library/Frameworks");
  1231. #endif
  1232. std::vector<std::string> includes;
  1233. lg->GetIncludeDirectories(includes, target, "C", config);
  1234. // check all include directories for frameworks as this
  1235. // will already have added a -F for the framework
  1236. for (std::string const& include : includes) {
  1237. if (lg->GetGlobalGenerator()->NameResolvesToFramework(include)) {
  1238. std::string frameworkDir = include;
  1239. frameworkDir += "/../";
  1240. frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
  1241. emitted.insert(frameworkDir);
  1242. }
  1243. }
  1244. std::string flags;
  1245. if (cmComputeLinkInformation* cli = target->GetLinkInformation(config)) {
  1246. std::vector<std::string> const& frameworks = cli->GetFrameworkPaths();
  1247. for (std::string const& framework : frameworks) {
  1248. if (emitted.insert(framework).second) {
  1249. flags += fwSearchFlag;
  1250. flags +=
  1251. lg->ConvertToOutputFormat(framework, cmOutputConverter::SHELL);
  1252. flags += " ";
  1253. }
  1254. }
  1255. }
  1256. return flags;
  1257. }
  1258. std::string cmLocalGenerator::GetFrameworkFlags(std::string const& l,
  1259. std::string const& config,
  1260. cmGeneratorTarget* target)
  1261. {
  1262. return ::GetFrameworkFlags(l, config, target);
  1263. }
  1264. void cmLocalGenerator::GetTargetDefines(cmGeneratorTarget const* target,
  1265. std::string const& config,
  1266. std::string const& lang,
  1267. std::set<std::string>& defines) const
  1268. {
  1269. std::set<BT<std::string>> tmp = this->GetTargetDefines(target, config, lang);
  1270. for (BT<std::string> const& v : tmp) {
  1271. defines.emplace(v.Value);
  1272. }
  1273. }
  1274. std::set<BT<std::string>> cmLocalGenerator::GetTargetDefines(
  1275. cmGeneratorTarget const* target, std::string const& config,
  1276. std::string const& lang) const
  1277. {
  1278. std::set<BT<std::string>> defines;
  1279. // Add the export symbol definition for shared library objects.
  1280. if (const std::string* exportMacro = target->GetExportMacro()) {
  1281. this->AppendDefines(defines, *exportMacro);
  1282. }
  1283. // Add preprocessor definitions for this target and configuration.
  1284. std::vector<BT<std::string>> targetDefines =
  1285. target->GetCompileDefinitions(config, lang);
  1286. this->AppendDefines(defines, targetDefines);
  1287. return defines;
  1288. }
  1289. std::string cmLocalGenerator::GetTargetFortranFlags(
  1290. cmGeneratorTarget const* /*unused*/, std::string const& /*unused*/)
  1291. {
  1292. // Implemented by specific generators that override this.
  1293. return std::string();
  1294. }
  1295. /**
  1296. * Output the linking rules on a command line. For executables,
  1297. * targetLibrary should be a NULL pointer. For libraries, it should point
  1298. * to the name of the library. This will not link a library against itself.
  1299. */
  1300. void cmLocalGenerator::OutputLinkLibraries(
  1301. cmComputeLinkInformation* pcli, cmLinkLineComputer* linkLineComputer,
  1302. std::string& linkLibraries, std::string& frameworkPath,
  1303. std::string& linkPath)
  1304. {
  1305. cmComputeLinkInformation& cli = *pcli;
  1306. std::string linkLanguage = cli.GetLinkLanguage();
  1307. std::string libPathFlag;
  1308. if (const char* value = this->Makefile->GetDefinition(
  1309. "CMAKE_" + cli.GetLinkLanguage() + "_LIBRARY_PATH_FLAG")) {
  1310. libPathFlag = value;
  1311. } else {
  1312. libPathFlag =
  1313. this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_FLAG");
  1314. }
  1315. std::string libPathTerminator;
  1316. if (const char* value = this->Makefile->GetDefinition(
  1317. "CMAKE_" + cli.GetLinkLanguage() + "_LIBRARY_PATH_TERMINATOR")) {
  1318. libPathTerminator = value;
  1319. } else {
  1320. libPathTerminator =
  1321. this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_TERMINATOR");
  1322. }
  1323. // Add standard libraries for this language.
  1324. std::string standardLibsVar = "CMAKE_";
  1325. standardLibsVar += cli.GetLinkLanguage();
  1326. standardLibsVar += "_STANDARD_LIBRARIES";
  1327. std::string stdLibString;
  1328. if (const char* stdLibs = this->Makefile->GetDefinition(standardLibsVar)) {
  1329. stdLibString = stdLibs;
  1330. }
  1331. // Append the framework search path flags.
  1332. std::string fwSearchFlagVar = "CMAKE_";
  1333. fwSearchFlagVar += linkLanguage;
  1334. fwSearchFlagVar += "_FRAMEWORK_SEARCH_FLAG";
  1335. std::string fwSearchFlag =
  1336. this->Makefile->GetSafeDefinition(fwSearchFlagVar);
  1337. frameworkPath = linkLineComputer->ComputeFrameworkPath(cli, fwSearchFlag);
  1338. linkPath =
  1339. linkLineComputer->ComputeLinkPath(cli, libPathFlag, libPathTerminator);
  1340. linkLibraries = linkLineComputer->ComputeLinkLibraries(cli, stdLibString);
  1341. }
  1342. std::string cmLocalGenerator::GetLinkLibsCMP0065(
  1343. std::string const& linkLanguage, cmGeneratorTarget& tgt) const
  1344. {
  1345. std::string linkFlags;
  1346. // Flags to link an executable to shared libraries.
  1347. if (tgt.GetType() == cmStateEnums::EXECUTABLE &&
  1348. this->StateSnapshot.GetState()->GetGlobalPropertyAsBool(
  1349. "TARGET_SUPPORTS_SHARED_LIBS")) {
  1350. bool add_shlib_flags = false;
  1351. switch (tgt.GetPolicyStatusCMP0065()) {
  1352. case cmPolicies::WARN:
  1353. if (!tgt.GetPropertyAsBool("ENABLE_EXPORTS") &&
  1354. this->Makefile->PolicyOptionalWarningEnabled(
  1355. "CMAKE_POLICY_WARNING_CMP0065")) {
  1356. std::ostringstream w;
  1357. /* clang-format off */
  1358. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0065) << "\n"
  1359. "For compatibility with older versions of CMake, "
  1360. "additional flags may be added to export symbols on all "
  1361. "executables regardless of their ENABLE_EXPORTS property.";
  1362. /* clang-format on */
  1363. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  1364. }
  1365. CM_FALLTHROUGH;
  1366. case cmPolicies::OLD:
  1367. // OLD behavior is to always add the flags, except on AIX where
  1368. // we compute symbol exports if ENABLE_EXPORTS is on.
  1369. add_shlib_flags =
  1370. !(tgt.Target->IsAIX() && tgt.GetPropertyAsBool("ENABLE_EXPORTS"));
  1371. break;
  1372. case cmPolicies::REQUIRED_IF_USED:
  1373. case cmPolicies::REQUIRED_ALWAYS:
  1374. this->IssueMessage(
  1375. MessageType::FATAL_ERROR,
  1376. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0065));
  1377. CM_FALLTHROUGH;
  1378. case cmPolicies::NEW:
  1379. // NEW behavior is to only add the flags if ENABLE_EXPORTS is on,
  1380. // except on AIX where we compute symbol exports.
  1381. add_shlib_flags =
  1382. !tgt.Target->IsAIX() && tgt.GetPropertyAsBool("ENABLE_EXPORTS");
  1383. break;
  1384. }
  1385. if (add_shlib_flags) {
  1386. std::string linkFlagsVar = "CMAKE_SHARED_LIBRARY_LINK_";
  1387. linkFlagsVar += linkLanguage;
  1388. linkFlagsVar += "_FLAGS";
  1389. linkFlags = this->Makefile->GetSafeDefinition(linkFlagsVar);
  1390. }
  1391. }
  1392. return linkFlags;
  1393. }
  1394. void cmLocalGenerator::AddArchitectureFlags(std::string& flags,
  1395. cmGeneratorTarget const* target,
  1396. const std::string& lang,
  1397. const std::string& config)
  1398. {
  1399. // Only add macOS specific flags on Darwin platforms (macOS and iOS):
  1400. if (this->Makefile->IsOn("APPLE") && this->EmitUniversalBinaryFlags) {
  1401. std::vector<std::string> archs;
  1402. target->GetAppleArchs(config, archs);
  1403. const char* sysroot = this->Makefile->GetDefinition("CMAKE_OSX_SYSROOT");
  1404. if (sysroot && sysroot[0] == '/' && !sysroot[1]) {
  1405. sysroot = nullptr;
  1406. }
  1407. std::string sysrootFlagVar =
  1408. std::string("CMAKE_") + lang + "_SYSROOT_FLAG";
  1409. const char* sysrootFlag = this->Makefile->GetDefinition(sysrootFlagVar);
  1410. const char* deploymentTarget =
  1411. this->Makefile->GetDefinition("CMAKE_OSX_DEPLOYMENT_TARGET");
  1412. std::string deploymentTargetFlagVar =
  1413. std::string("CMAKE_") + lang + "_OSX_DEPLOYMENT_TARGET_FLAG";
  1414. const char* deploymentTargetFlag =
  1415. this->Makefile->GetDefinition(deploymentTargetFlagVar);
  1416. if (!archs.empty() && !lang.empty() &&
  1417. (lang[0] == 'C' || lang[0] == 'F')) {
  1418. for (std::string const& arch : archs) {
  1419. flags += " -arch ";
  1420. flags += arch;
  1421. }
  1422. }
  1423. if (sysrootFlag && *sysrootFlag && sysroot && *sysroot) {
  1424. flags += " ";
  1425. flags += sysrootFlag;
  1426. flags += " ";
  1427. flags += this->ConvertToOutputFormat(sysroot, SHELL);
  1428. }
  1429. if (deploymentTargetFlag && *deploymentTargetFlag && deploymentTarget &&
  1430. *deploymentTarget) {
  1431. flags += " ";
  1432. flags += deploymentTargetFlag;
  1433. flags += deploymentTarget;
  1434. }
  1435. }
  1436. }
  1437. void cmLocalGenerator::AddLanguageFlags(std::string& flags,
  1438. cmGeneratorTarget const* target,
  1439. const std::string& lang,
  1440. const std::string& config)
  1441. {
  1442. // Add language-specific flags.
  1443. std::string flagsVar = "CMAKE_";
  1444. flagsVar += lang;
  1445. flagsVar += "_FLAGS";
  1446. this->AddConfigVariableFlags(flags, flagsVar, config);
  1447. // Add MSVC runtime library flags. This is activated by the presence
  1448. // of a default selection whether or not it is overridden by a property.
  1449. const char* msvcRuntimeLibraryDefault =
  1450. this->Makefile->GetDefinition("CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT");
  1451. if (msvcRuntimeLibraryDefault && *msvcRuntimeLibraryDefault) {
  1452. const char* msvcRuntimeLibraryValue =
  1453. target->GetProperty("MSVC_RUNTIME_LIBRARY");
  1454. if (!msvcRuntimeLibraryValue) {
  1455. msvcRuntimeLibraryValue = msvcRuntimeLibraryDefault;
  1456. }
  1457. cmGeneratorExpression ge;
  1458. std::unique_ptr<cmCompiledGeneratorExpression> cge =
  1459. ge.Parse(msvcRuntimeLibraryValue);
  1460. std::string const msvcRuntimeLibrary =
  1461. cge->Evaluate(this, config, false, target);
  1462. if (!msvcRuntimeLibrary.empty()) {
  1463. if (const char* msvcRuntimeLibraryOptions =
  1464. this->Makefile->GetDefinition(
  1465. "CMAKE_" + lang + "_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_" +
  1466. msvcRuntimeLibrary)) {
  1467. this->AppendCompileOptions(flags, msvcRuntimeLibraryOptions);
  1468. } else if ((this->Makefile->GetSafeDefinition(
  1469. "CMAKE_" + lang + "_COMPILER_ID") == "MSVC" ||
  1470. this->Makefile->GetSafeDefinition(
  1471. "CMAKE_" + lang + "_SIMULATE_ID") == "MSVC") &&
  1472. !cmSystemTools::GetErrorOccuredFlag()) {
  1473. // The compiler uses the MSVC ABI so it needs a known runtime library.
  1474. this->IssueMessage(MessageType::FATAL_ERROR,
  1475. "MSVC_RUNTIME_LIBRARY value '" +
  1476. msvcRuntimeLibrary + "' not known for this " +
  1477. lang + " compiler.");
  1478. }
  1479. }
  1480. }
  1481. }
  1482. void cmLocalGenerator::AddLanguageFlagsForLinking(
  1483. std::string& flags, cmGeneratorTarget const* target, const std::string& lang,
  1484. const std::string& config)
  1485. {
  1486. if (this->Makefile->IsOn("CMAKE_" + lang +
  1487. "_LINK_WITH_STANDARD_COMPILE_OPTION")) {
  1488. // This toolchain requires use of the language standard flag
  1489. // when linking in order to use the matching standard library.
  1490. // FIXME: If CMake gains an abstraction for standard library
  1491. // selection, this will have to be reconciled with it.
  1492. this->AddCompilerRequirementFlag(flags, target, lang);
  1493. }
  1494. this->AddLanguageFlags(flags, target, lang, config);
  1495. if (target->IsIPOEnabled(lang, config)) {
  1496. this->AppendFeatureOptions(flags, lang, "IPO");
  1497. }
  1498. }
  1499. cmGeneratorTarget* cmLocalGenerator::FindGeneratorTargetToUse(
  1500. const std::string& name) const
  1501. {
  1502. GeneratorTargetMap::const_iterator imported =
  1503. this->ImportedGeneratorTargets.find(name);
  1504. if (imported != this->ImportedGeneratorTargets.end()) {
  1505. return imported->second;
  1506. }
  1507. if (cmGeneratorTarget* t = this->FindLocalNonAliasGeneratorTarget(name)) {
  1508. return t;
  1509. }
  1510. return this->GetGlobalGenerator()->FindGeneratorTarget(name);
  1511. }
  1512. bool cmLocalGenerator::GetRealDependency(const std::string& inName,
  1513. const std::string& config,
  1514. std::string& dep)
  1515. {
  1516. // Older CMake code may specify the dependency using the target
  1517. // output file rather than the target name. Such code would have
  1518. // been written before there was support for target properties that
  1519. // modify the name so stripping down to just the file name should
  1520. // produce the target name in this case.
  1521. std::string name = cmSystemTools::GetFilenameName(inName);
  1522. // If the input name is the empty string, there is no real
  1523. // dependency. Short-circuit the other checks:
  1524. if (name.empty()) {
  1525. return false;
  1526. }
  1527. if (cmSystemTools::GetFilenameLastExtension(name) == ".exe") {
  1528. name = cmSystemTools::GetFilenameWithoutLastExtension(name);
  1529. }
  1530. // Look for a CMake target with the given name.
  1531. if (cmGeneratorTarget* target = this->FindGeneratorTargetToUse(name)) {
  1532. // make sure it is not just a coincidence that the target name
  1533. // found is part of the inName
  1534. if (cmSystemTools::FileIsFullPath(inName)) {
  1535. std::string tLocation;
  1536. if (target->GetType() >= cmStateEnums::EXECUTABLE &&
  1537. target->GetType() <= cmStateEnums::MODULE_LIBRARY) {
  1538. tLocation = target->GetLocation(config);
  1539. tLocation = cmSystemTools::GetFilenamePath(tLocation);
  1540. tLocation = cmSystemTools::CollapseFullPath(tLocation);
  1541. }
  1542. std::string depLocation =
  1543. cmSystemTools::GetFilenamePath(std::string(inName));
  1544. depLocation = cmSystemTools::CollapseFullPath(depLocation);
  1545. if (depLocation != tLocation) {
  1546. // it is a full path to a depend that has the same name
  1547. // as a target but is in a different location so do not use
  1548. // the target as the depend
  1549. dep = inName;
  1550. return true;
  1551. }
  1552. }
  1553. switch (target->GetType()) {
  1554. case cmStateEnums::EXECUTABLE:
  1555. case cmStateEnums::STATIC_LIBRARY:
  1556. case cmStateEnums::SHARED_LIBRARY:
  1557. case cmStateEnums::MODULE_LIBRARY:
  1558. case cmStateEnums::UNKNOWN_LIBRARY:
  1559. dep = target->GetLocation(config);
  1560. return true;
  1561. case cmStateEnums::OBJECT_LIBRARY:
  1562. // An object library has no single file on which to depend.
  1563. // This was listed to get the target-level dependency.
  1564. return false;
  1565. case cmStateEnums::INTERFACE_LIBRARY:
  1566. // An interface library has no file on which to depend.
  1567. // This was listed to get the target-level dependency.
  1568. return false;
  1569. case cmStateEnums::UTILITY:
  1570. case cmStateEnums::GLOBAL_TARGET:
  1571. // A utility target has no file on which to depend. This was listed
  1572. // only to get the target-level dependency.
  1573. return false;
  1574. }
  1575. }
  1576. // The name was not that of a CMake target. It must name a file.
  1577. if (cmSystemTools::FileIsFullPath(inName)) {
  1578. // This is a full path. Return it as given.
  1579. dep = inName;
  1580. return true;
  1581. }
  1582. // Check for a source file in this directory that matches the
  1583. // dependency.
  1584. if (cmSourceFile* sf = this->Makefile->GetSource(inName)) {
  1585. dep = sf->GetFullPath();
  1586. return true;
  1587. }
  1588. // Treat the name as relative to the source directory in which it
  1589. // was given.
  1590. dep = this->StateSnapshot.GetDirectory().GetCurrentSource();
  1591. dep += "/";
  1592. dep += inName;
  1593. return true;
  1594. }
  1595. void cmLocalGenerator::AddSharedFlags(std::string& flags,
  1596. const std::string& lang, bool shared)
  1597. {
  1598. std::string flagsVar;
  1599. // Add flags for dealing with shared libraries for this language.
  1600. if (shared) {
  1601. flagsVar = "CMAKE_SHARED_LIBRARY_";
  1602. flagsVar += lang;
  1603. flagsVar += "_FLAGS";
  1604. this->AppendFlags(flags, this->Makefile->GetDefinition(flagsVar));
  1605. }
  1606. }
  1607. void cmLocalGenerator::AddCompilerRequirementFlag(
  1608. std::string& flags, cmGeneratorTarget const* target, const std::string& lang)
  1609. {
  1610. if (lang.empty()) {
  1611. return;
  1612. }
  1613. const char* defaultStd =
  1614. this->Makefile->GetDefinition("CMAKE_" + lang + "_STANDARD_DEFAULT");
  1615. if (!defaultStd || !*defaultStd) {
  1616. // This compiler has no notion of language standard levels.
  1617. return;
  1618. }
  1619. std::string extProp = lang + "_EXTENSIONS";
  1620. bool ext = true;
  1621. if (const char* extPropValue = target->GetProperty(extProp)) {
  1622. if (cmSystemTools::IsOff(extPropValue)) {
  1623. ext = false;
  1624. }
  1625. }
  1626. std::string stdProp = lang + "_STANDARD";
  1627. const char* standardProp = target->GetProperty(stdProp);
  1628. if (!standardProp) {
  1629. if (ext) {
  1630. // No language standard is specified and extensions are not disabled.
  1631. // Check if this compiler needs a flag to enable extensions.
  1632. std::string const option_flag =
  1633. "CMAKE_" + lang + "_EXTENSION_COMPILE_OPTION";
  1634. if (const char* opt =
  1635. target->Target->GetMakefile()->GetDefinition(option_flag)) {
  1636. std::vector<std::string> optVec;
  1637. cmSystemTools::ExpandListArgument(opt, optVec);
  1638. for (std::string const& i : optVec) {
  1639. this->AppendFlagEscape(flags, i);
  1640. }
  1641. }
  1642. }
  1643. return;
  1644. }
  1645. std::string const type = ext ? "EXTENSION" : "STANDARD";
  1646. if (target->GetPropertyAsBool(lang + "_STANDARD_REQUIRED")) {
  1647. std::string option_flag =
  1648. "CMAKE_" + lang + standardProp + "_" + type + "_COMPILE_OPTION";
  1649. const char* opt =
  1650. target->Target->GetMakefile()->GetDefinition(option_flag);
  1651. if (!opt) {
  1652. std::ostringstream e;
  1653. e << "Target \"" << target->GetName()
  1654. << "\" requires the language "
  1655. "dialect \""
  1656. << lang << standardProp << "\" "
  1657. << (ext ? "(with compiler extensions)" : "")
  1658. << ", but CMake "
  1659. "does not know the compile flags to use to enable it.";
  1660. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  1661. } else {
  1662. std::vector<std::string> optVec;
  1663. cmSystemTools::ExpandListArgument(opt, optVec);
  1664. for (std::string const& i : optVec) {
  1665. this->AppendFlagEscape(flags, i);
  1666. }
  1667. }
  1668. return;
  1669. }
  1670. static std::map<std::string, std::vector<std::string>> langStdMap;
  1671. if (langStdMap.empty()) {
  1672. // Maintain sorted order, most recent first.
  1673. langStdMap["CXX"].emplace_back("20");
  1674. langStdMap["CXX"].emplace_back("17");
  1675. langStdMap["CXX"].emplace_back("14");
  1676. langStdMap["CXX"].emplace_back("11");
  1677. langStdMap["CXX"].emplace_back("98");
  1678. langStdMap["C"].emplace_back("11");
  1679. langStdMap["C"].emplace_back("99");
  1680. langStdMap["C"].emplace_back("90");
  1681. langStdMap["CUDA"].emplace_back("14");
  1682. langStdMap["CUDA"].emplace_back("11");
  1683. langStdMap["CUDA"].emplace_back("98");
  1684. }
  1685. std::string standard(standardProp);
  1686. std::vector<std::string>& stds = langStdMap[lang];
  1687. std::vector<std::string>::const_iterator stdIt =
  1688. std::find(stds.begin(), stds.end(), standard);
  1689. if (stdIt == stds.end()) {
  1690. std::string e =
  1691. lang + "_STANDARD is set to invalid value '" + standard + "'";
  1692. this->GetGlobalGenerator()->GetCMakeInstance()->IssueMessage(
  1693. MessageType::FATAL_ERROR, e, target->GetBacktrace());
  1694. return;
  1695. }
  1696. std::vector<std::string>::const_iterator defaultStdIt =
  1697. std::find(stds.begin(), stds.end(), defaultStd);
  1698. if (defaultStdIt == stds.end()) {
  1699. std::string e = "CMAKE_" + lang +
  1700. "_STANDARD_DEFAULT is set to invalid value '" + std::string(defaultStd) +
  1701. "'";
  1702. this->IssueMessage(MessageType::INTERNAL_ERROR, e);
  1703. return;
  1704. }
  1705. // If the standard requested is older than the compiler's default
  1706. // then we need to use a flag to change it. The comparison is
  1707. // greater-or-equal because the standards are stored in backward
  1708. // chronological order.
  1709. if (stdIt >= defaultStdIt) {
  1710. std::string option_flag =
  1711. "CMAKE_" + lang + *stdIt + "_" + type + "_COMPILE_OPTION";
  1712. std::string const& opt =
  1713. target->Target->GetMakefile()->GetRequiredDefinition(option_flag);
  1714. std::vector<std::string> optVec;
  1715. cmSystemTools::ExpandListArgument(opt, optVec);
  1716. for (std::string const& i : optVec) {
  1717. this->AppendFlagEscape(flags, i);
  1718. }
  1719. return;
  1720. }
  1721. // The standard requested is at least as new as the compiler's default,
  1722. // and the standard request is not required. Decay to the newest standard
  1723. // for which a flag is defined.
  1724. for (; stdIt < defaultStdIt; ++stdIt) {
  1725. std::string option_flag =
  1726. "CMAKE_" + lang + *stdIt + "_" + type + "_COMPILE_OPTION";
  1727. if (const char* opt =
  1728. target->Target->GetMakefile()->GetDefinition(option_flag)) {
  1729. std::vector<std::string> optVec;
  1730. cmSystemTools::ExpandListArgument(opt, optVec);
  1731. for (std::string const& i : optVec) {
  1732. this->AppendFlagEscape(flags, i);
  1733. }
  1734. return;
  1735. }
  1736. }
  1737. }
  1738. static void AddVisibilityCompileOption(std::string& flags,
  1739. cmGeneratorTarget const* target,
  1740. cmLocalGenerator* lg,
  1741. const std::string& lang,
  1742. std::string* warnCMP0063)
  1743. {
  1744. std::string compileOption = "CMAKE_" + lang + "_COMPILE_OPTIONS_VISIBILITY";
  1745. const char* opt = lg->GetMakefile()->GetDefinition(compileOption);
  1746. if (!opt) {
  1747. return;
  1748. }
  1749. std::string flagDefine = lang + "_VISIBILITY_PRESET";
  1750. const char* prop = target->GetProperty(flagDefine);
  1751. if (!prop) {
  1752. return;
  1753. }
  1754. if (warnCMP0063) {
  1755. *warnCMP0063 += " " + flagDefine + "\n";
  1756. return;
  1757. }
  1758. if (strcmp(prop, "hidden") != 0 && strcmp(prop, "default") != 0 &&
  1759. strcmp(prop, "protected") != 0 && strcmp(prop, "internal") != 0) {
  1760. std::ostringstream e;
  1761. e << "Target " << target->GetName() << " uses unsupported value \"" << prop
  1762. << "\" for " << flagDefine << "."
  1763. << " The supported values are: default, hidden, protected, and "
  1764. "internal.";
  1765. cmSystemTools::Error(e.str());
  1766. return;
  1767. }
  1768. std::string option = std::string(opt) + prop;
  1769. lg->AppendFlags(flags, option);
  1770. }
  1771. static void AddInlineVisibilityCompileOption(std::string& flags,
  1772. cmGeneratorTarget const* target,
  1773. cmLocalGenerator* lg,
  1774. std::string* warnCMP0063)
  1775. {
  1776. std::string compileOption =
  1777. "CMAKE_CXX_COMPILE_OPTIONS_VISIBILITY_INLINES_HIDDEN";
  1778. const char* opt = lg->GetMakefile()->GetDefinition(compileOption);
  1779. if (!opt) {
  1780. return;
  1781. }
  1782. bool prop = target->GetPropertyAsBool("VISIBILITY_INLINES_HIDDEN");
  1783. if (!prop) {
  1784. return;
  1785. }
  1786. if (warnCMP0063) {
  1787. *warnCMP0063 += " VISIBILITY_INLINES_HIDDEN\n";
  1788. return;
  1789. }
  1790. lg->AppendFlags(flags, opt);
  1791. }
  1792. void cmLocalGenerator::AddVisibilityPresetFlags(
  1793. std::string& flags, cmGeneratorTarget const* target, const std::string& lang)
  1794. {
  1795. if (lang.empty()) {
  1796. return;
  1797. }
  1798. std::string warnCMP0063;
  1799. std::string* pWarnCMP0063 = nullptr;
  1800. if (target->GetType() != cmStateEnums::SHARED_LIBRARY &&
  1801. target->GetType() != cmStateEnums::MODULE_LIBRARY &&
  1802. !target->IsExecutableWithExports()) {
  1803. switch (target->GetPolicyStatusCMP0063()) {
  1804. case cmPolicies::OLD:
  1805. return;
  1806. case cmPolicies::WARN:
  1807. pWarnCMP0063 = &warnCMP0063;
  1808. break;
  1809. default:
  1810. break;
  1811. }
  1812. }
  1813. AddVisibilityCompileOption(flags, target, this, lang, pWarnCMP0063);
  1814. if (lang == "CXX") {
  1815. AddInlineVisibilityCompileOption(flags, target, this, pWarnCMP0063);
  1816. }
  1817. if (!warnCMP0063.empty() && this->WarnCMP0063.insert(target).second) {
  1818. std::ostringstream w;
  1819. /* clang-format off */
  1820. w <<
  1821. cmPolicies::GetPolicyWarning(cmPolicies::CMP0063) << "\n"
  1822. "Target \"" << target->GetName() << "\" of "
  1823. "type \"" << cmState::GetTargetTypeName(target->GetType()) << "\" "
  1824. "has the following visibility properties set for " << lang << ":\n" <<
  1825. warnCMP0063 <<
  1826. "For compatibility CMake is not honoring them for this target.";
  1827. /* clang-format on */
  1828. target->GetLocalGenerator()->GetCMakeInstance()->IssueMessage(
  1829. MessageType::AUTHOR_WARNING, w.str(), target->GetBacktrace());
  1830. }
  1831. }
  1832. void cmLocalGenerator::AddCMP0018Flags(std::string& flags,
  1833. cmGeneratorTarget const* target,
  1834. std::string const& lang,
  1835. const std::string& config)
  1836. {
  1837. int targetType = target->GetType();
  1838. bool shared = ((targetType == cmStateEnums::SHARED_LIBRARY) ||
  1839. (targetType == cmStateEnums::MODULE_LIBRARY));
  1840. if (this->GetShouldUseOldFlags(shared, lang)) {
  1841. this->AddSharedFlags(flags, lang, shared);
  1842. } else {
  1843. if (target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  1844. if (target->GetPropertyAsBool("POSITION_INDEPENDENT_CODE")) {
  1845. this->AddPositionIndependentFlags(flags, lang, targetType);
  1846. }
  1847. return;
  1848. }
  1849. if (target->GetLinkInterfaceDependentBoolProperty(
  1850. "POSITION_INDEPENDENT_CODE", config)) {
  1851. this->AddPositionIndependentFlags(flags, lang, targetType);
  1852. }
  1853. if (shared) {
  1854. this->AppendFeatureOptions(flags, lang, "DLL");
  1855. }
  1856. }
  1857. }
  1858. bool cmLocalGenerator::GetShouldUseOldFlags(bool shared,
  1859. const std::string& lang) const
  1860. {
  1861. std::string originalFlags =
  1862. this->GlobalGenerator->GetSharedLibFlagsForLanguage(lang);
  1863. if (shared) {
  1864. std::string flagsVar = "CMAKE_SHARED_LIBRARY_";
  1865. flagsVar += lang;
  1866. flagsVar += "_FLAGS";
  1867. std::string const& flags = this->Makefile->GetSafeDefinition(flagsVar);
  1868. if (flags != originalFlags) {
  1869. switch (this->GetPolicyStatus(cmPolicies::CMP0018)) {
  1870. case cmPolicies::WARN: {
  1871. std::ostringstream e;
  1872. e << "Variable " << flagsVar
  1873. << " has been modified. CMake "
  1874. "will ignore the POSITION_INDEPENDENT_CODE target property for "
  1875. "shared libraries and will use the "
  1876. << flagsVar
  1877. << " variable "
  1878. "instead. This may cause errors if the original content of "
  1879. << flagsVar << " was removed.\n"
  1880. << cmPolicies::GetPolicyWarning(cmPolicies::CMP0018);
  1881. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  1882. CM_FALLTHROUGH;
  1883. }
  1884. case cmPolicies::OLD:
  1885. return true;
  1886. case cmPolicies::REQUIRED_IF_USED:
  1887. case cmPolicies::REQUIRED_ALWAYS:
  1888. case cmPolicies::NEW:
  1889. return false;
  1890. }
  1891. }
  1892. }
  1893. return false;
  1894. }
  1895. void cmLocalGenerator::AddPositionIndependentFlags(std::string& flags,
  1896. std::string const& lang,
  1897. int targetType)
  1898. {
  1899. std::string picFlags;
  1900. if (targetType == cmStateEnums::EXECUTABLE) {
  1901. std::string flagsVar = "CMAKE_";
  1902. flagsVar += lang;
  1903. flagsVar += "_COMPILE_OPTIONS_PIE";
  1904. picFlags = this->Makefile->GetSafeDefinition(flagsVar);
  1905. }
  1906. if (picFlags.empty()) {
  1907. std::string flagsVar = "CMAKE_";
  1908. flagsVar += lang;
  1909. flagsVar += "_COMPILE_OPTIONS_PIC";
  1910. picFlags = this->Makefile->GetSafeDefinition(flagsVar);
  1911. }
  1912. if (!picFlags.empty()) {
  1913. std::vector<std::string> options;
  1914. cmSystemTools::ExpandListArgument(picFlags, options);
  1915. for (std::string const& o : options) {
  1916. this->AppendFlagEscape(flags, o);
  1917. }
  1918. }
  1919. }
  1920. void cmLocalGenerator::AddConfigVariableFlags(std::string& flags,
  1921. const std::string& var,
  1922. const std::string& config)
  1923. {
  1924. // Add the flags from the variable itself.
  1925. std::string flagsVar = var;
  1926. this->AppendFlags(flags, this->Makefile->GetDefinition(flagsVar));
  1927. // Add the flags from the build-type specific variable.
  1928. if (!config.empty()) {
  1929. flagsVar += "_";
  1930. flagsVar += cmSystemTools::UpperCase(config);
  1931. this->AppendFlags(flags, this->Makefile->GetDefinition(flagsVar));
  1932. }
  1933. }
  1934. void cmLocalGenerator::AppendFlags(std::string& flags,
  1935. const std::string& newFlags) const
  1936. {
  1937. if (!newFlags.empty()) {
  1938. if (!flags.empty()) {
  1939. flags += " ";
  1940. }
  1941. flags += newFlags;
  1942. }
  1943. }
  1944. void cmLocalGenerator::AppendFlags(std::string& flags,
  1945. const char* newFlags) const
  1946. {
  1947. if (newFlags && *newFlags) {
  1948. this->AppendFlags(flags, std::string(newFlags));
  1949. }
  1950. }
  1951. void cmLocalGenerator::AppendFlagEscape(std::string& flags,
  1952. const std::string& rawFlag) const
  1953. {
  1954. this->AppendFlags(flags, this->EscapeForShell(rawFlag));
  1955. }
  1956. void cmLocalGenerator::AppendIPOLinkerFlags(std::string& flags,
  1957. cmGeneratorTarget* target,
  1958. const std::string& config,
  1959. const std::string& lang)
  1960. {
  1961. if (!target->IsIPOEnabled(lang, config)) {
  1962. return;
  1963. }
  1964. switch (target->GetType()) {
  1965. case cmStateEnums::EXECUTABLE:
  1966. case cmStateEnums::SHARED_LIBRARY:
  1967. case cmStateEnums::MODULE_LIBRARY:
  1968. break;
  1969. default:
  1970. return;
  1971. }
  1972. const std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_IPO";
  1973. const char* rawFlagsList = this->Makefile->GetDefinition(name);
  1974. if (rawFlagsList == nullptr) {
  1975. return;
  1976. }
  1977. std::vector<std::string> flagsList;
  1978. cmSystemTools::ExpandListArgument(rawFlagsList, flagsList);
  1979. for (std::string const& o : flagsList) {
  1980. this->AppendFlagEscape(flags, o);
  1981. }
  1982. }
  1983. void cmLocalGenerator::AppendPositionIndependentLinkerFlags(
  1984. std::string& flags, cmGeneratorTarget* target, const std::string& config,
  1985. const std::string& lang)
  1986. {
  1987. // For now, only EXECUTABLE is concerned
  1988. if (target->GetType() != cmStateEnums::EXECUTABLE) {
  1989. return;
  1990. }
  1991. const char* PICValue = target->GetLinkPIEProperty(config);
  1992. if (PICValue == nullptr) {
  1993. // POSITION_INDEPENDENT_CODE is not set
  1994. return;
  1995. }
  1996. const std::string mode = cmSystemTools::IsOn(PICValue) ? "PIE" : "NO_PIE";
  1997. std::string supported = "CMAKE_" + lang + "_LINK_" + mode + "_SUPPORTED";
  1998. if (cmSystemTools::IsOff(this->Makefile->GetDefinition(supported))) {
  1999. return;
  2000. }
  2001. std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_" + mode;
  2002. auto pieFlags = this->Makefile->GetSafeDefinition(name);
  2003. if (pieFlags.empty()) {
  2004. return;
  2005. }
  2006. std::vector<std::string> flagsList;
  2007. cmSystemTools::ExpandListArgument(pieFlags, flagsList);
  2008. for (const auto& flag : flagsList) {
  2009. this->AppendFlagEscape(flags, flag);
  2010. }
  2011. }
  2012. void cmLocalGenerator::AppendCompileOptions(std::string& options,
  2013. const char* options_list,
  2014. const char* regex) const
  2015. {
  2016. // Short-circuit if there are no options.
  2017. if (!options_list) {
  2018. return;
  2019. }
  2020. // Expand the list of options.
  2021. std::vector<std::string> options_vec;
  2022. cmSystemTools::ExpandListArgument(options_list, options_vec);
  2023. this->AppendCompileOptions(options, options_vec, regex);
  2024. }
  2025. void cmLocalGenerator::AppendCompileOptions(
  2026. std::string& options, const std::vector<std::string>& options_vec,
  2027. const char* regex) const
  2028. {
  2029. if (regex != nullptr) {
  2030. // Filter flags upon specified reges.
  2031. cmsys::RegularExpression r(regex);
  2032. for (std::string const& opt : options_vec) {
  2033. if (r.find(opt)) {
  2034. this->AppendFlagEscape(options, opt);
  2035. }
  2036. }
  2037. } else {
  2038. for (std::string const& opt : options_vec) {
  2039. this->AppendFlagEscape(options, opt);
  2040. }
  2041. }
  2042. }
  2043. void cmLocalGenerator::AppendIncludeDirectories(
  2044. std::vector<std::string>& includes, const char* includes_list,
  2045. const cmSourceFile& sourceFile) const
  2046. {
  2047. // Short-circuit if there are no includes.
  2048. if (!includes_list) {
  2049. return;
  2050. }
  2051. // Expand the list of includes.
  2052. std::vector<std::string> includes_vec;
  2053. cmSystemTools::ExpandListArgument(includes_list, includes_vec);
  2054. this->AppendIncludeDirectories(includes, includes_vec, sourceFile);
  2055. }
  2056. void cmLocalGenerator::AppendIncludeDirectories(
  2057. std::vector<std::string>& includes,
  2058. const std::vector<std::string>& includes_vec,
  2059. const cmSourceFile& sourceFile) const
  2060. {
  2061. std::unordered_set<std::string> uniqueIncludes;
  2062. for (const std::string& include : includes_vec) {
  2063. if (!cmSystemTools::FileIsFullPath(include)) {
  2064. std::ostringstream e;
  2065. e << "Found relative path while evaluating include directories of "
  2066. "\""
  2067. << sourceFile.GetLocation().GetName() << "\":\n \"" << include
  2068. << "\"\n";
  2069. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2070. return;
  2071. }
  2072. std::string inc = include;
  2073. if (!cmSystemTools::IsOff(inc)) {
  2074. cmSystemTools::ConvertToUnixSlashes(inc);
  2075. }
  2076. if (uniqueIncludes.insert(inc).second) {
  2077. includes.push_back(std::move(inc));
  2078. }
  2079. }
  2080. }
  2081. void cmLocalGenerator::AppendDefines(std::set<std::string>& defines,
  2082. std::string const& defines_list) const
  2083. {
  2084. std::set<BT<std::string>> tmp;
  2085. this->AppendDefines(tmp, ExpandListWithBacktrace(defines_list));
  2086. for (BT<std::string> const& i : tmp) {
  2087. defines.emplace(i.Value);
  2088. }
  2089. }
  2090. void cmLocalGenerator::AppendDefines(std::set<BT<std::string>>& defines,
  2091. std::string const& defines_list) const
  2092. {
  2093. // Short-circuit if there are no definitions.
  2094. if (defines_list.empty()) {
  2095. return;
  2096. }
  2097. // Expand the list of definitions.
  2098. this->AppendDefines(defines, ExpandListWithBacktrace(defines_list));
  2099. }
  2100. void cmLocalGenerator::AppendDefines(
  2101. std::set<BT<std::string>>& defines,
  2102. const std::vector<BT<std::string>>& defines_vec) const
  2103. {
  2104. for (BT<std::string> const& d : defines_vec) {
  2105. // Skip unsupported definitions.
  2106. if (!this->CheckDefinition(d.Value)) {
  2107. continue;
  2108. }
  2109. defines.insert(d);
  2110. }
  2111. }
  2112. void cmLocalGenerator::JoinDefines(const std::set<std::string>& defines,
  2113. std::string& definesString,
  2114. const std::string& lang)
  2115. {
  2116. // Lookup the define flag for the current language.
  2117. std::string dflag = "-D";
  2118. if (!lang.empty()) {
  2119. std::string defineFlagVar = "CMAKE_";
  2120. defineFlagVar += lang;
  2121. defineFlagVar += "_DEFINE_FLAG";
  2122. const char* df = this->Makefile->GetDefinition(defineFlagVar);
  2123. if (df && *df) {
  2124. dflag = df;
  2125. }
  2126. }
  2127. const char* itemSeparator = definesString.empty() ? "" : " ";
  2128. for (std::string const& define : defines) {
  2129. // Append the definition with proper escaping.
  2130. std::string def = dflag;
  2131. if (this->GetState()->UseWatcomWMake()) {
  2132. // The Watcom compiler does its own command line parsing instead
  2133. // of using the windows shell rules. Definitions are one of
  2134. // -DNAME
  2135. // -DNAME=<cpp-token>
  2136. // -DNAME="c-string with spaces and other characters(?@#$)"
  2137. //
  2138. // Watcom will properly parse each of these cases from the
  2139. // command line without any escapes. However we still have to
  2140. // get the '$' and '#' characters through WMake as '$$' and
  2141. // '$#'.
  2142. for (const char* c = define.c_str(); *c; ++c) {
  2143. if (*c == '$' || *c == '#') {
  2144. def += '$';
  2145. }
  2146. def += *c;
  2147. }
  2148. } else {
  2149. // Make the definition appear properly on the command line. Use
  2150. // -DNAME="value" instead of -D"NAME=value" for historical reasons.
  2151. std::string::size_type eq = define.find('=');
  2152. def += define.substr(0, eq);
  2153. if (eq != std::string::npos) {
  2154. def += "=";
  2155. def += this->EscapeForShell(define.substr(eq + 1), true);
  2156. }
  2157. }
  2158. definesString += itemSeparator;
  2159. itemSeparator = " ";
  2160. definesString += def;
  2161. }
  2162. }
  2163. void cmLocalGenerator::AppendFeatureOptions(std::string& flags,
  2164. const std::string& lang,
  2165. const char* feature)
  2166. {
  2167. std::string optVar = "CMAKE_";
  2168. optVar += lang;
  2169. optVar += "_COMPILE_OPTIONS_";
  2170. optVar += feature;
  2171. if (const char* optionList = this->Makefile->GetDefinition(optVar)) {
  2172. std::vector<std::string> options;
  2173. cmSystemTools::ExpandListArgument(optionList, options);
  2174. for (std::string const& o : options) {
  2175. this->AppendFlagEscape(flags, o);
  2176. }
  2177. }
  2178. }
  2179. const char* cmLocalGenerator::GetFeature(const std::string& feature,
  2180. const std::string& config)
  2181. {
  2182. std::string featureName = feature;
  2183. // TODO: Define accumulation policy for features (prepend, append, replace).
  2184. // Currently we always replace.
  2185. if (!config.empty()) {
  2186. featureName += "_";
  2187. featureName += cmSystemTools::UpperCase(config);
  2188. }
  2189. cmStateSnapshot snp = this->StateSnapshot;
  2190. while (snp.IsValid()) {
  2191. if (const char* value = snp.GetDirectory().GetProperty(featureName)) {
  2192. return value;
  2193. }
  2194. snp = snp.GetBuildsystemDirectoryParent();
  2195. }
  2196. return nullptr;
  2197. }
  2198. std::string cmLocalGenerator::GetProjectName() const
  2199. {
  2200. return this->StateSnapshot.GetProjectName();
  2201. }
  2202. std::string cmLocalGenerator::ConstructComment(
  2203. cmCustomCommandGenerator const& ccg, const char* default_comment)
  2204. {
  2205. // Check for a comment provided with the command.
  2206. if (ccg.GetComment()) {
  2207. return ccg.GetComment();
  2208. }
  2209. // Construct a reasonable default comment if possible.
  2210. if (!ccg.GetOutputs().empty()) {
  2211. std::string comment;
  2212. comment = "Generating ";
  2213. const char* sep = "";
  2214. std::string currentBinaryDir = this->GetCurrentBinaryDirectory();
  2215. for (std::string const& o : ccg.GetOutputs()) {
  2216. comment += sep;
  2217. comment += this->MaybeConvertToRelativePath(currentBinaryDir, o);
  2218. sep = ", ";
  2219. }
  2220. return comment;
  2221. }
  2222. // Otherwise use the provided default.
  2223. return default_comment;
  2224. }
  2225. class cmInstallTargetGeneratorLocal : public cmInstallTargetGenerator
  2226. {
  2227. public:
  2228. cmInstallTargetGeneratorLocal(cmLocalGenerator* lg, std::string const& t,
  2229. const char* dest, bool implib)
  2230. : cmInstallTargetGenerator(
  2231. t, dest, implib, "", std::vector<std::string>(), "Unspecified",
  2232. cmInstallGenerator::SelectMessageLevel(lg->GetMakefile()), false,
  2233. false)
  2234. {
  2235. this->Compute(lg);
  2236. }
  2237. };
  2238. void cmLocalGenerator::GenerateTargetInstallRules(
  2239. std::ostream& os, const std::string& config,
  2240. std::vector<std::string> const& configurationTypes)
  2241. {
  2242. // Convert the old-style install specification from each target to
  2243. // an install generator and run it.
  2244. const std::vector<cmGeneratorTarget*>& tgts = this->GetGeneratorTargets();
  2245. for (cmGeneratorTarget* l : tgts) {
  2246. if (l->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  2247. continue;
  2248. }
  2249. // Include the user-specified pre-install script for this target.
  2250. if (const char* preinstall = l->GetProperty("PRE_INSTALL_SCRIPT")) {
  2251. cmInstallScriptGenerator g(preinstall, false, nullptr, false);
  2252. g.Generate(os, config, configurationTypes);
  2253. }
  2254. // Install this target if a destination is given.
  2255. if (!l->Target->GetInstallPath().empty()) {
  2256. // Compute the full install destination. Note that converting
  2257. // to unix slashes also removes any trailing slash.
  2258. // We also skip over the leading slash given by the user.
  2259. std::string destination = l->Target->GetInstallPath().substr(1);
  2260. cmSystemTools::ConvertToUnixSlashes(destination);
  2261. if (destination.empty()) {
  2262. destination = ".";
  2263. }
  2264. // Generate the proper install generator for this target type.
  2265. switch (l->GetType()) {
  2266. case cmStateEnums::EXECUTABLE:
  2267. case cmStateEnums::STATIC_LIBRARY:
  2268. case cmStateEnums::MODULE_LIBRARY: {
  2269. // Use a target install generator.
  2270. cmInstallTargetGeneratorLocal g(this, l->GetName(),
  2271. destination.c_str(), false);
  2272. g.Generate(os, config, configurationTypes);
  2273. } break;
  2274. case cmStateEnums::SHARED_LIBRARY: {
  2275. #if defined(_WIN32) || defined(__CYGWIN__)
  2276. // Special code to handle DLL. Install the import library
  2277. // to the normal destination and the DLL to the runtime
  2278. // destination.
  2279. cmInstallTargetGeneratorLocal g1(this, l->GetName(),
  2280. destination.c_str(), true);
  2281. g1.Generate(os, config, configurationTypes);
  2282. // We also skip over the leading slash given by the user.
  2283. destination = l->Target->GetRuntimeInstallPath().substr(1);
  2284. cmSystemTools::ConvertToUnixSlashes(destination);
  2285. cmInstallTargetGeneratorLocal g2(this, l->GetName(),
  2286. destination.c_str(), false);
  2287. g2.Generate(os, config, configurationTypes);
  2288. #else
  2289. // Use a target install generator.
  2290. cmInstallTargetGeneratorLocal g(this, l->GetName(),
  2291. destination.c_str(), false);
  2292. g.Generate(os, config, configurationTypes);
  2293. #endif
  2294. } break;
  2295. default:
  2296. break;
  2297. }
  2298. }
  2299. // Include the user-specified post-install script for this target.
  2300. if (const char* postinstall = l->GetProperty("POST_INSTALL_SCRIPT")) {
  2301. cmInstallScriptGenerator g(postinstall, false, nullptr, false);
  2302. g.Generate(os, config, configurationTypes);
  2303. }
  2304. }
  2305. }
  2306. #if defined(CM_LG_ENCODE_OBJECT_NAMES)
  2307. static bool cmLocalGeneratorShortenObjectName(std::string& objName,
  2308. std::string::size_type max_len)
  2309. {
  2310. // Replace the beginning of the path portion of the object name with
  2311. // its own md5 sum.
  2312. std::string::size_type pos =
  2313. objName.find('/', objName.size() - max_len + 32);
  2314. if (pos != std::string::npos) {
  2315. cmCryptoHash md5(cmCryptoHash::AlgoMD5);
  2316. std::string md5name = md5.HashString(objName.substr(0, pos));
  2317. md5name += objName.substr(pos);
  2318. objName = md5name;
  2319. // The object name is now short enough.
  2320. return true;
  2321. }
  2322. // The object name could not be shortened enough.
  2323. return false;
  2324. }
  2325. bool cmLocalGeneratorCheckObjectName(std::string& objName,
  2326. std::string::size_type dir_len,
  2327. std::string::size_type max_total_len)
  2328. {
  2329. // Enforce the maximum file name length if possible.
  2330. std::string::size_type max_obj_len = max_total_len;
  2331. if (dir_len < max_total_len) {
  2332. max_obj_len = max_total_len - dir_len;
  2333. if (objName.size() > max_obj_len) {
  2334. // The current object file name is too long. Try to shorten it.
  2335. return cmLocalGeneratorShortenObjectName(objName, max_obj_len);
  2336. }
  2337. // The object file name is short enough.
  2338. return true;
  2339. }
  2340. // The build directory in which the object will be stored is
  2341. // already too deep.
  2342. return false;
  2343. }
  2344. #endif
  2345. std::string& cmLocalGenerator::CreateSafeUniqueObjectFileName(
  2346. const std::string& sin, std::string const& dir_max)
  2347. {
  2348. // Look for an existing mapped name for this object file.
  2349. std::map<std::string, std::string>::iterator it =
  2350. this->UniqueObjectNamesMap.find(sin);
  2351. // If no entry exists create one.
  2352. if (it == this->UniqueObjectNamesMap.end()) {
  2353. // Start with the original name.
  2354. std::string ssin = sin;
  2355. // Avoid full paths by removing leading slashes.
  2356. ssin.erase(0, ssin.find_first_not_of('/'));
  2357. // Avoid full paths by removing colons.
  2358. std::replace(ssin.begin(), ssin.end(), ':', '_');
  2359. // Avoid relative paths that go up the tree.
  2360. cmSystemTools::ReplaceString(ssin, "../", "__/");
  2361. // Avoid spaces.
  2362. std::replace(ssin.begin(), ssin.end(), ' ', '_');
  2363. // Mangle the name if necessary.
  2364. if (this->Makefile->IsOn("CMAKE_MANGLE_OBJECT_FILE_NAMES")) {
  2365. bool done;
  2366. int cc = 0;
  2367. char rpstr[100];
  2368. sprintf(rpstr, "_p_");
  2369. cmSystemTools::ReplaceString(ssin, "+", rpstr);
  2370. std::string sssin = sin;
  2371. do {
  2372. done = true;
  2373. for (it = this->UniqueObjectNamesMap.begin();
  2374. it != this->UniqueObjectNamesMap.end(); ++it) {
  2375. if (it->second == ssin) {
  2376. done = false;
  2377. }
  2378. }
  2379. if (done) {
  2380. break;
  2381. }
  2382. sssin = ssin;
  2383. cmSystemTools::ReplaceString(ssin, "_p_", rpstr);
  2384. sprintf(rpstr, "_p%d_", cc++);
  2385. } while (!done);
  2386. }
  2387. #if defined(CM_LG_ENCODE_OBJECT_NAMES)
  2388. if (!cmLocalGeneratorCheckObjectName(ssin, dir_max.size(),
  2389. this->ObjectPathMax)) {
  2390. // Warn if this is the first time the path has been seen.
  2391. if (this->ObjectMaxPathViolations.insert(dir_max).second) {
  2392. std::ostringstream m;
  2393. /* clang-format off */
  2394. m << "The object file directory\n"
  2395. << " " << dir_max << "\n"
  2396. << "has " << dir_max.size() << " characters. "
  2397. << "The maximum full path to an object file is "
  2398. << this->ObjectPathMax << " characters "
  2399. << "(see CMAKE_OBJECT_PATH_MAX). "
  2400. << "Object file\n"
  2401. << " " << ssin << "\n"
  2402. << "cannot be safely placed under this directory. "
  2403. << "The build may not work correctly.";
  2404. /* clang-format on */
  2405. this->IssueMessage(MessageType::WARNING, m.str());
  2406. }
  2407. }
  2408. #else
  2409. (void)dir_max;
  2410. #endif
  2411. // Insert the newly mapped object file name.
  2412. std::map<std::string, std::string>::value_type e(sin, ssin);
  2413. it = this->UniqueObjectNamesMap.insert(e).first;
  2414. }
  2415. // Return the map entry.
  2416. return it->second;
  2417. }
  2418. void cmLocalGenerator::ComputeObjectFilenames(
  2419. std::map<cmSourceFile const*, std::string>& /*unused*/,
  2420. cmGeneratorTarget const* /*unused*/)
  2421. {
  2422. }
  2423. bool cmLocalGenerator::IsWindowsShell() const
  2424. {
  2425. return this->GetState()->UseWindowsShell();
  2426. }
  2427. bool cmLocalGenerator::IsWatcomWMake() const
  2428. {
  2429. return this->GetState()->UseWatcomWMake();
  2430. }
  2431. bool cmLocalGenerator::IsMinGWMake() const
  2432. {
  2433. return this->GetState()->UseMinGWMake();
  2434. }
  2435. bool cmLocalGenerator::IsNMake() const
  2436. {
  2437. return this->GetState()->UseNMake();
  2438. }
  2439. std::string cmLocalGenerator::GetObjectFileNameWithoutTarget(
  2440. const cmSourceFile& source, std::string const& dir_max,
  2441. bool* hasSourceExtension, char const* customOutputExtension)
  2442. {
  2443. // Construct the object file name using the full path to the source
  2444. // file which is its only unique identification.
  2445. std::string const& fullPath = source.GetFullPath();
  2446. // Try referencing the source relative to the source tree.
  2447. std::string relFromSource = this->MaybeConvertToRelativePath(
  2448. this->GetCurrentSourceDirectory(), fullPath);
  2449. assert(!relFromSource.empty());
  2450. bool relSource = !cmSystemTools::FileIsFullPath(relFromSource);
  2451. bool subSource = relSource && relFromSource[0] != '.';
  2452. // Try referencing the source relative to the binary tree.
  2453. std::string relFromBinary = this->MaybeConvertToRelativePath(
  2454. this->GetCurrentBinaryDirectory(), fullPath);
  2455. assert(!relFromBinary.empty());
  2456. bool relBinary = !cmSystemTools::FileIsFullPath(relFromBinary);
  2457. bool subBinary = relBinary && relFromBinary[0] != '.';
  2458. // Select a nice-looking reference to the source file to construct
  2459. // the object file name.
  2460. std::string objectName;
  2461. if ((relSource && !relBinary) || (subSource && !subBinary)) {
  2462. objectName = relFromSource;
  2463. } else if ((relBinary && !relSource) || (subBinary && !subSource)) {
  2464. objectName = relFromBinary;
  2465. } else if (relFromBinary.length() < relFromSource.length()) {
  2466. objectName = relFromBinary;
  2467. } else {
  2468. objectName = relFromSource;
  2469. }
  2470. // if it is still a full path check for the try compile case
  2471. // try compile never have in source sources, and should not
  2472. // have conflicting source file names in the same target
  2473. if (cmSystemTools::FileIsFullPath(objectName)) {
  2474. if (this->GetGlobalGenerator()->GetCMakeInstance()->GetIsInTryCompile()) {
  2475. objectName = cmSystemTools::GetFilenameName(source.GetFullPath());
  2476. }
  2477. }
  2478. // Replace the original source file extension with the object file
  2479. // extension.
  2480. bool keptSourceExtension = true;
  2481. if (!source.GetPropertyAsBool("KEEP_EXTENSION")) {
  2482. // Decide whether this language wants to replace the source
  2483. // extension with the object extension. For CMake 2.4
  2484. // compatibility do this by default.
  2485. bool replaceExt = this->NeedBackwardsCompatibility_2_4();
  2486. if (!replaceExt) {
  2487. std::string lang = source.GetLanguage();
  2488. if (!lang.empty()) {
  2489. std::string repVar = "CMAKE_";
  2490. repVar += lang;
  2491. repVar += "_OUTPUT_EXTENSION_REPLACE";
  2492. replaceExt = this->Makefile->IsOn(repVar);
  2493. }
  2494. }
  2495. // Remove the source extension if it is to be replaced.
  2496. if (replaceExt || customOutputExtension) {
  2497. keptSourceExtension = false;
  2498. std::string::size_type dot_pos = objectName.rfind('.');
  2499. if (dot_pos != std::string::npos) {
  2500. objectName = objectName.substr(0, dot_pos);
  2501. }
  2502. }
  2503. // Store the new extension.
  2504. if (customOutputExtension) {
  2505. objectName += customOutputExtension;
  2506. } else {
  2507. objectName += this->GlobalGenerator->GetLanguageOutputExtension(source);
  2508. }
  2509. }
  2510. if (hasSourceExtension) {
  2511. *hasSourceExtension = keptSourceExtension;
  2512. }
  2513. // Convert to a safe name.
  2514. return this->CreateSafeUniqueObjectFileName(objectName, dir_max);
  2515. }
  2516. std::string cmLocalGenerator::GetSourceFileLanguage(const cmSourceFile& source)
  2517. {
  2518. return source.GetLanguage();
  2519. }
  2520. cmake* cmLocalGenerator::GetCMakeInstance() const
  2521. {
  2522. return this->GlobalGenerator->GetCMakeInstance();
  2523. }
  2524. std::string const& cmLocalGenerator::GetSourceDirectory() const
  2525. {
  2526. return this->GetCMakeInstance()->GetHomeDirectory();
  2527. }
  2528. std::string const& cmLocalGenerator::GetBinaryDirectory() const
  2529. {
  2530. return this->GetCMakeInstance()->GetHomeOutputDirectory();
  2531. }
  2532. std::string const& cmLocalGenerator::GetCurrentBinaryDirectory() const
  2533. {
  2534. return this->StateSnapshot.GetDirectory().GetCurrentBinary();
  2535. }
  2536. std::string const& cmLocalGenerator::GetCurrentSourceDirectory() const
  2537. {
  2538. return this->StateSnapshot.GetDirectory().GetCurrentSource();
  2539. }
  2540. std::string cmLocalGenerator::MaybeConvertToRelativePath(
  2541. std::string const& local_path, std::string const& remote_path) const
  2542. {
  2543. return this->StateSnapshot.GetDirectory().ConvertToRelPathIfNotContained(
  2544. local_path, remote_path);
  2545. }
  2546. std::string cmLocalGenerator::GetTargetDirectory(
  2547. const cmGeneratorTarget* /*unused*/) const
  2548. {
  2549. cmSystemTools::Error("GetTargetDirectory"
  2550. " called on cmLocalGenerator");
  2551. return "";
  2552. }
  2553. KWIML_INT_uint64_t cmLocalGenerator::GetBackwardsCompatibility()
  2554. {
  2555. // The computed version may change until the project is fully
  2556. // configured.
  2557. if (!this->BackwardsCompatibilityFinal) {
  2558. unsigned int major = 0;
  2559. unsigned int minor = 0;
  2560. unsigned int patch = 0;
  2561. if (const char* value =
  2562. this->Makefile->GetDefinition("CMAKE_BACKWARDS_COMPATIBILITY")) {
  2563. switch (sscanf(value, "%u.%u.%u", &major, &minor, &patch)) {
  2564. case 2:
  2565. patch = 0;
  2566. break;
  2567. case 1:
  2568. minor = 0;
  2569. patch = 0;
  2570. break;
  2571. default:
  2572. break;
  2573. }
  2574. }
  2575. this->BackwardsCompatibility = CMake_VERSION_ENCODE(major, minor, patch);
  2576. this->BackwardsCompatibilityFinal = true;
  2577. }
  2578. return this->BackwardsCompatibility;
  2579. }
  2580. bool cmLocalGenerator::NeedBackwardsCompatibility_2_4()
  2581. {
  2582. // Check the policy to decide whether to pay attention to this
  2583. // variable.
  2584. switch (this->GetPolicyStatus(cmPolicies::CMP0001)) {
  2585. case cmPolicies::WARN:
  2586. // WARN is just OLD without warning because user code does not
  2587. // always affect whether this check is done.
  2588. case cmPolicies::OLD:
  2589. // Old behavior is to check the variable.
  2590. break;
  2591. case cmPolicies::NEW:
  2592. // New behavior is to ignore the variable.
  2593. return false;
  2594. case cmPolicies::REQUIRED_IF_USED:
  2595. case cmPolicies::REQUIRED_ALWAYS:
  2596. // This will never be the case because the only way to require
  2597. // the setting is to require the user to specify version policy
  2598. // 2.6 or higher. Once we add that requirement then this whole
  2599. // method can be removed anyway.
  2600. return false;
  2601. }
  2602. // Compatibility is needed if CMAKE_BACKWARDS_COMPATIBILITY is set
  2603. // equal to or lower than the given version.
  2604. KWIML_INT_uint64_t actual_compat = this->GetBackwardsCompatibility();
  2605. return (actual_compat && actual_compat <= CMake_VERSION_ENCODE(2, 4, 255));
  2606. }
  2607. cmPolicies::PolicyStatus cmLocalGenerator::GetPolicyStatus(
  2608. cmPolicies::PolicyID id) const
  2609. {
  2610. return this->Makefile->GetPolicyStatus(id);
  2611. }
  2612. bool cmLocalGenerator::CheckDefinition(std::string const& define) const
  2613. {
  2614. // Many compilers do not support -DNAME(arg)=sdf so we disable it.
  2615. std::string::size_type pos = define.find_first_of("(=");
  2616. if (pos != std::string::npos) {
  2617. if (define[pos] == '(') {
  2618. std::ostringstream e;
  2619. /* clang-format off */
  2620. e << "WARNING: Function-style preprocessor definitions may not be "
  2621. << "passed on the compiler command line because many compilers "
  2622. << "do not support it.\n"
  2623. << "CMake is dropping a preprocessor definition: " << define << "\n"
  2624. << "Consider defining the macro in a (configured) header file.\n";
  2625. /* clang-format on */
  2626. cmSystemTools::Message(e.str());
  2627. return false;
  2628. }
  2629. }
  2630. // Many compilers do not support # in the value so we disable it.
  2631. if (define.find_first_of('#') != std::string::npos) {
  2632. std::ostringstream e;
  2633. /* clang-format off */
  2634. e << "WARNING: Preprocessor definitions containing '#' may not be "
  2635. << "passed on the compiler command line because many compilers "
  2636. << "do not support it.\n"
  2637. << "CMake is dropping a preprocessor definition: " << define << "\n"
  2638. << "Consider defining the macro in a (configured) header file.\n";
  2639. /* clang-format on */
  2640. cmSystemTools::Message(e.str());
  2641. return false;
  2642. }
  2643. // Assume it is supported.
  2644. return true;
  2645. }
  2646. static void cmLGInfoProp(cmMakefile* mf, cmGeneratorTarget* target,
  2647. const std::string& prop)
  2648. {
  2649. if (const char* val = target->GetProperty(prop)) {
  2650. mf->AddDefinition(prop, val);
  2651. }
  2652. }
  2653. void cmLocalGenerator::GenerateAppleInfoPList(cmGeneratorTarget* target,
  2654. const std::string& targetName,
  2655. const std::string& fname)
  2656. {
  2657. // Find the Info.plist template.
  2658. const char* in = target->GetProperty("MACOSX_BUNDLE_INFO_PLIST");
  2659. std::string inFile = (in && *in) ? in : "MacOSXBundleInfo.plist.in";
  2660. if (!cmSystemTools::FileIsFullPath(inFile)) {
  2661. std::string inMod = this->Makefile->GetModulesFile(inFile);
  2662. if (!inMod.empty()) {
  2663. inFile = inMod;
  2664. }
  2665. }
  2666. if (!cmSystemTools::FileExists(inFile, true)) {
  2667. std::ostringstream e;
  2668. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  2669. << "\" could not be found.";
  2670. cmSystemTools::Error(e.str());
  2671. return;
  2672. }
  2673. // Convert target properties to variables in an isolated makefile
  2674. // scope to configure the file. If properties are set they will
  2675. // override user make variables. If not the configuration will fall
  2676. // back to the directory-level values set by the user.
  2677. cmMakefile* mf = this->Makefile;
  2678. cmMakefile::ScopePushPop varScope(mf);
  2679. mf->AddDefinition("MACOSX_BUNDLE_EXECUTABLE_NAME", targetName.c_str());
  2680. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_INFO_STRING");
  2681. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_ICON_FILE");
  2682. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_GUI_IDENTIFIER");
  2683. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_LONG_VERSION_STRING");
  2684. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_NAME");
  2685. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_SHORT_VERSION_STRING");
  2686. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_VERSION");
  2687. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_COPYRIGHT");
  2688. mf->ConfigureFile(inFile, fname, false, false, false);
  2689. }
  2690. void cmLocalGenerator::GenerateFrameworkInfoPList(
  2691. cmGeneratorTarget* target, const std::string& targetName,
  2692. const std::string& fname)
  2693. {
  2694. // Find the Info.plist template.
  2695. const char* in = target->GetProperty("MACOSX_FRAMEWORK_INFO_PLIST");
  2696. std::string inFile = (in && *in) ? in : "MacOSXFrameworkInfo.plist.in";
  2697. if (!cmSystemTools::FileIsFullPath(inFile)) {
  2698. std::string inMod = this->Makefile->GetModulesFile(inFile);
  2699. if (!inMod.empty()) {
  2700. inFile = inMod;
  2701. }
  2702. }
  2703. if (!cmSystemTools::FileExists(inFile, true)) {
  2704. std::ostringstream e;
  2705. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  2706. << "\" could not be found.";
  2707. cmSystemTools::Error(e.str());
  2708. return;
  2709. }
  2710. // Convert target properties to variables in an isolated makefile
  2711. // scope to configure the file. If properties are set they will
  2712. // override user make variables. If not the configuration will fall
  2713. // back to the directory-level values set by the user.
  2714. cmMakefile* mf = this->Makefile;
  2715. cmMakefile::ScopePushPop varScope(mf);
  2716. mf->AddDefinition("MACOSX_FRAMEWORK_NAME", targetName.c_str());
  2717. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_ICON_FILE");
  2718. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_IDENTIFIER");
  2719. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_SHORT_VERSION_STRING");
  2720. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_BUNDLE_VERSION");
  2721. mf->ConfigureFile(inFile, fname, false, false, false);
  2722. }