cmLocalGenerator.cxx 118 KB

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