cmake.cxx 117 KB

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