1
0

cmake.cxx 149 KB

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