cmake.cxx 137 KB

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