cmake.cxx 97 KB

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