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