Esempio n. 1
0
    def callbefore(self, pid, call, args):
	state = ()
	handle2 = handle = -1
	if call == 'socketcall':
	    if args[0] > sockettable_num:
		raise 'Trying to do invalid socketcall?'
	    subcall, pattern = sockettable[args[0]]
	    nargs = len(pattern)
	    if debug: print 'Doing ', subcall, ' with ', nargs, ' parameters', 
	    params = Memory.getMemory(pid).peek(args[1], nargs*4)
	    params = list(params)

	    curfd = -1
	    addrlen = -1

	    for i in range(len(pattern)):
		if pattern[i] == 'l':
		    if debug: print 'Getint returned ', getint(params, i*4)
		    addrlen = getint(params, i*4)
# Note: this is not true for unix domain sockets
#		    assert getint(params, i*4) == 16, '== %s' % getint(params, i*4)

	    for i in range(len(pattern)):
		if pattern[i] == 'f':
		    curfd = getint(params, i*4)
		    if debug: print '(fd = ', curfd, ')',

		if pattern[i] == 'A':
		    paddr = getint(params, i*4)
#		    print 'Call = ', subcall
		    address = Memory.getMemory(pid).peek(paddr, addrlen)
		    #address = list(address) # WHY?
		    if not self.checkaddress(self.fdmap[pid][curfd], address, addrlen, call):
			return (None, -errno.EPERM, None, None)
		    if debug: print 'Address is ', address
		    handle2, addr2 = scratch.alloc_bytes(address, addrlen)
		    if debug: print 'Addr = %x' % addr2
		    setint(params, i*4, addr2)
		    if addr2 != getint(params, i*4):
			raise 'addr2 not equal to getint'

	    handle, addr = scratch.alloc_bytes(params, nargs*4)
	    if subcall == 'socket':
		state = ( getint(params, 0), getint(params, 4), getint(params, 8) )

	    if subcall == 'connect':
#	        assert 0
		pass

	    if subcall == 'bind':
		print 'Trying to bind'
		return (None, -errno.EPERM, None, None)

	    if subcall == 'invalid_call':
		raise 'Invalid socket call'

	    if debug: print state, '... copied them to ',
	    if debug: print '%x' % addr
	return ((subcall, handle, handle2, state), None, None, (args[0], addr))
Esempio n. 2
0
def exec_cmp(inst):
    rs_obj = Memory.get_obj(Registers.get_reg(inst['rs']))
    rt_obj = Memory.get_obj(Registers.get_reg(inst['rt']))
    if rs_obj['type'] == rt_obj['type'] and rs_obj['data'] == rt_obj['data']:
        Registers.set_reg(inst['rd'], Constants.get_int(1))
    else:
        Registers.set_reg(inst['rd'], Constants.get_int(0))
    inc_pc(4)
Esempio n. 3
0
def i_ISZ(indirect, address, instruction):
    global PC

    value = (Memory.get(address, indirect) + 1) & WORDMASK
    Memory.put(value, address, indirect)
    if value == 0:
        PC = (PC + 1) & WORDMASK
    Trace.itrace('ISZ', indirect, address)
    return 3 if indirect else 2
Esempio n. 4
0
def init(run_address, tracefile, tstart, tend, boot_rom=None, corefile=None):
    global tracestart, traceend

    Memory.init(boot_rom, corefile)
    Trace.init(tracefile)
    tracestart = tstart
    traceend = tend
    DisplayCPU.init()
    MainCPU.init()
Esempio n. 5
0
def i_JMS(indirect, address, instruction):
    global PC

    jmsaddr = EFFADDR(address)
    if indirect:
        jmsaddr = Memory.get(jmsaddr, False)
    Memory.put(PC, jmsaddr, False)
    PC = (jmsaddr + 1) & PCMASK
    Trace.itrace('JMS', indirect, address)
    return 3 if indirect else 2
Esempio n. 6
0
def i_SAM(indirect, address, instruction):
    global PC

    samaddr = EFFADDR(address)
    if indirect:
        samaddr = Memory.get(samaddr, False)
    if AC == Memory.get(samaddr, False):
        PC = (PC + 1) & PCMASK
    Trace.itrace('SAM', indirect, address)
    return 3 if indirect else 2
Esempio n. 7
0
def load_text(text):
    addr = 0
    for line in text:
        if line.startswith(';'):
            continue
        if line.find(':') == -1:
            Memory.write(addr, {'type': 2, 'inst': Parser.inst(line)})
            addr += 4
        else:
            Labels.add(line.strip().split(':')[0], addr)
