cmake.cxx 105 KB

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