Source

happygit / bcparser.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
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
from pypy.rlib.rarithmetic import intmask, r_ulonglong
import read_apc_dump as rad
import builtins
import sys
from objects import *

# must be consistent with read_apc_dump
IS_CONST   = (1<<0)
IS_TMP_VAR = (1<<1)
IS_VAR     = (1<<2)
IS_UNUSED  = (1<<3)
IS_CV      = (1<<4)
# These don't appear in Zend, we use them because the way the bytecode is
# stored. Zend znodes are instead unions which contain a type field.
INT_VAL    = (1<<5)
STR_VAL    = (1<<6)
DOUBLE_VAL = (1<<7)
BOOL_VAL   = (1<<8)
NULL_VAL   = (1<<9)
IS_CONST_MASK = INT_VAL | STR_VAL | DOUBLE_VAL | BOOL_VAL | NULL_VAL
# optimize binding for ZEND_INIT_FCALL_BY_NAME when operand is string constant
FN_IDX_VAL = (1<<10)

EXT_TYPE_UNUSED         = (1<<0)
EXT_TYPE_FREE_ON_RETURN = (2<<0)

EA_LOCAL   = (1<<0)
EA_STATIC  = (1<<1)
EA_GLOBAL  = (1<<2)

# method flags
ZEND_ACC_STATIC               = 0x01
ZEND_ACC_ABSTRACT             = 0x02
ZEND_ACC_FINAL                = 0x04
ZEND_ACC_IMPLEMENTED_ABSTRACT = 0x08

ZEND_FE_FETCH_BYREF     = 1
ZEND_FE_FETCH_WITH_KEY  = 2

ZEND_FE_RESET_VARIABLE  = 1
ZEND_FE_RESET_REFERENCE = 2

IS_NULL = 0
IS_LONG = 1
IS_DOUBLE = 2
IS_BOOL = 3
IS_ARRAY = 4
IS_OBJECT = 5
IS_STRING = 6
IS_RESOURCE = 7
IS_CONSTANT = 8
IS_CONSTANT_ARRAY = 9

INVALID_PC = -1

INSN_BYTES = 11

ZEND_ISSET = (1<<0)
ZEND_ISEMPTY = (1<<1)
ZEND_ISSET_ISEMPTY_MASK = (ZEND_ISSET | ZEND_ISEMPTY)

