cmLocalGenerator.cxx 133 KB

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