cmake.cxx 141 KB

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