cmake.cxx 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527
  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 "cmLocalGenerator.h"
  15. #include "cmMakefile.h"
  16. #include "cmMessenger.h"
  17. #include "cmState.h"
  18. #include "cmSystemTools.h"
  19. #include "cmTarget.h"
  20. #include "cmTargetLinkLibraryType.h"
  21. #include "cmUtils.hxx"
  22. #include "cmVersionConfig.h"
  23. #include "cm_auto_ptr.hxx"
  24. #if defined(CMAKE_BUILD_WITH_CMAKE)
  25. #include "cmGraphVizWriter.h"
  26. #include "cmVariableWatch.h"
  27. #include <cm_jsoncpp_writer.h>
  28. #endif
  29. // only build kdevelop generator on non-windows platforms
  30. // when not bootstrapping cmake
  31. #if !defined(_WIN32)
  32. #if defined(CMAKE_BUILD_WITH_CMAKE)
  33. #define CMAKE_USE_KDEVELOP
  34. #endif
  35. #endif
  36. #if defined(CMAKE_BUILD_WITH_CMAKE)
  37. #define CMAKE_USE_ECLIPSE
  38. #endif
  39. #if defined(__MINGW32__) && !defined(CMAKE_BUILD_WITH_CMAKE)
  40. #define CMAKE_BOOT_MINGW
  41. #endif
  42. // include the generator
  43. #if defined(_WIN32) && !defined(__CYGWIN__)
  44. #if !defined(CMAKE_BOOT_MINGW)
  45. #include "cmGlobalBorlandMakefileGenerator.h"
  46. #include "cmGlobalGhsMultiGenerator.h"
  47. #include "cmGlobalJOMMakefileGenerator.h"
  48. #include "cmGlobalNMakeMakefileGenerator.h"
  49. #include "cmGlobalVisualStudio10Generator.h"
  50. #include "cmGlobalVisualStudio11Generator.h"
  51. #include "cmGlobalVisualStudio12Generator.h"
  52. #include "cmGlobalVisualStudio14Generator.h"
  53. #include "cmGlobalVisualStudio15Generator.h"
  54. #include "cmGlobalVisualStudio71Generator.h"
  55. #include "cmGlobalVisualStudio8Generator.h"
  56. #include "cmGlobalVisualStudio9Generator.h"
  57. #define CMAKE_HAVE_VS_GENERATORS
  58. #endif
  59. #include "cmGlobalMSYSMakefileGenerator.h"
  60. #include "cmGlobalMinGWMakefileGenerator.h"
  61. #else
  62. #endif
  63. #if defined(CMAKE_USE_WMAKE)
  64. #include "cmGlobalWatcomWMakeGenerator.h"
  65. #endif
  66. #include "cmGlobalUnixMakefileGenerator3.h"
  67. #if defined(CMAKE_BUILD_WITH_CMAKE)
  68. #include "cmGlobalNinjaGenerator.h"
  69. #endif
  70. #include "cmExtraCodeLiteGenerator.h"
  71. #if !defined(CMAKE_BOOT_MINGW)
  72. #include "cmExtraCodeBlocksGenerator.h"
  73. #endif
  74. #include "cmExtraKateGenerator.h"
  75. #include "cmExtraSublimeTextGenerator.h"
  76. #ifdef CMAKE_USE_KDEVELOP
  77. #include "cmGlobalKdevelopGenerator.h"
  78. #endif
  79. #ifdef CMAKE_USE_ECLIPSE
  80. #include "cmExtraEclipseCDT4Generator.h"
  81. #endif
  82. #if defined(__APPLE__)
  83. #if defined(CMAKE_BUILD_WITH_CMAKE)
  84. #include "cmGlobalXCodeGenerator.h"
  85. #define CMAKE_USE_XCODE 1
  86. #endif
  87. #include <sys/resource.h>
  88. #include <sys/time.h>
  89. #endif
  90. #include <sys/types.h>
  91. // include sys/stat.h after sys/types.h
  92. #include <sys/stat.h> // struct stat
  93. #include <algorithm>
  94. #include <cmsys/FStream.hxx>
  95. #include <cmsys/Glob.hxx>
  96. #include <cmsys/RegularExpression.hxx>
  97. #include <iostream>
  98. #include <sstream>
  99. #include <stdio.h>
  100. #include <stdlib.h>
  101. #include <string.h>
  102. #include <utility>
  103. class cmCommand;
  104. namespace {
  105. #if defined(CMAKE_BUILD_WITH_CMAKE)
  106. #ifdef CMake_HAVE_CXX_UNORDERED_MAP
  107. typedef std::unordered_map<std::string, Json::Value> JsonValueMapType;
  108. #else
  109. typedef cmsys::hash_map<std::string, Json::Value> JsonValueMapType;
  110. #endif
  111. #endif
  112. } // namespace
  113. static bool cmakeCheckStampFile(const char* stampName);
  114. static bool cmakeCheckStampList(const char* stampName);
  115. void cmWarnUnusedCliWarning(const std::string& variable, int /*unused*/,
  116. void* ctx, const char* /*unused*/,
  117. const cmMakefile* /*unused*/)
  118. {
  119. cmake* cm = reinterpret_cast<cmake*>(ctx);
  120. cm->MarkCliAsUsed(variable);
  121. }
  122. cmake::cmake()
  123. {
  124. this->Trace = false;
  125. this->TraceExpand = false;
  126. this->WarnUninitialized = false;
  127. this->WarnUnused = false;
  128. this->WarnUnusedCli = true;
  129. this->CheckSystemVars = false;
  130. this->DebugOutput = false;
  131. this->DebugTryCompile = false;
  132. this->ClearBuildSystem = false;
  133. this->FileComparison = new cmFileTimeComparison;
  134. this->State = new cmState;
  135. this->CurrentSnapshot = this->State->CreateBaseSnapshot();
  136. this->Messenger = new cmMessenger(this->State);
  137. #ifdef __APPLE__
  138. struct rlimit rlp;
  139. if (!getrlimit(RLIMIT_STACK, &rlp)) {
  140. if (rlp.rlim_cur != rlp.rlim_max) {
  141. rlp.rlim_cur = rlp.rlim_max;
  142. setrlimit(RLIMIT_STACK, &rlp);
  143. }
  144. }
  145. #endif
  146. this->GlobalGenerator = CM_NULLPTR;
  147. this->ProgressCallback = CM_NULLPTR;
  148. this->ProgressCallbackClientData = CM_NULLPTR;
  149. this->CurrentWorkingMode = NORMAL_MODE;
  150. #ifdef CMAKE_BUILD_WITH_CMAKE
  151. this->VariableWatch = new cmVariableWatch;
  152. #endif
  153. this->AddDefaultGenerators();
  154. this->AddDefaultExtraGenerators();
  155. this->AddDefaultCommands();
  156. // Make sure we can capture the build tool output.
  157. cmSystemTools::EnableVSConsoleOutput();
  158. // Set up a list of source and header extensions
  159. // these are used to find files when the extension
  160. // is not given
  161. // The "c" extension MUST precede the "C" extension.
  162. this->SourceFileExtensions.push_back("c");
  163. this->SourceFileExtensions.push_back("C");
  164. this->SourceFileExtensions.push_back("c++");
  165. this->SourceFileExtensions.push_back("cc");
  166. this->SourceFileExtensions.push_back("cpp");
  167. this->SourceFileExtensions.push_back("cxx");
  168. this->SourceFileExtensions.push_back("m");
  169. this->SourceFileExtensions.push_back("M");
  170. this->SourceFileExtensions.push_back("mm");
  171. this->HeaderFileExtensions.push_back("h");
  172. this->HeaderFileExtensions.push_back("hh");
  173. this->HeaderFileExtensions.push_back("h++");
  174. this->HeaderFileExtensions.push_back("hm");
  175. this->HeaderFileExtensions.push_back("hpp");
  176. this->HeaderFileExtensions.push_back("hxx");
  177. this->HeaderFileExtensions.push_back("in");
  178. this->HeaderFileExtensions.push_back("txx");
  179. }
  180. cmake::~cmake()
  181. {
  182. delete this->State;
  183. delete this->Messenger;
  184. if (this->GlobalGenerator) {
  185. delete this->GlobalGenerator;
  186. this->GlobalGenerator = CM_NULLPTR;
  187. }
  188. cmDeleteAll(this->Generators);
  189. #ifdef CMAKE_BUILD_WITH_CMAKE
  190. delete this->VariableWatch;
  191. #endif
  192. delete this->FileComparison;
  193. }
  194. #if defined(CMAKE_BUILD_WITH_CMAKE)
  195. Json::Value cmake::ReportCapabilitiesJson(bool haveServerMode) const
  196. {
  197. Json::Value obj = Json::objectValue;
  198. // Version information:
  199. Json::Value version = Json::objectValue;
  200. version["string"] = CMake_VERSION;
  201. version["major"] = CMake_VERSION_MAJOR;
  202. version["minor"] = CMake_VERSION_MINOR;
  203. version["suffix"] = CMake_VERSION_SUFFIX;
  204. version["isDirty"] = (CMake_VERSION_IS_DIRTY == 1);
  205. version["patch"] = CMake_VERSION_PATCH;
  206. obj["version"] = version;
  207. // Generators:
  208. std::vector<cmake::GeneratorInfo> generatorInfoList;
  209. this->GetRegisteredGenerators(generatorInfoList);
  210. JsonValueMapType generatorMap;
  211. for (std::vector<cmake::GeneratorInfo>::const_iterator i =
  212. generatorInfoList.begin();
  213. i != generatorInfoList.end(); ++i) {
  214. if (i->isAlias) { // skip aliases, they are there for compatibility reasons
  215. // only
  216. continue;
  217. }
  218. if (i->extraName.empty()) {
  219. Json::Value gen = Json::objectValue;
  220. gen["name"] = i->name;
  221. gen["toolsetSupport"] = i->supportsToolset;
  222. gen["platformSupport"] = i->supportsPlatform;
  223. gen["extraGenerators"] = Json::arrayValue;
  224. generatorMap[i->name] = gen;
  225. } else {
  226. Json::Value& gen = generatorMap[i->baseName];
  227. gen["extraGenerators"].append(i->extraName);
  228. }
  229. }
  230. Json::Value generators = Json::arrayValue;
  231. for (JsonValueMapType::const_iterator i = generatorMap.begin();
  232. i != generatorMap.end(); ++i) {
  233. generators.append(i->second);
  234. }
  235. obj["generators"] = generators;
  236. obj["serverMode"] = haveServerMode;
  237. return obj;
  238. }
  239. #endif
  240. std::string cmake::ReportCapabilities(bool haveServerMode) const
  241. {
  242. std::string result;
  243. #if defined(CMAKE_BUILD_WITH_CMAKE)
  244. Json::FastWriter writer;
  245. result = writer.write(this->ReportCapabilitiesJson(haveServerMode));
  246. #else
  247. result = "Not supported";
  248. #endif
  249. return result;
  250. }
  251. void cmake::CleanupCommandsAndMacros()
  252. {
  253. this->CurrentSnapshot = this->State->Reset();
  254. this->State->RemoveUserDefinedCommands();
  255. this->CurrentSnapshot.SetDefaultDefinitions();
  256. }
  257. // Parse the args
  258. bool cmake::SetCacheArgs(const std::vector<std::string>& args)
  259. {
  260. bool findPackageMode = false;
  261. for (unsigned int i = 1; i < args.size(); ++i) {
  262. std::string arg = args[i];
  263. if (arg.find("-D", 0) == 0) {
  264. std::string entry = arg.substr(2);
  265. if (entry.empty()) {
  266. ++i;
  267. if (i < args.size()) {
  268. entry = args[i];
  269. } else {
  270. cmSystemTools::Error("-D must be followed with VAR=VALUE.");
  271. return false;
  272. }
  273. }
  274. std::string var, value;
  275. cmState::CacheEntryType type = cmState::UNINITIALIZED;
  276. if (cmState::ParseCacheEntry(entry, var, value, type)) {
  277. // The value is transformed if it is a filepath for example, so
  278. // we can't compare whether the value is already in the cache until
  279. // after we call AddCacheEntry.
  280. bool haveValue = false;
  281. std::string cachedValue;
  282. if (this->WarnUnusedCli) {
  283. if (const char* v = this->State->GetInitializedCacheValue(var)) {
  284. haveValue = true;
  285. cachedValue = v;
  286. }
  287. }
  288. this->AddCacheEntry(var, value.c_str(),
  289. "No help, variable specified on the command line.",
  290. type);
  291. if (this->WarnUnusedCli) {
  292. if (!haveValue ||
  293. cachedValue != this->State->GetInitializedCacheValue(var)) {
  294. this->WatchUnusedCli(var);
  295. }
  296. }
  297. } else {
  298. std::cerr << "Parse error in command line argument: " << arg << "\n"
  299. << "Should be: VAR:type=value\n";
  300. cmSystemTools::Error("No cmake script provided.");
  301. return false;
  302. }
  303. } else if (cmHasLiteralPrefix(arg, "-W")) {
  304. std::string entry = arg.substr(2);
  305. if (entry.empty()) {
  306. ++i;
  307. if (i < args.size()) {
  308. entry = args[i];
  309. } else {
  310. cmSystemTools::Error("-W must be followed with [no-]<name>.");
  311. return false;
  312. }
  313. }
  314. std::string name;
  315. bool foundNo = false;
  316. bool foundError = false;
  317. unsigned int nameStartPosition = 0;
  318. if (entry.find("no-", nameStartPosition) == 0) {
  319. foundNo = true;
  320. nameStartPosition += 3;
  321. }
  322. if (entry.find("error=", nameStartPosition) == 0) {
  323. foundError = true;
  324. nameStartPosition += 6;
  325. }
  326. name = entry.substr(nameStartPosition);
  327. if (name.empty()) {
  328. cmSystemTools::Error("No warning name provided.");
  329. return false;
  330. }
  331. if (!foundNo && !foundError) {
  332. // -W<name>
  333. this->DiagLevels[name] = std::max(this->DiagLevels[name], DIAG_WARN);
  334. } else if (foundNo && !foundError) {
  335. // -Wno<name>
  336. this->DiagLevels[name] = DIAG_IGNORE;
  337. } else if (!foundNo && foundError) {
  338. // -Werror=<name>
  339. this->DiagLevels[name] = DIAG_ERROR;
  340. } else {
  341. // -Wno-error=<name>
  342. this->DiagLevels[name] = std::min(this->DiagLevels[name], DIAG_WARN);
  343. }
  344. } else if (arg.find("-U", 0) == 0) {
  345. std::string entryPattern = arg.substr(2);
  346. if (entryPattern.empty()) {
  347. ++i;
  348. if (i < args.size()) {
  349. entryPattern = args[i];
  350. } else {
  351. cmSystemTools::Error("-U must be followed with VAR.");
  352. return false;
  353. }
  354. }
  355. cmsys::RegularExpression regex(
  356. cmsys::Glob::PatternToRegex(entryPattern, true, true).c_str());
  357. // go through all cache entries and collect the vars which will be
  358. // removed
  359. std::vector<std::string> entriesToDelete;
  360. std::vector<std::string> cacheKeys = this->State->GetCacheEntryKeys();
  361. for (std::vector<std::string>::const_iterator it = cacheKeys.begin();
  362. it != cacheKeys.end(); ++it) {
  363. cmState::CacheEntryType t = this->State->GetCacheEntryType(*it);
  364. if (t != cmState::STATIC) {
  365. if (regex.find(it->c_str())) {
  366. entriesToDelete.push_back(*it);
  367. }
  368. }
  369. }
  370. // now remove them from the cache
  371. for (std::vector<std::string>::const_iterator currentEntry =
  372. entriesToDelete.begin();
  373. currentEntry != entriesToDelete.end(); ++currentEntry) {
  374. this->State->RemoveCacheEntry(*currentEntry);
  375. }
  376. } else if (arg.find("-C", 0) == 0) {
  377. std::string path = arg.substr(2);
  378. if (path.empty()) {
  379. ++i;
  380. if (i < args.size()) {
  381. path = args[i];
  382. } else {
  383. cmSystemTools::Error("-C must be followed by a file name.");
  384. return false;
  385. }
  386. }
  387. std::cout << "loading initial cache file " << path << "\n";
  388. this->ReadListFile(args, path.c_str());
  389. } else if (arg.find("-P", 0) == 0) {
  390. i++;
  391. if (i >= args.size()) {
  392. cmSystemTools::Error("-P must be followed by a file name.");
  393. return false;
  394. }
  395. std::string path = args[i];
  396. if (path.empty()) {
  397. cmSystemTools::Error("No cmake script provided.");
  398. return false;
  399. }
  400. this->ReadListFile(args, path.c_str());
  401. } else if (arg.find("--find-package", 0) == 0) {
  402. findPackageMode = true;
  403. }
  404. }
  405. if (findPackageMode) {
  406. return this->FindPackage(args);
  407. }
  408. return true;
  409. }
  410. void cmake::ReadListFile(const std::vector<std::string>& args,
  411. const char* path)
  412. {
  413. // if a generator was not yet created, temporarily create one
  414. cmGlobalGenerator* gg = this->GetGlobalGenerator();
  415. bool created = false;
  416. // if a generator was not specified use a generic one
  417. if (!gg) {
  418. gg = new cmGlobalGenerator(this);
  419. created = true;
  420. }
  421. // read in the list file to fill the cache
  422. if (path) {
  423. this->CurrentSnapshot = this->State->Reset();
  424. std::string homeDir = this->GetHomeDirectory();
  425. std::string homeOutputDir = this->GetHomeOutputDirectory();
  426. this->SetHomeDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  427. this->SetHomeOutputDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  428. cmState::Snapshot snapshot = this->GetCurrentSnapshot();
  429. snapshot.GetDirectory().SetCurrentBinary(
  430. cmSystemTools::GetCurrentWorkingDirectory());
  431. snapshot.GetDirectory().SetCurrentSource(
  432. cmSystemTools::GetCurrentWorkingDirectory());
  433. snapshot.SetDefaultDefinitions();
  434. CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(gg, snapshot));
  435. if (this->GetWorkingMode() != NORMAL_MODE) {
  436. std::string file(cmSystemTools::CollapseFullPath(path));
  437. cmSystemTools::ConvertToUnixSlashes(file);
  438. mf->SetScriptModeFile(file.c_str());
  439. mf->SetArgcArgv(args);
  440. }
  441. if (!mf->ReadListFile(path)) {
  442. cmSystemTools::Error("Error processing file: ", path);
  443. }
  444. this->SetHomeDirectory(homeDir);
  445. this->SetHomeOutputDirectory(homeOutputDir);
  446. }
  447. // free generic one if generated
  448. if (created) {
  449. delete gg;
  450. }
  451. }
  452. bool cmake::FindPackage(const std::vector<std::string>& args)
  453. {
  454. this->SetHomeDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  455. this->SetHomeOutputDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  456. // if a generator was not yet created, temporarily create one
  457. cmGlobalGenerator* gg = new cmGlobalGenerator(this);
  458. this->SetGlobalGenerator(gg);
  459. cmState::Snapshot snapshot = this->GetCurrentSnapshot();
  460. snapshot.GetDirectory().SetCurrentBinary(
  461. cmSystemTools::GetCurrentWorkingDirectory());
  462. snapshot.GetDirectory().SetCurrentSource(
  463. cmSystemTools::GetCurrentWorkingDirectory());
  464. // read in the list file to fill the cache
  465. snapshot.SetDefaultDefinitions();
  466. cmMakefile* mf = new cmMakefile(gg, snapshot);
  467. gg->AddMakefile(mf);
  468. mf->SetArgcArgv(args);
  469. std::string systemFile = mf->GetModulesFile("CMakeFindPackageMode.cmake");
  470. mf->ReadListFile(systemFile.c_str());
  471. std::string language = mf->GetSafeDefinition("LANGUAGE");
  472. std::string mode = mf->GetSafeDefinition("MODE");
  473. std::string packageName = mf->GetSafeDefinition("NAME");
  474. bool packageFound = mf->IsOn("PACKAGE_FOUND");
  475. bool quiet = mf->IsOn("PACKAGE_QUIET");
  476. if (!packageFound) {
  477. if (!quiet) {
  478. printf("%s not found.\n", packageName.c_str());
  479. }
  480. } else if (mode == "EXIST") {
  481. if (!quiet) {
  482. printf("%s found.\n", packageName.c_str());
  483. }
  484. } else if (mode == "COMPILE") {
  485. std::string includes = mf->GetSafeDefinition("PACKAGE_INCLUDE_DIRS");
  486. std::vector<std::string> includeDirs;
  487. cmSystemTools::ExpandListArgument(includes, includeDirs);
  488. gg->CreateGenerationObjects();
  489. cmLocalGenerator* lg = gg->LocalGenerators[0];
  490. std::string includeFlags =
  491. lg->GetIncludeFlags(includeDirs, CM_NULLPTR, language);
  492. std::string definitions = mf->GetSafeDefinition("PACKAGE_DEFINITIONS");
  493. printf("%s %s\n", includeFlags.c_str(), definitions.c_str());
  494. } else if (mode == "LINK") {
  495. const char* targetName = "dummy";
  496. std::vector<std::string> srcs;
  497. cmTarget* tgt = mf->AddExecutable(targetName, srcs, true);
  498. tgt->SetProperty("LINKER_LANGUAGE", language.c_str());
  499. std::string libs = mf->GetSafeDefinition("PACKAGE_LIBRARIES");
  500. std::vector<std::string> libList;
  501. cmSystemTools::ExpandListArgument(libs, libList);
  502. for (std::vector<std::string>::const_iterator libIt = libList.begin();
  503. libIt != libList.end(); ++libIt) {
  504. tgt->AddLinkLibrary(*mf, *libIt, GENERAL_LibraryType);
  505. }
  506. std::string buildType = mf->GetSafeDefinition("CMAKE_BUILD_TYPE");
  507. buildType = cmSystemTools::UpperCase(buildType);
  508. std::string linkLibs;
  509. std::string frameworkPath;
  510. std::string linkPath;
  511. std::string flags;
  512. std::string linkFlags;
  513. gg->CreateGenerationObjects();
  514. cmGeneratorTarget* gtgt = gg->FindGeneratorTarget(tgt->GetName());
  515. cmLocalGenerator* lg = gtgt->GetLocalGenerator();
  516. lg->GetTargetFlags(buildType, linkLibs, flags, linkFlags, frameworkPath,
  517. linkPath, gtgt, false);
  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.", cmState::INTERNAL);
  780. #ifdef CMAKE_BUILD_WITH_CMAKE
  781. this->AddCacheEntry("CMAKE_CTEST_COMMAND",
  782. cmSystemTools::GetCTestCommand().c_str(),
  783. "Path to ctest program executable.", cmState::INTERNAL);
  784. this->AddCacheEntry("CMAKE_CPACK_COMMAND",
  785. cmSystemTools::GetCPackCommand().c_str(),
  786. "Path to cpack program executable.", cmState::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.", cmState::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. (*i)->GetName(), *gen);
  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. cmState::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. cmState::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. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(CMAKE_BOOT_MINGW)
  1195. std::string installedCompiler;
  1196. // Try to find the newest VS installed on the computer and
  1197. // use that as a default if -G is not specified
  1198. const std::string vsregBase =
  1199. "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\";
  1200. std::vector<std::string> vsVerions;
  1201. vsVerions.push_back("VisualStudio\\");
  1202. vsVerions.push_back("VCExpress\\");
  1203. vsVerions.push_back("WDExpress\\");
  1204. struct VSRegistryEntryName
  1205. {
  1206. const char* MSVersion;
  1207. const char* GeneratorName;
  1208. };
  1209. VSRegistryEntryName version[] = {
  1210. /* clang-format needs this comment to break after the opening brace */
  1211. { "7.1", "Visual Studio 7 .NET 2003" },
  1212. { "8.0", "Visual Studio 8 2005" },
  1213. { "9.0", "Visual Studio 9 2008" },
  1214. { "10.0", "Visual Studio 10 2010" },
  1215. { "11.0", "Visual Studio 11 2012" },
  1216. { "12.0", "Visual Studio 12 2013" },
  1217. { "14.0", "Visual Studio 14 2015" },
  1218. { "15.0", "Visual Studio 15" },
  1219. { 0, 0 }
  1220. };
  1221. for (int i = 0; version[i].MSVersion != 0; i++) {
  1222. for (size_t b = 0; b < vsVerions.size(); b++) {
  1223. std::string reg = vsregBase + vsVerions[b] + version[i].MSVersion;
  1224. reg += ";InstallDir]";
  1225. cmSystemTools::ExpandRegistryValues(reg, cmSystemTools::KeyWOW64_32);
  1226. if (!(reg == "/registry")) {
  1227. installedCompiler = version[i].GeneratorName;
  1228. break;
  1229. }
  1230. }
  1231. }
  1232. cmGlobalGenerator* gen =
  1233. this->CreateGlobalGenerator(installedCompiler.c_str());
  1234. if (!gen) {
  1235. gen = new cmGlobalNMakeMakefileGenerator(this);
  1236. }
  1237. this->SetGlobalGenerator(gen);
  1238. std::cout << "-- Building for: " << gen->GetName() << "\n";
  1239. #else
  1240. this->SetGlobalGenerator(new cmGlobalUnixMakefileGenerator3(this));
  1241. #endif
  1242. }
  1243. if (!this->GlobalGenerator) {
  1244. cmSystemTools::Error("Could not create generator");
  1245. return -1;
  1246. }
  1247. }
  1248. const char* genName =
  1249. this->State->GetInitializedCacheValue("CMAKE_GENERATOR");
  1250. if (genName) {
  1251. if (!this->GlobalGenerator->MatchesGeneratorName(genName)) {
  1252. std::string message = "Error: generator : ";
  1253. message += this->GlobalGenerator->GetName();
  1254. message += "\nDoes not match the generator used previously: ";
  1255. message += genName;
  1256. message += "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1257. "directory or choose a different binary directory.";
  1258. cmSystemTools::Error(message.c_str());
  1259. return -2;
  1260. }
  1261. }
  1262. if (!this->State->GetInitializedCacheValue("CMAKE_GENERATOR")) {
  1263. this->AddCacheEntry("CMAKE_GENERATOR",
  1264. this->GlobalGenerator->GetName().c_str(),
  1265. "Name of generator.", cmState::INTERNAL);
  1266. this->AddCacheEntry("CMAKE_EXTRA_GENERATOR",
  1267. this->GlobalGenerator->GetExtraGeneratorName().c_str(),
  1268. "Name of external makefile project generator.",
  1269. cmState::INTERNAL);
  1270. }
  1271. if (const char* platformName =
  1272. this->State->GetInitializedCacheValue("CMAKE_GENERATOR_PLATFORM")) {
  1273. if (this->GeneratorPlatform.empty()) {
  1274. this->GeneratorPlatform = platformName;
  1275. } else if (this->GeneratorPlatform != platformName) {
  1276. std::string message = "Error: generator platform: ";
  1277. message += this->GeneratorPlatform;
  1278. message += "\nDoes not match the platform used previously: ";
  1279. message += platformName;
  1280. message += "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1281. "directory or choose a different binary directory.";
  1282. cmSystemTools::Error(message.c_str());
  1283. return -2;
  1284. }
  1285. } else {
  1286. this->AddCacheEntry("CMAKE_GENERATOR_PLATFORM",
  1287. this->GeneratorPlatform.c_str(),
  1288. "Name of generator platform.", cmState::INTERNAL);
  1289. }
  1290. if (const char* tsName =
  1291. this->State->GetInitializedCacheValue("CMAKE_GENERATOR_TOOLSET")) {
  1292. if (this->GeneratorToolset.empty()) {
  1293. this->GeneratorToolset = tsName;
  1294. } else if (this->GeneratorToolset != tsName) {
  1295. std::string message = "Error: generator toolset: ";
  1296. message += this->GeneratorToolset;
  1297. message += "\nDoes not match the toolset used previously: ";
  1298. message += tsName;
  1299. message += "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1300. "directory or choose a different binary directory.";
  1301. cmSystemTools::Error(message.c_str());
  1302. return -2;
  1303. }
  1304. } else {
  1305. this->AddCacheEntry("CMAKE_GENERATOR_TOOLSET",
  1306. this->GeneratorToolset.c_str(),
  1307. "Name of generator toolset.", cmState::INTERNAL);
  1308. }
  1309. // reset any system configuration information, except for when we are
  1310. // InTryCompile. With TryCompile the system info is taken from the parent's
  1311. // info to save time
  1312. if (!this->State->GetIsInTryCompile()) {
  1313. this->GlobalGenerator->ClearEnabledLanguages();
  1314. this->TruncateOutputLog("CMakeOutput.log");
  1315. this->TruncateOutputLog("CMakeError.log");
  1316. }
  1317. // actually do the configure
  1318. this->GlobalGenerator->Configure();
  1319. // Before saving the cache
  1320. // if the project did not define one of the entries below, add them now
  1321. // so users can edit the values in the cache:
  1322. // We used to always present LIBRARY_OUTPUT_PATH and
  1323. // EXECUTABLE_OUTPUT_PATH. They are now documented as old-style and
  1324. // should no longer be used. Therefore we present them only if the
  1325. // project requires compatibility with CMake 2.4. We detect this
  1326. // here by looking for the old CMAKE_BACKWARDS_COMPATIBILITY
  1327. // variable created when CMP0001 is not set to NEW.
  1328. if (this->State->GetInitializedCacheValue("CMAKE_BACKWARDS_COMPATIBILITY")) {
  1329. if (!this->State->GetInitializedCacheValue("LIBRARY_OUTPUT_PATH")) {
  1330. this->AddCacheEntry(
  1331. "LIBRARY_OUTPUT_PATH", "",
  1332. "Single output directory for building all libraries.", cmState::PATH);
  1333. }
  1334. if (!this->State->GetInitializedCacheValue("EXECUTABLE_OUTPUT_PATH")) {
  1335. this->AddCacheEntry(
  1336. "EXECUTABLE_OUTPUT_PATH", "",
  1337. "Single output directory for building all executables.",
  1338. cmState::PATH);
  1339. }
  1340. }
  1341. cmMakefile* mf = this->GlobalGenerator->GetMakefiles()[0];
  1342. if (mf->IsOn("CTEST_USE_LAUNCHERS") &&
  1343. !this->State->GetGlobalProperty("RULE_LAUNCH_COMPILE")) {
  1344. cmSystemTools::Error(
  1345. "CTEST_USE_LAUNCHERS is enabled, but the "
  1346. "RULE_LAUNCH_COMPILE global property is not defined.\n"
  1347. "Did you forget to include(CTest) in the toplevel "
  1348. "CMakeLists.txt ?");
  1349. }
  1350. // only save the cache if there were no fatal errors
  1351. if (this->GetWorkingMode() == NORMAL_MODE) {
  1352. this->SaveCache(this->GetHomeOutputDirectory());
  1353. }
  1354. if (cmSystemTools::GetErrorOccuredFlag()) {
  1355. return -1;
  1356. }
  1357. return 0;
  1358. }
  1359. void cmake::PreLoadCMakeFiles()
  1360. {
  1361. std::vector<std::string> args;
  1362. std::string pre_load = this->GetHomeDirectory();
  1363. if (!pre_load.empty()) {
  1364. pre_load += "/PreLoad.cmake";
  1365. if (cmSystemTools::FileExists(pre_load.c_str())) {
  1366. this->ReadListFile(args, pre_load.c_str());
  1367. }
  1368. }
  1369. pre_load = this->GetHomeOutputDirectory();
  1370. if (!pre_load.empty()) {
  1371. pre_load += "/PreLoad.cmake";
  1372. if (cmSystemTools::FileExists(pre_load.c_str())) {
  1373. this->ReadListFile(args, pre_load.c_str());
  1374. }
  1375. }
  1376. }
  1377. // handle a command line invocation
  1378. int cmake::Run(const std::vector<std::string>& args, bool noconfigure)
  1379. {
  1380. // Process the arguments
  1381. this->SetArgs(args);
  1382. if (cmSystemTools::GetErrorOccuredFlag()) {
  1383. return -1;
  1384. }
  1385. // If we are given a stamp list file check if it is really out of date.
  1386. if (!this->CheckStampList.empty() &&
  1387. cmakeCheckStampList(this->CheckStampList.c_str())) {
  1388. return 0;
  1389. }
  1390. // If we are given a stamp file check if it is really out of date.
  1391. if (!this->CheckStampFile.empty() &&
  1392. cmakeCheckStampFile(this->CheckStampFile.c_str())) {
  1393. return 0;
  1394. }
  1395. if (this->GetWorkingMode() == NORMAL_MODE) {
  1396. // load the cache
  1397. if (this->LoadCache() < 0) {
  1398. cmSystemTools::Error("Error executing cmake::LoadCache(). Aborting.\n");
  1399. return -1;
  1400. }
  1401. } else {
  1402. this->AddCMakePaths();
  1403. }
  1404. // Add any cache args
  1405. if (!this->SetCacheArgs(args)) {
  1406. cmSystemTools::Error("Problem processing arguments. Aborting.\n");
  1407. return -1;
  1408. }
  1409. // In script mode we terminate after running the script.
  1410. if (this->GetWorkingMode() != NORMAL_MODE) {
  1411. if (cmSystemTools::GetErrorOccuredFlag()) {
  1412. return -1;
  1413. }
  1414. return 0;
  1415. }
  1416. // If MAKEFLAGS are given in the environment, remove the environment
  1417. // variable. This will prevent try-compile from succeeding when it
  1418. // should fail (if "-i" is an option). We cannot simply test
  1419. // whether "-i" is given and remove it because some make programs
  1420. // encode the MAKEFLAGS variable in a strange way.
  1421. if (cmSystemTools::HasEnv("MAKEFLAGS")) {
  1422. cmSystemTools::PutEnv("MAKEFLAGS=");
  1423. }
  1424. this->PreLoadCMakeFiles();
  1425. if (noconfigure) {
  1426. return 0;
  1427. }
  1428. // now run the global generate
  1429. // Check the state of the build system to see if we need to regenerate.
  1430. if (!this->CheckBuildSystem()) {
  1431. return 0;
  1432. }
  1433. int ret = this->Configure();
  1434. if (ret || this->GetWorkingMode() != NORMAL_MODE) {
  1435. #if defined(CMAKE_HAVE_VS_GENERATORS)
  1436. if (!this->VSSolutionFile.empty() && this->GlobalGenerator) {
  1437. // CMake is running to regenerate a Visual Studio build tree
  1438. // during a build from the VS IDE. The build files cannot be
  1439. // regenerated, so we should stop the build.
  1440. cmSystemTools::Message("CMake Configure step failed. "
  1441. "Build files cannot be regenerated correctly. "
  1442. "Attempting to stop IDE build.");
  1443. cmGlobalVisualStudioGenerator* gg =
  1444. static_cast<cmGlobalVisualStudioGenerator*>(this->GlobalGenerator);
  1445. gg->CallVisualStudioMacro(cmGlobalVisualStudioGenerator::MacroStop,
  1446. this->VSSolutionFile.c_str());
  1447. }
  1448. #endif
  1449. return ret;
  1450. }
  1451. ret = this->Generate();
  1452. std::string message = "Build files have been written to: ";
  1453. message += this->GetHomeOutputDirectory();
  1454. this->UpdateProgress(message.c_str(), -1);
  1455. return ret;
  1456. }
  1457. int cmake::Generate()
  1458. {
  1459. if (!this->GlobalGenerator) {
  1460. return -1;
  1461. }
  1462. if (!this->GlobalGenerator->Compute()) {
  1463. return -1;
  1464. }
  1465. this->GlobalGenerator->Generate();
  1466. if (!this->GraphVizFile.empty()) {
  1467. std::cout << "Generate graphviz: " << this->GraphVizFile << std::endl;
  1468. this->GenerateGraphViz(this->GraphVizFile.c_str());
  1469. }
  1470. if (this->WarnUnusedCli) {
  1471. this->RunCheckForUnusedVariables();
  1472. }
  1473. if (cmSystemTools::GetErrorOccuredFlag()) {
  1474. return -1;
  1475. }
  1476. // Save the cache again after a successful Generate so that any internal
  1477. // variables created during Generate are saved. (Specifically target GUIDs
  1478. // for the Visual Studio and Xcode generators.)
  1479. if (this->GetWorkingMode() == NORMAL_MODE) {
  1480. this->SaveCache(this->GetHomeOutputDirectory());
  1481. }
  1482. return 0;
  1483. }
  1484. void cmake::AddCacheEntry(const std::string& key, const char* value,
  1485. const char* helpString, int type)
  1486. {
  1487. this->State->AddCacheEntry(key, value, helpString,
  1488. cmState::CacheEntryType(type));
  1489. this->UnwatchUnusedCli(key);
  1490. }
  1491. const char* cmake::GetCacheDefinition(const std::string& name) const
  1492. {
  1493. return this->State->GetInitializedCacheValue(name);
  1494. }
  1495. void cmake::AddDefaultCommands()
  1496. {
  1497. std::vector<cmCommand*> commands;
  1498. GetBootstrapCommands1(commands);
  1499. GetBootstrapCommands2(commands);
  1500. GetPredefinedCommands(commands);
  1501. for (std::vector<cmCommand*>::iterator i = commands.begin();
  1502. i != commands.end(); ++i) {
  1503. this->State->AddCommand(*i);
  1504. }
  1505. }
  1506. void cmake::AddDefaultGenerators()
  1507. {
  1508. #if defined(_WIN32) && !defined(__CYGWIN__)
  1509. #if !defined(CMAKE_BOOT_MINGW)
  1510. this->Generators.push_back(cmGlobalVisualStudio15Generator::NewFactory());
  1511. this->Generators.push_back(cmGlobalVisualStudio14Generator::NewFactory());
  1512. this->Generators.push_back(cmGlobalVisualStudio12Generator::NewFactory());
  1513. this->Generators.push_back(cmGlobalVisualStudio11Generator::NewFactory());
  1514. this->Generators.push_back(cmGlobalVisualStudio10Generator::NewFactory());
  1515. this->Generators.push_back(cmGlobalVisualStudio9Generator::NewFactory());
  1516. this->Generators.push_back(cmGlobalVisualStudio8Generator::NewFactory());
  1517. this->Generators.push_back(cmGlobalVisualStudio71Generator::NewFactory());
  1518. this->Generators.push_back(cmGlobalBorlandMakefileGenerator::NewFactory());
  1519. this->Generators.push_back(cmGlobalNMakeMakefileGenerator::NewFactory());
  1520. this->Generators.push_back(cmGlobalJOMMakefileGenerator::NewFactory());
  1521. this->Generators.push_back(cmGlobalGhsMultiGenerator::NewFactory());
  1522. #endif
  1523. this->Generators.push_back(cmGlobalMSYSMakefileGenerator::NewFactory());
  1524. this->Generators.push_back(cmGlobalMinGWMakefileGenerator::NewFactory());
  1525. #endif
  1526. this->Generators.push_back(cmGlobalUnixMakefileGenerator3::NewFactory());
  1527. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1528. this->Generators.push_back(cmGlobalNinjaGenerator::NewFactory());
  1529. #endif
  1530. #if defined(CMAKE_USE_WMAKE)
  1531. this->Generators.push_back(cmGlobalWatcomWMakeGenerator::NewFactory());
  1532. #endif
  1533. #ifdef CMAKE_USE_XCODE
  1534. this->Generators.push_back(cmGlobalXCodeGenerator::NewFactory());
  1535. #endif
  1536. }
  1537. bool cmake::ParseCacheEntry(const std::string& entry, std::string& var,
  1538. std::string& value, cmState::CacheEntryType& type)
  1539. {
  1540. return cmState::ParseCacheEntry(entry, var, value, type);
  1541. }
  1542. int cmake::LoadCache()
  1543. {
  1544. // could we not read the cache
  1545. if (!this->LoadCache(this->GetHomeOutputDirectory())) {
  1546. // if it does exist, but isn't readable then warn the user
  1547. std::string cacheFile = this->GetHomeOutputDirectory();
  1548. cacheFile += "/CMakeCache.txt";
  1549. if (cmSystemTools::FileExists(cacheFile.c_str())) {
  1550. cmSystemTools::Error(
  1551. "There is a CMakeCache.txt file for the current binary tree but "
  1552. "cmake does not have permission to read it. Please check the "
  1553. "permissions of the directory you are trying to run CMake on.");
  1554. return -1;
  1555. }
  1556. }
  1557. // setup CMAKE_ROOT and CMAKE_COMMAND
  1558. if (!this->AddCMakePaths()) {
  1559. return -3;
  1560. }
  1561. return 0;
  1562. }
  1563. bool cmake::LoadCache(const std::string& path)
  1564. {
  1565. std::set<std::string> emptySet;
  1566. return this->LoadCache(path, true, emptySet, emptySet);
  1567. }
  1568. bool cmake::LoadCache(const std::string& path, bool internal,
  1569. std::set<std::string>& excludes,
  1570. std::set<std::string>& includes)
  1571. {
  1572. bool result = this->State->LoadCache(path, internal, excludes, includes);
  1573. static const char* entries[] = { "CMAKE_CACHE_MAJOR_VERSION",
  1574. "CMAKE_CACHE_MINOR_VERSION" };
  1575. for (const char* const* nameIt = cmArrayBegin(entries);
  1576. nameIt != cmArrayEnd(entries); ++nameIt) {
  1577. this->UnwatchUnusedCli(*nameIt);
  1578. }
  1579. return result;
  1580. }
  1581. bool cmake::SaveCache(const std::string& path)
  1582. {
  1583. bool result = this->State->SaveCache(path);
  1584. static const char* entries[] = { "CMAKE_CACHE_MAJOR_VERSION",
  1585. "CMAKE_CACHE_MINOR_VERSION",
  1586. "CMAKE_CACHE_PATCH_VERSION",
  1587. "CMAKE_CACHEFILE_DIR" };
  1588. for (const char* const* nameIt = cmArrayBegin(entries);
  1589. nameIt != cmArrayEnd(entries); ++nameIt) {
  1590. this->UnwatchUnusedCli(*nameIt);
  1591. }
  1592. return result;
  1593. }
  1594. bool cmake::DeleteCache(const std::string& path)
  1595. {
  1596. return this->State->DeleteCache(path);
  1597. }
  1598. void cmake::SetProgressCallback(ProgressCallbackType f, void* cd)
  1599. {
  1600. this->ProgressCallback = f;
  1601. this->ProgressCallbackClientData = cd;
  1602. }
  1603. void cmake::UpdateProgress(const char* msg, float prog)
  1604. {
  1605. if (this->ProgressCallback && !this->State->GetIsInTryCompile()) {
  1606. (*this->ProgressCallback)(msg, prog, this->ProgressCallbackClientData);
  1607. return;
  1608. }
  1609. }
  1610. bool cmake::GetIsInTryCompile() const
  1611. {
  1612. return this->State->GetIsInTryCompile();
  1613. }
  1614. void cmake::SetIsInTryCompile(bool b)
  1615. {
  1616. this->State->SetIsInTryCompile(b);
  1617. }
  1618. void cmake::GetGeneratorDocumentation(std::vector<cmDocumentationEntry>& v)
  1619. {
  1620. for (RegisteredGeneratorsVector::const_iterator i = this->Generators.begin();
  1621. i != this->Generators.end(); ++i) {
  1622. cmDocumentationEntry e;
  1623. (*i)->GetDocumentation(e);
  1624. v.push_back(e);
  1625. }
  1626. for (RegisteredExtraGeneratorsVector::const_iterator i =
  1627. this->ExtraGenerators.begin();
  1628. i != this->ExtraGenerators.end(); ++i) {
  1629. const std::string doc = (*i)->GetDocumentation();
  1630. const std::string name = (*i)->GetName();
  1631. // Aliases:
  1632. for (std::vector<std::string>::const_iterator a = (*i)->Aliases.begin();
  1633. a != (*i)->Aliases.end(); ++a) {
  1634. cmDocumentationEntry e;
  1635. e.Name = *a;
  1636. e.Brief = doc;
  1637. v.push_back(e);
  1638. }
  1639. // Full names:
  1640. const std::vector<std::string> generators =
  1641. (*i)->GetSupportedGlobalGenerators();
  1642. for (std::vector<std::string>::const_iterator g = generators.begin();
  1643. g != generators.end(); ++g) {
  1644. cmDocumentationEntry e;
  1645. e.Name =
  1646. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(*g, name);
  1647. e.Brief = doc;
  1648. v.push_back(e);
  1649. }
  1650. }
  1651. }
  1652. void cmake::PrintGeneratorList()
  1653. {
  1654. #ifdef CMAKE_BUILD_WITH_CMAKE
  1655. cmDocumentation doc;
  1656. std::vector<cmDocumentationEntry> generators;
  1657. this->GetGeneratorDocumentation(generators);
  1658. doc.AppendSection("Generators", generators);
  1659. std::cerr << "\n";
  1660. doc.PrintDocumentation(cmDocumentation::ListGenerators, std::cerr);
  1661. #endif
  1662. }
  1663. void cmake::UpdateConversionPathTable()
  1664. {
  1665. // Update the path conversion table with any specified file:
  1666. const char* tablepath =
  1667. this->State->GetInitializedCacheValue("CMAKE_PATH_TRANSLATION_FILE");
  1668. if (tablepath) {
  1669. cmsys::ifstream table(tablepath);
  1670. if (!table) {
  1671. cmSystemTools::Error("CMAKE_PATH_TRANSLATION_FILE set to ", tablepath,
  1672. ". CMake can not open file.");
  1673. cmSystemTools::ReportLastSystemError("CMake can not open file.");
  1674. } else {
  1675. std::string a, b;
  1676. while (!table.eof()) {
  1677. // two entries per line
  1678. table >> a;
  1679. table >> b;
  1680. cmSystemTools::AddTranslationPath(a, b);
  1681. }
  1682. }
  1683. }
  1684. }
  1685. int cmake::CheckBuildSystem()
  1686. {
  1687. // We do not need to rerun CMake. Check dependency integrity.
  1688. const bool verbose = isCMakeVerbose();
  1689. // This method will check the integrity of the build system if the
  1690. // option was given on the command line. It reads the given file to
  1691. // determine whether CMake should rerun.
  1692. // If no file is provided for the check, we have to rerun.
  1693. if (this->CheckBuildSystemArgument.empty()) {
  1694. if (verbose) {
  1695. std::ostringstream msg;
  1696. msg << "Re-run cmake no build system arguments\n";
  1697. cmSystemTools::Stdout(msg.str().c_str());
  1698. }
  1699. return 1;
  1700. }
  1701. // If the file provided does not exist, we have to rerun.
  1702. if (!cmSystemTools::FileExists(this->CheckBuildSystemArgument.c_str())) {
  1703. if (verbose) {
  1704. std::ostringstream msg;
  1705. msg << "Re-run cmake missing file: " << this->CheckBuildSystemArgument
  1706. << "\n";
  1707. cmSystemTools::Stdout(msg.str().c_str());
  1708. }
  1709. return 1;
  1710. }
  1711. // Read the rerun check file and use it to decide whether to do the
  1712. // global generate.
  1713. cmake cm;
  1714. cm.SetHomeDirectory("");
  1715. cm.SetHomeOutputDirectory("");
  1716. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  1717. cmGlobalGenerator gg(&cm);
  1718. CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(&gg, cm.GetCurrentSnapshot()));
  1719. if (!mf->ReadListFile(this->CheckBuildSystemArgument.c_str()) ||
  1720. cmSystemTools::GetErrorOccuredFlag()) {
  1721. if (verbose) {
  1722. std::ostringstream msg;
  1723. msg << "Re-run cmake error reading : " << this->CheckBuildSystemArgument
  1724. << "\n";
  1725. cmSystemTools::Stdout(msg.str().c_str());
  1726. }
  1727. // There was an error reading the file. Just rerun.
  1728. return 1;
  1729. }
  1730. if (this->ClearBuildSystem) {
  1731. // Get the generator used for this build system.
  1732. const char* genName = mf->GetDefinition("CMAKE_DEPENDS_GENERATOR");
  1733. if (!genName || genName[0] == '\0') {
  1734. genName = "Unix Makefiles";
  1735. }
  1736. // Create the generator and use it to clear the dependencies.
  1737. CM_AUTO_PTR<cmGlobalGenerator> ggd(this->CreateGlobalGenerator(genName));
  1738. if (ggd.get()) {
  1739. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  1740. CM_AUTO_PTR<cmMakefile> mfd(
  1741. new cmMakefile(ggd.get(), cm.GetCurrentSnapshot()));
  1742. CM_AUTO_PTR<cmLocalGenerator> lgd(ggd->CreateLocalGenerator(mfd.get()));
  1743. lgd->ClearDependencies(mfd.get(), verbose);
  1744. }
  1745. }
  1746. // If any byproduct of makefile generation is missing we must re-run.
  1747. std::vector<std::string> products;
  1748. if (const char* productStr = mf->GetDefinition("CMAKE_MAKEFILE_PRODUCTS")) {
  1749. cmSystemTools::ExpandListArgument(productStr, products);
  1750. }
  1751. for (std::vector<std::string>::const_iterator pi = products.begin();
  1752. pi != products.end(); ++pi) {
  1753. if (!(cmSystemTools::FileExists(pi->c_str()) ||
  1754. cmSystemTools::FileIsSymlink(*pi))) {
  1755. if (verbose) {
  1756. std::ostringstream msg;
  1757. msg << "Re-run cmake, missing byproduct: " << *pi << "\n";
  1758. cmSystemTools::Stdout(msg.str().c_str());
  1759. }
  1760. return 1;
  1761. }
  1762. }
  1763. // Get the set of dependencies and outputs.
  1764. std::vector<std::string> depends;
  1765. std::vector<std::string> outputs;
  1766. const char* dependsStr = mf->GetDefinition("CMAKE_MAKEFILE_DEPENDS");
  1767. const char* outputsStr = mf->GetDefinition("CMAKE_MAKEFILE_OUTPUTS");
  1768. if (dependsStr && outputsStr) {
  1769. cmSystemTools::ExpandListArgument(dependsStr, depends);
  1770. cmSystemTools::ExpandListArgument(outputsStr, outputs);
  1771. }
  1772. if (depends.empty() || outputs.empty()) {
  1773. // Not enough information was provided to do the test. Just rerun.
  1774. if (verbose) {
  1775. std::ostringstream msg;
  1776. msg << "Re-run cmake no CMAKE_MAKEFILE_DEPENDS "
  1777. "or CMAKE_MAKEFILE_OUTPUTS :\n";
  1778. cmSystemTools::Stdout(msg.str().c_str());
  1779. }
  1780. return 1;
  1781. }
  1782. // Find the newest dependency.
  1783. std::vector<std::string>::iterator dep = depends.begin();
  1784. std::string dep_newest = *dep++;
  1785. for (; dep != depends.end(); ++dep) {
  1786. int result = 0;
  1787. if (this->FileComparison->FileTimeCompare(dep_newest.c_str(), dep->c_str(),
  1788. &result)) {
  1789. if (result < 0) {
  1790. dep_newest = *dep;
  1791. }
  1792. } else {
  1793. if (verbose) {
  1794. std::ostringstream msg;
  1795. msg << "Re-run cmake: build system dependency is missing\n";
  1796. cmSystemTools::Stdout(msg.str().c_str());
  1797. }
  1798. return 1;
  1799. }
  1800. }
  1801. // Find the oldest output.
  1802. std::vector<std::string>::iterator out = outputs.begin();
  1803. std::string out_oldest = *out++;
  1804. for (; out != outputs.end(); ++out) {
  1805. int result = 0;
  1806. if (this->FileComparison->FileTimeCompare(out_oldest.c_str(), out->c_str(),
  1807. &result)) {
  1808. if (result > 0) {
  1809. out_oldest = *out;
  1810. }
  1811. } else {
  1812. if (verbose) {
  1813. std::ostringstream msg;
  1814. msg << "Re-run cmake: build system output is missing\n";
  1815. cmSystemTools::Stdout(msg.str().c_str());
  1816. }
  1817. return 1;
  1818. }
  1819. }
  1820. // If any output is older than any dependency then rerun.
  1821. {
  1822. int result = 0;
  1823. if (!this->FileComparison->FileTimeCompare(out_oldest.c_str(),
  1824. dep_newest.c_str(), &result) ||
  1825. result < 0) {
  1826. if (verbose) {
  1827. std::ostringstream msg;
  1828. msg << "Re-run cmake file: " << out_oldest
  1829. << " older than: " << dep_newest << "\n";
  1830. cmSystemTools::Stdout(msg.str().c_str());
  1831. }
  1832. return 1;
  1833. }
  1834. }
  1835. // No need to rerun.
  1836. return 0;
  1837. }
  1838. void cmake::TruncateOutputLog(const char* fname)
  1839. {
  1840. std::string fullPath = this->GetHomeOutputDirectory();
  1841. fullPath += "/";
  1842. fullPath += fname;
  1843. struct stat st;
  1844. if (::stat(fullPath.c_str(), &st)) {
  1845. return;
  1846. }
  1847. if (!this->State->GetInitializedCacheValue("CMAKE_CACHEFILE_DIR")) {
  1848. cmSystemTools::RemoveFile(fullPath);
  1849. return;
  1850. }
  1851. off_t fsize = st.st_size;
  1852. const off_t maxFileSize = 50 * 1024;
  1853. if (fsize < maxFileSize) {
  1854. // TODO: truncate file
  1855. return;
  1856. }
  1857. }
  1858. inline std::string removeQuotes(const std::string& s)
  1859. {
  1860. if (s[0] == '\"' && s[s.size() - 1] == '\"') {
  1861. return s.substr(1, s.size() - 2);
  1862. }
  1863. return s;
  1864. }
  1865. void cmake::MarkCliAsUsed(const std::string& variable)
  1866. {
  1867. this->UsedCliVariables[variable] = true;
  1868. }
  1869. void cmake::GenerateGraphViz(const char* fileName) const
  1870. {
  1871. #ifdef CMAKE_BUILD_WITH_CMAKE
  1872. CM_AUTO_PTR<cmGraphVizWriter> gvWriter(
  1873. new cmGraphVizWriter(this->GetGlobalGenerator()->GetLocalGenerators()));
  1874. std::string settingsFile = this->GetHomeOutputDirectory();
  1875. settingsFile += "/CMakeGraphVizOptions.cmake";
  1876. std::string fallbackSettingsFile = this->GetHomeDirectory();
  1877. fallbackSettingsFile += "/CMakeGraphVizOptions.cmake";
  1878. gvWriter->ReadSettings(settingsFile.c_str(), fallbackSettingsFile.c_str());
  1879. gvWriter->WritePerTargetFiles(fileName);
  1880. gvWriter->WriteTargetDependersFiles(fileName);
  1881. gvWriter->WriteGlobalFile(fileName);
  1882. #endif
  1883. }
  1884. void cmake::SetProperty(const std::string& prop, const char* value)
  1885. {
  1886. this->State->SetGlobalProperty(prop, value);
  1887. }
  1888. void cmake::AppendProperty(const std::string& prop, const char* value,
  1889. bool asString)
  1890. {
  1891. this->State->AppendGlobalProperty(prop, value, asString);
  1892. }
  1893. const char* cmake::GetProperty(const std::string& prop)
  1894. {
  1895. return this->State->GetGlobalProperty(prop);
  1896. }
  1897. bool cmake::GetPropertyAsBool(const std::string& prop)
  1898. {
  1899. return this->State->GetGlobalPropertyAsBool(prop);
  1900. }
  1901. cmInstalledFile* cmake::GetOrCreateInstalledFile(cmMakefile* mf,
  1902. const std::string& name)
  1903. {
  1904. std::map<std::string, cmInstalledFile>::iterator i =
  1905. this->InstalledFiles.find(name);
  1906. if (i != this->InstalledFiles.end()) {
  1907. cmInstalledFile& file = i->second;
  1908. return &file;
  1909. }
  1910. cmInstalledFile& file = this->InstalledFiles[name];
  1911. file.SetName(mf, name);
  1912. return &file;
  1913. }
  1914. cmInstalledFile const* cmake::GetInstalledFile(const std::string& name) const
  1915. {
  1916. std::map<std::string, cmInstalledFile>::const_iterator i =
  1917. this->InstalledFiles.find(name);
  1918. if (i != this->InstalledFiles.end()) {
  1919. cmInstalledFile const& file = i->second;
  1920. return &file;
  1921. }
  1922. return CM_NULLPTR;
  1923. }
  1924. int cmake::GetSystemInformation(std::vector<std::string>& args)
  1925. {
  1926. // so create the directory
  1927. std::string resultFile;
  1928. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1929. std::string destPath = cwd + "/__cmake_systeminformation";
  1930. cmSystemTools::RemoveADirectory(destPath);
  1931. if (!cmSystemTools::MakeDirectory(destPath.c_str())) {
  1932. std::cerr << "Error: --system-information must be run from a "
  1933. "writable directory!\n";
  1934. return 1;
  1935. }
  1936. // process the arguments
  1937. bool writeToStdout = true;
  1938. for (unsigned int i = 1; i < args.size(); ++i) {
  1939. std::string arg = args[i];
  1940. if (arg.find("-G", 0) == 0) {
  1941. std::string value = arg.substr(2);
  1942. if (value.empty()) {
  1943. ++i;
  1944. if (i >= args.size()) {
  1945. cmSystemTools::Error("No generator specified for -G");
  1946. this->PrintGeneratorList();
  1947. return -1;
  1948. }
  1949. value = args[i];
  1950. }
  1951. cmGlobalGenerator* gen = this->CreateGlobalGenerator(value);
  1952. if (!gen) {
  1953. cmSystemTools::Error("Could not create named generator ",
  1954. value.c_str());
  1955. this->PrintGeneratorList();
  1956. } else {
  1957. this->SetGlobalGenerator(gen);
  1958. }
  1959. }
  1960. // no option assume it is the output file
  1961. else {
  1962. if (!cmSystemTools::FileIsFullPath(arg.c_str())) {
  1963. resultFile = cwd;
  1964. resultFile += "/";
  1965. }
  1966. resultFile += arg;
  1967. writeToStdout = false;
  1968. }
  1969. }
  1970. // we have to find the module directory, so we can copy the files
  1971. this->AddCMakePaths();
  1972. std::string modulesPath = cmSystemTools::GetCMakeRoot();
  1973. modulesPath += "/Modules";
  1974. std::string inFile = modulesPath;
  1975. inFile += "/SystemInformation.cmake";
  1976. std::string outFile = destPath;
  1977. outFile += "/CMakeLists.txt";
  1978. // Copy file
  1979. if (!cmSystemTools::cmCopyFile(inFile.c_str(), outFile.c_str())) {
  1980. std::cerr << "Error copying file \"" << inFile << "\" to \"" << outFile
  1981. << "\".\n";
  1982. return 1;
  1983. }
  1984. // do we write to a file or to stdout?
  1985. if (resultFile.empty()) {
  1986. resultFile = cwd;
  1987. resultFile += "/__cmake_systeminformation/results.txt";
  1988. }
  1989. // now run cmake on the CMakeLists file
  1990. cmSystemTools::ChangeDirectory(destPath);
  1991. std::vector<std::string> args2;
  1992. args2.push_back(args[0]);
  1993. args2.push_back(destPath);
  1994. std::string resultArg = "-DRESULT_FILE=";
  1995. resultArg += resultFile;
  1996. args2.push_back(resultArg);
  1997. int res = this->Run(args2, false);
  1998. if (res != 0) {
  1999. std::cerr << "Error: --system-information failed on internal CMake!\n";
  2000. return res;
  2001. }
  2002. // change back to the original directory
  2003. cmSystemTools::ChangeDirectory(cwd);
  2004. // echo results to stdout if needed
  2005. if (writeToStdout) {
  2006. FILE* fin = cmsys::SystemTools::Fopen(resultFile, "r");
  2007. if (fin) {
  2008. const int bufferSize = 4096;
  2009. char buffer[bufferSize];
  2010. size_t n;
  2011. while ((n = fread(buffer, 1, bufferSize, fin)) > 0) {
  2012. for (char* c = buffer; c < buffer + n; ++c) {
  2013. putc(*c, stdout);
  2014. }
  2015. fflush(stdout);
  2016. }
  2017. fclose(fin);
  2018. }
  2019. }
  2020. // clean up the directory
  2021. cmSystemTools::RemoveADirectory(destPath);
  2022. return 0;
  2023. }
  2024. static bool cmakeCheckStampFile(const char* stampName)
  2025. {
  2026. // The stamp file does not exist. Use the stamp dependencies to
  2027. // determine whether it is really out of date. This works in
  2028. // conjunction with cmLocalVisualStudio7Generator to avoid
  2029. // repeatedly re-running CMake when the user rebuilds the entire
  2030. // solution.
  2031. std::string stampDepends = stampName;
  2032. stampDepends += ".depend";
  2033. #if defined(_WIN32) || defined(__CYGWIN__)
  2034. cmsys::ifstream fin(stampDepends.c_str(), std::ios::in | std::ios::binary);
  2035. #else
  2036. cmsys::ifstream fin(stampDepends.c_str());
  2037. #endif
  2038. if (!fin) {
  2039. // The stamp dependencies file cannot be read. Just assume the
  2040. // build system is really out of date.
  2041. std::cout << "CMake is re-running because " << stampName
  2042. << " dependency file is missing.\n";
  2043. return false;
  2044. }
  2045. // Compare the stamp dependencies against the dependency file itself.
  2046. cmFileTimeComparison ftc;
  2047. std::string dep;
  2048. while (cmSystemTools::GetLineFromStream(fin, dep)) {
  2049. int result;
  2050. if (!dep.empty() && dep[0] != '#' &&
  2051. (!ftc.FileTimeCompare(stampDepends.c_str(), dep.c_str(), &result) ||
  2052. result < 0)) {
  2053. // The stamp depends file is older than this dependency. The
  2054. // build system is really out of date.
  2055. std::cout << "CMake is re-running because " << stampName
  2056. << " is out-of-date.\n";
  2057. std::cout << " the file '" << dep << "'\n";
  2058. std::cout << " is newer than '" << stampDepends << "'\n";
  2059. std::cout << " result='" << result << "'\n";
  2060. return false;
  2061. }
  2062. }
  2063. // The build system is up to date. The stamp file has been removed
  2064. // by the VS IDE due to a "rebuild" request. Restore it atomically.
  2065. std::ostringstream stampTempStream;
  2066. stampTempStream << stampName << ".tmp" << cmSystemTools::RandomSeed();
  2067. std::string stampTempString = stampTempStream.str();
  2068. const char* stampTemp = stampTempString.c_str();
  2069. {
  2070. // TODO: Teach cmGeneratedFileStream to use a random temp file (with
  2071. // multiple tries in unlikely case of conflict) and use that here.
  2072. cmsys::ofstream stamp(stampTemp);
  2073. stamp << "# CMake generation timestamp file for this directory.\n";
  2074. }
  2075. if (cmSystemTools::RenameFile(stampTemp, stampName)) {
  2076. // Notify the user why CMake is not re-running. It is safe to
  2077. // just print to stdout here because this code is only reachable
  2078. // through an undocumented flag used by the VS generator.
  2079. std::cout << "CMake does not need to re-run because " << stampName
  2080. << " is up-to-date.\n";
  2081. return true;
  2082. }
  2083. cmSystemTools::RemoveFile(stampTemp);
  2084. cmSystemTools::Error("Cannot restore timestamp ", stampName);
  2085. return false;
  2086. }
  2087. static bool cmakeCheckStampList(const char* stampList)
  2088. {
  2089. // If the stamp list does not exist CMake must rerun to generate it.
  2090. if (!cmSystemTools::FileExists(stampList)) {
  2091. std::cout << "CMake is re-running because generate.stamp.list "
  2092. << "is missing.\n";
  2093. return false;
  2094. }
  2095. cmsys::ifstream fin(stampList);
  2096. if (!fin) {
  2097. std::cout << "CMake is re-running because generate.stamp.list "
  2098. << "could not be read.\n";
  2099. return false;
  2100. }
  2101. // Check each stamp.
  2102. std::string stampName;
  2103. while (cmSystemTools::GetLineFromStream(fin, stampName)) {
  2104. if (!cmakeCheckStampFile(stampName.c_str())) {
  2105. return false;
  2106. }
  2107. }
  2108. return true;
  2109. }
  2110. void cmake::IssueMessage(cmake::MessageType t, std::string const& text,
  2111. cmListFileBacktrace const& backtrace) const
  2112. {
  2113. this->Messenger->IssueMessage(t, text, backtrace);
  2114. }
  2115. std::vector<std::string> cmake::GetDebugConfigs()
  2116. {
  2117. std::vector<std::string> configs;
  2118. if (const char* config_list =
  2119. this->State->GetGlobalProperty("DEBUG_CONFIGURATIONS")) {
  2120. // Expand the specified list and convert to upper-case.
  2121. cmSystemTools::ExpandListArgument(config_list, configs);
  2122. std::transform(configs.begin(), configs.end(), configs.begin(),
  2123. cmSystemTools::UpperCase);
  2124. }
  2125. // If no configurations were specified, use a default list.
  2126. if (configs.empty()) {
  2127. configs.push_back("DEBUG");
  2128. }
  2129. return configs;
  2130. }
  2131. cmMessenger* cmake::GetMessenger() const
  2132. {
  2133. return this->Messenger;
  2134. }
  2135. int cmake::Build(const std::string& dir, const std::string& target,
  2136. const std::string& config,
  2137. const std::vector<std::string>& nativeOptions, bool clean)
  2138. {
  2139. this->SetHomeDirectory("");
  2140. this->SetHomeOutputDirectory("");
  2141. if (!cmSystemTools::FileIsDirectory(dir)) {
  2142. std::cerr << "Error: " << dir << " is not a directory\n";
  2143. return 1;
  2144. }
  2145. std::string cachePath = FindCacheFile(dir);
  2146. if (!this->LoadCache(cachePath)) {
  2147. std::cerr << "Error: could not load cache\n";
  2148. return 1;
  2149. }
  2150. const char* cachedGenerator =
  2151. this->State->GetCacheEntryValue("CMAKE_GENERATOR");
  2152. if (!cachedGenerator) {
  2153. std::cerr << "Error: could not find CMAKE_GENERATOR in Cache\n";
  2154. return 1;
  2155. }
  2156. CM_AUTO_PTR<cmGlobalGenerator> gen(
  2157. this->CreateGlobalGenerator(cachedGenerator));
  2158. if (!gen.get()) {
  2159. std::cerr << "Error: could create CMAKE_GENERATOR \"" << cachedGenerator
  2160. << "\"\n";
  2161. return 1;
  2162. }
  2163. std::string output;
  2164. std::string projName;
  2165. const char* cachedProjectName =
  2166. this->State->GetCacheEntryValue("CMAKE_PROJECT_NAME");
  2167. if (!cachedProjectName) {
  2168. std::cerr << "Error: could not find CMAKE_PROJECT_NAME in Cache\n";
  2169. return 1;
  2170. }
  2171. projName = cachedProjectName;
  2172. bool verbose = false;
  2173. const char* cachedVerbose =
  2174. this->State->GetCacheEntryValue("CMAKE_VERBOSE_MAKEFILE");
  2175. if (cachedVerbose) {
  2176. verbose = cmSystemTools::IsOn(cachedVerbose);
  2177. }
  2178. return gen->Build("", dir, projName, target, output, "", config, clean,
  2179. false, verbose, 0, cmSystemTools::OUTPUT_PASSTHROUGH,
  2180. nativeOptions);
  2181. }
  2182. void cmake::WatchUnusedCli(const std::string& var)
  2183. {
  2184. #ifdef CMAKE_BUILD_WITH_CMAKE
  2185. this->VariableWatch->AddWatch(var, cmWarnUnusedCliWarning, this);
  2186. if (this->UsedCliVariables.find(var) == this->UsedCliVariables.end()) {
  2187. this->UsedCliVariables[var] = false;
  2188. }
  2189. #endif
  2190. }
  2191. void cmake::UnwatchUnusedCli(const std::string& var)
  2192. {
  2193. #ifdef CMAKE_BUILD_WITH_CMAKE
  2194. this->VariableWatch->RemoveWatch(var, cmWarnUnusedCliWarning);
  2195. this->UsedCliVariables.erase(var);
  2196. #endif
  2197. }
  2198. void cmake::RunCheckForUnusedVariables()
  2199. {
  2200. #ifdef CMAKE_BUILD_WITH_CMAKE
  2201. bool haveUnused = false;
  2202. std::ostringstream msg;
  2203. msg << "Manually-specified variables were not used by the project:";
  2204. for (std::map<std::string, bool>::const_iterator it =
  2205. this->UsedCliVariables.begin();
  2206. it != this->UsedCliVariables.end(); ++it) {
  2207. if (!it->second) {
  2208. haveUnused = true;
  2209. msg << "\n " << it->first;
  2210. }
  2211. }
  2212. if (haveUnused) {
  2213. this->IssueMessage(cmake::WARNING, msg.str());
  2214. }
  2215. #endif
  2216. }
  2217. bool cmake::GetSuppressDevWarnings() const
  2218. {
  2219. return this->Messenger->GetSuppressDevWarnings();
  2220. }
  2221. void cmake::SetSuppressDevWarnings(bool b)
  2222. {
  2223. std::string value;
  2224. // equivalent to -Wno-dev
  2225. if (b) {
  2226. value = "TRUE";
  2227. }
  2228. // equivalent to -Wdev
  2229. else {
  2230. value = "FALSE";
  2231. }
  2232. this->AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", value.c_str(),
  2233. "Suppress Warnings that are meant for"
  2234. " the author of the CMakeLists.txt files.",
  2235. cmState::INTERNAL);
  2236. }
  2237. bool cmake::GetSuppressDeprecatedWarnings() const
  2238. {
  2239. return this->Messenger->GetSuppressDeprecatedWarnings();
  2240. }
  2241. void cmake::SetSuppressDeprecatedWarnings(bool b)
  2242. {
  2243. std::string value;
  2244. // equivalent to -Wno-deprecated
  2245. if (b) {
  2246. value = "FALSE";
  2247. }
  2248. // equivalent to -Wdeprecated
  2249. else {
  2250. value = "TRUE";
  2251. }
  2252. this->AddCacheEntry("CMAKE_WARN_DEPRECATED", value.c_str(),
  2253. "Whether to issue warnings for deprecated "
  2254. "functionality.",
  2255. cmState::INTERNAL);
  2256. }
  2257. bool cmake::GetDevWarningsAsErrors() const
  2258. {
  2259. return this->Messenger->GetDevWarningsAsErrors();
  2260. }
  2261. void cmake::SetDevWarningsAsErrors(bool b)
  2262. {
  2263. std::string value;
  2264. // equivalent to -Werror=dev
  2265. if (b) {
  2266. value = "FALSE";
  2267. }
  2268. // equivalent to -Wno-error=dev
  2269. else {
  2270. value = "TRUE";
  2271. }
  2272. this->AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_ERRORS", value.c_str(),
  2273. "Suppress errors that are meant for"
  2274. " the author of the CMakeLists.txt files.",
  2275. cmState::INTERNAL);
  2276. }
  2277. bool cmake::GetDeprecatedWarningsAsErrors() const
  2278. {
  2279. return this->Messenger->GetDeprecatedWarningsAsErrors();
  2280. }
  2281. void cmake::SetDeprecatedWarningsAsErrors(bool b)
  2282. {
  2283. std::string value;
  2284. // equivalent to -Werror=deprecated
  2285. if (b) {
  2286. value = "TRUE";
  2287. }
  2288. // equivalent to -Wno-error=deprecated
  2289. else {
  2290. value = "FALSE";
  2291. }
  2292. this->AddCacheEntry("CMAKE_ERROR_DEPRECATED", value.c_str(),
  2293. "Whether to issue deprecation errors for macros"
  2294. " and functions.",
  2295. cmState::INTERNAL);
  2296. }