cmake.cxx 118 KB

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