cmake.cxx 82 KB

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