cmake.cxx 134 KB

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