GitLab will be upgraded on 30 Jan 2023 from 2.00 pm (AEDT) to 3.00 pm (AEDT). During the update, GitLab and Mattermost services will not be available. If you have any concerns with this, please talk to us at N110 (b) CSIT building.

libmu.py 40.6 KB
Newer Older
Kunshan Wang's avatar
Kunshan Wang committed
1
"""
Kunshan Wang's avatar
Kunshan Wang committed
2
3
4
libmu: Python binding for the Mu-client API.

This module works for both Python 2 and Python 3.
Kunshan Wang's avatar
Kunshan Wang committed
5
6
7
8
9
10
11
12
13
14
15
16

For PyPy users: This module is not RPython!

The Mu reference implementation 2 contains a ``cbinding`` directory which
produces the ``libmurefimpl2start.so`` library. Users of this Python binding
should construct a MuRefImpl2StartDLL object with the pathname of that shared
object as the argument to the constructor.

This binding is a "medium-level" binding. It is more Python-friendly than the
low-level raw C API, and it does a lot of run-time type checking when API
functions are invoked, but it does not provide higher-level functionalities than
the C API, such as the LLVM-style CFG builder.
Kunshan Wang's avatar
Kunshan Wang committed
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38


==========
How to use
==========

Creating the Micro VM and Contexts
----------------------------------

This Python binding depends on the C binding. After building the C binding, a
shared object ``../cbinding/libmurefimpl2start.so`` will be generated. The
client needs to create a MuRefImpl2StartDLL object with the path of that SO as
its argument::

    dll = MuRefImpl2StartDLL("../cbinding/libmurefimpl2start.so")

Then a ``MuVM`` instance can be created from that object::

    mu = dll.mu_refimpl2_new()

or::

39
40
41
42
43
    mu = dll.mu_refimpl2_new_ex(
        sosSize = 2*1024*1024,
        losSize = 2*1024*1024,
        globalSize = 4*1024*1024,
        stackSize = 63*1024,
Kunshan Wang's avatar
Kunshan Wang committed
44
        staticCheck = False,
45
        sourceInfo = False,
Kunshan Wang's avatar
Kunshan Wang committed
46
47
        gcLog = "WARN",
        vmLog = "INFO",
48
    )
Kunshan Wang's avatar
Kunshan Wang committed
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

A ``MuCtx`` instance can be created from the ``MuVM`` object::

    ctx = mu.new_context()
    ...
    ctx.close_context()

or use the ``with`` statement:

    with mu.new_context() as ctx:
        ...


Exeucte Mu Programs
-------------------

To start executing Mu programs, the client should create a stack and a thread.
As a limitation of this reference implementation, the client also needs to
invoke the ``MuVM.execute()`` method to actually execute the program. For
example::

    dll = MuRefImpl2StartDLL("../cbinding/libmurefimpl2start.so")
    mu = dll.mu_refimpl2_new()

    with mu.new_context() as ctx:
        func   = ctx.handle_from_func(ctx.id_of("@main"))
        arg1   = ctx.handle_from_int(10, 64)
        arg2   = ctx.handle_from_double(3.14)
        stack  = ctx.new_stack(func)
        thread = ctx.new_thread(stack, PassValues(arg1, arg2))

    mu.execute()    # The thread will actually run now.


Invoking API Methods
--------------------

The ``MuVM`` and the ``MuCtx`` Python object mimics the ``MuVM`` and ``MuCtx``
structs in the C API.

Function pointers in the C struct are mapped to methods of the same name in the
corresponding Python object. The first argument of the function pointers in the
C API is always a pointer to the struct itself. This first argument is omitted.
Other arguments are auto converted to the corresponding C types thanks to the
``ctypes`` module. For example::

    # MuCtx *ctx = mvm->new_context(mvm);   // C
    ctx = mu.new_context()                  # Python

    # MuDoubleValue h = ctx->handle_from_double(ctx, 3.14);     // C
    h = ctx.handle_from_double(3.14)                            # Python

IDs are Python ``int`` and names are Python ``str``.

Handles are sub-classes of the ``MuValue`` class. They wrap the underlying
C-level handles (void*) and know which ``MuCtx`` they are created from. They can
be pasesed into methods like in C. For example::

    h = ctx.handle_from_double(3.14)    # a MuDoubleValue
    num = ctx.handle_to_double(h)       # num is the Python value 3.14

    id_of = ctx.id_of   # This method is so frequently used that it is
                        # preferrable to make a shorter alias.
    func   = ctx.handle_from_func(id_of("@factorial"))
    arg    = ctx.handle_from_int(10, 64)
    stack  = ctx.new_stack(func)
    thread = ctx.new_thread(stack, PassValues(arg))

Type checks are performed on each and every method call. Handles (instances of
MuValue) must match the expected argument types. For example, if a method
expects a ``MuIntValue``, passing a ``MuValue`` will raise an error::

    const_int = ctx.handle_from_const(id_of("@CONST_INT_42"))   # MuValue
    num = ctx.handle_to_sint(const_int)     # ERROR: Expect MuIntValue, got MuValue

``MuValue`` has a ``cast`` method to cast an instance to a desired subtype.::

    const_int = ctx.handle_from_const(id_of("@CONST_INT_42")).cast(MuIntValue) # MuIntValue
    num = ctx.handle_to_sint(const_int)     # OK

The following functions usually need casting: ``handle_from_const``,
``handle_from_expose``, ``extract_value``, ``extract_element``, ``load``,
``cmpxchg``, ``atomicrmw``, ``dump_keepalives``, ``expose``.

The signatures of some methods are completely re-designed in Python to make them
more "Pythonic". For example, the ``load_bundle`` method of ``MuCtx`` takes a
single Python ``str`` and does not need the length. The ``cmpxchg`` method now
returns a pair rather than having one of them as the "output argument". The trap
handler is also completely re-designed. Such methods are defined and documented
in ``MuVM`` and ``MuCtx``. If they are explicitly defined there, the original C
function is accessible with a suffix ``_``, such as ``load_bundle_`` which is
the original C function that takes a length as argument. If they are not
explicitly defined, they follow the conventions mentioned before.


Automatically Delete Handles
----------------------------

The ``DelayedDisposer`` class can delete selected handles created in a scope.
Read the docstring.


Further Reading
---------------

It is recommended to read the docstrings in the following types: ``MuVM``,
``MuCtx``, ``MuValue`` and ``MuTrapHandler``.

Kunshan Wang's avatar
Kunshan Wang committed
157
158
"""

Kunshan Wang's avatar
Kunshan Wang committed
159
160
from __future__ import division, absolute_import, print_function, unicode_literals

Kunshan Wang's avatar
Kunshan Wang committed
161
162
163
164
165
166
167
import sys

if sys.version_info[0] == 2:
    import _libmuprivpython2 as _priv
else:
    import _libmuprivpython3 as _priv

168
import ctypes, ctypes.util
Kunshan Wang's avatar
Kunshan Wang committed
169
170
171
import logging

logger = logging.getLogger(__name__)
172
173
174
175
176
177

_libc = ctypes.CDLL(ctypes.util.find_library("c"))
_libc.malloc.restype = ctypes.c_void_p
_libc.malloc.argtypes = [ctypes.c_size_t]
_libc.free.restype = None
_libc.free.argtypes = [ctypes.c_void_p]
Kunshan Wang's avatar
Kunshan Wang committed
178

Kunshan Wang's avatar
Kunshan Wang committed
179
180
181
182
183
184
185
186
187
188
#### Helper functions

