cmake.cxx 142 KB

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