Exemplo n.º 1
0
def main():
    arg_parser = ArgumentParser()
    arg_parser.add_argument(
        '--rom',
        help=
        'Named set of ROM files (space_invaders, lunar_rescue, balloon_bomber)'
    )
    arg_parser.add_argument('--filename', help='Single ROM file')
    arg_parser.add_argument('--state', help='Save state file')
    args = arg_parser.parse_args()

    rom = args.rom
    filename = args.filename
    if not rom or filename:
        rom = 'space_invaders'
    state = args.state

    if state:
        emu = Emulator.load(state)
    elif rom:
        emu = Emulator(mapname=rom)
    else:
        emu = Emulator(path=filename)

    emu.run()
Exemplo n.º 2
0
    def __init__(self,
                 host='localhost',
                 port=2828,
                 emulator=False,
                 connectToRunningEmulator=False,
                 homedir=None,
                 baseurl=None,
                 noWindow=False):
        self.host = host
        self.port = self.local_port = port
        self.session = None
        self.window = None
        self.emulator = None
        self.homedir = homedir
        self.baseurl = baseurl
        self.noWindow = noWindow

        if emulator:
            self.emulator = Emulator(homedir=homedir, noWindow=self.noWindow)
            self.emulator.start()
            self.port = self.emulator.setup_port_forwarding(self.port)
            assert (self.emulator.wait_for_port())

        if connectToRunningEmulator:
            self.emulator = Emulator(homedir=homedir)
            self.emulator.connect()
            self.port = self.emulator.setup_port_forwarding(self.port)
            assert (self.emulator.wait_for_port())

        self.client = MarionetteClient(self.host, self.port)
Exemplo n.º 3
0
    def __init__(self,
                 host='localhost',
                 port=2828,
                 bin=None,
                 profile=None,
                 emulator=None,
                 emulatorBinary=None,
                 emulatorImg=None,
                 emulator_res='480x800',
                 connectToRunningEmulator=False,
                 homedir=None,
                 baseurl=None,
                 noWindow=False,
                 logcat_dir=None):
        self.host = host
        self.port = self.local_port = port
        self.bin = bin
        self.instance = None
        self.profile = profile
        self.session = None
        self.window = None
        self.emulator = None
        self.extra_emulators = []
        self.homedir = homedir
        self.baseurl = baseurl
        self.noWindow = noWindow
        self.logcat_dir = logcat_dir

        if bin:
            self.instance = GeckoInstance(host=self.host,
                                          port=self.port,
                                          bin=self.bin,
                                          profile=self.profile)
            self.instance.start()
            assert (self.instance.wait_for_port())
        if emulator:
            self.emulator = Emulator(homedir=homedir,
                                     noWindow=self.noWindow,
                                     logcat_dir=self.logcat_dir,
                                     arch=emulator,
                                     emulatorBinary=emulatorBinary,
                                     userdata=emulatorImg,
                                     res=emulator_res)
            self.emulator.start()
            self.port = self.emulator.setup_port_forwarding(self.port)
            assert (self.emulator.wait_for_port())

        if connectToRunningEmulator:
            self.emulator = Emulator(homedir=homedir,
                                     logcat_dir=self.logcat_dir)
            self.emulator.connect()
            self.port = self.emulator.setup_port_forwarding(self.port)
            assert (self.emulator.wait_for_port())

        self.client = MarionetteClient(self.host, self.port)
Exemplo n.º 4
0
Arquivo: app.py Projeto: zed9/glass.py
 def __init__(self,
              name="",
              client_id=None,
              client_secret=None,
              emulator=False,
              debug=True,
              template_folder='templates'):
     self.name = name
     self.emulator = emulator
     self.debug = debug
     self.web = flask.Flask(self.name,
                            static_folder=os.path.join(
                                os.path.dirname(os.path.abspath(__file__)),
                                'emulator'),
                            static_url_path='/emulator')
     self.template_folder = template_folder
     self.logger = self.web.logger
     self.emulator_service = Emulator(app=self)
     self.subscriptions = Subscriptions(app=self)
     self.oauth = rauth.OAuth2Service(
         name=self.name,
         client_id=client_id,
         client_secret=client_secret,
         access_token_url=self.OAUTH_ACCESS_TOKEN_URL,
         authorize_url=self.OAUTH_AUTHORIZE_URL,
         base_url=self.OAUTH_API_BASE_URL)
