cmGlobalGenerator.cxx 117 KB

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