Esempio n. 8
0
def i_XAM(indirect, address, instruction):
    global AC

    if indirect:
        address = Memory.get(address, False)
    tmp = Memory.get(address, False)
    Memory.put(AC, address, False)
    AC = tmp
    Trace.itrace('XAM', indirect, address)
    return 3 if indirect else 2
Esempio n. 9
0
 def visit(self, node):
     fun = self.memoryStack.get(node.name)#EXCEPTION
     funMemory = Memory(node.name)
     for argExpr, actualArg in zip(node.args.children, fun.args.children):
         funMemory.put(actualArg.accept(self), argExpr.accept(self))
     self.memoryStack.push(funMemory)
     try:
         fun.body.accept(self)
     except ReturnValueException as e:
         return e.value
     finally:
         self.memoryStack.pop()
Esempio n. 10
0
 def visit(self, node):
     fun = self.functionStack.get(node.id)
     function_memory = Memory(node.id)
     for actualArg, argExpr in zip(fun.args.accept(self), node.arglist.accept(self)):
         function_memory.put(actualArg, argExpr)
     self.variableStack.push(function_memory)
     try:
         fun.body.accept(self)
     except ReturnValueException as e:
         return e.value
     finally:
         self.variableStack.pop()
Esempio n. 11
0
def exec_newfunc(inst):
    func_addr = Memory.new_func()
    address_prop = Memory.get_field(func_addr, Constants.get_str('address'))
    Memory.set_prop(address_prop, value=Memory.new_int(Labels.query(inst['label'])))
    outer_func = Memory.read_plain(Registers.read_fp() - 4)
    outer_prop = Memory.get_field(func_addr, Constants.get_str('outer'))
    Memory.set_prop(outer_prop, value=outer_func)
    Registers.set_reg(inst['rd'], func_addr)
    inc_pc(4)
Esempio n. 12
0
def exec_slt(inst):
    rs_obj = Memory.get_obj(Registers.get_reg(inst['rs']))
    rt_obj = Memory.get_obj(Registers.get_reg(inst['rt']))
    if (rs_obj['type'] == 0 and rt_obj['type'] == 0) or \
       (rs_obj['type'] == 2 and rt_obj['type'] == 2):
        if rs_obj['data'] < rt_obj['data']:
           Registers.set_reg(inst['rd'], Constants.get_int(1))
        else:
            Registers.set_reg(inst['rd'], Constants.get_int(0))
    else:
        raise Exception('The following object are not comparable yet.\n' +
                        '%s\n%s' % (str(rs_obj), str(rt_obj)))
    inc_pc(4)
Esempio n. 13
0
 def visit(self, node):
     function = self.memoryStack.get(node.id)
     functionMemory = Memory(node.id)
     for argId, argExpr in zip(function.arglist.arg_list, node.expression_list.expressions):
         functionMemory.put(argId.accept(self), argExpr.accept(self))
     self.memoryStack.push(functionMemory)
     self.isFunctionScope = True
     try:
         function.compound_instr.accept(self)
     except ReturnValueException as e:
         return e.value
     finally:
         self.isFunctionScope = False
         self.memoryStack.pop()
Esempio n. 14
0
 def visit(self, node):
     fun = self.globalMemory.get(node.name)
     funFrame = Memory(node.name)
     if (fun.arg_list != None):
         for arg, val in list(zip(fun.arg_list.children, node.expr.children)):
             funFrame.put(arg.accept(self), val.accept(self))
     self.functionMemory.push(funFrame)
     self.isFunctionCompound = True
     try:
         fun.compound_instr.accept(self)
     except ReturnValueException as e:
         return e.value
     finally:
         self.functionMemory.pop()
Esempio n. 15
0
 def visit(self, node, create_memory=True):
     fun = self.memory_stack.get(node.id)
     fun_memory = Memory(node.id)
     if node.expr_list is not None:
         for arg_expression, actual_arg in zip(node.expr_list.expr_list, fun.args_list.arg_list):
             arg = actual_arg.accept(self)
             expr = arg_expression.accept(self)
             fun_memory.put(arg, expr)
     self.memory_stack.push(fun_memory)
     try:
         fun.comp_instr.accept(self, False)
     except ReturnValueException as e:
         return e.value
     finally:
         self.memory_stack.pop()
Esempio n. 16
0
def get_int(value):
    if value in integer_pool:
        return integer_pool[value]
    else:
        addr = Memory.new_int(value)
        integer_pool[value] = addr
        return addr
Esempio n. 17
0
def get_str(string):
    if string in string_pool:
        return string_pool[string]
    else:
        addr = Memory.new_str(string)
        string_pool[string] = addr
        return addr