Exemplo n.º 5
0
def instances_manager():
    adb = config.config_file_reader('adb')
    adb_devices = str(subprocess.check_output([adb, 'devices']))
    # print(adb_devices)
    adb_devices = adb_devices.split('\n')
    # print(adb_devices)
    adb_devices = adb_devices[1:]
    # print(adb_devices)
    emulator_ports = []
    emulators = []
    for adb_device in adb_devices:
        emulator_port = adb_device.split('\t')[:1][0][9:]
        # print ("hello")
        # print adb_device.split('\t')[:1][0][9:]
        if (len(emulator_port) > 3):
            emulator_ports.append(emulator_port)
            # pid = str(subprocess.check_output(['netstat', '-tulpn' ,'|', 'grep', emulator_port]))[9:]
            # print(emulator_port, len(emulator_port), pid)
            # print(emulator_port)
            pid = str(
                subprocess.check_output(['lsof', '-i', 'tcp:' + emulator_port
                                         ])).split('\n')[1:][0].split(' ')[1]
            # print(pid)
            device_details_in_ps = str(subprocess.check_output(['ps', pid]))
            # print (device_details_in_ps)
            model = get_device_emulator_model(device_details_in_ps)
            # print(model)

            current_emulator = Emulator(emulator_port, pid, model)
            emulators.append(current_emulator)
            # print(current_emulator)
    return emulators
Exemplo n.º 6
0
def process_file(filename):
    print('Processing file: ', filename)
    with open(filename, 'rb') as file:

        # Note, we can't close file until we have finished reading data
        elf_file = ELFFile(file)

        # Code is normally in the data section
        text_section = elf_file.get_section_by_name(".text")
        base_address = text_section.header['sh_addr']
        disassembly = distorm3.Decompose(base_address, text_section.data())

        # Get the symbol table as table of addresses mapped to names
        symbol_table_section = elf_file.get_section_by_name(".symtab")
        symbol_table = {}  # TODO: Fill in the symbol table...

        # Create an LLVM emulator
        emulator = Emulator("module", symbol_table)
        for instruction in disassembly:
            if hasattr(emulator, instruction.mnemonic):
                method = getattr(emulator, instruction.mnemonic)
                method(instruction)
            else:
                print(instruction.mnemonic +
                      " not implemented yet. Please implement it!")

    return disassembly
Exemplo n.º 7
0
def input(q):
    from emulator import Emulator
    import json
    import math

    while True:
        text = q.get(True)
        print(text)

        emulator = Emulator(5554)

        pages = math.ceil(len(text) / 1500.0)
        counter = 0
        texts = []
        while len(text) > 0:
            t = "%04d" % counter
            if counter == 0:
                t = "#%04d%04d" % (counter, pages - 1)
            counter += 1
            texts.append(t + text[:1500])
            text = text[1500:]
            if counter >= pages:
                break

        for text in texts:  
            emulator.send_sms("6666", text)
    def start_training(self):
        self.emulators = dict()
        number_of_points = np.linspace(
            len(self.x_signal) / 6, len(self.x_signal),
            self.n_emulator).astype(int)

        number_of_rows = self.x_signal.shape[0]

        for i in range(self.n_emulator):
            print(number_of_points[i])
            print(number_of_rows)
            random_indices = np.random.choice(number_of_rows,
                                              size=number_of_points[i],
                                              replace=False)
            x_signal = self.x_signal[random_indices, :]
            y_signal = self.y_signal[random_indices, :]
            if self.x_min_max != None:
                x_min_max = self.x_min_max[random_indices, :]
                y_min_max = self.y_min_max[random_indices, :]
            else:
                x_min_max = None
                y_min_max = None

            print(f'training on emulator n° {i} : started ')
            # TODO dev other multi training methods

            emulator = Emulator(f'Emulator_{i}', self.x_parameters,
                                self.t_series_names, self.normalize,
                                self.drop_outliers)
            emulator.train(x_signal, y_signal, x_min_max, y_min_max)
            self.emulators[emulator.name] = emulator
            print(f'training on emulator n° {i} : done ')
