cmake.cxx 115 KB

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