def _assert_equal(a, b):
    if not (a == b):
        raise AssertionError("{} does not equal {}".format(a, b))

def _assert_range(v, lb, ub):
    if not (lb <= v <= ub):
        raise AssertionError("{} is not between {} and {}".format(v, lb, ub))

Kunshan Wang's avatar
Kunshan Wang committed
189
from _libmuprivcommon import _assert_instance
Kunshan Wang's avatar
Kunshan Wang committed
190

Kunshan Wang's avatar
Kunshan Wang committed
191
192
#### Low-level C types counterpart

Kunshan Wang's avatar
Kunshan Wang committed
193
def _funcptr(restype, *paramtypes, **kwargs):
Kunshan Wang's avatar
Kunshan Wang committed
194
    return ctypes.CFUNCTYPE(restype, *paramtypes, use_errno=True, **kwargs)
Kunshan Wang's avatar
Kunshan Wang committed
195
196

CMuValue = ctypes.c_void_p
Kunshan Wang's avatar
Kunshan Wang committed
197
198
199
CMuGenRefValue = CMuValue
CMuSeqValue = CMuValue

Kunshan Wang's avatar
Kunshan Wang committed
200
201
202
CMuIntValue = CMuValue
CMuFloatValue = CMuValue
CMuDoubleValue = CMuValue
Kunshan Wang's avatar
Kunshan Wang committed
203
204
CMuRefValue = CMuGenRefValue
CMuIRefValue = CMuGenRefValue
Kunshan Wang's avatar
Kunshan Wang committed
205
CMuStructValue = CMuValue
Kunshan Wang's avatar
Kunshan Wang committed
206
207
208
209
210
211
CMuArrayValue = CMuSeqValue
CMuVectorValue = CMuSeqValue
CMuFuncRefValue = CMuGenRefValue
CMuThreadRefValue = CMuGenRefValue
CMuStackRefValue = CMuGenRefValue
CMuFCRefValue = CMuGenRefValue
Kunshan Wang's avatar
Kunshan Wang committed
212
213
214
215
216
217
218
219
220
221
222
223
224
CMuTagRef64Value = CMuValue
CMuUPtrValue = CMuValue
CMuUFPValue = CMuValue

CMuID = ctypes.c_uint
CMuName = ctypes.c_char_p

CMuCPtr = ctypes.c_void_p
CMuCFP = ctypes.c_void_p

CMuTrapHandlerResult = ctypes.c_int
CMuHowToResume = ctypes.c_int

225
226
227
CMU_THREAD_EXIT = 0x00
CMU_REBIND_PASS_VALUES = 0x01
CMU_REBIND_THROW_EXC = 0x02
Kunshan Wang's avatar
Kunshan Wang committed
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246

CPtrMuValue = ctypes.POINTER(CMuValue)

CMuValuesFreer = _funcptr(
    None,   # return void
    CPtrMuValue,    # values
    CMuCPtr,        # freerdata
    )

class CMuVM(ctypes.Structure):
    pass    # Incomplete now. _fields_ will be patched later.

CPtrMuVM = ctypes.POINTER(CMuVM)

class CMuCtx(ctypes.Structure):
    pass    # Incomplete now. _fields_ will be patched later.

CPtrMuCtx = ctypes.POINTER(CMuCtx)

247
CMuTrapHandler = ctypes.CFUNCTYPE(
Kunshan Wang's avatar
Kunshan Wang committed
248
249
250
    # return value
    None,   # return void
    # input params
251
    ctypes.POINTER(CMuCtx),                 # ctx
Kunshan Wang's avatar
Kunshan Wang committed
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
    CMuThreadRefValue,                      # thread
    CMuStackRefValue,                       # stack
    ctypes.c_int,                           # wpid
    # output params
    ctypes.POINTER(CMuTrapHandlerResult),   # result
    ctypes.POINTER(CMuStackRefValue),       # new_stack
    ctypes.POINTER(CMuValue),               # values
    ctypes.POINTER(ctypes.c_int),           # nvalues
    ctypes.POINTER(CMuValuesFreer),         # freer
    ctypes.POINTER(CMuCPtr),                # freerdata
    ctypes.POINTER(CMuRefValue),            # exception
    # user-defined argument (input param)
    CMuCPtr,                                # userdata
    )

CMuMemOrd = ctypes.c_int

Kunshan Wang's avatar
Kunshan Wang committed
269
270
271
272
273
274
275
MU_NOT_ATOMIC = 0x00
MU_RELAXED    = 0x01
MU_CONSUME    = 0x02
MU_ACQUIRE    = 0x03
MU_RELEASE    = 0x04
MU_ACQ_REL    = 0x05
MU_SEQ_CST    = 0x06
Kunshan Wang's avatar
Kunshan Wang committed
276
277
278

CMuAtomicRMWOp = ctypes.c_int

Kunshan Wang's avatar
Kunshan Wang committed
279
280
281
282
283
284
285
286
287
288
289
MU_XCHG = 0x00
MU_ADD  = 0x01
MU_SUB  = 0x02
MU_AND  = 0x03
MU_NAND = 0x04
MU_OR   = 0x05
MU_XOR  = 0x06
MU_MAX  = 0x07
MU_MIN  = 0x08
MU_UMAX = 0x09
MU_UMIN = 0x0A
Kunshan Wang's avatar
Kunshan Wang committed
290
291
292

CMuCallConv = ctypes.c_int

Kunshan Wang's avatar
Kunshan Wang committed
293
MU_DEFAULT = 0x00
Kunshan Wang's avatar
Kunshan Wang committed
294

Kunshan Wang's avatar
Kunshan Wang committed
295
296
297
298
_MIN_SINT64 = (-1)<<63
_MAX_SINT64 = (1<<63)-1
_MAX_UINT64 = (1<<64)-1

Kunshan Wang's avatar
Kunshan Wang committed
299
#### High-level types which does type checking at run time.
Kunshan Wang's avatar
Kunshan Wang committed
300

Kunshan Wang's avatar
Kunshan Wang committed
301
302
class _LowLevelTypeWrapper(object):
    # _ctype_ = the low-level type
Kunshan Wang's avatar
Kunshan Wang committed
303

Kunshan Wang's avatar
Kunshan Wang committed
304
    def _to_low_level_arg(self):
Kunshan Wang's avatar
Kunshan Wang committed
305
        raise NotImplementedError()
Kunshan Wang's avatar
Kunshan Wang committed
306

Kunshan Wang's avatar
Kunshan Wang committed
307
    @classmethod
Kunshan Wang's avatar
Kunshan Wang committed
308
    def _from_low_level_retval(cls, v, high_level_struct):
Kunshan Wang's avatar
Kunshan Wang committed
309
        raise NotImplementedError()
Kunshan Wang's avatar
Kunshan Wang committed
310

Kunshan Wang's avatar
Kunshan Wang committed
311
class MuValue(_LowLevelTypeWrapper):
Kunshan Wang's avatar
Kunshan Wang committed
312
313
314
315
316
317
318
319
320
321
322
323
324
325
    """Wrapper of the C-level CMuValue.

    Concrete API methods in MuCtx expect subclasses of this type. Use the
    ``cast`` method to cast it to more specific types.
    """

    def delete(self):
        """Delete this MuValue from its MuCtx. Equivalent to ctx.delete_value(self)"""
        self.ctx.delete_value(self)

    def cast(self,ty):
        """Cast this MuValue to a different MuValue subclass."""
        return ty(self.c_mu_value, self.ctx)

