cmake.cxx 141 KB

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