cmake.cxx 116 KB

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