Kunshan Wang's avatar
Kunshan Wang committed
326
327
328
329
    _ctype_ = CMuValue
    def __init__(self, c_mu_value, ctx):
        self.c_mu_value = c_mu_value
        self.ctx = ctx
Kunshan Wang's avatar
Kunshan Wang committed
330

Kunshan Wang's avatar
Kunshan Wang committed
331
    def _to_low_level_arg(self):
Kunshan Wang's avatar
Kunshan Wang committed
332
        return self.c_mu_value
Kunshan Wang's avatar
Kunshan Wang committed
333

Kunshan Wang's avatar
Kunshan Wang committed
334
    @classmethod
Kunshan Wang's avatar
Kunshan Wang committed
335
    def _from_low_level_retval(cls, v, high_level_struct):
Kunshan Wang's avatar
Kunshan Wang committed
336
        _assert_instance(high_level_struct, MuCtx)
Kunshan Wang's avatar
Kunshan Wang committed
337
        return cls(v, high_level_struct)
Kunshan Wang's avatar
Kunshan Wang committed
338

Kunshan Wang's avatar
Kunshan Wang committed
339
340
341
342
343
344
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.delete()

Kunshan Wang's avatar
Kunshan Wang committed
345
346
    def __str__(self):
        return "<{} handle={}>".format(type(self).__name__, self.c_mu_value)
Kunshan Wang's avatar
Kunshan Wang committed
347

Kunshan Wang's avatar
Kunshan Wang committed
348
349
    def __repr__(self):
        return str(self)
Kunshan Wang's avatar
Kunshan Wang committed
350

Kunshan Wang's avatar
Kunshan Wang committed
351
352
353
class MuGenRefValue    (MuValue):       pass
class MuSeqValue       (MuValue):       pass

Kunshan Wang's avatar
Kunshan Wang committed
354
355
356
357
358
359
class MuIntValue       (MuValue):       _ctype_ = CMuIntValue      
class MuFloatValue     (MuValue):       _ctype_ = CMuFloatValue    
class MuDoubleValue    (MuValue):       _ctype_ = CMuDoubleValue   
class MuRefValue       (MuGenRefValue): _ctype_ = CMuRefValue      
class MuIRefValue      (MuGenRefValue): _ctype_ = CMuIRefValue     
class MuStructValue    (MuValue):       _ctype_ = CMuStructValue   
Kunshan Wang's avatar
Kunshan Wang committed
360
361
class MuArrayValue     (MuSeqValue):    _ctype_ = CMuArrayValue    
class MuVectorValue    (MuSeqValue):    _ctype_ = CMuVectorValue   
Kunshan Wang's avatar
Kunshan Wang committed
362
363
364
365
366
367
368
class MuFuncRefValue   (MuGenRefValue): _ctype_ = CMuFuncRefValue  
class MuThreadRefValue (MuGenRefValue): _ctype_ = CMuThreadRefValue
class MuStackRefValue  (MuGenRefValue): _ctype_ = CMuStackRefValue 
class MuFCRefValue     (MuGenRefValue): _ctype_ = CMuFCRefValue    
class MuTagRef64Value  (MuValue):       _ctype_ = CMuTagRef64Value 
class MuUPtrValue      (MuValue):       _ctype_ = CMuUPtrValue     
class MuUFPValue       (MuValue):       _ctype_ = CMuUFPValue      
Kunshan Wang's avatar
Kunshan Wang committed
369

370
371
# Trap handling

Kunshan Wang's avatar
Kunshan Wang committed
372
373
374
375
376
377
378
379
380
381
382
383
384
class TrapHandlerResult(object):
    def __init__(self):
        raise NotImplementedError()

class ThreadExit(TrapHandlerResult):
    def __init__(self):
        pass

class Rebind(TrapHandlerResult):
    def __init__(self, stack, how_to_resume):
        self.stack = stack
        self.how_to_resume = how_to_resume

385
386
# Binding threads to stacks. Used by new_stack and trap handling

Kunshan Wang's avatar
Kunshan Wang committed
387
388
389
390
391
392
393
394
395
class HowToResume(object):
    def __init__(self, *values):
        raise NotImplementedError()

class PassValues(HowToResume):
    def __init__(self, *values):
        self.values = values

class ThrowExc(HowToResume):
396
    def __init__(self, exc):
Kunshan Wang's avatar
Kunshan Wang committed
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
        self.exc = exc

class MuTrapHandler(object):
    def handle_trap(self, ctx, thread, stack, wpid):
        """Handle trap.

        This method is called when a trap is triggered by the micro VM. This
        method should handle the trap and tell the micro VM thread how to
        resume.

        Args:
            ctx: The MuCtx created by the micro VM for the trap handler to use.
                The trap handler should not close it.
            thread: A MuThreadRefValue of the thread that triggered the trap.
            stack: A MuStackRefValue of the current stack of the thread which
                triggered the trap.
            wpid: The watch-point ID if the trap is triggered by a WATCHPOINT.
                If it is triggered by TRAP, wpid==0.

        Returns:
            A TrapHandlerResult object which specifies how the thread that
            caused the trap should continue. Possible values are:

            ThreadExit(): The thread stops. The stack remains unbound.

            Rebind(new_stack, how_to_resume): The thread re-binds to a stack.

            In the case of Rebind:

            new_stack: The new stack the current thread should bind to after
                this trap. It may or may not be the same as the stack argument.

            how_to_resume: A HowToResume object which specifies how to bind a
                thread to the new_stack. Possible values are:

            PassValues(values...): The stack will continue normally, and the
                stack receives the list of values.

            ThrowExc(exc): The stack will continue exceptionally. exc is a
                MuRefValue which refers to the exception to be thrown to the
                stack.
Kunshan Wang's avatar
Kunshan Wang committed
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454

        Examples:
            Stop the current thread::

                return ThreadExit()

            Rebind to the original stack and pass values::

                h1 = ctx.handle_from_xxxxxxxx(xxxxx)
                h2 = ctx.handle_from_xxxxxxxx(xxxxx)
                h3 = ctx.handle_from_xxxxxxxx(xxxxx)
                return Rebind(stack, PassValues(h1, h2, h3))

            Rebind to the original stack and throw an exception::

                h = ctx.new_fixed(ctx.id_of("@MyExceptionType"))
                return Rebind(stack, ThrowExc(h1))
Kunshan Wang's avatar
Kunshan Wang committed
455
456
457
        """
        raise NotImplementedError()

458
# Expose Python objects to native programs
Kunshan Wang's avatar
Kunshan Wang committed
459
460

class _ObjectExposer(object):
461
462
463
464
465
    """ Expose Python objects to native programs

    Pointers are not given out, but native programs hold "keys" (i.e. an int
    uniquely assigned to the object) to refer to Python objects.
    """
Kunshan Wang's avatar
Kunshan Wang committed
466
467
468
469
470
471
    def __init__(self):
        self._dic = {}
        self._next_key = 1

    def _get_key(self):
        while True:
472
            key = self._next_key
Kunshan Wang's avatar
Kunshan Wang committed
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
            self._next_key = (self._next_key + 1) & _MAX_UINT64
            if key not in self._dic:
                break
        return key

    def expose(self, obj):
        key = self._get_key()
        self._dic[key] = obj
        return key

    def get(self, key):
        return self._dic[key]

    def unexpose(self, key):
        if key in self._dic:
            del self._dic[key]
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560

_trap_user_data_exposer = _ObjectExposer()

