cmake.cxx 142 KB

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