cmLocalGenerator.cxx 130 KB

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