def _word_array_malloc(nelems):
    return _libc.malloc(ctypes.sizeof(CMuValue*nelems))

def _word_array_free(addr, freerdata):
    _libc.free(addr)

_THE_LOW_LEVEL_WORD_ARRAY_FREE_PTR = CMuValuesFreer(_word_array_free)
    
def _the_low_level_trap_handler(
        c_ctx, c_thread, c_stack, c_wpid,
        c_result, c_new_stack, c_values, c_nvalues, c_freer, c_freerdata,
        c_exception,
        c_userdata_key):

    userdata = _trap_user_data_exposer.get(c_userdata_key)
    muvm, trap_handler = userdata

    ctx = MuCtx(c_ctx, muvm)
    thread = MuThreadRefValue(c_thread, ctx)
    stack = MuStackRefValue(c_stack, ctx)
    wpid = c_wpid

    result = trap_handler.handle_trap(ctx, thread, stack, wpid)

    _assert_instance(result, TrapHandlerResult)

    if isinstance(result, ThreadExit):
        c_result.contents.value = CMU_THREAD_EXIT
        c_new_stack.contents.value = 0
        c_values.contents.value = None
        c_nvalues.contents.value = 0
        c_freer.contents.value = None
        c_freerdata.contents.value = None
        c_exception.contents.value = None
    else: # Rebind
        new_stack = result.stack
        htr = result.how_to_resume
        if isinstance(htr, PassValues):
            values = htr.values
            nvalues = len(values)

            cvalues_array_addr = _word_array_malloc(nvalues)
            cvalues_array = (CMuValue*nvalues).from_address(cvalues_array_addr)

            for i,v in enumerate(values):
                cvalues_array[i] = v.c_mu_value

            c_result.contents.value = CMU_REBIND_PASS_VALUES
            c_new_stack.contents.value = new_stack.c_mu_value
            c_values.contents.value = cvalues_array_addr
            c_nvalues.contents.value = nvalues
            c_freer.contents.value = _THE_LOW_LEVEL_WORD_ARRAY_FREE_PTR
            c_freerdata.contents.value = None
            c_exception.contents.value = None

        else:   # ThrowExc
            exc = htr.exc

            c_result.contents.value = CMU_REBIND_THROW_EXC
            c_new_stack.contents.value = new_stack.c_mu_value
            c_values.contents.value = None
            c_nvalues.contents.value = 0
            c_freer.contents.value = None
            c_freerdata.contents.value = None
            c_exception.contents.value = exc.c_mu_value

    return

_THE_LOW_LEVEL_TRAP_HANDLER_PTR = CMuTrapHandler(_the_low_level_trap_handler)
Kunshan Wang's avatar
Kunshan Wang committed
561
        
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581

# Struct of methods

class _StructOfMethodsWrapper(_LowLevelTypeWrapper):
    """ High-level wrapper of "struct-of-method" types. """

    # _high_level_methods need to be assigned externally.
    # _muvm needs to refer to the associated MuVM object.

    def __init__(self, struct_ptr, parent=None):
        """
        struct_ptr: pointer to the underlying C struct

        parent: the Python object that returns this object. For example, If a
        MuVM returns a MuCtx via its ``new_context`` method, then the MuVM is
        the parent of the MuCtx.
        """
        self._struct_ptr = struct_ptr
        self._parent = parent

Kunshan Wang's avatar
Kunshan Wang committed
582
    def _to_low_level_arg(self):
583
584
585
        return self._struct_ptr

    @classmethod
Kunshan Wang's avatar
Kunshan Wang committed
586
    def _from_low_level_retval(cls, v, high_level_struct):
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
        return cls(v, high_level_struct)

    def _high_level_method(self, name):
        return self._high_level_methods[name]

    def _low_level_func(self, name):
        struct_ptr = self._struct_ptr
        ptr_contents = struct_ptr.contents
        func = getattr(ptr_contents, name)
        return func

    def __getattr__(self, name):
        high_level_method = self._high_level_method(name)
        return lambda *a: high_level_method(self, *a)

    def __str__(self):
        return "<{} _struct_ptr={}>".format(type(self).__name__,
                self._struct_ptr)

    def __repr__(self):
        return str(self)

Kunshan Wang's avatar
Kunshan Wang committed
609
class MuVM(_StructOfMethodsWrapper):
Kunshan Wang's avatar
Kunshan Wang committed
610
611
    """An instance of the Mu micro VM."""

Kunshan Wang's avatar
Kunshan Wang committed
612
613
614
    _c_struct_type_ = CMuVM
    _ctype_ = ctypes.POINTER(_c_struct_type_)

Kunshan Wang's avatar
Kunshan Wang committed
615
616
617
618
619
620
621
    def __init__(self, struct_ptr, dll):
        super(self.__class__, self).__init__(struct_ptr, dll)

        self.muvm = self
        self._mu_error_addr = self._low_level_func("get_mu_error_ptr_")(struct_ptr)
        self._mu_error = ctypes.c_int.from_address(self._mu_error_addr)

Kunshan Wang's avatar
Kunshan Wang committed
622
623
624
        self._cur_user_data_key = None

    # Mu writes to the memory location self._mu_error_addr when it throws an
Kunshan Wang's avatar
Kunshan Wang committed
625
626
    # exception before returning to C. It is specific to this implementation and
    # is only used internally in the Python binding.
Kunshan Wang's avatar
Kunshan Wang committed
627

Kunshan Wang's avatar
Kunshan Wang committed
628
    def _get_mu_error(self):
Kunshan Wang's avatar
Kunshan Wang committed
629
        return self._mu_error.value
Kunshan Wang's avatar
Kunshan Wang committed
630

Kunshan Wang's avatar
Kunshan Wang committed
631
    def _set_mu_error(self, v):
Kunshan Wang's avatar
Kunshan Wang committed
632
        self._mu_error.value = v
Kunshan Wang's avatar
Kunshan Wang committed
633

Kunshan Wang's avatar
Kunshan Wang committed
634
635
636
637
638
    ## The following overrides the C functions to make them more Pythonic
    
    def set_trap_handler(self, trap_handler):
        """Set the trap handler of this MuVM.

Kunshan Wang's avatar
Kunshan Wang committed
639
        trap_handler is any Python MuTrapHandler object.
Kunshan Wang's avatar
Kunshan Wang committed
640
641
642
643
644
        """

        userdata = (self, trap_handler)

        old_key = self._cur_user_data_key
645
        new_key = _trap_user_data_exposer.expose(userdata)
Kunshan Wang's avatar
Kunshan Wang committed
646
647
648

        self.set_trap_handler_(_THE_LOW_LEVEL_TRAP_HANDLER_PTR, new_key)

649
        _trap_user_data_exposer.unexpose(old_key)
Kunshan Wang's avatar
Kunshan Wang committed
650
        self._cur_user_data_key = new_key
Kunshan Wang's avatar
Kunshan Wang committed
651

Kunshan Wang's avatar
Kunshan Wang committed
652
class MuCtx(_StructOfMethodsWrapper):
Kunshan Wang's avatar
Kunshan Wang committed
653
654
655
656
657
    """A Mu context.

    It holds MuValues and thread-local resources for the client.
    """

Kunshan Wang's avatar
Kunshan Wang committed
658
659
660
    _c_struct_type_ = CMuCtx
    _ctype_ = ctypes.POINTER(_c_struct_type_)

Kunshan Wang's avatar
Kunshan Wang committed
661
662
663
664
665
    def __init__(self, struct_ptr, muvm):
        super(self.__class__, self).__init__(struct_ptr, muvm)

        self.muvm = muvm