Esempio n. 18
0
    def callbefore(self, pid, call, args):
        '''
        Entry point for the trick.
        @return: None
        '''
        m = Memory.getMemory(pid)
        arg_mem_addr_path = args[0]
        arg_flags = args[1]
        arg_mode = args[2]
        
        try:
            filename = m.get_string( arg_mem_addr_path )
        except:
            pass
        else:
        
            if not self._is_library( filename ):
            
                local_filename = self._download_file( filename )

                area, area_size = m.areas()[0]
                m.poke(area, local_filename + '\0')
        
                return (None, None, None, (area, arg_flags, arg_mode) )
        
        return None
    def callbefore(self, pid, call, args):
        sign = _callaccess[call]
        if not isinstance(sign, types.TupleType):
            if not call == 'socketcall' or not self._net:
                if not self._quiet:
                    print '%s denied' % call
                return (None, -errno.EPERM, None, None)
            return

        if (call == 'open'
            and args[1] & FCNTL.O_ACCMODE == FCNTL.O_RDONLY):
            sign = ('r',)

        getarg = Memory.getMemory(pid).get_string

        for i in range(len(sign)):
            if sign[i]:
                s = sign[i][0]
                assert s == 'r' or s == 'w'
                if s == 'r':
                    a = self._read
                    op = 'read'
                else:
                    a = self._write
                    op = 'write'
                followlink = len(sign[i]) < 2
                assert followlink or sign[i][1] == 'l'
                p = getarg(args[i])
                r = _access(pid, p, followlink, a)
                if r == -1:
                    if not self._quiet:
                        print '%s deny (%s): %s' % (op, call, repr(p))
                    return (None, -errno.EACCES, None, None)
                elif r != 0:
                    return (None, -r, None, None)
Esempio n. 20
0
def exec_mul(inst):
    rs_obj = Memory.get_obj(Registers.get_reg(inst['rs']))
    rt_obj = Memory.get_obj(Registers.get_reg(inst['rt']))
    rd_val = Registers.get_reg(inst['rd'])
    if rs_obj['type'] == 0 and rt_obj['type'] == 0:  # both are integers
        Memory.set_int(rd_val, rs_obj['data'] * rt_obj['data'])
    elif {rs_obj['type'], rt_obj['type']} == {0, 2}:  # an integer and a string
        str_addr = Memory.new_str(rs_obj['data'] * rt_obj['data'])
        Memory.set_obj(rd_val, Memory.get_obj(str_addr))
    inc_pc(4)
Esempio n. 21
0
def i_JMP(indirect, address, instruction):
    global PC

    jmpaddr = EFFADDR(address)
    if indirect:
        jmpaddr = Memory.get(jmpaddr, False)
    PC = jmpaddr & PCMASK
    Trace.itrace('JMP', indirect, address)
    return 3 if indirect else 2
Esempio n. 22
0
def load_data(data):
    addr = 0x10000000
    line = 0
    while line < len(data):
        label = data[line].strip().split(':')[0]
        Labels.add(label, addr)
        if label.startswith('int_'):
            value = int(re.match(r'\s+\.word\s+(-?\w+)', data[line+2]).group(1), 16)
            Memory.set_int(addr, value)
            Constants.set_int(value, addr)
            addr += 8
            line += 3
        elif label.startswith('str_'):
            string = re.match(r'\s+\.asciiz\s+"([^"]+)"', data[line+3]).group(1)
            string = string.decode('string_escape')
            Memory.set_str(addr, string)
            Constants.set_str(string, addr)
            addr += 8 + math.floor(len(string) / 4 + 1) * 4
            line += 4
Esempio n. 23
0
def i_SUB(indirect, address, instruction):
    global AC, L

    effaddr = EFFADDR(address)
    AC -= Memory.get(address, indirect)
    if AC & OVERFLOWMASK:
        L = not L
        AC &= WORDMASK
    Trace.itrace('SUB', indirect, address)
    return 3 if indirect else 2
 def callbefore(self, pid, call, args):
     if call == 'open':
         getarg = Memory.getMemory(pid).get_string
         if getarg(args[0]) == "/dev/tty":
             assert self.ttyfd == None, "tried to open /dev/tty twice"
             return (1, None, None, None)
     elif call == 'close':
         if self.ttyfd == args[0]:
             self.ttyfd = None
     elif call == 'read':
         if args[0] == self.ttyfd:
             buf = args[1]
             count = args[2]
             count = min(count, len(self.guess))
             if not count:
                 sys.exit("ran out of guess")
             m = Memory.getMemory(pid)
             m.poke(buf, self.guess[:count])
             self.guess = self.guess[count:]
             return (None, count, None, None)
    def set_up_write_back_stage(self, instruction_string):
        """Set up WriteBackStage with the appropriate memory_buffer, etc.
        """
        self.instruction_string = instruction_string
        self.instr = Instruction.Instruction(
            self.instruction_string.strip().split())
        self.memory = Memory.Memory([self.instruction_string.strip().split()])

        self.memory_buffer = Processor.Processor.get_stage_output(
            self.memory, self.register_file, 0, 0, 'memory')

        self.write_back_stage = write_back_stage.WriteBackStage(
            self.memory_buffer, self.register_file)
