cmFindPackageCommand.cxx 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320
  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 "cmFindPackageCommand.h"
  4. #include "cmSystemTools.h"
  5. #include "cmsys/Directory.hxx"
  6. #include "cmsys/FStream.hxx"
  7. #include "cmsys/Glob.hxx"
  8. #include "cmsys/RegularExpression.hxx"
  9. #include "cmsys/String.h"
  10. #include <algorithm>
  11. #include <assert.h>
  12. #include <deque>
  13. #include <functional>
  14. #include <iterator>
  15. #include <sstream>
  16. #include <stdio.h>
  17. #include <string.h>
  18. #include <utility>
  19. #include "cm_memory.hxx"
  20. #include "cmAlgorithms.h"
  21. #include "cmMakefile.h"
  22. #include "cmMessageType.h"
  23. #include "cmPolicies.h"
  24. #include "cmRange.h"
  25. #include "cmSearchPath.h"
  26. #include "cmState.h"
  27. #include "cmStateTypes.h"
  28. #include "cmStringAlgorithms.h"
  29. #include "cmVersion.h"
  30. #if defined(__HAIKU__)
  31. # include <FindDirectory.h>
  32. # include <StorageDefs.h>
  33. #endif
  34. class cmExecutionStatus;
  35. class cmFileList;
  36. cmFindPackageCommand::PathLabel cmFindPackageCommand::PathLabel::UserRegistry(
  37. "PACKAGE_REGISTRY");
  38. cmFindPackageCommand::PathLabel cmFindPackageCommand::PathLabel::Builds(
  39. "BUILDS");
  40. cmFindPackageCommand::PathLabel
  41. cmFindPackageCommand::PathLabel::SystemRegistry("SYSTEM_PACKAGE_REGISTRY");
  42. struct StrverscmpGreater
  43. {
  44. bool operator()(const std::string& lhs, const std::string& rhs) const
  45. {
  46. return cmSystemTools::strverscmp(lhs, rhs) > 0;
  47. }
  48. };
  49. struct StrverscmpLesser
  50. {
  51. bool operator()(const std::string& lhs, const std::string& rhs) const
  52. {
  53. return cmSystemTools::strverscmp(lhs, rhs) < 0;
  54. }
  55. };
  56. void cmFindPackageCommand::Sort(std::vector<std::string>::iterator begin,
  57. std::vector<std::string>::iterator end,
  58. SortOrderType order, SortDirectionType dir)
  59. {
  60. if (order == Name_order) {
  61. if (dir == Dec) {
  62. std::sort(begin, end, std::greater<std::string>());
  63. } else {
  64. std::sort(begin, end);
  65. }
  66. } else if (order == Natural)
  67. // natural order uses letters and numbers (contiguous numbers digit are
  68. // compared such that e.g. 000 00 < 01 < 010 < 09 < 0 < 1 < 9 < 10
  69. {
  70. if (dir == Dec) {
  71. std::sort(begin, end, StrverscmpGreater());
  72. } else {
  73. std::sort(begin, end, StrverscmpLesser());
  74. }
  75. }
  76. // else do not sort
  77. }
  78. cmFindPackageCommand::cmFindPackageCommand()
  79. {
  80. this->CMakePathName = "PACKAGE";
  81. this->Quiet = false;
  82. this->Required = false;
  83. this->NoUserRegistry = false;
  84. this->NoSystemRegistry = false;
  85. this->UseConfigFiles = true;
  86. this->UseFindModules = true;
  87. this->DebugMode = false;
  88. this->UseLib32Paths = false;
  89. this->UseLib64Paths = false;
  90. this->UseLibx32Paths = false;
  91. this->UseRealPath = false;
  92. this->PolicyScope = true;
  93. this->VersionMajor = 0;
  94. this->VersionMinor = 0;
  95. this->VersionPatch = 0;
  96. this->VersionTweak = 0;
  97. this->VersionCount = 0;
  98. this->VersionExact = false;
  99. this->VersionFoundMajor = 0;
  100. this->VersionFoundMinor = 0;
  101. this->VersionFoundPatch = 0;
  102. this->VersionFoundTweak = 0;
  103. this->VersionFoundCount = 0;
  104. this->RequiredCMakeVersion = 0;
  105. this->SortOrder = None;
  106. this->SortDirection = Asc;
  107. this->AppendSearchPathGroups();
  108. this->DeprecatedFindModules["Qt"] = cmPolicies::CMP0084;
  109. }
  110. void cmFindPackageCommand::AppendSearchPathGroups()
  111. {
  112. std::vector<cmFindCommon::PathLabel>* labels;
  113. // Update the All group with new paths
  114. labels = &this->PathGroupLabelMap[PathGroup::All];
  115. labels->insert(
  116. std::find(labels->begin(), labels->end(), PathLabel::CMakeSystem),
  117. PathLabel::UserRegistry);
  118. labels->insert(
  119. std::find(labels->begin(), labels->end(), PathLabel::CMakeSystem),
  120. PathLabel::Builds);
  121. labels->insert(std::find(labels->begin(), labels->end(), PathLabel::Guess),
  122. PathLabel::SystemRegistry);
  123. // Create the new path objects
  124. this->LabeledPaths.insert(
  125. std::make_pair(PathLabel::UserRegistry, cmSearchPath(this)));
  126. this->LabeledPaths.insert(
  127. std::make_pair(PathLabel::Builds, cmSearchPath(this)));
  128. this->LabeledPaths.insert(
  129. std::make_pair(PathLabel::SystemRegistry, cmSearchPath(this)));
  130. }
  131. bool cmFindPackageCommand::InitialPass(std::vector<std::string> const& args,
  132. cmExecutionStatus&)
  133. {
  134. if (args.empty()) {
  135. this->SetError("called with incorrect number of arguments");
  136. return false;
  137. }
  138. // Lookup required version of CMake.
  139. if (const char* rv =
  140. this->Makefile->GetDefinition("CMAKE_MINIMUM_REQUIRED_VERSION")) {
  141. unsigned int v[3] = { 0, 0, 0 };
  142. sscanf(rv, "%u.%u.%u", &v[0], &v[1], &v[2]);
  143. this->RequiredCMakeVersion = CMake_VERSION_ENCODE(v[0], v[1], v[2]);
  144. }
  145. // Check for debug mode.
  146. this->DebugMode = this->Makefile->IsOn("CMAKE_FIND_DEBUG_MODE");
  147. // Lookup target architecture, if any.
  148. if (const char* arch =
  149. this->Makefile->GetDefinition("CMAKE_LIBRARY_ARCHITECTURE")) {
  150. this->LibraryArchitecture = arch;
  151. }
  152. // Lookup whether lib32 paths should be used.
  153. if (this->Makefile->PlatformIs32Bit() &&
  154. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  155. "FIND_LIBRARY_USE_LIB32_PATHS")) {
  156. this->UseLib32Paths = true;
  157. }
  158. // Lookup whether lib64 paths should be used.
  159. if (this->Makefile->PlatformIs64Bit() &&
  160. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  161. "FIND_LIBRARY_USE_LIB64_PATHS")) {
  162. this->UseLib64Paths = true;
  163. }
  164. // Lookup whether libx32 paths should be used.
  165. if (this->Makefile->PlatformIsx32() &&
  166. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  167. "FIND_LIBRARY_USE_LIBX32_PATHS")) {
  168. this->UseLibx32Paths = true;
  169. }
  170. // Check if User Package Registry should be disabled
  171. // The `CMAKE_FIND_USE_PACKAGE_REGISTRY` has
  172. // priority over the deprecated CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY
  173. if (const char* def =
  174. this->Makefile->GetDefinition("CMAKE_FIND_USE_PACKAGE_REGISTRY")) {
  175. this->NoUserRegistry = !cmIsOn(def);
  176. } else if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY")) {
  177. this->NoUserRegistry = true;
  178. }
  179. // Check if System Package Registry should be disabled
  180. if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY")) {
  181. this->NoSystemRegistry = true;
  182. }
  183. // Check whether we should resolve symlinks when finding packages
  184. if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_RESOLVE_SYMLINKS")) {
  185. this->UseRealPath = true;
  186. }
  187. // Check if Sorting should be enabled
  188. if (const char* so =
  189. this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_SORT_ORDER")) {
  190. if (strcmp(so, "NAME") == 0) {
  191. this->SortOrder = Name_order;
  192. } else if (strcmp(so, "NATURAL") == 0) {
  193. this->SortOrder = Natural;
  194. } else {
  195. this->SortOrder = None;
  196. }
  197. }
  198. if (const char* sd =
  199. this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_SORT_DIRECTION")) {
  200. this->SortDirection = strcmp(sd, "ASC") == 0 ? Asc : Dec;
  201. }
  202. // Find what search path locations have been enabled/disable
  203. this->SelectDefaultSearchModes();
  204. // Find the current root path mode.
  205. this->SelectDefaultRootPathMode();
  206. // Find the current bundle/framework search policy.
  207. this->SelectDefaultMacMode();
  208. // Record options.
  209. this->Name = args[0];
  210. std::string components;
  211. const char* components_sep = "";
  212. std::set<std::string> requiredComponents;
  213. std::set<std::string> optionalComponents;
  214. // Always search directly in a generated path.
  215. this->SearchPathSuffixes.emplace_back();
  216. // Parse the arguments.
  217. enum Doing
  218. {
  219. DoingNone,
  220. DoingComponents,
  221. DoingOptionalComponents,
  222. DoingNames,
  223. DoingPaths,
  224. DoingPathSuffixes,
  225. DoingConfigs,
  226. DoingHints
  227. };
  228. Doing doing = DoingNone;
  229. cmsys::RegularExpression version("^[0-9.]+$");
  230. bool haveVersion = false;
  231. std::set<unsigned int> configArgs;
  232. std::set<unsigned int> moduleArgs;
  233. for (unsigned int i = 1; i < args.size(); ++i) {
  234. if (args[i] == "QUIET") {
  235. this->Quiet = true;
  236. doing = DoingNone;
  237. } else if (args[i] == "EXACT") {
  238. this->VersionExact = true;
  239. doing = DoingNone;
  240. } else if (args[i] == "MODULE") {
  241. moduleArgs.insert(i);
  242. doing = DoingNone;
  243. } else if (args[i] == "CONFIG") {
  244. configArgs.insert(i);
  245. doing = DoingNone;
  246. } else if (args[i] == "NO_MODULE") {
  247. configArgs.insert(i);
  248. doing = DoingNone;
  249. } else if (args[i] == "REQUIRED") {
  250. this->Required = true;
  251. doing = DoingComponents;
  252. } else if (args[i] == "COMPONENTS") {
  253. doing = DoingComponents;
  254. } else if (args[i] == "OPTIONAL_COMPONENTS") {
  255. doing = DoingOptionalComponents;
  256. } else if (args[i] == "NAMES") {
  257. configArgs.insert(i);
  258. doing = DoingNames;
  259. } else if (args[i] == "PATHS") {
  260. configArgs.insert(i);
  261. doing = DoingPaths;
  262. } else if (args[i] == "HINTS") {
  263. configArgs.insert(i);
  264. doing = DoingHints;
  265. } else if (args[i] == "PATH_SUFFIXES") {
  266. configArgs.insert(i);
  267. doing = DoingPathSuffixes;
  268. } else if (args[i] == "CONFIGS") {
  269. configArgs.insert(i);
  270. doing = DoingConfigs;
  271. } else if (args[i] == "NO_POLICY_SCOPE") {
  272. this->PolicyScope = false;
  273. doing = DoingNone;
  274. } else if (args[i] == "NO_CMAKE_PACKAGE_REGISTRY") {
  275. this->NoUserRegistry = true;
  276. configArgs.insert(i);
  277. doing = DoingNone;
  278. } else if (args[i] == "NO_CMAKE_SYSTEM_PACKAGE_REGISTRY") {
  279. this->NoSystemRegistry = true;
  280. configArgs.insert(i);
  281. doing = DoingNone;
  282. } else if (args[i] == "NO_CMAKE_BUILDS_PATH") {
  283. // Ignore legacy option.
  284. configArgs.insert(i);
  285. doing = DoingNone;
  286. } else if (this->CheckCommonArgument(args[i])) {
  287. configArgs.insert(i);
  288. doing = DoingNone;
  289. } else if ((doing == DoingComponents) ||
  290. (doing == DoingOptionalComponents)) {
  291. // Set a variable telling the find script whether this component
  292. // is required.
  293. const char* isRequired = "1";
  294. if (doing == DoingOptionalComponents) {
  295. isRequired = "0";
  296. optionalComponents.insert(args[i]);
  297. } else {
  298. requiredComponents.insert(args[i]);
  299. }
  300. std::string req_var = this->Name + "_FIND_REQUIRED_" + args[i];
  301. this->AddFindDefinition(req_var, isRequired);
  302. // Append to the list of required components.
  303. components += components_sep;
  304. components += args[i];
  305. components_sep = ";";
  306. } else if (doing == DoingNames) {
  307. this->Names.push_back(args[i]);
  308. } else if (doing == DoingPaths) {
  309. this->UserGuessArgs.push_back(args[i]);
  310. } else if (doing == DoingHints) {
  311. this->UserHintsArgs.push_back(args[i]);
  312. } else if (doing == DoingPathSuffixes) {
  313. this->AddPathSuffix(args[i]);
  314. } else if (doing == DoingConfigs) {
  315. if (args[i].find_first_of(":/\\") != std::string::npos ||
  316. cmSystemTools::GetFilenameLastExtension(args[i]) != ".cmake") {
  317. std::ostringstream e;
  318. e << "given CONFIGS option followed by invalid file name \"" << args[i]
  319. << "\". The names given must be file names without "
  320. << "a path and with a \".cmake\" extension.";
  321. this->SetError(e.str());
  322. return false;
  323. }
  324. this->Configs.push_back(args[i]);
  325. } else if (!haveVersion && version.find(args[i])) {
  326. haveVersion = true;
  327. this->Version = args[i];
  328. } else {
  329. std::ostringstream e;
  330. e << "called with invalid argument \"" << args[i] << "\"";
  331. this->SetError(e.str());
  332. return false;
  333. }
  334. }
  335. std::vector<std::string> doubledComponents;
  336. std::set_intersection(requiredComponents.begin(), requiredComponents.end(),
  337. optionalComponents.begin(), optionalComponents.end(),
  338. std::back_inserter(doubledComponents));
  339. if (!doubledComponents.empty()) {
  340. std::ostringstream e;
  341. e << "called with components that are both required and optional:\n";
  342. e << cmWrap(" ", doubledComponents, "", "\n") << "\n";
  343. this->SetError(e.str());
  344. return false;
  345. }
  346. // Maybe choose one mode exclusively.
  347. this->UseFindModules = configArgs.empty();
  348. this->UseConfigFiles = moduleArgs.empty();
  349. if (!this->UseFindModules && !this->UseConfigFiles) {
  350. std::ostringstream e;
  351. e << "given options exclusive to Module mode:\n";
  352. for (unsigned int si : moduleArgs) {
  353. e << " " << args[si] << "\n";
  354. }
  355. e << "and options exclusive to Config mode:\n";
  356. for (unsigned int si : configArgs) {
  357. e << " " << args[si] << "\n";
  358. }
  359. e << "The options are incompatible.";
  360. this->SetError(e.str());
  361. return false;
  362. }
  363. // Ignore EXACT with no version.
  364. if (this->Version.empty() && this->VersionExact) {
  365. this->VersionExact = false;
  366. this->Makefile->IssueMessage(
  367. MessageType::AUTHOR_WARNING,
  368. "Ignoring EXACT since no version is requested.");
  369. }
  370. if (this->Version.empty() || components.empty()) {
  371. // Check whether we are recursing inside "Find<name>.cmake" within
  372. // another find_package(<name>) call.
  373. std::string mod = this->Name;
  374. mod += "_FIND_MODULE";
  375. if (this->Makefile->IsOn(mod)) {
  376. if (this->Version.empty()) {
  377. // Get version information from the outer call if necessary.
  378. // Requested version string.
  379. std::string ver = this->Name;
  380. ver += "_FIND_VERSION";
  381. this->Version = this->Makefile->GetSafeDefinition(ver);
  382. // Whether an exact version is required.
  383. std::string exact = this->Name;
  384. exact += "_FIND_VERSION_EXACT";
  385. this->VersionExact = this->Makefile->IsOn(exact);
  386. }
  387. if (components.empty()) {
  388. std::string components_var = this->Name + "_FIND_COMPONENTS";
  389. components = this->Makefile->GetSafeDefinition(components_var);
  390. }
  391. }
  392. }
  393. if (!this->Version.empty()) {
  394. // Try to parse the version number and store the results that were
  395. // successfully parsed.
  396. unsigned int parsed_major;
  397. unsigned int parsed_minor;
  398. unsigned int parsed_patch;
  399. unsigned int parsed_tweak;
  400. this->VersionCount =
  401. sscanf(this->Version.c_str(), "%u.%u.%u.%u", &parsed_major,
  402. &parsed_minor, &parsed_patch, &parsed_tweak);
  403. switch (this->VersionCount) {
  404. case 4:
  405. this->VersionTweak = parsed_tweak;
  406. CM_FALLTHROUGH;
  407. case 3:
  408. this->VersionPatch = parsed_patch;
  409. CM_FALLTHROUGH;
  410. case 2:
  411. this->VersionMinor = parsed_minor;
  412. CM_FALLTHROUGH;
  413. case 1:
  414. this->VersionMajor = parsed_major;
  415. CM_FALLTHROUGH;
  416. default:
  417. break;
  418. }
  419. }
  420. std::string disableFindPackageVar = "CMAKE_DISABLE_FIND_PACKAGE_";
  421. disableFindPackageVar += this->Name;
  422. if (this->Makefile->IsOn(disableFindPackageVar)) {
  423. if (this->Required) {
  424. std::ostringstream e;
  425. e << "for module " << this->Name << " called with REQUIRED, but "
  426. << disableFindPackageVar
  427. << " is enabled. A REQUIRED package cannot be disabled.";
  428. this->SetError(e.str());
  429. return false;
  430. }
  431. return true;
  432. }
  433. {
  434. // Allocate a PACKAGE_ROOT_PATH for the current find_package call.
  435. this->Makefile->FindPackageRootPathStack.emplace_back();
  436. std::vector<std::string>& rootPaths =
  437. this->Makefile->FindPackageRootPathStack.back();
  438. // Add root paths from <PackageName>_ROOT CMake and environment variables,
  439. // subject to CMP0074.
  440. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0074)) {
  441. case cmPolicies::WARN:
  442. this->Makefile->MaybeWarnCMP0074(this->Name);
  443. CM_FALLTHROUGH;
  444. case cmPolicies::OLD:
  445. // OLD behavior is to ignore the <pkg>_ROOT variables.
  446. break;
  447. case cmPolicies::REQUIRED_IF_USED:
  448. case cmPolicies::REQUIRED_ALWAYS:
  449. this->Makefile->IssueMessage(
  450. MessageType::FATAL_ERROR,
  451. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0074));
  452. break;
  453. case cmPolicies::NEW: {
  454. // NEW behavior is to honor the <pkg>_ROOT variables.
  455. std::string const rootVar = this->Name + "_ROOT";
  456. if (const char* pkgRoot = this->Makefile->GetDefinition(rootVar)) {
  457. cmExpandList(pkgRoot, rootPaths, false);
  458. }
  459. cmSystemTools::GetPath(rootPaths, rootVar.c_str());
  460. } break;
  461. }
  462. }
  463. this->SetModuleVariables(components);
  464. // See if there is a Find<PackageName>.cmake module.
  465. bool loadedPackage = false;
  466. if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_PREFER_CONFIG")) {
  467. if (this->UseConfigFiles && this->FindPackageUsingConfigMode()) {
  468. loadedPackage = true;
  469. } else {
  470. if (this->FindPackageUsingModuleMode()) {
  471. loadedPackage = true;
  472. } else {
  473. // The package was not loaded. Report errors.
  474. if (HandlePackageMode(HandlePackageModeType::Module)) {
  475. loadedPackage = true;
  476. }
  477. }
  478. }
  479. } else {
  480. if (this->UseFindModules && this->FindPackageUsingModuleMode()) {
  481. loadedPackage = true;
  482. } else {
  483. // Handle CMAKE_FIND_PACKAGE_WARN_NO_MODULE (warn when CONFIG mode is
  484. // implicitly assumed)
  485. if (this->UseFindModules && this->UseConfigFiles &&
  486. this->Makefile->IsOn("CMAKE_FIND_PACKAGE_WARN_NO_MODULE")) {
  487. std::ostringstream aw;
  488. if (this->RequiredCMakeVersion >= CMake_VERSION_ENCODE(2, 8, 8)) {
  489. aw << "find_package called without either MODULE or CONFIG option "
  490. "and "
  491. "no Find"
  492. << this->Name
  493. << ".cmake module is in CMAKE_MODULE_PATH. "
  494. "Add MODULE to exclusively request Module mode and fail if "
  495. "Find"
  496. << this->Name
  497. << ".cmake is missing. "
  498. "Add CONFIG to exclusively request Config mode and search for "
  499. "a "
  500. "package configuration file provided by "
  501. << this->Name << " (" << this->Name << "Config.cmake or "
  502. << cmSystemTools::LowerCase(this->Name) << "-config.cmake). ";
  503. } else {
  504. aw << "find_package called without NO_MODULE option and no "
  505. "Find"
  506. << this->Name
  507. << ".cmake module is in CMAKE_MODULE_PATH. "
  508. "Add NO_MODULE to exclusively request Config mode and search "
  509. "for a "
  510. "package configuration file provided by "
  511. << this->Name << " (" << this->Name << "Config.cmake or "
  512. << cmSystemTools::LowerCase(this->Name)
  513. << "-config.cmake). "
  514. "Otherwise make Find"
  515. << this->Name
  516. << ".cmake available in "
  517. "CMAKE_MODULE_PATH.";
  518. }
  519. aw << "\n"
  520. "(Variable CMAKE_FIND_PACKAGE_WARN_NO_MODULE enabled this "
  521. "warning.)";
  522. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, aw.str());
  523. }
  524. if (this->FindPackageUsingConfigMode()) {
  525. loadedPackage = true;
  526. }
  527. }
  528. }
  529. this->AppendSuccessInformation();
  530. return loadedPackage;
  531. }
  532. bool cmFindPackageCommand::FindPackageUsingModuleMode()
  533. {
  534. bool foundModule = false;
  535. if (!this->FindModule(foundModule)) {
  536. return false;
  537. }
  538. return foundModule;
  539. }
  540. bool cmFindPackageCommand::FindPackageUsingConfigMode()
  541. {
  542. this->Variable = this->Name;
  543. this->Variable += "_DIR";
  544. // Add the default name.
  545. if (this->Names.empty()) {
  546. this->Names.push_back(this->Name);
  547. }
  548. // Add the default configs.
  549. if (this->Configs.empty()) {
  550. for (std::string const& n : this->Names) {
  551. std::string config = n;
  552. config += "Config.cmake";
  553. this->Configs.push_back(config);
  554. config = cmSystemTools::LowerCase(n);
  555. config += "-config.cmake";
  556. this->Configs.push_back(std::move(config));
  557. }
  558. }
  559. // get igonored paths from vars and reroot them.
  560. std::vector<std::string> ignored;
  561. this->GetIgnoredPaths(ignored);
  562. this->RerootPaths(ignored);
  563. // Construct a set of ignored paths
  564. this->IgnoredPaths.clear();
  565. this->IgnoredPaths.insert(ignored.begin(), ignored.end());
  566. // Find and load the package.
  567. return this->HandlePackageMode(HandlePackageModeType::Config);
  568. }
  569. void cmFindPackageCommand::SetModuleVariables(const std::string& components)
  570. {
  571. this->AddFindDefinition("CMAKE_FIND_PACKAGE_NAME", this->Name.c_str());
  572. // Store the list of components.
  573. std::string components_var = this->Name + "_FIND_COMPONENTS";
  574. this->AddFindDefinition(components_var, components.c_str());
  575. if (this->Quiet) {
  576. // Tell the module that is about to be read that it should find
  577. // quietly.
  578. std::string quietly = this->Name;
  579. quietly += "_FIND_QUIETLY";
  580. this->AddFindDefinition(quietly, "1");
  581. }
  582. if (this->Required) {
  583. // Tell the module that is about to be read that it should report
  584. // a fatal error if the package is not found.
  585. std::string req = this->Name;
  586. req += "_FIND_REQUIRED";
  587. this->AddFindDefinition(req, "1");
  588. }
  589. if (!this->Version.empty()) {
  590. // Tell the module that is about to be read what version of the
  591. // package has been requested.
  592. std::string ver = this->Name;
  593. ver += "_FIND_VERSION";
  594. this->AddFindDefinition(ver, this->Version.c_str());
  595. char buf[64];
  596. sprintf(buf, "%u", this->VersionMajor);
  597. this->AddFindDefinition(ver + "_MAJOR", buf);
  598. sprintf(buf, "%u", this->VersionMinor);
  599. this->AddFindDefinition(ver + "_MINOR", buf);
  600. sprintf(buf, "%u", this->VersionPatch);
  601. this->AddFindDefinition(ver + "_PATCH", buf);
  602. sprintf(buf, "%u", this->VersionTweak);
  603. this->AddFindDefinition(ver + "_TWEAK", buf);
  604. sprintf(buf, "%u", this->VersionCount);
  605. this->AddFindDefinition(ver + "_COUNT", buf);
  606. // Tell the module whether an exact version has been requested.
  607. std::string exact = this->Name;
  608. exact += "_FIND_VERSION_EXACT";
  609. this->AddFindDefinition(exact, this->VersionExact ? "1" : "0");
  610. }
  611. }
  612. void cmFindPackageCommand::AddFindDefinition(const std::string& var,
  613. const char* val)
  614. {
  615. if (const char* old = this->Makefile->GetDefinition(var)) {
  616. this->OriginalDefs[var].exists = true;
  617. this->OriginalDefs[var].value = old;
  618. } else {
  619. this->OriginalDefs[var].exists = false;
  620. }
  621. if (val) {
  622. this->Makefile->AddDefinition(var, val);
  623. }
  624. }
  625. void cmFindPackageCommand::RestoreFindDefinitions()
  626. {
  627. for (auto const& i : this->OriginalDefs) {
  628. OriginalDef const& od = i.second;
  629. if (od.exists) {
  630. this->Makefile->AddDefinition(i.first, od.value);
  631. } else {
  632. this->Makefile->RemoveDefinition(i.first);
  633. }
  634. }
  635. }
  636. bool cmFindPackageCommand::FindModule(bool& found)
  637. {
  638. std::string module = "Find";
  639. module += this->Name;
  640. module += ".cmake";
  641. bool system = false;
  642. std::string mfile = this->Makefile->GetModulesFile(module, system);
  643. if (!mfile.empty()) {
  644. if (system) {
  645. auto it = this->DeprecatedFindModules.find(this->Name);
  646. if (it != this->DeprecatedFindModules.end()) {
  647. cmPolicies::PolicyStatus status =
  648. this->Makefile->GetPolicyStatus(it->second);
  649. switch (status) {
  650. case cmPolicies::WARN: {
  651. std::ostringstream e;
  652. e << cmPolicies::GetPolicyWarning(it->second) << "\n";
  653. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  654. CM_FALLTHROUGH;
  655. }
  656. case cmPolicies::OLD:
  657. break;
  658. case cmPolicies::REQUIRED_IF_USED:
  659. case cmPolicies::REQUIRED_ALWAYS:
  660. case cmPolicies::NEW:
  661. return true;
  662. }
  663. }
  664. }
  665. // Load the module we found, and set "<name>_FIND_MODULE" to true
  666. // while inside it.
  667. found = true;
  668. std::string var = this->Name;
  669. var += "_FIND_MODULE";
  670. this->Makefile->AddDefinition(var, "1");
  671. bool result = this->ReadListFile(mfile, DoPolicyScope);
  672. this->Makefile->RemoveDefinition(var);
  673. return result;
  674. }
  675. return true;
  676. }
  677. bool cmFindPackageCommand::HandlePackageMode(
  678. HandlePackageModeType handlePackageModeType)
  679. {
  680. this->ConsideredConfigs.clear();
  681. // Try to find the config file.
  682. const char* def = this->Makefile->GetDefinition(this->Variable);
  683. // Try to load the config file if the directory is known
  684. bool fileFound = false;
  685. if (this->UseConfigFiles) {
  686. if (!cmIsOff(def)) {
  687. // Get the directory from the variable value.
  688. std::string dir = def;
  689. cmSystemTools::ConvertToUnixSlashes(dir);
  690. // Treat relative paths with respect to the current source dir.
  691. if (!cmSystemTools::FileIsFullPath(dir)) {
  692. dir = "/" + dir;
  693. dir = this->Makefile->GetCurrentSourceDirectory() + dir;
  694. }
  695. // The file location was cached. Look for the correct file.
  696. std::string file;
  697. if (this->FindConfigFile(dir, file)) {
  698. this->FileFound = file;
  699. fileFound = true;
  700. }
  701. def = this->Makefile->GetDefinition(this->Variable);
  702. }
  703. // Search for the config file if it is not already found.
  704. if (cmIsOff(def) || !fileFound) {
  705. fileFound = this->FindConfig();
  706. }
  707. // Sanity check.
  708. if (fileFound && this->FileFound.empty()) {
  709. this->Makefile->IssueMessage(
  710. MessageType::INTERNAL_ERROR,
  711. "fileFound is true but FileFound is empty!");
  712. fileFound = false;
  713. }
  714. }
  715. std::string foundVar = this->Name;
  716. foundVar += "_FOUND";
  717. std::string notFoundMessageVar = this->Name;
  718. notFoundMessageVar += "_NOT_FOUND_MESSAGE";
  719. std::string notFoundMessage;
  720. // If the directory for the config file was found, try to read the file.
  721. bool result = true;
  722. bool found = false;
  723. bool configFileSetFOUNDFalse = false;
  724. if (fileFound) {
  725. if (this->Makefile->IsDefinitionSet(foundVar) &&
  726. !this->Makefile->IsOn(foundVar)) {
  727. // by removing Foo_FOUND here if it is FALSE, we don't really change
  728. // the situation for the Config file which is about to be included,
  729. // but we make it possible to detect later on whether the Config file
  730. // has set Foo_FOUND to FALSE itself:
  731. this->Makefile->RemoveDefinition(foundVar);
  732. }
  733. this->Makefile->RemoveDefinition(notFoundMessageVar);
  734. // Set the version variables before loading the config file.
  735. // It may override them.
  736. this->StoreVersionFound();
  737. // Parse the configuration file.
  738. if (this->ReadListFile(this->FileFound, DoPolicyScope)) {
  739. // The package has been found.
  740. found = true;
  741. // Check whether the Config file has set Foo_FOUND to FALSE:
  742. if (this->Makefile->IsDefinitionSet(foundVar) &&
  743. !this->Makefile->IsOn(foundVar)) {
  744. // we get here if the Config file has set Foo_FOUND actively to FALSE
  745. found = false;
  746. configFileSetFOUNDFalse = true;
  747. notFoundMessage =
  748. this->Makefile->GetSafeDefinition(notFoundMessageVar);
  749. }
  750. } else {
  751. // The configuration file is invalid.
  752. result = false;
  753. }
  754. }
  755. if (this->UseFindModules && !found &&
  756. handlePackageModeType == HandlePackageModeType::Config &&
  757. this->Makefile->IsOn("CMAKE_FIND_PACKAGE_PREFER_CONFIG")) {
  758. // Config mode failed. Allow Module case.
  759. result = false;
  760. }
  761. // package not found
  762. if (result && !found) {
  763. // warn if package required or neither quiet nor in config mode
  764. if (this->Required ||
  765. !(this->Quiet ||
  766. (this->UseConfigFiles && !this->UseFindModules &&
  767. this->ConsideredConfigs.empty()))) {
  768. // The variable is not set.
  769. std::ostringstream e;
  770. std::ostringstream aw;
  771. if (configFileSetFOUNDFalse) {
  772. /* clang-format off */
  773. e << "Found package configuration file:\n"
  774. " " << this->FileFound << "\n"
  775. "but it set " << foundVar << " to FALSE so package \"" <<
  776. this->Name << "\" is considered to be NOT FOUND.";
  777. /* clang-format on */
  778. if (!notFoundMessage.empty()) {
  779. e << " Reason given by package: \n" << notFoundMessage << "\n";
  780. }
  781. }
  782. // If there are files in ConsideredConfigs, it means that FooConfig.cmake
  783. // have been found, but they didn't have appropriate versions.
  784. else if (!this->ConsideredConfigs.empty()) {
  785. std::vector<ConfigFileInfo>::const_iterator duplicate_end =
  786. cmRemoveDuplicates(this->ConsideredConfigs);
  787. e << "Could not find a configuration file for package \"" << this->Name
  788. << "\" that "
  789. << (this->VersionExact ? "exactly matches" : "is compatible with")
  790. << " requested version \"" << this->Version << "\".\n"
  791. << "The following configuration files were considered but not "
  792. "accepted:\n";
  793. for (ConfigFileInfo const& info :
  794. cmMakeRange(this->ConsideredConfigs.cbegin(), duplicate_end)) {
  795. e << " " << info.filename << ", version: " << info.version << "\n";
  796. }
  797. } else {
  798. std::string requestedVersionString;
  799. if (!this->Version.empty()) {
  800. requestedVersionString = " (requested version ";
  801. requestedVersionString += this->Version;
  802. requestedVersionString += ")";
  803. }
  804. if (this->UseConfigFiles) {
  805. if (this->UseFindModules) {
  806. e << "By not providing \"Find" << this->Name
  807. << ".cmake\" in "
  808. "CMAKE_MODULE_PATH this project has asked CMake to find a "
  809. "package configuration file provided by \""
  810. << this->Name
  811. << "\", "
  812. "but CMake did not find one.\n";
  813. }
  814. if (this->Configs.size() == 1) {
  815. e << "Could not find a package configuration file named \""
  816. << this->Configs[0] << "\" provided by package \"" << this->Name
  817. << "\"" << requestedVersionString << ".\n";
  818. } else {
  819. e << "Could not find a package configuration file provided by \""
  820. << this->Name << "\"" << requestedVersionString
  821. << " with any of the following names:\n"
  822. << cmWrap(" ", this->Configs, "", "\n") << "\n";
  823. }
  824. e << "Add the installation prefix of \"" << this->Name
  825. << "\" to "
  826. "CMAKE_PREFIX_PATH or set \""
  827. << this->Variable
  828. << "\" to a "
  829. "directory containing one of the above files. "
  830. "If \""
  831. << this->Name
  832. << "\" provides a separate development "
  833. "package or SDK, be sure it has been installed.";
  834. } else // if(!this->UseFindModules && !this->UseConfigFiles)
  835. {
  836. e << "No \"Find" << this->Name << ".cmake\" found in "
  837. << "CMAKE_MODULE_PATH.";
  838. aw
  839. << "Find" << this->Name
  840. << ".cmake must either be part of this "
  841. "project itself, in this case adjust CMAKE_MODULE_PATH so that "
  842. "it points to the correct location inside its source tree.\n"
  843. "Or it must be installed by a package which has already been "
  844. "found via find_package(). In this case make sure that "
  845. "package has indeed been found and adjust CMAKE_MODULE_PATH to "
  846. "contain the location where that package has installed "
  847. "Find"
  848. << this->Name
  849. << ".cmake. This must be a location "
  850. "provided by that package. This error in general means that "
  851. "the buildsystem of this project is relying on a Find-module "
  852. "without ensuring that it is actually available.\n";
  853. }
  854. }
  855. this->Makefile->IssueMessage(this->Required ? MessageType::FATAL_ERROR
  856. : MessageType::WARNING,
  857. e.str());
  858. if (this->Required) {
  859. cmSystemTools::SetFatalErrorOccured();
  860. }
  861. if (!aw.str().empty()) {
  862. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, aw.str());
  863. }
  864. }
  865. // output result if in config mode but not in quiet mode
  866. else if (!this->Quiet) {
  867. std::ostringstream aw;
  868. aw << "Could NOT find " << this->Name << " (missing: " << this->Name
  869. << "_DIR)";
  870. this->Makefile->DisplayStatus(aw.str(), -1);
  871. }
  872. }
  873. // Set a variable marking whether the package was found.
  874. this->Makefile->AddDefinition(foundVar, found ? "1" : "0");
  875. // Set a variable naming the configuration file that was found.
  876. std::string fileVar = this->Name;
  877. fileVar += "_CONFIG";
  878. if (found) {
  879. this->Makefile->AddDefinition(fileVar, this->FileFound);
  880. } else {
  881. this->Makefile->RemoveDefinition(fileVar);
  882. }
  883. std::string consideredConfigsVar = this->Name;
  884. consideredConfigsVar += "_CONSIDERED_CONFIGS";
  885. std::string consideredVersionsVar = this->Name;
  886. consideredVersionsVar += "_CONSIDERED_VERSIONS";
  887. std::string consideredConfigFiles;
  888. std::string consideredVersions;
  889. const char* sep = "";
  890. for (ConfigFileInfo const& i : this->ConsideredConfigs) {
  891. consideredConfigFiles += sep;
  892. consideredVersions += sep;
  893. consideredConfigFiles += i.filename;
  894. consideredVersions += i.version;
  895. sep = ";";
  896. }
  897. this->Makefile->AddDefinition(consideredConfigsVar, consideredConfigFiles);
  898. this->Makefile->AddDefinition(consideredVersionsVar, consideredVersions);
  899. return result;
  900. }
  901. bool cmFindPackageCommand::FindConfig()
  902. {
  903. // Compute the set of search prefixes.
  904. this->ComputePrefixes();
  905. // Look for the project's configuration file.
  906. bool found = false;
  907. // Search for frameworks.
  908. if (!found && (this->SearchFrameworkFirst || this->SearchFrameworkOnly)) {
  909. found = this->FindFrameworkConfig();
  910. }
  911. // Search for apps.
  912. if (!found && (this->SearchAppBundleFirst || this->SearchAppBundleOnly)) {
  913. found = this->FindAppBundleConfig();
  914. }
  915. // Search prefixes.
  916. if (!found && !(this->SearchFrameworkOnly || this->SearchAppBundleOnly)) {
  917. found = this->FindPrefixedConfig();
  918. }
  919. // Search for frameworks.
  920. if (!found && this->SearchFrameworkLast) {
  921. found = this->FindFrameworkConfig();
  922. }
  923. // Search for apps.
  924. if (!found && this->SearchAppBundleLast) {
  925. found = this->FindAppBundleConfig();
  926. }
  927. // Store the entry in the cache so it can be set by the user.
  928. std::string init;
  929. if (found) {
  930. init = cmSystemTools::GetFilenamePath(this->FileFound);
  931. } else {
  932. init = this->Variable + "-NOTFOUND";
  933. }
  934. std::string help =
  935. "The directory containing a CMake configuration file for ";
  936. help += this->Name;
  937. help += ".";
  938. // We force the value since we do not get here if it was already set.
  939. this->Makefile->AddCacheDefinition(this->Variable, init.c_str(),
  940. help.c_str(), cmStateEnums::PATH, true);
  941. return found;
  942. }
  943. bool cmFindPackageCommand::FindPrefixedConfig()
  944. {
  945. std::vector<std::string> const& prefixes = this->SearchPaths;
  946. for (std::string const& p : prefixes) {
  947. if (this->SearchPrefix(p)) {
  948. return true;
  949. }
  950. }
  951. return false;
  952. }
  953. bool cmFindPackageCommand::FindFrameworkConfig()
  954. {
  955. std::vector<std::string> const& prefixes = this->SearchPaths;
  956. for (std::string const& p : prefixes) {
  957. if (this->SearchFrameworkPrefix(p)) {
  958. return true;
  959. }
  960. }
  961. return false;
  962. }
  963. bool cmFindPackageCommand::FindAppBundleConfig()
  964. {
  965. std::vector<std::string> const& prefixes = this->SearchPaths;
  966. for (std::string const& p : prefixes) {
  967. if (this->SearchAppBundlePrefix(p)) {
  968. return true;
  969. }
  970. }
  971. return false;
  972. }
  973. bool cmFindPackageCommand::ReadListFile(const std::string& f,
  974. PolicyScopeRule psr)
  975. {
  976. const bool noPolicyScope = !this->PolicyScope || psr == NoPolicyScope;
  977. if (this->Makefile->ReadDependentFile(f, noPolicyScope)) {
  978. return true;
  979. }
  980. std::string e = "Error reading CMake code from \"";
  981. e += f;
  982. e += "\".";
  983. this->SetError(e);
  984. return false;
  985. }
  986. void cmFindPackageCommand::AppendToFoundProperty(bool found)
  987. {
  988. std::vector<std::string> foundContents;
  989. const char* foundProp =
  990. this->Makefile->GetState()->GetGlobalProperty("PACKAGES_FOUND");
  991. if (foundProp && *foundProp) {
  992. std::string tmp = foundProp;
  993. cmExpandList(tmp, foundContents, false);
  994. std::vector<std::string>::iterator nameIt =
  995. std::find(foundContents.begin(), foundContents.end(), this->Name);
  996. if (nameIt != foundContents.end()) {
  997. foundContents.erase(nameIt);
  998. }
  999. }
  1000. std::vector<std::string> notFoundContents;
  1001. const char* notFoundProp =
  1002. this->Makefile->GetState()->GetGlobalProperty("PACKAGES_NOT_FOUND");
  1003. if (notFoundProp && *notFoundProp) {
  1004. std::string tmp = notFoundProp;
  1005. cmExpandList(tmp, notFoundContents, false);
  1006. std::vector<std::string>::iterator nameIt =
  1007. std::find(notFoundContents.begin(), notFoundContents.end(), this->Name);
  1008. if (nameIt != notFoundContents.end()) {
  1009. notFoundContents.erase(nameIt);
  1010. }
  1011. }
  1012. if (found) {
  1013. foundContents.push_back(this->Name);
  1014. } else {
  1015. notFoundContents.push_back(this->Name);
  1016. }
  1017. std::string tmp = cmJoin(foundContents, ";");
  1018. this->Makefile->GetState()->SetGlobalProperty("PACKAGES_FOUND", tmp.c_str());
  1019. tmp = cmJoin(notFoundContents, ";");
  1020. this->Makefile->GetState()->SetGlobalProperty("PACKAGES_NOT_FOUND",
  1021. tmp.c_str());
  1022. }
  1023. void cmFindPackageCommand::AppendSuccessInformation()
  1024. {
  1025. {
  1026. std::string transitivePropName = "_CMAKE_";
  1027. transitivePropName += this->Name + "_TRANSITIVE_DEPENDENCY";
  1028. this->Makefile->GetState()->SetGlobalProperty(transitivePropName, "False");
  1029. }
  1030. std::string found = this->Name;
  1031. found += "_FOUND";
  1032. std::string upperFound = cmSystemTools::UpperCase(found);
  1033. const char* upperResult = this->Makefile->GetDefinition(upperFound);
  1034. const char* result = this->Makefile->GetDefinition(found);
  1035. bool packageFound = ((cmIsOn(result)) || (cmIsOn(upperResult)));
  1036. this->AppendToFoundProperty(packageFound);
  1037. // Record whether the find was quiet or not, so this can be used
  1038. // e.g. in FeatureSummary.cmake
  1039. std::string quietInfoPropName = "_CMAKE_";
  1040. quietInfoPropName += this->Name;
  1041. quietInfoPropName += "_QUIET";
  1042. this->Makefile->GetState()->SetGlobalProperty(
  1043. quietInfoPropName, this->Quiet ? "TRUE" : "FALSE");
  1044. // set a global property to record the required version of this package
  1045. std::string versionInfoPropName = "_CMAKE_";
  1046. versionInfoPropName += this->Name;
  1047. versionInfoPropName += "_REQUIRED_VERSION";
  1048. std::string versionInfo;
  1049. if (!this->Version.empty()) {
  1050. versionInfo = this->VersionExact ? "==" : ">=";
  1051. versionInfo += " ";
  1052. versionInfo += this->Version;
  1053. }
  1054. this->Makefile->GetState()->SetGlobalProperty(versionInfoPropName,
  1055. versionInfo.c_str());
  1056. if (this->Required) {
  1057. std::string requiredInfoPropName = "_CMAKE_";
  1058. requiredInfoPropName += this->Name;
  1059. requiredInfoPropName += "_TYPE";
  1060. this->Makefile->GetState()->SetGlobalProperty(requiredInfoPropName,
  1061. "REQUIRED");
  1062. }
  1063. // Restore original state of "_FIND_" variables we set.
  1064. this->RestoreFindDefinitions();
  1065. // Pop the package stack
  1066. this->Makefile->FindPackageRootPathStack.pop_back();
  1067. }
  1068. void cmFindPackageCommand::ComputePrefixes()
  1069. {
  1070. if (!this->NoDefaultPath) {
  1071. if (!this->NoPackageRootPath) {
  1072. this->FillPrefixesPackageRoot();
  1073. }
  1074. if (!this->NoCMakePath) {
  1075. this->FillPrefixesCMakeVariable();
  1076. }
  1077. if (!this->NoCMakeEnvironmentPath) {
  1078. this->FillPrefixesCMakeEnvironment();
  1079. }
  1080. }
  1081. this->FillPrefixesUserHints();
  1082. if (!this->NoDefaultPath) {
  1083. if (!this->NoSystemEnvironmentPath) {
  1084. this->FillPrefixesSystemEnvironment();
  1085. }
  1086. if (!this->NoUserRegistry) {
  1087. this->FillPrefixesUserRegistry();
  1088. }
  1089. if (!this->NoCMakeSystemPath) {
  1090. this->FillPrefixesCMakeSystemVariable();
  1091. }
  1092. if (!this->NoSystemRegistry) {
  1093. this->FillPrefixesSystemRegistry();
  1094. }
  1095. }
  1096. this->FillPrefixesUserGuess();
  1097. this->ComputeFinalPaths();
  1098. }
  1099. void cmFindPackageCommand::FillPrefixesPackageRoot()
  1100. {
  1101. cmSearchPath& paths = this->LabeledPaths[PathLabel::PackageRoot];
  1102. // Add the PACKAGE_ROOT_PATH from each enclosing find_package call.
  1103. for (std::deque<std::vector<std::string>>::const_reverse_iterator pkgPaths =
  1104. this->Makefile->FindPackageRootPathStack.rbegin();
  1105. pkgPaths != this->Makefile->FindPackageRootPathStack.rend();
  1106. ++pkgPaths) {
  1107. for (std::string const& path : *pkgPaths) {
  1108. paths.AddPath(path);
  1109. }
  1110. }
  1111. }
  1112. void cmFindPackageCommand::FillPrefixesCMakeEnvironment()
  1113. {
  1114. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeEnvironment];
  1115. // Check the environment variable with the same name as the cache
  1116. // entry.
  1117. paths.AddEnvPath(this->Variable);
  1118. // And now the general CMake environment variables
  1119. paths.AddEnvPath("CMAKE_PREFIX_PATH");
  1120. paths.AddEnvPath("CMAKE_FRAMEWORK_PATH");
  1121. paths.AddEnvPath("CMAKE_APPBUNDLE_PATH");
  1122. }
  1123. void cmFindPackageCommand::FillPrefixesCMakeVariable()
  1124. {
  1125. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMake];
  1126. paths.AddCMakePath("CMAKE_PREFIX_PATH");
  1127. paths.AddCMakePath("CMAKE_FRAMEWORK_PATH");
  1128. paths.AddCMakePath("CMAKE_APPBUNDLE_PATH");
  1129. }
  1130. void cmFindPackageCommand::FillPrefixesSystemEnvironment()
  1131. {
  1132. cmSearchPath& paths = this->LabeledPaths[PathLabel::SystemEnvironment];
  1133. // Use the system search path to generate prefixes.
  1134. // Relative paths are interpreted with respect to the current
  1135. // working directory.
  1136. std::vector<std::string> tmp;
  1137. cmSystemTools::GetPath(tmp);
  1138. for (std::string const& i : tmp) {
  1139. // If the path is a PREFIX/bin case then add its parent instead.
  1140. if ((cmHasLiteralSuffix(i, "/bin")) || (cmHasLiteralSuffix(i, "/sbin"))) {
  1141. paths.AddPath(cmSystemTools::GetFilenamePath(i));
  1142. } else {
  1143. paths.AddPath(i);
  1144. }
  1145. }
  1146. }
  1147. void cmFindPackageCommand::FillPrefixesUserRegistry()
  1148. {
  1149. #if defined(_WIN32) && !defined(__CYGWIN__)
  1150. this->LoadPackageRegistryWinUser();
  1151. #elif defined(__HAIKU__)
  1152. char dir[B_PATH_NAME_LENGTH];
  1153. if (find_directory(B_USER_SETTINGS_DIRECTORY, -1, false, dir, sizeof(dir)) ==
  1154. B_OK) {
  1155. std::string fname = dir;
  1156. fname += "/cmake/packages/";
  1157. fname += Name;
  1158. this->LoadPackageRegistryDir(fname,
  1159. this->LabeledPaths[PathLabel::UserRegistry]);
  1160. }
  1161. #else
  1162. std::string dir;
  1163. if (cmSystemTools::GetEnv("HOME", dir)) {
  1164. dir += "/.cmake/packages/";
  1165. dir += this->Name;
  1166. this->LoadPackageRegistryDir(dir,
  1167. this->LabeledPaths[PathLabel::UserRegistry]);
  1168. }
  1169. #endif
  1170. }
  1171. void cmFindPackageCommand::FillPrefixesSystemRegistry()
  1172. {
  1173. if (this->NoSystemRegistry || this->NoDefaultPath) {
  1174. return;
  1175. }
  1176. #if defined(_WIN32) && !defined(__CYGWIN__)
  1177. this->LoadPackageRegistryWinSystem();
  1178. #endif
  1179. }
  1180. #if defined(_WIN32) && !defined(__CYGWIN__)
  1181. # include <windows.h>
  1182. // http://msdn.microsoft.com/en-us/library/aa384253%28v=vs.85%29.aspx
  1183. # if !defined(KEY_WOW64_32KEY)
  1184. # define KEY_WOW64_32KEY 0x0200
  1185. # endif
  1186. # if !defined(KEY_WOW64_64KEY)
  1187. # define KEY_WOW64_64KEY 0x0100
  1188. # endif
  1189. void cmFindPackageCommand::LoadPackageRegistryWinUser()
  1190. {
  1191. // HKEY_CURRENT_USER\\Software shares 32-bit and 64-bit views.
  1192. this->LoadPackageRegistryWin(true, 0,
  1193. this->LabeledPaths[PathLabel::UserRegistry]);
  1194. }
  1195. void cmFindPackageCommand::LoadPackageRegistryWinSystem()
  1196. {
  1197. cmSearchPath& paths = this->LabeledPaths[PathLabel::SystemRegistry];
  1198. // HKEY_LOCAL_MACHINE\\SOFTWARE has separate 32-bit and 64-bit views.
  1199. // Prefer the target platform view first.
  1200. if (this->Makefile->PlatformIs64Bit()) {
  1201. this->LoadPackageRegistryWin(false, KEY_WOW64_64KEY, paths);
  1202. this->LoadPackageRegistryWin(false, KEY_WOW64_32KEY, paths);
  1203. } else {
  1204. this->LoadPackageRegistryWin(false, KEY_WOW64_32KEY, paths);
  1205. this->LoadPackageRegistryWin(false, KEY_WOW64_64KEY, paths);
  1206. }
  1207. }
  1208. void cmFindPackageCommand::LoadPackageRegistryWin(bool user, unsigned int view,
  1209. cmSearchPath& outPaths)
  1210. {
  1211. std::wstring key = L"Software\\Kitware\\CMake\\Packages\\";
  1212. key += cmsys::Encoding::ToWide(this->Name);
  1213. std::set<std::wstring> bad;
  1214. HKEY hKey;
  1215. if (RegOpenKeyExW(user ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE, key.c_str(),
  1216. 0, KEY_QUERY_VALUE | view, &hKey) == ERROR_SUCCESS) {
  1217. DWORD valueType = REG_NONE;
  1218. wchar_t name[16383]; // RegEnumValue docs limit name to 32767 _bytes_
  1219. std::vector<wchar_t> data(512);
  1220. bool done = false;
  1221. DWORD index = 0;
  1222. while (!done) {
  1223. DWORD nameSize = static_cast<DWORD>(sizeof(name));
  1224. DWORD dataSize = static_cast<DWORD>(data.size() * sizeof(data[0]));
  1225. switch (RegEnumValueW(hKey, index, name, &nameSize, 0, &valueType,
  1226. (BYTE*)&data[0], &dataSize)) {
  1227. case ERROR_SUCCESS:
  1228. ++index;
  1229. if (valueType == REG_SZ) {
  1230. data[dataSize] = 0;
  1231. if (!this->CheckPackageRegistryEntry(
  1232. cmsys::Encoding::ToNarrow(&data[0]), outPaths)) {
  1233. // The entry is invalid.
  1234. bad.insert(name);
  1235. }
  1236. }
  1237. break;
  1238. case ERROR_MORE_DATA:
  1239. data.resize((dataSize + sizeof(data[0]) - 1) / sizeof(data[0]));
  1240. break;
  1241. case ERROR_NO_MORE_ITEMS:
  1242. default:
  1243. done = true;
  1244. break;
  1245. }
  1246. }
  1247. RegCloseKey(hKey);
  1248. }
  1249. // Remove bad values if possible.
  1250. if (user && !bad.empty() &&
  1251. RegOpenKeyExW(HKEY_CURRENT_USER, key.c_str(), 0, KEY_SET_VALUE | view,
  1252. &hKey) == ERROR_SUCCESS) {
  1253. for (std::wstring const& v : bad) {
  1254. RegDeleteValueW(hKey, v.c_str());
  1255. }
  1256. RegCloseKey(hKey);
  1257. }
  1258. }
  1259. #else
  1260. class cmFindPackageCommandHoldFile
  1261. {
  1262. const char* File;
  1263. public:
  1264. cmFindPackageCommandHoldFile(const char* f)
  1265. : File(f)
  1266. {
  1267. }
  1268. ~cmFindPackageCommandHoldFile()
  1269. {
  1270. if (this->File) {
  1271. cmSystemTools::RemoveFile(this->File);
  1272. }
  1273. }
  1274. cmFindPackageCommandHoldFile(const cmFindPackageCommandHoldFile&) = delete;
  1275. cmFindPackageCommandHoldFile& operator=(
  1276. const cmFindPackageCommandHoldFile&) = delete;
  1277. void Release() { this->File = nullptr; }
  1278. };
  1279. void cmFindPackageCommand::LoadPackageRegistryDir(std::string const& dir,
  1280. cmSearchPath& outPaths)
  1281. {
  1282. cmsys::Directory files;
  1283. if (!files.Load(dir)) {
  1284. return;
  1285. }
  1286. std::string fname;
  1287. for (unsigned long i = 0; i < files.GetNumberOfFiles(); ++i) {
  1288. fname = dir;
  1289. fname += "/";
  1290. fname += files.GetFile(i);
  1291. if (!cmSystemTools::FileIsDirectory(fname)) {
  1292. // Hold this file hostage until it behaves.
  1293. cmFindPackageCommandHoldFile holdFile(fname.c_str());
  1294. // Load the file.
  1295. cmsys::ifstream fin(fname.c_str(), std::ios::in | std::ios::binary);
  1296. std::string fentry;
  1297. if (fin && cmSystemTools::GetLineFromStream(fin, fentry) &&
  1298. this->CheckPackageRegistryEntry(fentry, outPaths)) {
  1299. // The file references an existing package, so release it.
  1300. holdFile.Release();
  1301. }
  1302. }
  1303. }
  1304. // TODO: Wipe out the directory if it is empty.
  1305. }
  1306. #endif
  1307. bool cmFindPackageCommand::CheckPackageRegistryEntry(const std::string& fname,
  1308. cmSearchPath& outPaths)
  1309. {
  1310. // Parse the content of one package registry entry.
  1311. if (cmSystemTools::FileIsFullPath(fname)) {
  1312. // The first line in the stream is the full path to a file or
  1313. // directory containing the package.
  1314. if (cmSystemTools::FileExists(fname)) {
  1315. // The path exists. Look for the package here.
  1316. if (!cmSystemTools::FileIsDirectory(fname)) {
  1317. outPaths.AddPath(cmSystemTools::GetFilenamePath(fname));
  1318. } else {
  1319. outPaths.AddPath(fname);
  1320. }
  1321. return true;
  1322. }
  1323. // The path does not exist. Assume the stream content is
  1324. // associated with an old package that no longer exists, and
  1325. // delete it to keep the package registry clean.
  1326. return false;
  1327. }
  1328. // The first line in the stream is not the full path to a file or
  1329. // directory. Assume the stream content was created by a future
  1330. // version of CMake that uses a different format, and leave it.
  1331. return true;
  1332. }
  1333. void cmFindPackageCommand::FillPrefixesCMakeSystemVariable()
  1334. {
  1335. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeSystem];
  1336. paths.AddCMakePath("CMAKE_SYSTEM_PREFIX_PATH");
  1337. paths.AddCMakePath("CMAKE_SYSTEM_FRAMEWORK_PATH");
  1338. paths.AddCMakePath("CMAKE_SYSTEM_APPBUNDLE_PATH");
  1339. }
  1340. void cmFindPackageCommand::FillPrefixesUserGuess()
  1341. {
  1342. cmSearchPath& paths = this->LabeledPaths[PathLabel::Guess];
  1343. for (std::string const& p : this->UserGuessArgs) {
  1344. paths.AddUserPath(p);
  1345. }
  1346. }
  1347. void cmFindPackageCommand::FillPrefixesUserHints()
  1348. {
  1349. cmSearchPath& paths = this->LabeledPaths[PathLabel::Hints];
  1350. for (std::string const& p : this->UserHintsArgs) {
  1351. paths.AddUserPath(p);
  1352. }
  1353. }
  1354. bool cmFindPackageCommand::SearchDirectory(std::string const& dir)
  1355. {
  1356. assert(!dir.empty() && dir.back() == '/');
  1357. // Check each path suffix on this directory.
  1358. for (std::string const& s : this->SearchPathSuffixes) {
  1359. std::string d = dir;
  1360. if (!s.empty()) {
  1361. d += s;
  1362. d += "/";
  1363. }
  1364. if (this->CheckDirectory(d)) {
  1365. return true;
  1366. }
  1367. }
  1368. return false;
  1369. }
  1370. bool cmFindPackageCommand::CheckDirectory(std::string const& dir)
  1371. {
  1372. assert(!dir.empty() && dir.back() == '/');
  1373. // Look for the file in this directory.
  1374. std::string d = dir.substr(0, dir.size() - 1);
  1375. if (this->FindConfigFile(d, this->FileFound)) {
  1376. // Remove duplicate slashes.
  1377. cmSystemTools::ConvertToUnixSlashes(this->FileFound);
  1378. return true;
  1379. }
  1380. return false;
  1381. }
  1382. bool cmFindPackageCommand::FindConfigFile(std::string const& dir,
  1383. std::string& file)
  1384. {
  1385. if (this->IgnoredPaths.count(dir)) {
  1386. return false;
  1387. }
  1388. for (std::string const& c : this->Configs) {
  1389. file = dir;
  1390. file += "/";
  1391. file += c;
  1392. if (this->DebugMode) {
  1393. fprintf(stderr, "Checking file [%s]\n", file.c_str());
  1394. }
  1395. if (cmSystemTools::FileExists(file, true) && this->CheckVersion(file)) {
  1396. // Allow resolving symlinks when the config file is found through a link
  1397. if (this->UseRealPath) {
  1398. file = cmSystemTools::GetRealPath(file);
  1399. }
  1400. return true;
  1401. }
  1402. }
  1403. return false;
  1404. }
  1405. bool cmFindPackageCommand::CheckVersion(std::string const& config_file)
  1406. {
  1407. bool result = false; // by default, assume the version is not ok.
  1408. bool haveResult = false;
  1409. std::string version = "unknown";
  1410. // Get the filename without the .cmake extension.
  1411. std::string::size_type pos = config_file.rfind('.');
  1412. std::string version_file_base = config_file.substr(0, pos);
  1413. // Look for foo-config-version.cmake
  1414. std::string version_file = version_file_base;
  1415. version_file += "-version.cmake";
  1416. if (!haveResult && cmSystemTools::FileExists(version_file, true)) {
  1417. result = this->CheckVersionFile(version_file, version);
  1418. haveResult = true;
  1419. }
  1420. // Look for fooConfigVersion.cmake
  1421. version_file = version_file_base;
  1422. version_file += "Version.cmake";
  1423. if (!haveResult && cmSystemTools::FileExists(version_file, true)) {
  1424. result = this->CheckVersionFile(version_file, version);
  1425. haveResult = true;
  1426. }
  1427. // If no version was requested a versionless package is acceptable.
  1428. if (!haveResult && this->Version.empty()) {
  1429. result = true;
  1430. }
  1431. ConfigFileInfo configFileInfo;
  1432. configFileInfo.filename = config_file;
  1433. configFileInfo.version = version;
  1434. this->ConsideredConfigs.push_back(std::move(configFileInfo));
  1435. return result;
  1436. }
  1437. bool cmFindPackageCommand::CheckVersionFile(std::string const& version_file,
  1438. std::string& result_version)
  1439. {
  1440. // The version file will be loaded in an isolated scope.
  1441. cmMakefile::ScopePushPop varScope(this->Makefile);
  1442. cmMakefile::PolicyPushPop polScope(this->Makefile);
  1443. static_cast<void>(varScope);
  1444. static_cast<void>(polScope);
  1445. // Clear the output variables.
  1446. this->Makefile->RemoveDefinition("PACKAGE_VERSION");
  1447. this->Makefile->RemoveDefinition("PACKAGE_VERSION_UNSUITABLE");
  1448. this->Makefile->RemoveDefinition("PACKAGE_VERSION_COMPATIBLE");
  1449. this->Makefile->RemoveDefinition("PACKAGE_VERSION_EXACT");
  1450. // Set the input variables.
  1451. this->Makefile->AddDefinition("PACKAGE_FIND_NAME", this->Name);
  1452. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION", this->Version);
  1453. char buf[64];
  1454. sprintf(buf, "%u", this->VersionMajor);
  1455. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_MAJOR", buf);
  1456. sprintf(buf, "%u", this->VersionMinor);
  1457. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_MINOR", buf);
  1458. sprintf(buf, "%u", this->VersionPatch);
  1459. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_PATCH", buf);
  1460. sprintf(buf, "%u", this->VersionTweak);
  1461. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_TWEAK", buf);
  1462. sprintf(buf, "%u", this->VersionCount);
  1463. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_COUNT", buf);
  1464. // Load the version check file. Pass NoPolicyScope because we do
  1465. // our own policy push/pop independent of CMP0011.
  1466. bool suitable = false;
  1467. if (this->ReadListFile(version_file, NoPolicyScope)) {
  1468. // Check the output variables.
  1469. bool okay = this->Makefile->IsOn("PACKAGE_VERSION_EXACT");
  1470. bool unsuitable = this->Makefile->IsOn("PACKAGE_VERSION_UNSUITABLE");
  1471. if (!okay && !this->VersionExact) {
  1472. okay = this->Makefile->IsOn("PACKAGE_VERSION_COMPATIBLE");
  1473. }
  1474. // The package is suitable if the version is okay and not
  1475. // explicitly unsuitable.
  1476. suitable = !unsuitable && (okay || this->Version.empty());
  1477. if (suitable) {
  1478. // Get the version found.
  1479. this->VersionFound =
  1480. this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
  1481. // Try to parse the version number and store the results that were
  1482. // successfully parsed.
  1483. unsigned int parsed_major;
  1484. unsigned int parsed_minor;
  1485. unsigned int parsed_patch;
  1486. unsigned int parsed_tweak;
  1487. this->VersionFoundCount =
  1488. sscanf(this->VersionFound.c_str(), "%u.%u.%u.%u", &parsed_major,
  1489. &parsed_minor, &parsed_patch, &parsed_tweak);
  1490. switch (this->VersionFoundCount) {
  1491. case 4:
  1492. this->VersionFoundTweak = parsed_tweak;
  1493. CM_FALLTHROUGH;
  1494. case 3:
  1495. this->VersionFoundPatch = parsed_patch;
  1496. CM_FALLTHROUGH;
  1497. case 2:
  1498. this->VersionFoundMinor = parsed_minor;
  1499. CM_FALLTHROUGH;
  1500. case 1:
  1501. this->VersionFoundMajor = parsed_major;
  1502. CM_FALLTHROUGH;
  1503. default:
  1504. break;
  1505. }
  1506. }
  1507. }
  1508. result_version = this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
  1509. if (result_version.empty()) {
  1510. result_version = "unknown";
  1511. }
  1512. // Succeed if the version is suitable.
  1513. return suitable;
  1514. }
  1515. void cmFindPackageCommand::StoreVersionFound()
  1516. {
  1517. // Store the whole version string.
  1518. std::string ver = this->Name;
  1519. ver += "_VERSION";
  1520. if (this->VersionFound.empty()) {
  1521. this->Makefile->RemoveDefinition(ver);
  1522. } else {
  1523. this->Makefile->AddDefinition(ver, this->VersionFound);
  1524. }
  1525. // Store the version components.
  1526. char buf[64];
  1527. sprintf(buf, "%u", this->VersionFoundMajor);
  1528. this->Makefile->AddDefinition(ver + "_MAJOR", buf);
  1529. sprintf(buf, "%u", this->VersionFoundMinor);
  1530. this->Makefile->AddDefinition(ver + "_MINOR", buf);
  1531. sprintf(buf, "%u", this->VersionFoundPatch);
  1532. this->Makefile->AddDefinition(ver + "_PATCH", buf);
  1533. sprintf(buf, "%u", this->VersionFoundTweak);
  1534. this->Makefile->AddDefinition(ver + "_TWEAK", buf);
  1535. sprintf(buf, "%u", this->VersionFoundCount);
  1536. this->Makefile->AddDefinition(ver + "_COUNT", buf);
  1537. }
  1538. class cmFileListGeneratorBase
  1539. {
  1540. public:
  1541. virtual ~cmFileListGeneratorBase() = default;
  1542. protected:
  1543. bool Consider(std::string const& fullPath, cmFileList& listing);
  1544. private:
  1545. bool Search(cmFileList&);
  1546. virtual bool Search(std::string const& parent, cmFileList&) = 0;
  1547. virtual std::unique_ptr<cmFileListGeneratorBase> Clone() const = 0;
  1548. friend class cmFileList;
  1549. cmFileListGeneratorBase* SetNext(cmFileListGeneratorBase const& next);
  1550. std::unique_ptr<cmFileListGeneratorBase> Next;
  1551. };
  1552. class cmFileList
  1553. {
  1554. public:
  1555. virtual ~cmFileList() = default;
  1556. cmFileList& operator/(cmFileListGeneratorBase const& rhs)
  1557. {
  1558. if (this->Last) {
  1559. this->Last = this->Last->SetNext(rhs);
  1560. } else {
  1561. this->First = rhs.Clone();
  1562. this->Last = this->First.get();
  1563. }
  1564. return *this;
  1565. }
  1566. bool Search()
  1567. {
  1568. if (this->First) {
  1569. return this->First->Search(*this);
  1570. }
  1571. return false;
  1572. }
  1573. private:
  1574. virtual bool Visit(std::string const& fullPath) = 0;
  1575. friend class cmFileListGeneratorBase;
  1576. std::unique_ptr<cmFileListGeneratorBase> First;
  1577. cmFileListGeneratorBase* Last = nullptr;
  1578. };
  1579. class cmFindPackageFileList : public cmFileList
  1580. {
  1581. public:
  1582. cmFindPackageFileList(cmFindPackageCommand* fpc, bool use_suffixes = true)
  1583. : FPC(fpc)
  1584. , UseSuffixes(use_suffixes)
  1585. {
  1586. }
  1587. private:
  1588. bool Visit(std::string const& fullPath) override
  1589. {
  1590. if (this->UseSuffixes) {
  1591. return this->FPC->SearchDirectory(fullPath);
  1592. }
  1593. return this->FPC->CheckDirectory(fullPath);
  1594. }
  1595. cmFindPackageCommand* FPC;
  1596. bool UseSuffixes;
  1597. };
  1598. bool cmFileListGeneratorBase::Search(cmFileList& listing)
  1599. {
  1600. return this->Search("", listing);
  1601. }
  1602. cmFileListGeneratorBase* cmFileListGeneratorBase::SetNext(
  1603. cmFileListGeneratorBase const& next)
  1604. {
  1605. this->Next = next.Clone();
  1606. return this->Next.get();
  1607. }
  1608. bool cmFileListGeneratorBase::Consider(std::string const& fullPath,
  1609. cmFileList& listing)
  1610. {
  1611. if (this->Next) {
  1612. return this->Next->Search(fullPath + "/", listing);
  1613. }
  1614. return listing.Visit(fullPath + "/");
  1615. }
  1616. class cmFileListGeneratorFixed : public cmFileListGeneratorBase
  1617. {
  1618. public:
  1619. cmFileListGeneratorFixed(std::string str)
  1620. : String(std::move(str))
  1621. {
  1622. }
  1623. cmFileListGeneratorFixed(cmFileListGeneratorFixed const& r)
  1624. : String(r.String)
  1625. {
  1626. }
  1627. private:
  1628. std::string String;
  1629. bool Search(std::string const& parent, cmFileList& lister) override
  1630. {
  1631. std::string fullPath = parent + this->String;
  1632. return this->Consider(fullPath, lister);
  1633. }
  1634. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1635. {
  1636. std::unique_ptr<cmFileListGeneratorBase> g(
  1637. new cmFileListGeneratorFixed(*this));
  1638. return g;
  1639. }
  1640. };
  1641. class cmFileListGeneratorEnumerate : public cmFileListGeneratorBase
  1642. {
  1643. public:
  1644. cmFileListGeneratorEnumerate(std::vector<std::string> const& v)
  1645. : Vector(v)
  1646. {
  1647. }
  1648. cmFileListGeneratorEnumerate(cmFileListGeneratorEnumerate const& r)
  1649. : Vector(r.Vector)
  1650. {
  1651. }
  1652. private:
  1653. std::vector<std::string> const& Vector;
  1654. bool Search(std::string const& parent, cmFileList& lister) override
  1655. {
  1656. for (std::string const& i : this->Vector) {
  1657. if (this->Consider(parent + i, lister)) {
  1658. return true;
  1659. }
  1660. }
  1661. return false;
  1662. }
  1663. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1664. {
  1665. std::unique_ptr<cmFileListGeneratorBase> g(
  1666. new cmFileListGeneratorEnumerate(*this));
  1667. return g;
  1668. }
  1669. };
  1670. class cmFileListGeneratorProject : public cmFileListGeneratorBase
  1671. {
  1672. public:
  1673. cmFileListGeneratorProject(std::vector<std::string> const& names,
  1674. cmFindPackageCommand::SortOrderType so,
  1675. cmFindPackageCommand::SortDirectionType sd)
  1676. : Names(names)
  1677. {
  1678. this->SetSort(so, sd);
  1679. }
  1680. cmFileListGeneratorProject(cmFileListGeneratorProject const& r)
  1681. : Names(r.Names)
  1682. {
  1683. this->SetSort(r.SortOrder, r.SortDirection);
  1684. }
  1685. void SetSort(cmFindPackageCommand::SortOrderType o,
  1686. cmFindPackageCommand::SortDirectionType d)
  1687. {
  1688. SortOrder = o;
  1689. SortDirection = d;
  1690. }
  1691. protected:
  1692. // sort parameters
  1693. cmFindPackageCommand::SortOrderType SortOrder;
  1694. cmFindPackageCommand::SortDirectionType SortDirection;
  1695. private:
  1696. std::vector<std::string> const& Names;
  1697. bool Search(std::string const& parent, cmFileList& lister) override
  1698. {
  1699. // Construct a list of matches.
  1700. std::vector<std::string> matches;
  1701. cmsys::Directory d;
  1702. d.Load(parent);
  1703. for (unsigned long i = 0; i < d.GetNumberOfFiles(); ++i) {
  1704. const char* fname = d.GetFile(i);
  1705. if (strcmp(fname, ".") == 0 || strcmp(fname, "..") == 0) {
  1706. continue;
  1707. }
  1708. for (std::string const& n : this->Names) {
  1709. if (cmsysString_strncasecmp(fname, n.c_str(), n.length()) == 0) {
  1710. matches.emplace_back(fname);
  1711. }
  1712. }
  1713. }
  1714. // before testing the matches check if there is a specific sorting order to
  1715. // perform
  1716. if (this->SortOrder != cmFindPackageCommand::None) {
  1717. cmFindPackageCommand::Sort(matches.begin(), matches.end(), SortOrder,
  1718. SortDirection);
  1719. }
  1720. for (std::string const& i : matches) {
  1721. if (this->Consider(parent + i, lister)) {
  1722. return true;
  1723. }
  1724. }
  1725. return false;
  1726. }
  1727. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1728. {
  1729. std::unique_ptr<cmFileListGeneratorBase> g(
  1730. new cmFileListGeneratorProject(*this));
  1731. return g;
  1732. }
  1733. };
  1734. class cmFileListGeneratorMacProject : public cmFileListGeneratorBase
  1735. {
  1736. public:
  1737. cmFileListGeneratorMacProject(std::vector<std::string> const& names,
  1738. const char* ext)
  1739. : Names(names)
  1740. , Extension(ext)
  1741. {
  1742. }
  1743. cmFileListGeneratorMacProject(cmFileListGeneratorMacProject const& r)
  1744. : Names(r.Names)
  1745. , Extension(r.Extension)
  1746. {
  1747. }
  1748. private:
  1749. std::vector<std::string> const& Names;
  1750. std::string Extension;
  1751. bool Search(std::string const& parent, cmFileList& lister) override
  1752. {
  1753. // Construct a list of matches.
  1754. std::vector<std::string> matches;
  1755. cmsys::Directory d;
  1756. d.Load(parent);
  1757. for (unsigned long i = 0; i < d.GetNumberOfFiles(); ++i) {
  1758. const char* fname = d.GetFile(i);
  1759. if (strcmp(fname, ".") == 0 || strcmp(fname, "..") == 0) {
  1760. continue;
  1761. }
  1762. for (std::string name : this->Names) {
  1763. name += this->Extension;
  1764. if (cmsysString_strcasecmp(fname, name.c_str()) == 0) {
  1765. matches.emplace_back(fname);
  1766. }
  1767. }
  1768. }
  1769. for (std::string const& i : matches) {
  1770. if (this->Consider(parent + i, lister)) {
  1771. return true;
  1772. }
  1773. }
  1774. return false;
  1775. }
  1776. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1777. {
  1778. std::unique_ptr<cmFileListGeneratorBase> g(
  1779. new cmFileListGeneratorMacProject(*this));
  1780. return g;
  1781. }
  1782. };
  1783. class cmFileListGeneratorCaseInsensitive : public cmFileListGeneratorBase
  1784. {
  1785. public:
  1786. cmFileListGeneratorCaseInsensitive(std::string str)
  1787. : String(std::move(str))
  1788. {
  1789. }
  1790. cmFileListGeneratorCaseInsensitive(
  1791. cmFileListGeneratorCaseInsensitive const& r)
  1792. : String(r.String)
  1793. {
  1794. }
  1795. private:
  1796. std::string String;
  1797. bool Search(std::string const& parent, cmFileList& lister) override
  1798. {
  1799. // Look for matching files.
  1800. std::vector<std::string> matches;
  1801. cmsys::Directory d;
  1802. d.Load(parent);
  1803. for (unsigned long i = 0; i < d.GetNumberOfFiles(); ++i) {
  1804. const char* fname = d.GetFile(i);
  1805. if (strcmp(fname, ".") == 0 || strcmp(fname, "..") == 0) {
  1806. continue;
  1807. }
  1808. if (cmsysString_strcasecmp(fname, this->String.c_str()) == 0) {
  1809. if (this->Consider(parent + fname, lister)) {
  1810. return true;
  1811. }
  1812. }
  1813. }
  1814. return false;
  1815. }
  1816. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1817. {
  1818. std::unique_ptr<cmFileListGeneratorBase> g(
  1819. new cmFileListGeneratorCaseInsensitive(*this));
  1820. return g;
  1821. }
  1822. };
  1823. class cmFileListGeneratorGlob : public cmFileListGeneratorBase
  1824. {
  1825. public:
  1826. cmFileListGeneratorGlob(std::string str)
  1827. : Pattern(std::move(str))
  1828. {
  1829. }
  1830. cmFileListGeneratorGlob(cmFileListGeneratorGlob const& r)
  1831. : Pattern(r.Pattern)
  1832. {
  1833. }
  1834. private:
  1835. std::string Pattern;
  1836. bool Search(std::string const& parent, cmFileList& lister) override
  1837. {
  1838. // Glob the set of matching files.
  1839. std::string expr = parent;
  1840. expr += this->Pattern;
  1841. cmsys::Glob g;
  1842. if (!g.FindFiles(expr)) {
  1843. return false;
  1844. }
  1845. std::vector<std::string> const& files = g.GetFiles();
  1846. // Look for directories among the matches.
  1847. for (std::string const& f : files) {
  1848. if (cmSystemTools::FileIsDirectory(f)) {
  1849. if (this->Consider(f, lister)) {
  1850. return true;
  1851. }
  1852. }
  1853. }
  1854. return false;
  1855. }
  1856. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1857. {
  1858. return cm::make_unique<cmFileListGeneratorGlob>(*this);
  1859. }
  1860. };
  1861. bool cmFindPackageCommand::SearchPrefix(std::string const& prefix_in)
  1862. {
  1863. assert(!prefix_in.empty() && prefix_in.back() == '/');
  1864. if (this->DebugMode) {
  1865. fprintf(stderr, "Checking prefix [%s]\n", prefix_in.c_str());
  1866. }
  1867. // Skip this if the prefix does not exist.
  1868. if (!cmSystemTools::FileIsDirectory(prefix_in)) {
  1869. return false;
  1870. }
  1871. // PREFIX/ (useful on windows or in build trees)
  1872. if (this->SearchDirectory(prefix_in)) {
  1873. return true;
  1874. }
  1875. // Strip the trailing slash because the path generator is about to
  1876. // add one.
  1877. std::string prefix = prefix_in.substr(0, prefix_in.size() - 1);
  1878. // PREFIX/(cmake|CMake)/ (useful on windows or in build trees)
  1879. {
  1880. cmFindPackageFileList lister(this);
  1881. lister / cmFileListGeneratorFixed(prefix) /
  1882. cmFileListGeneratorCaseInsensitive("cmake");
  1883. if (lister.Search()) {
  1884. return true;
  1885. }
  1886. }
  1887. // PREFIX/(Foo|foo|FOO).*/
  1888. {
  1889. cmFindPackageFileList lister(this);
  1890. lister / cmFileListGeneratorFixed(prefix) /
  1891. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1892. this->SortDirection);
  1893. if (lister.Search()) {
  1894. return true;
  1895. }
  1896. }
  1897. // PREFIX/(Foo|foo|FOO).*/(cmake|CMake)/
  1898. {
  1899. cmFindPackageFileList lister(this);
  1900. lister / cmFileListGeneratorFixed(prefix) /
  1901. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1902. this->SortDirection) /
  1903. cmFileListGeneratorCaseInsensitive("cmake");
  1904. if (lister.Search()) {
  1905. return true;
  1906. }
  1907. }
  1908. // Construct list of common install locations (lib and share).
  1909. std::vector<std::string> common;
  1910. if (!this->LibraryArchitecture.empty()) {
  1911. common.push_back("lib/" + this->LibraryArchitecture);
  1912. }
  1913. if (this->UseLib32Paths) {
  1914. common.emplace_back("lib32");
  1915. }
  1916. if (this->UseLib64Paths) {
  1917. common.emplace_back("lib64");
  1918. }
  1919. if (this->UseLibx32Paths) {
  1920. common.emplace_back("libx32");
  1921. }
  1922. common.emplace_back("lib");
  1923. common.emplace_back("share");
  1924. // PREFIX/(lib/ARCH|lib*|share)/cmake/(Foo|foo|FOO).*/
  1925. {
  1926. cmFindPackageFileList lister(this);
  1927. lister / cmFileListGeneratorFixed(prefix) /
  1928. cmFileListGeneratorEnumerate(common) /
  1929. cmFileListGeneratorFixed("cmake") /
  1930. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1931. this->SortDirection);
  1932. if (lister.Search()) {
  1933. return true;
  1934. }
  1935. }
  1936. // PREFIX/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/
  1937. {
  1938. cmFindPackageFileList lister(this);
  1939. lister / cmFileListGeneratorFixed(prefix) /
  1940. cmFileListGeneratorEnumerate(common) /
  1941. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1942. this->SortDirection);
  1943. if (lister.Search()) {
  1944. return true;
  1945. }
  1946. }
  1947. // PREFIX/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/(cmake|CMake)/
  1948. {
  1949. cmFindPackageFileList lister(this);
  1950. lister / cmFileListGeneratorFixed(prefix) /
  1951. cmFileListGeneratorEnumerate(common) /
  1952. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1953. this->SortDirection) /
  1954. cmFileListGeneratorCaseInsensitive("cmake");
  1955. if (lister.Search()) {
  1956. return true;
  1957. }
  1958. }
  1959. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/cmake/(Foo|foo|FOO).*/
  1960. {
  1961. cmFindPackageFileList lister(this);
  1962. lister / cmFileListGeneratorFixed(prefix) /
  1963. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1964. this->SortDirection) /
  1965. cmFileListGeneratorEnumerate(common) /
  1966. cmFileListGeneratorFixed("cmake") /
  1967. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1968. this->SortDirection);
  1969. if (lister.Search()) {
  1970. return true;
  1971. }
  1972. }
  1973. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/
  1974. {
  1975. cmFindPackageFileList lister(this);
  1976. lister / cmFileListGeneratorFixed(prefix) /
  1977. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1978. this->SortDirection) /
  1979. cmFileListGeneratorEnumerate(common) /
  1980. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1981. this->SortDirection);
  1982. if (lister.Search()) {
  1983. return true;
  1984. }
  1985. }
  1986. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/(cmake|CMake)/
  1987. {
  1988. cmFindPackageFileList lister(this);
  1989. lister / cmFileListGeneratorFixed(prefix) /
  1990. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1991. this->SortDirection) /
  1992. cmFileListGeneratorEnumerate(common) /
  1993. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1994. this->SortDirection) /
  1995. cmFileListGeneratorCaseInsensitive("cmake");
  1996. if (lister.Search()) {
  1997. return true;
  1998. }
  1999. }
  2000. return false;
  2001. }
  2002. bool cmFindPackageCommand::SearchFrameworkPrefix(std::string const& prefix_in)
  2003. {
  2004. assert(!prefix_in.empty() && prefix_in.back() == '/');
  2005. if (this->DebugMode) {
  2006. fprintf(stderr, "Checking framework prefix [%s]\n", prefix_in.c_str());
  2007. }
  2008. // Strip the trailing slash because the path generator is about to
  2009. // add one.
  2010. std::string prefix = prefix_in.substr(0, prefix_in.size() - 1);
  2011. // <prefix>/Foo.framework/Resources/
  2012. {
  2013. cmFindPackageFileList lister(this);
  2014. lister / cmFileListGeneratorFixed(prefix) /
  2015. cmFileListGeneratorMacProject(this->Names, ".framework") /
  2016. cmFileListGeneratorFixed("Resources");
  2017. if (lister.Search()) {
  2018. return true;
  2019. }
  2020. }
  2021. // <prefix>/Foo.framework/Resources/CMake/
  2022. {
  2023. cmFindPackageFileList lister(this);
  2024. lister / cmFileListGeneratorFixed(prefix) /
  2025. cmFileListGeneratorMacProject(this->Names, ".framework") /
  2026. cmFileListGeneratorFixed("Resources") /
  2027. cmFileListGeneratorCaseInsensitive("cmake");
  2028. if (lister.Search()) {
  2029. return true;
  2030. }
  2031. }
  2032. // <prefix>/Foo.framework/Versions/*/Resources/
  2033. {
  2034. cmFindPackageFileList lister(this);
  2035. lister / cmFileListGeneratorFixed(prefix) /
  2036. cmFileListGeneratorMacProject(this->Names, ".framework") /
  2037. cmFileListGeneratorFixed("Versions") /
  2038. cmFileListGeneratorGlob("*/Resources");
  2039. if (lister.Search()) {
  2040. return true;
  2041. }
  2042. }
  2043. // <prefix>/Foo.framework/Versions/*/Resources/CMake/
  2044. {
  2045. cmFindPackageFileList lister(this);
  2046. lister / cmFileListGeneratorFixed(prefix) /
  2047. cmFileListGeneratorMacProject(this->Names, ".framework") /
  2048. cmFileListGeneratorFixed("Versions") /
  2049. cmFileListGeneratorGlob("*/Resources") /
  2050. cmFileListGeneratorCaseInsensitive("cmake");
  2051. if (lister.Search()) {
  2052. return true;
  2053. }
  2054. }
  2055. return false;
  2056. }
  2057. bool cmFindPackageCommand::SearchAppBundlePrefix(std::string const& prefix_in)
  2058. {
  2059. assert(!prefix_in.empty() && prefix_in.back() == '/');
  2060. if (this->DebugMode) {
  2061. fprintf(stderr, "Checking bundle prefix [%s]\n", prefix_in.c_str());
  2062. }
  2063. // Strip the trailing slash because the path generator is about to
  2064. // add one.
  2065. std::string prefix = prefix_in.substr(0, prefix_in.size() - 1);
  2066. // <prefix>/Foo.app/Contents/Resources
  2067. {
  2068. cmFindPackageFileList lister(this);
  2069. lister / cmFileListGeneratorFixed(prefix) /
  2070. cmFileListGeneratorMacProject(this->Names, ".app") /
  2071. cmFileListGeneratorFixed("Contents/Resources");
  2072. if (lister.Search()) {
  2073. return true;
  2074. }
  2075. }
  2076. // <prefix>/Foo.app/Contents/Resources/CMake
  2077. {
  2078. cmFindPackageFileList lister(this);
  2079. lister / cmFileListGeneratorFixed(prefix) /
  2080. cmFileListGeneratorMacProject(this->Names, ".app") /
  2081. cmFileListGeneratorFixed("Contents/Resources") /
  2082. cmFileListGeneratorCaseInsensitive("cmake");
  2083. if (lister.Search()) {
  2084. return true;
  2085. }
  2086. }
  2087. return false;
  2088. }
  2089. // TODO: Debug cmsys::Glob double slash problem.