cmake.cxx 141 KB

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