Esempio n. 26
0
	def __init__(self,program):
		self.bMC = Bus.Bus(1)
		self.bMAD = Bus.Bus(4)

		self.bAC = Bus.Bus(1)
		self.bAD = Bus.Bus(4)

		self.bRC = Bus.Bus(2)
		self.bRD = Bus.Bus(4)

		self.Memory = Memory.Memory(program,self.bMC,self.bMAD)
		self.Registers = Register.Register_bank(self.bRC,self,bRD)
		self.ALU = ALU.ALU(self.bAC,self.bAD)
 def visit(self, node):
     # print "ID WITH PARENTHESES"
     fundef = self.globalMemory.get(node.id)
     functionMemory = MemoryStack(Memory(node.id))
     map(lambda name, value: functionMemory.put(name, value),
         fundef.arglist.accept(self), node.expression_list.accept(self))
     self.functionMemories.append(functionMemory)
     try:
         fundef.accept(self)
         self.functionMemories.pop()
     except ReturnValueException as e:
         self.functionMemories.pop()
         return e.value
Esempio n. 28
0
 def visit(self, node):
     self.memory.push(Memory())
     self.memory.insert(node.assignment.id.id, None)
     range = node.assignment.value.accept(self)
     for i in range:
         self.memory.set(node.assignment.id.id, i)
         try:
             node.statements.accept(self)
         except ContinueException:
             continue
         except BreakException:
             break
     self.memory.pop()
Esempio n. 29
0
    def __init__(self):
        # saving variables
        self.image_path = \
          "/home/elisabeth/catkin_ws/src/DeepNeuralNetwork/dqn_neu_2" \
          "/images/Image"
        self.net_number = 1
        self.training_net_path = \
          "/home/elisabeth/catkin_ws/src/DeepNeuralNetwork/dqn_neu_2" \
          "/Training/Training_Network_" + str(self.net_number) + ".h5"
        self.target_net_path = \
          "/home/elisabeth/catkin_ws/src/DeepNeuralNetwork/dqn_neu_2" \
          "/Target/Target_Network_" + str(self.net_number) + ".h5"

        # hyperparameters
        self.speed = 15.0
        self.epsilon = 1.0
        self.max_episodes = 1000
        self.max_steps_per_episode = 400
        self.memory_size = 10000
        self.batch_size = 100
        self.image_length = 50
        self.action_repititions = 6
        self.images_in_one_input = 5
        self.net_input_size = self.images_in_one_input * self.image_length
        # self.net_input_size = 1
        self.update_rate = 5

        #other
        self.image = np.zeros(shape=[1, 50])
        self.image_buffer = []
        self.numpy_image_buffer = np.array(self.image_buffer)
        self.image_cnt = 0

        self.episode_counter = 0
        self.start_decaying = self.max_episodes / 5
        self.min_exploration_rate = 0.01
        self.decay_per_episode = self.calc_decay_per_episode()
        self.steps_in_episode = 0

        self.memory = Memory.Memory(self.memory_size)  # replay-buffer
        self.training_network = Network.Network(self.net_input_size)
        self.target_network = Network.Network(self.net_input_size)

        self.img_in_loop = 0
        self.lost_state = 25.0
        self.use_image = True

        # close to 1 --> long lasting consequences
        # low --> immediate rewards are preferred
        # or should this actually be alpha???!
        self.gamma = 0.95
Esempio n. 30
0
 def visit(self, node):
     r = None
     self.memory_stack.push(Memory('while'))
     try:
         while node.condition.accept(self):
             try:
                 r = node.instructions.accept(self)
             except ContinueException:
                 pass
     except BreakException:
         pass
     finally:
         self.memory_stack.pop()
     return r
Esempio n. 31
0
 def visit(self, node):
     self.global_mem.push(Memory())
     try:
         node.instrs.accept(self)
     except ReturnValueException as r_ex:
         self.global_mem.pop()
         raise ReturnValueException(r_ex.value)
     except BreakException as b_ex:
         self.global_mem.pop()
         raise BreakException
     except ContinueException as c_ex:
         self.global_mem.pop()
         raise ContinueException
     self.global_mem.pop()
