cmake.cxx 127 KB

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