1
0

cmake.cxx 136 KB

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