Kunshan Wang's avatar
Kunshan Wang committed
666
667
    ## The following methods enable the with statement.

Kunshan Wang's avatar
Kunshan Wang committed
668
669
670
671
672
673
674
675
676
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type != None:
            return False

        self.close_context()

Kunshan Wang's avatar
Kunshan Wang committed
677
    ## The following overrides the C functions to make them more Pythonic
Kunshan Wang's avatar
Kunshan Wang committed
678

Kunshan Wang's avatar
Kunshan Wang committed
679
    def load_bundle(self, bundle_str):
Kunshan Wang's avatar
Kunshan Wang committed
680
681
682
683
684
        """Load a Bundle.

        Arguments:
            bundle_str: a str or unicode as the text-based bundle.
        """
685
        ascii_bundle = _priv._encode(bundle_str, "ascii")
Kunshan Wang's avatar
Kunshan Wang committed
686
        return self.load_bundle_(ascii_bundle, len(ascii_bundle))
Kunshan Wang's avatar
Kunshan Wang committed
687

Kunshan Wang's avatar
Kunshan Wang committed
688
    def load_hail(self, hail_str):
Kunshan Wang's avatar
Kunshan Wang committed
689
690
691
692
693
        """Load a HAIL script.

        Arguments:
            bundle_str: a str or unicode as the text-based HAIL script.
        """
694
        ascii_bundle = _priv._encode(hail_str, "ascii")
Kunshan Wang's avatar
Kunshan Wang committed
695
        return self.load_hail_(ascii_bundle, len(ascii_bundle))
Kunshan Wang's avatar
Kunshan Wang committed
696
697

    def handle_from_int(self, value, length):
Kunshan Wang's avatar
Kunshan Wang committed
698
699
700
701
702
703
704
705
706
707
708
        """Convert a Python int to a Mu handle.

        Arguments:
            value: a Python int or long. Must be representable in 64-bit signed
            or unsigned number

            length: the desired bit length of the Mu int value

        Returns:
            a MuIntValue
        """
Kunshan Wang's avatar
Kunshan Wang committed
709
        _priv._assert_int_like(value)
Kunshan Wang's avatar
Kunshan Wang committed
710
711
712
713
714
715
716
717
718
        _assert_range(length, 0, 64)
        if _MIN_SINT64 <= value <= _MAX_SINT64:
            return self.handle_from_sint64_(value, length)
        elif 0 <= value <= _MAX_UINT64:
            return self.handle_from_uint64_(value, length)
        else:
            raise ValueError("value {} out of 64-bit range".format(value))

    def handle_to_sint(self, value):
Kunshan Wang's avatar
Kunshan Wang committed
719
720
721
722
723
724
725
726
        """Convert Mu int handle to a Python int, treating it as signed.

        Arguments:
            value: a MuIntValue.

        Returns:
            a Python int
        """
Kunshan Wang's avatar
Kunshan Wang committed
727
728
729
        return self.handle_to_sint64_(value)

    def handle_to_uint(self, value):
Kunshan Wang's avatar
Kunshan Wang committed
730
731
732
733
734
735
736
737
        """Convert Mu int handle to a Python int, treating it as unsigned.

        Arguments:
            value: a MuIntValue.

        Returns:
            a Python int
        """
Kunshan Wang's avatar
Kunshan Wang committed
738
        return self.handle_to_uint64_(value)
Kunshan Wang's avatar
Kunshan Wang committed
739

Kunshan Wang's avatar
Kunshan Wang committed
740
    def delete_values(self, *values):
Kunshan Wang's avatar
Kunshan Wang committed
741
742
        """Delete all values in the ``values`` argument. ``values`` is an
        iterable of MuValue."""
Kunshan Wang's avatar
Kunshan Wang committed
743
744
745
746
        for value in values:
            self.delete_value(value)

    def insert_element(self, value, index, newval):
Kunshan Wang's avatar
Kunshan Wang committed
747
748
749
        """Wrapper of the underlying ``insert_element``. The result is
        automatically cast to the same type as ``value``, which must be either
        ``MuArrayValue`` or ``MuVectorValue``."""
Kunshan Wang's avatar
Kunshan Wang committed
750
751
752
        return self.insert_element_(value, index, newval).cast(type(value))

    def load(self, loc, ord=MU_NOT_ATOMIC):
Kunshan Wang's avatar
Kunshan Wang committed
753
754
        """Wrapper of the underlying ``load``. The memory order is optional and
        defaults to MU_NOT_ATOMIC."""
Kunshan Wang's avatar
Kunshan Wang committed
755
756
757
758
        _assert_instance(loc, MuIRefValue)
        return self.load_(ord, loc)

    def store(self, loc, newval, ord=MU_NOT_ATOMIC):
Kunshan Wang's avatar
Kunshan Wang committed
759
760
        """Wrapper of the underlying ``store``. The memory order is optional and
        defaults to MU_NOT_ATOMIC."""
Kunshan Wang's avatar
Kunshan Wang committed
761
762
763
764
765
        _assert_instance(loc, MuIRefValue)
        return self.store_(ord, loc, newval)

    def cmpxchg(self, loc, expected, desired, weak=False, ord_succ=MU_SEQ_CST,
            ord_fail=MU_SEQ_CST):
Kunshan Wang's avatar
Kunshan Wang committed
766
767
768
769
770
771
772
773
774
775
        """Wrapper of the underlying ``cmpxchg``.

        It is strong by default.

        The memory orders are optional and defaults to MU_NOT_ATOMIC.

        The return value is a pair (value, succ), where value is a MuValue of
        the old value, and succ is a bool which indicates whether this operation
        is successful.
        """
Kunshan Wang's avatar
Kunshan Wang committed
776
777
778
779
780
781
782
783
784
        _assert_instance(loc, MuIRefValue)
        weak = int(weak)
        succ_buf = ctypes.c_int(0)
        rv = self.cmpxchg_(ord_succ, ord_fail, weak, loc, expected, desired,
                ctypes.byref(succ_buf))
        succ = succ_buf.value != 0
        return (rv, succ)

    def atomicrmw(self, op, loc, opnd, ord=MU_SEQ_CST):
Kunshan Wang's avatar
Kunshan Wang committed
785
786
        """Wrapper of the underlying ``atomicrmw``. The memory order is optional
        and defaults to MU_SEQ_CST."""
Kunshan Wang's avatar
Kunshan Wang committed
787
788
789
790
        _assert_instance(loc, MuIRefValue)
        return self.atomicrmw_(ord, op, loc, opnd)

    def fence(self, ord=MU_SEQ_CST):
Kunshan Wang's avatar
Kunshan Wang committed
791
792
        """Wrapper of the underlying ``fence``. The memory order is optional and
        defaults to MU_SEQ_CST."""
Kunshan Wang's avatar
Kunshan Wang committed
793
794
        return self.fence_(ord)

Kunshan Wang's avatar
Kunshan Wang committed
795
    def new_thread(self, stack, how_to_resume):
Kunshan Wang's avatar
Kunshan Wang committed
796
797
798
799
800
801
802
803
804
805
806
807
808
809
        """Wrapper of the underlying ``new_thread``.
        
        This method now takes only a stack and a ``HowToResume`` value which can
        be either ``PassValues`` or ``ThrowExc``.

        Arguments:
            stack: a MuStackRefValue, the initial stack the new thread should
                bind to.
            how_to_resume: a HowToResume value. See the docstring of
                MuTrapHandler.
        
        Returns:
            a MuThreadRefValue, referring to the newly created thread.
        """