Exemplo n.º 9
0
def main(argv):
    minidump = tempfile.mktemp('minidump')

    emulator = Emulator(FLAGS.emulator,
                        FLAGS.maxboot,
                        avd=FLAGS.avd,
                        sdk_root=FLAGS.sdk_root,
                        avd_home=FLAGS.avd_root)

    if not emulator.avd:
        logging.info("No avds available!.")
        sys.exit(1)

    emulator.launch(FLAGS.args)

    # Connection to the emulator
    connection = emulator.connect_console()
    crash_emulator(connection)
    emulator.grab_minidump(minidump)

    # Now let's analyze the crash report..
    if not FLAGS.symbol_src or not FLAGS.stackwalker:
        logging.error(
            "No symbols, or stackwalker defined, did not validate symbols.")
        sys.exit(1)

    check_minidump(minidump)
Exemplo n.º 10
0
    def __init__(self,
                 host='localhost',
                 port=2828,
                 b2gbin=False,
                 emulator=None,
                 emulatorBinary=None,
                 connectToRunningEmulator=False,
                 homedir=None,
                 baseurl=None,
                 noWindow=False,
                 logcat_dir=None):
        self.host = host
        self.port = self.local_port = port
        self.b2gbin = b2gbin
        self.session = None
        self.window = None
        self.emulator = None
        self.extra_emulators = []
        self.homedir = homedir
        self.baseurl = baseurl
        self.noWindow = noWindow
        self.logcat_dir = logcat_dir

        if b2gbin:
            self.b2ginstance = B2GInstance(host=self.host,
                                           port=self.port,
                                           b2gbin=self.b2gbin)
            self.b2ginstance.start()
            assert (self.b2ginstance.wait_for_port())
        if emulator:
            self.emulator = Emulator(homedir=homedir,
                                     noWindow=self.noWindow,
                                     logcat_dir=self.logcat_dir,
                                     arch=emulator,
                                     emulatorBinary=emulatorBinary)
            self.emulator.start()
            self.port = self.emulator.setup_port_forwarding(self.port)
            assert (self.emulator.wait_for_port())

        if connectToRunningEmulator:
            self.emulator = Emulator(homedir=homedir,
                                     logcat_dir=self.logcat_dir)
            self.emulator.connect()
            self.port = self.emulator.setup_port_forwarding(self.port)
            assert (self.emulator.wait_for_port())

        self.client = MarionetteClient(self.host, self.port)
Exemplo n.º 11
0
def init_app(app):
    app.mold_config = MouldConfig.from_common_config()
    app.tcs = tcs_from_config(app.mold_config)
    app.wlanbox = Emulator(app.mold_config.tc_count)
    # app.wlanbox = WLANBoxConnector(app.mold_config.tc_count)
    app.msd_config = MSDConfig()
    app.test_session = TestSession()
    return app
Exemplo n.º 12
0
 def shutdown(self):
     """
     :return:
     """
     e = Emulator("localhost", self._id)
     if e.connect():
         return e.kill()
     else:
         return None
Exemplo n.º 13
0
 def stop_traffic_capture(self):
     """
     Stop traffic capture via exposed console.
     """
     e = Emulator("localhost", self._id)
     if e.connect():
         return e.network_capture_stop()
     else:
         raise Exception("An error occured while connecting to the device.")
