cmake.cxx 142 KB

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