cmake.cxx 94 KB

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