cmake.cxx 151 KB

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