cmake.cxx 141 KB

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