cmake.cxx 97 KB

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