cmake.cxx 89 KB

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