Kunshan Wang's avatar
Kunshan Wang committed
810
811
        _assert_instance(how_to_resume, HowToResume)
        if isinstance(how_to_resume, PassValues):
812
            htr = CMU_REBIND_PASS_VALUES 
Kunshan Wang's avatar
Kunshan Wang committed
813
814
815
816
817
818
819
820
            values = how_to_resume.values
            cvals_ty = CMuValue * len(values)
            cvals = cvals_ty()
            for i,v in enumerate(values):
                cvals[i] = v.c_mu_value
            cnvals = len(values)
            cexc = 0
        else:
821
            htr = CMU_REBIND_THROW_EXC
Kunshan Wang's avatar
Kunshan Wang committed
822
823
824
825
826
827
828
            exc = how_to_resume.exc
            cvals = None
            cnvals = 0
            cexc = exc.c_mu_value

        return self.new_thread_(stack, htr, cvals, cnvals, cexc)

Kunshan Wang's avatar
Kunshan Wang committed
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
    def dump_keepalives(self, cursor, nvals):
        """Wrapper of the underlying ``dump_keepalives``.
        
        This method now takes a cursor and the number of keep-alive variables. It
        returns a list of handles.

        Arguments:
            cursor: a MuFCRefValue, the frame cursor to dump values from.

            nvals: a Python int, the number of keep-alive variables. Must be the
                same as the number of actual keep-alive variables of the current
                instruction. Since the client genereted all bundles, it should
                have full knowledge of the number of keep-alive variables and
                their types.
        
        Returns:
            a list of MuValue. Each of them is a keep-alive variable. They are
            in the same order as the KEEPALIVE clause in the Mu IR.
        """
848
        cvals = (CMuValue * nvals)()
Kunshan Wang's avatar
Kunshan Wang committed
849
        self.dump_keepalives_(cursor, cvals)
850
851
        return [MuValue(cvals[i], self) for i in range(nvals)]

Kunshan Wang's avatar
Kunshan Wang committed
852
853
854
855
856
857
def _to_low_level_type(ty):
    return (None if ty == None else 
            ty._ctype_ if issubclass(ty, _LowLevelTypeWrapper) else
            ty)

def _to_low_level_arg(arg):
Kunshan Wang's avatar
Kunshan Wang committed
858
    return (arg._to_low_level_arg() if isinstance(arg, _LowLevelTypeWrapper) else
859
            _priv._encode(arg, "ascii") if _priv._is_str_like(arg) else
Kunshan Wang's avatar
Kunshan Wang committed
860
            arg)
Kunshan Wang's avatar
Kunshan Wang committed
861
862

def _from_low_level_retval(restype, low_level_rv, self):
Kunshan Wang's avatar
Kunshan Wang committed
863
    return (restype._from_low_level_retval(low_level_rv, self)
Kunshan Wang's avatar
Kunshan Wang committed
864
            if isinstance(restype, type) and issubclass(restype, _LowLevelTypeWrapper) else
865
            _priv._decode(low_level_rv, "ascii") if _priv._is_str_like(low_level_rv) else
Kunshan Wang's avatar
Kunshan Wang committed
866
            low_level_rv)
Kunshan Wang's avatar
Kunshan Wang committed
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888

def _make_high_level_method(name, expected_nargs, restype, argtypes):
    def wrapper(self, *args):
        nargs = len(args)
        if nargs != expected_nargs:
            raise TypeError("{}() takes {} positional argument but "
                    "{} were given".format(name, expected_nargs, nargs))

        low_level_args = []
        for i, arg in enumerate(args):
            argtype = argtypes[i]
            if issubclass(argtype, _LowLevelTypeWrapper):
                # type checking
                if not isinstance(arg, argtype):
                    raise TypeError("Method {}, arg {}, expected type {}, "
                            "actual type: {}, value: {}".format(name, i,
                                argtypes[i], type(arg), arg))

            low_level_arg = _to_low_level_arg(arg)

            low_level_args.append(low_level_arg)

Kunshan Wang's avatar
Kunshan Wang committed
889
890
891
        struct_ptr = self._struct_ptr
        low_level_func = self._low_level_func(name)

Kunshan Wang's avatar
Kunshan Wang committed
892
        self.muvm._set_mu_error(0)
Kunshan Wang's avatar
Kunshan Wang committed
893
        low_level_rv = low_level_func(struct_ptr, *low_level_args)
Kunshan Wang's avatar
Kunshan Wang committed
894
        mu_error = self.muvm._get_mu_error()
Kunshan Wang's avatar
Kunshan Wang committed
895
896
897
898

        if mu_error != 0:
            raise RuntimeError("Error in Mu. mu_error={}".format(mu_error))

Kunshan Wang's avatar
Kunshan Wang committed
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
        rv = _from_low_level_retval(restype, low_level_rv, self)
        return rv

    return wrapper

def _initialize_methods(high_level_class, methods):
    """
    This function does two things:

    1. Populate the high_level_class (such as MuVM) with high-level methods.
    2. Populate the _field_ field of its low-level Structure (such as CMuVM).

    ``high_level_class`` is MuVM or MuCtx.
    
    ``method`` is a list of (name, restype, argtypes), where both restype and
    the elements of argtypes are high-level types, such as MuVM or MuIntValue.
    Type checking will be performed according to these descriptions in the
    generated high-level methods. C-level return values will be wrapped in
    high-level types.
    """

    low_level_class = high_level_class._c_struct_type_

    fields = [("header", ctypes.c_void_p)]
    high_level_methods = {}

    objtype_p = ctypes.POINTER(low_level_class)

    for name, restype, argtypes in methods:
        # make low-level struct field (function pointer)
        low_level_restype = _to_low_level_type(restype)
        low_level_argtypes = [_to_low_level_type(ty) for ty in argtypes]
Kunshan Wang's avatar
Kunshan Wang committed
931
        logger.debug("Python binding: %s :: %s %s", name, low_level_restype, low_level_argtypes)
Kunshan Wang's avatar
Kunshan Wang committed
932
933
934
935
936
937
938
        funcptr = _funcptr(
                low_level_restype, # return value
                objtype_p, *low_level_argtypes # params. Start with a struct ptr
                )
        fields.append((name, funcptr))

        expected_nargs = len(argtypes)
Kunshan Wang's avatar
Kunshan Wang committed
939

Kunshan Wang's avatar
Kunshan Wang committed
940
941
942
        # make high-level method
        wrapper = _make_high_level_method(name, expected_nargs, restype,
                argtypes)
Kunshan Wang's avatar
Kunshan Wang committed
943

Kunshan Wang's avatar
Kunshan Wang committed
944
945
946
947
948
949
950
951
952
        high_level_methods[name] = wrapper

    low_level_class._fields_ = fields
    high_level_class._high_level_methods = high_level_methods

_initialize_methods(MuVM, [
    ("new_context", MuCtx, []),
    ("id_of", CMuID, [CMuName]),
    ("name_of", CMuName, [CMuID]),
Kunshan Wang's avatar
Kunshan Wang committed
953
    ("set_trap_handler_", None, [CMuTrapHandler, CMuCPtr]),
Kunshan Wang's avatar
Kunshan Wang committed
954
    ("execute", None, []),
Kunshan Wang's avatar
Kunshan Wang committed
955
    ("get_mu_error_ptr_", ctypes.c_void_p, []),
Kunshan Wang's avatar
Kunshan Wang committed
956
957
958
    ])

