repl.it
@pyelias/

safe-py

Python

cursed and slow af but whatever

fork
loading
Files
  • main.py
  • test.py
main.py
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
import dis
import inspect
import enum
import weakref
import operator

UNARY_OP_FUNCS = {
  "UNARY_POSITIVE": operator.pos,
  "UNARY_NEGATIVE": operator.neg,
  "UNARY_NOT": operator.not_,
  "UNARY_INVERT": operator.inv,
  "GET_ITER": iter,

}

BINARY_OP_FUNCS = {
  "BINARY_ADD": operator.add,
  "BINARY_SUBTRACT": operator.sub,
  "BINARY_MULTIPLY": operator.mul,
  "BINARY_MATRIX_MULTIPLY": operator.matmul,
  "BINARY_TRUE_DIVIDE": operator.truediv,
  "BINARY_FLOOR_DIVIDE": operator.floordiv,
  "BINARY_MODULO": operator.mod,
  "BINARY_POWER": operator.pow,
  "BINARY_SUBSCR": operator.getitem,
  "BINARY_LSHIFT": operator.lshift,
  "BINARY_RSHIFT": operator.rshift,
  "BINARY_AND": operator.and_,
  "BINARY_OR": operator.or_,
  "BINARY_XOR": operator.xor,
}

INPLACE_OP_FUNCS = {
  "INPLACE_ADD": operator.iadd,
  "INPLACE_SUBTRACT": operator.isub,
  "INPLACE_MULTIPLY": operator.imul,
  "INPLACE_MATRIX_MULTIPLY": operator.imatmul,
  "INPLACE_TRUE_DIVIDE": operator.itruediv,
  "INPLACE_FLOOR_DIVIDE": operator.ifloordiv,
  "INPLACE_MODULO": operator.imod,
  "INPLACE_POWER": operator.ipow,
  "INPLACE_LSHIFT": operator.ilshift,
  "INPLACE_RSHIFT": operator.irshift,
  "INPLACE_AND": operator.iand,
  "INPLACE_OR": operator.ior,
  "INPLACE_XOR": operator.ixor,
}

class Code():
  """
  basically just a nicer version of the builtin code object
  """
  def __init__(self, code):
    self.argcount = code.co_argcount
    self.cellvars = code.co_cellvars
    self.code = list(dis.get_instructions(code)) # code.co_code
    self.code_inds = {instr.offset: i for i, instr in enumerate(self.code)}
    self.consts = code.co_consts
    self.flags = code.co_flags
    self.freevars = code.co_freevars
    self.kwonlyargcount = code.co_kwonlyargcount
    self.names = code.co_names
    # self.nlocals = code.co_nlocals # dont think this is needed, len(self.varnames)
    self.varnames = code.co_varnames
  
  def get_instr(self, ind):
    return self.code[ind]
  
  def get_ind(self, offset):
    return self.code_inds[offset]
  
  def get_const(self, ind):
    return self.consts[ind]
  
  def flag_set(self, flag):
    return flag & self.flags
  
  def allow(self, env):
    if env.allows(self):
      return
    env.allow(self)
    for const in self.consts:
      env.allow(const)

class Maybe():
  @classmethod
  def some(cls, val):
    res = cls()
    res.exists = True
    res.val = val
    return res
  
  @classmethod
  def none(cls):
    res = cls()
    res.exists = False
    return res
  
  def unwrap(self):
    assert self.exists
    return self.val

class Finished(enum.Enum):
  NOTHING = 0
  RETURN = 1
  EXCEPTION = 2

class Environment():
  def __init__(self):
    self.allowed = weakref.WeakSet()
    self.allowed_strong = set() # some things cant have weakrefs
    self.stack = []
  
  def allow(self, val):
    try:
      self.allowed.add(val)
    except TypeError:
      self.allowed_strong.add(val)
  
  def allows(self, val):
    return val in self.allowed or val in self.allowed_strong
  
  def run_step(self):
    finished, *finished_data = self.stack[-1].run_instr()
    while True:
      if finished == Finished.RETURN:
        self.stack.pop()
        if not self.stack:
          break
        self.stack[-1].push(finished_data[0])
        return (Finished.NOTHING,)

      elif finished == Finished.EXCEPTION:
        self.stack.pop()
        if not self.stack:
          break
        finished, *finished_data = self.stack[-1].throw(finished_data[0])
      
      else:
        break
    
    return (finished, *finished_data)

  def run(self):
    while self.stack:
      res = self.run_step()
    return res

