cmake.cxx 145 KB

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