cmake.cxx 136 KB

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