cmake.cxx 117 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568
  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. this->SetHomeOutputDirectory(expandedPreset->BinaryDir);
  1119. }
  1120. if (!this->GlobalGenerator) {
  1121. if (!this->CreateAndSetGlobalGenerator(expandedPreset->Generator,
  1122. false)) {
  1123. return;
  1124. }
  1125. }
  1126. this->UnprocessedPresetVariables = expandedPreset->CacheVariables;
  1127. this->UnprocessedPresetEnvironment = expandedPreset->Environment;
  1128. if (!expandedPreset->InstallDir.empty() &&
  1129. this->State->GetInitializedCacheValue("CMAKE_INSTALL_PREFIX") ==
  1130. nullptr) {
  1131. this->UnprocessedPresetVariables["CMAKE_INSTALL_PREFIX"] = {
  1132. "PATH", expandedPreset->InstallDir
  1133. };
  1134. }
  1135. if (!expandedPreset->ArchitectureStrategy ||
  1136. expandedPreset->ArchitectureStrategy ==
  1137. cmCMakePresetsFile::ArchToolsetStrategy::Set) {
  1138. if (!this->GeneratorPlatformSet) {
  1139. this->SetGeneratorPlatform(expandedPreset->Architecture);
  1140. }
  1141. }
  1142. if (!expandedPreset->ToolsetStrategy ||
  1143. expandedPreset->ToolsetStrategy ==
  1144. cmCMakePresetsFile::ArchToolsetStrategy::Set) {
  1145. if (!this->GeneratorToolsetSet) {
  1146. this->SetGeneratorToolset(expandedPreset->Toolset);
  1147. }
  1148. }
  1149. this->SetWarningFromPreset("dev", expandedPreset->WarnDev,
  1150. expandedPreset->ErrorDev);
  1151. this->SetWarningFromPreset("deprecated", expandedPreset->WarnDeprecated,
  1152. expandedPreset->ErrorDeprecated);
  1153. if (expandedPreset->WarnUninitialized == true) {
  1154. this->SetWarnUninitialized(true);
  1155. }
  1156. if (expandedPreset->WarnUnusedCli == false) {
  1157. this->SetWarnUnusedCli(false);
  1158. }
  1159. if (expandedPreset->WarnSystemVars == true) {
  1160. this->SetCheckSystemVars(true);
  1161. }
  1162. if (expandedPreset->DebugOutput == true) {
  1163. this->SetDebugOutputOn(true);
  1164. }
  1165. if (expandedPreset->DebugTryCompile == true) {
  1166. this->DebugTryCompileOn();
  1167. }
  1168. if (expandedPreset->DebugFind == true) {
  1169. this->SetDebugFindOutputOn(true);
  1170. }
  1171. }
  1172. #endif
  1173. }
  1174. cmake::LogLevel cmake::StringToLogLevel(const std::string& levelStr)
  1175. {
  1176. using LevelsPair = std::pair<std::string, LogLevel>;
  1177. static const std::vector<LevelsPair> levels = {
  1178. { "error", LogLevel::LOG_ERROR }, { "warning", LogLevel::LOG_WARNING },
  1179. { "notice", LogLevel::LOG_NOTICE }, { "status", LogLevel::LOG_STATUS },
  1180. { "verbose", LogLevel::LOG_VERBOSE }, { "debug", LogLevel::LOG_DEBUG },
  1181. { "trace", LogLevel::LOG_TRACE }
  1182. };
  1183. const auto levelStrLowCase = cmSystemTools::LowerCase(levelStr);
  1184. const auto it = std::find_if(levels.cbegin(), levels.cend(),
  1185. [&levelStrLowCase](const LevelsPair& p) {
  1186. return p.first == levelStrLowCase;
  1187. });
  1188. return (it != levels.cend()) ? it->second : LogLevel::LOG_UNDEFINED;
  1189. }
  1190. cmake::TraceFormat cmake::StringToTraceFormat(const std::string& traceStr)
  1191. {
  1192. using TracePair = std::pair<std::string, TraceFormat>;
  1193. static const std::vector<TracePair> levels = {
  1194. { "human", TraceFormat::TRACE_HUMAN },
  1195. { "json-v1", TraceFormat::TRACE_JSON_V1 },
  1196. };
  1197. const auto traceStrLowCase = cmSystemTools::LowerCase(traceStr);
  1198. const auto it = std::find_if(levels.cbegin(), levels.cend(),
  1199. [&traceStrLowCase](const TracePair& p) {
  1200. return p.first == traceStrLowCase;
  1201. });
  1202. return (it != levels.cend()) ? it->second : TraceFormat::TRACE_UNDEFINED;
  1203. }
  1204. void cmake::SetTraceFile(const std::string& file)
  1205. {
  1206. this->TraceFile.close();
  1207. this->TraceFile.open(file.c_str());
  1208. if (!this->TraceFile) {
  1209. std::stringstream ss;
  1210. ss << "Error opening trace file " << file << ": "
  1211. << cmSystemTools::GetLastSystemError();
  1212. cmSystemTools::Error(ss.str());
  1213. return;
  1214. }
  1215. std::cout << "Trace will be written to " << file << "\n";
  1216. }
  1217. void cmake::PrintTraceFormatVersion()
  1218. {
  1219. if (!this->GetTrace()) {
  1220. return;
  1221. }
  1222. std::string msg;
  1223. switch (this->GetTraceFormat()) {
  1224. case TraceFormat::TRACE_JSON_V1: {
  1225. #ifndef CMAKE_BOOTSTRAP
  1226. Json::Value val;
  1227. Json::Value version;
  1228. Json::StreamWriterBuilder builder;
  1229. builder["indentation"] = "";
  1230. version["major"] = 1;
  1231. version["minor"] = 1;
  1232. val["version"] = version;
  1233. msg = Json::writeString(builder, val);
  1234. #endif
  1235. break;
  1236. }
  1237. case TraceFormat::TRACE_HUMAN:
  1238. msg = "";
  1239. break;
  1240. case TraceFormat::TRACE_UNDEFINED:
  1241. msg = "INTERNAL ERROR: Trace format is TRACE_UNDEFINED";
  1242. break;
  1243. }
  1244. if (msg.empty()) {
  1245. return;
  1246. }
  1247. auto& f = this->GetTraceFile();
  1248. if (f) {
  1249. f << msg << '\n';
  1250. } else {
  1251. cmSystemTools::Message(msg);
  1252. }
  1253. }
  1254. void cmake::SetDirectoriesFromFile(const std::string& arg)
  1255. {
  1256. // Check if the argument refers to a CMakeCache.txt or
  1257. // CMakeLists.txt file.
  1258. std::string listPath;
  1259. std::string cachePath;
  1260. bool argIsFile = false;
  1261. if (cmSystemTools::FileIsDirectory(arg)) {
  1262. std::string path = cmSystemTools::CollapseFullPath(arg);
  1263. cmSystemTools::ConvertToUnixSlashes(path);
  1264. std::string cacheFile = cmStrCat(path, "/CMakeCache.txt");
  1265. std::string listFile = cmStrCat(path, "/CMakeLists.txt");
  1266. if (cmSystemTools::FileExists(cacheFile)) {
  1267. cachePath = path;
  1268. }
  1269. if (cmSystemTools::FileExists(listFile)) {
  1270. listPath = path;
  1271. }
  1272. } else if (cmSystemTools::FileExists(arg)) {
  1273. argIsFile = true;
  1274. std::string fullPath = cmSystemTools::CollapseFullPath(arg);
  1275. std::string name = cmSystemTools::GetFilenameName(fullPath);
  1276. name = cmSystemTools::LowerCase(name);
  1277. if (name == "cmakecache.txt"_s) {
  1278. cachePath = cmSystemTools::GetFilenamePath(fullPath);
  1279. } else if (name == "cmakelists.txt"_s) {
  1280. listPath = cmSystemTools::GetFilenamePath(fullPath);
  1281. }
  1282. } else {
  1283. // Specified file or directory does not exist. Try to set things
  1284. // up to produce a meaningful error message.
  1285. std::string fullPath = cmSystemTools::CollapseFullPath(arg);
  1286. std::string name = cmSystemTools::GetFilenameName(fullPath);
  1287. name = cmSystemTools::LowerCase(name);
  1288. if (name == "cmakecache.txt"_s || name == "cmakelists.txt"_s) {
  1289. argIsFile = true;
  1290. listPath = cmSystemTools::GetFilenamePath(fullPath);
  1291. } else {
  1292. listPath = fullPath;
  1293. }
  1294. }
  1295. // If there is a CMakeCache.txt file, use its settings.
  1296. if (!cachePath.empty()) {
  1297. if (this->LoadCache(cachePath)) {
  1298. cmProp existingValue =
  1299. this->State->GetCacheEntryValue("CMAKE_HOME_DIRECTORY");
  1300. if (existingValue) {
  1301. this->SetHomeOutputDirectory(cachePath);
  1302. this->SetHomeDirectory(*existingValue);
  1303. return;
  1304. }
  1305. }
  1306. }
  1307. // If there is a CMakeLists.txt file, use it as the source tree.
  1308. if (!listPath.empty()) {
  1309. this->SetHomeDirectory(listPath);
  1310. if (argIsFile) {
  1311. // Source CMakeLists.txt file given. It was probably dropped
  1312. // onto the executable in a GUI. Default to an in-source build.
  1313. this->SetHomeOutputDirectory(listPath);
  1314. } else {
  1315. // Source directory given on command line. Use current working
  1316. // directory as build tree if -B hasn't been given already
  1317. if (this->GetHomeOutputDirectory().empty()) {
  1318. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1319. this->SetHomeOutputDirectory(cwd);
  1320. }
  1321. }
  1322. return;
  1323. }
  1324. if (this->GetHomeDirectory().empty()) {
  1325. // We didn't find a CMakeLists.txt and it wasn't specified
  1326. // with -S. Assume it is the path to the source tree
  1327. std::string full = cmSystemTools::CollapseFullPath(arg);
  1328. this->SetHomeDirectory(full);
  1329. }
  1330. if (this->GetHomeOutputDirectory().empty()) {
  1331. // We didn't find a CMakeCache.txt and it wasn't specified
  1332. // with -B. Assume the current working directory as the build tree.
  1333. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1334. this->SetHomeOutputDirectory(cwd);
  1335. }
  1336. }
  1337. // at the end of this CMAKE_ROOT and CMAKE_COMMAND should be added to the
  1338. // cache
  1339. int cmake::AddCMakePaths()
  1340. {
  1341. // Save the value in the cache
  1342. this->AddCacheEntry("CMAKE_COMMAND",
  1343. cmSystemTools::GetCMakeCommand().c_str(),
  1344. "Path to CMake executable.", cmStateEnums::INTERNAL);
  1345. #ifndef CMAKE_BOOTSTRAP
  1346. this->AddCacheEntry(
  1347. "CMAKE_CTEST_COMMAND", cmSystemTools::GetCTestCommand().c_str(),
  1348. "Path to ctest program executable.", cmStateEnums::INTERNAL);
  1349. this->AddCacheEntry(
  1350. "CMAKE_CPACK_COMMAND", cmSystemTools::GetCPackCommand().c_str(),
  1351. "Path to cpack program executable.", cmStateEnums::INTERNAL);
  1352. #endif
  1353. if (!cmSystemTools::FileExists(
  1354. (cmSystemTools::GetCMakeRoot() + "/Modules/CMake.cmake"))) {
  1355. // couldn't find modules
  1356. cmSystemTools::Error(
  1357. "Could not find CMAKE_ROOT !!!\n"
  1358. "CMake has most likely not been installed correctly.\n"
  1359. "Modules directory not found in\n" +
  1360. cmSystemTools::GetCMakeRoot());
  1361. return 0;
  1362. }
  1363. this->AddCacheEntry("CMAKE_ROOT", cmSystemTools::GetCMakeRoot().c_str(),
  1364. "Path to CMake installation.", cmStateEnums::INTERNAL);
  1365. return 1;
  1366. }
  1367. void cmake::AddDefaultExtraGenerators()
  1368. {
  1369. #if !defined(CMAKE_BOOTSTRAP)
  1370. this->ExtraGenerators.push_back(cmExtraCodeBlocksGenerator::GetFactory());
  1371. this->ExtraGenerators.push_back(cmExtraCodeLiteGenerator::GetFactory());
  1372. this->ExtraGenerators.push_back(cmExtraEclipseCDT4Generator::GetFactory());
  1373. this->ExtraGenerators.push_back(cmExtraKateGenerator::GetFactory());
  1374. this->ExtraGenerators.push_back(cmExtraSublimeTextGenerator::GetFactory());
  1375. #endif
  1376. }
  1377. void cmake::GetRegisteredGenerators(std::vector<GeneratorInfo>& generators,
  1378. bool includeNamesWithPlatform) const
  1379. {
  1380. for (const auto& gen : this->Generators) {
  1381. std::vector<std::string> names = gen->GetGeneratorNames();
  1382. if (includeNamesWithPlatform) {
  1383. cm::append(names, gen->GetGeneratorNamesWithPlatform());
  1384. }
  1385. for (std::string const& name : names) {
  1386. GeneratorInfo info;
  1387. info.supportsToolset = gen->SupportsToolset();
  1388. info.supportsPlatform = gen->SupportsPlatform();
  1389. info.supportedPlatforms = gen->GetKnownPlatforms();
  1390. info.defaultPlatform = gen->GetDefaultPlatformName();
  1391. info.name = name;
  1392. info.baseName = name;
  1393. info.isAlias = false;
  1394. generators.push_back(std::move(info));
  1395. }
  1396. }
  1397. for (cmExternalMakefileProjectGeneratorFactory* eg : this->ExtraGenerators) {
  1398. const std::vector<std::string> genList =
  1399. eg->GetSupportedGlobalGenerators();
  1400. for (std::string const& gen : genList) {
  1401. GeneratorInfo info;
  1402. info.name = cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  1403. gen, eg->GetName());
  1404. info.baseName = gen;
  1405. info.extraName = eg->GetName();
  1406. info.supportsPlatform = false;
  1407. info.supportsToolset = false;
  1408. info.isAlias = false;
  1409. generators.push_back(std::move(info));
  1410. }
  1411. for (std::string const& a : eg->Aliases) {
  1412. GeneratorInfo info;
  1413. info.name = a;
  1414. if (!genList.empty()) {
  1415. info.baseName = genList.at(0);
  1416. }
  1417. info.extraName = eg->GetName();
  1418. info.supportsPlatform = false;
  1419. info.supportsToolset = false;
  1420. info.isAlias = true;
  1421. generators.push_back(std::move(info));
  1422. }
  1423. }
  1424. }
  1425. static std::pair<std::unique_ptr<cmExternalMakefileProjectGenerator>,
  1426. std::string>
  1427. createExtraGenerator(
  1428. const std::vector<cmExternalMakefileProjectGeneratorFactory*>& in,
  1429. const std::string& name)
  1430. {
  1431. for (cmExternalMakefileProjectGeneratorFactory* i : in) {
  1432. const std::vector<std::string> generators =
  1433. i->GetSupportedGlobalGenerators();
  1434. if (i->GetName() == name) { // Match aliases
  1435. return { i->CreateExternalMakefileProjectGenerator(), generators.at(0) };
  1436. }
  1437. for (std::string const& g : generators) {
  1438. const std::string fullName =
  1439. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  1440. g, i->GetName());
  1441. if (fullName == name) {
  1442. return { i->CreateExternalMakefileProjectGenerator(), g };
  1443. }
  1444. }
  1445. }
  1446. return { nullptr, name };
  1447. }
  1448. std::unique_ptr<cmGlobalGenerator> cmake::CreateGlobalGenerator(
  1449. const std::string& gname, bool allowArch)
  1450. {
  1451. std::pair<std::unique_ptr<cmExternalMakefileProjectGenerator>, std::string>
  1452. extra = createExtraGenerator(this->ExtraGenerators, gname);
  1453. std::unique_ptr<cmExternalMakefileProjectGenerator>& extraGenerator =
  1454. extra.first;
  1455. const std::string& name = extra.second;
  1456. std::unique_ptr<cmGlobalGenerator> generator;
  1457. for (const auto& g : this->Generators) {
  1458. generator = g->CreateGlobalGenerator(name, allowArch, this);
  1459. if (generator) {
  1460. break;
  1461. }
  1462. }
  1463. if (generator) {
  1464. generator->SetExternalMakefileProjectGenerator(std::move(extraGenerator));
  1465. }
  1466. return generator;
  1467. }
  1468. bool cmake::CreateAndSetGlobalGenerator(const std::string& name,
  1469. bool allowArch)
  1470. {
  1471. auto gen = this->CreateGlobalGenerator(name, allowArch);
  1472. if (!gen) {
  1473. std::string kdevError;
  1474. std::string vsError;
  1475. if (name.find("KDevelop3", 0) != std::string::npos) {
  1476. kdevError = "\nThe KDevelop3 generator is not supported anymore.";
  1477. }
  1478. if (!allowArch && cmHasLiteralPrefix(name, "Visual Studio ") &&
  1479. name.length() >= cmStrLen("Visual Studio xx xxxx ")) {
  1480. vsError = "\nUsing platforms in Visual Studio generator names is not "
  1481. "supported in CMakePresets.json.";
  1482. }
  1483. cmSystemTools::Error(
  1484. cmStrCat("Could not create named generator ", name, kdevError, vsError));
  1485. this->PrintGeneratorList();
  1486. return false;
  1487. }
  1488. this->SetGlobalGenerator(std::move(gen));
  1489. return true;
  1490. }
  1491. #ifndef CMAKE_BOOTSTRAP
  1492. void cmake::PrintPresetList(const cmCMakePresetsFile& file) const
  1493. {
  1494. std::vector<GeneratorInfo> generators;
  1495. this->GetRegisteredGenerators(generators, false);
  1496. auto filter =
  1497. [&generators](const cmCMakePresetsFile::ConfigurePreset& preset) -> bool {
  1498. auto condition = [&preset](const GeneratorInfo& info) -> bool {
  1499. return info.name == preset.Generator;
  1500. };
  1501. auto it = std::find_if(generators.begin(), generators.end(), condition);
  1502. return it != generators.end();
  1503. };
  1504. file.PrintConfigurePresetList(filter);
  1505. }
  1506. #endif
  1507. void cmake::SetHomeDirectory(const std::string& dir)
  1508. {
  1509. this->State->SetSourceDirectory(dir);
  1510. if (this->CurrentSnapshot.IsValid()) {
  1511. this->CurrentSnapshot.SetDefinition("CMAKE_SOURCE_DIR", dir);
  1512. }
  1513. }
  1514. std::string const& cmake::GetHomeDirectory() const
  1515. {
  1516. return this->State->GetSourceDirectory();
  1517. }
  1518. void cmake::SetHomeOutputDirectory(const std::string& dir)
  1519. {
  1520. this->State->SetBinaryDirectory(dir);
  1521. if (this->CurrentSnapshot.IsValid()) {
  1522. this->CurrentSnapshot.SetDefinition("CMAKE_BINARY_DIR", dir);
  1523. }
  1524. }
  1525. std::string const& cmake::GetHomeOutputDirectory() const
  1526. {
  1527. return this->State->GetBinaryDirectory();
  1528. }
  1529. std::string cmake::FindCacheFile(const std::string& binaryDir)
  1530. {
  1531. std::string cachePath = binaryDir;
  1532. cmSystemTools::ConvertToUnixSlashes(cachePath);
  1533. std::string cacheFile = cmStrCat(cachePath, "/CMakeCache.txt");
  1534. if (!cmSystemTools::FileExists(cacheFile)) {
  1535. // search in parent directories for cache
  1536. std::string cmakeFiles = cmStrCat(cachePath, "/CMakeFiles");
  1537. if (cmSystemTools::FileExists(cmakeFiles)) {
  1538. std::string cachePathFound =
  1539. cmSystemTools::FileExistsInParentDirectories("CMakeCache.txt",
  1540. cachePath, "/");
  1541. if (!cachePathFound.empty()) {
  1542. cachePath = cmSystemTools::GetFilenamePath(cachePathFound);
  1543. }
  1544. }
  1545. }
  1546. return cachePath;
  1547. }
  1548. void cmake::SetGlobalGenerator(std::unique_ptr<cmGlobalGenerator> gg)
  1549. {
  1550. if (!gg) {
  1551. cmSystemTools::Error("Error SetGlobalGenerator called with null");
  1552. return;
  1553. }
  1554. if (this->GlobalGenerator) {
  1555. // restore the original environment variables CXX and CC
  1556. // Restore CC
  1557. std::string env = "CC=";
  1558. if (!this->CCEnvironment.empty()) {
  1559. env += this->CCEnvironment;
  1560. }
  1561. cmSystemTools::PutEnv(env);
  1562. env = "CXX=";
  1563. if (!this->CXXEnvironment.empty()) {
  1564. env += this->CXXEnvironment;
  1565. }
  1566. cmSystemTools::PutEnv(env);
  1567. }
  1568. // set the new
  1569. this->GlobalGenerator = std::move(gg);
  1570. // set the global flag for unix style paths on cmSystemTools as soon as
  1571. // the generator is set. This allows gmake to be used on windows.
  1572. cmSystemTools::SetForceUnixPaths(this->GlobalGenerator->GetForceUnixPaths());
  1573. // Save the environment variables CXX and CC
  1574. if (!cmSystemTools::GetEnv("CXX", this->CXXEnvironment)) {
  1575. this->CXXEnvironment.clear();
  1576. }
  1577. if (!cmSystemTools::GetEnv("CC", this->CCEnvironment)) {
  1578. this->CCEnvironment.clear();
  1579. }
  1580. }
  1581. int cmake::DoPreConfigureChecks()
  1582. {
  1583. // Make sure the Source directory contains a CMakeLists.txt file.
  1584. std::string srcList = cmStrCat(this->GetHomeDirectory(), "/CMakeLists.txt");
  1585. if (!cmSystemTools::FileExists(srcList)) {
  1586. std::ostringstream err;
  1587. if (cmSystemTools::FileIsDirectory(this->GetHomeDirectory())) {
  1588. err << "The source directory \"" << this->GetHomeDirectory()
  1589. << "\" does not appear to contain CMakeLists.txt.\n";
  1590. } else if (cmSystemTools::FileExists(this->GetHomeDirectory())) {
  1591. err << "The source directory \"" << this->GetHomeDirectory()
  1592. << "\" is a file, not a directory.\n";
  1593. } else {
  1594. err << "The source directory \"" << this->GetHomeDirectory()
  1595. << "\" does not exist.\n";
  1596. }
  1597. err << "Specify --help for usage, or press the help button on the CMake "
  1598. "GUI.";
  1599. cmSystemTools::Error(err.str());
  1600. return -2;
  1601. }
  1602. // do a sanity check on some values
  1603. if (this->State->GetInitializedCacheValue("CMAKE_HOME_DIRECTORY")) {
  1604. std::string cacheStart =
  1605. cmStrCat(*this->State->GetInitializedCacheValue("CMAKE_HOME_DIRECTORY"),
  1606. "/CMakeLists.txt");
  1607. std::string currentStart =
  1608. cmStrCat(this->GetHomeDirectory(), "/CMakeLists.txt");
  1609. if (!cmSystemTools::SameFile(cacheStart, currentStart)) {
  1610. std::string message =
  1611. cmStrCat("The source \"", currentStart,
  1612. "\" does not match the source \"", cacheStart,
  1613. "\" used to generate cache. Re-run cmake with a different "
  1614. "source directory.");
  1615. cmSystemTools::Error(message);
  1616. return -2;
  1617. }
  1618. } else {
  1619. return 0;
  1620. }
  1621. return 1;
  1622. }
  1623. struct SaveCacheEntry
  1624. {
  1625. std::string key;
  1626. std::string value;
  1627. std::string help;
  1628. cmStateEnums::CacheEntryType type;
  1629. };
  1630. int cmake::HandleDeleteCacheVariables(const std::string& var)
  1631. {
  1632. std::vector<std::string> argsSplit = cmExpandedList(var, true);
  1633. // erase the property to avoid infinite recursion
  1634. this->State->SetGlobalProperty("__CMAKE_DELETE_CACHE_CHANGE_VARS_", "");
  1635. if (this->State->GetIsInTryCompile()) {
  1636. return 0;
  1637. }
  1638. std::vector<SaveCacheEntry> saved;
  1639. std::ostringstream warning;
  1640. /* clang-format off */
  1641. warning
  1642. << "You have changed variables that require your cache to be deleted.\n"
  1643. << "Configure will be re-run and you may have to reset some variables.\n"
  1644. << "The following variables have changed:\n";
  1645. /* clang-format on */
  1646. for (auto i = argsSplit.begin(); i != argsSplit.end(); ++i) {
  1647. SaveCacheEntry save;
  1648. save.key = *i;
  1649. warning << *i << "= ";
  1650. i++;
  1651. if (i != argsSplit.end()) {
  1652. save.value = *i;
  1653. warning << *i << "\n";
  1654. } else {
  1655. warning << "\n";
  1656. i -= 1;
  1657. }
  1658. cmProp existingValue = this->State->GetCacheEntryValue(save.key);
  1659. if (existingValue) {
  1660. save.type = this->State->GetCacheEntryType(save.key);
  1661. if (cmProp help =
  1662. this->State->GetCacheEntryProperty(save.key, "HELPSTRING")) {
  1663. save.help = *help;
  1664. }
  1665. } else {
  1666. save.type = cmStateEnums::CacheEntryType::UNINITIALIZED;
  1667. }
  1668. saved.push_back(std::move(save));
  1669. }
  1670. // remove the cache
  1671. this->DeleteCache(this->GetHomeOutputDirectory());
  1672. // load the empty cache
  1673. this->LoadCache();
  1674. // restore the changed compilers
  1675. for (SaveCacheEntry const& i : saved) {
  1676. this->AddCacheEntry(i.key, i.value.c_str(), i.help.c_str(), i.type);
  1677. }
  1678. cmSystemTools::Message(warning.str());
  1679. // avoid reconfigure if there were errors
  1680. if (!cmSystemTools::GetErrorOccuredFlag()) {
  1681. // re-run configure
  1682. return this->Configure();
  1683. }
  1684. return 0;
  1685. }
  1686. int cmake::Configure()
  1687. {
  1688. DiagLevel diagLevel;
  1689. if (this->DiagLevels.count("deprecated") == 1) {
  1690. diagLevel = this->DiagLevels["deprecated"];
  1691. if (diagLevel == DIAG_IGNORE) {
  1692. this->SetSuppressDeprecatedWarnings(true);
  1693. this->SetDeprecatedWarningsAsErrors(false);
  1694. } else if (diagLevel == DIAG_WARN) {
  1695. this->SetSuppressDeprecatedWarnings(false);
  1696. this->SetDeprecatedWarningsAsErrors(false);
  1697. } else if (diagLevel == DIAG_ERROR) {
  1698. this->SetSuppressDeprecatedWarnings(false);
  1699. this->SetDeprecatedWarningsAsErrors(true);
  1700. }
  1701. }
  1702. if (this->DiagLevels.count("dev") == 1) {
  1703. bool setDeprecatedVariables = false;
  1704. cmProp cachedWarnDeprecated =
  1705. this->State->GetCacheEntryValue("CMAKE_WARN_DEPRECATED");
  1706. cmProp cachedErrorDeprecated =
  1707. this->State->GetCacheEntryValue("CMAKE_ERROR_DEPRECATED");
  1708. // don't overwrite deprecated warning setting from a previous invocation
  1709. if (!cachedWarnDeprecated && !cachedErrorDeprecated) {
  1710. setDeprecatedVariables = true;
  1711. }
  1712. diagLevel = this->DiagLevels["dev"];
  1713. if (diagLevel == DIAG_IGNORE) {
  1714. this->SetSuppressDevWarnings(true);
  1715. this->SetDevWarningsAsErrors(false);
  1716. if (setDeprecatedVariables) {
  1717. this->SetSuppressDeprecatedWarnings(true);
  1718. this->SetDeprecatedWarningsAsErrors(false);
  1719. }
  1720. } else if (diagLevel == DIAG_WARN) {
  1721. this->SetSuppressDevWarnings(false);
  1722. this->SetDevWarningsAsErrors(false);
  1723. if (setDeprecatedVariables) {
  1724. this->SetSuppressDeprecatedWarnings(false);
  1725. this->SetDeprecatedWarningsAsErrors(false);
  1726. }
  1727. } else if (diagLevel == DIAG_ERROR) {
  1728. this->SetSuppressDevWarnings(false);
  1729. this->SetDevWarningsAsErrors(true);
  1730. if (setDeprecatedVariables) {
  1731. this->SetSuppressDeprecatedWarnings(false);
  1732. this->SetDeprecatedWarningsAsErrors(true);
  1733. }
  1734. }
  1735. }
  1736. // Cache variables may have already been set by a previous invocation,
  1737. // so we cannot rely on command line options alone. Always ensure our
  1738. // messenger is in sync with the cache.
  1739. cmProp value = this->State->GetCacheEntryValue("CMAKE_WARN_DEPRECATED");
  1740. this->Messenger->SetSuppressDeprecatedWarnings(value && cmIsOff(*value));
  1741. value = this->State->GetCacheEntryValue("CMAKE_ERROR_DEPRECATED");
  1742. this->Messenger->SetDeprecatedWarningsAsErrors(cmIsOn(value));
  1743. value = this->State->GetCacheEntryValue("CMAKE_SUPPRESS_DEVELOPER_WARNINGS");
  1744. this->Messenger->SetSuppressDevWarnings(cmIsOn(value));
  1745. value = this->State->GetCacheEntryValue("CMAKE_SUPPRESS_DEVELOPER_ERRORS");
  1746. this->Messenger->SetDevWarningsAsErrors(value && cmIsOff(*value));
  1747. int ret = this->ActualConfigure();
  1748. cmProp delCacheVars =
  1749. this->State->GetGlobalProperty("__CMAKE_DELETE_CACHE_CHANGE_VARS_");
  1750. if (delCacheVars && !delCacheVars->empty()) {
  1751. return this->HandleDeleteCacheVariables(*delCacheVars);
  1752. }
  1753. return ret;
  1754. }
  1755. int cmake::ActualConfigure()
  1756. {
  1757. // Construct right now our path conversion table before it's too late:
  1758. this->UpdateConversionPathTable();
  1759. this->CleanupCommandsAndMacros();
  1760. int res = this->DoPreConfigureChecks();
  1761. if (res < 0) {
  1762. return -2;
  1763. }
  1764. if (!res) {
  1765. this->AddCacheEntry(
  1766. "CMAKE_HOME_DIRECTORY", this->GetHomeDirectory().c_str(),
  1767. "Source directory with the top level CMakeLists.txt file for this "
  1768. "project",
  1769. cmStateEnums::INTERNAL);
  1770. }
  1771. // no generator specified on the command line
  1772. if (!this->GlobalGenerator) {
  1773. cmProp genName = this->State->GetInitializedCacheValue("CMAKE_GENERATOR");
  1774. cmProp extraGenName =
  1775. this->State->GetInitializedCacheValue("CMAKE_EXTRA_GENERATOR");
  1776. if (genName) {
  1777. std::string fullName =
  1778. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  1779. *genName, extraGenName ? *extraGenName : "");
  1780. this->GlobalGenerator = this->CreateGlobalGenerator(fullName);
  1781. }
  1782. if (this->GlobalGenerator) {
  1783. // set the global flag for unix style paths on cmSystemTools as
  1784. // soon as the generator is set. This allows gmake to be used
  1785. // on windows.
  1786. cmSystemTools::SetForceUnixPaths(
  1787. this->GlobalGenerator->GetForceUnixPaths());
  1788. } else {
  1789. this->CreateDefaultGlobalGenerator();
  1790. }
  1791. if (!this->GlobalGenerator) {
  1792. cmSystemTools::Error("Could not create generator");
  1793. return -1;
  1794. }
  1795. }
  1796. cmProp genName = this->State->GetInitializedCacheValue("CMAKE_GENERATOR");
  1797. if (genName) {
  1798. if (!this->GlobalGenerator->MatchesGeneratorName(*genName)) {
  1799. std::string message =
  1800. cmStrCat("Error: generator : ", this->GlobalGenerator->GetName(),
  1801. "\nDoes not match the generator used previously: ", *genName,
  1802. "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1803. "directory or choose a different binary directory.");
  1804. cmSystemTools::Error(message);
  1805. return -2;
  1806. }
  1807. }
  1808. if (!this->State->GetInitializedCacheValue("CMAKE_GENERATOR")) {
  1809. this->AddCacheEntry("CMAKE_GENERATOR",
  1810. this->GlobalGenerator->GetName().c_str(),
  1811. "Name of generator.", cmStateEnums::INTERNAL);
  1812. this->AddCacheEntry("CMAKE_EXTRA_GENERATOR",
  1813. this->GlobalGenerator->GetExtraGeneratorName().c_str(),
  1814. "Name of external makefile project generator.",
  1815. cmStateEnums::INTERNAL);
  1816. }
  1817. if (cmProp instance =
  1818. this->State->GetInitializedCacheValue("CMAKE_GENERATOR_INSTANCE")) {
  1819. if (this->GeneratorInstanceSet && this->GeneratorInstance != *instance) {
  1820. std::string message =
  1821. cmStrCat("Error: generator instance: ", this->GeneratorInstance,
  1822. "\nDoes not match the instance used previously: ", *instance,
  1823. "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1824. "directory or choose a different binary directory.");
  1825. cmSystemTools::Error(message);
  1826. return -2;
  1827. }
  1828. } else {
  1829. this->AddCacheEntry(
  1830. "CMAKE_GENERATOR_INSTANCE", this->GeneratorInstance.c_str(),
  1831. "Generator instance identifier.", cmStateEnums::INTERNAL);
  1832. }
  1833. if (cmProp platformName =
  1834. this->State->GetInitializedCacheValue("CMAKE_GENERATOR_PLATFORM")) {
  1835. if (this->GeneratorPlatformSet &&
  1836. this->GeneratorPlatform != *platformName) {
  1837. std::string message = cmStrCat(
  1838. "Error: generator platform: ", this->GeneratorPlatform,
  1839. "\nDoes not match the platform used previously: ", *platformName,
  1840. "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1841. "directory or choose a different binary directory.");
  1842. cmSystemTools::Error(message);
  1843. return -2;
  1844. }
  1845. } else {
  1846. this->AddCacheEntry("CMAKE_GENERATOR_PLATFORM",
  1847. this->GeneratorPlatform.c_str(),
  1848. "Name of generator platform.", cmStateEnums::INTERNAL);
  1849. }
  1850. if (cmProp tsName =
  1851. this->State->GetInitializedCacheValue("CMAKE_GENERATOR_TOOLSET")) {
  1852. if (this->GeneratorToolsetSet && this->GeneratorToolset != *tsName) {
  1853. std::string message =
  1854. cmStrCat("Error: generator toolset: ", this->GeneratorToolset,
  1855. "\nDoes not match the toolset used previously: ", *tsName,
  1856. "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1857. "directory or choose a different binary directory.");
  1858. cmSystemTools::Error(message);
  1859. return -2;
  1860. }
  1861. } else {
  1862. this->AddCacheEntry("CMAKE_GENERATOR_TOOLSET",
  1863. this->GeneratorToolset.c_str(),
  1864. "Name of generator toolset.", cmStateEnums::INTERNAL);
  1865. }
  1866. // reset any system configuration information, except for when we are
  1867. // InTryCompile. With TryCompile the system info is taken from the parent's
  1868. // info to save time
  1869. if (!this->State->GetIsInTryCompile()) {
  1870. this->GlobalGenerator->ClearEnabledLanguages();
  1871. this->TruncateOutputLog("CMakeOutput.log");
  1872. this->TruncateOutputLog("CMakeError.log");
  1873. }
  1874. #if !defined(CMAKE_BOOTSTRAP)
  1875. this->FileAPI = cm::make_unique<cmFileAPI>(this);
  1876. this->FileAPI->ReadQueries();
  1877. #endif
  1878. // actually do the configure
  1879. this->GlobalGenerator->Configure();
  1880. // Before saving the cache
  1881. // if the project did not define one of the entries below, add them now
  1882. // so users can edit the values in the cache:
  1883. // We used to always present LIBRARY_OUTPUT_PATH and
  1884. // EXECUTABLE_OUTPUT_PATH. They are now documented as old-style and
  1885. // should no longer be used. Therefore we present them only if the
  1886. // project requires compatibility with CMake 2.4. We detect this
  1887. // here by looking for the old CMAKE_BACKWARDS_COMPATIBILITY
  1888. // variable created when CMP0001 is not set to NEW.
  1889. if (this->State->GetInitializedCacheValue("CMAKE_BACKWARDS_COMPATIBILITY")) {
  1890. if (!this->State->GetInitializedCacheValue("LIBRARY_OUTPUT_PATH")) {
  1891. this->AddCacheEntry(
  1892. "LIBRARY_OUTPUT_PATH", "",
  1893. "Single output directory for building all libraries.",
  1894. cmStateEnums::PATH);
  1895. }
  1896. if (!this->State->GetInitializedCacheValue("EXECUTABLE_OUTPUT_PATH")) {
  1897. this->AddCacheEntry(
  1898. "EXECUTABLE_OUTPUT_PATH", "",
  1899. "Single output directory for building all executables.",
  1900. cmStateEnums::PATH);
  1901. }
  1902. }
  1903. const auto& mf = this->GlobalGenerator->GetMakefiles()[0];
  1904. if (mf->IsOn("CTEST_USE_LAUNCHERS") &&
  1905. !this->State->GetGlobalProperty("RULE_LAUNCH_COMPILE")) {
  1906. cmSystemTools::Error(
  1907. "CTEST_USE_LAUNCHERS is enabled, but the "
  1908. "RULE_LAUNCH_COMPILE global property is not defined.\n"
  1909. "Did you forget to include(CTest) in the toplevel "
  1910. "CMakeLists.txt ?");
  1911. }
  1912. this->State->SaveVerificationScript(this->GetHomeOutputDirectory());
  1913. this->SaveCache(this->GetHomeOutputDirectory());
  1914. if (cmSystemTools::GetErrorOccuredFlag()) {
  1915. return -1;
  1916. }
  1917. return 0;
  1918. }
  1919. std::unique_ptr<cmGlobalGenerator> cmake::EvaluateDefaultGlobalGenerator()
  1920. {
  1921. if (!this->EnvironmentGenerator.empty()) {
  1922. auto gen = this->CreateGlobalGenerator(this->EnvironmentGenerator);
  1923. if (!gen) {
  1924. cmSystemTools::Error("CMAKE_GENERATOR was set but the specified "
  1925. "generator doesn't exist. Using CMake default.");
  1926. } else {
  1927. return gen;
  1928. }
  1929. }
  1930. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(CMAKE_BOOT_MINGW)
  1931. std::string found;
  1932. // Try to find the newest VS installed on the computer and
  1933. // use that as a default if -G is not specified
  1934. const std::string vsregBase = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\";
  1935. static const char* const vsVariants[] = {
  1936. /* clang-format needs this comment to break after the opening brace */
  1937. "VisualStudio\\", "VCExpress\\", "WDExpress\\"
  1938. };
  1939. struct VSVersionedGenerator
  1940. {
  1941. const char* MSVersion;
  1942. const char* GeneratorName;
  1943. };
  1944. static VSVersionedGenerator const vsGenerators[] = {
  1945. { "14.0", "Visual Studio 14 2015" }, //
  1946. { "12.0", "Visual Studio 12 2013" }, //
  1947. { "11.0", "Visual Studio 11 2012" }, //
  1948. { "10.0", "Visual Studio 10 2010" }, //
  1949. { "9.0", "Visual Studio 9 2008" }
  1950. };
  1951. static const char* const vsEntries[] = {
  1952. "\\Setup\\VC;ProductDir", //
  1953. ";InstallDir" //
  1954. };
  1955. if (cmVSSetupAPIHelper(16).IsVSInstalled()) {
  1956. found = "Visual Studio 16 2019";
  1957. } else if (cmVSSetupAPIHelper(15).IsVSInstalled()) {
  1958. found = "Visual Studio 15 2017";
  1959. } else {
  1960. for (VSVersionedGenerator const* g = cm::cbegin(vsGenerators);
  1961. found.empty() && g != cm::cend(vsGenerators); ++g) {
  1962. for (const char* const* v = cm::cbegin(vsVariants);
  1963. found.empty() && v != cm::cend(vsVariants); ++v) {
  1964. for (const char* const* e = cm::cbegin(vsEntries);
  1965. found.empty() && e != cm::cend(vsEntries); ++e) {
  1966. std::string const reg = vsregBase + *v + g->MSVersion + *e;
  1967. std::string dir;
  1968. if (cmSystemTools::ReadRegistryValue(reg, dir,
  1969. cmSystemTools::KeyWOW64_32) &&
  1970. cmSystemTools::PathExists(dir)) {
  1971. found = g->GeneratorName;
  1972. }
  1973. }
  1974. }
  1975. }
  1976. }
  1977. auto gen = this->CreateGlobalGenerator(found);
  1978. if (!gen) {
  1979. gen = cm::make_unique<cmGlobalNMakeMakefileGenerator>(this);
  1980. }
  1981. return std::unique_ptr<cmGlobalGenerator>(std::move(gen));
  1982. #elif defined(CMAKE_BOOTSTRAP_NINJA)
  1983. return std::unique_ptr<cmGlobalGenerator>(
  1984. cm::make_unique<cmGlobalNinjaGenerator>(this));
  1985. #else
  1986. return std::unique_ptr<cmGlobalGenerator>(
  1987. cm::make_unique<cmGlobalUnixMakefileGenerator3>(this));
  1988. #endif
  1989. }
  1990. void cmake::CreateDefaultGlobalGenerator()
  1991. {
  1992. auto gen = this->EvaluateDefaultGlobalGenerator();
  1993. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(CMAKE_BOOT_MINGW)
  1994. // This print could be unified for all platforms
  1995. std::cout << "-- Building for: " << gen->GetName() << "\n";
  1996. #endif
  1997. this->SetGlobalGenerator(std::move(gen));
  1998. }
  1999. void cmake::PreLoadCMakeFiles()
  2000. {
  2001. std::vector<std::string> args;
  2002. std::string pre_load = this->GetHomeDirectory();
  2003. if (!pre_load.empty()) {
  2004. pre_load += "/PreLoad.cmake";
  2005. if (cmSystemTools::FileExists(pre_load)) {
  2006. this->ReadListFile(args, pre_load);
  2007. }
  2008. }
  2009. pre_load = this->GetHomeOutputDirectory();
  2010. if (!pre_load.empty()) {
  2011. pre_load += "/PreLoad.cmake";
  2012. if (cmSystemTools::FileExists(pre_load)) {
  2013. this->ReadListFile(args, pre_load);
  2014. }
  2015. }
  2016. }
  2017. // handle a command line invocation
  2018. int cmake::Run(const std::vector<std::string>& args, bool noconfigure)
  2019. {
  2020. // Process the arguments
  2021. this->SetArgs(args);
  2022. if (cmSystemTools::GetErrorOccuredFlag()) {
  2023. return -1;
  2024. }
  2025. if (this->GetWorkingMode() == HELP_MODE) {
  2026. return 0;
  2027. }
  2028. // Log the trace format version to the desired output
  2029. if (this->GetTrace()) {
  2030. this->PrintTraceFormatVersion();
  2031. }
  2032. // If we are given a stamp list file check if it is really out of date.
  2033. if (!this->CheckStampList.empty() &&
  2034. cmakeCheckStampList(this->CheckStampList)) {
  2035. return 0;
  2036. }
  2037. // If we are given a stamp file check if it is really out of date.
  2038. if (!this->CheckStampFile.empty() &&
  2039. cmakeCheckStampFile(this->CheckStampFile)) {
  2040. return 0;
  2041. }
  2042. if (this->GetWorkingMode() == NORMAL_MODE) {
  2043. // load the cache
  2044. if (this->LoadCache() < 0) {
  2045. cmSystemTools::Error("Error executing cmake::LoadCache(). Aborting.\n");
  2046. return -1;
  2047. }
  2048. } else {
  2049. this->AddCMakePaths();
  2050. }
  2051. #ifndef CMAKE_BOOTSTRAP
  2052. this->ProcessPresetVariables();
  2053. this->ProcessPresetEnvironment();
  2054. #endif
  2055. // Add any cache args
  2056. if (!this->SetCacheArgs(args)) {
  2057. cmSystemTools::Error("Run 'cmake --help' for all supported options.");
  2058. return -1;
  2059. }
  2060. #ifndef CMAKE_BOOTSTRAP
  2061. this->PrintPresetVariables();
  2062. this->PrintPresetEnvironment();
  2063. #endif
  2064. // In script mode we terminate after running the script.
  2065. if (this->GetWorkingMode() != NORMAL_MODE) {
  2066. if (cmSystemTools::GetErrorOccuredFlag()) {
  2067. return -1;
  2068. }
  2069. return 0;
  2070. }
  2071. // If MAKEFLAGS are given in the environment, remove the environment
  2072. // variable. This will prevent try-compile from succeeding when it
  2073. // should fail (if "-i" is an option). We cannot simply test
  2074. // whether "-i" is given and remove it because some make programs
  2075. // encode the MAKEFLAGS variable in a strange way.
  2076. if (cmSystemTools::HasEnv("MAKEFLAGS")) {
  2077. cmSystemTools::PutEnv("MAKEFLAGS=");
  2078. }
  2079. this->PreLoadCMakeFiles();
  2080. if (noconfigure) {
  2081. return 0;
  2082. }
  2083. // now run the global generate
  2084. // Check the state of the build system to see if we need to regenerate.
  2085. if (!this->CheckBuildSystem()) {
  2086. return 0;
  2087. }
  2088. int ret = this->Configure();
  2089. if (ret) {
  2090. #if defined(CMAKE_HAVE_VS_GENERATORS)
  2091. if (!this->VSSolutionFile.empty() && this->GlobalGenerator) {
  2092. // CMake is running to regenerate a Visual Studio build tree
  2093. // during a build from the VS IDE. The build files cannot be
  2094. // regenerated, so we should stop the build.
  2095. cmSystemTools::Message("CMake Configure step failed. "
  2096. "Build files cannot be regenerated correctly. "
  2097. "Attempting to stop IDE build.");
  2098. cmGlobalVisualStudioGenerator& gg =
  2099. cm::static_reference_cast<cmGlobalVisualStudioGenerator>(
  2100. this->GlobalGenerator);
  2101. gg.CallVisualStudioMacro(cmGlobalVisualStudioGenerator::MacroStop,
  2102. this->VSSolutionFile);
  2103. }
  2104. #endif
  2105. return ret;
  2106. }
  2107. ret = this->Generate();
  2108. if (ret) {
  2109. cmSystemTools::Message("CMake Generate step failed. "
  2110. "Build files cannot be regenerated correctly.");
  2111. return ret;
  2112. }
  2113. std::string message = cmStrCat("Build files have been written to: ",
  2114. this->GetHomeOutputDirectory());
  2115. this->UpdateProgress(message, -1);
  2116. return ret;
  2117. }
  2118. int cmake::Generate()
  2119. {
  2120. if (!this->GlobalGenerator) {
  2121. return -1;
  2122. }
  2123. if (!this->GlobalGenerator->Compute()) {
  2124. return -1;
  2125. }
  2126. this->GlobalGenerator->Generate();
  2127. if (!this->GraphVizFile.empty()) {
  2128. std::cout << "Generate graphviz: " << this->GraphVizFile << std::endl;
  2129. this->GenerateGraphViz(this->GraphVizFile);
  2130. }
  2131. if (this->WarnUnusedCli) {
  2132. this->RunCheckForUnusedVariables();
  2133. }
  2134. if (cmSystemTools::GetErrorOccuredFlag()) {
  2135. return -1;
  2136. }
  2137. // Save the cache again after a successful Generate so that any internal
  2138. // variables created during Generate are saved. (Specifically target GUIDs
  2139. // for the Visual Studio and Xcode generators.)
  2140. this->SaveCache(this->GetHomeOutputDirectory());
  2141. #if !defined(CMAKE_BOOTSTRAP)
  2142. this->FileAPI->WriteReplies();
  2143. #endif
  2144. return 0;
  2145. }
  2146. void cmake::AddCacheEntry(const std::string& key, const char* value,
  2147. const char* helpString, int type)
  2148. {
  2149. this->State->AddCacheEntry(key, value, helpString,
  2150. cmStateEnums::CacheEntryType(type));
  2151. this->UnwatchUnusedCli(key);
  2152. if (key == "CMAKE_WARN_DEPRECATED"_s) {
  2153. this->Messenger->SetSuppressDeprecatedWarnings(value && cmIsOff(value));
  2154. } else if (key == "CMAKE_ERROR_DEPRECATED"_s) {
  2155. this->Messenger->SetDeprecatedWarningsAsErrors(cmIsOn(value));
  2156. } else if (key == "CMAKE_SUPPRESS_DEVELOPER_WARNINGS"_s) {
  2157. this->Messenger->SetSuppressDevWarnings(cmIsOn(value));
  2158. } else if (key == "CMAKE_SUPPRESS_DEVELOPER_ERRORS"_s) {
  2159. this->Messenger->SetDevWarningsAsErrors(value && cmIsOff(value));
  2160. }
  2161. }
  2162. bool cmake::DoWriteGlobVerifyTarget() const
  2163. {
  2164. return this->State->DoWriteGlobVerifyTarget();
  2165. }
  2166. std::string const& cmake::GetGlobVerifyScript() const
  2167. {
  2168. return this->State->GetGlobVerifyScript();
  2169. }
  2170. std::string const& cmake::GetGlobVerifyStamp() const
  2171. {
  2172. return this->State->GetGlobVerifyStamp();
  2173. }
  2174. void cmake::AddGlobCacheEntry(bool recurse, bool listDirectories,
  2175. bool followSymlinks, const std::string& relative,
  2176. const std::string& expression,
  2177. const std::vector<std::string>& files,
  2178. const std::string& variable,
  2179. cmListFileBacktrace const& backtrace)
  2180. {
  2181. this->State->AddGlobCacheEntry(recurse, listDirectories, followSymlinks,
  2182. relative, expression, files, variable,
  2183. backtrace);
  2184. }
  2185. std::vector<std::string> cmake::GetAllExtensions() const
  2186. {
  2187. std::vector<std::string> allExt = this->CLikeSourceFileExtensions.ordered;
  2188. allExt.insert(allExt.end(), this->HeaderFileExtensions.ordered.begin(),
  2189. this->HeaderFileExtensions.ordered.end());
  2190. // cuda extensions are also in SourceFileExtensions so we ignore it here
  2191. allExt.insert(allExt.end(), this->FortranFileExtensions.ordered.begin(),
  2192. this->FortranFileExtensions.ordered.end());
  2193. allExt.insert(allExt.end(), this->ISPCFileExtensions.ordered.begin(),
  2194. this->ISPCFileExtensions.ordered.end());
  2195. return allExt;
  2196. }
  2197. std::string cmake::StripExtension(const std::string& file) const
  2198. {
  2199. auto dotpos = file.rfind('.');
  2200. if (dotpos != std::string::npos) {
  2201. #if defined(_WIN32) || defined(__APPLE__)
  2202. auto ext = cmSystemTools::LowerCase(file.substr(dotpos + 1));
  2203. #else
  2204. auto ext = cm::string_view(file).substr(dotpos + 1);
  2205. #endif
  2206. if (this->IsAKnownExtension(ext)) {
  2207. return file.substr(0, dotpos);
  2208. }
  2209. }
  2210. return file;
  2211. }
  2212. cmProp cmake::GetCacheDefinition(const std::string& name) const
  2213. {
  2214. return this->State->GetInitializedCacheValue(name);
  2215. }
  2216. void cmake::AddScriptingCommands() const
  2217. {
  2218. GetScriptingCommands(this->GetState());
  2219. }
  2220. void cmake::AddProjectCommands() const
  2221. {
  2222. GetProjectCommands(this->GetState());
  2223. }
  2224. void cmake::AddDefaultGenerators()
  2225. {
  2226. #if defined(_WIN32) && !defined(__CYGWIN__)
  2227. # if !defined(CMAKE_BOOT_MINGW)
  2228. this->Generators.push_back(
  2229. cmGlobalVisualStudioVersionedGenerator::NewFactory16());
  2230. this->Generators.push_back(
  2231. cmGlobalVisualStudioVersionedGenerator::NewFactory15());
  2232. this->Generators.push_back(cmGlobalVisualStudio14Generator::NewFactory());
  2233. this->Generators.push_back(cmGlobalVisualStudio12Generator::NewFactory());
  2234. this->Generators.push_back(cmGlobalVisualStudio11Generator::NewFactory());
  2235. this->Generators.push_back(cmGlobalVisualStudio10Generator::NewFactory());
  2236. this->Generators.push_back(cmGlobalVisualStudio9Generator::NewFactory());
  2237. this->Generators.push_back(cmGlobalBorlandMakefileGenerator::NewFactory());
  2238. this->Generators.push_back(cmGlobalNMakeMakefileGenerator::NewFactory());
  2239. this->Generators.push_back(cmGlobalJOMMakefileGenerator::NewFactory());
  2240. # endif
  2241. this->Generators.push_back(cmGlobalMSYSMakefileGenerator::NewFactory());
  2242. this->Generators.push_back(cmGlobalMinGWMakefileGenerator::NewFactory());
  2243. #endif
  2244. #if !defined(CMAKE_BOOTSTRAP)
  2245. # if defined(__linux__) || defined(_WIN32)
  2246. this->Generators.push_back(cmGlobalGhsMultiGenerator::NewFactory());
  2247. # endif
  2248. this->Generators.push_back(cmGlobalUnixMakefileGenerator3::NewFactory());
  2249. this->Generators.push_back(cmGlobalNinjaGenerator::NewFactory());
  2250. this->Generators.push_back(cmGlobalNinjaMultiGenerator::NewFactory());
  2251. #elif defined(CMAKE_BOOTSTRAP_NINJA)
  2252. this->Generators.push_back(cmGlobalNinjaGenerator::NewFactory());
  2253. #elif defined(CMAKE_BOOTSTRAP_MAKEFILES)
  2254. this->Generators.push_back(cmGlobalUnixMakefileGenerator3::NewFactory());
  2255. #endif
  2256. #if defined(CMAKE_USE_WMAKE)
  2257. this->Generators.push_back(cmGlobalWatcomWMakeGenerator::NewFactory());
  2258. #endif
  2259. #ifdef CMAKE_USE_XCODE
  2260. this->Generators.push_back(cmGlobalXCodeGenerator::NewFactory());
  2261. #endif
  2262. }
  2263. bool cmake::ParseCacheEntry(const std::string& entry, std::string& var,
  2264. std::string& value,
  2265. cmStateEnums::CacheEntryType& type)
  2266. {
  2267. return cmState::ParseCacheEntry(entry, var, value, type);
  2268. }
  2269. int cmake::LoadCache()
  2270. {
  2271. // could we not read the cache
  2272. if (!this->LoadCache(this->GetHomeOutputDirectory())) {
  2273. // if it does exist, but isn't readable then warn the user
  2274. std::string cacheFile =
  2275. cmStrCat(this->GetHomeOutputDirectory(), "/CMakeCache.txt");
  2276. if (cmSystemTools::FileExists(cacheFile)) {
  2277. cmSystemTools::Error(
  2278. "There is a CMakeCache.txt file for the current binary tree but "
  2279. "cmake does not have permission to read it. Please check the "
  2280. "permissions of the directory you are trying to run CMake on.");
  2281. return -1;
  2282. }
  2283. }
  2284. // setup CMAKE_ROOT and CMAKE_COMMAND
  2285. if (!this->AddCMakePaths()) {
  2286. return -3;
  2287. }
  2288. return 0;
  2289. }
  2290. bool cmake::LoadCache(const std::string& path)
  2291. {
  2292. std::set<std::string> emptySet;
  2293. return this->LoadCache(path, true, emptySet, emptySet);
  2294. }
  2295. bool cmake::LoadCache(const std::string& path, bool internal,
  2296. std::set<std::string>& excludes,
  2297. std::set<std::string>& includes)
  2298. {
  2299. bool result = this->State->LoadCache(path, internal, excludes, includes);
  2300. static const auto entries = { "CMAKE_CACHE_MAJOR_VERSION",
  2301. "CMAKE_CACHE_MINOR_VERSION" };
  2302. for (auto const& entry : entries) {
  2303. this->UnwatchUnusedCli(entry);
  2304. }
  2305. return result;
  2306. }
  2307. bool cmake::SaveCache(const std::string& path)
  2308. {
  2309. bool result = this->State->SaveCache(path, this->GetMessenger());
  2310. static const auto entries = { "CMAKE_CACHE_MAJOR_VERSION",
  2311. "CMAKE_CACHE_MINOR_VERSION",
  2312. "CMAKE_CACHE_PATCH_VERSION",
  2313. "CMAKE_CACHEFILE_DIR" };
  2314. for (auto const& entry : entries) {
  2315. this->UnwatchUnusedCli(entry);
  2316. }
  2317. return result;
  2318. }
  2319. bool cmake::DeleteCache(const std::string& path)
  2320. {
  2321. return this->State->DeleteCache(path);
  2322. }
  2323. void cmake::SetProgressCallback(ProgressCallbackType f)
  2324. {
  2325. this->ProgressCallback = std::move(f);
  2326. }
  2327. void cmake::UpdateProgress(const std::string& msg, float prog)
  2328. {
  2329. if (this->ProgressCallback && !this->State->GetIsInTryCompile()) {
  2330. this->ProgressCallback(msg, prog);
  2331. }
  2332. }
  2333. bool cmake::GetIsInTryCompile() const
  2334. {
  2335. return this->State->GetIsInTryCompile();
  2336. }
  2337. void cmake::SetIsInTryCompile(bool b)
  2338. {
  2339. this->State->SetIsInTryCompile(b);
  2340. }
  2341. void cmake::AppendGlobalGeneratorsDocumentation(
  2342. std::vector<cmDocumentationEntry>& v)
  2343. {
  2344. const auto defaultGenerator = this->EvaluateDefaultGlobalGenerator();
  2345. const std::string defaultName = defaultGenerator->GetName();
  2346. bool foundDefaultOne = false;
  2347. for (const auto& g : this->Generators) {
  2348. cmDocumentationEntry e;
  2349. g->GetDocumentation(e);
  2350. if (!foundDefaultOne && cmHasPrefix(e.Name, defaultName)) {
  2351. e.CustomNamePrefix = '*';
  2352. foundDefaultOne = true;
  2353. }
  2354. v.push_back(std::move(e));
  2355. }
  2356. }
  2357. void cmake::AppendExtraGeneratorsDocumentation(
  2358. std::vector<cmDocumentationEntry>& v)
  2359. {
  2360. for (cmExternalMakefileProjectGeneratorFactory* eg : this->ExtraGenerators) {
  2361. const std::string doc = eg->GetDocumentation();
  2362. const std::string name = eg->GetName();
  2363. // Aliases:
  2364. for (std::string const& a : eg->Aliases) {
  2365. cmDocumentationEntry e;
  2366. e.Name = a;
  2367. e.Brief = doc;
  2368. v.push_back(std::move(e));
  2369. }
  2370. // Full names:
  2371. const std::vector<std::string> generators =
  2372. eg->GetSupportedGlobalGenerators();
  2373. for (std::string const& g : generators) {
  2374. cmDocumentationEntry e;
  2375. e.Name =
  2376. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(g, name);
  2377. e.Brief = doc;
  2378. v.push_back(std::move(e));
  2379. }
  2380. }
  2381. }
  2382. std::vector<cmDocumentationEntry> cmake::GetGeneratorsDocumentation()
  2383. {
  2384. std::vector<cmDocumentationEntry> v;
  2385. this->AppendGlobalGeneratorsDocumentation(v);
  2386. this->AppendExtraGeneratorsDocumentation(v);
  2387. return v;
  2388. }
  2389. void cmake::PrintGeneratorList()
  2390. {
  2391. #ifndef CMAKE_BOOTSTRAP
  2392. cmDocumentation doc;
  2393. auto generators = this->GetGeneratorsDocumentation();
  2394. doc.AppendSection("Generators", generators);
  2395. std::cerr << "\n";
  2396. doc.PrintDocumentation(cmDocumentation::ListGenerators, std::cerr);
  2397. #endif
  2398. }
  2399. void cmake::UpdateConversionPathTable()
  2400. {
  2401. // Update the path conversion table with any specified file:
  2402. cmProp tablepath =
  2403. this->State->GetInitializedCacheValue("CMAKE_PATH_TRANSLATION_FILE");
  2404. if (tablepath) {
  2405. cmsys::ifstream table(tablepath->c_str());
  2406. if (!table) {
  2407. cmSystemTools::Error("CMAKE_PATH_TRANSLATION_FILE set to " + *tablepath +
  2408. ". CMake can not open file.");
  2409. cmSystemTools::ReportLastSystemError("CMake can not open file.");
  2410. } else {
  2411. std::string a;
  2412. std::string b;
  2413. while (!table.eof()) {
  2414. // two entries per line
  2415. table >> a;
  2416. table >> b;
  2417. cmSystemTools::AddTranslationPath(a, b);
  2418. }
  2419. }
  2420. }
  2421. }
  2422. int cmake::CheckBuildSystem()
  2423. {
  2424. // We do not need to rerun CMake. Check dependency integrity.
  2425. const bool verbose = isCMakeVerbose();
  2426. // This method will check the integrity of the build system if the
  2427. // option was given on the command line. It reads the given file to
  2428. // determine whether CMake should rerun.
  2429. // If no file is provided for the check, we have to rerun.
  2430. if (this->CheckBuildSystemArgument.empty()) {
  2431. if (verbose) {
  2432. cmSystemTools::Stdout("Re-run cmake no build system arguments\n");
  2433. }
  2434. return 1;
  2435. }
  2436. // If the file provided does not exist, we have to rerun.
  2437. if (!cmSystemTools::FileExists(this->CheckBuildSystemArgument)) {
  2438. if (verbose) {
  2439. std::ostringstream msg;
  2440. msg << "Re-run cmake missing file: " << this->CheckBuildSystemArgument
  2441. << "\n";
  2442. cmSystemTools::Stdout(msg.str());
  2443. }
  2444. return 1;
  2445. }
  2446. // Read the rerun check file and use it to decide whether to do the
  2447. // global generate.
  2448. // Actually, all we need is the `set` command.
  2449. cmake cm(RoleScript, cmState::Unknown);
  2450. cm.SetHomeDirectory("");
  2451. cm.SetHomeOutputDirectory("");
  2452. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  2453. cmGlobalGenerator gg(&cm);
  2454. cmMakefile mf(&gg, cm.GetCurrentSnapshot());
  2455. if (!mf.ReadListFile(this->CheckBuildSystemArgument) ||
  2456. cmSystemTools::GetErrorOccuredFlag()) {
  2457. if (verbose) {
  2458. std::ostringstream msg;
  2459. msg << "Re-run cmake error reading : " << this->CheckBuildSystemArgument
  2460. << "\n";
  2461. cmSystemTools::Stdout(msg.str());
  2462. }
  2463. // There was an error reading the file. Just rerun.
  2464. return 1;
  2465. }
  2466. if (this->ClearBuildSystem) {
  2467. // Get the generator used for this build system.
  2468. std::string genName = mf.GetSafeDefinition("CMAKE_DEPENDS_GENERATOR");
  2469. if (!cmNonempty(genName)) {
  2470. genName = "Unix Makefiles";
  2471. }
  2472. // Create the generator and use it to clear the dependencies.
  2473. std::unique_ptr<cmGlobalGenerator> ggd =
  2474. this->CreateGlobalGenerator(genName);
  2475. if (ggd) {
  2476. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  2477. cmMakefile mfd(ggd.get(), cm.GetCurrentSnapshot());
  2478. auto lgd = ggd->CreateLocalGenerator(&mfd);
  2479. lgd->ClearDependencies(&mfd, verbose);
  2480. }
  2481. }
  2482. // If any byproduct of makefile generation is missing we must re-run.
  2483. std::vector<std::string> products;
  2484. mf.GetDefExpandList("CMAKE_MAKEFILE_PRODUCTS", products);
  2485. for (std::string const& p : products) {
  2486. if (!(cmSystemTools::FileExists(p) || cmSystemTools::FileIsSymlink(p))) {
  2487. if (verbose) {
  2488. std::ostringstream msg;
  2489. msg << "Re-run cmake, missing byproduct: " << p << "\n";
  2490. cmSystemTools::Stdout(msg.str());
  2491. }
  2492. return 1;
  2493. }
  2494. }
  2495. // Get the set of dependencies and outputs.
  2496. std::vector<std::string> depends;
  2497. std::vector<std::string> outputs;
  2498. if (mf.GetDefExpandList("CMAKE_MAKEFILE_DEPENDS", depends)) {
  2499. mf.GetDefExpandList("CMAKE_MAKEFILE_OUTPUTS", outputs);
  2500. }
  2501. if (depends.empty() || outputs.empty()) {
  2502. // Not enough information was provided to do the test. Just rerun.
  2503. if (verbose) {
  2504. cmSystemTools::Stdout("Re-run cmake no CMAKE_MAKEFILE_DEPENDS "
  2505. "or CMAKE_MAKEFILE_OUTPUTS :\n");
  2506. }
  2507. return 1;
  2508. }
  2509. // Find the newest dependency.
  2510. auto dep = depends.begin();
  2511. std::string dep_newest = *dep++;
  2512. for (; dep != depends.end(); ++dep) {
  2513. int result = 0;
  2514. if (this->FileTimeCache->Compare(dep_newest, *dep, &result)) {
  2515. if (result < 0) {
  2516. dep_newest = *dep;
  2517. }
  2518. } else {
  2519. if (verbose) {
  2520. cmSystemTools::Stdout(
  2521. "Re-run cmake: build system dependency is missing\n");
  2522. }
  2523. return 1;
  2524. }
  2525. }
  2526. // Find the oldest output.
  2527. auto out = outputs.begin();
  2528. std::string out_oldest = *out++;
  2529. for (; out != outputs.end(); ++out) {
  2530. int result = 0;
  2531. if (this->FileTimeCache->Compare(out_oldest, *out, &result)) {
  2532. if (result > 0) {
  2533. out_oldest = *out;
  2534. }
  2535. } else {
  2536. if (verbose) {
  2537. cmSystemTools::Stdout(
  2538. "Re-run cmake: build system output is missing\n");
  2539. }
  2540. return 1;
  2541. }
  2542. }
  2543. // If any output is older than any dependency then rerun.
  2544. {
  2545. int result = 0;
  2546. if (!this->FileTimeCache->Compare(out_oldest, dep_newest, &result) ||
  2547. result < 0) {
  2548. if (verbose) {
  2549. std::ostringstream msg;
  2550. msg << "Re-run cmake file: " << out_oldest
  2551. << " older than: " << dep_newest << "\n";
  2552. cmSystemTools::Stdout(msg.str());
  2553. }
  2554. return 1;
  2555. }
  2556. }
  2557. // No need to rerun.
  2558. return 0;
  2559. }
  2560. void cmake::TruncateOutputLog(const char* fname)
  2561. {
  2562. std::string fullPath = cmStrCat(this->GetHomeOutputDirectory(), '/', fname);
  2563. struct stat st;
  2564. if (::stat(fullPath.c_str(), &st)) {
  2565. return;
  2566. }
  2567. if (!this->State->GetInitializedCacheValue("CMAKE_CACHEFILE_DIR")) {
  2568. cmSystemTools::RemoveFile(fullPath);
  2569. return;
  2570. }
  2571. off_t fsize = st.st_size;
  2572. const off_t maxFileSize = 50 * 1024;
  2573. if (fsize < maxFileSize) {
  2574. // TODO: truncate file
  2575. return;
  2576. }
  2577. }
  2578. void cmake::MarkCliAsUsed(const std::string& variable)
  2579. {
  2580. this->UsedCliVariables[variable] = true;
  2581. }
  2582. void cmake::GenerateGraphViz(const std::string& fileName) const
  2583. {
  2584. #ifndef CMAKE_BOOTSTRAP
  2585. cmGraphVizWriter gvWriter(fileName, this->GetGlobalGenerator());
  2586. std::string settingsFile =
  2587. cmStrCat(this->GetHomeOutputDirectory(), "/CMakeGraphVizOptions.cmake");
  2588. std::string fallbackSettingsFile =
  2589. cmStrCat(this->GetHomeDirectory(), "/CMakeGraphVizOptions.cmake");
  2590. gvWriter.ReadSettings(settingsFile, fallbackSettingsFile);
  2591. gvWriter.Write();
  2592. #endif
  2593. }
  2594. void cmake::SetProperty(const std::string& prop, const char* value)
  2595. {
  2596. this->State->SetGlobalProperty(prop, value);
  2597. }
  2598. void cmake::AppendProperty(const std::string& prop, const std::string& value,
  2599. bool asString)
  2600. {
  2601. this->State->AppendGlobalProperty(prop, value, asString);
  2602. }
  2603. cmProp cmake::GetProperty(const std::string& prop)
  2604. {
  2605. return this->State->GetGlobalProperty(prop);
  2606. }
  2607. bool cmake::GetPropertyAsBool(const std::string& prop)
  2608. {
  2609. return this->State->GetGlobalPropertyAsBool(prop);
  2610. }
  2611. cmInstalledFile* cmake::GetOrCreateInstalledFile(cmMakefile* mf,
  2612. const std::string& name)
  2613. {
  2614. auto i = this->InstalledFiles.find(name);
  2615. if (i != this->InstalledFiles.end()) {
  2616. cmInstalledFile& file = i->second;
  2617. return &file;
  2618. }
  2619. cmInstalledFile& file = this->InstalledFiles[name];
  2620. file.SetName(mf, name);
  2621. return &file;
  2622. }
  2623. cmInstalledFile const* cmake::GetInstalledFile(const std::string& name) const
  2624. {
  2625. auto i = this->InstalledFiles.find(name);
  2626. if (i != this->InstalledFiles.end()) {
  2627. cmInstalledFile const& file = i->second;
  2628. return &file;
  2629. }
  2630. return nullptr;
  2631. }
  2632. int cmake::GetSystemInformation(std::vector<std::string>& args)
  2633. {
  2634. // so create the directory
  2635. std::string resultFile;
  2636. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  2637. std::string destPath = cwd + "/__cmake_systeminformation";
  2638. cmSystemTools::RemoveADirectory(destPath);
  2639. if (!cmSystemTools::MakeDirectory(destPath)) {
  2640. std::cerr << "Error: --system-information must be run from a "
  2641. "writable directory!\n";
  2642. return 1;
  2643. }
  2644. // process the arguments
  2645. bool writeToStdout = true;
  2646. for (unsigned int i = 1; i < args.size(); ++i) {
  2647. std::string const& arg = args[i];
  2648. if (cmHasLiteralPrefix(arg, "-G")) {
  2649. std::string value = arg.substr(2);
  2650. if (value.empty()) {
  2651. ++i;
  2652. if (i >= args.size()) {
  2653. cmSystemTools::Error("No generator specified for -G");
  2654. this->PrintGeneratorList();
  2655. return -1;
  2656. }
  2657. value = args[i];
  2658. }
  2659. auto gen = this->CreateGlobalGenerator(value);
  2660. if (!gen) {
  2661. cmSystemTools::Error("Could not create named generator " + value);
  2662. this->PrintGeneratorList();
  2663. } else {
  2664. this->SetGlobalGenerator(std::move(gen));
  2665. }
  2666. }
  2667. // no option assume it is the output file
  2668. else {
  2669. if (!cmSystemTools::FileIsFullPath(arg)) {
  2670. resultFile = cmStrCat(cwd, '/');
  2671. }
  2672. resultFile += arg;
  2673. writeToStdout = false;
  2674. }
  2675. }
  2676. // we have to find the module directory, so we can copy the files
  2677. this->AddCMakePaths();
  2678. std::string modulesPath =
  2679. cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules");
  2680. std::string inFile = cmStrCat(modulesPath, "/SystemInformation.cmake");
  2681. std::string outFile = cmStrCat(destPath, "/CMakeLists.txt");
  2682. // Copy file
  2683. if (!cmsys::SystemTools::CopyFileAlways(inFile, outFile)) {
  2684. std::cerr << "Error copying file \"" << inFile << "\" to \"" << outFile
  2685. << "\".\n";
  2686. return 1;
  2687. }
  2688. // do we write to a file or to stdout?
  2689. if (resultFile.empty()) {
  2690. resultFile = cmStrCat(cwd, "/__cmake_systeminformation/results.txt");
  2691. }
  2692. {
  2693. // now run cmake on the CMakeLists file
  2694. cmWorkingDirectory workdir(destPath);
  2695. if (workdir.Failed()) {
  2696. // We created the directory and we were able to copy the CMakeLists.txt
  2697. // file to it, so we wouldn't expect to get here unless the default
  2698. // permissions are questionable or some other process has deleted the
  2699. // directory
  2700. std::cerr << "Failed to change to directory " << destPath << " : "
  2701. << std::strerror(workdir.GetLastResult()) << std::endl;
  2702. return 1;
  2703. }
  2704. std::vector<std::string> args2;
  2705. args2.push_back(args[0]);
  2706. args2.push_back(destPath);
  2707. args2.push_back("-DRESULT_FILE=" + resultFile);
  2708. int res = this->Run(args2, false);
  2709. if (res != 0) {
  2710. std::cerr << "Error: --system-information failed on internal CMake!\n";
  2711. return res;
  2712. }
  2713. }
  2714. // echo results to stdout if needed
  2715. if (writeToStdout) {
  2716. FILE* fin = cmsys::SystemTools::Fopen(resultFile, "r");
  2717. if (fin) {
  2718. const int bufferSize = 4096;
  2719. char buffer[bufferSize];
  2720. size_t n;
  2721. while ((n = fread(buffer, 1, bufferSize, fin)) > 0) {
  2722. for (char* c = buffer; c < buffer + n; ++c) {
  2723. putc(*c, stdout);
  2724. }
  2725. fflush(stdout);
  2726. }
  2727. fclose(fin);
  2728. }
  2729. }
  2730. // clean up the directory
  2731. cmSystemTools::RemoveADirectory(destPath);
  2732. return 0;
  2733. }
  2734. static bool cmakeCheckStampFile(const std::string& stampName)
  2735. {
  2736. // The stamp file does not exist. Use the stamp dependencies to
  2737. // determine whether it is really out of date. This works in
  2738. // conjunction with cmLocalVisualStudio7Generator to avoid
  2739. // repeatedly re-running CMake when the user rebuilds the entire
  2740. // solution.
  2741. std::string stampDepends = cmStrCat(stampName, ".depend");
  2742. #if defined(_WIN32) || defined(__CYGWIN__)
  2743. cmsys::ifstream fin(stampDepends.c_str(), std::ios::in | std::ios::binary);
  2744. #else
  2745. cmsys::ifstream fin(stampDepends.c_str());
  2746. #endif
  2747. if (!fin) {
  2748. // The stamp dependencies file cannot be read. Just assume the
  2749. // build system is really out of date.
  2750. std::cout << "CMake is re-running because " << stampName
  2751. << " dependency file is missing.\n";
  2752. return false;
  2753. }
  2754. // Compare the stamp dependencies against the dependency file itself.
  2755. {
  2756. cmFileTimeCache ftc;
  2757. std::string dep;
  2758. while (cmSystemTools::GetLineFromStream(fin, dep)) {
  2759. int result;
  2760. if (!dep.empty() && dep[0] != '#' &&
  2761. (!ftc.Compare(stampDepends, dep, &result) || result < 0)) {
  2762. // The stamp depends file is older than this dependency. The
  2763. // build system is really out of date.
  2764. std::cout << "CMake is re-running because " << stampName
  2765. << " is out-of-date.\n";
  2766. std::cout << " the file '" << dep << "'\n";
  2767. std::cout << " is newer than '" << stampDepends << "'\n";
  2768. std::cout << " result='" << result << "'\n";
  2769. return false;
  2770. }
  2771. }
  2772. }
  2773. // The build system is up to date. The stamp file has been removed
  2774. // by the VS IDE due to a "rebuild" request. Restore it atomically.
  2775. std::ostringstream stampTempStream;
  2776. stampTempStream << stampName << ".tmp" << cmSystemTools::RandomSeed();
  2777. std::string stampTemp = stampTempStream.str();
  2778. {
  2779. // TODO: Teach cmGeneratedFileStream to use a random temp file (with
  2780. // multiple tries in unlikely case of conflict) and use that here.
  2781. cmsys::ofstream stamp(stampTemp.c_str());
  2782. stamp << "# CMake generation timestamp file for this directory.\n";
  2783. }
  2784. if (cmSystemTools::RenameFile(stampTemp, stampName)) {
  2785. // CMake does not need to re-run because the stamp file is up-to-date.
  2786. return true;
  2787. }
  2788. cmSystemTools::RemoveFile(stampTemp);
  2789. cmSystemTools::Error("Cannot restore timestamp " + stampName);
  2790. return false;
  2791. }
  2792. static bool cmakeCheckStampList(const std::string& stampList)
  2793. {
  2794. // If the stamp list does not exist CMake must rerun to generate it.
  2795. if (!cmSystemTools::FileExists(stampList)) {
  2796. std::cout << "CMake is re-running because generate.stamp.list "
  2797. << "is missing.\n";
  2798. return false;
  2799. }
  2800. cmsys::ifstream fin(stampList.c_str());
  2801. if (!fin) {
  2802. std::cout << "CMake is re-running because generate.stamp.list "
  2803. << "could not be read.\n";
  2804. return false;
  2805. }
  2806. // Check each stamp.
  2807. std::string stampName;
  2808. while (cmSystemTools::GetLineFromStream(fin, stampName)) {
  2809. if (!cmakeCheckStampFile(stampName)) {
  2810. return false;
  2811. }
  2812. }
  2813. return true;
  2814. }
  2815. void cmake::IssueMessage(MessageType t, std::string const& text,
  2816. cmListFileBacktrace const& backtrace) const
  2817. {
  2818. this->Messenger->IssueMessage(t, text, backtrace);
  2819. }
  2820. std::vector<std::string> cmake::GetDebugConfigs()
  2821. {
  2822. std::vector<std::string> configs;
  2823. if (cmProp config_list =
  2824. this->State->GetGlobalProperty("DEBUG_CONFIGURATIONS")) {
  2825. // Expand the specified list and convert to upper-case.
  2826. cmExpandList(*config_list, configs);
  2827. std::transform(configs.begin(), configs.end(), configs.begin(),
  2828. cmSystemTools::UpperCase);
  2829. }
  2830. // If no configurations were specified, use a default list.
  2831. if (configs.empty()) {
  2832. configs.emplace_back("DEBUG");
  2833. }
  2834. return configs;
  2835. }
  2836. int cmake::Build(int jobs, std::string dir, std::vector<std::string> targets,
  2837. std::string config, std::vector<std::string> nativeOptions,
  2838. bool clean, bool verbose, const std::string& presetName,
  2839. bool listPresets)
  2840. {
  2841. this->SetHomeDirectory("");
  2842. this->SetHomeOutputDirectory("");
  2843. #if !defined(CMAKE_BOOTSTRAP)
  2844. if (!presetName.empty() || listPresets) {
  2845. this->SetHomeDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  2846. this->SetHomeOutputDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  2847. cmCMakePresetsFile settingsFile;
  2848. auto result = settingsFile.ReadProjectPresets(this->GetHomeDirectory());
  2849. if (result != cmCMakePresetsFile::ReadFileResult::READ_OK) {
  2850. cmSystemTools::Error(
  2851. cmStrCat("Could not read presets from ", this->GetHomeDirectory(),
  2852. ": ", cmCMakePresetsFile::ResultToString(result)));
  2853. return 1;
  2854. }
  2855. if (listPresets) {
  2856. settingsFile.PrintBuildPresetList();
  2857. return 0;
  2858. }
  2859. auto presetPair = settingsFile.BuildPresets.find(presetName);
  2860. if (presetPair == settingsFile.BuildPresets.end()) {
  2861. cmSystemTools::Error(cmStrCat("No such build preset in ",
  2862. this->GetHomeDirectory(), ": \"",
  2863. presetName, '"'));
  2864. settingsFile.PrintBuildPresetList();
  2865. return 1;
  2866. }
  2867. if (presetPair->second.Unexpanded.Hidden) {
  2868. cmSystemTools::Error(cmStrCat("Cannot use hidden build preset in ",
  2869. this->GetHomeDirectory(), ": \"",
  2870. presetName, '"'));
  2871. settingsFile.PrintBuildPresetList();
  2872. return 1;
  2873. }
  2874. auto const& expandedPreset = presetPair->second.Expanded;
  2875. if (!expandedPreset) {
  2876. cmSystemTools::Error(cmStrCat("Could not evaluate build preset \"",
  2877. presetName,
  2878. "\": Invalid macro expansion"));
  2879. settingsFile.PrintBuildPresetList();
  2880. return 1;
  2881. }
  2882. if (!expandedPreset->ConditionResult) {
  2883. cmSystemTools::Error(cmStrCat("Cannot use disabled build preset in ",
  2884. this->GetHomeDirectory(), ": \"",
  2885. presetName, '"'));
  2886. settingsFile.PrintBuildPresetList();
  2887. return 1;
  2888. }
  2889. auto configurePresetPair =
  2890. settingsFile.ConfigurePresets.find(expandedPreset->ConfigurePreset);
  2891. if (configurePresetPair == settingsFile.ConfigurePresets.end()) {
  2892. cmSystemTools::Error(cmStrCat("No such configure preset in ",
  2893. this->GetHomeDirectory(), ": \"",
  2894. expandedPreset->ConfigurePreset, '"'));
  2895. this->PrintPresetList(settingsFile);
  2896. return 1;
  2897. }
  2898. if (configurePresetPair->second.Unexpanded.Hidden) {
  2899. cmSystemTools::Error(cmStrCat("Cannot use hidden configure preset in ",
  2900. this->GetHomeDirectory(), ": \"",
  2901. expandedPreset->ConfigurePreset, '"'));
  2902. this->PrintPresetList(settingsFile);
  2903. return 1;
  2904. }
  2905. auto const& expandedConfigurePreset = configurePresetPair->second.Expanded;
  2906. if (!expandedConfigurePreset) {
  2907. cmSystemTools::Error(cmStrCat("Could not evaluate configure preset \"",
  2908. expandedPreset->ConfigurePreset,
  2909. "\": Invalid macro expansion"));
  2910. return 1;
  2911. }
  2912. dir = expandedConfigurePreset->BinaryDir;
  2913. this->UnprocessedPresetEnvironment = expandedPreset->Environment;
  2914. this->ProcessPresetEnvironment();
  2915. if (jobs == cmake::DEFAULT_BUILD_PARALLEL_LEVEL && expandedPreset->Jobs) {
  2916. jobs = *expandedPreset->Jobs;
  2917. }
  2918. if (targets.empty()) {
  2919. targets.insert(targets.begin(), expandedPreset->Targets.begin(),
  2920. expandedPreset->Targets.end());
  2921. }
  2922. if (config.empty()) {
  2923. config = expandedPreset->Configuration;
  2924. }
  2925. if (!clean && expandedPreset->CleanFirst) {
  2926. clean = *expandedPreset->CleanFirst;
  2927. }
  2928. if (!verbose && expandedPreset->Verbose) {
  2929. verbose = *expandedPreset->Verbose;
  2930. }
  2931. if (nativeOptions.empty()) {
  2932. nativeOptions.insert(nativeOptions.begin(),
  2933. expandedPreset->NativeToolOptions.begin(),
  2934. expandedPreset->NativeToolOptions.end());
  2935. }
  2936. }
  2937. #endif
  2938. if (!cmSystemTools::FileIsDirectory(dir)) {
  2939. std::cerr << "Error: " << dir << " is not a directory\n";
  2940. return 1;
  2941. }
  2942. std::string cachePath = FindCacheFile(dir);
  2943. if (!this->LoadCache(cachePath)) {
  2944. std::cerr << "Error: could not load cache\n";
  2945. return 1;
  2946. }
  2947. cmProp cachedGenerator = this->State->GetCacheEntryValue("CMAKE_GENERATOR");
  2948. if (!cachedGenerator) {
  2949. std::cerr << "Error: could not find CMAKE_GENERATOR in Cache\n";
  2950. return 1;
  2951. }
  2952. auto gen = this->CreateGlobalGenerator(*cachedGenerator);
  2953. if (!gen) {
  2954. std::cerr << "Error: could create CMAKE_GENERATOR \"" << *cachedGenerator
  2955. << "\"\n";
  2956. return 1;
  2957. }
  2958. this->SetGlobalGenerator(std::move(gen));
  2959. cmProp cachedGeneratorInstance =
  2960. this->State->GetCacheEntryValue("CMAKE_GENERATOR_INSTANCE");
  2961. if (cachedGeneratorInstance) {
  2962. cmMakefile mf(this->GetGlobalGenerator(), this->GetCurrentSnapshot());
  2963. if (!this->GlobalGenerator->SetGeneratorInstance(*cachedGeneratorInstance,
  2964. &mf)) {
  2965. return 1;
  2966. }
  2967. }
  2968. cmProp cachedGeneratorPlatform =
  2969. this->State->GetCacheEntryValue("CMAKE_GENERATOR_PLATFORM");
  2970. if (cachedGeneratorPlatform) {
  2971. cmMakefile mf(this->GetGlobalGenerator(), this->GetCurrentSnapshot());
  2972. if (!this->GlobalGenerator->SetGeneratorPlatform(*cachedGeneratorPlatform,
  2973. &mf)) {
  2974. return 1;
  2975. }
  2976. }
  2977. cmProp cachedGeneratorToolset =
  2978. this->State->GetCacheEntryValue("CMAKE_GENERATOR_TOOLSET");
  2979. if (cachedGeneratorToolset) {
  2980. cmMakefile mf(this->GetGlobalGenerator(), this->GetCurrentSnapshot());
  2981. if (!this->GlobalGenerator->SetGeneratorToolset(*cachedGeneratorToolset,
  2982. true, &mf)) {
  2983. return 1;
  2984. }
  2985. }
  2986. std::string output;
  2987. std::string projName;
  2988. cmProp cachedProjectName =
  2989. this->State->GetCacheEntryValue("CMAKE_PROJECT_NAME");
  2990. if (!cachedProjectName) {
  2991. std::cerr << "Error: could not find CMAKE_PROJECT_NAME in Cache\n";
  2992. return 1;
  2993. }
  2994. projName = *cachedProjectName;
  2995. if (cmIsOn(this->State->GetCacheEntryValue("CMAKE_VERBOSE_MAKEFILE"))) {
  2996. verbose = true;
  2997. }
  2998. #ifdef CMAKE_HAVE_VS_GENERATORS
  2999. // For VS generators, explicitly check if regeneration is necessary before
  3000. // actually starting the build. If not done separately from the build
  3001. // itself, there is the risk of building an out-of-date solution file due
  3002. // to limitations of the underlying build system.
  3003. std::string const stampList = cachePath + "/" + "CMakeFiles/" +
  3004. cmGlobalVisualStudio9Generator::GetGenerateStampList();
  3005. // Note that the stampList file only exists for VS generators.
  3006. if (cmSystemTools::FileExists(stampList)) {
  3007. // Check if running for Visual Studio 9 - we need to explicitly run
  3008. // the glob verification script before starting the build
  3009. this->AddScriptingCommands();
  3010. if (this->GlobalGenerator->MatchesGeneratorName("Visual Studio 9 2008")) {
  3011. std::string const globVerifyScript =
  3012. cachePath + "/" + "CMakeFiles/" + "VerifyGlobs.cmake";
  3013. if (cmSystemTools::FileExists(globVerifyScript)) {
  3014. std::vector<std::string> args;
  3015. this->ReadListFile(args, globVerifyScript);
  3016. }
  3017. }
  3018. if (!cmakeCheckStampList(stampList)) {
  3019. // Correctly initialize the home (=source) and home output (=binary)
  3020. // directories, which is required for running the generation step.
  3021. std::string homeOrig = this->GetHomeDirectory();
  3022. std::string homeOutputOrig = this->GetHomeOutputDirectory();
  3023. this->SetDirectoriesFromFile(cachePath);
  3024. this->AddProjectCommands();
  3025. int ret = this->Configure();
  3026. if (ret) {
  3027. cmSystemTools::Message("CMake Configure step failed. "
  3028. "Build files cannot be regenerated correctly.");
  3029. return ret;
  3030. }
  3031. ret = this->Generate();
  3032. if (ret) {
  3033. cmSystemTools::Message("CMake Generate step failed. "
  3034. "Build files cannot be regenerated correctly.");
  3035. return ret;
  3036. }
  3037. std::string message = cmStrCat("Build files have been written to: ",
  3038. this->GetHomeOutputDirectory());
  3039. this->UpdateProgress(message, -1);
  3040. // Restore the previously set directories to their original value.
  3041. this->SetHomeDirectory(homeOrig);
  3042. this->SetHomeOutputDirectory(homeOutputOrig);
  3043. }
  3044. }
  3045. #endif
  3046. if (!this->GlobalGenerator->ReadCacheEntriesForBuild(*this->State)) {
  3047. return 1;
  3048. }
  3049. this->GlobalGenerator->PrintBuildCommandAdvice(std::cerr, jobs);
  3050. return this->GlobalGenerator->Build(
  3051. jobs, "", dir, projName, targets, output, "", config, clean, false,
  3052. verbose, cmDuration::zero(), cmSystemTools::OUTPUT_PASSTHROUGH,
  3053. nativeOptions);
  3054. }
  3055. bool cmake::Open(const std::string& dir, bool dryRun)
  3056. {
  3057. this->SetHomeDirectory("");
  3058. this->SetHomeOutputDirectory("");
  3059. if (!cmSystemTools::FileIsDirectory(dir)) {
  3060. std::cerr << "Error: " << dir << " is not a directory\n";
  3061. return false;
  3062. }
  3063. std::string cachePath = FindCacheFile(dir);
  3064. if (!this->LoadCache(cachePath)) {
  3065. std::cerr << "Error: could not load cache\n";
  3066. return false;
  3067. }
  3068. cmProp genName = this->State->GetCacheEntryValue("CMAKE_GENERATOR");
  3069. if (!genName) {
  3070. std::cerr << "Error: could not find CMAKE_GENERATOR in Cache\n";
  3071. return false;
  3072. }
  3073. cmProp extraGenName =
  3074. this->State->GetInitializedCacheValue("CMAKE_EXTRA_GENERATOR");
  3075. std::string fullName =
  3076. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  3077. *genName, extraGenName ? *extraGenName : "");
  3078. std::unique_ptr<cmGlobalGenerator> gen =
  3079. this->CreateGlobalGenerator(fullName);
  3080. if (!gen) {
  3081. std::cerr << "Error: could create CMAKE_GENERATOR \"" << fullName
  3082. << "\"\n";
  3083. return false;
  3084. }
  3085. cmProp cachedProjectName =
  3086. this->State->GetCacheEntryValue("CMAKE_PROJECT_NAME");
  3087. if (!cachedProjectName) {
  3088. std::cerr << "Error: could not find CMAKE_PROJECT_NAME in Cache\n";
  3089. return false;
  3090. }
  3091. return gen->Open(dir, *cachedProjectName, dryRun);
  3092. }
  3093. void cmake::WatchUnusedCli(const std::string& var)
  3094. {
  3095. #ifndef CMAKE_BOOTSTRAP
  3096. this->VariableWatch->AddWatch(var, cmWarnUnusedCliWarning, this);
  3097. if (!cm::contains(this->UsedCliVariables, var)) {
  3098. this->UsedCliVariables[var] = false;
  3099. }
  3100. #endif
  3101. }
  3102. void cmake::UnwatchUnusedCli(const std::string& var)
  3103. {
  3104. #ifndef CMAKE_BOOTSTRAP
  3105. this->VariableWatch->RemoveWatch(var, cmWarnUnusedCliWarning);
  3106. this->UsedCliVariables.erase(var);
  3107. #endif
  3108. }
  3109. void cmake::RunCheckForUnusedVariables()
  3110. {
  3111. #ifndef CMAKE_BOOTSTRAP
  3112. bool haveUnused = false;
  3113. std::ostringstream msg;
  3114. msg << "Manually-specified variables were not used by the project:";
  3115. for (auto const& it : this->UsedCliVariables) {
  3116. if (!it.second) {
  3117. haveUnused = true;
  3118. msg << "\n " << it.first;
  3119. }
  3120. }
  3121. if (haveUnused) {
  3122. this->IssueMessage(MessageType::WARNING, msg.str());
  3123. }
  3124. #endif
  3125. }
  3126. bool cmake::GetSuppressDevWarnings() const
  3127. {
  3128. return this->Messenger->GetSuppressDevWarnings();
  3129. }
  3130. void cmake::SetSuppressDevWarnings(bool b)
  3131. {
  3132. std::string value;
  3133. // equivalent to -Wno-dev
  3134. if (b) {
  3135. value = "TRUE";
  3136. }
  3137. // equivalent to -Wdev
  3138. else {
  3139. value = "FALSE";
  3140. }
  3141. this->AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", value.c_str(),
  3142. "Suppress Warnings that are meant for"
  3143. " the author of the CMakeLists.txt files.",
  3144. cmStateEnums::INTERNAL);
  3145. }
  3146. bool cmake::GetSuppressDeprecatedWarnings() const
  3147. {
  3148. return this->Messenger->GetSuppressDeprecatedWarnings();
  3149. }
  3150. void cmake::SetSuppressDeprecatedWarnings(bool b)
  3151. {
  3152. std::string value;
  3153. // equivalent to -Wno-deprecated
  3154. if (b) {
  3155. value = "FALSE";
  3156. }
  3157. // equivalent to -Wdeprecated
  3158. else {
  3159. value = "TRUE";
  3160. }
  3161. this->AddCacheEntry("CMAKE_WARN_DEPRECATED", value.c_str(),
  3162. "Whether to issue warnings for deprecated "
  3163. "functionality.",
  3164. cmStateEnums::INTERNAL);
  3165. }
  3166. bool cmake::GetDevWarningsAsErrors() const
  3167. {
  3168. return this->Messenger->GetDevWarningsAsErrors();
  3169. }
  3170. void cmake::SetDevWarningsAsErrors(bool b)
  3171. {
  3172. std::string value;
  3173. // equivalent to -Werror=dev
  3174. if (b) {
  3175. value = "FALSE";
  3176. }
  3177. // equivalent to -Wno-error=dev
  3178. else {
  3179. value = "TRUE";
  3180. }
  3181. this->AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_ERRORS", value.c_str(),
  3182. "Suppress errors that are meant for"
  3183. " the author of the CMakeLists.txt files.",
  3184. cmStateEnums::INTERNAL);
  3185. }
  3186. bool cmake::GetDeprecatedWarningsAsErrors() const
  3187. {
  3188. return this->Messenger->GetDeprecatedWarningsAsErrors();
  3189. }
  3190. void cmake::SetDeprecatedWarningsAsErrors(bool b)
  3191. {
  3192. std::string value;
  3193. // equivalent to -Werror=deprecated
  3194. if (b) {
  3195. value = "TRUE";
  3196. }
  3197. // equivalent to -Wno-error=deprecated
  3198. else {
  3199. value = "FALSE";
  3200. }
  3201. this->AddCacheEntry("CMAKE_ERROR_DEPRECATED", value.c_str(),
  3202. "Whether to issue deprecation errors for macros"
  3203. " and functions.",
  3204. cmStateEnums::INTERNAL);
  3205. }
  3206. #if !defined(CMAKE_BOOTSTRAP)
  3207. cmMakefileProfilingData& cmake::GetProfilingOutput()
  3208. {
  3209. return *(this->ProfilingOutput);
  3210. }
  3211. bool cmake::IsProfilingEnabled() const
  3212. {
  3213. return static_cast<bool>(this->ProfilingOutput);
  3214. }
  3215. #endif