cmake.cxx 152 KB

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