cmake.cxx 140 KB

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