Esempio n. 32
0
    def visit(self, node):
        r = None
        cond = self.visit(node.condition)
        node.ifBlock.special = True
        if node.elseBlock:
            node.elseBlock.special = True
        self.scopes.push(Memory("IfElse"))
        if cond:
            r = self.visit(node.ifBlock)
        elif node.elseBlock:
            r = self.visit(node.elseBlock)
        self.scopes.pop()

        return r
Esempio n. 33
0
 def visit(self, node):
         r = None
         memory = Memory("for")
         self.memoryStack.push(memory)
         while node.condition.accept(self):
             try:
                 for s in node.stat_list:
                     tmp = s.accept(self)
             except BreakException as e:
                 self.memoryStack.pop()
                 return
             except ContinueException as e:
                 pass
         self.memoryStack.pop()
Esempio n. 34
0
    def visit(self, node):

        while node.booleanInParentheses.accept(self):
            try:
                self.memory_stack.push(Memory("While"))
                node.instruction.accept(self)
            except ReturnValueException:
                return
            except ContinueException:
                continue
            except BreakException:
                break
            finally:
                self.memory_stack.pop()
Esempio n. 35
0
 def visit(self, node: AST.IfElse):
     decision = node.condition.accept(self)
     self.stack.push(Memory(f'frame{len(self.stack.frames)}_if'))
     r = None
     try:
         if bool(decision):
             r = node.if_block.accept(self)
         elif node.else_block is not None:
             r = node.else_block.accept(self)
     except BaseException as e:
         raise e
     finally:
         self.stack.pop()
     return r
Esempio n. 36
0
 def visit(self, node):
     r = None
     try:
         if not node.special:
             self.scopes.push(Memory("Scope"))
         for instruction in node.instructions:
             r = self.visit(instruction)
         if not node.special:
             self.scopes.pop()
     except ReturnValueException as ret:
         ret_val = ret.value
         print(f"Program returned with value: {ret_val}")
         return ret_val
     return r
Esempio n. 37
0
    def __init__(self,
                 learning_rate=0.01,
                 state_size=4,
                 action_size=2,
                 hidden_size=10,
                 name='QNetwork'):
        self.state_size = state_size
        self.action_size = action_size
        self.memory = Memory(max_size=1000)
        self.gamma = 0.95  # discount rate
        self.step = 0
        self.lossQ = 0

        # Exploration parameters
        self.explore_start = 1.0  # exploration probability at start
        self.explore_stop = 0.01  # minimum exploration probability
        self.decay_rate = 0.0001  # exponential decay rate for exploration prob

        self.learning_rate = 0.001

        self.config = tf.ConfigProto(intra_op_parallelism_threads=0,
                                     inter_op_parallelism_threads=0,
                                     allow_soft_placement=True,
                                     device_count={
                                         'CPU': 1,
                                         'GPU': 1
                                     },
                                     log_device_placement=True)

        # now = datetime.utcnow().strftime("%Y%m%d")
        root_logdir = "savedModels"
        self.logdir = "{}/run-{}/".format(root_logdir, "DQN")
        print("The log file is located at:" + self.logdir)
        self.save_path = self.logdir + "DDQN.ckpt"
        self.comile_model_tf(name=name, hidden_size=hidden_size)
        self.session_init()
Esempio n. 38
0
    def __init__(self, Mn):
        self.Mn = Mn
        self.S = 4
        self.E = 1
        self.B = 2
        self.m = log2(Mn)
        self.s = log2(self.S)
        self.b = log2(self.B)
        self.t = self.m - (self.s + self.b)
        #        print(self.t)
        self.Mem = M.Memory(Mn)

        self.Cache = []
        for k in range(self.S):
            self.Cache += [Bloc(0, None, self.B)]
    def setUp(self):
        old_pickle_file_name = 'old-cycle-data.pickle'
        new_pickle_file_name = 'new-cycle-data.pickle'

        self.memory = Memory.Memory()
        self.memory.loadProgramDebug('fibo.txt')
        self.processor = Processor.Processor(self.memory, 0)
        self.processor.start(new_pickle_file_name)

        print
        print 'Processor Regression Testing...'
        self.old_data_list = Processor.Processor.read_saved_data(
            old_pickle_file_name)
        self.new_data_list = Processor.Processor.read_saved_data(
            new_pickle_file_name)
 def set_up_execute_stage(self, instruction_string):
     """Set up Execute Stage with the appropriate decoder_buffer, etc.
     
     Arguments:
     - `instruction_string`:
     """
     self.instruction_string = instruction_string
     self.instr = Instruction.Instruction(
         self.instruction_string.strip().split())
     self.memory = Memory.Memory([self.instruction_string.strip().split()])
     self.decoder_buffer = Processor.Processor.get_stage_output(
         self.memory, self.register_file, 0, 0, 'decode')
     self.executer_buffer = ExecuterBuffer()
     self.execute_stage = execute_stage.ExecuteStage(
         self.decoder_buffer, self.executer_buffer)