# opcodes
ZEND_NOP = 0
ZEND_ADD = 1
ZEND_SUB = 2
ZEND_MUL = 3
ZEND_DIV = 4
ZEND_MOD = 5
ZEND_SL = 6
ZEND_SR = 7
ZEND_CONCAT = 8
ZEND_BW_OR = 9
ZEND_BW_AND = 10
ZEND_BW_XOR = 11
ZEND_BW_NOT = 12
ZEND_BOOL_NOT = 13
ZEND_BOOL_XOR = 14
ZEND_IS_IDENTICAL = 15
ZEND_IS_NOT_IDENTICAL = 16
ZEND_IS_EQUAL = 17
ZEND_IS_NOT_EQUAL = 18
ZEND_IS_SMALLER = 19
ZEND_IS_SMALLER_OR_EQUAL = 20
ZEND_CAST = 21
ZEND_QM_ASSIGN = 22
ZEND_ASSIGN_ADD = 23
ZEND_ASSIGN_SUB = 24
ZEND_ASSIGN_MUL = 25
ZEND_ASSIGN_DIV = 26
ZEND_ASSIGN_MOD = 27
ZEND_ASSIGN_SL = 28
ZEND_ASSIGN_SR = 29
ZEND_ASSIGN_CONCAT = 30
ZEND_ASSIGN_BW_OR = 31
ZEND_ASSIGN_BW_AND = 32
ZEND_ASSIGN_BW_XOR = 33
ZEND_PRE_INC = 34
ZEND_PRE_DEC = 35
ZEND_POST_INC = 36
ZEND_POST_DEC = 37
ZEND_ASSIGN = 38
ZEND_ASSIGN_REF = 39
ZEND_ECHO = 40
ZEND_PRINT = 41
ZEND_JMP = 42
ZEND_JMPZ = 43
ZEND_JMPNZ = 44
ZEND_JMPZNZ = 45
ZEND_JMPZ_EX = 46
ZEND_JMPNZ_EX = 47
ZEND_SWITCH_FREE = 49
ZEND_BRK = 50
ZEND_CONT = 51
ZEND_BOOL = 52
ZEND_ADD_CHAR = 54
ZEND_ADD_STRING = 55
ZEND_ADD_VAR = 56
ZEND_BEGIN_SILENCE = 57
ZEND_END_SILENCE = 58
ZEND_INIT_FCALL_BY_NAME = 59
ZEND_DO_FCALL = 60
ZEND_DO_FCALL_BY_NAME = 61
ZEND_RETURN = 62
ZEND_RECV = 63
ZEND_SEND_VAL = 65
ZEND_SEND_VAR = 66
ZEND_SEND_REF = 67
ZEND_NEW = 68
ZEND_FREE = 70
ZEND_INIT_ARRAY = 71
ZEND_ADD_ARRAY_ELEMENT = 72
ZEND_UNSET_VAR = 74
ZEND_UNSET_DIM = 75
ZEND_UNSET_OBJ = 76
ZEND_FE_RESET = 77
ZEND_FE_FETCH = 78
ZEND_FETCH_R = 80
ZEND_FETCH_DIM_R = 81
ZEND_FETCH_OBJ_R = 82
ZEND_FETCH_W = 83
ZEND_FETCH_DIM_W = 84
ZEND_FETCH_DIM_RW = 87
ZEND_FETCH_DIM_FUNC_ARG = 93
ZEND_FETCH_UNSET = 95
ZEND_FETCH_DIM_UNSET = 96
ZEND_FETCH_OBJ_FUNC_ARG = 94
ZEND_FETCH_OBJ_UNSET = 97
ZEND_FETCH_CONSTANT = 99
ZEND_SEND_VAR_NO_REF = 106
ZEND_FETCH_CLASS = 109
ZEND_INIT_METHOD_CALL = 112
ZEND_ISSET_ISEMPTY_VAR = 114
ZEND_INIT_STATIC_METHOD_CALL = 113
ZEND_POST_INC_OBJ = 134
ZEND_ASSIGN_OBJ = 136
ZEND_OP_DATA = 137
ZEND_ASSIGN_DIM = 147
START_SCRIPT = 255


