cmake.cxx 86 KB

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