Esempio n. 41
0
    def visit(self, node):
        result = None
        self.stack.push(Memory("while"))
        while node.expression.accept(self):
            try:
                result = node.braced_expression.accept(self)
            except ContinueException:
                continue
            except BreakException:
                break
            except:
                break

        self.stack.pop()
        return result
Esempio n. 42
0
    def callbefore(self, pid, call, args):
	if call == 'mmap':
	    params = Memory.getMemory(pid).peek(args[0], 24)
	    params = list(params)
	    start = getint(params, 0)
	    len = getint(params, 4)
	    if self.check(start, len) != (1, None, None, None):
		return (None, -errno.EPERM, None, None)
	    # Notice >>12 in expression below. Ouch. mmap and mmap2 have subtly different parameters!
	    return (1, None, 'mmap2', (start, len, getint(params, 8), getint(params, 12), getint(params, 16), getint(params, 20)>>12) )
#	    return (1, None, None, None)
	    
	if call == 'munmap' or call == 'mremap' or call == 'mmap2':
	    return self.check(args[0], args[1])
	raise 'Unknown syscall?'
 def test_operand_forwarding_R_and_R_instruction(self):
     instruction_list = [
         'R ADD  R2 R3 R2',
         'R ADD  R2 R3 R1',
     ]
     instruction_list = [
         instruction_string.split()
         for instruction_string in instruction_list
     ]
     memory = Memory.Memory(instruction_list)
     processor = Processor.Processor(memory, 0)
     processor.start()
     print 'CPI: ', processor.getCPI()
     self.assertEqual(processor.decode_stage.num_stalls, 0)
     self.assertEqual(processor.execute_stage.num_stalls, 0)
     self.assertEqual(processor.memory_stage.num_stalls, 0)
Esempio n. 44
0
 def visit(self, node):
     self.memory.push(Memory("for"))
     self.memory.insert(node.var.name, None)
     arr = node.arr.accept(self)
     result = 0
     try:
         for i in arr.values:
             self.memory.set(node.var.name, i)
             try:
                 result = node.body.accept(self)
             except ContinueException:
                 pass
     except BreakException:
         pass
     self.memory.pop()
     return result
 def visit(self, node):
     variable_name = node.variable.name
     range_ = node.range_.accept(self)
     start, end = range_.start, range_.stop
     try:
         for i in range(start, end + 1):
             try:
                 self.memory_stack.push(Memory('for', {variable_name: i}))
                 # self.memory_stack.insert(variable_name, i)
                 node.instruction.accept(self)
             except ContinueException:
                 pass
             finally:
                 self.memory_stack.pop()
     except BreakException:
         pass
Esempio n. 46
0
 def visit(self, node, fundef=False):
     if not fundef:
         try:
             self.memory_stack_local.push(Memory('while'))
             # print('|' + str(node.line))
             self.visit(node.declarations)
             self.visit(node.instructions)
             self.memory_stack_local.pop()
             # print('\\' + str(node.line))
         except (BreakException, ContinueException):
             self.memory_stack_local.pop()
             # print('/' + str(node.line))
             raise
     else:
         self.visit(node.declarations)
         self.visit(node.instructions)
Esempio n. 47
0
def check_user_online_status(userid):
    '''
        查redis,检查用户连接信息,看用户是否在线
        入参:userid
        出参:True, 在线
              False, 不在线
        编写:liulk
        日期:2012.08.13  11:33
    '''
    key = Config.USER_ADDR_PREFIX + str(userid)
    user_addr = Memory.getUserConnection(key)
    logging.info('userid: %s, user_addr: %s' % (userid, str(user_addr)))
    if not user_addr:
        return False
    else:
        return True
 def visit(self, node):
     self.memory_stack.push(Memory("for"))
     r = None
     self.memory_stack.insert(node.var.name, node.for_range.left)
     try:
         for x in node.for_range.accept(self):
             try:
                 self.memory_stack.set(node.var.name, x)
                 r = node.instructions.accept(self)
             except ContinueException:
                 pass
     except BreakException:
         pass
     finally:
         self.memory_stack.pop()
     return r
