cmake.cxx 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832
  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 std::string& stampName,
  103. bool verbose = true);
  104. static bool cmakeCheckStampList(const std::string& stampList,
  105. bool verbose = true);
  106. void cmWarnUnusedCliWarning(const std::string& variable, int /*unused*/,
  107. void* ctx, const char* /*unused*/,
  108. const cmMakefile* /*unused*/)
  109. {
  110. cmake* cm = reinterpret_cast<cmake*>(ctx);
  111. cm->MarkCliAsUsed(variable);
  112. }
  113. cmake::cmake(Role role, cmState::Mode mode)
  114. {
  115. this->Trace = false;
  116. this->TraceExpand = false;
  117. this->WarnUninitialized = false;
  118. this->WarnUnused = false;
  119. this->WarnUnusedCli = true;
  120. this->CheckSystemVars = false;
  121. this->DebugOutput = false;
  122. this->DebugTryCompile = false;
  123. this->ClearBuildSystem = false;
  124. this->FileComparison = new cmFileTimeComparison;
  125. this->State = new cmState;
  126. this->State->SetMode(mode);
  127. this->CurrentSnapshot = this->State->CreateBaseSnapshot();
  128. this->Messenger = new cmMessenger;
  129. #ifdef __APPLE__
  130. struct rlimit rlp;
  131. if (!getrlimit(RLIMIT_STACK, &rlp)) {
  132. if (rlp.rlim_cur != rlp.rlim_max) {
  133. rlp.rlim_cur = rlp.rlim_max;
  134. setrlimit(RLIMIT_STACK, &rlp);
  135. }
  136. }
  137. #endif
  138. this->GlobalGenerator = 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);
  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);
  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 std::string& 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.empty()) {
  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);
  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. this->IssueMessage(
  736. MessageType::WARNING,
  737. "No source or binary directory provided. Both will be assumed to be "
  738. "the same as the current working directory, but note that this "
  739. "warning will become a fatal error in future CMake releases.");
  740. }
  741. if (!haveSourceDir) {
  742. this->SetHomeDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  743. }
  744. if (!haveBinaryDir) {
  745. this->SetHomeOutputDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  746. }
  747. }
  748. void cmake::SetDirectoriesFromFile(const char* arg)
  749. {
  750. // Check if the argument refers to a CMakeCache.txt or
  751. // CMakeLists.txt file.
  752. std::string listPath;
  753. std::string cachePath;
  754. bool argIsFile = false;
  755. if (cmSystemTools::FileIsDirectory(arg)) {
  756. std::string path = cmSystemTools::CollapseFullPath(arg);
  757. cmSystemTools::ConvertToUnixSlashes(path);
  758. std::string cacheFile = path;
  759. cacheFile += "/CMakeCache.txt";
  760. std::string listFile = path;
  761. listFile += "/CMakeLists.txt";
  762. if (cmSystemTools::FileExists(cacheFile)) {
  763. cachePath = path;
  764. }
  765. if (cmSystemTools::FileExists(listFile)) {
  766. listPath = path;
  767. }
  768. } else if (cmSystemTools::FileExists(arg)) {
  769. argIsFile = true;
  770. std::string fullPath = cmSystemTools::CollapseFullPath(arg);
  771. std::string name = cmSystemTools::GetFilenameName(fullPath);
  772. name = cmSystemTools::LowerCase(name);
  773. if (name == "cmakecache.txt") {
  774. cachePath = cmSystemTools::GetFilenamePath(fullPath);
  775. } else if (name == "cmakelists.txt") {
  776. listPath = cmSystemTools::GetFilenamePath(fullPath);
  777. }
  778. } else {
  779. // Specified file or directory does not exist. Try to set things
  780. // up to produce a meaningful error message.
  781. std::string fullPath = cmSystemTools::CollapseFullPath(arg);
  782. std::string name = cmSystemTools::GetFilenameName(fullPath);
  783. name = cmSystemTools::LowerCase(name);
  784. if (name == "cmakecache.txt" || name == "cmakelists.txt") {
  785. argIsFile = true;
  786. listPath = cmSystemTools::GetFilenamePath(fullPath);
  787. } else {
  788. listPath = fullPath;
  789. }
  790. }
  791. // If there is a CMakeCache.txt file, use its settings.
  792. if (!cachePath.empty()) {
  793. if (this->LoadCache(cachePath)) {
  794. const char* existingValue =
  795. this->State->GetCacheEntryValue("CMAKE_HOME_DIRECTORY");
  796. if (existingValue) {
  797. this->SetHomeOutputDirectory(cachePath);
  798. this->SetHomeDirectory(existingValue);
  799. return;
  800. }
  801. }
  802. }
  803. // If there is a CMakeLists.txt file, use it as the source tree.
  804. if (!listPath.empty()) {
  805. this->SetHomeDirectory(listPath);
  806. if (argIsFile) {
  807. // Source CMakeLists.txt file given. It was probably dropped
  808. // onto the executable in a GUI. Default to an in-source build.
  809. this->SetHomeOutputDirectory(listPath);
  810. } else {
  811. // Source directory given on command line. Use current working
  812. // directory as build tree if -B hasn't been given already
  813. if (this->GetHomeOutputDirectory().empty()) {
  814. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  815. this->SetHomeOutputDirectory(cwd);
  816. }
  817. }
  818. return;
  819. }
  820. if (this->GetHomeDirectory().empty()) {
  821. // We didn't find a CMakeLists.txt and it wasn't specified
  822. // with -S. Assume it is the path to the source tree
  823. std::string full = cmSystemTools::CollapseFullPath(arg);
  824. this->SetHomeDirectory(full);
  825. }
  826. if (this->GetHomeOutputDirectory().empty()) {
  827. // We didn't find a CMakeCache.txt and it wasn't specified
  828. // with -B. Assume the current working directory as the build tree.
  829. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  830. this->SetHomeOutputDirectory(cwd);
  831. }
  832. }
  833. // at the end of this CMAKE_ROOT and CMAKE_COMMAND should be added to the
  834. // cache
  835. int cmake::AddCMakePaths()
  836. {
  837. // Save the value in the cache
  838. this->AddCacheEntry("CMAKE_COMMAND",
  839. cmSystemTools::GetCMakeCommand().c_str(),
  840. "Path to CMake executable.", cmStateEnums::INTERNAL);
  841. #ifdef CMAKE_BUILD_WITH_CMAKE
  842. this->AddCacheEntry(
  843. "CMAKE_CTEST_COMMAND", cmSystemTools::GetCTestCommand().c_str(),
  844. "Path to ctest program executable.", cmStateEnums::INTERNAL);
  845. this->AddCacheEntry(
  846. "CMAKE_CPACK_COMMAND", cmSystemTools::GetCPackCommand().c_str(),
  847. "Path to cpack program executable.", cmStateEnums::INTERNAL);
  848. #endif
  849. if (!cmSystemTools::FileExists(
  850. (cmSystemTools::GetCMakeRoot() + "/Modules/CMake.cmake"))) {
  851. // couldn't find modules
  852. cmSystemTools::Error(
  853. "Could not find CMAKE_ROOT !!!\n"
  854. "CMake has most likely not been installed correctly.\n"
  855. "Modules directory not found in\n",
  856. cmSystemTools::GetCMakeRoot().c_str());
  857. return 0;
  858. }
  859. this->AddCacheEntry("CMAKE_ROOT", cmSystemTools::GetCMakeRoot().c_str(),
  860. "Path to CMake installation.", cmStateEnums::INTERNAL);
  861. return 1;
  862. }
  863. void cmake::AddDefaultExtraGenerators()
  864. {
  865. #if defined(CMAKE_BUILD_WITH_CMAKE)
  866. this->ExtraGenerators.push_back(cmExtraCodeBlocksGenerator::GetFactory());
  867. this->ExtraGenerators.push_back(cmExtraCodeLiteGenerator::GetFactory());
  868. this->ExtraGenerators.push_back(cmExtraSublimeTextGenerator::GetFactory());
  869. this->ExtraGenerators.push_back(cmExtraKateGenerator::GetFactory());
  870. # ifdef CMAKE_USE_ECLIPSE
  871. this->ExtraGenerators.push_back(cmExtraEclipseCDT4Generator::GetFactory());
  872. # endif
  873. #endif
  874. }
  875. void cmake::GetRegisteredGenerators(std::vector<GeneratorInfo>& generators,
  876. bool includeNamesWithPlatform) const
  877. {
  878. for (cmGlobalGeneratorFactory* gen : this->Generators) {
  879. std::vector<std::string> names = gen->GetGeneratorNames();
  880. if (includeNamesWithPlatform) {
  881. std::vector<std::string> namesWithPlatform =
  882. gen->GetGeneratorNamesWithPlatform();
  883. names.insert(names.end(), namesWithPlatform.begin(),
  884. namesWithPlatform.end());
  885. }
  886. for (std::string const& name : names) {
  887. GeneratorInfo info;
  888. info.supportsToolset = gen->SupportsToolset();
  889. info.supportsPlatform = gen->SupportsPlatform();
  890. info.supportedPlatforms = gen->GetKnownPlatforms();
  891. info.defaultPlatform = gen->GetDefaultPlatformName();
  892. info.name = name;
  893. info.baseName = name;
  894. info.isAlias = false;
  895. generators.push_back(std::move(info));
  896. }
  897. }
  898. for (cmExternalMakefileProjectGeneratorFactory* eg : this->ExtraGenerators) {
  899. const std::vector<std::string> genList =
  900. eg->GetSupportedGlobalGenerators();
  901. for (std::string const& gen : genList) {
  902. GeneratorInfo info;
  903. info.name = cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  904. gen, eg->GetName());
  905. info.baseName = gen;
  906. info.extraName = eg->GetName();
  907. info.supportsPlatform = false;
  908. info.supportsToolset = false;
  909. info.isAlias = false;
  910. generators.push_back(std::move(info));
  911. }
  912. for (std::string const& a : eg->Aliases) {
  913. GeneratorInfo info;
  914. info.name = a;
  915. if (!genList.empty()) {
  916. info.baseName = genList.at(0);
  917. }
  918. info.extraName = eg->GetName();
  919. info.supportsPlatform = false;
  920. info.supportsToolset = false;
  921. info.isAlias = true;
  922. generators.push_back(std::move(info));
  923. }
  924. }
  925. }
  926. static std::pair<cmExternalMakefileProjectGenerator*, std::string>
  927. createExtraGenerator(
  928. const std::vector<cmExternalMakefileProjectGeneratorFactory*>& in,
  929. const std::string& name)
  930. {
  931. for (cmExternalMakefileProjectGeneratorFactory* i : in) {
  932. const std::vector<std::string> generators =
  933. i->GetSupportedGlobalGenerators();
  934. if (i->GetName() == name) { // Match aliases
  935. return std::make_pair(i->CreateExternalMakefileProjectGenerator(),
  936. generators.at(0));
  937. }
  938. for (std::string const& g : generators) {
  939. const std::string fullName =
  940. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  941. g, i->GetName());
  942. if (fullName == name) {
  943. return std::make_pair(i->CreateExternalMakefileProjectGenerator(), g);
  944. }
  945. }
  946. }
  947. return std::make_pair(
  948. static_cast<cmExternalMakefileProjectGenerator*>(nullptr), name);
  949. }
  950. cmGlobalGenerator* cmake::CreateGlobalGenerator(const std::string& gname)
  951. {
  952. std::pair<cmExternalMakefileProjectGenerator*, std::string> extra =
  953. createExtraGenerator(this->ExtraGenerators, gname);
  954. cmExternalMakefileProjectGenerator* extraGenerator = extra.first;
  955. const std::string name = extra.second;
  956. cmGlobalGenerator* generator = nullptr;
  957. for (cmGlobalGeneratorFactory* g : this->Generators) {
  958. generator = g->CreateGlobalGenerator(name, this);
  959. if (generator) {
  960. break;
  961. }
  962. }
  963. if (generator) {
  964. generator->SetExternalMakefileProjectGenerator(extraGenerator);
  965. } else {
  966. delete extraGenerator;
  967. }
  968. return generator;
  969. }
  970. void cmake::SetHomeDirectory(const std::string& dir)
  971. {
  972. this->State->SetSourceDirectory(dir);
  973. if (this->CurrentSnapshot.IsValid()) {
  974. this->CurrentSnapshot.SetDefinition("CMAKE_SOURCE_DIR", dir);
  975. }
  976. }
  977. std::string const& cmake::GetHomeDirectory() const
  978. {
  979. return this->State->GetSourceDirectory();
  980. }
  981. void cmake::SetHomeOutputDirectory(const std::string& dir)
  982. {
  983. this->State->SetBinaryDirectory(dir);
  984. if (this->CurrentSnapshot.IsValid()) {
  985. this->CurrentSnapshot.SetDefinition("CMAKE_BINARY_DIR", dir);
  986. }
  987. }
  988. std::string const& cmake::GetHomeOutputDirectory() const
  989. {
  990. return this->State->GetBinaryDirectory();
  991. }
  992. std::string cmake::FindCacheFile(const std::string& binaryDir)
  993. {
  994. std::string cachePath = binaryDir;
  995. cmSystemTools::ConvertToUnixSlashes(cachePath);
  996. std::string cacheFile = cachePath;
  997. cacheFile += "/CMakeCache.txt";
  998. if (!cmSystemTools::FileExists(cacheFile)) {
  999. // search in parent directories for cache
  1000. std::string cmakeFiles = cachePath;
  1001. cmakeFiles += "/CMakeFiles";
  1002. if (cmSystemTools::FileExists(cmakeFiles)) {
  1003. std::string cachePathFound =
  1004. cmSystemTools::FileExistsInParentDirectories("CMakeCache.txt",
  1005. cachePath, "/");
  1006. if (!cachePathFound.empty()) {
  1007. cachePath = cmSystemTools::GetFilenamePath(cachePathFound);
  1008. }
  1009. }
  1010. }
  1011. return cachePath;
  1012. }
  1013. void cmake::SetGlobalGenerator(cmGlobalGenerator* gg)
  1014. {
  1015. if (!gg) {
  1016. cmSystemTools::Error("Error SetGlobalGenerator called with null");
  1017. return;
  1018. }
  1019. // delete the old generator
  1020. if (this->GlobalGenerator) {
  1021. delete this->GlobalGenerator;
  1022. // restore the original environment variables CXX and CC
  1023. // Restore CC
  1024. std::string env = "CC=";
  1025. if (!this->CCEnvironment.empty()) {
  1026. env += this->CCEnvironment;
  1027. }
  1028. cmSystemTools::PutEnv(env);
  1029. env = "CXX=";
  1030. if (!this->CXXEnvironment.empty()) {
  1031. env += this->CXXEnvironment;
  1032. }
  1033. cmSystemTools::PutEnv(env);
  1034. }
  1035. // set the new
  1036. this->GlobalGenerator = gg;
  1037. // set the global flag for unix style paths on cmSystemTools as soon as
  1038. // the generator is set. This allows gmake to be used on windows.
  1039. cmSystemTools::SetForceUnixPaths(this->GlobalGenerator->GetForceUnixPaths());
  1040. // Save the environment variables CXX and CC
  1041. if (!cmSystemTools::GetEnv("CXX", this->CXXEnvironment)) {
  1042. this->CXXEnvironment.clear();
  1043. }
  1044. if (!cmSystemTools::GetEnv("CC", this->CCEnvironment)) {
  1045. this->CCEnvironment.clear();
  1046. }
  1047. }
  1048. int cmake::DoPreConfigureChecks()
  1049. {
  1050. // Make sure the Source directory contains a CMakeLists.txt file.
  1051. std::string srcList = this->GetHomeDirectory();
  1052. srcList += "/CMakeLists.txt";
  1053. if (!cmSystemTools::FileExists(srcList)) {
  1054. std::ostringstream err;
  1055. if (cmSystemTools::FileIsDirectory(this->GetHomeDirectory())) {
  1056. err << "The source directory \"" << this->GetHomeDirectory()
  1057. << "\" does not appear to contain CMakeLists.txt.\n";
  1058. } else if (cmSystemTools::FileExists(this->GetHomeDirectory())) {
  1059. err << "The source directory \"" << this->GetHomeDirectory()
  1060. << "\" is a file, not a directory.\n";
  1061. } else {
  1062. err << "The source directory \"" << this->GetHomeDirectory()
  1063. << "\" does not exist.\n";
  1064. }
  1065. err << "Specify --help for usage, or press the help button on the CMake "
  1066. "GUI.";
  1067. cmSystemTools::Error(err.str());
  1068. return -2;
  1069. }
  1070. // do a sanity check on some values
  1071. if (this->State->GetInitializedCacheValue("CMAKE_HOME_DIRECTORY")) {
  1072. std::string cacheStart =
  1073. *this->State->GetInitializedCacheValue("CMAKE_HOME_DIRECTORY");
  1074. cacheStart += "/CMakeLists.txt";
  1075. std::string currentStart = this->GetHomeDirectory();
  1076. currentStart += "/CMakeLists.txt";
  1077. if (!cmSystemTools::SameFile(cacheStart, currentStart)) {
  1078. std::string message = "The source \"";
  1079. message += currentStart;
  1080. message += "\" does not match the source \"";
  1081. message += cacheStart;
  1082. message += "\" used to generate cache. ";
  1083. message += "Re-run cmake with a different source directory.";
  1084. cmSystemTools::Error(message);
  1085. return -2;
  1086. }
  1087. } else {
  1088. return 0;
  1089. }
  1090. return 1;
  1091. }
  1092. struct SaveCacheEntry
  1093. {
  1094. std::string key;
  1095. std::string value;
  1096. std::string help;
  1097. cmStateEnums::CacheEntryType type;
  1098. };
  1099. int cmake::HandleDeleteCacheVariables(const std::string& var)
  1100. {
  1101. std::vector<std::string> argsSplit;
  1102. cmSystemTools::ExpandListArgument(std::string(var), argsSplit, true);
  1103. // erase the property to avoid infinite recursion
  1104. this->State->SetGlobalProperty("__CMAKE_DELETE_CACHE_CHANGE_VARS_", "");
  1105. if (this->State->GetIsInTryCompile()) {
  1106. return 0;
  1107. }
  1108. std::vector<SaveCacheEntry> saved;
  1109. std::ostringstream warning;
  1110. /* clang-format off */
  1111. warning
  1112. << "You have changed variables that require your cache to be deleted.\n"
  1113. << "Configure will be re-run and you may have to reset some variables.\n"
  1114. << "The following variables have changed:\n";
  1115. /* clang-format on */
  1116. for (std::vector<std::string>::iterator i = argsSplit.begin();
  1117. i != argsSplit.end(); ++i) {
  1118. SaveCacheEntry save;
  1119. save.key = *i;
  1120. warning << *i << "= ";
  1121. i++;
  1122. save.value = *i;
  1123. warning << *i << "\n";
  1124. const char* existingValue = this->State->GetCacheEntryValue(save.key);
  1125. if (existingValue) {
  1126. save.type = this->State->GetCacheEntryType(save.key);
  1127. if (const char* help =
  1128. this->State->GetCacheEntryProperty(save.key, "HELPSTRING")) {
  1129. save.help = help;
  1130. }
  1131. }
  1132. saved.push_back(std::move(save));
  1133. }
  1134. // remove the cache
  1135. this->DeleteCache(this->GetHomeOutputDirectory());
  1136. // load the empty cache
  1137. this->LoadCache();
  1138. // restore the changed compilers
  1139. for (SaveCacheEntry const& i : saved) {
  1140. this->AddCacheEntry(i.key, i.value.c_str(), i.help.c_str(), i.type);
  1141. }
  1142. cmSystemTools::Message(warning.str());
  1143. // avoid reconfigure if there were errors
  1144. if (!cmSystemTools::GetErrorOccuredFlag()) {
  1145. // re-run configure
  1146. return this->Configure();
  1147. }
  1148. return 0;
  1149. }
  1150. int cmake::Configure()
  1151. {
  1152. DiagLevel diagLevel;
  1153. if (this->DiagLevels.count("deprecated") == 1) {
  1154. diagLevel = this->DiagLevels["deprecated"];
  1155. if (diagLevel == DIAG_IGNORE) {
  1156. this->SetSuppressDeprecatedWarnings(true);
  1157. this->SetDeprecatedWarningsAsErrors(false);
  1158. } else if (diagLevel == DIAG_WARN) {
  1159. this->SetSuppressDeprecatedWarnings(false);
  1160. this->SetDeprecatedWarningsAsErrors(false);
  1161. } else if (diagLevel == DIAG_ERROR) {
  1162. this->SetSuppressDeprecatedWarnings(false);
  1163. this->SetDeprecatedWarningsAsErrors(true);
  1164. }
  1165. }
  1166. if (this->DiagLevels.count("dev") == 1) {
  1167. bool setDeprecatedVariables = false;
  1168. const char* cachedWarnDeprecated =
  1169. this->State->GetCacheEntryValue("CMAKE_WARN_DEPRECATED");
  1170. const char* cachedErrorDeprecated =
  1171. this->State->GetCacheEntryValue("CMAKE_ERROR_DEPRECATED");
  1172. // don't overwrite deprecated warning setting from a previous invocation
  1173. if (!cachedWarnDeprecated && !cachedErrorDeprecated) {
  1174. setDeprecatedVariables = true;
  1175. }
  1176. diagLevel = this->DiagLevels["dev"];
  1177. if (diagLevel == DIAG_IGNORE) {
  1178. this->SetSuppressDevWarnings(true);
  1179. this->SetDevWarningsAsErrors(false);
  1180. if (setDeprecatedVariables) {
  1181. this->SetSuppressDeprecatedWarnings(true);
  1182. this->SetDeprecatedWarningsAsErrors(false);
  1183. }
  1184. } else if (diagLevel == DIAG_WARN) {
  1185. this->SetSuppressDevWarnings(false);
  1186. this->SetDevWarningsAsErrors(false);
  1187. if (setDeprecatedVariables) {
  1188. this->SetSuppressDeprecatedWarnings(false);
  1189. this->SetDeprecatedWarningsAsErrors(false);
  1190. }
  1191. } else if (diagLevel == DIAG_ERROR) {
  1192. this->SetSuppressDevWarnings(false);
  1193. this->SetDevWarningsAsErrors(true);
  1194. if (setDeprecatedVariables) {
  1195. this->SetSuppressDeprecatedWarnings(false);
  1196. this->SetDeprecatedWarningsAsErrors(true);
  1197. }
  1198. }
  1199. }
  1200. // Cache variables may have already been set by a previous invocation,
  1201. // so we cannot rely on command line options alone. Always ensure our
  1202. // messenger is in sync with the cache.
  1203. const char* value = this->State->GetCacheEntryValue("CMAKE_WARN_DEPRECATED");
  1204. this->Messenger->SetSuppressDeprecatedWarnings(value &&
  1205. cmSystemTools::IsOff(value));
  1206. value = this->State->GetCacheEntryValue("CMAKE_ERROR_DEPRECATED");
  1207. this->Messenger->SetDeprecatedWarningsAsErrors(cmSystemTools::IsOn(value));
  1208. value = this->State->GetCacheEntryValue("CMAKE_SUPPRESS_DEVELOPER_WARNINGS");
  1209. this->Messenger->SetSuppressDevWarnings(cmSystemTools::IsOn(value));
  1210. value = this->State->GetCacheEntryValue("CMAKE_SUPPRESS_DEVELOPER_ERRORS");
  1211. this->Messenger->SetDevWarningsAsErrors(value &&
  1212. cmSystemTools::IsOff(value));
  1213. int ret = this->ActualConfigure();
  1214. const char* delCacheVars =
  1215. this->State->GetGlobalProperty("__CMAKE_DELETE_CACHE_CHANGE_VARS_");
  1216. if (delCacheVars && delCacheVars[0] != 0) {
  1217. return this->HandleDeleteCacheVariables(delCacheVars);
  1218. }
  1219. return ret;
  1220. }
  1221. int cmake::ActualConfigure()
  1222. {
  1223. // Construct right now our path conversion table before it's too late:
  1224. this->UpdateConversionPathTable();
  1225. this->CleanupCommandsAndMacros();
  1226. int res = this->DoPreConfigureChecks();
  1227. if (res < 0) {
  1228. return -2;
  1229. }
  1230. if (!res) {
  1231. this->AddCacheEntry(
  1232. "CMAKE_HOME_DIRECTORY", this->GetHomeDirectory().c_str(),
  1233. "Source directory with the top level CMakeLists.txt file for this "
  1234. "project",
  1235. cmStateEnums::INTERNAL);
  1236. }
  1237. // no generator specified on the command line
  1238. if (!this->GlobalGenerator) {
  1239. const std::string* genName =
  1240. this->State->GetInitializedCacheValue("CMAKE_GENERATOR");
  1241. const std::string* extraGenName =
  1242. this->State->GetInitializedCacheValue("CMAKE_EXTRA_GENERATOR");
  1243. if (genName) {
  1244. std::string fullName =
  1245. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  1246. *genName, extraGenName ? *extraGenName : "");
  1247. this->GlobalGenerator = this->CreateGlobalGenerator(fullName);
  1248. }
  1249. if (this->GlobalGenerator) {
  1250. // set the global flag for unix style paths on cmSystemTools as
  1251. // soon as the generator is set. This allows gmake to be used
  1252. // on windows.
  1253. cmSystemTools::SetForceUnixPaths(
  1254. this->GlobalGenerator->GetForceUnixPaths());
  1255. } else {
  1256. this->CreateDefaultGlobalGenerator();
  1257. }
  1258. if (!this->GlobalGenerator) {
  1259. cmSystemTools::Error("Could not create generator");
  1260. return -1;
  1261. }
  1262. }
  1263. const std::string* genName =
  1264. this->State->GetInitializedCacheValue("CMAKE_GENERATOR");
  1265. if (genName) {
  1266. if (!this->GlobalGenerator->MatchesGeneratorName(*genName)) {
  1267. std::string message = "Error: generator : ";
  1268. message += this->GlobalGenerator->GetName();
  1269. message += "\nDoes not match the generator used previously: ";
  1270. message += *genName;
  1271. message += "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1272. "directory or choose a different binary directory.";
  1273. cmSystemTools::Error(message);
  1274. return -2;
  1275. }
  1276. }
  1277. if (!this->State->GetInitializedCacheValue("CMAKE_GENERATOR")) {
  1278. this->AddCacheEntry("CMAKE_GENERATOR",
  1279. this->GlobalGenerator->GetName().c_str(),
  1280. "Name of generator.", cmStateEnums::INTERNAL);
  1281. this->AddCacheEntry("CMAKE_EXTRA_GENERATOR",
  1282. this->GlobalGenerator->GetExtraGeneratorName().c_str(),
  1283. "Name of external makefile project generator.",
  1284. cmStateEnums::INTERNAL);
  1285. }
  1286. if (const std::string* instance =
  1287. this->State->GetInitializedCacheValue("CMAKE_GENERATOR_INSTANCE")) {
  1288. if (!this->GeneratorInstance.empty() &&
  1289. this->GeneratorInstance != *instance) {
  1290. std::string message = "Error: generator instance: ";
  1291. message += this->GeneratorInstance;
  1292. message += "\nDoes not match the instance used previously: ";
  1293. message += *instance;
  1294. message += "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1295. "directory or choose a different binary directory.";
  1296. cmSystemTools::Error(message);
  1297. return -2;
  1298. }
  1299. } else {
  1300. this->AddCacheEntry(
  1301. "CMAKE_GENERATOR_INSTANCE", this->GeneratorInstance.c_str(),
  1302. "Generator instance identifier.", cmStateEnums::INTERNAL);
  1303. }
  1304. if (const std::string* platformName =
  1305. this->State->GetInitializedCacheValue("CMAKE_GENERATOR_PLATFORM")) {
  1306. if (!this->GeneratorPlatform.empty() &&
  1307. this->GeneratorPlatform != *platformName) {
  1308. std::string message = "Error: generator platform: ";
  1309. message += this->GeneratorPlatform;
  1310. message += "\nDoes not match the platform used previously: ";
  1311. message += *platformName;
  1312. message += "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1313. "directory or choose a different binary directory.";
  1314. cmSystemTools::Error(message);
  1315. return -2;
  1316. }
  1317. } else {
  1318. this->AddCacheEntry("CMAKE_GENERATOR_PLATFORM",
  1319. this->GeneratorPlatform.c_str(),
  1320. "Name of generator platform.", cmStateEnums::INTERNAL);
  1321. }
  1322. if (const std::string* tsName =
  1323. this->State->GetInitializedCacheValue("CMAKE_GENERATOR_TOOLSET")) {
  1324. if (!this->GeneratorToolset.empty() && this->GeneratorToolset != *tsName) {
  1325. std::string message = "Error: generator toolset: ";
  1326. message += this->GeneratorToolset;
  1327. message += "\nDoes not match the toolset used previously: ";
  1328. message += *tsName;
  1329. message += "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1330. "directory or choose a different binary directory.";
  1331. cmSystemTools::Error(message);
  1332. return -2;
  1333. }
  1334. } else {
  1335. this->AddCacheEntry("CMAKE_GENERATOR_TOOLSET",
  1336. this->GeneratorToolset.c_str(),
  1337. "Name of generator toolset.", cmStateEnums::INTERNAL);
  1338. }
  1339. // reset any system configuration information, except for when we are
  1340. // InTryCompile. With TryCompile the system info is taken from the parent's
  1341. // info to save time
  1342. if (!this->State->GetIsInTryCompile()) {
  1343. this->GlobalGenerator->ClearEnabledLanguages();
  1344. this->TruncateOutputLog("CMakeOutput.log");
  1345. this->TruncateOutputLog("CMakeError.log");
  1346. }
  1347. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1348. this->FileAPI = cm::make_unique<cmFileAPI>(this);
  1349. this->FileAPI->ReadQueries();
  1350. #endif
  1351. // actually do the configure
  1352. this->GlobalGenerator->Configure();
  1353. // Before saving the cache
  1354. // if the project did not define one of the entries below, add them now
  1355. // so users can edit the values in the cache:
  1356. // We used to always present LIBRARY_OUTPUT_PATH and
  1357. // EXECUTABLE_OUTPUT_PATH. They are now documented as old-style and
  1358. // should no longer be used. Therefore we present them only if the
  1359. // project requires compatibility with CMake 2.4. We detect this
  1360. // here by looking for the old CMAKE_BACKWARDS_COMPATIBILITY
  1361. // variable created when CMP0001 is not set to NEW.
  1362. if (this->State->GetInitializedCacheValue("CMAKE_BACKWARDS_COMPATIBILITY")) {
  1363. if (!this->State->GetInitializedCacheValue("LIBRARY_OUTPUT_PATH")) {
  1364. this->AddCacheEntry(
  1365. "LIBRARY_OUTPUT_PATH", "",
  1366. "Single output directory for building all libraries.",
  1367. cmStateEnums::PATH);
  1368. }
  1369. if (!this->State->GetInitializedCacheValue("EXECUTABLE_OUTPUT_PATH")) {
  1370. this->AddCacheEntry(
  1371. "EXECUTABLE_OUTPUT_PATH", "",
  1372. "Single output directory for building all executables.",
  1373. cmStateEnums::PATH);
  1374. }
  1375. }
  1376. cmMakefile* mf = this->GlobalGenerator->GetMakefiles()[0];
  1377. if (mf->IsOn("CTEST_USE_LAUNCHERS") &&
  1378. !this->State->GetGlobalProperty("RULE_LAUNCH_COMPILE")) {
  1379. cmSystemTools::Error(
  1380. "CTEST_USE_LAUNCHERS is enabled, but the "
  1381. "RULE_LAUNCH_COMPILE global property is not defined.\n"
  1382. "Did you forget to include(CTest) in the toplevel "
  1383. "CMakeLists.txt ?");
  1384. }
  1385. this->State->SaveVerificationScript(this->GetHomeOutputDirectory());
  1386. this->SaveCache(this->GetHomeOutputDirectory());
  1387. if (cmSystemTools::GetErrorOccuredFlag()) {
  1388. return -1;
  1389. }
  1390. return 0;
  1391. }
  1392. std::unique_ptr<cmGlobalGenerator> cmake::EvaluateDefaultGlobalGenerator()
  1393. {
  1394. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(CMAKE_BOOT_MINGW)
  1395. std::string found;
  1396. // Try to find the newest VS installed on the computer and
  1397. // use that as a default if -G is not specified
  1398. const std::string vsregBase = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\";
  1399. static const char* const vsVariants[] = {
  1400. /* clang-format needs this comment to break after the opening brace */
  1401. "VisualStudio\\", "VCExpress\\", "WDExpress\\"
  1402. };
  1403. struct VSVersionedGenerator
  1404. {
  1405. const char* MSVersion;
  1406. const char* GeneratorName;
  1407. };
  1408. static VSVersionedGenerator const vsGenerators[] = {
  1409. { "14.0", "Visual Studio 14 2015" }, //
  1410. { "12.0", "Visual Studio 12 2013" }, //
  1411. { "11.0", "Visual Studio 11 2012" }, //
  1412. { "10.0", "Visual Studio 10 2010" }, //
  1413. { "9.0", "Visual Studio 9 2008" }
  1414. };
  1415. static const char* const vsEntries[] = {
  1416. "\\Setup\\VC;ProductDir", //
  1417. ";InstallDir" //
  1418. };
  1419. if (cmVSSetupAPIHelper(16).IsVSInstalled()) {
  1420. found = "Visual Studio 16 2019";
  1421. } else if (cmVSSetupAPIHelper(15).IsVSInstalled()) {
  1422. found = "Visual Studio 15 2017";
  1423. } else {
  1424. for (VSVersionedGenerator const* g = cm::cbegin(vsGenerators);
  1425. found.empty() && g != cm::cend(vsGenerators); ++g) {
  1426. for (const char* const* v = cm::cbegin(vsVariants);
  1427. found.empty() && v != cm::cend(vsVariants); ++v) {
  1428. for (const char* const* e = cm::cbegin(vsEntries);
  1429. found.empty() && e != cm::cend(vsEntries); ++e) {
  1430. std::string const reg = vsregBase + *v + g->MSVersion + *e;
  1431. std::string dir;
  1432. if (cmSystemTools::ReadRegistryValue(reg, dir,
  1433. cmSystemTools::KeyWOW64_32) &&
  1434. cmSystemTools::PathExists(dir)) {
  1435. found = g->GeneratorName;
  1436. }
  1437. }
  1438. }
  1439. }
  1440. }
  1441. cmGlobalGenerator* gen = this->CreateGlobalGenerator(found);
  1442. if (!gen) {
  1443. gen = new cmGlobalNMakeMakefileGenerator(this);
  1444. }
  1445. return std::unique_ptr<cmGlobalGenerator>(gen);
  1446. #else
  1447. return cm::make_unique<cmGlobalUnixMakefileGenerator3>(this);
  1448. #endif
  1449. }
  1450. void cmake::CreateDefaultGlobalGenerator()
  1451. {
  1452. auto gen = this->EvaluateDefaultGlobalGenerator();
  1453. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(CMAKE_BOOT_MINGW)
  1454. // This print could be unified for all platforms
  1455. std::cout << "-- Building for: " << gen->GetName() << "\n";
  1456. #endif
  1457. this->SetGlobalGenerator(gen.release());
  1458. }
  1459. void cmake::PreLoadCMakeFiles()
  1460. {
  1461. std::vector<std::string> args;
  1462. std::string pre_load = this->GetHomeDirectory();
  1463. if (!pre_load.empty()) {
  1464. pre_load += "/PreLoad.cmake";
  1465. if (cmSystemTools::FileExists(pre_load)) {
  1466. this->ReadListFile(args, pre_load);
  1467. }
  1468. }
  1469. pre_load = this->GetHomeOutputDirectory();
  1470. if (!pre_load.empty()) {
  1471. pre_load += "/PreLoad.cmake";
  1472. if (cmSystemTools::FileExists(pre_load)) {
  1473. this->ReadListFile(args, pre_load);
  1474. }
  1475. }
  1476. }
  1477. // handle a command line invocation
  1478. int cmake::Run(const std::vector<std::string>& args, bool noconfigure)
  1479. {
  1480. // Process the arguments
  1481. this->SetArgs(args);
  1482. if (cmSystemTools::GetErrorOccuredFlag()) {
  1483. return -1;
  1484. }
  1485. // If we are given a stamp list file check if it is really out of date.
  1486. if (!this->CheckStampList.empty() &&
  1487. cmakeCheckStampList(this->CheckStampList)) {
  1488. return 0;
  1489. }
  1490. // If we are given a stamp file check if it is really out of date.
  1491. if (!this->CheckStampFile.empty() &&
  1492. cmakeCheckStampFile(this->CheckStampFile)) {
  1493. return 0;
  1494. }
  1495. if (this->GetWorkingMode() == NORMAL_MODE) {
  1496. // load the cache
  1497. if (this->LoadCache() < 0) {
  1498. cmSystemTools::Error("Error executing cmake::LoadCache(). Aborting.\n");
  1499. return -1;
  1500. }
  1501. } else {
  1502. this->AddCMakePaths();
  1503. }
  1504. // Add any cache args
  1505. if (!this->SetCacheArgs(args)) {
  1506. cmSystemTools::Error("Problem processing arguments. Aborting.\n");
  1507. return -1;
  1508. }
  1509. // In script mode we terminate after running the script.
  1510. if (this->GetWorkingMode() != NORMAL_MODE) {
  1511. if (cmSystemTools::GetErrorOccuredFlag()) {
  1512. return -1;
  1513. }
  1514. return 0;
  1515. }
  1516. // If MAKEFLAGS are given in the environment, remove the environment
  1517. // variable. This will prevent try-compile from succeeding when it
  1518. // should fail (if "-i" is an option). We cannot simply test
  1519. // whether "-i" is given and remove it because some make programs
  1520. // encode the MAKEFLAGS variable in a strange way.
  1521. if (cmSystemTools::HasEnv("MAKEFLAGS")) {
  1522. cmSystemTools::PutEnv("MAKEFLAGS=");
  1523. }
  1524. this->PreLoadCMakeFiles();
  1525. if (noconfigure) {
  1526. return 0;
  1527. }
  1528. // now run the global generate
  1529. // Check the state of the build system to see if we need to regenerate.
  1530. if (!this->CheckBuildSystem()) {
  1531. return 0;
  1532. }
  1533. int ret = this->Configure();
  1534. if (ret) {
  1535. #if defined(CMAKE_HAVE_VS_GENERATORS)
  1536. if (!this->VSSolutionFile.empty() && this->GlobalGenerator) {
  1537. // CMake is running to regenerate a Visual Studio build tree
  1538. // during a build from the VS IDE. The build files cannot be
  1539. // regenerated, so we should stop the build.
  1540. cmSystemTools::Message("CMake Configure step failed. "
  1541. "Build files cannot be regenerated correctly. "
  1542. "Attempting to stop IDE build.");
  1543. cmGlobalVisualStudioGenerator* gg =
  1544. static_cast<cmGlobalVisualStudioGenerator*>(this->GlobalGenerator);
  1545. gg->CallVisualStudioMacro(cmGlobalVisualStudioGenerator::MacroStop,
  1546. this->VSSolutionFile.c_str());
  1547. }
  1548. #endif
  1549. return ret;
  1550. }
  1551. ret = this->Generate();
  1552. std::string message = "Build files have been written to: ";
  1553. message += this->GetHomeOutputDirectory();
  1554. this->UpdateProgress(message, -1);
  1555. return ret;
  1556. }
  1557. int cmake::Generate()
  1558. {
  1559. if (!this->GlobalGenerator) {
  1560. return -1;
  1561. }
  1562. if (!this->GlobalGenerator->Compute()) {
  1563. return -1;
  1564. }
  1565. this->GlobalGenerator->Generate();
  1566. if (!this->GraphVizFile.empty()) {
  1567. std::cout << "Generate graphviz: " << this->GraphVizFile << std::endl;
  1568. this->GenerateGraphViz(this->GraphVizFile.c_str());
  1569. }
  1570. if (this->WarnUnusedCli) {
  1571. this->RunCheckForUnusedVariables();
  1572. }
  1573. if (cmSystemTools::GetErrorOccuredFlag()) {
  1574. return -1;
  1575. }
  1576. // Save the cache again after a successful Generate so that any internal
  1577. // variables created during Generate are saved. (Specifically target GUIDs
  1578. // for the Visual Studio and Xcode generators.)
  1579. this->SaveCache(this->GetHomeOutputDirectory());
  1580. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1581. this->FileAPI->WriteReplies();
  1582. #endif
  1583. return 0;
  1584. }
  1585. void cmake::AddCacheEntry(const std::string& key, const char* value,
  1586. const char* helpString, int type)
  1587. {
  1588. this->State->AddCacheEntry(key, value, helpString,
  1589. cmStateEnums::CacheEntryType(type));
  1590. this->UnwatchUnusedCli(key);
  1591. if (key == "CMAKE_WARN_DEPRECATED") {
  1592. this->Messenger->SetSuppressDeprecatedWarnings(
  1593. value && cmSystemTools::IsOff(value));
  1594. } else if (key == "CMAKE_ERROR_DEPRECATED") {
  1595. this->Messenger->SetDeprecatedWarningsAsErrors(cmSystemTools::IsOn(value));
  1596. } else if (key == "CMAKE_SUPPRESS_DEVELOPER_WARNINGS") {
  1597. this->Messenger->SetSuppressDevWarnings(cmSystemTools::IsOn(value));
  1598. } else if (key == "CMAKE_SUPPRESS_DEVELOPER_ERRORS") {
  1599. this->Messenger->SetDevWarningsAsErrors(value &&
  1600. cmSystemTools::IsOff(value));
  1601. }
  1602. }
  1603. bool cmake::DoWriteGlobVerifyTarget() const
  1604. {
  1605. return this->State->DoWriteGlobVerifyTarget();
  1606. }
  1607. std::string const& cmake::GetGlobVerifyScript() const
  1608. {
  1609. return this->State->GetGlobVerifyScript();
  1610. }
  1611. std::string const& cmake::GetGlobVerifyStamp() const
  1612. {
  1613. return this->State->GetGlobVerifyStamp();
  1614. }
  1615. void cmake::AddGlobCacheEntry(bool recurse, bool listDirectories,
  1616. bool followSymlinks, const std::string& relative,
  1617. const std::string& expression,
  1618. const std::vector<std::string>& files,
  1619. const std::string& variable,
  1620. cmListFileBacktrace const& backtrace)
  1621. {
  1622. this->State->AddGlobCacheEntry(recurse, listDirectories, followSymlinks,
  1623. relative, expression, files, variable,
  1624. backtrace);
  1625. }
  1626. std::string cmake::StripExtension(const std::string& file) const
  1627. {
  1628. auto dotpos = file.rfind('.');
  1629. if (dotpos != std::string::npos) {
  1630. auto ext = file.substr(dotpos + 1);
  1631. #if defined(_WIN32) || defined(__APPLE__)
  1632. ext = cmSystemTools::LowerCase(ext);
  1633. #endif
  1634. if (this->IsSourceExtension(ext) || this->IsHeaderExtension(ext)) {
  1635. return file.substr(0, dotpos);
  1636. }
  1637. }
  1638. return file;
  1639. }
  1640. const char* cmake::GetCacheDefinition(const std::string& name) const
  1641. {
  1642. const std::string* p = this->State->GetInitializedCacheValue(name);
  1643. return p ? p->c_str() : nullptr;
  1644. }
  1645. void cmake::AddScriptingCommands()
  1646. {
  1647. GetScriptingCommands(this->State);
  1648. }
  1649. void cmake::AddProjectCommands()
  1650. {
  1651. GetProjectCommands(this->State);
  1652. }
  1653. void cmake::AddDefaultGenerators()
  1654. {
  1655. #if defined(_WIN32) && !defined(__CYGWIN__)
  1656. # if !defined(CMAKE_BOOT_MINGW)
  1657. this->Generators.push_back(
  1658. cmGlobalVisualStudioVersionedGenerator::NewFactory16());
  1659. this->Generators.push_back(
  1660. cmGlobalVisualStudioVersionedGenerator::NewFactory15());
  1661. this->Generators.push_back(cmGlobalVisualStudio14Generator::NewFactory());
  1662. this->Generators.push_back(cmGlobalVisualStudio12Generator::NewFactory());
  1663. this->Generators.push_back(cmGlobalVisualStudio11Generator::NewFactory());
  1664. this->Generators.push_back(cmGlobalVisualStudio10Generator::NewFactory());
  1665. this->Generators.push_back(cmGlobalVisualStudio9Generator::NewFactory());
  1666. this->Generators.push_back(cmGlobalBorlandMakefileGenerator::NewFactory());
  1667. this->Generators.push_back(cmGlobalNMakeMakefileGenerator::NewFactory());
  1668. this->Generators.push_back(cmGlobalJOMMakefileGenerator::NewFactory());
  1669. this->Generators.push_back(cmGlobalGhsMultiGenerator::NewFactory());
  1670. # endif
  1671. this->Generators.push_back(cmGlobalMSYSMakefileGenerator::NewFactory());
  1672. this->Generators.push_back(cmGlobalMinGWMakefileGenerator::NewFactory());
  1673. #endif
  1674. this->Generators.push_back(cmGlobalUnixMakefileGenerator3::NewFactory());
  1675. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1676. this->Generators.push_back(cmGlobalNinjaGenerator::NewFactory());
  1677. #endif
  1678. #if defined(CMAKE_USE_WMAKE)
  1679. this->Generators.push_back(cmGlobalWatcomWMakeGenerator::NewFactory());
  1680. #endif
  1681. #ifdef CMAKE_USE_XCODE
  1682. this->Generators.push_back(cmGlobalXCodeGenerator::NewFactory());
  1683. #endif
  1684. }
  1685. bool cmake::ParseCacheEntry(const std::string& entry, std::string& var,
  1686. std::string& value,
  1687. cmStateEnums::CacheEntryType& type)
  1688. {
  1689. return cmState::ParseCacheEntry(entry, var, value, type);
  1690. }
  1691. int cmake::LoadCache()
  1692. {
  1693. // could we not read the cache
  1694. if (!this->LoadCache(this->GetHomeOutputDirectory())) {
  1695. // if it does exist, but isn't readable then warn the user
  1696. std::string cacheFile = this->GetHomeOutputDirectory();
  1697. cacheFile += "/CMakeCache.txt";
  1698. if (cmSystemTools::FileExists(cacheFile)) {
  1699. cmSystemTools::Error(
  1700. "There is a CMakeCache.txt file for the current binary tree but "
  1701. "cmake does not have permission to read it. Please check the "
  1702. "permissions of the directory you are trying to run CMake on.");
  1703. return -1;
  1704. }
  1705. }
  1706. // setup CMAKE_ROOT and CMAKE_COMMAND
  1707. if (!this->AddCMakePaths()) {
  1708. return -3;
  1709. }
  1710. return 0;
  1711. }
  1712. bool cmake::LoadCache(const std::string& path)
  1713. {
  1714. std::set<std::string> emptySet;
  1715. return this->LoadCache(path, true, emptySet, emptySet);
  1716. }
  1717. bool cmake::LoadCache(const std::string& path, bool internal,
  1718. std::set<std::string>& excludes,
  1719. std::set<std::string>& includes)
  1720. {
  1721. bool result = this->State->LoadCache(path, internal, excludes, includes);
  1722. static const char* entries[] = { "CMAKE_CACHE_MAJOR_VERSION",
  1723. "CMAKE_CACHE_MINOR_VERSION" };
  1724. for (const char* const* nameIt = cm::cbegin(entries);
  1725. nameIt != cm::cend(entries); ++nameIt) {
  1726. this->UnwatchUnusedCli(*nameIt);
  1727. }
  1728. return result;
  1729. }
  1730. bool cmake::SaveCache(const std::string& path)
  1731. {
  1732. bool result = this->State->SaveCache(path, this->GetMessenger());
  1733. static const char* entries[] = { "CMAKE_CACHE_MAJOR_VERSION",
  1734. "CMAKE_CACHE_MINOR_VERSION",
  1735. "CMAKE_CACHE_PATCH_VERSION",
  1736. "CMAKE_CACHEFILE_DIR" };
  1737. for (const char* const* nameIt = cm::cbegin(entries);
  1738. nameIt != cm::cend(entries); ++nameIt) {
  1739. this->UnwatchUnusedCli(*nameIt);
  1740. }
  1741. return result;
  1742. }
  1743. bool cmake::DeleteCache(const std::string& path)
  1744. {
  1745. return this->State->DeleteCache(path);
  1746. }
  1747. void cmake::SetProgressCallback(ProgressCallbackType f)
  1748. {
  1749. this->ProgressCallback = std::move(f);
  1750. }
  1751. void cmake::UpdateProgress(const std::string& msg, float prog)
  1752. {
  1753. if (this->ProgressCallback && !this->State->GetIsInTryCompile()) {
  1754. this->ProgressCallback(msg, prog);
  1755. }
  1756. }
  1757. bool cmake::GetIsInTryCompile() const
  1758. {
  1759. return this->State->GetIsInTryCompile();
  1760. }
  1761. void cmake::SetIsInTryCompile(bool b)
  1762. {
  1763. this->State->SetIsInTryCompile(b);
  1764. }
  1765. void cmake::AppendGlobalGeneratorsDocumentation(
  1766. std::vector<cmDocumentationEntry>& v)
  1767. {
  1768. const auto defaultGenerator = this->EvaluateDefaultGlobalGenerator();
  1769. const std::string defaultName = defaultGenerator->GetName();
  1770. bool foundDefaultOne = false;
  1771. for (cmGlobalGeneratorFactory* g : this->Generators) {
  1772. cmDocumentationEntry e;
  1773. g->GetDocumentation(e);
  1774. if (!foundDefaultOne &&
  1775. cmSystemTools::StringStartsWith(e.Name, defaultName.c_str())) {
  1776. e.CustomNamePrefix = '*';
  1777. foundDefaultOne = true;
  1778. }
  1779. v.push_back(std::move(e));
  1780. }
  1781. }
  1782. void cmake::AppendExtraGeneratorsDocumentation(
  1783. std::vector<cmDocumentationEntry>& v)
  1784. {
  1785. for (cmExternalMakefileProjectGeneratorFactory* eg : this->ExtraGenerators) {
  1786. const std::string doc = eg->GetDocumentation();
  1787. const std::string name = eg->GetName();
  1788. // Aliases:
  1789. for (std::string const& a : eg->Aliases) {
  1790. cmDocumentationEntry e;
  1791. e.Name = a;
  1792. e.Brief = doc;
  1793. v.push_back(std::move(e));
  1794. }
  1795. // Full names:
  1796. const std::vector<std::string> generators =
  1797. eg->GetSupportedGlobalGenerators();
  1798. for (std::string const& g : generators) {
  1799. cmDocumentationEntry e;
  1800. e.Name =
  1801. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(g, name);
  1802. e.Brief = doc;
  1803. v.push_back(std::move(e));
  1804. }
  1805. }
  1806. }
  1807. std::vector<cmDocumentationEntry> cmake::GetGeneratorsDocumentation()
  1808. {
  1809. std::vector<cmDocumentationEntry> v;
  1810. this->AppendGlobalGeneratorsDocumentation(v);
  1811. this->AppendExtraGeneratorsDocumentation(v);
  1812. return v;
  1813. }
  1814. void cmake::PrintGeneratorList()
  1815. {
  1816. #ifdef CMAKE_BUILD_WITH_CMAKE
  1817. cmDocumentation doc;
  1818. auto generators = this->GetGeneratorsDocumentation();
  1819. doc.AppendSection("Generators", generators);
  1820. std::cerr << "\n";
  1821. doc.PrintDocumentation(cmDocumentation::ListGenerators, std::cerr);
  1822. #endif
  1823. }
  1824. void cmake::UpdateConversionPathTable()
  1825. {
  1826. // Update the path conversion table with any specified file:
  1827. const std::string* tablepath =
  1828. this->State->GetInitializedCacheValue("CMAKE_PATH_TRANSLATION_FILE");
  1829. if (tablepath) {
  1830. cmsys::ifstream table(tablepath->c_str());
  1831. if (!table) {
  1832. cmSystemTools::Error("CMAKE_PATH_TRANSLATION_FILE set to ",
  1833. tablepath->c_str(), ". CMake can not open file.");
  1834. cmSystemTools::ReportLastSystemError("CMake can not open file.");
  1835. } else {
  1836. std::string a, b;
  1837. while (!table.eof()) {
  1838. // two entries per line
  1839. table >> a;
  1840. table >> b;
  1841. cmSystemTools::AddTranslationPath(a, b);
  1842. }
  1843. }
  1844. }
  1845. }
  1846. int cmake::CheckBuildSystem()
  1847. {
  1848. // We do not need to rerun CMake. Check dependency integrity.
  1849. const bool verbose = isCMakeVerbose();
  1850. // This method will check the integrity of the build system if the
  1851. // option was given on the command line. It reads the given file to
  1852. // determine whether CMake should rerun.
  1853. // If no file is provided for the check, we have to rerun.
  1854. if (this->CheckBuildSystemArgument.empty()) {
  1855. if (verbose) {
  1856. std::ostringstream msg;
  1857. msg << "Re-run cmake no build system arguments\n";
  1858. cmSystemTools::Stdout(msg.str());
  1859. }
  1860. return 1;
  1861. }
  1862. // If the file provided does not exist, we have to rerun.
  1863. if (!cmSystemTools::FileExists(this->CheckBuildSystemArgument)) {
  1864. if (verbose) {
  1865. std::ostringstream msg;
  1866. msg << "Re-run cmake missing file: " << this->CheckBuildSystemArgument
  1867. << "\n";
  1868. cmSystemTools::Stdout(msg.str());
  1869. }
  1870. return 1;
  1871. }
  1872. // Read the rerun check file and use it to decide whether to do the
  1873. // global generate.
  1874. // Actually, all we need is the `set` command.
  1875. cmake cm(RoleScript, cmState::Unknown);
  1876. cm.SetHomeDirectory("");
  1877. cm.SetHomeOutputDirectory("");
  1878. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  1879. cmGlobalGenerator gg(&cm);
  1880. cmMakefile mf(&gg, cm.GetCurrentSnapshot());
  1881. if (!mf.ReadListFile(this->CheckBuildSystemArgument) ||
  1882. cmSystemTools::GetErrorOccuredFlag()) {
  1883. if (verbose) {
  1884. std::ostringstream msg;
  1885. msg << "Re-run cmake error reading : " << this->CheckBuildSystemArgument
  1886. << "\n";
  1887. cmSystemTools::Stdout(msg.str());
  1888. }
  1889. // There was an error reading the file. Just rerun.
  1890. return 1;
  1891. }
  1892. if (this->ClearBuildSystem) {
  1893. // Get the generator used for this build system.
  1894. const char* genName = mf.GetDefinition("CMAKE_DEPENDS_GENERATOR");
  1895. if (!genName || genName[0] == '\0') {
  1896. genName = "Unix Makefiles";
  1897. }
  1898. // Create the generator and use it to clear the dependencies.
  1899. std::unique_ptr<cmGlobalGenerator> ggd(
  1900. this->CreateGlobalGenerator(genName));
  1901. if (ggd) {
  1902. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  1903. cmMakefile mfd(ggd.get(), cm.GetCurrentSnapshot());
  1904. std::unique_ptr<cmLocalGenerator> lgd(ggd->CreateLocalGenerator(&mfd));
  1905. lgd->ClearDependencies(&mfd, verbose);
  1906. }
  1907. }
  1908. // If any byproduct of makefile generation is missing we must re-run.
  1909. std::vector<std::string> products;
  1910. if (const char* productStr = mf.GetDefinition("CMAKE_MAKEFILE_PRODUCTS")) {
  1911. cmSystemTools::ExpandListArgument(productStr, products);
  1912. }
  1913. for (std::string const& p : products) {
  1914. if (!(cmSystemTools::FileExists(p) || cmSystemTools::FileIsSymlink(p))) {
  1915. if (verbose) {
  1916. std::ostringstream msg;
  1917. msg << "Re-run cmake, missing byproduct: " << p << "\n";
  1918. cmSystemTools::Stdout(msg.str());
  1919. }
  1920. return 1;
  1921. }
  1922. }
  1923. // Get the set of dependencies and outputs.
  1924. std::vector<std::string> depends;
  1925. std::vector<std::string> outputs;
  1926. const char* dependsStr = mf.GetDefinition("CMAKE_MAKEFILE_DEPENDS");
  1927. const char* outputsStr = mf.GetDefinition("CMAKE_MAKEFILE_OUTPUTS");
  1928. if (dependsStr && outputsStr) {
  1929. cmSystemTools::ExpandListArgument(dependsStr, depends);
  1930. cmSystemTools::ExpandListArgument(outputsStr, outputs);
  1931. }
  1932. if (depends.empty() || outputs.empty()) {
  1933. // Not enough information was provided to do the test. Just rerun.
  1934. if (verbose) {
  1935. std::ostringstream msg;
  1936. msg << "Re-run cmake no CMAKE_MAKEFILE_DEPENDS "
  1937. "or CMAKE_MAKEFILE_OUTPUTS :\n";
  1938. cmSystemTools::Stdout(msg.str());
  1939. }
  1940. return 1;
  1941. }
  1942. // Find the newest dependency.
  1943. std::vector<std::string>::iterator dep = depends.begin();
  1944. std::string dep_newest = *dep++;
  1945. for (; dep != depends.end(); ++dep) {
  1946. int result = 0;
  1947. if (this->FileComparison->FileTimeCompare(dep_newest, *dep, &result)) {
  1948. if (result < 0) {
  1949. dep_newest = *dep;
  1950. }
  1951. } else {
  1952. if (verbose) {
  1953. std::ostringstream msg;
  1954. msg << "Re-run cmake: build system dependency is missing\n";
  1955. cmSystemTools::Stdout(msg.str());
  1956. }
  1957. return 1;
  1958. }
  1959. }
  1960. // Find the oldest output.
  1961. std::vector<std::string>::iterator out = outputs.begin();
  1962. std::string out_oldest = *out++;
  1963. for (; out != outputs.end(); ++out) {
  1964. int result = 0;
  1965. if (this->FileComparison->FileTimeCompare(out_oldest, *out, &result)) {
  1966. if (result > 0) {
  1967. out_oldest = *out;
  1968. }
  1969. } else {
  1970. if (verbose) {
  1971. std::ostringstream msg;
  1972. msg << "Re-run cmake: build system output is missing\n";
  1973. cmSystemTools::Stdout(msg.str());
  1974. }
  1975. return 1;
  1976. }
  1977. }
  1978. // If any output is older than any dependency then rerun.
  1979. {
  1980. int result = 0;
  1981. if (!this->FileComparison->FileTimeCompare(out_oldest, dep_newest,
  1982. &result) ||
  1983. result < 0) {
  1984. if (verbose) {
  1985. std::ostringstream msg;
  1986. msg << "Re-run cmake file: " << out_oldest
  1987. << " older than: " << dep_newest << "\n";
  1988. cmSystemTools::Stdout(msg.str());
  1989. }
  1990. return 1;
  1991. }
  1992. }
  1993. // No need to rerun.
  1994. return 0;
  1995. }
  1996. void cmake::TruncateOutputLog(const char* fname)
  1997. {
  1998. std::string fullPath = this->GetHomeOutputDirectory();
  1999. fullPath += "/";
  2000. fullPath += fname;
  2001. struct stat st;
  2002. if (::stat(fullPath.c_str(), &st)) {
  2003. return;
  2004. }
  2005. if (!this->State->GetInitializedCacheValue("CMAKE_CACHEFILE_DIR")) {
  2006. cmSystemTools::RemoveFile(fullPath);
  2007. return;
  2008. }
  2009. off_t fsize = st.st_size;
  2010. const off_t maxFileSize = 50 * 1024;
  2011. if (fsize < maxFileSize) {
  2012. // TODO: truncate file
  2013. return;
  2014. }
  2015. }
  2016. inline std::string removeQuotes(const std::string& s)
  2017. {
  2018. if (s.front() == '\"' && s.back() == '\"') {
  2019. return s.substr(1, s.size() - 2);
  2020. }
  2021. return s;
  2022. }
  2023. void cmake::MarkCliAsUsed(const std::string& variable)
  2024. {
  2025. this->UsedCliVariables[variable] = true;
  2026. }
  2027. void cmake::GenerateGraphViz(const char* fileName) const
  2028. {
  2029. #ifdef CMAKE_BUILD_WITH_CMAKE
  2030. cmGraphVizWriter gvWriter(this->GetGlobalGenerator());
  2031. std::string settingsFile = this->GetHomeOutputDirectory();
  2032. settingsFile += "/CMakeGraphVizOptions.cmake";
  2033. std::string fallbackSettingsFile = this->GetHomeDirectory();
  2034. fallbackSettingsFile += "/CMakeGraphVizOptions.cmake";
  2035. gvWriter.ReadSettings(settingsFile.c_str(), fallbackSettingsFile.c_str());
  2036. gvWriter.WritePerTargetFiles(fileName);
  2037. gvWriter.WriteTargetDependersFiles(fileName);
  2038. gvWriter.WriteGlobalFile(fileName);
  2039. #endif
  2040. }
  2041. void cmake::SetProperty(const std::string& prop, const char* value)
  2042. {
  2043. this->State->SetGlobalProperty(prop, value);
  2044. }
  2045. void cmake::AppendProperty(const std::string& prop, const char* value,
  2046. bool asString)
  2047. {
  2048. this->State->AppendGlobalProperty(prop, value, asString);
  2049. }
  2050. const char* cmake::GetProperty(const std::string& prop)
  2051. {
  2052. return this->State->GetGlobalProperty(prop);
  2053. }
  2054. bool cmake::GetPropertyAsBool(const std::string& prop)
  2055. {
  2056. return this->State->GetGlobalPropertyAsBool(prop);
  2057. }
  2058. cmInstalledFile* cmake::GetOrCreateInstalledFile(cmMakefile* mf,
  2059. const std::string& name)
  2060. {
  2061. std::map<std::string, cmInstalledFile>::iterator i =
  2062. this->InstalledFiles.find(name);
  2063. if (i != this->InstalledFiles.end()) {
  2064. cmInstalledFile& file = i->second;
  2065. return &file;
  2066. }
  2067. cmInstalledFile& file = this->InstalledFiles[name];
  2068. file.SetName(mf, name);
  2069. return &file;
  2070. }
  2071. cmInstalledFile const* cmake::GetInstalledFile(const std::string& name) const
  2072. {
  2073. std::map<std::string, cmInstalledFile>::const_iterator i =
  2074. this->InstalledFiles.find(name);
  2075. if (i != this->InstalledFiles.end()) {
  2076. cmInstalledFile const& file = i->second;
  2077. return &file;
  2078. }
  2079. return nullptr;
  2080. }
  2081. int cmake::GetSystemInformation(std::vector<std::string>& args)
  2082. {
  2083. // so create the directory
  2084. std::string resultFile;
  2085. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  2086. std::string destPath = cwd + "/__cmake_systeminformation";
  2087. cmSystemTools::RemoveADirectory(destPath);
  2088. if (!cmSystemTools::MakeDirectory(destPath)) {
  2089. std::cerr << "Error: --system-information must be run from a "
  2090. "writable directory!\n";
  2091. return 1;
  2092. }
  2093. // process the arguments
  2094. bool writeToStdout = true;
  2095. for (unsigned int i = 1; i < args.size(); ++i) {
  2096. std::string const& arg = args[i];
  2097. if (arg.find("-G", 0) == 0) {
  2098. std::string value = arg.substr(2);
  2099. if (value.empty()) {
  2100. ++i;
  2101. if (i >= args.size()) {
  2102. cmSystemTools::Error("No generator specified for -G");
  2103. this->PrintGeneratorList();
  2104. return -1;
  2105. }
  2106. value = args[i];
  2107. }
  2108. cmGlobalGenerator* gen = this->CreateGlobalGenerator(value);
  2109. if (!gen) {
  2110. cmSystemTools::Error("Could not create named generator ",
  2111. value.c_str());
  2112. this->PrintGeneratorList();
  2113. } else {
  2114. this->SetGlobalGenerator(gen);
  2115. }
  2116. }
  2117. // no option assume it is the output file
  2118. else {
  2119. if (!cmSystemTools::FileIsFullPath(arg)) {
  2120. resultFile = cwd;
  2121. resultFile += "/";
  2122. }
  2123. resultFile += arg;
  2124. writeToStdout = false;
  2125. }
  2126. }
  2127. // we have to find the module directory, so we can copy the files
  2128. this->AddCMakePaths();
  2129. std::string modulesPath = cmSystemTools::GetCMakeRoot();
  2130. modulesPath += "/Modules";
  2131. std::string inFile = modulesPath;
  2132. inFile += "/SystemInformation.cmake";
  2133. std::string outFile = destPath;
  2134. outFile += "/CMakeLists.txt";
  2135. // Copy file
  2136. if (!cmsys::SystemTools::CopyFileAlways(inFile, outFile)) {
  2137. std::cerr << "Error copying file \"" << inFile << "\" to \"" << outFile
  2138. << "\".\n";
  2139. return 1;
  2140. }
  2141. // do we write to a file or to stdout?
  2142. if (resultFile.empty()) {
  2143. resultFile = cwd;
  2144. resultFile += "/__cmake_systeminformation/results.txt";
  2145. }
  2146. {
  2147. // now run cmake on the CMakeLists file
  2148. cmWorkingDirectory workdir(destPath);
  2149. if (workdir.Failed()) {
  2150. // We created the directory and we were able to copy the CMakeLists.txt
  2151. // file to it, so we wouldn't expect to get here unless the default
  2152. // permissions are questionable or some other process has deleted the
  2153. // directory
  2154. std::cerr << "Failed to change to directory " << destPath << " : "
  2155. << std::strerror(workdir.GetLastResult()) << std::endl;
  2156. return 1;
  2157. }
  2158. std::vector<std::string> args2;
  2159. args2.push_back(args[0]);
  2160. args2.push_back(destPath);
  2161. args2.push_back("-DRESULT_FILE=" + resultFile);
  2162. int res = this->Run(args2, false);
  2163. if (res != 0) {
  2164. std::cerr << "Error: --system-information failed on internal CMake!\n";
  2165. return res;
  2166. }
  2167. }
  2168. // echo results to stdout if needed
  2169. if (writeToStdout) {
  2170. FILE* fin = cmsys::SystemTools::Fopen(resultFile, "r");
  2171. if (fin) {
  2172. const int bufferSize = 4096;
  2173. char buffer[bufferSize];
  2174. size_t n;
  2175. while ((n = fread(buffer, 1, bufferSize, fin)) > 0) {
  2176. for (char* c = buffer; c < buffer + n; ++c) {
  2177. putc(*c, stdout);
  2178. }
  2179. fflush(stdout);
  2180. }
  2181. fclose(fin);
  2182. }
  2183. }
  2184. // clean up the directory
  2185. cmSystemTools::RemoveADirectory(destPath);
  2186. return 0;
  2187. }
  2188. static bool cmakeCheckStampFile(const std::string& stampName, bool verbose)
  2189. {
  2190. // The stamp file does not exist. Use the stamp dependencies to
  2191. // determine whether it is really out of date. This works in
  2192. // conjunction with cmLocalVisualStudio7Generator to avoid
  2193. // repeatedly re-running CMake when the user rebuilds the entire
  2194. // solution.
  2195. std::string stampDepends = stampName;
  2196. stampDepends += ".depend";
  2197. #if defined(_WIN32) || defined(__CYGWIN__)
  2198. cmsys::ifstream fin(stampDepends.c_str(), std::ios::in | std::ios::binary);
  2199. #else
  2200. cmsys::ifstream fin(stampDepends.c_str());
  2201. #endif
  2202. if (!fin) {
  2203. // The stamp dependencies file cannot be read. Just assume the
  2204. // build system is really out of date.
  2205. std::cout << "CMake is re-running because " << stampName
  2206. << " dependency file is missing.\n";
  2207. return false;
  2208. }
  2209. // Compare the stamp dependencies against the dependency file itself.
  2210. cmFileTimeComparison ftc;
  2211. std::string dep;
  2212. while (cmSystemTools::GetLineFromStream(fin, dep)) {
  2213. int result;
  2214. if (!dep.empty() && dep[0] != '#' &&
  2215. (!ftc.FileTimeCompare(stampDepends, dep, &result) || result < 0)) {
  2216. // The stamp depends file is older than this dependency. The
  2217. // build system is really out of date.
  2218. std::cout << "CMake is re-running because " << stampName
  2219. << " is out-of-date.\n";
  2220. std::cout << " the file '" << dep << "'\n";
  2221. std::cout << " is newer than '" << stampDepends << "'\n";
  2222. std::cout << " result='" << result << "'\n";
  2223. return false;
  2224. }
  2225. }
  2226. // The build system is up to date. The stamp file has been removed
  2227. // by the VS IDE due to a "rebuild" request. Restore it atomically.
  2228. std::ostringstream stampTempStream;
  2229. stampTempStream << stampName << ".tmp" << cmSystemTools::RandomSeed();
  2230. std::string stampTemp = stampTempStream.str();
  2231. {
  2232. // TODO: Teach cmGeneratedFileStream to use a random temp file (with
  2233. // multiple tries in unlikely case of conflict) and use that here.
  2234. cmsys::ofstream stamp(stampTemp.c_str());
  2235. stamp << "# CMake generation timestamp file for this directory.\n";
  2236. }
  2237. if (cmSystemTools::RenameFile(stampTemp, stampName)) {
  2238. if (verbose) {
  2239. // Notify the user why CMake is not re-running. It is safe to
  2240. // just print to stdout here because this code is only reachable
  2241. // through an undocumented flag used by the VS generator.
  2242. std::cout << "CMake does not need to re-run because " << stampName
  2243. << " is up-to-date.\n";
  2244. }
  2245. return true;
  2246. }
  2247. cmSystemTools::RemoveFile(stampTemp);
  2248. cmSystemTools::Error("Cannot restore timestamp ", stampName.c_str());
  2249. return false;
  2250. }
  2251. static bool cmakeCheckStampList(const std::string& stampList, bool verbose)
  2252. {
  2253. // If the stamp list does not exist CMake must rerun to generate it.
  2254. if (!cmSystemTools::FileExists(stampList)) {
  2255. std::cout << "CMake is re-running because generate.stamp.list "
  2256. << "is missing.\n";
  2257. return false;
  2258. }
  2259. cmsys::ifstream fin(stampList.c_str());
  2260. if (!fin) {
  2261. std::cout << "CMake is re-running because generate.stamp.list "
  2262. << "could not be read.\n";
  2263. return false;
  2264. }
  2265. // Check each stamp.
  2266. std::string stampName;
  2267. while (cmSystemTools::GetLineFromStream(fin, stampName)) {
  2268. if (!cmakeCheckStampFile(stampName, verbose)) {
  2269. return false;
  2270. }
  2271. }
  2272. return true;
  2273. }
  2274. void cmake::IssueMessage(MessageType t, std::string const& text,
  2275. cmListFileBacktrace const& backtrace) const
  2276. {
  2277. this->Messenger->IssueMessage(t, text, backtrace);
  2278. }
  2279. std::vector<std::string> cmake::GetDebugConfigs()
  2280. {
  2281. std::vector<std::string> configs;
  2282. if (const char* config_list =
  2283. this->State->GetGlobalProperty("DEBUG_CONFIGURATIONS")) {
  2284. // Expand the specified list and convert to upper-case.
  2285. cmSystemTools::ExpandListArgument(config_list, configs);
  2286. std::transform(configs.begin(), configs.end(), configs.begin(),
  2287. cmSystemTools::UpperCase);
  2288. }
  2289. // If no configurations were specified, use a default list.
  2290. if (configs.empty()) {
  2291. configs.emplace_back("DEBUG");
  2292. }
  2293. return configs;
  2294. }
  2295. cmMessenger* cmake::GetMessenger() const
  2296. {
  2297. return this->Messenger;
  2298. }
  2299. int cmake::Build(int jobs, const std::string& dir, const std::string& target,
  2300. const std::string& config,
  2301. const std::vector<std::string>& nativeOptions, bool clean,
  2302. bool verbose)
  2303. {
  2304. this->SetHomeDirectory("");
  2305. this->SetHomeOutputDirectory("");
  2306. if (!cmSystemTools::FileIsDirectory(dir)) {
  2307. std::cerr << "Error: " << dir << " is not a directory\n";
  2308. return 1;
  2309. }
  2310. std::string cachePath = FindCacheFile(dir);
  2311. if (!this->LoadCache(cachePath)) {
  2312. std::cerr << "Error: could not load cache\n";
  2313. return 1;
  2314. }
  2315. const char* cachedGenerator =
  2316. this->State->GetCacheEntryValue("CMAKE_GENERATOR");
  2317. if (!cachedGenerator) {
  2318. std::cerr << "Error: could not find CMAKE_GENERATOR in Cache\n";
  2319. return 1;
  2320. }
  2321. cmGlobalGenerator* gen = this->CreateGlobalGenerator(cachedGenerator);
  2322. if (!gen) {
  2323. std::cerr << "Error: could create CMAKE_GENERATOR \"" << cachedGenerator
  2324. << "\"\n";
  2325. return 1;
  2326. }
  2327. this->SetGlobalGenerator(gen);
  2328. const char* cachedGeneratorInstance =
  2329. this->State->GetCacheEntryValue("CMAKE_GENERATOR_INSTANCE");
  2330. if (cachedGeneratorInstance) {
  2331. cmMakefile mf(gen, this->GetCurrentSnapshot());
  2332. if (!gen->SetGeneratorInstance(cachedGeneratorInstance, &mf)) {
  2333. return 1;
  2334. }
  2335. }
  2336. const char* cachedGeneratorPlatform =
  2337. this->State->GetCacheEntryValue("CMAKE_GENERATOR_PLATFORM");
  2338. if (cachedGeneratorPlatform) {
  2339. cmMakefile mf(gen, this->GetCurrentSnapshot());
  2340. if (!gen->SetGeneratorPlatform(cachedGeneratorPlatform, &mf)) {
  2341. return 1;
  2342. }
  2343. }
  2344. std::string output;
  2345. std::string projName;
  2346. const char* cachedProjectName =
  2347. this->State->GetCacheEntryValue("CMAKE_PROJECT_NAME");
  2348. if (!cachedProjectName) {
  2349. std::cerr << "Error: could not find CMAKE_PROJECT_NAME in Cache\n";
  2350. return 1;
  2351. }
  2352. projName = cachedProjectName;
  2353. const char* cachedVerbose =
  2354. this->State->GetCacheEntryValue("CMAKE_VERBOSE_MAKEFILE");
  2355. if (cmSystemTools::IsOn(cachedVerbose)) {
  2356. verbose = true;
  2357. }
  2358. #ifdef CMAKE_HAVE_VS_GENERATORS
  2359. // For VS generators, explicitly check if regeneration is necessary before
  2360. // actually starting the build. If not done separately from the build
  2361. // itself, there is the risk of building an out-of-date solution file due
  2362. // to limitations of the underlying build system.
  2363. std::string const stampList = cachePath + "/" + "CMakeFiles/" +
  2364. cmGlobalVisualStudio9Generator::GetGenerateStampList();
  2365. // Note that the stampList file only exists for VS generators.
  2366. if (cmSystemTools::FileExists(stampList)) {
  2367. // Check if running for Visual Studio 9 - we need to explicitly run
  2368. // the glob verification script before starting the build
  2369. this->AddScriptingCommands();
  2370. if (this->GlobalGenerator->MatchesGeneratorName("Visual Studio 9 2008")) {
  2371. std::string const globVerifyScript =
  2372. cachePath + "/" + "CMakeFiles/" + "VerifyGlobs.cmake";
  2373. if (cmSystemTools::FileExists(globVerifyScript)) {
  2374. std::vector<std::string> args;
  2375. this->ReadListFile(args, globVerifyScript);
  2376. }
  2377. }
  2378. if (!cmakeCheckStampList(stampList, false)) {
  2379. // Correctly initialize the home (=source) and home output (=binary)
  2380. // directories, which is required for running the generation step.
  2381. std::string homeOrig = this->GetHomeDirectory();
  2382. std::string homeOutputOrig = this->GetHomeOutputDirectory();
  2383. this->SetDirectoriesFromFile(cachePath.c_str());
  2384. this->AddProjectCommands();
  2385. int ret = this->Configure();
  2386. if (ret) {
  2387. cmSystemTools::Message("CMake Configure step failed. "
  2388. "Build files cannot be regenerated correctly.");
  2389. return ret;
  2390. }
  2391. ret = this->Generate();
  2392. if (ret) {
  2393. cmSystemTools::Message("CMake Generate step failed. "
  2394. "Build files cannot be regenerated correctly.");
  2395. return ret;
  2396. }
  2397. std::string message = "Build files have been written to: ";
  2398. message += this->GetHomeOutputDirectory();
  2399. this->UpdateProgress(message, -1);
  2400. // Restore the previously set directories to their original value.
  2401. this->SetHomeDirectory(homeOrig);
  2402. this->SetHomeOutputDirectory(homeOutputOrig);
  2403. }
  2404. }
  2405. #endif
  2406. gen->PrintBuildCommandAdvice(std::cerr, jobs);
  2407. return gen->Build(jobs, "", dir, projName, target, output, "", config, clean,
  2408. false, verbose, cmDuration::zero(),
  2409. cmSystemTools::OUTPUT_PASSTHROUGH, nativeOptions);
  2410. }
  2411. bool cmake::Open(const std::string& dir, bool dryRun)
  2412. {
  2413. this->SetHomeDirectory("");
  2414. this->SetHomeOutputDirectory("");
  2415. if (!cmSystemTools::FileIsDirectory(dir)) {
  2416. std::cerr << "Error: " << dir << " is not a directory\n";
  2417. return false;
  2418. }
  2419. std::string cachePath = FindCacheFile(dir);
  2420. if (!this->LoadCache(cachePath)) {
  2421. std::cerr << "Error: could not load cache\n";
  2422. return false;
  2423. }
  2424. const char* genName = this->State->GetCacheEntryValue("CMAKE_GENERATOR");
  2425. if (!genName) {
  2426. std::cerr << "Error: could not find CMAKE_GENERATOR in Cache\n";
  2427. return false;
  2428. }
  2429. const std::string* extraGenName =
  2430. this->State->GetInitializedCacheValue("CMAKE_EXTRA_GENERATOR");
  2431. std::string fullName =
  2432. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  2433. genName, extraGenName ? *extraGenName : "");
  2434. std::unique_ptr<cmGlobalGenerator> gen(
  2435. this->CreateGlobalGenerator(fullName));
  2436. if (!gen) {
  2437. std::cerr << "Error: could create CMAKE_GENERATOR \"" << fullName
  2438. << "\"\n";
  2439. return false;
  2440. }
  2441. const char* cachedProjectName =
  2442. this->State->GetCacheEntryValue("CMAKE_PROJECT_NAME");
  2443. if (!cachedProjectName) {
  2444. std::cerr << "Error: could not find CMAKE_PROJECT_NAME in Cache\n";
  2445. return false;
  2446. }
  2447. return gen->Open(dir, cachedProjectName, dryRun);
  2448. }
  2449. void cmake::WatchUnusedCli(const std::string& var)
  2450. {
  2451. #ifdef CMAKE_BUILD_WITH_CMAKE
  2452. this->VariableWatch->AddWatch(var, cmWarnUnusedCliWarning, this);
  2453. if (this->UsedCliVariables.find(var) == this->UsedCliVariables.end()) {
  2454. this->UsedCliVariables[var] = false;
  2455. }
  2456. #endif
  2457. }
  2458. void cmake::UnwatchUnusedCli(const std::string& var)
  2459. {
  2460. #ifdef CMAKE_BUILD_WITH_CMAKE
  2461. this->VariableWatch->RemoveWatch(var, cmWarnUnusedCliWarning);
  2462. this->UsedCliVariables.erase(var);
  2463. #endif
  2464. }
  2465. void cmake::RunCheckForUnusedVariables()
  2466. {
  2467. #ifdef CMAKE_BUILD_WITH_CMAKE
  2468. bool haveUnused = false;
  2469. std::ostringstream msg;
  2470. msg << "Manually-specified variables were not used by the project:";
  2471. for (auto const& it : this->UsedCliVariables) {
  2472. if (!it.second) {
  2473. haveUnused = true;
  2474. msg << "\n " << it.first;
  2475. }
  2476. }
  2477. if (haveUnused) {
  2478. this->IssueMessage(MessageType::WARNING, msg.str());
  2479. }
  2480. #endif
  2481. }
  2482. bool cmake::GetSuppressDevWarnings() const
  2483. {
  2484. return this->Messenger->GetSuppressDevWarnings();
  2485. }
  2486. void cmake::SetSuppressDevWarnings(bool b)
  2487. {
  2488. std::string value;
  2489. // equivalent to -Wno-dev
  2490. if (b) {
  2491. value = "TRUE";
  2492. }
  2493. // equivalent to -Wdev
  2494. else {
  2495. value = "FALSE";
  2496. }
  2497. this->AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", value.c_str(),
  2498. "Suppress Warnings that are meant for"
  2499. " the author of the CMakeLists.txt files.",
  2500. cmStateEnums::INTERNAL);
  2501. }
  2502. bool cmake::GetSuppressDeprecatedWarnings() const
  2503. {
  2504. return this->Messenger->GetSuppressDeprecatedWarnings();
  2505. }
  2506. void cmake::SetSuppressDeprecatedWarnings(bool b)
  2507. {
  2508. std::string value;
  2509. // equivalent to -Wno-deprecated
  2510. if (b) {
  2511. value = "FALSE";
  2512. }
  2513. // equivalent to -Wdeprecated
  2514. else {
  2515. value = "TRUE";
  2516. }
  2517. this->AddCacheEntry("CMAKE_WARN_DEPRECATED", value.c_str(),
  2518. "Whether to issue warnings for deprecated "
  2519. "functionality.",
  2520. cmStateEnums::INTERNAL);
  2521. }
  2522. bool cmake::GetDevWarningsAsErrors() const
  2523. {
  2524. return this->Messenger->GetDevWarningsAsErrors();
  2525. }
  2526. void cmake::SetDevWarningsAsErrors(bool b)
  2527. {
  2528. std::string value;
  2529. // equivalent to -Werror=dev
  2530. if (b) {
  2531. value = "FALSE";
  2532. }
  2533. // equivalent to -Wno-error=dev
  2534. else {
  2535. value = "TRUE";
  2536. }
  2537. this->AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_ERRORS", value.c_str(),
  2538. "Suppress errors that are meant for"
  2539. " the author of the CMakeLists.txt files.",
  2540. cmStateEnums::INTERNAL);
  2541. }
  2542. bool cmake::GetDeprecatedWarningsAsErrors() const
  2543. {
  2544. return this->Messenger->GetDeprecatedWarningsAsErrors();
  2545. }
  2546. void cmake::SetDeprecatedWarningsAsErrors(bool b)
  2547. {
  2548. std::string value;
  2549. // equivalent to -Werror=deprecated
  2550. if (b) {
  2551. value = "TRUE";
  2552. }
  2553. // equivalent to -Wno-error=deprecated
  2554. else {
  2555. value = "FALSE";
  2556. }
  2557. this->AddCacheEntry("CMAKE_ERROR_DEPRECATED", value.c_str(),
  2558. "Whether to issue deprecation errors for macros"
  2559. " and functions.",
  2560. cmStateEnums::INTERNAL);
  2561. }