Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stack overflow protection #4335

Open
chakaz opened this issue Dec 18, 2024 · 2 comments
Open

Stack overflow protection #4335

chakaz opened this issue Dec 18, 2024 · 2 comments

Comments

@chakaz
Copy link
Collaborator

chakaz commented Dec 18, 2024

Since we use Fibers, we can't utilize many tools (like Valgrind, -fstack-protector) to detect stack overflows.

Instead, we may implement a simple protection of our own (maybe in Debug builds only, or enabled with a flag):

  • Instead of allocating 32kb like we do today, we'll allocate 64k
  • We'll configure the last 32kb to be protected memory (mprotect(PROT_NONE))
  • Before freeing the memory (upon Fiber termination) we'll remove the protection
@chakaz
Copy link
Collaborator Author

chakaz commented Dec 18, 2024

A working allocator example:

class ProtectedStdMallocResource : public PMR_NS::memory_resource {
 private:
  void* do_allocate(std::size_t size, std::size_t align) final {
    void* ptr = aligned_alloc(getpagesize(), size * 2);
    CHECK_EQ(mprotect(ptr, size, PROT_NONE), 0);
    return shift_bytes(ptr, size);
  }

  void do_deallocate(void* ptr, std::size_t size, std::size_t align) final {
    ptr = shift_bytes(ptr, -size);
    CHECK_EQ(mprotect(ptr, size, PROT_READ | PROT_WRITE), 0);
    free(ptr);
  }

  bool do_is_equal(const PMR_NS::memory_resource& o) const noexcept final {
    return this == &o;
  }

  void* shift_bytes(void* ptr, size_t bytes) {
    return static_cast<uint8_t*>(ptr) + bytes;
  }
} protected_stack_alloc;

Then in dfly_main.cc:

  fb2::SetDefaultStackResource(&protected_stack_alloc, kFiberDefaultStackSize);

The only problem is that this is not used for the dispatch fibers, which use the fixed allocator so we need to plug that in there as well

@romange
Copy link
Collaborator

romange commented Dec 23, 2024

For now, helio provides a poor man solution, though I think it's very effective because can be used in both release and debug builds. See #4349

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants