cmake.cxx 96 KB

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