cmake.cxx 80 KB

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