Exemplo n.º 14
0
    def action_reset(self):
        self.last_frame = []
        if self.project_file is None:
            return

        self.emulator = Emulator(debug=False)
        self.load_project_files()

        self.emulator_state = EmulationState.LOADED

        self.next_instruction = self.emulator.run_step()
        self.actionReset.setEnabled(False)
 def __init__(self, n_emulator, simulation, x_parameters, t_series_names,
              normalize, drop_outliers):
     self.n_emulator = n_emulator
     self.simulation = simulation
     self.x_parameters = x_parameters
     self.t_series_names = t_series_names
     self.normalize = normalize
     self.drop_outliers = drop_outliers
     self.formater_emulator = Emulator(f'Emulator_formater',
                                       self.x_parameters,
                                       self.t_series_names, self.normalize,
                                       self.drop_outliers)
     self.x_signal, self.y_signal, self.x_min_max, self.y_min_max = self.formater_emulator.format_data(
         self.simulation)
Exemplo n.º 16
0
def main():
    arg_parser = ArgumentParser()
    arg_parser.add_argument('--filename', help='ROM file')
    arg_parser.add_argument('--state', help='Save state file')
    args = arg_parser.parse_args()

    filename = args.filename if args.filename else 'invaders.rom'
    state = args.state

    if state:
        emu = Emulator.load(state)
    else:
        emu = Emulator(path=filename)

    emu.run()
Exemplo n.º 17
0
    def start_traffic_capture(self, pcap_file):
        """
        Launch traffic capture via exposed console.
        Params:
            pcap_file: file where the traffic capture will be written
        Returns:
            True if successful, False otherwise
        """
        with open(pcap_file, "wb") as f:
            f.write("")

        e = Emulator("localhost", self._id)
        if e.connect():
            return e.network_capture_start(pcap_file)
        else:
            raise Exception("An error occured while connecting to the device.")
Exemplo n.º 18
0
def scan(images=True):
    """ scanning method that will scan all images or containers """

    # FIXME using default 'unix://var/run/docker.sock'
    client = docker.Client(base_url='unix://var/run/docker.sock')
    emu = Emulator()

    objs = client.images(quiet=True) 
    driver = client.info()['Driver']

    # If there are no images/containers on the machine, objs will be ['']
    if objs == ['']:
        return

    # does actual work here!
    for im in objs:
        try:

            emu.create_dirs()
            cid = mount_obj(emu.tmp_image_dir, im, driver)

            if emu.is_applicable():
                print "scanning " + im[:12]
                emu.intial_setup()
                emu.chroot_and_run()
                emu.unmount()
            else:
                print im[:12] + " is not RHEL based"

            unmount_obj(emu.tmp_image_dir, cid, driver)
            emu.remove_dirs()


        except MountError as dme:
            force_clean(cid, client, emu)
            print "Red Hat Insights was unable to complete " \
                  "due to the below error. All mounts and devices " \
                  "have been removed."
            raise ValueError(str(dme))
        except EmulatorError as eme:
            force_clean(cid, client, emu)
            print "Red Hat Insights was unable to complete " \
                  "due to the below error. All mounts and devices " \
                  "have been removed."
            raise ValueError(str(eme))

    emu.gather_data()
Exemplo n.º 19
0
def evaluate(agent,nb_ite):
    
train = np.asarray([10,100,1000])
score = np.zeros(train.shape)
eval_loop = 100
Fmax=1
game = ContinuousCatcher()
random_agent = RandomAgent(1)
agent = QAgent(10,Fmax,game.gamma())
init_emul = Emulator(agent=random_agent)
init_history = init_emul.run()
agent.train(init_history)

i = 0
for nb_train in range(train[-1]):
    if nb_train == train[i]:
        evaluate(agent)
Exemplo n.º 20
0
def adb_instances_manager() -> List[Emulator]:
    '''
    returns the List of emulators.

    :returns `List[Emulator]`:

    '''
    emulators = []
    api_commands.adb_start_server_safe()
    adb_ports = api_commands.adb_list_avd_ports()
    for adb_port in adb_ports:
        pid = util.pid_from_emulator_port(adb_port)
        model = api_commands.avd_model_from_pid(pid)
        current_emulator = Emulator(adb_port, pid, model)
        emulators.append(current_emulator)
    util.detail_print(emulators)
    return emulators