opnames = { 0: 'ZEND_NOP',
            1: 'ZEND_ADD',
            2: 'ZEND_SUB',
            3: 'ZEND_MUL',
            4: 'ZEND_DIV',
            5: 'ZEND_MOD',
            6: 'ZEND_SL',
            7: 'ZEND_SR',
            8: 'ZEND_CONCAT',
            9: 'ZEND_BW_OR',
            10: 'ZEND_BW_AND',
            11: 'ZEND_BW_XOR',
            12: 'ZEND_BW_NOT',
            13: 'ZEND_BOOL_NOT',
            14: 'ZEND_BOOL_XOR',
            15: 'ZEND_IS_IDENTICAL',
            16: 'ZEND_IS_NOT_IDENTICAL',
            17: 'ZEND_IS_EQUAL',
            18: 'ZEND_IS_NOT_EQUAL',
            19: 'ZEND_IS_SMALLER',
            20: 'ZEND_IS_SMALLER_OR_EQUAL',
            21: 'ZEND_CAST',
            22: 'ZEND_QM_ASSIGN',
            23: 'ZEND_ASSIGN_ADD',
            24: 'ZEND_ASSIGN_SUB',
            25: 'ZEND_ASSIGN_MUL',
            26: 'ZEND_ASSIGN_DIV',
            27: 'ZEND_ASSIGN_MOD',
            28: 'ZEND_ASSIGN_SL',
            29: 'ZEND_ASSIGN_SR',
            30: 'ZEND_ASSIGN_CONCAT',
            31: 'ZEND_ASSIGN_BW_OR',
            32: 'ZEND_ASSIGN_BW_AND',
            33: 'ZEND_ASSIGN_BW_XOR',
            34: 'ZEND_PRE_INC',
            35: 'ZEND_PRE_DEC',
            36: 'ZEND_POST_INC',
            37: 'ZEND_POST_DEC',
            38: 'ZEND_ASSIGN',
            39: 'ZEND_ASSIGN_REF',
            40: 'ZEND_ECHO',
            41: 'ZEND_PRINT',
            42: 'ZEND_JMP',
            43: 'ZEND_JMPZ',
            44: 'ZEND_JMPNZ',
            45: 'ZEND_JMPZNZ',
            46: 'ZEND_JMPZ_EX',
            47: 'ZEND_JMPNZ_EX',
            49: 'ZEND_SWITCH_FREE',
            50: 'ZEND_BRK',
            51: 'ZEND_CONT',
            52: 'ZEND_BOOL',
            54: 'ZEND_ADD_CHAR',
            55: 'ZEND_ADD_STRING',
            56: 'ZEND_ADD_VAR',
            57: 'ZEND_BEGIN_SILENCE',
            58: 'ZEND_END_SILENCE',
            59: 'ZEND_INIT_FCALL_BY_NAME',
            60: 'ZEND_DO_FCALL',
            61: 'ZEND_DO_FCALL_BY_NAME',
            62: 'ZEND_RETURN',
            63: 'ZEND_RECV',
            65: 'ZEND_SEND_VAL',
            66: 'ZEND_SEND_VAR',
            67: 'ZEND_SEND_REF',
            68: 'ZEND_NEW',
            70: 'ZEND_FREE',
            71: 'ZEND_INIT_ARRAY',
            72: 'ZEND_ADD_ARRAY_ELEMENT',
            74: 'ZEND_UNSET_VAR',
            75: 'ZEND_UNSET_DIM',
            76: 'ZEND_UNSET_OBJ',
            77: 'ZEND_FE_RESET',
            78: 'ZEND_FE_FETCH',
            80: 'ZEND_FETCH_R',
            81: 'ZEND_FETCH_DIM_R',
            82: 'ZEND_FETCH_OBJ_R',
            83: 'ZEND_FETCH_W',
            84: 'ZEND_FETCH_DIM_W',
            87: 'ZEND_FETCH_DIM_RW',
            93: 'ZEND_FETCH_DIM_FUNC_ARG',
            94: 'ZEND_FETCH_OBJ_FUNC_ARG',
            95: 'ZEND_FETCH_UNSET',
            96: 'ZEND_FETCH_DIM_UNSET',
            97: 'ZEND_FETCH_OBJ_UNSET',
            99: 'ZEND_FETCH_CONSTANT',
            106: 'ZEND_SEND_VAR_NO_REF',
            109: 'ZEND_FETCH_CLASS',
            112: 'ZEND_INIT_METHOD_CALL',
            114: 'ZEND_ISSET_ISEMPTY_VAR',
            113: 'ZEND_INIT_STATIC_METHOD_CALL',
            134: 'ZEND_POST_INC_OBJ',
            136: 'ZEND_ASSIGN_OBJ',
            137: 'ZEND_OP_DATA',
            147: 'ZEND_ASSIGN_DIM',
          }


class SymbolTable(object):
    def __init__(self):
        self.values = []
        self.indices = {}

    def add_value(self, value):
        val_key = value.get_as_key()
        if val_key in self.indices:
            return self.indices[val_key]

        idx = len(self.values)
        self.values.append(value)
        self.indices[val_key] = idx
        return idx

    def get_length(self):
        return len(self.values)

    def get_symbol(self, idx):
        return self.values[idx]

    def contains_value(self, value):
        return value.get_as_key() in self.indices

    def get_index(self, value):
        return self.indices[value.get_as_key()]

def zval_effective(zval, constant_table):
  if zval.type == zval.IS_LONG:
    return INT_VAL, intmask(zval.lval)
  elif zval.type == zval.IS_STRING:
    return STR_VAL, constant_table.add_value(W_str(zval.str))
  elif zval.type == zval.IS_DOUBLE:
    return DOUBLE_VAL, constant_table.add_value(W_float(zval.dval)) 
  elif zval.type == zval.IS_BOOL:
    return BOOL_VAL, intmask(zval.lval)
  elif zval.type == zval.IS_NULL:
    return NULL_VAL, 0
  return (zval.IS_UNUSED, zval.IS_UNUSED)


def znode_effective(znode, name_table, constant_table, cvars):
  if znode.op_type == znode.IS_VAR:
    var_name = '$' + str(znode.var / 20)
    return intmask(znode.op_type), name_table.add_value(W_str(var_name))
  elif znode.op_type == znode.IS_TMP_VAR:
    var_name = '~' + str(znode.var / 20)
    return intmask(znode.op_type), name_table.add_value(W_str(var_name))
  elif znode.op_type == znode.IS_CV:
    var_name = cvars[znode.var].name
    return intmask(znode.op_type), name_table.add_value(W_str(var_name))
  elif znode.op_type == znode.IS_CONST:
    return zval_effective(znode.constant, constant_table)
  elif znode.op_type == znode.IS_UNUSED:
    return intmask(znode.op_type), intmask(znode.opline_num)
  return (znode.IS_UNUSED, znode.IS_UNUSED)


