cmake.cxx 151 KB

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