cmLocalGenerator.cxx 108 KB

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