cmake.cxx 117 KB

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