Skip to content

Commit

Permalink
fix double free problem in the C++ guest (éxported resources)
Browse files Browse the repository at this point in the history
  • Loading branch information
cpetig committed Jun 9, 2024
1 parent 90082e5 commit 1fe949b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 9 deletions.
2 changes: 1 addition & 1 deletion crates/cpp/helper-types/wit-common.h
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

#include <assert.h>
#include <map>
#include <stdint.h>
#include <stddef.h> // size_t
#include <stdint.h>
#if __cplusplus > 202001L
#include <span>
#else
Expand Down
22 changes: 14 additions & 8 deletions crates/cpp/helper-types/wit-guest.h
Original file line number Diff line number Diff line change
Expand Up @@ -90,23 +90,29 @@ template <class T> class vector {
///
/// It registers with the host and should remain in a static location.
/// Typically referenced by the Owned type
///
/// Note that deregistering will cause the host to call Dtor which
/// in turn frees the object.
template <class R> class ResourceExportBase {
public:
struct Deleter {
void operator()(R *ptr) const { R::Dtor(ptr); }
struct Deregister {
void operator()(R *ptr) const {
// probably always true because of unique_ptr wrapping, TODO: check
if (ptr->handle >= 0) {
// we can't deallocate because the host calls Dtor
R::ResourceDrop(ptr->handle);
}
}
};
typedef std::unique_ptr<R, Deleter> Owned;
typedef std::unique_ptr<R, Deregister> Owned;

static const int32_t invalid = -1;

int32_t handle;

ResourceExportBase() : handle(R::ResourceNew((R *)this)) {}
~ResourceExportBase() {
if (handle >= 0) {
R::ResourceDrop(handle);
}
}
// because this function is called by the host via Dtor we must not deregister
~ResourceExportBase() {}
ResourceExportBase(ResourceExportBase const &) = delete;
ResourceExportBase(ResourceExportBase &&) = delete;
ResourceExportBase &operator=(ResourceExportBase &&b) = delete;
Expand Down

0 comments on commit 1fe949b

Please sign in to comment.