cmake.cxx 136 KB

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