cmake.cxx 115 KB

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