cmake.cxx 96 KB

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