class Frame():
  def __init__(self, env, code, args=None, kwargs=None):
    self.env = env
    self.code = code
    self.pc = 0
    self.locals = [Maybe.none()] * len(code.varnames)
    self.local_dict = {}
    self.stack = []

    self.set_args(args)
  
  def set_args(self, args):
    if args is None:
      args = []
    
    argcount = self.code.argcount
    if len(args) < argcount:
      raise ValueError("not enough arguments")
    
    for i in range(argcount):
      self.set_local(i, args[i])

    if self.code.flag_set(inspect.CO_VARARGS):
      self.set_local(argcount, Maybe.some(tuple(args[argcount:])))

    elif len(args) > argcount:
      raise ValueError("too many arguments")
    
    for arg in args:
      self.env.allow(arg)

  
  def get_local(self, ind):
    return self.locals[ind].unwrap()
  
  def set_local(self, ind, val):
    self.locals[ind] = Maybe.some(val)
  
  def del_local(self, ind):
    self.locals[ind] = Maybe.none()

  
  def pop(self):
    """pop from stack, checking that the result is allowed"""
    val = self.stack.pop() # errors if the stack is empty, but cpython segfaults so this is fine probably
    assert self.env.allows(val)
    return val
  
  def top(self):
    """top of stack, if allowed"""
    val = self.stack[-1]
    assert self.env.allows(val)
    return val
  
  def push(self, val):
    """push a value to the stack"""
    assert self.env.allows(val)
    self.stack.append(val)
  
  def push_built(self, val):
    """push a newly created (allowed by default) value"""
    self.env.allow(val)
    self.stack.append(val)
  
  def throw(self, e):
    return (Finished.EXCEPTION, e)

  def run_instr(self):
    instr = self.code.code[self.pc]
    opname = instr.opname
    self.pc += 1

    if opname == "NOP": # does this ever happen?
      pass

    elif opname == "POP_TOP":
      self.pop()

    elif opname == "ROT_TWO":
      a, b = self.pop(), self.pop()
      self.push(a)
      self.push(b)

    elif opname == "ROT_THREE":
      a, b, c = self.pop(), self.pop(), self.pop()
      self.push(a)
      self.push(c)
      self.push(b)

    elif opname == "DUP_TOP":
      self.push(self.top())
    
    elif opname == "DUP_TOP_TWO":
      a, b = self.pop(), self.pop()
      self.push(b)
      self.push(a)
      self.push(b)
      self.push(a)
    
    elif opname in UNARY_OP_FUNCS:
      op_func = UNARY_OP_FUNCS[opname]

      a = self.pop()
      try:
        res = op_func(a)
      except BaseException as e:
        return self.throw(e)
      self.push_built(res)

    elif opname in BINARY_OP_FUNCS:
      op_func = BINARY_OP_FUNCS[opname]

      a, b = self.pop(), self.pop()
      try:
        res = op_func(b, a)
      except BaseException as e:
        return self.throw(e)
      self.push_built(res)
    
    elif opname == "STORE_SUBSCR":
      index = self.pop()
      indexing = self.pop()
      val = self.pop()
      
      try:
        indexing[index] = val
      except BaseException as e:
        return self.throw(e)
    
    elif opname == "DELETE_SUBSCR":
      index = self.pop()
      indexing = self.pop()
      
      try:
        del indexing[index]
      except BaseException as e:
        return self.throw(e)
    
    elif opname == "PRINT_EXPR":
      val = self.pop()
      if val is not None:
        print(val)

    elif opname == "LOAD_CONST":
      self.push(self.code.get_const(instr.arg))

    elif opname == "LOAD_FAST":
      val = self.get_local(instr.arg)
      self.push(val)

    elif opname == "RETURN_VALUE":
      return (Finished.RETURN, self.pop())
    
    else:
      raise ValueError(f"unknown opname {opname}")
    
    return (Finished.NOTHING,)

def f(a):
  return -(a + 1)

dis.dis(f)
c = Code(f.__code__)

e = Environment()
c.allow(e)

f = Frame(e, c, [2])
e.stack.append(f)

print(e.run())
Fetching token
?