// This file is supposed to export everything needed by WASIX side modules
// to function properly, which at this point is just TLS area allocation

#include <stddef.h>

// Generated by the linker for this module
extern void __wasm_init_tls(void *memory);

// Will become an import and be filled in from the main module by the dynamic linker
void *aligned_alloc(size_t alignment, size_t bytes);

void __wasi_thread_exit(
    /**
     * The exit code returned by the process.
     */
    int rval);

__attribute__((export_name("__wasix_init_tls"))) size_t __wasix_init_tls(void)
{
    int size = __builtin_wasm_tls_size();
    int align = __builtin_wasm_tls_align();
    void *tls = aligned_alloc(align, size);
    if (!tls)
    {
        // If we can't allocate the TLS area, we can't continue
        __builtin_trap();
    }
    __wasm_init_tls(tls);
    return (size_t)tls;
}