#def znode_to_str(znode, name_to_idx, idx_to_name, immstr_to_idx,
#        idx_to_immstr, cvars):
#  znode_type, znode_eff = znode_effective(znode, name_to_idx, idx_to_name,
#          immstr_to_idx, idx_to_immstr, cvars)
#  if znode_type == LOCAL_VAR or znode_type == GLOBAL_VAR or znode_type == STATIC_VAR:
#    return idx_to_name[znode_eff]
#  elif znode_type == INT_VAL:
#    return 'const(' + str(znode_eff) + ')'
#  elif znode_type == STR_VAL:
#    return 'const('' + idx_to_immstr[znode_eff] + '')'
#  elif znode_type == UNUSED_VAL:
#    return 'unused(' + str(znode_eff)  + ')'


def create_bc_array(op_array, apc_dump, fn_to_idx, constant_table):
  opcodes = op_array.opcodes
  cvars = op_array.vars
  name_table = SymbolTable()
  bytecode = []
  cvs = {}
  for instr in opcodes:
    bytecode.append(intmask(instr.opcode))
    # RESULT
    res_type, res_eff = znode_effective(instr.result, name_table,
            constant_table, cvars)
    if res_type == IS_CV:
      cvs[res_eff] = True
    bytecode.append(res_type)
    bytecode.append(res_eff)
    # OP1
    if instr.opcode != ZEND_JMP:
      op1_type, op1_eff = znode_effective(instr.op1, name_table,
              constant_table, cvars)
      if op1_type == IS_CV:
        cvs[op1_eff] = True
      if (instr.opcode == ZEND_DO_FCALL or
          (instr.opcode == ZEND_INIT_FCALL_BY_NAME and op1_type == STR_VAL)):
        fn_name = instr.op1.constant.str.lower()
        if builtins.is_builtin_name(fn_name):
            fn_idx = builtins.get_builtin_for_name(fn_name)
        else:
            fn_idx = fn_to_idx[fn_name]
        op1_type, op1_eff = FN_IDX_VAL, fn_idx
      bytecode.append(op1_type)
      bytecode.append(op1_eff)
    else:
      for j in range(len(opcodes)):
        dict_key = instr.op1.jmp_addr, opcodes[j].get_dict_key() 
        if opcodes[j] == apc_dump.offset_struct_dict[dict_key]:
          bytecode.append(INT_VAL)
          bytecode.append(j)
          break
    # OP2
    if (instr.opcode != ZEND_JMPZ and instr.opcode != ZEND_JMPNZ and
        instr.opcode != ZEND_JMPZ_EX and instr.opcode != ZEND_JMPNZ_EX):
      op2_type, op2_eff = znode_effective(instr.op2, name_table,
              constant_table, cvars)
      if op2_type == IS_CV:
        cvs[op2_eff] = True
      bytecode.append(op2_type)
      bytecode.append(op2_eff)
    else:
      for j in range(len(opcodes)):
        dict_key = instr.op2.jmp_addr, opcodes[j].get_dict_key() 
        if opcodes[j] == apc_dump.offset_struct_dict[dict_key]:
          bytecode.append(INT_VAL)
          bytecode.append(j)
          break
    bytecode.append(intmask(instr.extended_value))
    bytecode.append(intmask(instr.op2.EA_type))
    bytecode.append(intmask(instr.result.EA_type))
    bytecode.append(INVALID_PC)
  return (bytecode, name_table, cvs)


