cmFindPackageCommand.cxx 68 KB

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