cmLocalGenerator.cxx 112 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269
  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::vector<BT<std::string>> tmpFlags;
  754. this->AddCompileOptions(tmpFlags, target, lang, config);
  755. this->AppendFlags(flags, tmpFlags);
  756. }
  757. void cmLocalGenerator::AddCompileOptions(std::vector<BT<std::string>>& flags,
  758. cmGeneratorTarget* target,
  759. const std::string& lang,
  760. const std::string& config)
  761. {
  762. std::string langFlagRegexVar = std::string("CMAKE_") + lang + "_FLAG_REGEX";
  763. if (const char* langFlagRegexStr =
  764. this->Makefile->GetDefinition(langFlagRegexVar)) {
  765. // Filter flags acceptable to this language.
  766. if (const char* targetFlags = target->GetProperty("COMPILE_FLAGS")) {
  767. std::vector<std::string> opts;
  768. cmSystemTools::ParseWindowsCommandLine(targetFlags, opts);
  769. // Re-escape these flags since COMPILE_FLAGS were already parsed
  770. // as a command line above.
  771. std::string compileOpts;
  772. this->AppendCompileOptions(compileOpts, opts, langFlagRegexStr);
  773. if (!compileOpts.empty()) {
  774. flags.emplace_back(std::move(compileOpts));
  775. }
  776. }
  777. std::vector<BT<std::string>> targetCompileOpts =
  778. target->GetCompileOptions(config, lang);
  779. // COMPILE_OPTIONS are escaped.
  780. this->AppendCompileOptions(flags, targetCompileOpts, langFlagRegexStr);
  781. } else {
  782. // Use all flags.
  783. if (const char* targetFlags = target->GetProperty("COMPILE_FLAGS")) {
  784. // COMPILE_FLAGS are not escaped for historical reasons.
  785. std::string compileFlags;
  786. this->AppendFlags(compileFlags, targetFlags);
  787. if (!compileFlags.empty()) {
  788. flags.emplace_back(std::move(compileFlags));
  789. }
  790. }
  791. std::vector<BT<std::string>> targetCompileOpts =
  792. target->GetCompileOptions(config, lang);
  793. // COMPILE_OPTIONS are escaped.
  794. this->AppendCompileOptions(flags, targetCompileOpts);
  795. }
  796. for (auto const& it : target->GetMaxLanguageStandards()) {
  797. const char* standard = target->GetProperty(it.first + "_STANDARD");
  798. if (!standard) {
  799. continue;
  800. }
  801. if (this->Makefile->IsLaterStandard(it.first, standard, it.second)) {
  802. std::ostringstream e;
  803. e << "The COMPILE_FEATURES property of target \"" << target->GetName()
  804. << "\" was evaluated when computing the link "
  805. "implementation, and the \""
  806. << it.first << "_STANDARD\" was \"" << it.second
  807. << "\" for that computation. Computing the "
  808. "COMPILE_FEATURES based on the link implementation resulted in a "
  809. "higher \""
  810. << it.first << "_STANDARD\" \"" << standard
  811. << "\". "
  812. "This is not permitted. The COMPILE_FEATURES may not both depend "
  813. "on "
  814. "and be depended on by the link implementation."
  815. << std::endl;
  816. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  817. return;
  818. }
  819. }
  820. std::string compReqFlag;
  821. this->AddCompilerRequirementFlag(compReqFlag, target, lang);
  822. if (!compReqFlag.empty()) {
  823. flags.emplace_back(std::move(compReqFlag));
  824. }
  825. // Add compile flag for the MSVC compiler only.
  826. cmMakefile* mf = this->GetMakefile();
  827. if (const char* jmc =
  828. mf->GetDefinition("CMAKE_" + lang + "_COMPILE_OPTIONS_JMC")) {
  829. // Handle Just My Code debugging flags, /JMC.
  830. // If the target is a Managed C++ one, /JMC is not compatible.
  831. if (target->GetManagedType(config) !=
  832. cmGeneratorTarget::ManagedType::Managed) {
  833. // add /JMC flags if target property VS_JUST_MY_CODE_DEBUGGING is set
  834. // to ON
  835. if (char const* jmcExprGen =
  836. target->GetProperty("VS_JUST_MY_CODE_DEBUGGING")) {
  837. cmGeneratorExpression ge;
  838. std::unique_ptr<cmCompiledGeneratorExpression> cge =
  839. ge.Parse(jmcExprGen);
  840. std::string isJMCEnabled = cge->Evaluate(this, config);
  841. if (cmIsOn(isJMCEnabled)) {
  842. std::vector<std::string> optVec = cmExpandedList(jmc);
  843. std::string jmcFlags;
  844. this->AppendCompileOptions(jmcFlags, optVec);
  845. if (!jmcFlags.empty()) {
  846. flags.emplace_back(std::move(jmcFlags));
  847. }
  848. }
  849. }
  850. }
  851. }
  852. }
  853. std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectoriesImplicit(
  854. cmGeneratorTarget const* target, std::string const& lang,
  855. std::string const& config, bool stripImplicitDirs,
  856. bool appendAllImplicitDirs) const
  857. {
  858. std::vector<BT<std::string>> result;
  859. // Do not repeat an include path.
  860. std::set<std::string> emitted;
  861. auto emitDir = [&result, &emitted](std::string const& dir) {
  862. if (emitted.insert(dir).second) {
  863. result.emplace_back(dir);
  864. }
  865. };
  866. auto emitBT = [&result, &emitted](BT<std::string> const& dir) {
  867. if (emitted.insert(dir.Value).second) {
  868. result.emplace_back(dir);
  869. }
  870. };
  871. // When automatic include directories are requested for a build then
  872. // include the source and binary directories at the beginning of the
  873. // include path to approximate include file behavior for an
  874. // in-source build. This does not account for the case of a source
  875. // file in a subdirectory of the current source directory but we
  876. // cannot fix this because not all native build tools support
  877. // per-source-file include paths.
  878. if (this->Makefile->IsOn("CMAKE_INCLUDE_CURRENT_DIR")) {
  879. // Current binary directory
  880. emitDir(this->StateSnapshot.GetDirectory().GetCurrentBinary());
  881. // Current source directory
  882. emitDir(this->StateSnapshot.GetDirectory().GetCurrentSource());
  883. }
  884. if (!target) {
  885. return result;
  886. }
  887. // Standard include directories to be added unconditionally at the end.
  888. // These are intended to simulate additional implicit include directories.
  889. std::vector<std::string> userStandardDirs;
  890. {
  891. std::string const value = this->Makefile->GetSafeDefinition(
  892. cmStrCat("CMAKE_", lang, "_STANDARD_INCLUDE_DIRECTORIES"));
  893. cmExpandList(value, userStandardDirs);
  894. for (std::string& usd : userStandardDirs) {
  895. cmSystemTools::ConvertToUnixSlashes(usd);
  896. }
  897. }
  898. // Implicit include directories
  899. std::vector<std::string> implicitDirs;
  900. std::set<std::string> implicitSet;
  901. // Include directories to be excluded as if they were implicit.
  902. std::set<std::string> implicitExclude;
  903. {
  904. // Raw list of implicit include directories
  905. // Start with "standard" directories that we unconditionally add below.
  906. std::vector<std::string> impDirVec = userStandardDirs;
  907. // Load implicit include directories for this language.
  908. // We ignore this for Fortran because:
  909. // * There are no standard library headers to avoid overriding.
  910. // * Compilers like gfortran do not search their own implicit include
  911. // directories for modules ('.mod' files).
  912. if (lang != "Fortran") {
  913. const char* value = this->Makefile->GetDefinition(
  914. cmStrCat("CMAKE_", lang, "_IMPLICIT_INCLUDE_DIRECTORIES"));
  915. if (value != nullptr) {
  916. size_t const impDirVecOldSize = impDirVec.size();
  917. cmExpandList(value, impDirVec);
  918. // FIXME: Use cmRange with 'advance()' when it supports non-const.
  919. for (size_t i = impDirVecOldSize; i < impDirVec.size(); ++i) {
  920. cmSystemTools::ConvertToUnixSlashes(impDirVec[i]);
  921. }
  922. }
  923. }
  924. // The Platform/UnixPaths module used to hard-code /usr/include for C, CXX,
  925. // and CUDA in CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES, but those
  926. // variables are now computed. On macOS the /usr/include directory is
  927. // inside the platform SDK so the computed value does not contain it
  928. // directly. In this case adding -I/usr/include can hide SDK headers so we
  929. // must still exclude it.
  930. if ((lang == "C" || lang == "CXX" || lang == "CUDA") &&
  931. !cmContains(impDirVec, "/usr/include") &&
  932. std::find_if(impDirVec.begin(), impDirVec.end(),
  933. [](std::string const& d) {
  934. return cmHasLiteralSuffix(d, "/usr/include");
  935. }) != impDirVec.end()) {
  936. // Only exclude this hard coded path for backwards compatibility.
  937. implicitExclude.emplace("/usr/include");
  938. }
  939. for (std::string const& i : impDirVec) {
  940. if (implicitSet.insert(cmSystemTools::GetRealPath(i)).second) {
  941. implicitDirs.emplace_back(i);
  942. }
  943. }
  944. }
  945. // Checks if this is not an excluded (implicit) include directory.
  946. auto notExcluded = [this, &implicitSet, &implicitExclude,
  947. &lang](std::string const& dir) {
  948. return (
  949. // Do not exclude directories that are not in an excluded set.
  950. ((!cmContains(implicitSet, cmSystemTools::GetRealPath(dir))) &&
  951. (!cmContains(implicitExclude, dir)))
  952. // Do not exclude entries of the CPATH environment variable even though
  953. // they are implicitly searched by the compiler. They are meant to be
  954. // user-specified directories that can be re-ordered or converted to
  955. // -isystem without breaking real compiler builtin headers.
  956. || ((lang == "C" || lang == "CXX") && cmContains(this->EnvCPATH, dir)));
  957. };
  958. // Get the target-specific include directories.
  959. std::vector<BT<std::string>> userDirs =
  960. target->GetIncludeDirectories(config, lang);
  961. // Support putting all the in-project include directories first if
  962. // it is requested by the project.
  963. if (this->Makefile->IsOn("CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE")) {
  964. std::string const& topSourceDir = this->GetState()->GetSourceDirectory();
  965. std::string const& topBinaryDir = this->GetState()->GetBinaryDirectory();
  966. for (BT<std::string> const& udr : userDirs) {
  967. // Emit this directory only if it is a subdirectory of the
  968. // top-level source or binary tree.
  969. if (cmSystemTools::ComparePath(udr.Value, topSourceDir) ||
  970. cmSystemTools::ComparePath(udr.Value, topBinaryDir) ||
  971. cmSystemTools::IsSubDirectory(udr.Value, topSourceDir) ||
  972. cmSystemTools::IsSubDirectory(udr.Value, topBinaryDir)) {
  973. if (notExcluded(udr.Value)) {
  974. emitBT(udr);
  975. }
  976. }
  977. }
  978. }
  979. // Emit remaining non implicit user direcories.
  980. for (BT<std::string> const& udr : userDirs) {
  981. if (notExcluded(udr.Value)) {
  982. emitBT(udr);
  983. }
  984. }
  985. // Sort result
  986. MoveSystemIncludesToEnd(result, config, lang, target);
  987. // Append standard include directories for this language.
  988. userDirs.reserve(userDirs.size() + userStandardDirs.size());
  989. for (std::string& usd : userStandardDirs) {
  990. emitDir(usd);
  991. userDirs.emplace_back(std::move(usd));
  992. }
  993. // Append compiler implicit include directories
  994. if (!stripImplicitDirs) {
  995. // Append implicit directories that were requested by the user only
  996. for (BT<std::string> const& udr : userDirs) {
  997. if (cmContains(implicitSet, cmSystemTools::GetRealPath(udr.Value))) {
  998. emitBT(udr);
  999. }
  1000. }
  1001. // Append remaining implicit directories (on demand)
  1002. if (appendAllImplicitDirs) {
  1003. for (std::string& imd : implicitDirs) {
  1004. emitDir(imd);
  1005. }
  1006. }
  1007. }
  1008. return result;
  1009. }
  1010. void cmLocalGenerator::GetIncludeDirectoriesImplicit(
  1011. std::vector<std::string>& dirs, cmGeneratorTarget const* target,
  1012. const std::string& lang, const std::string& config, bool stripImplicitDirs,
  1013. bool appendAllImplicitDirs) const
  1014. {
  1015. std::vector<BT<std::string>> tmp = this->GetIncludeDirectoriesImplicit(
  1016. target, lang, config, stripImplicitDirs, appendAllImplicitDirs);
  1017. dirs.reserve(dirs.size() + tmp.size());
  1018. for (BT<std::string>& v : tmp) {
  1019. dirs.emplace_back(std::move(v.Value));
  1020. }
  1021. }
  1022. std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectories(
  1023. cmGeneratorTarget const* target, std::string const& lang,
  1024. std::string const& config) const
  1025. {
  1026. return this->GetIncludeDirectoriesImplicit(target, lang, config);
  1027. }
  1028. void cmLocalGenerator::GetIncludeDirectories(std::vector<std::string>& dirs,
  1029. cmGeneratorTarget const* target,
  1030. const std::string& lang,
  1031. const std::string& config) const
  1032. {
  1033. this->GetIncludeDirectoriesImplicit(dirs, target, lang, config);
  1034. }
  1035. void cmLocalGenerator::GetStaticLibraryFlags(std::string& flags,
  1036. std::string const& config,
  1037. std::string const& linkLanguage,
  1038. cmGeneratorTarget* target)
  1039. {
  1040. std::vector<BT<std::string>> tmpFlags =
  1041. this->GetStaticLibraryFlags(config, linkLanguage, target);
  1042. this->AppendFlags(flags, tmpFlags);
  1043. }
  1044. std::vector<BT<std::string>> cmLocalGenerator::GetStaticLibraryFlags(
  1045. std::string const& config, std::string const& linkLanguage,
  1046. cmGeneratorTarget* target)
  1047. {
  1048. std::vector<BT<std::string>> flags;
  1049. if (linkLanguage != "Swift") {
  1050. std::string staticLibFlags;
  1051. this->AppendFlags(
  1052. staticLibFlags,
  1053. this->Makefile->GetSafeDefinition("CMAKE_STATIC_LINKER_FLAGS"));
  1054. if (!config.empty()) {
  1055. std::string name = "CMAKE_STATIC_LINKER_FLAGS_" + config;
  1056. this->AppendFlags(staticLibFlags,
  1057. this->Makefile->GetSafeDefinition(name));
  1058. }
  1059. if (!staticLibFlags.empty()) {
  1060. flags.emplace_back(std::move(staticLibFlags));
  1061. }
  1062. }
  1063. std::string staticLibFlags;
  1064. this->AppendFlags(staticLibFlags,
  1065. target->GetSafeProperty("STATIC_LIBRARY_FLAGS"));
  1066. if (!config.empty()) {
  1067. std::string name = "STATIC_LIBRARY_FLAGS_" + config;
  1068. this->AppendFlags(staticLibFlags, target->GetSafeProperty(name));
  1069. }
  1070. if (!staticLibFlags.empty()) {
  1071. flags.emplace_back(std::move(staticLibFlags));
  1072. }
  1073. std::vector<BT<std::string>> staticLibOpts =
  1074. target->GetStaticLibraryLinkOptions(config, linkLanguage);
  1075. // STATIC_LIBRARY_OPTIONS are escaped.
  1076. this->AppendCompileOptions(flags, staticLibOpts);
  1077. return flags;
  1078. }
  1079. void cmLocalGenerator::GetTargetFlags(
  1080. cmLinkLineComputer* linkLineComputer, const std::string& config,
  1081. std::string& linkLibs, std::string& flags, std::string& linkFlags,
  1082. std::string& frameworkPath, std::string& linkPath, cmGeneratorTarget* target)
  1083. {
  1084. std::vector<BT<std::string>> tmpLinkFlags;
  1085. this->GetTargetFlags(linkLineComputer, config, linkLibs, flags, tmpLinkFlags,
  1086. frameworkPath, linkPath, target);
  1087. this->AppendFlags(linkFlags, tmpLinkFlags);
  1088. }
  1089. void cmLocalGenerator::GetTargetFlags(
  1090. cmLinkLineComputer* linkLineComputer, const std::string& config,
  1091. std::string& linkLibs, std::string& flags,
  1092. std::vector<BT<std::string>>& linkFlags, std::string& frameworkPath,
  1093. std::string& linkPath, cmGeneratorTarget* target)
  1094. {
  1095. const std::string buildType = cmSystemTools::UpperCase(config);
  1096. cmComputeLinkInformation* pcli = target->GetLinkInformation(config);
  1097. const char* libraryLinkVariable =
  1098. "CMAKE_SHARED_LINKER_FLAGS"; // default to shared library
  1099. const std::string linkLanguage =
  1100. linkLineComputer->GetLinkerLanguage(target, buildType);
  1101. switch (target->GetType()) {
  1102. case cmStateEnums::STATIC_LIBRARY:
  1103. linkFlags = this->GetStaticLibraryFlags(buildType, linkLanguage, target);
  1104. if (pcli && dynamic_cast<cmLinkLineDeviceComputer*>(linkLineComputer)) {
  1105. // Compute the required cuda device link libraries when
  1106. // resolving cuda device symbols
  1107. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1108. frameworkPath, linkPath);
  1109. }
  1110. break;
  1111. case cmStateEnums::MODULE_LIBRARY:
  1112. libraryLinkVariable = "CMAKE_MODULE_LINKER_FLAGS";
  1113. CM_FALLTHROUGH;
  1114. case cmStateEnums::SHARED_LIBRARY: {
  1115. std::string sharedLibFlags;
  1116. if (linkLanguage != "Swift") {
  1117. sharedLibFlags = cmStrCat(
  1118. this->Makefile->GetSafeDefinition(libraryLinkVariable), ' ');
  1119. if (!buildType.empty()) {
  1120. std::string build = cmStrCat(libraryLinkVariable, '_', buildType);
  1121. sharedLibFlags += this->Makefile->GetSafeDefinition(build);
  1122. sharedLibFlags += " ";
  1123. }
  1124. if (this->Makefile->IsOn("WIN32") &&
  1125. !(this->Makefile->IsOn("CYGWIN") ||
  1126. this->Makefile->IsOn("MINGW"))) {
  1127. std::vector<cmSourceFile*> sources;
  1128. target->GetSourceFiles(sources, buildType);
  1129. std::string defFlag =
  1130. this->Makefile->GetSafeDefinition("CMAKE_LINK_DEF_FILE_FLAG");
  1131. for (cmSourceFile* sf : sources) {
  1132. if (sf->GetExtension() == "def") {
  1133. sharedLibFlags += defFlag;
  1134. sharedLibFlags += this->ConvertToOutputFormat(
  1135. cmSystemTools::CollapseFullPath(sf->ResolveFullPath()), SHELL);
  1136. sharedLibFlags += " ";
  1137. }
  1138. }
  1139. }
  1140. }
  1141. const char* targetLinkFlags = target->GetProperty("LINK_FLAGS");
  1142. if (targetLinkFlags) {
  1143. sharedLibFlags += targetLinkFlags;
  1144. sharedLibFlags += " ";
  1145. }
  1146. if (!buildType.empty()) {
  1147. targetLinkFlags =
  1148. target->GetProperty(cmStrCat("LINK_FLAGS_", buildType));
  1149. if (targetLinkFlags) {
  1150. sharedLibFlags += targetLinkFlags;
  1151. sharedLibFlags += " ";
  1152. }
  1153. }
  1154. if (!sharedLibFlags.empty()) {
  1155. linkFlags.emplace_back(std::move(sharedLibFlags));
  1156. }
  1157. std::vector<BT<std::string>> linkOpts =
  1158. target->GetLinkOptions(config, linkLanguage);
  1159. // LINK_OPTIONS are escaped.
  1160. this->AppendCompileOptions(linkFlags, linkOpts);
  1161. if (pcli) {
  1162. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1163. frameworkPath, linkPath);
  1164. }
  1165. } break;
  1166. case cmStateEnums::EXECUTABLE: {
  1167. std::string exeFlags;
  1168. if (linkLanguage != "Swift") {
  1169. exeFlags = this->Makefile->GetSafeDefinition("CMAKE_EXE_LINKER_FLAGS");
  1170. exeFlags += " ";
  1171. if (!buildType.empty()) {
  1172. exeFlags += this->Makefile->GetSafeDefinition(
  1173. cmStrCat("CMAKE_EXE_LINKER_FLAGS_", buildType));
  1174. exeFlags += " ";
  1175. }
  1176. if (linkLanguage.empty()) {
  1177. cmSystemTools::Error(
  1178. "CMake can not determine linker language for target: " +
  1179. target->GetName());
  1180. return;
  1181. }
  1182. if (target->GetPropertyAsBool("WIN32_EXECUTABLE")) {
  1183. exeFlags +=
  1184. this->Makefile->GetSafeDefinition("CMAKE_CREATE_WIN32_EXE");
  1185. exeFlags += " ";
  1186. } else {
  1187. exeFlags +=
  1188. this->Makefile->GetSafeDefinition("CMAKE_CREATE_CONSOLE_EXE");
  1189. exeFlags += " ";
  1190. }
  1191. if (target->IsExecutableWithExports()) {
  1192. exeFlags += this->Makefile->GetSafeDefinition(
  1193. cmStrCat("CMAKE_EXE_EXPORTS_", linkLanguage, "_FLAG"));
  1194. exeFlags += " ";
  1195. }
  1196. }
  1197. this->AddLanguageFlagsForLinking(flags, target, linkLanguage, buildType);
  1198. if (pcli) {
  1199. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1200. frameworkPath, linkPath);
  1201. }
  1202. if (cmIsOn(this->Makefile->GetDefinition("BUILD_SHARED_LIBS"))) {
  1203. std::string sFlagVar = std::string("CMAKE_SHARED_BUILD_") +
  1204. linkLanguage + std::string("_FLAGS");
  1205. exeFlags += this->Makefile->GetSafeDefinition(sFlagVar);
  1206. exeFlags += " ";
  1207. }
  1208. std::string cmp0065Flags =
  1209. this->GetLinkLibsCMP0065(linkLanguage, *target);
  1210. if (!cmp0065Flags.empty()) {
  1211. exeFlags += cmp0065Flags;
  1212. exeFlags += " ";
  1213. }
  1214. const char* targetLinkFlags = target->GetProperty("LINK_FLAGS");
  1215. if (targetLinkFlags) {
  1216. exeFlags += targetLinkFlags;
  1217. exeFlags += " ";
  1218. }
  1219. if (!buildType.empty()) {
  1220. targetLinkFlags =
  1221. target->GetProperty(cmStrCat("LINK_FLAGS_", buildType));
  1222. if (targetLinkFlags) {
  1223. exeFlags += targetLinkFlags;
  1224. exeFlags += " ";
  1225. }
  1226. }
  1227. if (!exeFlags.empty()) {
  1228. linkFlags.emplace_back(std::move(exeFlags));
  1229. }
  1230. std::vector<BT<std::string>> linkOpts =
  1231. target->GetLinkOptions(config, linkLanguage);
  1232. // LINK_OPTIONS are escaped.
  1233. this->AppendCompileOptions(linkFlags, linkOpts);
  1234. } break;
  1235. default:
  1236. break;
  1237. }
  1238. std::string extraLinkFlags;
  1239. this->AppendPositionIndependentLinkerFlags(extraLinkFlags, target, config,
  1240. linkLanguage);
  1241. this->AppendIPOLinkerFlags(extraLinkFlags, target, config, linkLanguage);
  1242. if (!extraLinkFlags.empty()) {
  1243. linkFlags.emplace_back(std::move(extraLinkFlags));
  1244. }
  1245. }
  1246. void cmLocalGenerator::GetTargetCompileFlags(cmGeneratorTarget* target,
  1247. std::string const& config,
  1248. std::string const& lang,
  1249. std::string& flags)
  1250. {
  1251. std::vector<BT<std::string>> tmpFlags =
  1252. this->GetTargetCompileFlags(target, config, lang);
  1253. this->AppendFlags(flags, tmpFlags);
  1254. }
  1255. std::vector<BT<std::string>> cmLocalGenerator::GetTargetCompileFlags(
  1256. cmGeneratorTarget* target, std::string const& config,
  1257. std::string const& lang)
  1258. {
  1259. std::vector<BT<std::string>> flags;
  1260. std::string compileFlags;
  1261. cmMakefile* mf = this->GetMakefile();
  1262. // Add language-specific flags.
  1263. this->AddLanguageFlags(compileFlags, target, lang, config);
  1264. if (target->IsIPOEnabled(lang, config)) {
  1265. this->AppendFeatureOptions(compileFlags, lang, "IPO");
  1266. }
  1267. this->AddArchitectureFlags(compileFlags, target, lang, config);
  1268. if (lang == "Fortran") {
  1269. this->AppendFlags(compileFlags,
  1270. this->GetTargetFortranFlags(target, config));
  1271. }
  1272. this->AddCMP0018Flags(compileFlags, target, lang, config);
  1273. this->AddVisibilityPresetFlags(compileFlags, target, lang);
  1274. this->AppendFlags(compileFlags, mf->GetDefineFlags());
  1275. this->AppendFlags(compileFlags,
  1276. this->GetFrameworkFlags(lang, config, target));
  1277. if (!compileFlags.empty()) {
  1278. flags.emplace_back(std::move(compileFlags));
  1279. }
  1280. this->AddCompileOptions(flags, target, lang, config);
  1281. return flags;
  1282. }
  1283. static std::string GetFrameworkFlags(const std::string& lang,
  1284. const std::string& config,
  1285. cmGeneratorTarget* target)
  1286. {
  1287. cmLocalGenerator* lg = target->GetLocalGenerator();
  1288. cmMakefile* mf = lg->GetMakefile();
  1289. if (!mf->IsOn("APPLE")) {
  1290. return std::string();
  1291. }
  1292. std::string fwSearchFlagVar = "CMAKE_" + lang + "_FRAMEWORK_SEARCH_FLAG";
  1293. const char* fwSearchFlag = mf->GetDefinition(fwSearchFlagVar);
  1294. if (!(fwSearchFlag && *fwSearchFlag)) {
  1295. return std::string();
  1296. }
  1297. std::set<std::string> emitted;
  1298. #ifdef __APPLE__ /* don't insert this when crosscompiling e.g. to iphone */
  1299. emitted.insert("/System/Library/Frameworks");
  1300. #endif
  1301. std::vector<std::string> includes;
  1302. lg->GetIncludeDirectories(includes, target, "C", config);
  1303. // check all include directories for frameworks as this
  1304. // will already have added a -F for the framework
  1305. for (std::string const& include : includes) {
  1306. if (lg->GetGlobalGenerator()->NameResolvesToFramework(include)) {
  1307. std::string frameworkDir = cmStrCat(include, "/../");
  1308. frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
  1309. emitted.insert(frameworkDir);
  1310. }
  1311. }
  1312. std::string flags;
  1313. if (cmComputeLinkInformation* cli = target->GetLinkInformation(config)) {
  1314. std::vector<std::string> const& frameworks = cli->GetFrameworkPaths();
  1315. for (std::string const& framework : frameworks) {
  1316. if (emitted.insert(framework).second) {
  1317. flags += fwSearchFlag;
  1318. flags +=
  1319. lg->ConvertToOutputFormat(framework, cmOutputConverter::SHELL);
  1320. flags += " ";
  1321. }
  1322. }
  1323. }
  1324. return flags;
  1325. }
  1326. std::string cmLocalGenerator::GetFrameworkFlags(std::string const& l,
  1327. std::string const& config,
  1328. cmGeneratorTarget* target)
  1329. {
  1330. return ::GetFrameworkFlags(l, config, target);
  1331. }
  1332. void cmLocalGenerator::GetTargetDefines(cmGeneratorTarget const* target,
  1333. std::string const& config,
  1334. std::string const& lang,
  1335. std::set<std::string>& defines) const
  1336. {
  1337. std::set<BT<std::string>> tmp = this->GetTargetDefines(target, config, lang);
  1338. for (BT<std::string> const& v : tmp) {
  1339. defines.emplace(v.Value);
  1340. }
  1341. }
  1342. std::set<BT<std::string>> cmLocalGenerator::GetTargetDefines(
  1343. cmGeneratorTarget const* target, std::string const& config,
  1344. std::string const& lang) const
  1345. {
  1346. std::set<BT<std::string>> defines;
  1347. // Add the export symbol definition for shared library objects.
  1348. if (const std::string* exportMacro = target->GetExportMacro()) {
  1349. this->AppendDefines(defines, *exportMacro);
  1350. }
  1351. // Add preprocessor definitions for this target and configuration.
  1352. std::vector<BT<std::string>> targetDefines =
  1353. target->GetCompileDefinitions(config, lang);
  1354. this->AppendDefines(defines, targetDefines);
  1355. return defines;
  1356. }
  1357. std::string cmLocalGenerator::GetTargetFortranFlags(
  1358. cmGeneratorTarget const* /*unused*/, std::string const& /*unused*/)
  1359. {
  1360. // Implemented by specific generators that override this.
  1361. return std::string();
  1362. }
  1363. /**
  1364. * Output the linking rules on a command line. For executables,
  1365. * targetLibrary should be a NULL pointer. For libraries, it should point
  1366. * to the name of the library. This will not link a library against itself.
  1367. */
  1368. void cmLocalGenerator::OutputLinkLibraries(
  1369. cmComputeLinkInformation* pcli, cmLinkLineComputer* linkLineComputer,
  1370. std::string& linkLibraries, std::string& frameworkPath,
  1371. std::string& linkPath)
  1372. {
  1373. cmComputeLinkInformation& cli = *pcli;
  1374. std::string linkLanguage = cli.GetLinkLanguage();
  1375. std::string libPathFlag;
  1376. if (const char* value = this->Makefile->GetDefinition(
  1377. "CMAKE_" + cli.GetLinkLanguage() + "_LIBRARY_PATH_FLAG")) {
  1378. libPathFlag = value;
  1379. } else {
  1380. libPathFlag =
  1381. this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_FLAG");
  1382. }
  1383. std::string libPathTerminator;
  1384. if (const char* value = this->Makefile->GetDefinition(
  1385. "CMAKE_" + cli.GetLinkLanguage() + "_LIBRARY_PATH_TERMINATOR")) {
  1386. libPathTerminator = value;
  1387. } else {
  1388. libPathTerminator =
  1389. this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_TERMINATOR");
  1390. }
  1391. // Add standard libraries for this language.
  1392. std::string stdLibString = this->Makefile->GetSafeDefinition(
  1393. cmStrCat("CMAKE_", cli.GetLinkLanguage(), "_STANDARD_LIBRARIES"));
  1394. // Append the framework search path flags.
  1395. std::string fwSearchFlag = this->Makefile->GetSafeDefinition(
  1396. cmStrCat("CMAKE_", linkLanguage, "_FRAMEWORK_SEARCH_FLAG"));
  1397. frameworkPath = linkLineComputer->ComputeFrameworkPath(cli, fwSearchFlag);
  1398. linkPath =
  1399. linkLineComputer->ComputeLinkPath(cli, libPathFlag, libPathTerminator);
  1400. linkLibraries = linkLineComputer->ComputeLinkLibraries(cli, stdLibString);
  1401. }
  1402. std::string cmLocalGenerator::GetLinkLibsCMP0065(
  1403. std::string const& linkLanguage, cmGeneratorTarget& tgt) const
  1404. {
  1405. std::string linkFlags;
  1406. // Flags to link an executable to shared libraries.
  1407. if (tgt.GetType() == cmStateEnums::EXECUTABLE &&
  1408. this->StateSnapshot.GetState()->GetGlobalPropertyAsBool(
  1409. "TARGET_SUPPORTS_SHARED_LIBS")) {
  1410. bool add_shlib_flags = false;
  1411. switch (tgt.GetPolicyStatusCMP0065()) {
  1412. case cmPolicies::WARN:
  1413. if (!tgt.GetPropertyAsBool("ENABLE_EXPORTS") &&
  1414. this->Makefile->PolicyOptionalWarningEnabled(
  1415. "CMAKE_POLICY_WARNING_CMP0065")) {
  1416. std::ostringstream w;
  1417. /* clang-format off */
  1418. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0065) << "\n"
  1419. "For compatibility with older versions of CMake, "
  1420. "additional flags may be added to export symbols on all "
  1421. "executables regardless of their ENABLE_EXPORTS property.";
  1422. /* clang-format on */
  1423. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  1424. }
  1425. CM_FALLTHROUGH;
  1426. case cmPolicies::OLD:
  1427. // OLD behavior is to always add the flags, except on AIX where
  1428. // we compute symbol exports if ENABLE_EXPORTS is on.
  1429. add_shlib_flags =
  1430. !(tgt.Target->IsAIX() && tgt.GetPropertyAsBool("ENABLE_EXPORTS"));
  1431. break;
  1432. case cmPolicies::REQUIRED_IF_USED:
  1433. case cmPolicies::REQUIRED_ALWAYS:
  1434. this->IssueMessage(
  1435. MessageType::FATAL_ERROR,
  1436. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0065));
  1437. CM_FALLTHROUGH;
  1438. case cmPolicies::NEW:
  1439. // NEW behavior is to only add the flags if ENABLE_EXPORTS is on,
  1440. // except on AIX where we compute symbol exports.
  1441. add_shlib_flags =
  1442. !tgt.Target->IsAIX() && tgt.GetPropertyAsBool("ENABLE_EXPORTS");
  1443. break;
  1444. }
  1445. if (add_shlib_flags) {
  1446. linkFlags = this->Makefile->GetSafeDefinition(
  1447. cmStrCat("CMAKE_SHARED_LIBRARY_LINK_", linkLanguage, "_FLAGS"));
  1448. }
  1449. }
  1450. return linkFlags;
  1451. }
  1452. void cmLocalGenerator::AddArchitectureFlags(std::string& flags,
  1453. cmGeneratorTarget const* target,
  1454. const std::string& lang,
  1455. const std::string& config)
  1456. {
  1457. // Only add macOS specific flags on Darwin platforms (macOS and iOS):
  1458. if (this->Makefile->IsOn("APPLE") && this->EmitUniversalBinaryFlags) {
  1459. std::vector<std::string> archs;
  1460. target->GetAppleArchs(config, archs);
  1461. const char* sysroot = this->Makefile->GetDefinition("CMAKE_OSX_SYSROOT");
  1462. if (sysroot && sysroot[0] == '/' && !sysroot[1]) {
  1463. sysroot = nullptr;
  1464. }
  1465. std::string sysrootFlagVar =
  1466. std::string("CMAKE_") + lang + "_SYSROOT_FLAG";
  1467. const char* sysrootFlag = this->Makefile->GetDefinition(sysrootFlagVar);
  1468. const char* deploymentTarget =
  1469. this->Makefile->GetDefinition("CMAKE_OSX_DEPLOYMENT_TARGET");
  1470. std::string deploymentTargetFlagVar =
  1471. std::string("CMAKE_") + lang + "_OSX_DEPLOYMENT_TARGET_FLAG";
  1472. const char* deploymentTargetFlag =
  1473. this->Makefile->GetDefinition(deploymentTargetFlagVar);
  1474. if (!archs.empty() && !lang.empty() &&
  1475. (lang[0] == 'C' || lang[0] == 'F')) {
  1476. for (std::string const& arch : archs) {
  1477. flags += " -arch ";
  1478. flags += arch;
  1479. }
  1480. }
  1481. if (sysrootFlag && *sysrootFlag && sysroot && *sysroot) {
  1482. flags += " ";
  1483. flags += sysrootFlag;
  1484. flags += " ";
  1485. flags += this->ConvertToOutputFormat(sysroot, SHELL);
  1486. }
  1487. if (deploymentTargetFlag && *deploymentTargetFlag && deploymentTarget &&
  1488. *deploymentTarget) {
  1489. flags += " ";
  1490. flags += deploymentTargetFlag;
  1491. flags += deploymentTarget;
  1492. }
  1493. }
  1494. }
  1495. void cmLocalGenerator::AddLanguageFlags(std::string& flags,
  1496. cmGeneratorTarget const* target,
  1497. const std::string& lang,
  1498. const std::string& config)
  1499. {
  1500. // Add language-specific flags.
  1501. this->AddConfigVariableFlags(flags, cmStrCat("CMAKE_", lang, "_FLAGS"),
  1502. config);
  1503. if (lang == "Swift") {
  1504. if (const char* v = target->GetProperty("Swift_LANGUAGE_VERSION")) {
  1505. if (cmSystemTools::VersionCompare(
  1506. cmSystemTools::OP_GREATER_EQUAL,
  1507. this->Makefile->GetDefinition("CMAKE_Swift_COMPILER_VERSION"),
  1508. "4.2")) {
  1509. this->AppendFlags(flags, "-swift-version " + std::string(v));
  1510. }
  1511. }
  1512. }
  1513. // Add MSVC runtime library flags. This is activated by the presence
  1514. // of a default selection whether or not it is overridden by a property.
  1515. const char* msvcRuntimeLibraryDefault =
  1516. this->Makefile->GetDefinition("CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT");
  1517. if (msvcRuntimeLibraryDefault && *msvcRuntimeLibraryDefault) {
  1518. const char* msvcRuntimeLibraryValue =
  1519. target->GetProperty("MSVC_RUNTIME_LIBRARY");
  1520. if (!msvcRuntimeLibraryValue) {
  1521. msvcRuntimeLibraryValue = msvcRuntimeLibraryDefault;
  1522. }
  1523. cmGeneratorExpression ge;
  1524. std::unique_ptr<cmCompiledGeneratorExpression> cge =
  1525. ge.Parse(msvcRuntimeLibraryValue);
  1526. std::string const msvcRuntimeLibrary =
  1527. cge->Evaluate(this, config, false, target);
  1528. if (!msvcRuntimeLibrary.empty()) {
  1529. if (const char* msvcRuntimeLibraryOptions =
  1530. this->Makefile->GetDefinition(
  1531. "CMAKE_" + lang + "_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_" +
  1532. msvcRuntimeLibrary)) {
  1533. this->AppendCompileOptions(flags, msvcRuntimeLibraryOptions);
  1534. } else if ((this->Makefile->GetSafeDefinition(
  1535. "CMAKE_" + lang + "_COMPILER_ID") == "MSVC" ||
  1536. this->Makefile->GetSafeDefinition(
  1537. "CMAKE_" + lang + "_SIMULATE_ID") == "MSVC") &&
  1538. !cmSystemTools::GetErrorOccuredFlag()) {
  1539. // The compiler uses the MSVC ABI so it needs a known runtime library.
  1540. this->IssueMessage(MessageType::FATAL_ERROR,
  1541. "MSVC_RUNTIME_LIBRARY value '" +
  1542. msvcRuntimeLibrary + "' not known for this " +
  1543. lang + " compiler.");
  1544. }
  1545. }
  1546. }
  1547. }
  1548. void cmLocalGenerator::AddLanguageFlagsForLinking(
  1549. std::string& flags, cmGeneratorTarget const* target, const std::string& lang,
  1550. const std::string& config)
  1551. {
  1552. if (this->Makefile->IsOn("CMAKE_" + lang +
  1553. "_LINK_WITH_STANDARD_COMPILE_OPTION")) {
  1554. // This toolchain requires use of the language standard flag
  1555. // when linking in order to use the matching standard library.
  1556. // FIXME: If CMake gains an abstraction for standard library
  1557. // selection, this will have to be reconciled with it.
  1558. this->AddCompilerRequirementFlag(flags, target, lang);
  1559. }
  1560. this->AddLanguageFlags(flags, target, lang, config);
  1561. if (target->IsIPOEnabled(lang, config)) {
  1562. this->AppendFeatureOptions(flags, lang, "IPO");
  1563. }
  1564. }
  1565. cmGeneratorTarget* cmLocalGenerator::FindGeneratorTargetToUse(
  1566. const std::string& name) const
  1567. {
  1568. auto imported = this->ImportedGeneratorTargets.find(name);
  1569. if (imported != this->ImportedGeneratorTargets.end()) {
  1570. return imported->second;
  1571. }
  1572. if (cmGeneratorTarget* t = this->FindLocalNonAliasGeneratorTarget(name)) {
  1573. return t;
  1574. }
  1575. return this->GetGlobalGenerator()->FindGeneratorTarget(name);
  1576. }
  1577. bool cmLocalGenerator::GetRealDependency(const std::string& inName,
  1578. const std::string& config,
  1579. std::string& dep)
  1580. {
  1581. // Older CMake code may specify the dependency using the target
  1582. // output file rather than the target name. Such code would have
  1583. // been written before there was support for target properties that
  1584. // modify the name so stripping down to just the file name should
  1585. // produce the target name in this case.
  1586. std::string name = cmSystemTools::GetFilenameName(inName);
  1587. // If the input name is the empty string, there is no real
  1588. // dependency. Short-circuit the other checks:
  1589. if (name.empty()) {
  1590. return false;
  1591. }
  1592. if (cmSystemTools::GetFilenameLastExtension(name) == ".exe") {
  1593. name = cmSystemTools::GetFilenameWithoutLastExtension(name);
  1594. }
  1595. // Look for a CMake target with the given name.
  1596. if (cmGeneratorTarget* target = this->FindGeneratorTargetToUse(name)) {
  1597. // make sure it is not just a coincidence that the target name
  1598. // found is part of the inName
  1599. if (cmSystemTools::FileIsFullPath(inName)) {
  1600. std::string tLocation;
  1601. if (target->GetType() >= cmStateEnums::EXECUTABLE &&
  1602. target->GetType() <= cmStateEnums::MODULE_LIBRARY) {
  1603. tLocation = target->GetLocation(config);
  1604. tLocation = cmSystemTools::GetFilenamePath(tLocation);
  1605. tLocation = cmSystemTools::CollapseFullPath(tLocation);
  1606. }
  1607. std::string depLocation =
  1608. cmSystemTools::GetFilenamePath(std::string(inName));
  1609. depLocation = cmSystemTools::CollapseFullPath(depLocation);
  1610. if (depLocation != tLocation) {
  1611. // it is a full path to a depend that has the same name
  1612. // as a target but is in a different location so do not use
  1613. // the target as the depend
  1614. dep = inName;
  1615. return true;
  1616. }
  1617. }
  1618. switch (target->GetType()) {
  1619. case cmStateEnums::EXECUTABLE:
  1620. case cmStateEnums::STATIC_LIBRARY:
  1621. case cmStateEnums::SHARED_LIBRARY:
  1622. case cmStateEnums::MODULE_LIBRARY:
  1623. case cmStateEnums::UNKNOWN_LIBRARY:
  1624. dep = target->GetLocation(config);
  1625. return true;
  1626. case cmStateEnums::OBJECT_LIBRARY:
  1627. // An object library has no single file on which to depend.
  1628. // This was listed to get the target-level dependency.
  1629. return false;
  1630. case cmStateEnums::INTERFACE_LIBRARY:
  1631. // An interface library has no file on which to depend.
  1632. // This was listed to get the target-level dependency.
  1633. return false;
  1634. case cmStateEnums::UTILITY:
  1635. case cmStateEnums::GLOBAL_TARGET:
  1636. // A utility target has no file on which to depend. This was listed
  1637. // only to get the target-level dependency.
  1638. return false;
  1639. }
  1640. }
  1641. // The name was not that of a CMake target. It must name a file.
  1642. if (cmSystemTools::FileIsFullPath(inName)) {
  1643. // This is a full path. Return it as given.
  1644. dep = inName;
  1645. return true;
  1646. }
  1647. // Check for a source file in this directory that matches the
  1648. // dependency.
  1649. if (cmSourceFile* sf = this->Makefile->GetSource(inName)) {
  1650. dep = sf->ResolveFullPath();
  1651. return true;
  1652. }
  1653. // Treat the name as relative to the source directory in which it
  1654. // was given.
  1655. dep = cmStrCat(this->StateSnapshot.GetDirectory().GetCurrentSource(), '/',
  1656. inName);
  1657. return true;
  1658. }
  1659. void cmLocalGenerator::AddSharedFlags(std::string& flags,
  1660. const std::string& lang, bool shared)
  1661. {
  1662. std::string flagsVar;
  1663. // Add flags for dealing with shared libraries for this language.
  1664. if (shared) {
  1665. this->AppendFlags(flags,
  1666. this->Makefile->GetSafeDefinition(
  1667. cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS")));
  1668. }
  1669. }
  1670. void cmLocalGenerator::AddCompilerRequirementFlag(
  1671. std::string& flags, cmGeneratorTarget const* target, const std::string& lang)
  1672. {
  1673. if (lang.empty()) {
  1674. return;
  1675. }
  1676. const char* defaultStd =
  1677. this->Makefile->GetDefinition("CMAKE_" + lang + "_STANDARD_DEFAULT");
  1678. if (!defaultStd || !*defaultStd) {
  1679. // This compiler has no notion of language standard levels.
  1680. return;
  1681. }
  1682. std::string extProp = lang + "_EXTENSIONS";
  1683. bool ext = true;
  1684. if (const char* extPropValue = target->GetProperty(extProp)) {
  1685. if (cmIsOff(extPropValue)) {
  1686. ext = false;
  1687. }
  1688. }
  1689. std::string stdProp = lang + "_STANDARD";
  1690. const char* standardProp = target->GetProperty(stdProp);
  1691. if (!standardProp) {
  1692. if (ext) {
  1693. // No language standard is specified and extensions are not disabled.
  1694. // Check if this compiler needs a flag to enable extensions.
  1695. std::string const option_flag =
  1696. "CMAKE_" + lang + "_EXTENSION_COMPILE_OPTION";
  1697. if (const char* opt =
  1698. target->Target->GetMakefile()->GetDefinition(option_flag)) {
  1699. std::vector<std::string> optVec = cmExpandedList(opt);
  1700. for (std::string const& i : optVec) {
  1701. this->AppendFlagEscape(flags, i);
  1702. }
  1703. }
  1704. }
  1705. return;
  1706. }
  1707. std::string const type = ext ? "EXTENSION" : "STANDARD";
  1708. if (target->GetPropertyAsBool(lang + "_STANDARD_REQUIRED")) {
  1709. std::string option_flag =
  1710. "CMAKE_" + lang + standardProp + "_" + type + "_COMPILE_OPTION";
  1711. const char* opt =
  1712. target->Target->GetMakefile()->GetDefinition(option_flag);
  1713. if (!opt) {
  1714. std::ostringstream e;
  1715. e << "Target \"" << target->GetName()
  1716. << "\" requires the language "
  1717. "dialect \""
  1718. << lang << standardProp << "\" "
  1719. << (ext ? "(with compiler extensions)" : "")
  1720. << ", but CMake "
  1721. "does not know the compile flags to use to enable it.";
  1722. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  1723. } else {
  1724. std::vector<std::string> optVec = cmExpandedList(opt);
  1725. for (std::string const& i : optVec) {
  1726. this->AppendFlagEscape(flags, i);
  1727. }
  1728. }
  1729. return;
  1730. }
  1731. static std::map<std::string, std::vector<std::string>> langStdMap;
  1732. if (langStdMap.empty()) {
  1733. // Maintain sorted order, most recent first.
  1734. langStdMap["CXX"].emplace_back("20");
  1735. langStdMap["CXX"].emplace_back("17");
  1736. langStdMap["CXX"].emplace_back("14");
  1737. langStdMap["CXX"].emplace_back("11");
  1738. langStdMap["CXX"].emplace_back("98");
  1739. langStdMap["C"].emplace_back("11");
  1740. langStdMap["C"].emplace_back("99");
  1741. langStdMap["C"].emplace_back("90");
  1742. langStdMap["CUDA"].emplace_back("14");
  1743. langStdMap["CUDA"].emplace_back("11");
  1744. langStdMap["CUDA"].emplace_back("98");
  1745. }
  1746. std::string standard(standardProp);
  1747. std::vector<std::string>& stds = langStdMap[lang];
  1748. auto stdIt = std::find(stds.begin(), stds.end(), standard);
  1749. if (stdIt == stds.end()) {
  1750. std::string e =
  1751. lang + "_STANDARD is set to invalid value '" + standard + "'";
  1752. this->GetGlobalGenerator()->GetCMakeInstance()->IssueMessage(
  1753. MessageType::FATAL_ERROR, e, target->GetBacktrace());
  1754. return;
  1755. }
  1756. auto defaultStdIt = std::find(stds.begin(), stds.end(), defaultStd);
  1757. if (defaultStdIt == stds.end()) {
  1758. std::string e = "CMAKE_" + lang +
  1759. "_STANDARD_DEFAULT is set to invalid value '" + std::string(defaultStd) +
  1760. "'";
  1761. this->IssueMessage(MessageType::INTERNAL_ERROR, e);
  1762. return;
  1763. }
  1764. // If the standard requested is older than the compiler's default
  1765. // then we need to use a flag to change it. The comparison is
  1766. // greater-or-equal because the standards are stored in backward
  1767. // chronological order.
  1768. if (stdIt >= defaultStdIt) {
  1769. std::string option_flag =
  1770. "CMAKE_" + lang + *stdIt + "_" + type + "_COMPILE_OPTION";
  1771. std::string const& opt =
  1772. target->Target->GetMakefile()->GetRequiredDefinition(option_flag);
  1773. std::vector<std::string> optVec = cmExpandedList(opt);
  1774. for (std::string const& i : optVec) {
  1775. this->AppendFlagEscape(flags, i);
  1776. }
  1777. return;
  1778. }
  1779. // The standard requested is at least as new as the compiler's default,
  1780. // and the standard request is not required. Decay to the newest standard
  1781. // for which a flag is defined.
  1782. for (; stdIt < defaultStdIt; ++stdIt) {
  1783. std::string option_flag =
  1784. cmStrCat("CMAKE_", lang, *stdIt, "_", type, "_COMPILE_OPTION");
  1785. if (const char* opt =
  1786. target->Target->GetMakefile()->GetDefinition(option_flag)) {
  1787. std::vector<std::string> optVec = cmExpandedList(opt);
  1788. for (std::string const& i : optVec) {
  1789. this->AppendFlagEscape(flags, i);
  1790. }
  1791. return;
  1792. }
  1793. }
  1794. }
  1795. static void AddVisibilityCompileOption(std::string& flags,
  1796. cmGeneratorTarget const* target,
  1797. cmLocalGenerator* lg,
  1798. const std::string& lang,
  1799. std::string* warnCMP0063)
  1800. {
  1801. std::string compileOption = "CMAKE_" + lang + "_COMPILE_OPTIONS_VISIBILITY";
  1802. const char* opt = lg->GetMakefile()->GetDefinition(compileOption);
  1803. if (!opt) {
  1804. return;
  1805. }
  1806. std::string flagDefine = lang + "_VISIBILITY_PRESET";
  1807. const char* prop = target->GetProperty(flagDefine);
  1808. if (!prop) {
  1809. return;
  1810. }
  1811. if (warnCMP0063) {
  1812. *warnCMP0063 += " " + flagDefine + "\n";
  1813. return;
  1814. }
  1815. if (strcmp(prop, "hidden") != 0 && strcmp(prop, "default") != 0 &&
  1816. strcmp(prop, "protected") != 0 && strcmp(prop, "internal") != 0) {
  1817. std::ostringstream e;
  1818. e << "Target " << target->GetName() << " uses unsupported value \"" << prop
  1819. << "\" for " << flagDefine << "."
  1820. << " The supported values are: default, hidden, protected, and "
  1821. "internal.";
  1822. cmSystemTools::Error(e.str());
  1823. return;
  1824. }
  1825. std::string option = std::string(opt) + prop;
  1826. lg->AppendFlags(flags, option);
  1827. }
  1828. static void AddInlineVisibilityCompileOption(std::string& flags,
  1829. cmGeneratorTarget const* target,
  1830. cmLocalGenerator* lg,
  1831. std::string* warnCMP0063)
  1832. {
  1833. std::string compileOption =
  1834. "CMAKE_CXX_COMPILE_OPTIONS_VISIBILITY_INLINES_HIDDEN";
  1835. const char* opt = lg->GetMakefile()->GetDefinition(compileOption);
  1836. if (!opt) {
  1837. return;
  1838. }
  1839. bool prop = target->GetPropertyAsBool("VISIBILITY_INLINES_HIDDEN");
  1840. if (!prop) {
  1841. return;
  1842. }
  1843. if (warnCMP0063) {
  1844. *warnCMP0063 += " VISIBILITY_INLINES_HIDDEN\n";
  1845. return;
  1846. }
  1847. lg->AppendFlags(flags, opt);
  1848. }
  1849. void cmLocalGenerator::AddVisibilityPresetFlags(
  1850. std::string& flags, cmGeneratorTarget const* target, const std::string& lang)
  1851. {
  1852. if (lang.empty()) {
  1853. return;
  1854. }
  1855. std::string warnCMP0063;
  1856. std::string* pWarnCMP0063 = nullptr;
  1857. if (target->GetType() != cmStateEnums::SHARED_LIBRARY &&
  1858. target->GetType() != cmStateEnums::MODULE_LIBRARY &&
  1859. !target->IsExecutableWithExports()) {
  1860. switch (target->GetPolicyStatusCMP0063()) {
  1861. case cmPolicies::OLD:
  1862. return;
  1863. case cmPolicies::WARN:
  1864. pWarnCMP0063 = &warnCMP0063;
  1865. break;
  1866. default:
  1867. break;
  1868. }
  1869. }
  1870. AddVisibilityCompileOption(flags, target, this, lang, pWarnCMP0063);
  1871. if (lang == "CXX") {
  1872. AddInlineVisibilityCompileOption(flags, target, this, pWarnCMP0063);
  1873. }
  1874. if (!warnCMP0063.empty() && this->WarnCMP0063.insert(target).second) {
  1875. std::ostringstream w;
  1876. /* clang-format off */
  1877. w <<
  1878. cmPolicies::GetPolicyWarning(cmPolicies::CMP0063) << "\n"
  1879. "Target \"" << target->GetName() << "\" of "
  1880. "type \"" << cmState::GetTargetTypeName(target->GetType()) << "\" "
  1881. "has the following visibility properties set for " << lang << ":\n" <<
  1882. warnCMP0063 <<
  1883. "For compatibility CMake is not honoring them for this target.";
  1884. /* clang-format on */
  1885. target->GetLocalGenerator()->GetCMakeInstance()->IssueMessage(
  1886. MessageType::AUTHOR_WARNING, w.str(), target->GetBacktrace());
  1887. }
  1888. }
  1889. void cmLocalGenerator::AddCMP0018Flags(std::string& flags,
  1890. cmGeneratorTarget const* target,
  1891. std::string const& lang,
  1892. const std::string& config)
  1893. {
  1894. int targetType = target->GetType();
  1895. bool shared = ((targetType == cmStateEnums::SHARED_LIBRARY) ||
  1896. (targetType == cmStateEnums::MODULE_LIBRARY));
  1897. if (this->GetShouldUseOldFlags(shared, lang)) {
  1898. this->AddSharedFlags(flags, lang, shared);
  1899. } else {
  1900. if (target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  1901. if (target->GetPropertyAsBool("POSITION_INDEPENDENT_CODE")) {
  1902. this->AddPositionIndependentFlags(flags, lang, targetType);
  1903. }
  1904. return;
  1905. }
  1906. if (target->GetLinkInterfaceDependentBoolProperty(
  1907. "POSITION_INDEPENDENT_CODE", config)) {
  1908. this->AddPositionIndependentFlags(flags, lang, targetType);
  1909. }
  1910. if (shared) {
  1911. this->AppendFeatureOptions(flags, lang, "DLL");
  1912. }
  1913. }
  1914. }
  1915. bool cmLocalGenerator::GetShouldUseOldFlags(bool shared,
  1916. const std::string& lang) const
  1917. {
  1918. std::string originalFlags =
  1919. this->GlobalGenerator->GetSharedLibFlagsForLanguage(lang);
  1920. if (shared) {
  1921. std::string flagsVar = cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS");
  1922. std::string const& flags = this->Makefile->GetSafeDefinition(flagsVar);
  1923. if (flags != originalFlags) {
  1924. switch (this->GetPolicyStatus(cmPolicies::CMP0018)) {
  1925. case cmPolicies::WARN: {
  1926. std::ostringstream e;
  1927. e << "Variable " << flagsVar
  1928. << " has been modified. CMake "
  1929. "will ignore the POSITION_INDEPENDENT_CODE target property for "
  1930. "shared libraries and will use the "
  1931. << flagsVar
  1932. << " variable "
  1933. "instead. This may cause errors if the original content of "
  1934. << flagsVar << " was removed.\n"
  1935. << cmPolicies::GetPolicyWarning(cmPolicies::CMP0018);
  1936. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  1937. CM_FALLTHROUGH;
  1938. }
  1939. case cmPolicies::OLD:
  1940. return true;
  1941. case cmPolicies::REQUIRED_IF_USED:
  1942. case cmPolicies::REQUIRED_ALWAYS:
  1943. case cmPolicies::NEW:
  1944. return false;
  1945. }
  1946. }
  1947. }
  1948. return false;
  1949. }
  1950. void cmLocalGenerator::AddPositionIndependentFlags(std::string& flags,
  1951. std::string const& lang,
  1952. int targetType)
  1953. {
  1954. std::string picFlags;
  1955. if (targetType == cmStateEnums::EXECUTABLE) {
  1956. picFlags = this->Makefile->GetSafeDefinition(
  1957. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIE"));
  1958. }
  1959. if (picFlags.empty()) {
  1960. picFlags = this->Makefile->GetSafeDefinition(
  1961. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIC"));
  1962. }
  1963. if (!picFlags.empty()) {
  1964. std::vector<std::string> options = cmExpandedList(picFlags);
  1965. for (std::string const& o : options) {
  1966. this->AppendFlagEscape(flags, o);
  1967. }
  1968. }
  1969. }
  1970. void cmLocalGenerator::AddConfigVariableFlags(std::string& flags,
  1971. const std::string& var,
  1972. const std::string& config)
  1973. {
  1974. // Add the flags from the variable itself.
  1975. this->AppendFlags(flags, this->Makefile->GetSafeDefinition(var));
  1976. // Add the flags from the build-type specific variable.
  1977. if (!config.empty()) {
  1978. const std::string flagsVar =
  1979. cmStrCat(var, '_', cmSystemTools::UpperCase(config));
  1980. this->AppendFlags(flags, this->Makefile->GetSafeDefinition(flagsVar));
  1981. }
  1982. }
  1983. void cmLocalGenerator::AppendFlags(std::string& flags,
  1984. const std::string& newFlags) const
  1985. {
  1986. if (!newFlags.empty()) {
  1987. if (!flags.empty()) {
  1988. flags += " ";
  1989. }
  1990. flags += newFlags;
  1991. }
  1992. }
  1993. void cmLocalGenerator::AppendFlags(
  1994. std::string& flags, const std::vector<BT<std::string>>& newFlags) const
  1995. {
  1996. for (BT<std::string> const& flag : newFlags) {
  1997. this->AppendFlags(flags, flag.Value);
  1998. }
  1999. }
  2000. void cmLocalGenerator::AppendFlagEscape(std::string& flags,
  2001. const std::string& rawFlag) const
  2002. {
  2003. this->AppendFlags(flags, this->EscapeForShell(rawFlag));
  2004. }
  2005. void cmLocalGenerator::AddPchDependencies(cmGeneratorTarget* target,
  2006. const std::string& config)
  2007. {
  2008. const std::string lang = target->GetLinkerLanguage(config);
  2009. const std::string buildType = cmSystemTools::UpperCase(config);
  2010. const std::string pchSource = target->GetPchSource(config, lang);
  2011. const std::string pchHeader = target->GetPchHeader(config, lang);
  2012. if (pchSource.empty() || pchHeader.empty()) {
  2013. return;
  2014. }
  2015. const std::string createOptVar =
  2016. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_CREATE_PCH");
  2017. std::string createOptionList =
  2018. this->Makefile->GetSafeDefinition(createOptVar);
  2019. const std::string useOptVar =
  2020. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_USE_PCH");
  2021. std::string useOptionList = this->Makefile->GetSafeDefinition(useOptVar);
  2022. const std::string pchExtension =
  2023. this->Makefile->GetSafeDefinition("CMAKE_PCH_EXTENSION");
  2024. if (createOptionList.empty() || useOptionList.empty() ||
  2025. pchExtension.empty()) {
  2026. return;
  2027. }
  2028. auto pch_sf = this->Makefile->GetOrCreateSource(
  2029. pchSource, false, cmSourceFileLocationKind::Known);
  2030. std::string pchFile = pchHeader;
  2031. if (!this->GetGlobalGenerator()->IsXcode()) {
  2032. // Exclude the pch files from linking
  2033. if (this->Makefile->IsOn("CMAKE_LINK_PCH")) {
  2034. cmSystemTools::ReplaceString(pchFile, (lang == "C" ? ".h" : ".hxx"),
  2035. pchExtension);
  2036. pch_sf->SetProperty("OBJECT_OUTPUTS", pchFile.c_str());
  2037. } else {
  2038. pchFile += pchExtension;
  2039. pch_sf->SetProperty("PCH_EXTENSION", pchExtension.c_str());
  2040. }
  2041. target->AddSource(pchSource, true);
  2042. for (auto& str : { std::ref(useOptionList), std::ref(createOptionList) }) {
  2043. cmSystemTools::ReplaceString(str, "<PCH_HEADER>", pchHeader);
  2044. cmSystemTools::ReplaceString(str, "<PCH_FILE>", pchFile);
  2045. }
  2046. }
  2047. pch_sf->SetProperty("COMPILE_OPTIONS", createOptionList.c_str());
  2048. std::vector<cmSourceFile*> sources;
  2049. target->GetSourceFiles(sources, buildType);
  2050. for (cmSourceFile* sf : sources) {
  2051. if (pch_sf == sf || sf->GetLanguage() != lang) {
  2052. continue;
  2053. }
  2054. if (sf->GetPropertyAsBool("SKIP_PRECOMPILE_HEADERS")) {
  2055. if (this->GetGlobalGenerator()->IsXcode()) {
  2056. sf->SetProperty("COMPILE_DEFINITIONS",
  2057. "CMAKE_SKIP_PRECOMPILE_HEADERS");
  2058. }
  2059. continue;
  2060. }
  2061. if (!this->GetGlobalGenerator()->IsXcode()) {
  2062. sf->SetProperty("OBJECT_DEPENDS", pchFile.c_str());
  2063. sf->SetProperty("COMPILE_OPTIONS", useOptionList.c_str());
  2064. }
  2065. }
  2066. }
  2067. void cmLocalGenerator::AddUnityBuild(cmGeneratorTarget* target,
  2068. const std::string& config)
  2069. {
  2070. if (!target->GetPropertyAsBool("UNITY_BUILD")) {
  2071. return;
  2072. }
  2073. const std::string buildType = cmSystemTools::UpperCase(config);
  2074. std::string filename_base =
  2075. cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles/",
  2076. target->GetName(), ".dir/Unity/");
  2077. std::vector<cmSourceFile*> sources;
  2078. target->GetSourceFiles(sources, buildType);
  2079. auto batchSizeString = target->GetProperty("UNITY_BUILD_BATCH_SIZE");
  2080. const size_t unityBatchSize =
  2081. static_cast<size_t>(std::atoi(batchSizeString));
  2082. auto beforeInclude = target->GetProperty("UNITY_BUILD_CODE_BEFORE_INCLUDE");
  2083. auto afterInclude = target->GetProperty("UNITY_BUILD_CODE_AFTER_INCLUDE");
  2084. for (std::string lang : { "C", "CXX" }) {
  2085. std::vector<cmSourceFile*> filtered_sources;
  2086. std::copy_if(sources.begin(), sources.end(),
  2087. std::back_inserter(filtered_sources), [&](cmSourceFile* sf) {
  2088. return sf->GetLanguage() == lang &&
  2089. !sf->GetPropertyAsBool("SKIP_UNITY_BUILD_INCLUSION") &&
  2090. !sf->GetPropertyAsBool("GENERATED") &&
  2091. !sf->GetProperty("COMPILE_OPTIONS") &&
  2092. !sf->GetProperty("COMPILE_DEFINITIONS") &&
  2093. !sf->GetProperty("COMPILE_FLAGS") &&
  2094. !sf->GetProperty("INCLUDE_DIRECTORIES");
  2095. });
  2096. size_t batchSize = unityBatchSize;
  2097. if (unityBatchSize == 0) {
  2098. batchSize = filtered_sources.size();
  2099. }
  2100. for (size_t itemsLeft = filtered_sources.size(), chunk = batchSize,
  2101. batch = 0;
  2102. itemsLeft > 0; itemsLeft -= chunk, ++batch) {
  2103. chunk = std::min(itemsLeft, batchSize);
  2104. std::string filename = cmStrCat(filename_base, "unity_", batch,
  2105. (lang == "C") ? ".c" : ".cxx");
  2106. const std::string filename_tmp = cmStrCat(filename, ".tmp");
  2107. {
  2108. size_t begin = batch * batchSize;
  2109. size_t end = begin + chunk;
  2110. cmGeneratedFileStream file(
  2111. filename_tmp, false,
  2112. this->GetGlobalGenerator()->GetMakefileEncoding());
  2113. file << "/* generated by CMake */\n\n";
  2114. for (; begin != end; ++begin) {
  2115. cmSourceFile* sf = filtered_sources[begin];
  2116. // Only in Visual Studio generator we keep the source files
  2117. // for explicit processing. For the rest the source files will
  2118. // not be included in the project.
  2119. if (!this->GetGlobalGenerator()->IsMultiConfig() ||
  2120. this->GetGlobalGenerator()->IsXcode()) {
  2121. sf->SetProperty("HEADER_FILE_ONLY", "ON");
  2122. }
  2123. sf->SetProperty("UNITY_SOURCE_FILE", filename.c_str());
  2124. if (beforeInclude) {
  2125. file << beforeInclude << "\n";
  2126. }
  2127. file << "#include \"" << sf->GetFullPath() << "\"\n";
  2128. if (afterInclude) {
  2129. file << afterInclude << "\n";
  2130. }
  2131. }
  2132. }
  2133. cmSystemTools::MoveFileIfDifferent(filename_tmp, filename);
  2134. target->AddSource(filename, true);
  2135. auto unity = this->Makefile->GetOrCreateSource(filename);
  2136. unity->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "ON");
  2137. unity->SetProperty("UNITY_SOURCE_FILE", filename.c_str());
  2138. }
  2139. }
  2140. }
  2141. void cmLocalGenerator::AppendIPOLinkerFlags(std::string& flags,
  2142. cmGeneratorTarget* target,
  2143. const std::string& config,
  2144. const std::string& lang)
  2145. {
  2146. if (!target->IsIPOEnabled(lang, config)) {
  2147. return;
  2148. }
  2149. switch (target->GetType()) {
  2150. case cmStateEnums::EXECUTABLE:
  2151. case cmStateEnums::SHARED_LIBRARY:
  2152. case cmStateEnums::MODULE_LIBRARY:
  2153. break;
  2154. default:
  2155. return;
  2156. }
  2157. const std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_IPO";
  2158. const char* rawFlagsList = this->Makefile->GetDefinition(name);
  2159. if (rawFlagsList == nullptr) {
  2160. return;
  2161. }
  2162. std::vector<std::string> flagsList = cmExpandedList(rawFlagsList);
  2163. for (std::string const& o : flagsList) {
  2164. this->AppendFlagEscape(flags, o);
  2165. }
  2166. }
  2167. void cmLocalGenerator::AppendPositionIndependentLinkerFlags(
  2168. std::string& flags, cmGeneratorTarget* target, const std::string& config,
  2169. const std::string& lang)
  2170. {
  2171. // For now, only EXECUTABLE is concerned
  2172. if (target->GetType() != cmStateEnums::EXECUTABLE) {
  2173. return;
  2174. }
  2175. const char* PICValue = target->GetLinkPIEProperty(config);
  2176. if (PICValue == nullptr) {
  2177. // POSITION_INDEPENDENT_CODE is not set
  2178. return;
  2179. }
  2180. const std::string mode = cmIsOn(PICValue) ? "PIE" : "NO_PIE";
  2181. std::string supported = "CMAKE_" + lang + "_LINK_" + mode + "_SUPPORTED";
  2182. if (cmIsOff(this->Makefile->GetDefinition(supported))) {
  2183. return;
  2184. }
  2185. std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_" + mode;
  2186. auto pieFlags = this->Makefile->GetSafeDefinition(name);
  2187. if (pieFlags.empty()) {
  2188. return;
  2189. }
  2190. std::vector<std::string> flagsList = cmExpandedList(pieFlags);
  2191. for (const auto& flag : flagsList) {
  2192. this->AppendFlagEscape(flags, flag);
  2193. }
  2194. }
  2195. void cmLocalGenerator::AppendCompileOptions(std::string& options,
  2196. const char* options_list,
  2197. const char* regex) const
  2198. {
  2199. // Short-circuit if there are no options.
  2200. if (!options_list) {
  2201. return;
  2202. }
  2203. // Expand the list of options.
  2204. std::vector<std::string> options_vec = cmExpandedList(options_list);
  2205. this->AppendCompileOptions(options, options_vec, regex);
  2206. }
  2207. void cmLocalGenerator::AppendCompileOptions(
  2208. std::string& options, const std::vector<std::string>& options_vec,
  2209. const char* regex) const
  2210. {
  2211. if (regex != nullptr) {
  2212. // Filter flags upon specified reges.
  2213. cmsys::RegularExpression r(regex);
  2214. for (std::string const& opt : options_vec) {
  2215. if (r.find(opt)) {
  2216. this->AppendFlagEscape(options, opt);
  2217. }
  2218. }
  2219. } else {
  2220. for (std::string const& opt : options_vec) {
  2221. this->AppendFlagEscape(options, opt);
  2222. }
  2223. }
  2224. }
  2225. void cmLocalGenerator::AppendCompileOptions(
  2226. std::vector<BT<std::string>>& options,
  2227. const std::vector<BT<std::string>>& options_vec, const char* regex) const
  2228. {
  2229. if (regex != nullptr) {
  2230. // Filter flags upon specified regular expressions.
  2231. cmsys::RegularExpression r(regex);
  2232. for (BT<std::string> const& opt : options_vec) {
  2233. if (r.find(opt.Value)) {
  2234. std::string flag;
  2235. this->AppendFlagEscape(flag, opt.Value);
  2236. options.emplace_back(std::move(flag), opt.Backtrace);
  2237. }
  2238. }
  2239. } else {
  2240. for (BT<std::string> const& opt : options_vec) {
  2241. std::string flag;
  2242. this->AppendFlagEscape(flag, opt.Value);
  2243. options.emplace_back(std::move(flag), opt.Backtrace);
  2244. }
  2245. }
  2246. }
  2247. void cmLocalGenerator::AppendIncludeDirectories(
  2248. std::vector<std::string>& includes, const char* includes_list,
  2249. const cmSourceFile& sourceFile) const
  2250. {
  2251. // Short-circuit if there are no includes.
  2252. if (!includes_list) {
  2253. return;
  2254. }
  2255. // Expand the list of includes.
  2256. std::vector<std::string> includes_vec = cmExpandedList(includes_list);
  2257. this->AppendIncludeDirectories(includes, includes_vec, sourceFile);
  2258. }
  2259. void cmLocalGenerator::AppendIncludeDirectories(
  2260. std::vector<std::string>& includes,
  2261. const std::vector<std::string>& includes_vec,
  2262. const cmSourceFile& sourceFile) const
  2263. {
  2264. std::unordered_set<std::string> uniqueIncludes;
  2265. for (const std::string& include : includes_vec) {
  2266. if (!cmSystemTools::FileIsFullPath(include)) {
  2267. std::ostringstream e;
  2268. e << "Found relative path while evaluating include directories of "
  2269. "\""
  2270. << sourceFile.GetLocation().GetName() << "\":\n \"" << include
  2271. << "\"\n";
  2272. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2273. return;
  2274. }
  2275. std::string inc = include;
  2276. if (!cmIsOff(inc)) {
  2277. cmSystemTools::ConvertToUnixSlashes(inc);
  2278. }
  2279. if (uniqueIncludes.insert(inc).second) {
  2280. includes.push_back(std::move(inc));
  2281. }
  2282. }
  2283. }
  2284. void cmLocalGenerator::AppendDefines(std::set<std::string>& defines,
  2285. std::string const& defines_list) const
  2286. {
  2287. std::set<BT<std::string>> tmp;
  2288. this->AppendDefines(tmp, ExpandListWithBacktrace(defines_list));
  2289. for (BT<std::string> const& i : tmp) {
  2290. defines.emplace(i.Value);
  2291. }
  2292. }
  2293. void cmLocalGenerator::AppendDefines(std::set<BT<std::string>>& defines,
  2294. std::string const& defines_list) const
  2295. {
  2296. // Short-circuit if there are no definitions.
  2297. if (defines_list.empty()) {
  2298. return;
  2299. }
  2300. // Expand the list of definitions.
  2301. this->AppendDefines(defines, ExpandListWithBacktrace(defines_list));
  2302. }
  2303. void cmLocalGenerator::AppendDefines(
  2304. std::set<BT<std::string>>& defines,
  2305. const std::vector<BT<std::string>>& defines_vec) const
  2306. {
  2307. for (BT<std::string> const& d : defines_vec) {
  2308. // Skip unsupported definitions.
  2309. if (!this->CheckDefinition(d.Value)) {
  2310. continue;
  2311. }
  2312. defines.insert(d);
  2313. }
  2314. }
  2315. void cmLocalGenerator::JoinDefines(const std::set<std::string>& defines,
  2316. std::string& definesString,
  2317. const std::string& lang)
  2318. {
  2319. // Lookup the define flag for the current language.
  2320. std::string dflag = "-D";
  2321. if (!lang.empty()) {
  2322. const char* df =
  2323. this->Makefile->GetDefinition(cmStrCat("CMAKE_", lang, "_DEFINE_FLAG"));
  2324. if (df && *df) {
  2325. dflag = df;
  2326. }
  2327. }
  2328. const char* itemSeparator = definesString.empty() ? "" : " ";
  2329. for (std::string const& define : defines) {
  2330. // Append the definition with proper escaping.
  2331. std::string def = dflag;
  2332. if (this->GetState()->UseWatcomWMake()) {
  2333. // The Watcom compiler does its own command line parsing instead
  2334. // of using the windows shell rules. Definitions are one of
  2335. // -DNAME
  2336. // -DNAME=<cpp-token>
  2337. // -DNAME="c-string with spaces and other characters(?@#$)"
  2338. //
  2339. // Watcom will properly parse each of these cases from the
  2340. // command line without any escapes. However we still have to
  2341. // get the '$' and '#' characters through WMake as '$$' and
  2342. // '$#'.
  2343. for (const char* c = define.c_str(); *c; ++c) {
  2344. if (*c == '$' || *c == '#') {
  2345. def += '$';
  2346. }
  2347. def += *c;
  2348. }
  2349. } else {
  2350. // Make the definition appear properly on the command line. Use
  2351. // -DNAME="value" instead of -D"NAME=value" for historical reasons.
  2352. std::string::size_type eq = define.find('=');
  2353. def += define.substr(0, eq);
  2354. if (eq != std::string::npos) {
  2355. def += "=";
  2356. def += this->EscapeForShell(define.substr(eq + 1), true);
  2357. }
  2358. }
  2359. definesString += itemSeparator;
  2360. itemSeparator = " ";
  2361. definesString += def;
  2362. }
  2363. }
  2364. void cmLocalGenerator::AppendFeatureOptions(std::string& flags,
  2365. const std::string& lang,
  2366. const char* feature)
  2367. {
  2368. const char* optionList = this->Makefile->GetDefinition(
  2369. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_", feature));
  2370. if (optionList != nullptr) {
  2371. std::vector<std::string> options = cmExpandedList(optionList);
  2372. for (std::string const& o : options) {
  2373. this->AppendFlagEscape(flags, o);
  2374. }
  2375. }
  2376. }
  2377. const char* cmLocalGenerator::GetFeature(const std::string& feature,
  2378. const std::string& config)
  2379. {
  2380. std::string featureName = feature;
  2381. // TODO: Define accumulation policy for features (prepend, append, replace).
  2382. // Currently we always replace.
  2383. if (!config.empty()) {
  2384. featureName += "_";
  2385. featureName += cmSystemTools::UpperCase(config);
  2386. }
  2387. cmStateSnapshot snp = this->StateSnapshot;
  2388. while (snp.IsValid()) {
  2389. if (const char* value = snp.GetDirectory().GetProperty(featureName)) {
  2390. return value;
  2391. }
  2392. snp = snp.GetBuildsystemDirectoryParent();
  2393. }
  2394. return nullptr;
  2395. }
  2396. std::string cmLocalGenerator::GetProjectName() const
  2397. {
  2398. return this->StateSnapshot.GetProjectName();
  2399. }
  2400. std::string cmLocalGenerator::ConstructComment(
  2401. cmCustomCommandGenerator const& ccg, const char* default_comment)
  2402. {
  2403. // Check for a comment provided with the command.
  2404. if (ccg.GetComment()) {
  2405. return ccg.GetComment();
  2406. }
  2407. // Construct a reasonable default comment if possible.
  2408. if (!ccg.GetOutputs().empty()) {
  2409. std::string comment;
  2410. comment = "Generating ";
  2411. const char* sep = "";
  2412. std::string currentBinaryDir = this->GetCurrentBinaryDirectory();
  2413. for (std::string const& o : ccg.GetOutputs()) {
  2414. comment += sep;
  2415. comment += this->MaybeConvertToRelativePath(currentBinaryDir, o);
  2416. sep = ", ";
  2417. }
  2418. return comment;
  2419. }
  2420. // Otherwise use the provided default.
  2421. return default_comment;
  2422. }
  2423. class cmInstallTargetGeneratorLocal : public cmInstallTargetGenerator
  2424. {
  2425. public:
  2426. cmInstallTargetGeneratorLocal(cmLocalGenerator* lg, std::string const& t,
  2427. const char* dest, bool implib)
  2428. : cmInstallTargetGenerator(
  2429. t, dest, implib, "", std::vector<std::string>(), "Unspecified",
  2430. cmInstallGenerator::SelectMessageLevel(lg->GetMakefile()), false,
  2431. false)
  2432. {
  2433. this->Compute(lg);
  2434. }
  2435. };
  2436. void cmLocalGenerator::GenerateTargetInstallRules(
  2437. std::ostream& os, const std::string& config,
  2438. std::vector<std::string> const& configurationTypes)
  2439. {
  2440. // Convert the old-style install specification from each target to
  2441. // an install generator and run it.
  2442. const std::vector<cmGeneratorTarget*>& tgts = this->GetGeneratorTargets();
  2443. for (cmGeneratorTarget* l : tgts) {
  2444. if (l->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  2445. continue;
  2446. }
  2447. // Include the user-specified pre-install script for this target.
  2448. if (const char* preinstall = l->GetProperty("PRE_INSTALL_SCRIPT")) {
  2449. cmInstallScriptGenerator g(preinstall, false, nullptr, false);
  2450. g.Generate(os, config, configurationTypes);
  2451. }
  2452. // Install this target if a destination is given.
  2453. if (!l->Target->GetInstallPath().empty()) {
  2454. // Compute the full install destination. Note that converting
  2455. // to unix slashes also removes any trailing slash.
  2456. // We also skip over the leading slash given by the user.
  2457. std::string destination = l->Target->GetInstallPath().substr(1);
  2458. cmSystemTools::ConvertToUnixSlashes(destination);
  2459. if (destination.empty()) {
  2460. destination = ".";
  2461. }
  2462. // Generate the proper install generator for this target type.
  2463. switch (l->GetType()) {
  2464. case cmStateEnums::EXECUTABLE:
  2465. case cmStateEnums::STATIC_LIBRARY:
  2466. case cmStateEnums::MODULE_LIBRARY: {
  2467. // Use a target install generator.
  2468. cmInstallTargetGeneratorLocal g(this, l->GetName(),
  2469. destination.c_str(), false);
  2470. g.Generate(os, config, configurationTypes);
  2471. } break;
  2472. case cmStateEnums::SHARED_LIBRARY: {
  2473. #if defined(_WIN32) || defined(__CYGWIN__)
  2474. // Special code to handle DLL. Install the import library
  2475. // to the normal destination and the DLL to the runtime
  2476. // destination.
  2477. cmInstallTargetGeneratorLocal g1(this, l->GetName(),
  2478. destination.c_str(), true);
  2479. g1.Generate(os, config, configurationTypes);
  2480. // We also skip over the leading slash given by the user.
  2481. destination = l->Target->GetRuntimeInstallPath().substr(1);
  2482. cmSystemTools::ConvertToUnixSlashes(destination);
  2483. cmInstallTargetGeneratorLocal g2(this, l->GetName(),
  2484. destination.c_str(), false);
  2485. g2.Generate(os, config, configurationTypes);
  2486. #else
  2487. // Use a target install generator.
  2488. cmInstallTargetGeneratorLocal g(this, l->GetName(),
  2489. destination.c_str(), false);
  2490. g.Generate(os, config, configurationTypes);
  2491. #endif
  2492. } break;
  2493. default:
  2494. break;
  2495. }
  2496. }
  2497. // Include the user-specified post-install script for this target.
  2498. if (const char* postinstall = l->GetProperty("POST_INSTALL_SCRIPT")) {
  2499. cmInstallScriptGenerator g(postinstall, false, nullptr, false);
  2500. g.Generate(os, config, configurationTypes);
  2501. }
  2502. }
  2503. }
  2504. #if defined(CM_LG_ENCODE_OBJECT_NAMES)
  2505. static bool cmLocalGeneratorShortenObjectName(std::string& objName,
  2506. std::string::size_type max_len)
  2507. {
  2508. // Replace the beginning of the path portion of the object name with
  2509. // its own md5 sum.
  2510. std::string::size_type pos =
  2511. objName.find('/', objName.size() - max_len + 32);
  2512. if (pos != std::string::npos) {
  2513. cmCryptoHash md5(cmCryptoHash::AlgoMD5);
  2514. std::string md5name = cmStrCat(md5.HashString(objName.substr(0, pos)),
  2515. cm::string_view(objName).substr(pos));
  2516. objName = md5name;
  2517. // The object name is now short enough.
  2518. return true;
  2519. }
  2520. // The object name could not be shortened enough.
  2521. return false;
  2522. }
  2523. bool cmLocalGeneratorCheckObjectName(std::string& objName,
  2524. std::string::size_type dir_len,
  2525. std::string::size_type max_total_len)
  2526. {
  2527. // Enforce the maximum file name length if possible.
  2528. std::string::size_type max_obj_len = max_total_len;
  2529. if (dir_len < max_total_len) {
  2530. max_obj_len = max_total_len - dir_len;
  2531. if (objName.size() > max_obj_len) {
  2532. // The current object file name is too long. Try to shorten it.
  2533. return cmLocalGeneratorShortenObjectName(objName, max_obj_len);
  2534. }
  2535. // The object file name is short enough.
  2536. return true;
  2537. }
  2538. // The build directory in which the object will be stored is
  2539. // already too deep.
  2540. return false;
  2541. }
  2542. #endif
  2543. std::string& cmLocalGenerator::CreateSafeUniqueObjectFileName(
  2544. const std::string& sin, std::string const& dir_max)
  2545. {
  2546. // Look for an existing mapped name for this object file.
  2547. auto it = this->UniqueObjectNamesMap.find(sin);
  2548. // If no entry exists create one.
  2549. if (it == this->UniqueObjectNamesMap.end()) {
  2550. // Start with the original name.
  2551. std::string ssin = sin;
  2552. // Avoid full paths by removing leading slashes.
  2553. ssin.erase(0, ssin.find_first_not_of('/'));
  2554. // Avoid full paths by removing colons.
  2555. std::replace(ssin.begin(), ssin.end(), ':', '_');
  2556. // Avoid relative paths that go up the tree.
  2557. cmSystemTools::ReplaceString(ssin, "../", "__/");
  2558. // Avoid spaces.
  2559. std::replace(ssin.begin(), ssin.end(), ' ', '_');
  2560. // Mangle the name if necessary.
  2561. if (this->Makefile->IsOn("CMAKE_MANGLE_OBJECT_FILE_NAMES")) {
  2562. bool done;
  2563. int cc = 0;
  2564. char rpstr[100];
  2565. sprintf(rpstr, "_p_");
  2566. cmSystemTools::ReplaceString(ssin, "+", rpstr);
  2567. std::string sssin = sin;
  2568. do {
  2569. done = true;
  2570. for (it = this->UniqueObjectNamesMap.begin();
  2571. it != this->UniqueObjectNamesMap.end(); ++it) {
  2572. if (it->second == ssin) {
  2573. done = false;
  2574. }
  2575. }
  2576. if (done) {
  2577. break;
  2578. }
  2579. sssin = ssin;
  2580. cmSystemTools::ReplaceString(ssin, "_p_", rpstr);
  2581. sprintf(rpstr, "_p%d_", cc++);
  2582. } while (!done);
  2583. }
  2584. #if defined(CM_LG_ENCODE_OBJECT_NAMES)
  2585. if (!cmLocalGeneratorCheckObjectName(ssin, dir_max.size(),
  2586. this->ObjectPathMax)) {
  2587. // Warn if this is the first time the path has been seen.
  2588. if (this->ObjectMaxPathViolations.insert(dir_max).second) {
  2589. std::ostringstream m;
  2590. /* clang-format off */
  2591. m << "The object file directory\n"
  2592. << " " << dir_max << "\n"
  2593. << "has " << dir_max.size() << " characters. "
  2594. << "The maximum full path to an object file is "
  2595. << this->ObjectPathMax << " characters "
  2596. << "(see CMAKE_OBJECT_PATH_MAX). "
  2597. << "Object file\n"
  2598. << " " << ssin << "\n"
  2599. << "cannot be safely placed under this directory. "
  2600. << "The build may not work correctly.";
  2601. /* clang-format on */
  2602. this->IssueMessage(MessageType::WARNING, m.str());
  2603. }
  2604. }
  2605. #else
  2606. (void)dir_max;
  2607. #endif
  2608. // Insert the newly mapped object file name.
  2609. std::map<std::string, std::string>::value_type e(sin, ssin);
  2610. it = this->UniqueObjectNamesMap.insert(e).first;
  2611. }
  2612. // Return the map entry.
  2613. return it->second;
  2614. }
  2615. void cmLocalGenerator::ComputeObjectFilenames(
  2616. std::map<cmSourceFile const*, std::string>& /*unused*/,
  2617. cmGeneratorTarget const* /*unused*/)
  2618. {
  2619. }
  2620. bool cmLocalGenerator::IsWindowsShell() const
  2621. {
  2622. return this->GetState()->UseWindowsShell();
  2623. }
  2624. bool cmLocalGenerator::IsWatcomWMake() const
  2625. {
  2626. return this->GetState()->UseWatcomWMake();
  2627. }
  2628. bool cmLocalGenerator::IsMinGWMake() const
  2629. {
  2630. return this->GetState()->UseMinGWMake();
  2631. }
  2632. bool cmLocalGenerator::IsNMake() const
  2633. {
  2634. return this->GetState()->UseNMake();
  2635. }
  2636. std::string cmLocalGenerator::GetObjectFileNameWithoutTarget(
  2637. const cmSourceFile& source, std::string const& dir_max,
  2638. bool* hasSourceExtension, char const* customOutputExtension)
  2639. {
  2640. // Construct the object file name using the full path to the source
  2641. // file which is its only unique identification.
  2642. std::string const& fullPath = source.GetFullPath();
  2643. // Try referencing the source relative to the source tree.
  2644. std::string relFromSource = this->MaybeConvertToRelativePath(
  2645. this->GetCurrentSourceDirectory(), fullPath);
  2646. assert(!relFromSource.empty());
  2647. bool relSource = !cmSystemTools::FileIsFullPath(relFromSource);
  2648. bool subSource = relSource && relFromSource[0] != '.';
  2649. // Try referencing the source relative to the binary tree.
  2650. std::string relFromBinary = this->MaybeConvertToRelativePath(
  2651. this->GetCurrentBinaryDirectory(), fullPath);
  2652. assert(!relFromBinary.empty());
  2653. bool relBinary = !cmSystemTools::FileIsFullPath(relFromBinary);
  2654. bool subBinary = relBinary && relFromBinary[0] != '.';
  2655. // Select a nice-looking reference to the source file to construct
  2656. // the object file name.
  2657. std::string objectName;
  2658. if ((relSource && !relBinary) || (subSource && !subBinary)) {
  2659. objectName = relFromSource;
  2660. } else if ((relBinary && !relSource) || (subBinary && !subSource)) {
  2661. objectName = relFromBinary;
  2662. } else if (relFromBinary.length() < relFromSource.length()) {
  2663. objectName = relFromBinary;
  2664. } else {
  2665. objectName = relFromSource;
  2666. }
  2667. // if it is still a full path check for the try compile case
  2668. // try compile never have in source sources, and should not
  2669. // have conflicting source file names in the same target
  2670. if (cmSystemTools::FileIsFullPath(objectName)) {
  2671. if (this->GetGlobalGenerator()->GetCMakeInstance()->GetIsInTryCompile()) {
  2672. objectName = cmSystemTools::GetFilenameName(source.GetFullPath());
  2673. }
  2674. }
  2675. // Replace the original source file extension with the object file
  2676. // extension.
  2677. bool keptSourceExtension = true;
  2678. if (!source.GetPropertyAsBool("KEEP_EXTENSION")) {
  2679. // Decide whether this language wants to replace the source
  2680. // extension with the object extension. For CMake 2.4
  2681. // compatibility do this by default.
  2682. bool replaceExt = this->NeedBackwardsCompatibility_2_4();
  2683. if (!replaceExt) {
  2684. std::string lang = source.GetLanguage();
  2685. if (!lang.empty()) {
  2686. replaceExt = this->Makefile->IsOn(
  2687. cmStrCat("CMAKE_", lang, "_OUTPUT_EXTENSION_REPLACE"));
  2688. }
  2689. }
  2690. const char* pchExtension = source.GetProperty("PCH_EXTENSION");
  2691. if (pchExtension) {
  2692. customOutputExtension = pchExtension;
  2693. }
  2694. // Remove the source extension if it is to be replaced.
  2695. if (replaceExt || customOutputExtension) {
  2696. keptSourceExtension = false;
  2697. std::string::size_type dot_pos = objectName.rfind('.');
  2698. if (dot_pos != std::string::npos) {
  2699. objectName = objectName.substr(0, dot_pos);
  2700. }
  2701. }
  2702. // Store the new extension.
  2703. if (customOutputExtension) {
  2704. objectName += customOutputExtension;
  2705. } else {
  2706. objectName += this->GlobalGenerator->GetLanguageOutputExtension(source);
  2707. }
  2708. }
  2709. if (hasSourceExtension) {
  2710. *hasSourceExtension = keptSourceExtension;
  2711. }
  2712. // Convert to a safe name.
  2713. return this->CreateSafeUniqueObjectFileName(objectName, dir_max);
  2714. }
  2715. std::string cmLocalGenerator::GetSourceFileLanguage(const cmSourceFile& source)
  2716. {
  2717. return source.GetLanguage();
  2718. }
  2719. cmake* cmLocalGenerator::GetCMakeInstance() const
  2720. {
  2721. return this->GlobalGenerator->GetCMakeInstance();
  2722. }
  2723. std::string const& cmLocalGenerator::GetSourceDirectory() const
  2724. {
  2725. return this->GetCMakeInstance()->GetHomeDirectory();
  2726. }
  2727. std::string const& cmLocalGenerator::GetBinaryDirectory() const
  2728. {
  2729. return this->GetCMakeInstance()->GetHomeOutputDirectory();
  2730. }
  2731. std::string const& cmLocalGenerator::GetCurrentBinaryDirectory() const
  2732. {
  2733. return this->StateSnapshot.GetDirectory().GetCurrentBinary();
  2734. }
  2735. std::string const& cmLocalGenerator::GetCurrentSourceDirectory() const
  2736. {
  2737. return this->StateSnapshot.GetDirectory().GetCurrentSource();
  2738. }
  2739. std::string cmLocalGenerator::MaybeConvertToRelativePath(
  2740. std::string const& local_path, std::string const& remote_path) const
  2741. {
  2742. return this->StateSnapshot.GetDirectory().ConvertToRelPathIfNotContained(
  2743. local_path, remote_path);
  2744. }
  2745. std::string cmLocalGenerator::GetTargetDirectory(
  2746. const cmGeneratorTarget* /*unused*/) const
  2747. {
  2748. cmSystemTools::Error("GetTargetDirectory"
  2749. " called on cmLocalGenerator");
  2750. return "";
  2751. }
  2752. KWIML_INT_uint64_t cmLocalGenerator::GetBackwardsCompatibility()
  2753. {
  2754. // The computed version may change until the project is fully
  2755. // configured.
  2756. if (!this->BackwardsCompatibilityFinal) {
  2757. unsigned int major = 0;
  2758. unsigned int minor = 0;
  2759. unsigned int patch = 0;
  2760. if (const char* value =
  2761. this->Makefile->GetDefinition("CMAKE_BACKWARDS_COMPATIBILITY")) {
  2762. switch (sscanf(value, "%u.%u.%u", &major, &minor, &patch)) {
  2763. case 2:
  2764. patch = 0;
  2765. break;
  2766. case 1:
  2767. minor = 0;
  2768. patch = 0;
  2769. break;
  2770. default:
  2771. break;
  2772. }
  2773. }
  2774. this->BackwardsCompatibility = CMake_VERSION_ENCODE(major, minor, patch);
  2775. this->BackwardsCompatibilityFinal = true;
  2776. }
  2777. return this->BackwardsCompatibility;
  2778. }
  2779. bool cmLocalGenerator::NeedBackwardsCompatibility_2_4()
  2780. {
  2781. // Check the policy to decide whether to pay attention to this
  2782. // variable.
  2783. switch (this->GetPolicyStatus(cmPolicies::CMP0001)) {
  2784. case cmPolicies::WARN:
  2785. // WARN is just OLD without warning because user code does not
  2786. // always affect whether this check is done.
  2787. case cmPolicies::OLD:
  2788. // Old behavior is to check the variable.
  2789. break;
  2790. case cmPolicies::NEW:
  2791. // New behavior is to ignore the variable.
  2792. return false;
  2793. case cmPolicies::REQUIRED_IF_USED:
  2794. case cmPolicies::REQUIRED_ALWAYS:
  2795. // This will never be the case because the only way to require
  2796. // the setting is to require the user to specify version policy
  2797. // 2.6 or higher. Once we add that requirement then this whole
  2798. // method can be removed anyway.
  2799. return false;
  2800. }
  2801. // Compatibility is needed if CMAKE_BACKWARDS_COMPATIBILITY is set
  2802. // equal to or lower than the given version.
  2803. KWIML_INT_uint64_t actual_compat = this->GetBackwardsCompatibility();
  2804. return (actual_compat && actual_compat <= CMake_VERSION_ENCODE(2, 4, 255));
  2805. }
  2806. cmPolicies::PolicyStatus cmLocalGenerator::GetPolicyStatus(
  2807. cmPolicies::PolicyID id) const
  2808. {
  2809. return this->Makefile->GetPolicyStatus(id);
  2810. }
  2811. bool cmLocalGenerator::CheckDefinition(std::string const& define) const
  2812. {
  2813. // Many compilers do not support -DNAME(arg)=sdf so we disable it.
  2814. std::string::size_type pos = define.find_first_of("(=");
  2815. if (pos != std::string::npos) {
  2816. if (define[pos] == '(') {
  2817. std::ostringstream e;
  2818. /* clang-format off */
  2819. e << "WARNING: Function-style preprocessor definitions may not be "
  2820. << "passed on the compiler command line because many compilers "
  2821. << "do not support it.\n"
  2822. << "CMake is dropping a preprocessor definition: " << define << "\n"
  2823. << "Consider defining the macro in a (configured) header file.\n";
  2824. /* clang-format on */
  2825. cmSystemTools::Message(e.str());
  2826. return false;
  2827. }
  2828. }
  2829. // Many compilers do not support # in the value so we disable it.
  2830. if (define.find_first_of('#') != std::string::npos) {
  2831. std::ostringstream e;
  2832. /* clang-format off */
  2833. e << "WARNING: Preprocessor definitions containing '#' may not be "
  2834. << "passed on the compiler command line because many compilers "
  2835. << "do not support it.\n"
  2836. << "CMake is dropping a preprocessor definition: " << define << "\n"
  2837. << "Consider defining the macro in a (configured) header file.\n";
  2838. /* clang-format on */
  2839. cmSystemTools::Message(e.str());
  2840. return false;
  2841. }
  2842. // Assume it is supported.
  2843. return true;
  2844. }
  2845. static void cmLGInfoProp(cmMakefile* mf, cmGeneratorTarget* target,
  2846. const std::string& prop)
  2847. {
  2848. if (const char* val = target->GetProperty(prop)) {
  2849. mf->AddDefinition(prop, val);
  2850. }
  2851. }
  2852. void cmLocalGenerator::GenerateAppleInfoPList(cmGeneratorTarget* target,
  2853. const std::string& targetName,
  2854. const std::string& fname)
  2855. {
  2856. // Find the Info.plist template.
  2857. const char* in = target->GetProperty("MACOSX_BUNDLE_INFO_PLIST");
  2858. std::string inFile = (in && *in) ? in : "MacOSXBundleInfo.plist.in";
  2859. if (!cmSystemTools::FileIsFullPath(inFile)) {
  2860. std::string inMod = this->Makefile->GetModulesFile(inFile);
  2861. if (!inMod.empty()) {
  2862. inFile = inMod;
  2863. }
  2864. }
  2865. if (!cmSystemTools::FileExists(inFile, true)) {
  2866. std::ostringstream e;
  2867. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  2868. << "\" could not be found.";
  2869. cmSystemTools::Error(e.str());
  2870. return;
  2871. }
  2872. // Convert target properties to variables in an isolated makefile
  2873. // scope to configure the file. If properties are set they will
  2874. // override user make variables. If not the configuration will fall
  2875. // back to the directory-level values set by the user.
  2876. cmMakefile* mf = this->Makefile;
  2877. cmMakefile::ScopePushPop varScope(mf);
  2878. mf->AddDefinition("MACOSX_BUNDLE_EXECUTABLE_NAME", targetName);
  2879. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_INFO_STRING");
  2880. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_ICON_FILE");
  2881. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_GUI_IDENTIFIER");
  2882. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_LONG_VERSION_STRING");
  2883. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_NAME");
  2884. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_SHORT_VERSION_STRING");
  2885. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_VERSION");
  2886. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_COPYRIGHT");
  2887. mf->ConfigureFile(inFile, fname, false, false, false);
  2888. }
  2889. void cmLocalGenerator::GenerateFrameworkInfoPList(
  2890. cmGeneratorTarget* target, const std::string& targetName,
  2891. const std::string& fname)
  2892. {
  2893. // Find the Info.plist template.
  2894. const char* in = target->GetProperty("MACOSX_FRAMEWORK_INFO_PLIST");
  2895. std::string inFile = (in && *in) ? in : "MacOSXFrameworkInfo.plist.in";
  2896. if (!cmSystemTools::FileIsFullPath(inFile)) {
  2897. std::string inMod = this->Makefile->GetModulesFile(inFile);
  2898. if (!inMod.empty()) {
  2899. inFile = inMod;
  2900. }
  2901. }
  2902. if (!cmSystemTools::FileExists(inFile, true)) {
  2903. std::ostringstream e;
  2904. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  2905. << "\" could not be found.";
  2906. cmSystemTools::Error(e.str());
  2907. return;
  2908. }
  2909. // Convert target properties to variables in an isolated makefile
  2910. // scope to configure the file. If properties are set they will
  2911. // override user make variables. If not the configuration will fall
  2912. // back to the directory-level values set by the user.
  2913. cmMakefile* mf = this->Makefile;
  2914. cmMakefile::ScopePushPop varScope(mf);
  2915. mf->AddDefinition("MACOSX_FRAMEWORK_NAME", targetName);
  2916. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_ICON_FILE");
  2917. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_IDENTIFIER");
  2918. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_SHORT_VERSION_STRING");
  2919. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_BUNDLE_VERSION");
  2920. mf->ConfigureFile(inFile, fname, false, false, false);
  2921. }