Esempio n. 49
0
 def visit(self, node: AST.WhileLoop):
     r = None
     self.stack.push(Memory(f'frame{len(self.stack.frames)}_while'))
     try:
         while bool(node.condition.accept(self)):
             try:
                 r = node.block.accept(self)
             except BreakException:
                 break
             except ContinueException:
                 continue
     except BaseException as e:
         raise e
     finally: 
         self.stack.pop()
     return r
Esempio n. 50
0
    def visit(self, node):
        try:
            fun = self.memory_stack_global.get(node.id)
            arg_calls = []
            for arg_call in node.args.list:
                arg_calls.append(self.visit(arg_call))
            self.memory_stack_local.push(Memory(node.id))
            for arg_def, arg_call in zip(fun[0].list, arg_calls):
                self.memory_stack_local.insert(arg_def.name, arg_call)

            self.visit(fun[1], True)
        except ReturnValueException as e:
            while self.memory_stack_local.memory[-1].name != node.id:
                self.memory_stack_local.pop()
            self.memory_stack_local.pop()
            return e.value
Esempio n. 51
0
	def cpu_load():
		count = psutil.cpu_count()
		condition_cpu_loop = True
		mem = Memory.Free_Space()
		if mem < 200:
			print "Achtung, sehr wenig Speicher frei!"
					
		while (condition_cpu_loop == True):
			cpu_load = psutil.cpu_percent(interval=cpu_interval)
			print(cpu_load)
			cpu_load_finish = cpu_load
			if(cpu_load > cpu_load_warning):
				condition_cpu_loop = False
				print("Warning Warning")
				print Pids.Pi(count, cpu_load_finish)  
				return(cpu_load)
Esempio n. 52
0
def exec_typeof(inst):
    obj = Memory.get_obj(Registers.get_reg(inst['rs']))
    types = {
        0: 'integer',
        2: 'string',
        3: 'object',
        4: 'function',
        5: 'null',
        6: 'undefined',
        7: 'function',
        8: 'function',
        9: 'function'
    }
    res = types[obj['type']]
    Registers.set_reg(inst['rd'], Constants.get_str(res))
    inc_pc(4)
    def callbefore(self, pid, call, args):
        if call == 'mmap':
            params = Memory.getMemory(pid).peek(args[0], 24)
            params = list(params)
            start = getint(params, 0)
            len = getint(params, 4)
            if self.check(start, len) != (1, None, None, None):
                return (None, -errno.EPERM, None, None)
            # Notice >>12 in expression below. Ouch. mmap and mmap2 have subtly different parameters!
            return (1, None, 'mmap2', (start, len, getint(params, 8),
                                       getint(params, 12), getint(params, 16),
                                       getint(params, 20) >> 12))
#	    return (1, None, None, None)

        if call == 'munmap' or call == 'mremap' or call == 'mmap2':
            return self.check(args[0], args[1])
        raise 'Unknown syscall?'
Esempio n. 54
0
def RDPmem():
    while True:
        try: 
            print("How much memory do you want the machine to have: [1-50] [C/c to cancel]")
            maxMem = input("> ")
            if maxMem.lower() == "c":
                return
            maxMem = int(maxMem)
            if maxMem < lowerBoundMemory or maxMem > upperBoundMemory:
                raise ValueError
            Machine = Memory.RDP(maxMem)
            jobCounter = 0
            break
        except ValueError:
            print("ERROR: Please input a valid choice")
    
    while True:
        print()
        Machine.printMemory(freeSymbol,takenSymbol)
        Machine.printJobs()
        print("\n[1] Add job")
        print("[2] Deallocate job")
        print("[3] Reallocate jobs")
        print("[4] EXIT")

        option = "0"
        optionChoices = ["1","2","3","4"]
        while option not in optionChoices:
            print("Choose an option")
            option = input("> ")
            if option not in optionChoices:
                print("ERROR: Please pick a valid option")
                input("press ENTER to continue")
        
        if option == "1":
            addJob(Machine, "RDP")
        elif option == "2":
            if len(Machine.objects) == 0:
                print("ERROR: No jobs to deallocate")
                input("press ENTER to continue")
            else:
                deleteJob(Machine, "RDP")
        elif option == "3":
            Machine.reallocate()
        elif option == "4":
            return
Esempio n. 55
0
    def visit(self, node):
        self.memory_stack.push(Memory("for"))

        range = node.range1.accept(self)
        name = node.variable.name
        self.memory_stack.insert(name, range[0])
        while self.memory_stack.get(name) < range[1]:
            try:
                node.instruction.accept(self)
            except ContinueException:
                self.memory_stack.set(name, self.memory_stack.get(name) + 1)
                continue
            except BreakException:
                break
            self.memory_stack.set(name, self.memory_stack.get(name) + 1)

        self.memory_stack.pop()
