cmake.cxx 120 KB

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