Exemplo n.º 21
0
def _setup_emulator(system):
    beacon_catcher = CaptureLastBeacon(system.frame_decoder)

    emulator_modules = [
        BeaconModule(system, beacon_catcher.last_beacon),
        AntennasModule(system),
        RTCModule(system),
        EPSModule(system),
        PayloadModule(system),
        CommModule(system, beacon_catcher.last_beacon),
        LastFramesModule(last_frames)
    ]

    emulator = Emulator(emulator_modules)
    emulator.start(IPython.lib.guisupport.get_app_wx())

    emulator.zmq_adapter = ZeroMQAdapter(system.comm)
    beacon_catcher.start()
def launch():
    if request.headers.get('authorization', None) != settings.LAUNCH_AUTH_HEADER:
        abort(403)
    if len(emulators) >= settings.EMULATOR_LIMIT:
        abort(503)
    uuid = uuid4()
    if '/' in request.form['platform'] or '/' in request.form['version']:
        abort(400)
    emu = Emulator(
        request.form['token'],
        request.form['platform'],
        request.form['version'],
        tz_offset=(int(request.form['tz_offset']) if 'tz_offset' in request.form else None),
        oauth=request.form.get('oauth', None)
    )
    emulators[uuid] = emu
    emu.last_ping = now()
    emu.run()
    return jsonify(uuid=uuid, ws_port=emu.ws_port, vnc_display=emu.vnc_display, vnc_ws_port=emu.vnc_ws_port)
Exemplo n.º 23
0
def configure(args):
    """create and configure an emulator"""

    emu = Emulator(args,
                   cpu='68030',
                   frequency=24 * 1000 * 1000)
    emu.add_memory(base=0, size=512 * 1024, writable=False, from_file=args.rom)
    emu.add_memory(base=0x4000000, size=64 * 1024 * 1024)
    emu.add_device(args,
                   MC68681,
                   address=0xfffff000,
                   interrupt=m68k.IRQ_2,
                   register_arrangement='16-bit')
    emu.add_device(args,
                   CompactFlash,
                   address=0xffffe000,
                   register_arrangement='8-bit')

    return emu
Exemplo n.º 24
0
def configure(args):
    iobase = 0xff0000

    emu = Emulator(args,
                   cpu=args.cpu_type,
                   frequency=args.cpu_frequency * 1000 * 1000)
    emu.add_memory(base=0, size=args.mem_size * 1024 * 1024)
    emu.add_device(args,
                   UART,
                   address=iobase,
                   interrupt=m68k.IRQ_2)
    emu.add_device(args,
                   Timer,
                   address=iobase + 0x1000,
                   interrupt=m68k.IRQ_6)
    emu.add_device(args,
                   Disk,
                   address=iobase + 0x2000)

    return emu
Exemplo n.º 25
0
    def analyse(self):
        ip = self.arch.instruction_pointer
        sp = self.arch.stack_pointer
        emu = Emulator(self.arch)

        emu.map_code(self.address, self.code)

        stack = get_random_page(self.arch)
        stack_data = randoms(self.arch.page_size)

        emu.setup_stack(
                stack,
                self.arch.page_size,
                stack_data
            )

        init_regs = {}

        for reg in self.arch.regs:
            if reg in (ip, sp): continue
            val = self.arch.unpack(randoms(self.arch.bits >> 3))
            emu[reg] = val
            init_regs[val] = reg

        emu.run(self.address, len(self.code))

        for reg in self.arch.regs:
            self.regs[reg] = ("junk", )
            val = emu[reg]
            if init_regs.get(val, None):
                self.regs[reg] = ("mov", init_regs[val])
                continue
            offset = gen_find(self.arch.pack(val), stack_data)
            if offset != -1:
                self.regs[reg] = ("stack", offset)

        if self.regs[sp][0] == "junk":
            self.move = emu[self.arch.stack_pointer] - stack
            self.regs[sp] = ("add", self.move)

        self.analysed = True
