cmake.cxx 135 KB

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