cmake.cxx 120 KB

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