cmake.cxx 82 KB

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