cmake.cxx 135 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045
  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. bool cmake::SetDirectoriesFromFile(const std::string& arg)
  1400. {
  1401. // Check if the argument refers to a CMakeCache.txt or
  1402. // CMakeLists.txt file.
  1403. std::string listPath;
  1404. std::string cachePath;
  1405. bool is_source_dir = false;
  1406. bool is_empty_directory = false;
  1407. if (cmSystemTools::FileIsDirectory(arg)) {
  1408. std::string path = cmSystemTools::CollapseFullPath(arg);
  1409. cmSystemTools::ConvertToUnixSlashes(path);
  1410. std::string cacheFile = cmStrCat(path, "/CMakeCache.txt");
  1411. std::string listFile = cmStrCat(path, "/CMakeLists.txt");
  1412. is_empty_directory = true;
  1413. if (cmSystemTools::FileExists(cacheFile)) {
  1414. cachePath = path;
  1415. is_empty_directory = false;
  1416. }
  1417. if (cmSystemTools::FileExists(listFile)) {
  1418. listPath = path;
  1419. is_empty_directory = false;
  1420. is_source_dir = true;
  1421. }
  1422. } else if (cmSystemTools::FileExists(arg)) {
  1423. std::string fullPath = cmSystemTools::CollapseFullPath(arg);
  1424. std::string name = cmSystemTools::GetFilenameName(fullPath);
  1425. name = cmSystemTools::LowerCase(name);
  1426. if (name == "cmakecache.txt"_s) {
  1427. cachePath = cmSystemTools::GetFilenamePath(fullPath);
  1428. } else if (name == "cmakelists.txt"_s) {
  1429. listPath = cmSystemTools::GetFilenamePath(fullPath);
  1430. }
  1431. } else {
  1432. // Specified file or directory does not exist. Try to set things
  1433. // up to produce a meaningful error message.
  1434. std::string fullPath = cmSystemTools::CollapseFullPath(arg);
  1435. std::string name = cmSystemTools::GetFilenameName(fullPath);
  1436. name = cmSystemTools::LowerCase(name);
  1437. if (name == "cmakecache.txt"_s || name == "cmakelists.txt"_s) {
  1438. listPath = cmSystemTools::GetFilenamePath(fullPath);
  1439. } else {
  1440. listPath = fullPath;
  1441. }
  1442. }
  1443. // If there is a CMakeCache.txt file, use its settings.
  1444. if (!cachePath.empty()) {
  1445. if (this->LoadCache(cachePath)) {
  1446. cmValue existingValue =
  1447. this->State->GetCacheEntryValue("CMAKE_HOME_DIRECTORY");
  1448. if (existingValue) {
  1449. this->SetHomeOutputDirectory(cachePath);
  1450. this->SetHomeDirectory(*existingValue);
  1451. return true;
  1452. }
  1453. }
  1454. }
  1455. bool no_source_tree = this->GetHomeDirectory().empty();
  1456. bool no_build_tree = this->GetHomeOutputDirectory().empty();
  1457. // When invoked with a path that points to an existing CMakeCache
  1458. // This function is called multiple times with the same path
  1459. const bool passed_same_path = (listPath == this->GetHomeDirectory()) ||
  1460. (listPath == this->GetHomeOutputDirectory());
  1461. bool used_provided_path =
  1462. (passed_same_path || is_source_dir || no_build_tree);
  1463. // If there is a CMakeLists.txt file, use it as the source tree.
  1464. if (!listPath.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. if (is_source_dir) {
  1468. this->SetHomeDirectoryViaCommandLine(listPath);
  1469. if (no_build_tree) {
  1470. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1471. this->SetHomeOutputDirectory(cwd);
  1472. }
  1473. } else if (no_source_tree && no_build_tree) {
  1474. this->SetHomeDirectory(listPath);
  1475. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1476. this->SetHomeOutputDirectory(cwd);
  1477. } else if (no_build_tree) {
  1478. this->SetHomeOutputDirectory(listPath);
  1479. }
  1480. } else {
  1481. if (no_source_tree) {
  1482. // We didn't find a CMakeLists.txt and it wasn't specified
  1483. // with -S. Assume it is the path to the source tree
  1484. std::string full = cmSystemTools::CollapseFullPath(arg);
  1485. this->SetHomeDirectory(full);
  1486. }
  1487. if (no_build_tree && !no_source_tree && is_empty_directory) {
  1488. // passed `-S <path> <build_dir> when build_dir is an empty directory
  1489. std::string full = cmSystemTools::CollapseFullPath(arg);
  1490. this->SetHomeOutputDirectory(full);
  1491. } else if (no_build_tree) {
  1492. // We didn't find a CMakeCache.txt and it wasn't specified
  1493. // with -B. Assume the current working directory as the build tree.
  1494. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1495. this->SetHomeOutputDirectory(cwd);
  1496. used_provided_path = false;
  1497. }
  1498. }
  1499. return used_provided_path;
  1500. }
  1501. // at the end of this CMAKE_ROOT and CMAKE_COMMAND should be added to the
  1502. // cache
  1503. int cmake::AddCMakePaths()
  1504. {
  1505. // Save the value in the cache
  1506. this->AddCacheEntry("CMAKE_COMMAND", cmSystemTools::GetCMakeCommand(),
  1507. "Path to CMake executable.", cmStateEnums::INTERNAL);
  1508. #ifndef CMAKE_BOOTSTRAP
  1509. this->AddCacheEntry("CMAKE_CTEST_COMMAND", cmSystemTools::GetCTestCommand(),
  1510. "Path to ctest program executable.",
  1511. cmStateEnums::INTERNAL);
  1512. this->AddCacheEntry("CMAKE_CPACK_COMMAND", cmSystemTools::GetCPackCommand(),
  1513. "Path to cpack program executable.",
  1514. cmStateEnums::INTERNAL);
  1515. #endif
  1516. if (!cmSystemTools::FileExists(
  1517. (cmSystemTools::GetCMakeRoot() + "/Modules/CMake.cmake"))) {
  1518. // couldn't find modules
  1519. cmSystemTools::Error(
  1520. "Could not find CMAKE_ROOT !!!\n"
  1521. "CMake has most likely not been installed correctly.\n"
  1522. "Modules directory not found in\n" +
  1523. cmSystemTools::GetCMakeRoot());
  1524. return 0;
  1525. }
  1526. this->AddCacheEntry("CMAKE_ROOT", cmSystemTools::GetCMakeRoot(),
  1527. "Path to CMake installation.", cmStateEnums::INTERNAL);
  1528. return 1;
  1529. }
  1530. void cmake::AddDefaultExtraGenerators()
  1531. {
  1532. #if !defined(CMAKE_BOOTSTRAP)
  1533. this->ExtraGenerators.push_back(cmExtraCodeBlocksGenerator::GetFactory());
  1534. this->ExtraGenerators.push_back(cmExtraCodeLiteGenerator::GetFactory());
  1535. this->ExtraGenerators.push_back(cmExtraEclipseCDT4Generator::GetFactory());
  1536. this->ExtraGenerators.push_back(cmExtraKateGenerator::GetFactory());
  1537. this->ExtraGenerators.push_back(cmExtraSublimeTextGenerator::GetFactory());
  1538. #endif
  1539. }
  1540. void cmake::GetRegisteredGenerators(std::vector<GeneratorInfo>& generators,
  1541. bool includeNamesWithPlatform) const
  1542. {
  1543. for (const auto& gen : this->Generators) {
  1544. std::vector<std::string> names = gen->GetGeneratorNames();
  1545. if (includeNamesWithPlatform) {
  1546. cm::append(names, gen->GetGeneratorNamesWithPlatform());
  1547. }
  1548. for (std::string const& name : names) {
  1549. GeneratorInfo info;
  1550. info.supportsToolset = gen->SupportsToolset();
  1551. info.supportsPlatform = gen->SupportsPlatform();
  1552. info.supportedPlatforms = gen->GetKnownPlatforms();
  1553. info.defaultPlatform = gen->GetDefaultPlatformName();
  1554. info.name = name;
  1555. info.baseName = name;
  1556. info.isAlias = false;
  1557. generators.push_back(std::move(info));
  1558. }
  1559. }
  1560. for (cmExternalMakefileProjectGeneratorFactory* eg : this->ExtraGenerators) {
  1561. const std::vector<std::string> genList =
  1562. eg->GetSupportedGlobalGenerators();
  1563. for (std::string const& gen : genList) {
  1564. GeneratorInfo info;
  1565. info.name = cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  1566. gen, eg->GetName());
  1567. info.baseName = gen;
  1568. info.extraName = eg->GetName();
  1569. info.supportsPlatform = false;
  1570. info.supportsToolset = false;
  1571. info.isAlias = false;
  1572. generators.push_back(std::move(info));
  1573. }
  1574. for (std::string const& a : eg->Aliases) {
  1575. GeneratorInfo info;
  1576. info.name = a;
  1577. if (!genList.empty()) {
  1578. info.baseName = genList.at(0);
  1579. }
  1580. info.extraName = eg->GetName();
  1581. info.supportsPlatform = false;
  1582. info.supportsToolset = false;
  1583. info.isAlias = true;
  1584. generators.push_back(std::move(info));
  1585. }
  1586. }
  1587. }
  1588. static std::pair<std::unique_ptr<cmExternalMakefileProjectGenerator>,
  1589. std::string>
  1590. createExtraGenerator(
  1591. const std::vector<cmExternalMakefileProjectGeneratorFactory*>& in,
  1592. const std::string& name)
  1593. {
  1594. for (cmExternalMakefileProjectGeneratorFactory* i : in) {
  1595. const std::vector<std::string> generators =
  1596. i->GetSupportedGlobalGenerators();
  1597. if (i->GetName() == name) { // Match aliases
  1598. return { i->CreateExternalMakefileProjectGenerator(), generators.at(0) };
  1599. }
  1600. for (std::string const& g : generators) {
  1601. const std::string fullName =
  1602. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  1603. g, i->GetName());
  1604. if (fullName == name) {
  1605. return { i->CreateExternalMakefileProjectGenerator(), g };
  1606. }
  1607. }
  1608. }
  1609. return { nullptr, name };
  1610. }
  1611. std::unique_ptr<cmGlobalGenerator> cmake::CreateGlobalGenerator(
  1612. const std::string& gname, bool allowArch)
  1613. {
  1614. std::pair<std::unique_ptr<cmExternalMakefileProjectGenerator>, std::string>
  1615. extra = createExtraGenerator(this->ExtraGenerators, gname);
  1616. std::unique_ptr<cmExternalMakefileProjectGenerator>& extraGenerator =
  1617. extra.first;
  1618. const std::string& name = extra.second;
  1619. std::unique_ptr<cmGlobalGenerator> generator;
  1620. for (const auto& g : this->Generators) {
  1621. generator = g->CreateGlobalGenerator(name, allowArch, this);
  1622. if (generator) {
  1623. break;
  1624. }
  1625. }
  1626. if (generator) {
  1627. generator->SetExternalMakefileProjectGenerator(std::move(extraGenerator));
  1628. }
  1629. return generator;
  1630. }
  1631. bool cmake::CreateAndSetGlobalGenerator(const std::string& name,
  1632. bool allowArch)
  1633. {
  1634. auto gen = this->CreateGlobalGenerator(name, allowArch);
  1635. if (!gen) {
  1636. std::string kdevError;
  1637. std::string vsError;
  1638. if (name.find("KDevelop3", 0) != std::string::npos) {
  1639. kdevError = "\nThe KDevelop3 generator is not supported anymore.";
  1640. }
  1641. if (!allowArch && cmHasLiteralPrefix(name, "Visual Studio ") &&
  1642. name.length() >= cmStrLen("Visual Studio xx xxxx ")) {
  1643. vsError = "\nUsing platforms in Visual Studio generator names is not "
  1644. "supported in CMakePresets.json.";
  1645. }
  1646. cmSystemTools::Error(
  1647. cmStrCat("Could not create named generator ", name, kdevError, vsError));
  1648. this->PrintGeneratorList();
  1649. return false;
  1650. }
  1651. this->SetGlobalGenerator(std::move(gen));
  1652. return true;
  1653. }
  1654. #ifndef CMAKE_BOOTSTRAP
  1655. void cmake::PrintPresetList(const cmCMakePresetsGraph& graph) const
  1656. {
  1657. std::vector<GeneratorInfo> generators;
  1658. this->GetRegisteredGenerators(generators, false);
  1659. auto filter =
  1660. [&generators](const cmCMakePresetsGraph::ConfigurePreset& preset) -> bool {
  1661. if (preset.Generator.empty()) {
  1662. return true;
  1663. }
  1664. auto condition = [&preset](const GeneratorInfo& info) -> bool {
  1665. return info.name == preset.Generator;
  1666. };
  1667. auto it = std::find_if(generators.begin(), generators.end(), condition);
  1668. return it != generators.end();
  1669. };
  1670. graph.PrintConfigurePresetList(filter);
  1671. }
  1672. #endif
  1673. void cmake::SetHomeDirectoryViaCommandLine(std::string const& path)
  1674. {
  1675. if (path.empty()) {
  1676. return;
  1677. }
  1678. auto prev_path = this->GetHomeDirectory();
  1679. if (prev_path != path && !prev_path.empty() &&
  1680. this->GetWorkingMode() == NORMAL_MODE) {
  1681. this->IssueMessage(MessageType::WARNING,
  1682. cmStrCat("Ignoring extra path from command line:\n \"",
  1683. prev_path, "\""));
  1684. }
  1685. this->SetHomeDirectory(path);
  1686. }
  1687. void cmake::SetHomeDirectory(const std::string& dir)
  1688. {
  1689. this->State->SetSourceDirectory(dir);
  1690. if (this->CurrentSnapshot.IsValid()) {
  1691. this->CurrentSnapshot.SetDefinition("CMAKE_SOURCE_DIR", dir);
  1692. }
  1693. if (this->State->GetProjectKind() == cmState::ProjectKind::Normal) {
  1694. this->Messenger->SetTopSource(this->GetHomeDirectory());
  1695. } else {
  1696. this->Messenger->SetTopSource(cm::nullopt);
  1697. }
  1698. }
  1699. std::string const& cmake::GetHomeDirectory() const
  1700. {
  1701. return this->State->GetSourceDirectory();
  1702. }
  1703. void cmake::SetHomeOutputDirectory(const std::string& dir)
  1704. {
  1705. this->State->SetBinaryDirectory(dir);
  1706. if (this->CurrentSnapshot.IsValid()) {
  1707. this->CurrentSnapshot.SetDefinition("CMAKE_BINARY_DIR", dir);
  1708. }
  1709. }
  1710. std::string const& cmake::GetHomeOutputDirectory() const
  1711. {
  1712. return this->State->GetBinaryDirectory();
  1713. }
  1714. std::string cmake::FindCacheFile(const std::string& binaryDir)
  1715. {
  1716. std::string cachePath = binaryDir;
  1717. cmSystemTools::ConvertToUnixSlashes(cachePath);
  1718. std::string cacheFile = cmStrCat(cachePath, "/CMakeCache.txt");
  1719. if (!cmSystemTools::FileExists(cacheFile)) {
  1720. // search in parent directories for cache
  1721. std::string cmakeFiles = cmStrCat(cachePath, "/CMakeFiles");
  1722. if (cmSystemTools::FileExists(cmakeFiles)) {
  1723. std::string cachePathFound =
  1724. cmSystemTools::FileExistsInParentDirectories("CMakeCache.txt",
  1725. cachePath, "/");
  1726. if (!cachePathFound.empty()) {
  1727. cachePath = cmSystemTools::GetFilenamePath(cachePathFound);
  1728. }
  1729. }
  1730. }
  1731. return cachePath;
  1732. }
  1733. void cmake::SetGlobalGenerator(std::unique_ptr<cmGlobalGenerator> gg)
  1734. {
  1735. if (!gg) {
  1736. cmSystemTools::Error("Error SetGlobalGenerator called with null");
  1737. return;
  1738. }
  1739. if (this->GlobalGenerator) {
  1740. // restore the original environment variables CXX and CC
  1741. std::string env = "CC=";
  1742. if (!this->CCEnvironment.empty()) {
  1743. env += this->CCEnvironment;
  1744. cmSystemTools::PutEnv(env);
  1745. } else {
  1746. cmSystemTools::UnPutEnv(env);
  1747. }
  1748. env = "CXX=";
  1749. if (!this->CXXEnvironment.empty()) {
  1750. env += this->CXXEnvironment;
  1751. cmSystemTools::PutEnv(env);
  1752. } else {
  1753. cmSystemTools::UnPutEnv(env);
  1754. }
  1755. }
  1756. // set the new
  1757. this->GlobalGenerator = std::move(gg);
  1758. // set the global flag for unix style paths on cmSystemTools as soon as
  1759. // the generator is set. This allows gmake to be used on windows.
  1760. cmSystemTools::SetForceUnixPaths(this->GlobalGenerator->GetForceUnixPaths());
  1761. // Save the environment variables CXX and CC
  1762. if (!cmSystemTools::GetEnv("CXX", this->CXXEnvironment)) {
  1763. this->CXXEnvironment.clear();
  1764. }
  1765. if (!cmSystemTools::GetEnv("CC", this->CCEnvironment)) {
  1766. this->CCEnvironment.clear();
  1767. }
  1768. }
  1769. int cmake::DoPreConfigureChecks()
  1770. {
  1771. // Make sure the Source directory contains a CMakeLists.txt file.
  1772. std::string srcList = cmStrCat(this->GetHomeDirectory(), "/CMakeLists.txt");
  1773. if (!cmSystemTools::FileExists(srcList)) {
  1774. std::ostringstream err;
  1775. if (cmSystemTools::FileIsDirectory(this->GetHomeDirectory())) {
  1776. err << "The source directory \"" << this->GetHomeDirectory()
  1777. << "\" does not appear to contain CMakeLists.txt.\n";
  1778. } else if (cmSystemTools::FileExists(this->GetHomeDirectory())) {
  1779. err << "The source directory \"" << this->GetHomeDirectory()
  1780. << "\" is a file, not a directory.\n";
  1781. } else {
  1782. err << "The source directory \"" << this->GetHomeDirectory()
  1783. << "\" does not exist.\n";
  1784. }
  1785. err << "Specify --help for usage, or press the help button on the CMake "
  1786. "GUI.";
  1787. cmSystemTools::Error(err.str());
  1788. return -2;
  1789. }
  1790. // do a sanity check on some values
  1791. if (this->State->GetInitializedCacheValue("CMAKE_HOME_DIRECTORY")) {
  1792. std::string cacheStart =
  1793. cmStrCat(*this->State->GetInitializedCacheValue("CMAKE_HOME_DIRECTORY"),
  1794. "/CMakeLists.txt");
  1795. std::string currentStart =
  1796. cmStrCat(this->GetHomeDirectory(), "/CMakeLists.txt");
  1797. if (!cmSystemTools::SameFile(cacheStart, currentStart)) {
  1798. std::string message =
  1799. cmStrCat("The source \"", currentStart,
  1800. "\" does not match the source \"", cacheStart,
  1801. "\" used to generate cache. Re-run cmake with a different "
  1802. "source directory.");
  1803. cmSystemTools::Error(message);
  1804. return -2;
  1805. }
  1806. } else {
  1807. return 0;
  1808. }
  1809. return 1;
  1810. }
  1811. struct SaveCacheEntry
  1812. {
  1813. std::string key;
  1814. std::string value;
  1815. std::string help;
  1816. cmStateEnums::CacheEntryType type;
  1817. };
  1818. int cmake::HandleDeleteCacheVariables(const std::string& var)
  1819. {
  1820. std::vector<std::string> argsSplit = cmExpandedList(var, true);
  1821. // erase the property to avoid infinite recursion
  1822. this->State->SetGlobalProperty("__CMAKE_DELETE_CACHE_CHANGE_VARS_", "");
  1823. if (this->GetIsInTryCompile()) {
  1824. return 0;
  1825. }
  1826. std::vector<SaveCacheEntry> saved;
  1827. std::ostringstream warning;
  1828. /* clang-format off */
  1829. warning
  1830. << "You have changed variables that require your cache to be deleted.\n"
  1831. << "Configure will be re-run and you may have to reset some variables.\n"
  1832. << "The following variables have changed:\n";
  1833. /* clang-format on */
  1834. for (auto i = argsSplit.begin(); i != argsSplit.end(); ++i) {
  1835. SaveCacheEntry save;
  1836. save.key = *i;
  1837. warning << *i << "= ";
  1838. i++;
  1839. if (i != argsSplit.end()) {
  1840. save.value = *i;
  1841. warning << *i << "\n";
  1842. } else {
  1843. warning << "\n";
  1844. i -= 1;
  1845. }
  1846. cmValue existingValue = this->State->GetCacheEntryValue(save.key);
  1847. if (existingValue) {
  1848. save.type = this->State->GetCacheEntryType(save.key);
  1849. if (cmValue help =
  1850. this->State->GetCacheEntryProperty(save.key, "HELPSTRING")) {
  1851. save.help = *help;
  1852. }
  1853. } else {
  1854. save.type = cmStateEnums::CacheEntryType::UNINITIALIZED;
  1855. }
  1856. saved.push_back(std::move(save));
  1857. }
  1858. // remove the cache
  1859. this->DeleteCache(this->GetHomeOutputDirectory());
  1860. // load the empty cache
  1861. this->LoadCache();
  1862. // restore the changed compilers
  1863. for (SaveCacheEntry const& i : saved) {
  1864. this->AddCacheEntry(i.key, i.value, i.help.c_str(), i.type);
  1865. }
  1866. cmSystemTools::Message(warning.str());
  1867. // avoid reconfigure if there were errors
  1868. if (!cmSystemTools::GetErrorOccurredFlag()) {
  1869. // re-run configure
  1870. return this->Configure();
  1871. }
  1872. return 0;
  1873. }
  1874. int cmake::Configure()
  1875. {
  1876. DiagLevel diagLevel;
  1877. if (this->DiagLevels.count("deprecated") == 1) {
  1878. diagLevel = this->DiagLevels["deprecated"];
  1879. if (diagLevel == DIAG_IGNORE) {
  1880. this->SetSuppressDeprecatedWarnings(true);
  1881. this->SetDeprecatedWarningsAsErrors(false);
  1882. } else if (diagLevel == DIAG_WARN) {
  1883. this->SetSuppressDeprecatedWarnings(false);
  1884. this->SetDeprecatedWarningsAsErrors(false);
  1885. } else if (diagLevel == DIAG_ERROR) {
  1886. this->SetSuppressDeprecatedWarnings(false);
  1887. this->SetDeprecatedWarningsAsErrors(true);
  1888. }
  1889. }
  1890. if (this->DiagLevels.count("dev") == 1) {
  1891. bool setDeprecatedVariables = false;
  1892. cmValue cachedWarnDeprecated =
  1893. this->State->GetCacheEntryValue("CMAKE_WARN_DEPRECATED");
  1894. cmValue cachedErrorDeprecated =
  1895. this->State->GetCacheEntryValue("CMAKE_ERROR_DEPRECATED");
  1896. // don't overwrite deprecated warning setting from a previous invocation
  1897. if (!cachedWarnDeprecated && !cachedErrorDeprecated) {
  1898. setDeprecatedVariables = true;
  1899. }
  1900. diagLevel = this->DiagLevels["dev"];
  1901. if (diagLevel == DIAG_IGNORE) {
  1902. this->SetSuppressDevWarnings(true);
  1903. this->SetDevWarningsAsErrors(false);
  1904. if (setDeprecatedVariables) {
  1905. this->SetSuppressDeprecatedWarnings(true);
  1906. this->SetDeprecatedWarningsAsErrors(false);
  1907. }
  1908. } else if (diagLevel == DIAG_WARN) {
  1909. this->SetSuppressDevWarnings(false);
  1910. this->SetDevWarningsAsErrors(false);
  1911. if (setDeprecatedVariables) {
  1912. this->SetSuppressDeprecatedWarnings(false);
  1913. this->SetDeprecatedWarningsAsErrors(false);
  1914. }
  1915. } else if (diagLevel == DIAG_ERROR) {
  1916. this->SetSuppressDevWarnings(false);
  1917. this->SetDevWarningsAsErrors(true);
  1918. if (setDeprecatedVariables) {
  1919. this->SetSuppressDeprecatedWarnings(false);
  1920. this->SetDeprecatedWarningsAsErrors(true);
  1921. }
  1922. }
  1923. }
  1924. // Cache variables may have already been set by a previous invocation,
  1925. // so we cannot rely on command line options alone. Always ensure our
  1926. // messenger is in sync with the cache.
  1927. cmValue value = this->State->GetCacheEntryValue("CMAKE_WARN_DEPRECATED");
  1928. this->Messenger->SetSuppressDeprecatedWarnings(value && cmIsOff(*value));
  1929. value = this->State->GetCacheEntryValue("CMAKE_ERROR_DEPRECATED");
  1930. this->Messenger->SetDeprecatedWarningsAsErrors(cmIsOn(value));
  1931. value = this->State->GetCacheEntryValue("CMAKE_SUPPRESS_DEVELOPER_WARNINGS");
  1932. this->Messenger->SetSuppressDevWarnings(cmIsOn(value));
  1933. value = this->State->GetCacheEntryValue("CMAKE_SUPPRESS_DEVELOPER_ERRORS");
  1934. this->Messenger->SetDevWarningsAsErrors(value && cmIsOff(*value));
  1935. int ret = this->ActualConfigure();
  1936. cmValue delCacheVars =
  1937. this->State->GetGlobalProperty("__CMAKE_DELETE_CACHE_CHANGE_VARS_");
  1938. if (delCacheVars && !delCacheVars->empty()) {
  1939. return this->HandleDeleteCacheVariables(*delCacheVars);
  1940. }
  1941. return ret;
  1942. }
  1943. int cmake::ActualConfigure()
  1944. {
  1945. // Construct right now our path conversion table before it's too late:
  1946. this->UpdateConversionPathTable();
  1947. this->CleanupCommandsAndMacros();
  1948. cmSystemTools::RemoveADirectory(this->GetHomeOutputDirectory() +
  1949. "/CMakeFiles/CMakeScratch");
  1950. int res = this->DoPreConfigureChecks();
  1951. if (res < 0) {
  1952. return -2;
  1953. }
  1954. if (!res) {
  1955. this->AddCacheEntry(
  1956. "CMAKE_HOME_DIRECTORY", this->GetHomeDirectory(),
  1957. "Source directory with the top level CMakeLists.txt file for this "
  1958. "project",
  1959. cmStateEnums::INTERNAL);
  1960. }
  1961. // We want to create the package redirects directory as early as possible,
  1962. // but not before pre-configure checks have passed. This ensures we get
  1963. // errors about inappropriate source/binary directories first.
  1964. const auto redirectsDir =
  1965. cmStrCat(this->GetHomeOutputDirectory(), "/CMakeFiles/pkgRedirects");
  1966. cmSystemTools::RemoveADirectory(redirectsDir);
  1967. if (!cmSystemTools::MakeDirectory(redirectsDir)) {
  1968. cmSystemTools::Error(
  1969. "Unable to (re)create the private pkgRedirects directory:\n" +
  1970. redirectsDir);
  1971. return -1;
  1972. }
  1973. this->AddCacheEntry("CMAKE_FIND_PACKAGE_REDIRECTS_DIR", redirectsDir,
  1974. "Value Computed by CMake.", cmStateEnums::STATIC);
  1975. // no generator specified on the command line
  1976. if (!this->GlobalGenerator) {
  1977. cmValue genName = this->State->GetInitializedCacheValue("CMAKE_GENERATOR");
  1978. cmValue extraGenName =
  1979. this->State->GetInitializedCacheValue("CMAKE_EXTRA_GENERATOR");
  1980. if (genName) {
  1981. std::string fullName =
  1982. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  1983. *genName, extraGenName ? *extraGenName : "");
  1984. this->GlobalGenerator = this->CreateGlobalGenerator(fullName);
  1985. }
  1986. if (this->GlobalGenerator) {
  1987. // set the global flag for unix style paths on cmSystemTools as
  1988. // soon as the generator is set. This allows gmake to be used
  1989. // on windows.
  1990. cmSystemTools::SetForceUnixPaths(
  1991. this->GlobalGenerator->GetForceUnixPaths());
  1992. } else {
  1993. this->CreateDefaultGlobalGenerator();
  1994. }
  1995. if (!this->GlobalGenerator) {
  1996. cmSystemTools::Error("Could not create generator");
  1997. return -1;
  1998. }
  1999. }
  2000. cmValue genName = this->State->GetInitializedCacheValue("CMAKE_GENERATOR");
  2001. if (genName) {
  2002. if (!this->GlobalGenerator->MatchesGeneratorName(*genName)) {
  2003. std::string message =
  2004. cmStrCat("Error: generator : ", this->GlobalGenerator->GetName(),
  2005. "\nDoes not match the generator used previously: ", *genName,
  2006. "\nEither remove the CMakeCache.txt file and CMakeFiles "
  2007. "directory or choose a different binary directory.");
  2008. cmSystemTools::Error(message);
  2009. return -2;
  2010. }
  2011. }
  2012. if (!this->State->GetInitializedCacheValue("CMAKE_GENERATOR")) {
  2013. this->AddCacheEntry("CMAKE_GENERATOR", this->GlobalGenerator->GetName(),
  2014. "Name of generator.", cmStateEnums::INTERNAL);
  2015. this->AddCacheEntry(
  2016. "CMAKE_EXTRA_GENERATOR", this->GlobalGenerator->GetExtraGeneratorName(),
  2017. "Name of external makefile project generator.", cmStateEnums::INTERNAL);
  2018. if (!this->State->GetInitializedCacheValue("CMAKE_TOOLCHAIN_FILE")) {
  2019. std::string envToolchain;
  2020. if (cmSystemTools::GetEnv("CMAKE_TOOLCHAIN_FILE", envToolchain) &&
  2021. !envToolchain.empty()) {
  2022. this->AddCacheEntry("CMAKE_TOOLCHAIN_FILE", envToolchain,
  2023. "The CMake toolchain file",
  2024. cmStateEnums::FILEPATH);
  2025. }
  2026. }
  2027. }
  2028. if (cmValue instance =
  2029. this->State->GetInitializedCacheValue("CMAKE_GENERATOR_INSTANCE")) {
  2030. if (this->GeneratorInstanceSet && this->GeneratorInstance != *instance) {
  2031. std::string message =
  2032. cmStrCat("Error: generator instance: ", this->GeneratorInstance,
  2033. "\nDoes not match the instance used previously: ", *instance,
  2034. "\nEither remove the CMakeCache.txt file and CMakeFiles "
  2035. "directory or choose a different binary directory.");
  2036. cmSystemTools::Error(message);
  2037. return -2;
  2038. }
  2039. } else {
  2040. this->AddCacheEntry("CMAKE_GENERATOR_INSTANCE", this->GeneratorInstance,
  2041. "Generator instance identifier.",
  2042. cmStateEnums::INTERNAL);
  2043. }
  2044. if (cmValue platformName =
  2045. this->State->GetInitializedCacheValue("CMAKE_GENERATOR_PLATFORM")) {
  2046. if (this->GeneratorPlatformSet &&
  2047. this->GeneratorPlatform != *platformName) {
  2048. std::string message = cmStrCat(
  2049. "Error: generator platform: ", this->GeneratorPlatform,
  2050. "\nDoes not match the platform used previously: ", *platformName,
  2051. "\nEither remove the CMakeCache.txt file and CMakeFiles "
  2052. "directory or choose a different binary directory.");
  2053. cmSystemTools::Error(message);
  2054. return -2;
  2055. }
  2056. } else {
  2057. this->AddCacheEntry("CMAKE_GENERATOR_PLATFORM", this->GeneratorPlatform,
  2058. "Name of generator platform.", cmStateEnums::INTERNAL);
  2059. }
  2060. if (cmValue tsName =
  2061. this->State->GetInitializedCacheValue("CMAKE_GENERATOR_TOOLSET")) {
  2062. if (this->GeneratorToolsetSet && this->GeneratorToolset != *tsName) {
  2063. std::string message =
  2064. cmStrCat("Error: generator toolset: ", this->GeneratorToolset,
  2065. "\nDoes not match the toolset used previously: ", *tsName,
  2066. "\nEither remove the CMakeCache.txt file and CMakeFiles "
  2067. "directory or choose a different binary directory.");
  2068. cmSystemTools::Error(message);
  2069. return -2;
  2070. }
  2071. } else {
  2072. this->AddCacheEntry("CMAKE_GENERATOR_TOOLSET", this->GeneratorToolset,
  2073. "Name of generator toolset.", cmStateEnums::INTERNAL);
  2074. }
  2075. // reset any system configuration information, except for when we are
  2076. // InTryCompile. With TryCompile the system info is taken from the parent's
  2077. // info to save time
  2078. if (!this->GetIsInTryCompile()) {
  2079. this->GlobalGenerator->ClearEnabledLanguages();
  2080. this->TruncateOutputLog("CMakeOutput.log");
  2081. this->TruncateOutputLog("CMakeError.log");
  2082. }
  2083. #if !defined(CMAKE_BOOTSTRAP)
  2084. this->FileAPI = cm::make_unique<cmFileAPI>(this);
  2085. this->FileAPI->ReadQueries();
  2086. #endif
  2087. // actually do the configure
  2088. this->GlobalGenerator->Configure();
  2089. // Before saving the cache
  2090. // if the project did not define one of the entries below, add them now
  2091. // so users can edit the values in the cache:
  2092. // We used to always present LIBRARY_OUTPUT_PATH and
  2093. // EXECUTABLE_OUTPUT_PATH. They are now documented as old-style and
  2094. // should no longer be used. Therefore we present them only if the
  2095. // project requires compatibility with CMake 2.4. We detect this
  2096. // here by looking for the old CMAKE_BACKWARDS_COMPATIBILITY
  2097. // variable created when CMP0001 is not set to NEW.
  2098. if (this->State->GetInitializedCacheValue("CMAKE_BACKWARDS_COMPATIBILITY")) {
  2099. if (!this->State->GetInitializedCacheValue("LIBRARY_OUTPUT_PATH")) {
  2100. this->AddCacheEntry(
  2101. "LIBRARY_OUTPUT_PATH", "",
  2102. "Single output directory for building all libraries.",
  2103. cmStateEnums::PATH);
  2104. }
  2105. if (!this->State->GetInitializedCacheValue("EXECUTABLE_OUTPUT_PATH")) {
  2106. this->AddCacheEntry(
  2107. "EXECUTABLE_OUTPUT_PATH", "",
  2108. "Single output directory for building all executables.",
  2109. cmStateEnums::PATH);
  2110. }
  2111. }
  2112. const auto& mf = this->GlobalGenerator->GetMakefiles()[0];
  2113. if (mf->IsOn("CTEST_USE_LAUNCHERS") &&
  2114. !this->State->GetGlobalProperty("RULE_LAUNCH_COMPILE")) {
  2115. cmSystemTools::Error(
  2116. "CTEST_USE_LAUNCHERS is enabled, but the "
  2117. "RULE_LAUNCH_COMPILE global property is not defined.\n"
  2118. "Did you forget to include(CTest) in the toplevel "
  2119. "CMakeLists.txt ?");
  2120. }
  2121. this->State->SaveVerificationScript(this->GetHomeOutputDirectory(),
  2122. this->Messenger.get());
  2123. this->SaveCache(this->GetHomeOutputDirectory());
  2124. if (cmSystemTools::GetErrorOccurredFlag()) {
  2125. return -1;
  2126. }
  2127. return 0;
  2128. }
  2129. std::unique_ptr<cmGlobalGenerator> cmake::EvaluateDefaultGlobalGenerator()
  2130. {
  2131. if (!this->EnvironmentGenerator.empty()) {
  2132. auto gen = this->CreateGlobalGenerator(this->EnvironmentGenerator);
  2133. if (!gen) {
  2134. cmSystemTools::Error("CMAKE_GENERATOR was set but the specified "
  2135. "generator doesn't exist. Using CMake default.");
  2136. } else {
  2137. return gen;
  2138. }
  2139. }
  2140. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(CMAKE_BOOT_MINGW)
  2141. std::string found;
  2142. // Try to find the newest VS installed on the computer and
  2143. // use that as a default if -G is not specified
  2144. const std::string vsregBase = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\";
  2145. static const char* const vsVariants[] = {
  2146. /* clang-format needs this comment to break after the opening brace */
  2147. "VisualStudio\\", "VCExpress\\", "WDExpress\\"
  2148. };
  2149. struct VSVersionedGenerator
  2150. {
  2151. const char* MSVersion;
  2152. const char* GeneratorName;
  2153. };
  2154. static VSVersionedGenerator const vsGenerators[] = {
  2155. { "14.0", "Visual Studio 14 2015" }, //
  2156. { "12.0", "Visual Studio 12 2013" }, //
  2157. { "11.0", "Visual Studio 11 2012" }, //
  2158. { "9.0", "Visual Studio 9 2008" }
  2159. };
  2160. static const char* const vsEntries[] = {
  2161. "\\Setup\\VC;ProductDir", //
  2162. ";InstallDir" //
  2163. };
  2164. if (cmVSSetupAPIHelper(17).IsVSInstalled()) {
  2165. found = "Visual Studio 17 2022";
  2166. } else if (cmVSSetupAPIHelper(16).IsVSInstalled()) {
  2167. found = "Visual Studio 16 2019";
  2168. } else if (cmVSSetupAPIHelper(15).IsVSInstalled()) {
  2169. found = "Visual Studio 15 2017";
  2170. } else {
  2171. for (VSVersionedGenerator const* g = cm::cbegin(vsGenerators);
  2172. found.empty() && g != cm::cend(vsGenerators); ++g) {
  2173. for (const char* const* v = cm::cbegin(vsVariants);
  2174. found.empty() && v != cm::cend(vsVariants); ++v) {
  2175. for (const char* const* e = cm::cbegin(vsEntries);
  2176. found.empty() && e != cm::cend(vsEntries); ++e) {
  2177. std::string const reg = vsregBase + *v + g->MSVersion + *e;
  2178. std::string dir;
  2179. if (cmSystemTools::ReadRegistryValue(reg, dir,
  2180. cmSystemTools::KeyWOW64_32) &&
  2181. cmSystemTools::PathExists(dir)) {
  2182. found = g->GeneratorName;
  2183. }
  2184. }
  2185. }
  2186. }
  2187. }
  2188. auto gen = this->CreateGlobalGenerator(found);
  2189. if (!gen) {
  2190. gen = cm::make_unique<cmGlobalNMakeMakefileGenerator>(this);
  2191. }
  2192. return std::unique_ptr<cmGlobalGenerator>(std::move(gen));
  2193. #elif defined(CMAKE_BOOTSTRAP_NINJA)
  2194. return std::unique_ptr<cmGlobalGenerator>(
  2195. cm::make_unique<cmGlobalNinjaGenerator>(this));
  2196. #else
  2197. return std::unique_ptr<cmGlobalGenerator>(
  2198. cm::make_unique<cmGlobalUnixMakefileGenerator3>(this));
  2199. #endif
  2200. }
  2201. void cmake::CreateDefaultGlobalGenerator()
  2202. {
  2203. auto gen = this->EvaluateDefaultGlobalGenerator();
  2204. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(CMAKE_BOOT_MINGW)
  2205. // This print could be unified for all platforms
  2206. std::cout << "-- Building for: " << gen->GetName() << "\n";
  2207. #endif
  2208. this->SetGlobalGenerator(std::move(gen));
  2209. }
  2210. void cmake::PreLoadCMakeFiles()
  2211. {
  2212. std::vector<std::string> args;
  2213. std::string pre_load = this->GetHomeDirectory();
  2214. if (!pre_load.empty()) {
  2215. pre_load += "/PreLoad.cmake";
  2216. if (cmSystemTools::FileExists(pre_load)) {
  2217. this->ReadListFile(args, pre_load);
  2218. }
  2219. }
  2220. pre_load = this->GetHomeOutputDirectory();
  2221. if (!pre_load.empty()) {
  2222. pre_load += "/PreLoad.cmake";
  2223. if (cmSystemTools::FileExists(pre_load)) {
  2224. this->ReadListFile(args, pre_load);
  2225. }
  2226. }
  2227. }
  2228. // handle a command line invocation
  2229. int cmake::Run(const std::vector<std::string>& args, bool noconfigure)
  2230. {
  2231. // Process the arguments
  2232. this->SetArgs(args);
  2233. if (cmSystemTools::GetErrorOccurredFlag()) {
  2234. return -1;
  2235. }
  2236. if (this->GetWorkingMode() == HELP_MODE) {
  2237. return 0;
  2238. }
  2239. // Log the trace format version to the desired output
  2240. if (this->GetTrace()) {
  2241. this->PrintTraceFormatVersion();
  2242. }
  2243. // If we are given a stamp list file check if it is really out of date.
  2244. if (!this->CheckStampList.empty() &&
  2245. cmakeCheckStampList(this->CheckStampList)) {
  2246. return 0;
  2247. }
  2248. // If we are given a stamp file check if it is really out of date.
  2249. if (!this->CheckStampFile.empty() &&
  2250. cmakeCheckStampFile(this->CheckStampFile)) {
  2251. return 0;
  2252. }
  2253. if (this->GetWorkingMode() == NORMAL_MODE) {
  2254. if (this->FreshCache) {
  2255. this->DeleteCache(this->GetHomeOutputDirectory());
  2256. }
  2257. // load the cache
  2258. if (this->LoadCache() < 0) {
  2259. cmSystemTools::Error("Error executing cmake::LoadCache(). Aborting.\n");
  2260. return -1;
  2261. }
  2262. } else {
  2263. if (this->FreshCache) {
  2264. cmSystemTools::Error("--fresh allowed only when configuring a project");
  2265. return -1;
  2266. }
  2267. this->AddCMakePaths();
  2268. }
  2269. #ifndef CMAKE_BOOTSTRAP
  2270. this->ProcessPresetVariables();
  2271. this->ProcessPresetEnvironment();
  2272. #endif
  2273. // Add any cache args
  2274. if (!this->SetCacheArgs(args)) {
  2275. cmSystemTools::Error("Run 'cmake --help' for all supported options.");
  2276. return -1;
  2277. }
  2278. #ifndef CMAKE_BOOTSTRAP
  2279. this->PrintPresetVariables();
  2280. this->PrintPresetEnvironment();
  2281. #endif
  2282. // In script mode we terminate after running the script.
  2283. if (this->GetWorkingMode() != NORMAL_MODE) {
  2284. if (cmSystemTools::GetErrorOccurredFlag()) {
  2285. return -1;
  2286. }
  2287. return 0;
  2288. }
  2289. // If MAKEFLAGS are given in the environment, remove the environment
  2290. // variable. This will prevent try-compile from succeeding when it
  2291. // should fail (if "-i" is an option). We cannot simply test
  2292. // whether "-i" is given and remove it because some make programs
  2293. // encode the MAKEFLAGS variable in a strange way.
  2294. if (cmSystemTools::HasEnv("MAKEFLAGS")) {
  2295. cmSystemTools::PutEnv("MAKEFLAGS=");
  2296. }
  2297. this->PreLoadCMakeFiles();
  2298. if (noconfigure) {
  2299. return 0;
  2300. }
  2301. // now run the global generate
  2302. // Check the state of the build system to see if we need to regenerate.
  2303. if (!this->CheckBuildSystem()) {
  2304. return 0;
  2305. }
  2306. int ret = this->Configure();
  2307. if (ret) {
  2308. #if defined(CMAKE_HAVE_VS_GENERATORS)
  2309. if (!this->VSSolutionFile.empty() && this->GlobalGenerator) {
  2310. // CMake is running to regenerate a Visual Studio build tree
  2311. // during a build from the VS IDE. The build files cannot be
  2312. // regenerated, so we should stop the build.
  2313. cmSystemTools::Message("CMake Configure step failed. "
  2314. "Build files cannot be regenerated correctly. "
  2315. "Attempting to stop IDE build.");
  2316. cmGlobalVisualStudioGenerator& gg =
  2317. cm::static_reference_cast<cmGlobalVisualStudioGenerator>(
  2318. this->GlobalGenerator);
  2319. gg.CallVisualStudioMacro(cmGlobalVisualStudioGenerator::MacroStop,
  2320. this->VSSolutionFile);
  2321. }
  2322. #endif
  2323. return ret;
  2324. }
  2325. ret = this->Generate();
  2326. if (ret) {
  2327. cmSystemTools::Message("CMake Generate step failed. "
  2328. "Build files cannot be regenerated correctly.");
  2329. return ret;
  2330. }
  2331. std::string message = cmStrCat("Build files have been written to: ",
  2332. this->GetHomeOutputDirectory());
  2333. this->UpdateProgress(message, -1);
  2334. return ret;
  2335. }
  2336. int cmake::Generate()
  2337. {
  2338. if (!this->GlobalGenerator) {
  2339. return -1;
  2340. }
  2341. if (!this->GlobalGenerator->Compute()) {
  2342. return -1;
  2343. }
  2344. this->GlobalGenerator->Generate();
  2345. if (!this->GraphVizFile.empty()) {
  2346. std::cout << "Generate graphviz: " << this->GraphVizFile << std::endl;
  2347. this->GenerateGraphViz(this->GraphVizFile);
  2348. }
  2349. if (this->WarnUnusedCli) {
  2350. this->RunCheckForUnusedVariables();
  2351. }
  2352. if (cmSystemTools::GetErrorOccurredFlag()) {
  2353. return -1;
  2354. }
  2355. // Save the cache again after a successful Generate so that any internal
  2356. // variables created during Generate are saved. (Specifically target GUIDs
  2357. // for the Visual Studio and Xcode generators.)
  2358. this->SaveCache(this->GetHomeOutputDirectory());
  2359. #if !defined(CMAKE_BOOTSTRAP)
  2360. this->FileAPI->WriteReplies();
  2361. #endif
  2362. return 0;
  2363. }
  2364. void cmake::AddCacheEntry(const std::string& key, cmValue value,
  2365. const char* helpString, int type)
  2366. {
  2367. this->State->AddCacheEntry(key, value, helpString,
  2368. static_cast<cmStateEnums::CacheEntryType>(type));
  2369. this->UnwatchUnusedCli(key);
  2370. if (key == "CMAKE_WARN_DEPRECATED"_s) {
  2371. this->Messenger->SetSuppressDeprecatedWarnings(value && cmIsOff(value));
  2372. } else if (key == "CMAKE_ERROR_DEPRECATED"_s) {
  2373. this->Messenger->SetDeprecatedWarningsAsErrors(cmIsOn(value));
  2374. } else if (key == "CMAKE_SUPPRESS_DEVELOPER_WARNINGS"_s) {
  2375. this->Messenger->SetSuppressDevWarnings(cmIsOn(value));
  2376. } else if (key == "CMAKE_SUPPRESS_DEVELOPER_ERRORS"_s) {
  2377. this->Messenger->SetDevWarningsAsErrors(value && cmIsOff(value));
  2378. }
  2379. }
  2380. bool cmake::DoWriteGlobVerifyTarget() const
  2381. {
  2382. return this->State->DoWriteGlobVerifyTarget();
  2383. }
  2384. std::string const& cmake::GetGlobVerifyScript() const
  2385. {
  2386. return this->State->GetGlobVerifyScript();
  2387. }
  2388. std::string const& cmake::GetGlobVerifyStamp() const
  2389. {
  2390. return this->State->GetGlobVerifyStamp();
  2391. }
  2392. void cmake::AddGlobCacheEntry(bool recurse, bool listDirectories,
  2393. bool followSymlinks, const std::string& relative,
  2394. const std::string& expression,
  2395. const std::vector<std::string>& files,
  2396. const std::string& variable,
  2397. cmListFileBacktrace const& backtrace)
  2398. {
  2399. this->State->AddGlobCacheEntry(recurse, listDirectories, followSymlinks,
  2400. relative, expression, files, variable,
  2401. backtrace, this->Messenger.get());
  2402. }
  2403. std::vector<std::string> cmake::GetAllExtensions() const
  2404. {
  2405. std::vector<std::string> allExt = this->CLikeSourceFileExtensions.ordered;
  2406. allExt.insert(allExt.end(), this->HeaderFileExtensions.ordered.begin(),
  2407. this->HeaderFileExtensions.ordered.end());
  2408. // cuda extensions are also in SourceFileExtensions so we ignore it here
  2409. allExt.insert(allExt.end(), this->FortranFileExtensions.ordered.begin(),
  2410. this->FortranFileExtensions.ordered.end());
  2411. allExt.insert(allExt.end(), this->HipFileExtensions.ordered.begin(),
  2412. this->HipFileExtensions.ordered.end());
  2413. allExt.insert(allExt.end(), this->ISPCFileExtensions.ordered.begin(),
  2414. this->ISPCFileExtensions.ordered.end());
  2415. return allExt;
  2416. }
  2417. std::string cmake::StripExtension(const std::string& file) const
  2418. {
  2419. auto dotpos = file.rfind('.');
  2420. if (dotpos != std::string::npos) {
  2421. #if defined(_WIN32) || defined(__APPLE__)
  2422. auto ext = cmSystemTools::LowerCase(file.substr(dotpos + 1));
  2423. #else
  2424. auto ext = cm::string_view(file).substr(dotpos + 1);
  2425. #endif
  2426. if (this->IsAKnownExtension(ext)) {
  2427. return file.substr(0, dotpos);
  2428. }
  2429. }
  2430. return file;
  2431. }
  2432. cmValue cmake::GetCacheDefinition(const std::string& name) const
  2433. {
  2434. return this->State->GetInitializedCacheValue(name);
  2435. }
  2436. void cmake::AddScriptingCommands() const
  2437. {
  2438. GetScriptingCommands(this->GetState());
  2439. }
  2440. void cmake::AddProjectCommands() const
  2441. {
  2442. GetProjectCommands(this->GetState());
  2443. }
  2444. void cmake::AddDefaultGenerators()
  2445. {
  2446. #if defined(_WIN32) && !defined(__CYGWIN__)
  2447. # if !defined(CMAKE_BOOT_MINGW)
  2448. this->Generators.push_back(
  2449. cmGlobalVisualStudioVersionedGenerator::NewFactory17());
  2450. this->Generators.push_back(
  2451. cmGlobalVisualStudioVersionedGenerator::NewFactory16());
  2452. this->Generators.push_back(
  2453. cmGlobalVisualStudioVersionedGenerator::NewFactory15());
  2454. this->Generators.push_back(cmGlobalVisualStudio14Generator::NewFactory());
  2455. this->Generators.push_back(cmGlobalVisualStudio12Generator::NewFactory());
  2456. this->Generators.push_back(cmGlobalVisualStudio11Generator::NewFactory());
  2457. this->Generators.push_back(cmGlobalVisualStudio9Generator::NewFactory());
  2458. this->Generators.push_back(cmGlobalBorlandMakefileGenerator::NewFactory());
  2459. this->Generators.push_back(cmGlobalNMakeMakefileGenerator::NewFactory());
  2460. this->Generators.push_back(cmGlobalJOMMakefileGenerator::NewFactory());
  2461. # endif
  2462. this->Generators.push_back(cmGlobalMSYSMakefileGenerator::NewFactory());
  2463. this->Generators.push_back(cmGlobalMinGWMakefileGenerator::NewFactory());
  2464. #endif
  2465. #if !defined(CMAKE_BOOTSTRAP)
  2466. # if (defined(__linux__) && !defined(__ANDROID__)) || defined(_WIN32)
  2467. this->Generators.push_back(cmGlobalGhsMultiGenerator::NewFactory());
  2468. # endif
  2469. this->Generators.push_back(cmGlobalUnixMakefileGenerator3::NewFactory());
  2470. this->Generators.push_back(cmGlobalNinjaGenerator::NewFactory());
  2471. this->Generators.push_back(cmGlobalNinjaMultiGenerator::NewFactory());
  2472. #elif defined(CMAKE_BOOTSTRAP_NINJA)
  2473. this->Generators.push_back(cmGlobalNinjaGenerator::NewFactory());
  2474. #elif defined(CMAKE_BOOTSTRAP_MAKEFILES)
  2475. this->Generators.push_back(cmGlobalUnixMakefileGenerator3::NewFactory());
  2476. #endif
  2477. #if defined(CMAKE_USE_WMAKE)
  2478. this->Generators.push_back(cmGlobalWatcomWMakeGenerator::NewFactory());
  2479. #endif
  2480. #ifdef CMAKE_USE_XCODE
  2481. this->Generators.push_back(cmGlobalXCodeGenerator::NewFactory());
  2482. #endif
  2483. }
  2484. bool cmake::ParseCacheEntry(const std::string& entry, std::string& var,
  2485. std::string& value,
  2486. cmStateEnums::CacheEntryType& type)
  2487. {
  2488. return cmState::ParseCacheEntry(entry, var, value, type);
  2489. }
  2490. int cmake::LoadCache()
  2491. {
  2492. // could we not read the cache
  2493. if (!this->LoadCache(this->GetHomeOutputDirectory())) {
  2494. // if it does exist, but isn't readable then warn the user
  2495. std::string cacheFile =
  2496. cmStrCat(this->GetHomeOutputDirectory(), "/CMakeCache.txt");
  2497. if (cmSystemTools::FileExists(cacheFile)) {
  2498. cmSystemTools::Error(
  2499. "There is a CMakeCache.txt file for the current binary tree but "
  2500. "cmake does not have permission to read it. Please check the "
  2501. "permissions of the directory you are trying to run CMake on.");
  2502. return -1;
  2503. }
  2504. }
  2505. // setup CMAKE_ROOT and CMAKE_COMMAND
  2506. if (!this->AddCMakePaths()) {
  2507. return -3;
  2508. }
  2509. return 0;
  2510. }
  2511. bool cmake::LoadCache(const std::string& path)
  2512. {
  2513. std::set<std::string> emptySet;
  2514. return this->LoadCache(path, true, emptySet, emptySet);
  2515. }
  2516. bool cmake::LoadCache(const std::string& path, bool internal,
  2517. std::set<std::string>& excludes,
  2518. std::set<std::string>& includes)
  2519. {
  2520. bool result = this->State->LoadCache(path, internal, excludes, includes);
  2521. static const auto entries = { "CMAKE_CACHE_MAJOR_VERSION",
  2522. "CMAKE_CACHE_MINOR_VERSION" };
  2523. for (auto const& entry : entries) {
  2524. this->UnwatchUnusedCli(entry);
  2525. }
  2526. return result;
  2527. }
  2528. bool cmake::SaveCache(const std::string& path)
  2529. {
  2530. bool result = this->State->SaveCache(path, this->GetMessenger());
  2531. static const auto entries = { "CMAKE_CACHE_MAJOR_VERSION",
  2532. "CMAKE_CACHE_MINOR_VERSION",
  2533. "CMAKE_CACHE_PATCH_VERSION",
  2534. "CMAKE_CACHEFILE_DIR" };
  2535. for (auto const& entry : entries) {
  2536. this->UnwatchUnusedCli(entry);
  2537. }
  2538. return result;
  2539. }
  2540. bool cmake::DeleteCache(const std::string& path)
  2541. {
  2542. return this->State->DeleteCache(path);
  2543. }
  2544. void cmake::SetProgressCallback(ProgressCallbackType f)
  2545. {
  2546. this->ProgressCallback = std::move(f);
  2547. }
  2548. void cmake::UpdateProgress(const std::string& msg, float prog)
  2549. {
  2550. if (this->ProgressCallback && !this->GetIsInTryCompile()) {
  2551. this->ProgressCallback(msg, prog);
  2552. }
  2553. }
  2554. bool cmake::GetIsInTryCompile() const
  2555. {
  2556. return this->State->GetProjectKind() == cmState::ProjectKind::TryCompile;
  2557. }
  2558. void cmake::AppendGlobalGeneratorsDocumentation(
  2559. std::vector<cmDocumentationEntry>& v)
  2560. {
  2561. const auto defaultGenerator = this->EvaluateDefaultGlobalGenerator();
  2562. const std::string defaultName = defaultGenerator->GetName();
  2563. bool foundDefaultOne = false;
  2564. for (const auto& g : this->Generators) {
  2565. cmDocumentationEntry e;
  2566. g->GetDocumentation(e);
  2567. if (!foundDefaultOne && cmHasPrefix(e.Name, defaultName)) {
  2568. e.CustomNamePrefix = '*';
  2569. foundDefaultOne = true;
  2570. }
  2571. v.push_back(std::move(e));
  2572. }
  2573. }
  2574. void cmake::AppendExtraGeneratorsDocumentation(
  2575. std::vector<cmDocumentationEntry>& v)
  2576. {
  2577. for (cmExternalMakefileProjectGeneratorFactory* eg : this->ExtraGenerators) {
  2578. const std::string doc = eg->GetDocumentation();
  2579. const std::string name = eg->GetName();
  2580. // Aliases:
  2581. for (std::string const& a : eg->Aliases) {
  2582. cmDocumentationEntry e;
  2583. e.Name = a;
  2584. e.Brief = doc;
  2585. v.push_back(std::move(e));
  2586. }
  2587. // Full names:
  2588. const std::vector<std::string> generators =
  2589. eg->GetSupportedGlobalGenerators();
  2590. for (std::string const& g : generators) {
  2591. cmDocumentationEntry e;
  2592. e.Name =
  2593. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(g, name);
  2594. e.Brief = doc;
  2595. v.push_back(std::move(e));
  2596. }
  2597. }
  2598. }
  2599. std::vector<cmDocumentationEntry> cmake::GetGeneratorsDocumentation()
  2600. {
  2601. std::vector<cmDocumentationEntry> v;
  2602. this->AppendGlobalGeneratorsDocumentation(v);
  2603. this->AppendExtraGeneratorsDocumentation(v);
  2604. return v;
  2605. }
  2606. void cmake::PrintGeneratorList()
  2607. {
  2608. #ifndef CMAKE_BOOTSTRAP
  2609. cmDocumentation doc;
  2610. auto generators = this->GetGeneratorsDocumentation();
  2611. doc.AppendSection("Generators", generators);
  2612. std::cerr << "\n";
  2613. doc.PrintDocumentation(cmDocumentation::ListGenerators, std::cerr);
  2614. #endif
  2615. }
  2616. void cmake::UpdateConversionPathTable()
  2617. {
  2618. // Update the path conversion table with any specified file:
  2619. cmValue tablepath =
  2620. this->State->GetInitializedCacheValue("CMAKE_PATH_TRANSLATION_FILE");
  2621. if (tablepath) {
  2622. cmsys::ifstream table(tablepath->c_str());
  2623. if (!table) {
  2624. cmSystemTools::Error("CMAKE_PATH_TRANSLATION_FILE set to " + *tablepath +
  2625. ". CMake can not open file.");
  2626. cmSystemTools::ReportLastSystemError("CMake can not open file.");
  2627. } else {
  2628. std::string a;
  2629. std::string b;
  2630. while (!table.eof()) {
  2631. // two entries per line
  2632. table >> a;
  2633. table >> b;
  2634. cmSystemTools::AddTranslationPath(a, b);
  2635. }
  2636. }
  2637. }
  2638. }
  2639. int cmake::CheckBuildSystem()
  2640. {
  2641. // We do not need to rerun CMake. Check dependency integrity.
  2642. const bool verbose = isCMakeVerbose();
  2643. // This method will check the integrity of the build system if the
  2644. // option was given on the command line. It reads the given file to
  2645. // determine whether CMake should rerun.
  2646. // If no file is provided for the check, we have to rerun.
  2647. if (this->CheckBuildSystemArgument.empty()) {
  2648. if (verbose) {
  2649. cmSystemTools::Stdout("Re-run cmake no build system arguments\n");
  2650. }
  2651. return 1;
  2652. }
  2653. // If the file provided does not exist, we have to rerun.
  2654. if (!cmSystemTools::FileExists(this->CheckBuildSystemArgument)) {
  2655. if (verbose) {
  2656. std::ostringstream msg;
  2657. msg << "Re-run cmake missing file: " << this->CheckBuildSystemArgument
  2658. << "\n";
  2659. cmSystemTools::Stdout(msg.str());
  2660. }
  2661. return 1;
  2662. }
  2663. // Read the rerun check file and use it to decide whether to do the
  2664. // global generate.
  2665. // Actually, all we need is the `set` command.
  2666. cmake cm(RoleScript, cmState::Unknown);
  2667. cm.SetHomeDirectory("");
  2668. cm.SetHomeOutputDirectory("");
  2669. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  2670. cmGlobalGenerator gg(&cm);
  2671. cmMakefile mf(&gg, cm.GetCurrentSnapshot());
  2672. if (!mf.ReadListFile(this->CheckBuildSystemArgument) ||
  2673. cmSystemTools::GetErrorOccurredFlag()) {
  2674. if (verbose) {
  2675. std::ostringstream msg;
  2676. msg << "Re-run cmake error reading : " << this->CheckBuildSystemArgument
  2677. << "\n";
  2678. cmSystemTools::Stdout(msg.str());
  2679. }
  2680. // There was an error reading the file. Just rerun.
  2681. return 1;
  2682. }
  2683. if (this->ClearBuildSystem) {
  2684. // Get the generator used for this build system.
  2685. std::string genName = mf.GetSafeDefinition("CMAKE_DEPENDS_GENERATOR");
  2686. if (!cmNonempty(genName)) {
  2687. genName = "Unix Makefiles";
  2688. }
  2689. // Create the generator and use it to clear the dependencies.
  2690. std::unique_ptr<cmGlobalGenerator> ggd =
  2691. this->CreateGlobalGenerator(genName);
  2692. if (ggd) {
  2693. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  2694. cmMakefile mfd(ggd.get(), cm.GetCurrentSnapshot());
  2695. auto lgd = ggd->CreateLocalGenerator(&mfd);
  2696. lgd->ClearDependencies(&mfd, verbose);
  2697. }
  2698. }
  2699. // If any byproduct of makefile generation is missing we must re-run.
  2700. std::vector<std::string> products;
  2701. mf.GetDefExpandList("CMAKE_MAKEFILE_PRODUCTS", products);
  2702. for (std::string const& p : products) {
  2703. if (!(cmSystemTools::FileExists(p) || cmSystemTools::FileIsSymlink(p))) {
  2704. if (verbose) {
  2705. std::ostringstream msg;
  2706. msg << "Re-run cmake, missing byproduct: " << p << "\n";
  2707. cmSystemTools::Stdout(msg.str());
  2708. }
  2709. return 1;
  2710. }
  2711. }
  2712. // Get the set of dependencies and outputs.
  2713. std::vector<std::string> depends;
  2714. std::vector<std::string> outputs;
  2715. if (mf.GetDefExpandList("CMAKE_MAKEFILE_DEPENDS", depends)) {
  2716. mf.GetDefExpandList("CMAKE_MAKEFILE_OUTPUTS", outputs);
  2717. }
  2718. if (depends.empty() || outputs.empty()) {
  2719. // Not enough information was provided to do the test. Just rerun.
  2720. if (verbose) {
  2721. cmSystemTools::Stdout("Re-run cmake no CMAKE_MAKEFILE_DEPENDS "
  2722. "or CMAKE_MAKEFILE_OUTPUTS :\n");
  2723. }
  2724. return 1;
  2725. }
  2726. // Find the newest dependency.
  2727. auto dep = depends.begin();
  2728. std::string dep_newest = *dep++;
  2729. for (; dep != depends.end(); ++dep) {
  2730. int result = 0;
  2731. if (this->FileTimeCache->Compare(dep_newest, *dep, &result)) {
  2732. if (result < 0) {
  2733. dep_newest = *dep;
  2734. }
  2735. } else {
  2736. if (verbose) {
  2737. cmSystemTools::Stdout(
  2738. "Re-run cmake: build system dependency is missing\n");
  2739. }
  2740. return 1;
  2741. }
  2742. }
  2743. // Find the oldest output.
  2744. auto out = outputs.begin();
  2745. std::string out_oldest = *out++;
  2746. for (; out != outputs.end(); ++out) {
  2747. int result = 0;
  2748. if (this->FileTimeCache->Compare(out_oldest, *out, &result)) {
  2749. if (result > 0) {
  2750. out_oldest = *out;
  2751. }
  2752. } else {
  2753. if (verbose) {
  2754. cmSystemTools::Stdout(
  2755. "Re-run cmake: build system output is missing\n");
  2756. }
  2757. return 1;
  2758. }
  2759. }
  2760. // If any output is older than any dependency then rerun.
  2761. {
  2762. int result = 0;
  2763. if (!this->FileTimeCache->Compare(out_oldest, dep_newest, &result) ||
  2764. result < 0) {
  2765. if (verbose) {
  2766. std::ostringstream msg;
  2767. msg << "Re-run cmake file: " << out_oldest
  2768. << " older than: " << dep_newest << "\n";
  2769. cmSystemTools::Stdout(msg.str());
  2770. }
  2771. return 1;
  2772. }
  2773. }
  2774. // No need to rerun.
  2775. return 0;
  2776. }
  2777. void cmake::TruncateOutputLog(const char* fname)
  2778. {
  2779. std::string fullPath = cmStrCat(this->GetHomeOutputDirectory(), '/', fname);
  2780. struct stat st;
  2781. if (::stat(fullPath.c_str(), &st)) {
  2782. return;
  2783. }
  2784. if (!this->State->GetInitializedCacheValue("CMAKE_CACHEFILE_DIR")) {
  2785. cmSystemTools::RemoveFile(fullPath);
  2786. return;
  2787. }
  2788. off_t fsize = st.st_size;
  2789. const off_t maxFileSize = 50 * 1024;
  2790. if (fsize < maxFileSize) {
  2791. // TODO: truncate file
  2792. return;
  2793. }
  2794. }
  2795. void cmake::MarkCliAsUsed(const std::string& variable)
  2796. {
  2797. this->UsedCliVariables[variable] = true;
  2798. }
  2799. void cmake::GenerateGraphViz(const std::string& fileName) const
  2800. {
  2801. #ifndef CMAKE_BOOTSTRAP
  2802. cmGraphVizWriter gvWriter(fileName, this->GetGlobalGenerator());
  2803. std::string settingsFile =
  2804. cmStrCat(this->GetHomeOutputDirectory(), "/CMakeGraphVizOptions.cmake");
  2805. std::string fallbackSettingsFile =
  2806. cmStrCat(this->GetHomeDirectory(), "/CMakeGraphVizOptions.cmake");
  2807. gvWriter.ReadSettings(settingsFile, fallbackSettingsFile);
  2808. gvWriter.Write();
  2809. #endif
  2810. }
  2811. void cmake::SetProperty(const std::string& prop, const char* value)
  2812. {
  2813. this->State->SetGlobalProperty(prop, value);
  2814. }
  2815. void cmake::SetProperty(const std::string& prop, cmValue value)
  2816. {
  2817. this->State->SetGlobalProperty(prop, value);
  2818. }
  2819. void cmake::AppendProperty(const std::string& prop, const std::string& value,
  2820. bool asString)
  2821. {
  2822. this->State->AppendGlobalProperty(prop, value, asString);
  2823. }
  2824. cmValue cmake::GetProperty(const std::string& prop)
  2825. {
  2826. return this->State->GetGlobalProperty(prop);
  2827. }
  2828. bool cmake::GetPropertyAsBool(const std::string& prop)
  2829. {
  2830. return this->State->GetGlobalPropertyAsBool(prop);
  2831. }
  2832. cmInstalledFile* cmake::GetOrCreateInstalledFile(cmMakefile* mf,
  2833. const std::string& name)
  2834. {
  2835. auto i = this->InstalledFiles.find(name);
  2836. if (i != this->InstalledFiles.end()) {
  2837. cmInstalledFile& file = i->second;
  2838. return &file;
  2839. }
  2840. cmInstalledFile& file = this->InstalledFiles[name];
  2841. file.SetName(mf, name);
  2842. return &file;
  2843. }
  2844. cmInstalledFile const* cmake::GetInstalledFile(const std::string& name) const
  2845. {
  2846. auto i = this->InstalledFiles.find(name);
  2847. if (i != this->InstalledFiles.end()) {
  2848. cmInstalledFile const& file = i->second;
  2849. return &file;
  2850. }
  2851. return nullptr;
  2852. }
  2853. int cmake::GetSystemInformation(std::vector<std::string>& args)
  2854. {
  2855. // so create the directory
  2856. std::string resultFile;
  2857. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  2858. std::string destPath = cwd + "/__cmake_systeminformation";
  2859. cmSystemTools::RemoveADirectory(destPath);
  2860. if (!cmSystemTools::MakeDirectory(destPath)) {
  2861. std::cerr << "Error: --system-information must be run from a "
  2862. "writable directory!\n";
  2863. return 1;
  2864. }
  2865. // process the arguments
  2866. bool writeToStdout = true;
  2867. for (unsigned int i = 1; i < args.size(); ++i) {
  2868. std::string const& arg = args[i];
  2869. if (cmHasLiteralPrefix(arg, "-G")) {
  2870. std::string value = arg.substr(2);
  2871. if (value.empty()) {
  2872. ++i;
  2873. if (i >= args.size()) {
  2874. cmSystemTools::Error("No generator specified for -G");
  2875. this->PrintGeneratorList();
  2876. return -1;
  2877. }
  2878. value = args[i];
  2879. }
  2880. auto gen = this->CreateGlobalGenerator(value);
  2881. if (!gen) {
  2882. cmSystemTools::Error("Could not create named generator " + value);
  2883. this->PrintGeneratorList();
  2884. } else {
  2885. this->SetGlobalGenerator(std::move(gen));
  2886. }
  2887. }
  2888. // no option assume it is the output file
  2889. else {
  2890. if (!cmSystemTools::FileIsFullPath(arg)) {
  2891. resultFile = cmStrCat(cwd, '/');
  2892. }
  2893. resultFile += arg;
  2894. writeToStdout = false;
  2895. }
  2896. }
  2897. // we have to find the module directory, so we can copy the files
  2898. this->AddCMakePaths();
  2899. std::string modulesPath =
  2900. cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules");
  2901. std::string inFile = cmStrCat(modulesPath, "/SystemInformation.cmake");
  2902. std::string outFile = cmStrCat(destPath, "/CMakeLists.txt");
  2903. // Copy file
  2904. if (!cmsys::SystemTools::CopyFileAlways(inFile, outFile)) {
  2905. std::cerr << "Error copying file \"" << inFile << "\" to \"" << outFile
  2906. << "\".\n";
  2907. return 1;
  2908. }
  2909. // do we write to a file or to stdout?
  2910. if (resultFile.empty()) {
  2911. resultFile = cmStrCat(cwd, "/__cmake_systeminformation/results.txt");
  2912. }
  2913. {
  2914. // now run cmake on the CMakeLists file
  2915. cmWorkingDirectory workdir(destPath);
  2916. if (workdir.Failed()) {
  2917. // We created the directory and we were able to copy the CMakeLists.txt
  2918. // file to it, so we wouldn't expect to get here unless the default
  2919. // permissions are questionable or some other process has deleted the
  2920. // directory
  2921. std::cerr << "Failed to change to directory " << destPath << " : "
  2922. << std::strerror(workdir.GetLastResult()) << std::endl;
  2923. return 1;
  2924. }
  2925. std::vector<std::string> args2;
  2926. args2.push_back(args[0]);
  2927. args2.push_back(destPath);
  2928. args2.push_back("-DRESULT_FILE=" + resultFile);
  2929. int res = this->Run(args2, false);
  2930. if (res != 0) {
  2931. std::cerr << "Error: --system-information failed on internal CMake!\n";
  2932. return res;
  2933. }
  2934. }
  2935. // echo results to stdout if needed
  2936. if (writeToStdout) {
  2937. FILE* fin = cmsys::SystemTools::Fopen(resultFile, "r");
  2938. if (fin) {
  2939. const int bufferSize = 4096;
  2940. char buffer[bufferSize];
  2941. size_t n;
  2942. while ((n = fread(buffer, 1, bufferSize, fin)) > 0) {
  2943. for (char* c = buffer; c < buffer + n; ++c) {
  2944. putc(*c, stdout);
  2945. }
  2946. fflush(stdout);
  2947. }
  2948. fclose(fin);
  2949. }
  2950. }
  2951. // clean up the directory
  2952. cmSystemTools::RemoveADirectory(destPath);
  2953. return 0;
  2954. }
  2955. static bool cmakeCheckStampFile(const std::string& stampName)
  2956. {
  2957. // The stamp file does not exist. Use the stamp dependencies to
  2958. // determine whether it is really out of date. This works in
  2959. // conjunction with cmLocalVisualStudio7Generator to avoid
  2960. // repeatedly re-running CMake when the user rebuilds the entire
  2961. // solution.
  2962. std::string stampDepends = cmStrCat(stampName, ".depend");
  2963. #if defined(_WIN32) || defined(__CYGWIN__)
  2964. cmsys::ifstream fin(stampDepends.c_str(), std::ios::in | std::ios::binary);
  2965. #else
  2966. cmsys::ifstream fin(stampDepends.c_str());
  2967. #endif
  2968. if (!fin) {
  2969. // The stamp dependencies file cannot be read. Just assume the
  2970. // build system is really out of date.
  2971. std::cout << "CMake is re-running because " << stampName
  2972. << " dependency file is missing.\n";
  2973. return false;
  2974. }
  2975. // Compare the stamp dependencies against the dependency file itself.
  2976. {
  2977. cmFileTimeCache ftc;
  2978. std::string dep;
  2979. while (cmSystemTools::GetLineFromStream(fin, dep)) {
  2980. int result;
  2981. if (!dep.empty() && dep[0] != '#' &&
  2982. (!ftc.Compare(stampDepends, dep, &result) || result < 0)) {
  2983. // The stamp depends file is older than this dependency. The
  2984. // build system is really out of date.
  2985. std::cout << "CMake is re-running because " << stampName
  2986. << " is out-of-date.\n";
  2987. std::cout << " the file '" << dep << "'\n";
  2988. std::cout << " is newer than '" << stampDepends << "'\n";
  2989. std::cout << " result='" << result << "'\n";
  2990. return false;
  2991. }
  2992. }
  2993. }
  2994. // The build system is up to date. The stamp file has been removed
  2995. // by the VS IDE due to a "rebuild" request. Restore it atomically.
  2996. std::ostringstream stampTempStream;
  2997. stampTempStream << stampName << ".tmp" << cmSystemTools::RandomSeed();
  2998. std::string stampTemp = stampTempStream.str();
  2999. {
  3000. // TODO: Teach cmGeneratedFileStream to use a random temp file (with
  3001. // multiple tries in unlikely case of conflict) and use that here.
  3002. cmsys::ofstream stamp(stampTemp.c_str());
  3003. stamp << "# CMake generation timestamp file for this directory.\n";
  3004. }
  3005. std::string err;
  3006. if (cmSystemTools::RenameFile(stampTemp, stampName,
  3007. cmSystemTools::Replace::Yes, &err) ==
  3008. cmSystemTools::RenameResult::Success) {
  3009. // CMake does not need to re-run because the stamp file is up-to-date.
  3010. return true;
  3011. }
  3012. cmSystemTools::RemoveFile(stampTemp);
  3013. cmSystemTools::Error(
  3014. cmStrCat("Cannot restore timestamp \"", stampName, "\": ", err));
  3015. return false;
  3016. }
  3017. static bool cmakeCheckStampList(const std::string& stampList)
  3018. {
  3019. // If the stamp list does not exist CMake must rerun to generate it.
  3020. if (!cmSystemTools::FileExists(stampList)) {
  3021. std::cout << "CMake is re-running because generate.stamp.list "
  3022. << "is missing.\n";
  3023. return false;
  3024. }
  3025. cmsys::ifstream fin(stampList.c_str());
  3026. if (!fin) {
  3027. std::cout << "CMake is re-running because generate.stamp.list "
  3028. << "could not be read.\n";
  3029. return false;
  3030. }
  3031. // Check each stamp.
  3032. std::string stampName;
  3033. while (cmSystemTools::GetLineFromStream(fin, stampName)) {
  3034. if (!cmakeCheckStampFile(stampName)) {
  3035. return false;
  3036. }
  3037. }
  3038. return true;
  3039. }
  3040. void cmake::IssueMessage(MessageType t, std::string const& text,
  3041. cmListFileBacktrace const& backtrace) const
  3042. {
  3043. this->Messenger->IssueMessage(t, text, backtrace);
  3044. }
  3045. std::vector<std::string> cmake::GetDebugConfigs()
  3046. {
  3047. std::vector<std::string> configs;
  3048. if (cmValue config_list =
  3049. this->State->GetGlobalProperty("DEBUG_CONFIGURATIONS")) {
  3050. // Expand the specified list and convert to upper-case.
  3051. cmExpandList(*config_list, configs);
  3052. std::transform(configs.begin(), configs.end(), configs.begin(),
  3053. cmSystemTools::UpperCase);
  3054. }
  3055. // If no configurations were specified, use a default list.
  3056. if (configs.empty()) {
  3057. configs.emplace_back("DEBUG");
  3058. }
  3059. return configs;
  3060. }
  3061. int cmake::Build(int jobs, std::string dir, std::vector<std::string> targets,
  3062. std::string config, std::vector<std::string> nativeOptions,
  3063. cmBuildOptions& buildOptions, bool verbose,
  3064. const std::string& presetName, bool listPresets)
  3065. {
  3066. this->SetHomeDirectory("");
  3067. this->SetHomeOutputDirectory("");
  3068. #if !defined(CMAKE_BOOTSTRAP)
  3069. if (!presetName.empty() || listPresets) {
  3070. this->SetHomeDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  3071. this->SetHomeOutputDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  3072. cmCMakePresetsGraph settingsFile;
  3073. auto result = settingsFile.ReadProjectPresets(this->GetHomeDirectory());
  3074. if (result != cmCMakePresetsGraph::ReadFileResult::READ_OK) {
  3075. cmSystemTools::Error(
  3076. cmStrCat("Could not read presets from ", this->GetHomeDirectory(),
  3077. ": ", cmCMakePresetsGraph::ResultToString(result)));
  3078. return 1;
  3079. }
  3080. if (listPresets) {
  3081. settingsFile.PrintBuildPresetList();
  3082. return 0;
  3083. }
  3084. auto presetPair = settingsFile.BuildPresets.find(presetName);
  3085. if (presetPair == settingsFile.BuildPresets.end()) {
  3086. cmSystemTools::Error(cmStrCat("No such build preset in ",
  3087. this->GetHomeDirectory(), ": \"",
  3088. presetName, '"'));
  3089. settingsFile.PrintBuildPresetList();
  3090. return 1;
  3091. }
  3092. if (presetPair->second.Unexpanded.Hidden) {
  3093. cmSystemTools::Error(cmStrCat("Cannot use hidden build preset in ",
  3094. this->GetHomeDirectory(), ": \"",
  3095. presetName, '"'));
  3096. settingsFile.PrintBuildPresetList();
  3097. return 1;
  3098. }
  3099. auto const& expandedPreset = presetPair->second.Expanded;
  3100. if (!expandedPreset) {
  3101. cmSystemTools::Error(cmStrCat("Could not evaluate build preset \"",
  3102. presetName,
  3103. "\": Invalid macro expansion"));
  3104. settingsFile.PrintBuildPresetList();
  3105. return 1;
  3106. }
  3107. if (!expandedPreset->ConditionResult) {
  3108. cmSystemTools::Error(cmStrCat("Cannot use disabled build preset in ",
  3109. this->GetHomeDirectory(), ": \"",
  3110. presetName, '"'));
  3111. settingsFile.PrintBuildPresetList();
  3112. return 1;
  3113. }
  3114. auto configurePresetPair =
  3115. settingsFile.ConfigurePresets.find(expandedPreset->ConfigurePreset);
  3116. if (configurePresetPair == settingsFile.ConfigurePresets.end()) {
  3117. cmSystemTools::Error(cmStrCat("No such configure preset in ",
  3118. this->GetHomeDirectory(), ": \"",
  3119. expandedPreset->ConfigurePreset, '"'));
  3120. this->PrintPresetList(settingsFile);
  3121. return 1;
  3122. }
  3123. if (configurePresetPair->second.Unexpanded.Hidden) {
  3124. cmSystemTools::Error(cmStrCat("Cannot use hidden configure preset in ",
  3125. this->GetHomeDirectory(), ": \"",
  3126. expandedPreset->ConfigurePreset, '"'));
  3127. this->PrintPresetList(settingsFile);
  3128. return 1;
  3129. }
  3130. auto const& expandedConfigurePreset = configurePresetPair->second.Expanded;
  3131. if (!expandedConfigurePreset) {
  3132. cmSystemTools::Error(cmStrCat("Could not evaluate configure preset \"",
  3133. expandedPreset->ConfigurePreset,
  3134. "\": Invalid macro expansion"));
  3135. return 1;
  3136. }
  3137. if (!expandedConfigurePreset->BinaryDir.empty()) {
  3138. dir = expandedConfigurePreset->BinaryDir;
  3139. }
  3140. this->UnprocessedPresetEnvironment = expandedPreset->Environment;
  3141. this->ProcessPresetEnvironment();
  3142. if ((jobs == cmake::DEFAULT_BUILD_PARALLEL_LEVEL ||
  3143. jobs == cmake::NO_BUILD_PARALLEL_LEVEL) &&
  3144. expandedPreset->Jobs) {
  3145. jobs = *expandedPreset->Jobs;
  3146. }
  3147. if (targets.empty()) {
  3148. targets.insert(targets.begin(), expandedPreset->Targets.begin(),
  3149. expandedPreset->Targets.end());
  3150. }
  3151. if (config.empty()) {
  3152. config = expandedPreset->Configuration;
  3153. }
  3154. if (!buildOptions.Clean && expandedPreset->CleanFirst) {
  3155. buildOptions.Clean = *expandedPreset->CleanFirst;
  3156. }
  3157. if (buildOptions.ResolveMode == PackageResolveMode::Default &&
  3158. expandedPreset->ResolvePackageReferences) {
  3159. buildOptions.ResolveMode = *expandedPreset->ResolvePackageReferences;
  3160. }
  3161. if (!verbose && expandedPreset->Verbose) {
  3162. verbose = *expandedPreset->Verbose;
  3163. }
  3164. if (nativeOptions.empty()) {
  3165. nativeOptions.insert(nativeOptions.begin(),
  3166. expandedPreset->NativeToolOptions.begin(),
  3167. expandedPreset->NativeToolOptions.end());
  3168. }
  3169. }
  3170. #endif
  3171. if (!cmSystemTools::FileIsDirectory(dir)) {
  3172. std::cerr << "Error: " << dir << " is not a directory\n";
  3173. return 1;
  3174. }
  3175. std::string cachePath = FindCacheFile(dir);
  3176. if (!this->LoadCache(cachePath)) {
  3177. std::cerr << "Error: could not load cache\n";
  3178. return 1;
  3179. }
  3180. cmValue cachedGenerator = this->State->GetCacheEntryValue("CMAKE_GENERATOR");
  3181. if (!cachedGenerator) {
  3182. std::cerr << "Error: could not find CMAKE_GENERATOR in Cache\n";
  3183. return 1;
  3184. }
  3185. auto gen = this->CreateGlobalGenerator(*cachedGenerator);
  3186. if (!gen) {
  3187. std::cerr << "Error: could not create CMAKE_GENERATOR \""
  3188. << *cachedGenerator << "\"\n";
  3189. return 1;
  3190. }
  3191. this->SetGlobalGenerator(std::move(gen));
  3192. cmValue cachedGeneratorInstance =
  3193. this->State->GetCacheEntryValue("CMAKE_GENERATOR_INSTANCE");
  3194. if (cachedGeneratorInstance) {
  3195. cmMakefile mf(this->GetGlobalGenerator(), this->GetCurrentSnapshot());
  3196. if (!this->GlobalGenerator->SetGeneratorInstance(*cachedGeneratorInstance,
  3197. &mf)) {
  3198. return 1;
  3199. }
  3200. }
  3201. cmValue cachedGeneratorPlatform =
  3202. this->State->GetCacheEntryValue("CMAKE_GENERATOR_PLATFORM");
  3203. if (cachedGeneratorPlatform) {
  3204. cmMakefile mf(this->GetGlobalGenerator(), this->GetCurrentSnapshot());
  3205. if (!this->GlobalGenerator->SetGeneratorPlatform(*cachedGeneratorPlatform,
  3206. &mf)) {
  3207. return 1;
  3208. }
  3209. }
  3210. cmValue cachedGeneratorToolset =
  3211. this->State->GetCacheEntryValue("CMAKE_GENERATOR_TOOLSET");
  3212. if (cachedGeneratorToolset) {
  3213. cmMakefile mf(this->GetGlobalGenerator(), this->GetCurrentSnapshot());
  3214. if (!this->GlobalGenerator->SetGeneratorToolset(*cachedGeneratorToolset,
  3215. true, &mf)) {
  3216. return 1;
  3217. }
  3218. }
  3219. std::string output;
  3220. std::string projName;
  3221. cmValue cachedProjectName =
  3222. this->State->GetCacheEntryValue("CMAKE_PROJECT_NAME");
  3223. if (!cachedProjectName) {
  3224. std::cerr << "Error: could not find CMAKE_PROJECT_NAME in Cache\n";
  3225. return 1;
  3226. }
  3227. projName = *cachedProjectName;
  3228. if (cmIsOn(this->State->GetCacheEntryValue("CMAKE_VERBOSE_MAKEFILE"))) {
  3229. verbose = true;
  3230. }
  3231. #ifdef CMAKE_HAVE_VS_GENERATORS
  3232. // For VS generators, explicitly check if regeneration is necessary before
  3233. // actually starting the build. If not done separately from the build
  3234. // itself, there is the risk of building an out-of-date solution file due
  3235. // to limitations of the underlying build system.
  3236. std::string const stampList = cachePath + "/" + "CMakeFiles/" +
  3237. cmGlobalVisualStudio9Generator::GetGenerateStampList();
  3238. // Note that the stampList file only exists for VS generators.
  3239. if (cmSystemTools::FileExists(stampList)) {
  3240. // Check if running for Visual Studio 9 - we need to explicitly run
  3241. // the glob verification script before starting the build
  3242. this->AddScriptingCommands();
  3243. if (this->GlobalGenerator->MatchesGeneratorName("Visual Studio 9 2008")) {
  3244. std::string const globVerifyScript =
  3245. cachePath + "/" + "CMakeFiles/" + "VerifyGlobs.cmake";
  3246. if (cmSystemTools::FileExists(globVerifyScript)) {
  3247. std::vector<std::string> args;
  3248. this->ReadListFile(args, globVerifyScript);
  3249. }
  3250. }
  3251. if (!cmakeCheckStampList(stampList)) {
  3252. // Correctly initialize the home (=source) and home output (=binary)
  3253. // directories, which is required for running the generation step.
  3254. std::string homeOrig = this->GetHomeDirectory();
  3255. std::string homeOutputOrig = this->GetHomeOutputDirectory();
  3256. this->SetDirectoriesFromFile(cachePath);
  3257. this->AddProjectCommands();
  3258. int ret = this->Configure();
  3259. if (ret) {
  3260. cmSystemTools::Message("CMake Configure step failed. "
  3261. "Build files cannot be regenerated correctly.");
  3262. return ret;
  3263. }
  3264. ret = this->Generate();
  3265. if (ret) {
  3266. cmSystemTools::Message("CMake Generate step failed. "
  3267. "Build files cannot be regenerated correctly.");
  3268. return ret;
  3269. }
  3270. std::string message = cmStrCat("Build files have been written to: ",
  3271. this->GetHomeOutputDirectory());
  3272. this->UpdateProgress(message, -1);
  3273. // Restore the previously set directories to their original value.
  3274. this->SetHomeDirectory(homeOrig);
  3275. this->SetHomeOutputDirectory(homeOutputOrig);
  3276. }
  3277. }
  3278. #endif
  3279. if (!this->GlobalGenerator->ReadCacheEntriesForBuild(*this->State)) {
  3280. return 1;
  3281. }
  3282. this->GlobalGenerator->PrintBuildCommandAdvice(std::cerr, jobs);
  3283. return this->GlobalGenerator->Build(
  3284. jobs, "", dir, projName, targets, output, "", config, buildOptions,
  3285. verbose, cmDuration::zero(), cmSystemTools::OUTPUT_PASSTHROUGH,
  3286. nativeOptions);
  3287. }
  3288. bool cmake::Open(const std::string& dir, bool dryRun)
  3289. {
  3290. this->SetHomeDirectory("");
  3291. this->SetHomeOutputDirectory("");
  3292. if (!cmSystemTools::FileIsDirectory(dir)) {
  3293. std::cerr << "Error: " << dir << " is not a directory\n";
  3294. return false;
  3295. }
  3296. std::string cachePath = FindCacheFile(dir);
  3297. if (!this->LoadCache(cachePath)) {
  3298. std::cerr << "Error: could not load cache\n";
  3299. return false;
  3300. }
  3301. cmValue genName = this->State->GetCacheEntryValue("CMAKE_GENERATOR");
  3302. if (!genName) {
  3303. std::cerr << "Error: could not find CMAKE_GENERATOR in Cache\n";
  3304. return false;
  3305. }
  3306. cmValue extraGenName =
  3307. this->State->GetInitializedCacheValue("CMAKE_EXTRA_GENERATOR");
  3308. std::string fullName =
  3309. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  3310. *genName, extraGenName ? *extraGenName : "");
  3311. std::unique_ptr<cmGlobalGenerator> gen =
  3312. this->CreateGlobalGenerator(fullName);
  3313. if (!gen) {
  3314. std::cerr << "Error: could not create CMAKE_GENERATOR \"" << fullName
  3315. << "\"\n";
  3316. return false;
  3317. }
  3318. cmValue cachedProjectName =
  3319. this->State->GetCacheEntryValue("CMAKE_PROJECT_NAME");
  3320. if (!cachedProjectName) {
  3321. std::cerr << "Error: could not find CMAKE_PROJECT_NAME in Cache\n";
  3322. return false;
  3323. }
  3324. return gen->Open(dir, *cachedProjectName, dryRun);
  3325. }
  3326. #if !defined(CMAKE_BOOTSTRAP)
  3327. template <typename T>
  3328. const T* cmake::FindPresetForWorkflow(
  3329. cm::static_string_view type,
  3330. const std::map<std::string, cmCMakePresetsGraph::PresetPair<T>>& presets,
  3331. const cmCMakePresetsGraph::WorkflowPreset::WorkflowStep& step)
  3332. {
  3333. auto it = presets.find(step.PresetName);
  3334. if (it == presets.end()) {
  3335. cmSystemTools::Error(cmStrCat("No such ", type, " preset in ",
  3336. this->GetHomeDirectory(), ": \"",
  3337. step.PresetName, '"'));
  3338. return nullptr;
  3339. }
  3340. if (it->second.Unexpanded.Hidden) {
  3341. cmSystemTools::Error(cmStrCat("Cannot use hidden ", type, " preset in ",
  3342. this->GetHomeDirectory(), ": \"",
  3343. step.PresetName, '"'));
  3344. return nullptr;
  3345. }
  3346. if (!it->second.Expanded) {
  3347. cmSystemTools::Error(cmStrCat("Could not evaluate ", type, " preset \"",
  3348. step.PresetName,
  3349. "\": Invalid macro expansion"));
  3350. return nullptr;
  3351. }
  3352. if (!it->second.Expanded->ConditionResult) {
  3353. cmSystemTools::Error(cmStrCat("Cannot use disabled ", type, " preset in ",
  3354. this->GetHomeDirectory(), ": \"",
  3355. step.PresetName, '"'));
  3356. return nullptr;
  3357. }
  3358. return &*it->second.Expanded;
  3359. }
  3360. std::function<int()> cmake::BuildWorkflowStep(
  3361. const std::vector<std::string>& args)
  3362. {
  3363. cmUVProcessChainBuilder builder;
  3364. builder
  3365. .AddCommand(args)
  3366. # ifdef _WIN32
  3367. .SetExternalStream(cmUVProcessChainBuilder::Stream_OUTPUT, _fileno(stdout))
  3368. .SetExternalStream(cmUVProcessChainBuilder::Stream_ERROR, _fileno(stderr));
  3369. # else
  3370. .SetExternalStream(cmUVProcessChainBuilder::Stream_OUTPUT, STDOUT_FILENO)
  3371. .SetExternalStream(cmUVProcessChainBuilder::Stream_ERROR, STDERR_FILENO);
  3372. # endif
  3373. return [builder]() -> int {
  3374. auto chain = builder.Start();
  3375. chain.Wait();
  3376. return static_cast<int>(chain.GetStatus().front()->ExitStatus);
  3377. };
  3378. }
  3379. #endif
  3380. int cmake::Workflow(const std::string& presetName,
  3381. WorkflowListPresets listPresets, WorkflowFresh fresh)
  3382. {
  3383. #ifndef CMAKE_BOOTSTRAP
  3384. this->SetHomeDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  3385. this->SetHomeOutputDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  3386. cmCMakePresetsGraph settingsFile;
  3387. auto result = settingsFile.ReadProjectPresets(this->GetHomeDirectory());
  3388. if (result != cmCMakePresetsGraph::ReadFileResult::READ_OK) {
  3389. cmSystemTools::Error(
  3390. cmStrCat("Could not read presets from ", this->GetHomeDirectory(), ": ",
  3391. cmCMakePresetsGraph::ResultToString(result)));
  3392. return 1;
  3393. }
  3394. if (listPresets == WorkflowListPresets::Yes) {
  3395. settingsFile.PrintWorkflowPresetList();
  3396. return 0;
  3397. }
  3398. auto presetPair = settingsFile.WorkflowPresets.find(presetName);
  3399. if (presetPair == settingsFile.WorkflowPresets.end()) {
  3400. cmSystemTools::Error(cmStrCat("No such workflow preset in ",
  3401. this->GetHomeDirectory(), ": \"", presetName,
  3402. '"'));
  3403. settingsFile.PrintWorkflowPresetList();
  3404. return 1;
  3405. }
  3406. if (presetPair->second.Unexpanded.Hidden) {
  3407. cmSystemTools::Error(cmStrCat("Cannot use hidden workflow preset in ",
  3408. this->GetHomeDirectory(), ": \"", presetName,
  3409. '"'));
  3410. settingsFile.PrintWorkflowPresetList();
  3411. return 1;
  3412. }
  3413. auto const& expandedPreset = presetPair->second.Expanded;
  3414. if (!expandedPreset) {
  3415. cmSystemTools::Error(cmStrCat("Could not evaluate workflow preset \"",
  3416. presetName, "\": Invalid macro expansion"));
  3417. settingsFile.PrintWorkflowPresetList();
  3418. return 1;
  3419. }
  3420. if (!expandedPreset->ConditionResult) {
  3421. cmSystemTools::Error(cmStrCat("Cannot use disabled workflow preset in ",
  3422. this->GetHomeDirectory(), ": \"", presetName,
  3423. '"'));
  3424. settingsFile.PrintWorkflowPresetList();
  3425. return 1;
  3426. }
  3427. struct CalculatedStep
  3428. {
  3429. int StepNumber;
  3430. cm::static_string_view Type;
  3431. std::string Name;
  3432. std::function<int()> Action;
  3433. CalculatedStep(int stepNumber, cm::static_string_view type,
  3434. std::string name, std::function<int()> action)
  3435. : StepNumber(stepNumber)
  3436. , Type(type)
  3437. , Name(std::move(name))
  3438. , Action(std::move(action))
  3439. {
  3440. }
  3441. };
  3442. std::vector<CalculatedStep> steps;
  3443. steps.reserve(expandedPreset->Steps.size());
  3444. int stepNumber = 1;
  3445. for (auto const& step : expandedPreset->Steps) {
  3446. switch (step.PresetType) {
  3447. case cmCMakePresetsGraph::WorkflowPreset::WorkflowStep::Type::
  3448. Configure: {
  3449. auto const* configurePreset = this->FindPresetForWorkflow(
  3450. "configure"_s, settingsFile.ConfigurePresets, step);
  3451. if (!configurePreset) {
  3452. return 1;
  3453. }
  3454. std::vector<std::string> args{ cmSystemTools::GetCMakeCommand(),
  3455. "--preset", step.PresetName };
  3456. if (fresh == WorkflowFresh::Yes) {
  3457. args.emplace_back("--fresh");
  3458. }
  3459. steps.emplace_back(stepNumber, "configure"_s, step.PresetName,
  3460. this->BuildWorkflowStep(args));
  3461. } break;
  3462. case cmCMakePresetsGraph::WorkflowPreset::WorkflowStep::Type::Build: {
  3463. auto const* buildPreset = this->FindPresetForWorkflow(
  3464. "build"_s, settingsFile.BuildPresets, step);
  3465. if (!buildPreset) {
  3466. return 1;
  3467. }
  3468. steps.emplace_back(
  3469. stepNumber, "build"_s, step.PresetName,
  3470. this->BuildWorkflowStep({ cmSystemTools::GetCMakeCommand(),
  3471. "--build", "--preset", step.PresetName }));
  3472. } break;
  3473. case cmCMakePresetsGraph::WorkflowPreset::WorkflowStep::Type::Test: {
  3474. auto const* testPreset = this->FindPresetForWorkflow(
  3475. "test"_s, settingsFile.TestPresets, step);
  3476. if (!testPreset) {
  3477. return 1;
  3478. }
  3479. steps.emplace_back(
  3480. stepNumber, "test"_s, step.PresetName,
  3481. this->BuildWorkflowStep({ cmSystemTools::GetCTestCommand(),
  3482. "--preset", step.PresetName }));
  3483. } break;
  3484. case cmCMakePresetsGraph::WorkflowPreset::WorkflowStep::Type::Package: {
  3485. auto const* packagePreset = this->FindPresetForWorkflow(
  3486. "package"_s, settingsFile.PackagePresets, step);
  3487. if (!packagePreset) {
  3488. return 1;
  3489. }
  3490. steps.emplace_back(
  3491. stepNumber, "package"_s, step.PresetName,
  3492. this->BuildWorkflowStep({ cmSystemTools::GetCPackCommand(),
  3493. "--preset", step.PresetName }));
  3494. } break;
  3495. }
  3496. stepNumber++;
  3497. }
  3498. int stepResult;
  3499. bool first = true;
  3500. for (auto const& step : steps) {
  3501. if (!first) {
  3502. std::cout << "\n";
  3503. }
  3504. std::cout << "Executing workflow step " << step.StepNumber << " of "
  3505. << steps.size() << ": " << step.Type << " preset \"" << step.Name
  3506. << "\"\n\n"
  3507. << std::flush;
  3508. if ((stepResult = step.Action()) != 0) {
  3509. return stepResult;
  3510. }
  3511. first = false;
  3512. }
  3513. #endif
  3514. return 0;
  3515. }
  3516. void cmake::WatchUnusedCli(const std::string& var)
  3517. {
  3518. #ifndef CMAKE_BOOTSTRAP
  3519. this->VariableWatch->AddWatch(var, cmWarnUnusedCliWarning, this);
  3520. if (!cm::contains(this->UsedCliVariables, var)) {
  3521. this->UsedCliVariables[var] = false;
  3522. }
  3523. #endif
  3524. }
  3525. void cmake::UnwatchUnusedCli(const std::string& var)
  3526. {
  3527. #ifndef CMAKE_BOOTSTRAP
  3528. this->VariableWatch->RemoveWatch(var, cmWarnUnusedCliWarning);
  3529. this->UsedCliVariables.erase(var);
  3530. #endif
  3531. }
  3532. void cmake::RunCheckForUnusedVariables()
  3533. {
  3534. #ifndef CMAKE_BOOTSTRAP
  3535. bool haveUnused = false;
  3536. std::ostringstream msg;
  3537. msg << "Manually-specified variables were not used by the project:";
  3538. for (auto const& it : this->UsedCliVariables) {
  3539. if (!it.second) {
  3540. haveUnused = true;
  3541. msg << "\n " << it.first;
  3542. }
  3543. }
  3544. if (haveUnused) {
  3545. this->IssueMessage(MessageType::WARNING, msg.str());
  3546. }
  3547. #endif
  3548. }
  3549. bool cmake::GetSuppressDevWarnings() const
  3550. {
  3551. return this->Messenger->GetSuppressDevWarnings();
  3552. }
  3553. void cmake::SetSuppressDevWarnings(bool b)
  3554. {
  3555. std::string value;
  3556. // equivalent to -Wno-dev
  3557. if (b) {
  3558. value = "TRUE";
  3559. }
  3560. // equivalent to -Wdev
  3561. else {
  3562. value = "FALSE";
  3563. }
  3564. this->AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", value,
  3565. "Suppress Warnings that are meant for"
  3566. " the author of the CMakeLists.txt files.",
  3567. cmStateEnums::INTERNAL);
  3568. }
  3569. bool cmake::GetSuppressDeprecatedWarnings() const
  3570. {
  3571. return this->Messenger->GetSuppressDeprecatedWarnings();
  3572. }
  3573. void cmake::SetSuppressDeprecatedWarnings(bool b)
  3574. {
  3575. std::string value;
  3576. // equivalent to -Wno-deprecated
  3577. if (b) {
  3578. value = "FALSE";
  3579. }
  3580. // equivalent to -Wdeprecated
  3581. else {
  3582. value = "TRUE";
  3583. }
  3584. this->AddCacheEntry("CMAKE_WARN_DEPRECATED", value,
  3585. "Whether to issue warnings for deprecated "
  3586. "functionality.",
  3587. cmStateEnums::INTERNAL);
  3588. }
  3589. bool cmake::GetDevWarningsAsErrors() const
  3590. {
  3591. return this->Messenger->GetDevWarningsAsErrors();
  3592. }
  3593. void cmake::SetDevWarningsAsErrors(bool b)
  3594. {
  3595. std::string value;
  3596. // equivalent to -Werror=dev
  3597. if (b) {
  3598. value = "FALSE";
  3599. }
  3600. // equivalent to -Wno-error=dev
  3601. else {
  3602. value = "TRUE";
  3603. }
  3604. this->AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_ERRORS", value,
  3605. "Suppress errors that are meant for"
  3606. " the author of the CMakeLists.txt files.",
  3607. cmStateEnums::INTERNAL);
  3608. }
  3609. bool cmake::GetDeprecatedWarningsAsErrors() const
  3610. {
  3611. return this->Messenger->GetDeprecatedWarningsAsErrors();
  3612. }
  3613. void cmake::SetDeprecatedWarningsAsErrors(bool b)
  3614. {
  3615. std::string value;
  3616. // equivalent to -Werror=deprecated
  3617. if (b) {
  3618. value = "TRUE";
  3619. }
  3620. // equivalent to -Wno-error=deprecated
  3621. else {
  3622. value = "FALSE";
  3623. }
  3624. this->AddCacheEntry("CMAKE_ERROR_DEPRECATED", value,
  3625. "Whether to issue deprecation errors for macros"
  3626. " and functions.",
  3627. cmStateEnums::INTERNAL);
  3628. }
  3629. void cmake::SetDebugFindOutputPkgs(std::string const& args)
  3630. {
  3631. this->DebugFindPkgs.emplace(args);
  3632. }
  3633. void cmake::SetDebugFindOutputVars(std::string const& args)
  3634. {
  3635. this->DebugFindVars.emplace(args);
  3636. }
  3637. bool cmake::GetDebugFindOutput(std::string const& var) const
  3638. {
  3639. return this->DebugFindVars.count(var);
  3640. }
  3641. bool cmake::GetDebugFindPkgOutput(std::string const& pkg) const
  3642. {
  3643. return this->DebugFindPkgs.count(pkg);
  3644. }
  3645. #if !defined(CMAKE_BOOTSTRAP)
  3646. cmMakefileProfilingData& cmake::GetProfilingOutput()
  3647. {
  3648. return *(this->ProfilingOutput);
  3649. }
  3650. bool cmake::IsProfilingEnabled() const
  3651. {
  3652. return static_cast<bool>(this->ProfilingOutput);
  3653. }
  3654. #endif