cmake.cxx 145 KB

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