_initialize_methods(MuCtx, [
Kunshan Wang's avatar
Kunshan Wang committed
959
960
961
962
963
964
965
966
    ("id_of"                , CMuID             , [CMuName]),
    ("name_of"              , CMuName           , [CMuID]),

    ("close_context"        , None              , []),

    ("load_bundle_"         , None              , [ctypes.c_char_p, ctypes.c_int]),
    ("load_hail_"           , None              , [ctypes.c_char_p, ctypes.c_int]),

Kunshan Wang's avatar
Kunshan Wang committed
967
968
969
970
971
972
973
974
    ("handle_from_sint8_"   , MuIntValue        , [ctypes.c_int8,   ctypes.c_int]),
    ("handle_from_uint8_"   , MuIntValue        , [ctypes.c_uint8,  ctypes.c_int]),
    ("handle_from_sint16_"  , MuIntValue        , [ctypes.c_int16,  ctypes.c_int]),
    ("handle_from_uint16_"  , MuIntValue        , [ctypes.c_uint16, ctypes.c_int]),
    ("handle_from_sint32_"  , MuIntValue        , [ctypes.c_int32,  ctypes.c_int]),
    ("handle_from_uint32_"  , MuIntValue        , [ctypes.c_uint32, ctypes.c_int]),
    ("handle_from_sint64_"  , MuIntValue        , [ctypes.c_int64,  ctypes.c_int]),
    ("handle_from_uint64_"  , MuIntValue        , [ctypes.c_uint64, ctypes.c_int]),
Kunshan Wang's avatar
Kunshan Wang committed
975
976
977
978
979
    ("handle_from_float"    , MuFloatValue      , [ctypes.c_float ]),
    ("handle_from_double"   , MuDoubleValue     , [ctypes.c_double]),
    ("handle_from_ptr"      , MuUPtrValue       , [CMuID, CMuCPtr ]),
    ("handle_from_fp"       , MuUFPValue        , [CMuID, CMuCFP  ]),

Kunshan Wang's avatar
Kunshan Wang committed
980
981
982
983
984
985
986
987
    ("handle_to_sint8_"     , ctypes.c_int8     , [MuIntValue]),
    ("handle_to_uint8_"     , ctypes.c_uint8    , [MuIntValue]),
    ("handle_to_sint16_"    , ctypes.c_int16    , [MuIntValue]),
    ("handle_to_uint16_"    , ctypes.c_uint16   , [MuIntValue]),
    ("handle_to_sint32_"    , ctypes.c_int32    , [MuIntValue]),
    ("handle_to_uint32_"    , ctypes.c_uint32   , [MuIntValue]),
    ("handle_to_sint64_"    , ctypes.c_int64    , [MuIntValue]),
    ("handle_to_uint64_"    , ctypes.c_uint64   , [MuIntValue]),
Kunshan Wang's avatar
Kunshan Wang committed
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
    ("handle_to_float"      , ctypes.c_float    , [MuFloatValue ]),
    ("handle_to_double"     , ctypes.c_double   , [MuDoubleValue]),
    ("handle_to_ptr"        , CMuCPtr           , [MuUPtrValue  ]),
    ("handle_to_fp"         , CMuCFP            , [MuUFPValue   ]),

    ("handle_from_const"    , MuValue           , [CMuID]),
    ("handle_from_global"   , MuIRefValue       , [CMuID]),
    ("handle_from_func"     , MuFuncRefValue    , [CMuID]),
    ("handle_from_expose"   , MuValue           , [CMuID]),

    ("delete_value"         , None              , [MuValue]),

    ("ref_eq"               , ctypes.c_int      , [MuGenRefValue, MuGenRefValue]),
    ("ref_ult"              , ctypes.c_int      , [MuIRefValue, MuIRefValue]),

    ("extract_value"        , MuValue           , [MuStructValue, ctypes.c_int]),
    ("insert_value"         , MuStructValue     , [MuStructValue, ctypes.c_int, MuValue]),
                            
    ("extract_element"      , MuValue           , [MuSeqValue, MuIntValue]),
Kunshan Wang's avatar
Kunshan Wang committed
1007
    ("insert_element_"      , MuSeqValue        , [MuSeqValue, MuIntValue, MuValue]),
Kunshan Wang's avatar
Kunshan Wang committed
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019

    ("new_fixed"            , MuRefValue        , [CMuID]),
    ("new_hybrid"           , MuRefValue        , [CMuID, MuIntValue]),

    ("refcast"              , MuGenRefValue     , [MuGenRefValue, CMuID]),

    ("get_iref"             , MuIRefValue       , [MuRefValue]),
    ("get_field_iref"       , MuIRefValue       , [MuIRefValue, ctypes.c_int]),
    ("get_elem_iref"        , MuIRefValue       , [MuIRefValue, MuIntValue]),
    ("shift_iref"           , MuIRefValue       , [MuIRefValue, MuIntValue]),
    ("get_var_part_iref"    , MuIRefValue       , [MuIRefValue]),

Kunshan Wang's avatar
Kunshan Wang committed
1020
1021
1022
1023
1024
1025
1026
    ("load_"                , MuValue           , [CMuMemOrd, MuIRefValue]),
    ("store_"               , None              , [CMuMemOrd, MuIRefValue, MuValue]),
    ("cmpxchg_"             , MuValue           , [CMuMemOrd, CMuMemOrd,
        ctypes.c_int, MuIRefValue, MuValue, MuValue,
        ctypes.POINTER(ctypes.c_int)]),
    ("atomicrmw_"           , MuValue           , [CMuMemOrd, CMuAtomicRMWOp, MuIRefValue, MuValue]),
    ("fence_"               , None              , [CMuMemOrd]),
Kunshan Wang's avatar
Kunshan Wang committed
1027
1028

    ("new_stack"            , MuStackRefValue   , [MuFuncRefValue]),
Kunshan Wang's avatar
Kunshan Wang committed
1029
1030
    ("new_thread_"          , MuThreadRefValue  , [MuStackRefValue, CMuHowToResume,
        ctypes.POINTER(CMuValue), ctypes.c_int, CMuRefValue]),
Kunshan Wang's avatar
Kunshan Wang committed
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
    ("kill_stack"           , None              , [MuStackRefValue]),

    ("new_cursor"           , MuFCRefValue      , [MuStackRefValue]),
    ("next_frame"           , None              , [MuFCRefValue]),
    ("copy_cursor"          , MuFCRefValue      , [MuFCRefValue]),
    ("close_cursor"         , None              , [MuFCRefValue]),

    ("cur_func"             , CMuID             , [MuFCRefValue]),
    ("cur_func_ver"         , CMuID             , [MuFCRefValue]),
    ("cur_inst"             , CMuID             , [MuFCRefValue]),
1041
1042
    ("dump_keepalives_"     , None              , [MuFCRefValue,
        ctypes.POINTER(CMuValue)]),
Kunshan Wang's avatar
Kunshan Wang committed
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065

    ("pop_frames_to"        , None              , [MuFCRefValue]),
    ("push_frame"           , None              , [MuStackRefValue, MuFuncRefValue]),

    ("tr64_is_fp"           , ctypes.c_int      , [MuTagRef64Value]),
    ("tr64_is_int"          , ctypes.c_int      , [MuTagRef64Value]),
    ("tr64_is_ref"          , ctypes.c_int      , [MuTagRef64Value]),
    ("tr64_to_fp"           , MuDoubleValue     , [MuTagRef64Value]),
    ("tr64_to_int"          , MuIntValue        , [MuTagRef64Value]),
    ("tr64_to_ref"          , MuRefValue        , [MuTagRef64Value]),
    ("tr64_to_tag"          , MuIntValue        , [MuTagRef64Value]),
    ("tr64_from_fp"         , MuTagRef64Value   , [MuDoubleValue]),
    ("tr64_from_int"        , MuTagRef64Value   , [MuIntValue]),
    ("tr64_from_ref"        , MuTagRef64Value   , [MuRefValue, MuIntValue]),

    ("enable_watchpoint"    , None              , [ctypes.c_int]),
    ("disable_watchpoint"   , None              , [ctypes.c_int]),

    ("pin"                  , MuUPtrValue       , [MuValue]),
    ("unpin"                , None              , [MuValue]),

    ("expose"               , MuValue           , [MuFuncRefValue, CMuCallConv, MuIntValue]),
    ("unexpose"             , None              , [CMuCallConv, MuValue]),
Kunshan Wang's avatar
Kunshan Wang committed
1066
    ])
