cmGlobalGenerator.cxx 102 KB

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