cmake.cxx 125 KB

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