Kunshan Wang's avatar
Kunshan Wang committed
1067

Kunshan Wang's avatar
Kunshan Wang committed
1068
class DelayedDisposer(object):
Kunshan Wang's avatar
Kunshan Wang committed
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
    """Automatically delete MuValues in the scope.

    Suggested usage::

        with mu.new_context() as ctx:
            ...

            with DelayedDisposer() as x:
                h1 = x << ctx.handle_from_int(1, 64)
                ...
            # h1 is deleted here

            for i in range(100):
                with DelayedDisposer() as x:
                    hi = x << ctx.handle_from_int(i, 64)
                    ...
                # hi is deleted here
    """
Kunshan Wang's avatar
Kunshan Wang committed
1087
1088
1089
    def __init__(self):
        self.garbages = []

Kunshan Wang's avatar
Kunshan Wang committed
1090
1091
1092
    def __enter__(self):
        return self

Kunshan Wang's avatar
Kunshan Wang committed
1093
    def __exit__(self, exc_type, exc_val, exc_tb):
Kunshan Wang's avatar
Kunshan Wang committed
1094
1095
1096
        if exc_type != None:
            return False

Kunshan Wang's avatar
Kunshan Wang committed
1097
        self.delete_all()
Kunshan Wang's avatar
Kunshan Wang committed
1098
        return False
Kunshan Wang's avatar
Kunshan Wang committed
1099
1100

    def add(self, handle):
Kunshan Wang's avatar
Kunshan Wang committed
1101
1102
        """Add handle as a MuValue to be disposed. If handle is not a MuValue,
        treat it as a list of handles."""
Kunshan Wang's avatar
Kunshan Wang committed
1103
1104
1105
1106
1107
        if isinstance(handle, MuValue):
            self.garbages.append(handle)
        else:
            for h in handle:
                self.add(h)
Kunshan Wang's avatar
Kunshan Wang committed
1108
1109
1110
        return handle

    def __lshift__(self, rhs):
Kunshan Wang's avatar
Kunshan Wang committed
1111
        """The same as self.add(rhs)"""
Kunshan Wang's avatar
Kunshan Wang committed
1112
1113
1114
        return self.add(rhs)

    def delete_all(self):
Kunshan Wang's avatar
Kunshan Wang committed
1115
        """Delete all added handles"""
Kunshan Wang's avatar
Kunshan Wang committed
1116
1117
1118
        for h in reversed(self.garbages):
            h.delete();

Kunshan Wang's avatar
Kunshan Wang committed
1119
class MuRefImpl2StartDLL(object):
Kunshan Wang's avatar
Kunshan Wang committed
1120
1121
    """The factory object of MuVM instances."""

Kunshan Wang's avatar
Kunshan Wang committed
1122
    def __init__(self, dll):
Kunshan Wang's avatar
Kunshan Wang committed
1123
1124
1125
1126
        """
        dll is a CDLL object of the "libmurefimpl2start.so" library, or a
        pathname to it. In the latter case, a CDLL will be created.
        """
Kunshan Wang's avatar
Kunshan Wang committed
1127
        if _priv._is_str_like(dll):
Kunshan Wang's avatar
Kunshan Wang committed
1128
1129
1130
1131
1132
1133
            dll = ctypes.CDLL(dll)

        dll.mu_refimpl2_new.restype = CPtrMuVM
        dll.mu_refimpl2_new.argtypes = []

        dll.mu_refimpl2_new_ex.restype = CPtrMuVM
1134
        dll.mu_refimpl2_new_ex.argtypes = [ctypes.c_char_p]
Kunshan Wang's avatar
Kunshan Wang committed
1135
1136
1137
1138
1139
1140
1141

        dll.mu_refimpl2_close.restype = None
        dll.mu_refimpl2_close.argtypes = [CPtrMuVM]

        self.dll = dll

    def mu_refimpl2_new(self):
Kunshan Wang's avatar
Kunshan Wang committed
1142
        """Create a MuVM instance using the default configuration."""
Kunshan Wang's avatar
Kunshan Wang committed
1143
        ptr = self.dll.mu_refimpl2_new()
Kunshan Wang's avatar
Kunshan Wang committed
1144
        return MuVM(ptr, self)
Kunshan Wang's avatar
Kunshan Wang committed
1145

1146
1147
    def mu_refimpl2_new_ex(self, **kwargs):
        """Create a MuVM instance using custom configuration.
Kunshan Wang's avatar
Kunshan Wang committed
1148

1149
1150
1151
1152
1153
        Currently supported keyword arguments:
            sosSize: small object space size (bytes, must be 4096-byte aligned)
            losSize: large object space size (bytes, must be 4096-byte aligned)
            globalSize: global space size (bytes, must be 4096-byte aligned)
            stackSize: stack size (bytes)
1154
1155
1156
            staticCheck: enable or disable static checks (bool)
            sourceInfo: enable or disable source information (bool). Disable
                this if the program is big.
Kunshan Wang's avatar
Kunshan Wang committed
1157
1158
1159
1160
1161
1162
1163
1164
1165

            vmLog: log level for the micro VM
            gcLog: log level fof the garbage collector
            
        possible values for log levels (strings, case insensitive):
            ALL, TRACE, DEBUG, INFO, WARN, ERROR, OFF

        Setting to WARN will disable almost all logs. Set vmLog to INFO to see
        the execution of each instruction; Set gcLog to DEBUG to see GC logs.
Kunshan Wang's avatar
Kunshan Wang committed
1166
        """
Kunshan Wang's avatar
Kunshan Wang committed
1167
1168
        conf = "".join("{}={}\n".format(k,to_vmconf_str(v))
                for k,v in kwargs.items())
1169
        ptr = self.dll.mu_refimpl2_new_ex(_priv._encode(conf, "utf8"))
Kunshan Wang's avatar
Kunshan Wang committed
1170
1171
1172
1173
1174
1175
1176
        return MuVM(ptr, self)

    def mu_refimpl2_close(self, muvm):
        """Close a MuVM instance. Currently does nothing, i.e. MuVM are never
        really closed."""
        self.dll.mu_refimpl2_close(muvm._struct_ptr)

Kunshan Wang's avatar
Kunshan Wang committed
1177
1178
1179
1180
1181
def to_vmconf_str(obj):
    if isinstance(obj, bool):
        return "true" if obj else "false"
    return str(obj)

Kunshan Wang's avatar
Kunshan Wang committed
1182
# vim: ts=4 sw=4 et sts=4 ai tw=80