cmake.cxx 118 KB

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