summaryrefslogtreecommitdiff
path: root/tools/standalone_miri/value.hpp
blob: ab7add8cc6b0e62cbe82ec8d1b0cec4de0dab125 (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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
/*
 * mrustc Standalone MIRI
 * - by John Hodge (Mutabah)
 *
 * value.hpp
 * - Runtime values
 */
#pragma once

#include <vector>
#include <memory>
#include <cstdint>
#include <cstring>	// memcpy
#include <cassert>

#include "debug.hpp"

namespace HIR {
    struct TypeRef;
    struct Path;
}
class Allocation;
struct Value;
struct ValueRef;

struct FfiLayout
{
    struct Range {
        size_t  len;
        bool    is_valid;
        bool    is_writable;
    };
    ::std::vector<Range>    ranges;

    static FfiLayout new_const_bytes(size_t s);

    size_t get_size() const {
        size_t rv = 0;
        for(const auto& r : ranges)
            rv += r.len;
        return rv;
    }
    bool is_valid_read(size_t o, size_t s) const;
};
struct FFIPointer
{
    // FFI pointers require the following:
    // - A tag indicating where they're valid/from
    // - A data format (e.g. size of allocation, internal data format)
    //   - If the data format is unspecified (null) then it's a void pointer
    // - An actual pointer

    // Pointer value, returned by the FFI
    void*   ptr_value;
    // Tag name, used for validty checking by FFI hooks
    const char* tag_name;
    ::std::shared_ptr<FfiLayout>    layout;

    static FFIPointer new_const_bytes(const char* name, const void* s, size_t size) {
        return FFIPointer { const_cast<void*>(s), name, ::std::make_shared<FfiLayout>(FfiLayout::new_const_bytes(size)) };
    };

    size_t get_size() const {
        return (layout ? layout->get_size() : 0);
    }
};

class AllocationHandle
{
    friend class Allocation;
    friend class RelocationPtr;
    Allocation* m_ptr;

private:
    AllocationHandle(Allocation* p):
        m_ptr(p)
    {
    }
public:
    AllocationHandle(): m_ptr(nullptr) {}
    AllocationHandle(AllocationHandle&& x): m_ptr(x.m_ptr) {
        x.m_ptr = nullptr;
    }
    AllocationHandle(const AllocationHandle& x);
    ~AllocationHandle();

    AllocationHandle& operator=(const AllocationHandle& x) = delete;
    AllocationHandle& operator=(AllocationHandle&& x) {
        this->~AllocationHandle();
        this->m_ptr = x.m_ptr;
        x.m_ptr = nullptr;
        return *this;
    }

    operator bool() const { return m_ptr != 0; }
    const Allocation& operator*() const { assert(m_ptr); return *m_ptr; }
          Allocation& operator*()       { assert(m_ptr); return *m_ptr; }
    const Allocation* operator->() const { assert(m_ptr); return m_ptr; }
          Allocation* operator->()       { assert(m_ptr); return m_ptr; }
};

// TODO: Split into RelocationPtr and AllocationHandle
class RelocationPtr
{
    void* m_ptr;

public:
    enum class Ty
    {
        Allocation,
        Function,   // m_ptr is a pointer to the function.
        StdString,
        FfiPointer,
    };

    RelocationPtr(): m_ptr(nullptr) {}
    RelocationPtr(RelocationPtr&& x): m_ptr(x.m_ptr) {
        x.m_ptr = nullptr;
    }
    RelocationPtr(const RelocationPtr& x);
    ~RelocationPtr();
    static RelocationPtr new_alloc(AllocationHandle h);
    static RelocationPtr new_fcn(::HIR::Path p);    // TODO: What if it's a FFI function? Could be encoded in here.
    static RelocationPtr new_string(const ::std::string* s);    // NOTE: The string must have a stable pointer
    static RelocationPtr new_ffi(FFIPointer info);

    RelocationPtr& operator=(const RelocationPtr& x) = delete;
    RelocationPtr& operator=(RelocationPtr&& x) {
        this->~RelocationPtr();
        this->m_ptr = x.m_ptr;
        x.m_ptr = nullptr;
        return *this;
    }

    size_t get_size() const;

    operator bool() const { return m_ptr != 0; }
    bool is_alloc() const {
        return *this && get_ty() == Ty::Allocation;
    }
    Allocation& alloc() {
        assert(*this);
        assert(get_ty() == Ty::Allocation);
        return *static_cast<Allocation*>(get_ptr());
    }
    const Allocation& alloc() const {
        assert(*this);
        assert(get_ty() == Ty::Allocation);
        return *static_cast<Allocation*>(get_ptr());
    }
    const ::HIR::Path& fcn() const {
        assert(*this);
        assert(get_ty() == Ty::Function);
        return *static_cast<const ::HIR::Path*>(get_ptr());
    }
    const ::std::string& str() const {
        assert(*this);
        assert(get_ty() == Ty::StdString);
        return *static_cast<const ::std::string*>(get_ptr());
    }
    const FFIPointer& ffi() const {
        assert(*this);
        assert(get_ty() == Ty::FfiPointer);
        return *static_cast<const FFIPointer*>(get_ptr());
    }

    Ty get_ty() const {
        return static_cast<Ty>( reinterpret_cast<uintptr_t>(m_ptr) & 3 );
    }

    friend ::std::ostream& operator<<(::std::ostream& os, const RelocationPtr& x);
private:
    void* get_ptr() const {
        return reinterpret_cast<void*>( reinterpret_cast<uintptr_t>(m_ptr) & ~3 );
    }
};
struct Relocation
{
    // Offset within parent allocation where this relocation is performed.
    // TODO: Size?
    size_t  slot_ofs;
    RelocationPtr   backing_alloc;
};

// TODO: Split write and read
struct ValueCommonRead
{
    virtual RelocationPtr get_relocation(size_t ofs) const = 0;
    virtual void read_bytes(size_t ofs, void* dst, size_t count) const = 0;

    uint8_t read_u8(size_t ofs) const { uint8_t rv; read_bytes(ofs, &rv, 1); return rv; }
    uint16_t read_u16(size_t ofs) const { uint16_t rv; read_bytes(ofs, &rv, 2); return rv; }
    uint32_t read_u32(size_t ofs) const { uint32_t rv; read_bytes(ofs, &rv, 4); return rv; }
    uint64_t read_u64(size_t ofs) const { uint64_t rv; read_bytes(ofs, &rv, 8); return rv; }
    int8_t read_i8(size_t ofs) const { return static_cast<int8_t>(read_u8(ofs)); }
    int16_t read_i16(size_t ofs) const { return static_cast<int16_t>(read_u16(ofs)); }
    int32_t read_i32(size_t ofs) const { return static_cast<int32_t>(read_u32(ofs)); }
    int64_t read_i64(size_t ofs) const { return static_cast<int64_t>(read_u64(ofs)); }
    float  read_f32(size_t ofs) const { float rv; read_bytes(ofs, &rv, 4); return rv; }
    double read_f64(size_t ofs) const { double rv; read_bytes(ofs, &rv, 8); return rv; }
    uint64_t read_usize(size_t ofs) const;
    int64_t read_isize(size_t ofs) const { return static_cast<int64_t>(read_usize(ofs)); }

    /// De-reference a pointer (of target type `ty`) at the given offset, and return a reference to it
    ValueRef deref(size_t ofs, const ::HIR::TypeRef& ty);

    /// Read a pointer from the value, requiring at least `req_valid` valid bytes, saves avaliable space in `size`
    void* read_pointer_unsafe(size_t rd_ofs, size_t req_valid, size_t& size, bool& is_mut) const;
    /// Read a pointer, requiring `req_len` valid bytes
    const void* read_pointer_const(size_t rd_ofs, size_t req_len) const {
        size_t  tmp;
        bool is_mut;
        return read_pointer_unsafe(rd_ofs, req_len, tmp, is_mut);
    }
    /// Read a pointer, not requiring that the target be initialised
    void* read_pointer_uninit(size_t rd_ofs, size_t& out_size) {
        bool is_mut;
        void* rv = read_pointer_unsafe(rd_ofs, 0, out_size, is_mut);
        if(!is_mut)
            LOG_FATAL("Attempting to get an uninit pointer to immutable data");
        return rv;
    }
    /// Read a pointer and return a ValueRef to it (mutable data)
    ValueRef read_pointer_valref_mut(size_t rd_ofs, size_t size);
};
struct ValueCommonWrite:
    public ValueCommonRead
{
    virtual void write_bytes(size_t ofs, const void* src, size_t count) = 0;

    void write_u8 (size_t ofs, uint8_t  v) { write_bytes(ofs, &v, 1); }
    void write_u16(size_t ofs, uint16_t v) { write_bytes(ofs, &v, 2); }
    void write_u32(size_t ofs, uint32_t v) { write_bytes(ofs, &v, 4); }
    void write_u64(size_t ofs, uint64_t v) { write_bytes(ofs, &v, 8); }
    void write_i8 (size_t ofs, int8_t  v) { write_u8 (ofs, static_cast<uint8_t >(v)); }
    void write_i16(size_t ofs, int16_t v) { write_u16(ofs, static_cast<uint16_t>(v)); }
    void write_i32(size_t ofs, int32_t v) { write_u32(ofs, static_cast<uint32_t>(v)); }
    void write_i64(size_t ofs, int64_t v) { write_u64(ofs, static_cast<uint64_t>(v)); }
    void write_f32(size_t ofs, float  v) { write_bytes(ofs, &v, 4); }
    void write_f64(size_t ofs, double v) { write_bytes(ofs, &v, 8); }
    void write_usize(size_t ofs, uint64_t v);
    void write_isize(size_t ofs, int64_t v) { write_usize(ofs, static_cast<uint64_t>(v)); }
    virtual void write_ptr(size_t ofs, size_t ptr_ofs, RelocationPtr reloc) = 0;
};

class Allocation:
    public ValueCommonWrite
{
    friend class AllocationHandle;
    ::std::string   m_tag;
    size_t  refcount;
    size_t  m_size;
    // TODO: Read-only flag?
    bool is_freed = false;

    ::std::vector<uint64_t> m_data;
public:
    ::std::vector<uint8_t> m_mask;
    ::std::vector<Relocation>   relocations;
public:
    virtual ~Allocation() {}
    static AllocationHandle new_alloc(size_t size, ::std::string tag);

    // NOTE: This should match the value in the MMIR backend
    static const size_t PTR_BASE = 0x1000;

    const uint8_t* data_ptr() const { return reinterpret_cast<const uint8_t*>(this->m_data.data()); }
          uint8_t* data_ptr()       { return reinterpret_cast<      uint8_t*>(this->m_data.data()); }
    size_t size() const { return m_size; }
    const ::std::string& tag() const { return m_tag; }

    RelocationPtr get_relocation(size_t ofs) const override {
        for(const auto& r : relocations) {
            if(r.slot_ofs == ofs)
                return r.backing_alloc;
        }
        return RelocationPtr();
    }
    void mark_as_freed() {
        is_freed = true;
        relocations.clear();
        for(auto& v : m_mask)
            v = 0;
    }

    void resize(size_t new_size);

    void check_bytes_valid(size_t ofs, size_t size) const;
    void mark_bytes_valid(size_t ofs, size_t size);

    Value read_value(size_t ofs, size_t size) const;
    void read_bytes(size_t ofs, void* dst, size_t count) const override;

    void write_value(size_t ofs, Value v);
    void write_bytes(size_t ofs, const void* src, size_t count) override;
    void write_ptr(size_t ofs, size_t ptr_ofs, RelocationPtr reloc) override;

    void set_reloc(size_t ofs, size_t len, RelocationPtr reloc);
};
extern ::std::ostream& operator<<(::std::ostream& os, const Allocation& x);

struct Value:
    public ValueCommonWrite
{
    // If NULL, data is direct
    AllocationHandle    allocation;
    struct {
        // NOTE: Can't pack the mask+size tighter, need 4 bits of size (8-15) leaving 12 bits of mask
        uint8_t data[2*8-3];   // 13 data bytes, plus 16bit mask, plus size = 16 bytes
        uint8_t mask[2];
        uint8_t size;
    } direct_data;

    Value();
    Value(::HIR::TypeRef ty);

    //Value(const Value&) = delete;
    //Value(Value&&) = default;
    //Value& operator=(const Value&) = delete;
    //Value& operator=(Value&&) = default;

    static Value with_size(size_t size, bool have_allocation);
    static Value new_fnptr(const ::HIR::Path& fn_path);
    static Value new_ffiptr(FFIPointer ffi);
    static Value new_pointer(::HIR::TypeRef ty, uint64_t v, RelocationPtr r);
    static Value new_usize(uint64_t v);
    static Value new_isize(int64_t v);
    static Value new_u32(uint32_t v);
    static Value new_i32(int32_t v);
    static Value new_i64(int64_t v);

    void create_allocation();
    size_t size() const { return allocation ? allocation->size() : direct_data.size; }
    const uint8_t* data_ptr() const { return allocation ? allocation->data_ptr() : direct_data.data; }
          uint8_t* data_ptr()       { return allocation ? allocation->data_ptr() : direct_data.data; }

    RelocationPtr get_relocation(size_t ofs) const override {
        if( this->allocation && this->allocation )
            return this->allocation->get_relocation(ofs);
        else
            return RelocationPtr();
    }

    void check_bytes_valid(size_t ofs, size_t size) const;
    void mark_bytes_valid(size_t ofs, size_t size);

    Value read_value(size_t ofs, size_t size) const;
    void read_bytes(size_t ofs, void* dst, size_t count) const override;

    void write_value(size_t ofs, Value v);
    void write_bytes(size_t ofs, const void* src, size_t count) override;

    void write_ptr(size_t ofs, size_t ptr_ofs, RelocationPtr reloc) override;
};
extern ::std::ostream& operator<<(::std::ostream& os, const Value& v);

// A read-only reference to a value (to write, you have to go through it)
struct ValueRef:
    public ValueCommonRead
{
    // Either an AllocationHandle, or a Value pointer
    RelocationPtr   m_alloc;
    Value*  m_value;
    size_t  m_offset;   // Offset within the value
    size_t  m_size; // Size in bytes of the referenced value
    ::std::shared_ptr<Value>    m_metadata;

    static bool in_bounds(size_t ofs, size_t size, size_t max_size) {
        if( size == 0 ) {
            return ofs <= max_size;
        }
        if( ofs > 0 && !(ofs < max_size) )
            return false;
        if( !(size <= max_size) )
            return false;
        return ofs + size <= max_size;
    }

    ValueRef(RelocationPtr ptr, size_t ofs, size_t size):
        m_alloc(ptr),
        m_value(nullptr),
        m_offset(ofs),
        m_size(size)
    {
        if( m_alloc )
        {
            switch(m_alloc.get_ty())
            {
            case RelocationPtr::Ty::Allocation:
                if( !in_bounds(ofs, size, m_alloc.alloc().size()) )
                {
                    LOG_ERROR("ValueRef exceeds bounds of " << m_alloc << " - " << ofs << "+" << size << " > " << m_alloc.alloc().size());
                }
                break;
            case RelocationPtr::Ty::StdString:
                if( !in_bounds(ofs, size, m_alloc.str().size()) )
                {
                    LOG_ERROR("ValueRef exceeds bounds of string - " << ofs << "+" << size << " > " << m_alloc.str().size());
                }
                break;
            case RelocationPtr::Ty::FfiPointer:
                if( !in_bounds(ofs, size, m_alloc.ffi().get_size()) )
                {
                    LOG_ERROR("ValueRef exceeds bounds of FFI buffer - " << ofs << "+" << size << " > " << m_alloc.ffi().get_size());
                }
                break;
            default:
                LOG_TODO("");
            }
        }
    }
    ValueRef(Value& val):
        ValueRef(val, 0, val.size())
    {
    }
    ValueRef(Value& val, size_t ofs, size_t size):
        m_value(&val),
        m_offset(ofs),
        m_size(size)
    {
    }

    RelocationPtr get_relocation(size_t ofs) const override {
        if(m_alloc)
        {
            if( m_alloc.is_alloc() )
                return m_alloc.alloc().get_relocation(m_offset + ofs);
            else
                return RelocationPtr();
        }
        else if( m_value )
        {
            return m_value->get_relocation(m_offset + ofs);
        }
        else
        {
            return RelocationPtr();
        }
    }
    Value read_value(size_t ofs, size_t size) const;
    const uint8_t* data_ptr() const {
        if( m_alloc ) {
            switch(m_alloc.get_ty())
            {
            case RelocationPtr::Ty::Allocation:
                return m_alloc.alloc().data_ptr() + m_offset;
                break;
            case RelocationPtr::Ty::StdString:
                return reinterpret_cast<const uint8_t*>(m_alloc.str().data() + m_offset);
            default:
                LOG_TODO("");
            }
        }
        else if( m_value ) {
            return m_value->data_ptr() + m_offset;
        }
        else {
            return nullptr;
        }
    }

    // TODO: Remove these two (move to a helper?)
    uint8_t* data_ptr_mut() {
        if( m_alloc ) {
            switch(m_alloc.get_ty())
            {
            case RelocationPtr::Ty::Allocation:
                return m_alloc.alloc().data_ptr() + m_offset;
                break;
            default:
                LOG_TODO("");
            }
        }
        else if( m_value ) {
            return m_value->data_ptr() + m_offset;
        }
        else {
            return nullptr;
        }
    }
    void mark_bytes_valid(size_t ofs, size_t size);

    void read_bytes(size_t ofs, void* dst, size_t size) const {
        if( size == 0 )
            return ;
        LOG_ASSERT(in_bounds(ofs, size, m_size), "read_bytes(" << ofs << "+" << size << " > " << m_size <<")");
        if( m_alloc ) {
            switch(m_alloc.get_ty())
            {
            case RelocationPtr::Ty::Allocation:
                m_alloc.alloc().read_bytes(m_offset + ofs, dst, size);
                break;
            case RelocationPtr::Ty::StdString:
                assert(m_offset+ofs <= m_alloc.str().size() && size <= m_alloc.str().size() && m_offset+ofs+size <= m_alloc.str().size());
                ::std::memcpy(dst, m_alloc.str().data() + m_offset + ofs, size);
                break;
            default:
                //ASSERT_BUG(m_alloc.is_alloc(), "read_value on non-data backed Value - " << );
                LOG_TODO("");
            }
        }
        else {
            m_value->read_bytes(m_offset + ofs, dst, size);
        }
    }
    void check_bytes_valid(size_t ofs, size_t size) const {
        if( size == 0 )
            return ;
        LOG_ASSERT(in_bounds(ofs, size, m_size), "check_bytes_valid(" << ofs << "+" << size << " > " << m_size <<")");
        if( m_alloc ) {
            switch(m_alloc.get_ty())
            {
            case RelocationPtr::Ty::Allocation:
                m_alloc.alloc().check_bytes_valid(m_offset + ofs, size);
                break;
            case RelocationPtr::Ty::StdString:
                assert(m_offset+ofs <= m_alloc.str().size() && size <= m_alloc.str().size() && m_offset+ofs+size <= m_alloc.str().size());
                break;
            default:
                //ASSERT_BUG(m_alloc.is_alloc(), "read_value on non-data backed Value - " << );
                LOG_TODO("");
            }
        }
        else {
            m_value->check_bytes_valid(m_offset + ofs, size);
        }
    }

    bool compare(size_t offset, const void* other, size_t other_len) const;
};
extern ::std::ostream& operator<<(::std::ostream& os, const ValueRef& v);