cmake.cxx 82 KB

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