Botan 3.14.1
Crypto and TLS for C&
ffi_util.h
Go to the documentation of this file.
1/*
2* (C) 2015,2017 Jack Lloyd
3*
4* Botan is released under the Simplified BSD License (see license.txt)
5*/
6
7#ifndef BOTAN_FFI_UTILS_H_
8#define BOTAN_FFI_UTILS_H_
9
10#include <botan/exceptn.h>
11#include <botan/ffi.h>
12#include <botan/internal/mem_utils.h>
13#include <concepts>
14#include <cstdint>
15#include <cstring>
16#include <exception>
17#include <memory>
18#include <type_traits>
19
20namespace Botan_FFI {
21
23
25 public:
26 FFI_Error(std::string_view what, int err_code) : Exception("FFI error", what), m_err_code(err_code) {}
27
28 int error_code() const noexcept override { return m_err_code; }
29
31
32 private:
33 int m_err_code;
34};
35
36namespace detail {
37
38template <typename T>
39struct is_std_unique_pointer : std::false_type {};
40
41template <typename T, typename Deleter>
42struct is_std_unique_pointer<std::unique_ptr<T, Deleter>> : std::true_type {};
43
44template <typename T>
45struct is_std_shared_pointer : std::false_type {};
46
47template <typename T>
48struct is_std_shared_pointer<std::shared_ptr<T>> : std::true_type {};
49
50} // namespace detail
51
52template <typename T>
54
55/**
56 * Base class of all FFI object handles. This allows dealing with arbitrary
57 * handles generically, e.g. when the downstream consumer passes them as void*.
58 */
60 protected:
61 explicit constexpr botan_ffi_obj_base(uint32_t magic) : m_magic(magic), m_magic_expected(magic) {}
62
63 /**
64 * Protected destructor to ensure that this class is never destroyed via
65 * this base type.
66 */
68
69 public:
70 botan_ffi_obj_base(const botan_ffi_obj_base& other) = delete;
74
75 /// @returns true if the underlying type is managed via a shared_ptr
76 virtual bool is_shared() const = 0;
77
78 /// @returns internal reference count of the underlying object
79 virtual size_t use_count() const = 0;
80
81 /**
82 * Heuristic, type-agnostic check whether some casted void* pointer
83 * plausibly points to a live FFI object handle. This deliberately does
84 * not use virtual dispatch, so that the check works without relying on a
85 * potentially bogus vtable.
86 *
87 * @note Calling this on any pointer that isn't actually a Botan FFI
88 * object handle is undefined behavior. This is really just a best
89 * effort check to avoid dereferencing a pointer that is definitely
90 * not a valid FFI object handle.
91 *
92 * @returns false if the this-pointer definitely does not reference an
93 * alive FFI object handle. In contrast, returns true if it
94 * plausibly references an alive FFI object with the possibility
95 * of false-positives.
96 */
97 bool appears_to_be_valid_ffi_handle() const { return m_magic != 0 && m_magic == m_magic_expected; }
98
99 protected:
100 void invalidate_magic() { m_magic = 0; }
101
102 uint32_t magic() const { return m_magic; }
103
104 private:
105 uint32_t m_magic;
106 uint32_t m_magic_expected;
107};
108
109/**
110 * Base class for all FFI object handles wrapped around some specific type in
111 * the library. The inner type is managed by a configurable smart pointer type
112 * (e.g. std::unique_ptr or std::shared_ptr).
113 */
114template <typename T, uint32_t MAGIC, template <typename... Args> typename PtrType>
115 requires ffi_object_smart_pointer<PtrType<T>>
117 public:
118 using element_type = T;
119 using smart_pointer_type = PtrType<T>;
120
121 public:
122 explicit botan_ffi_obj(smart_pointer_type obj) : botan_ffi_obj_base(MAGIC), m_obj(std::move(obj)) {}
123
124 virtual ~botan_ffi_obj() {
126 m_obj.reset(); // NOLINT(*-ambiguous-smartptr-reset-call)
127 }
128
129 botan_ffi_obj(const botan_ffi_obj& other) = delete;
130 botan_ffi_obj(botan_ffi_obj&& other) = delete;
131 botan_ffi_obj& operator=(const botan_ffi_obj& other) = delete;
133
134 bool magic_ok() const { return magic() == MAGIC; }
135
137
138 size_t use_count() const final {
140 return static_cast<size_t>(m_obj.use_count());
141 } else {
142 return 1; // unique_ptr always has an implicit use count of 1
143 }
144 }
145
146 /// Retrieve the raw pointer to the underlying object. May be nullptr.
147 T* unsafe_get() const { return m_obj.get(); }
148
149 /// Retrieve the smart pointer to the underlying object. May be invalid.
151
152 /// Retrieve the smart pointer to the underlying object. May be invalid.
153 const smart_pointer_type& unsafe_get_sp() const { return m_obj; }
154
155 private:
156 smart_pointer_type m_obj;
157};
158
159template <typename T>
160concept ffi_object = std::derived_from<T, botan_ffi_obj_base>;
161
162// NOLINTBEGIN(*-macro-usage)
163
164#define BOTAN_FFI_DECLARE_UNIQUE_STRUCT(NAME, TYPE, MAGIC) \
165 struct NAME final : public Botan_FFI::botan_ffi_obj<TYPE, MAGIC, std::unique_ptr> { \
166 using botan_ffi_obj::botan_ffi_obj; \
167 }
168
169#define BOTAN_FFI_DECLARE_SHARED_STRUCT(NAME, TYPE, MAGIC) \
170 struct NAME final : public Botan_FFI::botan_ffi_obj<TYPE, MAGIC, std::shared_ptr> { \
171 using botan_ffi_obj::botan_ffi_obj; \
172 }
173
174#define BOTAN_FFI_DECLARE_DUMMY_STRUCT(NAME, MAGIC) \
175 struct NAME final : public Botan_FFI::botan_ffi_obj<int, MAGIC, std::unique_ptr> {}
176
177// NOLINTEND(*-macro-usage)
178
179// Declared in ffi.cpp
181
182int ffi_error_exception_thrown(const char* func_name, const char* exn, int rc);
183
184int ffi_error_exception_thrown(const char* func_name, const char* exn, Botan::ErrorType err);
185
186/**
187 * Checked access to a reference of the underlying object wrapped in the
188 * FFI handle @p p.
189 */
190template <ffi_object T>
191auto safe_get(T* p) -> typename T::element_type& {
192 if(!p) {
193 throw FFI_Error("Null pointer argument", BOTAN_FFI_ERROR_NULL_POINTER);
194 }
195 if(!p->magic_ok()) {
196 throw FFI_Error("Bad magic in ffi object", BOTAN_FFI_ERROR_INVALID_OBJECT);
197 }
198
199 if(auto* t = p->unsafe_get()) {
200 return *t;
201 }
202
203 throw FFI_Error("Invalid object pointer", BOTAN_FFI_ERROR_INVALID_OBJECT);
204}
205
206/**
207 * Checked access to a reference of the smart pointer of the underlying object
208 * wrapped in the FFI handle @p p. Note that the smart pointer is returned by
209 * reference, so that the caller can copy it (if it is a std::shared_ptr).
210 */
211template <ffi_object T>
212auto safe_get_sp(T* p) -> const typename T::smart_pointer_type& {
213 if(!p) {
214 throw FFI_Error("Null pointer argument", BOTAN_FFI_ERROR_NULL_POINTER);
215 }
216 if(!p->magic_ok()) {
217 throw FFI_Error("Bad magic in ffi object", BOTAN_FFI_ERROR_INVALID_OBJECT);
218 }
219
220 auto& sp = p->unsafe_get_sp();
221 if(sp == nullptr) {
222 throw FFI_Error("Invalid object pointer", BOTAN_FFI_ERROR_INVALID_OBJECT);
223 }
224
225 return sp;
226}
227
228template <std::invocable T>
229int ffi_guard_thunk(const char* func_name, T thunk) {
231
232 try {
233 return thunk();
234 } catch(std::bad_alloc&) {
235 return ffi_error_exception_thrown(func_name, "bad_alloc", BOTAN_FFI_ERROR_OUT_OF_MEMORY);
236 } catch(Botan_FFI::FFI_Error& e) {
237 return ffi_error_exception_thrown(func_name, e.what(), e.error_code());
238 } catch(Botan::Exception& e) {
239 return ffi_error_exception_thrown(func_name, e.what(), e.error_type());
240 } catch(std::exception& e) {
242 } catch(...) {
243 return ffi_error_exception_thrown(func_name, "unknown exception", BOTAN_FFI_ERROR_EXCEPTION_THROWN);
244 }
245}
246
247namespace detail {
248
249template <typename T>
250concept ffi_visit_result = std::is_void_v<T> || std::same_as<T, int> || std::same_as<T, BOTAN_FFI_ERROR>;
251
252template <typename FnT, typename ArgT>
254
255} // namespace detail
256
257template <typename FnT, typename HandleT>
259
260template <typename FnT, typename HandleT>
262
263template <typename FnT, typename HandleT>
265
266/**
267 * Visit the underlying object wrapped in the FFI handle @p o with the visitor
268 * function @p func. The visitor function can either take a reference to the
269 * underlying object or a reference to the smart pointer of the underlying
270 * object and must return either void, BOTAN_FFI_ERROR or int.
271 *
272 * Note that a visitor lambda function with a generic parameter (e.g. `auto&`)
273 * will receive a reference to the underlying object, not the smart pointer.
274 */
275template <ffi_object HandleT, ffi_visitor_fn<HandleT> VisitorFnT>
276int botan_ffi_visit(HandleT* o, VisitorFnT func, const char* func_name) {
277 if(!o) {
279 }
280
281 if(!o->magic_ok()) {
283 }
284
285 const auto& p = o->unsafe_get_sp();
286 if(p == nullptr) {
288 }
289
290 auto call_visitor = [&](auto&& ref) -> int {
291 if constexpr(std::is_void_v<decltype(func(ref))>) {
292 return ffi_guard_thunk(func_name, [&] {
293 func(ref);
294 return BOTAN_FFI_SUCCESS;
295 });
296 } else {
297 return ffi_guard_thunk(func_name, [&] { return func(ref); });
298 }
299 };
300
301 // Call the visitor either with a reference to the visitee or its inner smart
302 // pointer depending on what the visitor expects. If it could handle both,
303 // the reference is preferred.
305 return call_visitor(*p);
306 } else {
307 return call_visitor(p);
308 }
309}
310
311// TODO: C++20 introduces std::source_location which will allow to eliminate this
312// macro altogether. Instead, using code would just call the C++ function
313// that makes use of std::source_location like so:
314//
315// template<typename T, uint32_t M, typename F>
316// int botan_ffi_visit(botan_ffi_obj<T, M, std::unique_ptr>* obj, F func,
317// const std::source_location sl = std::source_location::current())
318// {
319// // [...]
320// if constexpr(...)
321// {
322// return ffi_guard_thunk(sl.function_name(), [&] { return func(*p); })
323// }
324// // [...]
325// }
326// NOLINTNEXTLINE(*-macro-usage)
327#define BOTAN_FFI_VISIT(obj, lambda) botan_ffi_visit(obj, lambda, __func__)
328
329template <ffi_object T>
330int ffi_delete_object(T* obj, const char* func_name) {
331 return ffi_guard_thunk(func_name, [=]() -> int {
332 // ignore delete of null objects
333 if(obj == nullptr) {
334 return BOTAN_FFI_SUCCESS;
335 }
336
337 if(!obj->magic_ok()) {
339 }
340
341 delete obj; // NOLINT(*-owning-memory)
342 return BOTAN_FFI_SUCCESS;
343 });
344}
345
346template <typename T, typename... Args>
347BOTAN_FFI_ERROR ffi_new_object(T* obj, Args&&... args) {
348 if(obj == nullptr) {
350 }
351 // NOLINTNEXTLINE(*-owning-memory)
352 *obj = new std::remove_pointer_t<T>(std::forward<Args>(args)...);
353 return BOTAN_FFI_SUCCESS;
354}
355
356// NOLINTNEXTLINE(*-macro-usage)
357#define BOTAN_FFI_CHECKED_DELETE(o) ffi_delete_object(o, __func__)
358
359inline int invoke_view_callback(botan_view_bin_fn view, botan_view_ctx ctx, std::span<const uint8_t> buf) {
360 if(view == nullptr) {
362 }
363 return view(ctx, buf.data(), buf.size());
364}
365
366// Should not be std::string_view as we rely on being able to NULL terminate
367inline int invoke_view_callback(botan_view_str_fn view, botan_view_ctx ctx, const std::string& str) {
368 if(view == nullptr) {
370 }
371 return view(ctx, str.data(), str.size() + 1);
372}
373
375 uint8_t* out_ptr;
376 size_t* out_len;
377};
378
379int botan_view_bin_bounce_fn(botan_view_ctx ctx, const uint8_t* buf, size_t len);
380int botan_view_str_bounce_fn(botan_view_ctx ctx, const char* str, size_t len);
381
382template <typename Fn, typename... Args>
383int copy_view_bin(uint8_t out[], size_t* out_len, Fn fn, Args... args) {
384 if(out_len == nullptr) {
386 }
387 botan_view_bounce_struct ctx{out, out_len};
388 return fn(args..., &ctx, botan_view_bin_bounce_fn);
389}
390
391template <typename Fn, typename... Args>
392int copy_view_str(uint8_t out[], size_t* out_len, Fn fn, Args... args) {
393 if(any_null_pointers(fn, out_len)) {
395 }
396 botan_view_bounce_struct ctx{out, out_len};
397 return fn(args..., &ctx, botan_view_str_bounce_fn);
398}
399
400template <std::integral T>
401 requires(sizeof(T) == 1)
402inline int check_and_prepare_output_space(T out[], size_t* out_len, size_t required_len) {
403 if(out_len == nullptr) {
405 }
406
407 const size_t avail = *out_len;
408 *out_len = required_len;
409
410 if(avail < required_len || out == nullptr) {
411 if(out != nullptr) {
412 std::memset(out, 0, sizeof(T) * avail);
413 }
415 } else {
416 return BOTAN_FFI_SUCCESS;
417 }
418}
419
420template <std::integral T>
421inline int write_output(T out[], size_t* out_len, const T buf[], size_t buf_len) {
422 static_assert(sizeof(T) == 1, "T should be either uint8_t or char");
423
424 const auto rc = check_and_prepare_output_space(out, out_len, buf_len);
425 if(rc != BOTAN_FFI_SUCCESS) {
426 return rc;
427 }
428
429 if(out != nullptr) {
430 std::memcpy(out, buf, sizeof(T) * buf_len);
431 }
432
433 return BOTAN_FFI_SUCCESS;
434}
435
436inline int write_vec_output(uint8_t out[], size_t* out_len, std::span<const uint8_t> buf) {
437 return write_output<uint8_t>(out, out_len, buf.data(), buf.size());
438}
439
440inline int write_str_output(char out[], size_t* out_len, const std::string& str) {
441 return write_output<char>(out, out_len, str.data(), str.size() + 1);
442}
443
444} // namespace Botan_FFI
445
446#endif
#define BOTAN_UNSTABLE_API
Definition api.h:34
const char * what() const noexcept override
Definition exceptn.h:94
Exception(std::string_view msg)
Definition exceptn.cpp:71
Botan::ErrorType error_type() const noexcept override
Definition ffi_util.h:30
FFI_Error(std::string_view what, int err_code)
Definition ffi_util.h:26
int error_code() const noexcept override
Definition ffi_util.h:28
int(* botan_view_bin_fn)(botan_view_ctx view_ctx, const uint8_t *data, size_t len)
Definition ffi.h:161
void * botan_view_ctx
Definition ffi.h:152
BOTAN_FFI_ERROR
Definition ffi.h:113
@ BOTAN_FFI_ERROR_EXCEPTION_THROWN
Definition ffi.h:125
@ BOTAN_FFI_ERROR_OUT_OF_MEMORY
Definition ffi.h:126
@ BOTAN_FFI_ERROR_INVALID_OBJECT
Definition ffi.h:139
@ BOTAN_FFI_ERROR_NULL_POINTER
Definition ffi.h:131
@ BOTAN_FFI_SUCCESS
Definition ffi.h:114
@ BOTAN_FFI_ERROR_INSUFFICIENT_BUFFER_SPACE
Definition ffi.h:122
int(* botan_view_str_fn)(botan_view_ctx view_ctx, const char *str, size_t len)
Definition ffi.h:170
int botan_ffi_visit(HandleT *o, VisitorFnT func, const char *func_name)
Definition ffi_util.h:276
void ffi_clear_last_exception()
Definition ffi.cpp:92
int invoke_view_callback(botan_view_bin_fn view, botan_view_ctx ctx, std::span< const uint8_t > buf)
Definition ffi_util.h:359
auto safe_get_sp(T *p) -> const typename T::smart_pointer_type &
Definition ffi_util.h:212
int ffi_error_exception_thrown(const char *func_name, const char *exn, int rc)
Definition ffi.cpp:96
int botan_view_bin_bounce_fn(botan_view_ctx vctx, const uint8_t *buf, size_t len)
Definition ffi.cpp:126
int botan_view_str_bounce_fn(botan_view_ctx vctx, const char *str, size_t len)
Definition ffi.cpp:122
int copy_view_bin(uint8_t out[], size_t *out_len, Fn fn, Args... args)
Definition ffi_util.h:383
auto safe_get(T *p) -> typename T::element_type &
Definition ffi_util.h:191
int check_and_prepare_output_space(T out[], size_t *out_len, size_t required_len)
Definition ffi_util.h:402
int ffi_delete_object(T *obj, const char *func_name)
Definition ffi_util.h:330
BOTAN_FFI_ERROR ffi_new_object(T *obj, Args &&... args)
Definition ffi_util.h:347
int copy_view_str(uint8_t out[], size_t *out_len, Fn fn, Args... args)
Definition ffi_util.h:392
int write_output(T out[], size_t *out_len, const T buf[], size_t buf_len)
Definition ffi_util.h:421
int ffi_guard_thunk(const char *func_name, T thunk)
Definition ffi_util.h:229
int write_vec_output(uint8_t out[], size_t *out_len, std::span< const uint8_t > buf)
Definition ffi_util.h:436
bool any_null_pointers(Ptrs... ptr)
Definition mem_utils.h:54
int write_str_output(char out[], size_t *out_len, const std::string &str)
Definition ffi_util.h:440
ErrorType
Definition exceptn.h:21
bool any_null_pointers(Ptrs... ptr)
Definition mem_utils.h:54
botan_ffi_obj_base(botan_ffi_obj_base &&other)=delete
botan_ffi_obj_base(const botan_ffi_obj_base &other)=delete
virtual size_t use_count() const =0
bool appears_to_be_valid_ffi_handle() const
Definition ffi_util.h:97
botan_ffi_obj_base & operator=(const botan_ffi_obj_base &other)=delete
virtual bool is_shared() const =0
botan_ffi_obj_base & operator=(botan_ffi_obj_base &&other)=delete
constexpr botan_ffi_obj_base(uint32_t magic)
Definition ffi_util.h:61
const smart_pointer_type & unsafe_get_sp() const
Retrieve the smart pointer to the underlying object. May be invalid.
Definition ffi_util.h:153
bool magic_ok() const
Definition ffi_util.h:134
size_t use_count() const final
Definition ffi_util.h:138
botan_ffi_obj & operator=(const botan_ffi_obj &other)=delete
smart_pointer_type & unsafe_get_sp()
Retrieve the smart pointer to the underlying object. May be invalid.
Definition ffi_util.h:150
PtrType< T > smart_pointer_type
Definition ffi_util.h:119
botan_ffi_obj(botan_ffi_obj &&other)=delete
T * unsafe_get() const
Retrieve the raw pointer to the underlying object. May be nullptr.
Definition ffi_util.h:147
bool is_shared() const final
Definition ffi_util.h:136
botan_ffi_obj(smart_pointer_type obj)
Definition ffi_util.h:122
botan_ffi_obj(const botan_ffi_obj &other)=delete
botan_ffi_obj & operator=(botan_ffi_obj &&other)=delete