Exemplo n.º 26
0
 def get_running_devices():
     """
     Get running devices list
     Params:
     Returns:
     """
     devices = []
     output = subprocess.check_output(["adb", "devices"])
     matches = re.findall(r'([^\t]*)\t([^\n]*)\n',
                          "\n".join(output.split('\n')[1:]))
     for match in matches:
         if "emulator" in match[0]:
             port = int(match[0].split("-")[1])
             e = Emulator("127.0.0.1", port)
             e.connect()
             avd_name = e.avd_name()
             for a in Android.get_avds():
                 if a.name == avd_name:
                     a._id = port
                     devices.append(a)
     return devices
Exemplo n.º 27
0
def main():
    """Main script

    Acts as a terminal towards the DHT"""
    emu = Emulator(int(sys.argv[1]))
    emu.print_help('')
    for i in range(2, 10):
        emu.execute(['join', str(i)])

    emu.execute(['insert', 'Imagine', '2'])
    emu.execute(['insert', 'Ameranhs', '3'])
    emu.execute(['insert', 'Valkanos', '4'])
    emu.execute(['query', '*'])

    while True:
        command = raw_input('Action: ').split(', ')
        emu.execute(command)

        if command[0] == 'exit':
            break
        time.sleep(1)
    logging.debug('END')
Exemplo n.º 28
0
def scan(images=True):
    """ scanning method that will scan all images or containers """

    client = DockerClient()
    emu = Emulator()

    objs = client.images() if images is True else client.containers()

    # If there are no images/containers on the machine, objs will be ['']
    if objs == ['']:
        return

    # does actual work here!
    for im in objs:
        try:
            emu.create_dirs()
            mount_obj(emu.tmp_image_dir, im, client.info()['Storage Driver'])

            if emu.is_applicable():

                print "scanning " + im[:12]
                emu.intial_setup()

                emu.chroot_and_run()

                emu.unmount()
            else:
                print im[:12] + " is not RHEL based"

            unmount_obj(emu.tmp_image_dir, client.info()['Storage Driver'])
            emu.remove_dirs()

        except MountError as dme:
            raise ValueError(str(dme))

    emu.gather_data(images)
Exemplo n.º 29
0
def main():
    """Emulator

    Creates the DHT
    Adds another 9 nodes

    Uses the 'insert.txt' file to insert data and measures its throughput
    Uses the 'query.txt' file to find data and measures its throughput
    Uses the 'request.txt' file to perform requests and measures its throughput

    Closes the DHT"""
    # Create the DHT
    emu = Emulator(int(sys.argv[1]))
    for i in range(2, 10):
        emu.execute(['join', str(i)])

    # Measure throughputs and report them to the user
    write_throughput = measure_throughput(emu, 'insert.txt')
    print 'Write throughput:', write_throughput
    read_throughput = measure_throughput(emu, 'query.txt')
    print 'Read throughput:', read_throughput
    request_throughput = measure_throughput(emu, 'requests.txt')
    print 'Request throughput:', request_throughput
    emu.execute(['exit'])
Exemplo n.º 30
0
def configure(args):
    """create and configure an emulator"""

    emu = Emulator(args, cpu='68000', frequency=8 * 1000 * 1000)
    emu.add_memory(base=0, size=(16 * 1024 - 32) * 1024)
    emu.add_device(args,
                   MC68681,
                   address=0xfff001,
                   interrupt=m68k.IRQ_2,
                   console_port='A',
                   register_arrangement='16-bit')
    emu.add_device(args,
                   CompactFlash,
                   address=0xffe000,
                   register_arrangement='16-bit')

    if args.eeprom is not None:
        rom_image = open(args.eeprom, 'rb').read(32 * 1024 + 1)
        if (len(rom_image) > (32 * 1024)):
            raise RuntimeError(f'EEPROM image {args.eeprom} must be <= 32k')
        print(f'loaded {len(rom_image)} bytes of EEPROM')
        m68k.mem_write_bulk(0, rom_image)

    return emu