cmake.cxx 96 KB

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