cmake.cxx 152 KB

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