cmake.cxx 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536
  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. cmState::CacheEntryType type = cmState::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. cmState::CacheEntryType t = this->State->GetCacheEntryType(*it);
  365. if (t != cmState::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. cmState::Snapshot 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. cmState::Snapshot 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.", cmState::INTERNAL);
  783. #ifdef CMAKE_BUILD_WITH_CMAKE
  784. this->AddCacheEntry("CMAKE_CTEST_COMMAND",
  785. cmSystemTools::GetCTestCommand().c_str(),
  786. "Path to ctest program executable.", cmState::INTERNAL);
  787. this->AddCacheEntry("CMAKE_CPACK_COMMAND",
  788. cmSystemTools::GetCPackCommand().c_str(),
  789. "Path to cpack program executable.", cmState::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.", cmState::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. (*i)->GetName(), *gen);
  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. cmState::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. cmState::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.", cmState::INTERNAL);
  1222. this->AddCacheEntry("CMAKE_EXTRA_GENERATOR",
  1223. this->GlobalGenerator->GetExtraGeneratorName().c_str(),
  1224. "Name of external makefile project generator.",
  1225. cmState::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.", cmState::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.", cmState::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.", cmState::PATH);
  1289. }
  1290. if (!this->State->GetInitializedCacheValue("EXECUTABLE_OUTPUT_PATH")) {
  1291. this->AddCacheEntry(
  1292. "EXECUTABLE_OUTPUT_PATH", "",
  1293. "Single output directory for building all executables.",
  1294. cmState::PATH);
  1295. }
  1296. }
  1297. cmMakefile* mf = this->GlobalGenerator->GetMakefiles()[0];
  1298. if (mf->IsOn("CTEST_USE_LAUNCHERS") &&
  1299. !this->State->GetGlobalProperty("RULE_LAUNCH_COMPILE")) {
  1300. cmSystemTools::Error(
  1301. "CTEST_USE_LAUNCHERS is enabled, but the "
  1302. "RULE_LAUNCH_COMPILE global property is not defined.\n"
  1303. "Did you forget to include(CTest) in the toplevel "
  1304. "CMakeLists.txt ?");
  1305. }
  1306. // only save the cache if there were no fatal errors
  1307. if (this->GetWorkingMode() == NORMAL_MODE) {
  1308. this->SaveCache(this->GetHomeOutputDirectory());
  1309. }
  1310. if (cmSystemTools::GetErrorOccuredFlag()) {
  1311. return -1;
  1312. }
  1313. return 0;
  1314. }
  1315. void cmake::CreateDefaultGlobalGenerator()
  1316. {
  1317. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(CMAKE_BOOT_MINGW)
  1318. std::string installedCompiler;
  1319. // Try to find the newest VS installed on the computer and
  1320. // use that as a default if -G is not specified
  1321. const std::string vsregBase = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\";
  1322. std::vector<std::string> vsVerions;
  1323. vsVerions.push_back("VisualStudio\\");
  1324. vsVerions.push_back("VCExpress\\");
  1325. vsVerions.push_back("WDExpress\\");
  1326. struct VSRegistryEntryName
  1327. {
  1328. const char* MSVersion;
  1329. const char* GeneratorName;
  1330. };
  1331. VSRegistryEntryName version[] = {
  1332. /* clang-format needs this comment to break after the opening brace */
  1333. { "7.1", "Visual Studio 7 .NET 2003" },
  1334. { "8.0", "Visual Studio 8 2005" },
  1335. { "9.0", "Visual Studio 9 2008" },
  1336. { "10.0", "Visual Studio 10 2010" },
  1337. { "11.0", "Visual Studio 11 2012" },
  1338. { "12.0", "Visual Studio 12 2013" },
  1339. { "14.0", "Visual Studio 14 2015" },
  1340. { "15.0", "Visual Studio 15" },
  1341. { 0, 0 }
  1342. };
  1343. for (int i = 0; version[i].MSVersion != 0; i++) {
  1344. for (size_t b = 0; b < vsVerions.size(); b++) {
  1345. std::string reg = vsregBase + vsVerions[b] + version[i].MSVersion;
  1346. reg += ";InstallDir";
  1347. std::string dir;
  1348. if (cmSystemTools::ReadRegistryValue(reg, dir,
  1349. cmSystemTools::KeyWOW64_32) &&
  1350. cmSystemTools::PathExists(dir)) {
  1351. installedCompiler = version[i].GeneratorName;
  1352. break;
  1353. }
  1354. }
  1355. }
  1356. cmGlobalGenerator* gen =
  1357. this->CreateGlobalGenerator(installedCompiler.c_str());
  1358. if (!gen) {
  1359. gen = new cmGlobalNMakeMakefileGenerator(this);
  1360. }
  1361. this->SetGlobalGenerator(gen);
  1362. std::cout << "-- Building for: " << gen->GetName() << "\n";
  1363. #else
  1364. this->SetGlobalGenerator(new cmGlobalUnixMakefileGenerator3(this));
  1365. #endif
  1366. }
  1367. void cmake::PreLoadCMakeFiles()
  1368. {
  1369. std::vector<std::string> args;
  1370. std::string pre_load = this->GetHomeDirectory();
  1371. if (!pre_load.empty()) {
  1372. pre_load += "/PreLoad.cmake";
  1373. if (cmSystemTools::FileExists(pre_load.c_str())) {
  1374. this->ReadListFile(args, pre_load.c_str());
  1375. }
  1376. }
  1377. pre_load = this->GetHomeOutputDirectory();
  1378. if (!pre_load.empty()) {
  1379. pre_load += "/PreLoad.cmake";
  1380. if (cmSystemTools::FileExists(pre_load.c_str())) {
  1381. this->ReadListFile(args, pre_load.c_str());
  1382. }
  1383. }
  1384. }
  1385. // handle a command line invocation
  1386. int cmake::Run(const std::vector<std::string>& args, bool noconfigure)
  1387. {
  1388. // Process the arguments
  1389. this->SetArgs(args);
  1390. if (cmSystemTools::GetErrorOccuredFlag()) {
  1391. return -1;
  1392. }
  1393. // If we are given a stamp list file check if it is really out of date.
  1394. if (!this->CheckStampList.empty() &&
  1395. cmakeCheckStampList(this->CheckStampList.c_str())) {
  1396. return 0;
  1397. }
  1398. // If we are given a stamp file check if it is really out of date.
  1399. if (!this->CheckStampFile.empty() &&
  1400. cmakeCheckStampFile(this->CheckStampFile.c_str())) {
  1401. return 0;
  1402. }
  1403. if (this->GetWorkingMode() == NORMAL_MODE) {
  1404. // load the cache
  1405. if (this->LoadCache() < 0) {
  1406. cmSystemTools::Error("Error executing cmake::LoadCache(). Aborting.\n");
  1407. return -1;
  1408. }
  1409. } else {
  1410. this->AddCMakePaths();
  1411. }
  1412. // Add any cache args
  1413. if (!this->SetCacheArgs(args)) {
  1414. cmSystemTools::Error("Problem processing arguments. Aborting.\n");
  1415. return -1;
  1416. }
  1417. // In script mode we terminate after running the script.
  1418. if (this->GetWorkingMode() != NORMAL_MODE) {
  1419. if (cmSystemTools::GetErrorOccuredFlag()) {
  1420. return -1;
  1421. }
  1422. return 0;
  1423. }
  1424. // If MAKEFLAGS are given in the environment, remove the environment
  1425. // variable. This will prevent try-compile from succeeding when it
  1426. // should fail (if "-i" is an option). We cannot simply test
  1427. // whether "-i" is given and remove it because some make programs
  1428. // encode the MAKEFLAGS variable in a strange way.
  1429. if (cmSystemTools::HasEnv("MAKEFLAGS")) {
  1430. cmSystemTools::PutEnv("MAKEFLAGS=");
  1431. }
  1432. this->PreLoadCMakeFiles();
  1433. if (noconfigure) {
  1434. return 0;
  1435. }
  1436. // now run the global generate
  1437. // Check the state of the build system to see if we need to regenerate.
  1438. if (!this->CheckBuildSystem()) {
  1439. return 0;
  1440. }
  1441. int ret = this->Configure();
  1442. if (ret || this->GetWorkingMode() != NORMAL_MODE) {
  1443. #if defined(CMAKE_HAVE_VS_GENERATORS)
  1444. if (!this->VSSolutionFile.empty() && this->GlobalGenerator) {
  1445. // CMake is running to regenerate a Visual Studio build tree
  1446. // during a build from the VS IDE. The build files cannot be
  1447. // regenerated, so we should stop the build.
  1448. cmSystemTools::Message("CMake Configure step failed. "
  1449. "Build files cannot be regenerated correctly. "
  1450. "Attempting to stop IDE build.");
  1451. cmGlobalVisualStudioGenerator* gg =
  1452. static_cast<cmGlobalVisualStudioGenerator*>(this->GlobalGenerator);
  1453. gg->CallVisualStudioMacro(cmGlobalVisualStudioGenerator::MacroStop,
  1454. this->VSSolutionFile.c_str());
  1455. }
  1456. #endif
  1457. return ret;
  1458. }
  1459. ret = this->Generate();
  1460. std::string message = "Build files have been written to: ";
  1461. message += this->GetHomeOutputDirectory();
  1462. this->UpdateProgress(message.c_str(), -1);
  1463. return ret;
  1464. }
  1465. int cmake::Generate()
  1466. {
  1467. if (!this->GlobalGenerator) {
  1468. return -1;
  1469. }
  1470. if (!this->GlobalGenerator->Compute()) {
  1471. return -1;
  1472. }
  1473. this->GlobalGenerator->Generate();
  1474. if (!this->GraphVizFile.empty()) {
  1475. std::cout << "Generate graphviz: " << this->GraphVizFile << std::endl;
  1476. this->GenerateGraphViz(this->GraphVizFile.c_str());
  1477. }
  1478. if (this->WarnUnusedCli) {
  1479. this->RunCheckForUnusedVariables();
  1480. }
  1481. if (cmSystemTools::GetErrorOccuredFlag()) {
  1482. return -1;
  1483. }
  1484. // Save the cache again after a successful Generate so that any internal
  1485. // variables created during Generate are saved. (Specifically target GUIDs
  1486. // for the Visual Studio and Xcode generators.)
  1487. if (this->GetWorkingMode() == NORMAL_MODE) {
  1488. this->SaveCache(this->GetHomeOutputDirectory());
  1489. }
  1490. return 0;
  1491. }
  1492. void cmake::AddCacheEntry(const std::string& key, const char* value,
  1493. const char* helpString, int type)
  1494. {
  1495. this->State->AddCacheEntry(key, value, helpString,
  1496. cmState::CacheEntryType(type));
  1497. this->UnwatchUnusedCli(key);
  1498. }
  1499. const char* cmake::GetCacheDefinition(const std::string& name) const
  1500. {
  1501. return this->State->GetInitializedCacheValue(name);
  1502. }
  1503. void cmake::AddDefaultCommands()
  1504. {
  1505. std::vector<cmCommand*> commands;
  1506. GetBootstrapCommands1(commands);
  1507. GetBootstrapCommands2(commands);
  1508. GetPredefinedCommands(commands);
  1509. for (std::vector<cmCommand*>::iterator i = commands.begin();
  1510. i != commands.end(); ++i) {
  1511. this->State->AddCommand(*i);
  1512. }
  1513. }
  1514. void cmake::AddDefaultGenerators()
  1515. {
  1516. #if defined(_WIN32) && !defined(__CYGWIN__)
  1517. #if !defined(CMAKE_BOOT_MINGW)
  1518. this->Generators.push_back(cmGlobalVisualStudio15Generator::NewFactory());
  1519. this->Generators.push_back(cmGlobalVisualStudio14Generator::NewFactory());
  1520. this->Generators.push_back(cmGlobalVisualStudio12Generator::NewFactory());
  1521. this->Generators.push_back(cmGlobalVisualStudio11Generator::NewFactory());
  1522. this->Generators.push_back(cmGlobalVisualStudio10Generator::NewFactory());
  1523. this->Generators.push_back(cmGlobalVisualStudio9Generator::NewFactory());
  1524. this->Generators.push_back(cmGlobalVisualStudio8Generator::NewFactory());
  1525. this->Generators.push_back(cmGlobalVisualStudio71Generator::NewFactory());
  1526. this->Generators.push_back(cmGlobalBorlandMakefileGenerator::NewFactory());
  1527. this->Generators.push_back(cmGlobalNMakeMakefileGenerator::NewFactory());
  1528. this->Generators.push_back(cmGlobalJOMMakefileGenerator::NewFactory());
  1529. this->Generators.push_back(cmGlobalGhsMultiGenerator::NewFactory());
  1530. #endif
  1531. this->Generators.push_back(cmGlobalMSYSMakefileGenerator::NewFactory());
  1532. this->Generators.push_back(cmGlobalMinGWMakefileGenerator::NewFactory());
  1533. #endif
  1534. this->Generators.push_back(cmGlobalUnixMakefileGenerator3::NewFactory());
  1535. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1536. this->Generators.push_back(cmGlobalNinjaGenerator::NewFactory());
  1537. #endif
  1538. #if defined(CMAKE_USE_WMAKE)
  1539. this->Generators.push_back(cmGlobalWatcomWMakeGenerator::NewFactory());
  1540. #endif
  1541. #ifdef CMAKE_USE_XCODE
  1542. this->Generators.push_back(cmGlobalXCodeGenerator::NewFactory());
  1543. #endif
  1544. }
  1545. bool cmake::ParseCacheEntry(const std::string& entry, std::string& var,
  1546. std::string& value, cmState::CacheEntryType& type)
  1547. {
  1548. return cmState::ParseCacheEntry(entry, var, value, type);
  1549. }
  1550. int cmake::LoadCache()
  1551. {
  1552. // could we not read the cache
  1553. if (!this->LoadCache(this->GetHomeOutputDirectory())) {
  1554. // if it does exist, but isn't readable then warn the user
  1555. std::string cacheFile = this->GetHomeOutputDirectory();
  1556. cacheFile += "/CMakeCache.txt";
  1557. if (cmSystemTools::FileExists(cacheFile.c_str())) {
  1558. cmSystemTools::Error(
  1559. "There is a CMakeCache.txt file for the current binary tree but "
  1560. "cmake does not have permission to read it. Please check the "
  1561. "permissions of the directory you are trying to run CMake on.");
  1562. return -1;
  1563. }
  1564. }
  1565. // setup CMAKE_ROOT and CMAKE_COMMAND
  1566. if (!this->AddCMakePaths()) {
  1567. return -3;
  1568. }
  1569. return 0;
  1570. }
  1571. bool cmake::LoadCache(const std::string& path)
  1572. {
  1573. std::set<std::string> emptySet;
  1574. return this->LoadCache(path, true, emptySet, emptySet);
  1575. }
  1576. bool cmake::LoadCache(const std::string& path, bool internal,
  1577. std::set<std::string>& excludes,
  1578. std::set<std::string>& includes)
  1579. {
  1580. bool result = this->State->LoadCache(path, internal, excludes, includes);
  1581. static const char* entries[] = { "CMAKE_CACHE_MAJOR_VERSION",
  1582. "CMAKE_CACHE_MINOR_VERSION" };
  1583. for (const char* const* nameIt = cmArrayBegin(entries);
  1584. nameIt != cmArrayEnd(entries); ++nameIt) {
  1585. this->UnwatchUnusedCli(*nameIt);
  1586. }
  1587. return result;
  1588. }
  1589. bool cmake::SaveCache(const std::string& path)
  1590. {
  1591. bool result = this->State->SaveCache(path);
  1592. static const char* entries[] = { "CMAKE_CACHE_MAJOR_VERSION",
  1593. "CMAKE_CACHE_MINOR_VERSION",
  1594. "CMAKE_CACHE_PATCH_VERSION",
  1595. "CMAKE_CACHEFILE_DIR" };
  1596. for (const char* const* nameIt = cmArrayBegin(entries);
  1597. nameIt != cmArrayEnd(entries); ++nameIt) {
  1598. this->UnwatchUnusedCli(*nameIt);
  1599. }
  1600. return result;
  1601. }
  1602. bool cmake::DeleteCache(const std::string& path)
  1603. {
  1604. return this->State->DeleteCache(path);
  1605. }
  1606. void cmake::SetProgressCallback(ProgressCallbackType f, void* cd)
  1607. {
  1608. this->ProgressCallback = f;
  1609. this->ProgressCallbackClientData = cd;
  1610. }
  1611. void cmake::UpdateProgress(const char* msg, float prog)
  1612. {
  1613. if (this->ProgressCallback && !this->State->GetIsInTryCompile()) {
  1614. (*this->ProgressCallback)(msg, prog, this->ProgressCallbackClientData);
  1615. return;
  1616. }
  1617. }
  1618. bool cmake::GetIsInTryCompile() const
  1619. {
  1620. return this->State->GetIsInTryCompile();
  1621. }
  1622. void cmake::SetIsInTryCompile(bool b)
  1623. {
  1624. this->State->SetIsInTryCompile(b);
  1625. }
  1626. void cmake::GetGeneratorDocumentation(std::vector<cmDocumentationEntry>& v)
  1627. {
  1628. for (RegisteredGeneratorsVector::const_iterator i = this->Generators.begin();
  1629. i != this->Generators.end(); ++i) {
  1630. cmDocumentationEntry e;
  1631. (*i)->GetDocumentation(e);
  1632. v.push_back(e);
  1633. }
  1634. for (RegisteredExtraGeneratorsVector::const_iterator i =
  1635. this->ExtraGenerators.begin();
  1636. i != this->ExtraGenerators.end(); ++i) {
  1637. const std::string doc = (*i)->GetDocumentation();
  1638. const std::string name = (*i)->GetName();
  1639. // Aliases:
  1640. for (std::vector<std::string>::const_iterator a = (*i)->Aliases.begin();
  1641. a != (*i)->Aliases.end(); ++a) {
  1642. cmDocumentationEntry e;
  1643. e.Name = *a;
  1644. e.Brief = doc;
  1645. v.push_back(e);
  1646. }
  1647. // Full names:
  1648. const std::vector<std::string> generators =
  1649. (*i)->GetSupportedGlobalGenerators();
  1650. for (std::vector<std::string>::const_iterator g = generators.begin();
  1651. g != generators.end(); ++g) {
  1652. cmDocumentationEntry e;
  1653. e.Name =
  1654. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(*g, name);
  1655. e.Brief = doc;
  1656. v.push_back(e);
  1657. }
  1658. }
  1659. }
  1660. void cmake::PrintGeneratorList()
  1661. {
  1662. #ifdef CMAKE_BUILD_WITH_CMAKE
  1663. cmDocumentation doc;
  1664. std::vector<cmDocumentationEntry> generators;
  1665. this->GetGeneratorDocumentation(generators);
  1666. doc.AppendSection("Generators", generators);
  1667. std::cerr << "\n";
  1668. doc.PrintDocumentation(cmDocumentation::ListGenerators, std::cerr);
  1669. #endif
  1670. }
  1671. void cmake::UpdateConversionPathTable()
  1672. {
  1673. // Update the path conversion table with any specified file:
  1674. const char* tablepath =
  1675. this->State->GetInitializedCacheValue("CMAKE_PATH_TRANSLATION_FILE");
  1676. if (tablepath) {
  1677. cmsys::ifstream table(tablepath);
  1678. if (!table) {
  1679. cmSystemTools::Error("CMAKE_PATH_TRANSLATION_FILE set to ", tablepath,
  1680. ". CMake can not open file.");
  1681. cmSystemTools::ReportLastSystemError("CMake can not open file.");
  1682. } else {
  1683. std::string a, b;
  1684. while (!table.eof()) {
  1685. // two entries per line
  1686. table >> a;
  1687. table >> b;
  1688. cmSystemTools::AddTranslationPath(a, b);
  1689. }
  1690. }
  1691. }
  1692. }
  1693. int cmake::CheckBuildSystem()
  1694. {
  1695. // We do not need to rerun CMake. Check dependency integrity.
  1696. const bool verbose = isCMakeVerbose();
  1697. // This method will check the integrity of the build system if the
  1698. // option was given on the command line. It reads the given file to
  1699. // determine whether CMake should rerun.
  1700. // If no file is provided for the check, we have to rerun.
  1701. if (this->CheckBuildSystemArgument.empty()) {
  1702. if (verbose) {
  1703. std::ostringstream msg;
  1704. msg << "Re-run cmake no build system arguments\n";
  1705. cmSystemTools::Stdout(msg.str().c_str());
  1706. }
  1707. return 1;
  1708. }
  1709. // If the file provided does not exist, we have to rerun.
  1710. if (!cmSystemTools::FileExists(this->CheckBuildSystemArgument.c_str())) {
  1711. if (verbose) {
  1712. std::ostringstream msg;
  1713. msg << "Re-run cmake missing file: " << this->CheckBuildSystemArgument
  1714. << "\n";
  1715. cmSystemTools::Stdout(msg.str().c_str());
  1716. }
  1717. return 1;
  1718. }
  1719. // Read the rerun check file and use it to decide whether to do the
  1720. // global generate.
  1721. cmake cm;
  1722. cm.SetHomeDirectory("");
  1723. cm.SetHomeOutputDirectory("");
  1724. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  1725. cmGlobalGenerator gg(&cm);
  1726. CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(&gg, cm.GetCurrentSnapshot()));
  1727. if (!mf->ReadListFile(this->CheckBuildSystemArgument.c_str()) ||
  1728. cmSystemTools::GetErrorOccuredFlag()) {
  1729. if (verbose) {
  1730. std::ostringstream msg;
  1731. msg << "Re-run cmake error reading : " << this->CheckBuildSystemArgument
  1732. << "\n";
  1733. cmSystemTools::Stdout(msg.str().c_str());
  1734. }
  1735. // There was an error reading the file. Just rerun.
  1736. return 1;
  1737. }
  1738. if (this->ClearBuildSystem) {
  1739. // Get the generator used for this build system.
  1740. const char* genName = mf->GetDefinition("CMAKE_DEPENDS_GENERATOR");
  1741. if (!genName || genName[0] == '\0') {
  1742. genName = "Unix Makefiles";
  1743. }
  1744. // Create the generator and use it to clear the dependencies.
  1745. CM_AUTO_PTR<cmGlobalGenerator> ggd(this->CreateGlobalGenerator(genName));
  1746. if (ggd.get()) {
  1747. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  1748. CM_AUTO_PTR<cmMakefile> mfd(
  1749. new cmMakefile(ggd.get(), cm.GetCurrentSnapshot()));
  1750. CM_AUTO_PTR<cmLocalGenerator> lgd(ggd->CreateLocalGenerator(mfd.get()));
  1751. lgd->ClearDependencies(mfd.get(), verbose);
  1752. }
  1753. }
  1754. // If any byproduct of makefile generation is missing we must re-run.
  1755. std::vector<std::string> products;
  1756. if (const char* productStr = mf->GetDefinition("CMAKE_MAKEFILE_PRODUCTS")) {
  1757. cmSystemTools::ExpandListArgument(productStr, products);
  1758. }
  1759. for (std::vector<std::string>::const_iterator pi = products.begin();
  1760. pi != products.end(); ++pi) {
  1761. if (!(cmSystemTools::FileExists(pi->c_str()) ||
  1762. cmSystemTools::FileIsSymlink(*pi))) {
  1763. if (verbose) {
  1764. std::ostringstream msg;
  1765. msg << "Re-run cmake, missing byproduct: " << *pi << "\n";
  1766. cmSystemTools::Stdout(msg.str().c_str());
  1767. }
  1768. return 1;
  1769. }
  1770. }
  1771. // Get the set of dependencies and outputs.
  1772. std::vector<std::string> depends;
  1773. std::vector<std::string> outputs;
  1774. const char* dependsStr = mf->GetDefinition("CMAKE_MAKEFILE_DEPENDS");
  1775. const char* outputsStr = mf->GetDefinition("CMAKE_MAKEFILE_OUTPUTS");
  1776. if (dependsStr && outputsStr) {
  1777. cmSystemTools::ExpandListArgument(dependsStr, depends);
  1778. cmSystemTools::ExpandListArgument(outputsStr, outputs);
  1779. }
  1780. if (depends.empty() || outputs.empty()) {
  1781. // Not enough information was provided to do the test. Just rerun.
  1782. if (verbose) {
  1783. std::ostringstream msg;
  1784. msg << "Re-run cmake no CMAKE_MAKEFILE_DEPENDS "
  1785. "or CMAKE_MAKEFILE_OUTPUTS :\n";
  1786. cmSystemTools::Stdout(msg.str().c_str());
  1787. }
  1788. return 1;
  1789. }
  1790. // Find the newest dependency.
  1791. std::vector<std::string>::iterator dep = depends.begin();
  1792. std::string dep_newest = *dep++;
  1793. for (; dep != depends.end(); ++dep) {
  1794. int result = 0;
  1795. if (this->FileComparison->FileTimeCompare(dep_newest.c_str(), dep->c_str(),
  1796. &result)) {
  1797. if (result < 0) {
  1798. dep_newest = *dep;
  1799. }
  1800. } else {
  1801. if (verbose) {
  1802. std::ostringstream msg;
  1803. msg << "Re-run cmake: build system dependency is missing\n";
  1804. cmSystemTools::Stdout(msg.str().c_str());
  1805. }
  1806. return 1;
  1807. }
  1808. }
  1809. // Find the oldest output.
  1810. std::vector<std::string>::iterator out = outputs.begin();
  1811. std::string out_oldest = *out++;
  1812. for (; out != outputs.end(); ++out) {
  1813. int result = 0;
  1814. if (this->FileComparison->FileTimeCompare(out_oldest.c_str(), out->c_str(),
  1815. &result)) {
  1816. if (result > 0) {
  1817. out_oldest = *out;
  1818. }
  1819. } else {
  1820. if (verbose) {
  1821. std::ostringstream msg;
  1822. msg << "Re-run cmake: build system output is missing\n";
  1823. cmSystemTools::Stdout(msg.str().c_str());
  1824. }
  1825. return 1;
  1826. }
  1827. }
  1828. // If any output is older than any dependency then rerun.
  1829. {
  1830. int result = 0;
  1831. if (!this->FileComparison->FileTimeCompare(out_oldest.c_str(),
  1832. dep_newest.c_str(), &result) ||
  1833. result < 0) {
  1834. if (verbose) {
  1835. std::ostringstream msg;
  1836. msg << "Re-run cmake file: " << out_oldest
  1837. << " older than: " << dep_newest << "\n";
  1838. cmSystemTools::Stdout(msg.str().c_str());
  1839. }
  1840. return 1;
  1841. }
  1842. }
  1843. // No need to rerun.
  1844. return 0;
  1845. }
  1846. void cmake::TruncateOutputLog(const char* fname)
  1847. {
  1848. std::string fullPath = this->GetHomeOutputDirectory();
  1849. fullPath += "/";
  1850. fullPath += fname;
  1851. struct stat st;
  1852. if (::stat(fullPath.c_str(), &st)) {
  1853. return;
  1854. }
  1855. if (!this->State->GetInitializedCacheValue("CMAKE_CACHEFILE_DIR")) {
  1856. cmSystemTools::RemoveFile(fullPath);
  1857. return;
  1858. }
  1859. off_t fsize = st.st_size;
  1860. const off_t maxFileSize = 50 * 1024;
  1861. if (fsize < maxFileSize) {
  1862. // TODO: truncate file
  1863. return;
  1864. }
  1865. }
  1866. inline std::string removeQuotes(const std::string& s)
  1867. {
  1868. if (s[0] == '\"' && s[s.size() - 1] == '\"') {
  1869. return s.substr(1, s.size() - 2);
  1870. }
  1871. return s;
  1872. }
  1873. void cmake::MarkCliAsUsed(const std::string& variable)
  1874. {
  1875. this->UsedCliVariables[variable] = true;
  1876. }
  1877. void cmake::GenerateGraphViz(const char* fileName) const
  1878. {
  1879. #ifdef CMAKE_BUILD_WITH_CMAKE
  1880. CM_AUTO_PTR<cmGraphVizWriter> gvWriter(
  1881. new cmGraphVizWriter(this->GetGlobalGenerator()->GetLocalGenerators()));
  1882. std::string settingsFile = this->GetHomeOutputDirectory();
  1883. settingsFile += "/CMakeGraphVizOptions.cmake";
  1884. std::string fallbackSettingsFile = this->GetHomeDirectory();
  1885. fallbackSettingsFile += "/CMakeGraphVizOptions.cmake";
  1886. gvWriter->ReadSettings(settingsFile.c_str(), fallbackSettingsFile.c_str());
  1887. gvWriter->WritePerTargetFiles(fileName);
  1888. gvWriter->WriteTargetDependersFiles(fileName);
  1889. gvWriter->WriteGlobalFile(fileName);
  1890. #endif
  1891. }
  1892. void cmake::SetProperty(const std::string& prop, const char* value)
  1893. {
  1894. this->State->SetGlobalProperty(prop, value);
  1895. }
  1896. void cmake::AppendProperty(const std::string& prop, const char* value,
  1897. bool asString)
  1898. {
  1899. this->State->AppendGlobalProperty(prop, value, asString);
  1900. }
  1901. const char* cmake::GetProperty(const std::string& prop)
  1902. {
  1903. return this->State->GetGlobalProperty(prop);
  1904. }
  1905. bool cmake::GetPropertyAsBool(const std::string& prop)
  1906. {
  1907. return this->State->GetGlobalPropertyAsBool(prop);
  1908. }
  1909. cmInstalledFile* cmake::GetOrCreateInstalledFile(cmMakefile* mf,
  1910. const std::string& name)
  1911. {
  1912. std::map<std::string, cmInstalledFile>::iterator i =
  1913. this->InstalledFiles.find(name);
  1914. if (i != this->InstalledFiles.end()) {
  1915. cmInstalledFile& file = i->second;
  1916. return &file;
  1917. }
  1918. cmInstalledFile& file = this->InstalledFiles[name];
  1919. file.SetName(mf, name);
  1920. return &file;
  1921. }
  1922. cmInstalledFile const* cmake::GetInstalledFile(const std::string& name) const
  1923. {
  1924. std::map<std::string, cmInstalledFile>::const_iterator i =
  1925. this->InstalledFiles.find(name);
  1926. if (i != this->InstalledFiles.end()) {
  1927. cmInstalledFile const& file = i->second;
  1928. return &file;
  1929. }
  1930. return CM_NULLPTR;
  1931. }
  1932. int cmake::GetSystemInformation(std::vector<std::string>& args)
  1933. {
  1934. // so create the directory
  1935. std::string resultFile;
  1936. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1937. std::string destPath = cwd + "/__cmake_systeminformation";
  1938. cmSystemTools::RemoveADirectory(destPath);
  1939. if (!cmSystemTools::MakeDirectory(destPath.c_str())) {
  1940. std::cerr << "Error: --system-information must be run from a "
  1941. "writable directory!\n";
  1942. return 1;
  1943. }
  1944. // process the arguments
  1945. bool writeToStdout = true;
  1946. for (unsigned int i = 1; i < args.size(); ++i) {
  1947. std::string arg = args[i];
  1948. if (arg.find("-G", 0) == 0) {
  1949. std::string value = arg.substr(2);
  1950. if (value.empty()) {
  1951. ++i;
  1952. if (i >= args.size()) {
  1953. cmSystemTools::Error("No generator specified for -G");
  1954. this->PrintGeneratorList();
  1955. return -1;
  1956. }
  1957. value = args[i];
  1958. }
  1959. cmGlobalGenerator* gen = this->CreateGlobalGenerator(value);
  1960. if (!gen) {
  1961. cmSystemTools::Error("Could not create named generator ",
  1962. value.c_str());
  1963. this->PrintGeneratorList();
  1964. } else {
  1965. this->SetGlobalGenerator(gen);
  1966. }
  1967. }
  1968. // no option assume it is the output file
  1969. else {
  1970. if (!cmSystemTools::FileIsFullPath(arg.c_str())) {
  1971. resultFile = cwd;
  1972. resultFile += "/";
  1973. }
  1974. resultFile += arg;
  1975. writeToStdout = false;
  1976. }
  1977. }
  1978. // we have to find the module directory, so we can copy the files
  1979. this->AddCMakePaths();
  1980. std::string modulesPath = cmSystemTools::GetCMakeRoot();
  1981. modulesPath += "/Modules";
  1982. std::string inFile = modulesPath;
  1983. inFile += "/SystemInformation.cmake";
  1984. std::string outFile = destPath;
  1985. outFile += "/CMakeLists.txt";
  1986. // Copy file
  1987. if (!cmSystemTools::cmCopyFile(inFile.c_str(), outFile.c_str())) {
  1988. std::cerr << "Error copying file \"" << inFile << "\" to \"" << outFile
  1989. << "\".\n";
  1990. return 1;
  1991. }
  1992. // do we write to a file or to stdout?
  1993. if (resultFile.empty()) {
  1994. resultFile = cwd;
  1995. resultFile += "/__cmake_systeminformation/results.txt";
  1996. }
  1997. // now run cmake on the CMakeLists file
  1998. cmSystemTools::ChangeDirectory(destPath);
  1999. std::vector<std::string> args2;
  2000. args2.push_back(args[0]);
  2001. args2.push_back(destPath);
  2002. std::string resultArg = "-DRESULT_FILE=";
  2003. resultArg += resultFile;
  2004. args2.push_back(resultArg);
  2005. int res = this->Run(args2, false);
  2006. if (res != 0) {
  2007. std::cerr << "Error: --system-information failed on internal CMake!\n";
  2008. return res;
  2009. }
  2010. // change back to the original directory
  2011. cmSystemTools::ChangeDirectory(cwd);
  2012. // echo results to stdout if needed
  2013. if (writeToStdout) {
  2014. FILE* fin = cmsys::SystemTools::Fopen(resultFile, "r");
  2015. if (fin) {
  2016. const int bufferSize = 4096;
  2017. char buffer[bufferSize];
  2018. size_t n;
  2019. while ((n = fread(buffer, 1, bufferSize, fin)) > 0) {
  2020. for (char* c = buffer; c < buffer + n; ++c) {
  2021. putc(*c, stdout);
  2022. }
  2023. fflush(stdout);
  2024. }
  2025. fclose(fin);
  2026. }
  2027. }
  2028. // clean up the directory
  2029. cmSystemTools::RemoveADirectory(destPath);
  2030. return 0;
  2031. }
  2032. static bool cmakeCheckStampFile(const char* stampName)
  2033. {
  2034. // The stamp file does not exist. Use the stamp dependencies to
  2035. // determine whether it is really out of date. This works in
  2036. // conjunction with cmLocalVisualStudio7Generator to avoid
  2037. // repeatedly re-running CMake when the user rebuilds the entire
  2038. // solution.
  2039. std::string stampDepends = stampName;
  2040. stampDepends += ".depend";
  2041. #if defined(_WIN32) || defined(__CYGWIN__)
  2042. cmsys::ifstream fin(stampDepends.c_str(), std::ios::in | std::ios::binary);
  2043. #else
  2044. cmsys::ifstream fin(stampDepends.c_str());
  2045. #endif
  2046. if (!fin) {
  2047. // The stamp dependencies file cannot be read. Just assume the
  2048. // build system is really out of date.
  2049. std::cout << "CMake is re-running because " << stampName
  2050. << " dependency file is missing.\n";
  2051. return false;
  2052. }
  2053. // Compare the stamp dependencies against the dependency file itself.
  2054. cmFileTimeComparison ftc;
  2055. std::string dep;
  2056. while (cmSystemTools::GetLineFromStream(fin, dep)) {
  2057. int result;
  2058. if (!dep.empty() && dep[0] != '#' &&
  2059. (!ftc.FileTimeCompare(stampDepends.c_str(), dep.c_str(), &result) ||
  2060. result < 0)) {
  2061. // The stamp depends file is older than this dependency. The
  2062. // build system is really out of date.
  2063. std::cout << "CMake is re-running because " << stampName
  2064. << " is out-of-date.\n";
  2065. std::cout << " the file '" << dep << "'\n";
  2066. std::cout << " is newer than '" << stampDepends << "'\n";
  2067. std::cout << " result='" << result << "'\n";
  2068. return false;
  2069. }
  2070. }
  2071. // The build system is up to date. The stamp file has been removed
  2072. // by the VS IDE due to a "rebuild" request. Restore it atomically.
  2073. std::ostringstream stampTempStream;
  2074. stampTempStream << stampName << ".tmp" << cmSystemTools::RandomSeed();
  2075. std::string stampTempString = stampTempStream.str();
  2076. const char* stampTemp = stampTempString.c_str();
  2077. {
  2078. // TODO: Teach cmGeneratedFileStream to use a random temp file (with
  2079. // multiple tries in unlikely case of conflict) and use that here.
  2080. cmsys::ofstream stamp(stampTemp);
  2081. stamp << "# CMake generation timestamp file for this directory.\n";
  2082. }
  2083. if (cmSystemTools::RenameFile(stampTemp, stampName)) {
  2084. // Notify the user why CMake is not re-running. It is safe to
  2085. // just print to stdout here because this code is only reachable
  2086. // through an undocumented flag used by the VS generator.
  2087. std::cout << "CMake does not need to re-run because " << stampName
  2088. << " is up-to-date.\n";
  2089. return true;
  2090. }
  2091. cmSystemTools::RemoveFile(stampTemp);
  2092. cmSystemTools::Error("Cannot restore timestamp ", stampName);
  2093. return false;
  2094. }
  2095. static bool cmakeCheckStampList(const char* stampList)
  2096. {
  2097. // If the stamp list does not exist CMake must rerun to generate it.
  2098. if (!cmSystemTools::FileExists(stampList)) {
  2099. std::cout << "CMake is re-running because generate.stamp.list "
  2100. << "is missing.\n";
  2101. return false;
  2102. }
  2103. cmsys::ifstream fin(stampList);
  2104. if (!fin) {
  2105. std::cout << "CMake is re-running because generate.stamp.list "
  2106. << "could not be read.\n";
  2107. return false;
  2108. }
  2109. // Check each stamp.
  2110. std::string stampName;
  2111. while (cmSystemTools::GetLineFromStream(fin, stampName)) {
  2112. if (!cmakeCheckStampFile(stampName.c_str())) {
  2113. return false;
  2114. }
  2115. }
  2116. return true;
  2117. }
  2118. void cmake::IssueMessage(cmake::MessageType t, std::string const& text,
  2119. cmListFileBacktrace const& backtrace) const
  2120. {
  2121. this->Messenger->IssueMessage(t, text, backtrace);
  2122. }
  2123. std::vector<std::string> cmake::GetDebugConfigs()
  2124. {
  2125. std::vector<std::string> configs;
  2126. if (const char* config_list =
  2127. this->State->GetGlobalProperty("DEBUG_CONFIGURATIONS")) {
  2128. // Expand the specified list and convert to upper-case.
  2129. cmSystemTools::ExpandListArgument(config_list, configs);
  2130. std::transform(configs.begin(), configs.end(), configs.begin(),
  2131. cmSystemTools::UpperCase);
  2132. }
  2133. // If no configurations were specified, use a default list.
  2134. if (configs.empty()) {
  2135. configs.push_back("DEBUG");
  2136. }
  2137. return configs;
  2138. }
  2139. cmMessenger* cmake::GetMessenger() const
  2140. {
  2141. return this->Messenger;
  2142. }
  2143. int cmake::Build(const std::string& dir, const std::string& target,
  2144. const std::string& config,
  2145. const std::vector<std::string>& nativeOptions, bool clean)
  2146. {
  2147. this->SetHomeDirectory("");
  2148. this->SetHomeOutputDirectory("");
  2149. if (!cmSystemTools::FileIsDirectory(dir)) {
  2150. std::cerr << "Error: " << dir << " is not a directory\n";
  2151. return 1;
  2152. }
  2153. std::string cachePath = FindCacheFile(dir);
  2154. if (!this->LoadCache(cachePath)) {
  2155. std::cerr << "Error: could not load cache\n";
  2156. return 1;
  2157. }
  2158. const char* cachedGenerator =
  2159. this->State->GetCacheEntryValue("CMAKE_GENERATOR");
  2160. if (!cachedGenerator) {
  2161. std::cerr << "Error: could not find CMAKE_GENERATOR in Cache\n";
  2162. return 1;
  2163. }
  2164. CM_AUTO_PTR<cmGlobalGenerator> gen(
  2165. this->CreateGlobalGenerator(cachedGenerator));
  2166. if (!gen.get()) {
  2167. std::cerr << "Error: could create CMAKE_GENERATOR \"" << cachedGenerator
  2168. << "\"\n";
  2169. return 1;
  2170. }
  2171. std::string output;
  2172. std::string projName;
  2173. const char* cachedProjectName =
  2174. this->State->GetCacheEntryValue("CMAKE_PROJECT_NAME");
  2175. if (!cachedProjectName) {
  2176. std::cerr << "Error: could not find CMAKE_PROJECT_NAME in Cache\n";
  2177. return 1;
  2178. }
  2179. projName = cachedProjectName;
  2180. bool verbose = false;
  2181. const char* cachedVerbose =
  2182. this->State->GetCacheEntryValue("CMAKE_VERBOSE_MAKEFILE");
  2183. if (cachedVerbose) {
  2184. verbose = cmSystemTools::IsOn(cachedVerbose);
  2185. }
  2186. return gen->Build("", dir, projName, target, output, "", config, clean,
  2187. false, verbose, 0, cmSystemTools::OUTPUT_PASSTHROUGH,
  2188. nativeOptions);
  2189. }
  2190. void cmake::WatchUnusedCli(const std::string& var)
  2191. {
  2192. #ifdef CMAKE_BUILD_WITH_CMAKE
  2193. this->VariableWatch->AddWatch(var, cmWarnUnusedCliWarning, this);
  2194. if (this->UsedCliVariables.find(var) == this->UsedCliVariables.end()) {
  2195. this->UsedCliVariables[var] = false;
  2196. }
  2197. #endif
  2198. }
  2199. void cmake::UnwatchUnusedCli(const std::string& var)
  2200. {
  2201. #ifdef CMAKE_BUILD_WITH_CMAKE
  2202. this->VariableWatch->RemoveWatch(var, cmWarnUnusedCliWarning);
  2203. this->UsedCliVariables.erase(var);
  2204. #endif
  2205. }
  2206. void cmake::RunCheckForUnusedVariables()
  2207. {
  2208. #ifdef CMAKE_BUILD_WITH_CMAKE
  2209. bool haveUnused = false;
  2210. std::ostringstream msg;
  2211. msg << "Manually-specified variables were not used by the project:";
  2212. for (std::map<std::string, bool>::const_iterator it =
  2213. this->UsedCliVariables.begin();
  2214. it != this->UsedCliVariables.end(); ++it) {
  2215. if (!it->second) {
  2216. haveUnused = true;
  2217. msg << "\n " << it->first;
  2218. }
  2219. }
  2220. if (haveUnused) {
  2221. this->IssueMessage(cmake::WARNING, msg.str());
  2222. }
  2223. #endif
  2224. }
  2225. bool cmake::GetSuppressDevWarnings() const
  2226. {
  2227. return this->Messenger->GetSuppressDevWarnings();
  2228. }
  2229. void cmake::SetSuppressDevWarnings(bool b)
  2230. {
  2231. std::string value;
  2232. // equivalent to -Wno-dev
  2233. if (b) {
  2234. value = "TRUE";
  2235. }
  2236. // equivalent to -Wdev
  2237. else {
  2238. value = "FALSE";
  2239. }
  2240. this->AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", value.c_str(),
  2241. "Suppress Warnings that are meant for"
  2242. " the author of the CMakeLists.txt files.",
  2243. cmState::INTERNAL);
  2244. }
  2245. bool cmake::GetSuppressDeprecatedWarnings() const
  2246. {
  2247. return this->Messenger->GetSuppressDeprecatedWarnings();
  2248. }
  2249. void cmake::SetSuppressDeprecatedWarnings(bool b)
  2250. {
  2251. std::string value;
  2252. // equivalent to -Wno-deprecated
  2253. if (b) {
  2254. value = "FALSE";
  2255. }
  2256. // equivalent to -Wdeprecated
  2257. else {
  2258. value = "TRUE";
  2259. }
  2260. this->AddCacheEntry("CMAKE_WARN_DEPRECATED", value.c_str(),
  2261. "Whether to issue warnings for deprecated "
  2262. "functionality.",
  2263. cmState::INTERNAL);
  2264. }
  2265. bool cmake::GetDevWarningsAsErrors() const
  2266. {
  2267. return this->Messenger->GetDevWarningsAsErrors();
  2268. }
  2269. void cmake::SetDevWarningsAsErrors(bool b)
  2270. {
  2271. std::string value;
  2272. // equivalent to -Werror=dev
  2273. if (b) {
  2274. value = "FALSE";
  2275. }
  2276. // equivalent to -Wno-error=dev
  2277. else {
  2278. value = "TRUE";
  2279. }
  2280. this->AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_ERRORS", value.c_str(),
  2281. "Suppress errors that are meant for"
  2282. " the author of the CMakeLists.txt files.",
  2283. cmState::INTERNAL);
  2284. }
  2285. bool cmake::GetDeprecatedWarningsAsErrors() const
  2286. {
  2287. return this->Messenger->GetDeprecatedWarningsAsErrors();
  2288. }
  2289. void cmake::SetDeprecatedWarningsAsErrors(bool b)
  2290. {
  2291. std::string value;
  2292. // equivalent to -Werror=deprecated
  2293. if (b) {
  2294. value = "TRUE";
  2295. }
  2296. // equivalent to -Wno-error=deprecated
  2297. else {
  2298. value = "FALSE";
  2299. }
  2300. this->AddCacheEntry("CMAKE_ERROR_DEPRECATED", value.c_str(),
  2301. "Whether to issue deprecation errors for macros"
  2302. " and functions.",
  2303. cmState::INTERNAL);
  2304. }