cmGlobalGenerator.cxx 105 KB

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