cmake.cxx 114 KB

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