cmLocalGenerator.cxx 93 KB

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