cmake.cxx 123 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709
  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 "cmake.h"
  4. #include <algorithm>
  5. #include <cstdio>
  6. #include <cstdlib>
  7. #include <cstring>
  8. #include <initializer_list>
  9. #include <iostream>
  10. #include <sstream>
  11. #include <stdexcept>
  12. #include <utility>
  13. #include <cm/memory>
  14. #include <cm/optional>
  15. #include <cm/string_view>
  16. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(CMAKE_BOOT_MINGW)
  17. # include <cm/iterator>
  18. #endif
  19. #include <cmext/algorithm>
  20. #include <cmext/string_view>
  21. #include "cmsys/FStream.hxx"
  22. #include "cmsys/Glob.hxx"
  23. #include "cmsys/RegularExpression.hxx"
  24. #include "cm_sys_stat.h"
  25. #include "cmBuildOptions.h"
  26. #include "cmCMakePath.h"
  27. #include "cmCMakePresetsGraph.h"
  28. #include "cmCommandLineArgument.h"
  29. #include "cmCommands.h"
  30. #include "cmDocumentation.h"
  31. #include "cmDocumentationEntry.h"
  32. #include "cmDocumentationFormatter.h"
  33. #include "cmDuration.h"
  34. #include "cmExternalMakefileProjectGenerator.h"
  35. #include "cmFileTimeCache.h"
  36. #include "cmGeneratorTarget.h"
  37. #include "cmGlobalGenerator.h"
  38. #include "cmGlobalGeneratorFactory.h"
  39. #include "cmLinkLineComputer.h"
  40. #include "cmLocalGenerator.h"
  41. #include "cmMakefile.h"
  42. #if !defined(CMAKE_BOOTSTRAP)
  43. # include "cmMakefileProfilingData.h"
  44. #endif
  45. #include "cmMessenger.h"
  46. #include "cmState.h"
  47. #include "cmStateDirectory.h"
  48. #include "cmStringAlgorithms.h"
  49. #include "cmSystemTools.h"
  50. #include "cmTarget.h"
  51. #include "cmTargetLinkLibraryType.h"
  52. #include "cmUtils.hxx"
  53. #include "cmVersionConfig.h"
  54. #include "cmWorkingDirectory.h"
  55. #if !defined(CMAKE_BOOTSTRAP)
  56. # include <unordered_map>
  57. # include <cm3p/json/writer.h>
  58. # include "cmFileAPI.h"
  59. # include "cmGraphVizWriter.h"
  60. # include "cmVariableWatch.h"
  61. #endif
  62. #if defined(__MINGW32__) && defined(CMAKE_BOOTSTRAP)
  63. # define CMAKE_BOOT_MINGW
  64. #endif
  65. // include the generator
  66. #if defined(_WIN32) && !defined(__CYGWIN__)
  67. # if !defined(CMAKE_BOOT_MINGW)
  68. # include <cmext/memory>
  69. # include "cmGlobalBorlandMakefileGenerator.h"
  70. # include "cmGlobalJOMMakefileGenerator.h"
  71. # include "cmGlobalNMakeMakefileGenerator.h"
  72. # include "cmGlobalVisualStudio10Generator.h"
  73. # include "cmGlobalVisualStudio11Generator.h"
  74. # include "cmGlobalVisualStudio12Generator.h"
  75. # include "cmGlobalVisualStudio14Generator.h"
  76. # include "cmGlobalVisualStudio9Generator.h"
  77. # include "cmGlobalVisualStudioVersionedGenerator.h"
  78. # include "cmVSSetupHelper.h"
  79. # define CMAKE_HAVE_VS_GENERATORS
  80. # endif
  81. # include "cmGlobalMSYSMakefileGenerator.h"
  82. # include "cmGlobalMinGWMakefileGenerator.h"
  83. #else
  84. #endif
  85. #if defined(CMAKE_USE_WMAKE)
  86. # include "cmGlobalWatcomWMakeGenerator.h"
  87. #endif
  88. #if !defined(CMAKE_BOOTSTRAP)
  89. # include "cmGlobalNinjaGenerator.h"
  90. # include "cmGlobalUnixMakefileGenerator3.h"
  91. #elif defined(CMAKE_BOOTSTRAP_MAKEFILES)
  92. # include "cmGlobalUnixMakefileGenerator3.h"
  93. #elif defined(CMAKE_BOOTSTRAP_NINJA)
  94. # include "cmGlobalNinjaGenerator.h"
  95. #endif
  96. #if !defined(CMAKE_BOOTSTRAP)
  97. # include "cmExtraCodeBlocksGenerator.h"
  98. # include "cmExtraCodeLiteGenerator.h"
  99. # include "cmExtraEclipseCDT4Generator.h"
  100. # include "cmExtraKateGenerator.h"
  101. # include "cmExtraSublimeTextGenerator.h"
  102. #endif
  103. // NOTE: the __linux__ macro is predefined on Android host too, but
  104. // main CMakeLists.txt filters out this generator by host name.
  105. #if (defined(__linux__) && !defined(__ANDROID__)) || defined(_WIN32)
  106. # include "cmGlobalGhsMultiGenerator.h"
  107. #endif
  108. #if defined(__APPLE__)
  109. # if !defined(CMAKE_BOOTSTRAP)
  110. # include "cmGlobalXCodeGenerator.h"
  111. # define CMAKE_USE_XCODE 1
  112. # endif
  113. # include <sys/resource.h>
  114. # include <sys/time.h>
  115. #endif
  116. namespace {
  117. #if !defined(CMAKE_BOOTSTRAP)
  118. using JsonValueMapType = std::unordered_map<std::string, Json::Value>;
  119. #endif
  120. auto IgnoreAndTrueLambda = [](std::string const&, cmake*) -> bool {
  121. return true;
  122. };
  123. using CommandArgument =
  124. cmCommandLineArgument<bool(std::string const& value, cmake* state)>;
  125. } // namespace
  126. static bool cmakeCheckStampFile(const std::string& stampName);
  127. static bool cmakeCheckStampList(const std::string& stampList);
  128. #ifndef CMAKE_BOOTSTRAP
  129. static void cmWarnUnusedCliWarning(const std::string& variable, int /*unused*/,
  130. void* ctx, const char* /*unused*/,
  131. const cmMakefile* /*unused*/)
  132. {
  133. cmake* cm = reinterpret_cast<cmake*>(ctx);
  134. cm->MarkCliAsUsed(variable);
  135. }
  136. #endif
  137. cmake::cmake(Role role, cmState::Mode mode, cmState::ProjectKind projectKind)
  138. : CMakeWorkingDirectory(cmSystemTools::GetCurrentWorkingDirectory())
  139. , FileTimeCache(cm::make_unique<cmFileTimeCache>())
  140. #ifndef CMAKE_BOOTSTRAP
  141. , VariableWatch(cm::make_unique<cmVariableWatch>())
  142. #endif
  143. , State(cm::make_unique<cmState>(mode, projectKind))
  144. , Messenger(cm::make_unique<cmMessenger>())
  145. {
  146. this->TraceFile.close();
  147. this->CurrentSnapshot = this->State->CreateBaseSnapshot();
  148. #ifdef __APPLE__
  149. struct rlimit rlp;
  150. if (!getrlimit(RLIMIT_STACK, &rlp)) {
  151. if (rlp.rlim_cur != rlp.rlim_max) {
  152. rlp.rlim_cur = rlp.rlim_max;
  153. setrlimit(RLIMIT_STACK, &rlp);
  154. }
  155. }
  156. #endif
  157. this->AddDefaultGenerators();
  158. this->AddDefaultExtraGenerators();
  159. if (role == RoleScript || role == RoleProject) {
  160. this->AddScriptingCommands();
  161. }
  162. if (role == RoleProject) {
  163. this->AddProjectCommands();
  164. }
  165. if (mode == cmState::Project) {
  166. this->LoadEnvironmentPresets();
  167. }
  168. // Make sure we can capture the build tool output.
  169. cmSystemTools::EnableVSConsoleOutput();
  170. // Set up a list of source and header extensions.
  171. // These are used to find files when the extension is not given.
  172. {
  173. auto setupExts = [](FileExtensions& exts,
  174. std::initializer_list<cm::string_view> extList) {
  175. // Fill ordered vector
  176. exts.ordered.reserve(extList.size());
  177. for (cm::string_view ext : extList) {
  178. exts.ordered.emplace_back(ext);
  179. }
  180. // Fill unordered set
  181. exts.unordered.insert(exts.ordered.begin(), exts.ordered.end());
  182. };
  183. // The "c" extension MUST precede the "C" extension.
  184. setupExts(this->CLikeSourceFileExtensions,
  185. { "c", "C", "c++", "cc", "cpp", "cxx", "cu", "mpp", "m", "M",
  186. "mm", "ixx", "cppm" });
  187. setupExts(this->HeaderFileExtensions,
  188. { "h", "hh", "h++", "hm", "hpp", "hxx", "in", "txx" });
  189. setupExts(this->CudaFileExtensions, { "cu" });
  190. setupExts(this->FortranFileExtensions,
  191. { "f", "F", "for", "f77", "f90", "f95", "f03" });
  192. setupExts(this->HipFileExtensions, { "hip" });
  193. setupExts(this->ISPCFileExtensions, { "ispc" });
  194. }
  195. }
  196. cmake::~cmake() = default;
  197. #if !defined(CMAKE_BOOTSTRAP)
  198. Json::Value cmake::ReportVersionJson() const
  199. {
  200. Json::Value version = Json::objectValue;
  201. version["string"] = CMake_VERSION;
  202. version["major"] = CMake_VERSION_MAJOR;
  203. version["minor"] = CMake_VERSION_MINOR;
  204. version["suffix"] = CMake_VERSION_SUFFIX;
  205. version["isDirty"] = (CMake_VERSION_IS_DIRTY == 1);
  206. version["patch"] = CMake_VERSION_PATCH;
  207. return version;
  208. }
  209. Json::Value cmake::ReportCapabilitiesJson() const
  210. {
  211. Json::Value obj = Json::objectValue;
  212. // Version information:
  213. obj["version"] = this->ReportVersionJson();
  214. // Generators:
  215. std::vector<cmake::GeneratorInfo> generatorInfoList;
  216. this->GetRegisteredGenerators(generatorInfoList);
  217. JsonValueMapType generatorMap;
  218. for (cmake::GeneratorInfo const& gi : generatorInfoList) {
  219. if (gi.isAlias) { // skip aliases, they are there for compatibility reasons
  220. // only
  221. continue;
  222. }
  223. if (gi.extraName.empty()) {
  224. Json::Value gen = Json::objectValue;
  225. gen["name"] = gi.name;
  226. gen["toolsetSupport"] = gi.supportsToolset;
  227. gen["platformSupport"] = gi.supportsPlatform;
  228. if (!gi.supportedPlatforms.empty()) {
  229. Json::Value supportedPlatforms = Json::arrayValue;
  230. for (std::string const& platform : gi.supportedPlatforms) {
  231. supportedPlatforms.append(platform);
  232. }
  233. gen["supportedPlatforms"] = std::move(supportedPlatforms);
  234. }
  235. gen["extraGenerators"] = Json::arrayValue;
  236. generatorMap[gi.name] = gen;
  237. } else {
  238. Json::Value& gen = generatorMap[gi.baseName];
  239. gen["extraGenerators"].append(gi.extraName);
  240. }
  241. }
  242. Json::Value generators = Json::arrayValue;
  243. for (auto const& i : generatorMap) {
  244. generators.append(i.second);
  245. }
  246. obj["generators"] = generators;
  247. obj["fileApi"] = cmFileAPI::ReportCapabilities();
  248. obj["serverMode"] = false;
  249. return obj;
  250. }
  251. #endif
  252. std::string cmake::ReportCapabilities() const
  253. {
  254. std::string result;
  255. #if !defined(CMAKE_BOOTSTRAP)
  256. Json::FastWriter writer;
  257. result = writer.write(this->ReportCapabilitiesJson());
  258. #else
  259. result = "Not supported";
  260. #endif
  261. return result;
  262. }
  263. void cmake::CleanupCommandsAndMacros()
  264. {
  265. this->CurrentSnapshot = this->State->Reset();
  266. this->State->RemoveUserDefinedCommands();
  267. this->CurrentSnapshot.SetDefaultDefinitions();
  268. // FIXME: InstalledFiles probably belongs in the global generator.
  269. this->InstalledFiles.clear();
  270. }
  271. #ifndef CMAKE_BOOTSTRAP
  272. void cmake::SetWarningFromPreset(const std::string& name,
  273. const cm::optional<bool>& warning,
  274. const cm::optional<bool>& error)
  275. {
  276. if (warning) {
  277. if (*warning) {
  278. this->DiagLevels[name] = std::max(this->DiagLevels[name], DIAG_WARN);
  279. } else {
  280. this->DiagLevels[name] = DIAG_IGNORE;
  281. }
  282. }
  283. if (error) {
  284. if (*error) {
  285. this->DiagLevels[name] = DIAG_ERROR;
  286. } else {
  287. this->DiagLevels[name] = std::min(this->DiagLevels[name], DIAG_WARN);
  288. }
  289. }
  290. }
  291. void cmake::ProcessPresetVariables()
  292. {
  293. for (auto const& var : this->UnprocessedPresetVariables) {
  294. if (!var.second) {
  295. continue;
  296. }
  297. cmStateEnums::CacheEntryType type = cmStateEnums::UNINITIALIZED;
  298. if (!var.second->Type.empty()) {
  299. type = cmState::StringToCacheEntryType(var.second->Type);
  300. }
  301. this->ProcessCacheArg(var.first, var.second->Value, type);
  302. }
  303. }
  304. void cmake::PrintPresetVariables()
  305. {
  306. bool first = true;
  307. for (auto const& var : this->UnprocessedPresetVariables) {
  308. if (!var.second) {
  309. continue;
  310. }
  311. cmStateEnums::CacheEntryType type = cmStateEnums::UNINITIALIZED;
  312. if (!var.second->Type.empty()) {
  313. type = cmState::StringToCacheEntryType(var.second->Type);
  314. }
  315. if (first) {
  316. std::cout << "Preset CMake variables:\n\n";
  317. first = false;
  318. }
  319. std::cout << " " << var.first;
  320. if (type != cmStateEnums::UNINITIALIZED) {
  321. std::cout << ':' << cmState::CacheEntryTypeToString(type);
  322. }
  323. std::cout << "=\"" << var.second->Value << "\"\n";
  324. }
  325. if (!first) {
  326. std::cout << '\n';
  327. }
  328. this->UnprocessedPresetVariables.clear();
  329. }
  330. void cmake::ProcessPresetEnvironment()
  331. {
  332. for (auto const& var : this->UnprocessedPresetEnvironment) {
  333. if (var.second) {
  334. cmSystemTools::PutEnv(cmStrCat(var.first, '=', *var.second));
  335. }
  336. }
  337. }
  338. void cmake::PrintPresetEnvironment()
  339. {
  340. bool first = true;
  341. for (auto const& var : this->UnprocessedPresetEnvironment) {
  342. if (!var.second) {
  343. continue;
  344. }
  345. if (first) {
  346. std::cout << "Preset environment variables:\n\n";
  347. first = false;
  348. }
  349. std::cout << " " << var.first << "=\"" << *var.second << "\"\n";
  350. }
  351. if (!first) {
  352. std::cout << '\n';
  353. }
  354. this->UnprocessedPresetEnvironment.clear();
  355. }
  356. #endif
  357. // Parse the args
  358. bool cmake::SetCacheArgs(const std::vector<std::string>& args)
  359. {
  360. auto findPackageMode = false;
  361. auto seenScriptOption = false;
  362. auto DefineLambda = [](std::string const& entry, cmake* state) -> bool {
  363. std::string var;
  364. std::string value;
  365. cmStateEnums::CacheEntryType type = cmStateEnums::UNINITIALIZED;
  366. if (cmState::ParseCacheEntry(entry, var, value, type)) {
  367. #ifndef CMAKE_BOOTSTRAP
  368. state->UnprocessedPresetVariables.erase(var);
  369. #endif
  370. state->ProcessCacheArg(var, value, type);
  371. } else {
  372. cmSystemTools::Error(cmStrCat("Parse error in command line argument: ",
  373. entry, "\n Should be: VAR:type=value\n"));
  374. return false;
  375. }
  376. return true;
  377. };
  378. auto WarningLambda = [](cm::string_view entry, cmake* state) -> bool {
  379. bool foundNo = false;
  380. bool foundError = false;
  381. if (cmHasLiteralPrefix(entry, "no-")) {
  382. foundNo = true;
  383. entry.remove_prefix(3);
  384. }
  385. if (cmHasLiteralPrefix(entry, "error=")) {
  386. foundError = true;
  387. entry.remove_prefix(6);
  388. }
  389. if (entry.empty()) {
  390. cmSystemTools::Error("No warning name provided.");
  391. return false;
  392. }
  393. std::string const name = std::string(entry);
  394. if (!foundNo && !foundError) {
  395. // -W<name>
  396. state->DiagLevels[name] = std::max(state->DiagLevels[name], DIAG_WARN);
  397. } else if (foundNo && !foundError) {
  398. // -Wno<name>
  399. state->DiagLevels[name] = DIAG_IGNORE;
  400. } else if (!foundNo && foundError) {
  401. // -Werror=<name>
  402. state->DiagLevels[name] = DIAG_ERROR;
  403. } else {
  404. // -Wno-error=<name>
  405. // This can downgrade an error to a warning, but should not enable
  406. // or disable a warning in the first place.
  407. auto dli = state->DiagLevels.find(name);
  408. if (dli != state->DiagLevels.end()) {
  409. dli->second = std::min(dli->second, DIAG_WARN);
  410. }
  411. }
  412. return true;
  413. };
  414. auto UnSetLambda = [](std::string const& entryPattern,
  415. cmake* state) -> bool {
  416. cmsys::RegularExpression regex(
  417. cmsys::Glob::PatternToRegex(entryPattern, true, true));
  418. // go through all cache entries and collect the vars which will be
  419. // removed
  420. std::vector<std::string> entriesToDelete;
  421. std::vector<std::string> cacheKeys = state->State->GetCacheEntryKeys();
  422. for (std::string const& ck : cacheKeys) {
  423. cmStateEnums::CacheEntryType t = state->State->GetCacheEntryType(ck);
  424. if (t != cmStateEnums::STATIC) {
  425. if (regex.find(ck)) {
  426. entriesToDelete.push_back(ck);
  427. }
  428. }
  429. }
  430. // now remove them from the cache
  431. for (std::string const& currentEntry : entriesToDelete) {
  432. #ifndef CMAKE_BOOTSTRAP
  433. state->UnprocessedPresetVariables.erase(currentEntry);
  434. #endif
  435. state->State->RemoveCacheEntry(currentEntry);
  436. }
  437. return true;
  438. };
  439. auto ScriptLambda = [&](std::string const& path, cmake* state) -> bool {
  440. // Register fake project commands that hint misuse in script mode.
  441. GetProjectCommandsInScriptMode(state->GetState());
  442. // Documented behavior of CMAKE{,_CURRENT}_{SOURCE,BINARY}_DIR is to be
  443. // set to $PWD for -P mode.
  444. state->SetHomeDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  445. state->SetHomeOutputDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  446. state->ReadListFile(args, path);
  447. seenScriptOption = true;
  448. return true;
  449. };
  450. auto PrefixLambda = [&](std::string const& path, cmake* state) -> bool {
  451. const std::string var = "CMAKE_INSTALL_PREFIX";
  452. cmStateEnums::CacheEntryType type = cmStateEnums::PATH;
  453. cmCMakePath absolutePath(path);
  454. if (absolutePath.IsAbsolute()) {
  455. #ifndef CMAKE_BOOTSTRAP
  456. state->UnprocessedPresetVariables.erase(var);
  457. #endif
  458. state->ProcessCacheArg(var, path, type);
  459. return true;
  460. }
  461. cmSystemTools::Error("Absolute paths are required for --install-prefix");
  462. return false;
  463. };
  464. auto ToolchainLambda = [&](std::string const& path, cmake* state) -> bool {
  465. const std::string var = "CMAKE_TOOLCHAIN_FILE";
  466. cmStateEnums::CacheEntryType type = cmStateEnums::FILEPATH;
  467. #ifndef CMAKE_BOOTSTRAP
  468. state->UnprocessedPresetVariables.erase(var);
  469. #endif
  470. state->ProcessCacheArg(var, path, type);
  471. return true;
  472. };
  473. std::vector<CommandArgument> arguments = {
  474. CommandArgument{ "-D", "-D must be followed with VAR=VALUE.",
  475. CommandArgument::Values::One,
  476. CommandArgument::RequiresSeparator::No, DefineLambda },
  477. CommandArgument{ "-W", "-W must be followed with [no-]<name>.",
  478. CommandArgument::Values::One,
  479. CommandArgument::RequiresSeparator::No, WarningLambda },
  480. CommandArgument{ "-U", "-U must be followed with VAR.",
  481. CommandArgument::Values::One,
  482. CommandArgument::RequiresSeparator::No, UnSetLambda },
  483. CommandArgument{
  484. "-C", "-C must be followed by a file name.",
  485. CommandArgument::Values::One, CommandArgument::RequiresSeparator::No,
  486. [&](std::string const& value, cmake* state) -> bool {
  487. cmSystemTools::Stdout("loading initial cache file " + value + "\n");
  488. // Resolve script path specified on command line
  489. // relative to $PWD.
  490. auto path = cmSystemTools::CollapseFullPath(value);
  491. state->ReadListFile(args, path);
  492. return true;
  493. } },
  494. CommandArgument{ "-P", "-P must be followed by a file name.",
  495. CommandArgument::Values::One,
  496. CommandArgument::RequiresSeparator::No, ScriptLambda },
  497. CommandArgument{ "--toolchain", "No file specified for --toolchain",
  498. CommandArgument::Values::One, ToolchainLambda },
  499. CommandArgument{ "--install-prefix",
  500. "No install directory specified for --install-prefix",
  501. CommandArgument::Values::One, PrefixLambda },
  502. CommandArgument{ "--find-package", CommandArgument::Values::Zero,
  503. [&](std::string const&, cmake*) -> bool {
  504. findPackageMode = true;
  505. return true;
  506. } },
  507. };
  508. for (decltype(args.size()) i = 1; i < args.size(); ++i) {
  509. std::string const& arg = args[i];
  510. if (arg == "--" && seenScriptOption) {
  511. // Stop processing CMake args and avoid possible errors
  512. // when arbitrary args are given to CMake script.
  513. break;
  514. }
  515. for (auto const& m : arguments) {
  516. if (m.matches(arg)) {
  517. const bool parsedCorrectly = m.parse(arg, i, args, this);
  518. if (!parsedCorrectly) {
  519. return false;
  520. }
  521. }
  522. }
  523. }
  524. if (findPackageMode) {
  525. return this->FindPackage(args);
  526. }
  527. return true;
  528. }
  529. void cmake::ProcessCacheArg(const std::string& var, const std::string& value,
  530. cmStateEnums::CacheEntryType type)
  531. {
  532. // The value is transformed if it is a filepath for example, so
  533. // we can't compare whether the value is already in the cache until
  534. // after we call AddCacheEntry.
  535. bool haveValue = false;
  536. std::string cachedValue;
  537. if (this->WarnUnusedCli) {
  538. if (cmValue v = this->State->GetInitializedCacheValue(var)) {
  539. haveValue = true;
  540. cachedValue = *v;
  541. }
  542. }
  543. this->AddCacheEntry(
  544. var, value, "No help, variable specified on the command line.", type);
  545. if (this->WarnUnusedCli) {
  546. if (!haveValue ||
  547. cachedValue != *this->State->GetInitializedCacheValue(var)) {
  548. this->WatchUnusedCli(var);
  549. }
  550. }
  551. }
  552. void cmake::ReadListFile(const std::vector<std::string>& args,
  553. const std::string& path)
  554. {
  555. // if a generator was not yet created, temporarily create one
  556. cmGlobalGenerator* gg = this->GetGlobalGenerator();
  557. // if a generator was not specified use a generic one
  558. std::unique_ptr<cmGlobalGenerator> gen;
  559. if (!gg) {
  560. gen = cm::make_unique<cmGlobalGenerator>(this);
  561. gg = gen.get();
  562. }
  563. // read in the list file to fill the cache
  564. if (!path.empty()) {
  565. this->CurrentSnapshot = this->State->Reset();
  566. cmStateSnapshot snapshot = this->GetCurrentSnapshot();
  567. snapshot.GetDirectory().SetCurrentBinary(this->GetHomeOutputDirectory());
  568. snapshot.GetDirectory().SetCurrentSource(this->GetHomeDirectory());
  569. snapshot.SetDefaultDefinitions();
  570. cmMakefile mf(gg, snapshot);
  571. if (this->GetWorkingMode() != NORMAL_MODE) {
  572. std::string file(cmSystemTools::CollapseFullPath(path));
  573. cmSystemTools::ConvertToUnixSlashes(file);
  574. mf.SetScriptModeFile(file);
  575. mf.SetArgcArgv(args);
  576. }
  577. if (!mf.ReadListFile(path)) {
  578. cmSystemTools::Error("Error processing file: " + path);
  579. }
  580. }
  581. }
  582. bool cmake::FindPackage(const std::vector<std::string>& args)
  583. {
  584. this->SetHomeDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  585. this->SetHomeOutputDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  586. this->SetGlobalGenerator(cm::make_unique<cmGlobalGenerator>(this));
  587. cmStateSnapshot snapshot = this->GetCurrentSnapshot();
  588. snapshot.GetDirectory().SetCurrentBinary(
  589. cmSystemTools::GetCurrentWorkingDirectory());
  590. snapshot.GetDirectory().SetCurrentSource(
  591. cmSystemTools::GetCurrentWorkingDirectory());
  592. // read in the list file to fill the cache
  593. snapshot.SetDefaultDefinitions();
  594. auto mfu = cm::make_unique<cmMakefile>(this->GetGlobalGenerator(), snapshot);
  595. cmMakefile* mf = mfu.get();
  596. this->GlobalGenerator->AddMakefile(std::move(mfu));
  597. mf->SetArgcArgv(args);
  598. std::string systemFile = mf->GetModulesFile("CMakeFindPackageMode.cmake");
  599. mf->ReadListFile(systemFile);
  600. std::string language = mf->GetSafeDefinition("LANGUAGE");
  601. std::string mode = mf->GetSafeDefinition("MODE");
  602. std::string packageName = mf->GetSafeDefinition("NAME");
  603. bool packageFound = mf->IsOn("PACKAGE_FOUND");
  604. bool quiet = mf->IsOn("PACKAGE_QUIET");
  605. if (!packageFound) {
  606. if (!quiet) {
  607. printf("%s not found.\n", packageName.c_str());
  608. }
  609. } else if (mode == "EXIST"_s) {
  610. if (!quiet) {
  611. printf("%s found.\n", packageName.c_str());
  612. }
  613. } else if (mode == "COMPILE"_s) {
  614. std::string includes = mf->GetSafeDefinition("PACKAGE_INCLUDE_DIRS");
  615. std::vector<std::string> includeDirs = cmExpandedList(includes);
  616. this->GlobalGenerator->CreateGenerationObjects();
  617. const auto& lg = this->GlobalGenerator->LocalGenerators[0];
  618. std::string includeFlags =
  619. lg->GetIncludeFlags(includeDirs, nullptr, language, std::string());
  620. std::string definitions = mf->GetSafeDefinition("PACKAGE_DEFINITIONS");
  621. printf("%s %s\n", includeFlags.c_str(), definitions.c_str());
  622. } else if (mode == "LINK"_s) {
  623. const char* targetName = "dummy";
  624. std::vector<std::string> srcs;
  625. cmTarget* tgt = mf->AddExecutable(targetName, srcs, true);
  626. tgt->SetProperty("LINKER_LANGUAGE", language);
  627. std::string libs = mf->GetSafeDefinition("PACKAGE_LIBRARIES");
  628. std::vector<std::string> libList = cmExpandedList(libs);
  629. for (std::string const& lib : libList) {
  630. tgt->AddLinkLibrary(*mf, lib, GENERAL_LibraryType);
  631. }
  632. std::string buildType = mf->GetSafeDefinition("CMAKE_BUILD_TYPE");
  633. buildType = cmSystemTools::UpperCase(buildType);
  634. std::string linkLibs;
  635. std::string frameworkPath;
  636. std::string linkPath;
  637. std::string flags;
  638. std::string linkFlags;
  639. this->GlobalGenerator->CreateGenerationObjects();
  640. cmGeneratorTarget* gtgt =
  641. this->GlobalGenerator->FindGeneratorTarget(tgt->GetName());
  642. cmLocalGenerator* lg = gtgt->GetLocalGenerator();
  643. cmLinkLineComputer linkLineComputer(lg,
  644. lg->GetStateSnapshot().GetDirectory());
  645. lg->GetTargetFlags(&linkLineComputer, buildType, linkLibs, flags,
  646. linkFlags, frameworkPath, linkPath, gtgt);
  647. linkLibs = frameworkPath + linkPath + linkLibs;
  648. printf("%s\n", linkLibs.c_str());
  649. /* if ( use_win32 )
  650. {
  651. tgt->SetProperty("WIN32_EXECUTABLE", "ON");
  652. }
  653. if ( use_macbundle)
  654. {
  655. tgt->SetProperty("MACOSX_BUNDLE", "ON");
  656. }*/
  657. }
  658. return packageFound;
  659. }
  660. void cmake::LoadEnvironmentPresets()
  661. {
  662. std::string envGenVar;
  663. bool hasEnvironmentGenerator = false;
  664. if (cmSystemTools::GetEnv("CMAKE_GENERATOR", envGenVar)) {
  665. hasEnvironmentGenerator = true;
  666. this->EnvironmentGenerator = envGenVar;
  667. }
  668. auto readGeneratorVar = [&](std::string const& name, std::string& key) {
  669. std::string varValue;
  670. if (cmSystemTools::GetEnv(name, varValue)) {
  671. if (hasEnvironmentGenerator) {
  672. key = varValue;
  673. } else if (!this->GetIsInTryCompile()) {
  674. std::string message =
  675. cmStrCat("Warning: Environment variable ", name,
  676. " will be ignored, because CMAKE_GENERATOR is not set.");
  677. cmSystemTools::Message(message, "Warning");
  678. }
  679. }
  680. };
  681. readGeneratorVar("CMAKE_GENERATOR_INSTANCE", this->GeneratorInstance);
  682. readGeneratorVar("CMAKE_GENERATOR_PLATFORM", this->GeneratorPlatform);
  683. readGeneratorVar("CMAKE_GENERATOR_TOOLSET", this->GeneratorToolset);
  684. }
  685. namespace {
  686. enum class ListPresets
  687. {
  688. None,
  689. Configure,
  690. Build,
  691. Test,
  692. All,
  693. };
  694. }
  695. // Parse the args
  696. void cmake::SetArgs(const std::vector<std::string>& args)
  697. {
  698. bool haveToolset = false;
  699. bool havePlatform = false;
  700. bool haveBArg = false;
  701. bool scriptMode = false;
  702. std::string possibleUnknownArg;
  703. std::string extraProvidedPath;
  704. #if !defined(CMAKE_BOOTSTRAP)
  705. std::string profilingFormat;
  706. std::string profilingOutput;
  707. std::string presetName;
  708. ListPresets listPresets = ListPresets::None;
  709. #endif
  710. auto SourceArgLambda = [](std::string const& value, cmake* state) -> bool {
  711. std::string path = cmSystemTools::CollapseFullPath(value);
  712. cmSystemTools::ConvertToUnixSlashes(path);
  713. state->SetHomeDirectory(path);
  714. return true;
  715. };
  716. auto BuildArgLambda = [&](std::string const& value, cmake* state) -> bool {
  717. std::string path = cmSystemTools::CollapseFullPath(value);
  718. cmSystemTools::ConvertToUnixSlashes(path);
  719. state->SetHomeOutputDirectory(path);
  720. haveBArg = true;
  721. return true;
  722. };
  723. auto PlatformLambda = [&](std::string const& value, cmake* state) -> bool {
  724. if (havePlatform) {
  725. cmSystemTools::Error("Multiple -A options not allowed");
  726. return false;
  727. }
  728. state->SetGeneratorPlatform(value);
  729. havePlatform = true;
  730. return true;
  731. };
  732. auto ToolsetLamda = [&](std::string const& value, cmake* state) -> bool {
  733. if (haveToolset) {
  734. cmSystemTools::Error("Multiple -T options not allowed");
  735. return false;
  736. }
  737. state->SetGeneratorToolset(value);
  738. haveToolset = true;
  739. return true;
  740. };
  741. std::vector<CommandArgument> arguments = {
  742. CommandArgument{ "-S", "No source directory specified for -S",
  743. CommandArgument::Values::One,
  744. CommandArgument::RequiresSeparator::No, SourceArgLambda },
  745. CommandArgument{ "-H", "No source directory specified for -H",
  746. CommandArgument::Values::One,
  747. CommandArgument::RequiresSeparator::No, SourceArgLambda },
  748. CommandArgument{ "-O", CommandArgument::Values::Zero,
  749. IgnoreAndTrueLambda },
  750. CommandArgument{ "-B", "No build directory specified for -B",
  751. CommandArgument::Values::One,
  752. CommandArgument::RequiresSeparator::No, BuildArgLambda },
  753. CommandArgument{ "-P", "-P must be followed by a file name.",
  754. CommandArgument::Values::One,
  755. CommandArgument::RequiresSeparator::No,
  756. [&](std::string const&, cmake*) -> bool {
  757. scriptMode = true;
  758. return true;
  759. } },
  760. CommandArgument{ "-D", "-D must be followed with VAR=VALUE.",
  761. CommandArgument::Values::One,
  762. CommandArgument::RequiresSeparator::No,
  763. IgnoreAndTrueLambda },
  764. CommandArgument{ "-C", "-C must be followed by a file name.",
  765. CommandArgument::Values::One,
  766. CommandArgument::RequiresSeparator::No,
  767. IgnoreAndTrueLambda },
  768. CommandArgument{
  769. "-U", "-U must be followed with VAR.", CommandArgument::Values::One,
  770. CommandArgument::RequiresSeparator::No, IgnoreAndTrueLambda },
  771. CommandArgument{ "-W", "-W must be followed with [no-]<name>.",
  772. CommandArgument::Values::One,
  773. CommandArgument::RequiresSeparator::No,
  774. IgnoreAndTrueLambda },
  775. CommandArgument{ "-A", "No platform specified for -A",
  776. CommandArgument::Values::One,
  777. CommandArgument::RequiresSeparator::No, PlatformLambda },
  778. CommandArgument{ "-T", "No toolset specified for -T",
  779. CommandArgument::Values::One,
  780. CommandArgument::RequiresSeparator::No, ToolsetLamda },
  781. CommandArgument{ "--toolchain", "No file specified for --toolchain",
  782. CommandArgument::Values::One, IgnoreAndTrueLambda },
  783. CommandArgument{ "--install-prefix",
  784. "No install directory specified for --install-prefix",
  785. CommandArgument::Values::One, IgnoreAndTrueLambda },
  786. CommandArgument{ "--check-build-system", CommandArgument::Values::Two,
  787. [](std::string const& value, cmake* state) -> bool {
  788. std::vector<std::string> values = cmExpandedList(value);
  789. state->CheckBuildSystemArgument = values[0];
  790. state->ClearBuildSystem = (atoi(values[1].c_str()) > 0);
  791. return true;
  792. } },
  793. CommandArgument{ "--check-stamp-file", CommandArgument::Values::One,
  794. [](std::string const& value, cmake* state) -> bool {
  795. state->CheckStampFile = value;
  796. return true;
  797. } },
  798. CommandArgument{ "--check-stamp-list", CommandArgument::Values::One,
  799. [](std::string const& value, cmake* state) -> bool {
  800. state->CheckStampList = value;
  801. return true;
  802. } },
  803. CommandArgument{ "--regenerate-during-build",
  804. CommandArgument::Values::Zero,
  805. [](std::string const&, cmake* state) -> bool {
  806. state->RegenerateDuringBuild = true;
  807. return true;
  808. } },
  809. CommandArgument{ "--find-package", CommandArgument::Values::Zero,
  810. IgnoreAndTrueLambda },
  811. CommandArgument{ "--graphviz", "No file specified for --graphviz",
  812. CommandArgument::Values::One,
  813. [](std::string const& value, cmake* state) -> bool {
  814. std::string path =
  815. cmSystemTools::CollapseFullPath(value);
  816. cmSystemTools::ConvertToUnixSlashes(path);
  817. state->GraphVizFile = path;
  818. return true;
  819. } },
  820. CommandArgument{ "--debug-trycompile", CommandArgument::Values::Zero,
  821. [](std::string const&, cmake* state) -> bool {
  822. std::cout << "debug trycompile on\n";
  823. state->DebugTryCompileOn();
  824. return true;
  825. } },
  826. CommandArgument{ "--debug-output", CommandArgument::Values::Zero,
  827. [](std::string const&, cmake* state) -> bool {
  828. std::cout << "Running with debug output on.\n";
  829. state->SetDebugOutputOn(true);
  830. return true;
  831. } },
  832. CommandArgument{ "--log-level", "Invalid level specified for --log-level",
  833. CommandArgument::Values::One,
  834. [](std::string const& value, cmake* state) -> bool {
  835. const auto logLevel = StringToLogLevel(value);
  836. if (logLevel == LogLevel::LOG_UNDEFINED) {
  837. cmSystemTools::Error(
  838. "Invalid level specified for --log-level");
  839. return false;
  840. }
  841. state->SetLogLevel(logLevel);
  842. state->LogLevelWasSetViaCLI = true;
  843. return true;
  844. } },
  845. // This is supported for backward compatibility. This option only
  846. // appeared in the 3.15.x release series and was renamed to
  847. // --log-level in 3.16.0
  848. CommandArgument{ "--loglevel", "Invalid level specified for --loglevel",
  849. CommandArgument::Values::One,
  850. [](std::string const& value, cmake* state) -> bool {
  851. const auto logLevel = StringToLogLevel(value);
  852. if (logLevel == LogLevel::LOG_UNDEFINED) {
  853. cmSystemTools::Error(
  854. "Invalid level specified for --loglevel");
  855. return false;
  856. }
  857. state->SetLogLevel(logLevel);
  858. state->LogLevelWasSetViaCLI = true;
  859. return true;
  860. } },
  861. CommandArgument{ "--log-context", CommandArgument::Values::Zero,
  862. [](std::string const&, cmake* state) -> bool {
  863. state->SetShowLogContext(true);
  864. return true;
  865. } },
  866. CommandArgument{
  867. "--debug-find", CommandArgument::Values::Zero,
  868. [](std::string const&, cmake* state) -> bool {
  869. std::cout << "Running with debug output on for the `find` commands.\n";
  870. state->SetDebugFindOutput(true);
  871. return true;
  872. } },
  873. CommandArgument{
  874. "--debug-find-pkg", "Provide a package argument for --debug-find-pkg",
  875. CommandArgument::Values::One, CommandArgument::RequiresSeparator::Yes,
  876. [](std::string const& value, cmake* state) -> bool {
  877. std::vector<std::string> find_pkgs(cmTokenize(value, ","));
  878. std::cout << "Running with debug output on for the 'find' commands "
  879. "for package(s)";
  880. for (auto const& v : find_pkgs) {
  881. std::cout << " " << v;
  882. state->SetDebugFindOutputPkgs(v);
  883. }
  884. std::cout << ".\n";
  885. return true;
  886. } },
  887. CommandArgument{
  888. "--debug-find-var", CommandArgument::Values::One,
  889. CommandArgument::RequiresSeparator::Yes,
  890. [](std::string const& value, cmake* state) -> bool {
  891. std::vector<std::string> find_vars(cmTokenize(value, ","));
  892. std::cout << "Running with debug output on for the variable(s)";
  893. for (auto const& v : find_vars) {
  894. std::cout << " " << v;
  895. state->SetDebugFindOutputVars(v);
  896. }
  897. std::cout << ".\n";
  898. return true;
  899. } },
  900. CommandArgument{ "--trace-expand", CommandArgument::Values::Zero,
  901. [](std::string const&, cmake* state) -> bool {
  902. std::cout << "Running with expanded trace output on.\n";
  903. state->SetTrace(true);
  904. state->SetTraceExpand(true);
  905. return true;
  906. } },
  907. CommandArgument{ "--trace-format", CommandArgument::Values::One,
  908. [](std::string const& value, cmake* state) -> bool {
  909. state->SetTrace(true);
  910. const auto traceFormat = StringToTraceFormat(value);
  911. if (traceFormat == TraceFormat::TRACE_UNDEFINED) {
  912. cmSystemTools::Error(
  913. "Invalid format specified for --trace-format. "
  914. "Valid formats are human, json-v1.");
  915. return false;
  916. }
  917. state->SetTraceFormat(traceFormat);
  918. return true;
  919. } },
  920. CommandArgument{ "--trace-source", CommandArgument::Values::One,
  921. [](std::string const& value, cmake* state) -> bool {
  922. std::string file(value);
  923. cmSystemTools::ConvertToUnixSlashes(file);
  924. state->AddTraceSource(file);
  925. state->SetTrace(true);
  926. return true;
  927. } },
  928. CommandArgument{ "--trace-redirect", CommandArgument::Values::One,
  929. [](std::string const& value, cmake* state) -> bool {
  930. std::string file(value);
  931. cmSystemTools::ConvertToUnixSlashes(file);
  932. state->SetTraceFile(file);
  933. state->SetTrace(true);
  934. return true;
  935. } },
  936. CommandArgument{ "--trace", CommandArgument::Values::Zero,
  937. [](std::string const&, cmake* state) -> bool {
  938. std::cout << "Running with trace output on.\n";
  939. state->SetTrace(true);
  940. state->SetTraceExpand(false);
  941. return true;
  942. } },
  943. CommandArgument{ "--warn-uninitialized", CommandArgument::Values::Zero,
  944. [](std::string const&, cmake* state) -> bool {
  945. std::cout << "Warn about uninitialized values.\n";
  946. state->SetWarnUninitialized(true);
  947. return true;
  948. } },
  949. CommandArgument{ "--warn-unused-vars", CommandArgument::Values::Zero,
  950. IgnoreAndTrueLambda }, // Option was removed.
  951. CommandArgument{ "--no-warn-unused-cli", CommandArgument::Values::Zero,
  952. [](std::string const&, cmake* state) -> bool {
  953. std::cout
  954. << "Not searching for unused variables given on the "
  955. << "command line.\n";
  956. state->SetWarnUnusedCli(false);
  957. return true;
  958. } },
  959. CommandArgument{
  960. "--check-system-vars", CommandArgument::Values::Zero,
  961. [](std::string const&, cmake* state) -> bool {
  962. std::cout << "Also check system files when warning about unused and "
  963. << "uninitialized variables.\n";
  964. state->SetCheckSystemVars(true);
  965. return true;
  966. } }
  967. };
  968. #if defined(CMAKE_HAVE_VS_GENERATORS)
  969. arguments.emplace_back("--vs-solution-file", CommandArgument::Values::One,
  970. [](std::string const& value, cmake* state) -> bool {
  971. state->VSSolutionFile = value;
  972. return true;
  973. });
  974. #endif
  975. #if !defined(CMAKE_BOOTSTRAP)
  976. arguments.emplace_back("--profiling-format",
  977. "No format specified for --profiling-format",
  978. CommandArgument::Values::One,
  979. [&](std::string const& value, cmake*) -> bool {
  980. profilingFormat = value;
  981. return true;
  982. });
  983. arguments.emplace_back(
  984. "--profiling-output", "No path specified for --profiling-output",
  985. CommandArgument::Values::One,
  986. [&](std::string const& value, cmake*) -> bool {
  987. profilingOutput = cmSystemTools::CollapseFullPath(value);
  988. cmSystemTools::ConvertToUnixSlashes(profilingOutput);
  989. return true;
  990. });
  991. arguments.emplace_back("--preset", "No preset specified for --preset",
  992. CommandArgument::Values::One,
  993. [&](std::string const& value, cmake*) -> bool {
  994. presetName = value;
  995. return true;
  996. });
  997. arguments.emplace_back(
  998. "--list-presets", CommandArgument::Values::ZeroOrOne,
  999. [&](std::string const& value, cmake*) -> bool {
  1000. if (value.empty() || value == "configure") {
  1001. listPresets = ListPresets::Configure;
  1002. } else if (value == "build") {
  1003. listPresets = ListPresets::Build;
  1004. } else if (value == "test") {
  1005. listPresets = ListPresets::Test;
  1006. } else if (value == "all") {
  1007. listPresets = ListPresets::All;
  1008. } else {
  1009. cmSystemTools::Error(
  1010. "Invalid value specified for --list-presets.\n"
  1011. "Valid values are configure, build, test, or all. "
  1012. "When no value is passed the default is configure.");
  1013. return false;
  1014. }
  1015. return true;
  1016. });
  1017. #endif
  1018. bool badGeneratorName = false;
  1019. CommandArgument generatorCommand(
  1020. "-G", "No generator specified for -G", CommandArgument::Values::One,
  1021. CommandArgument::RequiresSeparator::No,
  1022. [&](std::string const& value, cmake* state) -> bool {
  1023. bool valid = state->CreateAndSetGlobalGenerator(value, true);
  1024. badGeneratorName = !valid;
  1025. return valid;
  1026. });
  1027. for (decltype(args.size()) i = 1; i < args.size(); ++i) {
  1028. // iterate each argument
  1029. std::string const& arg = args[i];
  1030. // Generator flag has special handling for when to print help
  1031. // so it becomes the exception
  1032. if (generatorCommand.matches(arg)) {
  1033. bool parsed = generatorCommand.parse(arg, i, args, this);
  1034. if (!parsed && !badGeneratorName) {
  1035. this->PrintGeneratorList();
  1036. return;
  1037. }
  1038. continue;
  1039. }
  1040. bool matched = false;
  1041. bool parsedCorrectly = true; // needs to be true so we can ignore
  1042. // arguments so as -E
  1043. for (auto const& m : arguments) {
  1044. if (m.matches(arg)) {
  1045. matched = true;
  1046. parsedCorrectly = m.parse(arg, i, args, this);
  1047. break;
  1048. }
  1049. }
  1050. // We have an issue where arguments to a "-P" script mode
  1051. // can be provided before the "-P" argument. This means
  1052. // that we need to lazily check this argument after checking
  1053. // all args.
  1054. // Additionally it can't be the source/binary tree location
  1055. if (!parsedCorrectly) {
  1056. cmSystemTools::Error("Run 'cmake --help' for all supported options.");
  1057. exit(1);
  1058. } else if (!matched && cmHasLiteralPrefix(arg, "-")) {
  1059. possibleUnknownArg = arg;
  1060. } else if (!matched) {
  1061. bool parsedDirectory = this->SetDirectoriesFromFile(arg);
  1062. if (!parsedDirectory) {
  1063. extraProvidedPath = arg;
  1064. }
  1065. }
  1066. }
  1067. if (!extraProvidedPath.empty() && !scriptMode) {
  1068. this->IssueMessage(MessageType::WARNING,
  1069. cmStrCat("Ignoring extra path from command line:\n ",
  1070. extraProvidedPath));
  1071. }
  1072. if (!possibleUnknownArg.empty() && !scriptMode) {
  1073. cmSystemTools::Error(cmStrCat("Unknown argument ", possibleUnknownArg));
  1074. cmSystemTools::Error("Run 'cmake --help' for all supported options.");
  1075. exit(1);
  1076. }
  1077. // Empty instance, platform and toolset if only a generator is specified
  1078. if (this->GlobalGenerator) {
  1079. this->GeneratorInstance = "";
  1080. if (!this->GeneratorPlatformSet) {
  1081. this->GeneratorPlatform = "";
  1082. }
  1083. if (!this->GeneratorToolsetSet) {
  1084. this->GeneratorToolset = "";
  1085. }
  1086. }
  1087. #if !defined(CMAKE_BOOTSTRAP)
  1088. if (!profilingOutput.empty() || !profilingFormat.empty()) {
  1089. if (profilingOutput.empty()) {
  1090. cmSystemTools::Error(
  1091. "--profiling-format specified but no --profiling-output!");
  1092. return;
  1093. }
  1094. if (profilingFormat == "google-trace"_s) {
  1095. try {
  1096. this->ProfilingOutput =
  1097. cm::make_unique<cmMakefileProfilingData>(profilingOutput);
  1098. } catch (std::runtime_error& e) {
  1099. cmSystemTools::Error(
  1100. cmStrCat("Could not start profiling: ", e.what()));
  1101. return;
  1102. }
  1103. } else {
  1104. cmSystemTools::Error("Invalid format specified for --profiling-format");
  1105. return;
  1106. }
  1107. }
  1108. #endif
  1109. const bool haveSourceDir = !this->GetHomeDirectory().empty();
  1110. const bool haveBinaryDir = !this->GetHomeOutputDirectory().empty();
  1111. const bool havePreset =
  1112. #ifdef CMAKE_BOOTSTRAP
  1113. false;
  1114. #else
  1115. !presetName.empty();
  1116. #endif
  1117. if (this->CurrentWorkingMode == cmake::NORMAL_MODE && !haveSourceDir &&
  1118. !haveBinaryDir && !havePreset) {
  1119. this->IssueMessage(
  1120. MessageType::WARNING,
  1121. "No source or binary directory provided. Both will be assumed to be "
  1122. "the same as the current working directory, but note that this "
  1123. "warning will become a fatal error in future CMake releases.");
  1124. }
  1125. if (!haveSourceDir) {
  1126. this->SetHomeDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  1127. }
  1128. if (!haveBinaryDir) {
  1129. this->SetHomeOutputDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  1130. }
  1131. #if !defined(CMAKE_BOOTSTRAP)
  1132. if (listPresets != ListPresets::None || !presetName.empty()) {
  1133. cmCMakePresetsGraph presetsGraph;
  1134. auto result = presetsGraph.ReadProjectPresets(this->GetHomeDirectory());
  1135. if (result != cmCMakePresetsGraph::ReadFileResult::READ_OK) {
  1136. cmSystemTools::Error(
  1137. cmStrCat("Could not read presets from ", this->GetHomeDirectory(),
  1138. ": ", cmCMakePresetsGraph::ResultToString(result)));
  1139. return;
  1140. }
  1141. if (listPresets != ListPresets::None) {
  1142. if (listPresets == ListPresets::Configure) {
  1143. this->PrintPresetList(presetsGraph);
  1144. } else if (listPresets == ListPresets::Build) {
  1145. presetsGraph.PrintBuildPresetList();
  1146. } else if (listPresets == ListPresets::Test) {
  1147. presetsGraph.PrintTestPresetList();
  1148. } else if (listPresets == ListPresets::All) {
  1149. presetsGraph.PrintAllPresets();
  1150. }
  1151. this->SetWorkingMode(WorkingMode::HELP_MODE);
  1152. return;
  1153. }
  1154. auto preset = presetsGraph.ConfigurePresets.find(presetName);
  1155. if (preset == presetsGraph.ConfigurePresets.end()) {
  1156. cmSystemTools::Error(cmStrCat("No such preset in ",
  1157. this->GetHomeDirectory(), ": \"",
  1158. presetName, '"'));
  1159. this->PrintPresetList(presetsGraph);
  1160. return;
  1161. }
  1162. if (preset->second.Unexpanded.Hidden) {
  1163. cmSystemTools::Error(cmStrCat("Cannot use hidden preset in ",
  1164. this->GetHomeDirectory(), ": \"",
  1165. presetName, '"'));
  1166. this->PrintPresetList(presetsGraph);
  1167. return;
  1168. }
  1169. auto const& expandedPreset = preset->second.Expanded;
  1170. if (!expandedPreset) {
  1171. cmSystemTools::Error(cmStrCat("Could not evaluate preset \"",
  1172. preset->second.Unexpanded.Name,
  1173. "\": Invalid macro expansion"));
  1174. return;
  1175. }
  1176. if (!expandedPreset->ConditionResult) {
  1177. cmSystemTools::Error(cmStrCat("Could not use disabled preset \"",
  1178. preset->second.Unexpanded.Name, "\""));
  1179. return;
  1180. }
  1181. if (!this->State->IsCacheLoaded() && !haveBArg &&
  1182. !expandedPreset->BinaryDir.empty()) {
  1183. this->SetHomeOutputDirectory(expandedPreset->BinaryDir);
  1184. }
  1185. if (!this->GlobalGenerator && !expandedPreset->Generator.empty()) {
  1186. if (!this->CreateAndSetGlobalGenerator(expandedPreset->Generator,
  1187. false)) {
  1188. return;
  1189. }
  1190. }
  1191. this->UnprocessedPresetVariables = expandedPreset->CacheVariables;
  1192. this->UnprocessedPresetEnvironment = expandedPreset->Environment;
  1193. if (!expandedPreset->InstallDir.empty() &&
  1194. !this->State->GetInitializedCacheValue("CMAKE_INSTALL_PREFIX")) {
  1195. this->UnprocessedPresetVariables["CMAKE_INSTALL_PREFIX"] = {
  1196. "PATH", expandedPreset->InstallDir
  1197. };
  1198. }
  1199. if (!expandedPreset->ToolchainFile.empty() &&
  1200. !this->State->GetInitializedCacheValue("CMAKE_TOOLCHAIN_FILE")) {
  1201. this->UnprocessedPresetVariables["CMAKE_TOOLCHAIN_FILE"] = {
  1202. "FILEPATH", expandedPreset->ToolchainFile
  1203. };
  1204. }
  1205. if (!expandedPreset->ArchitectureStrategy ||
  1206. expandedPreset->ArchitectureStrategy ==
  1207. cmCMakePresetsGraph::ArchToolsetStrategy::Set) {
  1208. if (!this->GeneratorPlatformSet) {
  1209. this->SetGeneratorPlatform(expandedPreset->Architecture);
  1210. }
  1211. }
  1212. if (!expandedPreset->ToolsetStrategy ||
  1213. expandedPreset->ToolsetStrategy ==
  1214. cmCMakePresetsGraph::ArchToolsetStrategy::Set) {
  1215. if (!this->GeneratorToolsetSet) {
  1216. this->SetGeneratorToolset(expandedPreset->Toolset);
  1217. }
  1218. }
  1219. this->SetWarningFromPreset("dev", expandedPreset->WarnDev,
  1220. expandedPreset->ErrorDev);
  1221. this->SetWarningFromPreset("deprecated", expandedPreset->WarnDeprecated,
  1222. expandedPreset->ErrorDeprecated);
  1223. if (expandedPreset->WarnUninitialized == true) {
  1224. this->SetWarnUninitialized(true);
  1225. }
  1226. if (expandedPreset->WarnUnusedCli == false) {
  1227. this->SetWarnUnusedCli(false);
  1228. }
  1229. if (expandedPreset->WarnSystemVars == true) {
  1230. this->SetCheckSystemVars(true);
  1231. }
  1232. if (expandedPreset->DebugOutput == true) {
  1233. this->SetDebugOutputOn(true);
  1234. }
  1235. if (expandedPreset->DebugTryCompile == true) {
  1236. this->DebugTryCompileOn();
  1237. }
  1238. if (expandedPreset->DebugFind == true) {
  1239. this->SetDebugFindOutput(true);
  1240. }
  1241. }
  1242. #endif
  1243. }
  1244. cmake::LogLevel cmake::StringToLogLevel(const std::string& levelStr)
  1245. {
  1246. using LevelsPair = std::pair<std::string, LogLevel>;
  1247. static const std::vector<LevelsPair> levels = {
  1248. { "error", LogLevel::LOG_ERROR }, { "warning", LogLevel::LOG_WARNING },
  1249. { "notice", LogLevel::LOG_NOTICE }, { "status", LogLevel::LOG_STATUS },
  1250. { "verbose", LogLevel::LOG_VERBOSE }, { "debug", LogLevel::LOG_DEBUG },
  1251. { "trace", LogLevel::LOG_TRACE }
  1252. };
  1253. const auto levelStrLowCase = cmSystemTools::LowerCase(levelStr);
  1254. const auto it = std::find_if(levels.cbegin(), levels.cend(),
  1255. [&levelStrLowCase](const LevelsPair& p) {
  1256. return p.first == levelStrLowCase;
  1257. });
  1258. return (it != levels.cend()) ? it->second : LogLevel::LOG_UNDEFINED;
  1259. }
  1260. cmake::TraceFormat cmake::StringToTraceFormat(const std::string& traceStr)
  1261. {
  1262. using TracePair = std::pair<std::string, TraceFormat>;
  1263. static const std::vector<TracePair> levels = {
  1264. { "human", TraceFormat::TRACE_HUMAN },
  1265. { "json-v1", TraceFormat::TRACE_JSON_V1 },
  1266. };
  1267. const auto traceStrLowCase = cmSystemTools::LowerCase(traceStr);
  1268. const auto it = std::find_if(levels.cbegin(), levels.cend(),
  1269. [&traceStrLowCase](const TracePair& p) {
  1270. return p.first == traceStrLowCase;
  1271. });
  1272. return (it != levels.cend()) ? it->second : TraceFormat::TRACE_UNDEFINED;
  1273. }
  1274. void cmake::SetTraceFile(const std::string& file)
  1275. {
  1276. this->TraceFile.close();
  1277. this->TraceFile.open(file.c_str());
  1278. if (!this->TraceFile) {
  1279. std::stringstream ss;
  1280. ss << "Error opening trace file " << file << ": "
  1281. << cmSystemTools::GetLastSystemError();
  1282. cmSystemTools::Error(ss.str());
  1283. return;
  1284. }
  1285. std::cout << "Trace will be written to " << file << "\n";
  1286. }
  1287. void cmake::PrintTraceFormatVersion()
  1288. {
  1289. if (!this->GetTrace()) {
  1290. return;
  1291. }
  1292. std::string msg;
  1293. switch (this->GetTraceFormat()) {
  1294. case TraceFormat::TRACE_JSON_V1: {
  1295. #ifndef CMAKE_BOOTSTRAP
  1296. Json::Value val;
  1297. Json::Value version;
  1298. Json::StreamWriterBuilder builder;
  1299. builder["indentation"] = "";
  1300. version["major"] = 1;
  1301. version["minor"] = 2;
  1302. val["version"] = version;
  1303. msg = Json::writeString(builder, val);
  1304. #endif
  1305. break;
  1306. }
  1307. case TraceFormat::TRACE_HUMAN:
  1308. msg = "";
  1309. break;
  1310. case TraceFormat::TRACE_UNDEFINED:
  1311. msg = "INTERNAL ERROR: Trace format is TRACE_UNDEFINED";
  1312. break;
  1313. }
  1314. if (msg.empty()) {
  1315. return;
  1316. }
  1317. auto& f = this->GetTraceFile();
  1318. if (f) {
  1319. f << msg << '\n';
  1320. } else {
  1321. cmSystemTools::Message(msg);
  1322. }
  1323. }
  1324. bool cmake::SetDirectoriesFromFile(const std::string& arg)
  1325. {
  1326. // Check if the argument refers to a CMakeCache.txt or
  1327. // CMakeLists.txt file.
  1328. std::string listPath;
  1329. std::string cachePath;
  1330. bool is_empty_directory = false;
  1331. if (cmSystemTools::FileIsDirectory(arg)) {
  1332. std::string path = cmSystemTools::CollapseFullPath(arg);
  1333. cmSystemTools::ConvertToUnixSlashes(path);
  1334. std::string cacheFile = cmStrCat(path, "/CMakeCache.txt");
  1335. std::string listFile = cmStrCat(path, "/CMakeLists.txt");
  1336. is_empty_directory = true;
  1337. if (cmSystemTools::FileExists(cacheFile)) {
  1338. cachePath = path;
  1339. is_empty_directory = false;
  1340. }
  1341. if (cmSystemTools::FileExists(listFile)) {
  1342. listPath = path;
  1343. is_empty_directory = false;
  1344. }
  1345. } else if (cmSystemTools::FileExists(arg)) {
  1346. std::string fullPath = cmSystemTools::CollapseFullPath(arg);
  1347. std::string name = cmSystemTools::GetFilenameName(fullPath);
  1348. name = cmSystemTools::LowerCase(name);
  1349. if (name == "cmakecache.txt"_s) {
  1350. cachePath = cmSystemTools::GetFilenamePath(fullPath);
  1351. } else if (name == "cmakelists.txt"_s) {
  1352. listPath = cmSystemTools::GetFilenamePath(fullPath);
  1353. }
  1354. } else {
  1355. // Specified file or directory does not exist. Try to set things
  1356. // up to produce a meaningful error message.
  1357. std::string fullPath = cmSystemTools::CollapseFullPath(arg);
  1358. std::string name = cmSystemTools::GetFilenameName(fullPath);
  1359. name = cmSystemTools::LowerCase(name);
  1360. if (name == "cmakecache.txt"_s || name == "cmakelists.txt"_s) {
  1361. listPath = cmSystemTools::GetFilenamePath(fullPath);
  1362. } else {
  1363. listPath = fullPath;
  1364. }
  1365. }
  1366. // If there is a CMakeCache.txt file, use its settings.
  1367. if (!cachePath.empty()) {
  1368. if (this->LoadCache(cachePath)) {
  1369. cmValue existingValue =
  1370. this->State->GetCacheEntryValue("CMAKE_HOME_DIRECTORY");
  1371. if (existingValue) {
  1372. this->SetHomeOutputDirectory(cachePath);
  1373. this->SetHomeDirectory(*existingValue);
  1374. return true;
  1375. }
  1376. }
  1377. }
  1378. bool no_source_tree = this->GetHomeDirectory().empty();
  1379. bool no_build_tree = this->GetHomeOutputDirectory().empty();
  1380. // When invoked with a path that points to an existing CMakeCache
  1381. // This function is called multiple times with the same path
  1382. const bool passed_same_path = (listPath == this->GetHomeDirectory()) ||
  1383. (listPath == this->GetHomeOutputDirectory());
  1384. bool used_provided_path =
  1385. (passed_same_path || no_source_tree || no_build_tree);
  1386. // If there is a CMakeLists.txt file, use it as the source tree.
  1387. if (!listPath.empty()) {
  1388. // When invoked with a path that points to an existing CMakeCache
  1389. // This function is called multiple times with the same path
  1390. if (no_source_tree && no_build_tree) {
  1391. this->SetHomeDirectory(listPath);
  1392. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1393. this->SetHomeOutputDirectory(cwd);
  1394. } else if (no_source_tree) {
  1395. this->SetHomeDirectory(listPath);
  1396. } else if (no_build_tree) {
  1397. this->SetHomeOutputDirectory(listPath);
  1398. }
  1399. } else {
  1400. if (no_source_tree) {
  1401. // We didn't find a CMakeLists.txt and it wasn't specified
  1402. // with -S. Assume it is the path to the source tree
  1403. std::string full = cmSystemTools::CollapseFullPath(arg);
  1404. this->SetHomeDirectory(full);
  1405. }
  1406. if (no_build_tree && !no_source_tree && is_empty_directory) {
  1407. // passed `-S <path> <build_dir> when build_dir is an empty directory
  1408. std::string full = cmSystemTools::CollapseFullPath(arg);
  1409. this->SetHomeOutputDirectory(full);
  1410. } else if (no_build_tree) {
  1411. // We didn't find a CMakeCache.txt and it wasn't specified
  1412. // with -B. Assume the current working directory as the build tree.
  1413. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1414. this->SetHomeOutputDirectory(cwd);
  1415. used_provided_path = false;
  1416. }
  1417. }
  1418. return used_provided_path;
  1419. }
  1420. // at the end of this CMAKE_ROOT and CMAKE_COMMAND should be added to the
  1421. // cache
  1422. int cmake::AddCMakePaths()
  1423. {
  1424. // Save the value in the cache
  1425. this->AddCacheEntry("CMAKE_COMMAND", cmSystemTools::GetCMakeCommand(),
  1426. "Path to CMake executable.", cmStateEnums::INTERNAL);
  1427. #ifndef CMAKE_BOOTSTRAP
  1428. this->AddCacheEntry("CMAKE_CTEST_COMMAND", cmSystemTools::GetCTestCommand(),
  1429. "Path to ctest program executable.",
  1430. cmStateEnums::INTERNAL);
  1431. this->AddCacheEntry("CMAKE_CPACK_COMMAND", cmSystemTools::GetCPackCommand(),
  1432. "Path to cpack program executable.",
  1433. cmStateEnums::INTERNAL);
  1434. #endif
  1435. if (!cmSystemTools::FileExists(
  1436. (cmSystemTools::GetCMakeRoot() + "/Modules/CMake.cmake"))) {
  1437. // couldn't find modules
  1438. cmSystemTools::Error(
  1439. "Could not find CMAKE_ROOT !!!\n"
  1440. "CMake has most likely not been installed correctly.\n"
  1441. "Modules directory not found in\n" +
  1442. cmSystemTools::GetCMakeRoot());
  1443. return 0;
  1444. }
  1445. this->AddCacheEntry("CMAKE_ROOT", cmSystemTools::GetCMakeRoot(),
  1446. "Path to CMake installation.", cmStateEnums::INTERNAL);
  1447. return 1;
  1448. }
  1449. void cmake::AddDefaultExtraGenerators()
  1450. {
  1451. #if !defined(CMAKE_BOOTSTRAP)
  1452. this->ExtraGenerators.push_back(cmExtraCodeBlocksGenerator::GetFactory());
  1453. this->ExtraGenerators.push_back(cmExtraCodeLiteGenerator::GetFactory());
  1454. this->ExtraGenerators.push_back(cmExtraEclipseCDT4Generator::GetFactory());
  1455. this->ExtraGenerators.push_back(cmExtraKateGenerator::GetFactory());
  1456. this->ExtraGenerators.push_back(cmExtraSublimeTextGenerator::GetFactory());
  1457. #endif
  1458. }
  1459. void cmake::GetRegisteredGenerators(std::vector<GeneratorInfo>& generators,
  1460. bool includeNamesWithPlatform) const
  1461. {
  1462. for (const auto& gen : this->Generators) {
  1463. std::vector<std::string> names = gen->GetGeneratorNames();
  1464. if (includeNamesWithPlatform) {
  1465. cm::append(names, gen->GetGeneratorNamesWithPlatform());
  1466. }
  1467. for (std::string const& name : names) {
  1468. GeneratorInfo info;
  1469. info.supportsToolset = gen->SupportsToolset();
  1470. info.supportsPlatform = gen->SupportsPlatform();
  1471. info.supportedPlatforms = gen->GetKnownPlatforms();
  1472. info.defaultPlatform = gen->GetDefaultPlatformName();
  1473. info.name = name;
  1474. info.baseName = name;
  1475. info.isAlias = false;
  1476. generators.push_back(std::move(info));
  1477. }
  1478. }
  1479. for (cmExternalMakefileProjectGeneratorFactory* eg : this->ExtraGenerators) {
  1480. const std::vector<std::string> genList =
  1481. eg->GetSupportedGlobalGenerators();
  1482. for (std::string const& gen : genList) {
  1483. GeneratorInfo info;
  1484. info.name = cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  1485. gen, eg->GetName());
  1486. info.baseName = gen;
  1487. info.extraName = eg->GetName();
  1488. info.supportsPlatform = false;
  1489. info.supportsToolset = false;
  1490. info.isAlias = false;
  1491. generators.push_back(std::move(info));
  1492. }
  1493. for (std::string const& a : eg->Aliases) {
  1494. GeneratorInfo info;
  1495. info.name = a;
  1496. if (!genList.empty()) {
  1497. info.baseName = genList.at(0);
  1498. }
  1499. info.extraName = eg->GetName();
  1500. info.supportsPlatform = false;
  1501. info.supportsToolset = false;
  1502. info.isAlias = true;
  1503. generators.push_back(std::move(info));
  1504. }
  1505. }
  1506. }
  1507. static std::pair<std::unique_ptr<cmExternalMakefileProjectGenerator>,
  1508. std::string>
  1509. createExtraGenerator(
  1510. const std::vector<cmExternalMakefileProjectGeneratorFactory*>& in,
  1511. const std::string& name)
  1512. {
  1513. for (cmExternalMakefileProjectGeneratorFactory* i : in) {
  1514. const std::vector<std::string> generators =
  1515. i->GetSupportedGlobalGenerators();
  1516. if (i->GetName() == name) { // Match aliases
  1517. return { i->CreateExternalMakefileProjectGenerator(), generators.at(0) };
  1518. }
  1519. for (std::string const& g : generators) {
  1520. const std::string fullName =
  1521. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  1522. g, i->GetName());
  1523. if (fullName == name) {
  1524. return { i->CreateExternalMakefileProjectGenerator(), g };
  1525. }
  1526. }
  1527. }
  1528. return { nullptr, name };
  1529. }
  1530. std::unique_ptr<cmGlobalGenerator> cmake::CreateGlobalGenerator(
  1531. const std::string& gname, bool allowArch)
  1532. {
  1533. std::pair<std::unique_ptr<cmExternalMakefileProjectGenerator>, std::string>
  1534. extra = createExtraGenerator(this->ExtraGenerators, gname);
  1535. std::unique_ptr<cmExternalMakefileProjectGenerator>& extraGenerator =
  1536. extra.first;
  1537. const std::string& name = extra.second;
  1538. std::unique_ptr<cmGlobalGenerator> generator;
  1539. for (const auto& g : this->Generators) {
  1540. generator = g->CreateGlobalGenerator(name, allowArch, this);
  1541. if (generator) {
  1542. break;
  1543. }
  1544. }
  1545. if (generator) {
  1546. generator->SetExternalMakefileProjectGenerator(std::move(extraGenerator));
  1547. }
  1548. return generator;
  1549. }
  1550. bool cmake::CreateAndSetGlobalGenerator(const std::string& name,
  1551. bool allowArch)
  1552. {
  1553. auto gen = this->CreateGlobalGenerator(name, allowArch);
  1554. if (!gen) {
  1555. std::string kdevError;
  1556. std::string vsError;
  1557. if (name.find("KDevelop3", 0) != std::string::npos) {
  1558. kdevError = "\nThe KDevelop3 generator is not supported anymore.";
  1559. }
  1560. if (!allowArch && cmHasLiteralPrefix(name, "Visual Studio ") &&
  1561. name.length() >= cmStrLen("Visual Studio xx xxxx ")) {
  1562. vsError = "\nUsing platforms in Visual Studio generator names is not "
  1563. "supported in CMakePresets.json.";
  1564. }
  1565. cmSystemTools::Error(
  1566. cmStrCat("Could not create named generator ", name, kdevError, vsError));
  1567. this->PrintGeneratorList();
  1568. return false;
  1569. }
  1570. this->SetGlobalGenerator(std::move(gen));
  1571. return true;
  1572. }
  1573. #ifndef CMAKE_BOOTSTRAP
  1574. void cmake::PrintPresetList(const cmCMakePresetsGraph& graph) const
  1575. {
  1576. std::vector<GeneratorInfo> generators;
  1577. this->GetRegisteredGenerators(generators, false);
  1578. auto filter =
  1579. [&generators](const cmCMakePresetsGraph::ConfigurePreset& preset) -> bool {
  1580. if (preset.Generator.empty()) {
  1581. return true;
  1582. }
  1583. auto condition = [&preset](const GeneratorInfo& info) -> bool {
  1584. return info.name == preset.Generator;
  1585. };
  1586. auto it = std::find_if(generators.begin(), generators.end(), condition);
  1587. return it != generators.end();
  1588. };
  1589. graph.PrintConfigurePresetList(filter);
  1590. }
  1591. #endif
  1592. void cmake::SetHomeDirectory(const std::string& dir)
  1593. {
  1594. this->State->SetSourceDirectory(dir);
  1595. if (this->CurrentSnapshot.IsValid()) {
  1596. this->CurrentSnapshot.SetDefinition("CMAKE_SOURCE_DIR", dir);
  1597. }
  1598. if (this->State->GetProjectKind() == cmState::ProjectKind::Normal) {
  1599. this->Messenger->SetTopSource(this->GetHomeDirectory());
  1600. } else {
  1601. this->Messenger->SetTopSource(cm::nullopt);
  1602. }
  1603. }
  1604. std::string const& cmake::GetHomeDirectory() const
  1605. {
  1606. return this->State->GetSourceDirectory();
  1607. }
  1608. void cmake::SetHomeOutputDirectory(const std::string& dir)
  1609. {
  1610. this->State->SetBinaryDirectory(dir);
  1611. if (this->CurrentSnapshot.IsValid()) {
  1612. this->CurrentSnapshot.SetDefinition("CMAKE_BINARY_DIR", dir);
  1613. }
  1614. }
  1615. std::string const& cmake::GetHomeOutputDirectory() const
  1616. {
  1617. return this->State->GetBinaryDirectory();
  1618. }
  1619. std::string cmake::FindCacheFile(const std::string& binaryDir)
  1620. {
  1621. std::string cachePath = binaryDir;
  1622. cmSystemTools::ConvertToUnixSlashes(cachePath);
  1623. std::string cacheFile = cmStrCat(cachePath, "/CMakeCache.txt");
  1624. if (!cmSystemTools::FileExists(cacheFile)) {
  1625. // search in parent directories for cache
  1626. std::string cmakeFiles = cmStrCat(cachePath, "/CMakeFiles");
  1627. if (cmSystemTools::FileExists(cmakeFiles)) {
  1628. std::string cachePathFound =
  1629. cmSystemTools::FileExistsInParentDirectories("CMakeCache.txt",
  1630. cachePath, "/");
  1631. if (!cachePathFound.empty()) {
  1632. cachePath = cmSystemTools::GetFilenamePath(cachePathFound);
  1633. }
  1634. }
  1635. }
  1636. return cachePath;
  1637. }
  1638. void cmake::SetGlobalGenerator(std::unique_ptr<cmGlobalGenerator> gg)
  1639. {
  1640. if (!gg) {
  1641. cmSystemTools::Error("Error SetGlobalGenerator called with null");
  1642. return;
  1643. }
  1644. if (this->GlobalGenerator) {
  1645. // restore the original environment variables CXX and CC
  1646. std::string env = "CC=";
  1647. if (!this->CCEnvironment.empty()) {
  1648. env += this->CCEnvironment;
  1649. cmSystemTools::PutEnv(env);
  1650. } else {
  1651. cmSystemTools::UnPutEnv(env);
  1652. }
  1653. env = "CXX=";
  1654. if (!this->CXXEnvironment.empty()) {
  1655. env += this->CXXEnvironment;
  1656. cmSystemTools::PutEnv(env);
  1657. } else {
  1658. cmSystemTools::UnPutEnv(env);
  1659. }
  1660. }
  1661. // set the new
  1662. this->GlobalGenerator = std::move(gg);
  1663. // set the global flag for unix style paths on cmSystemTools as soon as
  1664. // the generator is set. This allows gmake to be used on windows.
  1665. cmSystemTools::SetForceUnixPaths(this->GlobalGenerator->GetForceUnixPaths());
  1666. // Save the environment variables CXX and CC
  1667. if (!cmSystemTools::GetEnv("CXX", this->CXXEnvironment)) {
  1668. this->CXXEnvironment.clear();
  1669. }
  1670. if (!cmSystemTools::GetEnv("CC", this->CCEnvironment)) {
  1671. this->CCEnvironment.clear();
  1672. }
  1673. }
  1674. int cmake::DoPreConfigureChecks()
  1675. {
  1676. // Make sure the Source directory contains a CMakeLists.txt file.
  1677. std::string srcList = cmStrCat(this->GetHomeDirectory(), "/CMakeLists.txt");
  1678. if (!cmSystemTools::FileExists(srcList)) {
  1679. std::ostringstream err;
  1680. if (cmSystemTools::FileIsDirectory(this->GetHomeDirectory())) {
  1681. err << "The source directory \"" << this->GetHomeDirectory()
  1682. << "\" does not appear to contain CMakeLists.txt.\n";
  1683. } else if (cmSystemTools::FileExists(this->GetHomeDirectory())) {
  1684. err << "The source directory \"" << this->GetHomeDirectory()
  1685. << "\" is a file, not a directory.\n";
  1686. } else {
  1687. err << "The source directory \"" << this->GetHomeDirectory()
  1688. << "\" does not exist.\n";
  1689. }
  1690. err << "Specify --help for usage, or press the help button on the CMake "
  1691. "GUI.";
  1692. cmSystemTools::Error(err.str());
  1693. return -2;
  1694. }
  1695. // do a sanity check on some values
  1696. if (this->State->GetInitializedCacheValue("CMAKE_HOME_DIRECTORY")) {
  1697. std::string cacheStart =
  1698. cmStrCat(*this->State->GetInitializedCacheValue("CMAKE_HOME_DIRECTORY"),
  1699. "/CMakeLists.txt");
  1700. std::string currentStart =
  1701. cmStrCat(this->GetHomeDirectory(), "/CMakeLists.txt");
  1702. if (!cmSystemTools::SameFile(cacheStart, currentStart)) {
  1703. std::string message =
  1704. cmStrCat("The source \"", currentStart,
  1705. "\" does not match the source \"", cacheStart,
  1706. "\" used to generate cache. Re-run cmake with a different "
  1707. "source directory.");
  1708. cmSystemTools::Error(message);
  1709. return -2;
  1710. }
  1711. } else {
  1712. return 0;
  1713. }
  1714. return 1;
  1715. }
  1716. struct SaveCacheEntry
  1717. {
  1718. std::string key;
  1719. std::string value;
  1720. std::string help;
  1721. cmStateEnums::CacheEntryType type;
  1722. };
  1723. int cmake::HandleDeleteCacheVariables(const std::string& var)
  1724. {
  1725. std::vector<std::string> argsSplit = cmExpandedList(var, true);
  1726. // erase the property to avoid infinite recursion
  1727. this->State->SetGlobalProperty("__CMAKE_DELETE_CACHE_CHANGE_VARS_", "");
  1728. if (this->GetIsInTryCompile()) {
  1729. return 0;
  1730. }
  1731. std::vector<SaveCacheEntry> saved;
  1732. std::ostringstream warning;
  1733. /* clang-format off */
  1734. warning
  1735. << "You have changed variables that require your cache to be deleted.\n"
  1736. << "Configure will be re-run and you may have to reset some variables.\n"
  1737. << "The following variables have changed:\n";
  1738. /* clang-format on */
  1739. for (auto i = argsSplit.begin(); i != argsSplit.end(); ++i) {
  1740. SaveCacheEntry save;
  1741. save.key = *i;
  1742. warning << *i << "= ";
  1743. i++;
  1744. if (i != argsSplit.end()) {
  1745. save.value = *i;
  1746. warning << *i << "\n";
  1747. } else {
  1748. warning << "\n";
  1749. i -= 1;
  1750. }
  1751. cmValue existingValue = this->State->GetCacheEntryValue(save.key);
  1752. if (existingValue) {
  1753. save.type = this->State->GetCacheEntryType(save.key);
  1754. if (cmValue help =
  1755. this->State->GetCacheEntryProperty(save.key, "HELPSTRING")) {
  1756. save.help = *help;
  1757. }
  1758. } else {
  1759. save.type = cmStateEnums::CacheEntryType::UNINITIALIZED;
  1760. }
  1761. saved.push_back(std::move(save));
  1762. }
  1763. // remove the cache
  1764. this->DeleteCache(this->GetHomeOutputDirectory());
  1765. // load the empty cache
  1766. this->LoadCache();
  1767. // restore the changed compilers
  1768. for (SaveCacheEntry const& i : saved) {
  1769. this->AddCacheEntry(i.key, i.value, i.help.c_str(), i.type);
  1770. }
  1771. cmSystemTools::Message(warning.str());
  1772. // avoid reconfigure if there were errors
  1773. if (!cmSystemTools::GetErrorOccuredFlag()) {
  1774. // re-run configure
  1775. return this->Configure();
  1776. }
  1777. return 0;
  1778. }
  1779. int cmake::Configure()
  1780. {
  1781. DiagLevel diagLevel;
  1782. if (this->DiagLevels.count("deprecated") == 1) {
  1783. diagLevel = this->DiagLevels["deprecated"];
  1784. if (diagLevel == DIAG_IGNORE) {
  1785. this->SetSuppressDeprecatedWarnings(true);
  1786. this->SetDeprecatedWarningsAsErrors(false);
  1787. } else if (diagLevel == DIAG_WARN) {
  1788. this->SetSuppressDeprecatedWarnings(false);
  1789. this->SetDeprecatedWarningsAsErrors(false);
  1790. } else if (diagLevel == DIAG_ERROR) {
  1791. this->SetSuppressDeprecatedWarnings(false);
  1792. this->SetDeprecatedWarningsAsErrors(true);
  1793. }
  1794. }
  1795. if (this->DiagLevels.count("dev") == 1) {
  1796. bool setDeprecatedVariables = false;
  1797. cmValue cachedWarnDeprecated =
  1798. this->State->GetCacheEntryValue("CMAKE_WARN_DEPRECATED");
  1799. cmValue cachedErrorDeprecated =
  1800. this->State->GetCacheEntryValue("CMAKE_ERROR_DEPRECATED");
  1801. // don't overwrite deprecated warning setting from a previous invocation
  1802. if (!cachedWarnDeprecated && !cachedErrorDeprecated) {
  1803. setDeprecatedVariables = true;
  1804. }
  1805. diagLevel = this->DiagLevels["dev"];
  1806. if (diagLevel == DIAG_IGNORE) {
  1807. this->SetSuppressDevWarnings(true);
  1808. this->SetDevWarningsAsErrors(false);
  1809. if (setDeprecatedVariables) {
  1810. this->SetSuppressDeprecatedWarnings(true);
  1811. this->SetDeprecatedWarningsAsErrors(false);
  1812. }
  1813. } else if (diagLevel == DIAG_WARN) {
  1814. this->SetSuppressDevWarnings(false);
  1815. this->SetDevWarningsAsErrors(false);
  1816. if (setDeprecatedVariables) {
  1817. this->SetSuppressDeprecatedWarnings(false);
  1818. this->SetDeprecatedWarningsAsErrors(false);
  1819. }
  1820. } else if (diagLevel == DIAG_ERROR) {
  1821. this->SetSuppressDevWarnings(false);
  1822. this->SetDevWarningsAsErrors(true);
  1823. if (setDeprecatedVariables) {
  1824. this->SetSuppressDeprecatedWarnings(false);
  1825. this->SetDeprecatedWarningsAsErrors(true);
  1826. }
  1827. }
  1828. }
  1829. // Cache variables may have already been set by a previous invocation,
  1830. // so we cannot rely on command line options alone. Always ensure our
  1831. // messenger is in sync with the cache.
  1832. cmValue value = this->State->GetCacheEntryValue("CMAKE_WARN_DEPRECATED");
  1833. this->Messenger->SetSuppressDeprecatedWarnings(value && cmIsOff(*value));
  1834. value = this->State->GetCacheEntryValue("CMAKE_ERROR_DEPRECATED");
  1835. this->Messenger->SetDeprecatedWarningsAsErrors(cmIsOn(value));
  1836. value = this->State->GetCacheEntryValue("CMAKE_SUPPRESS_DEVELOPER_WARNINGS");
  1837. this->Messenger->SetSuppressDevWarnings(cmIsOn(value));
  1838. value = this->State->GetCacheEntryValue("CMAKE_SUPPRESS_DEVELOPER_ERRORS");
  1839. this->Messenger->SetDevWarningsAsErrors(value && cmIsOff(*value));
  1840. int ret = this->ActualConfigure();
  1841. cmValue delCacheVars =
  1842. this->State->GetGlobalProperty("__CMAKE_DELETE_CACHE_CHANGE_VARS_");
  1843. if (delCacheVars && !delCacheVars->empty()) {
  1844. return this->HandleDeleteCacheVariables(*delCacheVars);
  1845. }
  1846. return ret;
  1847. }
  1848. int cmake::ActualConfigure()
  1849. {
  1850. // Construct right now our path conversion table before it's too late:
  1851. this->UpdateConversionPathTable();
  1852. this->CleanupCommandsAndMacros();
  1853. int res = this->DoPreConfigureChecks();
  1854. if (res < 0) {
  1855. return -2;
  1856. }
  1857. if (!res) {
  1858. this->AddCacheEntry(
  1859. "CMAKE_HOME_DIRECTORY", this->GetHomeDirectory(),
  1860. "Source directory with the top level CMakeLists.txt file for this "
  1861. "project",
  1862. cmStateEnums::INTERNAL);
  1863. }
  1864. // no generator specified on the command line
  1865. if (!this->GlobalGenerator) {
  1866. cmValue genName = this->State->GetInitializedCacheValue("CMAKE_GENERATOR");
  1867. cmValue extraGenName =
  1868. this->State->GetInitializedCacheValue("CMAKE_EXTRA_GENERATOR");
  1869. if (genName) {
  1870. std::string fullName =
  1871. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  1872. *genName, extraGenName ? *extraGenName : "");
  1873. this->GlobalGenerator = this->CreateGlobalGenerator(fullName);
  1874. }
  1875. if (this->GlobalGenerator) {
  1876. // set the global flag for unix style paths on cmSystemTools as
  1877. // soon as the generator is set. This allows gmake to be used
  1878. // on windows.
  1879. cmSystemTools::SetForceUnixPaths(
  1880. this->GlobalGenerator->GetForceUnixPaths());
  1881. } else {
  1882. this->CreateDefaultGlobalGenerator();
  1883. }
  1884. if (!this->GlobalGenerator) {
  1885. cmSystemTools::Error("Could not create generator");
  1886. return -1;
  1887. }
  1888. }
  1889. cmValue genName = this->State->GetInitializedCacheValue("CMAKE_GENERATOR");
  1890. if (genName) {
  1891. if (!this->GlobalGenerator->MatchesGeneratorName(*genName)) {
  1892. std::string message =
  1893. cmStrCat("Error: generator : ", this->GlobalGenerator->GetName(),
  1894. "\nDoes not match the generator used previously: ", *genName,
  1895. "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1896. "directory or choose a different binary directory.");
  1897. cmSystemTools::Error(message);
  1898. return -2;
  1899. }
  1900. }
  1901. if (!this->State->GetInitializedCacheValue("CMAKE_GENERATOR")) {
  1902. this->AddCacheEntry("CMAKE_GENERATOR", this->GlobalGenerator->GetName(),
  1903. "Name of generator.", cmStateEnums::INTERNAL);
  1904. this->AddCacheEntry(
  1905. "CMAKE_EXTRA_GENERATOR", this->GlobalGenerator->GetExtraGeneratorName(),
  1906. "Name of external makefile project generator.", cmStateEnums::INTERNAL);
  1907. if (!this->State->GetInitializedCacheValue("CMAKE_TOOLCHAIN_FILE")) {
  1908. std::string envToolchain;
  1909. if (cmSystemTools::GetEnv("CMAKE_TOOLCHAIN_FILE", envToolchain) &&
  1910. !envToolchain.empty()) {
  1911. this->AddCacheEntry("CMAKE_TOOLCHAIN_FILE", envToolchain,
  1912. "The CMake toolchain file",
  1913. cmStateEnums::FILEPATH);
  1914. }
  1915. }
  1916. }
  1917. if (cmValue instance =
  1918. this->State->GetInitializedCacheValue("CMAKE_GENERATOR_INSTANCE")) {
  1919. if (this->GeneratorInstanceSet && this->GeneratorInstance != *instance) {
  1920. std::string message =
  1921. cmStrCat("Error: generator instance: ", this->GeneratorInstance,
  1922. "\nDoes not match the instance used previously: ", *instance,
  1923. "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1924. "directory or choose a different binary directory.");
  1925. cmSystemTools::Error(message);
  1926. return -2;
  1927. }
  1928. } else {
  1929. this->AddCacheEntry("CMAKE_GENERATOR_INSTANCE", this->GeneratorInstance,
  1930. "Generator instance identifier.",
  1931. cmStateEnums::INTERNAL);
  1932. }
  1933. if (cmValue platformName =
  1934. this->State->GetInitializedCacheValue("CMAKE_GENERATOR_PLATFORM")) {
  1935. if (this->GeneratorPlatformSet &&
  1936. this->GeneratorPlatform != *platformName) {
  1937. std::string message = cmStrCat(
  1938. "Error: generator platform: ", this->GeneratorPlatform,
  1939. "\nDoes not match the platform used previously: ", *platformName,
  1940. "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1941. "directory or choose a different binary directory.");
  1942. cmSystemTools::Error(message);
  1943. return -2;
  1944. }
  1945. } else {
  1946. this->AddCacheEntry("CMAKE_GENERATOR_PLATFORM", this->GeneratorPlatform,
  1947. "Name of generator platform.", cmStateEnums::INTERNAL);
  1948. }
  1949. if (cmValue tsName =
  1950. this->State->GetInitializedCacheValue("CMAKE_GENERATOR_TOOLSET")) {
  1951. if (this->GeneratorToolsetSet && this->GeneratorToolset != *tsName) {
  1952. std::string message =
  1953. cmStrCat("Error: generator toolset: ", this->GeneratorToolset,
  1954. "\nDoes not match the toolset used previously: ", *tsName,
  1955. "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1956. "directory or choose a different binary directory.");
  1957. cmSystemTools::Error(message);
  1958. return -2;
  1959. }
  1960. } else {
  1961. this->AddCacheEntry("CMAKE_GENERATOR_TOOLSET", this->GeneratorToolset,
  1962. "Name of generator toolset.", cmStateEnums::INTERNAL);
  1963. }
  1964. // reset any system configuration information, except for when we are
  1965. // InTryCompile. With TryCompile the system info is taken from the parent's
  1966. // info to save time
  1967. if (!this->GetIsInTryCompile()) {
  1968. this->GlobalGenerator->ClearEnabledLanguages();
  1969. this->TruncateOutputLog("CMakeOutput.log");
  1970. this->TruncateOutputLog("CMakeError.log");
  1971. }
  1972. #if !defined(CMAKE_BOOTSTRAP)
  1973. this->FileAPI = cm::make_unique<cmFileAPI>(this);
  1974. this->FileAPI->ReadQueries();
  1975. #endif
  1976. // actually do the configure
  1977. this->GlobalGenerator->Configure();
  1978. // Before saving the cache
  1979. // if the project did not define one of the entries below, add them now
  1980. // so users can edit the values in the cache:
  1981. // We used to always present LIBRARY_OUTPUT_PATH and
  1982. // EXECUTABLE_OUTPUT_PATH. They are now documented as old-style and
  1983. // should no longer be used. Therefore we present them only if the
  1984. // project requires compatibility with CMake 2.4. We detect this
  1985. // here by looking for the old CMAKE_BACKWARDS_COMPATIBILITY
  1986. // variable created when CMP0001 is not set to NEW.
  1987. if (this->State->GetInitializedCacheValue("CMAKE_BACKWARDS_COMPATIBILITY")) {
  1988. if (!this->State->GetInitializedCacheValue("LIBRARY_OUTPUT_PATH")) {
  1989. this->AddCacheEntry(
  1990. "LIBRARY_OUTPUT_PATH", "",
  1991. "Single output directory for building all libraries.",
  1992. cmStateEnums::PATH);
  1993. }
  1994. if (!this->State->GetInitializedCacheValue("EXECUTABLE_OUTPUT_PATH")) {
  1995. this->AddCacheEntry(
  1996. "EXECUTABLE_OUTPUT_PATH", "",
  1997. "Single output directory for building all executables.",
  1998. cmStateEnums::PATH);
  1999. }
  2000. }
  2001. const auto& mf = this->GlobalGenerator->GetMakefiles()[0];
  2002. if (mf->IsOn("CTEST_USE_LAUNCHERS") &&
  2003. !this->State->GetGlobalProperty("RULE_LAUNCH_COMPILE")) {
  2004. cmSystemTools::Error(
  2005. "CTEST_USE_LAUNCHERS is enabled, but the "
  2006. "RULE_LAUNCH_COMPILE global property is not defined.\n"
  2007. "Did you forget to include(CTest) in the toplevel "
  2008. "CMakeLists.txt ?");
  2009. }
  2010. this->State->SaveVerificationScript(this->GetHomeOutputDirectory(),
  2011. this->Messenger.get());
  2012. this->SaveCache(this->GetHomeOutputDirectory());
  2013. if (cmSystemTools::GetErrorOccuredFlag()) {
  2014. return -1;
  2015. }
  2016. return 0;
  2017. }
  2018. std::unique_ptr<cmGlobalGenerator> cmake::EvaluateDefaultGlobalGenerator()
  2019. {
  2020. if (!this->EnvironmentGenerator.empty()) {
  2021. auto gen = this->CreateGlobalGenerator(this->EnvironmentGenerator);
  2022. if (!gen) {
  2023. cmSystemTools::Error("CMAKE_GENERATOR was set but the specified "
  2024. "generator doesn't exist. Using CMake default.");
  2025. } else {
  2026. return gen;
  2027. }
  2028. }
  2029. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(CMAKE_BOOT_MINGW)
  2030. std::string found;
  2031. // Try to find the newest VS installed on the computer and
  2032. // use that as a default if -G is not specified
  2033. const std::string vsregBase = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\";
  2034. static const char* const vsVariants[] = {
  2035. /* clang-format needs this comment to break after the opening brace */
  2036. "VisualStudio\\", "VCExpress\\", "WDExpress\\"
  2037. };
  2038. struct VSVersionedGenerator
  2039. {
  2040. const char* MSVersion;
  2041. const char* GeneratorName;
  2042. };
  2043. static VSVersionedGenerator const vsGenerators[] = {
  2044. { "14.0", "Visual Studio 14 2015" }, //
  2045. { "12.0", "Visual Studio 12 2013" }, //
  2046. { "11.0", "Visual Studio 11 2012" }, //
  2047. { "10.0", "Visual Studio 10 2010" }, //
  2048. { "9.0", "Visual Studio 9 2008" }
  2049. };
  2050. static const char* const vsEntries[] = {
  2051. "\\Setup\\VC;ProductDir", //
  2052. ";InstallDir" //
  2053. };
  2054. if (cmVSSetupAPIHelper(17).IsVSInstalled()) {
  2055. found = "Visual Studio 17 2022";
  2056. } else if (cmVSSetupAPIHelper(16).IsVSInstalled()) {
  2057. found = "Visual Studio 16 2019";
  2058. } else if (cmVSSetupAPIHelper(15).IsVSInstalled()) {
  2059. found = "Visual Studio 15 2017";
  2060. } else {
  2061. for (VSVersionedGenerator const* g = cm::cbegin(vsGenerators);
  2062. found.empty() && g != cm::cend(vsGenerators); ++g) {
  2063. for (const char* const* v = cm::cbegin(vsVariants);
  2064. found.empty() && v != cm::cend(vsVariants); ++v) {
  2065. for (const char* const* e = cm::cbegin(vsEntries);
  2066. found.empty() && e != cm::cend(vsEntries); ++e) {
  2067. std::string const reg = vsregBase + *v + g->MSVersion + *e;
  2068. std::string dir;
  2069. if (cmSystemTools::ReadRegistryValue(reg, dir,
  2070. cmSystemTools::KeyWOW64_32) &&
  2071. cmSystemTools::PathExists(dir)) {
  2072. found = g->GeneratorName;
  2073. }
  2074. }
  2075. }
  2076. }
  2077. }
  2078. auto gen = this->CreateGlobalGenerator(found);
  2079. if (!gen) {
  2080. gen = cm::make_unique<cmGlobalNMakeMakefileGenerator>(this);
  2081. }
  2082. return std::unique_ptr<cmGlobalGenerator>(std::move(gen));
  2083. #elif defined(CMAKE_BOOTSTRAP_NINJA)
  2084. return std::unique_ptr<cmGlobalGenerator>(
  2085. cm::make_unique<cmGlobalNinjaGenerator>(this));
  2086. #else
  2087. return std::unique_ptr<cmGlobalGenerator>(
  2088. cm::make_unique<cmGlobalUnixMakefileGenerator3>(this));
  2089. #endif
  2090. }
  2091. void cmake::CreateDefaultGlobalGenerator()
  2092. {
  2093. auto gen = this->EvaluateDefaultGlobalGenerator();
  2094. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(CMAKE_BOOT_MINGW)
  2095. // This print could be unified for all platforms
  2096. std::cout << "-- Building for: " << gen->GetName() << "\n";
  2097. #endif
  2098. this->SetGlobalGenerator(std::move(gen));
  2099. }
  2100. void cmake::PreLoadCMakeFiles()
  2101. {
  2102. std::vector<std::string> args;
  2103. std::string pre_load = this->GetHomeDirectory();
  2104. if (!pre_load.empty()) {
  2105. pre_load += "/PreLoad.cmake";
  2106. if (cmSystemTools::FileExists(pre_load)) {
  2107. this->ReadListFile(args, pre_load);
  2108. }
  2109. }
  2110. pre_load = this->GetHomeOutputDirectory();
  2111. if (!pre_load.empty()) {
  2112. pre_load += "/PreLoad.cmake";
  2113. if (cmSystemTools::FileExists(pre_load)) {
  2114. this->ReadListFile(args, pre_load);
  2115. }
  2116. }
  2117. }
  2118. // handle a command line invocation
  2119. int cmake::Run(const std::vector<std::string>& args, bool noconfigure)
  2120. {
  2121. // Process the arguments
  2122. this->SetArgs(args);
  2123. if (cmSystemTools::GetErrorOccuredFlag()) {
  2124. return -1;
  2125. }
  2126. if (this->GetWorkingMode() == HELP_MODE) {
  2127. return 0;
  2128. }
  2129. // Log the trace format version to the desired output
  2130. if (this->GetTrace()) {
  2131. this->PrintTraceFormatVersion();
  2132. }
  2133. // If we are given a stamp list file check if it is really out of date.
  2134. if (!this->CheckStampList.empty() &&
  2135. cmakeCheckStampList(this->CheckStampList)) {
  2136. return 0;
  2137. }
  2138. // If we are given a stamp file check if it is really out of date.
  2139. if (!this->CheckStampFile.empty() &&
  2140. cmakeCheckStampFile(this->CheckStampFile)) {
  2141. return 0;
  2142. }
  2143. if (this->GetWorkingMode() == NORMAL_MODE) {
  2144. // load the cache
  2145. if (this->LoadCache() < 0) {
  2146. cmSystemTools::Error("Error executing cmake::LoadCache(). Aborting.\n");
  2147. return -1;
  2148. }
  2149. } else {
  2150. this->AddCMakePaths();
  2151. }
  2152. #ifndef CMAKE_BOOTSTRAP
  2153. this->ProcessPresetVariables();
  2154. this->ProcessPresetEnvironment();
  2155. #endif
  2156. // Add any cache args
  2157. if (!this->SetCacheArgs(args)) {
  2158. cmSystemTools::Error("Run 'cmake --help' for all supported options.");
  2159. return -1;
  2160. }
  2161. #ifndef CMAKE_BOOTSTRAP
  2162. this->PrintPresetVariables();
  2163. this->PrintPresetEnvironment();
  2164. #endif
  2165. // In script mode we terminate after running the script.
  2166. if (this->GetWorkingMode() != NORMAL_MODE) {
  2167. if (cmSystemTools::GetErrorOccuredFlag()) {
  2168. return -1;
  2169. }
  2170. return 0;
  2171. }
  2172. // If MAKEFLAGS are given in the environment, remove the environment
  2173. // variable. This will prevent try-compile from succeeding when it
  2174. // should fail (if "-i" is an option). We cannot simply test
  2175. // whether "-i" is given and remove it because some make programs
  2176. // encode the MAKEFLAGS variable in a strange way.
  2177. if (cmSystemTools::HasEnv("MAKEFLAGS")) {
  2178. cmSystemTools::PutEnv("MAKEFLAGS=");
  2179. }
  2180. this->PreLoadCMakeFiles();
  2181. if (noconfigure) {
  2182. return 0;
  2183. }
  2184. // now run the global generate
  2185. // Check the state of the build system to see if we need to regenerate.
  2186. if (!this->CheckBuildSystem()) {
  2187. return 0;
  2188. }
  2189. int ret = this->Configure();
  2190. if (ret) {
  2191. #if defined(CMAKE_HAVE_VS_GENERATORS)
  2192. if (!this->VSSolutionFile.empty() && this->GlobalGenerator) {
  2193. // CMake is running to regenerate a Visual Studio build tree
  2194. // during a build from the VS IDE. The build files cannot be
  2195. // regenerated, so we should stop the build.
  2196. cmSystemTools::Message("CMake Configure step failed. "
  2197. "Build files cannot be regenerated correctly. "
  2198. "Attempting to stop IDE build.");
  2199. cmGlobalVisualStudioGenerator& gg =
  2200. cm::static_reference_cast<cmGlobalVisualStudioGenerator>(
  2201. this->GlobalGenerator);
  2202. gg.CallVisualStudioMacro(cmGlobalVisualStudioGenerator::MacroStop,
  2203. this->VSSolutionFile);
  2204. }
  2205. #endif
  2206. return ret;
  2207. }
  2208. ret = this->Generate();
  2209. if (ret) {
  2210. cmSystemTools::Message("CMake Generate step failed. "
  2211. "Build files cannot be regenerated correctly.");
  2212. return ret;
  2213. }
  2214. std::string message = cmStrCat("Build files have been written to: ",
  2215. this->GetHomeOutputDirectory());
  2216. this->UpdateProgress(message, -1);
  2217. return ret;
  2218. }
  2219. int cmake::Generate()
  2220. {
  2221. if (!this->GlobalGenerator) {
  2222. return -1;
  2223. }
  2224. if (!this->GlobalGenerator->Compute()) {
  2225. return -1;
  2226. }
  2227. this->GlobalGenerator->Generate();
  2228. if (!this->GraphVizFile.empty()) {
  2229. std::cout << "Generate graphviz: " << this->GraphVizFile << std::endl;
  2230. this->GenerateGraphViz(this->GraphVizFile);
  2231. }
  2232. if (this->WarnUnusedCli) {
  2233. this->RunCheckForUnusedVariables();
  2234. }
  2235. if (cmSystemTools::GetErrorOccuredFlag()) {
  2236. return -1;
  2237. }
  2238. // Save the cache again after a successful Generate so that any internal
  2239. // variables created during Generate are saved. (Specifically target GUIDs
  2240. // for the Visual Studio and Xcode generators.)
  2241. this->SaveCache(this->GetHomeOutputDirectory());
  2242. #if !defined(CMAKE_BOOTSTRAP)
  2243. this->FileAPI->WriteReplies();
  2244. #endif
  2245. return 0;
  2246. }
  2247. void cmake::AddCacheEntry(const std::string& key, cmValue value,
  2248. const char* helpString, int type)
  2249. {
  2250. this->State->AddCacheEntry(key, value, helpString,
  2251. cmStateEnums::CacheEntryType(type));
  2252. this->UnwatchUnusedCli(key);
  2253. if (key == "CMAKE_WARN_DEPRECATED"_s) {
  2254. this->Messenger->SetSuppressDeprecatedWarnings(value && cmIsOff(value));
  2255. } else if (key == "CMAKE_ERROR_DEPRECATED"_s) {
  2256. this->Messenger->SetDeprecatedWarningsAsErrors(cmIsOn(value));
  2257. } else if (key == "CMAKE_SUPPRESS_DEVELOPER_WARNINGS"_s) {
  2258. this->Messenger->SetSuppressDevWarnings(cmIsOn(value));
  2259. } else if (key == "CMAKE_SUPPRESS_DEVELOPER_ERRORS"_s) {
  2260. this->Messenger->SetDevWarningsAsErrors(value && cmIsOff(value));
  2261. }
  2262. }
  2263. bool cmake::DoWriteGlobVerifyTarget() const
  2264. {
  2265. return this->State->DoWriteGlobVerifyTarget();
  2266. }
  2267. std::string const& cmake::GetGlobVerifyScript() const
  2268. {
  2269. return this->State->GetGlobVerifyScript();
  2270. }
  2271. std::string const& cmake::GetGlobVerifyStamp() const
  2272. {
  2273. return this->State->GetGlobVerifyStamp();
  2274. }
  2275. void cmake::AddGlobCacheEntry(bool recurse, bool listDirectories,
  2276. bool followSymlinks, const std::string& relative,
  2277. const std::string& expression,
  2278. const std::vector<std::string>& files,
  2279. const std::string& variable,
  2280. cmListFileBacktrace const& backtrace)
  2281. {
  2282. this->State->AddGlobCacheEntry(recurse, listDirectories, followSymlinks,
  2283. relative, expression, files, variable,
  2284. backtrace, this->Messenger.get());
  2285. }
  2286. std::vector<std::string> cmake::GetAllExtensions() const
  2287. {
  2288. std::vector<std::string> allExt = this->CLikeSourceFileExtensions.ordered;
  2289. allExt.insert(allExt.end(), this->HeaderFileExtensions.ordered.begin(),
  2290. this->HeaderFileExtensions.ordered.end());
  2291. // cuda extensions are also in SourceFileExtensions so we ignore it here
  2292. allExt.insert(allExt.end(), this->FortranFileExtensions.ordered.begin(),
  2293. this->FortranFileExtensions.ordered.end());
  2294. allExt.insert(allExt.end(), this->HipFileExtensions.ordered.begin(),
  2295. this->HipFileExtensions.ordered.end());
  2296. allExt.insert(allExt.end(), this->ISPCFileExtensions.ordered.begin(),
  2297. this->ISPCFileExtensions.ordered.end());
  2298. return allExt;
  2299. }
  2300. std::string cmake::StripExtension(const std::string& file) const
  2301. {
  2302. auto dotpos = file.rfind('.');
  2303. if (dotpos != std::string::npos) {
  2304. #if defined(_WIN32) || defined(__APPLE__)
  2305. auto ext = cmSystemTools::LowerCase(file.substr(dotpos + 1));
  2306. #else
  2307. auto ext = cm::string_view(file).substr(dotpos + 1);
  2308. #endif
  2309. if (this->IsAKnownExtension(ext)) {
  2310. return file.substr(0, dotpos);
  2311. }
  2312. }
  2313. return file;
  2314. }
  2315. cmValue cmake::GetCacheDefinition(const std::string& name) const
  2316. {
  2317. return this->State->GetInitializedCacheValue(name);
  2318. }
  2319. void cmake::AddScriptingCommands() const
  2320. {
  2321. GetScriptingCommands(this->GetState());
  2322. }
  2323. void cmake::AddProjectCommands() const
  2324. {
  2325. GetProjectCommands(this->GetState());
  2326. }
  2327. void cmake::AddDefaultGenerators()
  2328. {
  2329. #if defined(_WIN32) && !defined(__CYGWIN__)
  2330. # if !defined(CMAKE_BOOT_MINGW)
  2331. this->Generators.push_back(
  2332. cmGlobalVisualStudioVersionedGenerator::NewFactory17());
  2333. this->Generators.push_back(
  2334. cmGlobalVisualStudioVersionedGenerator::NewFactory16());
  2335. this->Generators.push_back(
  2336. cmGlobalVisualStudioVersionedGenerator::NewFactory15());
  2337. this->Generators.push_back(cmGlobalVisualStudio14Generator::NewFactory());
  2338. this->Generators.push_back(cmGlobalVisualStudio12Generator::NewFactory());
  2339. this->Generators.push_back(cmGlobalVisualStudio11Generator::NewFactory());
  2340. this->Generators.push_back(cmGlobalVisualStudio10Generator::NewFactory());
  2341. this->Generators.push_back(cmGlobalVisualStudio9Generator::NewFactory());
  2342. this->Generators.push_back(cmGlobalBorlandMakefileGenerator::NewFactory());
  2343. this->Generators.push_back(cmGlobalNMakeMakefileGenerator::NewFactory());
  2344. this->Generators.push_back(cmGlobalJOMMakefileGenerator::NewFactory());
  2345. # endif
  2346. this->Generators.push_back(cmGlobalMSYSMakefileGenerator::NewFactory());
  2347. this->Generators.push_back(cmGlobalMinGWMakefileGenerator::NewFactory());
  2348. #endif
  2349. #if !defined(CMAKE_BOOTSTRAP)
  2350. # if (defined(__linux__) && !defined(__ANDROID__)) || defined(_WIN32)
  2351. this->Generators.push_back(cmGlobalGhsMultiGenerator::NewFactory());
  2352. # endif
  2353. this->Generators.push_back(cmGlobalUnixMakefileGenerator3::NewFactory());
  2354. this->Generators.push_back(cmGlobalNinjaGenerator::NewFactory());
  2355. this->Generators.push_back(cmGlobalNinjaMultiGenerator::NewFactory());
  2356. #elif defined(CMAKE_BOOTSTRAP_NINJA)
  2357. this->Generators.push_back(cmGlobalNinjaGenerator::NewFactory());
  2358. #elif defined(CMAKE_BOOTSTRAP_MAKEFILES)
  2359. this->Generators.push_back(cmGlobalUnixMakefileGenerator3::NewFactory());
  2360. #endif
  2361. #if defined(CMAKE_USE_WMAKE)
  2362. this->Generators.push_back(cmGlobalWatcomWMakeGenerator::NewFactory());
  2363. #endif
  2364. #ifdef CMAKE_USE_XCODE
  2365. this->Generators.push_back(cmGlobalXCodeGenerator::NewFactory());
  2366. #endif
  2367. }
  2368. bool cmake::ParseCacheEntry(const std::string& entry, std::string& var,
  2369. std::string& value,
  2370. cmStateEnums::CacheEntryType& type)
  2371. {
  2372. return cmState::ParseCacheEntry(entry, var, value, type);
  2373. }
  2374. int cmake::LoadCache()
  2375. {
  2376. // could we not read the cache
  2377. if (!this->LoadCache(this->GetHomeOutputDirectory())) {
  2378. // if it does exist, but isn't readable then warn the user
  2379. std::string cacheFile =
  2380. cmStrCat(this->GetHomeOutputDirectory(), "/CMakeCache.txt");
  2381. if (cmSystemTools::FileExists(cacheFile)) {
  2382. cmSystemTools::Error(
  2383. "There is a CMakeCache.txt file for the current binary tree but "
  2384. "cmake does not have permission to read it. Please check the "
  2385. "permissions of the directory you are trying to run CMake on.");
  2386. return -1;
  2387. }
  2388. }
  2389. // setup CMAKE_ROOT and CMAKE_COMMAND
  2390. if (!this->AddCMakePaths()) {
  2391. return -3;
  2392. }
  2393. return 0;
  2394. }
  2395. bool cmake::LoadCache(const std::string& path)
  2396. {
  2397. std::set<std::string> emptySet;
  2398. return this->LoadCache(path, true, emptySet, emptySet);
  2399. }
  2400. bool cmake::LoadCache(const std::string& path, bool internal,
  2401. std::set<std::string>& excludes,
  2402. std::set<std::string>& includes)
  2403. {
  2404. bool result = this->State->LoadCache(path, internal, excludes, includes);
  2405. static const auto entries = { "CMAKE_CACHE_MAJOR_VERSION",
  2406. "CMAKE_CACHE_MINOR_VERSION" };
  2407. for (auto const& entry : entries) {
  2408. this->UnwatchUnusedCli(entry);
  2409. }
  2410. return result;
  2411. }
  2412. bool cmake::SaveCache(const std::string& path)
  2413. {
  2414. bool result = this->State->SaveCache(path, this->GetMessenger());
  2415. static const auto entries = { "CMAKE_CACHE_MAJOR_VERSION",
  2416. "CMAKE_CACHE_MINOR_VERSION",
  2417. "CMAKE_CACHE_PATCH_VERSION",
  2418. "CMAKE_CACHEFILE_DIR" };
  2419. for (auto const& entry : entries) {
  2420. this->UnwatchUnusedCli(entry);
  2421. }
  2422. return result;
  2423. }
  2424. bool cmake::DeleteCache(const std::string& path)
  2425. {
  2426. return this->State->DeleteCache(path);
  2427. }
  2428. void cmake::SetProgressCallback(ProgressCallbackType f)
  2429. {
  2430. this->ProgressCallback = std::move(f);
  2431. }
  2432. void cmake::UpdateProgress(const std::string& msg, float prog)
  2433. {
  2434. if (this->ProgressCallback && !this->GetIsInTryCompile()) {
  2435. this->ProgressCallback(msg, prog);
  2436. }
  2437. }
  2438. bool cmake::GetIsInTryCompile() const
  2439. {
  2440. return this->State->GetProjectKind() == cmState::ProjectKind::TryCompile;
  2441. }
  2442. void cmake::AppendGlobalGeneratorsDocumentation(
  2443. std::vector<cmDocumentationEntry>& v)
  2444. {
  2445. const auto defaultGenerator = this->EvaluateDefaultGlobalGenerator();
  2446. const std::string defaultName = defaultGenerator->GetName();
  2447. bool foundDefaultOne = false;
  2448. for (const auto& g : this->Generators) {
  2449. cmDocumentationEntry e;
  2450. g->GetDocumentation(e);
  2451. if (!foundDefaultOne && cmHasPrefix(e.Name, defaultName)) {
  2452. e.CustomNamePrefix = '*';
  2453. foundDefaultOne = true;
  2454. }
  2455. v.push_back(std::move(e));
  2456. }
  2457. }
  2458. void cmake::AppendExtraGeneratorsDocumentation(
  2459. std::vector<cmDocumentationEntry>& v)
  2460. {
  2461. for (cmExternalMakefileProjectGeneratorFactory* eg : this->ExtraGenerators) {
  2462. const std::string doc = eg->GetDocumentation();
  2463. const std::string name = eg->GetName();
  2464. // Aliases:
  2465. for (std::string const& a : eg->Aliases) {
  2466. cmDocumentationEntry e;
  2467. e.Name = a;
  2468. e.Brief = doc;
  2469. v.push_back(std::move(e));
  2470. }
  2471. // Full names:
  2472. const std::vector<std::string> generators =
  2473. eg->GetSupportedGlobalGenerators();
  2474. for (std::string const& g : generators) {
  2475. cmDocumentationEntry e;
  2476. e.Name =
  2477. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(g, name);
  2478. e.Brief = doc;
  2479. v.push_back(std::move(e));
  2480. }
  2481. }
  2482. }
  2483. std::vector<cmDocumentationEntry> cmake::GetGeneratorsDocumentation()
  2484. {
  2485. std::vector<cmDocumentationEntry> v;
  2486. this->AppendGlobalGeneratorsDocumentation(v);
  2487. this->AppendExtraGeneratorsDocumentation(v);
  2488. return v;
  2489. }
  2490. void cmake::PrintGeneratorList()
  2491. {
  2492. #ifndef CMAKE_BOOTSTRAP
  2493. cmDocumentation doc;
  2494. auto generators = this->GetGeneratorsDocumentation();
  2495. doc.AppendSection("Generators", generators);
  2496. std::cerr << "\n";
  2497. doc.PrintDocumentation(cmDocumentation::ListGenerators, std::cerr);
  2498. #endif
  2499. }
  2500. void cmake::UpdateConversionPathTable()
  2501. {
  2502. // Update the path conversion table with any specified file:
  2503. cmValue tablepath =
  2504. this->State->GetInitializedCacheValue("CMAKE_PATH_TRANSLATION_FILE");
  2505. if (tablepath) {
  2506. cmsys::ifstream table(tablepath->c_str());
  2507. if (!table) {
  2508. cmSystemTools::Error("CMAKE_PATH_TRANSLATION_FILE set to " + *tablepath +
  2509. ". CMake can not open file.");
  2510. cmSystemTools::ReportLastSystemError("CMake can not open file.");
  2511. } else {
  2512. std::string a;
  2513. std::string b;
  2514. while (!table.eof()) {
  2515. // two entries per line
  2516. table >> a;
  2517. table >> b;
  2518. cmSystemTools::AddTranslationPath(a, b);
  2519. }
  2520. }
  2521. }
  2522. }
  2523. int cmake::CheckBuildSystem()
  2524. {
  2525. // We do not need to rerun CMake. Check dependency integrity.
  2526. const bool verbose = isCMakeVerbose();
  2527. // This method will check the integrity of the build system if the
  2528. // option was given on the command line. It reads the given file to
  2529. // determine whether CMake should rerun.
  2530. // If no file is provided for the check, we have to rerun.
  2531. if (this->CheckBuildSystemArgument.empty()) {
  2532. if (verbose) {
  2533. cmSystemTools::Stdout("Re-run cmake no build system arguments\n");
  2534. }
  2535. return 1;
  2536. }
  2537. // If the file provided does not exist, we have to rerun.
  2538. if (!cmSystemTools::FileExists(this->CheckBuildSystemArgument)) {
  2539. if (verbose) {
  2540. std::ostringstream msg;
  2541. msg << "Re-run cmake missing file: " << this->CheckBuildSystemArgument
  2542. << "\n";
  2543. cmSystemTools::Stdout(msg.str());
  2544. }
  2545. return 1;
  2546. }
  2547. // Read the rerun check file and use it to decide whether to do the
  2548. // global generate.
  2549. // Actually, all we need is the `set` command.
  2550. cmake cm(RoleScript, cmState::Unknown);
  2551. cm.SetHomeDirectory("");
  2552. cm.SetHomeOutputDirectory("");
  2553. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  2554. cmGlobalGenerator gg(&cm);
  2555. cmMakefile mf(&gg, cm.GetCurrentSnapshot());
  2556. if (!mf.ReadListFile(this->CheckBuildSystemArgument) ||
  2557. cmSystemTools::GetErrorOccuredFlag()) {
  2558. if (verbose) {
  2559. std::ostringstream msg;
  2560. msg << "Re-run cmake error reading : " << this->CheckBuildSystemArgument
  2561. << "\n";
  2562. cmSystemTools::Stdout(msg.str());
  2563. }
  2564. // There was an error reading the file. Just rerun.
  2565. return 1;
  2566. }
  2567. if (this->ClearBuildSystem) {
  2568. // Get the generator used for this build system.
  2569. std::string genName = mf.GetSafeDefinition("CMAKE_DEPENDS_GENERATOR");
  2570. if (!cmNonempty(genName)) {
  2571. genName = "Unix Makefiles";
  2572. }
  2573. // Create the generator and use it to clear the dependencies.
  2574. std::unique_ptr<cmGlobalGenerator> ggd =
  2575. this->CreateGlobalGenerator(genName);
  2576. if (ggd) {
  2577. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  2578. cmMakefile mfd(ggd.get(), cm.GetCurrentSnapshot());
  2579. auto lgd = ggd->CreateLocalGenerator(&mfd);
  2580. lgd->ClearDependencies(&mfd, verbose);
  2581. }
  2582. }
  2583. // If any byproduct of makefile generation is missing we must re-run.
  2584. std::vector<std::string> products;
  2585. mf.GetDefExpandList("CMAKE_MAKEFILE_PRODUCTS", products);
  2586. for (std::string const& p : products) {
  2587. if (!(cmSystemTools::FileExists(p) || cmSystemTools::FileIsSymlink(p))) {
  2588. if (verbose) {
  2589. std::ostringstream msg;
  2590. msg << "Re-run cmake, missing byproduct: " << p << "\n";
  2591. cmSystemTools::Stdout(msg.str());
  2592. }
  2593. return 1;
  2594. }
  2595. }
  2596. // Get the set of dependencies and outputs.
  2597. std::vector<std::string> depends;
  2598. std::vector<std::string> outputs;
  2599. if (mf.GetDefExpandList("CMAKE_MAKEFILE_DEPENDS", depends)) {
  2600. mf.GetDefExpandList("CMAKE_MAKEFILE_OUTPUTS", outputs);
  2601. }
  2602. if (depends.empty() || outputs.empty()) {
  2603. // Not enough information was provided to do the test. Just rerun.
  2604. if (verbose) {
  2605. cmSystemTools::Stdout("Re-run cmake no CMAKE_MAKEFILE_DEPENDS "
  2606. "or CMAKE_MAKEFILE_OUTPUTS :\n");
  2607. }
  2608. return 1;
  2609. }
  2610. // Find the newest dependency.
  2611. auto dep = depends.begin();
  2612. std::string dep_newest = *dep++;
  2613. for (; dep != depends.end(); ++dep) {
  2614. int result = 0;
  2615. if (this->FileTimeCache->Compare(dep_newest, *dep, &result)) {
  2616. if (result < 0) {
  2617. dep_newest = *dep;
  2618. }
  2619. } else {
  2620. if (verbose) {
  2621. cmSystemTools::Stdout(
  2622. "Re-run cmake: build system dependency is missing\n");
  2623. }
  2624. return 1;
  2625. }
  2626. }
  2627. // Find the oldest output.
  2628. auto out = outputs.begin();
  2629. std::string out_oldest = *out++;
  2630. for (; out != outputs.end(); ++out) {
  2631. int result = 0;
  2632. if (this->FileTimeCache->Compare(out_oldest, *out, &result)) {
  2633. if (result > 0) {
  2634. out_oldest = *out;
  2635. }
  2636. } else {
  2637. if (verbose) {
  2638. cmSystemTools::Stdout(
  2639. "Re-run cmake: build system output is missing\n");
  2640. }
  2641. return 1;
  2642. }
  2643. }
  2644. // If any output is older than any dependency then rerun.
  2645. {
  2646. int result = 0;
  2647. if (!this->FileTimeCache->Compare(out_oldest, dep_newest, &result) ||
  2648. result < 0) {
  2649. if (verbose) {
  2650. std::ostringstream msg;
  2651. msg << "Re-run cmake file: " << out_oldest
  2652. << " older than: " << dep_newest << "\n";
  2653. cmSystemTools::Stdout(msg.str());
  2654. }
  2655. return 1;
  2656. }
  2657. }
  2658. // No need to rerun.
  2659. return 0;
  2660. }
  2661. void cmake::TruncateOutputLog(const char* fname)
  2662. {
  2663. std::string fullPath = cmStrCat(this->GetHomeOutputDirectory(), '/', fname);
  2664. struct stat st;
  2665. if (::stat(fullPath.c_str(), &st)) {
  2666. return;
  2667. }
  2668. if (!this->State->GetInitializedCacheValue("CMAKE_CACHEFILE_DIR")) {
  2669. cmSystemTools::RemoveFile(fullPath);
  2670. return;
  2671. }
  2672. off_t fsize = st.st_size;
  2673. const off_t maxFileSize = 50 * 1024;
  2674. if (fsize < maxFileSize) {
  2675. // TODO: truncate file
  2676. return;
  2677. }
  2678. }
  2679. void cmake::MarkCliAsUsed(const std::string& variable)
  2680. {
  2681. this->UsedCliVariables[variable] = true;
  2682. }
  2683. void cmake::GenerateGraphViz(const std::string& fileName) const
  2684. {
  2685. #ifndef CMAKE_BOOTSTRAP
  2686. cmGraphVizWriter gvWriter(fileName, this->GetGlobalGenerator());
  2687. std::string settingsFile =
  2688. cmStrCat(this->GetHomeOutputDirectory(), "/CMakeGraphVizOptions.cmake");
  2689. std::string fallbackSettingsFile =
  2690. cmStrCat(this->GetHomeDirectory(), "/CMakeGraphVizOptions.cmake");
  2691. gvWriter.ReadSettings(settingsFile, fallbackSettingsFile);
  2692. gvWriter.Write();
  2693. #endif
  2694. }
  2695. void cmake::SetProperty(const std::string& prop, const char* value)
  2696. {
  2697. this->State->SetGlobalProperty(prop, value);
  2698. }
  2699. void cmake::SetProperty(const std::string& prop, cmValue value)
  2700. {
  2701. this->State->SetGlobalProperty(prop, value);
  2702. }
  2703. void cmake::AppendProperty(const std::string& prop, const std::string& value,
  2704. bool asString)
  2705. {
  2706. this->State->AppendGlobalProperty(prop, value, asString);
  2707. }
  2708. cmValue cmake::GetProperty(const std::string& prop)
  2709. {
  2710. return this->State->GetGlobalProperty(prop);
  2711. }
  2712. bool cmake::GetPropertyAsBool(const std::string& prop)
  2713. {
  2714. return this->State->GetGlobalPropertyAsBool(prop);
  2715. }
  2716. cmInstalledFile* cmake::GetOrCreateInstalledFile(cmMakefile* mf,
  2717. const std::string& name)
  2718. {
  2719. auto i = this->InstalledFiles.find(name);
  2720. if (i != this->InstalledFiles.end()) {
  2721. cmInstalledFile& file = i->second;
  2722. return &file;
  2723. }
  2724. cmInstalledFile& file = this->InstalledFiles[name];
  2725. file.SetName(mf, name);
  2726. return &file;
  2727. }
  2728. cmInstalledFile const* cmake::GetInstalledFile(const std::string& name) const
  2729. {
  2730. auto i = this->InstalledFiles.find(name);
  2731. if (i != this->InstalledFiles.end()) {
  2732. cmInstalledFile const& file = i->second;
  2733. return &file;
  2734. }
  2735. return nullptr;
  2736. }
  2737. int cmake::GetSystemInformation(std::vector<std::string>& args)
  2738. {
  2739. // so create the directory
  2740. std::string resultFile;
  2741. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  2742. std::string destPath = cwd + "/__cmake_systeminformation";
  2743. cmSystemTools::RemoveADirectory(destPath);
  2744. if (!cmSystemTools::MakeDirectory(destPath)) {
  2745. std::cerr << "Error: --system-information must be run from a "
  2746. "writable directory!\n";
  2747. return 1;
  2748. }
  2749. // process the arguments
  2750. bool writeToStdout = true;
  2751. for (unsigned int i = 1; i < args.size(); ++i) {
  2752. std::string const& arg = args[i];
  2753. if (cmHasLiteralPrefix(arg, "-G")) {
  2754. std::string value = arg.substr(2);
  2755. if (value.empty()) {
  2756. ++i;
  2757. if (i >= args.size()) {
  2758. cmSystemTools::Error("No generator specified for -G");
  2759. this->PrintGeneratorList();
  2760. return -1;
  2761. }
  2762. value = args[i];
  2763. }
  2764. auto gen = this->CreateGlobalGenerator(value);
  2765. if (!gen) {
  2766. cmSystemTools::Error("Could not create named generator " + value);
  2767. this->PrintGeneratorList();
  2768. } else {
  2769. this->SetGlobalGenerator(std::move(gen));
  2770. }
  2771. }
  2772. // no option assume it is the output file
  2773. else {
  2774. if (!cmSystemTools::FileIsFullPath(arg)) {
  2775. resultFile = cmStrCat(cwd, '/');
  2776. }
  2777. resultFile += arg;
  2778. writeToStdout = false;
  2779. }
  2780. }
  2781. // we have to find the module directory, so we can copy the files
  2782. this->AddCMakePaths();
  2783. std::string modulesPath =
  2784. cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules");
  2785. std::string inFile = cmStrCat(modulesPath, "/SystemInformation.cmake");
  2786. std::string outFile = cmStrCat(destPath, "/CMakeLists.txt");
  2787. // Copy file
  2788. if (!cmsys::SystemTools::CopyFileAlways(inFile, outFile)) {
  2789. std::cerr << "Error copying file \"" << inFile << "\" to \"" << outFile
  2790. << "\".\n";
  2791. return 1;
  2792. }
  2793. // do we write to a file or to stdout?
  2794. if (resultFile.empty()) {
  2795. resultFile = cmStrCat(cwd, "/__cmake_systeminformation/results.txt");
  2796. }
  2797. {
  2798. // now run cmake on the CMakeLists file
  2799. cmWorkingDirectory workdir(destPath);
  2800. if (workdir.Failed()) {
  2801. // We created the directory and we were able to copy the CMakeLists.txt
  2802. // file to it, so we wouldn't expect to get here unless the default
  2803. // permissions are questionable or some other process has deleted the
  2804. // directory
  2805. std::cerr << "Failed to change to directory " << destPath << " : "
  2806. << std::strerror(workdir.GetLastResult()) << std::endl;
  2807. return 1;
  2808. }
  2809. std::vector<std::string> args2;
  2810. args2.push_back(args[0]);
  2811. args2.push_back(destPath);
  2812. args2.push_back("-DRESULT_FILE=" + resultFile);
  2813. int res = this->Run(args2, false);
  2814. if (res != 0) {
  2815. std::cerr << "Error: --system-information failed on internal CMake!\n";
  2816. return res;
  2817. }
  2818. }
  2819. // echo results to stdout if needed
  2820. if (writeToStdout) {
  2821. FILE* fin = cmsys::SystemTools::Fopen(resultFile, "r");
  2822. if (fin) {
  2823. const int bufferSize = 4096;
  2824. char buffer[bufferSize];
  2825. size_t n;
  2826. while ((n = fread(buffer, 1, bufferSize, fin)) > 0) {
  2827. for (char* c = buffer; c < buffer + n; ++c) {
  2828. putc(*c, stdout);
  2829. }
  2830. fflush(stdout);
  2831. }
  2832. fclose(fin);
  2833. }
  2834. }
  2835. // clean up the directory
  2836. cmSystemTools::RemoveADirectory(destPath);
  2837. return 0;
  2838. }
  2839. static bool cmakeCheckStampFile(const std::string& stampName)
  2840. {
  2841. // The stamp file does not exist. Use the stamp dependencies to
  2842. // determine whether it is really out of date. This works in
  2843. // conjunction with cmLocalVisualStudio7Generator to avoid
  2844. // repeatedly re-running CMake when the user rebuilds the entire
  2845. // solution.
  2846. std::string stampDepends = cmStrCat(stampName, ".depend");
  2847. #if defined(_WIN32) || defined(__CYGWIN__)
  2848. cmsys::ifstream fin(stampDepends.c_str(), std::ios::in | std::ios::binary);
  2849. #else
  2850. cmsys::ifstream fin(stampDepends.c_str());
  2851. #endif
  2852. if (!fin) {
  2853. // The stamp dependencies file cannot be read. Just assume the
  2854. // build system is really out of date.
  2855. std::cout << "CMake is re-running because " << stampName
  2856. << " dependency file is missing.\n";
  2857. return false;
  2858. }
  2859. // Compare the stamp dependencies against the dependency file itself.
  2860. {
  2861. cmFileTimeCache ftc;
  2862. std::string dep;
  2863. while (cmSystemTools::GetLineFromStream(fin, dep)) {
  2864. int result;
  2865. if (!dep.empty() && dep[0] != '#' &&
  2866. (!ftc.Compare(stampDepends, dep, &result) || result < 0)) {
  2867. // The stamp depends file is older than this dependency. The
  2868. // build system is really out of date.
  2869. std::cout << "CMake is re-running because " << stampName
  2870. << " is out-of-date.\n";
  2871. std::cout << " the file '" << dep << "'\n";
  2872. std::cout << " is newer than '" << stampDepends << "'\n";
  2873. std::cout << " result='" << result << "'\n";
  2874. return false;
  2875. }
  2876. }
  2877. }
  2878. // The build system is up to date. The stamp file has been removed
  2879. // by the VS IDE due to a "rebuild" request. Restore it atomically.
  2880. std::ostringstream stampTempStream;
  2881. stampTempStream << stampName << ".tmp" << cmSystemTools::RandomSeed();
  2882. std::string stampTemp = stampTempStream.str();
  2883. {
  2884. // TODO: Teach cmGeneratedFileStream to use a random temp file (with
  2885. // multiple tries in unlikely case of conflict) and use that here.
  2886. cmsys::ofstream stamp(stampTemp.c_str());
  2887. stamp << "# CMake generation timestamp file for this directory.\n";
  2888. }
  2889. std::string err;
  2890. if (cmSystemTools::RenameFile(stampTemp, stampName,
  2891. cmSystemTools::Replace::Yes, &err) ==
  2892. cmSystemTools::RenameResult::Success) {
  2893. // CMake does not need to re-run because the stamp file is up-to-date.
  2894. return true;
  2895. }
  2896. cmSystemTools::RemoveFile(stampTemp);
  2897. cmSystemTools::Error(
  2898. cmStrCat("Cannot restore timestamp \"", stampName, "\": ", err));
  2899. return false;
  2900. }
  2901. static bool cmakeCheckStampList(const std::string& stampList)
  2902. {
  2903. // If the stamp list does not exist CMake must rerun to generate it.
  2904. if (!cmSystemTools::FileExists(stampList)) {
  2905. std::cout << "CMake is re-running because generate.stamp.list "
  2906. << "is missing.\n";
  2907. return false;
  2908. }
  2909. cmsys::ifstream fin(stampList.c_str());
  2910. if (!fin) {
  2911. std::cout << "CMake is re-running because generate.stamp.list "
  2912. << "could not be read.\n";
  2913. return false;
  2914. }
  2915. // Check each stamp.
  2916. std::string stampName;
  2917. while (cmSystemTools::GetLineFromStream(fin, stampName)) {
  2918. if (!cmakeCheckStampFile(stampName)) {
  2919. return false;
  2920. }
  2921. }
  2922. return true;
  2923. }
  2924. void cmake::IssueMessage(MessageType t, std::string const& text,
  2925. cmListFileBacktrace const& backtrace) const
  2926. {
  2927. this->Messenger->IssueMessage(t, text, backtrace);
  2928. }
  2929. std::vector<std::string> cmake::GetDebugConfigs()
  2930. {
  2931. std::vector<std::string> configs;
  2932. if (cmValue config_list =
  2933. this->State->GetGlobalProperty("DEBUG_CONFIGURATIONS")) {
  2934. // Expand the specified list and convert to upper-case.
  2935. cmExpandList(*config_list, configs);
  2936. std::transform(configs.begin(), configs.end(), configs.begin(),
  2937. cmSystemTools::UpperCase);
  2938. }
  2939. // If no configurations were specified, use a default list.
  2940. if (configs.empty()) {
  2941. configs.emplace_back("DEBUG");
  2942. }
  2943. return configs;
  2944. }
  2945. int cmake::Build(int jobs, std::string dir, std::vector<std::string> targets,
  2946. std::string config, std::vector<std::string> nativeOptions,
  2947. cmBuildOptions& buildOptions, bool verbose,
  2948. const std::string& presetName, bool listPresets)
  2949. {
  2950. this->SetHomeDirectory("");
  2951. this->SetHomeOutputDirectory("");
  2952. #if !defined(CMAKE_BOOTSTRAP)
  2953. if (!presetName.empty() || listPresets) {
  2954. this->SetHomeDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  2955. this->SetHomeOutputDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  2956. cmCMakePresetsGraph settingsFile;
  2957. auto result = settingsFile.ReadProjectPresets(this->GetHomeDirectory());
  2958. if (result != cmCMakePresetsGraph::ReadFileResult::READ_OK) {
  2959. cmSystemTools::Error(
  2960. cmStrCat("Could not read presets from ", this->GetHomeDirectory(),
  2961. ": ", cmCMakePresetsGraph::ResultToString(result)));
  2962. return 1;
  2963. }
  2964. if (listPresets) {
  2965. settingsFile.PrintBuildPresetList();
  2966. return 0;
  2967. }
  2968. auto presetPair = settingsFile.BuildPresets.find(presetName);
  2969. if (presetPair == settingsFile.BuildPresets.end()) {
  2970. cmSystemTools::Error(cmStrCat("No such build preset in ",
  2971. this->GetHomeDirectory(), ": \"",
  2972. presetName, '"'));
  2973. settingsFile.PrintBuildPresetList();
  2974. return 1;
  2975. }
  2976. if (presetPair->second.Unexpanded.Hidden) {
  2977. cmSystemTools::Error(cmStrCat("Cannot use hidden build preset in ",
  2978. this->GetHomeDirectory(), ": \"",
  2979. presetName, '"'));
  2980. settingsFile.PrintBuildPresetList();
  2981. return 1;
  2982. }
  2983. auto const& expandedPreset = presetPair->second.Expanded;
  2984. if (!expandedPreset) {
  2985. cmSystemTools::Error(cmStrCat("Could not evaluate build preset \"",
  2986. presetName,
  2987. "\": Invalid macro expansion"));
  2988. settingsFile.PrintBuildPresetList();
  2989. return 1;
  2990. }
  2991. if (!expandedPreset->ConditionResult) {
  2992. cmSystemTools::Error(cmStrCat("Cannot use disabled build preset in ",
  2993. this->GetHomeDirectory(), ": \"",
  2994. presetName, '"'));
  2995. settingsFile.PrintBuildPresetList();
  2996. return 1;
  2997. }
  2998. auto configurePresetPair =
  2999. settingsFile.ConfigurePresets.find(expandedPreset->ConfigurePreset);
  3000. if (configurePresetPair == settingsFile.ConfigurePresets.end()) {
  3001. cmSystemTools::Error(cmStrCat("No such configure preset in ",
  3002. this->GetHomeDirectory(), ": \"",
  3003. expandedPreset->ConfigurePreset, '"'));
  3004. this->PrintPresetList(settingsFile);
  3005. return 1;
  3006. }
  3007. if (configurePresetPair->second.Unexpanded.Hidden) {
  3008. cmSystemTools::Error(cmStrCat("Cannot use hidden configure preset in ",
  3009. this->GetHomeDirectory(), ": \"",
  3010. expandedPreset->ConfigurePreset, '"'));
  3011. this->PrintPresetList(settingsFile);
  3012. return 1;
  3013. }
  3014. auto const& expandedConfigurePreset = configurePresetPair->second.Expanded;
  3015. if (!expandedConfigurePreset) {
  3016. cmSystemTools::Error(cmStrCat("Could not evaluate configure preset \"",
  3017. expandedPreset->ConfigurePreset,
  3018. "\": Invalid macro expansion"));
  3019. return 1;
  3020. }
  3021. if (!expandedConfigurePreset->BinaryDir.empty()) {
  3022. dir = expandedConfigurePreset->BinaryDir;
  3023. }
  3024. this->UnprocessedPresetEnvironment = expandedPreset->Environment;
  3025. this->ProcessPresetEnvironment();
  3026. if ((jobs == cmake::DEFAULT_BUILD_PARALLEL_LEVEL ||
  3027. jobs == cmake::NO_BUILD_PARALLEL_LEVEL) &&
  3028. expandedPreset->Jobs) {
  3029. jobs = *expandedPreset->Jobs;
  3030. }
  3031. if (targets.empty()) {
  3032. targets.insert(targets.begin(), expandedPreset->Targets.begin(),
  3033. expandedPreset->Targets.end());
  3034. }
  3035. if (config.empty()) {
  3036. config = expandedPreset->Configuration;
  3037. }
  3038. if (!buildOptions.Clean && expandedPreset->CleanFirst) {
  3039. buildOptions.Clean = *expandedPreset->CleanFirst;
  3040. }
  3041. if (expandedPreset->ResolvePackageReferences) {
  3042. buildOptions.ResolveMode = *expandedPreset->ResolvePackageReferences;
  3043. }
  3044. if (!verbose && expandedPreset->Verbose) {
  3045. verbose = *expandedPreset->Verbose;
  3046. }
  3047. if (nativeOptions.empty()) {
  3048. nativeOptions.insert(nativeOptions.begin(),
  3049. expandedPreset->NativeToolOptions.begin(),
  3050. expandedPreset->NativeToolOptions.end());
  3051. }
  3052. }
  3053. #endif
  3054. if (!cmSystemTools::FileIsDirectory(dir)) {
  3055. std::cerr << "Error: " << dir << " is not a directory\n";
  3056. return 1;
  3057. }
  3058. std::string cachePath = FindCacheFile(dir);
  3059. if (!this->LoadCache(cachePath)) {
  3060. std::cerr << "Error: could not load cache\n";
  3061. return 1;
  3062. }
  3063. cmValue cachedGenerator = this->State->GetCacheEntryValue("CMAKE_GENERATOR");
  3064. if (!cachedGenerator) {
  3065. std::cerr << "Error: could not find CMAKE_GENERATOR in Cache\n";
  3066. return 1;
  3067. }
  3068. auto gen = this->CreateGlobalGenerator(*cachedGenerator);
  3069. if (!gen) {
  3070. std::cerr << "Error: could not create CMAKE_GENERATOR \""
  3071. << *cachedGenerator << "\"\n";
  3072. return 1;
  3073. }
  3074. this->SetGlobalGenerator(std::move(gen));
  3075. cmValue cachedGeneratorInstance =
  3076. this->State->GetCacheEntryValue("CMAKE_GENERATOR_INSTANCE");
  3077. if (cachedGeneratorInstance) {
  3078. cmMakefile mf(this->GetGlobalGenerator(), this->GetCurrentSnapshot());
  3079. if (!this->GlobalGenerator->SetGeneratorInstance(*cachedGeneratorInstance,
  3080. &mf)) {
  3081. return 1;
  3082. }
  3083. }
  3084. cmValue cachedGeneratorPlatform =
  3085. this->State->GetCacheEntryValue("CMAKE_GENERATOR_PLATFORM");
  3086. if (cachedGeneratorPlatform) {
  3087. cmMakefile mf(this->GetGlobalGenerator(), this->GetCurrentSnapshot());
  3088. if (!this->GlobalGenerator->SetGeneratorPlatform(*cachedGeneratorPlatform,
  3089. &mf)) {
  3090. return 1;
  3091. }
  3092. }
  3093. cmValue cachedGeneratorToolset =
  3094. this->State->GetCacheEntryValue("CMAKE_GENERATOR_TOOLSET");
  3095. if (cachedGeneratorToolset) {
  3096. cmMakefile mf(this->GetGlobalGenerator(), this->GetCurrentSnapshot());
  3097. if (!this->GlobalGenerator->SetGeneratorToolset(*cachedGeneratorToolset,
  3098. true, &mf)) {
  3099. return 1;
  3100. }
  3101. }
  3102. std::string output;
  3103. std::string projName;
  3104. cmValue cachedProjectName =
  3105. this->State->GetCacheEntryValue("CMAKE_PROJECT_NAME");
  3106. if (!cachedProjectName) {
  3107. std::cerr << "Error: could not find CMAKE_PROJECT_NAME in Cache\n";
  3108. return 1;
  3109. }
  3110. projName = *cachedProjectName;
  3111. if (cmIsOn(this->State->GetCacheEntryValue("CMAKE_VERBOSE_MAKEFILE"))) {
  3112. verbose = true;
  3113. }
  3114. #ifdef CMAKE_HAVE_VS_GENERATORS
  3115. // For VS generators, explicitly check if regeneration is necessary before
  3116. // actually starting the build. If not done separately from the build
  3117. // itself, there is the risk of building an out-of-date solution file due
  3118. // to limitations of the underlying build system.
  3119. std::string const stampList = cachePath + "/" + "CMakeFiles/" +
  3120. cmGlobalVisualStudio9Generator::GetGenerateStampList();
  3121. // Note that the stampList file only exists for VS generators.
  3122. if (cmSystemTools::FileExists(stampList)) {
  3123. // Check if running for Visual Studio 9 - we need to explicitly run
  3124. // the glob verification script before starting the build
  3125. this->AddScriptingCommands();
  3126. if (this->GlobalGenerator->MatchesGeneratorName("Visual Studio 9 2008")) {
  3127. std::string const globVerifyScript =
  3128. cachePath + "/" + "CMakeFiles/" + "VerifyGlobs.cmake";
  3129. if (cmSystemTools::FileExists(globVerifyScript)) {
  3130. std::vector<std::string> args;
  3131. this->ReadListFile(args, globVerifyScript);
  3132. }
  3133. }
  3134. if (!cmakeCheckStampList(stampList)) {
  3135. // Correctly initialize the home (=source) and home output (=binary)
  3136. // directories, which is required for running the generation step.
  3137. std::string homeOrig = this->GetHomeDirectory();
  3138. std::string homeOutputOrig = this->GetHomeOutputDirectory();
  3139. this->SetDirectoriesFromFile(cachePath);
  3140. this->AddProjectCommands();
  3141. int ret = this->Configure();
  3142. if (ret) {
  3143. cmSystemTools::Message("CMake Configure step failed. "
  3144. "Build files cannot be regenerated correctly.");
  3145. return ret;
  3146. }
  3147. ret = this->Generate();
  3148. if (ret) {
  3149. cmSystemTools::Message("CMake Generate step failed. "
  3150. "Build files cannot be regenerated correctly.");
  3151. return ret;
  3152. }
  3153. std::string message = cmStrCat("Build files have been written to: ",
  3154. this->GetHomeOutputDirectory());
  3155. this->UpdateProgress(message, -1);
  3156. // Restore the previously set directories to their original value.
  3157. this->SetHomeDirectory(homeOrig);
  3158. this->SetHomeOutputDirectory(homeOutputOrig);
  3159. }
  3160. }
  3161. #endif
  3162. if (!this->GlobalGenerator->ReadCacheEntriesForBuild(*this->State)) {
  3163. return 1;
  3164. }
  3165. this->GlobalGenerator->PrintBuildCommandAdvice(std::cerr, jobs);
  3166. return this->GlobalGenerator->Build(
  3167. jobs, "", dir, projName, targets, output, "", config, buildOptions,
  3168. verbose, cmDuration::zero(), cmSystemTools::OUTPUT_PASSTHROUGH,
  3169. nativeOptions);
  3170. }
  3171. bool cmake::Open(const std::string& dir, bool dryRun)
  3172. {
  3173. this->SetHomeDirectory("");
  3174. this->SetHomeOutputDirectory("");
  3175. if (!cmSystemTools::FileIsDirectory(dir)) {
  3176. std::cerr << "Error: " << dir << " is not a directory\n";
  3177. return false;
  3178. }
  3179. std::string cachePath = FindCacheFile(dir);
  3180. if (!this->LoadCache(cachePath)) {
  3181. std::cerr << "Error: could not load cache\n";
  3182. return false;
  3183. }
  3184. cmValue genName = this->State->GetCacheEntryValue("CMAKE_GENERATOR");
  3185. if (!genName) {
  3186. std::cerr << "Error: could not find CMAKE_GENERATOR in Cache\n";
  3187. return false;
  3188. }
  3189. cmValue extraGenName =
  3190. this->State->GetInitializedCacheValue("CMAKE_EXTRA_GENERATOR");
  3191. std::string fullName =
  3192. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  3193. *genName, extraGenName ? *extraGenName : "");
  3194. std::unique_ptr<cmGlobalGenerator> gen =
  3195. this->CreateGlobalGenerator(fullName);
  3196. if (!gen) {
  3197. std::cerr << "Error: could not create CMAKE_GENERATOR \"" << fullName
  3198. << "\"\n";
  3199. return false;
  3200. }
  3201. cmValue cachedProjectName =
  3202. this->State->GetCacheEntryValue("CMAKE_PROJECT_NAME");
  3203. if (!cachedProjectName) {
  3204. std::cerr << "Error: could not find CMAKE_PROJECT_NAME in Cache\n";
  3205. return false;
  3206. }
  3207. return gen->Open(dir, *cachedProjectName, dryRun);
  3208. }
  3209. void cmake::WatchUnusedCli(const std::string& var)
  3210. {
  3211. #ifndef CMAKE_BOOTSTRAP
  3212. this->VariableWatch->AddWatch(var, cmWarnUnusedCliWarning, this);
  3213. if (!cm::contains(this->UsedCliVariables, var)) {
  3214. this->UsedCliVariables[var] = false;
  3215. }
  3216. #endif
  3217. }
  3218. void cmake::UnwatchUnusedCli(const std::string& var)
  3219. {
  3220. #ifndef CMAKE_BOOTSTRAP
  3221. this->VariableWatch->RemoveWatch(var, cmWarnUnusedCliWarning);
  3222. this->UsedCliVariables.erase(var);
  3223. #endif
  3224. }
  3225. void cmake::RunCheckForUnusedVariables()
  3226. {
  3227. #ifndef CMAKE_BOOTSTRAP
  3228. bool haveUnused = false;
  3229. std::ostringstream msg;
  3230. msg << "Manually-specified variables were not used by the project:";
  3231. for (auto const& it : this->UsedCliVariables) {
  3232. if (!it.second) {
  3233. haveUnused = true;
  3234. msg << "\n " << it.first;
  3235. }
  3236. }
  3237. if (haveUnused) {
  3238. this->IssueMessage(MessageType::WARNING, msg.str());
  3239. }
  3240. #endif
  3241. }
  3242. bool cmake::GetSuppressDevWarnings() const
  3243. {
  3244. return this->Messenger->GetSuppressDevWarnings();
  3245. }
  3246. void cmake::SetSuppressDevWarnings(bool b)
  3247. {
  3248. std::string value;
  3249. // equivalent to -Wno-dev
  3250. if (b) {
  3251. value = "TRUE";
  3252. }
  3253. // equivalent to -Wdev
  3254. else {
  3255. value = "FALSE";
  3256. }
  3257. this->AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", value,
  3258. "Suppress Warnings that are meant for"
  3259. " the author of the CMakeLists.txt files.",
  3260. cmStateEnums::INTERNAL);
  3261. }
  3262. bool cmake::GetSuppressDeprecatedWarnings() const
  3263. {
  3264. return this->Messenger->GetSuppressDeprecatedWarnings();
  3265. }
  3266. void cmake::SetSuppressDeprecatedWarnings(bool b)
  3267. {
  3268. std::string value;
  3269. // equivalent to -Wno-deprecated
  3270. if (b) {
  3271. value = "FALSE";
  3272. }
  3273. // equivalent to -Wdeprecated
  3274. else {
  3275. value = "TRUE";
  3276. }
  3277. this->AddCacheEntry("CMAKE_WARN_DEPRECATED", value,
  3278. "Whether to issue warnings for deprecated "
  3279. "functionality.",
  3280. cmStateEnums::INTERNAL);
  3281. }
  3282. bool cmake::GetDevWarningsAsErrors() const
  3283. {
  3284. return this->Messenger->GetDevWarningsAsErrors();
  3285. }
  3286. void cmake::SetDevWarningsAsErrors(bool b)
  3287. {
  3288. std::string value;
  3289. // equivalent to -Werror=dev
  3290. if (b) {
  3291. value = "FALSE";
  3292. }
  3293. // equivalent to -Wno-error=dev
  3294. else {
  3295. value = "TRUE";
  3296. }
  3297. this->AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_ERRORS", value,
  3298. "Suppress errors that are meant for"
  3299. " the author of the CMakeLists.txt files.",
  3300. cmStateEnums::INTERNAL);
  3301. }
  3302. bool cmake::GetDeprecatedWarningsAsErrors() const
  3303. {
  3304. return this->Messenger->GetDeprecatedWarningsAsErrors();
  3305. }
  3306. void cmake::SetDeprecatedWarningsAsErrors(bool b)
  3307. {
  3308. std::string value;
  3309. // equivalent to -Werror=deprecated
  3310. if (b) {
  3311. value = "TRUE";
  3312. }
  3313. // equivalent to -Wno-error=deprecated
  3314. else {
  3315. value = "FALSE";
  3316. }
  3317. this->AddCacheEntry("CMAKE_ERROR_DEPRECATED", value,
  3318. "Whether to issue deprecation errors for macros"
  3319. " and functions.",
  3320. cmStateEnums::INTERNAL);
  3321. }
  3322. void cmake::SetDebugFindOutputPkgs(std::string const& args)
  3323. {
  3324. this->DebugFindPkgs.emplace(args);
  3325. }
  3326. void cmake::SetDebugFindOutputVars(std::string const& args)
  3327. {
  3328. this->DebugFindVars.emplace(args);
  3329. }
  3330. bool cmake::GetDebugFindOutput(std::string const& var) const
  3331. {
  3332. return this->DebugFindVars.count(var);
  3333. }
  3334. bool cmake::GetDebugFindPkgOutput(std::string const& pkg) const
  3335. {
  3336. return this->DebugFindPkgs.count(pkg);
  3337. }
  3338. #if !defined(CMAKE_BOOTSTRAP)
  3339. cmMakefileProfilingData& cmake::GetProfilingOutput()
  3340. {
  3341. return *(this->ProfilingOutput);
  3342. }
  3343. bool cmake::IsProfilingEnabled() const
  3344. {
  3345. return static_cast<bool>(this->ProfilingOutput);
  3346. }
  3347. #endif