cmake.cxx 141 KB

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