cmake.cxx 124 KB

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