def parse_bytecode(filename):
  apc_dump = rad.APCFile(filename)
  # 0 reserved for main
  fn_to_idx = { '': 0 }
  idx_to_fn = [ '' ]
  fn_code = []
  names_to_idx = []
  constant_table = SymbolTable()

  for fn in apc_dump.apc_bd.entries[0].value.functions:
    fn_to_idx[fn.name.lower()] = len(idx_to_fn)
    idx_to_fn.append(fn.name.lower())

  for cl in apc_dump.apc_bd.entries[0].value.classes:
    fn_table = cl.class_entry.function_table
    for it in fn_table.members():
      member = it.pData
      if not isinstance(member, rad.APCFile.ZEND_function):
        continue
      methodName = cl.class_entry.name + '::' + it.arKey[:-1].lower()
      fn_to_idx[methodName] = len(idx_to_fn)
      idx_to_fn.append(methodName)

  bytecode, name_table, cvs = create_bc_array(
          apc_dump.apc_bd.entries[0].value.op_array,
          apc_dump, fn_to_idx, constant_table)
  fn_code.append((bytecode, apc_dump.apc_bd.entries[0].value,
                  name_table.get_length(), cvs))
  names_to_idx.append(name_table)

  class_table = { '': ({ '': 0 }, {}, {}, 0, 0, None, '') }
  method_to_class = {}
  statics_table = { 0: {} }

  for fn in apc_dump.apc_bd.entries[0].value.functions:
    bytecode, name_table, cvs = create_bc_array(fn.function.op_array, apc_dump,
            fn_to_idx, constant_table)
    fn_code.append((bytecode, fn.function, name_table.get_length(), cvs))
    names_to_idx.append(name_table)

    fn_idx = fn_to_idx[fn.name.lower()]
    statics_table[fn_idx] = {}
    static_vars = fn.function.op_array.static_variables
    if not isinstance(static_vars, rad.APCFile.NullStruct): 
      for it in static_vars.members():
        if not isinstance(it.pData, rad.APCFile.ZEND_zval):
          continue
        static_name = it.arKey[:-1]
        statics_table[fn_idx][static_name] = zval_effective(it.pData,
            constant_table)

  for cl in apc_dump.apc_bd.entries[0].value.classes:
    has_constructor = not isinstance(cl.class_entry.constructor, rad.APCFile.NullStruct)
    has_destructor = not isinstance(cl.class_entry.destructor, rad.APCFile.NullStruct)

    method_table = {}

    # Add inherited methods.
    # TODO: do the same thing for fields and handle inherited classes declared
    # before their parents in the source code.
    parent_method_table = {}
    if cl.parent_name != '':
      parent_method_table = class_table[cl.parent_name.lower()][0]
    for parent_method_name in parent_method_table:
      method_table[parent_method_name] = parent_method_table[parent_method_name]

    fn_table = cl.class_entry.function_table
    for it in fn_table.members():
      member = it.pData
      if not isinstance(member, rad.APCFile.ZEND_function):
        continue
      bytecode, name_table, cvs = create_bc_array(member.op_array, apc_dump,
              fn_to_idx, constant_table)
      names_to_idx.append(name_table)
      # Maybe we should store the flags as well, but PHP seems to handle
      # "gracefully" (swallowing any error or warning) using instance methods
      # as class methods and vice versa as long as they don't access $this. If
      # they do, Zend handles $this as any other undefined variable.
      methodName = it.arKey[:-1].lower()
      method_table[methodName] = len(fn_code)
      method_to_class[len(fn_code)] = cl
      fn_code.append((bytecode, member, name_table.get_length(), cvs))

    default_properties = {}
    for it in cl.class_entry.default_properties.members():
      if not isinstance(it.pData, rad.APCFile.ZEND_zval):
        continue
      # FIXME: case-insensitive?
      propName = it.arKey[:-1]
      default_properties[W_str(propName)] = zval_effective(
              it.pData, constant_table)

    default_static_members = {}
    for it in cl.class_entry.default_static_members.members():
      if not isinstance(it.pData, rad.APCFile.ZEND_zval):
        continue
      # FIXME: case-insensitive?
      propName = it.arKey[:-1]
      default_static_members[W_str(propName)] = zval_effective(
              it.pData, constant_table)

    construct_idx = method_table["__construct"]\
        if "__construct" in method_table else 0
    destruct_idx = method_table["__destruct"]\
        if "__destruct" in method_table else 0

    class_table[cl.name.lower()] = (method_table, default_properties,
        default_static_members, construct_idx, destruct_idx,
        cl.class_entry, cl.parent_name)

  return (fn_code, fn_to_idx, constant_table, names_to_idx, class_table,
          statics_table, method_to_class)


def entry_point(argv):
    p = parse_bytecode(argv[1])
    bytecode, var_count = p[0][0]
    constant_table = p[2]
    print bytecode
    print constant_table
    print var_count
    return 0


def target(*args):
    return entry_point, None


if __name__== '__main__':
    entry_point(sys.argv)