Esempio n. 56
0
def execute_one_instruction():
    """Execute one MAIN instruction, return # cycles used"""

    global PC, BlockBase

    if not running:
        return 0

    # get instruction word to execute, advance PC
    instruction = Memory.get(PC, False)
    BlockBase = PC & ADDRHIGHMASK
    PC = MASK_MEM(PC + 1)

    # get instruction opcode, indirect bit and address
    opcode = (instruction >> 11) & 017
    indirect = (instruction & 0100000)
    address = (instruction & 03777)

    return main_decode.get(opcode, illegal)(indirect, address, instruction)
Esempio n. 57
0
def run():
    Processor.init()
    try:
        while True:
            content = Memory.read(Processor.read_pc())
            assert content['type'] == 2, 'Following content %s is unexpected.' % str(content)
            inst = content['inst']

            """
            print 'Current PC is 0x%08X.' % Processor.read_pc()
            print inst
            """

            Processor.execute(inst)
    except KeyboardInterrupt:
        pass
    except:
        print traceback.print_exc()
        print 'Current PC is 0x%08X.' % Processor.read_pc()
        print 'Current instruction is %s.' % str(inst)
Esempio n. 58
0
    def callbefore(self, pid, call, args):
	global nchildren, lastpid, lastbrk, grace
	if call == 'mmap2':
	    assert 0, 'mmap2 -- what is that?'
	if call == 'fork' or call == 'vfork' or call == 'clone':
	    nchildren = nchildren + 1
	    print 'SANDBOX NUMPROC ', nchildren
	    if nchildren > self.maxproc:
		raise 'Too much processes'
	    return (1, None, None, None)
	if call == '_exit':
	    nchildren = nchildren - 1
	    print 'SANDBOX NUMPROC ', nchildren
	    return (1, None, None, None)

	# We allow real number to be one meg too low
	if (call == 'brk'):
	    if (pid == lastpid) and ((args[0]-lastbrk)<grace):
#	    print 'short path'
	    	return (0, None, None, None)
	    else:
	        lastbrk = args[0]
	        return (1, None, None, None)

	if (call == 'munmap'):
	    return (0, None, None, None)

	if (call == 'mmap2'):
	    return self.mmap(pid, args[1])

	if (call == 'mmap'):
	    params = Memory.getMemory(pid).peek(args[0], 8)
	    params = list(params)
# People can actually play races on us at this point.
# But as this is only Denial of Service protection, and as race succeeds
# only very seldom, it is probably not important.
# If you want to avoid races, use another trick to convert mmap into mmap2
	    return self.mmap(pid, getint(params, 4))

	raise 'Impossible: unknown syscall in DoStrick'
Esempio n. 59
0
    def callbefore(self, pid, call, args):
        sign = self.callaccess[call]
	tofree = [-1] * 6
        if not isinstance(sign, types.TupleType):
	    return (tofree, None, None, None)

        mem = Memory.getMemory(pid)
        getarg = mem.get_string
	cargs = args[:]
        for i in range(len(sign)):
            followlink = len(sign[i]) < 2
            assert followlink or sign[i][1] == 'l'
            p = getarg(args[i])
	    p = self.mappath(p) # This is still not quite good -- user could pass /home////johanka and bypass this
	    p = tricklib.canonical_path(pid, p, followlink) # Resolve to FQN
	    if not isinstance(p, types.StringType):
#		print 'Panic: what to do when canonical path fails:', p, '(', getarg(args[i]), ')'
# FIXME: We need to kill it in order to prevent bad races. But killing it means problems for creat!
		return (tofree, -p, None, None)
	    p = self.mappath(p)
	    tofree[i], cargs[i] = scratch.alloc_str(p)
 
        # don't mess with creation of relative symlinks
        if call=='symlink':
            if mem.get_string(args[0])[0] != '/':
                cargs[0] = args[0]

	if call=='open':
# FIXME:
# if we allow user to do ln -s a b without permissions for a, and
# user tries to access /tmp/b/local/bin...
#	    cargs[1] = cargs[1] | os.O_NOFOLLOW
	    cargs[1] = cargs[1] | 0400000	# Not supported by python, yet. This is true for 386

	if call=='creat':
	    print "Creat disabled, should be modified to open"
	    return (tofree, -errno.EFAULT, None, None)	# Creat should be rewritten to open()
	return (tofree, None, None, cargs)