summary refs log tree commit diff
path: root/src/rt/arch/x86_64/context.h
blob: bb35486dbc182e224dec8d8c4eaaac297cf916f7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// -*- mode: c++ -*-

#ifndef CONTEXT_H
#define CONTEXT_H

#include <cstdlib>
#include <inttypes.h>
#include <stdint.h>
#include <xmmintrin.h>

#include "vg/memcheck.h"

template<typename T>
T align_down(T sp)
{
    // There is no platform we care about that needs more than a
    // 16-byte alignment.
    return (T)((uint64_t)sp & ~(16 - 1));
}

// The struct in which we store the saved data.  This is mostly the
// volatile registers and instruction pointer, but it also includes
// RCX/RDI which are used to pass arguments.  The indices for each
// register are found in "regs.h".  Note that the alignment must be
// 16 bytes so that SSE instructions can be used.
#include "regs.h"
struct registers_t {
    uint64_t data[RUSTRT_MAX];
} __attribute__((aligned(16)));

extern "C" void __morestack(void *args, void *fn_ptr, uintptr_t stack_ptr);

class context {
public:
    registers_t regs;
    
    context();
    
    context *next;
    
    void swap(context &out);
    void call(void *f, void *arg, void *sp);
    void call(void *f, void *sp);
    
    // Note that this doesn't actually adjust esp. Instead, we adjust esp when
    // we actually do the call. This is needed for exception safety -- if the
    // function being called causes the task to fail, then we have to avoid
    // leaking space on the C stack.
    inline void *alloc_stack(size_t nbytes) {
        uint64_t bot = regs.data[RUSTRT_RSP];
        uint64_t top = align_down(bot - nbytes);

        (void)VALGRIND_MAKE_MEM_UNDEFINED(top - 4, bot - top + 4);

        return reinterpret_cast<void *>(top);
    }

    void call_shim_on_c_stack(void *args, void *fn_ptr) {
        __morestack(args, fn_ptr, regs.data[RUSTRT_RSP]);
    }
};

#endif