+ if (has_code()) {
+ xbt_assert((smx_context_stack_size & 0xf) == 0, "smx_context_stack_size should be multiple of 16");
+ if (smx_context_guard_size > 0 && not MC_is_active()) {
+#if !defined(PTH_STACKGROWTH) || (PTH_STACKGROWTH != -1)
+ xbt_die(
+ "Stack overflow protection is known to be broken on your system: you stacks grow upwards (or detection is "
+ "broken). "
+ "Please disable stack guards with --cfg=contexts:guard-size:0");
+ /* Current code for stack overflow protection assumes that stacks are growing downward (PTH_STACKGROWTH == -1).
+ * Protected pages need to be put after the stack when PTH_STACKGROWTH == 1. */
+#endif
+
+ size_t size = smx_context_stack_size + smx_context_guard_size;
+#if SIMGRID_HAVE_MC
+ /* Cannot use posix_memalign when SIMGRID_HAVE_MC. Align stack by hand, and save the
+ * pointer returned by xbt_malloc0. */
+ unsigned char* alloc = static_cast<unsigned char*>(xbt_malloc0(size + xbt_pagesize));
+ stack_ = alloc - (reinterpret_cast<uintptr_t>(alloc) & (xbt_pagesize - 1)) + xbt_pagesize;
+ reinterpret_cast<unsigned char**>(stack_)[-1] = alloc;
+#elif !defined(_WIN32)
+ void* alloc;
+ if (posix_memalign(&alloc, xbt_pagesize, size) != 0)
+ xbt_die("Failed to allocate stack.");
+ this->stack_ = static_cast<unsigned char*>(alloc);
+#else
+ this->stack_ = static_cast<unsigned char*>(_aligned_malloc(size, xbt_pagesize));
+#endif
+
+#ifndef _WIN32
+ if (mprotect(this->stack_, smx_context_guard_size, PROT_NONE) == -1) {
+ xbt_die(
+ "Failed to protect stack: %s.\n"
+ "If you are running a lot of actors, you may be exceeding the amount of mappings allowed per process.\n"
+ "On Linux systems, change this value with sudo sysctl -w vm.max_map_count=newvalue (default value: 65536)\n"
+ "Please see "
+ "https://simgrid.org/doc/latest/Configuring_SimGrid.html#configuring-the-user-code-virtualization for more "
+ "information.",
+ strerror(errno));
+ /* This is fatal. We are going to fail at some point when we try reusing this. */
+ }
+#endif
+ this->stack_ = this->stack_ + smx_context_guard_size;
+ } else {
+ this->stack_ = static_cast<unsigned char*>(xbt_malloc0(smx_context_stack_size));
+ }
+
+#if PTH_STACKGROWTH == -1
+ ASAN_ONLY(this->asan_stack_ = this->stack_ + smx_context_stack_size);
+#else
+ ASAN_ONLY(this->asan_stack_ = this->stack_);
+#endif
+#if HAVE_VALGRIND_H
+ if (RUNNING_ON_VALGRIND)
+ this->valgrind_stack_id_ = VALGRIND_STACK_REGISTER(this->stack_, this->stack_ + smx_context_stack_size);
+#endif
+ }
+}
+
+SwappedContext::~SwappedContext()