cmake.cxx 120 KB

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