cmake.cxx 84 KB

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