cmake.cxx 120 KB

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