cmake.cxx 127 KB

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