cmGlobalGenerator.cxx 120 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685
  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 "cmGlobalGenerator.h"
  4. #include <algorithm>
  5. #include <cassert>
  6. #include <cstdio>
  7. #include <cstdlib>
  8. #include <cstring>
  9. #include <functional>
  10. #include <initializer_list>
  11. #include <iterator>
  12. #include <sstream>
  13. #include <type_traits>
  14. #include <utility>
  15. #include <cm/memory>
  16. #include <cm/optional>
  17. #include <cmext/algorithm>
  18. #include <cmext/string_view>
  19. #include "cmsys/Directory.hxx"
  20. #include "cmsys/FStream.hxx"
  21. #include "cmsys/RegularExpression.hxx"
  22. #include "cm_codecvt_Encoding.hxx"
  23. #include "cmAlgorithms.h"
  24. #include "cmCMakePath.h"
  25. #include "cmCPackPropertiesGenerator.h"
  26. #include "cmComputeTargetDepends.h"
  27. #include "cmCryptoHash.h"
  28. #include "cmCustomCommand.h"
  29. #include "cmCustomCommandLines.h"
  30. #include "cmDuration.h"
  31. #include "cmExportBuildFileGenerator.h"
  32. #include "cmExternalMakefileProjectGenerator.h"
  33. #include "cmGeneratedFileStream.h"
  34. #include "cmGeneratorExpression.h"
  35. #include "cmGeneratorTarget.h"
  36. #include "cmInstallGenerator.h"
  37. #include "cmInstallRuntimeDependencySet.h"
  38. #include "cmLinkLineComputer.h"
  39. #include "cmList.h"
  40. #include "cmLocalGenerator.h"
  41. #include "cmMSVC60LinkLineComputer.h"
  42. #include "cmMakefile.h"
  43. #include "cmMessageType.h"
  44. #include "cmOutputConverter.h"
  45. #include "cmPolicies.h"
  46. #include "cmRange.h"
  47. #include "cmSourceFile.h"
  48. #include "cmState.h"
  49. #include "cmStateDirectory.h"
  50. #include "cmStateTypes.h"
  51. #include "cmStringAlgorithms.h"
  52. #include "cmSyntheticTargetCache.h"
  53. #include "cmSystemTools.h"
  54. #include "cmValue.h"
  55. #include "cmVersion.h"
  56. #include "cmWorkingDirectory.h"
  57. #include "cmake.h"
  58. #if !defined(CMAKE_BOOTSTRAP)
  59. # include <cm3p/json/value.h>
  60. # include <cm3p/json/writer.h>
  61. # include "cmQtAutoGenGlobalInitializer.h"
  62. #endif
  63. const std::string kCMAKE_PLATFORM_INFO_INITIALIZED =
  64. "CMAKE_PLATFORM_INFO_INITIALIZED";
  65. class cmInstalledFile;
  66. namespace detail {
  67. std::string GeneratedMakeCommand::QuotedPrintable() const
  68. {
  69. std::string output;
  70. const char* sep = "";
  71. int flags = 0;
  72. #if !defined(_WIN32)
  73. flags |= cmOutputConverter::Shell_Flag_IsUnix;
  74. #endif
  75. for (auto const& arg : this->PrimaryCommand) {
  76. output += cmStrCat(sep, cmOutputConverter::EscapeForShell(arg, flags));
  77. sep = " ";
  78. }
  79. return output;
  80. }
  81. }
  82. bool cmTarget::StrictTargetComparison::operator()(cmTarget const* t1,
  83. cmTarget const* t2) const
  84. {
  85. int nameResult = strcmp(t1->GetName().c_str(), t2->GetName().c_str());
  86. if (nameResult == 0) {
  87. return strcmp(t1->GetMakefile()->GetCurrentBinaryDirectory().c_str(),
  88. t2->GetMakefile()->GetCurrentBinaryDirectory().c_str()) < 0;
  89. }
  90. return nameResult < 0;
  91. }
  92. cmGlobalGenerator::cmGlobalGenerator(cmake* cm)
  93. : CMakeInstance(cm)
  94. {
  95. // By default the .SYMBOLIC dependency is not needed on symbolic rules.
  96. this->NeedSymbolicMark = false;
  97. // by default use the native paths
  98. this->ForceUnixPaths = false;
  99. // By default do not try to support color.
  100. this->ToolSupportsColor = false;
  101. // By default do not use link scripts.
  102. this->UseLinkScript = false;
  103. // Whether an install target is needed.
  104. this->InstallTargetEnabled = false;
  105. // how long to let try compiles run
  106. this->TryCompileTimeout = cmDuration::zero();
  107. this->CurrentConfigureMakefile = nullptr;
  108. this->TryCompileOuterMakefile = nullptr;
  109. this->ConfigureDoneCMP0026AndCMP0024 = false;
  110. this->FirstTimeProgress = 0.0f;
  111. cm->GetState()->SetIsGeneratorMultiConfig(false);
  112. cm->GetState()->SetMinGWMake(false);
  113. cm->GetState()->SetMSYSShell(false);
  114. cm->GetState()->SetNMake(false);
  115. cm->GetState()->SetWatcomWMake(false);
  116. cm->GetState()->SetWindowsShell(false);
  117. cm->GetState()->SetWindowsVSIDE(false);
  118. }
  119. cmGlobalGenerator::~cmGlobalGenerator()
  120. {
  121. this->ClearGeneratorMembers();
  122. }
  123. codecvt_Encoding cmGlobalGenerator::GetMakefileEncoding() const
  124. {
  125. return codecvt_Encoding::None;
  126. }
  127. #if !defined(CMAKE_BOOTSTRAP)
  128. Json::Value cmGlobalGenerator::GetJson() const
  129. {
  130. Json::Value generator = Json::objectValue;
  131. generator["name"] = this->GetName();
  132. generator["multiConfig"] = this->IsMultiConfig();
  133. return generator;
  134. }
  135. #endif
  136. bool cmGlobalGenerator::SetGeneratorInstance(std::string const& i,
  137. cmMakefile* mf)
  138. {
  139. if (i.empty()) {
  140. return true;
  141. }
  142. std::ostringstream e;
  143. /* clang-format off */
  144. e <<
  145. "Generator\n"
  146. " " << this->GetName() << "\n"
  147. "does not support instance specification, but instance\n"
  148. " " << i << "\n"
  149. "was specified.";
  150. /* clang-format on */
  151. mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
  152. return false;
  153. }
  154. bool cmGlobalGenerator::SetGeneratorPlatform(std::string const& p,
  155. cmMakefile* mf)
  156. {
  157. if (p.empty()) {
  158. return true;
  159. }
  160. std::ostringstream e;
  161. /* clang-format off */
  162. e <<
  163. "Generator\n"
  164. " " << this->GetName() << "\n"
  165. "does not support platform specification, but platform\n"
  166. " " << p << "\n"
  167. "was specified.";
  168. /* clang-format on */
  169. mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
  170. return false;
  171. }
  172. bool cmGlobalGenerator::SetGeneratorToolset(std::string const& ts, bool,
  173. cmMakefile* mf)
  174. {
  175. if (ts.empty()) {
  176. return true;
  177. }
  178. std::ostringstream e;
  179. /* clang-format off */
  180. e <<
  181. "Generator\n"
  182. " " << this->GetName() << "\n"
  183. "does not support toolset specification, but toolset\n"
  184. " " << ts << "\n"
  185. "was specified.";
  186. /* clang-format on */
  187. mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
  188. return false;
  189. }
  190. std::string cmGlobalGenerator::SelectMakeProgram(
  191. const std::string& inMakeProgram, const std::string& makeDefault) const
  192. {
  193. std::string makeProgram = inMakeProgram;
  194. if (cmIsOff(makeProgram)) {
  195. cmValue makeProgramCSTR =
  196. this->CMakeInstance->GetCacheDefinition("CMAKE_MAKE_PROGRAM");
  197. if (makeProgramCSTR.IsOff()) {
  198. makeProgram = makeDefault;
  199. } else {
  200. makeProgram = *makeProgramCSTR;
  201. }
  202. if (cmIsOff(makeProgram) && !makeProgram.empty()) {
  203. makeProgram = "CMAKE_MAKE_PROGRAM-NOTFOUND";
  204. }
  205. }
  206. return makeProgram;
  207. }
  208. void cmGlobalGenerator::ResolveLanguageCompiler(const std::string& lang,
  209. cmMakefile* mf,
  210. bool optional) const
  211. {
  212. std::string langComp = cmStrCat("CMAKE_", lang, "_COMPILER");
  213. if (!mf->GetDefinition(langComp)) {
  214. if (!optional) {
  215. cmSystemTools::Error(
  216. cmStrCat(langComp, " not set, after EnableLanguage"));
  217. }
  218. return;
  219. }
  220. std::string const& name = mf->GetRequiredDefinition(langComp);
  221. std::string path;
  222. if (!cmSystemTools::FileIsFullPath(name)) {
  223. path = cmSystemTools::FindProgram(name);
  224. } else {
  225. path = name;
  226. }
  227. if (!optional && (path.empty() || !cmSystemTools::FileExists(path))) {
  228. return;
  229. }
  230. cmValue cname =
  231. this->GetCMakeInstance()->GetState()->GetInitializedCacheValue(langComp);
  232. // Split compiler from arguments
  233. cmList cnameArgList;
  234. if (cname && !cname->empty()) {
  235. cnameArgList.assign(*cname);
  236. cname = cmValue(cnameArgList.front());
  237. }
  238. std::string changeVars;
  239. if (cname && !optional) {
  240. cmCMakePath cachedPath;
  241. if (!cmSystemTools::FileIsFullPath(*cname)) {
  242. cachedPath = cmSystemTools::FindProgram(*cname);
  243. } else {
  244. cachedPath = *cname;
  245. }
  246. cmCMakePath foundPath = path;
  247. if (foundPath.Normal() != cachedPath.Normal()) {
  248. cmValue cvars = this->GetCMakeInstance()->GetState()->GetGlobalProperty(
  249. "__CMAKE_DELETE_CACHE_CHANGE_VARS_");
  250. if (cvars) {
  251. changeVars += *cvars;
  252. changeVars += ";";
  253. }
  254. changeVars += langComp;
  255. changeVars += ";";
  256. changeVars += *cname;
  257. this->GetCMakeInstance()->GetState()->SetGlobalProperty(
  258. "__CMAKE_DELETE_CACHE_CHANGE_VARS_", changeVars);
  259. }
  260. }
  261. }
  262. void cmGlobalGenerator::AddBuildExportSet(cmExportBuildFileGenerator* gen)
  263. {
  264. this->BuildExportSets[gen->GetMainExportFileName()] = gen;
  265. }
  266. void cmGlobalGenerator::AddBuildExportExportSet(
  267. cmExportBuildFileGenerator* gen)
  268. {
  269. this->BuildExportExportSets[gen->GetMainExportFileName()] = gen;
  270. this->AddBuildExportSet(gen);
  271. }
  272. bool cmGlobalGenerator::GenerateImportFile(const std::string& file)
  273. {
  274. auto const it = this->BuildExportSets.find(file);
  275. if (it != this->BuildExportSets.end()) {
  276. bool result = it->second->GenerateImportFile();
  277. if (!this->ConfigureDoneCMP0026AndCMP0024) {
  278. for (const auto& m : this->Makefiles) {
  279. m->RemoveExportBuildFileGeneratorCMP0024(it->second);
  280. }
  281. }
  282. this->BuildExportSets.erase(it);
  283. return result;
  284. }
  285. return false;
  286. }
  287. void cmGlobalGenerator::ForceLinkerLanguages()
  288. {
  289. }
  290. bool cmGlobalGenerator::CheckTargetsForMissingSources() const
  291. {
  292. bool failed = false;
  293. for (const auto& localGen : this->LocalGenerators) {
  294. for (const auto& target : localGen->GetGeneratorTargets()) {
  295. if (!target->CanCompileSources() ||
  296. target->GetProperty("ghs_integrity_app").IsOn()) {
  297. continue;
  298. }
  299. if (target->GetAllConfigSources().empty()) {
  300. std::ostringstream e;
  301. e << "No SOURCES given to target: " << target->GetName();
  302. this->GetCMakeInstance()->IssueMessage(
  303. MessageType::FATAL_ERROR, e.str(), target->GetBacktrace());
  304. failed = true;
  305. }
  306. }
  307. }
  308. return failed;
  309. }
  310. void cmGlobalGenerator::CheckTargetLinkLibraries() const
  311. {
  312. for (const auto& generator : this->LocalGenerators) {
  313. for (const auto& gt : generator->GetGeneratorTargets()) {
  314. gt->CheckLinkLibraries();
  315. }
  316. for (const auto& gt : generator->GetOwnedImportedGeneratorTargets()) {
  317. gt->CheckLinkLibraries();
  318. }
  319. }
  320. }
  321. bool cmGlobalGenerator::CheckTargetsForType() const
  322. {
  323. if (!this->GetLanguageEnabled("Swift")) {
  324. return false;
  325. }
  326. bool failed = false;
  327. for (const auto& generator : this->LocalGenerators) {
  328. for (const auto& target : generator->GetGeneratorTargets()) {
  329. std::string systemName =
  330. target->Makefile->GetSafeDefinition("CMAKE_SYSTEM_NAME");
  331. if (systemName.find("Windows") == std::string::npos) {
  332. continue;
  333. }
  334. if (target->GetType() == cmStateEnums::EXECUTABLE) {
  335. std::vector<std::string> const& configs =
  336. target->Makefile->GetGeneratorConfigs(
  337. cmMakefile::IncludeEmptyConfig);
  338. for (std::string const& config : configs) {
  339. if (target->IsWin32Executable(config) &&
  340. target->GetLinkerLanguage(config) == "Swift") {
  341. this->GetCMakeInstance()->IssueMessage(
  342. MessageType::FATAL_ERROR,
  343. "WIN32_EXECUTABLE property is not supported on Swift "
  344. "executables",
  345. target->GetBacktrace());
  346. failed = true;
  347. }
  348. }
  349. }
  350. }
  351. }
  352. return failed;
  353. }
  354. bool cmGlobalGenerator::CheckTargetsForPchCompilePdb() const
  355. {
  356. if (!this->GetLanguageEnabled("C") && !this->GetLanguageEnabled("CXX")) {
  357. return false;
  358. }
  359. bool failed = false;
  360. for (const auto& generator : this->LocalGenerators) {
  361. for (const auto& target : generator->GetGeneratorTargets()) {
  362. if (!target->CanCompileSources() ||
  363. target->GetProperty("ghs_integrity_app").IsOn()) {
  364. continue;
  365. }
  366. std::string const& reuseFrom =
  367. target->GetSafeProperty("PRECOMPILE_HEADERS_REUSE_FROM");
  368. std::string const& compilePdb =
  369. target->GetSafeProperty("COMPILE_PDB_NAME");
  370. if (!reuseFrom.empty() && reuseFrom != compilePdb) {
  371. const std::string e = cmStrCat(
  372. "PRECOMPILE_HEADERS_REUSE_FROM property is set on target (\"",
  373. target->GetName(),
  374. "\"). Reusable precompile headers requires the COMPILE_PDB_NAME"
  375. " property to have the value \"",
  376. reuseFrom, "\"\n");
  377. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR, e,
  378. target->GetBacktrace());
  379. failed = true;
  380. }
  381. }
  382. }
  383. return failed;
  384. }
  385. bool cmGlobalGenerator::IsExportedTargetsFile(
  386. const std::string& filename) const
  387. {
  388. auto const it = this->BuildExportSets.find(filename);
  389. if (it == this->BuildExportSets.end()) {
  390. return false;
  391. }
  392. return !cm::contains(this->BuildExportExportSets, filename);
  393. }
  394. // Find the make program for the generator, required for try compiles
  395. bool cmGlobalGenerator::FindMakeProgram(cmMakefile* mf)
  396. {
  397. if (this->FindMakeProgramFile.empty()) {
  398. cmSystemTools::Error(
  399. "Generator implementation error, "
  400. "all generators must specify this->FindMakeProgramFile");
  401. return false;
  402. }
  403. if (mf->GetDefinition("CMAKE_MAKE_PROGRAM").IsOff()) {
  404. std::string setMakeProgram = mf->GetModulesFile(this->FindMakeProgramFile);
  405. if (!setMakeProgram.empty()) {
  406. mf->ReadListFile(setMakeProgram);
  407. }
  408. }
  409. if (mf->GetDefinition("CMAKE_MAKE_PROGRAM").IsOff()) {
  410. std::ostringstream err;
  411. err << "CMake was unable to find a build program corresponding to \""
  412. << this->GetName() << "\". CMAKE_MAKE_PROGRAM is not set. You "
  413. << "probably need to select a different build tool.";
  414. cmSystemTools::Error(err.str());
  415. cmSystemTools::SetFatalErrorOccurred();
  416. return false;
  417. }
  418. std::string makeProgram = mf->GetRequiredDefinition("CMAKE_MAKE_PROGRAM");
  419. // if there are spaces in the make program use short path
  420. // but do not short path the actual program name, as
  421. // this can cause trouble with VSExpress
  422. if (makeProgram.find(' ') != std::string::npos) {
  423. std::string dir;
  424. std::string file;
  425. cmSystemTools::SplitProgramPath(makeProgram, dir, file);
  426. std::string saveFile = file;
  427. cmSystemTools::GetShortPath(makeProgram, makeProgram);
  428. cmSystemTools::SplitProgramPath(makeProgram, dir, file);
  429. makeProgram = cmStrCat(dir, '/', saveFile);
  430. mf->AddCacheDefinition("CMAKE_MAKE_PROGRAM", makeProgram, "make program",
  431. cmStateEnums::FILEPATH);
  432. }
  433. return true;
  434. }
  435. bool cmGlobalGenerator::CheckLanguages(
  436. std::vector<std::string> const& /* languages */, cmMakefile* /* mf */) const
  437. {
  438. return true;
  439. }
  440. // enable the given language
  441. //
  442. // The following files are loaded in this order:
  443. //
  444. // First figure out what OS we are running on:
  445. //
  446. // CMakeSystem.cmake - configured file created by CMakeDetermineSystem.cmake
  447. // CMakeDetermineSystem.cmake - figure out os info and create
  448. // CMakeSystem.cmake IF CMAKE_SYSTEM
  449. // not set
  450. // CMakeSystem.cmake - configured file created by
  451. // CMakeDetermineSystem.cmake IF CMAKE_SYSTEM_LOADED
  452. // CMakeSystemSpecificInitialize.cmake
  453. // - includes Platform/${CMAKE_SYSTEM_NAME}-Initialize.cmake
  454. // Next try and enable all languages found in the languages vector
  455. //
  456. // FOREACH LANG in languages
  457. // CMake(LANG)Compiler.cmake - configured file create by
  458. // CMakeDetermine(LANG)Compiler.cmake
  459. // CMakeDetermine(LANG)Compiler.cmake - Finds compiler for LANG and
  460. // creates CMake(LANG)Compiler.cmake
  461. // CMake(LANG)Compiler.cmake - configured file created by
  462. // CMakeDetermine(LANG)Compiler.cmake
  463. //
  464. // CMakeSystemSpecificInformation.cmake
  465. // - includes Platform/${CMAKE_SYSTEM_NAME}.cmake
  466. // may use compiler stuff
  467. // FOREACH LANG in languages
  468. // CMake(LANG)Information.cmake
  469. // - loads Platform/${CMAKE_SYSTEM_NAME}-${COMPILER}.cmake
  470. // CMakeTest(LANG)Compiler.cmake
  471. // - Make sure the compiler works with a try compile if
  472. // CMakeDetermine(LANG) was loaded
  473. //
  474. // Now load a few files that can override values set in any of the above
  475. // (PROJECTNAME)Compatibility.cmake
  476. // - load any backwards compatibility stuff for current project
  477. // ${CMAKE_USER_MAKE_RULES_OVERRIDE}
  478. // - allow users a chance to override system variables
  479. //
  480. //
  481. void cmGlobalGenerator::EnableLanguage(
  482. std::vector<std::string> const& languages, cmMakefile* mf, bool optional)
  483. {
  484. if (!this->IsMultiConfig() &&
  485. !this->GetCMakeInstance()->GetIsInTryCompile()) {
  486. std::string envBuildType;
  487. if (!mf->GetDefinition("CMAKE_BUILD_TYPE") &&
  488. cmSystemTools::GetEnv("CMAKE_BUILD_TYPE", envBuildType)) {
  489. mf->AddCacheDefinition(
  490. "CMAKE_BUILD_TYPE", envBuildType,
  491. "Choose the type of build. Options include: empty, "
  492. "Debug, Release, RelWithDebInfo, MinSizeRel.",
  493. cmStateEnums::STRING);
  494. }
  495. }
  496. if (languages.empty()) {
  497. cmSystemTools::Error("EnableLanguage must have a lang specified!");
  498. cmSystemTools::SetFatalErrorOccurred();
  499. return;
  500. }
  501. std::set<std::string> cur_languages(languages.begin(), languages.end());
  502. for (std::string const& li : cur_languages) {
  503. if (!this->LanguagesInProgress.insert(li).second) {
  504. std::ostringstream e;
  505. e << "Language '" << li
  506. << "' is currently being enabled. "
  507. "Recursive call not allowed.";
  508. mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
  509. cmSystemTools::SetFatalErrorOccurred();
  510. return;
  511. }
  512. }
  513. if (this->TryCompileOuterMakefile) {
  514. // In a try-compile we can only enable languages provided by caller.
  515. for (std::string const& lang : languages) {
  516. if (lang == "NONE") {
  517. this->SetLanguageEnabled("NONE", mf);
  518. } else {
  519. if (!cm::contains(this->LanguagesReady, lang)) {
  520. std::ostringstream e;
  521. e << "The test project needs language " << lang
  522. << " which is not enabled.";
  523. this->TryCompileOuterMakefile->IssueMessage(MessageType::FATAL_ERROR,
  524. e.str());
  525. cmSystemTools::SetFatalErrorOccurred();
  526. return;
  527. }
  528. }
  529. }
  530. }
  531. bool fatalError = false;
  532. mf->AddDefinitionBool("RUN_CONFIGURE", true);
  533. std::string rootBin =
  534. cmStrCat(this->CMakeInstance->GetHomeOutputDirectory(), "/CMakeFiles");
  535. // If the configuration files path has been set,
  536. // then we are in a try compile and need to copy the enable language
  537. // files from the parent cmake bin dir, into the try compile bin dir
  538. if (!this->ConfiguredFilesPath.empty()) {
  539. rootBin = this->ConfiguredFilesPath;
  540. }
  541. rootBin += '/';
  542. rootBin += cmVersion::GetCMakeVersion();
  543. // set the dir for parent files so they can be used by modules
  544. mf->AddDefinition("CMAKE_PLATFORM_INFO_DIR", rootBin);
  545. if (!this->CMakeInstance->GetIsInTryCompile()) {
  546. // Keep a mark in the cache to indicate that we've initialized the
  547. // platform information directory. If the platform information
  548. // directory exists but the mark is missing then CMakeCache.txt
  549. // has been removed or replaced without also removing the CMakeFiles/
  550. // directory. In this case remove the platform information directory
  551. // so that it will be re-initialized and the relevant information
  552. // restored in the cache.
  553. if (cmSystemTools::FileIsDirectory(rootBin) &&
  554. !mf->IsOn(kCMAKE_PLATFORM_INFO_INITIALIZED)) {
  555. cmSystemTools::RemoveADirectory(rootBin);
  556. }
  557. this->GetCMakeInstance()->AddCacheEntry(
  558. kCMAKE_PLATFORM_INFO_INITIALIZED, "1",
  559. "Platform information initialized", cmStateEnums::INTERNAL);
  560. }
  561. // try and load the CMakeSystem.cmake if it is there
  562. std::string fpath = rootBin;
  563. bool const readCMakeSystem = !mf->GetDefinition("CMAKE_SYSTEM_LOADED");
  564. if (readCMakeSystem) {
  565. fpath += "/CMakeSystem.cmake";
  566. if (cmSystemTools::FileExists(fpath)) {
  567. mf->ReadListFile(fpath);
  568. }
  569. }
  570. // Load the CMakeDetermineSystem.cmake file and find out
  571. // what platform we are running on
  572. if (!mf->GetDefinition("CMAKE_SYSTEM")) {
  573. #if defined(_WIN32) && !defined(__CYGWIN__)
  574. cmSystemTools::WindowsVersion windowsVersion =
  575. cmSystemTools::GetWindowsVersion();
  576. auto windowsVersionString = cmStrCat(windowsVersion.dwMajorVersion, '.',
  577. windowsVersion.dwMinorVersion, '.',
  578. windowsVersion.dwBuildNumber);
  579. mf->AddDefinition("CMAKE_HOST_SYSTEM_VERSION", windowsVersionString);
  580. #endif
  581. // Read the DetermineSystem file
  582. std::string systemFile = mf->GetModulesFile("CMakeDetermineSystem.cmake");
  583. mf->ReadListFile(systemFile);
  584. // load the CMakeSystem.cmake from the binary directory
  585. // this file is configured by the CMakeDetermineSystem.cmake file
  586. fpath = cmStrCat(rootBin, "/CMakeSystem.cmake");
  587. mf->ReadListFile(fpath);
  588. }
  589. if (readCMakeSystem) {
  590. // Tell the generator about the instance, if any.
  591. std::string instance = mf->GetSafeDefinition("CMAKE_GENERATOR_INSTANCE");
  592. if (!this->SetGeneratorInstance(instance, mf)) {
  593. cmSystemTools::SetFatalErrorOccurred();
  594. return;
  595. }
  596. // Tell the generator about the target system.
  597. std::string system = mf->GetSafeDefinition("CMAKE_SYSTEM_NAME");
  598. if (!this->SetSystemName(system, mf)) {
  599. cmSystemTools::SetFatalErrorOccurred();
  600. return;
  601. }
  602. // Tell the generator about the platform, if any.
  603. std::string platform = mf->GetSafeDefinition("CMAKE_GENERATOR_PLATFORM");
  604. if (!this->SetGeneratorPlatform(platform, mf)) {
  605. cmSystemTools::SetFatalErrorOccurred();
  606. return;
  607. }
  608. // Tell the generator about the toolset, if any.
  609. std::string toolset = mf->GetSafeDefinition("CMAKE_GENERATOR_TOOLSET");
  610. if (!this->SetGeneratorToolset(toolset, false, mf)) {
  611. cmSystemTools::SetFatalErrorOccurred();
  612. return;
  613. }
  614. // Find the native build tool for this generator.
  615. if (!this->FindMakeProgram(mf)) {
  616. return;
  617. }
  618. // One-time includes of user-provided project setup files
  619. mf->GetState()->SetInTopLevelIncludes(true);
  620. std::string includes =
  621. mf->GetSafeDefinition("CMAKE_PROJECT_TOP_LEVEL_INCLUDES");
  622. cmList includesList{ includes };
  623. for (std::string setupFile : includesList) {
  624. // Any relative path without a .cmake extension is checked for valid
  625. // cmake modules. This logic should be consistent with CMake's include()
  626. // command. Otherwise default to checking relative path w.r.t. source
  627. // directory
  628. if (!cmSystemTools::FileIsFullPath(setupFile) &&
  629. !cmHasLiteralSuffix(setupFile, ".cmake")) {
  630. std::string mfile = mf->GetModulesFile(cmStrCat(setupFile, ".cmake"));
  631. if (mfile.empty()) {
  632. cmSystemTools::Error(cmStrCat(
  633. "CMAKE_PROJECT_TOP_LEVEL_INCLUDES module:\n ", setupFile));
  634. mf->GetState()->SetInTopLevelIncludes(false);
  635. return;
  636. }
  637. setupFile = mfile;
  638. }
  639. std::string absSetupFile = cmSystemTools::CollapseFullPath(
  640. setupFile, mf->GetCurrentSourceDirectory());
  641. if (!cmSystemTools::FileExists(absSetupFile)) {
  642. cmSystemTools::Error(
  643. cmStrCat("CMAKE_PROJECT_TOP_LEVEL_INCLUDES file does not exist: ",
  644. setupFile));
  645. mf->GetState()->SetInTopLevelIncludes(false);
  646. return;
  647. }
  648. if (cmSystemTools::FileIsDirectory(absSetupFile)) {
  649. cmSystemTools::Error(
  650. cmStrCat("CMAKE_PROJECT_TOP_LEVEL_INCLUDES file is a directory: ",
  651. setupFile));
  652. mf->GetState()->SetInTopLevelIncludes(false);
  653. return;
  654. }
  655. if (!mf->ReadListFile(absSetupFile)) {
  656. cmSystemTools::Error(
  657. cmStrCat("Failed reading CMAKE_PROJECT_TOP_LEVEL_INCLUDES file: ",
  658. setupFile));
  659. mf->GetState()->SetInTopLevelIncludes(false);
  660. return;
  661. }
  662. }
  663. }
  664. mf->GetState()->SetInTopLevelIncludes(false);
  665. // Check that the languages are supported by the generator and its
  666. // native build tool found above.
  667. if (!this->CheckLanguages(languages, mf)) {
  668. return;
  669. }
  670. // **** Load the system specific initialization if not yet loaded
  671. if (!mf->GetDefinition("CMAKE_SYSTEM_SPECIFIC_INITIALIZE_LOADED")) {
  672. fpath = mf->GetModulesFile("CMakeSystemSpecificInitialize.cmake");
  673. if (!mf->ReadListFile(fpath)) {
  674. cmSystemTools::Error("Could not find cmake module file: "
  675. "CMakeSystemSpecificInitialize.cmake");
  676. }
  677. }
  678. std::map<std::string, bool> needTestLanguage;
  679. std::map<std::string, bool> needSetLanguageEnabledMaps;
  680. // foreach language
  681. // load the CMakeDetermine(LANG)Compiler.cmake file to find
  682. // the compiler
  683. for (std::string const& lang : languages) {
  684. needSetLanguageEnabledMaps[lang] = false;
  685. if (lang == "NONE") {
  686. this->SetLanguageEnabled("NONE", mf);
  687. continue;
  688. }
  689. std::string loadedLang = cmStrCat("CMAKE_", lang, "_COMPILER_LOADED");
  690. if (!mf->GetDefinition(loadedLang)) {
  691. fpath = cmStrCat(rootBin, "/CMake", lang, "Compiler.cmake");
  692. // If the existing build tree was already configured with this
  693. // version of CMake then try to load the configured file first
  694. // to avoid duplicate compiler tests.
  695. if (cmSystemTools::FileExists(fpath)) {
  696. if (!mf->ReadListFile(fpath)) {
  697. cmSystemTools::Error(
  698. cmStrCat("Could not find cmake module file: ", fpath));
  699. }
  700. // if this file was found then the language was already determined
  701. // to be working
  702. needTestLanguage[lang] = false;
  703. this->SetLanguageEnabledFlag(lang, mf);
  704. needSetLanguageEnabledMaps[lang] = true;
  705. // this can only be called after loading CMake(LANG)Compiler.cmake
  706. }
  707. }
  708. if (!this->GetLanguageEnabled(lang)) {
  709. if (this->CMakeInstance->GetIsInTryCompile()) {
  710. cmSystemTools::Error("This should not have happened. "
  711. "If you see this message, you are probably "
  712. "using a broken CMakeLists.txt file or a "
  713. "problematic release of CMake");
  714. }
  715. // if the CMake(LANG)Compiler.cmake file was not found then
  716. // load CMakeDetermine(LANG)Compiler.cmake
  717. std::string determineCompiler =
  718. cmStrCat("CMakeDetermine", lang, "Compiler.cmake");
  719. std::string determineFile = mf->GetModulesFile(determineCompiler);
  720. if (!mf->ReadListFile(determineFile)) {
  721. cmSystemTools::Error(
  722. cmStrCat("Could not find cmake module file: ", determineCompiler));
  723. }
  724. if (cmSystemTools::GetFatalErrorOccurred()) {
  725. return;
  726. }
  727. needTestLanguage[lang] = true;
  728. // Some generators like visual studio should not use the env variables
  729. // So the global generator can specify that in this variable
  730. if ((mf->GetPolicyStatus(cmPolicies::CMP0132) == cmPolicies::OLD ||
  731. mf->GetPolicyStatus(cmPolicies::CMP0132) == cmPolicies::WARN) &&
  732. !mf->GetDefinition("CMAKE_GENERATOR_NO_COMPILER_ENV")) {
  733. // put ${CMake_(LANG)_COMPILER_ENV_VAR}=${CMAKE_(LANG)_COMPILER
  734. // into the environment, in case user scripts want to run
  735. // configure, or sub cmakes
  736. std::string compilerName = cmStrCat("CMAKE_", lang, "_COMPILER");
  737. std::string compilerEnv =
  738. cmStrCat("CMAKE_", lang, "_COMPILER_ENV_VAR");
  739. const std::string& envVar = mf->GetRequiredDefinition(compilerEnv);
  740. const std::string& envVarValue =
  741. mf->GetRequiredDefinition(compilerName);
  742. std::string env = cmStrCat(envVar, '=', envVarValue);
  743. cmSystemTools::PutEnv(env);
  744. }
  745. // if determineLanguage was called then load the file it
  746. // configures CMake(LANG)Compiler.cmake
  747. fpath = cmStrCat(rootBin, "/CMake", lang, "Compiler.cmake");
  748. if (!mf->ReadListFile(fpath)) {
  749. cmSystemTools::Error(
  750. cmStrCat("Could not find cmake module file: ", fpath));
  751. }
  752. this->SetLanguageEnabledFlag(lang, mf);
  753. needSetLanguageEnabledMaps[lang] = true;
  754. // this can only be called after loading CMake(LANG)Compiler.cmake
  755. // the language must be enabled for try compile to work, but we do
  756. // not know if it is a working compiler yet so set the test language
  757. // flag
  758. needTestLanguage[lang] = true;
  759. } // end if(!this->GetLanguageEnabled(lang) )
  760. } // end loop over languages
  761. // **** Load the system specific information if not yet loaded
  762. if (!mf->GetDefinition("CMAKE_SYSTEM_SPECIFIC_INFORMATION_LOADED")) {
  763. fpath = mf->GetModulesFile("CMakeSystemSpecificInformation.cmake");
  764. if (!mf->ReadListFile(fpath)) {
  765. cmSystemTools::Error("Could not find cmake module file: "
  766. "CMakeSystemSpecificInformation.cmake");
  767. }
  768. }
  769. // loop over languages again loading CMake(LANG)Information.cmake
  770. //
  771. for (std::string const& lang : languages) {
  772. if (lang == "NONE") {
  773. this->SetLanguageEnabled("NONE", mf);
  774. continue;
  775. }
  776. // Check that the compiler was found.
  777. std::string compilerName = cmStrCat("CMAKE_", lang, "_COMPILER");
  778. std::string compilerEnv = cmStrCat("CMAKE_", lang, "_COMPILER_ENV_VAR");
  779. std::ostringstream noCompiler;
  780. cmValue compilerFile = mf->GetDefinition(compilerName);
  781. if (!cmNonempty(compilerFile) || cmIsNOTFOUND(*compilerFile)) {
  782. /* clang-format off */
  783. noCompiler <<
  784. "No " << compilerName << " could be found.\n"
  785. ;
  786. /* clang-format on */
  787. } else if ((lang != "RC") && (lang != "ASM_MARMASM") &&
  788. (lang != "ASM_MASM")) {
  789. if (!cmSystemTools::FileIsFullPath(*compilerFile)) {
  790. /* clang-format off */
  791. noCompiler <<
  792. "The " << compilerName << ":\n"
  793. " " << *compilerFile << "\n"
  794. "is not a full path and was not found in the PATH."
  795. #ifdef _WIN32
  796. " Perhaps the extension is missing?"
  797. #endif
  798. "\n"
  799. ;
  800. /* clang-format on */
  801. } else if (!cmSystemTools::FileExists(*compilerFile)) {
  802. /* clang-format off */
  803. noCompiler <<
  804. "The " << compilerName << ":\n"
  805. " " << *compilerFile << "\n"
  806. "is not a full path to an existing compiler tool.\n"
  807. ;
  808. /* clang-format on */
  809. }
  810. }
  811. if (!noCompiler.str().empty()) {
  812. // Skip testing this language since the compiler is not found.
  813. needTestLanguage[lang] = false;
  814. if (!optional) {
  815. // The compiler was not found and it is not optional. Remove
  816. // CMake(LANG)Compiler.cmake so we try again next time CMake runs.
  817. std::string compilerLangFile =
  818. cmStrCat(rootBin, "/CMake", lang, "Compiler.cmake");
  819. cmSystemTools::RemoveFile(compilerLangFile);
  820. if (!this->CMakeInstance->GetIsInTryCompile()) {
  821. this->PrintCompilerAdvice(noCompiler, lang,
  822. mf->GetDefinition(compilerEnv));
  823. mf->IssueMessage(MessageType::FATAL_ERROR, noCompiler.str());
  824. fatalError = true;
  825. }
  826. }
  827. }
  828. std::string langLoadedVar =
  829. cmStrCat("CMAKE_", lang, "_INFORMATION_LOADED");
  830. if (!mf->GetDefinition(langLoadedVar)) {
  831. fpath = cmStrCat("CMake", lang, "Information.cmake");
  832. std::string informationFile = mf->GetModulesFile(fpath);
  833. if (informationFile.empty()) {
  834. cmSystemTools::Error(
  835. cmStrCat("Could not find cmake module file: ", fpath));
  836. } else if (!mf->ReadListFile(informationFile)) {
  837. cmSystemTools::Error(
  838. cmStrCat("Could not process cmake module file: ", informationFile));
  839. }
  840. }
  841. if (needSetLanguageEnabledMaps[lang]) {
  842. this->SetLanguageEnabledMaps(lang, mf);
  843. }
  844. this->LanguagesReady.insert(lang);
  845. // Test the compiler for the language just setup
  846. // (but only if a compiler has been actually found)
  847. // At this point we should have enough info for a try compile
  848. // which is used in the backward stuff
  849. // If the language is untested then test it now with a try compile.
  850. if (needTestLanguage[lang]) {
  851. if (!this->CMakeInstance->GetIsInTryCompile()) {
  852. std::string testLang = cmStrCat("CMakeTest", lang, "Compiler.cmake");
  853. std::string ifpath = mf->GetModulesFile(testLang);
  854. if (!mf->ReadListFile(ifpath)) {
  855. cmSystemTools::Error(
  856. cmStrCat("Could not find cmake module file: ", testLang));
  857. }
  858. std::string compilerWorks =
  859. cmStrCat("CMAKE_", lang, "_COMPILER_WORKS");
  860. // if the compiler did not work, then remove the
  861. // CMake(LANG)Compiler.cmake file so that it will get tested the
  862. // next time cmake is run
  863. if (!mf->IsOn(compilerWorks)) {
  864. std::string compilerLangFile =
  865. cmStrCat(rootBin, "/CMake", lang, "Compiler.cmake");
  866. cmSystemTools::RemoveFile(compilerLangFile);
  867. }
  868. } // end if in try compile
  869. } // end need test language
  870. // Store the shared library flags so that we can satisfy CMP0018
  871. std::string sharedLibFlagsVar =
  872. cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS");
  873. this->LanguageToOriginalSharedLibFlags[lang] =
  874. mf->GetSafeDefinition(sharedLibFlagsVar);
  875. // Translate compiler ids for compatibility.
  876. this->CheckCompilerIdCompatibility(mf, lang);
  877. } // end for each language
  878. // Now load files that can override any settings on the platform or for
  879. // the project First load the project compatibility file if it is in
  880. // cmake
  881. std::string projectCompatibility =
  882. cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules/",
  883. mf->GetSafeDefinition("PROJECT_NAME"), "Compatibility.cmake");
  884. if (cmSystemTools::FileExists(projectCompatibility)) {
  885. mf->ReadListFile(projectCompatibility);
  886. }
  887. // Inform any extra generator of the new language.
  888. if (this->ExtraGenerator) {
  889. this->ExtraGenerator->EnableLanguage(languages, mf, false);
  890. }
  891. if (fatalError) {
  892. cmSystemTools::SetFatalErrorOccurred();
  893. }
  894. for (std::string const& lang : cur_languages) {
  895. this->LanguagesInProgress.erase(lang);
  896. }
  897. }
  898. void cmGlobalGenerator::PrintCompilerAdvice(std::ostream& os,
  899. std::string const& lang,
  900. cmValue envVar) const
  901. {
  902. // Subclasses override this method if they do not support this advice.
  903. os << "Tell CMake where to find the compiler by setting ";
  904. if (envVar) {
  905. os << "either the environment variable \"" << *envVar << "\" or ";
  906. }
  907. os << "the CMake cache entry CMAKE_" << lang
  908. << "_COMPILER "
  909. "to the full path to the compiler, or to the compiler name "
  910. "if it is in the PATH.";
  911. }
  912. void cmGlobalGenerator::CheckCompilerIdCompatibility(
  913. cmMakefile* mf, std::string const& lang) const
  914. {
  915. std::string compilerIdVar = cmStrCat("CMAKE_", lang, "_COMPILER_ID");
  916. std::string const compilerId = mf->GetSafeDefinition(compilerIdVar);
  917. if (compilerId == "AppleClang") {
  918. switch (mf->GetPolicyStatus(cmPolicies::CMP0025)) {
  919. case cmPolicies::WARN:
  920. if (!this->CMakeInstance->GetIsInTryCompile() &&
  921. mf->PolicyOptionalWarningEnabled("CMAKE_POLICY_WARNING_CMP0025")) {
  922. std::ostringstream w;
  923. /* clang-format off */
  924. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0025) << "\n"
  925. "Converting " << lang <<
  926. R"( compiler id "AppleClang" to "Clang" for compatibility.)"
  927. ;
  928. /* clang-format on */
  929. mf->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  930. }
  931. CM_FALLTHROUGH;
  932. case cmPolicies::OLD:
  933. // OLD behavior is to convert AppleClang to Clang.
  934. mf->AddDefinition(compilerIdVar, "Clang");
  935. break;
  936. case cmPolicies::REQUIRED_IF_USED:
  937. case cmPolicies::REQUIRED_ALWAYS:
  938. mf->IssueMessage(
  939. MessageType::FATAL_ERROR,
  940. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0025));
  941. break;
  942. case cmPolicies::NEW:
  943. // NEW behavior is to keep AppleClang.
  944. break;
  945. }
  946. }
  947. if (compilerId == "QCC") {
  948. switch (mf->GetPolicyStatus(cmPolicies::CMP0047)) {
  949. case cmPolicies::WARN:
  950. if (!this->CMakeInstance->GetIsInTryCompile() &&
  951. mf->PolicyOptionalWarningEnabled("CMAKE_POLICY_WARNING_CMP0047")) {
  952. std::ostringstream w;
  953. /* clang-format off */
  954. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0047) << "\n"
  955. "Converting " << lang <<
  956. R"( compiler id "QCC" to "GNU" for compatibility.)"
  957. ;
  958. /* clang-format on */
  959. mf->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  960. }
  961. CM_FALLTHROUGH;
  962. case cmPolicies::OLD:
  963. // OLD behavior is to convert QCC to GNU.
  964. mf->AddDefinition(compilerIdVar, "GNU");
  965. if (lang == "C") {
  966. mf->AddDefinition("CMAKE_COMPILER_IS_GNUCC", "1");
  967. } else if (lang == "CXX") {
  968. mf->AddDefinition("CMAKE_COMPILER_IS_GNUCXX", "1");
  969. }
  970. break;
  971. case cmPolicies::REQUIRED_IF_USED:
  972. case cmPolicies::REQUIRED_ALWAYS:
  973. mf->IssueMessage(
  974. MessageType::FATAL_ERROR,
  975. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0047));
  976. CM_FALLTHROUGH;
  977. case cmPolicies::NEW:
  978. // NEW behavior is to keep QCC.
  979. break;
  980. }
  981. }
  982. if (compilerId == "XLClang") {
  983. switch (mf->GetPolicyStatus(cmPolicies::CMP0089)) {
  984. case cmPolicies::WARN:
  985. if (!this->CMakeInstance->GetIsInTryCompile() &&
  986. mf->PolicyOptionalWarningEnabled("CMAKE_POLICY_WARNING_CMP0089")) {
  987. std::ostringstream w;
  988. /* clang-format off */
  989. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0089) << "\n"
  990. "Converting " << lang <<
  991. R"( compiler id "XLClang" to "XL" for compatibility.)"
  992. ;
  993. /* clang-format on */
  994. mf->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  995. }
  996. CM_FALLTHROUGH;
  997. case cmPolicies::OLD:
  998. // OLD behavior is to convert XLClang to XL.
  999. mf->AddDefinition(compilerIdVar, "XL");
  1000. break;
  1001. case cmPolicies::REQUIRED_IF_USED:
  1002. case cmPolicies::REQUIRED_ALWAYS:
  1003. mf->IssueMessage(
  1004. MessageType::FATAL_ERROR,
  1005. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0089));
  1006. break;
  1007. case cmPolicies::NEW:
  1008. // NEW behavior is to keep AppleClang.
  1009. break;
  1010. }
  1011. }
  1012. if (compilerId == "LCC") {
  1013. switch (mf->GetPolicyStatus(cmPolicies::CMP0129)) {
  1014. case cmPolicies::WARN:
  1015. if (!this->CMakeInstance->GetIsInTryCompile() &&
  1016. mf->PolicyOptionalWarningEnabled("CMAKE_POLICY_WARNING_CMP0129")) {
  1017. std::ostringstream w;
  1018. /* clang-format off */
  1019. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0129) << "\n"
  1020. "Converting " << lang <<
  1021. R"( compiler id "LCC" to "GNU" for compatibility.)"
  1022. ;
  1023. /* clang-format on */
  1024. mf->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  1025. }
  1026. CM_FALLTHROUGH;
  1027. case cmPolicies::OLD:
  1028. // OLD behavior is to convert LCC to GNU.
  1029. mf->AddDefinition(compilerIdVar, "GNU");
  1030. if (lang == "C") {
  1031. mf->AddDefinition("CMAKE_COMPILER_IS_GNUCC", "1");
  1032. } else if (lang == "CXX") {
  1033. mf->AddDefinition("CMAKE_COMPILER_IS_GNUCXX", "1");
  1034. } else if (lang == "Fortran") {
  1035. mf->AddDefinition("CMAKE_COMPILER_IS_GNUG77", "1");
  1036. }
  1037. {
  1038. // Fix compiler versions.
  1039. std::string version = cmStrCat("CMAKE_", lang, "_COMPILER_VERSION");
  1040. std::string emulated = cmStrCat("CMAKE_", lang, "_SIMULATE_VERSION");
  1041. std::string emulatedId = cmStrCat("CMAKE_", lang, "_SIMULATE_ID");
  1042. std::string const& actual = mf->GetRequiredDefinition(emulated);
  1043. mf->AddDefinition(version, actual);
  1044. mf->RemoveDefinition(emulatedId);
  1045. mf->RemoveDefinition(emulated);
  1046. }
  1047. break;
  1048. case cmPolicies::REQUIRED_IF_USED:
  1049. case cmPolicies::REQUIRED_ALWAYS:
  1050. mf->IssueMessage(
  1051. MessageType::FATAL_ERROR,
  1052. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0129));
  1053. CM_FALLTHROUGH;
  1054. case cmPolicies::NEW:
  1055. // NEW behavior is to keep LCC.
  1056. break;
  1057. }
  1058. }
  1059. }
  1060. std::string cmGlobalGenerator::GetLanguageOutputExtension(
  1061. cmSourceFile const& source) const
  1062. {
  1063. const std::string& lang = source.GetLanguage();
  1064. if (!lang.empty()) {
  1065. return this->GetLanguageOutputExtension(lang);
  1066. }
  1067. // if no language is found then check to see if it is already an
  1068. // output extension for some language. In that case it should be ignored
  1069. // and in this map, so it will not be compiled but will just be used.
  1070. std::string const& ext = source.GetExtension();
  1071. if (!ext.empty()) {
  1072. if (this->OutputExtensions.count(ext)) {
  1073. return ext;
  1074. }
  1075. }
  1076. return "";
  1077. }
  1078. std::string cmGlobalGenerator::GetLanguageOutputExtension(
  1079. std::string const& lang) const
  1080. {
  1081. auto const it = this->LanguageToOutputExtension.find(lang);
  1082. if (it != this->LanguageToOutputExtension.end()) {
  1083. return it->second;
  1084. }
  1085. return "";
  1086. }
  1087. std::string cmGlobalGenerator::GetLanguageFromExtension(const char* ext) const
  1088. {
  1089. // if there is an extension and it starts with . then move past the
  1090. // . because the extensions are not stored with a . in the map
  1091. if (!ext) {
  1092. return "";
  1093. }
  1094. if (*ext == '.') {
  1095. ++ext;
  1096. }
  1097. auto const it = this->ExtensionToLanguage.find(ext);
  1098. if (it != this->ExtensionToLanguage.end()) {
  1099. return it->second;
  1100. }
  1101. return "";
  1102. }
  1103. /* SetLanguageEnabled() is now split in two parts:
  1104. at first the enabled-flag is set. This can then be used in EnabledLanguage()
  1105. for checking whether the language is already enabled. After setting this
  1106. flag still the values from the cmake variables have to be copied into the
  1107. internal maps, this is done in SetLanguageEnabledMaps() which is called
  1108. after the system- and compiler specific files have been loaded.
  1109. This split was done originally so that compiler-specific configuration
  1110. files could change the object file extension
  1111. (CMAKE_<LANG>_OUTPUT_EXTENSION) before the CMake variables were copied
  1112. to the C++ maps.
  1113. */
  1114. void cmGlobalGenerator::SetLanguageEnabled(const std::string& l,
  1115. cmMakefile* mf)
  1116. {
  1117. this->SetLanguageEnabledFlag(l, mf);
  1118. this->SetLanguageEnabledMaps(l, mf);
  1119. }
  1120. void cmGlobalGenerator::SetLanguageEnabledFlag(const std::string& l,
  1121. cmMakefile* mf)
  1122. {
  1123. this->CMakeInstance->GetState()->SetLanguageEnabled(l);
  1124. // Fill the language-to-extension map with the current variable
  1125. // settings to make sure it is available for the try_compile()
  1126. // command source file signature. In SetLanguageEnabledMaps this
  1127. // will be done again to account for any compiler- or
  1128. // platform-specific entries.
  1129. this->FillExtensionToLanguageMap(l, mf);
  1130. }
  1131. void cmGlobalGenerator::SetLanguageEnabledMaps(const std::string& l,
  1132. cmMakefile* mf)
  1133. {
  1134. // use LanguageToLinkerPreference to detect whether this functions has
  1135. // run before
  1136. if (cm::contains(this->LanguageToLinkerPreference, l)) {
  1137. return;
  1138. }
  1139. std::string linkerPrefVar = cmStrCat("CMAKE_", l, "_LINKER_PREFERENCE");
  1140. cmValue linkerPref = mf->GetDefinition(linkerPrefVar);
  1141. int preference = 0;
  1142. if (cmNonempty(linkerPref)) {
  1143. if (sscanf(linkerPref->c_str(), "%d", &preference) != 1) {
  1144. // backward compatibility: before 2.6 LINKER_PREFERENCE
  1145. // was either "None" or "Preferred", and only the first character was
  1146. // tested. So if there is a custom language out there and it is
  1147. // "Preferred", set its preference high
  1148. if ((*linkerPref)[0] == 'P') {
  1149. preference = 100;
  1150. } else {
  1151. preference = 0;
  1152. }
  1153. }
  1154. }
  1155. if (preference < 0) {
  1156. std::string msg =
  1157. cmStrCat(linkerPrefVar, " is negative, adjusting it to 0");
  1158. cmSystemTools::Message(msg, "Warning");
  1159. preference = 0;
  1160. }
  1161. this->LanguageToLinkerPreference[l] = preference;
  1162. std::string outputExtensionVar = cmStrCat("CMAKE_", l, "_OUTPUT_EXTENSION");
  1163. if (cmValue p = mf->GetDefinition(outputExtensionVar)) {
  1164. std::string outputExtension = *p;
  1165. this->LanguageToOutputExtension[l] = outputExtension;
  1166. this->OutputExtensions[outputExtension] = outputExtension;
  1167. if (cmHasPrefix(outputExtension, ".")) {
  1168. outputExtension = outputExtension.substr(1);
  1169. this->OutputExtensions[outputExtension] = outputExtension;
  1170. }
  1171. }
  1172. // The map was originally filled by SetLanguageEnabledFlag, but
  1173. // since then the compiler- and platform-specific files have been
  1174. // loaded which might have added more entries.
  1175. this->FillExtensionToLanguageMap(l, mf);
  1176. std::string ignoreExtensionsVar =
  1177. cmStrCat("CMAKE_", l, "_IGNORE_EXTENSIONS");
  1178. std::string ignoreExts = mf->GetSafeDefinition(ignoreExtensionsVar);
  1179. cmList extensionList{ ignoreExts };
  1180. for (std::string const& i : extensionList) {
  1181. this->IgnoreExtensions[i] = true;
  1182. }
  1183. }
  1184. void cmGlobalGenerator::FillExtensionToLanguageMap(const std::string& l,
  1185. cmMakefile* mf)
  1186. {
  1187. std::string extensionsVar = cmStrCat("CMAKE_", l, "_SOURCE_FILE_EXTENSIONS");
  1188. const std::string& exts = mf->GetSafeDefinition(extensionsVar);
  1189. cmList extensionList{ exts };
  1190. for (std::string const& i : extensionList) {
  1191. this->ExtensionToLanguage[i] = l;
  1192. }
  1193. }
  1194. cmValue cmGlobalGenerator::GetGlobalSetting(std::string const& name) const
  1195. {
  1196. assert(!this->Makefiles.empty());
  1197. return this->Makefiles[0]->GetDefinition(name);
  1198. }
  1199. bool cmGlobalGenerator::GlobalSettingIsOn(std::string const& name) const
  1200. {
  1201. assert(!this->Makefiles.empty());
  1202. return this->Makefiles[0]->IsOn(name);
  1203. }
  1204. std::string cmGlobalGenerator::GetSafeGlobalSetting(
  1205. std::string const& name) const
  1206. {
  1207. assert(!this->Makefiles.empty());
  1208. return this->Makefiles[0]->GetDefinition(name);
  1209. }
  1210. bool cmGlobalGenerator::IgnoreFile(const char* ext) const
  1211. {
  1212. if (!this->GetLanguageFromExtension(ext).empty()) {
  1213. return false;
  1214. }
  1215. return (this->IgnoreExtensions.count(ext) > 0);
  1216. }
  1217. bool cmGlobalGenerator::GetLanguageEnabled(const std::string& l) const
  1218. {
  1219. return this->CMakeInstance->GetState()->GetLanguageEnabled(l);
  1220. }
  1221. void cmGlobalGenerator::ClearEnabledLanguages()
  1222. {
  1223. this->CMakeInstance->GetState()->ClearEnabledLanguages();
  1224. }
  1225. void cmGlobalGenerator::CreateLocalGenerators()
  1226. {
  1227. this->LocalGeneratorSearchIndex.clear();
  1228. this->LocalGenerators.clear();
  1229. this->LocalGenerators.reserve(this->Makefiles.size());
  1230. for (const auto& m : this->Makefiles) {
  1231. auto lg = this->CreateLocalGenerator(m.get());
  1232. this->IndexLocalGenerator(lg.get());
  1233. this->LocalGenerators.push_back(std::move(lg));
  1234. }
  1235. }
  1236. void cmGlobalGenerator::Configure()
  1237. {
  1238. this->FirstTimeProgress = 0.0f;
  1239. this->ClearGeneratorMembers();
  1240. this->NextDeferId = 0;
  1241. cmStateSnapshot snapshot = this->CMakeInstance->GetCurrentSnapshot();
  1242. snapshot.GetDirectory().SetCurrentSource(
  1243. this->CMakeInstance->GetHomeDirectory());
  1244. snapshot.GetDirectory().SetCurrentBinary(
  1245. this->CMakeInstance->GetHomeOutputDirectory());
  1246. auto dirMfu = cm::make_unique<cmMakefile>(this, snapshot);
  1247. auto* dirMf = dirMfu.get();
  1248. this->Makefiles.push_back(std::move(dirMfu));
  1249. dirMf->SetRecursionDepth(this->RecursionDepth);
  1250. this->IndexMakefile(dirMf);
  1251. this->BinaryDirectories.insert(
  1252. this->CMakeInstance->GetHomeOutputDirectory());
  1253. if (this->ExtraGenerator && !this->CMakeInstance->GetIsInTryCompile()) {
  1254. this->CMakeInstance->IssueMessage(
  1255. MessageType::DEPRECATION_WARNING,
  1256. cmStrCat("Support for \"Extra Generators\" like\n ",
  1257. this->ExtraGenerator->GetName(),
  1258. "\nis deprecated and will be removed from a future version "
  1259. "of CMake. IDEs may use the cmake-file-api(7) to view "
  1260. "CMake-generated project build trees."));
  1261. }
  1262. // now do it
  1263. this->ConfigureDoneCMP0026AndCMP0024 = false;
  1264. dirMf->Configure();
  1265. dirMf->EnforceDirectoryLevelRules();
  1266. this->ConfigureDoneCMP0026AndCMP0024 = true;
  1267. // Put a copy of each global target in every directory.
  1268. {
  1269. std::vector<GlobalTargetInfo> globalTargets;
  1270. this->CreateDefaultGlobalTargets(globalTargets);
  1271. for (const auto& mf : this->Makefiles) {
  1272. for (GlobalTargetInfo const& globalTarget : globalTargets) {
  1273. this->CreateGlobalTarget(globalTarget, mf.get());
  1274. }
  1275. }
  1276. }
  1277. // update the cache entry for the number of local generators, this is used
  1278. // for progress
  1279. this->GetCMakeInstance()->AddCacheEntry(
  1280. "CMAKE_NUMBER_OF_MAKEFILES", std::to_string(this->Makefiles.size()),
  1281. "number of local generators", cmStateEnums::INTERNAL);
  1282. }
  1283. void cmGlobalGenerator::CreateGenerationObjects(TargetTypes targetTypes)
  1284. {
  1285. this->CreateLocalGenerators();
  1286. // Commit side effects only if we are actually generating
  1287. if (this->GetConfigureDoneCMP0026()) {
  1288. this->CheckTargetProperties();
  1289. }
  1290. this->CreateGeneratorTargets(targetTypes);
  1291. if (targetTypes == TargetTypes::AllTargets) {
  1292. this->ComputeBuildFileGenerators();
  1293. }
  1294. }
  1295. void cmGlobalGenerator::CreateImportedGenerationObjects(
  1296. cmMakefile* mf, const std::vector<std::string>& targets,
  1297. std::vector<const cmGeneratorTarget*>& exports)
  1298. {
  1299. this->CreateGenerationObjects(ImportedOnly);
  1300. auto const mfit =
  1301. std::find_if(this->Makefiles.begin(), this->Makefiles.end(),
  1302. [mf](const std::unique_ptr<cmMakefile>& item) {
  1303. return item.get() == mf;
  1304. });
  1305. auto& lg =
  1306. this->LocalGenerators[std::distance(this->Makefiles.begin(), mfit)];
  1307. for (std::string const& t : targets) {
  1308. cmGeneratorTarget* gt = lg->FindGeneratorTargetToUse(t);
  1309. if (gt) {
  1310. exports.push_back(gt);
  1311. }
  1312. }
  1313. }
  1314. cmExportBuildFileGenerator* cmGlobalGenerator::GetExportedTargetsFile(
  1315. const std::string& filename) const
  1316. {
  1317. auto const it = this->BuildExportSets.find(filename);
  1318. return it == this->BuildExportSets.end() ? nullptr : it->second;
  1319. }
  1320. void cmGlobalGenerator::AddCMP0042WarnTarget(const std::string& target)
  1321. {
  1322. this->CMP0042WarnTargets.insert(target);
  1323. }
  1324. void cmGlobalGenerator::AddCMP0068WarnTarget(const std::string& target)
  1325. {
  1326. this->CMP0068WarnTargets.insert(target);
  1327. }
  1328. bool cmGlobalGenerator::CheckALLOW_DUPLICATE_CUSTOM_TARGETS() const
  1329. {
  1330. // If the property is not enabled then okay.
  1331. if (!this->CMakeInstance->GetState()->GetGlobalPropertyAsBool(
  1332. "ALLOW_DUPLICATE_CUSTOM_TARGETS")) {
  1333. return true;
  1334. }
  1335. // This generator does not support duplicate custom targets.
  1336. std::ostringstream e;
  1337. e << "This project has enabled the ALLOW_DUPLICATE_CUSTOM_TARGETS "
  1338. << "global property. "
  1339. << "The \"" << this->GetName() << "\" generator does not support "
  1340. << "duplicate custom targets. "
  1341. << "Consider using a Makefiles generator or fix the project to not "
  1342. << "use duplicate target names.";
  1343. cmSystemTools::Error(e.str());
  1344. return false;
  1345. }
  1346. void cmGlobalGenerator::ComputeBuildFileGenerators()
  1347. {
  1348. for (unsigned int i = 0; i < this->LocalGenerators.size(); ++i) {
  1349. std::vector<std::unique_ptr<cmExportBuildFileGenerator>> const& gens =
  1350. this->Makefiles[i]->GetExportBuildFileGenerators();
  1351. for (std::unique_ptr<cmExportBuildFileGenerator> const& g : gens) {
  1352. g->Compute(this->LocalGenerators[i].get());
  1353. }
  1354. }
  1355. }
  1356. bool cmGlobalGenerator::UnsupportedVariableIsDefined(const std::string& name,
  1357. bool supported) const
  1358. {
  1359. if (!supported && this->Makefiles.front()->GetDefinition(name)) {
  1360. std::ostringstream e;
  1361. /* clang-format off */
  1362. e <<
  1363. "Generator\n"
  1364. " " << this->GetName() << "\n"
  1365. "does not support variable\n"
  1366. " " << name << "\n"
  1367. "but it has been specified."
  1368. ;
  1369. /* clang-format on */
  1370. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR, e.str());
  1371. return true;
  1372. }
  1373. return false;
  1374. }
  1375. bool cmGlobalGenerator::Compute()
  1376. {
  1377. // Make sure unsupported variables are not used.
  1378. if (this->UnsupportedVariableIsDefined("CMAKE_DEFAULT_BUILD_TYPE",
  1379. this->SupportsDefaultBuildType())) {
  1380. return false;
  1381. }
  1382. if (this->UnsupportedVariableIsDefined("CMAKE_CROSS_CONFIGS",
  1383. this->SupportsCrossConfigs())) {
  1384. return false;
  1385. }
  1386. if (this->UnsupportedVariableIsDefined("CMAKE_DEFAULT_CONFIGS",
  1387. this->SupportsDefaultConfigs())) {
  1388. return false;
  1389. }
  1390. if (!this->InspectConfigTypeVariables()) {
  1391. return false;
  1392. }
  1393. // Some generators track files replaced during the Generate.
  1394. // Start with an empty vector:
  1395. this->FilesReplacedDuringGenerate.clear();
  1396. // clear targets to issue warning CMP0042 for
  1397. this->CMP0042WarnTargets.clear();
  1398. // clear targets to issue warning CMP0068 for
  1399. this->CMP0068WarnTargets.clear();
  1400. // Check whether this generator is allowed to run.
  1401. if (!this->CheckALLOW_DUPLICATE_CUSTOM_TARGETS()) {
  1402. return false;
  1403. }
  1404. this->FinalizeTargetConfiguration();
  1405. this->CreateGenerationObjects();
  1406. // at this point this->LocalGenerators has been filled,
  1407. // so create the map from project name to vector of local generators
  1408. this->FillProjectMap();
  1409. this->CreateFileGenerateOutputs();
  1410. // Iterate through all targets and add verification targets for header sets
  1411. if (!this->AddHeaderSetVerification()) {
  1412. return false;
  1413. }
  1414. #ifndef CMAKE_BOOTSTRAP
  1415. this->QtAutoGen =
  1416. cm::make_unique<cmQtAutoGenGlobalInitializer>(this->LocalGenerators);
  1417. if (!this->QtAutoGen->InitializeCustomTargets()) {
  1418. return false;
  1419. }
  1420. #endif
  1421. // Perform up-front computation in order to handle errors (such as unknown
  1422. // features) at this point. While processing the compile features we also
  1423. // calculate and cache the language standard required by the compile
  1424. // features.
  1425. //
  1426. // Synthetic targets performed this inside of
  1427. // `cmLocalGenerator::DiscoverSyntheticTargets`
  1428. for (const auto& localGen : this->LocalGenerators) {
  1429. if (!localGen->ComputeTargetCompileFeatures()) {
  1430. return false;
  1431. }
  1432. }
  1433. // We now have all targets set up and std levels constructed. Add
  1434. // `__CMAKE::CXX*` targets as link dependencies to all targets which need
  1435. // them.
  1436. //
  1437. // Synthetic targets performed this inside of
  1438. // `cmLocalGenerator::DiscoverSyntheticTargets`
  1439. if (!this->ApplyCXXStdTargets()) {
  1440. return false;
  1441. }
  1442. // Iterate through all targets and set up C++20 module targets.
  1443. // Create target templates for each imported target with C++20 modules.
  1444. // INTERFACE library with BMI-generating rules and a collation step?
  1445. // Maybe INTERFACE libraries with modules files should just do BMI-only?
  1446. // Make `add_dependencies(imported_target
  1447. // $<$<TARGET_NAME_IF_EXISTS:uses_imported>:synth1>
  1448. // $<$<TARGET_NAME_IF_EXISTS:other_uses_imported>:synth2>)`
  1449. //
  1450. // Note that synthetic target creation performs the above marked
  1451. // steps on the created targets.
  1452. if (!this->DiscoverSyntheticTargets()) {
  1453. return false;
  1454. }
  1455. // Add generator specific helper commands
  1456. for (const auto& localGen : this->LocalGenerators) {
  1457. localGen->AddHelperCommands();
  1458. }
  1459. // Add automatically generated sources (e.g. unity build).
  1460. // Add unity sources after computing compile features. Unity sources do
  1461. // not change the set of languages or features, but we need to know them
  1462. // to filter out sources that are scanned for C++ module dependencies.
  1463. if (!this->AddAutomaticSources()) {
  1464. return false;
  1465. }
  1466. for (const auto& localGen : this->LocalGenerators) {
  1467. cmMakefile* mf = localGen->GetMakefile();
  1468. for (const auto& g : mf->GetInstallGenerators()) {
  1469. if (!g->Compute(localGen.get())) {
  1470. return false;
  1471. }
  1472. }
  1473. }
  1474. this->AddExtraIDETargets();
  1475. // Trace the dependencies, after that no custom commands should be added
  1476. // because their dependencies might not be handled correctly
  1477. for (const auto& localGen : this->LocalGenerators) {
  1478. localGen->TraceDependencies();
  1479. }
  1480. // Make sure that all (non-imported) targets have source files added!
  1481. if (this->CheckTargetsForMissingSources()) {
  1482. return false;
  1483. }
  1484. this->ForceLinkerLanguages();
  1485. // Compute the manifest of main targets generated.
  1486. for (const auto& localGen : this->LocalGenerators) {
  1487. localGen->ComputeTargetManifest();
  1488. }
  1489. // Compute the inter-target dependencies.
  1490. if (!this->ComputeTargetDepends()) {
  1491. return false;
  1492. }
  1493. this->ComputeTargetOrder();
  1494. if (this->CheckTargetsForType()) {
  1495. return false;
  1496. }
  1497. if (this->CheckTargetsForPchCompilePdb()) {
  1498. return false;
  1499. }
  1500. for (const auto& localGen : this->LocalGenerators) {
  1501. localGen->ComputeHomeRelativeOutputPath();
  1502. }
  1503. return true;
  1504. }
  1505. void cmGlobalGenerator::Generate()
  1506. {
  1507. // Create a map from local generator to the complete set of targets
  1508. // it builds by default.
  1509. this->InitializeProgressMarks();
  1510. this->ProcessEvaluationFiles();
  1511. this->CMakeInstance->UpdateProgress("Generating", 0.1f);
  1512. #ifndef CMAKE_BOOTSTRAP
  1513. if (!this->QtAutoGen->SetupCustomTargets()) {
  1514. if (!cmSystemTools::GetErrorOccurredFlag()) {
  1515. this->GetCMakeInstance()->IssueMessage(
  1516. MessageType::FATAL_ERROR,
  1517. "Problem setting up custom targets for QtAutoGen");
  1518. }
  1519. return;
  1520. }
  1521. #endif
  1522. // Generate project files
  1523. for (unsigned int i = 0; i < this->LocalGenerators.size(); ++i) {
  1524. this->SetCurrentMakefile(this->LocalGenerators[i]->GetMakefile());
  1525. this->LocalGenerators[i]->Generate();
  1526. if (!this->LocalGenerators[i]->GetMakefile()->IsOn(
  1527. "CMAKE_SKIP_INSTALL_RULES")) {
  1528. this->LocalGenerators[i]->GenerateInstallRules();
  1529. }
  1530. this->LocalGenerators[i]->GenerateTestFiles();
  1531. this->CMakeInstance->UpdateProgress(
  1532. "Generating",
  1533. 0.1f +
  1534. 0.9f * (static_cast<float>(i) + 1.0f) /
  1535. static_cast<float>(this->LocalGenerators.size()));
  1536. }
  1537. this->SetCurrentMakefile(nullptr);
  1538. if (!this->GenerateCPackPropertiesFile()) {
  1539. this->GetCMakeInstance()->IssueMessage(
  1540. MessageType::FATAL_ERROR, "Could not write CPack properties file.");
  1541. }
  1542. for (auto& buildExpSet : this->BuildExportSets) {
  1543. if (!buildExpSet.second->GenerateImportFile()) {
  1544. if (!cmSystemTools::GetErrorOccurredFlag()) {
  1545. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  1546. "Could not write export file.");
  1547. }
  1548. return;
  1549. }
  1550. }
  1551. // Update rule hashes.
  1552. this->CheckRuleHashes();
  1553. this->WriteSummary();
  1554. if (this->ExtraGenerator) {
  1555. this->ExtraGenerator->Generate();
  1556. }
  1557. // Perform validation checks on memoized link structures.
  1558. this->CheckTargetLinkLibraries();
  1559. if (!this->CMP0042WarnTargets.empty()) {
  1560. std::ostringstream w;
  1561. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0042) << "\n";
  1562. w << "MACOSX_RPATH is not specified for"
  1563. " the following targets:\n";
  1564. for (std::string const& t : this->CMP0042WarnTargets) {
  1565. w << " " << t << "\n";
  1566. }
  1567. this->GetCMakeInstance()->IssueMessage(MessageType::AUTHOR_WARNING,
  1568. w.str());
  1569. }
  1570. if (!this->CMP0068WarnTargets.empty()) {
  1571. std::ostringstream w;
  1572. /* clang-format off */
  1573. w <<
  1574. cmPolicies::GetPolicyWarning(cmPolicies::CMP0068) << "\n"
  1575. "For compatibility with older versions of CMake, the install_name "
  1576. "fields for the following targets are still affected by RPATH "
  1577. "settings:\n"
  1578. ;
  1579. /* clang-format on */
  1580. for (std::string const& t : this->CMP0068WarnTargets) {
  1581. w << " " << t << "\n";
  1582. }
  1583. this->GetCMakeInstance()->IssueMessage(MessageType::AUTHOR_WARNING,
  1584. w.str());
  1585. }
  1586. }
  1587. bool cmGlobalGenerator::ComputeTargetDepends()
  1588. {
  1589. cmComputeTargetDepends ctd(this);
  1590. if (!ctd.Compute()) {
  1591. return false;
  1592. }
  1593. for (cmGeneratorTarget const* target : ctd.GetTargets()) {
  1594. ctd.GetTargetDirectDepends(target, this->TargetDependencies[target]);
  1595. }
  1596. return true;
  1597. }
  1598. std::vector<cmGeneratorTarget*>
  1599. cmGlobalGenerator::GetLocalGeneratorTargetsInOrder(cmLocalGenerator* lg) const
  1600. {
  1601. std::vector<cmGeneratorTarget*> gts;
  1602. cm::append(gts, lg->GetGeneratorTargets());
  1603. std::sort(gts.begin(), gts.end(),
  1604. [this](cmGeneratorTarget const* l, cmGeneratorTarget const* r) {
  1605. return this->TargetOrderIndexLess(l, r);
  1606. });
  1607. return gts;
  1608. }
  1609. void cmGlobalGenerator::ComputeTargetOrder()
  1610. {
  1611. size_t index = 0;
  1612. auto const& lgens = this->GetLocalGenerators();
  1613. for (auto const& lgen : lgens) {
  1614. const auto& targets = lgen->GetGeneratorTargets();
  1615. for (const auto& gt : targets) {
  1616. this->ComputeTargetOrder(gt.get(), index);
  1617. }
  1618. }
  1619. assert(index == this->TargetOrderIndex.size());
  1620. }
  1621. void cmGlobalGenerator::ComputeTargetOrder(cmGeneratorTarget const* gt,
  1622. size_t& index)
  1623. {
  1624. std::map<cmGeneratorTarget const*, size_t>::value_type value(gt, 0);
  1625. auto insertion = this->TargetOrderIndex.insert(value);
  1626. if (!insertion.second) {
  1627. return;
  1628. }
  1629. auto entry = insertion.first;
  1630. const auto& deps = this->GetTargetDirectDepends(gt);
  1631. for (const auto& d : deps) {
  1632. this->ComputeTargetOrder(d, index);
  1633. }
  1634. entry->second = index++;
  1635. }
  1636. bool cmGlobalGenerator::ApplyCXXStdTargets()
  1637. {
  1638. for (auto const& gen : this->LocalGenerators) {
  1639. for (auto const& tgt : gen->GetGeneratorTargets()) {
  1640. if (!tgt->ApplyCXXStdTargets()) {
  1641. return false;
  1642. }
  1643. }
  1644. }
  1645. return true;
  1646. }
  1647. bool cmGlobalGenerator::DiscoverSyntheticTargets()
  1648. {
  1649. cmSyntheticTargetCache cache;
  1650. for (auto const& gen : this->LocalGenerators) {
  1651. // Because DiscoverSyntheticTargets() adds generator targets, we need to
  1652. // cache the existing list of generator targets before starting.
  1653. std::vector<cmGeneratorTarget*> genTargets;
  1654. genTargets.reserve(gen->GetGeneratorTargets().size());
  1655. for (auto const& tgt : gen->GetGeneratorTargets()) {
  1656. genTargets.push_back(tgt.get());
  1657. }
  1658. for (auto* tgt : genTargets) {
  1659. std::vector<std::string> const& configs =
  1660. tgt->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  1661. for (auto const& config : configs) {
  1662. if (!tgt->DiscoverSyntheticTargets(cache, config)) {
  1663. return false;
  1664. }
  1665. }
  1666. }
  1667. }
  1668. return true;
  1669. }
  1670. bool cmGlobalGenerator::AddHeaderSetVerification()
  1671. {
  1672. for (auto const& gen : this->LocalGenerators) {
  1673. // Because AddHeaderSetVerification() adds generator targets, we need to
  1674. // cache the existing list of generator targets before starting.
  1675. std::vector<cmGeneratorTarget*> genTargets;
  1676. genTargets.reserve(gen->GetGeneratorTargets().size());
  1677. for (auto const& tgt : gen->GetGeneratorTargets()) {
  1678. genTargets.push_back(tgt.get());
  1679. }
  1680. for (auto* tgt : genTargets) {
  1681. if (!tgt->AddHeaderSetVerification()) {
  1682. return false;
  1683. }
  1684. }
  1685. }
  1686. cmTarget* allVerifyTarget = this->Makefiles.front()->FindTargetToUse(
  1687. "all_verify_interface_header_sets", true);
  1688. if (allVerifyTarget) {
  1689. this->LocalGenerators.front()->AddGeneratorTarget(
  1690. cm::make_unique<cmGeneratorTarget>(allVerifyTarget,
  1691. this->LocalGenerators.front().get()));
  1692. }
  1693. return true;
  1694. }
  1695. void cmGlobalGenerator::CreateFileGenerateOutputs()
  1696. {
  1697. for (const auto& lg : this->LocalGenerators) {
  1698. lg->CreateEvaluationFileOutputs();
  1699. }
  1700. }
  1701. bool cmGlobalGenerator::AddAutomaticSources()
  1702. {
  1703. for (const auto& lg : this->LocalGenerators) {
  1704. for (const auto& gt : lg->GetGeneratorTargets()) {
  1705. if (!gt->CanCompileSources()) {
  1706. continue;
  1707. }
  1708. lg->AddUnityBuild(gt.get());
  1709. lg->AddISPCDependencies(gt.get());
  1710. // Targets that reuse a PCH are handled below.
  1711. if (!gt->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM")) {
  1712. lg->AddPchDependencies(gt.get());
  1713. }
  1714. lg->AddXCConfigSources(gt.get());
  1715. }
  1716. }
  1717. for (const auto& lg : this->LocalGenerators) {
  1718. for (const auto& gt : lg->GetGeneratorTargets()) {
  1719. if (!gt->CanCompileSources()) {
  1720. continue;
  1721. }
  1722. // Handle targets that reuse a PCH from an above-handled target.
  1723. if (gt->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM")) {
  1724. lg->AddPchDependencies(gt.get());
  1725. }
  1726. }
  1727. }
  1728. // The above transformations may have changed the classification of sources,
  1729. // e.g., sources that go into unity builds become SourceKindUnityBatched.
  1730. // Clear the source list and classification cache (KindedSources) of all
  1731. // targets so that it will be recomputed correctly by the generators later
  1732. // now that the above transformations are done for all targets.
  1733. // Also clear the link interface cache to support $<TARGET_OBJECTS:objlib>
  1734. // in INTERFACE_LINK_LIBRARIES because the list of object files may have
  1735. // been changed by conversion to a unity build or addition of a PCH source.
  1736. for (const auto& lg : this->LocalGenerators) {
  1737. for (const auto& gt : lg->GetGeneratorTargets()) {
  1738. gt->ClearSourcesCache();
  1739. gt->ClearLinkInterfaceCache();
  1740. }
  1741. }
  1742. return true;
  1743. }
  1744. std::unique_ptr<cmLinkLineComputer> cmGlobalGenerator::CreateLinkLineComputer(
  1745. cmOutputConverter* outputConverter, cmStateDirectory const& stateDir) const
  1746. {
  1747. return cm::make_unique<cmLinkLineComputer>(outputConverter, stateDir);
  1748. }
  1749. std::unique_ptr<cmLinkLineComputer>
  1750. cmGlobalGenerator::CreateMSVC60LinkLineComputer(
  1751. cmOutputConverter* outputConverter, cmStateDirectory const& stateDir) const
  1752. {
  1753. return std::unique_ptr<cmLinkLineComputer>(
  1754. cm::make_unique<cmMSVC60LinkLineComputer>(outputConverter, stateDir));
  1755. }
  1756. void cmGlobalGenerator::FinalizeTargetConfiguration()
  1757. {
  1758. std::vector<std::string> const langs =
  1759. this->CMakeInstance->GetState()->GetEnabledLanguages();
  1760. // Construct per-target generator information.
  1761. for (const auto& mf : this->Makefiles) {
  1762. const cmBTStringRange noConfigCompileDefinitions =
  1763. mf->GetCompileDefinitionsEntries();
  1764. cm::optional<std::map<std::string, cmValue>> perConfigCompileDefinitions;
  1765. for (auto& target : mf->GetTargets()) {
  1766. cmTarget* t = &target.second;
  1767. t->FinalizeTargetConfiguration(noConfigCompileDefinitions,
  1768. perConfigCompileDefinitions);
  1769. }
  1770. // The standard include directories for each language
  1771. // should be treated as system include directories.
  1772. std::set<std::string> standardIncludesSet;
  1773. for (std::string const& li : langs) {
  1774. std::string const standardIncludesVar =
  1775. cmStrCat("CMAKE_", li, "_STANDARD_INCLUDE_DIRECTORIES");
  1776. std::string const& standardIncludesStr =
  1777. mf->GetSafeDefinition(standardIncludesVar);
  1778. cmList standardIncludesList{ standardIncludesStr };
  1779. standardIncludesSet.insert(standardIncludesList.begin(),
  1780. standardIncludesList.end());
  1781. }
  1782. mf->AddSystemIncludeDirectories(standardIncludesSet);
  1783. }
  1784. }
  1785. void cmGlobalGenerator::CreateGeneratorTargets(
  1786. TargetTypes targetTypes, cmMakefile* mf, cmLocalGenerator* lg,
  1787. std::map<cmTarget*, cmGeneratorTarget*> const& importedMap)
  1788. {
  1789. if (targetTypes == AllTargets) {
  1790. for (cmTarget* target : mf->GetOrderedTargets()) {
  1791. lg->AddGeneratorTarget(cm::make_unique<cmGeneratorTarget>(target, lg));
  1792. }
  1793. }
  1794. for (cmTarget* t : mf->GetImportedTargets()) {
  1795. lg->AddImportedGeneratorTarget(importedMap.find(t)->second);
  1796. }
  1797. }
  1798. void cmGlobalGenerator::CreateGeneratorTargets(TargetTypes targetTypes)
  1799. {
  1800. std::map<cmTarget*, cmGeneratorTarget*> importedMap;
  1801. for (unsigned int i = 0; i < this->Makefiles.size(); ++i) {
  1802. auto& mf = this->Makefiles[i];
  1803. for (const auto& ownedImpTgt : mf->GetOwnedImportedTargets()) {
  1804. cmLocalGenerator* lg = this->LocalGenerators[i].get();
  1805. auto gt = cm::make_unique<cmGeneratorTarget>(ownedImpTgt.get(), lg);
  1806. importedMap[ownedImpTgt.get()] = gt.get();
  1807. lg->AddOwnedImportedGeneratorTarget(std::move(gt));
  1808. }
  1809. }
  1810. // Construct per-target generator information.
  1811. for (unsigned int i = 0; i < this->LocalGenerators.size(); ++i) {
  1812. this->CreateGeneratorTargets(targetTypes, this->Makefiles[i].get(),
  1813. this->LocalGenerators[i].get(), importedMap);
  1814. }
  1815. }
  1816. void cmGlobalGenerator::ClearGeneratorMembers()
  1817. {
  1818. this->BuildExportSets.clear();
  1819. this->Makefiles.clear();
  1820. this->LocalGenerators.clear();
  1821. this->AliasTargets.clear();
  1822. this->ExportSets.clear();
  1823. this->InstallComponents.clear();
  1824. this->TargetDependencies.clear();
  1825. this->TargetSearchIndex.clear();
  1826. this->GeneratorTargetSearchIndex.clear();
  1827. this->MakefileSearchIndex.clear();
  1828. this->LocalGeneratorSearchIndex.clear();
  1829. this->TargetOrderIndex.clear();
  1830. this->ProjectMap.clear();
  1831. this->RuleHashes.clear();
  1832. this->DirectoryContentMap.clear();
  1833. this->BinaryDirectories.clear();
  1834. this->GeneratedFiles.clear();
  1835. this->RuntimeDependencySets.clear();
  1836. this->RuntimeDependencySetsByName.clear();
  1837. }
  1838. void cmGlobalGenerator::ComputeTargetObjectDirectory(
  1839. cmGeneratorTarget* /*unused*/) const
  1840. {
  1841. }
  1842. void cmGlobalGenerator::CheckTargetProperties()
  1843. {
  1844. // check for link libraries and include directories containing "NOTFOUND"
  1845. // and for infinite loops
  1846. std::map<std::string, std::string> notFoundMap;
  1847. cmState* state = this->GetCMakeInstance()->GetState();
  1848. for (unsigned int i = 0; i < this->Makefiles.size(); ++i) {
  1849. this->Makefiles[i]->Generate(*this->LocalGenerators[i]);
  1850. for (auto const& target : this->Makefiles[i]->GetTargets()) {
  1851. if (target.second.GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  1852. continue;
  1853. }
  1854. for (auto const& lib : target.second.GetOriginalLinkLibraries()) {
  1855. if (lib.first.size() > 9 && cmIsNOTFOUND(lib.first)) {
  1856. std::string varName = lib.first.substr(0, lib.first.size() - 9);
  1857. if (state->GetCacheEntryPropertyAsBool(varName, "ADVANCED")) {
  1858. varName += " (ADVANCED)";
  1859. }
  1860. std::string text =
  1861. cmStrCat(notFoundMap[varName], "\n linked by target \"",
  1862. target.second.GetName(), "\" in directory ",
  1863. this->Makefiles[i]->GetCurrentSourceDirectory());
  1864. notFoundMap[varName] = text;
  1865. }
  1866. }
  1867. cmValue incDirProp = target.second.GetProperty("INCLUDE_DIRECTORIES");
  1868. if (!incDirProp) {
  1869. continue;
  1870. }
  1871. std::string incDirs = cmGeneratorExpression::Preprocess(
  1872. *incDirProp, cmGeneratorExpression::StripAllGeneratorExpressions);
  1873. cmList incs(incDirs);
  1874. for (std::string const& incDir : incs) {
  1875. if (incDir.size() > 9 && cmIsNOTFOUND(incDir)) {
  1876. std::string varName = incDir.substr(0, incDir.size() - 9);
  1877. if (state->GetCacheEntryPropertyAsBool(varName, "ADVANCED")) {
  1878. varName += " (ADVANCED)";
  1879. }
  1880. std::string text =
  1881. cmStrCat(notFoundMap[varName],
  1882. "\n used as include directory in directory ",
  1883. this->Makefiles[i]->GetCurrentSourceDirectory());
  1884. notFoundMap[varName] = text;
  1885. }
  1886. }
  1887. }
  1888. }
  1889. if (!notFoundMap.empty()) {
  1890. std::string notFoundVars;
  1891. for (auto const& notFound : notFoundMap) {
  1892. notFoundVars += notFound.first;
  1893. notFoundVars += notFound.second;
  1894. notFoundVars += '\n';
  1895. }
  1896. cmSystemTools::Error(
  1897. cmStrCat("The following variables are used in this project, "
  1898. "but they are set to NOTFOUND.\n"
  1899. "Please set them or make sure they are set and "
  1900. "tested correctly in the CMake files:\n",
  1901. notFoundVars));
  1902. }
  1903. }
  1904. int cmGlobalGenerator::TryCompile(int jobs, const std::string& srcdir,
  1905. const std::string& bindir,
  1906. const std::string& projectName,
  1907. const std::string& target, bool fast,
  1908. std::string& output, cmMakefile* mf)
  1909. {
  1910. // if this is not set, then this is a first time configure
  1911. // and there is a good chance that the try compile stuff will
  1912. // take the bulk of the time, so try and guess some progress
  1913. // by getting closer and closer to 100 without actually getting there.
  1914. if (!this->CMakeInstance->GetState()->GetInitializedCacheValue(
  1915. "CMAKE_NUMBER_OF_MAKEFILES")) {
  1916. // If CMAKE_NUMBER_OF_MAKEFILES is not set
  1917. // we are in the first time progress and we have no
  1918. // idea how long it will be. So, just move 1/10th of the way
  1919. // there each time, and don't go over 95%
  1920. this->FirstTimeProgress += ((1.0f - this->FirstTimeProgress) / 30.0f);
  1921. if (this->FirstTimeProgress > 0.95f) {
  1922. this->FirstTimeProgress = 0.95f;
  1923. }
  1924. this->CMakeInstance->UpdateProgress("Configuring",
  1925. this->FirstTimeProgress);
  1926. }
  1927. std::vector<std::string> newTarget = {};
  1928. if (!target.empty()) {
  1929. newTarget = { target };
  1930. }
  1931. std::string config =
  1932. mf->GetSafeDefinition("CMAKE_TRY_COMPILE_CONFIGURATION");
  1933. cmBuildOptions defaultBuildOptions(false, fast, PackageResolveMode::Disable);
  1934. std::stringstream ostr;
  1935. auto ret =
  1936. this->Build(jobs, srcdir, bindir, projectName, newTarget, ostr, "", config,
  1937. defaultBuildOptions, true, this->TryCompileTimeout);
  1938. output = ostr.str();
  1939. return ret;
  1940. }
  1941. std::vector<cmGlobalGenerator::GeneratedMakeCommand>
  1942. cmGlobalGenerator::GenerateBuildCommand(
  1943. const std::string& /*unused*/, const std::string& /*unused*/,
  1944. const std::string& /*unused*/, std::vector<std::string> const& /*unused*/,
  1945. const std::string& /*unused*/, int /*unused*/, bool /*unused*/,
  1946. const cmBuildOptions& /*unused*/, std::vector<std::string> const& /*unused*/)
  1947. {
  1948. GeneratedMakeCommand makeCommand;
  1949. makeCommand.Add("cmGlobalGenerator::GenerateBuildCommand not implemented");
  1950. return { std::move(makeCommand) };
  1951. }
  1952. void cmGlobalGenerator::PrintBuildCommandAdvice(std::ostream& /*os*/,
  1953. int /*jobs*/) const
  1954. {
  1955. // Subclasses override this method if they e.g want to give a warning that
  1956. // they do not support certain build command line options
  1957. }
  1958. int cmGlobalGenerator::Build(
  1959. int jobs, const std::string& /*unused*/, const std::string& bindir,
  1960. const std::string& projectName, const std::vector<std::string>& targets,
  1961. std::ostream& ostr, const std::string& makeCommandCSTR,
  1962. const std::string& config, const cmBuildOptions& buildOptions, bool verbose,
  1963. cmDuration timeout, cmSystemTools::OutputOption outputflag,
  1964. std::vector<std::string> const& nativeOptions)
  1965. {
  1966. bool hideconsole = cmSystemTools::GetRunCommandHideConsole();
  1967. /**
  1968. * Run an executable command and put the stdout in output.
  1969. */
  1970. cmWorkingDirectory workdir(bindir);
  1971. ostr << "Change Dir: '" << bindir << '\'' << std::endl;
  1972. if (workdir.Failed()) {
  1973. cmSystemTools::SetRunCommandHideConsole(hideconsole);
  1974. std::string err = cmStrCat("Failed to change directory: ",
  1975. std::strerror(workdir.GetLastResult()));
  1976. cmSystemTools::Error(err);
  1977. ostr << err << std::endl;
  1978. return 1;
  1979. }
  1980. std::string realConfig = config;
  1981. if (realConfig.empty()) {
  1982. realConfig = this->GetDefaultBuildConfig();
  1983. }
  1984. int retVal = 0;
  1985. cmSystemTools::SetRunCommandHideConsole(true);
  1986. std::string outputBuffer;
  1987. std::string* outputPtr = &outputBuffer;
  1988. std::vector<GeneratedMakeCommand> makeCommand = this->GenerateBuildCommand(
  1989. makeCommandCSTR, projectName, bindir, targets, realConfig, jobs, verbose,
  1990. buildOptions, nativeOptions);
  1991. // Workaround to convince some commands to produce output.
  1992. if (outputflag == cmSystemTools::OUTPUT_PASSTHROUGH &&
  1993. makeCommand.back().RequiresOutputForward) {
  1994. outputflag = cmSystemTools::OUTPUT_FORWARD;
  1995. }
  1996. // should we do a clean first?
  1997. if (buildOptions.Clean) {
  1998. std::vector<GeneratedMakeCommand> cleanCommand =
  1999. this->GenerateBuildCommand(makeCommandCSTR, projectName, bindir,
  2000. { "clean" }, realConfig, jobs, verbose,
  2001. buildOptions);
  2002. ostr << "\nRun Clean Command: " << cleanCommand.front().QuotedPrintable()
  2003. << std::endl;
  2004. if (cleanCommand.size() != 1) {
  2005. this->GetCMakeInstance()->IssueMessage(MessageType::INTERNAL_ERROR,
  2006. "The generator did not produce "
  2007. "exactly one command for the "
  2008. "'clean' target");
  2009. return 1;
  2010. }
  2011. if (!cmSystemTools::RunSingleCommand(cleanCommand.front().PrimaryCommand,
  2012. outputPtr, outputPtr, &retVal,
  2013. nullptr, outputflag, timeout)) {
  2014. cmSystemTools::SetRunCommandHideConsole(hideconsole);
  2015. cmSystemTools::Error("Generator: execution of make clean failed.");
  2016. ostr << *outputPtr << "\nGenerator: execution of make clean failed."
  2017. << std::endl;
  2018. return 1;
  2019. }
  2020. ostr << *outputPtr;
  2021. }
  2022. // now build
  2023. std::string makeCommandStr;
  2024. std::string outputMakeCommandStr;
  2025. bool isWatcomWMake = this->CMakeInstance->GetState()->UseWatcomWMake();
  2026. bool needBuildOutput = isWatcomWMake;
  2027. std::string buildOutput;
  2028. ostr << "\nRun Build Command(s): ";
  2029. retVal = 0;
  2030. for (auto command = makeCommand.begin();
  2031. command != makeCommand.end() && retVal == 0; ++command) {
  2032. makeCommandStr = command->Printable();
  2033. outputMakeCommandStr = command->QuotedPrintable();
  2034. if ((command + 1) != makeCommand.end()) {
  2035. makeCommandStr += " && ";
  2036. outputMakeCommandStr += " && ";
  2037. }
  2038. ostr << outputMakeCommandStr << std::endl;
  2039. if (!cmSystemTools::RunSingleCommand(command->PrimaryCommand, outputPtr,
  2040. outputPtr, &retVal, nullptr,
  2041. outputflag, timeout)) {
  2042. cmSystemTools::SetRunCommandHideConsole(hideconsole);
  2043. cmSystemTools::Error(
  2044. cmStrCat("Generator: execution of make failed. Make command was: ",
  2045. makeCommandStr));
  2046. ostr << *outputPtr
  2047. << "\nGenerator: execution of make failed. Make command was: "
  2048. << outputMakeCommandStr << std::endl;
  2049. return 1;
  2050. }
  2051. ostr << *outputPtr << std::flush;
  2052. if (needBuildOutput) {
  2053. buildOutput += *outputPtr;
  2054. }
  2055. }
  2056. ostr << std::endl;
  2057. cmSystemTools::SetRunCommandHideConsole(hideconsole);
  2058. // The OpenWatcom tools do not return an error code when a link
  2059. // library is not found!
  2060. if (isWatcomWMake && retVal == 0 &&
  2061. buildOutput.find("W1008: cannot open") != std::string::npos) {
  2062. retVal = 1;
  2063. }
  2064. return retVal;
  2065. }
  2066. bool cmGlobalGenerator::Open(const std::string& bindir,
  2067. const std::string& projectName, bool dryRun)
  2068. {
  2069. if (this->ExtraGenerator) {
  2070. return this->ExtraGenerator->Open(bindir, projectName, dryRun);
  2071. }
  2072. return false;
  2073. }
  2074. std::string cmGlobalGenerator::GenerateCMakeBuildCommand(
  2075. const std::string& target, const std::string& config,
  2076. const std::string& parallel, const std::string& native, bool ignoreErrors)
  2077. {
  2078. std::string makeCommand = cmSystemTools::GetCMakeCommand();
  2079. makeCommand =
  2080. cmStrCat(cmSystemTools::ConvertToOutputPath(makeCommand), " --build .");
  2081. if (!config.empty()) {
  2082. makeCommand += " --config \"";
  2083. makeCommand += config;
  2084. makeCommand += "\"";
  2085. }
  2086. if (!parallel.empty()) {
  2087. makeCommand += " --parallel \"";
  2088. makeCommand += parallel;
  2089. makeCommand += "\"";
  2090. }
  2091. if (!target.empty()) {
  2092. makeCommand += " --target \"";
  2093. makeCommand += target;
  2094. makeCommand += "\"";
  2095. }
  2096. const char* sep = " -- ";
  2097. if (ignoreErrors) {
  2098. const char* iflag = this->GetBuildIgnoreErrorsFlag();
  2099. if (iflag && *iflag) {
  2100. makeCommand += sep;
  2101. makeCommand += iflag;
  2102. sep = " ";
  2103. }
  2104. }
  2105. if (!native.empty()) {
  2106. makeCommand += sep;
  2107. makeCommand += native;
  2108. }
  2109. return makeCommand;
  2110. }
  2111. void cmGlobalGenerator::AddMakefile(std::unique_ptr<cmMakefile> mf)
  2112. {
  2113. this->IndexMakefile(mf.get());
  2114. this->Makefiles.push_back(std::move(mf));
  2115. // update progress
  2116. // estimate how many lg there will be
  2117. cmValue numGenC = this->CMakeInstance->GetState()->GetInitializedCacheValue(
  2118. "CMAKE_NUMBER_OF_MAKEFILES");
  2119. if (!numGenC) {
  2120. // If CMAKE_NUMBER_OF_MAKEFILES is not set
  2121. // we are in the first time progress and we have no
  2122. // idea how long it will be. So, just move half way
  2123. // there each time, and don't go over 95%
  2124. this->FirstTimeProgress += ((1.0f - this->FirstTimeProgress) / 30.0f);
  2125. if (this->FirstTimeProgress > 0.95f) {
  2126. this->FirstTimeProgress = 0.95f;
  2127. }
  2128. this->CMakeInstance->UpdateProgress("Configuring",
  2129. this->FirstTimeProgress);
  2130. return;
  2131. }
  2132. int numGen = atoi(numGenC->c_str());
  2133. float prog =
  2134. static_cast<float>(this->Makefiles.size()) / static_cast<float>(numGen);
  2135. if (prog > 1.0f) {
  2136. prog = 1.0f;
  2137. }
  2138. this->CMakeInstance->UpdateProgress("Configuring", prog);
  2139. }
  2140. void cmGlobalGenerator::AddInstallComponent(const std::string& component)
  2141. {
  2142. if (!component.empty()) {
  2143. this->InstallComponents.insert(component);
  2144. }
  2145. }
  2146. void cmGlobalGenerator::MarkAsGeneratedFile(const std::string& filepath)
  2147. {
  2148. this->GeneratedFiles.insert(filepath);
  2149. }
  2150. bool cmGlobalGenerator::IsGeneratedFile(const std::string& filepath)
  2151. {
  2152. return this->GeneratedFiles.find(filepath) != this->GeneratedFiles.end();
  2153. }
  2154. void cmGlobalGenerator::EnableInstallTarget()
  2155. {
  2156. this->InstallTargetEnabled = true;
  2157. }
  2158. std::unique_ptr<cmLocalGenerator> cmGlobalGenerator::CreateLocalGenerator(
  2159. cmMakefile* mf)
  2160. {
  2161. return cm::make_unique<cmLocalGenerator>(this, mf);
  2162. }
  2163. void cmGlobalGenerator::EnableLanguagesFromGenerator(cmGlobalGenerator* gen,
  2164. cmMakefile* mf)
  2165. {
  2166. this->SetConfiguredFilesPath(gen);
  2167. this->TryCompileOuterMakefile = mf;
  2168. cmValue make =
  2169. gen->GetCMakeInstance()->GetCacheDefinition("CMAKE_MAKE_PROGRAM");
  2170. this->GetCMakeInstance()->AddCacheEntry(
  2171. "CMAKE_MAKE_PROGRAM", make, "make program", cmStateEnums::FILEPATH);
  2172. // copy the enabled languages
  2173. this->GetCMakeInstance()->GetState()->SetEnabledLanguages(
  2174. gen->GetCMakeInstance()->GetState()->GetEnabledLanguages());
  2175. this->LanguagesReady = gen->LanguagesReady;
  2176. this->ExtensionToLanguage = gen->ExtensionToLanguage;
  2177. this->IgnoreExtensions = gen->IgnoreExtensions;
  2178. this->LanguageToOutputExtension = gen->LanguageToOutputExtension;
  2179. this->LanguageToLinkerPreference = gen->LanguageToLinkerPreference;
  2180. this->OutputExtensions = gen->OutputExtensions;
  2181. }
  2182. void cmGlobalGenerator::SetConfiguredFilesPath(cmGlobalGenerator* gen)
  2183. {
  2184. if (!gen->ConfiguredFilesPath.empty()) {
  2185. this->ConfiguredFilesPath = gen->ConfiguredFilesPath;
  2186. } else {
  2187. this->ConfiguredFilesPath =
  2188. cmStrCat(gen->CMakeInstance->GetHomeOutputDirectory(), "/CMakeFiles");
  2189. }
  2190. }
  2191. bool cmGlobalGenerator::IsExcluded(cmStateSnapshot const& rootSnp,
  2192. cmStateSnapshot const& snp_) const
  2193. {
  2194. cmStateSnapshot snp = snp_;
  2195. while (snp.IsValid()) {
  2196. if (snp == rootSnp) {
  2197. // No directory excludes itself.
  2198. return false;
  2199. }
  2200. if (snp.GetDirectory().GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
  2201. // This directory is excluded from its parent.
  2202. return true;
  2203. }
  2204. snp = snp.GetBuildsystemDirectoryParent();
  2205. }
  2206. return false;
  2207. }
  2208. bool cmGlobalGenerator::IsExcluded(cmLocalGenerator* root,
  2209. cmLocalGenerator* gen) const
  2210. {
  2211. assert(gen);
  2212. cmStateSnapshot rootSnp = root->GetStateSnapshot();
  2213. cmStateSnapshot snp = gen->GetStateSnapshot();
  2214. return this->IsExcluded(rootSnp, snp);
  2215. }
  2216. bool cmGlobalGenerator::IsExcluded(cmLocalGenerator* root,
  2217. const cmGeneratorTarget* target) const
  2218. {
  2219. if (!target->IsInBuildSystem()) {
  2220. return true;
  2221. }
  2222. cmMakefile* mf = root->GetMakefile();
  2223. const std::string EXCLUDE_FROM_ALL = "EXCLUDE_FROM_ALL";
  2224. if (cmValue exclude = target->GetProperty(EXCLUDE_FROM_ALL)) {
  2225. // Expand the property value per configuration.
  2226. unsigned int trueCount = 0;
  2227. unsigned int falseCount = 0;
  2228. const std::vector<std::string>& configs =
  2229. mf->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  2230. for (const std::string& config : configs) {
  2231. cmGeneratorExpressionInterpreter genexInterpreter(root, config, target);
  2232. if (cmIsOn(genexInterpreter.Evaluate(*exclude, EXCLUDE_FROM_ALL))) {
  2233. ++trueCount;
  2234. } else {
  2235. ++falseCount;
  2236. }
  2237. }
  2238. // Check whether the genex expansion of the property agrees in all
  2239. // configurations.
  2240. if (trueCount > 0 && falseCount > 0) {
  2241. std::ostringstream e;
  2242. e << "The EXCLUDE_FROM_ALL property of target \"" << target->GetName()
  2243. << "\" varies by configuration. This is not supported by the \""
  2244. << root->GetGlobalGenerator()->GetName() << "\" generator.";
  2245. mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2246. }
  2247. return trueCount;
  2248. }
  2249. // This target is included in its directory. Check whether the
  2250. // directory is excluded.
  2251. return this->IsExcluded(root, target->GetLocalGenerator());
  2252. }
  2253. void cmGlobalGenerator::GetEnabledLanguages(
  2254. std::vector<std::string>& lang) const
  2255. {
  2256. lang = this->CMakeInstance->GetState()->GetEnabledLanguages();
  2257. }
  2258. int cmGlobalGenerator::GetLinkerPreference(const std::string& lang) const
  2259. {
  2260. auto const it = this->LanguageToLinkerPreference.find(lang);
  2261. if (it != this->LanguageToLinkerPreference.end()) {
  2262. return it->second;
  2263. }
  2264. return 0;
  2265. }
  2266. void cmGlobalGenerator::FillProjectMap()
  2267. {
  2268. this->ProjectMap.clear(); // make sure we start with a clean map
  2269. for (const auto& localGen : this->LocalGenerators) {
  2270. // for each local generator add all projects
  2271. cmStateSnapshot snp = localGen->GetStateSnapshot();
  2272. std::string name;
  2273. do {
  2274. std::string snpProjName = snp.GetProjectName();
  2275. if (name != snpProjName) {
  2276. name = snpProjName;
  2277. this->ProjectMap[name].push_back(localGen.get());
  2278. }
  2279. snp = snp.GetBuildsystemDirectoryParent();
  2280. } while (snp.IsValid());
  2281. }
  2282. }
  2283. cmMakefile* cmGlobalGenerator::FindMakefile(const std::string& start_dir) const
  2284. {
  2285. auto const it = this->MakefileSearchIndex.find(start_dir);
  2286. if (it != this->MakefileSearchIndex.end()) {
  2287. return it->second;
  2288. }
  2289. return nullptr;
  2290. }
  2291. cmLocalGenerator* cmGlobalGenerator::FindLocalGenerator(
  2292. cmDirectoryId const& id) const
  2293. {
  2294. auto const it = this->LocalGeneratorSearchIndex.find(id.String);
  2295. if (it != this->LocalGeneratorSearchIndex.end()) {
  2296. return it->second;
  2297. }
  2298. return nullptr;
  2299. }
  2300. void cmGlobalGenerator::AddAlias(const std::string& name,
  2301. std::string const& tgtName)
  2302. {
  2303. this->AliasTargets[name] = tgtName;
  2304. }
  2305. bool cmGlobalGenerator::IsAlias(const std::string& name) const
  2306. {
  2307. return cm::contains(this->AliasTargets, name);
  2308. }
  2309. void cmGlobalGenerator::IndexTarget(cmTarget* t)
  2310. {
  2311. if (!t->IsImported() || t->IsImportedGloballyVisible()) {
  2312. this->TargetSearchIndex[t->GetName()] = t;
  2313. }
  2314. }
  2315. void cmGlobalGenerator::IndexGeneratorTarget(cmGeneratorTarget* gt)
  2316. {
  2317. if (!gt->IsImported() || gt->IsImportedGloballyVisible()) {
  2318. this->GeneratorTargetSearchIndex[gt->GetName()] = gt;
  2319. }
  2320. }
  2321. static char const hexDigits[] = "0123456789abcdef";
  2322. std::string cmGlobalGenerator::IndexGeneratorTargetUniquely(
  2323. cmGeneratorTarget const* gt)
  2324. {
  2325. // Use the pointer value to uniquely identify the target instance.
  2326. // Use a ":" prefix to avoid conflict with project-defined targets.
  2327. // We must satisfy cmGeneratorExpression::IsValidTargetName so use no
  2328. // other special characters.
  2329. constexpr size_t sizeof_ptr =
  2330. sizeof(gt); // NOLINT(bugprone-sizeof-expression)
  2331. char buf[1 + sizeof_ptr * 2];
  2332. char* b = buf;
  2333. *b++ = ':';
  2334. for (size_t i = 0; i < sizeof_ptr; ++i) {
  2335. unsigned char const c = reinterpret_cast<unsigned char const*>(&gt)[i];
  2336. *b++ = hexDigits[(c & 0xf0) >> 4];
  2337. *b++ = hexDigits[(c & 0x0f)];
  2338. }
  2339. std::string id(buf, sizeof(buf));
  2340. // We internally index pointers to non-const generator targets
  2341. // but our callers only have pointers to const generator targets.
  2342. // They will give up non-const privileges when looking up anyway.
  2343. this->GeneratorTargetSearchIndex[id] = const_cast<cmGeneratorTarget*>(gt);
  2344. return id;
  2345. }
  2346. void cmGlobalGenerator::IndexMakefile(cmMakefile* mf)
  2347. {
  2348. // We index by both source and binary directory. add_subdirectory
  2349. // supports multiple build directories sharing the same source directory.
  2350. // The source directory index will reference only the first time it is used.
  2351. this->MakefileSearchIndex.insert(
  2352. MakefileMap::value_type(mf->GetCurrentSourceDirectory(), mf));
  2353. this->MakefileSearchIndex.insert(
  2354. MakefileMap::value_type(mf->GetCurrentBinaryDirectory(), mf));
  2355. }
  2356. void cmGlobalGenerator::IndexLocalGenerator(cmLocalGenerator* lg)
  2357. {
  2358. cmDirectoryId id = lg->GetMakefile()->GetDirectoryId();
  2359. this->LocalGeneratorSearchIndex[id.String] = lg;
  2360. }
  2361. cmTarget* cmGlobalGenerator::FindTargetImpl(std::string const& name) const
  2362. {
  2363. auto const it = this->TargetSearchIndex.find(name);
  2364. if (it != this->TargetSearchIndex.end()) {
  2365. return it->second;
  2366. }
  2367. return nullptr;
  2368. }
  2369. cmGeneratorTarget* cmGlobalGenerator::FindGeneratorTargetImpl(
  2370. std::string const& name) const
  2371. {
  2372. auto const it = this->GeneratorTargetSearchIndex.find(name);
  2373. if (it != this->GeneratorTargetSearchIndex.end()) {
  2374. return it->second;
  2375. }
  2376. return nullptr;
  2377. }
  2378. cmTarget* cmGlobalGenerator::FindTarget(const std::string& name,
  2379. bool excludeAliases) const
  2380. {
  2381. if (!excludeAliases) {
  2382. auto const ai = this->AliasTargets.find(name);
  2383. if (ai != this->AliasTargets.end()) {
  2384. return this->FindTargetImpl(ai->second);
  2385. }
  2386. }
  2387. return this->FindTargetImpl(name);
  2388. }
  2389. cmGeneratorTarget* cmGlobalGenerator::FindGeneratorTarget(
  2390. const std::string& name) const
  2391. {
  2392. auto const ai = this->AliasTargets.find(name);
  2393. if (ai != this->AliasTargets.end()) {
  2394. return this->FindGeneratorTargetImpl(ai->second);
  2395. }
  2396. return this->FindGeneratorTargetImpl(name);
  2397. }
  2398. bool cmGlobalGenerator::NameResolvesToFramework(
  2399. const std::string& libname) const
  2400. {
  2401. if (cmSystemTools::IsPathToFramework(libname)) {
  2402. return true;
  2403. }
  2404. if (cmTarget* tgt = this->FindTarget(libname)) {
  2405. if (tgt->IsFrameworkOnApple()) {
  2406. return true;
  2407. }
  2408. }
  2409. return false;
  2410. }
  2411. // If the file has no extension it's either a raw executable or might
  2412. // be a direct reference to a binary within a framework (bad practice!).
  2413. // This is where we change the path to point to the framework directory.
  2414. // .tbd files also can be located in SDK frameworks (they are
  2415. // placeholders for actual libraries shipped with the OS)
  2416. cm::optional<cmGlobalGenerator::FrameworkDescriptor>
  2417. cmGlobalGenerator::SplitFrameworkPath(const std::string& path,
  2418. FrameworkFormat format) const
  2419. {
  2420. // Check for framework structure:
  2421. // (/path/to/)?FwName.framework
  2422. // or (/path/to/)?FwName.framework/FwName(.tbd)?
  2423. // or (/path/to/)?FwName.framework/Versions/*/FwName(.tbd)?
  2424. static cmsys::RegularExpression frameworkPath(
  2425. "((.+)/)?([^/]+)\\.framework(/Versions/([^/]+))?(/(.+))?$");
  2426. auto ext = cmSystemTools::GetFilenameLastExtension(path);
  2427. if ((ext.empty() || ext == ".tbd" || ext == ".framework") &&
  2428. frameworkPath.find(path)) {
  2429. auto name = frameworkPath.match(3);
  2430. auto libname =
  2431. cmSystemTools::GetFilenameWithoutExtension(frameworkPath.match(7));
  2432. if (format == FrameworkFormat::Strict && libname.empty()) {
  2433. return cm::nullopt;
  2434. }
  2435. if (!libname.empty() && !cmHasPrefix(libname, name)) {
  2436. return cm::nullopt;
  2437. }
  2438. if (libname.empty() || name.size() == libname.size()) {
  2439. return FrameworkDescriptor{ frameworkPath.match(2),
  2440. frameworkPath.match(5), name };
  2441. }
  2442. return FrameworkDescriptor{ frameworkPath.match(2), frameworkPath.match(5),
  2443. name, libname.substr(name.size()) };
  2444. }
  2445. if (format == FrameworkFormat::Extended) {
  2446. // path format can be more flexible: (/path/to/)?fwName(.framework)?
  2447. auto fwDir = cmSystemTools::GetParentDirectory(path);
  2448. auto name = cmSystemTools::GetFilenameLastExtension(path) == ".framework"
  2449. ? cmSystemTools::GetFilenameWithoutExtension(path)
  2450. : cmSystemTools::GetFilenameName(path);
  2451. return FrameworkDescriptor{ fwDir, name };
  2452. }
  2453. return cm::nullopt;
  2454. }
  2455. static bool RaiseCMP0037Message(cmake* cm, cmTarget* tgt,
  2456. std::string const& targetNameAsWritten,
  2457. std::string const& reason)
  2458. {
  2459. MessageType messageType = MessageType::AUTHOR_WARNING;
  2460. std::ostringstream e;
  2461. bool issueMessage = false;
  2462. switch (tgt->GetPolicyStatusCMP0037()) {
  2463. case cmPolicies::WARN:
  2464. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0037) << "\n";
  2465. issueMessage = true;
  2466. CM_FALLTHROUGH;
  2467. case cmPolicies::OLD:
  2468. break;
  2469. case cmPolicies::NEW:
  2470. case cmPolicies::REQUIRED_IF_USED:
  2471. case cmPolicies::REQUIRED_ALWAYS:
  2472. issueMessage = true;
  2473. messageType = MessageType::FATAL_ERROR;
  2474. break;
  2475. }
  2476. if (issueMessage) {
  2477. e << "The target name \"" << targetNameAsWritten << "\" is reserved "
  2478. << reason << ".";
  2479. if (messageType == MessageType::AUTHOR_WARNING) {
  2480. e << " It may result in undefined behavior.";
  2481. }
  2482. cm->IssueMessage(messageType, e.str(), tgt->GetBacktrace());
  2483. if (messageType == MessageType::FATAL_ERROR) {
  2484. return false;
  2485. }
  2486. }
  2487. return true;
  2488. }
  2489. bool cmGlobalGenerator::CheckCMP0037(std::string const& targetName,
  2490. std::string const& reason) const
  2491. {
  2492. cmTarget* tgt = this->FindTarget(targetName);
  2493. if (!tgt) {
  2494. return true;
  2495. }
  2496. return RaiseCMP0037Message(this->GetCMakeInstance(), tgt, targetName,
  2497. reason);
  2498. }
  2499. void cmGlobalGenerator::CreateDefaultGlobalTargets(
  2500. std::vector<GlobalTargetInfo>& targets)
  2501. {
  2502. this->AddGlobalTarget_Package(targets);
  2503. this->AddGlobalTarget_PackageSource(targets);
  2504. this->AddGlobalTarget_Test(targets);
  2505. this->AddGlobalTarget_EditCache(targets);
  2506. this->AddGlobalTarget_RebuildCache(targets);
  2507. this->AddGlobalTarget_Install(targets);
  2508. }
  2509. void cmGlobalGenerator::AddGlobalTarget_Package(
  2510. std::vector<GlobalTargetInfo>& targets)
  2511. {
  2512. auto& mf = this->Makefiles[0];
  2513. std::string configFile =
  2514. cmStrCat(mf->GetCurrentBinaryDirectory(), "/CPackConfig.cmake");
  2515. if (!cmSystemTools::FileExists(configFile)) {
  2516. return;
  2517. }
  2518. static const auto reservedTargets = { "package", "PACKAGE" };
  2519. for (auto const& target : reservedTargets) {
  2520. if (!this->CheckCMP0037(target, "when CPack packaging is enabled")) {
  2521. return;
  2522. }
  2523. }
  2524. const char* cmakeCfgIntDir = this->GetCMakeCFGIntDir();
  2525. GlobalTargetInfo gti;
  2526. gti.Name = this->GetPackageTargetName();
  2527. gti.Message = "Run CPack packaging tool...";
  2528. gti.UsesTerminal = true;
  2529. gti.WorkingDir = mf->GetCurrentBinaryDirectory();
  2530. cmCustomCommandLine singleLine;
  2531. singleLine.push_back(cmSystemTools::GetCPackCommand());
  2532. if (cmNonempty(cmakeCfgIntDir) && cmakeCfgIntDir[0] != '.') {
  2533. singleLine.push_back("-C");
  2534. singleLine.push_back(cmakeCfgIntDir);
  2535. }
  2536. singleLine.push_back("--config");
  2537. singleLine.push_back("./CPackConfig.cmake");
  2538. gti.CommandLines.push_back(std::move(singleLine));
  2539. if (this->GetPreinstallTargetName()) {
  2540. gti.Depends.emplace_back(this->GetPreinstallTargetName());
  2541. } else {
  2542. cmValue noPackageAll =
  2543. mf->GetDefinition("CMAKE_SKIP_PACKAGE_ALL_DEPENDENCY");
  2544. if (noPackageAll.IsOff()) {
  2545. gti.Depends.emplace_back(this->GetAllTargetName());
  2546. }
  2547. }
  2548. targets.push_back(std::move(gti));
  2549. }
  2550. void cmGlobalGenerator::AddGlobalTarget_PackageSource(
  2551. std::vector<GlobalTargetInfo>& targets)
  2552. {
  2553. const char* packageSourceTargetName = this->GetPackageSourceTargetName();
  2554. if (!packageSourceTargetName) {
  2555. return;
  2556. }
  2557. auto& mf = this->Makefiles[0];
  2558. std::string configFile =
  2559. cmStrCat(mf->GetCurrentBinaryDirectory(), "/CPackSourceConfig.cmake");
  2560. if (!cmSystemTools::FileExists(configFile)) {
  2561. return;
  2562. }
  2563. static const auto reservedTargets = { "package_source" };
  2564. for (auto const& target : reservedTargets) {
  2565. if (!this->CheckCMP0037(target,
  2566. "when CPack source packaging is enabled")) {
  2567. return;
  2568. }
  2569. }
  2570. GlobalTargetInfo gti;
  2571. gti.Name = packageSourceTargetName;
  2572. gti.Message = "Run CPack packaging tool for source...";
  2573. gti.WorkingDir = mf->GetCurrentBinaryDirectory();
  2574. gti.UsesTerminal = true;
  2575. cmCustomCommandLine singleLine;
  2576. singleLine.push_back(cmSystemTools::GetCPackCommand());
  2577. singleLine.push_back("--config");
  2578. singleLine.push_back("./CPackSourceConfig.cmake");
  2579. singleLine.push_back(std::move(configFile));
  2580. gti.CommandLines.push_back(std::move(singleLine));
  2581. targets.push_back(std::move(gti));
  2582. }
  2583. void cmGlobalGenerator::AddGlobalTarget_Test(
  2584. std::vector<GlobalTargetInfo>& targets)
  2585. {
  2586. auto& mf = this->Makefiles[0];
  2587. if (!mf->IsOn("CMAKE_TESTING_ENABLED")) {
  2588. return;
  2589. }
  2590. static const auto reservedTargets = { "test", "RUN_TESTS" };
  2591. for (auto const& target : reservedTargets) {
  2592. if (!this->CheckCMP0037(target, "when CTest testing is enabled")) {
  2593. return;
  2594. }
  2595. }
  2596. const char* cmakeCfgIntDir = this->GetCMakeCFGIntDir();
  2597. GlobalTargetInfo gti;
  2598. gti.Name = this->GetTestTargetName();
  2599. gti.Message = "Running tests...";
  2600. gti.UsesTerminal = true;
  2601. // Unlike the 'install' target, the 'test' target does not depend on 'all'
  2602. // by default. Enable it only if CMAKE_SKIP_TEST_ALL_DEPENDENCY is
  2603. // explicitly set to OFF.
  2604. if (cmValue noall = mf->GetDefinition("CMAKE_SKIP_TEST_ALL_DEPENDENCY")) {
  2605. if (noall.IsOff()) {
  2606. gti.Depends.emplace_back(this->GetAllTargetName());
  2607. }
  2608. }
  2609. cmCustomCommandLine singleLine;
  2610. singleLine.push_back(cmSystemTools::GetCTestCommand());
  2611. singleLine.push_back("--force-new-ctest-process");
  2612. cmList args(mf->GetDefinition("CMAKE_CTEST_ARGUMENTS"));
  2613. for (auto const& arg : args) {
  2614. singleLine.push_back(arg);
  2615. }
  2616. if (cmNonempty(cmakeCfgIntDir) && cmakeCfgIntDir[0] != '.') {
  2617. singleLine.push_back("-C");
  2618. singleLine.push_back(cmakeCfgIntDir);
  2619. } else // TODO: This is a hack. Should be something to do with the
  2620. // generator
  2621. {
  2622. singleLine.push_back("$(ARGS)");
  2623. }
  2624. gti.CommandLines.push_back(std::move(singleLine));
  2625. targets.push_back(std::move(gti));
  2626. }
  2627. void cmGlobalGenerator::AddGlobalTarget_EditCache(
  2628. std::vector<GlobalTargetInfo>& targets) const
  2629. {
  2630. const char* editCacheTargetName = this->GetEditCacheTargetName();
  2631. if (!editCacheTargetName) {
  2632. return;
  2633. }
  2634. GlobalTargetInfo gti;
  2635. gti.Name = editCacheTargetName;
  2636. gti.PerConfig = cmTarget::PerConfig::No;
  2637. cmCustomCommandLine singleLine;
  2638. // Use generator preference for the edit_cache rule if it is defined.
  2639. std::string edit_cmd = this->GetEditCacheCommand();
  2640. if (!edit_cmd.empty()) {
  2641. singleLine.push_back(std::move(edit_cmd));
  2642. if (this->GetCMakeInstance()->GetIgnoreWarningAsError()) {
  2643. singleLine.push_back("--compile-no-warning-as-error");
  2644. }
  2645. singleLine.push_back("-S$(CMAKE_SOURCE_DIR)");
  2646. singleLine.push_back("-B$(CMAKE_BINARY_DIR)");
  2647. gti.Message = "Running CMake cache editor...";
  2648. gti.UsesTerminal = true;
  2649. } else {
  2650. singleLine.push_back(cmSystemTools::GetCMakeCommand());
  2651. singleLine.push_back("-E");
  2652. singleLine.push_back("echo");
  2653. singleLine.push_back("No interactive CMake dialog available.");
  2654. gti.Message = "No interactive CMake dialog available...";
  2655. gti.UsesTerminal = false;
  2656. gti.StdPipesUTF8 = true;
  2657. }
  2658. gti.CommandLines.push_back(std::move(singleLine));
  2659. targets.push_back(std::move(gti));
  2660. }
  2661. void cmGlobalGenerator::AddGlobalTarget_RebuildCache(
  2662. std::vector<GlobalTargetInfo>& targets) const
  2663. {
  2664. const char* rebuildCacheTargetName = this->GetRebuildCacheTargetName();
  2665. if (!rebuildCacheTargetName) {
  2666. return;
  2667. }
  2668. GlobalTargetInfo gti;
  2669. gti.Name = rebuildCacheTargetName;
  2670. gti.Message = "Running CMake to regenerate build system...";
  2671. gti.UsesTerminal = true;
  2672. gti.PerConfig = cmTarget::PerConfig::No;
  2673. cmCustomCommandLine singleLine;
  2674. singleLine.push_back(cmSystemTools::GetCMakeCommand());
  2675. singleLine.push_back("--regenerate-during-build");
  2676. if (this->GetCMakeInstance()->GetIgnoreWarningAsError()) {
  2677. singleLine.push_back("--compile-no-warning-as-error");
  2678. }
  2679. singleLine.push_back("-S$(CMAKE_SOURCE_DIR)");
  2680. singleLine.push_back("-B$(CMAKE_BINARY_DIR)");
  2681. gti.CommandLines.push_back(std::move(singleLine));
  2682. gti.StdPipesUTF8 = true;
  2683. targets.push_back(std::move(gti));
  2684. }
  2685. void cmGlobalGenerator::AddGlobalTarget_Install(
  2686. std::vector<GlobalTargetInfo>& targets)
  2687. {
  2688. auto& mf = this->Makefiles[0];
  2689. const char* cmakeCfgIntDir = this->GetCMakeCFGIntDir();
  2690. bool skipInstallRules = mf->IsOn("CMAKE_SKIP_INSTALL_RULES");
  2691. if (this->InstallTargetEnabled && skipInstallRules) {
  2692. this->CMakeInstance->IssueMessage(
  2693. MessageType::WARNING,
  2694. "CMAKE_SKIP_INSTALL_RULES was enabled even though "
  2695. "installation rules have been specified",
  2696. mf->GetBacktrace());
  2697. } else if (this->InstallTargetEnabled && !skipInstallRules) {
  2698. if (!(cmNonempty(cmakeCfgIntDir) && cmakeCfgIntDir[0] != '.')) {
  2699. std::set<std::string>* componentsSet = &this->InstallComponents;
  2700. std::ostringstream ostr;
  2701. if (!componentsSet->empty()) {
  2702. ostr << "Available install components are: ";
  2703. ostr << cmWrap('"', *componentsSet, '"', " ");
  2704. } else {
  2705. ostr << "Only default component available";
  2706. }
  2707. GlobalTargetInfo gti;
  2708. gti.Name = "list_install_components";
  2709. gti.Message = ostr.str();
  2710. gti.UsesTerminal = false;
  2711. targets.push_back(std::move(gti));
  2712. }
  2713. std::string cmd = cmSystemTools::GetCMakeCommand();
  2714. GlobalTargetInfo gti;
  2715. gti.Name = this->GetInstallTargetName();
  2716. gti.Message = "Install the project...";
  2717. gti.UsesTerminal = true;
  2718. gti.StdPipesUTF8 = true;
  2719. cmCustomCommandLine singleLine;
  2720. if (this->GetPreinstallTargetName()) {
  2721. gti.Depends.emplace_back(this->GetPreinstallTargetName());
  2722. } else {
  2723. cmValue noall = mf->GetDefinition("CMAKE_SKIP_INSTALL_ALL_DEPENDENCY");
  2724. if (noall.IsOff()) {
  2725. gti.Depends.emplace_back(this->GetAllTargetName());
  2726. }
  2727. }
  2728. if (mf->GetDefinition("CMake_BINARY_DIR") &&
  2729. !mf->IsOn("CMAKE_CROSSCOMPILING")) {
  2730. // We are building CMake itself. We cannot use the original
  2731. // executable to install over itself. The generator will
  2732. // automatically convert this name to the build-time location.
  2733. cmd = "cmake";
  2734. }
  2735. singleLine.push_back(cmd);
  2736. if (cmNonempty(cmakeCfgIntDir) && cmakeCfgIntDir[0] != '.') {
  2737. std::string cfgArg = "-DBUILD_TYPE=";
  2738. bool useEPN = this->UseEffectivePlatformName(mf.get());
  2739. if (useEPN) {
  2740. cfgArg += "$(CONFIGURATION)";
  2741. singleLine.push_back(cfgArg);
  2742. cfgArg = "-DEFFECTIVE_PLATFORM_NAME=$(EFFECTIVE_PLATFORM_NAME)";
  2743. } else {
  2744. cfgArg += this->GetCMakeCFGIntDir();
  2745. }
  2746. singleLine.push_back(cfgArg);
  2747. }
  2748. singleLine.push_back("-P");
  2749. singleLine.push_back("cmake_install.cmake");
  2750. gti.CommandLines.push_back(singleLine);
  2751. targets.push_back(gti);
  2752. // install_local
  2753. if (const char* install_local = this->GetInstallLocalTargetName()) {
  2754. gti.Name = install_local;
  2755. gti.Message = "Installing only the local directory...";
  2756. gti.UsesTerminal =
  2757. !this->GetCMakeInstance()->GetState()->GetGlobalPropertyAsBool(
  2758. "INSTALL_PARALLEL");
  2759. gti.CommandLines.clear();
  2760. cmCustomCommandLine localCmdLine = singleLine;
  2761. localCmdLine.insert(localCmdLine.begin() + 1,
  2762. "-DCMAKE_INSTALL_LOCAL_ONLY=1");
  2763. gti.CommandLines.push_back(std::move(localCmdLine));
  2764. targets.push_back(gti);
  2765. }
  2766. // install_strip
  2767. const char* install_strip = this->GetInstallStripTargetName();
  2768. if ((install_strip != nullptr) && (mf->IsSet("CMAKE_STRIP"))) {
  2769. gti.Name = install_strip;
  2770. gti.Message = "Installing the project stripped...";
  2771. gti.UsesTerminal = true;
  2772. gti.CommandLines.clear();
  2773. cmCustomCommandLine stripCmdLine = singleLine;
  2774. stripCmdLine.insert(stripCmdLine.begin() + 1,
  2775. "-DCMAKE_INSTALL_DO_STRIP=1");
  2776. gti.CommandLines.push_back(std::move(stripCmdLine));
  2777. targets.push_back(gti);
  2778. }
  2779. }
  2780. }
  2781. std::string cmGlobalGenerator::GetPredefinedTargetsFolder() const
  2782. {
  2783. cmValue prop = this->GetCMakeInstance()->GetState()->GetGlobalProperty(
  2784. "PREDEFINED_TARGETS_FOLDER");
  2785. if (prop) {
  2786. return *prop;
  2787. }
  2788. return "CMakePredefinedTargets";
  2789. }
  2790. bool cmGlobalGenerator::UseFolderProperty() const
  2791. {
  2792. const cmValue prop =
  2793. this->GetCMakeInstance()->GetState()->GetGlobalProperty("USE_FOLDERS");
  2794. // If this property is defined, let the setter turn this on or off.
  2795. if (prop) {
  2796. return prop.IsOn();
  2797. }
  2798. // If CMP0143 is NEW `treat` "USE_FOLDERS" as ON. Otherwise `treat` it as OFF
  2799. assert(!this->Makefiles.empty());
  2800. return (this->Makefiles[0]->GetPolicyStatus(cmPolicies::CMP0143) ==
  2801. cmPolicies::NEW);
  2802. }
  2803. void cmGlobalGenerator::CreateGlobalTarget(GlobalTargetInfo const& gti,
  2804. cmMakefile* mf)
  2805. {
  2806. // Package
  2807. auto tb =
  2808. mf->CreateNewTarget(gti.Name, cmStateEnums::GLOBAL_TARGET, gti.PerConfig);
  2809. // Do nothing if gti.Name is already used
  2810. if (!tb.second) {
  2811. return;
  2812. }
  2813. cmTarget& target = tb.first;
  2814. target.SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  2815. // Store the custom command in the target.
  2816. cmCustomCommand cc;
  2817. cc.SetCommandLines(gti.CommandLines);
  2818. cc.SetWorkingDirectory(gti.WorkingDir.c_str());
  2819. cc.SetStdPipesUTF8(gti.StdPipesUTF8);
  2820. cc.SetUsesTerminal(gti.UsesTerminal);
  2821. target.AddPostBuildCommand(std::move(cc));
  2822. if (!gti.Message.empty()) {
  2823. target.SetProperty("EchoString", gti.Message);
  2824. }
  2825. for (std::string const& d : gti.Depends) {
  2826. target.AddUtility(d, false);
  2827. }
  2828. // Organize in the "predefined targets" folder:
  2829. //
  2830. if (this->UseFolderProperty()) {
  2831. target.SetProperty("FOLDER", this->GetPredefinedTargetsFolder());
  2832. }
  2833. }
  2834. std::string cmGlobalGenerator::GenerateRuleFile(
  2835. std::string const& output) const
  2836. {
  2837. std::string ruleFile = cmStrCat(output, ".rule");
  2838. const char* dir = this->GetCMakeCFGIntDir();
  2839. if (dir && dir[0] == '$') {
  2840. cmSystemTools::ReplaceString(ruleFile, dir, "/CMakeFiles");
  2841. }
  2842. return ruleFile;
  2843. }
  2844. bool cmGlobalGenerator::ShouldStripResourcePath(cmMakefile* mf) const
  2845. {
  2846. return mf->PlatformIsAppleEmbedded();
  2847. }
  2848. std::string cmGlobalGenerator::GetSharedLibFlagsForLanguage(
  2849. std::string const& l) const
  2850. {
  2851. auto const it = this->LanguageToOriginalSharedLibFlags.find(l);
  2852. if (it != this->LanguageToOriginalSharedLibFlags.end()) {
  2853. return it->second;
  2854. }
  2855. return "";
  2856. }
  2857. void cmGlobalGenerator::AppendDirectoryForConfig(const std::string& /*unused*/,
  2858. const std::string& /*unused*/,
  2859. const std::string& /*unused*/,
  2860. std::string& /*unused*/)
  2861. {
  2862. // Subclasses that support multiple configurations should implement
  2863. // this method to append the subdirectory for the given build
  2864. // configuration.
  2865. }
  2866. cmGlobalGenerator::TargetDependSet const&
  2867. cmGlobalGenerator::GetTargetDirectDepends(cmGeneratorTarget const* target)
  2868. {
  2869. return this->TargetDependencies[target];
  2870. }
  2871. bool cmGlobalGenerator::TargetOrderIndexLess(cmGeneratorTarget const* l,
  2872. cmGeneratorTarget const* r) const
  2873. {
  2874. return this->TargetOrderIndex.at(l) < this->TargetOrderIndex.at(r);
  2875. }
  2876. bool cmGlobalGenerator::IsReservedTarget(std::string const& name)
  2877. {
  2878. // The following is a list of targets reserved
  2879. // by one or more of the cmake generators.
  2880. // Adding additional targets to this list will require a policy!
  2881. static const cm::static_string_view reservedTargets[] = {
  2882. "all"_s, "ALL_BUILD"_s, "help"_s, "install"_s,
  2883. "INSTALL"_s, "preinstall"_s, "clean"_s, "edit_cache"_s,
  2884. "rebuild_cache"_s, "ZERO_CHECK"_s
  2885. };
  2886. return cm::contains(reservedTargets, name);
  2887. }
  2888. void cmGlobalGenerator::SetExternalMakefileProjectGenerator(
  2889. std::unique_ptr<cmExternalMakefileProjectGenerator> extraGenerator)
  2890. {
  2891. this->ExtraGenerator = std::move(extraGenerator);
  2892. if (this->ExtraGenerator) {
  2893. this->ExtraGenerator->SetGlobalGenerator(this);
  2894. }
  2895. }
  2896. std::string cmGlobalGenerator::GetExtraGeneratorName() const
  2897. {
  2898. return this->ExtraGenerator ? this->ExtraGenerator->GetName()
  2899. : std::string();
  2900. }
  2901. void cmGlobalGenerator::FileReplacedDuringGenerate(const std::string& filename)
  2902. {
  2903. this->FilesReplacedDuringGenerate.push_back(filename);
  2904. }
  2905. void cmGlobalGenerator::GetFilesReplacedDuringGenerate(
  2906. std::vector<std::string>& filenames)
  2907. {
  2908. filenames.clear();
  2909. std::copy(this->FilesReplacedDuringGenerate.begin(),
  2910. this->FilesReplacedDuringGenerate.end(),
  2911. std::back_inserter(filenames));
  2912. }
  2913. void cmGlobalGenerator::GetTargetSets(
  2914. TargetDependSet& projectTargets, TargetDependSet& originalTargets,
  2915. cmLocalGenerator* root, std::vector<cmLocalGenerator*>& generators)
  2916. {
  2917. // loop over all local generators
  2918. for (auto* generator : generators) {
  2919. // check to make sure generator is not excluded
  2920. if (this->IsExcluded(root, generator)) {
  2921. continue;
  2922. }
  2923. // loop over all the generator targets in the makefile
  2924. for (const auto& target : generator->GetGeneratorTargets()) {
  2925. if (this->IsRootOnlyTarget(target.get()) &&
  2926. target->GetLocalGenerator() != root) {
  2927. continue;
  2928. }
  2929. // put the target in the set of original targets
  2930. originalTargets.insert(target.get());
  2931. // Get the set of targets that depend on target
  2932. this->AddTargetDepends(target.get(), projectTargets);
  2933. }
  2934. }
  2935. }
  2936. bool cmGlobalGenerator::IsRootOnlyTarget(cmGeneratorTarget* target) const
  2937. {
  2938. return (target->GetType() == cmStateEnums::GLOBAL_TARGET ||
  2939. target->GetName() == this->GetAllTargetName());
  2940. }
  2941. void cmGlobalGenerator::AddTargetDepends(cmGeneratorTarget const* target,
  2942. TargetDependSet& projectTargets)
  2943. {
  2944. // add the target itself
  2945. if (projectTargets.insert(target).second) {
  2946. // This is the first time we have encountered the target.
  2947. // Recursively follow its dependencies.
  2948. for (auto const& t : this->GetTargetDirectDepends(target)) {
  2949. this->AddTargetDepends(t, projectTargets);
  2950. }
  2951. }
  2952. }
  2953. void cmGlobalGenerator::AddToManifest(std::string const& f)
  2954. {
  2955. // Add to the content listing for the file's directory.
  2956. std::string dir = cmSystemTools::GetFilenamePath(f);
  2957. std::string file = cmSystemTools::GetFilenameName(f);
  2958. DirectoryContent& dc = this->DirectoryContentMap[dir];
  2959. dc.Generated.insert(file);
  2960. dc.All.insert(file);
  2961. }
  2962. std::set<std::string> const& cmGlobalGenerator::GetDirectoryContent(
  2963. std::string const& dir, bool needDisk)
  2964. {
  2965. DirectoryContent& dc = this->DirectoryContentMap[dir];
  2966. if (needDisk) {
  2967. long mt = cmSystemTools::ModifiedTime(dir);
  2968. if (mt != dc.LastDiskTime) {
  2969. // Reset to non-loaded directory content.
  2970. dc.All = dc.Generated;
  2971. // Load the directory content from disk.
  2972. cmsys::Directory d;
  2973. if (d.Load(dir)) {
  2974. unsigned long n = d.GetNumberOfFiles();
  2975. for (unsigned long i = 0; i < n; ++i) {
  2976. const char* f = d.GetFile(i);
  2977. if (strcmp(f, ".") != 0 && strcmp(f, "..") != 0) {
  2978. dc.All.insert(f);
  2979. }
  2980. }
  2981. }
  2982. dc.LastDiskTime = mt;
  2983. }
  2984. }
  2985. return dc.All;
  2986. }
  2987. void cmGlobalGenerator::AddRuleHash(const std::vector<std::string>& outputs,
  2988. std::string const& content)
  2989. {
  2990. // Ignore if there are no outputs.
  2991. if (outputs.empty()) {
  2992. return;
  2993. }
  2994. // Compute a hash of the rule.
  2995. RuleHash hash;
  2996. {
  2997. cmCryptoHash md5(cmCryptoHash::AlgoMD5);
  2998. std::string const md5_hex = md5.HashString(content);
  2999. memcpy(hash.Data, md5_hex.c_str(), 32);
  3000. }
  3001. // Shorten the output name (in expected use case).
  3002. std::string fname =
  3003. this->LocalGenerators[0]->MaybeRelativeToTopBinDir(outputs[0]);
  3004. // Associate the hash with this output.
  3005. this->RuleHashes[fname] = hash;
  3006. }
  3007. void cmGlobalGenerator::CheckRuleHashes()
  3008. {
  3009. std::string home = this->GetCMakeInstance()->GetHomeOutputDirectory();
  3010. std::string pfile = cmStrCat(home, "/CMakeFiles/CMakeRuleHashes.txt");
  3011. this->CheckRuleHashes(pfile, home);
  3012. this->WriteRuleHashes(pfile);
  3013. }
  3014. void cmGlobalGenerator::CheckRuleHashes(std::string const& pfile,
  3015. std::string const& home)
  3016. {
  3017. #if defined(_WIN32) || defined(__CYGWIN__)
  3018. cmsys::ifstream fin(pfile.c_str(), std::ios::in | std::ios::binary);
  3019. #else
  3020. cmsys::ifstream fin(pfile.c_str());
  3021. #endif
  3022. if (!fin) {
  3023. return;
  3024. }
  3025. std::string line;
  3026. std::string fname;
  3027. while (cmSystemTools::GetLineFromStream(fin, line)) {
  3028. // Line format is a 32-byte hex string followed by a space
  3029. // followed by a file name (with no escaping).
  3030. // Skip blank and comment lines.
  3031. if (line.size() < 34 || line[0] == '#') {
  3032. continue;
  3033. }
  3034. // Get the filename.
  3035. fname = line.substr(33);
  3036. // Look for a hash for this file's rule.
  3037. auto const rhi = this->RuleHashes.find(fname);
  3038. if (rhi != this->RuleHashes.end()) {
  3039. // Compare the rule hash in the file to that we were given.
  3040. if (strncmp(line.c_str(), rhi->second.Data, 32) != 0) {
  3041. // The rule has changed. Delete the output so it will be
  3042. // built again.
  3043. fname = cmSystemTools::CollapseFullPath(fname, home);
  3044. cmSystemTools::RemoveFile(fname);
  3045. }
  3046. } else {
  3047. // We have no hash for a rule previously listed. This may be a
  3048. // case where a user has turned off a build option and might
  3049. // want to turn it back on later, so do not delete the file.
  3050. // Instead, we keep the rule hash as long as the file exists so
  3051. // that if the feature is turned back on and the rule has
  3052. // changed the file is still rebuilt.
  3053. std::string fpath = cmSystemTools::CollapseFullPath(fname, home);
  3054. if (cmSystemTools::FileExists(fpath)) {
  3055. RuleHash hash;
  3056. memcpy(hash.Data, line.c_str(), 32);
  3057. this->RuleHashes[fname] = hash;
  3058. }
  3059. }
  3060. }
  3061. }
  3062. void cmGlobalGenerator::WriteRuleHashes(std::string const& pfile)
  3063. {
  3064. // Now generate a new persistence file with the current hashes.
  3065. if (this->RuleHashes.empty()) {
  3066. cmSystemTools::RemoveFile(pfile);
  3067. } else {
  3068. cmGeneratedFileStream fout(pfile);
  3069. fout << "# Hashes of file build rules.\n";
  3070. for (auto const& rh : this->RuleHashes) {
  3071. fout.write(rh.second.Data, 32);
  3072. fout << " " << rh.first << "\n";
  3073. }
  3074. }
  3075. }
  3076. void cmGlobalGenerator::WriteSummary()
  3077. {
  3078. // Record all target directories in a central location.
  3079. std::string fname = cmStrCat(this->CMakeInstance->GetHomeOutputDirectory(),
  3080. "/CMakeFiles/TargetDirectories.txt");
  3081. cmGeneratedFileStream fout(fname);
  3082. for (const auto& lg : this->LocalGenerators) {
  3083. for (const auto& tgt : lg->GetGeneratorTargets()) {
  3084. if (!tgt->IsInBuildSystem()) {
  3085. continue;
  3086. }
  3087. this->WriteSummary(tgt.get());
  3088. fout << tgt->GetSupportDirectory() << "\n";
  3089. }
  3090. }
  3091. }
  3092. void cmGlobalGenerator::WriteSummary(cmGeneratorTarget* target)
  3093. {
  3094. // Place the labels file in a per-target support directory.
  3095. std::string dir = target->GetSupportDirectory();
  3096. std::string file = cmStrCat(dir, "/Labels.txt");
  3097. std::string json_file = cmStrCat(dir, "/Labels.json");
  3098. #ifndef CMAKE_BOOTSTRAP
  3099. // Check whether labels are enabled for this target.
  3100. cmValue targetLabels = target->GetProperty("LABELS");
  3101. cmValue directoryLabels =
  3102. target->Target->GetMakefile()->GetProperty("LABELS");
  3103. cmValue cmakeDirectoryLabels =
  3104. target->Target->GetMakefile()->GetDefinition("CMAKE_DIRECTORY_LABELS");
  3105. if (targetLabels || directoryLabels || cmakeDirectoryLabels) {
  3106. Json::Value lj_root(Json::objectValue);
  3107. Json::Value& lj_target = lj_root["target"] = Json::objectValue;
  3108. lj_target["name"] = target->GetName();
  3109. Json::Value& lj_target_labels = lj_target["labels"] = Json::arrayValue;
  3110. Json::Value& lj_sources = lj_root["sources"] = Json::arrayValue;
  3111. cmSystemTools::MakeDirectory(dir);
  3112. cmGeneratedFileStream fout(file);
  3113. cmList labels;
  3114. // List the target-wide labels. All sources in the target get
  3115. // these labels.
  3116. if (targetLabels) {
  3117. labels.assign(*targetLabels);
  3118. if (!labels.empty()) {
  3119. fout << "# Target labels\n";
  3120. for (std::string const& l : labels) {
  3121. fout << " " << l << "\n";
  3122. lj_target_labels.append(l);
  3123. }
  3124. }
  3125. }
  3126. // List directory labels
  3127. cmList directoryLabelsList;
  3128. cmList cmakeDirectoryLabelsList;
  3129. if (directoryLabels) {
  3130. directoryLabelsList.assign(*directoryLabels);
  3131. }
  3132. if (cmakeDirectoryLabels) {
  3133. cmakeDirectoryLabelsList.assign(*cmakeDirectoryLabels);
  3134. }
  3135. if (!directoryLabelsList.empty() || !cmakeDirectoryLabelsList.empty()) {
  3136. fout << "# Directory labels\n";
  3137. }
  3138. for (auto const& li : directoryLabelsList) {
  3139. fout << " " << li << "\n";
  3140. lj_target_labels.append(li);
  3141. }
  3142. for (auto const& li : cmakeDirectoryLabelsList) {
  3143. fout << " " << li << "\n";
  3144. lj_target_labels.append(li);
  3145. }
  3146. // List the source files with any per-source labels.
  3147. fout << "# Source files and their labels\n";
  3148. std::vector<cmSourceFile*> sources;
  3149. std::vector<std::string> const& configs =
  3150. target->Target->GetMakefile()->GetGeneratorConfigs(
  3151. cmMakefile::IncludeEmptyConfig);
  3152. for (std::string const& c : configs) {
  3153. target->GetSourceFiles(sources, c);
  3154. }
  3155. auto const sourcesEnd = cmRemoveDuplicates(sources);
  3156. for (cmSourceFile* sf : cmMakeRange(sources.cbegin(), sourcesEnd)) {
  3157. Json::Value& lj_source = lj_sources.append(Json::objectValue);
  3158. std::string const& sfp = sf->ResolveFullPath();
  3159. fout << sfp << "\n";
  3160. lj_source["file"] = sfp;
  3161. if (cmValue svalue = sf->GetProperty("LABELS")) {
  3162. Json::Value& lj_source_labels = lj_source["labels"] = Json::arrayValue;
  3163. labels.assign(*svalue);
  3164. for (auto const& label : labels) {
  3165. fout << " " << label << "\n";
  3166. lj_source_labels.append(label);
  3167. }
  3168. }
  3169. }
  3170. cmGeneratedFileStream json_fout(json_file);
  3171. json_fout << lj_root;
  3172. } else
  3173. #endif
  3174. {
  3175. cmSystemTools::RemoveFile(file);
  3176. cmSystemTools::RemoveFile(json_file);
  3177. }
  3178. }
  3179. // static
  3180. std::string cmGlobalGenerator::EscapeJSON(const std::string& s)
  3181. {
  3182. std::string result;
  3183. result.reserve(s.size());
  3184. for (char i : s) {
  3185. switch (i) {
  3186. case '"':
  3187. case '\\':
  3188. result += '\\';
  3189. result += i;
  3190. break;
  3191. case '\n':
  3192. result += "\\n";
  3193. break;
  3194. case '\t':
  3195. result += "\\t";
  3196. break;
  3197. default:
  3198. result += i;
  3199. }
  3200. }
  3201. return result;
  3202. }
  3203. void cmGlobalGenerator::SetFilenameTargetDepends(
  3204. cmSourceFile* sf, std::set<cmGeneratorTarget const*> const& tgts)
  3205. {
  3206. this->FilenameTargetDepends[sf] = tgts;
  3207. }
  3208. std::set<cmGeneratorTarget const*> const&
  3209. cmGlobalGenerator::GetFilenameTargetDepends(cmSourceFile* sf) const
  3210. {
  3211. return this->FilenameTargetDepends[sf];
  3212. }
  3213. const std::string& cmGlobalGenerator::GetRealPath(const std::string& dir)
  3214. {
  3215. auto i = this->RealPaths.lower_bound(dir);
  3216. if (i == this->RealPaths.end() ||
  3217. this->RealPaths.key_comp()(dir, i->first)) {
  3218. i = this->RealPaths.emplace_hint(i, dir, cmSystemTools::GetRealPath(dir));
  3219. }
  3220. return i->second;
  3221. }
  3222. std::string cmGlobalGenerator::NewDeferId()
  3223. {
  3224. return cmStrCat("__"_s, std::to_string(this->NextDeferId++));
  3225. }
  3226. void cmGlobalGenerator::ProcessEvaluationFiles()
  3227. {
  3228. std::vector<std::string> generatedFiles;
  3229. for (auto& localGen : this->LocalGenerators) {
  3230. localGen->ProcessEvaluationFiles(generatedFiles);
  3231. }
  3232. }
  3233. std::string cmGlobalGenerator::ExpandCFGIntDir(
  3234. const std::string& str, const std::string& /*config*/) const
  3235. {
  3236. return str;
  3237. }
  3238. bool cmGlobalGenerator::GenerateCPackPropertiesFile()
  3239. {
  3240. cmake::InstalledFilesMap const& installedFiles =
  3241. this->CMakeInstance->GetInstalledFiles();
  3242. const auto& lg = this->LocalGenerators[0];
  3243. cmMakefile* mf = lg->GetMakefile();
  3244. std::vector<std::string> configs =
  3245. mf->GetGeneratorConfigs(cmMakefile::OnlyMultiConfig);
  3246. std::string config = mf->GetDefaultConfiguration();
  3247. std::string path = cmStrCat(this->CMakeInstance->GetHomeOutputDirectory(),
  3248. "/CPackProperties.cmake");
  3249. if (!cmSystemTools::FileExists(path) && installedFiles.empty()) {
  3250. return true;
  3251. }
  3252. cmGeneratedFileStream file(path);
  3253. file << "# CPack properties\n";
  3254. for (auto const& i : installedFiles) {
  3255. cmInstalledFile const& installedFile = i.second;
  3256. cmCPackPropertiesGenerator cpackPropertiesGenerator(
  3257. lg.get(), installedFile, configs);
  3258. cpackPropertiesGenerator.Generate(file, config, configs);
  3259. }
  3260. return true;
  3261. }
  3262. cmInstallRuntimeDependencySet*
  3263. cmGlobalGenerator::CreateAnonymousRuntimeDependencySet()
  3264. {
  3265. auto set = cm::make_unique<cmInstallRuntimeDependencySet>();
  3266. auto* retval = set.get();
  3267. this->RuntimeDependencySets.push_back(std::move(set));
  3268. return retval;
  3269. }
  3270. cmInstallRuntimeDependencySet* cmGlobalGenerator::GetNamedRuntimeDependencySet(
  3271. const std::string& name)
  3272. {
  3273. auto it = this->RuntimeDependencySetsByName.find(name);
  3274. if (it == this->RuntimeDependencySetsByName.end()) {
  3275. auto set = cm::make_unique<cmInstallRuntimeDependencySet>(name);
  3276. it =
  3277. this->RuntimeDependencySetsByName.insert(std::make_pair(name, set.get()))
  3278. .first;
  3279. this->RuntimeDependencySets.push_back(std::move(set));
  3280. }
  3281. return it->second;
  3282. }
  3283. cmGlobalGenerator::StripCommandStyle cmGlobalGenerator::GetStripCommandStyle(
  3284. std::string const& strip)
  3285. {
  3286. #ifdef __APPLE__
  3287. auto i = this->StripCommandStyleMap.find(strip);
  3288. if (i == this->StripCommandStyleMap.end()) {
  3289. StripCommandStyle style = StripCommandStyle::Default;
  3290. // Try running strip tool with Apple-specific options.
  3291. std::vector<std::string> cmd{ strip, "-u", "-r" };
  3292. std::string out;
  3293. std::string err;
  3294. int ret;
  3295. if (cmSystemTools::RunSingleCommand(cmd, &out, &err, &ret, nullptr,
  3296. cmSystemTools::OUTPUT_NONE) &&
  3297. // Check for Apple-specific output.
  3298. ret != 0 && cmHasLiteralPrefix(err, "fatal error: /") &&
  3299. err.find("/usr/bin/strip: no files specified") != std::string::npos) {
  3300. style = StripCommandStyle::Apple;
  3301. }
  3302. i = this->StripCommandStyleMap.emplace(strip, style).first;
  3303. }
  3304. return i->second;
  3305. #else
  3306. static_cast<void>(strip);
  3307. return StripCommandStyle::Default;
  3308. #endif
  3309. }