cmGlobalGenerator.cxx 119 KB

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