cmake.cxx 89 KB

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