cmake.cxx 87 KB

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