1//===-- UserIDResolver.h ----------------------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef LLDB_UTILITY_USERIDRESOLVER_H
10#define LLDB_UTILITY_USERIDRESOLVER_H
11
12#include "llvm/ADT/DenseMap.h"
13#include "llvm/ADT/StringRef.h"
14#include <mutex>
15
16namespace lldb_private {
17
18/// An abstract interface for things that know how to map numeric user/group IDs
19/// into names. It caches the resolved names to avoid repeating expensive
20/// queries. The cache is internally protected by a mutex, so concurrent queries
21/// are safe.
22class UserIDResolver {
23public:
24  typedef uint32_t id_t;
25  virtual ~UserIDResolver(); // anchor
26
27  llvm::Optional<llvm::StringRef> GetUserName(id_t uid) {
28    return Get(uid, m_uid_cache, &UserIDResolver::DoGetUserName);
29  }
30  llvm::Optional<llvm::StringRef> GetGroupName(id_t gid) {
31    return Get(gid, m_gid_cache, &UserIDResolver::DoGetGroupName);
32  }
33
34  /// Returns a resolver which returns a failure value for each query. Useful as
35  /// a fallback value for the case when we know all lookups will fail.
36  static UserIDResolver &GetNoopResolver();
37
38protected:
39  virtual llvm::Optional<std::string> DoGetUserName(id_t uid) = 0;
40  virtual llvm::Optional<std::string> DoGetGroupName(id_t gid) = 0;
41
42private:
43  using Map = llvm::DenseMap<id_t, llvm::Optional<std::string>>;
44
45  llvm::Optional<llvm::StringRef>
46  Get(id_t id, Map &cache,
47      llvm::Optional<std::string> (UserIDResolver::*do_get)(id_t));
48
49  std::mutex m_mutex;
50  Map m_uid_cache;
51  Map m_gid_cache;
52};
53
54} // namespace lldb_private
55
56#endif // #ifndef LLDB_HOST_USERIDRESOLVER_H
57